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