add and document experimental options to make aggressive
[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 /*{{{*/
03e39e59
AL
11#include <apt-pkg/dpkgpm.h>
12#include <apt-pkg/error.h>
13#include <apt-pkg/configuration.h>
b2e465d6
AL
14#include <apt-pkg/depcache.h>
15#include <apt-pkg/strutl.h>
a4cf3665 16#include <apti18n.h>
614adaa0 17#include <apt-pkg/fileutl.h>
233b185f 18
03e39e59
AL
19#include <unistd.h>
20#include <stdlib.h>
21#include <fcntl.h>
090c6566 22#include <sys/select.h>
03e39e59
AL
23#include <sys/types.h>
24#include <sys/wait.h>
25#include <signal.h>
26#include <errno.h>
db0c350f 27#include <stdio.h>
f7dec19f
DB
28#include <string.h>
29#include <algorithm>
75ef8f14
MV
30#include <sstream>
31#include <map>
32
d8cb4aa4
MV
33#include <termios.h>
34#include <unistd.h>
35#include <sys/ioctl.h>
36#include <pty.h>
37
75ef8f14
MV
38#include <config.h>
39#include <apti18n.h>
b0ebdef5 40 /*}}}*/
233b185f
AL
41
42using namespace std;
03e39e59 43
f7dec19f
DB
44namespace
45{
46 // Maps the dpkg "processing" info to human readable names. Entry 0
47 // of each array is the key, entry 1 is the value.
48 const std::pair<const char *, const char *> PackageProcessingOps[] = {
49 std::make_pair("install", N_("Installing %s")),
50 std::make_pair("configure", N_("Configuring %s")),
51 std::make_pair("remove", N_("Removing %s")),
52 std::make_pair("trigproc", N_("Running post-installation trigger %s"))
53 };
54
55 const std::pair<const char *, const char *> * const PackageProcessingOpsBegin = PackageProcessingOps;
56 const std::pair<const char *, const char *> * const PackageProcessingOpsEnd = PackageProcessingOps + sizeof(PackageProcessingOps) / sizeof(PackageProcessingOps[0]);
57
58 // Predicate to test whether an entry in the PackageProcessingOps
59 // array matches a string.
60 class MatchProcessingOp
61 {
62 const char *target;
63
64 public:
65 MatchProcessingOp(const char *the_target)
66 : target(the_target)
67 {
68 }
69
70 bool operator()(const std::pair<const char *, const char *> &pair) const
71 {
72 return strcmp(pair.first, target) == 0;
73 }
74 };
75}
09fa2df2 76
cebe0287
MV
77/* helper function to ionice the given PID
78
79 there is no C header for ionice yet - just the syscall interface
80 so we use the binary from util-linux
81*/
82static bool
83ionice(int PID)
84{
85 if (!FileExists("/usr/bin/ionice"))
86 return false;
87 pid_t Process = ExecFork();
88 if (Process == 0)
89 {
90 char buf[32];
91 snprintf(buf, sizeof(buf), "-p%d", PID);
92 const char *Args[4];
93 Args[0] = "/usr/bin/ionice";
94 Args[1] = "-c3";
95 Args[2] = buf;
96 Args[3] = 0;
97 execv(Args[0], (char **)Args);
98 }
99 return ExecWait(Process, "ionice");
100}
101
03e39e59
AL
102// DPkgPM::pkgDPkgPM - Constructor /*{{{*/
103// ---------------------------------------------------------------------
104/* */
09fa2df2 105pkgDPkgPM::pkgDPkgPM(pkgDepCache *Cache)
71afbdb5
OS
106 : pkgPackageManager(Cache), dpkgbuf_pos(0),
107 term_out(NULL), PackagesDone(0), PackagesTotal(0)
03e39e59
AL
108{
109}
110 /*}}}*/
111// DPkgPM::pkgDPkgPM - Destructor /*{{{*/
112// ---------------------------------------------------------------------
113/* */
114pkgDPkgPM::~pkgDPkgPM()
115{
116}
117 /*}}}*/
118// DPkgPM::Install - Install a package /*{{{*/
119// ---------------------------------------------------------------------
120/* Add an install operation to the sequence list */
121bool pkgDPkgPM::Install(PkgIterator Pkg,string File)
122{
123 if (File.empty() == true || Pkg.end() == true)
124 return _error->Error("Internal Error, No file name for %s",Pkg.Name());
125
126 List.push_back(Item(Item::Install,Pkg,File));
127 return true;
128}
129 /*}}}*/
130// DPkgPM::Configure - Configure a package /*{{{*/
131// ---------------------------------------------------------------------
132/* Add a configure operation to the sequence list */
133bool pkgDPkgPM::Configure(PkgIterator Pkg)
134{
135 if (Pkg.end() == true)
136 return false;
3e9c4f70
DK
137
138 bool static const NoConfigure = _config->FindB("DPkg::NoConfigure",false);
139 if (NoConfigure == false)
140 List.push_back(Item(Item::Configure,Pkg));
141
03e39e59
AL
142 return true;
143}
144 /*}}}*/
145// DPkgPM::Remove - Remove a package /*{{{*/
146// ---------------------------------------------------------------------
147/* Add a remove operation to the sequence list */
fc4b5c9f 148bool pkgDPkgPM::Remove(PkgIterator Pkg,bool Purge)
03e39e59
AL
149{
150 if (Pkg.end() == true)
151 return false;
152
fc4b5c9f
AL
153 if (Purge == true)
154 List.push_back(Item(Item::Purge,Pkg));
155 else
156 List.push_back(Item(Item::Remove,Pkg));
6dd55be7
AL
157 return true;
158}
159 /*}}}*/
b2e465d6
AL
160// DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
161// ---------------------------------------------------------------------
162/* This is part of the helper script communication interface, it sends
163 very complete information down to the other end of the pipe.*/
164bool pkgDPkgPM::SendV2Pkgs(FILE *F)
165{
166 fprintf(F,"VERSION 2\n");
167
168 /* Write out all of the configuration directives by walking the
169 configuration tree */
170 const Configuration::Item *Top = _config->Tree(0);
171 for (; Top != 0;)
172 {
173 if (Top->Value.empty() == false)
174 {
175 fprintf(F,"%s=%s\n",
176 QuoteString(Top->FullTag(),"=\"\n").c_str(),
177 QuoteString(Top->Value,"\n").c_str());
178 }
179
180 if (Top->Child != 0)
181 {
182 Top = Top->Child;
183 continue;
184 }
185
186 while (Top != 0 && Top->Next == 0)
187 Top = Top->Parent;
188 if (Top != 0)
189 Top = Top->Next;
190 }
191 fprintf(F,"\n");
192
193 // Write out the package actions in order.
194 for (vector<Item>::iterator I = List.begin(); I != List.end(); I++)
195 {
3e9c4f70
DK
196 if(I->Pkg.end() == true)
197 continue;
198
b2e465d6
AL
199 pkgDepCache::StateCache &S = Cache[I->Pkg];
200
201 fprintf(F,"%s ",I->Pkg.Name());
202 // Current version
203 if (I->Pkg->CurrentVer == 0)
204 fprintf(F,"- ");
205 else
206 fprintf(F,"%s ",I->Pkg.CurrentVer().VerStr());
207
208 // Show the compare operator
209 // Target version
210 if (S.InstallVer != 0)
211 {
212 int Comp = 2;
213 if (I->Pkg->CurrentVer != 0)
214 Comp = S.InstVerIter(Cache).CompareVer(I->Pkg.CurrentVer());
215 if (Comp < 0)
216 fprintf(F,"> ");
217 if (Comp == 0)
218 fprintf(F,"= ");
219 if (Comp > 0)
220 fprintf(F,"< ");
221 fprintf(F,"%s ",S.InstVerIter(Cache).VerStr());
222 }
223 else
224 fprintf(F,"> - ");
225
226 // Show the filename/operation
227 if (I->Op == Item::Install)
228 {
229 // No errors here..
230 if (I->File[0] != '/')
231 fprintf(F,"**ERROR**\n");
232 else
233 fprintf(F,"%s\n",I->File.c_str());
234 }
235 if (I->Op == Item::Configure)
236 fprintf(F,"**CONFIGURE**\n");
237 if (I->Op == Item::Remove ||
238 I->Op == Item::Purge)
239 fprintf(F,"**REMOVE**\n");
240
241 if (ferror(F) != 0)
242 return false;
243 }
244 return true;
245}
246 /*}}}*/
db0c350f
AL
247// DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
248// ---------------------------------------------------------------------
249/* This looks for a list of scripts to run from the configuration file
250 each one is run and is fed on standard input a list of all .deb files
251 that are due to be installed. */
252bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf)
253{
254 Configuration::Item const *Opts = _config->Tree(Cnf);
255 if (Opts == 0 || Opts->Child == 0)
256 return true;
257 Opts = Opts->Child;
258
259 unsigned int Count = 1;
260 for (; Opts != 0; Opts = Opts->Next, Count++)
261 {
262 if (Opts->Value.empty() == true)
263 continue;
b2e465d6
AL
264
265 // Determine the protocol version
266 string OptSec = Opts->Value;
267 string::size_type Pos;
268 if ((Pos = OptSec.find(' ')) == string::npos || Pos == 0)
269 Pos = OptSec.length();
b2e465d6
AL
270 OptSec = "DPkg::Tools::Options::" + string(Opts->Value.c_str(),Pos);
271
272 unsigned int Version = _config->FindI(OptSec+"::Version",1);
273
db0c350f
AL
274 // Create the pipes
275 int Pipes[2];
276 if (pipe(Pipes) != 0)
277 return _error->Errno("pipe","Failed to create IPC pipe to subprocess");
278 SetCloseExec(Pipes[0],true);
279 SetCloseExec(Pipes[1],true);
280
281 // Purified Fork for running the script
282 pid_t Process = ExecFork();
283 if (Process == 0)
284 {
285 // Setup the FDs
286 dup2(Pipes[0],STDIN_FILENO);
287 SetCloseExec(STDOUT_FILENO,false);
288 SetCloseExec(STDIN_FILENO,false);
289 SetCloseExec(STDERR_FILENO,false);
90ecbd7d
AL
290
291 const char *Args[4];
db0c350f 292 Args[0] = "/bin/sh";
90ecbd7d
AL
293 Args[1] = "-c";
294 Args[2] = Opts->Value.c_str();
295 Args[3] = 0;
db0c350f
AL
296 execv(Args[0],(char **)Args);
297 _exit(100);
298 }
299 close(Pipes[0]);
b2e465d6
AL
300 FILE *F = fdopen(Pipes[1],"w");
301 if (F == 0)
302 return _error->Errno("fdopen","Faild to open new FD");
303
db0c350f 304 // Feed it the filenames.
b2e465d6
AL
305 bool Die = false;
306 if (Version <= 1)
db0c350f 307 {
b2e465d6 308 for (vector<Item>::iterator I = List.begin(); I != List.end(); I++)
db0c350f 309 {
b2e465d6
AL
310 // Only deal with packages to be installed from .deb
311 if (I->Op != Item::Install)
312 continue;
313
314 // No errors here..
315 if (I->File[0] != '/')
316 continue;
317
318 /* Feed the filename of each package that is pending install
319 into the pipe. */
320 fprintf(F,"%s\n",I->File.c_str());
321 if (ferror(F) != 0)
322 {
323 Die = true;
324 break;
325 }
90ecbd7d 326 }
db0c350f 327 }
b2e465d6
AL
328 else
329 Die = !SendV2Pkgs(F);
330
331 fclose(F);
db0c350f
AL
332
333 // Clean up the sub process
334 if (ExecWait(Process,Opts->Value.c_str()) == false)
90ecbd7d 335 return _error->Error("Failure running script %s",Opts->Value.c_str());
db0c350f
AL
336 }
337
338 return true;
339}
ceabc520
MV
340
341 /*}}}*/
342// DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
343// ---------------------------------------------------------------------
344/*
345*/
346void pkgDPkgPM::DoStdin(int master)
347{
aff87a76
MV
348 unsigned char input_buf[256] = {0,};
349 ssize_t len = read(0, input_buf, sizeof(input_buf));
9983591d
OS
350 if (len)
351 write(master, input_buf, len);
352 else
353 stdin_is_dev_null = true;
ceabc520 354}
03e39e59 355 /*}}}*/
ceabc520
MV
356// DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
357// ---------------------------------------------------------------------
358/*
359 * read the terminal pty and write log
360 */
1ba38171 361void pkgDPkgPM::DoTerminalPty(int master)
ceabc520 362{
aff87a76 363 unsigned char term_buf[1024] = {0,0, };
ceabc520 364
aff87a76 365 ssize_t len=read(master, term_buf, sizeof(term_buf));
7052511e
MV
366 if(len == -1 && errno == EIO)
367 {
368 // this happens when the child is about to exit, we
369 // give it time to actually exit, otherwise we run
370 // into a race
371 usleep(500000);
372 return;
373 }
374 if(len <= 0)
955a6ddb 375 return;
955a6ddb 376 write(1, term_buf, len);
8da1f029
MV
377 if(term_out)
378 fwrite(term_buf, len, sizeof(char), term_out);
ceabc520 379}
03e39e59 380 /*}}}*/
6191b008
MV
381// DPkgPM::ProcessDpkgStatusBuf /*{{{*/
382// ---------------------------------------------------------------------
383/*
384 */
09fa2df2 385void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd, char *line)
6191b008 386{
887f5036 387 bool const Debug = _config->FindB("Debug::pkgDPkgProgressReporting",false);
09fa2df2
MV
388 // the status we output
389 ostringstream status;
390
887f5036 391 if (Debug == true)
09fa2df2
MV
392 std::clog << "got from dpkg '" << line << "'" << std::endl;
393
394
395 /* dpkg sends strings like this:
396 'status: <pkg>: <pkg qstate>'
397 errors look like this:
398 '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
399 and conffile-prompt like this
400 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
fc2d32c0
MV
401
402 Newer versions of dpkg sent also:
403 'processing: install: pkg'
404 'processing: configure: pkg'
405 'processing: remove: pkg'
887f5036 406 'processing: purge: pkg' - but for apt is it a ignored "unknown" action
fc2d32c0 407 'processing: trigproc: trigger'
09fa2df2
MV
408
409 */
410 char* list[5];
411 // dpkg sends multiline error messages sometimes (see
412 // #374195 for a example. we should support this by
413 // either patching dpkg to not send multiline over the
414 // statusfd or by rewriting the code here to deal with
415 // it. for now we just ignore it and not crash
416 TokSplitString(':', line, list, sizeof(list)/sizeof(list[0]));
f26fcbc7 417 if( list[0] == NULL || list[1] == NULL || list[2] == NULL)
09fa2df2 418 {
887f5036 419 if (Debug == true)
09fa2df2
MV
420 std::clog << "ignoring line: not enough ':'" << std::endl;
421 return;
422 }
887f5036
DK
423 const char* const pkg = list[1];
424 const char* action = _strstrip(list[2]);
09fa2df2 425
fc2d32c0
MV
426 // 'processing' from dpkg looks like
427 // 'processing: action: pkg'
428 if(strncmp(list[0], "processing", strlen("processing")) == 0)
429 {
430 char s[200];
887f5036
DK
431 const char* const pkg_or_trigger = _strstrip(list[2]);
432 action = _strstrip( list[1]);
f7dec19f
DB
433 const std::pair<const char *, const char *> * const iter =
434 std::find_if(PackageProcessingOpsBegin,
435 PackageProcessingOpsEnd,
436 MatchProcessingOp(action));
437 if(iter == PackageProcessingOpsEnd)
fc2d32c0 438 {
887f5036
DK
439 if (Debug == true)
440 std::clog << "ignoring unknown action: " << action << std::endl;
fc2d32c0
MV
441 return;
442 }
f7dec19f 443 snprintf(s, sizeof(s), _(iter->second), pkg_or_trigger);
fc2d32c0
MV
444
445 status << "pmstatus:" << pkg_or_trigger
446 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
447 << ":" << s
448 << endl;
449 if(OutStatusFd > 0)
450 write(OutStatusFd, status.str().c_str(), status.str().size());
887f5036 451 if (Debug == true)
fc2d32c0
MV
452 std::clog << "send: '" << status.str() << "'" << endl;
453 return;
454 }
455
09fa2df2
MV
456 if(strncmp(action,"error",strlen("error")) == 0)
457 {
458 status << "pmerror:" << list[1]
ff56e980 459 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
09fa2df2
MV
460 << ":" << list[3]
461 << endl;
462 if(OutStatusFd > 0)
463 write(OutStatusFd, status.str().c_str(), status.str().size());
887f5036 464 if (Debug == true)
09fa2df2
MV
465 std::clog << "send: '" << status.str() << "'" << endl;
466 return;
467 }
887f5036 468 else if(strncmp(action,"conffile",strlen("conffile")) == 0)
09fa2df2
MV
469 {
470 status << "pmconffile:" << list[1]
ff56e980 471 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
09fa2df2
MV
472 << ":" << list[3]
473 << endl;
474 if(OutStatusFd > 0)
475 write(OutStatusFd, status.str().c_str(), status.str().size());
887f5036 476 if (Debug == true)
09fa2df2
MV
477 std::clog << "send: '" << status.str() << "'" << endl;
478 return;
479 }
480
887f5036 481 vector<struct DpkgState> const &states = PackageOps[pkg];
09fa2df2
MV
482 const char *next_action = NULL;
483 if(PackageOpsDone[pkg] < states.size())
484 next_action = states[PackageOpsDone[pkg]].state;
485 // check if the package moved to the next dpkg state
486 if(next_action && (strcmp(action, next_action) == 0))
487 {
488 // only read the translation if there is actually a next
489 // action
490 const char *translation = _(states[PackageOpsDone[pkg]].str);
491 char s[200];
492 snprintf(s, sizeof(s), translation, pkg);
493
494 // we moved from one dpkg state to a new one, report that
495 PackageOpsDone[pkg]++;
ff56e980 496 PackagesDone++;
09fa2df2
MV
497 // build the status str
498 status << "pmstatus:" << pkg
ff56e980 499 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
09fa2df2
MV
500 << ":" << s
501 << endl;
502 if(OutStatusFd > 0)
503 write(OutStatusFd, status.str().c_str(), status.str().size());
887f5036 504 if (Debug == true)
09fa2df2
MV
505 std::clog << "send: '" << status.str() << "'" << endl;
506 }
887f5036 507 if (Debug == true)
09fa2df2
MV
508 std::clog << "(parsed from dpkg) pkg: " << pkg
509 << " action: " << action << endl;
6191b008 510}
887f5036
DK
511 /*}}}*/
512// DPkgPM::DoDpkgStatusFd /*{{{*/
6191b008
MV
513// ---------------------------------------------------------------------
514/*
515 */
09fa2df2 516void pkgDPkgPM::DoDpkgStatusFd(int statusfd, int OutStatusFd)
6191b008
MV
517{
518 char *p, *q;
519 int len;
520
521 len=read(statusfd, &dpkgbuf[dpkgbuf_pos], sizeof(dpkgbuf)-dpkgbuf_pos);
522 dpkgbuf_pos += len;
523 if(len <= 0)
524 return;
ceabc520 525
6191b008
MV
526 // process line by line if we have a buffer
527 p = q = dpkgbuf;
528 while((q=(char*)memchr(p, '\n', dpkgbuf+dpkgbuf_pos-p)) != NULL)
529 {
530 *q = 0;
09fa2df2 531 ProcessDpkgStatusLine(OutStatusFd, p);
6191b008
MV
532 p=q+1; // continue with next line
533 }
534
535 // now move the unprocessed bits (after the final \n that is now a 0x0)
536 // to the start and update dpkgbuf_pos
537 p = (char*)memrchr(dpkgbuf, 0, dpkgbuf_pos);
538 if(p == NULL)
539 return;
540
541 // we are interessted in the first char *after* 0x0
542 p++;
543
544 // move the unprocessed tail to the start and update pos
545 memmove(dpkgbuf, p, p-dpkgbuf);
546 dpkgbuf_pos = dpkgbuf+dpkgbuf_pos-p;
547}
548 /*}}}*/
887f5036 549// DPkgPM::OpenLog /*{{{*/
2e1715ea
MV
550bool pkgDPkgPM::OpenLog()
551{
552 string logdir = _config->FindDir("Dir::Log");
553 if(not FileExists(logdir))
554 return _error->Error(_("Directory '%s' missing"), logdir.c_str());
555 string logfile_name = flCombine(logdir,
556 _config->Find("Dir::Log::Terminal"));
557 if (!logfile_name.empty())
558 {
559 term_out = fopen(logfile_name.c_str(),"a");
560 chmod(logfile_name.c_str(), 0600);
561 // output current time
562 char outstr[200];
563 time_t t = time(NULL);
564 struct tm *tmp = localtime(&t);
565 strftime(outstr, sizeof(outstr), "%F %T", tmp);
566 fprintf(term_out, "\nLog started: ");
9b5d79ec 567 fprintf(term_out, "%s", outstr);
2e1715ea
MV
568 fprintf(term_out, "\n");
569 }
570 return true;
571}
887f5036
DK
572 /*}}}*/
573// DPkg::CloseLog /*{{{*/
2e1715ea
MV
574bool pkgDPkgPM::CloseLog()
575{
576 if(term_out)
577 {
578 char outstr[200];
579 time_t t = time(NULL);
580 struct tm *tmp = localtime(&t);
581 strftime(outstr, sizeof(outstr), "%F %T", tmp);
8398ac36 582 fprintf(term_out, "Log ended: ");
9b5d79ec 583 fprintf(term_out, "%s", outstr);
2e1715ea
MV
584 fprintf(term_out, "\n");
585 fclose(term_out);
586 }
587 term_out = NULL;
588 return true;
589}
887f5036 590 /*}}}*/
919e5852
OS
591/*{{{*/
592// This implements a racy version of pselect for those architectures
593// that don't have a working implementation.
594// FIXME: Probably can be removed on Lenny+1
595static int racy_pselect(int nfds, fd_set *readfds, fd_set *writefds,
596 fd_set *exceptfds, const struct timespec *timeout,
597 const sigset_t *sigmask)
598{
599 sigset_t origmask;
600 struct timeval tv;
601 int retval;
602
f6b37f38
OS
603 tv.tv_sec = timeout->tv_sec;
604 tv.tv_usec = timeout->tv_nsec/1000;
919e5852 605
f6b37f38 606 sigprocmask(SIG_SETMASK, sigmask, &origmask);
919e5852
OS
607 retval = select(nfds, readfds, writefds, exceptfds, &tv);
608 sigprocmask(SIG_SETMASK, &origmask, 0);
609 return retval;
610}
611/*}}}*/
03e39e59
AL
612// DPkgPM::Go - Run the sequence /*{{{*/
613// ---------------------------------------------------------------------
75ef8f14
MV
614/* This globs the operations and calls dpkg
615 *
616 * If it is called with "OutStatusFd" set to a valid file descriptor
617 * apt will report the install progress over this fd. It maps the
618 * dpkg states a package goes through to human readable (and i10n-able)
619 * names and calculates a percentage for each step.
620*/
621bool pkgDPkgPM::Go(int OutStatusFd)
03e39e59 622{
17745b02
MV
623 fd_set rfds;
624 struct timespec tv;
625 sigset_t sigmask;
626 sigset_t original_sigmask;
627
887f5036
DK
628 unsigned int const MaxArgs = _config->FindI("Dpkg::MaxArgs",8*1024);
629 unsigned int const MaxArgBytes = _config->FindI("Dpkg::MaxArgBytes",32*1024);
630 bool const NoTriggers = _config->FindB("DPkg::NoTriggers",false);
aff4e2f1 631
6dd55be7
AL
632 if (RunScripts("DPkg::Pre-Invoke") == false)
633 return false;
db0c350f
AL
634
635 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
636 return false;
fc2d32c0 637
3e9c4f70
DK
638 // support subpressing of triggers processing for special
639 // cases like d-i that runs the triggers handling manually
640 if(_config->FindB("DPkg::ConfigurePending",_config->FindB("DPkg::NoConfigure",false)) == true)
641 List.push_back(Item(Item::ConfigurePending,PkgIterator()));
642
75ef8f14
MV
643 // map the dpkg states to the operations that are performed
644 // (this is sorted in the same way as Item::Ops)
9d06bc80 645 static const struct DpkgState DpkgStatesOpMap[][7] = {
75ef8f14
MV
646 // Install operation
647 {
21e1008e
MV
648 {"half-installed", N_("Preparing %s")},
649 {"unpacked", N_("Unpacking %s") },
75ef8f14
MV
650 {NULL, NULL}
651 },
652 // Configure operation
653 {
21e1008e
MV
654 {"unpacked",N_("Preparing to configure %s") },
655 {"half-configured", N_("Configuring %s") },
656 { "installed", N_("Installed %s")},
75ef8f14
MV
657 {NULL, NULL}
658 },
659 // Remove operation
660 {
21e1008e
MV
661 {"half-configured", N_("Preparing for removal of %s")},
662 {"half-installed", N_("Removing %s")},
663 {"config-files", N_("Removed %s")},
75ef8f14
MV
664 {NULL, NULL}
665 },
666 // Purge operation
667 {
21e1008e
MV
668 {"config-files", N_("Preparing to completely remove %s")},
669 {"not-installed", N_("Completely removed %s")},
75ef8f14
MV
670 {NULL, NULL}
671 },
672 };
db0c350f 673
75ef8f14
MV
674 // init the PackageOps map, go over the list of packages that
675 // that will be [installed|configured|removed|purged] and add
676 // them to the PackageOps map (the dpkg states it goes through)
677 // and the PackageOpsTranslations (human readable strings)
887f5036 678 for (vector<Item>::const_iterator I = List.begin(); I != List.end();I++)
75ef8f14 679 {
3e9c4f70
DK
680 if((*I).Pkg.end() == true)
681 continue;
682
887f5036 683 string const name = (*I).Pkg.Name();
75ef8f14
MV
684 PackageOpsDone[name] = 0;
685 for(int i=0; (DpkgStatesOpMap[(*I).Op][i]).state != NULL; i++)
686 {
687 PackageOps[name].push_back(DpkgStatesOpMap[(*I).Op][i]);
ff56e980 688 PackagesTotal++;
75ef8f14 689 }
887f5036 690 }
75ef8f14 691
9983591d
OS
692 stdin_is_dev_null = false;
693
ff56e980 694 // create log
2e1715ea 695 OpenLog();
ff56e980 696
75ef8f14 697 // this loop is runs once per operation
887f5036 698 for (vector<Item>::const_iterator I = List.begin(); I != List.end();)
03e39e59 699 {
887f5036 700 vector<Item>::const_iterator J = I;
599d6ad5
MV
701 for (; J != List.end() && J->Op == I->Op; J++)
702 /* nothing */;
30e1eab5 703
03e39e59 704 // Generate the argument list
aff4e2f1 705 const char *Args[MaxArgs + 50];
599d6ad5
MV
706
707 // Now check if we are within the MaxArgs limit
708 //
709 // this code below is problematic, because it may happen that
710 // the argument list is split in a way that A depends on B
711 // and they are in the same "--configure A B" run
712 // - with the split they may now be configured in different
713 // runs
aff4e2f1
AL
714 if (J - I > (signed)MaxArgs)
715 J = I + MaxArgs;
03e39e59 716
30e1eab5
AL
717 unsigned int n = 0;
718 unsigned long Size = 0;
887f5036 719 string const Tmp = _config->Find("Dir::Bin::dpkg","dpkg");
50914ffa 720 Args[n++] = Tmp.c_str();
30e1eab5 721 Size += strlen(Args[n-1]);
03e39e59 722
6dd55be7
AL
723 // Stick in any custom dpkg options
724 Configuration::Item const *Opts = _config->Tree("DPkg::Options");
725 if (Opts != 0)
726 {
727 Opts = Opts->Child;
728 for (; Opts != 0; Opts = Opts->Next)
729 {
730 if (Opts->Value.empty() == true)
731 continue;
732 Args[n++] = Opts->Value.c_str();
733 Size += Opts->Value.length();
734 }
735 }
736
007dc9e0 737 char status_fd_buf[20];
75ef8f14
MV
738 int fd[2];
739 pipe(fd);
740
741 Args[n++] = "--status-fd";
742 Size += strlen(Args[n-1]);
743 snprintf(status_fd_buf,sizeof(status_fd_buf),"%i", fd[1]);
744 Args[n++] = status_fd_buf;
745 Size += strlen(Args[n-1]);
007dc9e0 746
03e39e59
AL
747 switch (I->Op)
748 {
749 case Item::Remove:
750 Args[n++] = "--force-depends";
30e1eab5 751 Size += strlen(Args[n-1]);
03e39e59 752 Args[n++] = "--force-remove-essential";
30e1eab5 753 Size += strlen(Args[n-1]);
03e39e59 754 Args[n++] = "--remove";
30e1eab5 755 Size += strlen(Args[n-1]);
03e39e59
AL
756 break;
757
fc4b5c9f
AL
758 case Item::Purge:
759 Args[n++] = "--force-depends";
760 Size += strlen(Args[n-1]);
761 Args[n++] = "--force-remove-essential";
762 Size += strlen(Args[n-1]);
763 Args[n++] = "--purge";
764 Size += strlen(Args[n-1]);
765 break;
766
03e39e59
AL
767 case Item::Configure:
768 Args[n++] = "--configure";
30e1eab5 769 Size += strlen(Args[n-1]);
03e39e59 770 break;
3e9c4f70
DK
771
772 case Item::ConfigurePending:
773 Args[n++] = "--configure";
774 Size += strlen(Args[n-1]);
775 Args[n++] = "--pending";
776 Size += strlen(Args[n-1]);
777 break;
778
03e39e59
AL
779 case Item::Install:
780 Args[n++] = "--unpack";
30e1eab5 781 Size += strlen(Args[n-1]);
857a1d4a
MV
782 Args[n++] = "--auto-deconfigure";
783 Size += strlen(Args[n-1]);
03e39e59
AL
784 break;
785 }
3e9c4f70
DK
786
787 if (NoTriggers == true && I->Op != Item::ConfigurePending)
788 {
789 Args[n++] = "--no-triggers";
790 Size += strlen(Args[n-1]);
791 }
792
03e39e59
AL
793 // Write in the file or package names
794 if (I->Op == Item::Install)
30e1eab5 795 {
aff4e2f1 796 for (;I != J && Size < MaxArgBytes; I++)
30e1eab5 797 {
cf544e14
AL
798 if (I->File[0] != '/')
799 return _error->Error("Internal Error, Pathname to install is not absolute '%s'",I->File.c_str());
03e39e59 800 Args[n++] = I->File.c_str();
30e1eab5
AL
801 Size += strlen(Args[n-1]);
802 }
803 }
03e39e59 804 else
30e1eab5 805 {
aff4e2f1 806 for (;I != J && Size < MaxArgBytes; I++)
30e1eab5 807 {
3e9c4f70
DK
808 if((*I).Pkg.end() == true)
809 continue;
03e39e59 810 Args[n++] = I->Pkg.Name();
30e1eab5
AL
811 Size += strlen(Args[n-1]);
812 }
813 }
03e39e59 814 Args[n] = 0;
30e1eab5
AL
815 J = I;
816
817 if (_config->FindB("Debug::pkgDPkgPM",false) == true)
818 {
819 for (unsigned int k = 0; k != n; k++)
820 clog << Args[k] << ' ';
821 clog << endl;
822 continue;
823 }
03e39e59 824
03e39e59
AL
825 cout << flush;
826 clog << flush;
827 cerr << flush;
828
829 /* Mask off sig int/quit. We do this because dpkg also does when
830 it forks scripts. What happens is that when you hit ctrl-c it sends
831 it to all processes in the group. Since dpkg ignores the signal
832 it doesn't die but we do! So we must also ignore it */
7f9a6360
AL
833 sighandler_t old_SIGQUIT = signal(SIGQUIT,SIG_IGN);
834 sighandler_t old_SIGINT = signal(SIGINT,SIG_IGN);
d8cb4aa4 835
73e598c3
MV
836 // ignore SIGHUP as well (debian #463030)
837 sighandler_t old_SIGHUP = signal(SIGHUP,SIG_IGN);
838
d8cb4aa4
MV
839 struct termios tt;
840 struct winsize win;
841 int master;
842 int slave;
843
ceabc520 844 // FIXME: setup sensible signal handling (*ick*)
d8cb4aa4
MV
845 tcgetattr(0, &tt);
846 ioctl(0, TIOCGWINSZ, (char *)&win);
51f07d32 847 if (openpty(&master, &slave, NULL, &tt, &win) < 0)
090c6566 848 {
a4cf3665
MV
849 const char *s = _("Can not write log, openpty() "
850 "failed (/dev/pts not mounted?)\n");
851 fprintf(stderr, "%s",s);
852 fprintf(term_out, "%s",s);
853 master = slave = -1;
854 } else {
855 struct termios rtt;
856 rtt = tt;
857 cfmakeraw(&rtt);
858 rtt.c_lflag &= ~ECHO;
17745b02
MV
859 // block SIGTTOU during tcsetattr to prevent a hang if
860 // the process is a member of the background process group
861 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
862 sigemptyset(&sigmask);
863 sigaddset(&sigmask, SIGTTOU);
864 sigprocmask(SIG_BLOCK,&sigmask, &original_sigmask);
a4cf3665 865 tcsetattr(0, TCSAFLUSH, &rtt);
17745b02 866 sigprocmask(SIG_SETMASK, &original_sigmask, 0);
d8cb4aa4
MV
867 }
868
75ef8f14 869 // Fork dpkg
007dc9e0 870 pid_t Child;
75ef8f14 871 _config->Set("APT::Keep-Fds::",fd[1]);
ccd8e28f
MV
872 // send status information that we are about to fork dpkg
873 if(OutStatusFd > 0) {
874 ostringstream status;
875 status << "pmstatus:dpkg-exec:"
876 << (PackagesDone/float(PackagesTotal)*100.0)
877 << ":" << _("Running dpkg")
878 << endl;
879 write(OutStatusFd, status.str().c_str(), status.str().size());
880 }
75ef8f14 881 Child = ExecFork();
6dd55be7 882
03e39e59
AL
883 // This is the child
884 if (Child == 0)
885 {
a4cf3665
MV
886 if(slave >= 0 && master >= 0)
887 {
888 setsid();
889 ioctl(slave, TIOCSCTTY, 0);
890 close(master);
891 dup2(slave, 0);
892 dup2(slave, 1);
893 dup2(slave, 2);
894 close(slave);
895 }
75ef8f14 896 close(fd[0]); // close the read end of the pipe
d8cb4aa4 897
4b7cfe96
MV
898 if (_config->FindDir("DPkg::Chroot-Directory","/") != "/")
899 {
900 std::cerr << "Chrooting into "
901 << _config->FindDir("DPkg::Chroot-Directory")
902 << std::endl;
903 if (chroot(_config->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
904 _exit(100);
905 }
906
cf544e14 907 if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
0dbb95d8 908 _exit(100);
03e39e59 909
421ff807 910 if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
8b5fe26c
AL
911 {
912 int Flags,dummy;
913 if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
914 _exit(100);
915
916 // Discard everything in stdin before forking dpkg
917 if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
918 _exit(100);
919
920 while (read(STDIN_FILENO,&dummy,1) == 1);
921
922 if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
923 _exit(100);
924 }
d8cb4aa4 925
03e39e59
AL
926 /* No Job Control Stop Env is a magic dpkg var that prevents it
927 from using sigstop */
71afbdb5 928 putenv((char *)"DPKG_NO_TSTP=yes");
d568ed2d 929 execvp(Args[0],(char **)Args);
03e39e59 930 cerr << "Could not exec dpkg!" << endl;
0dbb95d8 931 _exit(100);
03e39e59
AL
932 }
933
cebe0287
MV
934 // apply ionice
935 if (_config->FindB("DPkg::UseIoNice", false) == true)
936 ionice(Child);
937
75ef8f14
MV
938 // clear the Keep-Fd again
939 _config->Clear("APT::Keep-Fds",fd[1]);
940
03e39e59
AL
941 // Wait for dpkg
942 int Status = 0;
75ef8f14
MV
943
944 // we read from dpkg here
887f5036 945 int const _dpkgin = fd[0];
75ef8f14
MV
946 close(fd[1]); // close the write end of the pipe
947
a4cf3665
MV
948 if(slave > 0)
949 close(slave);
6191b008 950
97efd303 951 // setups fds
7052511e
MV
952 sigemptyset(&sigmask);
953 sigprocmask(SIG_BLOCK,&sigmask,&original_sigmask);
954
887f5036
DK
955 // the result of the waitpid call
956 int res;
090c6566 957 int select_ret;
75ef8f14
MV
958 while ((res=waitpid(Child,&Status, WNOHANG)) != Child) {
959 if(res < 0) {
960 // FIXME: move this to a function or something, looks ugly here
961 // error handling, waitpid returned -1
962 if (errno == EINTR)
963 continue;
964 RunScripts("DPkg::Post-Invoke");
965
966 // Restore sig int/quit
967 signal(SIGQUIT,old_SIGQUIT);
968 signal(SIGINT,old_SIGINT);
e306ec47 969 signal(SIGHUP,old_SIGHUP);
75ef8f14
MV
970 return _error->Errno("waitpid","Couldn't wait for subprocess");
971 }
d8cb4aa4
MV
972
973 // wait for input or output here
955a6ddb 974 FD_ZERO(&rfds);
9983591d
OS
975 if (!stdin_is_dev_null)
976 FD_SET(0, &rfds);
955a6ddb 977 FD_SET(_dpkgin, &rfds);
a4cf3665
MV
978 if(master >= 0)
979 FD_SET(master, &rfds);
090c6566 980 tv.tv_sec = 1;
7052511e
MV
981 tv.tv_nsec = 0;
982 select_ret = pselect(max(master, _dpkgin)+1, &rfds, NULL, NULL,
983 &tv, &original_sigmask);
919e5852
OS
984 if (select_ret < 0 && (errno == EINVAL || errno == ENOSYS))
985 select_ret = racy_pselect(max(master, _dpkgin)+1, &rfds, NULL,
986 NULL, &tv, &original_sigmask);
da50ba30
MV
987 if (select_ret == 0)
988 continue;
989 else if (select_ret < 0 && errno == EINTR)
990 continue;
991 else if (select_ret < 0)
992 {
993 perror("select() returned error");
994 continue;
995 }
996
a4cf3665 997 if(master >= 0 && FD_ISSET(master, &rfds))
1ba38171 998 DoTerminalPty(master);
a4cf3665 999 if(master >= 0 && FD_ISSET(0, &rfds))
955a6ddb 1000 DoStdin(master);
955a6ddb 1001 if(FD_ISSET(_dpkgin, &rfds))
09fa2df2 1002 DoDpkgStatusFd(_dpkgin, OutStatusFd);
03e39e59 1003 }
75ef8f14 1004 close(_dpkgin);
03e39e59
AL
1005
1006 // Restore sig int/quit
7f9a6360
AL
1007 signal(SIGQUIT,old_SIGQUIT);
1008 signal(SIGINT,old_SIGINT);
d9ec0fac 1009 signal(SIGHUP,old_SIGHUP);
d8cb4aa4 1010
477b5d6c
MV
1011 if(master >= 0)
1012 {
a4cf3665 1013 tcsetattr(0, TCSAFLUSH, &tt);
477b5d6c
MV
1014 close(master);
1015 }
6dd55be7
AL
1016
1017 // Check for an error code.
1018 if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
1019 {
c70496f9
MV
1020 // if it was set to "keep-dpkg-runing" then we won't return
1021 // here but keep the loop going and just report it as a error
1022 // for later
887f5036 1023 bool const stopOnError = _config->FindB("Dpkg::StopOnError",true);
f956efb4 1024
c70496f9
MV
1025 if(stopOnError)
1026 RunScripts("DPkg::Post-Invoke");
1027
1028 if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
1029 _error->Error("Sub-process %s received a segmentation fault.",Args[0]);
1030 else if (WIFEXITED(Status) != 0)
1031 _error->Error("Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
1032 else
1033 _error->Error("Sub-process %s exited unexpectedly",Args[0]);
1034
ff56e980
MV
1035 if(stopOnError)
1036 {
2e1715ea 1037 CloseLog();
c70496f9 1038 return false;
ff56e980 1039 }
6dd55be7 1040 }
03e39e59 1041 }
2e1715ea 1042 CloseLog();
6dd55be7
AL
1043
1044 if (RunScripts("DPkg::Post-Invoke") == false)
1045 return false;
b462d75a
MV
1046
1047 Cache.writeStateFile(NULL);
03e39e59
AL
1048 return true;
1049}
1050 /*}}}*/
281daf46
AL
1051// pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1052// ---------------------------------------------------------------------
1053/* */
1054void pkgDPkgPM::Reset()
1055{
1056 List.erase(List.begin(),List.end());
1057}
1058 /*}}}*/