]> 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/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 if (_config->FindB("DPkg::ConfigurePending", SmartConf) == true)
656 List.push_back(Item(Item::ConfigurePending, PkgIterator()));
657
658 // map the dpkg states to the operations that are performed
659 // (this is sorted in the same way as Item::Ops)
660 static const struct DpkgState DpkgStatesOpMap[][7] = {
661 // Install operation
662 {
663 {"half-installed", N_("Preparing %s")},
664 {"unpacked", N_("Unpacking %s") },
665 {NULL, NULL}
666 },
667 // Configure operation
668 {
669 {"unpacked",N_("Preparing to configure %s") },
670 {"half-configured", N_("Configuring %s") },
671 { "installed", N_("Installed %s")},
672 {NULL, NULL}
673 },
674 // Remove operation
675 {
676 {"half-configured", N_("Preparing for removal of %s")},
677 {"half-installed", N_("Removing %s")},
678 {"config-files", N_("Removed %s")},
679 {NULL, NULL}
680 },
681 // Purge operation
682 {
683 {"config-files", N_("Preparing to completely remove %s")},
684 {"not-installed", N_("Completely removed %s")},
685 {NULL, NULL}
686 },
687 };
688
689 // init the PackageOps map, go over the list of packages that
690 // that will be [installed|configured|removed|purged] and add
691 // them to the PackageOps map (the dpkg states it goes through)
692 // and the PackageOpsTranslations (human readable strings)
693 for (vector<Item>::const_iterator I = List.begin(); I != List.end();I++)
694 {
695 if((*I).Pkg.end() == true)
696 continue;
697
698 string const name = (*I).Pkg.Name();
699 PackageOpsDone[name] = 0;
700 for(int i=0; (DpkgStatesOpMap[(*I).Op][i]).state != NULL; i++)
701 {
702 PackageOps[name].push_back(DpkgStatesOpMap[(*I).Op][i]);
703 PackagesTotal++;
704 }
705 }
706
707 stdin_is_dev_null = false;
708
709 // create log
710 OpenLog();
711
712 // this loop is runs once per operation
713 for (vector<Item>::const_iterator I = List.begin(); I != List.end();)
714 {
715 vector<Item>::const_iterator J = I;
716 for (; J != List.end() && J->Op == I->Op; J++)
717 /* nothing */;
718
719 // Generate the argument list
720 const char *Args[MaxArgs + 50];
721
722 // Now check if we are within the MaxArgs limit
723 //
724 // this code below is problematic, because it may happen that
725 // the argument list is split in a way that A depends on B
726 // and they are in the same "--configure A B" run
727 // - with the split they may now be configured in different
728 // runs
729 if (J - I > (signed)MaxArgs)
730 J = I + MaxArgs;
731
732 unsigned int n = 0;
733 unsigned long Size = 0;
734 string const Tmp = _config->Find("Dir::Bin::dpkg","dpkg");
735 Args[n++] = Tmp.c_str();
736 Size += strlen(Args[n-1]);
737
738 // Stick in any custom dpkg options
739 Configuration::Item const *Opts = _config->Tree("DPkg::Options");
740 if (Opts != 0)
741 {
742 Opts = Opts->Child;
743 for (; Opts != 0; Opts = Opts->Next)
744 {
745 if (Opts->Value.empty() == true)
746 continue;
747 Args[n++] = Opts->Value.c_str();
748 Size += Opts->Value.length();
749 }
750 }
751
752 char status_fd_buf[20];
753 int fd[2];
754 pipe(fd);
755
756 Args[n++] = "--status-fd";
757 Size += strlen(Args[n-1]);
758 snprintf(status_fd_buf,sizeof(status_fd_buf),"%i", fd[1]);
759 Args[n++] = status_fd_buf;
760 Size += strlen(Args[n-1]);
761
762 switch (I->Op)
763 {
764 case Item::Remove:
765 Args[n++] = "--force-depends";
766 Size += strlen(Args[n-1]);
767 Args[n++] = "--force-remove-essential";
768 Size += strlen(Args[n-1]);
769 Args[n++] = "--remove";
770 Size += strlen(Args[n-1]);
771 break;
772
773 case Item::Purge:
774 Args[n++] = "--force-depends";
775 Size += strlen(Args[n-1]);
776 Args[n++] = "--force-remove-essential";
777 Size += strlen(Args[n-1]);
778 Args[n++] = "--purge";
779 Size += strlen(Args[n-1]);
780 break;
781
782 case Item::Configure:
783 Args[n++] = "--configure";
784 Size += strlen(Args[n-1]);
785 break;
786
787 case Item::ConfigurePending:
788 Args[n++] = "--configure";
789 Size += strlen(Args[n-1]);
790 Args[n++] = "--pending";
791 Size += strlen(Args[n-1]);
792 break;
793
794 case Item::TriggersPending:
795 Args[n++] = "--triggers-only";
796 Size += strlen(Args[n-1]);
797 Args[n++] = "--pending";
798 Size += strlen(Args[n-1]);
799 break;
800
801 case Item::Install:
802 Args[n++] = "--unpack";
803 Size += strlen(Args[n-1]);
804 Args[n++] = "--auto-deconfigure";
805 Size += strlen(Args[n-1]);
806 break;
807 }
808
809 if (NoTriggers == true && I->Op != Item::TriggersPending &&
810 I->Op != Item::ConfigurePending)
811 {
812 Args[n++] = "--no-triggers";
813 Size += strlen(Args[n-1]);
814 }
815
816 // Write in the file or package names
817 if (I->Op == Item::Install)
818 {
819 for (;I != J && Size < MaxArgBytes; I++)
820 {
821 if (I->File[0] != '/')
822 return _error->Error("Internal Error, Pathname to install is not absolute '%s'",I->File.c_str());
823 Args[n++] = I->File.c_str();
824 Size += strlen(Args[n-1]);
825 }
826 }
827 else
828 {
829 for (;I != J && Size < MaxArgBytes; I++)
830 {
831 if((*I).Pkg.end() == true)
832 continue;
833 Args[n++] = I->Pkg.Name();
834 Size += strlen(Args[n-1]);
835 }
836 }
837 Args[n] = 0;
838 J = I;
839
840 if (_config->FindB("Debug::pkgDPkgPM",false) == true)
841 {
842 for (unsigned int k = 0; k != n; k++)
843 clog << Args[k] << ' ';
844 clog << endl;
845 continue;
846 }
847
848 cout << flush;
849 clog << flush;
850 cerr << flush;
851
852 /* Mask off sig int/quit. We do this because dpkg also does when
853 it forks scripts. What happens is that when you hit ctrl-c it sends
854 it to all processes in the group. Since dpkg ignores the signal
855 it doesn't die but we do! So we must also ignore it */
856 sighandler_t old_SIGQUIT = signal(SIGQUIT,SIG_IGN);
857 sighandler_t old_SIGINT = signal(SIGINT,SIG_IGN);
858
859 // ignore SIGHUP as well (debian #463030)
860 sighandler_t old_SIGHUP = signal(SIGHUP,SIG_IGN);
861
862 struct termios tt;
863 struct winsize win;
864 int master = -1;
865 int slave = -1;
866
867 // if tcgetattr does not return zero there was a error
868 // and we do not do any pty magic
869 if (tcgetattr(0, &tt) == 0)
870 {
871 ioctl(0, TIOCGWINSZ, (char *)&win);
872 if (openpty(&master, &slave, NULL, &tt, &win) < 0)
873 {
874 const char *s = _("Can not write log, openpty() "
875 "failed (/dev/pts not mounted?)\n");
876 fprintf(stderr, "%s",s);
877 fprintf(term_out, "%s",s);
878 master = slave = -1;
879 } else {
880 struct termios rtt;
881 rtt = tt;
882 cfmakeraw(&rtt);
883 rtt.c_lflag &= ~ECHO;
884 // block SIGTTOU during tcsetattr to prevent a hang if
885 // the process is a member of the background process group
886 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
887 sigemptyset(&sigmask);
888 sigaddset(&sigmask, SIGTTOU);
889 sigprocmask(SIG_BLOCK,&sigmask, &original_sigmask);
890 tcsetattr(0, TCSAFLUSH, &rtt);
891 sigprocmask(SIG_SETMASK, &original_sigmask, 0);
892 }
893 }
894
895 // Fork dpkg
896 pid_t Child;
897 _config->Set("APT::Keep-Fds::",fd[1]);
898 // send status information that we are about to fork dpkg
899 if(OutStatusFd > 0) {
900 ostringstream status;
901 status << "pmstatus:dpkg-exec:"
902 << (PackagesDone/float(PackagesTotal)*100.0)
903 << ":" << _("Running dpkg")
904 << endl;
905 write(OutStatusFd, status.str().c_str(), status.str().size());
906 }
907 Child = ExecFork();
908
909 // This is the child
910 if (Child == 0)
911 {
912 if(slave >= 0 && master >= 0)
913 {
914 setsid();
915 ioctl(slave, TIOCSCTTY, 0);
916 close(master);
917 dup2(slave, 0);
918 dup2(slave, 1);
919 dup2(slave, 2);
920 close(slave);
921 }
922 close(fd[0]); // close the read end of the pipe
923
924 if (_config->FindDir("DPkg::Chroot-Directory","/") != "/")
925 {
926 std::cerr << "Chrooting into "
927 << _config->FindDir("DPkg::Chroot-Directory")
928 << std::endl;
929 if (chroot(_config->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
930 _exit(100);
931 }
932
933 if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
934 _exit(100);
935
936 if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
937 {
938 int Flags,dummy;
939 if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
940 _exit(100);
941
942 // Discard everything in stdin before forking dpkg
943 if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
944 _exit(100);
945
946 while (read(STDIN_FILENO,&dummy,1) == 1);
947
948 if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
949 _exit(100);
950 }
951
952 /* No Job Control Stop Env is a magic dpkg var that prevents it
953 from using sigstop */
954 putenv((char *)"DPKG_NO_TSTP=yes");
955 execvp(Args[0],(char **)Args);
956 cerr << "Could not exec dpkg!" << endl;
957 _exit(100);
958 }
959
960 // apply ionice
961 if (_config->FindB("DPkg::UseIoNice", false) == true)
962 ionice(Child);
963
964 // clear the Keep-Fd again
965 _config->Clear("APT::Keep-Fds",fd[1]);
966
967 // Wait for dpkg
968 int Status = 0;
969
970 // we read from dpkg here
971 int const _dpkgin = fd[0];
972 close(fd[1]); // close the write end of the pipe
973
974 if(slave > 0)
975 close(slave);
976
977 // setups fds
978 sigemptyset(&sigmask);
979 sigprocmask(SIG_BLOCK,&sigmask,&original_sigmask);
980
981 // the result of the waitpid call
982 int res;
983 int select_ret;
984 while ((res=waitpid(Child,&Status, WNOHANG)) != Child) {
985 if(res < 0) {
986 // FIXME: move this to a function or something, looks ugly here
987 // error handling, waitpid returned -1
988 if (errno == EINTR)
989 continue;
990 RunScripts("DPkg::Post-Invoke");
991
992 // Restore sig int/quit
993 signal(SIGQUIT,old_SIGQUIT);
994 signal(SIGINT,old_SIGINT);
995 signal(SIGHUP,old_SIGHUP);
996 return _error->Errno("waitpid","Couldn't wait for subprocess");
997 }
998 // wait for input or output here
999 FD_ZERO(&rfds);
1000 if (!stdin_is_dev_null)
1001 FD_SET(0, &rfds);
1002 FD_SET(_dpkgin, &rfds);
1003 if(master >= 0)
1004 FD_SET(master, &rfds);
1005 tv.tv_sec = 1;
1006 tv.tv_nsec = 0;
1007 select_ret = pselect(max(master, _dpkgin)+1, &rfds, NULL, NULL,
1008 &tv, &original_sigmask);
1009 if (select_ret < 0 && (errno == EINVAL || errno == ENOSYS))
1010 select_ret = racy_pselect(max(master, _dpkgin)+1, &rfds, NULL,
1011 NULL, &tv, &original_sigmask);
1012 if (select_ret == 0)
1013 continue;
1014 else if (select_ret < 0 && errno == EINTR)
1015 continue;
1016 else if (select_ret < 0)
1017 {
1018 perror("select() returned error");
1019 continue;
1020 }
1021
1022 if(master >= 0 && FD_ISSET(master, &rfds))
1023 DoTerminalPty(master);
1024 if(master >= 0 && FD_ISSET(0, &rfds))
1025 DoStdin(master);
1026 if(FD_ISSET(_dpkgin, &rfds))
1027 DoDpkgStatusFd(_dpkgin, OutStatusFd);
1028 }
1029 close(_dpkgin);
1030
1031 // Restore sig int/quit
1032 signal(SIGQUIT,old_SIGQUIT);
1033 signal(SIGINT,old_SIGINT);
1034 signal(SIGHUP,old_SIGHUP);
1035
1036 if(master >= 0)
1037 {
1038 tcsetattr(0, TCSAFLUSH, &tt);
1039 close(master);
1040 }
1041
1042 // Check for an error code.
1043 if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
1044 {
1045 // if it was set to "keep-dpkg-runing" then we won't return
1046 // here but keep the loop going and just report it as a error
1047 // for later
1048 bool const stopOnError = _config->FindB("Dpkg::StopOnError",true);
1049
1050 if(stopOnError)
1051 RunScripts("DPkg::Post-Invoke");
1052
1053 if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
1054 _error->Error("Sub-process %s received a segmentation fault.",Args[0]);
1055 else if (WIFEXITED(Status) != 0)
1056 _error->Error("Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
1057 else
1058 _error->Error("Sub-process %s exited unexpectedly",Args[0]);
1059
1060 if(stopOnError)
1061 {
1062 CloseLog();
1063 return false;
1064 }
1065 }
1066 }
1067 CloseLog();
1068
1069 if (RunScripts("DPkg::Post-Invoke") == false)
1070 return false;
1071
1072 Cache.writeStateFile(NULL);
1073 return true;
1074 }
1075 /*}}}*/
1076 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1077 // ---------------------------------------------------------------------
1078 /* */
1079 void pkgDPkgPM::Reset()
1080 {
1081 List.erase(List.begin(),List.end());
1082 }
1083 /*}}}*/
1084 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1085 // ---------------------------------------------------------------------
1086 /* */
1087 void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
1088 {
1089 string pkgname, reportfile, srcpkgname, pkgver, arch;
1090 string::size_type pos;
1091 FILE *report;
1092
1093 if (_config->FindB("Dpkg::ApportFailureReport",true) == false)
1094 {
1095 std::clog << "configured to not write apport reports" << std::endl;
1096 return;
1097 }
1098
1099 // only report the first errors
1100 if(pkgFailures > _config->FindI("APT::Apport::MaxReports", 3))
1101 {
1102 std::clog << _("No apport report written because MaxReports is reached already") << std::endl;
1103 return;
1104 }
1105
1106 // check if its not a follow up error
1107 const char *needle = dgettext("dpkg", "dependency problems - leaving unconfigured");
1108 if(strstr(errormsg, needle) != NULL) {
1109 std::clog << _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl;
1110 return;
1111 }
1112
1113 // do not report disk-full failures
1114 if(strstr(errormsg, strerror(ENOSPC)) != NULL) {
1115 std::clog << _("No apport report written because the error message indicates a disk full error") << std::endl;
1116 return;
1117 }
1118
1119 // do not report out-of-memory failures
1120 if(strstr(errormsg, strerror(ENOMEM)) != NULL) {
1121 std::clog << _("No apport report written because the error message indicates a out of memory error") << std::endl;
1122 return;
1123 }
1124
1125 // do not report dpkg I/O errors
1126 // XXX - this message is localized, but this only matches the English version. This is better than nothing.
1127 if(strstr(errormsg, "short read in buffer_copy (")) {
1128 std::clog << _("No apport report written because the error message indicates a dpkg I/O error") << std::endl;
1129 return;
1130 }
1131
1132 // get the pkgname and reportfile
1133 pkgname = flNotDir(pkgpath);
1134 pos = pkgname.find('_');
1135 if(pos != string::npos)
1136 pkgname = pkgname.substr(0, pos);
1137
1138 // find the package versin and source package name
1139 pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
1140 if (Pkg.end() == true)
1141 return;
1142 pkgCache::VerIterator Ver = Cache.GetCandidateVer(Pkg);
1143 if (Ver.end() == true)
1144 return;
1145 pkgver = Ver.VerStr() == NULL ? "unknown" : Ver.VerStr();
1146 pkgRecords Recs(Cache);
1147 pkgRecords::Parser &Parse = Recs.Lookup(Ver.FileList());
1148 srcpkgname = Parse.SourcePkg();
1149 if(srcpkgname.empty())
1150 srcpkgname = pkgname;
1151
1152 // if the file exists already, we check:
1153 // - if it was reported already (touched by apport).
1154 // If not, we do nothing, otherwise
1155 // we overwrite it. This is the same behaviour as apport
1156 // - if we have a report with the same pkgversion already
1157 // then we skip it
1158 reportfile = flCombine("/var/crash",pkgname+".0.crash");
1159 if(FileExists(reportfile))
1160 {
1161 struct stat buf;
1162 char strbuf[255];
1163
1164 // check atime/mtime
1165 stat(reportfile.c_str(), &buf);
1166 if(buf.st_mtime > buf.st_atime)
1167 return;
1168
1169 // check if the existing report is the same version
1170 report = fopen(reportfile.c_str(),"r");
1171 while(fgets(strbuf, sizeof(strbuf), report) != NULL)
1172 {
1173 if(strstr(strbuf,"Package:") == strbuf)
1174 {
1175 char pkgname[255], version[255];
1176 if(sscanf(strbuf, "Package: %s %s", pkgname, version) == 2)
1177 if(strcmp(pkgver.c_str(), version) == 0)
1178 {
1179 fclose(report);
1180 return;
1181 }
1182 }
1183 }
1184 fclose(report);
1185 }
1186
1187 // now write the report
1188 arch = _config->Find("APT::Architecture");
1189 report = fopen(reportfile.c_str(),"w");
1190 if(report == NULL)
1191 return;
1192 if(_config->FindB("DPkgPM::InitialReportOnly",false) == true)
1193 chmod(reportfile.c_str(), 0);
1194 else
1195 chmod(reportfile.c_str(), 0600);
1196 fprintf(report, "ProblemType: Package\n");
1197 fprintf(report, "Architecture: %s\n", arch.c_str());
1198 time_t now = time(NULL);
1199 fprintf(report, "Date: %s" , ctime(&now));
1200 fprintf(report, "Package: %s %s\n", pkgname.c_str(), pkgver.c_str());
1201 fprintf(report, "SourcePackage: %s\n", srcpkgname.c_str());
1202 fprintf(report, "ErrorMessage:\n %s\n", errormsg);
1203
1204 // ensure that the log is flushed
1205 if(term_out)
1206 fflush(term_out);
1207
1208 // attach terminal log it if we have it
1209 string logfile_name = _config->FindFile("Dir::Log::Terminal");
1210 if (!logfile_name.empty())
1211 {
1212 FILE *log = NULL;
1213 char buf[1024];
1214
1215 fprintf(report, "DpkgTerminalLog:\n");
1216 log = fopen(logfile_name.c_str(),"r");
1217 if(log != NULL)
1218 {
1219 while( fgets(buf, sizeof(buf), log) != NULL)
1220 fprintf(report, " %s", buf);
1221 fclose(log);
1222 }
1223 }
1224
1225 // log the ordering
1226 const char *ops_str[] = {"Install", "Configure","Remove","Purge"};
1227 fprintf(report, "AptOrdering:\n");
1228 for (vector<Item>::iterator I = List.begin(); I != List.end(); I++)
1229 fprintf(report, " %s: %s\n", (*I).Pkg.Name(), ops_str[(*I).Op]);
1230
1231 // attach dmesg log (to learn about segfaults)
1232 if (FileExists("/bin/dmesg"))
1233 {
1234 FILE *log = NULL;
1235 char buf[1024];
1236
1237 fprintf(report, "Dmesg:\n");
1238 log = popen("/bin/dmesg","r");
1239 if(log != NULL)
1240 {
1241 while( fgets(buf, sizeof(buf), log) != NULL)
1242 fprintf(report, " %s", buf);
1243 fclose(log);
1244 }
1245 }
1246
1247 // attach df -l log (to learn about filesystem status)
1248 if (FileExists("/bin/df"))
1249 {
1250 FILE *log = NULL;
1251 char buf[1024];
1252
1253 fprintf(report, "Df:\n");
1254 log = popen("/bin/df -l","r");
1255 if(log != NULL)
1256 {
1257 while( fgets(buf, sizeof(buf), log) != NULL)
1258 fprintf(report, " %s", buf);
1259 fclose(log);
1260 }
1261 }
1262
1263 fclose(report);
1264
1265 }
1266 /*}}}*/