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