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