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