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