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