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