]> git.saurik.com Git - apt.git/blob - apt-pkg/deb/dpkgpm.cc
Merge branch 'debian/sid' into ubuntu/master
[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 <stdio.h>
34 #include <string.h>
35 #include <algorithm>
36 #include <sstream>
37 #include <map>
38 #include <pwd.h>
39 #include <grp.h>
40 #include <iomanip>
41
42 #include <termios.h>
43 #include <unistd.h>
44 #include <sys/ioctl.h>
45 #include <pty.h>
46
47 #include <apti18n.h>
48 /*}}}*/
49
50 using namespace std;
51
52 class pkgDPkgPMPrivate
53 {
54 public:
55 pkgDPkgPMPrivate() : stdin_is_dev_null(false), dpkgbuf_pos(0),
56 term_out(NULL), history_out(NULL),
57 progress(NULL), master(-1), slave(-1)
58 {
59 dpkgbuf[0] = '\0';
60 }
61 ~pkgDPkgPMPrivate()
62 {
63 }
64 bool stdin_is_dev_null;
65 // the buffer we use for the dpkg status-fd reading
66 char dpkgbuf[1024];
67 int dpkgbuf_pos;
68 FILE *term_out;
69 FILE *history_out;
70 string dpkg_error;
71 APT::Progress::PackageManager *progress;
72
73 // pty stuff
74 struct termios tt;
75 int master;
76 int slave;
77
78 // signals
79 sigset_t sigmask;
80 sigset_t original_sigmask;
81
82 };
83
84 namespace
85 {
86 // Maps the dpkg "processing" info to human readable names. Entry 0
87 // of each array is the key, entry 1 is the value.
88 const std::pair<const char *, const char *> PackageProcessingOps[] = {
89 std::make_pair("install", N_("Installing %s")),
90 std::make_pair("configure", N_("Configuring %s")),
91 std::make_pair("remove", N_("Removing %s")),
92 std::make_pair("purge", N_("Completely removing %s")),
93 std::make_pair("disappear", N_("Noting disappearance of %s")),
94 std::make_pair("trigproc", N_("Running post-installation trigger %s"))
95 };
96
97 const std::pair<const char *, const char *> * const PackageProcessingOpsBegin = PackageProcessingOps;
98 const std::pair<const char *, const char *> * const PackageProcessingOpsEnd = PackageProcessingOps + sizeof(PackageProcessingOps) / sizeof(PackageProcessingOps[0]);
99
100 // Predicate to test whether an entry in the PackageProcessingOps
101 // array matches a string.
102 class MatchProcessingOp
103 {
104 const char *target;
105
106 public:
107 MatchProcessingOp(const char *the_target)
108 : target(the_target)
109 {
110 }
111
112 bool operator()(const std::pair<const char *, const char *> &pair) const
113 {
114 return strcmp(pair.first, target) == 0;
115 }
116 };
117 }
118
119 /* helper function to ionice the given PID
120
121 there is no C header for ionice yet - just the syscall interface
122 so we use the binary from util-linux
123 */
124 static bool
125 ionice(int PID)
126 {
127 if (!FileExists("/usr/bin/ionice"))
128 return false;
129 pid_t Process = ExecFork();
130 if (Process == 0)
131 {
132 char buf[32];
133 snprintf(buf, sizeof(buf), "-p%d", PID);
134 const char *Args[4];
135 Args[0] = "/usr/bin/ionice";
136 Args[1] = "-c3";
137 Args[2] = buf;
138 Args[3] = 0;
139 execv(Args[0], (char **)Args);
140 }
141 return ExecWait(Process, "ionice");
142 }
143
144 static std::string getDpkgExecutable()
145 {
146 string Tmp = _config->Find("Dir::Bin::dpkg","dpkg");
147 string const dpkgChrootDir = _config->FindDir("DPkg::Chroot-Directory", "/");
148 size_t dpkgChrootLen = dpkgChrootDir.length();
149 if (dpkgChrootDir != "/" && Tmp.find(dpkgChrootDir) == 0)
150 {
151 if (dpkgChrootDir[dpkgChrootLen - 1] == '/')
152 --dpkgChrootLen;
153 Tmp = Tmp.substr(dpkgChrootLen);
154 }
155 return Tmp;
156 }
157
158 // dpkgChrootDirectory - chrooting for dpkg if needed /*{{{*/
159 static void dpkgChrootDirectory()
160 {
161 std::string const chrootDir = _config->FindDir("DPkg::Chroot-Directory");
162 if (chrootDir == "/")
163 return;
164 std::cerr << "Chrooting into " << chrootDir << std::endl;
165 if (chroot(chrootDir.c_str()) != 0)
166 _exit(100);
167 if (chdir("/") != 0)
168 _exit(100);
169 }
170 /*}}}*/
171
172
173 // FindNowVersion - Helper to find a Version in "now" state /*{{{*/
174 // ---------------------------------------------------------------------
175 /* This is helpful when a package is no longer installed but has residual
176 * config files
177 */
178 static
179 pkgCache::VerIterator FindNowVersion(const pkgCache::PkgIterator &Pkg)
180 {
181 pkgCache::VerIterator Ver;
182 for (Ver = Pkg.VersionList(); Ver.end() == false; ++Ver)
183 {
184 pkgCache::VerFileIterator Vf = Ver.FileList();
185 pkgCache::PkgFileIterator F = Vf.File();
186 for (F = Vf.File(); F.end() == false; ++F)
187 {
188 if (F && F.Archive())
189 {
190 if (strcmp(F.Archive(), "now"))
191 return Ver;
192 }
193 }
194 }
195 return Ver;
196 }
197 /*}}}*/
198
199 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
200 // ---------------------------------------------------------------------
201 /* */
202 pkgDPkgPM::pkgDPkgPM(pkgDepCache *Cache)
203 : pkgPackageManager(Cache), PackagesDone(0), PackagesTotal(0)
204 {
205 d = new pkgDPkgPMPrivate();
206 }
207 /*}}}*/
208 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
209 // ---------------------------------------------------------------------
210 /* */
211 pkgDPkgPM::~pkgDPkgPM()
212 {
213 delete d;
214 }
215 /*}}}*/
216 // DPkgPM::Install - Install a package /*{{{*/
217 // ---------------------------------------------------------------------
218 /* Add an install operation to the sequence list */
219 bool pkgDPkgPM::Install(PkgIterator Pkg,string File)
220 {
221 if (File.empty() == true || Pkg.end() == true)
222 return _error->Error("Internal Error, No file name for %s",Pkg.FullName().c_str());
223
224 // If the filename string begins with DPkg::Chroot-Directory, return the
225 // substr that is within the chroot so dpkg can access it.
226 string const chrootdir = _config->FindDir("DPkg::Chroot-Directory","/");
227 if (chrootdir != "/" && File.find(chrootdir) == 0)
228 {
229 size_t len = chrootdir.length();
230 if (chrootdir.at(len - 1) == '/')
231 len--;
232 List.push_back(Item(Item::Install,Pkg,File.substr(len)));
233 }
234 else
235 List.push_back(Item(Item::Install,Pkg,File));
236
237 return true;
238 }
239 /*}}}*/
240 // DPkgPM::Configure - Configure a package /*{{{*/
241 // ---------------------------------------------------------------------
242 /* Add a configure operation to the sequence list */
243 bool pkgDPkgPM::Configure(PkgIterator Pkg)
244 {
245 if (Pkg.end() == true)
246 return false;
247
248 List.push_back(Item(Item::Configure, Pkg));
249
250 // Use triggers for config calls if we configure "smart"
251 // as otherwise Pre-Depends will not be satisfied, see #526774
252 if (_config->FindB("DPkg::TriggersPending", false) == true)
253 List.push_back(Item(Item::TriggersPending, PkgIterator()));
254
255 return true;
256 }
257 /*}}}*/
258 // DPkgPM::Remove - Remove a package /*{{{*/
259 // ---------------------------------------------------------------------
260 /* Add a remove operation to the sequence list */
261 bool pkgDPkgPM::Remove(PkgIterator Pkg,bool Purge)
262 {
263 if (Pkg.end() == true)
264 return false;
265
266 if (Purge == true)
267 List.push_back(Item(Item::Purge,Pkg));
268 else
269 List.push_back(Item(Item::Remove,Pkg));
270 return true;
271 }
272 /*}}}*/
273 // DPkgPM::SendPkgInfo - Send info for install-pkgs hook /*{{{*/
274 // ---------------------------------------------------------------------
275 /* This is part of the helper script communication interface, it sends
276 very complete information down to the other end of the pipe.*/
277 bool pkgDPkgPM::SendV2Pkgs(FILE *F)
278 {
279 return SendPkgsInfo(F, 2);
280 }
281 bool pkgDPkgPM::SendPkgsInfo(FILE * const F, unsigned int const &Version)
282 {
283 // This version of APT supports only v3, so don't sent higher versions
284 if (Version <= 3)
285 fprintf(F,"VERSION %u\n", Version);
286 else
287 fprintf(F,"VERSION 3\n");
288
289 /* Write out all of the configuration directives by walking the
290 configuration tree */
291 const Configuration::Item *Top = _config->Tree(0);
292 for (; Top != 0;)
293 {
294 if (Top->Value.empty() == false)
295 {
296 fprintf(F,"%s=%s\n",
297 QuoteString(Top->FullTag(),"=\"\n").c_str(),
298 QuoteString(Top->Value,"\n").c_str());
299 }
300
301 if (Top->Child != 0)
302 {
303 Top = Top->Child;
304 continue;
305 }
306
307 while (Top != 0 && Top->Next == 0)
308 Top = Top->Parent;
309 if (Top != 0)
310 Top = Top->Next;
311 }
312 fprintf(F,"\n");
313
314 // Write out the package actions in order.
315 for (vector<Item>::iterator I = List.begin(); I != List.end(); ++I)
316 {
317 if(I->Pkg.end() == true)
318 continue;
319
320 pkgDepCache::StateCache &S = Cache[I->Pkg];
321
322 fprintf(F,"%s ",I->Pkg.Name());
323
324 // Current version which we are going to replace
325 pkgCache::VerIterator CurVer = I->Pkg.CurrentVer();
326 if (CurVer.end() == true && (I->Op == Item::Remove || I->Op == Item::Purge))
327 CurVer = FindNowVersion(I->Pkg);
328
329 if (CurVer.end() == true)
330 {
331 if (Version <= 2)
332 fprintf(F, "- ");
333 else
334 fprintf(F, "- - none ");
335 }
336 else
337 {
338 fprintf(F, "%s ", CurVer.VerStr());
339 if (Version >= 3)
340 fprintf(F, "%s %s ", CurVer.Arch(), CurVer.MultiArchType());
341 }
342
343 // Show the compare operator between current and install version
344 if (S.InstallVer != 0)
345 {
346 pkgCache::VerIterator const InstVer = S.InstVerIter(Cache);
347 int Comp = 2;
348 if (CurVer.end() == false)
349 Comp = InstVer.CompareVer(CurVer);
350 if (Comp < 0)
351 fprintf(F,"> ");
352 else if (Comp == 0)
353 fprintf(F,"= ");
354 else if (Comp > 0)
355 fprintf(F,"< ");
356 fprintf(F, "%s ", InstVer.VerStr());
357 if (Version >= 3)
358 fprintf(F, "%s %s ", InstVer.Arch(), InstVer.MultiArchType());
359 }
360 else
361 {
362 if (Version <= 2)
363 fprintf(F, "> - ");
364 else
365 fprintf(F, "> - - none ");
366 }
367
368 // Show the filename/operation
369 if (I->Op == Item::Install)
370 {
371 // No errors here..
372 if (I->File[0] != '/')
373 fprintf(F,"**ERROR**\n");
374 else
375 fprintf(F,"%s\n",I->File.c_str());
376 }
377 else if (I->Op == Item::Configure)
378 fprintf(F,"**CONFIGURE**\n");
379 else if (I->Op == Item::Remove ||
380 I->Op == Item::Purge)
381 fprintf(F,"**REMOVE**\n");
382
383 if (ferror(F) != 0)
384 return false;
385 }
386 return true;
387 }
388 /*}}}*/
389 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
390 // ---------------------------------------------------------------------
391 /* This looks for a list of scripts to run from the configuration file
392 each one is run and is fed on standard input a list of all .deb files
393 that are due to be installed. */
394 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf)
395 {
396 Configuration::Item const *Opts = _config->Tree(Cnf);
397 if (Opts == 0 || Opts->Child == 0)
398 return true;
399 Opts = Opts->Child;
400
401 unsigned int Count = 1;
402 for (; Opts != 0; Opts = Opts->Next, Count++)
403 {
404 if (Opts->Value.empty() == true)
405 continue;
406
407 // Determine the protocol version
408 string OptSec = Opts->Value;
409 string::size_type Pos;
410 if ((Pos = OptSec.find(' ')) == string::npos || Pos == 0)
411 Pos = OptSec.length();
412 OptSec = "DPkg::Tools::Options::" + string(Opts->Value.c_str(),Pos);
413
414 unsigned int Version = _config->FindI(OptSec+"::Version",1);
415 unsigned int InfoFD = _config->FindI(OptSec + "::InfoFD", STDIN_FILENO);
416
417 // Create the pipes
418 std::set<int> KeepFDs;
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 KeepFDs.insert(Pipes[0]);
426
427
428 SetCloseExec(Pipes[1],true);
429
430 // Purified Fork for running the script
431 pid_t Process = ExecFork(KeepFDs);
432 if (Process == 0)
433 {
434 // Setup the FDs
435 dup2(Pipes[0], InfoFD);
436 SetCloseExec(STDOUT_FILENO,false);
437 SetCloseExec(STDIN_FILENO,false);
438 SetCloseExec(STDERR_FILENO,false);
439
440 string hookfd;
441 strprintf(hookfd, "%d", InfoFD);
442 setenv("APT_HOOK_INFO_FD", hookfd.c_str(), 1);
443
444 dpkgChrootDirectory();
445 const char *Args[4];
446 Args[0] = "/bin/sh";
447 Args[1] = "-c";
448 Args[2] = Opts->Value.c_str();
449 Args[3] = 0;
450 execv(Args[0],(char **)Args);
451 _exit(100);
452 }
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 // now run dpkg
1379 d->progress->StartDpkg();
1380 std::set<int> KeepFDs;
1381 KeepFDs.insert(fd[1]);
1382 pid_t Child = ExecFork(KeepFDs);
1383 if (Child == 0)
1384 {
1385 // This is the child
1386 if(d->slave >= 0 && d->master >= 0)
1387 {
1388 setsid();
1389 ioctl(d->slave, TIOCSCTTY, 0);
1390 close(d->master);
1391 dup2(d->slave, 0);
1392 dup2(d->slave, 1);
1393 dup2(d->slave, 2);
1394 close(d->slave);
1395 }
1396 close(fd[0]); // close the read end of the pipe
1397
1398 dpkgChrootDirectory();
1399
1400 if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
1401 _exit(100);
1402
1403 if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
1404 {
1405 int Flags,dummy;
1406 if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
1407 _exit(100);
1408
1409 // Discard everything in stdin before forking dpkg
1410 if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
1411 _exit(100);
1412
1413 while (read(STDIN_FILENO,&dummy,1) == 1);
1414
1415 if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
1416 _exit(100);
1417 }
1418
1419 /* No Job Control Stop Env is a magic dpkg var that prevents it
1420 from using sigstop */
1421 putenv((char *)"DPKG_NO_TSTP=yes");
1422 execvp(Args[0], (char**) &Args[0]);
1423 cerr << "Could not exec dpkg!" << endl;
1424 _exit(100);
1425 }
1426
1427 // apply ionice
1428 if (_config->FindB("DPkg::UseIoNice", false) == true)
1429 ionice(Child);
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 = 0;
1475 tv.tv_nsec = d->progress->GetPulseInterval();
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 d->progress->Pulse();
1482 if (select_ret == 0)
1483 continue;
1484 else if (select_ret < 0 && errno == EINTR)
1485 continue;
1486 else if (select_ret < 0)
1487 {
1488 perror("select() returned error");
1489 continue;
1490 }
1491
1492 if(d->master >= 0 && FD_ISSET(d->master, &rfds))
1493 DoTerminalPty(d->master);
1494 if(d->master >= 0 && FD_ISSET(0, &rfds))
1495 DoStdin(d->master);
1496 if(FD_ISSET(_dpkgin, &rfds))
1497 DoDpkgStatusFd(_dpkgin);
1498 }
1499 close(_dpkgin);
1500
1501 // Restore sig int/quit
1502 signal(SIGQUIT,old_SIGQUIT);
1503 signal(SIGINT,old_SIGINT);
1504
1505 signal(SIGHUP,old_SIGHUP);
1506 // Check for an error code.
1507 if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
1508 {
1509 // if it was set to "keep-dpkg-runing" then we won't return
1510 // here but keep the loop going and just report it as a error
1511 // for later
1512 bool const stopOnError = _config->FindB("Dpkg::StopOnError",true);
1513
1514 if(stopOnError)
1515 RunScripts("DPkg::Post-Invoke");
1516
1517 if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
1518 strprintf(d->dpkg_error, "Sub-process %s received a segmentation fault.",Args[0]);
1519 else if (WIFEXITED(Status) != 0)
1520 strprintf(d->dpkg_error, "Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
1521 else
1522 strprintf(d->dpkg_error, "Sub-process %s exited unexpectedly",Args[0]);
1523
1524 if(d->dpkg_error.size() > 0)
1525 _error->Error("%s", d->dpkg_error.c_str());
1526
1527 if(stopOnError)
1528 {
1529 CloseLog();
1530 d->progress->Stop();
1531 return false;
1532 }
1533 }
1534 }
1535 // dpkg is done at this point
1536 d->progress->Stop();
1537 StopPtyMagic();
1538 CloseLog();
1539
1540 if (pkgPackageManager::SigINTStop)
1541 _error->Warning(_("Operation was interrupted before it could finish"));
1542
1543 if (RunScripts("DPkg::Post-Invoke") == false)
1544 return false;
1545
1546 if (_config->FindB("Debug::pkgDPkgPM",false) == false)
1547 {
1548 std::string const oldpkgcache = _config->FindFile("Dir::cache::pkgcache");
1549 if (oldpkgcache.empty() == false && RealFileExists(oldpkgcache) == true &&
1550 unlink(oldpkgcache.c_str()) == 0)
1551 {
1552 std::string const srcpkgcache = _config->FindFile("Dir::cache::srcpkgcache");
1553 if (srcpkgcache.empty() == false && RealFileExists(srcpkgcache) == true)
1554 {
1555 _error->PushToStack();
1556 pkgCacheFile CacheFile;
1557 CacheFile.BuildCaches(NULL, true);
1558 _error->RevertToStack();
1559 }
1560 }
1561 }
1562
1563 Cache.writeStateFile(NULL);
1564 return true;
1565 }
1566
1567 void SigINT(int sig) {
1568 pkgPackageManager::SigINTStop = true;
1569 }
1570 /*}}}*/
1571 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1572 // ---------------------------------------------------------------------
1573 /* */
1574 void pkgDPkgPM::Reset()
1575 {
1576 List.erase(List.begin(),List.end());
1577 }
1578 /*}}}*/
1579 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1580 // ---------------------------------------------------------------------
1581 /* */
1582 void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
1583 {
1584 // If apport doesn't exist or isn't installed do nothing
1585 // This e.g. prevents messages in 'universes' without apport
1586 pkgCache::PkgIterator apportPkg = Cache.FindPkg("apport");
1587 if (apportPkg.end() == true || apportPkg->CurrentVer == 0)
1588 return;
1589
1590 string pkgname, reportfile, srcpkgname, pkgver, arch;
1591 string::size_type pos;
1592 FILE *report;
1593
1594 if (_config->FindB("Dpkg::ApportFailureReport", true) == false)
1595 {
1596 std::clog << "configured to not write apport reports" << std::endl;
1597 return;
1598 }
1599
1600 // only report the first errors
1601 if(pkgFailures > _config->FindI("APT::Apport::MaxReports", 3))
1602 {
1603 std::clog << _("No apport report written because MaxReports is reached already") << std::endl;
1604 return;
1605 }
1606
1607 // check if its not a follow up error
1608 const char *needle = dgettext("dpkg", "dependency problems - leaving unconfigured");
1609 if(strstr(errormsg, needle) != NULL) {
1610 std::clog << _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl;
1611 return;
1612 }
1613
1614 // do not report disk-full failures
1615 if(strstr(errormsg, strerror(ENOSPC)) != NULL) {
1616 std::clog << _("No apport report written because the error message indicates a disk full error") << std::endl;
1617 return;
1618 }
1619
1620 // do not report out-of-memory failures
1621 if(strstr(errormsg, strerror(ENOMEM)) != NULL ||
1622 strstr(errormsg, "failed to allocate memory") != NULL) {
1623 std::clog << _("No apport report written because the error message indicates a out of memory error") << std::endl;
1624 return;
1625 }
1626
1627 // do not report bugs regarding inaccessible local files
1628 if(strstr(errormsg, strerror(ENOENT)) != NULL ||
1629 strstr(errormsg, "cannot access archive") != NULL) {
1630 std::clog << _("No apport report written because the error message indicates an issue on the local system") << std::endl;
1631 return;
1632 }
1633
1634 // do not report errors encountered when decompressing packages
1635 if(strstr(errormsg, "--fsys-tarfile returned error exit status 2") != NULL) {
1636 std::clog << _("No apport report written because the error message indicates an issue on the local system") << std::endl;
1637 return;
1638 }
1639
1640 // do not report dpkg I/O errors, this is a format string, so we compare
1641 // the prefix and the suffix of the error with the dpkg error message
1642 vector<string> io_errors;
1643 io_errors.push_back(string("failed to read on buffer copy for %s"));
1644 io_errors.push_back(string("failed in write on buffer copy for %s"));
1645 io_errors.push_back(string("short read on buffer copy for %s"));
1646
1647 for (vector<string>::iterator I = io_errors.begin(); I != io_errors.end(); I++)
1648 {
1649 vector<string> list = VectorizeString(dgettext("dpkg", (*I).c_str()), '%');
1650 if (list.size() > 1) {
1651 // we need to split %s, VectorizeString only allows char so we need
1652 // to kill the "s" manually
1653 if (list[1].size() > 1) {
1654 list[1].erase(0, 1);
1655 if(strstr(errormsg, list[0].c_str()) &&
1656 strstr(errormsg, list[1].c_str())) {
1657 std::clog << _("No apport report written because the error message indicates a dpkg I/O error") << std::endl;
1658 return;
1659 }
1660 }
1661 }
1662 }
1663
1664 // get the pkgname and reportfile
1665 pkgname = flNotDir(pkgpath);
1666 pos = pkgname.find('_');
1667 if(pos != string::npos)
1668 pkgname = pkgname.substr(0, pos);
1669
1670 // find the package versin and source package name
1671 pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
1672 if (Pkg.end() == true)
1673 return;
1674 pkgCache::VerIterator Ver = Cache.GetCandidateVer(Pkg);
1675 if (Ver.end() == true)
1676 return;
1677 pkgver = Ver.VerStr() == NULL ? "unknown" : Ver.VerStr();
1678 pkgRecords Recs(Cache);
1679 pkgRecords::Parser &Parse = Recs.Lookup(Ver.FileList());
1680 srcpkgname = Parse.SourcePkg();
1681 if(srcpkgname.empty())
1682 srcpkgname = pkgname;
1683
1684 // if the file exists already, we check:
1685 // - if it was reported already (touched by apport).
1686 // If not, we do nothing, otherwise
1687 // we overwrite it. This is the same behaviour as apport
1688 // - if we have a report with the same pkgversion already
1689 // then we skip it
1690 reportfile = flCombine("/var/crash",pkgname+".0.crash");
1691 if(FileExists(reportfile))
1692 {
1693 struct stat buf;
1694 char strbuf[255];
1695
1696 // check atime/mtime
1697 stat(reportfile.c_str(), &buf);
1698 if(buf.st_mtime > buf.st_atime)
1699 return;
1700
1701 // check if the existing report is the same version
1702 report = fopen(reportfile.c_str(),"r");
1703 while(fgets(strbuf, sizeof(strbuf), report) != NULL)
1704 {
1705 if(strstr(strbuf,"Package:") == strbuf)
1706 {
1707 char pkgname[255], version[255];
1708 if(sscanf(strbuf, "Package: %254s %254s", pkgname, version) == 2)
1709 if(strcmp(pkgver.c_str(), version) == 0)
1710 {
1711 fclose(report);
1712 return;
1713 }
1714 }
1715 }
1716 fclose(report);
1717 }
1718
1719 // now write the report
1720 arch = _config->Find("APT::Architecture");
1721 report = fopen(reportfile.c_str(),"w");
1722 if(report == NULL)
1723 return;
1724 if(_config->FindB("DPkgPM::InitialReportOnly",false) == true)
1725 chmod(reportfile.c_str(), 0);
1726 else
1727 chmod(reportfile.c_str(), 0600);
1728 fprintf(report, "ProblemType: Package\n");
1729 fprintf(report, "Architecture: %s\n", arch.c_str());
1730 time_t now = time(NULL);
1731 fprintf(report, "Date: %s" , ctime(&now));
1732 fprintf(report, "Package: %s %s\n", pkgname.c_str(), pkgver.c_str());
1733 fprintf(report, "SourcePackage: %s\n", srcpkgname.c_str());
1734 fprintf(report, "ErrorMessage:\n %s\n", errormsg);
1735
1736 // ensure that the log is flushed
1737 if(d->term_out)
1738 fflush(d->term_out);
1739
1740 // attach terminal log it if we have it
1741 string logfile_name = _config->FindFile("Dir::Log::Terminal");
1742 if (!logfile_name.empty())
1743 {
1744 FILE *log = NULL;
1745
1746 fprintf(report, "DpkgTerminalLog:\n");
1747 log = fopen(logfile_name.c_str(),"r");
1748 if(log != NULL)
1749 {
1750 char buf[1024];
1751 while( fgets(buf, sizeof(buf), log) != NULL)
1752 fprintf(report, " %s", buf);
1753 fprintf(report, " \n");
1754 fclose(log);
1755 }
1756 }
1757
1758 // attach history log it if we have it
1759 string histfile_name = _config->FindFile("Dir::Log::History");
1760 if (!histfile_name.empty())
1761 {
1762 FILE *log = NULL;
1763 char buf[1024];
1764
1765 fprintf(report, "DpkgHistoryLog:\n");
1766 log = fopen(histfile_name.c_str(),"r");
1767 if(log != NULL)
1768 {
1769 while( fgets(buf, sizeof(buf), log) != NULL)
1770 fprintf(report, " %s", buf);
1771 fclose(log);
1772 }
1773 }
1774
1775 // log the ordering
1776 const char *ops_str[] = {"Install", "Configure","Remove","Purge"};
1777 fprintf(report, "AptOrdering:\n");
1778 for (vector<Item>::iterator I = List.begin(); I != List.end(); ++I)
1779 if ((*I).Pkg != NULL)
1780 fprintf(report, " %s: %s\n", (*I).Pkg.Name(), ops_str[(*I).Op]);
1781 else
1782 fprintf(report, " %s: %s\n", "NULL", ops_str[(*I).Op]);
1783
1784 // attach dmesg log (to learn about segfaults)
1785 if (FileExists("/bin/dmesg"))
1786 {
1787 fprintf(report, "Dmesg:\n");
1788 FILE *log = popen("/bin/dmesg","r");
1789 if(log != NULL)
1790 {
1791 char buf[1024];
1792 while( fgets(buf, sizeof(buf), log) != NULL)
1793 fprintf(report, " %s", buf);
1794 pclose(log);
1795 }
1796 }
1797
1798 // attach df -l log (to learn about filesystem status)
1799 if (FileExists("/bin/df"))
1800 {
1801
1802 fprintf(report, "Df:\n");
1803 FILE *log = popen("/bin/df -l","r");
1804 if(log != NULL)
1805 {
1806 char buf[1024];
1807 while( fgets(buf, sizeof(buf), log) != NULL)
1808 fprintf(report, " %s", buf);
1809 pclose(log);
1810 }
1811 }
1812
1813 fclose(report);
1814
1815 }
1816 /*}}}*/