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