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