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