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