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