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