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