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