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