]> git.saurik.com Git - apt.git/blame - apt-pkg/deb/dpkgpm.cc
* debian/rules:
[apt.git] / apt-pkg / deb / dpkgpm.cc
CommitLineData
c0c0b100 1// -*- mode: cpp; mode: fold -*-
03e39e59 2// Description /*{{{*/
7f9a6360 3// $Id: dpkgpm.cc,v 1.28 2004/01/27 02:25:01 mdz Exp $
03e39e59
AL
4/* ######################################################################
5
6 DPKG Package Manager - Provide an interface to dpkg
7
8 ##################################################################### */
9 /*}}}*/
10// Includes /*{{{*/
ea542140
DK
11#include <config.h>
12
03e39e59
AL
13#include <apt-pkg/dpkgpm.h>
14#include <apt-pkg/error.h>
15#include <apt-pkg/configuration.h>
b2e465d6 16#include <apt-pkg/depcache.h>
5e457a93 17#include <apt-pkg/pkgrecords.h>
b2e465d6 18#include <apt-pkg/strutl.h>
614adaa0 19#include <apt-pkg/fileutl.h>
388f2962 20#include <apt-pkg/cachefile.h>
590f1923 21#include <apt-pkg/packagemanager.h>
233b185f 22
03e39e59
AL
23#include <unistd.h>
24#include <stdlib.h>
25#include <fcntl.h>
090c6566 26#include <sys/select.h>
96db74ce 27#include <sys/stat.h>
03e39e59
AL
28#include <sys/types.h>
29#include <sys/wait.h>
30#include <signal.h>
31#include <errno.h>
2f0d5dea 32#include <string.h>
db0c350f 33#include <stdio.h>
f7dec19f
DB
34#include <string.h>
35#include <algorithm>
75ef8f14
MV
36#include <sstream>
37#include <map>
9c76a881
MV
38#include <pwd.h>
39#include <grp.h>
75ef8f14 40
d8cb4aa4
MV
41#include <termios.h>
42#include <unistd.h>
43#include <sys/ioctl.h>
44#include <pty.h>
45
75ef8f14 46#include <apti18n.h>
b0ebdef5 47 /*}}}*/
233b185f
AL
48
49using namespace std;
03e39e59 50
697a1d8a
MV
51class pkgDPkgPMPrivate
52{
53public:
dcaa1185
DK
54 pkgDPkgPMPrivate() : stdin_is_dev_null(false), dpkgbuf_pos(0),
55 term_out(NULL), history_out(NULL)
697a1d8a 56 {
dcaa1185 57 dpkgbuf[0] = '\0';
697a1d8a
MV
58 }
59 bool stdin_is_dev_null;
60 // the buffer we use for the dpkg status-fd reading
61 char dpkgbuf[1024];
62 int dpkgbuf_pos;
63 FILE *term_out;
64 FILE *history_out;
65 string dpkg_error;
66};
67
f7dec19f
DB
68namespace
69{
70 // Maps the dpkg "processing" info to human readable names. Entry 0
71 // of each array is the key, entry 1 is the value.
72 const std::pair<const char *, const char *> PackageProcessingOps[] = {
73 std::make_pair("install", N_("Installing %s")),
74 std::make_pair("configure", N_("Configuring %s")),
75 std::make_pair("remove", N_("Removing %s")),
ac81ae9c 76 std::make_pair("purge", N_("Completely removing %s")),
b3514c56 77 std::make_pair("disappear", N_("Noting disappearance of %s")),
f7dec19f
DB
78 std::make_pair("trigproc", N_("Running post-installation trigger %s"))
79 };
80
81 const std::pair<const char *, const char *> * const PackageProcessingOpsBegin = PackageProcessingOps;
82 const std::pair<const char *, const char *> * const PackageProcessingOpsEnd = PackageProcessingOps + sizeof(PackageProcessingOps) / sizeof(PackageProcessingOps[0]);
83
84 // Predicate to test whether an entry in the PackageProcessingOps
85 // array matches a string.
86 class MatchProcessingOp
87 {
88 const char *target;
89
90 public:
91 MatchProcessingOp(const char *the_target)
92 : target(the_target)
93 {
94 }
95
96 bool operator()(const std::pair<const char *, const char *> &pair) const
97 {
98 return strcmp(pair.first, target) == 0;
99 }
100 };
101}
09fa2df2 102
cebe0287
MV
103/* helper function to ionice the given PID
104
105 there is no C header for ionice yet - just the syscall interface
106 so we use the binary from util-linux
107*/
108static bool
109ionice(int PID)
110{
111 if (!FileExists("/usr/bin/ionice"))
112 return false;
86fc2ca8 113 pid_t Process = ExecFork();
cebe0287
MV
114 if (Process == 0)
115 {
116 char buf[32];
117 snprintf(buf, sizeof(buf), "-p%d", PID);
118 const char *Args[4];
119 Args[0] = "/usr/bin/ionice";
120 Args[1] = "-c3";
121 Args[2] = buf;
122 Args[3] = 0;
123 execv(Args[0], (char **)Args);
124 }
125 return ExecWait(Process, "ionice");
126}
127
e6ee75af
DK
128// dpkgChrootDirectory - chrooting for dpkg if needed /*{{{*/
129static void dpkgChrootDirectory()
130{
131 std::string const chrootDir = _config->FindDir("DPkg::Chroot-Directory");
132 if (chrootDir == "/")
133 return;
134 std::cerr << "Chrooting into " << chrootDir << std::endl;
135 if (chroot(chrootDir.c_str()) != 0)
136 _exit(100);
137}
138 /*}}}*/
139
a1355481
MV
140
141// FindNowVersion - Helper to find a Version in "now" state /*{{{*/
142// ---------------------------------------------------------------------
143/* This is helpful when a package is no longer installed but has residual
144 * config files
145 */
146static
147pkgCache::VerIterator FindNowVersion(const pkgCache::PkgIterator &Pkg)
148{
149 pkgCache::VerIterator Ver;
150 for (Ver = Pkg.VersionList(); Ver.end() == false; Ver++)
151 {
152 pkgCache::VerFileIterator Vf = Ver.FileList();
153 pkgCache::PkgFileIterator F = Vf.File();
154 for (F = Vf.File(); F.end() == false; F++)
155 {
156 if (F && F.Archive())
157 {
158 if (strcmp(F.Archive(), "now"))
159 return Ver;
160 }
161 }
162 }
163 return Ver;
164}
165 /*}}}*/
319790f4
DK
166ssize_t retry_write(int fd, const void *buf, size_t count)
167{
168 int Res;
169 ssize_t i = 0;
170 errno = 0;
171 do
172 {
173 Res = write(fd, buf, count);
174 if (Res < 0 && errno == EINTR)
175 continue;
176 if (Res < 0)
177 break;
178 buf = (char *)buf + Res;
179 count -= Res;
180 i += Res;
181 }
182 while (Res > 0 && count > 0);
183 return i;
184}
a1355481 185
03e39e59
AL
186// DPkgPM::pkgDPkgPM - Constructor /*{{{*/
187// ---------------------------------------------------------------------
188/* */
09fa2df2 189pkgDPkgPM::pkgDPkgPM(pkgDepCache *Cache)
697a1d8a 190 : pkgPackageManager(Cache), PackagesDone(0), PackagesTotal(0)
03e39e59 191{
697a1d8a 192 d = new pkgDPkgPMPrivate();
03e39e59
AL
193}
194 /*}}}*/
195// DPkgPM::pkgDPkgPM - Destructor /*{{{*/
196// ---------------------------------------------------------------------
197/* */
198pkgDPkgPM::~pkgDPkgPM()
199{
697a1d8a 200 delete d;
03e39e59
AL
201}
202 /*}}}*/
203// DPkgPM::Install - Install a package /*{{{*/
204// ---------------------------------------------------------------------
205/* Add an install operation to the sequence list */
206bool pkgDPkgPM::Install(PkgIterator Pkg,string File)
207{
208 if (File.empty() == true || Pkg.end() == true)
209 return _error->Error("Internal Error, No file name for %s",Pkg.Name());
210
05bae55f
DK
211 // If the filename string begins with DPkg::Chroot-Directory, return the
212 // substr that is within the chroot so dpkg can access it.
213 string const chrootdir = _config->FindDir("DPkg::Chroot-Directory","/");
214 if (chrootdir != "/" && File.find(chrootdir) == 0)
215 {
216 size_t len = chrootdir.length();
217 if (chrootdir.at(len - 1) == '/')
218 len--;
219 List.push_back(Item(Item::Install,Pkg,File.substr(len)));
220 }
221 else
222 List.push_back(Item(Item::Install,Pkg,File));
223
03e39e59
AL
224 return true;
225}
226 /*}}}*/
227// DPkgPM::Configure - Configure a package /*{{{*/
228// ---------------------------------------------------------------------
229/* Add a configure operation to the sequence list */
230bool pkgDPkgPM::Configure(PkgIterator Pkg)
231{
232 if (Pkg.end() == true)
233 return false;
3e9c4f70 234
5e312de7
DK
235 List.push_back(Item(Item::Configure, Pkg));
236
237 // Use triggers for config calls if we configure "smart"
238 // as otherwise Pre-Depends will not be satisfied, see #526774
239 if (_config->FindB("DPkg::TriggersPending", false) == true)
240 List.push_back(Item(Item::TriggersPending, PkgIterator()));
3e9c4f70 241
03e39e59
AL
242 return true;
243}
244 /*}}}*/
245// DPkgPM::Remove - Remove a package /*{{{*/
246// ---------------------------------------------------------------------
247/* Add a remove operation to the sequence list */
fc4b5c9f 248bool pkgDPkgPM::Remove(PkgIterator Pkg,bool Purge)
03e39e59
AL
249{
250 if (Pkg.end() == true)
251 return false;
252
fc4b5c9f
AL
253 if (Purge == true)
254 List.push_back(Item(Item::Purge,Pkg));
255 else
256 List.push_back(Item(Item::Remove,Pkg));
6dd55be7
AL
257 return true;
258}
259 /*}}}*/
b2e465d6
AL
260// DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
261// ---------------------------------------------------------------------
262/* This is part of the helper script communication interface, it sends
263 very complete information down to the other end of the pipe.*/
264bool pkgDPkgPM::SendV2Pkgs(FILE *F)
265{
266 fprintf(F,"VERSION 2\n");
267
268 /* Write out all of the configuration directives by walking the
269 configuration tree */
270 const Configuration::Item *Top = _config->Tree(0);
271 for (; Top != 0;)
272 {
273 if (Top->Value.empty() == false)
274 {
275 fprintf(F,"%s=%s\n",
276 QuoteString(Top->FullTag(),"=\"\n").c_str(),
277 QuoteString(Top->Value,"\n").c_str());
278 }
279
280 if (Top->Child != 0)
281 {
282 Top = Top->Child;
283 continue;
284 }
285
286 while (Top != 0 && Top->Next == 0)
287 Top = Top->Parent;
288 if (Top != 0)
289 Top = Top->Next;
290 }
291 fprintf(F,"\n");
292
293 // Write out the package actions in order.
f7f0d6c7 294 for (vector<Item>::iterator I = List.begin(); I != List.end(); ++I)
b2e465d6 295 {
3e9c4f70
DK
296 if(I->Pkg.end() == true)
297 continue;
298
b2e465d6
AL
299 pkgDepCache::StateCache &S = Cache[I->Pkg];
300
301 fprintf(F,"%s ",I->Pkg.Name());
302 // Current version
303 if (I->Pkg->CurrentVer == 0)
304 fprintf(F,"- ");
305 else
306 fprintf(F,"%s ",I->Pkg.CurrentVer().VerStr());
307
308 // Show the compare operator
309 // Target version
310 if (S.InstallVer != 0)
311 {
312 int Comp = 2;
313 if (I->Pkg->CurrentVer != 0)
314 Comp = S.InstVerIter(Cache).CompareVer(I->Pkg.CurrentVer());
315 if (Comp < 0)
316 fprintf(F,"> ");
317 if (Comp == 0)
318 fprintf(F,"= ");
319 if (Comp > 0)
320 fprintf(F,"< ");
321 fprintf(F,"%s ",S.InstVerIter(Cache).VerStr());
322 }
323 else
324 fprintf(F,"> - ");
325
326 // Show the filename/operation
327 if (I->Op == Item::Install)
328 {
329 // No errors here..
330 if (I->File[0] != '/')
331 fprintf(F,"**ERROR**\n");
332 else
333 fprintf(F,"%s\n",I->File.c_str());
334 }
335 if (I->Op == Item::Configure)
336 fprintf(F,"**CONFIGURE**\n");
337 if (I->Op == Item::Remove ||
338 I->Op == Item::Purge)
339 fprintf(F,"**REMOVE**\n");
340
341 if (ferror(F) != 0)
342 return false;
343 }
344 return true;
345}
346 /*}}}*/
db0c350f
AL
347// DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
348// ---------------------------------------------------------------------
349/* This looks for a list of scripts to run from the configuration file
350 each one is run and is fed on standard input a list of all .deb files
351 that are due to be installed. */
352bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf)
353{
354 Configuration::Item const *Opts = _config->Tree(Cnf);
355 if (Opts == 0 || Opts->Child == 0)
356 return true;
357 Opts = Opts->Child;
358
359 unsigned int Count = 1;
360 for (; Opts != 0; Opts = Opts->Next, Count++)
361 {
362 if (Opts->Value.empty() == true)
363 continue;
b2e465d6
AL
364
365 // Determine the protocol version
366 string OptSec = Opts->Value;
367 string::size_type Pos;
368 if ((Pos = OptSec.find(' ')) == string::npos || Pos == 0)
369 Pos = OptSec.length();
b2e465d6
AL
370 OptSec = "DPkg::Tools::Options::" + string(Opts->Value.c_str(),Pos);
371
372 unsigned int Version = _config->FindI(OptSec+"::Version",1);
373
db0c350f
AL
374 // Create the pipes
375 int Pipes[2];
376 if (pipe(Pipes) != 0)
377 return _error->Errno("pipe","Failed to create IPC pipe to subprocess");
378 SetCloseExec(Pipes[0],true);
379 SetCloseExec(Pipes[1],true);
380
381 // Purified Fork for running the script
382 pid_t Process = ExecFork();
383 if (Process == 0)
384 {
385 // Setup the FDs
386 dup2(Pipes[0],STDIN_FILENO);
387 SetCloseExec(STDOUT_FILENO,false);
388 SetCloseExec(STDIN_FILENO,false);
389 SetCloseExec(STDERR_FILENO,false);
90ecbd7d 390
e6ee75af 391 dpkgChrootDirectory();
90ecbd7d 392 const char *Args[4];
db0c350f 393 Args[0] = "/bin/sh";
90ecbd7d
AL
394 Args[1] = "-c";
395 Args[2] = Opts->Value.c_str();
396 Args[3] = 0;
db0c350f
AL
397 execv(Args[0],(char **)Args);
398 _exit(100);
399 }
400 close(Pipes[0]);
b2e465d6
AL
401 FILE *F = fdopen(Pipes[1],"w");
402 if (F == 0)
403 return _error->Errno("fdopen","Faild to open new FD");
404
db0c350f 405 // Feed it the filenames.
b2e465d6 406 if (Version <= 1)
db0c350f 407 {
f7f0d6c7 408 for (vector<Item>::iterator I = List.begin(); I != List.end(); ++I)
db0c350f 409 {
b2e465d6
AL
410 // Only deal with packages to be installed from .deb
411 if (I->Op != Item::Install)
412 continue;
413
414 // No errors here..
415 if (I->File[0] != '/')
416 continue;
417
418 /* Feed the filename of each package that is pending install
419 into the pipe. */
420 fprintf(F,"%s\n",I->File.c_str());
421 if (ferror(F) != 0)
b2e465d6 422 break;
90ecbd7d 423 }
db0c350f 424 }
b2e465d6 425 else
ed0fe654 426 SendV2Pkgs(F);
b2e465d6
AL
427
428 fclose(F);
db0c350f
AL
429
430 // Clean up the sub process
431 if (ExecWait(Process,Opts->Value.c_str()) == false)
90ecbd7d 432 return _error->Error("Failure running script %s",Opts->Value.c_str());
db0c350f
AL
433 }
434
435 return true;
436}
ceabc520
MV
437 /*}}}*/
438// DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
439// ---------------------------------------------------------------------
440/*
441*/
442void pkgDPkgPM::DoStdin(int master)
443{
aff87a76
MV
444 unsigned char input_buf[256] = {0,};
445 ssize_t len = read(0, input_buf, sizeof(input_buf));
9983591d 446 if (len)
319790f4 447 retry_write(master, input_buf, len);
9983591d 448 else
697a1d8a 449 d->stdin_is_dev_null = true;
ceabc520 450}
03e39e59 451 /*}}}*/
ceabc520
MV
452// DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
453// ---------------------------------------------------------------------
454/*
455 * read the terminal pty and write log
456 */
1ba38171 457void pkgDPkgPM::DoTerminalPty(int master)
ceabc520 458{
aff87a76 459 unsigned char term_buf[1024] = {0,0, };
ceabc520 460
aff87a76 461 ssize_t len=read(master, term_buf, sizeof(term_buf));
7052511e
MV
462 if(len == -1 && errno == EIO)
463 {
464 // this happens when the child is about to exit, we
465 // give it time to actually exit, otherwise we run
b6ff6913
DK
466 // into a race so we sleep for half a second.
467 struct timespec sleepfor = { 0, 500000000 };
468 nanosleep(&sleepfor, NULL);
7052511e
MV
469 return;
470 }
471 if(len <= 0)
955a6ddb 472 return;
319790f4 473 retry_write(1, term_buf, len);
697a1d8a
MV
474 if(d->term_out)
475 fwrite(term_buf, len, sizeof(char), d->term_out);
ceabc520 476}
03e39e59 477 /*}}}*/
6191b008
MV
478// DPkgPM::ProcessDpkgStatusBuf /*{{{*/
479// ---------------------------------------------------------------------
480/*
481 */
09fa2df2 482void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd, char *line)
6191b008 483{
887f5036 484 bool const Debug = _config->FindB("Debug::pkgDPkgProgressReporting",false);
09fa2df2
MV
485 // the status we output
486 ostringstream status;
487
887f5036 488 if (Debug == true)
09fa2df2
MV
489 std::clog << "got from dpkg '" << line << "'" << std::endl;
490
491
492 /* dpkg sends strings like this:
493 'status: <pkg>: <pkg qstate>'
494 errors look like this:
495 'status: /var/cache/apt/archives/krecipes_0.8.1-0ubuntu1_i386.deb : error : trying to overwrite `/usr/share/doc/kde/HTML/en/krecipes/krectip.png', which is also in package krecipes-data
496 and conffile-prompt like this
497 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
fc2d32c0
MV
498
499 Newer versions of dpkg sent also:
500 'processing: install: pkg'
501 'processing: configure: pkg'
502 'processing: remove: pkg'
b3514c56
DK
503 'processing: purge: pkg'
504 'processing: disappear: pkg'
fc2d32c0 505 'processing: trigproc: trigger'
09fa2df2
MV
506
507 */
5279f566 508 char* list[6];
09fa2df2
MV
509 // dpkg sends multiline error messages sometimes (see
510 // #374195 for a example. we should support this by
511 // either patching dpkg to not send multiline over the
512 // statusfd or by rewriting the code here to deal with
513 // it. for now we just ignore it and not crash
514 TokSplitString(':', line, list, sizeof(list)/sizeof(list[0]));
f26fcbc7 515 if( list[0] == NULL || list[1] == NULL || list[2] == NULL)
09fa2df2 516 {
887f5036 517 if (Debug == true)
09fa2df2
MV
518 std::clog << "ignoring line: not enough ':'" << std::endl;
519 return;
520 }
887f5036
DK
521 const char* const pkg = list[1];
522 const char* action = _strstrip(list[2]);
09fa2df2 523
fc2d32c0
MV
524 // 'processing' from dpkg looks like
525 // 'processing: action: pkg'
526 if(strncmp(list[0], "processing", strlen("processing")) == 0)
527 {
528 char s[200];
887f5036
DK
529 const char* const pkg_or_trigger = _strstrip(list[2]);
530 action = _strstrip( list[1]);
f7dec19f
DB
531 const std::pair<const char *, const char *> * const iter =
532 std::find_if(PackageProcessingOpsBegin,
533 PackageProcessingOpsEnd,
534 MatchProcessingOp(action));
535 if(iter == PackageProcessingOpsEnd)
fc2d32c0 536 {
887f5036
DK
537 if (Debug == true)
538 std::clog << "ignoring unknown action: " << action << std::endl;
fc2d32c0
MV
539 return;
540 }
f7dec19f 541 snprintf(s, sizeof(s), _(iter->second), pkg_or_trigger);
fc2d32c0
MV
542
543 status << "pmstatus:" << pkg_or_trigger
544 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
545 << ":" << s
546 << endl;
547 if(OutStatusFd > 0)
319790f4 548 retry_write(OutStatusFd, status.str().c_str(), status.str().size());
887f5036 549 if (Debug == true)
fc2d32c0 550 std::clog << "send: '" << status.str() << "'" << endl;
642ebc1a
DK
551
552 if (strncmp(action, "disappear", strlen("disappear")) == 0)
eb6f9bac 553 handleDisappearAction(pkg_or_trigger);
fc2d32c0
MV
554 return;
555 }
556
09fa2df2
MV
557 if(strncmp(action,"error",strlen("error")) == 0)
558 {
d6a4afcb
MV
559 // urgs, sometime has ":" in its error string so that we
560 // end up with the error message split between list[3]
561 // and list[4], e.g. the message:
5279f566 562 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
d6a4afcb 563 // concat them again
5279f566
MV
564 if( list[4] != NULL )
565 list[3][strlen(list[3])] = ':';
d6a4afcb 566
09fa2df2 567 status << "pmerror:" << list[1]
ff56e980 568 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
09fa2df2
MV
569 << ":" << list[3]
570 << endl;
571 if(OutStatusFd > 0)
319790f4 572 retry_write(OutStatusFd, status.str().c_str(), status.str().size());
887f5036 573 if (Debug == true)
09fa2df2 574 std::clog << "send: '" << status.str() << "'" << endl;
f060e833
MV
575 pkgFailures++;
576 WriteApportReport(list[1], list[3]);
09fa2df2
MV
577 return;
578 }
887f5036 579 else if(strncmp(action,"conffile",strlen("conffile")) == 0)
09fa2df2
MV
580 {
581 status << "pmconffile:" << list[1]
ff56e980 582 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
09fa2df2
MV
583 << ":" << list[3]
584 << endl;
585 if(OutStatusFd > 0)
319790f4 586 retry_write(OutStatusFd, status.str().c_str(), status.str().size());
887f5036 587 if (Debug == true)
09fa2df2
MV
588 std::clog << "send: '" << status.str() << "'" << endl;
589 return;
590 }
591
887f5036 592 vector<struct DpkgState> const &states = PackageOps[pkg];
09fa2df2
MV
593 const char *next_action = NULL;
594 if(PackageOpsDone[pkg] < states.size())
595 next_action = states[PackageOpsDone[pkg]].state;
596 // check if the package moved to the next dpkg state
597 if(next_action && (strcmp(action, next_action) == 0))
598 {
599 // only read the translation if there is actually a next
600 // action
601 const char *translation = _(states[PackageOpsDone[pkg]].str);
602 char s[200];
603 snprintf(s, sizeof(s), translation, pkg);
604
605 // we moved from one dpkg state to a new one, report that
606 PackageOpsDone[pkg]++;
ff56e980 607 PackagesDone++;
09fa2df2
MV
608 // build the status str
609 status << "pmstatus:" << pkg
ff56e980 610 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
09fa2df2
MV
611 << ":" << s
612 << endl;
613 if(OutStatusFd > 0)
319790f4 614 retry_write(OutStatusFd, status.str().c_str(), status.str().size());
887f5036 615 if (Debug == true)
09fa2df2
MV
616 std::clog << "send: '" << status.str() << "'" << endl;
617 }
887f5036 618 if (Debug == true)
09fa2df2
MV
619 std::clog << "(parsed from dpkg) pkg: " << pkg
620 << " action: " << action << endl;
6191b008 621}
887f5036 622 /*}}}*/
eb6f9bac
DK
623// DPkgPM::handleDisappearAction /*{{{*/
624void pkgDPkgPM::handleDisappearAction(string const &pkgname)
625{
626 // record the package name for display and stuff later
627 disappearedPkgs.insert(pkgname);
628
629 pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
630 if (unlikely(Pkg.end() == true))
631 return;
632 // the disappeared package was auto-installed - nothing to do
633 if ((Cache[Pkg].Flags & pkgCache::Flag::Auto) == pkgCache::Flag::Auto)
634 return;
75954ae2 635 pkgCache::VerIterator PkgVer = Cache[Pkg].InstVerIter(Cache);
eb6f9bac
DK
636 if (unlikely(PkgVer.end() == true))
637 return;
638 /* search in the list of dependencies for (Pre)Depends,
639 check if this dependency has a Replaces on our package
640 and if so transfer the manual installed flag to it */
641 for (pkgCache::DepIterator Dep = PkgVer.DependsList(); Dep.end() != true; ++Dep)
642 {
643 if (Dep->Type != pkgCache::Dep::Depends &&
644 Dep->Type != pkgCache::Dep::PreDepends)
645 continue;
646 pkgCache::PkgIterator Tar = Dep.TargetPkg();
647 if (unlikely(Tar.end() == true))
648 continue;
649 // the package is already marked as manual
650 if ((Cache[Tar].Flags & pkgCache::Flag::Auto) != pkgCache::Flag::Auto)
651 continue;
75954ae2
DK
652 pkgCache::VerIterator TarVer = Cache[Tar].InstVerIter(Cache);
653 if (TarVer.end() == true)
654 continue;
eb6f9bac
DK
655 for (pkgCache::DepIterator Rep = TarVer.DependsList(); Rep.end() != true; ++Rep)
656 {
657 if (Rep->Type != pkgCache::Dep::Replaces)
658 continue;
659 if (Pkg != Rep.TargetPkg())
660 continue;
661 // okay, they are strongly connected - transfer manual-bit
662 if (Debug == true)
663 std::clog << "transfer manual-bit from disappeared »" << pkgname << "« to »" << Tar.FullName() << "«" << std::endl;
664 Cache[Tar].Flags &= ~Flag::Auto;
665 break;
666 }
667 }
668}
669 /*}}}*/
887f5036 670// DPkgPM::DoDpkgStatusFd /*{{{*/
6191b008
MV
671// ---------------------------------------------------------------------
672/*
673 */
09fa2df2 674void pkgDPkgPM::DoDpkgStatusFd(int statusfd, int OutStatusFd)
6191b008
MV
675{
676 char *p, *q;
677 int len;
678
697a1d8a
MV
679 len=read(statusfd, &d->dpkgbuf[d->dpkgbuf_pos], sizeof(d->dpkgbuf)-d->dpkgbuf_pos);
680 d->dpkgbuf_pos += len;
6191b008
MV
681 if(len <= 0)
682 return;
ceabc520 683
6191b008 684 // process line by line if we have a buffer
697a1d8a
MV
685 p = q = d->dpkgbuf;
686 while((q=(char*)memchr(p, '\n', d->dpkgbuf+d->dpkgbuf_pos-p)) != NULL)
6191b008
MV
687 {
688 *q = 0;
09fa2df2 689 ProcessDpkgStatusLine(OutStatusFd, p);
6191b008
MV
690 p=q+1; // continue with next line
691 }
692
693 // now move the unprocessed bits (after the final \n that is now a 0x0)
697a1d8a
MV
694 // to the start and update d->dpkgbuf_pos
695 p = (char*)memrchr(d->dpkgbuf, 0, d->dpkgbuf_pos);
6191b008
MV
696 if(p == NULL)
697 return;
698
699 // we are interessted in the first char *after* 0x0
700 p++;
701
702 // move the unprocessed tail to the start and update pos
697a1d8a
MV
703 memmove(d->dpkgbuf, p, p-d->dpkgbuf);
704 d->dpkgbuf_pos = d->dpkgbuf+d->dpkgbuf_pos-p;
6191b008
MV
705}
706 /*}}}*/
d7a4ffd6 707// DPkgPM::WriteHistoryTag /*{{{*/
6cb1060b 708void pkgDPkgPM::WriteHistoryTag(string const &tag, string value)
d7a4ffd6 709{
6cb1060b
DK
710 size_t const length = value.length();
711 if (length == 0)
712 return;
713 // poor mans rstrip(", ")
714 if (value[length-2] == ',' && value[length-1] == ' ')
715 value.erase(length - 2, 2);
697a1d8a 716 fprintf(d->history_out, "%s: %s\n", tag.c_str(), value.c_str());
d7a4ffd6 717} /*}}}*/
887f5036 718// DPkgPM::OpenLog /*{{{*/
2e1715ea
MV
719bool pkgDPkgPM::OpenLog()
720{
569cc934 721 string const logdir = _config->FindDir("Dir::Log");
7753e468 722 if(CreateAPTDirectoryIfNeeded(logdir, logdir) == false)
b29c3712 723 // FIXME: use a better string after freeze
2e1715ea 724 return _error->Error(_("Directory '%s' missing"), logdir.c_str());
9169c871
MV
725
726 // get current time
727 char timestr[200];
569cc934
DK
728 time_t const t = time(NULL);
729 struct tm const * const tmp = localtime(&t);
9169c871
MV
730 strftime(timestr, sizeof(timestr), "%F %T", tmp);
731
732 // open terminal log
569cc934 733 string const logfile_name = flCombine(logdir,
2e1715ea
MV
734 _config->Find("Dir::Log::Terminal"));
735 if (!logfile_name.empty())
736 {
697a1d8a
MV
737 d->term_out = fopen(logfile_name.c_str(),"a");
738 if (d->term_out == NULL)
569cc934 739 return _error->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name.c_str());
697a1d8a
MV
740 setvbuf(d->term_out, NULL, _IONBF, 0);
741 SetCloseExec(fileno(d->term_out), true);
9c76a881
MV
742 struct passwd *pw;
743 struct group *gr;
744 pw = getpwnam("root");
745 gr = getgrnam("adm");
746 if (pw != NULL && gr != NULL)
747 chown(logfile_name.c_str(), pw->pw_uid, gr->gr_gid);
748 chmod(logfile_name.c_str(), 0644);
697a1d8a 749 fprintf(d->term_out, "\nLog started: %s\n", timestr);
2e1715ea 750 }
9169c871 751
569cc934
DK
752 // write your history
753 string const history_name = flCombine(logdir,
9169c871
MV
754 _config->Find("Dir::Log::History"));
755 if (!history_name.empty())
756 {
697a1d8a
MV
757 d->history_out = fopen(history_name.c_str(),"a");
758 if (d->history_out == NULL)
569cc934 759 return _error->WarningE("OpenLog", _("Could not open file '%s'"), history_name.c_str());
9169c871 760 chmod(history_name.c_str(), 0644);
697a1d8a 761 fprintf(d->history_out, "\nStart-Date: %s\n", timestr);
97be52d4 762 string remove, purge, install, reinstall, upgrade, downgrade;
f7f0d6c7 763 for (pkgCache::PkgIterator I = Cache.PkgBegin(); I.end() == false; ++I)
9169c871 764 {
97be52d4
DK
765 enum { CANDIDATE, CANDIDATE_AUTO, CURRENT_CANDIDATE, CURRENT } infostring;
766 string *line = NULL;
767 #define HISTORYINFO(X, Y) { line = &X; infostring = Y; }
768 if (Cache[I].NewInstall() == true)
769 HISTORYINFO(install, CANDIDATE_AUTO)
770 else if (Cache[I].ReInstall() == true)
771 HISTORYINFO(reinstall, CANDIDATE)
772 else if (Cache[I].Upgrade() == true)
773 HISTORYINFO(upgrade, CURRENT_CANDIDATE)
774 else if (Cache[I].Downgrade() == true)
775 HISTORYINFO(downgrade, CURRENT_CANDIDATE)
776 else if (Cache[I].Delete() == true)
777 HISTORYINFO((Cache[I].Purge() ? purge : remove), CURRENT)
778 else
779 continue;
780 #undef HISTORYINFO
781 line->append(I.FullName(false)).append(" (");
782 switch (infostring) {
783 case CANDIDATE: line->append(Cache[I].CandVersion); break;
784 case CANDIDATE_AUTO:
785 line->append(Cache[I].CandVersion);
786 if ((Cache[I].Flags & pkgCache::Flag::Auto) == pkgCache::Flag::Auto)
787 line->append(", automatic");
788 break;
789 case CURRENT_CANDIDATE: line->append(Cache[I].CurVersion).append(", ").append(Cache[I].CandVersion); break;
790 case CURRENT: line->append(Cache[I].CurVersion); break;
9169c871 791 }
97be52d4 792 line->append("), ");
9169c871 793 }
2bb25574
DK
794 if (_config->Exists("Commandline::AsString") == true)
795 WriteHistoryTag("Commandline", _config->Find("Commandline::AsString"));
d7a4ffd6 796 WriteHistoryTag("Install", install);
97be52d4 797 WriteHistoryTag("Reinstall", reinstall);
d7a4ffd6
MV
798 WriteHistoryTag("Upgrade", upgrade);
799 WriteHistoryTag("Downgrade",downgrade);
800 WriteHistoryTag("Remove",remove);
801 WriteHistoryTag("Purge",purge);
697a1d8a 802 fflush(d->history_out);
9169c871
MV
803 }
804
2e1715ea
MV
805 return true;
806}
887f5036
DK
807 /*}}}*/
808// DPkg::CloseLog /*{{{*/
2e1715ea
MV
809bool pkgDPkgPM::CloseLog()
810{
9169c871
MV
811 char timestr[200];
812 time_t t = time(NULL);
813 struct tm *tmp = localtime(&t);
814 strftime(timestr, sizeof(timestr), "%F %T", tmp);
815
697a1d8a 816 if(d->term_out)
2e1715ea 817 {
697a1d8a
MV
818 fprintf(d->term_out, "Log ended: ");
819 fprintf(d->term_out, "%s", timestr);
820 fprintf(d->term_out, "\n");
821 fclose(d->term_out);
2e1715ea 822 }
697a1d8a 823 d->term_out = NULL;
9169c871 824
697a1d8a 825 if(d->history_out)
9169c871 826 {
6cb1060b
DK
827 if (disappearedPkgs.empty() == false)
828 {
829 string disappear;
830 for (std::set<std::string>::const_iterator d = disappearedPkgs.begin();
831 d != disappearedPkgs.end(); ++d)
832 {
833 pkgCache::PkgIterator P = Cache.FindPkg(*d);
834 disappear.append(*d);
835 if (P.end() == true)
836 disappear.append(", ");
837 else
838 disappear.append(" (").append(Cache[P].CurVersion).append("), ");
839 }
840 WriteHistoryTag("Disappeared", disappear);
841 }
697a1d8a
MV
842 if (d->dpkg_error.empty() == false)
843 fprintf(d->history_out, "Error: %s\n", d->dpkg_error.c_str());
844 fprintf(d->history_out, "End-Date: %s\n", timestr);
845 fclose(d->history_out);
9169c871 846 }
697a1d8a 847 d->history_out = NULL;
9169c871 848
2e1715ea
MV
849 return true;
850}
887f5036 851 /*}}}*/
919e5852
OS
852/*{{{*/
853// This implements a racy version of pselect for those architectures
854// that don't have a working implementation.
855// FIXME: Probably can be removed on Lenny+1
856static int racy_pselect(int nfds, fd_set *readfds, fd_set *writefds,
857 fd_set *exceptfds, const struct timespec *timeout,
858 const sigset_t *sigmask)
859{
860 sigset_t origmask;
861 struct timeval tv;
862 int retval;
863
f6b37f38
OS
864 tv.tv_sec = timeout->tv_sec;
865 tv.tv_usec = timeout->tv_nsec/1000;
919e5852 866
f6b37f38 867 sigprocmask(SIG_SETMASK, sigmask, &origmask);
919e5852
OS
868 retval = select(nfds, readfds, writefds, exceptfds, &tv);
869 sigprocmask(SIG_SETMASK, &origmask, 0);
870 return retval;
871}
872/*}}}*/
03e39e59
AL
873// DPkgPM::Go - Run the sequence /*{{{*/
874// ---------------------------------------------------------------------
75ef8f14
MV
875/* This globs the operations and calls dpkg
876 *
877 * If it is called with "OutStatusFd" set to a valid file descriptor
878 * apt will report the install progress over this fd. It maps the
879 * dpkg states a package goes through to human readable (and i10n-able)
880 * names and calculates a percentage for each step.
881*/
882bool pkgDPkgPM::Go(int OutStatusFd)
03e39e59 883{
b1803e01
DK
884 pkgPackageManager::SigINTStop = false;
885
86fc2ca8
DK
886 // Generate the base argument list for dpkg
887 std::vector<const char *> Args;
888 unsigned long StartSize = 0;
734a6727
DK
889 string Tmp = _config->Find("Dir::Bin::dpkg","dpkg");
890 {
891 string const dpkgChrootDir = _config->FindDir("DPkg::Chroot-Directory", "/");
892 size_t dpkgChrootLen = dpkgChrootDir.length();
893 if (dpkgChrootDir != "/" && Tmp.find(dpkgChrootDir) == 0)
894 {
895 if (dpkgChrootDir[dpkgChrootLen - 1] == '/')
896 --dpkgChrootLen;
897 Tmp = Tmp.substr(dpkgChrootLen);
898 }
899 }
86fc2ca8
DK
900 Args.push_back(Tmp.c_str());
901 StartSize += Tmp.length();
902
903 // Stick in any custom dpkg options
904 Configuration::Item const *Opts = _config->Tree("DPkg::Options");
905 if (Opts != 0)
906 {
907 Opts = Opts->Child;
908 for (; Opts != 0; Opts = Opts->Next)
909 {
910 if (Opts->Value.empty() == true)
911 continue;
912 Args.push_back(Opts->Value.c_str());
913 StartSize += Opts->Value.length();
914 }
915 }
916
917 size_t const BaseArgs = Args.size();
918 // we need to detect if we can qualify packages with the architecture or not
919 Args.push_back("--assert-multi-arch");
920 Args.push_back(NULL);
921
922 pid_t dpkgAssertMultiArch = ExecFork();
923 if (dpkgAssertMultiArch == 0)
924 {
e6ee75af 925 dpkgChrootDirectory();
67b5d3dc
DK
926 // redirect everything to the ultimate sink as we only need the exit-status
927 int const nullfd = open("/dev/null", O_RDONLY);
928 dup2(nullfd, STDIN_FILENO);
929 dup2(nullfd, STDOUT_FILENO);
930 dup2(nullfd, STDERR_FILENO);
17019a09 931 execvp(Args[0], (char**) &Args[0]);
86fc2ca8
DK
932 _error->WarningE("dpkgGo", "Can't detect if dpkg supports multi-arch!");
933 _exit(2);
934 }
935
17745b02
MV
936 fd_set rfds;
937 struct timespec tv;
938 sigset_t sigmask;
939 sigset_t original_sigmask;
940
887f5036
DK
941 unsigned int const MaxArgs = _config->FindI("Dpkg::MaxArgs",8*1024);
942 unsigned int const MaxArgBytes = _config->FindI("Dpkg::MaxArgBytes",32*1024);
5e312de7 943 bool const NoTriggers = _config->FindB("DPkg::NoTriggers", false);
aff4e2f1 944
6dd55be7
AL
945 if (RunScripts("DPkg::Pre-Invoke") == false)
946 return false;
db0c350f
AL
947
948 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
949 return false;
fc2d32c0 950
3e9c4f70
DK
951 // support subpressing of triggers processing for special
952 // cases like d-i that runs the triggers handling manually
5e312de7 953 bool const SmartConf = (_config->Find("PackageManager::Configure", "all") != "all");
5c23dbcc 954 bool const TriggersPending = _config->FindB("DPkg::TriggersPending", false);
5e312de7
DK
955 if (_config->FindB("DPkg::ConfigurePending", SmartConf) == true)
956 List.push_back(Item(Item::ConfigurePending, PkgIterator()));
3e9c4f70 957
75ef8f14
MV
958 // map the dpkg states to the operations that are performed
959 // (this is sorted in the same way as Item::Ops)
9d06bc80 960 static const struct DpkgState DpkgStatesOpMap[][7] = {
75ef8f14
MV
961 // Install operation
962 {
21e1008e
MV
963 {"half-installed", N_("Preparing %s")},
964 {"unpacked", N_("Unpacking %s") },
75ef8f14
MV
965 {NULL, NULL}
966 },
967 // Configure operation
968 {
21e1008e
MV
969 {"unpacked",N_("Preparing to configure %s") },
970 {"half-configured", N_("Configuring %s") },
971 { "installed", N_("Installed %s")},
75ef8f14
MV
972 {NULL, NULL}
973 },
974 // Remove operation
975 {
21e1008e
MV
976 {"half-configured", N_("Preparing for removal of %s")},
977 {"half-installed", N_("Removing %s")},
978 {"config-files", N_("Removed %s")},
75ef8f14
MV
979 {NULL, NULL}
980 },
981 // Purge operation
982 {
21e1008e
MV
983 {"config-files", N_("Preparing to completely remove %s")},
984 {"not-installed", N_("Completely removed %s")},
75ef8f14
MV
985 {NULL, NULL}
986 },
987 };
db0c350f 988
75ef8f14
MV
989 // init the PackageOps map, go over the list of packages that
990 // that will be [installed|configured|removed|purged] and add
991 // them to the PackageOps map (the dpkg states it goes through)
992 // and the PackageOpsTranslations (human readable strings)
f7f0d6c7 993 for (vector<Item>::const_iterator I = List.begin(); I != List.end(); ++I)
75ef8f14 994 {
3e9c4f70
DK
995 if((*I).Pkg.end() == true)
996 continue;
997
887f5036 998 string const name = (*I).Pkg.Name();
75ef8f14 999 PackageOpsDone[name] = 0;
f7f0d6c7 1000 for(int i=0; (DpkgStatesOpMap[(*I).Op][i]).state != NULL; ++i)
75ef8f14
MV
1001 {
1002 PackageOps[name].push_back(DpkgStatesOpMap[(*I).Op][i]);
ff56e980 1003 PackagesTotal++;
75ef8f14 1004 }
887f5036 1005 }
75ef8f14 1006
697a1d8a 1007 d->stdin_is_dev_null = false;
9983591d 1008
ff56e980 1009 // create log
2e1715ea 1010 OpenLog();
ff56e980 1011
86fc2ca8
DK
1012 bool dpkgMultiArch = false;
1013 if (dpkgAssertMultiArch > 0)
11bcbdb9 1014 {
86fc2ca8
DK
1015 int Status = 0;
1016 while (waitpid(dpkgAssertMultiArch, &Status, 0) != dpkgAssertMultiArch)
11bcbdb9 1017 {
86fc2ca8 1018 if (errno == EINTR)
11bcbdb9 1019 continue;
86fc2ca8
DK
1020 _error->WarningE("dpkgGo", _("Waited for %s but it wasn't there"), "dpkg --assert-multi-arch");
1021 break;
11bcbdb9 1022 }
86fc2ca8
DK
1023 if (WIFEXITED(Status) == true && WEXITSTATUS(Status) == 0)
1024 dpkgMultiArch = true;
11bcbdb9 1025 }
11bcbdb9 1026
75ef8f14 1027 // this loop is runs once per operation
887f5036 1028 for (vector<Item>::const_iterator I = List.begin(); I != List.end();)
03e39e59 1029 {
5c23dbcc 1030 // Do all actions with the same Op in one run
887f5036 1031 vector<Item>::const_iterator J = I;
5c23dbcc 1032 if (TriggersPending == true)
f7f0d6c7 1033 for (; J != List.end(); ++J)
5c23dbcc
DK
1034 {
1035 if (J->Op == I->Op)
1036 continue;
1037 if (J->Op != Item::TriggersPending)
1038 break;
1039 vector<Item>::const_iterator T = J + 1;
1040 if (T != List.end() && T->Op == I->Op)
1041 continue;
1042 break;
1043 }
1044 else
f7f0d6c7 1045 for (; J != List.end() && J->Op == I->Op; ++J)
5c23dbcc 1046 /* nothing */;
30e1eab5 1047
8e11253d 1048 // keep track of allocated strings for multiarch package names
edca7af0 1049 std::vector<char *> Packages;
8e11253d 1050
11bcbdb9
DK
1051 // start with the baseset of arguments
1052 unsigned long Size = StartSize;
1053 Args.erase(Args.begin() + BaseArgs, Args.end());
1054
599d6ad5
MV
1055 // Now check if we are within the MaxArgs limit
1056 //
1057 // this code below is problematic, because it may happen that
1058 // the argument list is split in a way that A depends on B
1059 // and they are in the same "--configure A B" run
1060 // - with the split they may now be configured in different
1cecd437 1061 // runs, using Immediate-Configure-All can help prevent this.
aff4e2f1 1062 if (J - I > (signed)MaxArgs)
edca7af0 1063 {
aff4e2f1 1064 J = I + MaxArgs;
86fc2ca8
DK
1065 unsigned long const size = MaxArgs + 10;
1066 Args.reserve(size);
1067 Packages.reserve(size);
edca7af0
DK
1068 }
1069 else
1070 {
86fc2ca8
DK
1071 unsigned long const size = (J - I) + 10;
1072 Args.reserve(size);
1073 Packages.reserve(size);
edca7af0
DK
1074 }
1075
75ef8f14 1076 int fd[2];
319790f4
DK
1077 if (pipe(fd) != 0)
1078 return _error->Errno("pipe","Failed to create IPC pipe to dpkg");
edca7af0
DK
1079
1080#define ADDARG(X) Args.push_back(X); Size += strlen(X)
1081#define ADDARGC(X) Args.push_back(X); Size += sizeof(X) - 1
1082
1083 ADDARGC("--status-fd");
1084 char status_fd_buf[20];
75ef8f14 1085 snprintf(status_fd_buf,sizeof(status_fd_buf),"%i", fd[1]);
edca7af0 1086 ADDARG(status_fd_buf);
11b87a08 1087 unsigned long const Op = I->Op;
007dc9e0 1088
03e39e59
AL
1089 switch (I->Op)
1090 {
1091 case Item::Remove:
edca7af0
DK
1092 ADDARGC("--force-depends");
1093 ADDARGC("--force-remove-essential");
1094 ADDARGC("--remove");
03e39e59
AL
1095 break;
1096
fc4b5c9f 1097 case Item::Purge:
edca7af0
DK
1098 ADDARGC("--force-depends");
1099 ADDARGC("--force-remove-essential");
1100 ADDARGC("--purge");
fc4b5c9f
AL
1101 break;
1102
03e39e59 1103 case Item::Configure:
edca7af0 1104 ADDARGC("--configure");
03e39e59 1105 break;
3e9c4f70
DK
1106
1107 case Item::ConfigurePending:
edca7af0
DK
1108 ADDARGC("--configure");
1109 ADDARGC("--pending");
3e9c4f70
DK
1110 break;
1111
5e312de7 1112 case Item::TriggersPending:
edca7af0
DK
1113 ADDARGC("--triggers-only");
1114 ADDARGC("--pending");
5e312de7
DK
1115 break;
1116
03e39e59 1117 case Item::Install:
edca7af0
DK
1118 ADDARGC("--unpack");
1119 ADDARGC("--auto-deconfigure");
03e39e59
AL
1120 break;
1121 }
3e9c4f70 1122
5e312de7 1123 if (NoTriggers == true && I->Op != Item::TriggersPending &&
d5081aee 1124 I->Op != Item::ConfigurePending)
3e9c4f70 1125 {
edca7af0 1126 ADDARGC("--no-triggers");
3e9c4f70 1127 }
edca7af0 1128#undef ADDARGC
3e9c4f70 1129
03e39e59
AL
1130 // Write in the file or package names
1131 if (I->Op == Item::Install)
30e1eab5 1132 {
f7f0d6c7 1133 for (;I != J && Size < MaxArgBytes; ++I)
30e1eab5 1134 {
cf544e14
AL
1135 if (I->File[0] != '/')
1136 return _error->Error("Internal Error, Pathname to install is not absolute '%s'",I->File.c_str());
edca7af0
DK
1137 Args.push_back(I->File.c_str());
1138 Size += I->File.length();
30e1eab5 1139 }
edca7af0 1140 }
03e39e59 1141 else
30e1eab5 1142 {
8e11253d 1143 string const nativeArch = _config->Find("APT::Architecture");
6f31b247 1144 unsigned long const oldSize = I->Op == Item::Configure ? Size : 0;
f7f0d6c7 1145 for (;I != J && Size < MaxArgBytes; ++I)
30e1eab5 1146 {
3e9c4f70
DK
1147 if((*I).Pkg.end() == true)
1148 continue;
642ebc1a
DK
1149 if (I->Op == Item::Configure && disappearedPkgs.find(I->Pkg.Name()) != disappearedPkgs.end())
1150 continue;
86fc2ca8
DK
1151 // We keep this here to allow "smooth" transitions from e.g. multiarch dpkg/ubuntu to dpkg/debian
1152 if (dpkgMultiArch == false && (I->Pkg.Arch() == nativeArch || !strcmp(I->Pkg.Arch(), "all")))
edca7af0
DK
1153 {
1154 char const * const name = I->Pkg.Name();
1155 ADDARG(name);
1156 }
8e11253d
SL
1157 else
1158 {
7720666f 1159 pkgCache::VerIterator PkgVer;
3a5ec305 1160 std::string name = I->Pkg.Name();
a1355481
MV
1161 if (Op == Item::Remove || Op == Item::Purge)
1162 {
2a2a7ef4 1163 PkgVer = I->Pkg.CurrentVer();
a1355481
MV
1164 if(PkgVer.end() == true)
1165 PkgVer = FindNowVersion(I->Pkg);
1166 }
7720666f 1167 else
2a2a7ef4 1168 PkgVer = Cache[I->Pkg].InstVerIter(Cache);
a1355481
MV
1169 if (PkgVer.end() == false)
1170 name.append(":").append(PkgVer.Arch());
1171 else
1172 _error->Warning("Can not find PkgVer for '%s'", name.c_str());
3a5ec305 1173 char * const fullname = strdup(name.c_str());
edca7af0
DK
1174 Packages.push_back(fullname);
1175 ADDARG(fullname);
8e11253d 1176 }
6f31b247
DK
1177 }
1178 // skip configure action if all sheduled packages disappeared
1179 if (oldSize == Size)
1180 continue;
1181 }
edca7af0
DK
1182#undef ADDARG
1183
30e1eab5
AL
1184 J = I;
1185
1186 if (_config->FindB("Debug::pkgDPkgPM",false) == true)
1187 {
edca7af0
DK
1188 for (std::vector<const char *>::const_iterator a = Args.begin();
1189 a != Args.end(); ++a)
1190 clog << *a << ' ';
11bcbdb9 1191 clog << endl;
30e1eab5
AL
1192 continue;
1193 }
edca7af0
DK
1194 Args.push_back(NULL);
1195
03e39e59
AL
1196 cout << flush;
1197 clog << flush;
1198 cerr << flush;
1199
1200 /* Mask off sig int/quit. We do this because dpkg also does when
1201 it forks scripts. What happens is that when you hit ctrl-c it sends
1202 it to all processes in the group. Since dpkg ignores the signal
1203 it doesn't die but we do! So we must also ignore it */
7f9a6360 1204 sighandler_t old_SIGQUIT = signal(SIGQUIT,SIG_IGN);
590f1923 1205 sighandler_t old_SIGINT = signal(SIGINT,SigINT);
1cecd437
CB
1206
1207 // Check here for any SIGINT
11b87a08
CB
1208 if (pkgPackageManager::SigINTStop && (Op == Item::Remove || Op == Item::Purge || Op == Item::Install))
1209 break;
1210
1211
73e598c3
MV
1212 // ignore SIGHUP as well (debian #463030)
1213 sighandler_t old_SIGHUP = signal(SIGHUP,SIG_IGN);
1214
d8cb4aa4
MV
1215 struct termios tt;
1216 struct winsize win;
4e550036
MV
1217 int master = -1;
1218 int slave = -1;
d8cb4aa4 1219
4e550036
MV
1220 // if tcgetattr does not return zero there was a error
1221 // and we do not do any pty magic
1222 if (tcgetattr(0, &tt) == 0)
090c6566 1223 {
4e550036
MV
1224 ioctl(0, TIOCGWINSZ, (char *)&win);
1225 if (openpty(&master, &slave, NULL, &tt, &win) < 0)
1226 {
1227 const char *s = _("Can not write log, openpty() "
1228 "failed (/dev/pts not mounted?)\n");
1229 fprintf(stderr, "%s",s);
697a1d8a
MV
1230 if(d->term_out)
1231 fprintf(d->term_out, "%s",s);
4e550036
MV
1232 master = slave = -1;
1233 } else {
1234 struct termios rtt;
1235 rtt = tt;
1236 cfmakeraw(&rtt);
1237 rtt.c_lflag &= ~ECHO;
4d7ac88c 1238 rtt.c_lflag |= ISIG;
4e550036
MV
1239 // block SIGTTOU during tcsetattr to prevent a hang if
1240 // the process is a member of the background process group
1241 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
1242 sigemptyset(&sigmask);
1243 sigaddset(&sigmask, SIGTTOU);
1244 sigprocmask(SIG_BLOCK,&sigmask, &original_sigmask);
1245 tcsetattr(0, TCSAFLUSH, &rtt);
1246 sigprocmask(SIG_SETMASK, &original_sigmask, 0);
1247 }
d8cb4aa4 1248 }
75ef8f14 1249 // Fork dpkg
007dc9e0 1250 pid_t Child;
75ef8f14 1251 _config->Set("APT::Keep-Fds::",fd[1]);
ccd8e28f
MV
1252 // send status information that we are about to fork dpkg
1253 if(OutStatusFd > 0) {
1254 ostringstream status;
1255 status << "pmstatus:dpkg-exec:"
1256 << (PackagesDone/float(PackagesTotal)*100.0)
1257 << ":" << _("Running dpkg")
1258 << endl;
319790f4 1259 retry_write(OutStatusFd, status.str().c_str(), status.str().size());
ccd8e28f 1260 }
75ef8f14 1261 Child = ExecFork();
6dd55be7 1262
03e39e59
AL
1263 // This is the child
1264 if (Child == 0)
1265 {
a4cf3665
MV
1266 if(slave >= 0 && master >= 0)
1267 {
1268 setsid();
1269 ioctl(slave, TIOCSCTTY, 0);
1270 close(master);
1271 dup2(slave, 0);
1272 dup2(slave, 1);
1273 dup2(slave, 2);
1274 close(slave);
1275 }
75ef8f14 1276 close(fd[0]); // close the read end of the pipe
d8cb4aa4 1277
e6ee75af 1278 dpkgChrootDirectory();
4b7cfe96 1279
cf544e14 1280 if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
0dbb95d8 1281 _exit(100);
03e39e59 1282
421ff807 1283 if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
8b5fe26c
AL
1284 {
1285 int Flags,dummy;
1286 if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
1287 _exit(100);
1288
1289 // Discard everything in stdin before forking dpkg
1290 if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
1291 _exit(100);
1292
1293 while (read(STDIN_FILENO,&dummy,1) == 1);
1294
1295 if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
1296 _exit(100);
1297 }
d8cb4aa4 1298
03e39e59
AL
1299 /* No Job Control Stop Env is a magic dpkg var that prevents it
1300 from using sigstop */
71afbdb5 1301 putenv((char *)"DPKG_NO_TSTP=yes");
edca7af0 1302 execvp(Args[0], (char**) &Args[0]);
03e39e59 1303 cerr << "Could not exec dpkg!" << endl;
0dbb95d8 1304 _exit(100);
03e39e59
AL
1305 }
1306
cebe0287
MV
1307 // apply ionice
1308 if (_config->FindB("DPkg::UseIoNice", false) == true)
1309 ionice(Child);
1310
75ef8f14
MV
1311 // clear the Keep-Fd again
1312 _config->Clear("APT::Keep-Fds",fd[1]);
1313
03e39e59
AL
1314 // Wait for dpkg
1315 int Status = 0;
75ef8f14
MV
1316
1317 // we read from dpkg here
887f5036 1318 int const _dpkgin = fd[0];
75ef8f14
MV
1319 close(fd[1]); // close the write end of the pipe
1320
a4cf3665
MV
1321 if(slave > 0)
1322 close(slave);
6191b008 1323
97efd303 1324 // setups fds
7052511e
MV
1325 sigemptyset(&sigmask);
1326 sigprocmask(SIG_BLOCK,&sigmask,&original_sigmask);
1327
edca7af0
DK
1328 /* free vectors (and therefore memory) as we don't need the included data anymore */
1329 for (std::vector<char *>::const_iterator p = Packages.begin();
1330 p != Packages.end(); ++p)
1331 free(*p);
1332 Packages.clear();
8e11253d 1333
887f5036
DK
1334 // the result of the waitpid call
1335 int res;
090c6566 1336 int select_ret;
75ef8f14
MV
1337 while ((res=waitpid(Child,&Status, WNOHANG)) != Child) {
1338 if(res < 0) {
1339 // FIXME: move this to a function or something, looks ugly here
1340 // error handling, waitpid returned -1
1341 if (errno == EINTR)
1342 continue;
1343 RunScripts("DPkg::Post-Invoke");
1344
1345 // Restore sig int/quit
1346 signal(SIGQUIT,old_SIGQUIT);
1347 signal(SIGINT,old_SIGINT);
590f1923 1348
e306ec47 1349 signal(SIGHUP,old_SIGHUP);
75ef8f14
MV
1350 return _error->Errno("waitpid","Couldn't wait for subprocess");
1351 }
d8cb4aa4
MV
1352
1353 // wait for input or output here
955a6ddb 1354 FD_ZERO(&rfds);
697a1d8a 1355 if (master >= 0 && !d->stdin_is_dev_null)
9983591d 1356 FD_SET(0, &rfds);
955a6ddb 1357 FD_SET(_dpkgin, &rfds);
a4cf3665
MV
1358 if(master >= 0)
1359 FD_SET(master, &rfds);
090c6566 1360 tv.tv_sec = 1;
7052511e
MV
1361 tv.tv_nsec = 0;
1362 select_ret = pselect(max(master, _dpkgin)+1, &rfds, NULL, NULL,
1363 &tv, &original_sigmask);
919e5852
OS
1364 if (select_ret < 0 && (errno == EINVAL || errno == ENOSYS))
1365 select_ret = racy_pselect(max(master, _dpkgin)+1, &rfds, NULL,
1366 NULL, &tv, &original_sigmask);
da50ba30
MV
1367 if (select_ret == 0)
1368 continue;
1369 else if (select_ret < 0 && errno == EINTR)
1370 continue;
1371 else if (select_ret < 0)
1372 {
1373 perror("select() returned error");
1374 continue;
1375 }
1376
a4cf3665 1377 if(master >= 0 && FD_ISSET(master, &rfds))
1ba38171 1378 DoTerminalPty(master);
a4cf3665 1379 if(master >= 0 && FD_ISSET(0, &rfds))
955a6ddb 1380 DoStdin(master);
955a6ddb 1381 if(FD_ISSET(_dpkgin, &rfds))
09fa2df2 1382 DoDpkgStatusFd(_dpkgin, OutStatusFd);
03e39e59 1383 }
75ef8f14 1384 close(_dpkgin);
03e39e59
AL
1385
1386 // Restore sig int/quit
7f9a6360
AL
1387 signal(SIGQUIT,old_SIGQUIT);
1388 signal(SIGINT,old_SIGINT);
590f1923 1389
d9ec0fac 1390 signal(SIGHUP,old_SIGHUP);
d8cb4aa4 1391
477b5d6c
MV
1392 if(master >= 0)
1393 {
a4cf3665 1394 tcsetattr(0, TCSAFLUSH, &tt);
477b5d6c
MV
1395 close(master);
1396 }
6dd55be7
AL
1397
1398 // Check for an error code.
1399 if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
1400 {
c70496f9
MV
1401 // if it was set to "keep-dpkg-runing" then we won't return
1402 // here but keep the loop going and just report it as a error
1403 // for later
887f5036 1404 bool const stopOnError = _config->FindB("Dpkg::StopOnError",true);
f956efb4 1405
c70496f9
MV
1406 if(stopOnError)
1407 RunScripts("DPkg::Post-Invoke");
1408
1409 if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
697a1d8a 1410 strprintf(d->dpkg_error, "Sub-process %s received a segmentation fault.",Args[0]);
c70496f9 1411 else if (WIFEXITED(Status) != 0)
697a1d8a 1412 strprintf(d->dpkg_error, "Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
c70496f9 1413 else
697a1d8a 1414 strprintf(d->dpkg_error, "Sub-process %s exited unexpectedly",Args[0]);
9169c871 1415
697a1d8a 1416 if(d->dpkg_error.size() > 0)
36b8ebbb 1417 _error->Error("%s", d->dpkg_error.c_str());
c70496f9 1418
ff56e980
MV
1419 if(stopOnError)
1420 {
2e1715ea 1421 CloseLog();
c70496f9 1422 return false;
ff56e980 1423 }
6dd55be7 1424 }
03e39e59 1425 }
2e1715ea 1426 CloseLog();
11b87a08
CB
1427
1428 if (pkgPackageManager::SigINTStop)
1429 _error->Warning(_("Operation was interrupted before it could finish"));
6dd55be7
AL
1430
1431 if (RunScripts("DPkg::Post-Invoke") == false)
1432 return false;
b462d75a 1433
388f2962
DK
1434 if (_config->FindB("Debug::pkgDPkgPM",false) == false)
1435 {
1436 std::string const oldpkgcache = _config->FindFile("Dir::cache::pkgcache");
1437 if (oldpkgcache.empty() == false && RealFileExists(oldpkgcache) == true &&
1438 unlink(oldpkgcache.c_str()) == 0)
1439 {
1440 std::string const srcpkgcache = _config->FindFile("Dir::cache::srcpkgcache");
1441 if (srcpkgcache.empty() == false && RealFileExists(srcpkgcache) == true)
1442 {
1443 _error->PushToStack();
1444 pkgCacheFile CacheFile;
1445 CacheFile.BuildCaches(NULL, true);
1446 _error->RevertToStack();
1447 }
1448 }
1449 }
1450
b462d75a 1451 Cache.writeStateFile(NULL);
03e39e59
AL
1452 return true;
1453}
590f1923
CB
1454
1455void SigINT(int sig) {
b1803e01
DK
1456 pkgPackageManager::SigINTStop = true;
1457}
03e39e59 1458 /*}}}*/
281daf46
AL
1459// pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1460// ---------------------------------------------------------------------
1461/* */
1462void pkgDPkgPM::Reset()
1463{
1464 List.erase(List.begin(),List.end());
1465}
1466 /*}}}*/
5e457a93
MV
1467// pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1468// ---------------------------------------------------------------------
1469/* */
1470void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
1471{
dd61e64d
DK
1472 // If apport doesn't exist or isn't installed do nothing
1473 // This e.g. prevents messages in 'universes' without apport
1474 pkgCache::PkgIterator apportPkg = Cache.FindPkg("apport");
1475 if (apportPkg.end() == true || apportPkg->CurrentVer == 0)
1476 return;
1477
5e457a93
MV
1478 string pkgname, reportfile, srcpkgname, pkgver, arch;
1479 string::size_type pos;
1480 FILE *report;
1481
23c5897c 1482 if (_config->FindB("Dpkg::ApportFailureReport", false) == false)
ff38d63b
MV
1483 {
1484 std::clog << "configured to not write apport reports" << std::endl;
5e457a93 1485 return;
ff38d63b 1486 }
5e457a93 1487
d6a4afcb 1488 // only report the first errors
5273f1bf 1489 if(pkgFailures > _config->FindI("APT::Apport::MaxReports", 3))
ff38d63b
MV
1490 {
1491 std::clog << _("No apport report written because MaxReports is reached already") << std::endl;
5e457a93 1492 return;
ff38d63b 1493 }
5e457a93 1494
d6a4afcb
MV
1495 // check if its not a follow up error
1496 const char *needle = dgettext("dpkg", "dependency problems - leaving unconfigured");
1497 if(strstr(errormsg, needle) != NULL) {
1498 std::clog << _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl;
1499 return;
1500 }
1501
2f0d5dea
MV
1502 // do not report disk-full failures
1503 if(strstr(errormsg, strerror(ENOSPC)) != NULL) {
1504 std::clog << _("No apport report written because the error message indicates a disk full error") << std::endl;
1505 return;
1506 }
1507
3024a85e
MV
1508 // do not report out-of-memory failures
1509 if(strstr(errormsg, strerror(ENOMEM)) != NULL) {
1510 std::clog << _("No apport report written because the error message indicates a out of memory error") << std::endl;
1511 return;
1512 }
1513
076c46e5
MZ
1514 // do not report dpkg I/O errors
1515 // XXX - this message is localized, but this only matches the English version. This is better than nothing.
1516 if(strstr(errormsg, "short read in buffer_copy (")) {
1517 std::clog << _("No apport report written because the error message indicates a dpkg I/O error") << std::endl;
1518 return;
1519 }
1520
5e457a93
MV
1521 // get the pkgname and reportfile
1522 pkgname = flNotDir(pkgpath);
25ffa4e8 1523 pos = pkgname.find('_');
5e457a93 1524 if(pos != string::npos)
25ffa4e8 1525 pkgname = pkgname.substr(0, pos);
5e457a93
MV
1526
1527 // find the package versin and source package name
1528 pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
1529 if (Pkg.end() == true)
1530 return;
1531 pkgCache::VerIterator Ver = Cache.GetCandidateVer(Pkg);
5e457a93
MV
1532 if (Ver.end() == true)
1533 return;
986d97bb 1534 pkgver = Ver.VerStr() == NULL ? "unknown" : Ver.VerStr();
5e457a93
MV
1535 pkgRecords Recs(Cache);
1536 pkgRecords::Parser &Parse = Recs.Lookup(Ver.FileList());
1537 srcpkgname = Parse.SourcePkg();
1538 if(srcpkgname.empty())
1539 srcpkgname = pkgname;
1540
1541 // if the file exists already, we check:
1542 // - if it was reported already (touched by apport).
1543 // If not, we do nothing, otherwise
1544 // we overwrite it. This is the same behaviour as apport
1545 // - if we have a report with the same pkgversion already
1546 // then we skip it
1547 reportfile = flCombine("/var/crash",pkgname+".0.crash");
1548 if(FileExists(reportfile))
1549 {
1550 struct stat buf;
1551 char strbuf[255];
1552
1553 // check atime/mtime
1554 stat(reportfile.c_str(), &buf);
1555 if(buf.st_mtime > buf.st_atime)
1556 return;
1557
1558 // check if the existing report is the same version
1559 report = fopen(reportfile.c_str(),"r");
1560 while(fgets(strbuf, sizeof(strbuf), report) != NULL)
1561 {
1562 if(strstr(strbuf,"Package:") == strbuf)
1563 {
1564 char pkgname[255], version[255];
b3c36c6e 1565 if(sscanf(strbuf, "Package: %254s %254s", pkgname, version) == 2)
5e457a93
MV
1566 if(strcmp(pkgver.c_str(), version) == 0)
1567 {
1568 fclose(report);
1569 return;
1570 }
1571 }
1572 }
1573 fclose(report);
1574 }
1575
1576 // now write the report
1577 arch = _config->Find("APT::Architecture");
1578 report = fopen(reportfile.c_str(),"w");
1579 if(report == NULL)
1580 return;
1581 if(_config->FindB("DPkgPM::InitialReportOnly",false) == true)
1582 chmod(reportfile.c_str(), 0);
1583 else
1584 chmod(reportfile.c_str(), 0600);
1585 fprintf(report, "ProblemType: Package\n");
1586 fprintf(report, "Architecture: %s\n", arch.c_str());
1587 time_t now = time(NULL);
1588 fprintf(report, "Date: %s" , ctime(&now));
1589 fprintf(report, "Package: %s %s\n", pkgname.c_str(), pkgver.c_str());
1590 fprintf(report, "SourcePackage: %s\n", srcpkgname.c_str());
1591 fprintf(report, "ErrorMessage:\n %s\n", errormsg);
8ecd1fed
MV
1592
1593 // ensure that the log is flushed
697a1d8a
MV
1594 if(d->term_out)
1595 fflush(d->term_out);
8ecd1fed
MV
1596
1597 // attach terminal log it if we have it
1598 string logfile_name = _config->FindFile("Dir::Log::Terminal");
1599 if (!logfile_name.empty())
1600 {
1601 FILE *log = NULL;
1602 char buf[1024];
1603
1604 fprintf(report, "DpkgTerminalLog:\n");
1605 log = fopen(logfile_name.c_str(),"r");
1606 if(log != NULL)
1607 {
1608 while( fgets(buf, sizeof(buf), log) != NULL)
1609 fprintf(report, " %s", buf);
1610 fclose(log);
1611 }
1612 }
76dbdfc7 1613
5c8a2aa8
MV
1614 // log the ordering
1615 const char *ops_str[] = {"Install", "Configure","Remove","Purge"};
1616 fprintf(report, "AptOrdering:\n");
f7f0d6c7 1617 for (vector<Item>::iterator I = List.begin(); I != List.end(); ++I)
5c8a2aa8
MV
1618 fprintf(report, " %s: %s\n", (*I).Pkg.Name(), ops_str[(*I).Op]);
1619
76dbdfc7
MV
1620 // attach dmesg log (to learn about segfaults)
1621 if (FileExists("/bin/dmesg"))
1622 {
1623 FILE *log = NULL;
1624 char buf[1024];
1625
1626 fprintf(report, "Dmesg:\n");
1627 log = popen("/bin/dmesg","r");
1628 if(log != NULL)
1629 {
1630 while( fgets(buf, sizeof(buf), log) != NULL)
1631 fprintf(report, " %s", buf);
23f3cfd0 1632 pclose(log);
76dbdfc7
MV
1633 }
1634 }
2183a086
MV
1635
1636 // attach df -l log (to learn about filesystem status)
1637 if (FileExists("/bin/df"))
1638 {
1639 FILE *log = NULL;
1640 char buf[1024];
1641
1642 fprintf(report, "Df:\n");
1643 log = popen("/bin/df -l","r");
1644 if(log != NULL)
1645 {
1646 while( fgets(buf, sizeof(buf), log) != NULL)
1647 fprintf(report, " %s", buf);
23f3cfd0 1648 pclose(log);
2183a086
MV
1649 }
1650 }
1651
5e457a93 1652 fclose(report);
76dbdfc7 1653
5e457a93
MV
1654}
1655 /*}}}*/