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