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