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