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