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