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