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