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