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