]> git.saurik.com Git - apt.git/blob - apt-pkg/deb/dpkgpm.cc
merged from debian
[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/pkgrecords.h>
16 #include <apt-pkg/strutl.h>
17 #include <apti18n.h>
18 #include <apt-pkg/fileutl.h>
19
20 #include <unistd.h>
21 #include <stdlib.h>
22 #include <fcntl.h>
23 #include <sys/select.h>
24 #include <sys/types.h>
25 #include <sys/wait.h>
26 #include <signal.h>
27 #include <errno.h>
28 #include <string.h>
29 #include <stdio.h>
30 #include <string.h>
31 #include <algorithm>
32 #include <sstream>
33 #include <map>
34
35 #include <termios.h>
36 #include <unistd.h>
37 #include <sys/ioctl.h>
38 #include <pty.h>
39
40 #include <config.h>
41 #include <apti18n.h>
42 /*}}}*/
43
44 using namespace std;
45
46 namespace
47 {
48 // Maps the dpkg "processing" info to human readable names. Entry 0
49 // of each array is the key, entry 1 is the value.
50 const std::pair<const char *, const char *> PackageProcessingOps[] = {
51 std::make_pair("install", N_("Installing %s")),
52 std::make_pair("configure", N_("Configuring %s")),
53 std::make_pair("remove", N_("Removing %s")),
54 std::make_pair("trigproc", N_("Running post-installation trigger %s"))
55 };
56
57 const std::pair<const char *, const char *> * const PackageProcessingOpsBegin = PackageProcessingOps;
58 const std::pair<const char *, const char *> * const PackageProcessingOpsEnd = PackageProcessingOps + sizeof(PackageProcessingOps) / sizeof(PackageProcessingOps[0]);
59
60 // Predicate to test whether an entry in the PackageProcessingOps
61 // array matches a string.
62 class MatchProcessingOp
63 {
64 const char *target;
65
66 public:
67 MatchProcessingOp(const char *the_target)
68 : target(the_target)
69 {
70 }
71
72 bool operator()(const std::pair<const char *, const char *> &pair) const
73 {
74 return strcmp(pair.first, target) == 0;
75 }
76 };
77 }
78
79 /* helper function to ionice the given PID
80
81 there is no C header for ionice yet - just the syscall interface
82 so we use the binary from util-linux
83 */
84 static bool
85 ionice(int PID)
86 {
87 if (!FileExists("/usr/bin/ionice"))
88 return false;
89 pid_t Process = ExecFork();
90 if (Process == 0)
91 {
92 char buf[32];
93 snprintf(buf, sizeof(buf), "-p%d", PID);
94 const char *Args[4];
95 Args[0] = "/usr/bin/ionice";
96 Args[1] = "-c3";
97 Args[2] = buf;
98 Args[3] = 0;
99 execv(Args[0], (char **)Args);
100 }
101 return ExecWait(Process, "ionice");
102 }
103
104 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
105 // ---------------------------------------------------------------------
106 /* */
107 pkgDPkgPM::pkgDPkgPM(pkgDepCache *Cache)
108 : pkgPackageManager(Cache), dpkgbuf_pos(0),
109 term_out(NULL), PackagesDone(0), PackagesTotal(0), pkgFailures(0)
110 {
111 }
112 /*}}}*/
113 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
114 // ---------------------------------------------------------------------
115 /* */
116 pkgDPkgPM::~pkgDPkgPM()
117 {
118 }
119 /*}}}*/
120 // DPkgPM::Install - Install a package /*{{{*/
121 // ---------------------------------------------------------------------
122 /* Add an install operation to the sequence list */
123 bool pkgDPkgPM::Install(PkgIterator Pkg,string File)
124 {
125 if (File.empty() == true || Pkg.end() == true)
126 return _error->Error("Internal Error, No file name for %s",Pkg.Name());
127
128 List.push_back(Item(Item::Install,Pkg,File));
129 return true;
130 }
131 /*}}}*/
132 // DPkgPM::Configure - Configure a package /*{{{*/
133 // ---------------------------------------------------------------------
134 /* Add a configure operation to the sequence list */
135 bool pkgDPkgPM::Configure(PkgIterator Pkg)
136 {
137 if (Pkg.end() == true)
138 return false;
139
140 List.push_back(Item(Item::Configure,Pkg));
141 return true;
142 }
143 /*}}}*/
144 // DPkgPM::Remove - Remove a package /*{{{*/
145 // ---------------------------------------------------------------------
146 /* Add a remove operation to the sequence list */
147 bool pkgDPkgPM::Remove(PkgIterator Pkg,bool Purge)
148 {
149 if (Pkg.end() == true)
150 return false;
151
152 if (Purge == true)
153 List.push_back(Item(Item::Purge,Pkg));
154 else
155 List.push_back(Item(Item::Remove,Pkg));
156 return true;
157 }
158 /*}}}*/
159 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
160 // ---------------------------------------------------------------------
161 /* This is part of the helper script communication interface, it sends
162 very complete information down to the other end of the pipe.*/
163 bool pkgDPkgPM::SendV2Pkgs(FILE *F)
164 {
165 fprintf(F,"VERSION 2\n");
166
167 /* Write out all of the configuration directives by walking the
168 configuration tree */
169 const Configuration::Item *Top = _config->Tree(0);
170 for (; Top != 0;)
171 {
172 if (Top->Value.empty() == false)
173 {
174 fprintf(F,"%s=%s\n",
175 QuoteString(Top->FullTag(),"=\"\n").c_str(),
176 QuoteString(Top->Value,"\n").c_str());
177 }
178
179 if (Top->Child != 0)
180 {
181 Top = Top->Child;
182 continue;
183 }
184
185 while (Top != 0 && Top->Next == 0)
186 Top = Top->Parent;
187 if (Top != 0)
188 Top = Top->Next;
189 }
190 fprintf(F,"\n");
191
192 // Write out the package actions in order.
193 for (vector<Item>::iterator I = List.begin(); I != List.end(); I++)
194 {
195 pkgDepCache::StateCache &S = Cache[I->Pkg];
196
197 fprintf(F,"%s ",I->Pkg.Name());
198 // Current version
199 if (I->Pkg->CurrentVer == 0)
200 fprintf(F,"- ");
201 else
202 fprintf(F,"%s ",I->Pkg.CurrentVer().VerStr());
203
204 // Show the compare operator
205 // Target version
206 if (S.InstallVer != 0)
207 {
208 int Comp = 2;
209 if (I->Pkg->CurrentVer != 0)
210 Comp = S.InstVerIter(Cache).CompareVer(I->Pkg.CurrentVer());
211 if (Comp < 0)
212 fprintf(F,"> ");
213 if (Comp == 0)
214 fprintf(F,"= ");
215 if (Comp > 0)
216 fprintf(F,"< ");
217 fprintf(F,"%s ",S.InstVerIter(Cache).VerStr());
218 }
219 else
220 fprintf(F,"> - ");
221
222 // Show the filename/operation
223 if (I->Op == Item::Install)
224 {
225 // No errors here..
226 if (I->File[0] != '/')
227 fprintf(F,"**ERROR**\n");
228 else
229 fprintf(F,"%s\n",I->File.c_str());
230 }
231 if (I->Op == Item::Configure)
232 fprintf(F,"**CONFIGURE**\n");
233 if (I->Op == Item::Remove ||
234 I->Op == Item::Purge)
235 fprintf(F,"**REMOVE**\n");
236
237 if (ferror(F) != 0)
238 return false;
239 }
240 return true;
241 }
242 /*}}}*/
243 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
244 // ---------------------------------------------------------------------
245 /* This looks for a list of scripts to run from the configuration file
246 each one is run and is fed on standard input a list of all .deb files
247 that are due to be installed. */
248 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf)
249 {
250 Configuration::Item const *Opts = _config->Tree(Cnf);
251 if (Opts == 0 || Opts->Child == 0)
252 return true;
253 Opts = Opts->Child;
254
255 unsigned int Count = 1;
256 for (; Opts != 0; Opts = Opts->Next, Count++)
257 {
258 if (Opts->Value.empty() == true)
259 continue;
260
261 // Determine the protocol version
262 string OptSec = Opts->Value;
263 string::size_type Pos;
264 if ((Pos = OptSec.find(' ')) == string::npos || Pos == 0)
265 Pos = OptSec.length();
266 OptSec = "DPkg::Tools::Options::" + string(Opts->Value.c_str(),Pos);
267
268 unsigned int Version = _config->FindI(OptSec+"::Version",1);
269
270 // Create the pipes
271 int Pipes[2];
272 if (pipe(Pipes) != 0)
273 return _error->Errno("pipe","Failed to create IPC pipe to subprocess");
274 SetCloseExec(Pipes[0],true);
275 SetCloseExec(Pipes[1],true);
276
277 // Purified Fork for running the script
278 pid_t Process = ExecFork();
279 if (Process == 0)
280 {
281 // Setup the FDs
282 dup2(Pipes[0],STDIN_FILENO);
283 SetCloseExec(STDOUT_FILENO,false);
284 SetCloseExec(STDIN_FILENO,false);
285 SetCloseExec(STDERR_FILENO,false);
286
287 const char *Args[4];
288 Args[0] = "/bin/sh";
289 Args[1] = "-c";
290 Args[2] = Opts->Value.c_str();
291 Args[3] = 0;
292 execv(Args[0],(char **)Args);
293 _exit(100);
294 }
295 close(Pipes[0]);
296 FILE *F = fdopen(Pipes[1],"w");
297 if (F == 0)
298 return _error->Errno("fdopen","Faild to open new FD");
299
300 // Feed it the filenames.
301 bool Die = false;
302 if (Version <= 1)
303 {
304 for (vector<Item>::iterator I = List.begin(); I != List.end(); I++)
305 {
306 // Only deal with packages to be installed from .deb
307 if (I->Op != Item::Install)
308 continue;
309
310 // No errors here..
311 if (I->File[0] != '/')
312 continue;
313
314 /* Feed the filename of each package that is pending install
315 into the pipe. */
316 fprintf(F,"%s\n",I->File.c_str());
317 if (ferror(F) != 0)
318 {
319 Die = true;
320 break;
321 }
322 }
323 }
324 else
325 Die = !SendV2Pkgs(F);
326
327 fclose(F);
328
329 // Clean up the sub process
330 if (ExecWait(Process,Opts->Value.c_str()) == false)
331 return _error->Error("Failure running script %s",Opts->Value.c_str());
332 }
333
334 return true;
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[6];
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 // urgs, sometime has ":" in its error string so that we
452 // end up with the error message split between list[3]
453 // and list[4], e.g. the message:
454 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
455 // concat them again
456 if( list[4] != NULL )
457 list[3][strlen(list[3])] = ':';
458
459 status << "pmerror:" << list[1]
460 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
461 << ":" << list[3]
462 << endl;
463 if(OutStatusFd > 0)
464 write(OutStatusFd, status.str().c_str(), status.str().size());
465 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
466 std::clog << "send: '" << status.str() << "'" << endl;
467 pkgFailures++;
468 WriteApportReport(list[1], list[3]);
469 return;
470 }
471 if(strncmp(action,"conffile",strlen("conffile")) == 0)
472 {
473 status << "pmconffile:" << list[1]
474 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
475 << ":" << list[3]
476 << endl;
477 if(OutStatusFd > 0)
478 write(OutStatusFd, status.str().c_str(), status.str().size());
479 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
480 std::clog << "send: '" << status.str() << "'" << endl;
481 return;
482 }
483
484 vector<struct DpkgState> &states = PackageOps[pkg];
485 const char *next_action = NULL;
486 if(PackageOpsDone[pkg] < states.size())
487 next_action = states[PackageOpsDone[pkg]].state;
488 // check if the package moved to the next dpkg state
489 if(next_action && (strcmp(action, next_action) == 0))
490 {
491 // only read the translation if there is actually a next
492 // action
493 const char *translation = _(states[PackageOpsDone[pkg]].str);
494 char s[200];
495 snprintf(s, sizeof(s), translation, pkg);
496
497 // we moved from one dpkg state to a new one, report that
498 PackageOpsDone[pkg]++;
499 PackagesDone++;
500 // build the status str
501 status << "pmstatus:" << pkg
502 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
503 << ":" << s
504 << endl;
505 if(OutStatusFd > 0)
506 write(OutStatusFd, status.str().c_str(), status.str().size());
507 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
508 std::clog << "send: '" << status.str() << "'" << endl;
509 }
510 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
511 std::clog << "(parsed from dpkg) pkg: " << pkg
512 << " action: " << action << endl;
513 }
514
515 // DPkgPM::DoDpkgStatusFd /*{{{*/
516 // ---------------------------------------------------------------------
517 /*
518 */
519 void pkgDPkgPM::DoDpkgStatusFd(int statusfd, int OutStatusFd)
520 {
521 char *p, *q;
522 int len;
523
524 len=read(statusfd, &dpkgbuf[dpkgbuf_pos], sizeof(dpkgbuf)-dpkgbuf_pos);
525 dpkgbuf_pos += len;
526 if(len <= 0)
527 return;
528
529 // process line by line if we have a buffer
530 p = q = dpkgbuf;
531 while((q=(char*)memchr(p, '\n', dpkgbuf+dpkgbuf_pos-p)) != NULL)
532 {
533 *q = 0;
534 ProcessDpkgStatusLine(OutStatusFd, p);
535 p=q+1; // continue with next line
536 }
537
538 // now move the unprocessed bits (after the final \n that is now a 0x0)
539 // to the start and update dpkgbuf_pos
540 p = (char*)memrchr(dpkgbuf, 0, dpkgbuf_pos);
541 if(p == NULL)
542 return;
543
544 // we are interessted in the first char *after* 0x0
545 p++;
546
547 // move the unprocessed tail to the start and update pos
548 memmove(dpkgbuf, p, p-dpkgbuf);
549 dpkgbuf_pos = dpkgbuf+dpkgbuf_pos-p;
550 }
551 /*}}}*/
552
553 bool pkgDPkgPM::OpenLog()
554 {
555 string logdir = _config->FindDir("Dir::Log");
556 if(not FileExists(logdir))
557 return _error->Error(_("Directory '%s' missing"), logdir.c_str());
558 string logfile_name = flCombine(logdir,
559 _config->Find("Dir::Log::Terminal"));
560 if (!logfile_name.empty())
561 {
562 term_out = fopen(logfile_name.c_str(),"a");
563 chmod(logfile_name.c_str(), 0600);
564 // output current time
565 char outstr[200];
566 time_t t = time(NULL);
567 struct tm *tmp = localtime(&t);
568 strftime(outstr, sizeof(outstr), "%F %T", tmp);
569 fprintf(term_out, "\nLog started: ");
570 fprintf(term_out, "%s", outstr);
571 fprintf(term_out, "\n");
572 }
573 return true;
574 }
575
576 bool pkgDPkgPM::CloseLog()
577 {
578 if(term_out)
579 {
580 char outstr[200];
581 time_t t = time(NULL);
582 struct tm *tmp = localtime(&t);
583 strftime(outstr, sizeof(outstr), "%F %T", tmp);
584 fprintf(term_out, "Log ended: ");
585 fprintf(term_out, "%s", outstr);
586 fprintf(term_out, "\n");
587 fclose(term_out);
588 }
589 term_out = NULL;
590 return true;
591 }
592
593 /*{{{*/
594 // This implements a racy version of pselect for those architectures
595 // that don't have a working implementation.
596 // FIXME: Probably can be removed on Lenny+1
597 static int racy_pselect(int nfds, fd_set *readfds, fd_set *writefds,
598 fd_set *exceptfds, const struct timespec *timeout,
599 const sigset_t *sigmask)
600 {
601 sigset_t origmask;
602 struct timeval tv;
603 int retval;
604
605 tv.tv_sec = timeout->tv_sec;
606 tv.tv_usec = timeout->tv_nsec/1000;
607
608 sigprocmask(SIG_SETMASK, sigmask, &origmask);
609 retval = select(nfds, readfds, writefds, exceptfds, &tv);
610 sigprocmask(SIG_SETMASK, &origmask, 0);
611 return retval;
612 }
613 /*}}}*/
614
615 // DPkgPM::Go - Run the sequence /*{{{*/
616 // ---------------------------------------------------------------------
617 /* This globs the operations and calls dpkg
618 *
619 * If it is called with "OutStatusFd" set to a valid file descriptor
620 * apt will report the install progress over this fd. It maps the
621 * dpkg states a package goes through to human readable (and i10n-able)
622 * names and calculates a percentage for each step.
623 */
624 bool pkgDPkgPM::Go(int OutStatusFd)
625 {
626 fd_set rfds;
627 struct timespec tv;
628 sigset_t sigmask;
629 sigset_t original_sigmask;
630
631 unsigned int MaxArgs = _config->FindI("Dpkg::MaxArgs",8*1024);
632 unsigned int MaxArgBytes = _config->FindI("Dpkg::MaxArgBytes",32*1024);
633 bool NoTriggers = _config->FindB("DPkg::NoTriggers",false);
634
635 if (RunScripts("DPkg::Pre-Invoke") == false)
636 return false;
637
638 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
639 return false;
640
641 // map the dpkg states to the operations that are performed
642 // (this is sorted in the same way as Item::Ops)
643 static const struct DpkgState DpkgStatesOpMap[][7] = {
644 // Install operation
645 {
646 {"half-installed", N_("Preparing %s")},
647 {"unpacked", N_("Unpacking %s") },
648 {NULL, NULL}
649 },
650 // Configure operation
651 {
652 {"unpacked",N_("Preparing to configure %s") },
653 {"half-configured", N_("Configuring %s") },
654 { "installed", N_("Installed %s")},
655 {NULL, NULL}
656 },
657 // Remove operation
658 {
659 {"half-configured", N_("Preparing for removal of %s")},
660 {"half-installed", N_("Removing %s")},
661 {"config-files", N_("Removed %s")},
662 {NULL, NULL}
663 },
664 // Purge operation
665 {
666 {"config-files", N_("Preparing to completely remove %s")},
667 {"not-installed", N_("Completely removed %s")},
668 {NULL, NULL}
669 },
670 };
671
672 // init the PackageOps map, go over the list of packages that
673 // that will be [installed|configured|removed|purged] and add
674 // them to the PackageOps map (the dpkg states it goes through)
675 // and the PackageOpsTranslations (human readable strings)
676 for (vector<Item>::iterator I = List.begin(); I != List.end();I++)
677 {
678 string name = (*I).Pkg.Name();
679 PackageOpsDone[name] = 0;
680 for(int i=0; (DpkgStatesOpMap[(*I).Op][i]).state != NULL; i++)
681 {
682 PackageOps[name].push_back(DpkgStatesOpMap[(*I).Op][i]);
683 PackagesTotal++;
684 }
685 }
686
687 stdin_is_dev_null = false;
688
689 // create log
690 OpenLog();
691
692 // this loop is runs once per operation
693 for (vector<Item>::iterator I = List.begin(); I != List.end();)
694 {
695 vector<Item>::iterator J = I;
696 for (; J != List.end() && J->Op == I->Op; J++)
697 /* nothing */;
698
699 // Generate the argument list
700 const char *Args[MaxArgs + 50];
701
702 // Now check if we are within the MaxArgs limit
703 //
704 // this code below is problematic, because it may happen that
705 // the argument list is split in a way that A depends on B
706 // and they are in the same "--configure A B" run
707 // - with the split they may now be configured in different
708 // runs
709 if (J - I > (signed)MaxArgs)
710 J = I + MaxArgs;
711
712 unsigned int n = 0;
713 unsigned long Size = 0;
714 string Tmp = _config->Find("Dir::Bin::dpkg","dpkg");
715 Args[n++] = Tmp.c_str();
716 Size += strlen(Args[n-1]);
717
718 // Stick in any custom dpkg options
719 Configuration::Item const *Opts = _config->Tree("DPkg::Options");
720 if (Opts != 0)
721 {
722 Opts = Opts->Child;
723 for (; Opts != 0; Opts = Opts->Next)
724 {
725 if (Opts->Value.empty() == true)
726 continue;
727 Args[n++] = Opts->Value.c_str();
728 Size += Opts->Value.length();
729 }
730 }
731
732 char status_fd_buf[20];
733 int fd[2];
734 pipe(fd);
735
736 Args[n++] = "--status-fd";
737 Size += strlen(Args[n-1]);
738 snprintf(status_fd_buf,sizeof(status_fd_buf),"%i", fd[1]);
739 Args[n++] = status_fd_buf;
740 Size += strlen(Args[n-1]);
741
742 switch (I->Op)
743 {
744 case Item::Remove:
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++] = "--remove";
750 Size += strlen(Args[n-1]);
751 break;
752
753 case Item::Purge:
754 Args[n++] = "--force-depends";
755 Size += strlen(Args[n-1]);
756 Args[n++] = "--force-remove-essential";
757 Size += strlen(Args[n-1]);
758 Args[n++] = "--purge";
759 Size += strlen(Args[n-1]);
760 break;
761
762 case Item::Configure:
763 Args[n++] = "--configure";
764 if (NoTriggers)
765 Args[n++] = "--no-triggers";
766 Size += strlen(Args[n-1]);
767 break;
768
769 case Item::Install:
770 Args[n++] = "--unpack";
771 Size += strlen(Args[n-1]);
772 Args[n++] = "--auto-deconfigure";
773 Size += strlen(Args[n-1]);
774 break;
775 }
776
777 // Write in the file or package names
778 if (I->Op == Item::Install)
779 {
780 for (;I != J && Size < MaxArgBytes; I++)
781 {
782 if (I->File[0] != '/')
783 return _error->Error("Internal Error, Pathname to install is not absolute '%s'",I->File.c_str());
784 Args[n++] = I->File.c_str();
785 Size += strlen(Args[n-1]);
786 }
787 }
788 else
789 {
790 for (;I != J && Size < MaxArgBytes; I++)
791 {
792 Args[n++] = I->Pkg.Name();
793 Size += strlen(Args[n-1]);
794 }
795 }
796 Args[n] = 0;
797 J = I;
798
799 if (_config->FindB("Debug::pkgDPkgPM",false) == true)
800 {
801 for (unsigned int k = 0; k != n; k++)
802 clog << Args[k] << ' ';
803 clog << endl;
804 continue;
805 }
806
807 cout << flush;
808 clog << flush;
809 cerr << flush;
810
811 /* Mask off sig int/quit. We do this because dpkg also does when
812 it forks scripts. What happens is that when you hit ctrl-c it sends
813 it to all processes in the group. Since dpkg ignores the signal
814 it doesn't die but we do! So we must also ignore it */
815 sighandler_t old_SIGQUIT = signal(SIGQUIT,SIG_IGN);
816 sighandler_t old_SIGINT = signal(SIGINT,SIG_IGN);
817
818 // ignore SIGHUP as well (debian #463030)
819 sighandler_t old_SIGHUP = signal(SIGHUP,SIG_IGN);
820
821 struct termios tt;
822 struct winsize win;
823 int master;
824 int slave;
825
826 // FIXME: setup sensible signal handling (*ick*)
827 tcgetattr(0, &tt);
828 ioctl(0, TIOCGWINSZ, (char *)&win);
829 if (openpty(&master, &slave, NULL, &tt, &win) < 0)
830 {
831 const char *s = _("Can not write log, openpty() "
832 "failed (/dev/pts not mounted?)\n");
833 fprintf(stderr, "%s",s);
834 fprintf(term_out, "%s",s);
835 master = slave = -1;
836 } else {
837 struct termios rtt;
838 rtt = tt;
839 cfmakeraw(&rtt);
840 rtt.c_lflag &= ~ECHO;
841 // block SIGTTOU during tcsetattr to prevent a hang if
842 // the process is a member of the background process group
843 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
844 sigemptyset(&sigmask);
845 sigaddset(&sigmask, SIGTTOU);
846 sigprocmask(SIG_BLOCK,&sigmask, &original_sigmask);
847 tcsetattr(0, TCSAFLUSH, &rtt);
848 sigprocmask(SIG_SETMASK, &original_sigmask, 0);
849 }
850
851 // Fork dpkg
852 pid_t Child;
853 _config->Set("APT::Keep-Fds::",fd[1]);
854 // send status information that we are about to fork dpkg
855 if(OutStatusFd > 0) {
856 ostringstream status;
857 status << "pmstatus:dpkg-exec:"
858 << (PackagesDone/float(PackagesTotal)*100.0)
859 << ":" << _("Running dpkg")
860 << endl;
861 write(OutStatusFd, status.str().c_str(), status.str().size());
862 }
863 Child = ExecFork();
864
865 // This is the child
866 if (Child == 0)
867 {
868 if(slave >= 0 && master >= 0)
869 {
870 setsid();
871 ioctl(slave, TIOCSCTTY, 0);
872 close(master);
873 dup2(slave, 0);
874 dup2(slave, 1);
875 dup2(slave, 2);
876 close(slave);
877 }
878 close(fd[0]); // close the read end of the pipe
879
880 if (_config->FindDir("DPkg::Chroot-Directory","/") != "/")
881 {
882 std::cerr << "Chrooting into "
883 << _config->FindDir("DPkg::Chroot-Directory")
884 << std::endl;
885 if (chroot(_config->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
886 _exit(100);
887 }
888
889 if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
890 _exit(100);
891
892 if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
893 {
894 int Flags,dummy;
895 if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
896 _exit(100);
897
898 // Discard everything in stdin before forking dpkg
899 if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
900 _exit(100);
901
902 while (read(STDIN_FILENO,&dummy,1) == 1);
903
904 if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
905 _exit(100);
906 }
907
908 /* No Job Control Stop Env is a magic dpkg var that prevents it
909 from using sigstop */
910 putenv((char *)"DPKG_NO_TSTP=yes");
911 execvp(Args[0],(char **)Args);
912 cerr << "Could not exec dpkg!" << endl;
913 _exit(100);
914 }
915
916 // apply ionice
917 if (_config->FindB("DPkg::UseIoNice", false) == true)
918 ionice(Child);
919
920 // clear the Keep-Fd again
921 _config->Clear("APT::Keep-Fds",fd[1]);
922
923 // Wait for dpkg
924 int Status = 0;
925
926 // we read from dpkg here
927 int _dpkgin = fd[0];
928 close(fd[1]); // close the write end of the pipe
929
930 // the result of the waitpid call
931 int res;
932 if(slave > 0)
933 close(slave);
934
935 // setups fds
936 sigemptyset(&sigmask);
937 sigprocmask(SIG_BLOCK,&sigmask,&original_sigmask);
938
939 int select_ret;
940 while ((res=waitpid(Child,&Status, WNOHANG)) != Child) {
941 if(res < 0) {
942 // FIXME: move this to a function or something, looks ugly here
943 // error handling, waitpid returned -1
944 if (errno == EINTR)
945 continue;
946 RunScripts("DPkg::Post-Invoke");
947
948 // Restore sig int/quit
949 signal(SIGQUIT,old_SIGQUIT);
950 signal(SIGINT,old_SIGINT);
951 signal(SIGHUP,old_SIGHUP);
952 return _error->Errno("waitpid","Couldn't wait for subprocess");
953 }
954 // wait for input or output here
955 FD_ZERO(&rfds);
956 if (!stdin_is_dev_null)
957 FD_SET(0, &rfds);
958 FD_SET(_dpkgin, &rfds);
959 if(master >= 0)
960 FD_SET(master, &rfds);
961 tv.tv_sec = 1;
962 tv.tv_nsec = 0;
963 select_ret = pselect(max(master, _dpkgin)+1, &rfds, NULL, NULL,
964 &tv, &original_sigmask);
965 if (select_ret < 0 && (errno == EINVAL || errno == ENOSYS))
966 select_ret = racy_pselect(max(master, _dpkgin)+1, &rfds, NULL,
967 NULL, &tv, &original_sigmask);
968 if (select_ret == 0)
969 continue;
970 else if (select_ret < 0 && errno == EINTR)
971 continue;
972 else if (select_ret < 0)
973 {
974 perror("select() returned error");
975 continue;
976 }
977
978 if(master >= 0 && FD_ISSET(master, &rfds))
979 DoTerminalPty(master);
980 if(master >= 0 && FD_ISSET(0, &rfds))
981 DoStdin(master);
982 if(FD_ISSET(_dpkgin, &rfds))
983 DoDpkgStatusFd(_dpkgin, OutStatusFd);
984 }
985 close(_dpkgin);
986
987 // Restore sig int/quit
988 signal(SIGQUIT,old_SIGQUIT);
989 signal(SIGINT,old_SIGINT);
990 signal(SIGHUP,old_SIGHUP);
991
992 if(master >= 0)
993 {
994 tcsetattr(0, TCSAFLUSH, &tt);
995 close(master);
996 }
997
998 // Check for an error code.
999 if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
1000 {
1001 // if it was set to "keep-dpkg-runing" then we won't return
1002 // here but keep the loop going and just report it as a error
1003 // for later
1004 bool stopOnError = _config->FindB("Dpkg::StopOnError",true);
1005
1006 if(stopOnError)
1007 RunScripts("DPkg::Post-Invoke");
1008
1009 if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
1010 _error->Error("Sub-process %s received a segmentation fault.",Args[0]);
1011 else if (WIFEXITED(Status) != 0)
1012 _error->Error("Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
1013 else
1014 _error->Error("Sub-process %s exited unexpectedly",Args[0]);
1015
1016 if(stopOnError)
1017 {
1018 CloseLog();
1019 return false;
1020 }
1021 }
1022 }
1023 CloseLog();
1024
1025 if (RunScripts("DPkg::Post-Invoke") == false)
1026 return false;
1027
1028 Cache.writeStateFile(NULL);
1029 return true;
1030 }
1031 /*}}}*/
1032 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1033 // ---------------------------------------------------------------------
1034 /* */
1035 void pkgDPkgPM::Reset()
1036 {
1037 List.erase(List.begin(),List.end());
1038 }
1039 /*}}}*/
1040 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1041 // ---------------------------------------------------------------------
1042 /* */
1043 void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
1044 {
1045 string pkgname, reportfile, srcpkgname, pkgver, arch;
1046 string::size_type pos;
1047 FILE *report;
1048
1049 if (_config->FindB("Dpkg::ApportFailureReport",true) == false)
1050 {
1051 std::clog << "configured to not write apport reports" << std::endl;
1052 return;
1053 }
1054
1055 // only report the first errors
1056 if(pkgFailures > _config->FindI("APT::Apport::MaxReports", 3))
1057 {
1058 std::clog << _("No apport report written because MaxReports is reached already") << std::endl;
1059 return;
1060 }
1061
1062 // check if its not a follow up error
1063 const char *needle = dgettext("dpkg", "dependency problems - leaving unconfigured");
1064 if(strstr(errormsg, needle) != NULL) {
1065 std::clog << _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl;
1066 return;
1067 }
1068
1069 // do not report disk-full failures
1070 if(strstr(errormsg, strerror(ENOSPC)) != NULL) {
1071 std::clog << _("No apport report written because the error message indicates a disk full error") << std::endl;
1072 return;
1073 }
1074
1075 // do not report out-of-memory failures
1076 if(strstr(errormsg, strerror(ENOMEM)) != NULL) {
1077 std::clog << _("No apport report written because the error message indicates a out of memory error") << std::endl;
1078 return;
1079 }
1080
1081 // get the pkgname and reportfile
1082 pkgname = flNotDir(pkgpath);
1083 pos = pkgname.find('_');
1084 if(pos != string::npos)
1085 pkgname = pkgname.substr(0, pos);
1086
1087 // find the package versin and source package name
1088 pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
1089 if (Pkg.end() == true)
1090 return;
1091 pkgCache::VerIterator Ver = Cache.GetCandidateVer(Pkg);
1092 if (Ver.end() == true)
1093 return;
1094 pkgver = Ver.VerStr() == NULL ? "unknown" : Ver.VerStr();
1095 pkgRecords Recs(Cache);
1096 pkgRecords::Parser &Parse = Recs.Lookup(Ver.FileList());
1097 srcpkgname = Parse.SourcePkg();
1098 if(srcpkgname.empty())
1099 srcpkgname = pkgname;
1100
1101 // if the file exists already, we check:
1102 // - if it was reported already (touched by apport).
1103 // If not, we do nothing, otherwise
1104 // we overwrite it. This is the same behaviour as apport
1105 // - if we have a report with the same pkgversion already
1106 // then we skip it
1107 reportfile = flCombine("/var/crash",pkgname+".0.crash");
1108 if(FileExists(reportfile))
1109 {
1110 struct stat buf;
1111 char strbuf[255];
1112
1113 // check atime/mtime
1114 stat(reportfile.c_str(), &buf);
1115 if(buf.st_mtime > buf.st_atime)
1116 return;
1117
1118 // check if the existing report is the same version
1119 report = fopen(reportfile.c_str(),"r");
1120 while(fgets(strbuf, sizeof(strbuf), report) != NULL)
1121 {
1122 if(strstr(strbuf,"Package:") == strbuf)
1123 {
1124 char pkgname[255], version[255];
1125 if(sscanf(strbuf, "Package: %s %s", pkgname, version) == 2)
1126 if(strcmp(pkgver.c_str(), version) == 0)
1127 {
1128 fclose(report);
1129 return;
1130 }
1131 }
1132 }
1133 fclose(report);
1134 }
1135
1136 // now write the report
1137 arch = _config->Find("APT::Architecture");
1138 report = fopen(reportfile.c_str(),"w");
1139 if(report == NULL)
1140 return;
1141 if(_config->FindB("DPkgPM::InitialReportOnly",false) == true)
1142 chmod(reportfile.c_str(), 0);
1143 else
1144 chmod(reportfile.c_str(), 0600);
1145 fprintf(report, "ProblemType: Package\n");
1146 fprintf(report, "Architecture: %s\n", arch.c_str());
1147 time_t now = time(NULL);
1148 fprintf(report, "Date: %s" , ctime(&now));
1149 fprintf(report, "Package: %s %s\n", pkgname.c_str(), pkgver.c_str());
1150 fprintf(report, "SourcePackage: %s\n", srcpkgname.c_str());
1151 fprintf(report, "ErrorMessage:\n %s\n", errormsg);
1152
1153 // ensure that the log is flushed
1154 if(term_out)
1155 fflush(term_out);
1156
1157 // attach terminal log it if we have it
1158 string logfile_name = _config->FindFile("Dir::Log::Terminal");
1159 if (!logfile_name.empty())
1160 {
1161 FILE *log = NULL;
1162 char buf[1024];
1163
1164 fprintf(report, "DpkgTerminalLog:\n");
1165 log = fopen(logfile_name.c_str(),"r");
1166 if(log != NULL)
1167 {
1168 while( fgets(buf, sizeof(buf), log) != NULL)
1169 fprintf(report, " %s", buf);
1170 fclose(log);
1171 }
1172 }
1173
1174 // log the ordering
1175 const char *ops_str[] = {"Install", "Configure","Remove","Purge"};
1176 fprintf(report, "AptOrdering:\n");
1177 for (vector<Item>::iterator I = List.begin(); I != List.end(); I++)
1178 fprintf(report, " %s: %s\n", (*I).Pkg.Name(), ops_str[(*I).Op]);
1179
1180 // attach dmesg log (to learn about segfaults)
1181 if (FileExists("/bin/dmesg"))
1182 {
1183 FILE *log = NULL;
1184 char buf[1024];
1185
1186 fprintf(report, "Dmesg:\n");
1187 log = popen("/bin/dmesg","r");
1188 if(log != NULL)
1189 {
1190 while( fgets(buf, sizeof(buf), log) != NULL)
1191 fprintf(report, " %s", buf);
1192 fclose(log);
1193 }
1194 }
1195 fclose(report);
1196
1197 }
1198 /*}}}*/