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