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