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