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