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