]> git.saurik.com Git - apt.git/blame - apt-pkg/deb/dpkgpm.cc
merged from the mvo 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 14#include <apt-pkg/depcache.h>
5e457a93 15#include <apt-pkg/pkgrecords.h>
b2e465d6 16#include <apt-pkg/strutl.h>
a4cf3665 17#include <apti18n.h>
614adaa0 18#include <apt-pkg/fileutl.h>
233b185f 19
03e39e59
AL
20#include <unistd.h>
21#include <stdlib.h>
22#include <fcntl.h>
090c6566 23#include <sys/select.h>
03e39e59
AL
24#include <sys/types.h>
25#include <sys/wait.h>
26#include <signal.h>
27#include <errno.h>
2f0d5dea 28#include <string.h>
db0c350f 29#include <stdio.h>
f7dec19f
DB
30#include <string.h>
31#include <algorithm>
75ef8f14
MV
32#include <sstream>
33#include <map>
34
d8cb4aa4
MV
35#include <termios.h>
36#include <unistd.h>
37#include <sys/ioctl.h>
38#include <pty.h>
39
75ef8f14
MV
40#include <config.h>
41#include <apti18n.h>
b0ebdef5 42 /*}}}*/
233b185f
AL
43
44using namespace std;
03e39e59 45
f7dec19f
DB
46namespace
47{
48 // Maps the dpkg "processing" info to human readable names. Entry 0
49 // of each array is the key, entry 1 is the value.
50 const std::pair<const char *, const char *> PackageProcessingOps[] = {
51 std::make_pair("install", N_("Installing %s")),
52 std::make_pair("configure", N_("Configuring %s")),
53 std::make_pair("remove", N_("Removing %s")),
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/* */
5e457a93 107pkgDPkgPM::pkgDPkgPM(pkgDepCache *Cache)
71afbdb5 108 : pkgPackageManager(Cache), dpkgbuf_pos(0),
ff38d63b 109 term_out(NULL), PackagesDone(0), PackagesTotal(0), pkgFailures(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
128 List.push_back(Item(Item::Install,Pkg,File));
129 return true;
130}
131 /*}}}*/
132// DPkgPM::Configure - Configure a package /*{{{*/
133// ---------------------------------------------------------------------
134/* Add a configure operation to the sequence list */
135bool pkgDPkgPM::Configure(PkgIterator Pkg)
136{
137 if (Pkg.end() == true)
138 return false;
139
140 List.push_back(Item(Item::Configure,Pkg));
141 return true;
142}
143 /*}}}*/
144// DPkgPM::Remove - Remove a package /*{{{*/
145// ---------------------------------------------------------------------
146/* Add a remove operation to the sequence list */
fc4b5c9f 147bool pkgDPkgPM::Remove(PkgIterator Pkg,bool Purge)
03e39e59
AL
148{
149 if (Pkg.end() == true)
150 return false;
151
fc4b5c9f
AL
152 if (Purge == true)
153 List.push_back(Item(Item::Purge,Pkg));
154 else
155 List.push_back(Item(Item::Remove,Pkg));
6dd55be7
AL
156 return true;
157}
158 /*}}}*/
b2e465d6
AL
159// DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
160// ---------------------------------------------------------------------
161/* This is part of the helper script communication interface, it sends
162 very complete information down to the other end of the pipe.*/
163bool pkgDPkgPM::SendV2Pkgs(FILE *F)
164{
165 fprintf(F,"VERSION 2\n");
166
167 /* Write out all of the configuration directives by walking the
168 configuration tree */
169 const Configuration::Item *Top = _config->Tree(0);
170 for (; Top != 0;)
171 {
172 if (Top->Value.empty() == false)
173 {
174 fprintf(F,"%s=%s\n",
175 QuoteString(Top->FullTag(),"=\"\n").c_str(),
176 QuoteString(Top->Value,"\n").c_str());
177 }
178
179 if (Top->Child != 0)
180 {
181 Top = Top->Child;
182 continue;
183 }
184
185 while (Top != 0 && Top->Next == 0)
186 Top = Top->Parent;
187 if (Top != 0)
188 Top = Top->Next;
189 }
190 fprintf(F,"\n");
191
192 // Write out the package actions in order.
193 for (vector<Item>::iterator I = List.begin(); I != List.end(); I++)
194 {
195 pkgDepCache::StateCache &S = Cache[I->Pkg];
196
197 fprintf(F,"%s ",I->Pkg.Name());
198 // Current version
199 if (I->Pkg->CurrentVer == 0)
200 fprintf(F,"- ");
201 else
202 fprintf(F,"%s ",I->Pkg.CurrentVer().VerStr());
203
204 // Show the compare operator
205 // Target version
206 if (S.InstallVer != 0)
207 {
208 int Comp = 2;
209 if (I->Pkg->CurrentVer != 0)
210 Comp = S.InstVerIter(Cache).CompareVer(I->Pkg.CurrentVer());
211 if (Comp < 0)
212 fprintf(F,"> ");
213 if (Comp == 0)
214 fprintf(F,"= ");
215 if (Comp > 0)
216 fprintf(F,"< ");
217 fprintf(F,"%s ",S.InstVerIter(Cache).VerStr());
218 }
219 else
220 fprintf(F,"> - ");
221
222 // Show the filename/operation
223 if (I->Op == Item::Install)
224 {
225 // No errors here..
226 if (I->File[0] != '/')
227 fprintf(F,"**ERROR**\n");
228 else
229 fprintf(F,"%s\n",I->File.c_str());
230 }
231 if (I->Op == Item::Configure)
232 fprintf(F,"**CONFIGURE**\n");
233 if (I->Op == Item::Remove ||
234 I->Op == Item::Purge)
235 fprintf(F,"**REMOVE**\n");
236
237 if (ferror(F) != 0)
238 return false;
239 }
240 return true;
241}
242 /*}}}*/
db0c350f
AL
243// DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
244// ---------------------------------------------------------------------
245/* This looks for a list of scripts to run from the configuration file
246 each one is run and is fed on standard input a list of all .deb files
247 that are due to be installed. */
248bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf)
249{
250 Configuration::Item const *Opts = _config->Tree(Cnf);
251 if (Opts == 0 || Opts->Child == 0)
252 return true;
253 Opts = Opts->Child;
254
255 unsigned int Count = 1;
256 for (; Opts != 0; Opts = Opts->Next, Count++)
257 {
258 if (Opts->Value.empty() == true)
259 continue;
b2e465d6
AL
260
261 // Determine the protocol version
262 string OptSec = Opts->Value;
263 string::size_type Pos;
264 if ((Pos = OptSec.find(' ')) == string::npos || Pos == 0)
265 Pos = OptSec.length();
b2e465d6
AL
266 OptSec = "DPkg::Tools::Options::" + string(Opts->Value.c_str(),Pos);
267
268 unsigned int Version = _config->FindI(OptSec+"::Version",1);
269
db0c350f
AL
270 // Create the pipes
271 int Pipes[2];
272 if (pipe(Pipes) != 0)
273 return _error->Errno("pipe","Failed to create IPC pipe to subprocess");
274 SetCloseExec(Pipes[0],true);
275 SetCloseExec(Pipes[1],true);
276
277 // Purified Fork for running the script
278 pid_t Process = ExecFork();
279 if (Process == 0)
280 {
281 // Setup the FDs
282 dup2(Pipes[0],STDIN_FILENO);
283 SetCloseExec(STDOUT_FILENO,false);
284 SetCloseExec(STDIN_FILENO,false);
285 SetCloseExec(STDERR_FILENO,false);
90ecbd7d
AL
286
287 const char *Args[4];
db0c350f 288 Args[0] = "/bin/sh";
90ecbd7d
AL
289 Args[1] = "-c";
290 Args[2] = Opts->Value.c_str();
291 Args[3] = 0;
db0c350f
AL
292 execv(Args[0],(char **)Args);
293 _exit(100);
294 }
295 close(Pipes[0]);
b2e465d6
AL
296 FILE *F = fdopen(Pipes[1],"w");
297 if (F == 0)
298 return _error->Errno("fdopen","Faild to open new FD");
299
db0c350f 300 // Feed it the filenames.
b2e465d6
AL
301 bool Die = false;
302 if (Version <= 1)
db0c350f 303 {
b2e465d6 304 for (vector<Item>::iterator I = List.begin(); I != List.end(); I++)
db0c350f 305 {
b2e465d6
AL
306 // Only deal with packages to be installed from .deb
307 if (I->Op != Item::Install)
308 continue;
309
310 // No errors here..
311 if (I->File[0] != '/')
312 continue;
313
314 /* Feed the filename of each package that is pending install
315 into the pipe. */
316 fprintf(F,"%s\n",I->File.c_str());
317 if (ferror(F) != 0)
318 {
319 Die = true;
320 break;
321 }
90ecbd7d 322 }
db0c350f 323 }
b2e465d6
AL
324 else
325 Die = !SendV2Pkgs(F);
326
327 fclose(F);
db0c350f
AL
328
329 // Clean up the sub process
330 if (ExecWait(Process,Opts->Value.c_str()) == false)
90ecbd7d 331 return _error->Error("Failure running script %s",Opts->Value.c_str());
db0c350f
AL
332 }
333
334 return true;
335}
ceabc520
MV
336 /*}}}*/
337// DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
338// ---------------------------------------------------------------------
339/*
340*/
341void pkgDPkgPM::DoStdin(int master)
342{
aff87a76
MV
343 unsigned char input_buf[256] = {0,};
344 ssize_t len = read(0, input_buf, sizeof(input_buf));
9983591d
OS
345 if (len)
346 write(master, input_buf, len);
347 else
348 stdin_is_dev_null = true;
ceabc520 349}
03e39e59 350 /*}}}*/
ceabc520
MV
351// DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
352// ---------------------------------------------------------------------
353/*
354 * read the terminal pty and write log
355 */
8ecd1fed 356void pkgDPkgPM::DoTerminalPty(int master)
ceabc520 357{
aff87a76 358 unsigned char term_buf[1024] = {0,0, };
ceabc520 359
aff87a76 360 ssize_t len=read(master, term_buf, sizeof(term_buf));
1fc825bf
MV
361 if(len == -1 && errno == EIO)
362 {
363 // this happens when the child is about to exit, we
364 // give it time to actually exit, otherwise we run
365 // into a race
366 usleep(500000);
367 return;
368 }
369 if(len <= 0)
955a6ddb 370 return;
955a6ddb 371 write(1, term_buf, len);
8da1f029
MV
372 if(term_out)
373 fwrite(term_buf, len, sizeof(char), term_out);
ceabc520 374}
03e39e59 375 /*}}}*/
6191b008
MV
376// DPkgPM::ProcessDpkgStatusBuf /*{{{*/
377// ---------------------------------------------------------------------
378/*
379 */
09fa2df2 380void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd, char *line)
6191b008 381{
09fa2df2
MV
382 // the status we output
383 ostringstream status;
384
385 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
386 std::clog << "got from dpkg '" << line << "'" << std::endl;
387
388
389 /* dpkg sends strings like this:
390 'status: <pkg>: <pkg qstate>'
391 errors look like this:
392 'status: /var/cache/apt/archives/krecipes_0.8.1-0ubuntu1_i386.deb : error : trying to overwrite `/usr/share/doc/kde/HTML/en/krecipes/krectip.png', which is also in package krecipes-data
393 and conffile-prompt like this
394 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
fc2d32c0
MV
395
396 Newer versions of dpkg sent also:
397 'processing: install: pkg'
398 'processing: configure: pkg'
399 'processing: remove: pkg'
400 'processing: trigproc: trigger'
09fa2df2
MV
401
402 */
5279f566 403 char* list[6];
09fa2df2
MV
404 // dpkg sends multiline error messages sometimes (see
405 // #374195 for a example. we should support this by
406 // either patching dpkg to not send multiline over the
407 // statusfd or by rewriting the code here to deal with
408 // it. for now we just ignore it and not crash
409 TokSplitString(':', line, list, sizeof(list)/sizeof(list[0]));
f26fcbc7 410 if( list[0] == NULL || list[1] == NULL || list[2] == NULL)
09fa2df2
MV
411 {
412 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
413 std::clog << "ignoring line: not enough ':'" << std::endl;
414 return;
415 }
f26fcbc7
MV
416 char *pkg = list[1];
417 char *action = _strstrip(list[2]);
09fa2df2 418
fc2d32c0
MV
419 // 'processing' from dpkg looks like
420 // 'processing: action: pkg'
421 if(strncmp(list[0], "processing", strlen("processing")) == 0)
422 {
423 char s[200];
fc2d32c0
MV
424 char *pkg_or_trigger = _strstrip(list[2]);
425 action =_strstrip( list[1]);
f7dec19f
DB
426 const std::pair<const char *, const char *> * const iter =
427 std::find_if(PackageProcessingOpsBegin,
428 PackageProcessingOpsEnd,
429 MatchProcessingOp(action));
430 if(iter == PackageProcessingOpsEnd)
fc2d32c0
MV
431 {
432 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
433 std::clog << "ignoring unknwon action: " << action << std::endl;
434 return;
435 }
f7dec19f 436 snprintf(s, sizeof(s), _(iter->second), pkg_or_trigger);
fc2d32c0
MV
437
438 status << "pmstatus:" << pkg_or_trigger
439 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
440 << ":" << s
441 << endl;
442 if(OutStatusFd > 0)
443 write(OutStatusFd, status.str().c_str(), status.str().size());
444 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
445 std::clog << "send: '" << status.str() << "'" << endl;
446 return;
447 }
448
09fa2df2
MV
449 if(strncmp(action,"error",strlen("error")) == 0)
450 {
d6a4afcb
MV
451 // urgs, sometime has ":" in its error string so that we
452 // end up with the error message split between list[3]
453 // and list[4], e.g. the message:
5279f566 454 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
d6a4afcb 455 // concat them again
5279f566
MV
456 if( list[4] != NULL )
457 list[3][strlen(list[3])] = ':';
d6a4afcb 458
09fa2df2 459 status << "pmerror:" << list[1]
ff56e980 460 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
09fa2df2
MV
461 << ":" << list[3]
462 << endl;
463 if(OutStatusFd > 0)
464 write(OutStatusFd, status.str().c_str(), status.str().size());
465 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
466 std::clog << "send: '" << status.str() << "'" << endl;
f060e833
MV
467 pkgFailures++;
468 WriteApportReport(list[1], list[3]);
09fa2df2
MV
469 return;
470 }
471 if(strncmp(action,"conffile",strlen("conffile")) == 0)
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());
479 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
480 std::clog << "send: '" << status.str() << "'" << endl;
481 return;
482 }
483
484 vector<struct DpkgState> &states = PackageOps[pkg];
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());
507 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
508 std::clog << "send: '" << status.str() << "'" << endl;
509 }
510 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
511 std::clog << "(parsed from dpkg) pkg: " << pkg
512 << " action: " << action << endl;
6191b008
MV
513}
514
515// DPkgPM::DoDpkgStatusFd /*{{{*/
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 /*}}}*/
ceabc520 552
5d053270
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);
5d053270
MV
571 fprintf(term_out, "\n");
572 }
573 return true;
574}
575
576bool pkgDPkgPM::CloseLog()
577{
578 if(term_out)
579 {
580 char outstr[200];
581 time_t t = time(NULL);
582 struct tm *tmp = localtime(&t);
583 strftime(outstr, sizeof(outstr), "%F %T", tmp);
584 fprintf(term_out, "Log ended: ");
9b5d79ec 585 fprintf(term_out, "%s", outstr);
5d053270
MV
586 fprintf(term_out, "\n");
587 fclose(term_out);
588 }
589 term_out = NULL;
590 return true;
591}
592
919e5852
OS
593/*{{{*/
594// This implements a racy version of pselect for those architectures
595// that don't have a working implementation.
596// FIXME: Probably can be removed on Lenny+1
597static int racy_pselect(int nfds, fd_set *readfds, fd_set *writefds,
598 fd_set *exceptfds, const struct timespec *timeout,
599 const sigset_t *sigmask)
600{
601 sigset_t origmask;
602 struct timeval tv;
603 int retval;
604
f6b37f38
OS
605 tv.tv_sec = timeout->tv_sec;
606 tv.tv_usec = timeout->tv_nsec/1000;
919e5852 607
f6b37f38 608 sigprocmask(SIG_SETMASK, sigmask, &origmask);
919e5852
OS
609 retval = select(nfds, readfds, writefds, exceptfds, &tv);
610 sigprocmask(SIG_SETMASK, &origmask, 0);
611 return retval;
612}
613/*}}}*/
ceabc520 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{
07dd557b
MV
626 fd_set rfds;
627 struct timespec tv;
628 sigset_t sigmask;
629 sigset_t original_sigmask;
630
6b8147b8
MZ
631 unsigned int MaxArgs = _config->FindI("Dpkg::MaxArgs",8*1024);
632 unsigned int MaxArgBytes = _config->FindI("Dpkg::MaxArgBytes",32*1024);
870ce08f 633 bool 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
75ef8f14
MV
641 // map the dpkg states to the operations that are performed
642 // (this is sorted in the same way as Item::Ops)
fb7bf91c 643 static const struct DpkgState DpkgStatesOpMap[][7] = {
75ef8f14
MV
644 // Install operation
645 {
1d52ce01
MV
646 {"half-installed", N_("Preparing %s")},
647 {"unpacked", N_("Unpacking %s") },
75ef8f14
MV
648 {NULL, NULL}
649 },
650 // Configure operation
651 {
1d52ce01
MV
652 {"unpacked",N_("Preparing to configure %s") },
653 {"half-configured", N_("Configuring %s") },
654 { "installed", N_("Installed %s")},
75ef8f14
MV
655 {NULL, NULL}
656 },
657 // Remove operation
658 {
1d52ce01
MV
659 {"half-configured", N_("Preparing for removal of %s")},
660 {"half-installed", N_("Removing %s")},
661 {"config-files", N_("Removed %s")},
75ef8f14
MV
662 {NULL, NULL}
663 },
664 // Purge operation
665 {
1d52ce01
MV
666 {"config-files", N_("Preparing to completely remove %s")},
667 {"not-installed", N_("Completely removed %s")},
75ef8f14
MV
668 {NULL, NULL}
669 },
670 };
db0c350f 671
75ef8f14
MV
672 // init the PackageOps map, go over the list of packages that
673 // that will be [installed|configured|removed|purged] and add
674 // them to the PackageOps map (the dpkg states it goes through)
675 // and the PackageOpsTranslations (human readable strings)
676 for (vector<Item>::iterator I = List.begin(); I != List.end();I++)
677 {
678 string name = (*I).Pkg.Name();
679 PackageOpsDone[name] = 0;
680 for(int i=0; (DpkgStatesOpMap[(*I).Op][i]).state != NULL; i++)
681 {
682 PackageOps[name].push_back(DpkgStatesOpMap[(*I).Op][i]);
ff56e980 683 PackagesTotal++;
75ef8f14
MV
684 }
685 }
686
9983591d
OS
687 stdin_is_dev_null = false;
688
ff56e980 689 // create log
5d053270 690 OpenLog();
ff56e980 691
75ef8f14 692 // this loop is runs once per operation
03e39e59
AL
693 for (vector<Item>::iterator I = List.begin(); I != List.end();)
694 {
695 vector<Item>::iterator J = I;
599d6ad5
MV
696 for (; J != List.end() && J->Op == I->Op; J++)
697 /* nothing */;
30e1eab5 698
03e39e59 699 // Generate the argument list
aff4e2f1 700 const char *Args[MaxArgs + 50];
599d6ad5
MV
701
702 // Now check if we are within the MaxArgs limit
703 //
704 // this code below is problematic, because it may happen that
705 // the argument list is split in a way that A depends on B
706 // and they are in the same "--configure A B" run
707 // - with the split they may now be configured in different
708 // runs
aff4e2f1
AL
709 if (J - I > (signed)MaxArgs)
710 J = I + MaxArgs;
03e39e59 711
30e1eab5
AL
712 unsigned int n = 0;
713 unsigned long Size = 0;
43b3b626 714 string Tmp = _config->Find("Dir::Bin::dpkg","dpkg");
50914ffa 715 Args[n++] = Tmp.c_str();
30e1eab5 716 Size += strlen(Args[n-1]);
03e39e59 717
6dd55be7
AL
718 // Stick in any custom dpkg options
719 Configuration::Item const *Opts = _config->Tree("DPkg::Options");
720 if (Opts != 0)
721 {
722 Opts = Opts->Child;
723 for (; Opts != 0; Opts = Opts->Next)
724 {
725 if (Opts->Value.empty() == true)
726 continue;
727 Args[n++] = Opts->Value.c_str();
728 Size += Opts->Value.length();
729 }
730 }
731
007dc9e0 732 char status_fd_buf[20];
75ef8f14
MV
733 int fd[2];
734 pipe(fd);
735
736 Args[n++] = "--status-fd";
737 Size += strlen(Args[n-1]);
738 snprintf(status_fd_buf,sizeof(status_fd_buf),"%i", fd[1]);
739 Args[n++] = status_fd_buf;
740 Size += strlen(Args[n-1]);
007dc9e0 741
03e39e59
AL
742 switch (I->Op)
743 {
744 case Item::Remove:
745 Args[n++] = "--force-depends";
30e1eab5 746 Size += strlen(Args[n-1]);
03e39e59 747 Args[n++] = "--force-remove-essential";
30e1eab5 748 Size += strlen(Args[n-1]);
03e39e59 749 Args[n++] = "--remove";
30e1eab5 750 Size += strlen(Args[n-1]);
03e39e59
AL
751 break;
752
fc4b5c9f
AL
753 case Item::Purge:
754 Args[n++] = "--force-depends";
755 Size += strlen(Args[n-1]);
756 Args[n++] = "--force-remove-essential";
757 Size += strlen(Args[n-1]);
758 Args[n++] = "--purge";
759 Size += strlen(Args[n-1]);
760 break;
761
03e39e59
AL
762 case Item::Configure:
763 Args[n++] = "--configure";
870ce08f
MV
764 if (NoTriggers)
765 Args[n++] = "--no-triggers";
30e1eab5 766 Size += strlen(Args[n-1]);
03e39e59
AL
767 break;
768
769 case Item::Install:
770 Args[n++] = "--unpack";
30e1eab5 771 Size += strlen(Args[n-1]);
857a1d4a
MV
772 Args[n++] = "--auto-deconfigure";
773 Size += strlen(Args[n-1]);
03e39e59
AL
774 break;
775 }
776
777 // Write in the file or package names
778 if (I->Op == Item::Install)
30e1eab5 779 {
aff4e2f1 780 for (;I != J && Size < MaxArgBytes; I++)
30e1eab5 781 {
cf544e14
AL
782 if (I->File[0] != '/')
783 return _error->Error("Internal Error, Pathname to install is not absolute '%s'",I->File.c_str());
03e39e59 784 Args[n++] = I->File.c_str();
30e1eab5
AL
785 Size += strlen(Args[n-1]);
786 }
787 }
03e39e59 788 else
30e1eab5 789 {
aff4e2f1 790 for (;I != J && Size < MaxArgBytes; I++)
30e1eab5 791 {
03e39e59 792 Args[n++] = I->Pkg.Name();
30e1eab5
AL
793 Size += strlen(Args[n-1]);
794 }
795 }
03e39e59 796 Args[n] = 0;
30e1eab5
AL
797 J = I;
798
799 if (_config->FindB("Debug::pkgDPkgPM",false) == true)
800 {
801 for (unsigned int k = 0; k != n; k++)
802 clog << Args[k] << ' ';
803 clog << endl;
804 continue;
805 }
03e39e59 806
03e39e59
AL
807 cout << flush;
808 clog << flush;
809 cerr << flush;
810
811 /* Mask off sig int/quit. We do this because dpkg also does when
812 it forks scripts. What happens is that when you hit ctrl-c it sends
813 it to all processes in the group. Since dpkg ignores the signal
814 it doesn't die but we do! So we must also ignore it */
7f9a6360
AL
815 sighandler_t old_SIGQUIT = signal(SIGQUIT,SIG_IGN);
816 sighandler_t old_SIGINT = signal(SIGINT,SIG_IGN);
d8cb4aa4 817
6e7f872d
MV
818 // ignore SIGHUP as well (debian #463030)
819 sighandler_t old_SIGHUP = signal(SIGHUP,SIG_IGN);
820
d8cb4aa4
MV
821 struct termios tt;
822 struct winsize win;
823 int master;
824 int slave;
825
ceabc520 826 // FIXME: setup sensible signal handling (*ick*)
d8cb4aa4
MV
827 tcgetattr(0, &tt);
828 ioctl(0, TIOCGWINSZ, (char *)&win);
494c293c 829 if (openpty(&master, &slave, NULL, &tt, &win) < 0)
090c6566 830 {
a4cf3665
MV
831 const char *s = _("Can not write log, openpty() "
832 "failed (/dev/pts not mounted?)\n");
833 fprintf(stderr, "%s",s);
834 fprintf(term_out, "%s",s);
835 master = slave = -1;
836 } else {
837 struct termios rtt;
838 rtt = tt;
839 cfmakeraw(&rtt);
840 rtt.c_lflag &= ~ECHO;
07dd557b
MV
841 // block SIGTTOU during tcsetattr to prevent a hang if
842 // the process is a member of the background process group
843 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
844 sigemptyset(&sigmask);
845 sigaddset(&sigmask, SIGTTOU);
846 sigprocmask(SIG_BLOCK,&sigmask, &original_sigmask);
a4cf3665 847 tcsetattr(0, TCSAFLUSH, &rtt);
07dd557b 848 sigprocmask(SIG_SETMASK, &original_sigmask, 0);
d8cb4aa4
MV
849 }
850
75ef8f14 851 // Fork dpkg
007dc9e0 852 pid_t Child;
75ef8f14 853 _config->Set("APT::Keep-Fds::",fd[1]);
ccd8e28f
MV
854 // send status information that we are about to fork dpkg
855 if(OutStatusFd > 0) {
856 ostringstream status;
857 status << "pmstatus:dpkg-exec:"
858 << (PackagesDone/float(PackagesTotal)*100.0)
859 << ":" << _("Running dpkg")
860 << endl;
861 write(OutStatusFd, status.str().c_str(), status.str().size());
862 }
75ef8f14 863 Child = ExecFork();
6dd55be7 864
03e39e59
AL
865 // This is the child
866 if (Child == 0)
867 {
a4cf3665
MV
868 if(slave >= 0 && master >= 0)
869 {
870 setsid();
871 ioctl(slave, TIOCSCTTY, 0);
872 close(master);
873 dup2(slave, 0);
874 dup2(slave, 1);
875 dup2(slave, 2);
876 close(slave);
877 }
75ef8f14 878 close(fd[0]); // close the read end of the pipe
d8cb4aa4 879
4b7cfe96
MV
880 if (_config->FindDir("DPkg::Chroot-Directory","/") != "/")
881 {
882 std::cerr << "Chrooting into "
883 << _config->FindDir("DPkg::Chroot-Directory")
884 << std::endl;
885 if (chroot(_config->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
886 _exit(100);
887 }
888
cf544e14 889 if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
0dbb95d8 890 _exit(100);
03e39e59 891
421ff807 892 if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
8b5fe26c
AL
893 {
894 int Flags,dummy;
895 if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
896 _exit(100);
897
898 // Discard everything in stdin before forking dpkg
899 if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
900 _exit(100);
901
902 while (read(STDIN_FILENO,&dummy,1) == 1);
903
904 if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
905 _exit(100);
906 }
d8cb4aa4 907
03e39e59
AL
908 /* No Job Control Stop Env is a magic dpkg var that prevents it
909 from using sigstop */
71afbdb5 910 putenv((char *)"DPKG_NO_TSTP=yes");
d568ed2d 911 execvp(Args[0],(char **)Args);
03e39e59 912 cerr << "Could not exec dpkg!" << endl;
0dbb95d8 913 _exit(100);
03e39e59
AL
914 }
915
cebe0287
MV
916 // apply ionice
917 if (_config->FindB("DPkg::UseIoNice", false) == true)
918 ionice(Child);
919
75ef8f14
MV
920 // clear the Keep-Fd again
921 _config->Clear("APT::Keep-Fds",fd[1]);
922
03e39e59
AL
923 // Wait for dpkg
924 int Status = 0;
75ef8f14
MV
925
926 // we read from dpkg here
927 int _dpkgin = fd[0];
75ef8f14
MV
928 close(fd[1]); // close the write end of the pipe
929
75ef8f14
MV
930 // the result of the waitpid call
931 int res;
a4cf3665
MV
932 if(slave > 0)
933 close(slave);
75ef8f14 934
97efd303 935 // setups fds
1fc825bf
MV
936 sigemptyset(&sigmask);
937 sigprocmask(SIG_BLOCK,&sigmask,&original_sigmask);
938
090c6566 939 int select_ret;
75ef8f14
MV
940 while ((res=waitpid(Child,&Status, WNOHANG)) != Child) {
941 if(res < 0) {
942 // FIXME: move this to a function or something, looks ugly here
943 // error handling, waitpid returned -1
944 if (errno == EINTR)
945 continue;
946 RunScripts("DPkg::Post-Invoke");
947
948 // Restore sig int/quit
949 signal(SIGQUIT,old_SIGQUIT);
950 signal(SIGINT,old_SIGINT);
1a853738 951 signal(SIGHUP,old_SIGHUP);
75ef8f14
MV
952 return _error->Errno("waitpid","Couldn't wait for subprocess");
953 }
d8cb4aa4 954 // wait for input or output here
955a6ddb 955 FD_ZERO(&rfds);
9983591d
OS
956 if (!stdin_is_dev_null)
957 FD_SET(0, &rfds);
955a6ddb 958 FD_SET(_dpkgin, &rfds);
a4cf3665
MV
959 if(master >= 0)
960 FD_SET(master, &rfds);
090c6566 961 tv.tv_sec = 1;
1fc825bf
MV
962 tv.tv_nsec = 0;
963 select_ret = pselect(max(master, _dpkgin)+1, &rfds, NULL, NULL,
964 &tv, &original_sigmask);
919e5852
OS
965 if (select_ret < 0 && (errno == EINVAL || errno == ENOSYS))
966 select_ret = racy_pselect(max(master, _dpkgin)+1, &rfds, NULL,
967 NULL, &tv, &original_sigmask);
da50ba30 968 if (select_ret == 0)
5d053270
MV
969 continue;
970 else if (select_ret < 0 && errno == EINTR)
971 continue;
972 else if (select_ret < 0)
973 {
974 perror("select() returned error");
975 continue;
976 }
da50ba30 977
a4cf3665 978 if(master >= 0 && FD_ISSET(master, &rfds))
1ba38171 979 DoTerminalPty(master);
a4cf3665 980 if(master >= 0 && FD_ISSET(0, &rfds))
955a6ddb 981 DoStdin(master);
955a6ddb 982 if(FD_ISSET(_dpkgin, &rfds))
09fa2df2 983 DoDpkgStatusFd(_dpkgin, OutStatusFd);
03e39e59 984 }
75ef8f14 985 close(_dpkgin);
03e39e59
AL
986
987 // Restore sig int/quit
7f9a6360
AL
988 signal(SIGQUIT,old_SIGQUIT);
989 signal(SIGINT,old_SIGINT);
4e648e0b 990 signal(SIGHUP,old_SIGHUP);
d8cb4aa4 991
c771f6d9
MV
992 if(master >= 0)
993 {
a4cf3665 994 tcsetattr(0, TCSAFLUSH, &tt);
c771f6d9
MV
995 close(master);
996 }
6dd55be7
AL
997
998 // Check for an error code.
999 if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
1000 {
c70496f9
MV
1001 // if it was set to "keep-dpkg-runing" then we won't return
1002 // here but keep the loop going and just report it as a error
1003 // for later
1004 bool stopOnError = _config->FindB("Dpkg::StopOnError",true);
f956efb4 1005
c70496f9
MV
1006 if(stopOnError)
1007 RunScripts("DPkg::Post-Invoke");
1008
1009 if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
1010 _error->Error("Sub-process %s received a segmentation fault.",Args[0]);
1011 else if (WIFEXITED(Status) != 0)
1012 _error->Error("Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
1013 else
1014 _error->Error("Sub-process %s exited unexpectedly",Args[0]);
1015
ff56e980
MV
1016 if(stopOnError)
1017 {
5d053270 1018 CloseLog();
c70496f9 1019 return false;
ff56e980 1020 }
6dd55be7 1021 }
03e39e59 1022 }
5d053270 1023 CloseLog();
6dd55be7
AL
1024
1025 if (RunScripts("DPkg::Post-Invoke") == false)
1026 return false;
496d5c70
MV
1027
1028 Cache.writeStateFile(NULL);
03e39e59
AL
1029 return true;
1030}
1031 /*}}}*/
281daf46
AL
1032// pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1033// ---------------------------------------------------------------------
1034/* */
1035void pkgDPkgPM::Reset()
1036{
1037 List.erase(List.begin(),List.end());
1038}
1039 /*}}}*/
5e457a93
MV
1040// pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1041// ---------------------------------------------------------------------
1042/* */
1043void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
1044{
1045 string pkgname, reportfile, srcpkgname, pkgver, arch;
1046 string::size_type pos;
1047 FILE *report;
1048
1049 if (_config->FindB("Dpkg::ApportFailureReport",true) == false)
ff38d63b
MV
1050 {
1051 std::clog << "configured to not write apport reports" << std::endl;
5e457a93 1052 return;
ff38d63b 1053 }
5e457a93 1054
d6a4afcb 1055 // only report the first errors
5273f1bf 1056 if(pkgFailures > _config->FindI("APT::Apport::MaxReports", 3))
ff38d63b
MV
1057 {
1058 std::clog << _("No apport report written because MaxReports is reached already") << std::endl;
5e457a93 1059 return;
ff38d63b 1060 }
5e457a93 1061
d6a4afcb
MV
1062 // check if its not a follow up error
1063 const char *needle = dgettext("dpkg", "dependency problems - leaving unconfigured");
1064 if(strstr(errormsg, needle) != NULL) {
1065 std::clog << _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl;
1066 return;
1067 }
1068
2f0d5dea
MV
1069 // do not report disk-full failures
1070 if(strstr(errormsg, strerror(ENOSPC)) != NULL) {
1071 std::clog << _("No apport report written because the error message indicates a disk full error") << std::endl;
1072 return;
1073 }
1074
3024a85e
MV
1075 // do not report out-of-memory failures
1076 if(strstr(errormsg, strerror(ENOMEM)) != NULL) {
1077 std::clog << _("No apport report written because the error message indicates a out of memory error") << std::endl;
1078 return;
1079 }
1080
076c46e5
MZ
1081 // do not report dpkg I/O errors
1082 // XXX - this message is localized, but this only matches the English version. This is better than nothing.
1083 if(strstr(errormsg, "short read in buffer_copy (")) {
1084 std::clog << _("No apport report written because the error message indicates a dpkg I/O error") << std::endl;
1085 return;
1086 }
1087
5e457a93
MV
1088 // get the pkgname and reportfile
1089 pkgname = flNotDir(pkgpath);
25ffa4e8 1090 pos = pkgname.find('_');
5e457a93 1091 if(pos != string::npos)
25ffa4e8 1092 pkgname = pkgname.substr(0, pos);
5e457a93
MV
1093
1094 // find the package versin and source package name
1095 pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
1096 if (Pkg.end() == true)
1097 return;
1098 pkgCache::VerIterator Ver = Cache.GetCandidateVer(Pkg);
5e457a93
MV
1099 if (Ver.end() == true)
1100 return;
986d97bb 1101 pkgver = Ver.VerStr() == NULL ? "unknown" : Ver.VerStr();
5e457a93
MV
1102 pkgRecords Recs(Cache);
1103 pkgRecords::Parser &Parse = Recs.Lookup(Ver.FileList());
1104 srcpkgname = Parse.SourcePkg();
1105 if(srcpkgname.empty())
1106 srcpkgname = pkgname;
1107
1108 // if the file exists already, we check:
1109 // - if it was reported already (touched by apport).
1110 // If not, we do nothing, otherwise
1111 // we overwrite it. This is the same behaviour as apport
1112 // - if we have a report with the same pkgversion already
1113 // then we skip it
1114 reportfile = flCombine("/var/crash",pkgname+".0.crash");
1115 if(FileExists(reportfile))
1116 {
1117 struct stat buf;
1118 char strbuf[255];
1119
1120 // check atime/mtime
1121 stat(reportfile.c_str(), &buf);
1122 if(buf.st_mtime > buf.st_atime)
1123 return;
1124
1125 // check if the existing report is the same version
1126 report = fopen(reportfile.c_str(),"r");
1127 while(fgets(strbuf, sizeof(strbuf), report) != NULL)
1128 {
1129 if(strstr(strbuf,"Package:") == strbuf)
1130 {
1131 char pkgname[255], version[255];
1132 if(sscanf(strbuf, "Package: %s %s", pkgname, version) == 2)
1133 if(strcmp(pkgver.c_str(), version) == 0)
1134 {
1135 fclose(report);
1136 return;
1137 }
1138 }
1139 }
1140 fclose(report);
1141 }
1142
1143 // now write the report
1144 arch = _config->Find("APT::Architecture");
1145 report = fopen(reportfile.c_str(),"w");
1146 if(report == NULL)
1147 return;
1148 if(_config->FindB("DPkgPM::InitialReportOnly",false) == true)
1149 chmod(reportfile.c_str(), 0);
1150 else
1151 chmod(reportfile.c_str(), 0600);
1152 fprintf(report, "ProblemType: Package\n");
1153 fprintf(report, "Architecture: %s\n", arch.c_str());
1154 time_t now = time(NULL);
1155 fprintf(report, "Date: %s" , ctime(&now));
1156 fprintf(report, "Package: %s %s\n", pkgname.c_str(), pkgver.c_str());
1157 fprintf(report, "SourcePackage: %s\n", srcpkgname.c_str());
1158 fprintf(report, "ErrorMessage:\n %s\n", errormsg);
8ecd1fed
MV
1159
1160 // ensure that the log is flushed
1161 if(term_out)
1162 fflush(term_out);
1163
1164 // attach terminal log it if we have it
1165 string logfile_name = _config->FindFile("Dir::Log::Terminal");
1166 if (!logfile_name.empty())
1167 {
1168 FILE *log = NULL;
1169 char buf[1024];
1170
1171 fprintf(report, "DpkgTerminalLog:\n");
1172 log = fopen(logfile_name.c_str(),"r");
1173 if(log != NULL)
1174 {
1175 while( fgets(buf, sizeof(buf), log) != NULL)
1176 fprintf(report, " %s", buf);
1177 fclose(log);
1178 }
1179 }
76dbdfc7 1180
5c8a2aa8
MV
1181 // log the ordering
1182 const char *ops_str[] = {"Install", "Configure","Remove","Purge"};
1183 fprintf(report, "AptOrdering:\n");
1184 for (vector<Item>::iterator I = List.begin(); I != List.end(); I++)
1185 fprintf(report, " %s: %s\n", (*I).Pkg.Name(), ops_str[(*I).Op]);
1186
76dbdfc7
MV
1187 // attach dmesg log (to learn about segfaults)
1188 if (FileExists("/bin/dmesg"))
1189 {
1190 FILE *log = NULL;
1191 char buf[1024];
1192
1193 fprintf(report, "Dmesg:\n");
1194 log = popen("/bin/dmesg","r");
1195 if(log != NULL)
1196 {
1197 while( fgets(buf, sizeof(buf), log) != NULL)
1198 fprintf(report, " %s", buf);
1199 fclose(log);
1200 }
1201 }
5e457a93 1202 fclose(report);
76dbdfc7 1203
5e457a93
MV
1204}
1205 /*}}}*/