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