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