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