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