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