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