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