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