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