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