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