]> git.saurik.com Git - apt.git/blame - apt-pkg/deb/dpkgpm.cc
apt-pkg/deb/dpkgpm.{cc,h}:
[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
MV
45pkgDPkgPM::pkgDPkgPM(pkgDepCache *Cache)
46 : pkgPackageManager(Cache), dpkgbuf_pos(0), Total(0), Done(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;
360 fwrite(term_buf, len, sizeof(char), term_out);
361 write(1, term_buf, len);
ceabc520 362}
03e39e59 363 /*}}}*/
6191b008
MV
364// DPkgPM::ProcessDpkgStatusBuf /*{{{*/
365// ---------------------------------------------------------------------
366/*
367 */
09fa2df2 368void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd, char *line)
6191b008 369{
09fa2df2
MV
370 // the status we output
371 ostringstream status;
372
373 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
374 std::clog << "got from dpkg '" << line << "'" << std::endl;
375
376
377 /* dpkg sends strings like this:
378 'status: <pkg>: <pkg qstate>'
379 errors look like this:
380 '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
381 and conffile-prompt like this
382 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
383
384 */
385 char* list[5];
386 // dpkg sends multiline error messages sometimes (see
387 // #374195 for a example. we should support this by
388 // either patching dpkg to not send multiline over the
389 // statusfd or by rewriting the code here to deal with
390 // it. for now we just ignore it and not crash
391 TokSplitString(':', line, list, sizeof(list)/sizeof(list[0]));
392 char *pkg = list[1];
393 char *action = _strstrip(list[2]);
394 if( pkg == NULL || action == NULL)
395 {
396 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
397 std::clog << "ignoring line: not enough ':'" << std::endl;
398 return;
399 }
400
401 if(strncmp(action,"error",strlen("error")) == 0)
402 {
403 status << "pmerror:" << list[1]
404 << ":" << (Done/float(Total)*100.0)
405 << ":" << list[3]
406 << endl;
407 if(OutStatusFd > 0)
408 write(OutStatusFd, status.str().c_str(), status.str().size());
409 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
410 std::clog << "send: '" << status.str() << "'" << endl;
411 return;
412 }
413 if(strncmp(action,"conffile",strlen("conffile")) == 0)
414 {
415 status << "pmconffile:" << list[1]
416 << ":" << (Done/float(Total)*100.0)
417 << ":" << list[3]
418 << endl;
419 if(OutStatusFd > 0)
420 write(OutStatusFd, status.str().c_str(), status.str().size());
421 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
422 std::clog << "send: '" << status.str() << "'" << endl;
423 return;
424 }
425
426 vector<struct DpkgState> &states = PackageOps[pkg];
427 const char *next_action = NULL;
428 if(PackageOpsDone[pkg] < states.size())
429 next_action = states[PackageOpsDone[pkg]].state;
430 // check if the package moved to the next dpkg state
431 if(next_action && (strcmp(action, next_action) == 0))
432 {
433 // only read the translation if there is actually a next
434 // action
435 const char *translation = _(states[PackageOpsDone[pkg]].str);
436 char s[200];
437 snprintf(s, sizeof(s), translation, pkg);
438
439 // we moved from one dpkg state to a new one, report that
440 PackageOpsDone[pkg]++;
441 Done++;
442 // build the status str
443 status << "pmstatus:" << pkg
444 << ":" << (Done/float(Total)*100.0)
445 << ":" << s
446 << endl;
447 if(OutStatusFd > 0)
448 write(OutStatusFd, status.str().c_str(), status.str().size());
449 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
450 std::clog << "send: '" << status.str() << "'" << endl;
451 }
452 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
453 std::clog << "(parsed from dpkg) pkg: " << pkg
454 << " action: " << action << endl;
6191b008
MV
455}
456
457// DPkgPM::DoDpkgStatusFd /*{{{*/
458// ---------------------------------------------------------------------
459/*
460 */
09fa2df2 461void pkgDPkgPM::DoDpkgStatusFd(int statusfd, int OutStatusFd)
6191b008
MV
462{
463 char *p, *q;
464 int len;
465
466 len=read(statusfd, &dpkgbuf[dpkgbuf_pos], sizeof(dpkgbuf)-dpkgbuf_pos);
467 dpkgbuf_pos += len;
468 if(len <= 0)
469 return;
ceabc520 470
6191b008
MV
471 // process line by line if we have a buffer
472 p = q = dpkgbuf;
473 while((q=(char*)memchr(p, '\n', dpkgbuf+dpkgbuf_pos-p)) != NULL)
474 {
475 *q = 0;
09fa2df2 476 ProcessDpkgStatusLine(OutStatusFd, p);
6191b008
MV
477 p=q+1; // continue with next line
478 }
479
480 // now move the unprocessed bits (after the final \n that is now a 0x0)
481 // to the start and update dpkgbuf_pos
482 p = (char*)memrchr(dpkgbuf, 0, dpkgbuf_pos);
483 if(p == NULL)
484 return;
485
486 // we are interessted in the first char *after* 0x0
487 p++;
488
489 // move the unprocessed tail to the start and update pos
490 memmove(dpkgbuf, p, p-dpkgbuf);
491 dpkgbuf_pos = dpkgbuf+dpkgbuf_pos-p;
492}
493 /*}}}*/
ceabc520
MV
494
495
03e39e59
AL
496// DPkgPM::Go - Run the sequence /*{{{*/
497// ---------------------------------------------------------------------
75ef8f14
MV
498/* This globs the operations and calls dpkg
499 *
500 * If it is called with "OutStatusFd" set to a valid file descriptor
501 * apt will report the install progress over this fd. It maps the
502 * dpkg states a package goes through to human readable (and i10n-able)
503 * names and calculates a percentage for each step.
504*/
505bool pkgDPkgPM::Go(int OutStatusFd)
03e39e59 506{
6b8147b8
MZ
507 unsigned int MaxArgs = _config->FindI("Dpkg::MaxArgs",8*1024);
508 unsigned int MaxArgBytes = _config->FindI("Dpkg::MaxArgBytes",32*1024);
aff4e2f1 509
6dd55be7
AL
510 if (RunScripts("DPkg::Pre-Invoke") == false)
511 return false;
db0c350f
AL
512
513 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
514 return false;
75ef8f14 515
75ef8f14
MV
516 // map the dpkg states to the operations that are performed
517 // (this is sorted in the same way as Item::Ops)
518 static const struct DpkgState DpkgStatesOpMap[][5] = {
519 // Install operation
520 {
21e1008e
MV
521 {"half-installed", N_("Preparing %s")},
522 {"unpacked", N_("Unpacking %s") },
75ef8f14
MV
523 {NULL, NULL}
524 },
525 // Configure operation
526 {
21e1008e
MV
527 {"unpacked",N_("Preparing to configure %s") },
528 {"half-configured", N_("Configuring %s") },
529 { "installed", N_("Installed %s")},
75ef8f14
MV
530 {NULL, NULL}
531 },
532 // Remove operation
533 {
21e1008e
MV
534 {"half-configured", N_("Preparing for removal of %s")},
535 {"half-installed", N_("Removing %s")},
536 {"config-files", N_("Removed %s")},
75ef8f14
MV
537 {NULL, NULL}
538 },
539 // Purge operation
540 {
21e1008e
MV
541 {"config-files", N_("Preparing to completely remove %s")},
542 {"not-installed", N_("Completely removed %s")},
75ef8f14
MV
543 {NULL, NULL}
544 },
545 };
db0c350f 546
75ef8f14
MV
547 // init the PackageOps map, go over the list of packages that
548 // that will be [installed|configured|removed|purged] and add
549 // them to the PackageOps map (the dpkg states it goes through)
550 // and the PackageOpsTranslations (human readable strings)
551 for (vector<Item>::iterator I = List.begin(); I != List.end();I++)
552 {
553 string name = (*I).Pkg.Name();
554 PackageOpsDone[name] = 0;
555 for(int i=0; (DpkgStatesOpMap[(*I).Op][i]).state != NULL; i++)
556 {
557 PackageOps[name].push_back(DpkgStatesOpMap[(*I).Op][i]);
558 Total++;
559 }
560 }
561
562 // this loop is runs once per operation
03e39e59
AL
563 for (vector<Item>::iterator I = List.begin(); I != List.end();)
564 {
565 vector<Item>::iterator J = I;
566 for (; J != List.end() && J->Op == I->Op; J++);
30e1eab5 567
03e39e59 568 // Generate the argument list
aff4e2f1
AL
569 const char *Args[MaxArgs + 50];
570 if (J - I > (signed)MaxArgs)
571 J = I + MaxArgs;
03e39e59 572
30e1eab5
AL
573 unsigned int n = 0;
574 unsigned long Size = 0;
43b3b626 575 string Tmp = _config->Find("Dir::Bin::dpkg","dpkg");
50914ffa 576 Args[n++] = Tmp.c_str();
30e1eab5 577 Size += strlen(Args[n-1]);
03e39e59 578
6dd55be7
AL
579 // Stick in any custom dpkg options
580 Configuration::Item const *Opts = _config->Tree("DPkg::Options");
581 if (Opts != 0)
582 {
583 Opts = Opts->Child;
584 for (; Opts != 0; Opts = Opts->Next)
585 {
586 if (Opts->Value.empty() == true)
587 continue;
588 Args[n++] = Opts->Value.c_str();
589 Size += Opts->Value.length();
590 }
591 }
592
007dc9e0 593 char status_fd_buf[20];
75ef8f14
MV
594 int fd[2];
595 pipe(fd);
596
597 Args[n++] = "--status-fd";
598 Size += strlen(Args[n-1]);
599 snprintf(status_fd_buf,sizeof(status_fd_buf),"%i", fd[1]);
600 Args[n++] = status_fd_buf;
601 Size += strlen(Args[n-1]);
007dc9e0 602
03e39e59
AL
603 switch (I->Op)
604 {
605 case Item::Remove:
606 Args[n++] = "--force-depends";
30e1eab5 607 Size += strlen(Args[n-1]);
03e39e59 608 Args[n++] = "--force-remove-essential";
30e1eab5 609 Size += strlen(Args[n-1]);
03e39e59 610 Args[n++] = "--remove";
30e1eab5 611 Size += strlen(Args[n-1]);
03e39e59
AL
612 break;
613
fc4b5c9f
AL
614 case Item::Purge:
615 Args[n++] = "--force-depends";
616 Size += strlen(Args[n-1]);
617 Args[n++] = "--force-remove-essential";
618 Size += strlen(Args[n-1]);
619 Args[n++] = "--purge";
620 Size += strlen(Args[n-1]);
621 break;
622
03e39e59
AL
623 case Item::Configure:
624 Args[n++] = "--configure";
30e1eab5 625 Size += strlen(Args[n-1]);
03e39e59
AL
626 break;
627
628 case Item::Install:
629 Args[n++] = "--unpack";
30e1eab5 630 Size += strlen(Args[n-1]);
857a1d4a
MV
631 Args[n++] = "--auto-deconfigure";
632 Size += strlen(Args[n-1]);
03e39e59
AL
633 break;
634 }
635
636 // Write in the file or package names
637 if (I->Op == Item::Install)
30e1eab5 638 {
aff4e2f1 639 for (;I != J && Size < MaxArgBytes; I++)
30e1eab5 640 {
cf544e14
AL
641 if (I->File[0] != '/')
642 return _error->Error("Internal Error, Pathname to install is not absolute '%s'",I->File.c_str());
03e39e59 643 Args[n++] = I->File.c_str();
30e1eab5
AL
644 Size += strlen(Args[n-1]);
645 }
646 }
03e39e59 647 else
30e1eab5 648 {
aff4e2f1 649 for (;I != J && Size < MaxArgBytes; I++)
30e1eab5 650 {
03e39e59 651 Args[n++] = I->Pkg.Name();
30e1eab5
AL
652 Size += strlen(Args[n-1]);
653 }
654 }
03e39e59 655 Args[n] = 0;
30e1eab5
AL
656 J = I;
657
658 if (_config->FindB("Debug::pkgDPkgPM",false) == true)
659 {
660 for (unsigned int k = 0; k != n; k++)
661 clog << Args[k] << ' ';
662 clog << endl;
663 continue;
664 }
03e39e59 665
03e39e59
AL
666 cout << flush;
667 clog << flush;
668 cerr << flush;
669
670 /* Mask off sig int/quit. We do this because dpkg also does when
671 it forks scripts. What happens is that when you hit ctrl-c it sends
672 it to all processes in the group. Since dpkg ignores the signal
673 it doesn't die but we do! So we must also ignore it */
7f9a6360
AL
674 sighandler_t old_SIGQUIT = signal(SIGQUIT,SIG_IGN);
675 sighandler_t old_SIGINT = signal(SIGINT,SIG_IGN);
d8cb4aa4
MV
676
677 struct termios tt;
678 struct winsize win;
679 int master;
680 int slave;
681
ceabc520 682 // FIXME: setup sensible signal handling (*ick*)
d8cb4aa4
MV
683 tcgetattr(0, &tt);
684 ioctl(0, TIOCGWINSZ, (char *)&win);
090c6566
MV
685 if (openpty(&master, &slave, NULL, &tt, &win) < 0)
686 {
d8cb4aa4
MV
687 fprintf(stderr, _("openpty failed\n"));
688 }
689
690 struct termios rtt;
691 rtt = tt;
692 cfmakeraw(&rtt);
693 rtt.c_lflag &= ~ECHO;
694 tcsetattr(0, TCSAFLUSH, &rtt);
695
75ef8f14 696 // Fork dpkg
007dc9e0 697 pid_t Child;
75ef8f14
MV
698 _config->Set("APT::Keep-Fds::",fd[1]);
699 Child = ExecFork();
6dd55be7 700
03e39e59
AL
701 // This is the child
702 if (Child == 0)
703 {
d8cb4aa4
MV
704 setsid();
705 ioctl(slave, TIOCSCTTY, 0);
706 close(master);
707 dup2(slave, 0);
708 dup2(slave, 1);
709 dup2(slave, 2);
710 close(slave);
75ef8f14 711 close(fd[0]); // close the read end of the pipe
d8cb4aa4 712
cf544e14 713 if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
0dbb95d8 714 _exit(100);
03e39e59 715
421ff807 716 if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
8b5fe26c
AL
717 {
718 int Flags,dummy;
719 if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
720 _exit(100);
721
722 // Discard everything in stdin before forking dpkg
723 if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
724 _exit(100);
725
726 while (read(STDIN_FILENO,&dummy,1) == 1);
727
728 if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
729 _exit(100);
730 }
d8cb4aa4
MV
731
732
03e39e59
AL
733 /* No Job Control Stop Env is a magic dpkg var that prevents it
734 from using sigstop */
101030ab 735 putenv("DPKG_NO_TSTP=yes");
d568ed2d 736 execvp(Args[0],(char **)Args);
03e39e59 737 cerr << "Could not exec dpkg!" << endl;
0dbb95d8 738 _exit(100);
03e39e59
AL
739 }
740
75ef8f14
MV
741 // clear the Keep-Fd again
742 _config->Clear("APT::Keep-Fds",fd[1]);
743
03e39e59
AL
744 // Wait for dpkg
745 int Status = 0;
75ef8f14
MV
746
747 // we read from dpkg here
748 int _dpkgin = fd[0];
75ef8f14
MV
749 close(fd[1]); // close the write end of the pipe
750
751 // the read buffers for the communication with dpkg
75ef8f14
MV
752 char buf[2] = {0,0};
753
754 // the result of the waitpid call
755 int res;
d8cb4aa4 756 close(slave);
6191b008 757
090c6566 758 // FIXME: make this a apt config option and add a logrotate file
d8cb4aa4
MV
759 FILE *term_out = fopen("/var/log/dpkg-out.log","a");
760 chmod("/var/log/dpkg-out.log", 0600);
97efd303
MV
761 // output current time
762 char outstr[200];
763 time_t t = time(NULL);
764 struct tm *tmp = localtime(&t);
765 strftime(outstr, sizeof(outstr), "%F %T", tmp);
766 fprintf(term_out, "Log started: ");
767 fprintf(term_out, outstr);
768 fprintf(term_out, "\n");
769
770 // setups fds
090c6566
MV
771 fd_set rfds;
772 struct timeval tv;
773 int select_ret;
75ef8f14
MV
774 while ((res=waitpid(Child,&Status, WNOHANG)) != Child) {
775 if(res < 0) {
776 // FIXME: move this to a function or something, looks ugly here
777 // error handling, waitpid returned -1
778 if (errno == EINTR)
779 continue;
780 RunScripts("DPkg::Post-Invoke");
781
782 // Restore sig int/quit
783 signal(SIGQUIT,old_SIGQUIT);
784 signal(SIGINT,old_SIGINT);
785 return _error->Errno("waitpid","Couldn't wait for subprocess");
786 }
d8cb4aa4
MV
787
788 // wait for input or output here
955a6ddb
MV
789 FD_ZERO(&rfds);
790 FD_SET(0, &rfds);
791 FD_SET(_dpkgin, &rfds);
792 FD_SET(master, &rfds);
090c6566
MV
793 tv.tv_sec = 1;
794 tv.tv_usec = 0;
7fdafa0f 795 select_ret = select(max(master, _dpkgin)+1, &rfds, NULL, NULL, &tv);
090c6566
MV
796 if (select_ret < 0)
797 std::cerr << "Error in select()" << std::endl;
798 else if (select_ret == 0)
03e39e59 799 continue;
d8cb4aa4 800
955a6ddb
MV
801 if(FD_ISSET(master, &rfds))
802 DoTerminalPty(master, term_out);
803 if(FD_ISSET(0, &rfds))
804 DoStdin(master);
955a6ddb 805 if(FD_ISSET(_dpkgin, &rfds))
09fa2df2 806 DoDpkgStatusFd(_dpkgin, OutStatusFd);
03e39e59 807 }
75ef8f14 808 close(_dpkgin);
d8cb4aa4 809 fclose(term_out);
03e39e59
AL
810
811 // Restore sig int/quit
7f9a6360
AL
812 signal(SIGQUIT,old_SIGQUIT);
813 signal(SIGINT,old_SIGINT);
d8cb4aa4
MV
814
815 tcsetattr(0, TCSAFLUSH, &tt);
6dd55be7
AL
816
817 // Check for an error code.
818 if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
819 {
c70496f9
MV
820 // if it was set to "keep-dpkg-runing" then we won't return
821 // here but keep the loop going and just report it as a error
822 // for later
823 bool stopOnError = _config->FindB("Dpkg::StopOnError",true);
f956efb4 824
c70496f9
MV
825 if(stopOnError)
826 RunScripts("DPkg::Post-Invoke");
827
828 if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
829 _error->Error("Sub-process %s received a segmentation fault.",Args[0]);
830 else if (WIFEXITED(Status) != 0)
831 _error->Error("Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
832 else
833 _error->Error("Sub-process %s exited unexpectedly",Args[0]);
834
835 if(stopOnError)
836 return false;
6dd55be7 837 }
03e39e59 838 }
6dd55be7
AL
839
840 if (RunScripts("DPkg::Post-Invoke") == false)
841 return false;
03e39e59
AL
842 return true;
843}
844 /*}}}*/
281daf46
AL
845// pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
846// ---------------------------------------------------------------------
847/* */
848void pkgDPkgPM::Reset()
849{
850 List.erase(List.begin(),List.end());
851}
852 /*}}}*/