]> 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>
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
394 // into a race
395 usleep(500000);
396 return;
397 }
398 if(len <= 0)
955a6ddb 399 return;
955a6ddb 400 write(1, term_buf, len);
8da1f029
MV
401 if(term_out)
402 fwrite(term_buf, len, sizeof(char), term_out);
ceabc520 403}
03e39e59 404 /*}}}*/
6191b008
MV
405// DPkgPM::ProcessDpkgStatusBuf /*{{{*/
406// ---------------------------------------------------------------------
407/*
408 */
09fa2df2 409void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd, char *line)
6191b008 410{
887f5036 411 bool const Debug = _config->FindB("Debug::pkgDPkgProgressReporting",false);
09fa2df2
MV
412 // the status we output
413 ostringstream status;
414
887f5036 415 if (Debug == true)
09fa2df2
MV
416 std::clog << "got from dpkg '" << line << "'" << std::endl;
417
418
419 /* dpkg sends strings like this:
420 'status: <pkg>: <pkg qstate>'
421 errors look like this:
422 '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
423 and conffile-prompt like this
424 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
fc2d32c0
MV
425
426 Newer versions of dpkg sent also:
427 'processing: install: pkg'
428 'processing: configure: pkg'
429 'processing: remove: pkg'
b3514c56
DK
430 'processing: purge: pkg'
431 'processing: disappear: pkg'
fc2d32c0 432 'processing: trigproc: trigger'
09fa2df2
MV
433
434 */
5279f566 435 char* list[6];
09fa2df2
MV
436 // dpkg sends multiline error messages sometimes (see
437 // #374195 for a example. we should support this by
438 // either patching dpkg to not send multiline over the
439 // statusfd or by rewriting the code here to deal with
440 // it. for now we just ignore it and not crash
441 TokSplitString(':', line, list, sizeof(list)/sizeof(list[0]));
f26fcbc7 442 if( list[0] == NULL || list[1] == NULL || list[2] == NULL)
09fa2df2 443 {
887f5036 444 if (Debug == true)
09fa2df2
MV
445 std::clog << "ignoring line: not enough ':'" << std::endl;
446 return;
447 }
887f5036
DK
448 const char* const pkg = list[1];
449 const char* action = _strstrip(list[2]);
09fa2df2 450
fc2d32c0
MV
451 // 'processing' from dpkg looks like
452 // 'processing: action: pkg'
453 if(strncmp(list[0], "processing", strlen("processing")) == 0)
454 {
455 char s[200];
887f5036
DK
456 const char* const pkg_or_trigger = _strstrip(list[2]);
457 action = _strstrip( list[1]);
f7dec19f
DB
458 const std::pair<const char *, const char *> * const iter =
459 std::find_if(PackageProcessingOpsBegin,
460 PackageProcessingOpsEnd,
461 MatchProcessingOp(action));
462 if(iter == PackageProcessingOpsEnd)
fc2d32c0 463 {
887f5036
DK
464 if (Debug == true)
465 std::clog << "ignoring unknown action: " << action << std::endl;
fc2d32c0
MV
466 return;
467 }
f7dec19f 468 snprintf(s, sizeof(s), _(iter->second), pkg_or_trigger);
fc2d32c0
MV
469
470 status << "pmstatus:" << pkg_or_trigger
471 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
472 << ":" << s
473 << endl;
474 if(OutStatusFd > 0)
475 write(OutStatusFd, status.str().c_str(), status.str().size());
887f5036 476 if (Debug == true)
fc2d32c0 477 std::clog << "send: '" << status.str() << "'" << endl;
642ebc1a
DK
478
479 if (strncmp(action, "disappear", strlen("disappear")) == 0)
eb6f9bac 480 handleDisappearAction(pkg_or_trigger);
fc2d32c0
MV
481 return;
482 }
483
09fa2df2
MV
484 if(strncmp(action,"error",strlen("error")) == 0)
485 {
d6a4afcb
MV
486 // urgs, sometime has ":" in its error string so that we
487 // end up with the error message split between list[3]
488 // and list[4], e.g. the message:
5279f566 489 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
d6a4afcb 490 // concat them again
5279f566
MV
491 if( list[4] != NULL )
492 list[3][strlen(list[3])] = ':';
d6a4afcb 493
09fa2df2 494 status << "pmerror:" << list[1]
ff56e980 495 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
09fa2df2
MV
496 << ":" << list[3]
497 << endl;
498 if(OutStatusFd > 0)
499 write(OutStatusFd, status.str().c_str(), status.str().size());
887f5036 500 if (Debug == true)
09fa2df2 501 std::clog << "send: '" << status.str() << "'" << endl;
f060e833
MV
502 pkgFailures++;
503 WriteApportReport(list[1], list[3]);
09fa2df2
MV
504 return;
505 }
887f5036 506 else if(strncmp(action,"conffile",strlen("conffile")) == 0)
09fa2df2
MV
507 {
508 status << "pmconffile:" << list[1]
ff56e980 509 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
09fa2df2
MV
510 << ":" << list[3]
511 << endl;
512 if(OutStatusFd > 0)
513 write(OutStatusFd, status.str().c_str(), status.str().size());
887f5036 514 if (Debug == true)
09fa2df2
MV
515 std::clog << "send: '" << status.str() << "'" << endl;
516 return;
517 }
518
887f5036 519 vector<struct DpkgState> const &states = PackageOps[pkg];
09fa2df2
MV
520 const char *next_action = NULL;
521 if(PackageOpsDone[pkg] < states.size())
522 next_action = states[PackageOpsDone[pkg]].state;
523 // check if the package moved to the next dpkg state
524 if(next_action && (strcmp(action, next_action) == 0))
525 {
526 // only read the translation if there is actually a next
527 // action
528 const char *translation = _(states[PackageOpsDone[pkg]].str);
529 char s[200];
530 snprintf(s, sizeof(s), translation, pkg);
531
532 // we moved from one dpkg state to a new one, report that
533 PackageOpsDone[pkg]++;
ff56e980 534 PackagesDone++;
09fa2df2
MV
535 // build the status str
536 status << "pmstatus:" << pkg
ff56e980 537 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
09fa2df2
MV
538 << ":" << s
539 << endl;
540 if(OutStatusFd > 0)
541 write(OutStatusFd, status.str().c_str(), status.str().size());
887f5036 542 if (Debug == true)
09fa2df2
MV
543 std::clog << "send: '" << status.str() << "'" << endl;
544 }
887f5036 545 if (Debug == true)
09fa2df2
MV
546 std::clog << "(parsed from dpkg) pkg: " << pkg
547 << " action: " << action << endl;
6191b008 548}
887f5036 549 /*}}}*/
eb6f9bac
DK
550// DPkgPM::handleDisappearAction /*{{{*/
551void pkgDPkgPM::handleDisappearAction(string const &pkgname)
552{
553 // record the package name for display and stuff later
554 disappearedPkgs.insert(pkgname);
555
556 pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
557 if (unlikely(Pkg.end() == true))
558 return;
559 // the disappeared package was auto-installed - nothing to do
560 if ((Cache[Pkg].Flags & pkgCache::Flag::Auto) == pkgCache::Flag::Auto)
561 return;
75954ae2 562 pkgCache::VerIterator PkgVer = Cache[Pkg].InstVerIter(Cache);
eb6f9bac
DK
563 if (unlikely(PkgVer.end() == true))
564 return;
565 /* search in the list of dependencies for (Pre)Depends,
566 check if this dependency has a Replaces on our package
567 and if so transfer the manual installed flag to it */
568 for (pkgCache::DepIterator Dep = PkgVer.DependsList(); Dep.end() != true; ++Dep)
569 {
570 if (Dep->Type != pkgCache::Dep::Depends &&
571 Dep->Type != pkgCache::Dep::PreDepends)
572 continue;
573 pkgCache::PkgIterator Tar = Dep.TargetPkg();
574 if (unlikely(Tar.end() == true))
575 continue;
576 // the package is already marked as manual
577 if ((Cache[Tar].Flags & pkgCache::Flag::Auto) != pkgCache::Flag::Auto)
578 continue;
75954ae2
DK
579 pkgCache::VerIterator TarVer = Cache[Tar].InstVerIter(Cache);
580 if (TarVer.end() == true)
581 continue;
eb6f9bac
DK
582 for (pkgCache::DepIterator Rep = TarVer.DependsList(); Rep.end() != true; ++Rep)
583 {
584 if (Rep->Type != pkgCache::Dep::Replaces)
585 continue;
586 if (Pkg != Rep.TargetPkg())
587 continue;
588 // okay, they are strongly connected - transfer manual-bit
589 if (Debug == true)
590 std::clog << "transfer manual-bit from disappeared »" << pkgname << "« to »" << Tar.FullName() << "«" << std::endl;
591 Cache[Tar].Flags &= ~Flag::Auto;
592 break;
593 }
594 }
595}
596 /*}}}*/
887f5036 597// DPkgPM::DoDpkgStatusFd /*{{{*/
6191b008
MV
598// ---------------------------------------------------------------------
599/*
600 */
09fa2df2 601void pkgDPkgPM::DoDpkgStatusFd(int statusfd, int OutStatusFd)
6191b008
MV
602{
603 char *p, *q;
604 int len;
605
606 len=read(statusfd, &dpkgbuf[dpkgbuf_pos], sizeof(dpkgbuf)-dpkgbuf_pos);
607 dpkgbuf_pos += len;
608 if(len <= 0)
609 return;
ceabc520 610
6191b008
MV
611 // process line by line if we have a buffer
612 p = q = dpkgbuf;
613 while((q=(char*)memchr(p, '\n', dpkgbuf+dpkgbuf_pos-p)) != NULL)
614 {
615 *q = 0;
09fa2df2 616 ProcessDpkgStatusLine(OutStatusFd, p);
6191b008
MV
617 p=q+1; // continue with next line
618 }
619
620 // now move the unprocessed bits (after the final \n that is now a 0x0)
621 // to the start and update dpkgbuf_pos
622 p = (char*)memrchr(dpkgbuf, 0, dpkgbuf_pos);
623 if(p == NULL)
624 return;
625
626 // we are interessted in the first char *after* 0x0
627 p++;
628
629 // move the unprocessed tail to the start and update pos
630 memmove(dpkgbuf, p, p-dpkgbuf);
631 dpkgbuf_pos = dpkgbuf+dpkgbuf_pos-p;
632}
633 /*}}}*/
d7a4ffd6 634// DPkgPM::WriteHistoryTag /*{{{*/
6cb1060b 635void pkgDPkgPM::WriteHistoryTag(string const &tag, string value)
d7a4ffd6 636{
6cb1060b
DK
637 size_t const length = value.length();
638 if (length == 0)
639 return;
640 // poor mans rstrip(", ")
641 if (value[length-2] == ',' && value[length-1] == ' ')
642 value.erase(length - 2, 2);
643 fprintf(history_out, "%s: %s\n", tag.c_str(), value.c_str());
d7a4ffd6 644} /*}}}*/
887f5036 645// DPkgPM::OpenLog /*{{{*/
2e1715ea
MV
646bool pkgDPkgPM::OpenLog()
647{
569cc934 648 string const logdir = _config->FindDir("Dir::Log");
7753e468 649 if(CreateAPTDirectoryIfNeeded(logdir, logdir) == false)
b29c3712 650 // FIXME: use a better string after freeze
2e1715ea 651 return _error->Error(_("Directory '%s' missing"), logdir.c_str());
9169c871
MV
652
653 // get current time
654 char timestr[200];
569cc934
DK
655 time_t const t = time(NULL);
656 struct tm const * const tmp = localtime(&t);
9169c871
MV
657 strftime(timestr, sizeof(timestr), "%F %T", tmp);
658
659 // open terminal log
569cc934 660 string const logfile_name = flCombine(logdir,
2e1715ea
MV
661 _config->Find("Dir::Log::Terminal"));
662 if (!logfile_name.empty())
663 {
664 term_out = fopen(logfile_name.c_str(),"a");
b39c1859 665 if (term_out == NULL)
569cc934 666 return _error->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name.c_str());
24baab5c 667 setvbuf(term_out, NULL, _IONBF, 0);
fd8bb61d 668 SetCloseExec(fileno(term_out), true);
2e1715ea 669 chmod(logfile_name.c_str(), 0600);
762d7367 670 fprintf(term_out, "\nLog started: %s\n", timestr);
2e1715ea 671 }
9169c871 672
569cc934
DK
673 // write your history
674 string const history_name = flCombine(logdir,
9169c871
MV
675 _config->Find("Dir::Log::History"));
676 if (!history_name.empty())
677 {
678 history_out = fopen(history_name.c_str(),"a");
569cc934
DK
679 if (history_out == NULL)
680 return _error->WarningE("OpenLog", _("Could not open file '%s'"), history_name.c_str());
9169c871
MV
681 chmod(history_name.c_str(), 0644);
682 fprintf(history_out, "\nStart-Date: %s\n", timestr);
683 string remove, purge, install, upgrade, downgrade;
684 for (pkgCache::PkgIterator I = Cache.PkgBegin(); I.end() == false; I++)
685 {
d7a4ffd6 686 if (Cache[I].NewInstall())
6bf8f0d1
JAK
687 {
688 install += I.FullName(false) + string(" (") + Cache[I].CandVersion;
689 if (Cache[I].Flags & pkgCache::Flag::Auto)
690 install+= ", automatic";
691 install += string("), ");
692 }
d7a4ffd6 693 else if (Cache[I].Upgrade())
621e918e 694 upgrade += I.FullName(false) + string(" (") + Cache[I].CurVersion + string(", ") + Cache[I].CandVersion + string("), ");
9c59aada 695 else if (Cache[I].Downgrade())
621e918e 696 downgrade += I.FullName(false) + string(" (") + Cache[I].CurVersion + string(", ") + Cache[I].CandVersion + string("), ");
9169c871
MV
697 else if (Cache[I].Delete())
698 {
699 if ((Cache[I].iFlags & pkgDepCache::Purge) == pkgDepCache::Purge)
621e918e 700 purge += I.FullName(false) + string(" (") + Cache[I].CurVersion + string("), ");
9169c871 701 else
621e918e 702 remove += I.FullName(false) + string(" (") + Cache[I].CurVersion + string("), ");
9169c871 703 }
9169c871 704 }
2bb25574
DK
705 if (_config->Exists("Commandline::AsString") == true)
706 WriteHistoryTag("Commandline", _config->Find("Commandline::AsString"));
d7a4ffd6
MV
707 WriteHistoryTag("Install", install);
708 WriteHistoryTag("Upgrade", upgrade);
709 WriteHistoryTag("Downgrade",downgrade);
710 WriteHistoryTag("Remove",remove);
711 WriteHistoryTag("Purge",purge);
06d5520f 712 fflush(history_out);
9169c871
MV
713 }
714
2e1715ea
MV
715 return true;
716}
887f5036
DK
717 /*}}}*/
718// DPkg::CloseLog /*{{{*/
2e1715ea
MV
719bool pkgDPkgPM::CloseLog()
720{
9169c871
MV
721 char timestr[200];
722 time_t t = time(NULL);
723 struct tm *tmp = localtime(&t);
724 strftime(timestr, sizeof(timestr), "%F %T", tmp);
725
2e1715ea
MV
726 if(term_out)
727 {
8398ac36 728 fprintf(term_out, "Log ended: ");
9169c871 729 fprintf(term_out, "%s", timestr);
2e1715ea
MV
730 fprintf(term_out, "\n");
731 fclose(term_out);
732 }
733 term_out = NULL;
9169c871
MV
734
735 if(history_out)
736 {
6cb1060b
DK
737 if (disappearedPkgs.empty() == false)
738 {
739 string disappear;
740 for (std::set<std::string>::const_iterator d = disappearedPkgs.begin();
741 d != disappearedPkgs.end(); ++d)
742 {
743 pkgCache::PkgIterator P = Cache.FindPkg(*d);
744 disappear.append(*d);
745 if (P.end() == true)
746 disappear.append(", ");
747 else
748 disappear.append(" (").append(Cache[P].CurVersion).append("), ");
749 }
750 WriteHistoryTag("Disappeared", disappear);
751 }
752 if (dpkg_error.empty() == false)
9169c871
MV
753 fprintf(history_out, "Error: %s\n", dpkg_error.c_str());
754 fprintf(history_out, "End-Date: %s\n", timestr);
755 fclose(history_out);
756 }
5e8b2b74 757 history_out = NULL;
9169c871 758
2e1715ea
MV
759 return true;
760}
887f5036 761 /*}}}*/
919e5852
OS
762/*{{{*/
763// This implements a racy version of pselect for those architectures
764// that don't have a working implementation.
765// FIXME: Probably can be removed on Lenny+1
766static int racy_pselect(int nfds, fd_set *readfds, fd_set *writefds,
767 fd_set *exceptfds, const struct timespec *timeout,
768 const sigset_t *sigmask)
769{
770 sigset_t origmask;
771 struct timeval tv;
772 int retval;
773
f6b37f38
OS
774 tv.tv_sec = timeout->tv_sec;
775 tv.tv_usec = timeout->tv_nsec/1000;
919e5852 776
f6b37f38 777 sigprocmask(SIG_SETMASK, sigmask, &origmask);
919e5852
OS
778 retval = select(nfds, readfds, writefds, exceptfds, &tv);
779 sigprocmask(SIG_SETMASK, &origmask, 0);
780 return retval;
781}
782/*}}}*/
03e39e59
AL
783// DPkgPM::Go - Run the sequence /*{{{*/
784// ---------------------------------------------------------------------
75ef8f14
MV
785/* This globs the operations and calls dpkg
786 *
787 * If it is called with "OutStatusFd" set to a valid file descriptor
788 * apt will report the install progress over this fd. It maps the
789 * dpkg states a package goes through to human readable (and i10n-able)
790 * names and calculates a percentage for each step.
791*/
792bool pkgDPkgPM::Go(int OutStatusFd)
03e39e59 793{
17745b02
MV
794 fd_set rfds;
795 struct timespec tv;
796 sigset_t sigmask;
797 sigset_t original_sigmask;
798
887f5036
DK
799 unsigned int const MaxArgs = _config->FindI("Dpkg::MaxArgs",8*1024);
800 unsigned int const MaxArgBytes = _config->FindI("Dpkg::MaxArgBytes",32*1024);
5e312de7 801 bool const NoTriggers = _config->FindB("DPkg::NoTriggers", false);
aff4e2f1 802
6dd55be7
AL
803 if (RunScripts("DPkg::Pre-Invoke") == false)
804 return false;
db0c350f
AL
805
806 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
807 return false;
fc2d32c0 808
3e9c4f70
DK
809 // support subpressing of triggers processing for special
810 // cases like d-i that runs the triggers handling manually
5e312de7 811 bool const SmartConf = (_config->Find("PackageManager::Configure", "all") != "all");
5c23dbcc 812 bool const TriggersPending = _config->FindB("DPkg::TriggersPending", false);
5e312de7
DK
813 if (_config->FindB("DPkg::ConfigurePending", SmartConf) == true)
814 List.push_back(Item(Item::ConfigurePending, PkgIterator()));
3e9c4f70 815
75ef8f14
MV
816 // map the dpkg states to the operations that are performed
817 // (this is sorted in the same way as Item::Ops)
9d06bc80 818 static const struct DpkgState DpkgStatesOpMap[][7] = {
75ef8f14
MV
819 // Install operation
820 {
21e1008e
MV
821 {"half-installed", N_("Preparing %s")},
822 {"unpacked", N_("Unpacking %s") },
75ef8f14
MV
823 {NULL, NULL}
824 },
825 // Configure operation
826 {
21e1008e
MV
827 {"unpacked",N_("Preparing to configure %s") },
828 {"half-configured", N_("Configuring %s") },
829 { "installed", N_("Installed %s")},
75ef8f14
MV
830 {NULL, NULL}
831 },
832 // Remove operation
833 {
21e1008e
MV
834 {"half-configured", N_("Preparing for removal of %s")},
835 {"half-installed", N_("Removing %s")},
836 {"config-files", N_("Removed %s")},
75ef8f14
MV
837 {NULL, NULL}
838 },
839 // Purge operation
840 {
21e1008e
MV
841 {"config-files", N_("Preparing to completely remove %s")},
842 {"not-installed", N_("Completely removed %s")},
75ef8f14
MV
843 {NULL, NULL}
844 },
845 };
db0c350f 846
75ef8f14
MV
847 // init the PackageOps map, go over the list of packages that
848 // that will be [installed|configured|removed|purged] and add
849 // them to the PackageOps map (the dpkg states it goes through)
850 // and the PackageOpsTranslations (human readable strings)
887f5036 851 for (vector<Item>::const_iterator I = List.begin(); I != List.end();I++)
75ef8f14 852 {
3e9c4f70
DK
853 if((*I).Pkg.end() == true)
854 continue;
855
887f5036 856 string const name = (*I).Pkg.Name();
75ef8f14
MV
857 PackageOpsDone[name] = 0;
858 for(int i=0; (DpkgStatesOpMap[(*I).Op][i]).state != NULL; i++)
859 {
860 PackageOps[name].push_back(DpkgStatesOpMap[(*I).Op][i]);
ff56e980 861 PackagesTotal++;
75ef8f14 862 }
887f5036 863 }
75ef8f14 864
9983591d
OS
865 stdin_is_dev_null = false;
866
ff56e980 867 // create log
2e1715ea 868 OpenLog();
ff56e980 869
75ef8f14 870 // this loop is runs once per operation
887f5036 871 for (vector<Item>::const_iterator I = List.begin(); I != List.end();)
03e39e59 872 {
5c23dbcc 873 // Do all actions with the same Op in one run
887f5036 874 vector<Item>::const_iterator J = I;
5c23dbcc
DK
875 if (TriggersPending == true)
876 for (; J != List.end(); J++)
877 {
878 if (J->Op == I->Op)
879 continue;
880 if (J->Op != Item::TriggersPending)
881 break;
882 vector<Item>::const_iterator T = J + 1;
883 if (T != List.end() && T->Op == I->Op)
884 continue;
885 break;
886 }
887 else
888 for (; J != List.end() && J->Op == I->Op; J++)
889 /* nothing */;
30e1eab5 890
03e39e59 891 // Generate the argument list
aff4e2f1 892 const char *Args[MaxArgs + 50];
8e11253d
SL
893 // keep track of allocated strings for multiarch package names
894 char *Packages[MaxArgs + 50];
895 unsigned int pkgcount = 0;
896
599d6ad5
MV
897 // Now check if we are within the MaxArgs limit
898 //
899 // this code below is problematic, because it may happen that
900 // the argument list is split in a way that A depends on B
901 // and they are in the same "--configure A B" run
902 // - with the split they may now be configured in different
903 // runs
aff4e2f1
AL
904 if (J - I > (signed)MaxArgs)
905 J = I + MaxArgs;
03e39e59 906
30e1eab5
AL
907 unsigned int n = 0;
908 unsigned long Size = 0;
887f5036 909 string const Tmp = _config->Find("Dir::Bin::dpkg","dpkg");
50914ffa 910 Args[n++] = Tmp.c_str();
30e1eab5 911 Size += strlen(Args[n-1]);
03e39e59 912
6dd55be7
AL
913 // Stick in any custom dpkg options
914 Configuration::Item const *Opts = _config->Tree("DPkg::Options");
915 if (Opts != 0)
916 {
917 Opts = Opts->Child;
918 for (; Opts != 0; Opts = Opts->Next)
919 {
920 if (Opts->Value.empty() == true)
921 continue;
922 Args[n++] = Opts->Value.c_str();
923 Size += Opts->Value.length();
924 }
925 }
926
007dc9e0 927 char status_fd_buf[20];
75ef8f14
MV
928 int fd[2];
929 pipe(fd);
930
931 Args[n++] = "--status-fd";
932 Size += strlen(Args[n-1]);
933 snprintf(status_fd_buf,sizeof(status_fd_buf),"%i", fd[1]);
934 Args[n++] = status_fd_buf;
935 Size += strlen(Args[n-1]);
007dc9e0 936
03e39e59
AL
937 switch (I->Op)
938 {
939 case Item::Remove:
940 Args[n++] = "--force-depends";
30e1eab5 941 Size += strlen(Args[n-1]);
03e39e59 942 Args[n++] = "--force-remove-essential";
30e1eab5 943 Size += strlen(Args[n-1]);
03e39e59 944 Args[n++] = "--remove";
30e1eab5 945 Size += strlen(Args[n-1]);
03e39e59
AL
946 break;
947
fc4b5c9f
AL
948 case Item::Purge:
949 Args[n++] = "--force-depends";
950 Size += strlen(Args[n-1]);
951 Args[n++] = "--force-remove-essential";
952 Size += strlen(Args[n-1]);
953 Args[n++] = "--purge";
954 Size += strlen(Args[n-1]);
955 break;
956
03e39e59
AL
957 case Item::Configure:
958 Args[n++] = "--configure";
30e1eab5 959 Size += strlen(Args[n-1]);
03e39e59 960 break;
3e9c4f70
DK
961
962 case Item::ConfigurePending:
963 Args[n++] = "--configure";
964 Size += strlen(Args[n-1]);
965 Args[n++] = "--pending";
966 Size += strlen(Args[n-1]);
967 break;
968
5e312de7
DK
969 case Item::TriggersPending:
970 Args[n++] = "--triggers-only";
971 Size += strlen(Args[n-1]);
972 Args[n++] = "--pending";
973 Size += strlen(Args[n-1]);
974 break;
975
03e39e59
AL
976 case Item::Install:
977 Args[n++] = "--unpack";
30e1eab5 978 Size += strlen(Args[n-1]);
857a1d4a
MV
979 Args[n++] = "--auto-deconfigure";
980 Size += strlen(Args[n-1]);
03e39e59
AL
981 break;
982 }
3e9c4f70 983
5e312de7 984 if (NoTriggers == true && I->Op != Item::TriggersPending &&
d5081aee 985 I->Op != Item::ConfigurePending)
3e9c4f70
DK
986 {
987 Args[n++] = "--no-triggers";
988 Size += strlen(Args[n-1]);
989 }
990
03e39e59
AL
991 // Write in the file or package names
992 if (I->Op == Item::Install)
30e1eab5 993 {
aff4e2f1 994 for (;I != J && Size < MaxArgBytes; I++)
30e1eab5 995 {
cf544e14
AL
996 if (I->File[0] != '/')
997 return _error->Error("Internal Error, Pathname to install is not absolute '%s'",I->File.c_str());
03e39e59 998 Args[n++] = I->File.c_str();
30e1eab5
AL
999 Size += strlen(Args[n-1]);
1000 }
1001 }
03e39e59 1002 else
30e1eab5 1003 {
8e11253d 1004 string const nativeArch = _config->Find("APT::Architecture");
6f31b247 1005 unsigned long const oldSize = I->Op == Item::Configure ? Size : 0;
aff4e2f1 1006 for (;I != J && Size < MaxArgBytes; I++)
30e1eab5 1007 {
3e9c4f70
DK
1008 if((*I).Pkg.end() == true)
1009 continue;
642ebc1a
DK
1010 if (I->Op == Item::Configure && disappearedPkgs.find(I->Pkg.Name()) != disappearedPkgs.end())
1011 continue;
8e11253d
SL
1012 if (I->Pkg.Arch() == nativeArch || !strcmp(I->Pkg.Arch(), "all"))
1013 Args[n++] = I->Pkg.Name();
1014 else
1015 {
69f76a34
DK
1016 Packages[pkgcount] = strdup(I->Pkg.FullName(false).c_str());
1017 Args[n++] = Packages[pkgcount++];
8e11253d 1018 }
30e1eab5 1019 Size += strlen(Args[n-1]);
6f31b247
DK
1020 }
1021 // skip configure action if all sheduled packages disappeared
1022 if (oldSize == Size)
1023 continue;
1024 }
03e39e59 1025 Args[n] = 0;
30e1eab5
AL
1026 J = I;
1027
1028 if (_config->FindB("Debug::pkgDPkgPM",false) == true)
1029 {
1030 for (unsigned int k = 0; k != n; k++)
1031 clog << Args[k] << ' ';
1032 clog << endl;
1033 continue;
1034 }
03e39e59 1035
03e39e59
AL
1036 cout << flush;
1037 clog << flush;
1038 cerr << flush;
1039
1040 /* Mask off sig int/quit. We do this because dpkg also does when
1041 it forks scripts. What happens is that when you hit ctrl-c it sends
1042 it to all processes in the group. Since dpkg ignores the signal
1043 it doesn't die but we do! So we must also ignore it */
7f9a6360
AL
1044 sighandler_t old_SIGQUIT = signal(SIGQUIT,SIG_IGN);
1045 sighandler_t old_SIGINT = signal(SIGINT,SIG_IGN);
d8cb4aa4 1046
73e598c3
MV
1047 // ignore SIGHUP as well (debian #463030)
1048 sighandler_t old_SIGHUP = signal(SIGHUP,SIG_IGN);
1049
d8cb4aa4
MV
1050 struct termios tt;
1051 struct winsize win;
4e550036
MV
1052 int master = -1;
1053 int slave = -1;
d8cb4aa4 1054
4e550036
MV
1055 // if tcgetattr does not return zero there was a error
1056 // and we do not do any pty magic
1057 if (tcgetattr(0, &tt) == 0)
090c6566 1058 {
4e550036
MV
1059 ioctl(0, TIOCGWINSZ, (char *)&win);
1060 if (openpty(&master, &slave, NULL, &tt, &win) < 0)
1061 {
1062 const char *s = _("Can not write log, openpty() "
1063 "failed (/dev/pts not mounted?)\n");
1064 fprintf(stderr, "%s",s);
6847d275
MV
1065 if(term_out)
1066 fprintf(term_out, "%s",s);
4e550036
MV
1067 master = slave = -1;
1068 } else {
1069 struct termios rtt;
1070 rtt = tt;
1071 cfmakeraw(&rtt);
1072 rtt.c_lflag &= ~ECHO;
4d7ac88c 1073 rtt.c_lflag |= ISIG;
4e550036
MV
1074 // block SIGTTOU during tcsetattr to prevent a hang if
1075 // the process is a member of the background process group
1076 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
1077 sigemptyset(&sigmask);
1078 sigaddset(&sigmask, SIGTTOU);
1079 sigprocmask(SIG_BLOCK,&sigmask, &original_sigmask);
1080 tcsetattr(0, TCSAFLUSH, &rtt);
1081 sigprocmask(SIG_SETMASK, &original_sigmask, 0);
1082 }
d8cb4aa4
MV
1083 }
1084
75ef8f14 1085 // Fork dpkg
007dc9e0 1086 pid_t Child;
75ef8f14 1087 _config->Set("APT::Keep-Fds::",fd[1]);
ccd8e28f
MV
1088 // send status information that we are about to fork dpkg
1089 if(OutStatusFd > 0) {
1090 ostringstream status;
1091 status << "pmstatus:dpkg-exec:"
1092 << (PackagesDone/float(PackagesTotal)*100.0)
1093 << ":" << _("Running dpkg")
1094 << endl;
1095 write(OutStatusFd, status.str().c_str(), status.str().size());
1096 }
75ef8f14 1097 Child = ExecFork();
6dd55be7 1098
03e39e59
AL
1099 // This is the child
1100 if (Child == 0)
1101 {
a4cf3665
MV
1102 if(slave >= 0 && master >= 0)
1103 {
1104 setsid();
1105 ioctl(slave, TIOCSCTTY, 0);
1106 close(master);
1107 dup2(slave, 0);
1108 dup2(slave, 1);
1109 dup2(slave, 2);
1110 close(slave);
1111 }
75ef8f14 1112 close(fd[0]); // close the read end of the pipe
d8cb4aa4 1113
4b7cfe96
MV
1114 if (_config->FindDir("DPkg::Chroot-Directory","/") != "/")
1115 {
1116 std::cerr << "Chrooting into "
1117 << _config->FindDir("DPkg::Chroot-Directory")
1118 << std::endl;
1119 if (chroot(_config->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
1120 _exit(100);
1121 }
1122
cf544e14 1123 if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
0dbb95d8 1124 _exit(100);
03e39e59 1125
421ff807 1126 if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
8b5fe26c
AL
1127 {
1128 int Flags,dummy;
1129 if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
1130 _exit(100);
1131
1132 // Discard everything in stdin before forking dpkg
1133 if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
1134 _exit(100);
1135
1136 while (read(STDIN_FILENO,&dummy,1) == 1);
1137
1138 if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
1139 _exit(100);
1140 }
d8cb4aa4 1141
03e39e59
AL
1142 /* No Job Control Stop Env is a magic dpkg var that prevents it
1143 from using sigstop */
71afbdb5 1144 putenv((char *)"DPKG_NO_TSTP=yes");
d568ed2d 1145 execvp(Args[0],(char **)Args);
03e39e59 1146 cerr << "Could not exec dpkg!" << endl;
0dbb95d8 1147 _exit(100);
03e39e59
AL
1148 }
1149
cebe0287
MV
1150 // apply ionice
1151 if (_config->FindB("DPkg::UseIoNice", false) == true)
1152 ionice(Child);
1153
75ef8f14
MV
1154 // clear the Keep-Fd again
1155 _config->Clear("APT::Keep-Fds",fd[1]);
1156
03e39e59
AL
1157 // Wait for dpkg
1158 int Status = 0;
75ef8f14
MV
1159
1160 // we read from dpkg here
887f5036 1161 int const _dpkgin = fd[0];
75ef8f14
MV
1162 close(fd[1]); // close the write end of the pipe
1163
a4cf3665
MV
1164 if(slave > 0)
1165 close(slave);
6191b008 1166
97efd303 1167 // setups fds
7052511e
MV
1168 sigemptyset(&sigmask);
1169 sigprocmask(SIG_BLOCK,&sigmask,&original_sigmask);
1170
8e11253d
SL
1171 /* clean up the temporary allocation for multiarch package names in
1172 the parent, so we don't leak memory when we return. */
1173 for (unsigned int i = 0; i < pkgcount; i++)
69f76a34 1174 free(Packages[i]);
8e11253d 1175
887f5036
DK
1176 // the result of the waitpid call
1177 int res;
090c6566 1178 int select_ret;
75ef8f14
MV
1179 while ((res=waitpid(Child,&Status, WNOHANG)) != Child) {
1180 if(res < 0) {
1181 // FIXME: move this to a function or something, looks ugly here
1182 // error handling, waitpid returned -1
1183 if (errno == EINTR)
1184 continue;
1185 RunScripts("DPkg::Post-Invoke");
1186
1187 // Restore sig int/quit
1188 signal(SIGQUIT,old_SIGQUIT);
1189 signal(SIGINT,old_SIGINT);
e306ec47 1190 signal(SIGHUP,old_SIGHUP);
75ef8f14
MV
1191 return _error->Errno("waitpid","Couldn't wait for subprocess");
1192 }
d8cb4aa4
MV
1193
1194 // wait for input or output here
955a6ddb 1195 FD_ZERO(&rfds);
897165af 1196 if (master >= 0 && !stdin_is_dev_null)
9983591d 1197 FD_SET(0, &rfds);
955a6ddb 1198 FD_SET(_dpkgin, &rfds);
a4cf3665
MV
1199 if(master >= 0)
1200 FD_SET(master, &rfds);
090c6566 1201 tv.tv_sec = 1;
7052511e
MV
1202 tv.tv_nsec = 0;
1203 select_ret = pselect(max(master, _dpkgin)+1, &rfds, NULL, NULL,
1204 &tv, &original_sigmask);
919e5852
OS
1205 if (select_ret < 0 && (errno == EINVAL || errno == ENOSYS))
1206 select_ret = racy_pselect(max(master, _dpkgin)+1, &rfds, NULL,
1207 NULL, &tv, &original_sigmask);
da50ba30
MV
1208 if (select_ret == 0)
1209 continue;
1210 else if (select_ret < 0 && errno == EINTR)
1211 continue;
1212 else if (select_ret < 0)
1213 {
1214 perror("select() returned error");
1215 continue;
1216 }
1217
a4cf3665 1218 if(master >= 0 && FD_ISSET(master, &rfds))
1ba38171 1219 DoTerminalPty(master);
a4cf3665 1220 if(master >= 0 && FD_ISSET(0, &rfds))
955a6ddb 1221 DoStdin(master);
955a6ddb 1222 if(FD_ISSET(_dpkgin, &rfds))
09fa2df2 1223 DoDpkgStatusFd(_dpkgin, OutStatusFd);
03e39e59 1224 }
75ef8f14 1225 close(_dpkgin);
03e39e59
AL
1226
1227 // Restore sig int/quit
7f9a6360
AL
1228 signal(SIGQUIT,old_SIGQUIT);
1229 signal(SIGINT,old_SIGINT);
d9ec0fac 1230 signal(SIGHUP,old_SIGHUP);
d8cb4aa4 1231
477b5d6c
MV
1232 if(master >= 0)
1233 {
a4cf3665 1234 tcsetattr(0, TCSAFLUSH, &tt);
477b5d6c
MV
1235 close(master);
1236 }
6dd55be7
AL
1237
1238 // Check for an error code.
1239 if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
1240 {
c70496f9
MV
1241 // if it was set to "keep-dpkg-runing" then we won't return
1242 // here but keep the loop going and just report it as a error
1243 // for later
887f5036 1244 bool const stopOnError = _config->FindB("Dpkg::StopOnError",true);
f956efb4 1245
c70496f9
MV
1246 if(stopOnError)
1247 RunScripts("DPkg::Post-Invoke");
1248
1249 if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
9169c871 1250 strprintf(dpkg_error, "Sub-process %s received a segmentation fault.",Args[0]);
c70496f9 1251 else if (WIFEXITED(Status) != 0)
9169c871 1252 strprintf(dpkg_error, "Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
c70496f9 1253 else
9169c871
MV
1254 strprintf(dpkg_error, "Sub-process %s exited unexpectedly",Args[0]);
1255
1256 if(dpkg_error.size() > 0)
7763525d 1257 _error->Error("%s", dpkg_error.c_str());
c70496f9 1258
ff56e980
MV
1259 if(stopOnError)
1260 {
2e1715ea 1261 CloseLog();
c70496f9 1262 return false;
ff56e980 1263 }
6dd55be7 1264 }
03e39e59 1265 }
2e1715ea 1266 CloseLog();
6dd55be7
AL
1267
1268 if (RunScripts("DPkg::Post-Invoke") == false)
1269 return false;
b462d75a
MV
1270
1271 Cache.writeStateFile(NULL);
03e39e59
AL
1272 return true;
1273}
1274 /*}}}*/
281daf46
AL
1275// pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1276// ---------------------------------------------------------------------
1277/* */
1278void pkgDPkgPM::Reset()
1279{
1280 List.erase(List.begin(),List.end());
1281}
1282 /*}}}*/
5e457a93
MV
1283// pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1284// ---------------------------------------------------------------------
1285/* */
1286void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
1287{
1288 string pkgname, reportfile, srcpkgname, pkgver, arch;
1289 string::size_type pos;
1290 FILE *report;
1291
23c5897c 1292 if (_config->FindB("Dpkg::ApportFailureReport", false) == false)
ff38d63b
MV
1293 {
1294 std::clog << "configured to not write apport reports" << std::endl;
5e457a93 1295 return;
ff38d63b 1296 }
5e457a93 1297
d6a4afcb 1298 // only report the first errors
5273f1bf 1299 if(pkgFailures > _config->FindI("APT::Apport::MaxReports", 3))
ff38d63b
MV
1300 {
1301 std::clog << _("No apport report written because MaxReports is reached already") << std::endl;
5e457a93 1302 return;
ff38d63b 1303 }
5e457a93 1304
d6a4afcb
MV
1305 // check if its not a follow up error
1306 const char *needle = dgettext("dpkg", "dependency problems - leaving unconfigured");
1307 if(strstr(errormsg, needle) != NULL) {
1308 std::clog << _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl;
1309 return;
1310 }
1311
2f0d5dea
MV
1312 // do not report disk-full failures
1313 if(strstr(errormsg, strerror(ENOSPC)) != NULL) {
1314 std::clog << _("No apport report written because the error message indicates a disk full error") << std::endl;
1315 return;
1316 }
1317
3024a85e
MV
1318 // do not report out-of-memory failures
1319 if(strstr(errormsg, strerror(ENOMEM)) != NULL) {
1320 std::clog << _("No apport report written because the error message indicates a out of memory error") << std::endl;
1321 return;
1322 }
1323
076c46e5
MZ
1324 // do not report dpkg I/O errors
1325 // XXX - this message is localized, but this only matches the English version. This is better than nothing.
1326 if(strstr(errormsg, "short read in buffer_copy (")) {
1327 std::clog << _("No apport report written because the error message indicates a dpkg I/O error") << std::endl;
1328 return;
1329 }
1330
5e457a93
MV
1331 // get the pkgname and reportfile
1332 pkgname = flNotDir(pkgpath);
25ffa4e8 1333 pos = pkgname.find('_');
5e457a93 1334 if(pos != string::npos)
25ffa4e8 1335 pkgname = pkgname.substr(0, pos);
5e457a93
MV
1336
1337 // find the package versin and source package name
1338 pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
1339 if (Pkg.end() == true)
1340 return;
1341 pkgCache::VerIterator Ver = Cache.GetCandidateVer(Pkg);
5e457a93
MV
1342 if (Ver.end() == true)
1343 return;
986d97bb 1344 pkgver = Ver.VerStr() == NULL ? "unknown" : Ver.VerStr();
5e457a93
MV
1345 pkgRecords Recs(Cache);
1346 pkgRecords::Parser &Parse = Recs.Lookup(Ver.FileList());
1347 srcpkgname = Parse.SourcePkg();
1348 if(srcpkgname.empty())
1349 srcpkgname = pkgname;
1350
1351 // if the file exists already, we check:
1352 // - if it was reported already (touched by apport).
1353 // If not, we do nothing, otherwise
1354 // we overwrite it. This is the same behaviour as apport
1355 // - if we have a report with the same pkgversion already
1356 // then we skip it
1357 reportfile = flCombine("/var/crash",pkgname+".0.crash");
1358 if(FileExists(reportfile))
1359 {
1360 struct stat buf;
1361 char strbuf[255];
1362
1363 // check atime/mtime
1364 stat(reportfile.c_str(), &buf);
1365 if(buf.st_mtime > buf.st_atime)
1366 return;
1367
1368 // check if the existing report is the same version
1369 report = fopen(reportfile.c_str(),"r");
1370 while(fgets(strbuf, sizeof(strbuf), report) != NULL)
1371 {
1372 if(strstr(strbuf,"Package:") == strbuf)
1373 {
1374 char pkgname[255], version[255];
1375 if(sscanf(strbuf, "Package: %s %s", pkgname, version) == 2)
1376 if(strcmp(pkgver.c_str(), version) == 0)
1377 {
1378 fclose(report);
1379 return;
1380 }
1381 }
1382 }
1383 fclose(report);
1384 }
1385
1386 // now write the report
1387 arch = _config->Find("APT::Architecture");
1388 report = fopen(reportfile.c_str(),"w");
1389 if(report == NULL)
1390 return;
1391 if(_config->FindB("DPkgPM::InitialReportOnly",false) == true)
1392 chmod(reportfile.c_str(), 0);
1393 else
1394 chmod(reportfile.c_str(), 0600);
1395 fprintf(report, "ProblemType: Package\n");
1396 fprintf(report, "Architecture: %s\n", arch.c_str());
1397 time_t now = time(NULL);
1398 fprintf(report, "Date: %s" , ctime(&now));
1399 fprintf(report, "Package: %s %s\n", pkgname.c_str(), pkgver.c_str());
1400 fprintf(report, "SourcePackage: %s\n", srcpkgname.c_str());
1401 fprintf(report, "ErrorMessage:\n %s\n", errormsg);
8ecd1fed
MV
1402
1403 // ensure that the log is flushed
1404 if(term_out)
1405 fflush(term_out);
1406
1407 // attach terminal log it if we have it
1408 string logfile_name = _config->FindFile("Dir::Log::Terminal");
1409 if (!logfile_name.empty())
1410 {
1411 FILE *log = NULL;
1412 char buf[1024];
1413
1414 fprintf(report, "DpkgTerminalLog:\n");
1415 log = fopen(logfile_name.c_str(),"r");
1416 if(log != NULL)
1417 {
1418 while( fgets(buf, sizeof(buf), log) != NULL)
1419 fprintf(report, " %s", buf);
1420 fclose(log);
1421 }
1422 }
76dbdfc7 1423
5c8a2aa8
MV
1424 // log the ordering
1425 const char *ops_str[] = {"Install", "Configure","Remove","Purge"};
1426 fprintf(report, "AptOrdering:\n");
1427 for (vector<Item>::iterator I = List.begin(); I != List.end(); I++)
1428 fprintf(report, " %s: %s\n", (*I).Pkg.Name(), ops_str[(*I).Op]);
1429
76dbdfc7
MV
1430 // attach dmesg log (to learn about segfaults)
1431 if (FileExists("/bin/dmesg"))
1432 {
1433 FILE *log = NULL;
1434 char buf[1024];
1435
1436 fprintf(report, "Dmesg:\n");
1437 log = popen("/bin/dmesg","r");
1438 if(log != NULL)
1439 {
1440 while( fgets(buf, sizeof(buf), log) != NULL)
1441 fprintf(report, " %s", buf);
23f3cfd0 1442 pclose(log);
76dbdfc7
MV
1443 }
1444 }
2183a086
MV
1445
1446 // attach df -l log (to learn about filesystem status)
1447 if (FileExists("/bin/df"))
1448 {
1449 FILE *log = NULL;
1450 char buf[1024];
1451
1452 fprintf(report, "Df:\n");
1453 log = popen("/bin/df -l","r");
1454 if(log != NULL)
1455 {
1456 while( fgets(buf, sizeof(buf), log) != NULL)
1457 fprintf(report, " %s", buf);
23f3cfd0 1458 pclose(log);
2183a086
MV
1459 }
1460 }
1461
5e457a93 1462 fclose(report);
76dbdfc7 1463
5e457a93
MV
1464}
1465 /*}}}*/