]> git.saurik.com Git - apt.git/blame - apt-pkg/deb/dpkgpm.cc
cherry pick -r 1954..1955 lp:~donkult/apt/sid
[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 /*{{{*/
03e39e59
AL
11#include <apt-pkg/dpkgpm.h>
12#include <apt-pkg/error.h>
13#include <apt-pkg/configuration.h>
b2e465d6 14#include <apt-pkg/depcache.h>
5e457a93 15#include <apt-pkg/pkgrecords.h>
b2e465d6 16#include <apt-pkg/strutl.h>
a4cf3665 17#include <apti18n.h>
614adaa0 18#include <apt-pkg/fileutl.h>
233b185f 19
03e39e59
AL
20#include <unistd.h>
21#include <stdlib.h>
22#include <fcntl.h>
090c6566 23#include <sys/select.h>
03e39e59
AL
24#include <sys/types.h>
25#include <sys/wait.h>
26#include <signal.h>
27#include <errno.h>
2f0d5dea 28#include <string.h>
db0c350f 29#include <stdio.h>
f7dec19f
DB
30#include <string.h>
31#include <algorithm>
75ef8f14
MV
32#include <sstream>
33#include <map>
34
d8cb4aa4
MV
35#include <termios.h>
36#include <unistd.h>
37#include <sys/ioctl.h>
38#include <pty.h>
39
75ef8f14
MV
40#include <config.h>
41#include <apti18n.h>
b0ebdef5 42 /*}}}*/
233b185f
AL
43
44using namespace std;
03e39e59 45
f7dec19f
DB
46namespace
47{
48 // Maps the dpkg "processing" info to human readable names. Entry 0
49 // of each array is the key, entry 1 is the value.
50 const std::pair<const char *, const char *> PackageProcessingOps[] = {
51 std::make_pair("install", N_("Installing %s")),
52 std::make_pair("configure", N_("Configuring %s")),
53 std::make_pair("remove", N_("Removing %s")),
ac81ae9c 54 std::make_pair("purge", N_("Completely removing %s")),
f7dec19f
DB
55 std::make_pair("trigproc", N_("Running post-installation trigger %s"))
56 };
57
58 const std::pair<const char *, const char *> * const PackageProcessingOpsBegin = PackageProcessingOps;
59 const std::pair<const char *, const char *> * const PackageProcessingOpsEnd = PackageProcessingOps + sizeof(PackageProcessingOps) / sizeof(PackageProcessingOps[0]);
60
61 // Predicate to test whether an entry in the PackageProcessingOps
62 // array matches a string.
63 class MatchProcessingOp
64 {
65 const char *target;
66
67 public:
68 MatchProcessingOp(const char *the_target)
69 : target(the_target)
70 {
71 }
72
73 bool operator()(const std::pair<const char *, const char *> &pair) const
74 {
75 return strcmp(pair.first, target) == 0;
76 }
77 };
78}
09fa2df2 79
cebe0287
MV
80/* helper function to ionice the given PID
81
82 there is no C header for ionice yet - just the syscall interface
83 so we use the binary from util-linux
84*/
85static bool
86ionice(int PID)
87{
88 if (!FileExists("/usr/bin/ionice"))
89 return false;
90 pid_t Process = ExecFork();
91 if (Process == 0)
92 {
93 char buf[32];
94 snprintf(buf, sizeof(buf), "-p%d", PID);
95 const char *Args[4];
96 Args[0] = "/usr/bin/ionice";
97 Args[1] = "-c3";
98 Args[2] = buf;
99 Args[3] = 0;
100 execv(Args[0], (char **)Args);
101 }
102 return ExecWait(Process, "ionice");
103}
104
03e39e59
AL
105// DPkgPM::pkgDPkgPM - Constructor /*{{{*/
106// ---------------------------------------------------------------------
107/* */
5e457a93 108pkgDPkgPM::pkgDPkgPM(pkgDepCache *Cache)
71afbdb5 109 : pkgPackageManager(Cache), dpkgbuf_pos(0),
ff38d63b 110 term_out(NULL), PackagesDone(0), PackagesTotal(0), pkgFailures(0)
03e39e59
AL
111{
112}
113 /*}}}*/
114// DPkgPM::pkgDPkgPM - Destructor /*{{{*/
115// ---------------------------------------------------------------------
116/* */
117pkgDPkgPM::~pkgDPkgPM()
118{
119}
120 /*}}}*/
121// DPkgPM::Install - Install a package /*{{{*/
122// ---------------------------------------------------------------------
123/* Add an install operation to the sequence list */
124bool pkgDPkgPM::Install(PkgIterator Pkg,string File)
125{
126 if (File.empty() == true || Pkg.end() == true)
127 return _error->Error("Internal Error, No file name for %s",Pkg.Name());
128
129 List.push_back(Item(Item::Install,Pkg,File));
130 return true;
131}
132 /*}}}*/
133// DPkgPM::Configure - Configure a package /*{{{*/
134// ---------------------------------------------------------------------
135/* Add a configure operation to the sequence list */
136bool pkgDPkgPM::Configure(PkgIterator Pkg)
137{
138 if (Pkg.end() == true)
139 return false;
3e9c4f70 140
5e312de7
DK
141 List.push_back(Item(Item::Configure, Pkg));
142
143 // Use triggers for config calls if we configure "smart"
144 // as otherwise Pre-Depends will not be satisfied, see #526774
145 if (_config->FindB("DPkg::TriggersPending", false) == true)
146 List.push_back(Item(Item::TriggersPending, PkgIterator()));
3e9c4f70 147
03e39e59
AL
148 return true;
149}
150 /*}}}*/
151// DPkgPM::Remove - Remove a package /*{{{*/
152// ---------------------------------------------------------------------
153/* Add a remove operation to the sequence list */
fc4b5c9f 154bool pkgDPkgPM::Remove(PkgIterator Pkg,bool Purge)
03e39e59
AL
155{
156 if (Pkg.end() == true)
157 return false;
158
fc4b5c9f
AL
159 if (Purge == true)
160 List.push_back(Item(Item::Purge,Pkg));
161 else
162 List.push_back(Item(Item::Remove,Pkg));
6dd55be7
AL
163 return true;
164}
165 /*}}}*/
b2e465d6
AL
166// DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
167// ---------------------------------------------------------------------
168/* This is part of the helper script communication interface, it sends
169 very complete information down to the other end of the pipe.*/
170bool pkgDPkgPM::SendV2Pkgs(FILE *F)
171{
172 fprintf(F,"VERSION 2\n");
173
174 /* Write out all of the configuration directives by walking the
175 configuration tree */
176 const Configuration::Item *Top = _config->Tree(0);
177 for (; Top != 0;)
178 {
179 if (Top->Value.empty() == false)
180 {
181 fprintf(F,"%s=%s\n",
182 QuoteString(Top->FullTag(),"=\"\n").c_str(),
183 QuoteString(Top->Value,"\n").c_str());
184 }
185
186 if (Top->Child != 0)
187 {
188 Top = Top->Child;
189 continue;
190 }
191
192 while (Top != 0 && Top->Next == 0)
193 Top = Top->Parent;
194 if (Top != 0)
195 Top = Top->Next;
196 }
197 fprintf(F,"\n");
198
199 // Write out the package actions in order.
200 for (vector<Item>::iterator I = List.begin(); I != List.end(); I++)
201 {
3e9c4f70
DK
202 if(I->Pkg.end() == true)
203 continue;
204
b2e465d6
AL
205 pkgDepCache::StateCache &S = Cache[I->Pkg];
206
207 fprintf(F,"%s ",I->Pkg.Name());
208 // Current version
209 if (I->Pkg->CurrentVer == 0)
210 fprintf(F,"- ");
211 else
212 fprintf(F,"%s ",I->Pkg.CurrentVer().VerStr());
213
214 // Show the compare operator
215 // Target version
216 if (S.InstallVer != 0)
217 {
218 int Comp = 2;
219 if (I->Pkg->CurrentVer != 0)
220 Comp = S.InstVerIter(Cache).CompareVer(I->Pkg.CurrentVer());
221 if (Comp < 0)
222 fprintf(F,"> ");
223 if (Comp == 0)
224 fprintf(F,"= ");
225 if (Comp > 0)
226 fprintf(F,"< ");
227 fprintf(F,"%s ",S.InstVerIter(Cache).VerStr());
228 }
229 else
230 fprintf(F,"> - ");
231
232 // Show the filename/operation
233 if (I->Op == Item::Install)
234 {
235 // No errors here..
236 if (I->File[0] != '/')
237 fprintf(F,"**ERROR**\n");
238 else
239 fprintf(F,"%s\n",I->File.c_str());
240 }
241 if (I->Op == Item::Configure)
242 fprintf(F,"**CONFIGURE**\n");
243 if (I->Op == Item::Remove ||
244 I->Op == Item::Purge)
245 fprintf(F,"**REMOVE**\n");
246
247 if (ferror(F) != 0)
248 return false;
249 }
250 return true;
251}
252 /*}}}*/
db0c350f
AL
253// DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
254// ---------------------------------------------------------------------
255/* This looks for a list of scripts to run from the configuration file
256 each one is run and is fed on standard input a list of all .deb files
257 that are due to be installed. */
258bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf)
259{
260 Configuration::Item const *Opts = _config->Tree(Cnf);
261 if (Opts == 0 || Opts->Child == 0)
262 return true;
263 Opts = Opts->Child;
264
265 unsigned int Count = 1;
266 for (; Opts != 0; Opts = Opts->Next, Count++)
267 {
268 if (Opts->Value.empty() == true)
269 continue;
b2e465d6
AL
270
271 // Determine the protocol version
272 string OptSec = Opts->Value;
273 string::size_type Pos;
274 if ((Pos = OptSec.find(' ')) == string::npos || Pos == 0)
275 Pos = OptSec.length();
b2e465d6
AL
276 OptSec = "DPkg::Tools::Options::" + string(Opts->Value.c_str(),Pos);
277
278 unsigned int Version = _config->FindI(OptSec+"::Version",1);
279
db0c350f
AL
280 // Create the pipes
281 int Pipes[2];
282 if (pipe(Pipes) != 0)
283 return _error->Errno("pipe","Failed to create IPC pipe to subprocess");
284 SetCloseExec(Pipes[0],true);
285 SetCloseExec(Pipes[1],true);
286
287 // Purified Fork for running the script
288 pid_t Process = ExecFork();
289 if (Process == 0)
290 {
291 // Setup the FDs
292 dup2(Pipes[0],STDIN_FILENO);
293 SetCloseExec(STDOUT_FILENO,false);
294 SetCloseExec(STDIN_FILENO,false);
295 SetCloseExec(STDERR_FILENO,false);
90ecbd7d
AL
296
297 const char *Args[4];
db0c350f 298 Args[0] = "/bin/sh";
90ecbd7d
AL
299 Args[1] = "-c";
300 Args[2] = Opts->Value.c_str();
301 Args[3] = 0;
db0c350f
AL
302 execv(Args[0],(char **)Args);
303 _exit(100);
304 }
305 close(Pipes[0]);
b2e465d6
AL
306 FILE *F = fdopen(Pipes[1],"w");
307 if (F == 0)
308 return _error->Errno("fdopen","Faild to open new FD");
309
db0c350f 310 // Feed it the filenames.
b2e465d6
AL
311 bool Die = false;
312 if (Version <= 1)
db0c350f 313 {
b2e465d6 314 for (vector<Item>::iterator I = List.begin(); I != List.end(); I++)
db0c350f 315 {
b2e465d6
AL
316 // Only deal with packages to be installed from .deb
317 if (I->Op != Item::Install)
318 continue;
319
320 // No errors here..
321 if (I->File[0] != '/')
322 continue;
323
324 /* Feed the filename of each package that is pending install
325 into the pipe. */
326 fprintf(F,"%s\n",I->File.c_str());
327 if (ferror(F) != 0)
328 {
329 Die = true;
330 break;
331 }
90ecbd7d 332 }
db0c350f 333 }
b2e465d6
AL
334 else
335 Die = !SendV2Pkgs(F);
336
337 fclose(F);
db0c350f
AL
338
339 // Clean up the sub process
340 if (ExecWait(Process,Opts->Value.c_str()) == false)
90ecbd7d 341 return _error->Error("Failure running script %s",Opts->Value.c_str());
db0c350f
AL
342 }
343
344 return true;
345}
ceabc520
MV
346 /*}}}*/
347// DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
348// ---------------------------------------------------------------------
349/*
350*/
351void pkgDPkgPM::DoStdin(int master)
352{
aff87a76
MV
353 unsigned char input_buf[256] = {0,};
354 ssize_t len = read(0, input_buf, sizeof(input_buf));
9983591d
OS
355 if (len)
356 write(master, input_buf, len);
357 else
358 stdin_is_dev_null = true;
ceabc520 359}
03e39e59 360 /*}}}*/
ceabc520
MV
361// DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
362// ---------------------------------------------------------------------
363/*
364 * read the terminal pty and write log
365 */
8ecd1fed 366void pkgDPkgPM::DoTerminalPty(int master)
ceabc520 367{
aff87a76 368 unsigned char term_buf[1024] = {0,0, };
ceabc520 369
aff87a76 370 ssize_t len=read(master, term_buf, sizeof(term_buf));
1fc825bf
MV
371 if(len == -1 && errno == EIO)
372 {
373 // this happens when the child is about to exit, we
374 // give it time to actually exit, otherwise we run
375 // into a race
376 usleep(500000);
377 return;
378 }
379 if(len <= 0)
955a6ddb 380 return;
955a6ddb 381 write(1, term_buf, len);
8da1f029
MV
382 if(term_out)
383 fwrite(term_buf, len, sizeof(char), term_out);
ceabc520 384}
03e39e59 385 /*}}}*/
6191b008
MV
386// DPkgPM::ProcessDpkgStatusBuf /*{{{*/
387// ---------------------------------------------------------------------
388/*
389 */
09fa2df2 390void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd, char *line)
6191b008 391{
887f5036 392 bool const Debug = _config->FindB("Debug::pkgDPkgProgressReporting",false);
09fa2df2
MV
393 // the status we output
394 ostringstream status;
395
887f5036 396 if (Debug == true)
09fa2df2
MV
397 std::clog << "got from dpkg '" << line << "'" << std::endl;
398
399
400 /* dpkg sends strings like this:
401 'status: <pkg>: <pkg qstate>'
402 errors look like this:
403 '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
404 and conffile-prompt like this
405 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
fc2d32c0
MV
406
407 Newer versions of dpkg sent also:
408 'processing: install: pkg'
409 'processing: configure: pkg'
410 'processing: remove: pkg'
887f5036 411 'processing: purge: pkg' - but for apt is it a ignored "unknown" action
fc2d32c0 412 'processing: trigproc: trigger'
09fa2df2
MV
413
414 */
5279f566 415 char* list[6];
09fa2df2
MV
416 // dpkg sends multiline error messages sometimes (see
417 // #374195 for a example. we should support this by
418 // either patching dpkg to not send multiline over the
419 // statusfd or by rewriting the code here to deal with
420 // it. for now we just ignore it and not crash
421 TokSplitString(':', line, list, sizeof(list)/sizeof(list[0]));
f26fcbc7 422 if( list[0] == NULL || list[1] == NULL || list[2] == NULL)
09fa2df2 423 {
887f5036 424 if (Debug == true)
09fa2df2
MV
425 std::clog << "ignoring line: not enough ':'" << std::endl;
426 return;
427 }
887f5036
DK
428 const char* const pkg = list[1];
429 const char* action = _strstrip(list[2]);
09fa2df2 430
fc2d32c0
MV
431 // 'processing' from dpkg looks like
432 // 'processing: action: pkg'
433 if(strncmp(list[0], "processing", strlen("processing")) == 0)
434 {
435 char s[200];
887f5036
DK
436 const char* const pkg_or_trigger = _strstrip(list[2]);
437 action = _strstrip( list[1]);
f7dec19f
DB
438 const std::pair<const char *, const char *> * const iter =
439 std::find_if(PackageProcessingOpsBegin,
440 PackageProcessingOpsEnd,
441 MatchProcessingOp(action));
442 if(iter == PackageProcessingOpsEnd)
fc2d32c0 443 {
887f5036
DK
444 if (Debug == true)
445 std::clog << "ignoring unknown action: " << action << std::endl;
fc2d32c0
MV
446 return;
447 }
f7dec19f 448 snprintf(s, sizeof(s), _(iter->second), pkg_or_trigger);
fc2d32c0
MV
449
450 status << "pmstatus:" << pkg_or_trigger
451 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
452 << ":" << s
453 << endl;
454 if(OutStatusFd > 0)
455 write(OutStatusFd, status.str().c_str(), status.str().size());
887f5036 456 if (Debug == true)
fc2d32c0
MV
457 std::clog << "send: '" << status.str() << "'" << endl;
458 return;
459 }
460
09fa2df2
MV
461 if(strncmp(action,"error",strlen("error")) == 0)
462 {
d6a4afcb
MV
463 // urgs, sometime has ":" in its error string so that we
464 // end up with the error message split between list[3]
465 // and list[4], e.g. the message:
5279f566 466 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
d6a4afcb 467 // concat them again
5279f566
MV
468 if( list[4] != NULL )
469 list[3][strlen(list[3])] = ':';
d6a4afcb 470
09fa2df2 471 status << "pmerror:" << list[1]
ff56e980 472 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
09fa2df2
MV
473 << ":" << list[3]
474 << endl;
475 if(OutStatusFd > 0)
476 write(OutStatusFd, status.str().c_str(), status.str().size());
887f5036 477 if (Debug == true)
09fa2df2 478 std::clog << "send: '" << status.str() << "'" << endl;
f060e833
MV
479 pkgFailures++;
480 WriteApportReport(list[1], list[3]);
09fa2df2
MV
481 return;
482 }
887f5036 483 else if(strncmp(action,"conffile",strlen("conffile")) == 0)
09fa2df2
MV
484 {
485 status << "pmconffile:" << list[1]
ff56e980 486 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
09fa2df2
MV
487 << ":" << list[3]
488 << endl;
489 if(OutStatusFd > 0)
490 write(OutStatusFd, status.str().c_str(), status.str().size());
887f5036 491 if (Debug == true)
09fa2df2
MV
492 std::clog << "send: '" << status.str() << "'" << endl;
493 return;
494 }
495
887f5036 496 vector<struct DpkgState> const &states = PackageOps[pkg];
09fa2df2
MV
497 const char *next_action = NULL;
498 if(PackageOpsDone[pkg] < states.size())
499 next_action = states[PackageOpsDone[pkg]].state;
500 // check if the package moved to the next dpkg state
501 if(next_action && (strcmp(action, next_action) == 0))
502 {
503 // only read the translation if there is actually a next
504 // action
505 const char *translation = _(states[PackageOpsDone[pkg]].str);
506 char s[200];
507 snprintf(s, sizeof(s), translation, pkg);
508
509 // we moved from one dpkg state to a new one, report that
510 PackageOpsDone[pkg]++;
ff56e980 511 PackagesDone++;
09fa2df2
MV
512 // build the status str
513 status << "pmstatus:" << pkg
ff56e980 514 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
09fa2df2
MV
515 << ":" << s
516 << endl;
517 if(OutStatusFd > 0)
518 write(OutStatusFd, status.str().c_str(), status.str().size());
887f5036 519 if (Debug == true)
09fa2df2
MV
520 std::clog << "send: '" << status.str() << "'" << endl;
521 }
887f5036 522 if (Debug == true)
09fa2df2
MV
523 std::clog << "(parsed from dpkg) pkg: " << pkg
524 << " action: " << action << endl;
6191b008 525}
887f5036
DK
526 /*}}}*/
527// DPkgPM::DoDpkgStatusFd /*{{{*/
6191b008
MV
528// ---------------------------------------------------------------------
529/*
530 */
09fa2df2 531void pkgDPkgPM::DoDpkgStatusFd(int statusfd, int OutStatusFd)
6191b008
MV
532{
533 char *p, *q;
534 int len;
535
536 len=read(statusfd, &dpkgbuf[dpkgbuf_pos], sizeof(dpkgbuf)-dpkgbuf_pos);
537 dpkgbuf_pos += len;
538 if(len <= 0)
539 return;
ceabc520 540
6191b008
MV
541 // process line by line if we have a buffer
542 p = q = dpkgbuf;
543 while((q=(char*)memchr(p, '\n', dpkgbuf+dpkgbuf_pos-p)) != NULL)
544 {
545 *q = 0;
09fa2df2 546 ProcessDpkgStatusLine(OutStatusFd, p);
6191b008
MV
547 p=q+1; // continue with next line
548 }
549
550 // now move the unprocessed bits (after the final \n that is now a 0x0)
551 // to the start and update dpkgbuf_pos
552 p = (char*)memrchr(dpkgbuf, 0, dpkgbuf_pos);
553 if(p == NULL)
554 return;
555
556 // we are interessted in the first char *after* 0x0
557 p++;
558
559 // move the unprocessed tail to the start and update pos
560 memmove(dpkgbuf, p, p-dpkgbuf);
561 dpkgbuf_pos = dpkgbuf+dpkgbuf_pos-p;
562}
563 /*}}}*/
d7a4ffd6 564// DPkgPM::WriteHistoryTag /*{{{*/
a29b2c0b 565void pkgDPkgPM::WriteHistoryTag(FILE *history_out, string tag, string value)
d7a4ffd6
MV
566{
567 if (value.size() > 0)
568 {
569 // poor mans rstrip(", ")
570 if (value[value.size()-2] == ',' && value[value.size()-1] == ' ')
571 value.erase(value.size() - 2, 2);
572 fprintf(history_out, "%s: %s\n", tag.c_str(), value.c_str());
573 }
574} /*}}}*/
887f5036 575// DPkgPM::OpenLog /*{{{*/
5d053270
MV
576bool pkgDPkgPM::OpenLog()
577{
c5a4be87 578 string const logdir = _config->FindDir("Dir::Log");
5d053270
MV
579 if(not FileExists(logdir))
580 return _error->Error(_("Directory '%s' missing"), logdir.c_str());
9169c871
MV
581
582 // get current time
583 char timestr[200];
c5a4be87
MV
584 time_t const t = time(NULL);
585 struct tm const * const tmp = localtime(&t);
9169c871
MV
586 strftime(timestr, sizeof(timestr), "%F %T", tmp);
587
588 // open terminal log
c5a4be87 589 string const logfile_name = flCombine(logdir,
5d053270
MV
590 _config->Find("Dir::Log::Terminal"));
591 if (!logfile_name.empty())
592 {
593 term_out = fopen(logfile_name.c_str(),"a");
b39c1859 594 if (term_out == NULL)
c5a4be87 595 return _error->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name.c_str());
b39c1859 596
5d053270 597 chmod(logfile_name.c_str(), 0600);
762d7367 598 fprintf(term_out, "\nLog started: %s\n", timestr);
5d053270 599 }
9169c871 600
c5a4be87
MV
601 // write your history
602 string const history_name = flCombine(logdir,
9169c871
MV
603 _config->Find("Dir::Log::History"));
604 if (!history_name.empty())
605 {
a29b2c0b 606 FILE *history_out = fopen(history_name.c_str(),"a");
c5a4be87
MV
607 if (history_out == NULL)
608 return _error->WarningE("OpenLog", _("Could not open file '%s'"), history_name.c_str());
9169c871
MV
609 chmod(history_name.c_str(), 0644);
610 fprintf(history_out, "\nStart-Date: %s\n", timestr);
611 string remove, purge, install, upgrade, downgrade;
612 for (pkgCache::PkgIterator I = Cache.PkgBegin(); I.end() == false; I++)
613 {
d7a4ffd6
MV
614 if (Cache[I].NewInstall())
615 install += I.Name() + string(" (") + Cache[I].CandVersion + string("), ");
616 else if (Cache[I].Upgrade())
617 upgrade += I.Name() + string(" (") + Cache[I].CurVersion + string(", ") + Cache[I].CandVersion + string("), ");
9c59aada 618 else if (Cache[I].Downgrade())
d7a4ffd6 619 downgrade += I.Name() + string(" (") + Cache[I].CurVersion + string(", ") + Cache[I].CandVersion + string("), ");
9169c871
MV
620 else if (Cache[I].Delete())
621 {
622 if ((Cache[I].iFlags & pkgDepCache::Purge) == pkgDepCache::Purge)
d7a4ffd6 623 purge += I.Name() + string(" (") + Cache[I].CurVersion + string("), ");
9169c871 624 else
d7a4ffd6 625 remove += I.Name() + string(" (") + Cache[I].CurVersion + string("), ");
9169c871 626 }
9169c871 627 }
a29b2c0b
MV
628 WriteHistoryTag(history_out, "Install", install);
629 WriteHistoryTag(history_out, "Upgrade", upgrade);
630 WriteHistoryTag(history_out, "Downgrade",downgrade);
631 WriteHistoryTag(history_out, "Remove",remove);
632 WriteHistoryTag(history_out, "Purge",purge);
633 fclose(history_out);
9169c871
MV
634 }
635
5d053270
MV
636 return true;
637}
887f5036
DK
638 /*}}}*/
639// DPkg::CloseLog /*{{{*/
5d053270
MV
640bool pkgDPkgPM::CloseLog()
641{
9169c871
MV
642 char timestr[200];
643 time_t t = time(NULL);
644 struct tm *tmp = localtime(&t);
645 strftime(timestr, sizeof(timestr), "%F %T", tmp);
646
5d053270
MV
647 if(term_out)
648 {
5d053270 649 fprintf(term_out, "Log ended: ");
9169c871 650 fprintf(term_out, "%s", timestr);
5d053270
MV
651 fprintf(term_out, "\n");
652 fclose(term_out);
653 }
654 term_out = NULL;
9169c871 655
a29b2c0b
MV
656 string history_name = flCombine(_config->FindDir("Dir::Log"),
657 _config->Find("Dir::Log::History"));
658 if (!history_name.empty())
9169c871 659 {
a29b2c0b 660 FILE *history_out = fopen(history_name.c_str(),"a");
9169c871
MV
661 fprintf(history_out, "End-Date: %s\n", timestr);
662 fclose(history_out);
663 }
664
5d053270
MV
665 return true;
666}
887f5036 667 /*}}}*/
919e5852
OS
668/*{{{*/
669// This implements a racy version of pselect for those architectures
670// that don't have a working implementation.
671// FIXME: Probably can be removed on Lenny+1
672static int racy_pselect(int nfds, fd_set *readfds, fd_set *writefds,
673 fd_set *exceptfds, const struct timespec *timeout,
674 const sigset_t *sigmask)
675{
676 sigset_t origmask;
677 struct timeval tv;
678 int retval;
679
f6b37f38
OS
680 tv.tv_sec = timeout->tv_sec;
681 tv.tv_usec = timeout->tv_nsec/1000;
919e5852 682
f6b37f38 683 sigprocmask(SIG_SETMASK, sigmask, &origmask);
919e5852
OS
684 retval = select(nfds, readfds, writefds, exceptfds, &tv);
685 sigprocmask(SIG_SETMASK, &origmask, 0);
686 return retval;
687}
688/*}}}*/
03e39e59
AL
689// DPkgPM::Go - Run the sequence /*{{{*/
690// ---------------------------------------------------------------------
75ef8f14
MV
691/* This globs the operations and calls dpkg
692 *
693 * If it is called with "OutStatusFd" set to a valid file descriptor
694 * apt will report the install progress over this fd. It maps the
695 * dpkg states a package goes through to human readable (and i10n-able)
696 * names and calculates a percentage for each step.
697*/
698bool pkgDPkgPM::Go(int OutStatusFd)
03e39e59 699{
07dd557b
MV
700 fd_set rfds;
701 struct timespec tv;
702 sigset_t sigmask;
703 sigset_t original_sigmask;
704
887f5036
DK
705 unsigned int const MaxArgs = _config->FindI("Dpkg::MaxArgs",8*1024);
706 unsigned int const MaxArgBytes = _config->FindI("Dpkg::MaxArgBytes",32*1024);
5e312de7 707 bool const NoTriggers = _config->FindB("DPkg::NoTriggers", false);
aff4e2f1 708
6dd55be7
AL
709 if (RunScripts("DPkg::Pre-Invoke") == false)
710 return false;
db0c350f
AL
711
712 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
713 return false;
fc2d32c0 714
3e9c4f70
DK
715 // support subpressing of triggers processing for special
716 // cases like d-i that runs the triggers handling manually
5e312de7 717 bool const SmartConf = (_config->Find("PackageManager::Configure", "all") != "all");
5c23dbcc 718 bool const TriggersPending = _config->FindB("DPkg::TriggersPending", false);
5e312de7
DK
719 if (_config->FindB("DPkg::ConfigurePending", SmartConf) == true)
720 List.push_back(Item(Item::ConfigurePending, PkgIterator()));
3e9c4f70 721
75ef8f14
MV
722 // map the dpkg states to the operations that are performed
723 // (this is sorted in the same way as Item::Ops)
fb7bf91c 724 static const struct DpkgState DpkgStatesOpMap[][7] = {
75ef8f14
MV
725 // Install operation
726 {
1d52ce01
MV
727 {"half-installed", N_("Preparing %s")},
728 {"unpacked", N_("Unpacking %s") },
75ef8f14
MV
729 {NULL, NULL}
730 },
731 // Configure operation
732 {
1d52ce01
MV
733 {"unpacked",N_("Preparing to configure %s") },
734 {"half-configured", N_("Configuring %s") },
735 { "installed", N_("Installed %s")},
75ef8f14
MV
736 {NULL, NULL}
737 },
738 // Remove operation
739 {
1d52ce01
MV
740 {"half-configured", N_("Preparing for removal of %s")},
741 {"half-installed", N_("Removing %s")},
742 {"config-files", N_("Removed %s")},
75ef8f14
MV
743 {NULL, NULL}
744 },
745 // Purge operation
746 {
1d52ce01
MV
747 {"config-files", N_("Preparing to completely remove %s")},
748 {"not-installed", N_("Completely removed %s")},
75ef8f14
MV
749 {NULL, NULL}
750 },
751 };
db0c350f 752
75ef8f14
MV
753 // init the PackageOps map, go over the list of packages that
754 // that will be [installed|configured|removed|purged] and add
755 // them to the PackageOps map (the dpkg states it goes through)
756 // and the PackageOpsTranslations (human readable strings)
887f5036 757 for (vector<Item>::const_iterator I = List.begin(); I != List.end();I++)
75ef8f14 758 {
3e9c4f70
DK
759 if((*I).Pkg.end() == true)
760 continue;
761
887f5036 762 string const name = (*I).Pkg.Name();
75ef8f14
MV
763 PackageOpsDone[name] = 0;
764 for(int i=0; (DpkgStatesOpMap[(*I).Op][i]).state != NULL; i++)
765 {
766 PackageOps[name].push_back(DpkgStatesOpMap[(*I).Op][i]);
ff56e980 767 PackagesTotal++;
75ef8f14 768 }
887f5036 769 }
75ef8f14 770
9983591d
OS
771 stdin_is_dev_null = false;
772
ff56e980 773 // create log
5d053270 774 OpenLog();
ff56e980 775
75ef8f14 776 // this loop is runs once per operation
887f5036 777 for (vector<Item>::const_iterator I = List.begin(); I != List.end();)
03e39e59 778 {
5c23dbcc 779 // Do all actions with the same Op in one run
887f5036 780 vector<Item>::const_iterator J = I;
5c23dbcc
DK
781 if (TriggersPending == true)
782 for (; J != List.end(); J++)
783 {
784 if (J->Op == I->Op)
785 continue;
786 if (J->Op != Item::TriggersPending)
787 break;
788 vector<Item>::const_iterator T = J + 1;
789 if (T != List.end() && T->Op == I->Op)
790 continue;
791 break;
792 }
793 else
794 for (; J != List.end() && J->Op == I->Op; J++)
795 /* nothing */;
30e1eab5 796
03e39e59 797 // Generate the argument list
aff4e2f1 798 const char *Args[MaxArgs + 50];
599d6ad5
MV
799
800 // Now check if we are within the MaxArgs limit
801 //
802 // this code below is problematic, because it may happen that
803 // the argument list is split in a way that A depends on B
804 // and they are in the same "--configure A B" run
805 // - with the split they may now be configured in different
806 // runs
aff4e2f1
AL
807 if (J - I > (signed)MaxArgs)
808 J = I + MaxArgs;
03e39e59 809
30e1eab5
AL
810 unsigned int n = 0;
811 unsigned long Size = 0;
887f5036 812 string const Tmp = _config->Find("Dir::Bin::dpkg","dpkg");
50914ffa 813 Args[n++] = Tmp.c_str();
30e1eab5 814 Size += strlen(Args[n-1]);
03e39e59 815
6dd55be7
AL
816 // Stick in any custom dpkg options
817 Configuration::Item const *Opts = _config->Tree("DPkg::Options");
818 if (Opts != 0)
819 {
820 Opts = Opts->Child;
821 for (; Opts != 0; Opts = Opts->Next)
822 {
823 if (Opts->Value.empty() == true)
824 continue;
825 Args[n++] = Opts->Value.c_str();
826 Size += Opts->Value.length();
827 }
828 }
829
007dc9e0 830 char status_fd_buf[20];
75ef8f14
MV
831 int fd[2];
832 pipe(fd);
833
834 Args[n++] = "--status-fd";
835 Size += strlen(Args[n-1]);
836 snprintf(status_fd_buf,sizeof(status_fd_buf),"%i", fd[1]);
837 Args[n++] = status_fd_buf;
838 Size += strlen(Args[n-1]);
007dc9e0 839
03e39e59
AL
840 switch (I->Op)
841 {
842 case Item::Remove:
843 Args[n++] = "--force-depends";
30e1eab5 844 Size += strlen(Args[n-1]);
03e39e59 845 Args[n++] = "--force-remove-essential";
30e1eab5 846 Size += strlen(Args[n-1]);
03e39e59 847 Args[n++] = "--remove";
30e1eab5 848 Size += strlen(Args[n-1]);
03e39e59
AL
849 break;
850
fc4b5c9f
AL
851 case Item::Purge:
852 Args[n++] = "--force-depends";
853 Size += strlen(Args[n-1]);
854 Args[n++] = "--force-remove-essential";
855 Size += strlen(Args[n-1]);
856 Args[n++] = "--purge";
857 Size += strlen(Args[n-1]);
858 break;
859
03e39e59
AL
860 case Item::Configure:
861 Args[n++] = "--configure";
30e1eab5 862 Size += strlen(Args[n-1]);
03e39e59 863 break;
3e9c4f70
DK
864
865 case Item::ConfigurePending:
866 Args[n++] = "--configure";
867 Size += strlen(Args[n-1]);
868 Args[n++] = "--pending";
869 Size += strlen(Args[n-1]);
870 break;
871
5e312de7
DK
872 case Item::TriggersPending:
873 Args[n++] = "--triggers-only";
874 Size += strlen(Args[n-1]);
875 Args[n++] = "--pending";
876 Size += strlen(Args[n-1]);
877 break;
878
03e39e59
AL
879 case Item::Install:
880 Args[n++] = "--unpack";
30e1eab5 881 Size += strlen(Args[n-1]);
857a1d4a
MV
882 Args[n++] = "--auto-deconfigure";
883 Size += strlen(Args[n-1]);
03e39e59
AL
884 break;
885 }
3e9c4f70 886
5e312de7 887 if (NoTriggers == true && I->Op != Item::TriggersPending &&
d5081aee 888 I->Op != Item::ConfigurePending)
3e9c4f70
DK
889 {
890 Args[n++] = "--no-triggers";
891 Size += strlen(Args[n-1]);
892 }
893
03e39e59
AL
894 // Write in the file or package names
895 if (I->Op == Item::Install)
30e1eab5 896 {
aff4e2f1 897 for (;I != J && Size < MaxArgBytes; I++)
30e1eab5 898 {
cf544e14
AL
899 if (I->File[0] != '/')
900 return _error->Error("Internal Error, Pathname to install is not absolute '%s'",I->File.c_str());
03e39e59 901 Args[n++] = I->File.c_str();
30e1eab5
AL
902 Size += strlen(Args[n-1]);
903 }
904 }
03e39e59 905 else
30e1eab5 906 {
aff4e2f1 907 for (;I != J && Size < MaxArgBytes; I++)
30e1eab5 908 {
3e9c4f70
DK
909 if((*I).Pkg.end() == true)
910 continue;
03e39e59 911 Args[n++] = I->Pkg.Name();
30e1eab5
AL
912 Size += strlen(Args[n-1]);
913 }
914 }
03e39e59 915 Args[n] = 0;
30e1eab5
AL
916 J = I;
917
918 if (_config->FindB("Debug::pkgDPkgPM",false) == true)
919 {
920 for (unsigned int k = 0; k != n; k++)
921 clog << Args[k] << ' ';
922 clog << endl;
923 continue;
924 }
03e39e59 925
03e39e59
AL
926 cout << flush;
927 clog << flush;
928 cerr << flush;
929
930 /* Mask off sig int/quit. We do this because dpkg also does when
931 it forks scripts. What happens is that when you hit ctrl-c it sends
932 it to all processes in the group. Since dpkg ignores the signal
933 it doesn't die but we do! So we must also ignore it */
7f9a6360
AL
934 sighandler_t old_SIGQUIT = signal(SIGQUIT,SIG_IGN);
935 sighandler_t old_SIGINT = signal(SIGINT,SIG_IGN);
d8cb4aa4 936
6e7f872d
MV
937 // ignore SIGHUP as well (debian #463030)
938 sighandler_t old_SIGHUP = signal(SIGHUP,SIG_IGN);
939
d8cb4aa4
MV
940 struct termios tt;
941 struct winsize win;
4e550036
MV
942 int master = -1;
943 int slave = -1;
d8cb4aa4 944
4e550036
MV
945 // if tcgetattr does not return zero there was a error
946 // and we do not do any pty magic
947 if (tcgetattr(0, &tt) == 0)
090c6566 948 {
4e550036
MV
949 ioctl(0, TIOCGWINSZ, (char *)&win);
950 if (openpty(&master, &slave, NULL, &tt, &win) < 0)
951 {
952 const char *s = _("Can not write log, openpty() "
953 "failed (/dev/pts not mounted?)\n");
954 fprintf(stderr, "%s",s);
6847d275
MV
955 if(term_out)
956 fprintf(term_out, "%s",s);
4e550036
MV
957 master = slave = -1;
958 } else {
959 struct termios rtt;
960 rtt = tt;
961 cfmakeraw(&rtt);
962 rtt.c_lflag &= ~ECHO;
4d7ac88c 963 rtt.c_lflag |= ISIG;
4e550036
MV
964 // block SIGTTOU during tcsetattr to prevent a hang if
965 // the process is a member of the background process group
966 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
967 sigemptyset(&sigmask);
968 sigaddset(&sigmask, SIGTTOU);
969 sigprocmask(SIG_BLOCK,&sigmask, &original_sigmask);
970 tcsetattr(0, TCSAFLUSH, &rtt);
971 sigprocmask(SIG_SETMASK, &original_sigmask, 0);
972 }
d8cb4aa4
MV
973 }
974
75ef8f14 975 // Fork dpkg
007dc9e0 976 pid_t Child;
75ef8f14 977 _config->Set("APT::Keep-Fds::",fd[1]);
ccd8e28f
MV
978 // send status information that we are about to fork dpkg
979 if(OutStatusFd > 0) {
980 ostringstream status;
981 status << "pmstatus:dpkg-exec:"
982 << (PackagesDone/float(PackagesTotal)*100.0)
983 << ":" << _("Running dpkg")
984 << endl;
985 write(OutStatusFd, status.str().c_str(), status.str().size());
986 }
75ef8f14 987 Child = ExecFork();
6dd55be7 988
03e39e59
AL
989 // This is the child
990 if (Child == 0)
991 {
a4cf3665
MV
992 if(slave >= 0 && master >= 0)
993 {
994 setsid();
995 ioctl(slave, TIOCSCTTY, 0);
996 close(master);
997 dup2(slave, 0);
998 dup2(slave, 1);
999 dup2(slave, 2);
1000 close(slave);
1001 }
75ef8f14 1002 close(fd[0]); // close the read end of the pipe
d8cb4aa4 1003
4b7cfe96
MV
1004 if (_config->FindDir("DPkg::Chroot-Directory","/") != "/")
1005 {
1006 std::cerr << "Chrooting into "
1007 << _config->FindDir("DPkg::Chroot-Directory")
1008 << std::endl;
1009 if (chroot(_config->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
1010 _exit(100);
1011 }
1012
cf544e14 1013 if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
0dbb95d8 1014 _exit(100);
03e39e59 1015
421ff807 1016 if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
8b5fe26c
AL
1017 {
1018 int Flags,dummy;
1019 if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
1020 _exit(100);
1021
1022 // Discard everything in stdin before forking dpkg
1023 if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
1024 _exit(100);
1025
1026 while (read(STDIN_FILENO,&dummy,1) == 1);
1027
1028 if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
1029 _exit(100);
1030 }
d8cb4aa4 1031
03e39e59
AL
1032 /* No Job Control Stop Env is a magic dpkg var that prevents it
1033 from using sigstop */
71afbdb5 1034 putenv((char *)"DPKG_NO_TSTP=yes");
d568ed2d 1035 execvp(Args[0],(char **)Args);
03e39e59 1036 cerr << "Could not exec dpkg!" << endl;
0dbb95d8 1037 _exit(100);
03e39e59
AL
1038 }
1039
cebe0287
MV
1040 // apply ionice
1041 if (_config->FindB("DPkg::UseIoNice", false) == true)
1042 ionice(Child);
1043
75ef8f14
MV
1044 // clear the Keep-Fd again
1045 _config->Clear("APT::Keep-Fds",fd[1]);
1046
03e39e59
AL
1047 // Wait for dpkg
1048 int Status = 0;
75ef8f14
MV
1049
1050 // we read from dpkg here
887f5036 1051 int const _dpkgin = fd[0];
75ef8f14
MV
1052 close(fd[1]); // close the write end of the pipe
1053
a4cf3665
MV
1054 if(slave > 0)
1055 close(slave);
75ef8f14 1056
97efd303 1057 // setups fds
1fc825bf
MV
1058 sigemptyset(&sigmask);
1059 sigprocmask(SIG_BLOCK,&sigmask,&original_sigmask);
1060
887f5036
DK
1061 // the result of the waitpid call
1062 int res;
090c6566 1063 int select_ret;
75ef8f14
MV
1064 while ((res=waitpid(Child,&Status, WNOHANG)) != Child) {
1065 if(res < 0) {
1066 // FIXME: move this to a function or something, looks ugly here
1067 // error handling, waitpid returned -1
1068 if (errno == EINTR)
1069 continue;
1070 RunScripts("DPkg::Post-Invoke");
1071
1072 // Restore sig int/quit
1073 signal(SIGQUIT,old_SIGQUIT);
1074 signal(SIGINT,old_SIGINT);
1a853738 1075 signal(SIGHUP,old_SIGHUP);
75ef8f14
MV
1076 return _error->Errno("waitpid","Couldn't wait for subprocess");
1077 }
d8cb4aa4 1078 // wait for input or output here
955a6ddb 1079 FD_ZERO(&rfds);
9983591d
OS
1080 if (!stdin_is_dev_null)
1081 FD_SET(0, &rfds);
955a6ddb 1082 FD_SET(_dpkgin, &rfds);
a4cf3665
MV
1083 if(master >= 0)
1084 FD_SET(master, &rfds);
090c6566 1085 tv.tv_sec = 1;
1fc825bf
MV
1086 tv.tv_nsec = 0;
1087 select_ret = pselect(max(master, _dpkgin)+1, &rfds, NULL, NULL,
1088 &tv, &original_sigmask);
919e5852
OS
1089 if (select_ret < 0 && (errno == EINVAL || errno == ENOSYS))
1090 select_ret = racy_pselect(max(master, _dpkgin)+1, &rfds, NULL,
1091 NULL, &tv, &original_sigmask);
da50ba30 1092 if (select_ret == 0)
5d053270
MV
1093 continue;
1094 else if (select_ret < 0 && errno == EINTR)
1095 continue;
1096 else if (select_ret < 0)
1097 {
1098 perror("select() returned error");
1099 continue;
1100 }
da50ba30 1101
a4cf3665 1102 if(master >= 0 && FD_ISSET(master, &rfds))
1ba38171 1103 DoTerminalPty(master);
a4cf3665 1104 if(master >= 0 && FD_ISSET(0, &rfds))
955a6ddb 1105 DoStdin(master);
955a6ddb 1106 if(FD_ISSET(_dpkgin, &rfds))
09fa2df2 1107 DoDpkgStatusFd(_dpkgin, OutStatusFd);
03e39e59 1108 }
75ef8f14 1109 close(_dpkgin);
03e39e59
AL
1110
1111 // Restore sig int/quit
7f9a6360
AL
1112 signal(SIGQUIT,old_SIGQUIT);
1113 signal(SIGINT,old_SIGINT);
4e648e0b 1114 signal(SIGHUP,old_SIGHUP);
d8cb4aa4 1115
c771f6d9
MV
1116 if(master >= 0)
1117 {
a4cf3665 1118 tcsetattr(0, TCSAFLUSH, &tt);
c771f6d9
MV
1119 close(master);
1120 }
6dd55be7
AL
1121
1122 // Check for an error code.
1123 if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
1124 {
c70496f9
MV
1125 // if it was set to "keep-dpkg-runing" then we won't return
1126 // here but keep the loop going and just report it as a error
1127 // for later
887f5036 1128 bool const stopOnError = _config->FindB("Dpkg::StopOnError",true);
f956efb4 1129
c70496f9
MV
1130 if(stopOnError)
1131 RunScripts("DPkg::Post-Invoke");
1132
a29b2c0b 1133 string dpkg_error;
c70496f9 1134 if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
9169c871 1135 strprintf(dpkg_error, "Sub-process %s received a segmentation fault.",Args[0]);
c70496f9 1136 else if (WIFEXITED(Status) != 0)
9169c871 1137 strprintf(dpkg_error, "Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
c70496f9 1138 else
9169c871
MV
1139 strprintf(dpkg_error, "Sub-process %s exited unexpectedly",Args[0]);
1140
1141 if(dpkg_error.size() > 0)
a29b2c0b 1142 {
9169c871 1143 _error->Error(dpkg_error.c_str());
a29b2c0b
MV
1144 string history_name = flCombine(_config->FindDir("Dir::Log"),
1145 _config->Find("Dir::Log::History"));
1146 if (!history_name.empty())
1147 {
1148 FILE *history_out = fopen(history_name.c_str(),"a");
1149 fprintf(history_out, "Error: %s\n", dpkg_error.c_str());
1150 fclose(history_out);
1151 }
1152 }
c70496f9 1153
ff56e980
MV
1154 if(stopOnError)
1155 {
5d053270 1156 CloseLog();
c70496f9 1157 return false;
ff56e980 1158 }
6dd55be7 1159 }
03e39e59 1160 }
5d053270 1161 CloseLog();
6dd55be7
AL
1162
1163 if (RunScripts("DPkg::Post-Invoke") == false)
1164 return false;
496d5c70
MV
1165
1166 Cache.writeStateFile(NULL);
03e39e59
AL
1167 return true;
1168}
1169 /*}}}*/
281daf46
AL
1170// pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1171// ---------------------------------------------------------------------
1172/* */
1173void pkgDPkgPM::Reset()
1174{
1175 List.erase(List.begin(),List.end());
1176}
1177 /*}}}*/
5e457a93
MV
1178// pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1179// ---------------------------------------------------------------------
1180/* */
1181void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
1182{
1183 string pkgname, reportfile, srcpkgname, pkgver, arch;
1184 string::size_type pos;
1185 FILE *report;
1186
1187 if (_config->FindB("Dpkg::ApportFailureReport",true) == false)
ff38d63b
MV
1188 {
1189 std::clog << "configured to not write apport reports" << std::endl;
5e457a93 1190 return;
ff38d63b 1191 }
5e457a93 1192
d6a4afcb 1193 // only report the first errors
5273f1bf 1194 if(pkgFailures > _config->FindI("APT::Apport::MaxReports", 3))
ff38d63b
MV
1195 {
1196 std::clog << _("No apport report written because MaxReports is reached already") << std::endl;
5e457a93 1197 return;
ff38d63b 1198 }
5e457a93 1199
d6a4afcb
MV
1200 // check if its not a follow up error
1201 const char *needle = dgettext("dpkg", "dependency problems - leaving unconfigured");
1202 if(strstr(errormsg, needle) != NULL) {
1203 std::clog << _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl;
1204 return;
1205 }
1206
2f0d5dea
MV
1207 // do not report disk-full failures
1208 if(strstr(errormsg, strerror(ENOSPC)) != NULL) {
1209 std::clog << _("No apport report written because the error message indicates a disk full error") << std::endl;
1210 return;
1211 }
1212
3024a85e
MV
1213 // do not report out-of-memory failures
1214 if(strstr(errormsg, strerror(ENOMEM)) != NULL) {
1215 std::clog << _("No apport report written because the error message indicates a out of memory error") << std::endl;
1216 return;
1217 }
1218
076c46e5
MZ
1219 // do not report dpkg I/O errors
1220 // XXX - this message is localized, but this only matches the English version. This is better than nothing.
1221 if(strstr(errormsg, "short read in buffer_copy (")) {
1222 std::clog << _("No apport report written because the error message indicates a dpkg I/O error") << std::endl;
1223 return;
1224 }
1225
5e457a93
MV
1226 // get the pkgname and reportfile
1227 pkgname = flNotDir(pkgpath);
25ffa4e8 1228 pos = pkgname.find('_');
5e457a93 1229 if(pos != string::npos)
25ffa4e8 1230 pkgname = pkgname.substr(0, pos);
5e457a93
MV
1231
1232 // find the package versin and source package name
1233 pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
1234 if (Pkg.end() == true)
1235 return;
1236 pkgCache::VerIterator Ver = Cache.GetCandidateVer(Pkg);
5e457a93
MV
1237 if (Ver.end() == true)
1238 return;
986d97bb 1239 pkgver = Ver.VerStr() == NULL ? "unknown" : Ver.VerStr();
5e457a93
MV
1240 pkgRecords Recs(Cache);
1241 pkgRecords::Parser &Parse = Recs.Lookup(Ver.FileList());
1242 srcpkgname = Parse.SourcePkg();
1243 if(srcpkgname.empty())
1244 srcpkgname = pkgname;
1245
1246 // if the file exists already, we check:
1247 // - if it was reported already (touched by apport).
1248 // If not, we do nothing, otherwise
1249 // we overwrite it. This is the same behaviour as apport
1250 // - if we have a report with the same pkgversion already
1251 // then we skip it
1252 reportfile = flCombine("/var/crash",pkgname+".0.crash");
1253 if(FileExists(reportfile))
1254 {
1255 struct stat buf;
1256 char strbuf[255];
1257
1258 // check atime/mtime
1259 stat(reportfile.c_str(), &buf);
1260 if(buf.st_mtime > buf.st_atime)
1261 return;
1262
1263 // check if the existing report is the same version
1264 report = fopen(reportfile.c_str(),"r");
1265 while(fgets(strbuf, sizeof(strbuf), report) != NULL)
1266 {
1267 if(strstr(strbuf,"Package:") == strbuf)
1268 {
1269 char pkgname[255], version[255];
1270 if(sscanf(strbuf, "Package: %s %s", pkgname, version) == 2)
1271 if(strcmp(pkgver.c_str(), version) == 0)
1272 {
1273 fclose(report);
1274 return;
1275 }
1276 }
1277 }
1278 fclose(report);
1279 }
1280
1281 // now write the report
1282 arch = _config->Find("APT::Architecture");
1283 report = fopen(reportfile.c_str(),"w");
1284 if(report == NULL)
1285 return;
1286 if(_config->FindB("DPkgPM::InitialReportOnly",false) == true)
1287 chmod(reportfile.c_str(), 0);
1288 else
1289 chmod(reportfile.c_str(), 0600);
1290 fprintf(report, "ProblemType: Package\n");
1291 fprintf(report, "Architecture: %s\n", arch.c_str());
1292 time_t now = time(NULL);
1293 fprintf(report, "Date: %s" , ctime(&now));
1294 fprintf(report, "Package: %s %s\n", pkgname.c_str(), pkgver.c_str());
1295 fprintf(report, "SourcePackage: %s\n", srcpkgname.c_str());
1296 fprintf(report, "ErrorMessage:\n %s\n", errormsg);
8ecd1fed
MV
1297
1298 // ensure that the log is flushed
1299 if(term_out)
1300 fflush(term_out);
1301
1302 // attach terminal log it if we have it
1303 string logfile_name = _config->FindFile("Dir::Log::Terminal");
1304 if (!logfile_name.empty())
1305 {
1306 FILE *log = NULL;
1307 char buf[1024];
1308
1309 fprintf(report, "DpkgTerminalLog:\n");
1310 log = fopen(logfile_name.c_str(),"r");
1311 if(log != NULL)
1312 {
1313 while( fgets(buf, sizeof(buf), log) != NULL)
1314 fprintf(report, " %s", buf);
1315 fclose(log);
1316 }
1317 }
76dbdfc7 1318
5c8a2aa8
MV
1319 // log the ordering
1320 const char *ops_str[] = {"Install", "Configure","Remove","Purge"};
1321 fprintf(report, "AptOrdering:\n");
1322 for (vector<Item>::iterator I = List.begin(); I != List.end(); I++)
1323 fprintf(report, " %s: %s\n", (*I).Pkg.Name(), ops_str[(*I).Op]);
1324
76dbdfc7
MV
1325 // attach dmesg log (to learn about segfaults)
1326 if (FileExists("/bin/dmesg"))
1327 {
1328 FILE *log = NULL;
1329 char buf[1024];
1330
1331 fprintf(report, "Dmesg:\n");
1332 log = popen("/bin/dmesg","r");
1333 if(log != NULL)
1334 {
1335 while( fgets(buf, sizeof(buf), log) != NULL)
1336 fprintf(report, " %s", buf);
1337 fclose(log);
1338 }
1339 }
2183a086
MV
1340
1341 // attach df -l log (to learn about filesystem status)
1342 if (FileExists("/bin/df"))
1343 {
1344 FILE *log = NULL;
1345 char buf[1024];
1346
1347 fprintf(report, "Df:\n");
1348 log = popen("/bin/df -l","r");
1349 if(log != NULL)
1350 {
1351 while( fgets(buf, sizeof(buf), log) != NULL)
1352 fprintf(report, " %s", buf);
1353 fclose(log);
1354 }
1355 }
1356
5e457a93 1357 fclose(report);
76dbdfc7 1358
5e457a93
MV
1359}
1360 /*}}}*/