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