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