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