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