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