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