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