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