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