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