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