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