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