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