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