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