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