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