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