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