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