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