]> git.saurik.com Git - apt.git/blame - apt-pkg/deb/dpkgpm.cc
add -o DpkgPM::Progress-Fancy for better dpkg progress output on vt100+ terminals
[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';
af6b4169
MV
61 if(_config->FindB("DpkgPM::Progress-Fancy", false))
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);
09fa2df2
MV
519 // the status we output
520 ostringstream status;
521
887f5036 522 if (Debug == true)
09fa2df2
MV
523 std::clog << "got from dpkg '" << line << "'" << std::endl;
524
525
526 /* dpkg sends strings like this:
cd4ee27d
MV
527 'status: <pkg>: <pkg qstate>'
528 'status: <pkg>:<arch>: <pkg qstate>'
09fa2df2
MV
529 errors look like this:
530 '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
531 and conffile-prompt like this
532 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
fc2d32c0
MV
533
534 Newer versions of dpkg sent also:
535 'processing: install: pkg'
536 'processing: configure: pkg'
537 'processing: remove: pkg'
b3514c56
DK
538 'processing: purge: pkg'
539 'processing: disappear: pkg'
fc2d32c0 540 'processing: trigproc: trigger'
09fa2df2
MV
541
542 */
cd4ee27d
MV
543 // we need to split on ": " (note the appended space) as the ':' is
544 // part of the pkgname:arch information that dpkg sends
545 //
546 // A dpkg error message may contain additional ":" (like
547 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
548 // so we need to ensure to not split too much
549 std::vector<std::string> list = StringSplit(line, ": ", 3);
550 if(list.size() != 3)
09fa2df2 551 {
887f5036 552 if (Debug == true)
09fa2df2
MV
553 std::clog << "ignoring line: not enough ':'" << std::endl;
554 return;
555 }
cd4ee27d
MV
556 // dpkg does not send always send "pkgname:arch" so we add it here if needed
557 std::string pkgname = list[1];
558 if (pkgname.find(":") == std::string::npos)
559 {
560 string const nativeArch = _config->Find("APT::Architecture");
561 pkgname = pkgname + ":" + nativeArch;
562 }
563 const char* const pkg = pkgname.c_str();
564 const char* action = list[2].c_str();
09fa2df2 565
fc2d32c0
MV
566 // 'processing' from dpkg looks like
567 // 'processing: action: pkg'
cd4ee27d 568 if(strncmp(list[0].c_str(), "processing", strlen("processing")) == 0)
fc2d32c0
MV
569 {
570 char s[200];
cd4ee27d
MV
571 const char* const pkg_or_trigger = list[2].c_str();
572 action = list[1].c_str();
f7dec19f
DB
573 const std::pair<const char *, const char *> * const iter =
574 std::find_if(PackageProcessingOpsBegin,
575 PackageProcessingOpsEnd,
576 MatchProcessingOp(action));
577 if(iter == PackageProcessingOpsEnd)
fc2d32c0 578 {
887f5036
DK
579 if (Debug == true)
580 std::clog << "ignoring unknown action: " << action << std::endl;
fc2d32c0
MV
581 return;
582 }
f7dec19f 583 snprintf(s, sizeof(s), _(iter->second), pkg_or_trigger);
fc2d32c0
MV
584
585 status << "pmstatus:" << pkg_or_trigger
586 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
587 << ":" << s
588 << endl;
589 if(OutStatusFd > 0)
d68d65ad 590 FileFd::Write(OutStatusFd, status.str().c_str(), status.str().size());
887f5036 591 if (Debug == true)
fc2d32c0 592 std::clog << "send: '" << status.str() << "'" << endl;
642ebc1a
DK
593
594 if (strncmp(action, "disappear", strlen("disappear")) == 0)
eb6f9bac 595 handleDisappearAction(pkg_or_trigger);
fc2d32c0
MV
596 return;
597 }
598
09fa2df2
MV
599 if(strncmp(action,"error",strlen("error")) == 0)
600 {
601 status << "pmerror:" << list[1]
ff56e980 602 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
09fa2df2
MV
603 << ":" << list[3]
604 << endl;
605 if(OutStatusFd > 0)
d68d65ad 606 FileFd::Write(OutStatusFd, status.str().c_str(), status.str().size());
887f5036 607 if (Debug == true)
09fa2df2 608 std::clog << "send: '" << status.str() << "'" << endl;
f060e833 609 pkgFailures++;
cd4ee27d 610 WriteApportReport(list[1].c_str(), list[3].c_str());
09fa2df2
MV
611 return;
612 }
887f5036 613 else if(strncmp(action,"conffile",strlen("conffile")) == 0)
09fa2df2
MV
614 {
615 status << "pmconffile:" << list[1]
ff56e980 616 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
09fa2df2
MV
617 << ":" << list[3]
618 << endl;
619 if(OutStatusFd > 0)
d68d65ad 620 FileFd::Write(OutStatusFd, status.str().c_str(), status.str().size());
887f5036 621 if (Debug == true)
09fa2df2
MV
622 std::clog << "send: '" << status.str() << "'" << endl;
623 return;
624 }
625
887f5036 626 vector<struct DpkgState> const &states = PackageOps[pkg];
09fa2df2
MV
627 const char *next_action = NULL;
628 if(PackageOpsDone[pkg] < states.size())
629 next_action = states[PackageOpsDone[pkg]].state;
630 // check if the package moved to the next dpkg state
631 if(next_action && (strcmp(action, next_action) == 0))
632 {
633 // only read the translation if there is actually a next
634 // action
635 const char *translation = _(states[PackageOpsDone[pkg]].str);
636 char s[200];
637 snprintf(s, sizeof(s), translation, pkg);
638
639 // we moved from one dpkg state to a new one, report that
640 PackageOpsDone[pkg]++;
ff56e980 641 PackagesDone++;
09fa2df2
MV
642 // build the status str
643 status << "pmstatus:" << pkg
ff56e980 644 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
09fa2df2
MV
645 << ":" << s
646 << endl;
7546c8da
MV
647 if(_config->FindB("DPkgPM::Progress", false) == true)
648 SendTerminalProgress(PackagesDone/float(PackagesTotal)*100.0);
649
09fa2df2 650 if(OutStatusFd > 0)
d68d65ad 651 FileFd::Write(OutStatusFd, status.str().c_str(), status.str().size());
887f5036 652 if (Debug == true)
09fa2df2
MV
653 std::clog << "send: '" << status.str() << "'" << endl;
654 }
887f5036 655 if (Debug == true)
09fa2df2
MV
656 std::clog << "(parsed from dpkg) pkg: " << pkg
657 << " action: " << action << endl;
6191b008 658}
887f5036 659 /*}}}*/
eb6f9bac
DK
660// DPkgPM::handleDisappearAction /*{{{*/
661void pkgDPkgPM::handleDisappearAction(string const &pkgname)
662{
663 // record the package name for display and stuff later
664 disappearedPkgs.insert(pkgname);
665
666 pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
667 if (unlikely(Pkg.end() == true))
668 return;
669 // the disappeared package was auto-installed - nothing to do
670 if ((Cache[Pkg].Flags & pkgCache::Flag::Auto) == pkgCache::Flag::Auto)
671 return;
75954ae2 672 pkgCache::VerIterator PkgVer = Cache[Pkg].InstVerIter(Cache);
eb6f9bac
DK
673 if (unlikely(PkgVer.end() == true))
674 return;
675 /* search in the list of dependencies for (Pre)Depends,
676 check if this dependency has a Replaces on our package
677 and if so transfer the manual installed flag to it */
678 for (pkgCache::DepIterator Dep = PkgVer.DependsList(); Dep.end() != true; ++Dep)
679 {
680 if (Dep->Type != pkgCache::Dep::Depends &&
681 Dep->Type != pkgCache::Dep::PreDepends)
682 continue;
683 pkgCache::PkgIterator Tar = Dep.TargetPkg();
684 if (unlikely(Tar.end() == true))
685 continue;
686 // the package is already marked as manual
687 if ((Cache[Tar].Flags & pkgCache::Flag::Auto) != pkgCache::Flag::Auto)
688 continue;
75954ae2
DK
689 pkgCache::VerIterator TarVer = Cache[Tar].InstVerIter(Cache);
690 if (TarVer.end() == true)
691 continue;
eb6f9bac
DK
692 for (pkgCache::DepIterator Rep = TarVer.DependsList(); Rep.end() != true; ++Rep)
693 {
694 if (Rep->Type != pkgCache::Dep::Replaces)
695 continue;
696 if (Pkg != Rep.TargetPkg())
697 continue;
698 // okay, they are strongly connected - transfer manual-bit
699 if (Debug == true)
700 std::clog << "transfer manual-bit from disappeared »" << pkgname << "« to »" << Tar.FullName() << "«" << std::endl;
701 Cache[Tar].Flags &= ~Flag::Auto;
702 break;
703 }
704 }
705}
706 /*}}}*/
887f5036 707// DPkgPM::DoDpkgStatusFd /*{{{*/
6191b008
MV
708// ---------------------------------------------------------------------
709/*
710 */
09fa2df2 711void pkgDPkgPM::DoDpkgStatusFd(int statusfd, int OutStatusFd)
6191b008
MV
712{
713 char *p, *q;
714 int len;
715
697a1d8a
MV
716 len=read(statusfd, &d->dpkgbuf[d->dpkgbuf_pos], sizeof(d->dpkgbuf)-d->dpkgbuf_pos);
717 d->dpkgbuf_pos += len;
6191b008
MV
718 if(len <= 0)
719 return;
ceabc520 720
6191b008 721 // process line by line if we have a buffer
697a1d8a
MV
722 p = q = d->dpkgbuf;
723 while((q=(char*)memchr(p, '\n', d->dpkgbuf+d->dpkgbuf_pos-p)) != NULL)
6191b008
MV
724 {
725 *q = 0;
09fa2df2 726 ProcessDpkgStatusLine(OutStatusFd, p);
6191b008
MV
727 p=q+1; // continue with next line
728 }
729
730 // now move the unprocessed bits (after the final \n that is now a 0x0)
697a1d8a
MV
731 // to the start and update d->dpkgbuf_pos
732 p = (char*)memrchr(d->dpkgbuf, 0, d->dpkgbuf_pos);
6191b008
MV
733 if(p == NULL)
734 return;
735
736 // we are interessted in the first char *after* 0x0
737 p++;
738
739 // move the unprocessed tail to the start and update pos
697a1d8a
MV
740 memmove(d->dpkgbuf, p, p-d->dpkgbuf);
741 d->dpkgbuf_pos = d->dpkgbuf+d->dpkgbuf_pos-p;
6191b008
MV
742}
743 /*}}}*/
d7a4ffd6 744// DPkgPM::WriteHistoryTag /*{{{*/
6cb1060b 745void pkgDPkgPM::WriteHistoryTag(string const &tag, string value)
d7a4ffd6 746{
6cb1060b
DK
747 size_t const length = value.length();
748 if (length == 0)
749 return;
750 // poor mans rstrip(", ")
751 if (value[length-2] == ',' && value[length-1] == ' ')
752 value.erase(length - 2, 2);
697a1d8a 753 fprintf(d->history_out, "%s: %s\n", tag.c_str(), value.c_str());
d7a4ffd6 754} /*}}}*/
887f5036 755// DPkgPM::OpenLog /*{{{*/
2e1715ea
MV
756bool pkgDPkgPM::OpenLog()
757{
569cc934 758 string const logdir = _config->FindDir("Dir::Log");
7753e468 759 if(CreateAPTDirectoryIfNeeded(logdir, logdir) == false)
b29c3712 760 // FIXME: use a better string after freeze
2e1715ea 761 return _error->Error(_("Directory '%s' missing"), logdir.c_str());
9169c871
MV
762
763 // get current time
764 char timestr[200];
569cc934
DK
765 time_t const t = time(NULL);
766 struct tm const * const tmp = localtime(&t);
9169c871
MV
767 strftime(timestr, sizeof(timestr), "%F %T", tmp);
768
769 // open terminal log
569cc934 770 string const logfile_name = flCombine(logdir,
2e1715ea
MV
771 _config->Find("Dir::Log::Terminal"));
772 if (!logfile_name.empty())
773 {
697a1d8a
MV
774 d->term_out = fopen(logfile_name.c_str(),"a");
775 if (d->term_out == NULL)
569cc934 776 return _error->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name.c_str());
697a1d8a
MV
777 setvbuf(d->term_out, NULL, _IONBF, 0);
778 SetCloseExec(fileno(d->term_out), true);
11b126f9
DK
779 if (getuid() == 0) // if we aren't root, we can't chown a file, so don't try it
780 {
781 struct passwd *pw = getpwnam("root");
782 struct group *gr = getgrnam("adm");
783 if (pw != NULL && gr != NULL && chown(logfile_name.c_str(), pw->pw_uid, gr->gr_gid) != 0)
784 _error->WarningE("OpenLog", "chown to root:adm of file %s failed", logfile_name.c_str());
785 }
786 if (chmod(logfile_name.c_str(), 0640) != 0)
787 _error->WarningE("OpenLog", "chmod 0640 of file %s failed", logfile_name.c_str());
697a1d8a 788 fprintf(d->term_out, "\nLog started: %s\n", timestr);
2e1715ea 789 }
9169c871 790
569cc934
DK
791 // write your history
792 string const history_name = flCombine(logdir,
9169c871
MV
793 _config->Find("Dir::Log::History"));
794 if (!history_name.empty())
795 {
697a1d8a
MV
796 d->history_out = fopen(history_name.c_str(),"a");
797 if (d->history_out == NULL)
569cc934 798 return _error->WarningE("OpenLog", _("Could not open file '%s'"), history_name.c_str());
d4621f82 799 SetCloseExec(fileno(d->history_out), true);
9169c871 800 chmod(history_name.c_str(), 0644);
697a1d8a 801 fprintf(d->history_out, "\nStart-Date: %s\n", timestr);
97be52d4 802 string remove, purge, install, reinstall, upgrade, downgrade;
f7f0d6c7 803 for (pkgCache::PkgIterator I = Cache.PkgBegin(); I.end() == false; ++I)
9169c871 804 {
97be52d4
DK
805 enum { CANDIDATE, CANDIDATE_AUTO, CURRENT_CANDIDATE, CURRENT } infostring;
806 string *line = NULL;
807 #define HISTORYINFO(X, Y) { line = &X; infostring = Y; }
808 if (Cache[I].NewInstall() == true)
809 HISTORYINFO(install, CANDIDATE_AUTO)
810 else if (Cache[I].ReInstall() == true)
811 HISTORYINFO(reinstall, CANDIDATE)
812 else if (Cache[I].Upgrade() == true)
813 HISTORYINFO(upgrade, CURRENT_CANDIDATE)
814 else if (Cache[I].Downgrade() == true)
815 HISTORYINFO(downgrade, CURRENT_CANDIDATE)
816 else if (Cache[I].Delete() == true)
817 HISTORYINFO((Cache[I].Purge() ? purge : remove), CURRENT)
818 else
819 continue;
820 #undef HISTORYINFO
821 line->append(I.FullName(false)).append(" (");
822 switch (infostring) {
823 case CANDIDATE: line->append(Cache[I].CandVersion); break;
824 case CANDIDATE_AUTO:
825 line->append(Cache[I].CandVersion);
826 if ((Cache[I].Flags & pkgCache::Flag::Auto) == pkgCache::Flag::Auto)
827 line->append(", automatic");
828 break;
829 case CURRENT_CANDIDATE: line->append(Cache[I].CurVersion).append(", ").append(Cache[I].CandVersion); break;
830 case CURRENT: line->append(Cache[I].CurVersion); break;
9169c871 831 }
97be52d4 832 line->append("), ");
9169c871 833 }
2bb25574
DK
834 if (_config->Exists("Commandline::AsString") == true)
835 WriteHistoryTag("Commandline", _config->Find("Commandline::AsString"));
d7a4ffd6 836 WriteHistoryTag("Install", install);
97be52d4 837 WriteHistoryTag("Reinstall", reinstall);
d7a4ffd6
MV
838 WriteHistoryTag("Upgrade", upgrade);
839 WriteHistoryTag("Downgrade",downgrade);
840 WriteHistoryTag("Remove",remove);
841 WriteHistoryTag("Purge",purge);
697a1d8a 842 fflush(d->history_out);
9169c871
MV
843 }
844
2e1715ea
MV
845 return true;
846}
887f5036
DK
847 /*}}}*/
848// DPkg::CloseLog /*{{{*/
2e1715ea
MV
849bool pkgDPkgPM::CloseLog()
850{
9169c871
MV
851 char timestr[200];
852 time_t t = time(NULL);
853 struct tm *tmp = localtime(&t);
854 strftime(timestr, sizeof(timestr), "%F %T", tmp);
855
697a1d8a 856 if(d->term_out)
2e1715ea 857 {
697a1d8a
MV
858 fprintf(d->term_out, "Log ended: ");
859 fprintf(d->term_out, "%s", timestr);
860 fprintf(d->term_out, "\n");
861 fclose(d->term_out);
2e1715ea 862 }
697a1d8a 863 d->term_out = NULL;
9169c871 864
697a1d8a 865 if(d->history_out)
9169c871 866 {
6cb1060b
DK
867 if (disappearedPkgs.empty() == false)
868 {
869 string disappear;
870 for (std::set<std::string>::const_iterator d = disappearedPkgs.begin();
871 d != disappearedPkgs.end(); ++d)
872 {
873 pkgCache::PkgIterator P = Cache.FindPkg(*d);
874 disappear.append(*d);
875 if (P.end() == true)
876 disappear.append(", ");
877 else
878 disappear.append(" (").append(Cache[P].CurVersion).append("), ");
879 }
880 WriteHistoryTag("Disappeared", disappear);
881 }
697a1d8a
MV
882 if (d->dpkg_error.empty() == false)
883 fprintf(d->history_out, "Error: %s\n", d->dpkg_error.c_str());
884 fprintf(d->history_out, "End-Date: %s\n", timestr);
885 fclose(d->history_out);
9169c871 886 }
697a1d8a 887 d->history_out = NULL;
9169c871 888
2e1715ea
MV
889 return true;
890}
887f5036 891 /*}}}*/
7546c8da
MV
892// DPkgPM::SendTerminalProgress /*{{{*/
893// ---------------------------------------------------------------------
894/* Send progress info to the terminal
895 */
896void pkgDPkgPM::SendTerminalProgress(float percentage)
897{
a38e023c
MV
898 int reporting_steps = _config->FindI("DpkgPM::Reporting-Steps", 1);
899
900 if(percentage < (d->last_reported_progress + reporting_steps))
901 return;
902
af6b4169
MV
903 std::string progress_str;
904 strprintf(progress_str, "Progress: [%3i%%]", (int)percentage);
905 if (d->fancy_progress_output)
906 {
907 int row = d->nr_terminal_rows;
908
909 static string save_cursor = "\033[s";
910 static string restore_cursor = "\033[u";
911
912 static string set_bg_color = "\033[42m"; // green
913 static string set_fg_color = "\033[30m"; // black
914
915 static string restore_bg = "\033[49m";
916 static string restore_fg = "\033[39m";
917
918 std::cout << save_cursor
919 // move cursor position to last row
920 << "\033[" << row << ";0f"
921 << set_bg_color
922 << set_fg_color
923 << progress_str
924 << restore_cursor
925 << restore_bg
926 << restore_fg;
927 }
928 else
929 {
930 std::cout << progress_str << "\r\n";
931 }
932 std::flush(std::cout);
933
a38e023c 934 d->last_reported_progress = percentage;
7546c8da
MV
935}
936 /*}}}*/
919e5852
OS
937/*{{{*/
938// This implements a racy version of pselect for those architectures
939// that don't have a working implementation.
940// FIXME: Probably can be removed on Lenny+1
941static int racy_pselect(int nfds, fd_set *readfds, fd_set *writefds,
942 fd_set *exceptfds, const struct timespec *timeout,
943 const sigset_t *sigmask)
944{
945 sigset_t origmask;
946 struct timeval tv;
947 int retval;
948
f6b37f38
OS
949 tv.tv_sec = timeout->tv_sec;
950 tv.tv_usec = timeout->tv_nsec/1000;
919e5852 951
f6b37f38 952 sigprocmask(SIG_SETMASK, sigmask, &origmask);
919e5852
OS
953 retval = select(nfds, readfds, writefds, exceptfds, &tv);
954 sigprocmask(SIG_SETMASK, &origmask, 0);
955 return retval;
956}
957/*}}}*/
af6b4169
MV
958
959void pkgDPkgPM::SetupTerminalScrollArea(int nr_rows)
960{
961 if(!d->fancy_progress_output)
962 return;
963
964 // scroll down a bit to avoid visual glitch when the screen
965 // area shrinks by one row
966 std::cout << "\n\n";
967
968 // save cursor
969 std::cout << "\033[s";
970
971 // set scroll region (this will place the cursor in the top left)
972 std::cout << "\033[1;" << nr_rows - 1 << "r";
973
974 // restore cursor but ensure its inside the scrolling area
975 std::cout << "\033[u";
976 static const char *move_cursor_up = "\033[1A";
977 std::cout << move_cursor_up;
978 std::flush(std::cout);
979}
980
03e39e59
AL
981// DPkgPM::Go - Run the sequence /*{{{*/
982// ---------------------------------------------------------------------
75ef8f14
MV
983/* This globs the operations and calls dpkg
984 *
985 * If it is called with "OutStatusFd" set to a valid file descriptor
986 * apt will report the install progress over this fd. It maps the
987 * dpkg states a package goes through to human readable (and i10n-able)
988 * names and calculates a percentage for each step.
989*/
990bool pkgDPkgPM::Go(int OutStatusFd)
03e39e59 991{
b1803e01
DK
992 pkgPackageManager::SigINTStop = false;
993
86fc2ca8
DK
994 // Generate the base argument list for dpkg
995 std::vector<const char *> Args;
996 unsigned long StartSize = 0;
734a6727
DK
997 string Tmp = _config->Find("Dir::Bin::dpkg","dpkg");
998 {
999 string const dpkgChrootDir = _config->FindDir("DPkg::Chroot-Directory", "/");
1000 size_t dpkgChrootLen = dpkgChrootDir.length();
1001 if (dpkgChrootDir != "/" && Tmp.find(dpkgChrootDir) == 0)
1002 {
1003 if (dpkgChrootDir[dpkgChrootLen - 1] == '/')
1004 --dpkgChrootLen;
1005 Tmp = Tmp.substr(dpkgChrootLen);
1006 }
1007 }
86fc2ca8
DK
1008 Args.push_back(Tmp.c_str());
1009 StartSize += Tmp.length();
1010
1011 // Stick in any custom dpkg options
1012 Configuration::Item const *Opts = _config->Tree("DPkg::Options");
1013 if (Opts != 0)
1014 {
1015 Opts = Opts->Child;
1016 for (; Opts != 0; Opts = Opts->Next)
1017 {
1018 if (Opts->Value.empty() == true)
1019 continue;
1020 Args.push_back(Opts->Value.c_str());
1021 StartSize += Opts->Value.length();
1022 }
1023 }
1024
1025 size_t const BaseArgs = Args.size();
1026 // we need to detect if we can qualify packages with the architecture or not
1027 Args.push_back("--assert-multi-arch");
1028 Args.push_back(NULL);
1029
1030 pid_t dpkgAssertMultiArch = ExecFork();
1031 if (dpkgAssertMultiArch == 0)
1032 {
e6ee75af 1033 dpkgChrootDirectory();
67b5d3dc
DK
1034 // redirect everything to the ultimate sink as we only need the exit-status
1035 int const nullfd = open("/dev/null", O_RDONLY);
1036 dup2(nullfd, STDIN_FILENO);
1037 dup2(nullfd, STDOUT_FILENO);
1038 dup2(nullfd, STDERR_FILENO);
17019a09 1039 execvp(Args[0], (char**) &Args[0]);
86fc2ca8
DK
1040 _error->WarningE("dpkgGo", "Can't detect if dpkg supports multi-arch!");
1041 _exit(2);
1042 }
1043
17745b02
MV
1044 fd_set rfds;
1045 struct timespec tv;
1046 sigset_t sigmask;
1047 sigset_t original_sigmask;
1048
887f5036
DK
1049 unsigned int const MaxArgs = _config->FindI("Dpkg::MaxArgs",8*1024);
1050 unsigned int const MaxArgBytes = _config->FindI("Dpkg::MaxArgBytes",32*1024);
5e312de7 1051 bool const NoTriggers = _config->FindB("DPkg::NoTriggers", false);
aff4e2f1 1052
6dd55be7
AL
1053 if (RunScripts("DPkg::Pre-Invoke") == false)
1054 return false;
db0c350f
AL
1055
1056 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
1057 return false;
fc2d32c0 1058
3e9c4f70
DK
1059 // support subpressing of triggers processing for special
1060 // cases like d-i that runs the triggers handling manually
5e312de7 1061 bool const SmartConf = (_config->Find("PackageManager::Configure", "all") != "all");
5c23dbcc 1062 bool const TriggersPending = _config->FindB("DPkg::TriggersPending", false);
5e312de7
DK
1063 if (_config->FindB("DPkg::ConfigurePending", SmartConf) == true)
1064 List.push_back(Item(Item::ConfigurePending, PkgIterator()));
3e9c4f70 1065
75ef8f14
MV
1066 // map the dpkg states to the operations that are performed
1067 // (this is sorted in the same way as Item::Ops)
9d06bc80 1068 static const struct DpkgState DpkgStatesOpMap[][7] = {
75ef8f14
MV
1069 // Install operation
1070 {
21e1008e
MV
1071 {"half-installed", N_("Preparing %s")},
1072 {"unpacked", N_("Unpacking %s") },
75ef8f14
MV
1073 {NULL, NULL}
1074 },
1075 // Configure operation
1076 {
21e1008e
MV
1077 {"unpacked",N_("Preparing to configure %s") },
1078 {"half-configured", N_("Configuring %s") },
1079 { "installed", N_("Installed %s")},
75ef8f14
MV
1080 {NULL, NULL}
1081 },
1082 // Remove operation
1083 {
21e1008e
MV
1084 {"half-configured", N_("Preparing for removal of %s")},
1085 {"half-installed", N_("Removing %s")},
1086 {"config-files", N_("Removed %s")},
75ef8f14
MV
1087 {NULL, NULL}
1088 },
1089 // Purge operation
1090 {
21e1008e
MV
1091 {"config-files", N_("Preparing to completely remove %s")},
1092 {"not-installed", N_("Completely removed %s")},
75ef8f14
MV
1093 {NULL, NULL}
1094 },
1095 };
db0c350f 1096
75ef8f14
MV
1097 // init the PackageOps map, go over the list of packages that
1098 // that will be [installed|configured|removed|purged] and add
1099 // them to the PackageOps map (the dpkg states it goes through)
1100 // and the PackageOpsTranslations (human readable strings)
f7f0d6c7 1101 for (vector<Item>::const_iterator I = List.begin(); I != List.end(); ++I)
75ef8f14 1102 {
3e9c4f70
DK
1103 if((*I).Pkg.end() == true)
1104 continue;
1105
cd4ee27d 1106 string const name = (*I).Pkg.FullName();
75ef8f14 1107 PackageOpsDone[name] = 0;
f7f0d6c7 1108 for(int i=0; (DpkgStatesOpMap[(*I).Op][i]).state != NULL; ++i)
75ef8f14
MV
1109 {
1110 PackageOps[name].push_back(DpkgStatesOpMap[(*I).Op][i]);
ff56e980 1111 PackagesTotal++;
75ef8f14 1112 }
887f5036 1113 }
75ef8f14 1114
697a1d8a 1115 d->stdin_is_dev_null = false;
9983591d 1116
ff56e980 1117 // create log
2e1715ea 1118 OpenLog();
ff56e980 1119
86fc2ca8
DK
1120 bool dpkgMultiArch = false;
1121 if (dpkgAssertMultiArch > 0)
11bcbdb9 1122 {
86fc2ca8
DK
1123 int Status = 0;
1124 while (waitpid(dpkgAssertMultiArch, &Status, 0) != dpkgAssertMultiArch)
11bcbdb9 1125 {
86fc2ca8 1126 if (errno == EINTR)
11bcbdb9 1127 continue;
86fc2ca8
DK
1128 _error->WarningE("dpkgGo", _("Waited for %s but it wasn't there"), "dpkg --assert-multi-arch");
1129 break;
11bcbdb9 1130 }
86fc2ca8
DK
1131 if (WIFEXITED(Status) == true && WEXITSTATUS(Status) == 0)
1132 dpkgMultiArch = true;
11bcbdb9 1133 }
11bcbdb9 1134
75ef8f14 1135 // this loop is runs once per operation
887f5036 1136 for (vector<Item>::const_iterator I = List.begin(); I != List.end();)
03e39e59 1137 {
5c23dbcc 1138 // Do all actions with the same Op in one run
887f5036 1139 vector<Item>::const_iterator J = I;
5c23dbcc 1140 if (TriggersPending == true)
f7f0d6c7 1141 for (; J != List.end(); ++J)
5c23dbcc
DK
1142 {
1143 if (J->Op == I->Op)
1144 continue;
1145 if (J->Op != Item::TriggersPending)
1146 break;
1147 vector<Item>::const_iterator T = J + 1;
1148 if (T != List.end() && T->Op == I->Op)
1149 continue;
1150 break;
1151 }
1152 else
f7f0d6c7 1153 for (; J != List.end() && J->Op == I->Op; ++J)
5c23dbcc 1154 /* nothing */;
30e1eab5 1155
8e11253d 1156 // keep track of allocated strings for multiarch package names
edca7af0 1157 std::vector<char *> Packages;
8e11253d 1158
11bcbdb9
DK
1159 // start with the baseset of arguments
1160 unsigned long Size = StartSize;
1161 Args.erase(Args.begin() + BaseArgs, Args.end());
1162
599d6ad5
MV
1163 // Now check if we are within the MaxArgs limit
1164 //
1165 // this code below is problematic, because it may happen that
1166 // the argument list is split in a way that A depends on B
1167 // and they are in the same "--configure A B" run
1168 // - with the split they may now be configured in different
1cecd437 1169 // runs, using Immediate-Configure-All can help prevent this.
aff4e2f1 1170 if (J - I > (signed)MaxArgs)
edca7af0 1171 {
aff4e2f1 1172 J = I + MaxArgs;
86fc2ca8
DK
1173 unsigned long const size = MaxArgs + 10;
1174 Args.reserve(size);
1175 Packages.reserve(size);
edca7af0
DK
1176 }
1177 else
1178 {
86fc2ca8
DK
1179 unsigned long const size = (J - I) + 10;
1180 Args.reserve(size);
1181 Packages.reserve(size);
edca7af0
DK
1182 }
1183
75ef8f14 1184 int fd[2];
319790f4
DK
1185 if (pipe(fd) != 0)
1186 return _error->Errno("pipe","Failed to create IPC pipe to dpkg");
edca7af0
DK
1187
1188#define ADDARG(X) Args.push_back(X); Size += strlen(X)
1189#define ADDARGC(X) Args.push_back(X); Size += sizeof(X) - 1
1190
1191 ADDARGC("--status-fd");
1192 char status_fd_buf[20];
75ef8f14 1193 snprintf(status_fd_buf,sizeof(status_fd_buf),"%i", fd[1]);
edca7af0 1194 ADDARG(status_fd_buf);
11b87a08 1195 unsigned long const Op = I->Op;
007dc9e0 1196
03e39e59
AL
1197 switch (I->Op)
1198 {
1199 case Item::Remove:
edca7af0
DK
1200 ADDARGC("--force-depends");
1201 ADDARGC("--force-remove-essential");
1202 ADDARGC("--remove");
03e39e59
AL
1203 break;
1204
fc4b5c9f 1205 case Item::Purge:
edca7af0
DK
1206 ADDARGC("--force-depends");
1207 ADDARGC("--force-remove-essential");
1208 ADDARGC("--purge");
fc4b5c9f
AL
1209 break;
1210
03e39e59 1211 case Item::Configure:
edca7af0 1212 ADDARGC("--configure");
03e39e59 1213 break;
3e9c4f70
DK
1214
1215 case Item::ConfigurePending:
edca7af0
DK
1216 ADDARGC("--configure");
1217 ADDARGC("--pending");
3e9c4f70
DK
1218 break;
1219
5e312de7 1220 case Item::TriggersPending:
edca7af0
DK
1221 ADDARGC("--triggers-only");
1222 ADDARGC("--pending");
5e312de7
DK
1223 break;
1224
03e39e59 1225 case Item::Install:
edca7af0
DK
1226 ADDARGC("--unpack");
1227 ADDARGC("--auto-deconfigure");
03e39e59
AL
1228 break;
1229 }
3e9c4f70 1230
5e312de7 1231 if (NoTriggers == true && I->Op != Item::TriggersPending &&
d5081aee 1232 I->Op != Item::ConfigurePending)
3e9c4f70 1233 {
edca7af0 1234 ADDARGC("--no-triggers");
3e9c4f70 1235 }
edca7af0 1236#undef ADDARGC
3e9c4f70 1237
03e39e59
AL
1238 // Write in the file or package names
1239 if (I->Op == Item::Install)
30e1eab5 1240 {
f7f0d6c7 1241 for (;I != J && Size < MaxArgBytes; ++I)
30e1eab5 1242 {
cf544e14
AL
1243 if (I->File[0] != '/')
1244 return _error->Error("Internal Error, Pathname to install is not absolute '%s'",I->File.c_str());
edca7af0
DK
1245 Args.push_back(I->File.c_str());
1246 Size += I->File.length();
30e1eab5 1247 }
edca7af0 1248 }
03e39e59 1249 else
30e1eab5 1250 {
8e11253d 1251 string const nativeArch = _config->Find("APT::Architecture");
6f31b247 1252 unsigned long const oldSize = I->Op == Item::Configure ? Size : 0;
f7f0d6c7 1253 for (;I != J && Size < MaxArgBytes; ++I)
30e1eab5 1254 {
3e9c4f70
DK
1255 if((*I).Pkg.end() == true)
1256 continue;
642ebc1a
DK
1257 if (I->Op == Item::Configure && disappearedPkgs.find(I->Pkg.Name()) != disappearedPkgs.end())
1258 continue;
86fc2ca8 1259 // We keep this here to allow "smooth" transitions from e.g. multiarch dpkg/ubuntu to dpkg/debian
c919ad6e
DK
1260 if (dpkgMultiArch == false && (I->Pkg.Arch() == nativeArch ||
1261 strcmp(I->Pkg.Arch(), "all") == 0 ||
1262 strcmp(I->Pkg.Arch(), "none") == 0))
edca7af0
DK
1263 {
1264 char const * const name = I->Pkg.Name();
1265 ADDARG(name);
1266 }
8e11253d
SL
1267 else
1268 {
7720666f 1269 pkgCache::VerIterator PkgVer;
3a5ec305 1270 std::string name = I->Pkg.Name();
a1355481
MV
1271 if (Op == Item::Remove || Op == Item::Purge)
1272 {
2a2a7ef4 1273 PkgVer = I->Pkg.CurrentVer();
a1355481
MV
1274 if(PkgVer.end() == true)
1275 PkgVer = FindNowVersion(I->Pkg);
1276 }
7720666f 1277 else
2a2a7ef4 1278 PkgVer = Cache[I->Pkg].InstVerIter(Cache);
c919ad6e
DK
1279 if (strcmp(I->Pkg.Arch(), "none") == 0)
1280 ; // never arch-qualify a package without an arch
1281 else if (PkgVer.end() == false)
a1355481
MV
1282 name.append(":").append(PkgVer.Arch());
1283 else
1284 _error->Warning("Can not find PkgVer for '%s'", name.c_str());
3a5ec305 1285 char * const fullname = strdup(name.c_str());
edca7af0
DK
1286 Packages.push_back(fullname);
1287 ADDARG(fullname);
8e11253d 1288 }
6f31b247
DK
1289 }
1290 // skip configure action if all sheduled packages disappeared
1291 if (oldSize == Size)
1292 continue;
1293 }
edca7af0
DK
1294#undef ADDARG
1295
30e1eab5
AL
1296 J = I;
1297
1298 if (_config->FindB("Debug::pkgDPkgPM",false) == true)
1299 {
edca7af0
DK
1300 for (std::vector<const char *>::const_iterator a = Args.begin();
1301 a != Args.end(); ++a)
1302 clog << *a << ' ';
11bcbdb9 1303 clog << endl;
30e1eab5
AL
1304 continue;
1305 }
edca7af0
DK
1306 Args.push_back(NULL);
1307
03e39e59
AL
1308 cout << flush;
1309 clog << flush;
1310 cerr << flush;
1311
1312 /* Mask off sig int/quit. We do this because dpkg also does when
1313 it forks scripts. What happens is that when you hit ctrl-c it sends
1314 it to all processes in the group. Since dpkg ignores the signal
1315 it doesn't die but we do! So we must also ignore it */
7f9a6360 1316 sighandler_t old_SIGQUIT = signal(SIGQUIT,SIG_IGN);
590f1923 1317 sighandler_t old_SIGINT = signal(SIGINT,SigINT);
1cecd437
CB
1318
1319 // Check here for any SIGINT
11b87a08
CB
1320 if (pkgPackageManager::SigINTStop && (Op == Item::Remove || Op == Item::Purge || Op == Item::Install))
1321 break;
1322
1323
73e598c3
MV
1324 // ignore SIGHUP as well (debian #463030)
1325 sighandler_t old_SIGHUP = signal(SIGHUP,SIG_IGN);
1326
d8cb4aa4
MV
1327 struct termios tt;
1328 struct winsize win;
4e550036
MV
1329 int master = -1;
1330 int slave = -1;
d8cb4aa4 1331
4e550036
MV
1332 // if tcgetattr does not return zero there was a error
1333 // and we do not do any pty magic
87281603
DK
1334 _error->PushToStack();
1335 if (tcgetattr(STDOUT_FILENO, &tt) == 0)
090c6566 1336 {
af6b4169
MV
1337 ioctl(1, TIOCGWINSZ, (char *)&win);
1338 d->nr_terminal_rows = win.ws_row;
87281603 1339 if (openpty(&master, &slave, NULL, &tt, &win) < 0)
4e550036 1340 {
87281603 1341 _error->Errno("openpty", _("Can not write log (%s)"), _("Is /dev/pts mounted?"));
4e550036
MV
1342 master = slave = -1;
1343 } else {
1344 struct termios rtt;
1345 rtt = tt;
1346 cfmakeraw(&rtt);
1347 rtt.c_lflag &= ~ECHO;
4d7ac88c 1348 rtt.c_lflag |= ISIG;
4e550036
MV
1349 // block SIGTTOU during tcsetattr to prevent a hang if
1350 // the process is a member of the background process group
1351 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
1352 sigemptyset(&sigmask);
1353 sigaddset(&sigmask, SIGTTOU);
1354 sigprocmask(SIG_BLOCK,&sigmask, &original_sigmask);
1355 tcsetattr(0, TCSAFLUSH, &rtt);
1356 sigprocmask(SIG_SETMASK, &original_sigmask, 0);
1357 }
d8cb4aa4 1358 }
87281603
DK
1359 // complain only if stdout is either a terminal (but still failed) or is an invalid
1360 // descriptor otherwise we would complain about redirection to e.g. /dev/null as well.
1361 else if (isatty(STDOUT_FILENO) == 1 || errno == EBADF)
1362 _error->Errno("tcgetattr", _("Can not write log (%s)"), _("Is stdout a terminal?"));
1363
1364 if (_error->PendingError() == true)
1365 _error->DumpErrors(std::cerr);
1366 _error->RevertToStack();
1367
75ef8f14 1368 // Fork dpkg
007dc9e0 1369 pid_t Child;
75ef8f14 1370 _config->Set("APT::Keep-Fds::",fd[1]);
ccd8e28f
MV
1371 // send status information that we are about to fork dpkg
1372 if(OutStatusFd > 0) {
1373 ostringstream status;
1374 status << "pmstatus:dpkg-exec:"
1375 << (PackagesDone/float(PackagesTotal)*100.0)
1376 << ":" << _("Running dpkg")
1377 << endl;
d68d65ad 1378 FileFd::Write(OutStatusFd, status.str().c_str(), status.str().size());
ccd8e28f 1379 }
af6b4169 1380
75ef8f14 1381 Child = ExecFork();
03e39e59
AL
1382 // This is the child
1383 if (Child == 0)
1384 {
af6b4169 1385
a4cf3665
MV
1386 if(slave >= 0 && master >= 0)
1387 {
1388 setsid();
1389 ioctl(slave, TIOCSCTTY, 0);
1390 close(master);
1391 dup2(slave, 0);
1392 dup2(slave, 1);
1393 dup2(slave, 2);
1394 close(slave);
1395 }
75ef8f14 1396 close(fd[0]); // close the read end of the pipe
d8cb4aa4 1397
e6ee75af 1398 dpkgChrootDirectory();
4b7cfe96 1399
cf544e14 1400 if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
0dbb95d8 1401 _exit(100);
af6b4169 1402
421ff807 1403 if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
8b5fe26c
AL
1404 {
1405 int Flags,dummy;
1406 if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
1407 _exit(100);
1408
1409 // Discard everything in stdin before forking dpkg
1410 if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
1411 _exit(100);
1412
1413 while (read(STDIN_FILENO,&dummy,1) == 1);
1414
1415 if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
1416 _exit(100);
1417 }
af6b4169 1418 SetupTerminalScrollArea(d->nr_terminal_rows);
d8cb4aa4 1419
03e39e59
AL
1420 /* No Job Control Stop Env is a magic dpkg var that prevents it
1421 from using sigstop */
71afbdb5 1422 putenv((char *)"DPKG_NO_TSTP=yes");
edca7af0 1423 execvp(Args[0], (char**) &Args[0]);
03e39e59 1424 cerr << "Could not exec dpkg!" << endl;
0dbb95d8 1425 _exit(100);
03e39e59
AL
1426 }
1427
cebe0287
MV
1428 // apply ionice
1429 if (_config->FindB("DPkg::UseIoNice", false) == true)
1430 ionice(Child);
1431
75ef8f14
MV
1432 // clear the Keep-Fd again
1433 _config->Clear("APT::Keep-Fds",fd[1]);
1434
03e39e59
AL
1435 // Wait for dpkg
1436 int Status = 0;
75ef8f14
MV
1437
1438 // we read from dpkg here
887f5036 1439 int const _dpkgin = fd[0];
75ef8f14
MV
1440 close(fd[1]); // close the write end of the pipe
1441
a4cf3665
MV
1442 if(slave > 0)
1443 close(slave);
6191b008 1444
97efd303 1445 // setups fds
7052511e
MV
1446 sigemptyset(&sigmask);
1447 sigprocmask(SIG_BLOCK,&sigmask,&original_sigmask);
1448
edca7af0
DK
1449 /* free vectors (and therefore memory) as we don't need the included data anymore */
1450 for (std::vector<char *>::const_iterator p = Packages.begin();
1451 p != Packages.end(); ++p)
1452 free(*p);
1453 Packages.clear();
8e11253d 1454
887f5036
DK
1455 // the result of the waitpid call
1456 int res;
090c6566 1457 int select_ret;
75ef8f14
MV
1458 while ((res=waitpid(Child,&Status, WNOHANG)) != Child) {
1459 if(res < 0) {
1460 // FIXME: move this to a function or something, looks ugly here
1461 // error handling, waitpid returned -1
1462 if (errno == EINTR)
1463 continue;
1464 RunScripts("DPkg::Post-Invoke");
1465
1466 // Restore sig int/quit
1467 signal(SIGQUIT,old_SIGQUIT);
1468 signal(SIGINT,old_SIGINT);
590f1923 1469
e306ec47 1470 signal(SIGHUP,old_SIGHUP);
75ef8f14
MV
1471 return _error->Errno("waitpid","Couldn't wait for subprocess");
1472 }
d8cb4aa4
MV
1473
1474 // wait for input or output here
955a6ddb 1475 FD_ZERO(&rfds);
697a1d8a 1476 if (master >= 0 && !d->stdin_is_dev_null)
9983591d 1477 FD_SET(0, &rfds);
955a6ddb 1478 FD_SET(_dpkgin, &rfds);
a4cf3665
MV
1479 if(master >= 0)
1480 FD_SET(master, &rfds);
090c6566 1481 tv.tv_sec = 1;
7052511e
MV
1482 tv.tv_nsec = 0;
1483 select_ret = pselect(max(master, _dpkgin)+1, &rfds, NULL, NULL,
1484 &tv, &original_sigmask);
919e5852
OS
1485 if (select_ret < 0 && (errno == EINVAL || errno == ENOSYS))
1486 select_ret = racy_pselect(max(master, _dpkgin)+1, &rfds, NULL,
1487 NULL, &tv, &original_sigmask);
da50ba30
MV
1488 if (select_ret == 0)
1489 continue;
1490 else if (select_ret < 0 && errno == EINTR)
1491 continue;
1492 else if (select_ret < 0)
1493 {
1494 perror("select() returned error");
1495 continue;
1496 }
1497
a4cf3665 1498 if(master >= 0 && FD_ISSET(master, &rfds))
1ba38171 1499 DoTerminalPty(master);
a4cf3665 1500 if(master >= 0 && FD_ISSET(0, &rfds))
955a6ddb 1501 DoStdin(master);
955a6ddb 1502 if(FD_ISSET(_dpkgin, &rfds))
09fa2df2 1503 DoDpkgStatusFd(_dpkgin, OutStatusFd);
03e39e59 1504 }
75ef8f14 1505 close(_dpkgin);
03e39e59
AL
1506
1507 // Restore sig int/quit
7f9a6360
AL
1508 signal(SIGQUIT,old_SIGQUIT);
1509 signal(SIGINT,old_SIGINT);
590f1923 1510
d9ec0fac 1511 signal(SIGHUP,old_SIGHUP);
d8cb4aa4 1512
af6b4169
MV
1513 // reset scroll area
1514 SetupTerminalScrollArea(d->nr_terminal_rows);
1515 if(d->fancy_progress_output)
1516 {
1517 // override the progress line (sledgehammer)
1518 static const char* clear_screen_below_cursor = "\033[J";
1519 std::cout << clear_screen_below_cursor;
1520 }
1521
477b5d6c
MV
1522 if(master >= 0)
1523 {
a4cf3665 1524 tcsetattr(0, TCSAFLUSH, &tt);
477b5d6c
MV
1525 close(master);
1526 }
a38e023c 1527
6dd55be7
AL
1528 // Check for an error code.
1529 if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
1530 {
c70496f9
MV
1531 // if it was set to "keep-dpkg-runing" then we won't return
1532 // here but keep the loop going and just report it as a error
1533 // for later
887f5036 1534 bool const stopOnError = _config->FindB("Dpkg::StopOnError",true);
f956efb4 1535
c70496f9
MV
1536 if(stopOnError)
1537 RunScripts("DPkg::Post-Invoke");
1538
1539 if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
697a1d8a 1540 strprintf(d->dpkg_error, "Sub-process %s received a segmentation fault.",Args[0]);
c70496f9 1541 else if (WIFEXITED(Status) != 0)
697a1d8a 1542 strprintf(d->dpkg_error, "Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
c70496f9 1543 else
697a1d8a 1544 strprintf(d->dpkg_error, "Sub-process %s exited unexpectedly",Args[0]);
9169c871 1545
697a1d8a 1546 if(d->dpkg_error.size() > 0)
36b8ebbb 1547 _error->Error("%s", d->dpkg_error.c_str());
c70496f9 1548
ff56e980
MV
1549 if(stopOnError)
1550 {
2e1715ea 1551 CloseLog();
c70496f9 1552 return false;
ff56e980 1553 }
6dd55be7 1554 }
03e39e59 1555 }
2e1715ea 1556 CloseLog();
a38e023c
MV
1557
1558 // dpkg is done at this point
1559 if(_config->FindB("DPkgPM::Progress", false) == true)
1560 SendTerminalProgress(100);
af6b4169 1561
11b87a08
CB
1562 if (pkgPackageManager::SigINTStop)
1563 _error->Warning(_("Operation was interrupted before it could finish"));
6dd55be7
AL
1564
1565 if (RunScripts("DPkg::Post-Invoke") == false)
1566 return false;
b462d75a 1567
388f2962
DK
1568 if (_config->FindB("Debug::pkgDPkgPM",false) == false)
1569 {
1570 std::string const oldpkgcache = _config->FindFile("Dir::cache::pkgcache");
1571 if (oldpkgcache.empty() == false && RealFileExists(oldpkgcache) == true &&
1572 unlink(oldpkgcache.c_str()) == 0)
1573 {
1574 std::string const srcpkgcache = _config->FindFile("Dir::cache::srcpkgcache");
1575 if (srcpkgcache.empty() == false && RealFileExists(srcpkgcache) == true)
1576 {
1577 _error->PushToStack();
1578 pkgCacheFile CacheFile;
1579 CacheFile.BuildCaches(NULL, true);
1580 _error->RevertToStack();
1581 }
1582 }
1583 }
1584
b462d75a 1585 Cache.writeStateFile(NULL);
03e39e59
AL
1586 return true;
1587}
590f1923
CB
1588
1589void SigINT(int sig) {
b1803e01
DK
1590 pkgPackageManager::SigINTStop = true;
1591}
03e39e59 1592 /*}}}*/
281daf46
AL
1593// pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1594// ---------------------------------------------------------------------
1595/* */
1596void pkgDPkgPM::Reset()
1597{
1598 List.erase(List.begin(),List.end());
1599}
1600 /*}}}*/
5e457a93
MV
1601// pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1602// ---------------------------------------------------------------------
1603/* */
1604void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
1605{
dd61e64d
DK
1606 // If apport doesn't exist or isn't installed do nothing
1607 // This e.g. prevents messages in 'universes' without apport
1608 pkgCache::PkgIterator apportPkg = Cache.FindPkg("apport");
1609 if (apportPkg.end() == true || apportPkg->CurrentVer == 0)
1610 return;
1611
5e457a93
MV
1612 string pkgname, reportfile, srcpkgname, pkgver, arch;
1613 string::size_type pos;
1614 FILE *report;
1615
23c5897c 1616 if (_config->FindB("Dpkg::ApportFailureReport", false) == false)
ff38d63b
MV
1617 {
1618 std::clog << "configured to not write apport reports" << std::endl;
5e457a93 1619 return;
ff38d63b 1620 }
5e457a93 1621
d6a4afcb 1622 // only report the first errors
5273f1bf 1623 if(pkgFailures > _config->FindI("APT::Apport::MaxReports", 3))
ff38d63b
MV
1624 {
1625 std::clog << _("No apport report written because MaxReports is reached already") << std::endl;
5e457a93 1626 return;
ff38d63b 1627 }
5e457a93 1628
d6a4afcb
MV
1629 // check if its not a follow up error
1630 const char *needle = dgettext("dpkg", "dependency problems - leaving unconfigured");
1631 if(strstr(errormsg, needle) != NULL) {
1632 std::clog << _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl;
1633 return;
1634 }
1635
2f0d5dea
MV
1636 // do not report disk-full failures
1637 if(strstr(errormsg, strerror(ENOSPC)) != NULL) {
1638 std::clog << _("No apport report written because the error message indicates a disk full error") << std::endl;
1639 return;
1640 }
1641
3024a85e
MV
1642 // do not report out-of-memory failures
1643 if(strstr(errormsg, strerror(ENOMEM)) != NULL) {
1644 std::clog << _("No apport report written because the error message indicates a out of memory error") << std::endl;
1645 return;
1646 }
1647
076c46e5
MZ
1648 // do not report dpkg I/O errors
1649 // XXX - this message is localized, but this only matches the English version. This is better than nothing.
1650 if(strstr(errormsg, "short read in buffer_copy (")) {
1651 std::clog << _("No apport report written because the error message indicates a dpkg I/O error") << std::endl;
1652 return;
1653 }
1654
5e457a93
MV
1655 // get the pkgname and reportfile
1656 pkgname = flNotDir(pkgpath);
25ffa4e8 1657 pos = pkgname.find('_');
5e457a93 1658 if(pos != string::npos)
25ffa4e8 1659 pkgname = pkgname.substr(0, pos);
5e457a93
MV
1660
1661 // find the package versin and source package name
1662 pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
1663 if (Pkg.end() == true)
1664 return;
1665 pkgCache::VerIterator Ver = Cache.GetCandidateVer(Pkg);
5e457a93
MV
1666 if (Ver.end() == true)
1667 return;
986d97bb 1668 pkgver = Ver.VerStr() == NULL ? "unknown" : Ver.VerStr();
5e457a93
MV
1669 pkgRecords Recs(Cache);
1670 pkgRecords::Parser &Parse = Recs.Lookup(Ver.FileList());
1671 srcpkgname = Parse.SourcePkg();
1672 if(srcpkgname.empty())
1673 srcpkgname = pkgname;
1674
1675 // if the file exists already, we check:
1676 // - if it was reported already (touched by apport).
1677 // If not, we do nothing, otherwise
1678 // we overwrite it. This is the same behaviour as apport
1679 // - if we have a report with the same pkgversion already
1680 // then we skip it
1681 reportfile = flCombine("/var/crash",pkgname+".0.crash");
1682 if(FileExists(reportfile))
1683 {
1684 struct stat buf;
1685 char strbuf[255];
1686
1687 // check atime/mtime
1688 stat(reportfile.c_str(), &buf);
1689 if(buf.st_mtime > buf.st_atime)
1690 return;
1691
1692 // check if the existing report is the same version
1693 report = fopen(reportfile.c_str(),"r");
1694 while(fgets(strbuf, sizeof(strbuf), report) != NULL)
1695 {
1696 if(strstr(strbuf,"Package:") == strbuf)
1697 {
1698 char pkgname[255], version[255];
b3c36c6e 1699 if(sscanf(strbuf, "Package: %254s %254s", pkgname, version) == 2)
5e457a93
MV
1700 if(strcmp(pkgver.c_str(), version) == 0)
1701 {
1702 fclose(report);
1703 return;
1704 }
1705 }
1706 }
1707 fclose(report);
1708 }
1709
1710 // now write the report
1711 arch = _config->Find("APT::Architecture");
1712 report = fopen(reportfile.c_str(),"w");
1713 if(report == NULL)
1714 return;
1715 if(_config->FindB("DPkgPM::InitialReportOnly",false) == true)
1716 chmod(reportfile.c_str(), 0);
1717 else
1718 chmod(reportfile.c_str(), 0600);
1719 fprintf(report, "ProblemType: Package\n");
1720 fprintf(report, "Architecture: %s\n", arch.c_str());
1721 time_t now = time(NULL);
1722 fprintf(report, "Date: %s" , ctime(&now));
1723 fprintf(report, "Package: %s %s\n", pkgname.c_str(), pkgver.c_str());
1724 fprintf(report, "SourcePackage: %s\n", srcpkgname.c_str());
1725 fprintf(report, "ErrorMessage:\n %s\n", errormsg);
8ecd1fed
MV
1726
1727 // ensure that the log is flushed
697a1d8a
MV
1728 if(d->term_out)
1729 fflush(d->term_out);
8ecd1fed
MV
1730
1731 // attach terminal log it if we have it
1732 string logfile_name = _config->FindFile("Dir::Log::Terminal");
1733 if (!logfile_name.empty())
1734 {
1735 FILE *log = NULL;
8ecd1fed
MV
1736
1737 fprintf(report, "DpkgTerminalLog:\n");
1738 log = fopen(logfile_name.c_str(),"r");
1739 if(log != NULL)
1740 {
69c2ecbd 1741 char buf[1024];
8ecd1fed
MV
1742 while( fgets(buf, sizeof(buf), log) != NULL)
1743 fprintf(report, " %s", buf);
1744 fclose(log);
1745 }
1746 }
76dbdfc7 1747
5c8a2aa8
MV
1748 // log the ordering
1749 const char *ops_str[] = {"Install", "Configure","Remove","Purge"};
1750 fprintf(report, "AptOrdering:\n");
f7f0d6c7 1751 for (vector<Item>::iterator I = List.begin(); I != List.end(); ++I)
671b7116
MV
1752 if ((*I).Pkg != NULL)
1753 fprintf(report, " %s: %s\n", (*I).Pkg.Name(), ops_str[(*I).Op]);
1754 else
1755 fprintf(report, " %s: %s\n", "NULL", ops_str[(*I).Op]);
5c8a2aa8 1756
76dbdfc7
MV
1757 // attach dmesg log (to learn about segfaults)
1758 if (FileExists("/bin/dmesg"))
1759 {
76dbdfc7 1760 fprintf(report, "Dmesg:\n");
69c2ecbd 1761 FILE *log = popen("/bin/dmesg","r");
76dbdfc7
MV
1762 if(log != NULL)
1763 {
69c2ecbd 1764 char buf[1024];
76dbdfc7
MV
1765 while( fgets(buf, sizeof(buf), log) != NULL)
1766 fprintf(report, " %s", buf);
23f3cfd0 1767 pclose(log);
76dbdfc7
MV
1768 }
1769 }
2183a086
MV
1770
1771 // attach df -l log (to learn about filesystem status)
1772 if (FileExists("/bin/df"))
1773 {
2183a086
MV
1774
1775 fprintf(report, "Df:\n");
69c2ecbd 1776 FILE *log = popen("/bin/df -l","r");
2183a086
MV
1777 if(log != NULL)
1778 {
69c2ecbd 1779 char buf[1024];
2183a086
MV
1780 while( fgets(buf, sizeof(buf), log) != NULL)
1781 fprintf(report, " %s", buf);
23f3cfd0 1782 pclose(log);
2183a086
MV
1783 }
1784 }
1785
5e457a93 1786 fclose(report);
76dbdfc7 1787
5e457a93
MV
1788}
1789 /*}}}*/