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