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