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