]> git.saurik.com Git - apt.git/blame - apt-pkg/deb/dpkgpm.cc
merged from lp:~mvo/apt/mvo
[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{
578 string logdir = _config->FindDir("Dir::Log");
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];
584 time_t t = time(NULL);
585 struct tm *tmp = localtime(&t);
586 strftime(timestr, sizeof(timestr), "%F %T", tmp);
587
588 // open terminal log
5d053270
MV
589 string logfile_name = flCombine(logdir,
590 _config->Find("Dir::Log::Terminal"));
591 if (!logfile_name.empty())
592 {
593 term_out = fopen(logfile_name.c_str(),"a");
594 chmod(logfile_name.c_str(), 0600);
9169c871
MV
595 fprintf(term_out, "\n\nLog started: ");
596 fprintf(term_out, "%s", timestr);
5d053270
MV
597 fprintf(term_out, "\n");
598 }
9169c871
MV
599
600 // write
601 string history_name = flCombine(logdir,
602 _config->Find("Dir::Log::History"));
603 if (!history_name.empty())
604 {
a29b2c0b 605 FILE *history_out = fopen(history_name.c_str(),"a");
9169c871
MV
606 chmod(history_name.c_str(), 0644);
607 fprintf(history_out, "\nStart-Date: %s\n", timestr);
608 string remove, purge, install, upgrade, downgrade;
609 for (pkgCache::PkgIterator I = Cache.PkgBegin(); I.end() == false; I++)
610 {
d7a4ffd6
MV
611 if (Cache[I].NewInstall())
612 install += I.Name() + string(" (") + Cache[I].CandVersion + string("), ");
613 else if (Cache[I].Upgrade())
614 upgrade += I.Name() + string(" (") + Cache[I].CurVersion + string(", ") + Cache[I].CandVersion + string("), ");
9c59aada 615 else if (Cache[I].Downgrade())
d7a4ffd6 616 downgrade += I.Name() + string(" (") + Cache[I].CurVersion + string(", ") + Cache[I].CandVersion + string("), ");
9169c871
MV
617 else if (Cache[I].Delete())
618 {
619 if ((Cache[I].iFlags & pkgDepCache::Purge) == pkgDepCache::Purge)
d7a4ffd6 620 purge += I.Name() + string(" (") + Cache[I].CurVersion + string("), ");
9169c871 621 else
d7a4ffd6 622 remove += I.Name() + string(" (") + Cache[I].CurVersion + string("), ");
9169c871 623 }
9169c871 624 }
a29b2c0b
MV
625 WriteHistoryTag(history_out, "Install", install);
626 WriteHistoryTag(history_out, "Upgrade", upgrade);
627 WriteHistoryTag(history_out, "Downgrade",downgrade);
628 WriteHistoryTag(history_out, "Remove",remove);
629 WriteHistoryTag(history_out, "Purge",purge);
630 fclose(history_out);
9169c871
MV
631 }
632
5d053270
MV
633 return true;
634}
887f5036
DK
635 /*}}}*/
636// DPkg::CloseLog /*{{{*/
5d053270
MV
637bool pkgDPkgPM::CloseLog()
638{
9169c871
MV
639 char timestr[200];
640 time_t t = time(NULL);
641 struct tm *tmp = localtime(&t);
642 strftime(timestr, sizeof(timestr), "%F %T", tmp);
643
5d053270
MV
644 if(term_out)
645 {
5d053270 646 fprintf(term_out, "Log ended: ");
9169c871 647 fprintf(term_out, "%s", timestr);
5d053270
MV
648 fprintf(term_out, "\n");
649 fclose(term_out);
650 }
651 term_out = NULL;
9169c871 652
a29b2c0b
MV
653 string history_name = flCombine(_config->FindDir("Dir::Log"),
654 _config->Find("Dir::Log::History"));
655 if (!history_name.empty())
9169c871 656 {
a29b2c0b 657 FILE *history_out = fopen(history_name.c_str(),"a");
9169c871
MV
658 fprintf(history_out, "End-Date: %s\n", timestr);
659 fclose(history_out);
660 }
661
5d053270
MV
662 return true;
663}
887f5036 664 /*}}}*/
919e5852
OS
665/*{{{*/
666// This implements a racy version of pselect for those architectures
667// that don't have a working implementation.
668// FIXME: Probably can be removed on Lenny+1
669static int racy_pselect(int nfds, fd_set *readfds, fd_set *writefds,
670 fd_set *exceptfds, const struct timespec *timeout,
671 const sigset_t *sigmask)
672{
673 sigset_t origmask;
674 struct timeval tv;
675 int retval;
676
f6b37f38
OS
677 tv.tv_sec = timeout->tv_sec;
678 tv.tv_usec = timeout->tv_nsec/1000;
919e5852 679
f6b37f38 680 sigprocmask(SIG_SETMASK, sigmask, &origmask);
919e5852
OS
681 retval = select(nfds, readfds, writefds, exceptfds, &tv);
682 sigprocmask(SIG_SETMASK, &origmask, 0);
683 return retval;
684}
685/*}}}*/
03e39e59
AL
686// DPkgPM::Go - Run the sequence /*{{{*/
687// ---------------------------------------------------------------------
75ef8f14
MV
688/* This globs the operations and calls dpkg
689 *
690 * If it is called with "OutStatusFd" set to a valid file descriptor
691 * apt will report the install progress over this fd. It maps the
692 * dpkg states a package goes through to human readable (and i10n-able)
693 * names and calculates a percentage for each step.
694*/
695bool pkgDPkgPM::Go(int OutStatusFd)
03e39e59 696{
07dd557b
MV
697 fd_set rfds;
698 struct timespec tv;
699 sigset_t sigmask;
700 sigset_t original_sigmask;
701
887f5036
DK
702 unsigned int const MaxArgs = _config->FindI("Dpkg::MaxArgs",8*1024);
703 unsigned int const MaxArgBytes = _config->FindI("Dpkg::MaxArgBytes",32*1024);
5e312de7 704 bool const NoTriggers = _config->FindB("DPkg::NoTriggers", false);
aff4e2f1 705
6dd55be7
AL
706 if (RunScripts("DPkg::Pre-Invoke") == false)
707 return false;
db0c350f
AL
708
709 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
710 return false;
fc2d32c0 711
3e9c4f70
DK
712 // support subpressing of triggers processing for special
713 // cases like d-i that runs the triggers handling manually
5e312de7 714 bool const SmartConf = (_config->Find("PackageManager::Configure", "all") != "all");
5c23dbcc 715 bool const TriggersPending = _config->FindB("DPkg::TriggersPending", false);
5e312de7
DK
716 if (_config->FindB("DPkg::ConfigurePending", SmartConf) == true)
717 List.push_back(Item(Item::ConfigurePending, PkgIterator()));
3e9c4f70 718
75ef8f14
MV
719 // map the dpkg states to the operations that are performed
720 // (this is sorted in the same way as Item::Ops)
fb7bf91c 721 static const struct DpkgState DpkgStatesOpMap[][7] = {
75ef8f14
MV
722 // Install operation
723 {
1d52ce01
MV
724 {"half-installed", N_("Preparing %s")},
725 {"unpacked", N_("Unpacking %s") },
75ef8f14
MV
726 {NULL, NULL}
727 },
728 // Configure operation
729 {
1d52ce01
MV
730 {"unpacked",N_("Preparing to configure %s") },
731 {"half-configured", N_("Configuring %s") },
732 { "installed", N_("Installed %s")},
75ef8f14
MV
733 {NULL, NULL}
734 },
735 // Remove operation
736 {
1d52ce01
MV
737 {"half-configured", N_("Preparing for removal of %s")},
738 {"half-installed", N_("Removing %s")},
739 {"config-files", N_("Removed %s")},
75ef8f14
MV
740 {NULL, NULL}
741 },
742 // Purge operation
743 {
1d52ce01
MV
744 {"config-files", N_("Preparing to completely remove %s")},
745 {"not-installed", N_("Completely removed %s")},
75ef8f14
MV
746 {NULL, NULL}
747 },
748 };
db0c350f 749
75ef8f14
MV
750 // init the PackageOps map, go over the list of packages that
751 // that will be [installed|configured|removed|purged] and add
752 // them to the PackageOps map (the dpkg states it goes through)
753 // and the PackageOpsTranslations (human readable strings)
887f5036 754 for (vector<Item>::const_iterator I = List.begin(); I != List.end();I++)
75ef8f14 755 {
3e9c4f70
DK
756 if((*I).Pkg.end() == true)
757 continue;
758
887f5036 759 string const name = (*I).Pkg.Name();
75ef8f14
MV
760 PackageOpsDone[name] = 0;
761 for(int i=0; (DpkgStatesOpMap[(*I).Op][i]).state != NULL; i++)
762 {
763 PackageOps[name].push_back(DpkgStatesOpMap[(*I).Op][i]);
ff56e980 764 PackagesTotal++;
75ef8f14 765 }
887f5036 766 }
75ef8f14 767
9983591d
OS
768 stdin_is_dev_null = false;
769
ff56e980 770 // create log
5d053270 771 OpenLog();
ff56e980 772
75ef8f14 773 // this loop is runs once per operation
887f5036 774 for (vector<Item>::const_iterator I = List.begin(); I != List.end();)
03e39e59 775 {
5c23dbcc 776 // Do all actions with the same Op in one run
887f5036 777 vector<Item>::const_iterator J = I;
5c23dbcc
DK
778 if (TriggersPending == true)
779 for (; J != List.end(); J++)
780 {
781 if (J->Op == I->Op)
782 continue;
783 if (J->Op != Item::TriggersPending)
784 break;
785 vector<Item>::const_iterator T = J + 1;
786 if (T != List.end() && T->Op == I->Op)
787 continue;
788 break;
789 }
790 else
791 for (; J != List.end() && J->Op == I->Op; J++)
792 /* nothing */;
30e1eab5 793
03e39e59 794 // Generate the argument list
aff4e2f1 795 const char *Args[MaxArgs + 50];
599d6ad5
MV
796
797 // Now check if we are within the MaxArgs limit
798 //
799 // this code below is problematic, because it may happen that
800 // the argument list is split in a way that A depends on B
801 // and they are in the same "--configure A B" run
802 // - with the split they may now be configured in different
803 // runs
aff4e2f1
AL
804 if (J - I > (signed)MaxArgs)
805 J = I + MaxArgs;
03e39e59 806
30e1eab5
AL
807 unsigned int n = 0;
808 unsigned long Size = 0;
887f5036 809 string const Tmp = _config->Find("Dir::Bin::dpkg","dpkg");
50914ffa 810 Args[n++] = Tmp.c_str();
30e1eab5 811 Size += strlen(Args[n-1]);
03e39e59 812
6dd55be7
AL
813 // Stick in any custom dpkg options
814 Configuration::Item const *Opts = _config->Tree("DPkg::Options");
815 if (Opts != 0)
816 {
817 Opts = Opts->Child;
818 for (; Opts != 0; Opts = Opts->Next)
819 {
820 if (Opts->Value.empty() == true)
821 continue;
822 Args[n++] = Opts->Value.c_str();
823 Size += Opts->Value.length();
824 }
825 }
826
007dc9e0 827 char status_fd_buf[20];
75ef8f14
MV
828 int fd[2];
829 pipe(fd);
830
831 Args[n++] = "--status-fd";
832 Size += strlen(Args[n-1]);
833 snprintf(status_fd_buf,sizeof(status_fd_buf),"%i", fd[1]);
834 Args[n++] = status_fd_buf;
835 Size += strlen(Args[n-1]);
007dc9e0 836
03e39e59
AL
837 switch (I->Op)
838 {
839 case Item::Remove:
840 Args[n++] = "--force-depends";
30e1eab5 841 Size += strlen(Args[n-1]);
03e39e59 842 Args[n++] = "--force-remove-essential";
30e1eab5 843 Size += strlen(Args[n-1]);
03e39e59 844 Args[n++] = "--remove";
30e1eab5 845 Size += strlen(Args[n-1]);
03e39e59
AL
846 break;
847
fc4b5c9f
AL
848 case Item::Purge:
849 Args[n++] = "--force-depends";
850 Size += strlen(Args[n-1]);
851 Args[n++] = "--force-remove-essential";
852 Size += strlen(Args[n-1]);
853 Args[n++] = "--purge";
854 Size += strlen(Args[n-1]);
855 break;
856
03e39e59
AL
857 case Item::Configure:
858 Args[n++] = "--configure";
30e1eab5 859 Size += strlen(Args[n-1]);
03e39e59 860 break;
3e9c4f70
DK
861
862 case Item::ConfigurePending:
863 Args[n++] = "--configure";
864 Size += strlen(Args[n-1]);
865 Args[n++] = "--pending";
866 Size += strlen(Args[n-1]);
867 break;
868
5e312de7
DK
869 case Item::TriggersPending:
870 Args[n++] = "--triggers-only";
871 Size += strlen(Args[n-1]);
872 Args[n++] = "--pending";
873 Size += strlen(Args[n-1]);
874 break;
875
03e39e59
AL
876 case Item::Install:
877 Args[n++] = "--unpack";
30e1eab5 878 Size += strlen(Args[n-1]);
857a1d4a
MV
879 Args[n++] = "--auto-deconfigure";
880 Size += strlen(Args[n-1]);
03e39e59
AL
881 break;
882 }
3e9c4f70 883
5e312de7 884 if (NoTriggers == true && I->Op != Item::TriggersPending &&
d5081aee 885 I->Op != Item::ConfigurePending)
3e9c4f70
DK
886 {
887 Args[n++] = "--no-triggers";
888 Size += strlen(Args[n-1]);
889 }
890
03e39e59
AL
891 // Write in the file or package names
892 if (I->Op == Item::Install)
30e1eab5 893 {
aff4e2f1 894 for (;I != J && Size < MaxArgBytes; I++)
30e1eab5 895 {
cf544e14
AL
896 if (I->File[0] != '/')
897 return _error->Error("Internal Error, Pathname to install is not absolute '%s'",I->File.c_str());
03e39e59 898 Args[n++] = I->File.c_str();
30e1eab5
AL
899 Size += strlen(Args[n-1]);
900 }
901 }
03e39e59 902 else
30e1eab5 903 {
aff4e2f1 904 for (;I != J && Size < MaxArgBytes; I++)
30e1eab5 905 {
3e9c4f70
DK
906 if((*I).Pkg.end() == true)
907 continue;
03e39e59 908 Args[n++] = I->Pkg.Name();
30e1eab5
AL
909 Size += strlen(Args[n-1]);
910 }
911 }
03e39e59 912 Args[n] = 0;
30e1eab5
AL
913 J = I;
914
915 if (_config->FindB("Debug::pkgDPkgPM",false) == true)
916 {
917 for (unsigned int k = 0; k != n; k++)
918 clog << Args[k] << ' ';
919 clog << endl;
920 continue;
921 }
03e39e59 922
03e39e59
AL
923 cout << flush;
924 clog << flush;
925 cerr << flush;
926
927 /* Mask off sig int/quit. We do this because dpkg also does when
928 it forks scripts. What happens is that when you hit ctrl-c it sends
929 it to all processes in the group. Since dpkg ignores the signal
930 it doesn't die but we do! So we must also ignore it */
7f9a6360
AL
931 sighandler_t old_SIGQUIT = signal(SIGQUIT,SIG_IGN);
932 sighandler_t old_SIGINT = signal(SIGINT,SIG_IGN);
d8cb4aa4 933
6e7f872d
MV
934 // ignore SIGHUP as well (debian #463030)
935 sighandler_t old_SIGHUP = signal(SIGHUP,SIG_IGN);
936
d8cb4aa4
MV
937 struct termios tt;
938 struct winsize win;
4e550036
MV
939 int master = -1;
940 int slave = -1;
d8cb4aa4 941
4e550036
MV
942 // if tcgetattr does not return zero there was a error
943 // and we do not do any pty magic
944 if (tcgetattr(0, &tt) == 0)
090c6566 945 {
4e550036
MV
946 ioctl(0, TIOCGWINSZ, (char *)&win);
947 if (openpty(&master, &slave, NULL, &tt, &win) < 0)
948 {
949 const char *s = _("Can not write log, openpty() "
950 "failed (/dev/pts not mounted?)\n");
951 fprintf(stderr, "%s",s);
6847d275
MV
952 if(term_out)
953 fprintf(term_out, "%s",s);
4e550036
MV
954 master = slave = -1;
955 } else {
956 struct termios rtt;
957 rtt = tt;
958 cfmakeraw(&rtt);
959 rtt.c_lflag &= ~ECHO;
960 // block SIGTTOU during tcsetattr to prevent a hang if
961 // the process is a member of the background process group
962 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
963 sigemptyset(&sigmask);
964 sigaddset(&sigmask, SIGTTOU);
965 sigprocmask(SIG_BLOCK,&sigmask, &original_sigmask);
966 tcsetattr(0, TCSAFLUSH, &rtt);
967 sigprocmask(SIG_SETMASK, &original_sigmask, 0);
968 }
d8cb4aa4
MV
969 }
970
75ef8f14 971 // Fork dpkg
007dc9e0 972 pid_t Child;
75ef8f14 973 _config->Set("APT::Keep-Fds::",fd[1]);
ccd8e28f
MV
974 // send status information that we are about to fork dpkg
975 if(OutStatusFd > 0) {
976 ostringstream status;
977 status << "pmstatus:dpkg-exec:"
978 << (PackagesDone/float(PackagesTotal)*100.0)
979 << ":" << _("Running dpkg")
980 << endl;
981 write(OutStatusFd, status.str().c_str(), status.str().size());
982 }
75ef8f14 983 Child = ExecFork();
6dd55be7 984
03e39e59
AL
985 // This is the child
986 if (Child == 0)
987 {
a4cf3665
MV
988 if(slave >= 0 && master >= 0)
989 {
990 setsid();
991 ioctl(slave, TIOCSCTTY, 0);
992 close(master);
993 dup2(slave, 0);
994 dup2(slave, 1);
995 dup2(slave, 2);
996 close(slave);
997 }
75ef8f14 998 close(fd[0]); // close the read end of the pipe
d8cb4aa4 999
4b7cfe96
MV
1000 if (_config->FindDir("DPkg::Chroot-Directory","/") != "/")
1001 {
1002 std::cerr << "Chrooting into "
1003 << _config->FindDir("DPkg::Chroot-Directory")
1004 << std::endl;
1005 if (chroot(_config->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
1006 _exit(100);
1007 }
1008
cf544e14 1009 if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
0dbb95d8 1010 _exit(100);
03e39e59 1011
421ff807 1012 if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
8b5fe26c
AL
1013 {
1014 int Flags,dummy;
1015 if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
1016 _exit(100);
1017
1018 // Discard everything in stdin before forking dpkg
1019 if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
1020 _exit(100);
1021
1022 while (read(STDIN_FILENO,&dummy,1) == 1);
1023
1024 if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
1025 _exit(100);
1026 }
d8cb4aa4 1027
03e39e59
AL
1028 /* No Job Control Stop Env is a magic dpkg var that prevents it
1029 from using sigstop */
71afbdb5 1030 putenv((char *)"DPKG_NO_TSTP=yes");
d568ed2d 1031 execvp(Args[0],(char **)Args);
03e39e59 1032 cerr << "Could not exec dpkg!" << endl;
0dbb95d8 1033 _exit(100);
03e39e59
AL
1034 }
1035
cebe0287
MV
1036 // apply ionice
1037 if (_config->FindB("DPkg::UseIoNice", false) == true)
1038 ionice(Child);
1039
75ef8f14
MV
1040 // clear the Keep-Fd again
1041 _config->Clear("APT::Keep-Fds",fd[1]);
1042
03e39e59
AL
1043 // Wait for dpkg
1044 int Status = 0;
75ef8f14
MV
1045
1046 // we read from dpkg here
887f5036 1047 int const _dpkgin = fd[0];
75ef8f14
MV
1048 close(fd[1]); // close the write end of the pipe
1049
a4cf3665
MV
1050 if(slave > 0)
1051 close(slave);
75ef8f14 1052
97efd303 1053 // setups fds
1fc825bf
MV
1054 sigemptyset(&sigmask);
1055 sigprocmask(SIG_BLOCK,&sigmask,&original_sigmask);
1056
887f5036
DK
1057 // the result of the waitpid call
1058 int res;
090c6566 1059 int select_ret;
75ef8f14
MV
1060 while ((res=waitpid(Child,&Status, WNOHANG)) != Child) {
1061 if(res < 0) {
1062 // FIXME: move this to a function or something, looks ugly here
1063 // error handling, waitpid returned -1
1064 if (errno == EINTR)
1065 continue;
1066 RunScripts("DPkg::Post-Invoke");
1067
1068 // Restore sig int/quit
1069 signal(SIGQUIT,old_SIGQUIT);
1070 signal(SIGINT,old_SIGINT);
1a853738 1071 signal(SIGHUP,old_SIGHUP);
75ef8f14
MV
1072 return _error->Errno("waitpid","Couldn't wait for subprocess");
1073 }
d8cb4aa4 1074 // wait for input or output here
955a6ddb 1075 FD_ZERO(&rfds);
9983591d
OS
1076 if (!stdin_is_dev_null)
1077 FD_SET(0, &rfds);
955a6ddb 1078 FD_SET(_dpkgin, &rfds);
a4cf3665
MV
1079 if(master >= 0)
1080 FD_SET(master, &rfds);
090c6566 1081 tv.tv_sec = 1;
1fc825bf
MV
1082 tv.tv_nsec = 0;
1083 select_ret = pselect(max(master, _dpkgin)+1, &rfds, NULL, NULL,
1084 &tv, &original_sigmask);
919e5852
OS
1085 if (select_ret < 0 && (errno == EINVAL || errno == ENOSYS))
1086 select_ret = racy_pselect(max(master, _dpkgin)+1, &rfds, NULL,
1087 NULL, &tv, &original_sigmask);
da50ba30 1088 if (select_ret == 0)
5d053270
MV
1089 continue;
1090 else if (select_ret < 0 && errno == EINTR)
1091 continue;
1092 else if (select_ret < 0)
1093 {
1094 perror("select() returned error");
1095 continue;
1096 }
da50ba30 1097
a4cf3665 1098 if(master >= 0 && FD_ISSET(master, &rfds))
1ba38171 1099 DoTerminalPty(master);
a4cf3665 1100 if(master >= 0 && FD_ISSET(0, &rfds))
955a6ddb 1101 DoStdin(master);
955a6ddb 1102 if(FD_ISSET(_dpkgin, &rfds))
09fa2df2 1103 DoDpkgStatusFd(_dpkgin, OutStatusFd);
03e39e59 1104 }
75ef8f14 1105 close(_dpkgin);
03e39e59
AL
1106
1107 // Restore sig int/quit
7f9a6360
AL
1108 signal(SIGQUIT,old_SIGQUIT);
1109 signal(SIGINT,old_SIGINT);
4e648e0b 1110 signal(SIGHUP,old_SIGHUP);
d8cb4aa4 1111
c771f6d9
MV
1112 if(master >= 0)
1113 {
a4cf3665 1114 tcsetattr(0, TCSAFLUSH, &tt);
c771f6d9
MV
1115 close(master);
1116 }
6dd55be7
AL
1117
1118 // Check for an error code.
1119 if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
1120 {
c70496f9
MV
1121 // if it was set to "keep-dpkg-runing" then we won't return
1122 // here but keep the loop going and just report it as a error
1123 // for later
887f5036 1124 bool const stopOnError = _config->FindB("Dpkg::StopOnError",true);
f956efb4 1125
c70496f9
MV
1126 if(stopOnError)
1127 RunScripts("DPkg::Post-Invoke");
1128
a29b2c0b 1129 string dpkg_error;
c70496f9 1130 if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
9169c871 1131 strprintf(dpkg_error, "Sub-process %s received a segmentation fault.",Args[0]);
c70496f9 1132 else if (WIFEXITED(Status) != 0)
9169c871 1133 strprintf(dpkg_error, "Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
c70496f9 1134 else
9169c871
MV
1135 strprintf(dpkg_error, "Sub-process %s exited unexpectedly",Args[0]);
1136
1137 if(dpkg_error.size() > 0)
a29b2c0b 1138 {
9169c871 1139 _error->Error(dpkg_error.c_str());
a29b2c0b
MV
1140 string history_name = flCombine(_config->FindDir("Dir::Log"),
1141 _config->Find("Dir::Log::History"));
1142 if (!history_name.empty())
1143 {
1144 FILE *history_out = fopen(history_name.c_str(),"a");
1145 fprintf(history_out, "Error: %s\n", dpkg_error.c_str());
1146 fclose(history_out);
1147 }
1148 }
c70496f9 1149
ff56e980
MV
1150 if(stopOnError)
1151 {
5d053270 1152 CloseLog();
c70496f9 1153 return false;
ff56e980 1154 }
6dd55be7 1155 }
03e39e59 1156 }
5d053270 1157 CloseLog();
6dd55be7
AL
1158
1159 if (RunScripts("DPkg::Post-Invoke") == false)
1160 return false;
496d5c70
MV
1161
1162 Cache.writeStateFile(NULL);
03e39e59
AL
1163 return true;
1164}
1165 /*}}}*/
281daf46
AL
1166// pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1167// ---------------------------------------------------------------------
1168/* */
1169void pkgDPkgPM::Reset()
1170{
1171 List.erase(List.begin(),List.end());
1172}
1173 /*}}}*/
5e457a93
MV
1174// pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1175// ---------------------------------------------------------------------
1176/* */
1177void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
1178{
1179 string pkgname, reportfile, srcpkgname, pkgver, arch;
1180 string::size_type pos;
1181 FILE *report;
1182
1183 if (_config->FindB("Dpkg::ApportFailureReport",true) == false)
ff38d63b
MV
1184 {
1185 std::clog << "configured to not write apport reports" << std::endl;
5e457a93 1186 return;
ff38d63b 1187 }
5e457a93 1188
d6a4afcb 1189 // only report the first errors
5273f1bf 1190 if(pkgFailures > _config->FindI("APT::Apport::MaxReports", 3))
ff38d63b
MV
1191 {
1192 std::clog << _("No apport report written because MaxReports is reached already") << std::endl;
5e457a93 1193 return;
ff38d63b 1194 }
5e457a93 1195
d6a4afcb
MV
1196 // check if its not a follow up error
1197 const char *needle = dgettext("dpkg", "dependency problems - leaving unconfigured");
1198 if(strstr(errormsg, needle) != NULL) {
1199 std::clog << _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl;
1200 return;
1201 }
1202
2f0d5dea
MV
1203 // do not report disk-full failures
1204 if(strstr(errormsg, strerror(ENOSPC)) != NULL) {
1205 std::clog << _("No apport report written because the error message indicates a disk full error") << std::endl;
1206 return;
1207 }
1208
3024a85e
MV
1209 // do not report out-of-memory failures
1210 if(strstr(errormsg, strerror(ENOMEM)) != NULL) {
1211 std::clog << _("No apport report written because the error message indicates a out of memory error") << std::endl;
1212 return;
1213 }
1214
076c46e5
MZ
1215 // do not report dpkg I/O errors
1216 // XXX - this message is localized, but this only matches the English version. This is better than nothing.
1217 if(strstr(errormsg, "short read in buffer_copy (")) {
1218 std::clog << _("No apport report written because the error message indicates a dpkg I/O error") << std::endl;
1219 return;
1220 }
1221
5e457a93
MV
1222 // get the pkgname and reportfile
1223 pkgname = flNotDir(pkgpath);
25ffa4e8 1224 pos = pkgname.find('_');
5e457a93 1225 if(pos != string::npos)
25ffa4e8 1226 pkgname = pkgname.substr(0, pos);
5e457a93
MV
1227
1228 // find the package versin and source package name
1229 pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
1230 if (Pkg.end() == true)
1231 return;
1232 pkgCache::VerIterator Ver = Cache.GetCandidateVer(Pkg);
5e457a93
MV
1233 if (Ver.end() == true)
1234 return;
986d97bb 1235 pkgver = Ver.VerStr() == NULL ? "unknown" : Ver.VerStr();
5e457a93
MV
1236 pkgRecords Recs(Cache);
1237 pkgRecords::Parser &Parse = Recs.Lookup(Ver.FileList());
1238 srcpkgname = Parse.SourcePkg();
1239 if(srcpkgname.empty())
1240 srcpkgname = pkgname;
1241
1242 // if the file exists already, we check:
1243 // - if it was reported already (touched by apport).
1244 // If not, we do nothing, otherwise
1245 // we overwrite it. This is the same behaviour as apport
1246 // - if we have a report with the same pkgversion already
1247 // then we skip it
1248 reportfile = flCombine("/var/crash",pkgname+".0.crash");
1249 if(FileExists(reportfile))
1250 {
1251 struct stat buf;
1252 char strbuf[255];
1253
1254 // check atime/mtime
1255 stat(reportfile.c_str(), &buf);
1256 if(buf.st_mtime > buf.st_atime)
1257 return;
1258
1259 // check if the existing report is the same version
1260 report = fopen(reportfile.c_str(),"r");
1261 while(fgets(strbuf, sizeof(strbuf), report) != NULL)
1262 {
1263 if(strstr(strbuf,"Package:") == strbuf)
1264 {
1265 char pkgname[255], version[255];
1266 if(sscanf(strbuf, "Package: %s %s", pkgname, version) == 2)
1267 if(strcmp(pkgver.c_str(), version) == 0)
1268 {
1269 fclose(report);
1270 return;
1271 }
1272 }
1273 }
1274 fclose(report);
1275 }
1276
1277 // now write the report
1278 arch = _config->Find("APT::Architecture");
1279 report = fopen(reportfile.c_str(),"w");
1280 if(report == NULL)
1281 return;
1282 if(_config->FindB("DPkgPM::InitialReportOnly",false) == true)
1283 chmod(reportfile.c_str(), 0);
1284 else
1285 chmod(reportfile.c_str(), 0600);
1286 fprintf(report, "ProblemType: Package\n");
1287 fprintf(report, "Architecture: %s\n", arch.c_str());
1288 time_t now = time(NULL);
1289 fprintf(report, "Date: %s" , ctime(&now));
1290 fprintf(report, "Package: %s %s\n", pkgname.c_str(), pkgver.c_str());
1291 fprintf(report, "SourcePackage: %s\n", srcpkgname.c_str());
1292 fprintf(report, "ErrorMessage:\n %s\n", errormsg);
8ecd1fed
MV
1293
1294 // ensure that the log is flushed
1295 if(term_out)
1296 fflush(term_out);
1297
1298 // attach terminal log it if we have it
1299 string logfile_name = _config->FindFile("Dir::Log::Terminal");
1300 if (!logfile_name.empty())
1301 {
1302 FILE *log = NULL;
1303 char buf[1024];
1304
1305 fprintf(report, "DpkgTerminalLog:\n");
1306 log = fopen(logfile_name.c_str(),"r");
1307 if(log != NULL)
1308 {
1309 while( fgets(buf, sizeof(buf), log) != NULL)
1310 fprintf(report, " %s", buf);
1311 fclose(log);
1312 }
1313 }
76dbdfc7 1314
5c8a2aa8
MV
1315 // log the ordering
1316 const char *ops_str[] = {"Install", "Configure","Remove","Purge"};
1317 fprintf(report, "AptOrdering:\n");
1318 for (vector<Item>::iterator I = List.begin(); I != List.end(); I++)
1319 fprintf(report, " %s: %s\n", (*I).Pkg.Name(), ops_str[(*I).Op]);
1320
76dbdfc7
MV
1321 // attach dmesg log (to learn about segfaults)
1322 if (FileExists("/bin/dmesg"))
1323 {
1324 FILE *log = NULL;
1325 char buf[1024];
1326
1327 fprintf(report, "Dmesg:\n");
1328 log = popen("/bin/dmesg","r");
1329 if(log != NULL)
1330 {
1331 while( fgets(buf, sizeof(buf), log) != NULL)
1332 fprintf(report, " %s", buf);
1333 fclose(log);
1334 }
1335 }
2183a086
MV
1336
1337 // attach df -l log (to learn about filesystem status)
1338 if (FileExists("/bin/df"))
1339 {
1340 FILE *log = NULL;
1341 char buf[1024];
1342
1343 fprintf(report, "Df:\n");
1344 log = popen("/bin/df -l","r");
1345 if(log != NULL)
1346 {
1347 while( fgets(buf, sizeof(buf), log) != NULL)
1348 fprintf(report, " %s", buf);
1349 fclose(log);
1350 }
1351 }
1352
5e457a93 1353 fclose(report);
76dbdfc7 1354
5e457a93
MV
1355}
1356 /*}}}*/