]> git.saurik.com Git - apt.git/blame - apt-pkg/deb/dpkgpm.cc
* merged from dpkg-log
[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>
233b185f 17
03e39e59
AL
18#include <unistd.h>
19#include <stdlib.h>
20#include <fcntl.h>
090c6566 21#include <sys/select.h>
03e39e59
AL
22#include <sys/types.h>
23#include <sys/wait.h>
24#include <signal.h>
25#include <errno.h>
db0c350f 26#include <stdio.h>
75ef8f14
MV
27#include <sstream>
28#include <map>
29
d8cb4aa4
MV
30#include <termios.h>
31#include <unistd.h>
32#include <sys/ioctl.h>
33#include <pty.h>
34
75ef8f14
MV
35#include <config.h>
36#include <apti18n.h>
b0ebdef5 37 /*}}}*/
233b185f
AL
38
39using namespace std;
03e39e59 40
09fa2df2
MV
41
42
03e39e59
AL
43// DPkgPM::pkgDPkgPM - Constructor /*{{{*/
44// ---------------------------------------------------------------------
45/* */
5e457a93 46pkgDPkgPM::pkgDPkgPM(pkgDepCache *Cache)
ff56e980 47 : pkgPackageManager(Cache), dpkgbuf_pos(0), PackagesTotal(0), PackagesDone(0)
03e39e59
AL
48{
49}
50 /*}}}*/
51// DPkgPM::pkgDPkgPM - Destructor /*{{{*/
52// ---------------------------------------------------------------------
53/* */
54pkgDPkgPM::~pkgDPkgPM()
55{
56}
57 /*}}}*/
58// DPkgPM::Install - Install a package /*{{{*/
59// ---------------------------------------------------------------------
60/* Add an install operation to the sequence list */
61bool pkgDPkgPM::Install(PkgIterator Pkg,string File)
62{
63 if (File.empty() == true || Pkg.end() == true)
64 return _error->Error("Internal Error, No file name for %s",Pkg.Name());
65
66 List.push_back(Item(Item::Install,Pkg,File));
67 return true;
68}
69 /*}}}*/
70// DPkgPM::Configure - Configure a package /*{{{*/
71// ---------------------------------------------------------------------
72/* Add a configure operation to the sequence list */
73bool pkgDPkgPM::Configure(PkgIterator Pkg)
74{
75 if (Pkg.end() == true)
76 return false;
77
78 List.push_back(Item(Item::Configure,Pkg));
79 return true;
80}
81 /*}}}*/
82// DPkgPM::Remove - Remove a package /*{{{*/
83// ---------------------------------------------------------------------
84/* Add a remove operation to the sequence list */
fc4b5c9f 85bool pkgDPkgPM::Remove(PkgIterator Pkg,bool Purge)
03e39e59
AL
86{
87 if (Pkg.end() == true)
88 return false;
89
fc4b5c9f
AL
90 if (Purge == true)
91 List.push_back(Item(Item::Purge,Pkg));
92 else
93 List.push_back(Item(Item::Remove,Pkg));
6dd55be7
AL
94 return true;
95}
96 /*}}}*/
97// DPkgPM::RunScripts - Run a set of scripts /*{{{*/
98// ---------------------------------------------------------------------
99/* This looks for a list of script sto run from the configuration file,
100 each one is run with system from a forked child. */
101bool pkgDPkgPM::RunScripts(const char *Cnf)
102{
103 Configuration::Item const *Opts = _config->Tree(Cnf);
104 if (Opts == 0 || Opts->Child == 0)
105 return true;
106 Opts = Opts->Child;
107
108 // Fork for running the system calls
54676e1a 109 pid_t Child = ExecFork();
6dd55be7
AL
110
111 // This is the child
112 if (Child == 0)
113 {
6dd55be7
AL
114 if (chdir("/tmp/") != 0)
115 _exit(100);
116
6dd55be7
AL
117 unsigned int Count = 1;
118 for (; Opts != 0; Opts = Opts->Next, Count++)
119 {
120 if (Opts->Value.empty() == true)
121 continue;
122
123 if (system(Opts->Value.c_str()) != 0)
124 _exit(100+Count);
125 }
126 _exit(0);
127 }
128
129 // Wait for the child
130 int Status = 0;
131 while (waitpid(Child,&Status,0) != Child)
132 {
133 if (errno == EINTR)
134 continue;
135 return _error->Errno("waitpid","Couldn't wait for subprocess");
136 }
137
138 // Restore sig int/quit
139 signal(SIGQUIT,SIG_DFL);
140 signal(SIGINT,SIG_DFL);
ddc1d8d0 141
6dd55be7
AL
142 // Check for an error code.
143 if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
144 {
145 unsigned int Count = WEXITSTATUS(Status);
146 if (Count > 100)
147 {
148 Count -= 100;
149 for (; Opts != 0 && Count != 1; Opts = Opts->Next, Count--);
cf544e14 150 _error->Error("Problem executing scripts %s '%s'",Cnf,Opts->Value.c_str());
6dd55be7
AL
151 }
152
153 return _error->Error("Sub-process returned an error code");
154 }
155
03e39e59
AL
156 return true;
157}
db0c350f 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 /*}}}*/
338// DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
339// ---------------------------------------------------------------------
340/*
341*/
342void pkgDPkgPM::DoStdin(int master)
343{
955a6ddb
MV
344 char input_buf[256] = {0,};
345 int len = read(0, input_buf, sizeof(input_buf));
346 write(master, input_buf, len);
ceabc520 347}
03e39e59 348 /*}}}*/
ceabc520
MV
349// DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
350// ---------------------------------------------------------------------
351/*
352 * read the terminal pty and write log
353 */
354void pkgDPkgPM::DoTerminalPty(int master, FILE *term_out)
355{
955a6ddb 356 char term_buf[1024] = {0,};
ceabc520 357
955a6ddb
MV
358 int len=read(master, term_buf, sizeof(term_buf));
359 if(len <= 0)
360 return;
955a6ddb 361 write(1, term_buf, len);
8da1f029
MV
362 if(term_out)
363 fwrite(term_buf, len, sizeof(char), term_out);
ceabc520 364}
03e39e59 365 /*}}}*/
6191b008
MV
366// DPkgPM::ProcessDpkgStatusBuf /*{{{*/
367// ---------------------------------------------------------------------
368/*
369 */
09fa2df2 370void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd, char *line)
6191b008 371{
09fa2df2
MV
372 // the status we output
373 ostringstream status;
374
375 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
376 std::clog << "got from dpkg '" << line << "'" << std::endl;
377
378
379 /* dpkg sends strings like this:
380 'status: <pkg>: <pkg qstate>'
381 errors look like this:
382 '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
383 and conffile-prompt like this
384 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
385
386 */
387 char* list[5];
388 // dpkg sends multiline error messages sometimes (see
389 // #374195 for a example. we should support this by
390 // either patching dpkg to not send multiline over the
391 // statusfd or by rewriting the code here to deal with
392 // it. for now we just ignore it and not crash
393 TokSplitString(':', line, list, sizeof(list)/sizeof(list[0]));
394 char *pkg = list[1];
395 char *action = _strstrip(list[2]);
396 if( pkg == NULL || action == NULL)
397 {
398 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
399 std::clog << "ignoring line: not enough ':'" << std::endl;
400 return;
401 }
402
403 if(strncmp(action,"error",strlen("error")) == 0)
404 {
405 status << "pmerror:" << list[1]
ff56e980 406 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
09fa2df2
MV
407 << ":" << list[3]
408 << endl;
409 if(OutStatusFd > 0)
410 write(OutStatusFd, status.str().c_str(), status.str().size());
411 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
412 std::clog << "send: '" << status.str() << "'" << endl;
f060e833
MV
413 pkgFailures++;
414 WriteApportReport(list[1], list[3]);
09fa2df2
MV
415 return;
416 }
417 if(strncmp(action,"conffile",strlen("conffile")) == 0)
418 {
419 status << "pmconffile:" << list[1]
ff56e980 420 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
09fa2df2
MV
421 << ":" << list[3]
422 << endl;
423 if(OutStatusFd > 0)
424 write(OutStatusFd, status.str().c_str(), status.str().size());
425 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
426 std::clog << "send: '" << status.str() << "'" << endl;
427 return;
428 }
429
430 vector<struct DpkgState> &states = PackageOps[pkg];
431 const char *next_action = NULL;
432 if(PackageOpsDone[pkg] < states.size())
433 next_action = states[PackageOpsDone[pkg]].state;
434 // check if the package moved to the next dpkg state
435 if(next_action && (strcmp(action, next_action) == 0))
436 {
437 // only read the translation if there is actually a next
438 // action
439 const char *translation = _(states[PackageOpsDone[pkg]].str);
440 char s[200];
441 snprintf(s, sizeof(s), translation, pkg);
442
443 // we moved from one dpkg state to a new one, report that
444 PackageOpsDone[pkg]++;
ff56e980 445 PackagesDone++;
09fa2df2
MV
446 // build the status str
447 status << "pmstatus:" << pkg
ff56e980 448 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
09fa2df2
MV
449 << ":" << s
450 << endl;
451 if(OutStatusFd > 0)
452 write(OutStatusFd, status.str().c_str(), status.str().size());
453 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
454 std::clog << "send: '" << status.str() << "'" << endl;
455 }
456 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
457 std::clog << "(parsed from dpkg) pkg: " << pkg
458 << " action: " << action << endl;
6191b008
MV
459}
460
461// DPkgPM::DoDpkgStatusFd /*{{{*/
462// ---------------------------------------------------------------------
463/*
464 */
09fa2df2 465void pkgDPkgPM::DoDpkgStatusFd(int statusfd, int OutStatusFd)
6191b008
MV
466{
467 char *p, *q;
468 int len;
469
470 len=read(statusfd, &dpkgbuf[dpkgbuf_pos], sizeof(dpkgbuf)-dpkgbuf_pos);
471 dpkgbuf_pos += len;
472 if(len <= 0)
473 return;
ceabc520 474
6191b008
MV
475 // process line by line if we have a buffer
476 p = q = dpkgbuf;
477 while((q=(char*)memchr(p, '\n', dpkgbuf+dpkgbuf_pos-p)) != NULL)
478 {
479 *q = 0;
09fa2df2 480 ProcessDpkgStatusLine(OutStatusFd, p);
6191b008
MV
481 p=q+1; // continue with next line
482 }
483
484 // now move the unprocessed bits (after the final \n that is now a 0x0)
485 // to the start and update dpkgbuf_pos
486 p = (char*)memrchr(dpkgbuf, 0, dpkgbuf_pos);
487 if(p == NULL)
488 return;
489
490 // we are interessted in the first char *after* 0x0
491 p++;
492
493 // move the unprocessed tail to the start and update pos
494 memmove(dpkgbuf, p, p-dpkgbuf);
495 dpkgbuf_pos = dpkgbuf+dpkgbuf_pos-p;
496}
497 /*}}}*/
ceabc520
MV
498
499
03e39e59
AL
500// DPkgPM::Go - Run the sequence /*{{{*/
501// ---------------------------------------------------------------------
75ef8f14
MV
502/* This globs the operations and calls dpkg
503 *
504 * If it is called with "OutStatusFd" set to a valid file descriptor
505 * apt will report the install progress over this fd. It maps the
506 * dpkg states a package goes through to human readable (and i10n-able)
507 * names and calculates a percentage for each step.
508*/
509bool pkgDPkgPM::Go(int OutStatusFd)
03e39e59 510{
6b8147b8
MZ
511 unsigned int MaxArgs = _config->FindI("Dpkg::MaxArgs",8*1024);
512 unsigned int MaxArgBytes = _config->FindI("Dpkg::MaxArgBytes",32*1024);
aff4e2f1 513
6dd55be7
AL
514 if (RunScripts("DPkg::Pre-Invoke") == false)
515 return false;
db0c350f
AL
516
517 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
518 return false;
75ef8f14 519
75ef8f14
MV
520 // map the dpkg states to the operations that are performed
521 // (this is sorted in the same way as Item::Ops)
522 static const struct DpkgState DpkgStatesOpMap[][5] = {
523 // Install operation
524 {
1d52ce01
MV
525 {"half-installed", N_("Preparing %s")},
526 {"unpacked", N_("Unpacking %s") },
75ef8f14
MV
527 {NULL, NULL}
528 },
529 // Configure operation
530 {
1d52ce01
MV
531 {"unpacked",N_("Preparing to configure %s") },
532 {"half-configured", N_("Configuring %s") },
533 { "installed", N_("Installed %s")},
75ef8f14
MV
534 {NULL, NULL}
535 },
536 // Remove operation
537 {
1d52ce01
MV
538 {"half-configured", N_("Preparing for removal of %s")},
539 {"half-installed", N_("Removing %s")},
540 {"config-files", N_("Removed %s")},
75ef8f14
MV
541 {NULL, NULL}
542 },
543 // Purge operation
544 {
1d52ce01
MV
545 {"config-files", N_("Preparing to completely remove %s")},
546 {"not-installed", N_("Completely removed %s")},
75ef8f14
MV
547 {NULL, NULL}
548 },
549 };
db0c350f 550
75ef8f14
MV
551 // init the PackageOps map, go over the list of packages that
552 // that will be [installed|configured|removed|purged] and add
553 // them to the PackageOps map (the dpkg states it goes through)
554 // and the PackageOpsTranslations (human readable strings)
555 for (vector<Item>::iterator I = List.begin(); I != List.end();I++)
556 {
557 string name = (*I).Pkg.Name();
558 PackageOpsDone[name] = 0;
559 for(int i=0; (DpkgStatesOpMap[(*I).Op][i]).state != NULL; i++)
560 {
561 PackageOps[name].push_back(DpkgStatesOpMap[(*I).Op][i]);
ff56e980 562 PackagesTotal++;
75ef8f14
MV
563 }
564 }
565
ff56e980
MV
566 // create log
567 string logdir = _config->FindDir("Dir::Log");
568 if(not FileExists(logdir))
569 return _error->Error(_("Directory '%s' missing"), logdir.c_str());
570 string logfile_name = flCombine(logdir,
8da1f029
MV
571 _config->Find("Dir::Log::Terminal"));
572 FILE *term_out = NULL;
573 if (!logfile_name.empty())
574 {
575 term_out = fopen(logfile_name.c_str(),"a");
576 chmod(logfile_name.c_str(), 0600);
577 // output current time
578 char outstr[200];
579 time_t t = time(NULL);
580 struct tm *tmp = localtime(&t);
581 strftime(outstr, sizeof(outstr), "%F %T", tmp);
582 fprintf(term_out, "\nLog started: ");
583 fprintf(term_out, outstr);
584 fprintf(term_out, "\n");
585 }
ff56e980 586
75ef8f14 587 // this loop is runs once per operation
03e39e59
AL
588 for (vector<Item>::iterator I = List.begin(); I != List.end();)
589 {
590 vector<Item>::iterator J = I;
591 for (; J != List.end() && J->Op == I->Op; J++);
30e1eab5 592
03e39e59 593 // Generate the argument list
aff4e2f1
AL
594 const char *Args[MaxArgs + 50];
595 if (J - I > (signed)MaxArgs)
596 J = I + MaxArgs;
03e39e59 597
30e1eab5
AL
598 unsigned int n = 0;
599 unsigned long Size = 0;
43b3b626 600 string Tmp = _config->Find("Dir::Bin::dpkg","dpkg");
50914ffa 601 Args[n++] = Tmp.c_str();
30e1eab5 602 Size += strlen(Args[n-1]);
03e39e59 603
6dd55be7
AL
604 // Stick in any custom dpkg options
605 Configuration::Item const *Opts = _config->Tree("DPkg::Options");
606 if (Opts != 0)
607 {
608 Opts = Opts->Child;
609 for (; Opts != 0; Opts = Opts->Next)
610 {
611 if (Opts->Value.empty() == true)
612 continue;
613 Args[n++] = Opts->Value.c_str();
614 Size += Opts->Value.length();
615 }
616 }
617
007dc9e0 618 char status_fd_buf[20];
75ef8f14
MV
619 int fd[2];
620 pipe(fd);
621
622 Args[n++] = "--status-fd";
623 Size += strlen(Args[n-1]);
624 snprintf(status_fd_buf,sizeof(status_fd_buf),"%i", fd[1]);
625 Args[n++] = status_fd_buf;
626 Size += strlen(Args[n-1]);
007dc9e0 627
03e39e59
AL
628 switch (I->Op)
629 {
630 case Item::Remove:
631 Args[n++] = "--force-depends";
30e1eab5 632 Size += strlen(Args[n-1]);
03e39e59 633 Args[n++] = "--force-remove-essential";
30e1eab5 634 Size += strlen(Args[n-1]);
03e39e59 635 Args[n++] = "--remove";
30e1eab5 636 Size += strlen(Args[n-1]);
03e39e59
AL
637 break;
638
fc4b5c9f
AL
639 case Item::Purge:
640 Args[n++] = "--force-depends";
641 Size += strlen(Args[n-1]);
642 Args[n++] = "--force-remove-essential";
643 Size += strlen(Args[n-1]);
644 Args[n++] = "--purge";
645 Size += strlen(Args[n-1]);
646 break;
647
03e39e59
AL
648 case Item::Configure:
649 Args[n++] = "--configure";
30e1eab5 650 Size += strlen(Args[n-1]);
03e39e59
AL
651 break;
652
653 case Item::Install:
654 Args[n++] = "--unpack";
30e1eab5 655 Size += strlen(Args[n-1]);
857a1d4a
MV
656 Args[n++] = "--auto-deconfigure";
657 Size += strlen(Args[n-1]);
03e39e59
AL
658 break;
659 }
660
661 // Write in the file or package names
662 if (I->Op == Item::Install)
30e1eab5 663 {
aff4e2f1 664 for (;I != J && Size < MaxArgBytes; I++)
30e1eab5 665 {
cf544e14
AL
666 if (I->File[0] != '/')
667 return _error->Error("Internal Error, Pathname to install is not absolute '%s'",I->File.c_str());
03e39e59 668 Args[n++] = I->File.c_str();
30e1eab5
AL
669 Size += strlen(Args[n-1]);
670 }
671 }
03e39e59 672 else
30e1eab5 673 {
aff4e2f1 674 for (;I != J && Size < MaxArgBytes; I++)
30e1eab5 675 {
03e39e59 676 Args[n++] = I->Pkg.Name();
30e1eab5
AL
677 Size += strlen(Args[n-1]);
678 }
679 }
03e39e59 680 Args[n] = 0;
30e1eab5
AL
681 J = I;
682
683 if (_config->FindB("Debug::pkgDPkgPM",false) == true)
684 {
685 for (unsigned int k = 0; k != n; k++)
686 clog << Args[k] << ' ';
687 clog << endl;
688 continue;
689 }
03e39e59 690
03e39e59
AL
691 cout << flush;
692 clog << flush;
693 cerr << flush;
694
695 /* Mask off sig int/quit. We do this because dpkg also does when
696 it forks scripts. What happens is that when you hit ctrl-c it sends
697 it to all processes in the group. Since dpkg ignores the signal
698 it doesn't die but we do! So we must also ignore it */
7f9a6360
AL
699 sighandler_t old_SIGQUIT = signal(SIGQUIT,SIG_IGN);
700 sighandler_t old_SIGINT = signal(SIGINT,SIG_IGN);
d8cb4aa4
MV
701
702 struct termios tt;
703 struct winsize win;
704 int master;
705 int slave;
706
ceabc520 707 // FIXME: setup sensible signal handling (*ick*)
d8cb4aa4
MV
708 tcgetattr(0, &tt);
709 ioctl(0, TIOCGWINSZ, (char *)&win);
090c6566
MV
710 if (openpty(&master, &slave, NULL, &tt, &win) < 0)
711 {
d8cb4aa4
MV
712 fprintf(stderr, _("openpty failed\n"));
713 }
714
715 struct termios rtt;
716 rtt = tt;
717 cfmakeraw(&rtt);
718 rtt.c_lflag &= ~ECHO;
719 tcsetattr(0, TCSAFLUSH, &rtt);
720
75ef8f14 721 // Fork dpkg
007dc9e0 722 pid_t Child;
75ef8f14
MV
723 _config->Set("APT::Keep-Fds::",fd[1]);
724 Child = ExecFork();
6dd55be7 725
03e39e59
AL
726 // This is the child
727 if (Child == 0)
728 {
d8cb4aa4
MV
729 setsid();
730 ioctl(slave, TIOCSCTTY, 0);
731 close(master);
732 dup2(slave, 0);
733 dup2(slave, 1);
734 dup2(slave, 2);
735 close(slave);
75ef8f14 736 close(fd[0]); // close the read end of the pipe
d8cb4aa4 737
cf544e14 738 if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
0dbb95d8 739 _exit(100);
03e39e59 740
421ff807 741 if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
8b5fe26c
AL
742 {
743 int Flags,dummy;
744 if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
745 _exit(100);
746
747 // Discard everything in stdin before forking dpkg
748 if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
749 _exit(100);
750
751 while (read(STDIN_FILENO,&dummy,1) == 1);
752
753 if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
754 _exit(100);
755 }
d8cb4aa4
MV
756
757
03e39e59
AL
758 /* No Job Control Stop Env is a magic dpkg var that prevents it
759 from using sigstop */
101030ab 760 putenv("DPKG_NO_TSTP=yes");
d568ed2d 761 execvp(Args[0],(char **)Args);
03e39e59 762 cerr << "Could not exec dpkg!" << endl;
0dbb95d8 763 _exit(100);
03e39e59
AL
764 }
765
75ef8f14
MV
766 // clear the Keep-Fd again
767 _config->Clear("APT::Keep-Fds",fd[1]);
768
03e39e59
AL
769 // Wait for dpkg
770 int Status = 0;
75ef8f14
MV
771
772 // we read from dpkg here
773 int _dpkgin = fd[0];
75ef8f14
MV
774 close(fd[1]); // close the write end of the pipe
775
776 // the read buffers for the communication with dpkg
75ef8f14
MV
777 char buf[2] = {0,0};
778
779 // the result of the waitpid call
780 int res;
d8cb4aa4 781 close(slave);
75ef8f14 782
97efd303 783 // setups fds
090c6566
MV
784 fd_set rfds;
785 struct timeval tv;
786 int select_ret;
75ef8f14
MV
787 while ((res=waitpid(Child,&Status, WNOHANG)) != Child) {
788 if(res < 0) {
789 // FIXME: move this to a function or something, looks ugly here
790 // error handling, waitpid returned -1
791 if (errno == EINTR)
792 continue;
793 RunScripts("DPkg::Post-Invoke");
794
795 // Restore sig int/quit
796 signal(SIGQUIT,old_SIGQUIT);
797 signal(SIGINT,old_SIGINT);
798 return _error->Errno("waitpid","Couldn't wait for subprocess");
799 }
75ef8f14 800
d8cb4aa4 801 // wait for input or output here
955a6ddb
MV
802 FD_ZERO(&rfds);
803 FD_SET(0, &rfds);
804 FD_SET(_dpkgin, &rfds);
805 FD_SET(master, &rfds);
090c6566
MV
806 tv.tv_sec = 1;
807 tv.tv_usec = 0;
7fdafa0f 808 select_ret = select(max(master, _dpkgin)+1, &rfds, NULL, NULL, &tv);
090c6566
MV
809 if (select_ret < 0)
810 std::cerr << "Error in select()" << std::endl;
811 else if (select_ret == 0)
75ef8f14 812 continue;
75ef8f14 813
955a6ddb
MV
814 if(FD_ISSET(master, &rfds))
815 DoTerminalPty(master, term_out);
816 if(FD_ISSET(0, &rfds))
817 DoStdin(master);
955a6ddb 818 if(FD_ISSET(_dpkgin, &rfds))
09fa2df2 819 DoDpkgStatusFd(_dpkgin, OutStatusFd);
03e39e59 820 }
75ef8f14 821 close(_dpkgin);
03e39e59
AL
822
823 // Restore sig int/quit
7f9a6360
AL
824 signal(SIGQUIT,old_SIGQUIT);
825 signal(SIGINT,old_SIGINT);
d8cb4aa4
MV
826
827 tcsetattr(0, TCSAFLUSH, &tt);
6dd55be7
AL
828
829 // Check for an error code.
830 if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
831 {
c70496f9
MV
832 // if it was set to "keep-dpkg-runing" then we won't return
833 // here but keep the loop going and just report it as a error
834 // for later
835 bool stopOnError = _config->FindB("Dpkg::StopOnError",true);
f956efb4 836
c70496f9
MV
837 if(stopOnError)
838 RunScripts("DPkg::Post-Invoke");
839
840 if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
841 _error->Error("Sub-process %s received a segmentation fault.",Args[0]);
842 else if (WIFEXITED(Status) != 0)
843 _error->Error("Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
844 else
845 _error->Error("Sub-process %s exited unexpectedly",Args[0]);
846
ff56e980
MV
847 if(stopOnError)
848 {
b3aac1bb
MV
849 if(term_out)
850 fclose(term_out);
c70496f9 851 return false;
ff56e980 852 }
6dd55be7 853 }
03e39e59 854 }
b3aac1bb
MV
855 if(term_out)
856 fclose(term_out);
6dd55be7
AL
857
858 if (RunScripts("DPkg::Post-Invoke") == false)
859 return false;
03e39e59
AL
860 return true;
861}
862 /*}}}*/
281daf46
AL
863// pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
864// ---------------------------------------------------------------------
865/* */
866void pkgDPkgPM::Reset()
867{
868 List.erase(List.begin(),List.end());
869}
870 /*}}}*/
5e457a93
MV
871// pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
872// ---------------------------------------------------------------------
873/* */
874void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
875{
876 string pkgname, reportfile, srcpkgname, pkgver, arch;
877 string::size_type pos;
878 FILE *report;
879
880 if (_config->FindB("Dpkg::ApportFailureReport",true) == false)
881 return;
882
883 // only report the first error if we are in StopOnError=false mode
884 // to prevent bogus reports
885 if((_config->FindB("Dpkg::StopOnError",true) == false) && pkgFailures > 1)
886 return;
887
888 // get the pkgname and reportfile
889 pkgname = flNotDir(pkgpath);
890 pos = pkgname.rfind('_');
891 if(pos != string::npos)
892 pkgname = string(pkgname, 0, pos);
893
894 // find the package versin and source package name
895 pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
896 if (Pkg.end() == true)
897 return;
898 pkgCache::VerIterator Ver = Cache.GetCandidateVer(Pkg);
899 pkgver = Ver.VerStr();
900 if (Ver.end() == true)
901 return;
902 pkgRecords Recs(Cache);
903 pkgRecords::Parser &Parse = Recs.Lookup(Ver.FileList());
904 srcpkgname = Parse.SourcePkg();
905 if(srcpkgname.empty())
906 srcpkgname = pkgname;
907
908 // if the file exists already, we check:
909 // - if it was reported already (touched by apport).
910 // If not, we do nothing, otherwise
911 // we overwrite it. This is the same behaviour as apport
912 // - if we have a report with the same pkgversion already
913 // then we skip it
914 reportfile = flCombine("/var/crash",pkgname+".0.crash");
915 if(FileExists(reportfile))
916 {
917 struct stat buf;
918 char strbuf[255];
919
920 // check atime/mtime
921 stat(reportfile.c_str(), &buf);
922 if(buf.st_mtime > buf.st_atime)
923 return;
924
925 // check if the existing report is the same version
926 report = fopen(reportfile.c_str(),"r");
927 while(fgets(strbuf, sizeof(strbuf), report) != NULL)
928 {
929 if(strstr(strbuf,"Package:") == strbuf)
930 {
931 char pkgname[255], version[255];
932 if(sscanf(strbuf, "Package: %s %s", pkgname, version) == 2)
933 if(strcmp(pkgver.c_str(), version) == 0)
934 {
935 fclose(report);
936 return;
937 }
938 }
939 }
940 fclose(report);
941 }
942
943 // now write the report
944 arch = _config->Find("APT::Architecture");
945 report = fopen(reportfile.c_str(),"w");
946 if(report == NULL)
947 return;
948 if(_config->FindB("DPkgPM::InitialReportOnly",false) == true)
949 chmod(reportfile.c_str(), 0);
950 else
951 chmod(reportfile.c_str(), 0600);
952 fprintf(report, "ProblemType: Package\n");
953 fprintf(report, "Architecture: %s\n", arch.c_str());
954 time_t now = time(NULL);
955 fprintf(report, "Date: %s" , ctime(&now));
956 fprintf(report, "Package: %s %s\n", pkgname.c_str(), pkgver.c_str());
957 fprintf(report, "SourcePackage: %s\n", srcpkgname.c_str());
958 fprintf(report, "ErrorMessage:\n %s\n", errormsg);
959 fclose(report);
960}
961 /*}}}*/