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