]> git.saurik.com Git - apt.git/blob - apt-pkg/deb/dpkgpm.cc
merged from davids branch
[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/strutl.h>
16 #include <apti18n.h>
17 #include <apt-pkg/fileutl.h>
18
19 #include <unistd.h>
20 #include <stdlib.h>
21 #include <fcntl.h>
22 #include <sys/select.h>
23 #include <sys/types.h>
24 #include <sys/wait.h>
25 #include <signal.h>
26 #include <errno.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <algorithm>
30 #include <sstream>
31 #include <map>
32
33 #include <termios.h>
34 #include <unistd.h>
35 #include <sys/ioctl.h>
36 #include <pty.h>
37
38 #include <config.h>
39 #include <apti18n.h>
40 /*}}}*/
41
42 using namespace std;
43
44 namespace
45 {
46 // Maps the dpkg "processing" info to human readable names. Entry 0
47 // of each array is the key, entry 1 is the value.
48 const std::pair<const char *, const char *> PackageProcessingOps[] = {
49 std::make_pair("install", N_("Installing %s")),
50 std::make_pair("configure", N_("Configuring %s")),
51 std::make_pair("remove", N_("Removing %s")),
52 std::make_pair("purge", N_("Completely removing %s")),
53 std::make_pair("trigproc", N_("Running post-installation trigger %s"))
54 };
55
56 const std::pair<const char *, const char *> * const PackageProcessingOpsBegin = PackageProcessingOps;
57 const std::pair<const char *, const char *> * const PackageProcessingOpsEnd = PackageProcessingOps + sizeof(PackageProcessingOps) / sizeof(PackageProcessingOps[0]);
58
59 // Predicate to test whether an entry in the PackageProcessingOps
60 // array matches a string.
61 class MatchProcessingOp
62 {
63 const char *target;
64
65 public:
66 MatchProcessingOp(const char *the_target)
67 : target(the_target)
68 {
69 }
70
71 bool operator()(const std::pair<const char *, const char *> &pair) const
72 {
73 return strcmp(pair.first, target) == 0;
74 }
75 };
76 }
77
78 /* helper function to ionice the given PID
79
80 there is no C header for ionice yet - just the syscall interface
81 so we use the binary from util-linux
82 */
83 static bool
84 ionice(int PID)
85 {
86 if (!FileExists("/usr/bin/ionice"))
87 return false;
88 pid_t Process = ExecFork();
89 if (Process == 0)
90 {
91 char buf[32];
92 snprintf(buf, sizeof(buf), "-p%d", PID);
93 const char *Args[4];
94 Args[0] = "/usr/bin/ionice";
95 Args[1] = "-c3";
96 Args[2] = buf;
97 Args[3] = 0;
98 execv(Args[0], (char **)Args);
99 }
100 return ExecWait(Process, "ionice");
101 }
102
103 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
104 // ---------------------------------------------------------------------
105 /* */
106 pkgDPkgPM::pkgDPkgPM(pkgDepCache *Cache)
107 : pkgPackageManager(Cache), dpkgbuf_pos(0),
108 term_out(NULL), history_out(NULL), PackagesDone(0), PackagesTotal(0)
109 {
110 }
111 /*}}}*/
112 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
113 // ---------------------------------------------------------------------
114 /* */
115 pkgDPkgPM::~pkgDPkgPM()
116 {
117 }
118 /*}}}*/
119 // DPkgPM::Install - Install a package /*{{{*/
120 // ---------------------------------------------------------------------
121 /* Add an install operation to the sequence list */
122 bool pkgDPkgPM::Install(PkgIterator Pkg,string File)
123 {
124 if (File.empty() == true || Pkg.end() == true)
125 return _error->Error("Internal Error, No file name for %s",Pkg.Name());
126
127 // If the filename string begins with DPkg::Chroot-Directory, return the
128 // substr that is within the chroot so dpkg can access it.
129 string const chrootdir = _config->FindDir("DPkg::Chroot-Directory","/");
130 if (chrootdir != "/" && File.find(chrootdir) == 0)
131 {
132 size_t len = chrootdir.length();
133 if (chrootdir.at(len - 1) == '/')
134 len--;
135 List.push_back(Item(Item::Install,Pkg,File.substr(len)));
136 }
137 else
138 List.push_back(Item(Item::Install,Pkg,File));
139
140 return true;
141 }
142 /*}}}*/
143 // DPkgPM::Configure - Configure a package /*{{{*/
144 // ---------------------------------------------------------------------
145 /* Add a configure operation to the sequence list */
146 bool pkgDPkgPM::Configure(PkgIterator Pkg)
147 {
148 if (Pkg.end() == true)
149 return false;
150
151 List.push_back(Item(Item::Configure, Pkg));
152
153 // Use triggers for config calls if we configure "smart"
154 // as otherwise Pre-Depends will not be satisfied, see #526774
155 if (_config->FindB("DPkg::TriggersPending", false) == true)
156 List.push_back(Item(Item::TriggersPending, PkgIterator()));
157
158 return true;
159 }
160 /*}}}*/
161 // DPkgPM::Remove - Remove a package /*{{{*/
162 // ---------------------------------------------------------------------
163 /* Add a remove operation to the sequence list */
164 bool pkgDPkgPM::Remove(PkgIterator Pkg,bool Purge)
165 {
166 if (Pkg.end() == true)
167 return false;
168
169 if (Purge == true)
170 List.push_back(Item(Item::Purge,Pkg));
171 else
172 List.push_back(Item(Item::Remove,Pkg));
173 return true;
174 }
175 /*}}}*/
176 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
177 // ---------------------------------------------------------------------
178 /* This is part of the helper script communication interface, it sends
179 very complete information down to the other end of the pipe.*/
180 bool pkgDPkgPM::SendV2Pkgs(FILE *F)
181 {
182 fprintf(F,"VERSION 2\n");
183
184 /* Write out all of the configuration directives by walking the
185 configuration tree */
186 const Configuration::Item *Top = _config->Tree(0);
187 for (; Top != 0;)
188 {
189 if (Top->Value.empty() == false)
190 {
191 fprintf(F,"%s=%s\n",
192 QuoteString(Top->FullTag(),"=\"\n").c_str(),
193 QuoteString(Top->Value,"\n").c_str());
194 }
195
196 if (Top->Child != 0)
197 {
198 Top = Top->Child;
199 continue;
200 }
201
202 while (Top != 0 && Top->Next == 0)
203 Top = Top->Parent;
204 if (Top != 0)
205 Top = Top->Next;
206 }
207 fprintf(F,"\n");
208
209 // Write out the package actions in order.
210 for (vector<Item>::iterator I = List.begin(); I != List.end(); I++)
211 {
212 if(I->Pkg.end() == true)
213 continue;
214
215 pkgDepCache::StateCache &S = Cache[I->Pkg];
216
217 fprintf(F,"%s ",I->Pkg.Name());
218 // Current version
219 if (I->Pkg->CurrentVer == 0)
220 fprintf(F,"- ");
221 else
222 fprintf(F,"%s ",I->Pkg.CurrentVer().VerStr());
223
224 // Show the compare operator
225 // Target version
226 if (S.InstallVer != 0)
227 {
228 int Comp = 2;
229 if (I->Pkg->CurrentVer != 0)
230 Comp = S.InstVerIter(Cache).CompareVer(I->Pkg.CurrentVer());
231 if (Comp < 0)
232 fprintf(F,"> ");
233 if (Comp == 0)
234 fprintf(F,"= ");
235 if (Comp > 0)
236 fprintf(F,"< ");
237 fprintf(F,"%s ",S.InstVerIter(Cache).VerStr());
238 }
239 else
240 fprintf(F,"> - ");
241
242 // Show the filename/operation
243 if (I->Op == Item::Install)
244 {
245 // No errors here..
246 if (I->File[0] != '/')
247 fprintf(F,"**ERROR**\n");
248 else
249 fprintf(F,"%s\n",I->File.c_str());
250 }
251 if (I->Op == Item::Configure)
252 fprintf(F,"**CONFIGURE**\n");
253 if (I->Op == Item::Remove ||
254 I->Op == Item::Purge)
255 fprintf(F,"**REMOVE**\n");
256
257 if (ferror(F) != 0)
258 return false;
259 }
260 return true;
261 }
262 /*}}}*/
263 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
264 // ---------------------------------------------------------------------
265 /* This looks for a list of scripts to run from the configuration file
266 each one is run and is fed on standard input a list of all .deb files
267 that are due to be installed. */
268 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf)
269 {
270 Configuration::Item const *Opts = _config->Tree(Cnf);
271 if (Opts == 0 || Opts->Child == 0)
272 return true;
273 Opts = Opts->Child;
274
275 unsigned int Count = 1;
276 for (; Opts != 0; Opts = Opts->Next, Count++)
277 {
278 if (Opts->Value.empty() == true)
279 continue;
280
281 // Determine the protocol version
282 string OptSec = Opts->Value;
283 string::size_type Pos;
284 if ((Pos = OptSec.find(' ')) == string::npos || Pos == 0)
285 Pos = OptSec.length();
286 OptSec = "DPkg::Tools::Options::" + string(Opts->Value.c_str(),Pos);
287
288 unsigned int Version = _config->FindI(OptSec+"::Version",1);
289
290 // Create the pipes
291 int Pipes[2];
292 if (pipe(Pipes) != 0)
293 return _error->Errno("pipe","Failed to create IPC pipe to subprocess");
294 SetCloseExec(Pipes[0],true);
295 SetCloseExec(Pipes[1],true);
296
297 // Purified Fork for running the script
298 pid_t Process = ExecFork();
299 if (Process == 0)
300 {
301 // Setup the FDs
302 dup2(Pipes[0],STDIN_FILENO);
303 SetCloseExec(STDOUT_FILENO,false);
304 SetCloseExec(STDIN_FILENO,false);
305 SetCloseExec(STDERR_FILENO,false);
306
307 const char *Args[4];
308 Args[0] = "/bin/sh";
309 Args[1] = "-c";
310 Args[2] = Opts->Value.c_str();
311 Args[3] = 0;
312 execv(Args[0],(char **)Args);
313 _exit(100);
314 }
315 close(Pipes[0]);
316 FILE *F = fdopen(Pipes[1],"w");
317 if (F == 0)
318 return _error->Errno("fdopen","Faild to open new FD");
319
320 // Feed it the filenames.
321 bool Die = false;
322 if (Version <= 1)
323 {
324 for (vector<Item>::iterator I = List.begin(); I != List.end(); I++)
325 {
326 // Only deal with packages to be installed from .deb
327 if (I->Op != Item::Install)
328 continue;
329
330 // No errors here..
331 if (I->File[0] != '/')
332 continue;
333
334 /* Feed the filename of each package that is pending install
335 into the pipe. */
336 fprintf(F,"%s\n",I->File.c_str());
337 if (ferror(F) != 0)
338 {
339 Die = true;
340 break;
341 }
342 }
343 }
344 else
345 Die = !SendV2Pkgs(F);
346
347 fclose(F);
348
349 // Clean up the sub process
350 if (ExecWait(Process,Opts->Value.c_str()) == false)
351 return _error->Error("Failure running script %s",Opts->Value.c_str());
352 }
353
354 return true;
355 }
356
357 /*}}}*/
358 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
359 // ---------------------------------------------------------------------
360 /*
361 */
362 void pkgDPkgPM::DoStdin(int master)
363 {
364 unsigned char input_buf[256] = {0,};
365 ssize_t len = read(0, input_buf, sizeof(input_buf));
366 if (len)
367 write(master, input_buf, len);
368 else
369 stdin_is_dev_null = true;
370 }
371 /*}}}*/
372 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
373 // ---------------------------------------------------------------------
374 /*
375 * read the terminal pty and write log
376 */
377 void pkgDPkgPM::DoTerminalPty(int master)
378 {
379 unsigned char term_buf[1024] = {0,0, };
380
381 ssize_t len=read(master, term_buf, sizeof(term_buf));
382 if(len == -1 && errno == EIO)
383 {
384 // this happens when the child is about to exit, we
385 // give it time to actually exit, otherwise we run
386 // into a race
387 usleep(500000);
388 return;
389 }
390 if(len <= 0)
391 return;
392 write(1, term_buf, len);
393 if(term_out)
394 fwrite(term_buf, len, sizeof(char), term_out);
395 }
396 /*}}}*/
397 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
398 // ---------------------------------------------------------------------
399 /*
400 */
401 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd, char *line)
402 {
403 bool const Debug = _config->FindB("Debug::pkgDPkgProgressReporting",false);
404 // the status we output
405 ostringstream status;
406
407 if (Debug == true)
408 std::clog << "got from dpkg '" << line << "'" << std::endl;
409
410
411 /* dpkg sends strings like this:
412 'status: <pkg>: <pkg qstate>'
413 errors look like this:
414 '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
415 and conffile-prompt like this
416 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
417
418 Newer versions of dpkg sent also:
419 'processing: install: pkg'
420 'processing: configure: pkg'
421 'processing: remove: pkg'
422 'processing: purge: pkg' - but for apt is it a ignored "unknown" action
423 'processing: trigproc: trigger'
424
425 */
426 char* list[5];
427 // dpkg sends multiline error messages sometimes (see
428 // #374195 for a example. we should support this by
429 // either patching dpkg to not send multiline over the
430 // statusfd or by rewriting the code here to deal with
431 // it. for now we just ignore it and not crash
432 TokSplitString(':', line, list, sizeof(list)/sizeof(list[0]));
433 if( list[0] == NULL || list[1] == NULL || list[2] == NULL)
434 {
435 if (Debug == true)
436 std::clog << "ignoring line: not enough ':'" << std::endl;
437 return;
438 }
439 const char* const pkg = list[1];
440 const char* action = _strstrip(list[2]);
441
442 // 'processing' from dpkg looks like
443 // 'processing: action: pkg'
444 if(strncmp(list[0], "processing", strlen("processing")) == 0)
445 {
446 char s[200];
447 const char* const pkg_or_trigger = _strstrip(list[2]);
448 action = _strstrip( list[1]);
449 const std::pair<const char *, const char *> * const iter =
450 std::find_if(PackageProcessingOpsBegin,
451 PackageProcessingOpsEnd,
452 MatchProcessingOp(action));
453 if(iter == PackageProcessingOpsEnd)
454 {
455 if (Debug == true)
456 std::clog << "ignoring unknown action: " << action << std::endl;
457 return;
458 }
459 snprintf(s, sizeof(s), _(iter->second), pkg_or_trigger);
460
461 status << "pmstatus:" << pkg_or_trigger
462 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
463 << ":" << s
464 << endl;
465 if(OutStatusFd > 0)
466 write(OutStatusFd, status.str().c_str(), status.str().size());
467 if (Debug == true)
468 std::clog << "send: '" << status.str() << "'" << endl;
469 return;
470 }
471
472 if(strncmp(action,"error",strlen("error")) == 0)
473 {
474 status << "pmerror:" << list[1]
475 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
476 << ":" << list[3]
477 << endl;
478 if(OutStatusFd > 0)
479 write(OutStatusFd, status.str().c_str(), status.str().size());
480 if (Debug == true)
481 std::clog << "send: '" << status.str() << "'" << endl;
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(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 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 if (_config->Exists("Commandline::AsString") == true)
630 WriteHistoryTag("Commandline", _config->Find("Commandline::AsString"));
631 WriteHistoryTag("Install", install);
632 WriteHistoryTag("Upgrade", upgrade);
633 WriteHistoryTag("Downgrade",downgrade);
634 WriteHistoryTag("Remove",remove);
635 WriteHistoryTag("Purge",purge);
636 fflush(history_out);
637 }
638
639 return true;
640 }
641 /*}}}*/
642 // DPkg::CloseLog /*{{{*/
643 bool pkgDPkgPM::CloseLog()
644 {
645 char timestr[200];
646 time_t t = time(NULL);
647 struct tm *tmp = localtime(&t);
648 strftime(timestr, sizeof(timestr), "%F %T", tmp);
649
650 if(term_out)
651 {
652 fprintf(term_out, "Log ended: ");
653 fprintf(term_out, "%s", timestr);
654 fprintf(term_out, "\n");
655 fclose(term_out);
656 }
657 term_out = NULL;
658
659 if(history_out)
660 {
661 if (dpkg_error.size() > 0)
662 fprintf(history_out, "Error: %s\n", dpkg_error.c_str());
663 fprintf(history_out, "End-Date: %s\n", timestr);
664 fclose(history_out);
665 }
666 history_out = NULL;
667
668 return true;
669 }
670 /*}}}*/
671 /*{{{*/
672 // This implements a racy version of pselect for those architectures
673 // that don't have a working implementation.
674 // FIXME: Probably can be removed on Lenny+1
675 static int racy_pselect(int nfds, fd_set *readfds, fd_set *writefds,
676 fd_set *exceptfds, const struct timespec *timeout,
677 const sigset_t *sigmask)
678 {
679 sigset_t origmask;
680 struct timeval tv;
681 int retval;
682
683 tv.tv_sec = timeout->tv_sec;
684 tv.tv_usec = timeout->tv_nsec/1000;
685
686 sigprocmask(SIG_SETMASK, sigmask, &origmask);
687 retval = select(nfds, readfds, writefds, exceptfds, &tv);
688 sigprocmask(SIG_SETMASK, &origmask, 0);
689 return retval;
690 }
691 /*}}}*/
692 // DPkgPM::Go - Run the sequence /*{{{*/
693 // ---------------------------------------------------------------------
694 /* This globs the operations and calls dpkg
695 *
696 * If it is called with "OutStatusFd" set to a valid file descriptor
697 * apt will report the install progress over this fd. It maps the
698 * dpkg states a package goes through to human readable (and i10n-able)
699 * names and calculates a percentage for each step.
700 */
701 bool pkgDPkgPM::Go(int OutStatusFd)
702 {
703 fd_set rfds;
704 struct timespec tv;
705 sigset_t sigmask;
706 sigset_t original_sigmask;
707
708 unsigned int const MaxArgs = _config->FindI("Dpkg::MaxArgs",8*1024);
709 unsigned int const MaxArgBytes = _config->FindI("Dpkg::MaxArgBytes",32*1024);
710 bool const NoTriggers = _config->FindB("DPkg::NoTriggers", false);
711
712 if (RunScripts("DPkg::Pre-Invoke") == false)
713 return false;
714
715 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
716 return false;
717
718 // support subpressing of triggers processing for special
719 // cases like d-i that runs the triggers handling manually
720 bool const SmartConf = (_config->Find("PackageManager::Configure", "all") != "all");
721 bool const TriggersPending = _config->FindB("DPkg::TriggersPending", false);
722 if (_config->FindB("DPkg::ConfigurePending", SmartConf) == true)
723 List.push_back(Item(Item::ConfigurePending, PkgIterator()));
724
725 // map the dpkg states to the operations that are performed
726 // (this is sorted in the same way as Item::Ops)
727 static const struct DpkgState DpkgStatesOpMap[][7] = {
728 // Install operation
729 {
730 {"half-installed", N_("Preparing %s")},
731 {"unpacked", N_("Unpacking %s") },
732 {NULL, NULL}
733 },
734 // Configure operation
735 {
736 {"unpacked",N_("Preparing to configure %s") },
737 {"half-configured", N_("Configuring %s") },
738 { "installed", N_("Installed %s")},
739 {NULL, NULL}
740 },
741 // Remove operation
742 {
743 {"half-configured", N_("Preparing for removal of %s")},
744 {"half-installed", N_("Removing %s")},
745 {"config-files", N_("Removed %s")},
746 {NULL, NULL}
747 },
748 // Purge operation
749 {
750 {"config-files", N_("Preparing to completely remove %s")},
751 {"not-installed", N_("Completely removed %s")},
752 {NULL, NULL}
753 },
754 };
755
756 // init the PackageOps map, go over the list of packages that
757 // that will be [installed|configured|removed|purged] and add
758 // them to the PackageOps map (the dpkg states it goes through)
759 // and the PackageOpsTranslations (human readable strings)
760 for (vector<Item>::const_iterator I = List.begin(); I != List.end();I++)
761 {
762 if((*I).Pkg.end() == true)
763 continue;
764
765 string const name = (*I).Pkg.Name();
766 PackageOpsDone[name] = 0;
767 for(int i=0; (DpkgStatesOpMap[(*I).Op][i]).state != NULL; i++)
768 {
769 PackageOps[name].push_back(DpkgStatesOpMap[(*I).Op][i]);
770 PackagesTotal++;
771 }
772 }
773
774 stdin_is_dev_null = false;
775
776 // create log
777 OpenLog();
778
779 // this loop is runs once per operation
780 for (vector<Item>::const_iterator I = List.begin(); I != List.end();)
781 {
782 // Do all actions with the same Op in one run
783 vector<Item>::const_iterator J = I;
784 if (TriggersPending == true)
785 for (; J != List.end(); J++)
786 {
787 if (J->Op == I->Op)
788 continue;
789 if (J->Op != Item::TriggersPending)
790 break;
791 vector<Item>::const_iterator T = J + 1;
792 if (T != List.end() && T->Op == I->Op)
793 continue;
794 break;
795 }
796 else
797 for (; J != List.end() && J->Op == I->Op; J++)
798 /* nothing */;
799
800 // Generate the argument list
801 const char *Args[MaxArgs + 50];
802
803 // Now check if we are within the MaxArgs limit
804 //
805 // this code below is problematic, because it may happen that
806 // the argument list is split in a way that A depends on B
807 // and they are in the same "--configure A B" run
808 // - with the split they may now be configured in different
809 // runs
810 if (J - I > (signed)MaxArgs)
811 J = I + MaxArgs;
812
813 unsigned int n = 0;
814 unsigned long Size = 0;
815 string const Tmp = _config->Find("Dir::Bin::dpkg","dpkg");
816 Args[n++] = Tmp.c_str();
817 Size += strlen(Args[n-1]);
818
819 // Stick in any custom dpkg options
820 Configuration::Item const *Opts = _config->Tree("DPkg::Options");
821 if (Opts != 0)
822 {
823 Opts = Opts->Child;
824 for (; Opts != 0; Opts = Opts->Next)
825 {
826 if (Opts->Value.empty() == true)
827 continue;
828 Args[n++] = Opts->Value.c_str();
829 Size += Opts->Value.length();
830 }
831 }
832
833 char status_fd_buf[20];
834 int fd[2];
835 pipe(fd);
836
837 Args[n++] = "--status-fd";
838 Size += strlen(Args[n-1]);
839 snprintf(status_fd_buf,sizeof(status_fd_buf),"%i", fd[1]);
840 Args[n++] = status_fd_buf;
841 Size += strlen(Args[n-1]);
842
843 switch (I->Op)
844 {
845 case Item::Remove:
846 Args[n++] = "--force-depends";
847 Size += strlen(Args[n-1]);
848 Args[n++] = "--force-remove-essential";
849 Size += strlen(Args[n-1]);
850 Args[n++] = "--remove";
851 Size += strlen(Args[n-1]);
852 break;
853
854 case Item::Purge:
855 Args[n++] = "--force-depends";
856 Size += strlen(Args[n-1]);
857 Args[n++] = "--force-remove-essential";
858 Size += strlen(Args[n-1]);
859 Args[n++] = "--purge";
860 Size += strlen(Args[n-1]);
861 break;
862
863 case Item::Configure:
864 Args[n++] = "--configure";
865 Size += strlen(Args[n-1]);
866 break;
867
868 case Item::ConfigurePending:
869 Args[n++] = "--configure";
870 Size += strlen(Args[n-1]);
871 Args[n++] = "--pending";
872 Size += strlen(Args[n-1]);
873 break;
874
875 case Item::TriggersPending:
876 Args[n++] = "--triggers-only";
877 Size += strlen(Args[n-1]);
878 Args[n++] = "--pending";
879 Size += strlen(Args[n-1]);
880 break;
881
882 case Item::Install:
883 Args[n++] = "--unpack";
884 Size += strlen(Args[n-1]);
885 Args[n++] = "--auto-deconfigure";
886 Size += strlen(Args[n-1]);
887 break;
888 }
889
890 if (NoTriggers == true && I->Op != Item::TriggersPending &&
891 I->Op != Item::ConfigurePending)
892 {
893 Args[n++] = "--no-triggers";
894 Size += strlen(Args[n-1]);
895 }
896
897 // Write in the file or package names
898 if (I->Op == Item::Install)
899 {
900 for (;I != J && Size < MaxArgBytes; I++)
901 {
902 if (I->File[0] != '/')
903 return _error->Error("Internal Error, Pathname to install is not absolute '%s'",I->File.c_str());
904 Args[n++] = I->File.c_str();
905 Size += strlen(Args[n-1]);
906 }
907 }
908 else
909 {
910 for (;I != J && Size < MaxArgBytes; I++)
911 {
912 if((*I).Pkg.end() == true)
913 continue;
914 Args[n++] = I->Pkg.Name();
915 Size += strlen(Args[n-1]);
916 }
917 }
918 Args[n] = 0;
919 J = I;
920
921 if (_config->FindB("Debug::pkgDPkgPM",false) == true)
922 {
923 for (unsigned int k = 0; k != n; k++)
924 clog << Args[k] << ' ';
925 clog << endl;
926 continue;
927 }
928
929 cout << flush;
930 clog << flush;
931 cerr << flush;
932
933 /* Mask off sig int/quit. We do this because dpkg also does when
934 it forks scripts. What happens is that when you hit ctrl-c it sends
935 it to all processes in the group. Since dpkg ignores the signal
936 it doesn't die but we do! So we must also ignore it */
937 sighandler_t old_SIGQUIT = signal(SIGQUIT,SIG_IGN);
938 sighandler_t old_SIGINT = signal(SIGINT,SIG_IGN);
939
940 // ignore SIGHUP as well (debian #463030)
941 sighandler_t old_SIGHUP = signal(SIGHUP,SIG_IGN);
942
943 struct termios tt;
944 struct winsize win;
945 int master = -1;
946 int slave = -1;
947
948 // if tcgetattr does not return zero there was a error
949 // and we do not do any pty magic
950 if (tcgetattr(0, &tt) == 0)
951 {
952 ioctl(0, TIOCGWINSZ, (char *)&win);
953 if (openpty(&master, &slave, NULL, &tt, &win) < 0)
954 {
955 const char *s = _("Can not write log, openpty() "
956 "failed (/dev/pts not mounted?)\n");
957 fprintf(stderr, "%s",s);
958 if(term_out)
959 fprintf(term_out, "%s",s);
960 master = slave = -1;
961 } else {
962 struct termios rtt;
963 rtt = tt;
964 cfmakeraw(&rtt);
965 rtt.c_lflag &= ~ECHO;
966 rtt.c_lflag |= ISIG;
967 // block SIGTTOU during tcsetattr to prevent a hang if
968 // the process is a member of the background process group
969 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
970 sigemptyset(&sigmask);
971 sigaddset(&sigmask, SIGTTOU);
972 sigprocmask(SIG_BLOCK,&sigmask, &original_sigmask);
973 tcsetattr(0, TCSAFLUSH, &rtt);
974 sigprocmask(SIG_SETMASK, &original_sigmask, 0);
975 }
976 }
977
978 // Fork dpkg
979 pid_t Child;
980 _config->Set("APT::Keep-Fds::",fd[1]);
981 // send status information that we are about to fork dpkg
982 if(OutStatusFd > 0) {
983 ostringstream status;
984 status << "pmstatus:dpkg-exec:"
985 << (PackagesDone/float(PackagesTotal)*100.0)
986 << ":" << _("Running dpkg")
987 << endl;
988 write(OutStatusFd, status.str().c_str(), status.str().size());
989 }
990 Child = ExecFork();
991
992 // This is the child
993 if (Child == 0)
994 {
995 if(slave >= 0 && master >= 0)
996 {
997 setsid();
998 ioctl(slave, TIOCSCTTY, 0);
999 close(master);
1000 dup2(slave, 0);
1001 dup2(slave, 1);
1002 dup2(slave, 2);
1003 close(slave);
1004 }
1005 close(fd[0]); // close the read end of the pipe
1006
1007 if (_config->FindDir("DPkg::Chroot-Directory","/") != "/")
1008 {
1009 std::cerr << "Chrooting into "
1010 << _config->FindDir("DPkg::Chroot-Directory")
1011 << std::endl;
1012 if (chroot(_config->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
1013 _exit(100);
1014 }
1015
1016 if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
1017 _exit(100);
1018
1019 if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
1020 {
1021 int Flags,dummy;
1022 if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
1023 _exit(100);
1024
1025 // Discard everything in stdin before forking dpkg
1026 if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
1027 _exit(100);
1028
1029 while (read(STDIN_FILENO,&dummy,1) == 1);
1030
1031 if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
1032 _exit(100);
1033 }
1034
1035 /* No Job Control Stop Env is a magic dpkg var that prevents it
1036 from using sigstop */
1037 putenv((char *)"DPKG_NO_TSTP=yes");
1038 execvp(Args[0],(char **)Args);
1039 cerr << "Could not exec dpkg!" << endl;
1040 _exit(100);
1041 }
1042
1043 // apply ionice
1044 if (_config->FindB("DPkg::UseIoNice", false) == true)
1045 ionice(Child);
1046
1047 // clear the Keep-Fd again
1048 _config->Clear("APT::Keep-Fds",fd[1]);
1049
1050 // Wait for dpkg
1051 int Status = 0;
1052
1053 // we read from dpkg here
1054 int const _dpkgin = fd[0];
1055 close(fd[1]); // close the write end of the pipe
1056
1057 if(slave > 0)
1058 close(slave);
1059
1060 // setups fds
1061 sigemptyset(&sigmask);
1062 sigprocmask(SIG_BLOCK,&sigmask,&original_sigmask);
1063
1064 // the result of the waitpid call
1065 int res;
1066 int select_ret;
1067 while ((res=waitpid(Child,&Status, WNOHANG)) != Child) {
1068 if(res < 0) {
1069 // FIXME: move this to a function or something, looks ugly here
1070 // error handling, waitpid returned -1
1071 if (errno == EINTR)
1072 continue;
1073 RunScripts("DPkg::Post-Invoke");
1074
1075 // Restore sig int/quit
1076 signal(SIGQUIT,old_SIGQUIT);
1077 signal(SIGINT,old_SIGINT);
1078 signal(SIGHUP,old_SIGHUP);
1079 return _error->Errno("waitpid","Couldn't wait for subprocess");
1080 }
1081
1082 // wait for input or output here
1083 FD_ZERO(&rfds);
1084 if (master >= 0 && !stdin_is_dev_null)
1085 FD_SET(0, &rfds);
1086 FD_SET(_dpkgin, &rfds);
1087 if(master >= 0)
1088 FD_SET(master, &rfds);
1089 tv.tv_sec = 1;
1090 tv.tv_nsec = 0;
1091 select_ret = pselect(max(master, _dpkgin)+1, &rfds, NULL, NULL,
1092 &tv, &original_sigmask);
1093 if (select_ret < 0 && (errno == EINVAL || errno == ENOSYS))
1094 select_ret = racy_pselect(max(master, _dpkgin)+1, &rfds, NULL,
1095 NULL, &tv, &original_sigmask);
1096 if (select_ret == 0)
1097 continue;
1098 else if (select_ret < 0 && errno == EINTR)
1099 continue;
1100 else if (select_ret < 0)
1101 {
1102 perror("select() returned error");
1103 continue;
1104 }
1105
1106 if(master >= 0 && FD_ISSET(master, &rfds))
1107 DoTerminalPty(master);
1108 if(master >= 0 && FD_ISSET(0, &rfds))
1109 DoStdin(master);
1110 if(FD_ISSET(_dpkgin, &rfds))
1111 DoDpkgStatusFd(_dpkgin, OutStatusFd);
1112 }
1113 close(_dpkgin);
1114
1115 // Restore sig int/quit
1116 signal(SIGQUIT,old_SIGQUIT);
1117 signal(SIGINT,old_SIGINT);
1118 signal(SIGHUP,old_SIGHUP);
1119
1120 if(master >= 0)
1121 {
1122 tcsetattr(0, TCSAFLUSH, &tt);
1123 close(master);
1124 }
1125
1126 // Check for an error code.
1127 if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
1128 {
1129 // if it was set to "keep-dpkg-runing" then we won't return
1130 // here but keep the loop going and just report it as a error
1131 // for later
1132 bool const stopOnError = _config->FindB("Dpkg::StopOnError",true);
1133
1134 if(stopOnError)
1135 RunScripts("DPkg::Post-Invoke");
1136
1137 if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
1138 strprintf(dpkg_error, "Sub-process %s received a segmentation fault.",Args[0]);
1139 else if (WIFEXITED(Status) != 0)
1140 strprintf(dpkg_error, "Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
1141 else
1142 strprintf(dpkg_error, "Sub-process %s exited unexpectedly",Args[0]);
1143
1144 if(dpkg_error.size() > 0)
1145 _error->Error(dpkg_error.c_str());
1146
1147 if(stopOnError)
1148 {
1149 CloseLog();
1150 return false;
1151 }
1152 }
1153 }
1154 CloseLog();
1155
1156 if (RunScripts("DPkg::Post-Invoke") == false)
1157 return false;
1158
1159 Cache.writeStateFile(NULL);
1160 return true;
1161 }
1162 /*}}}*/
1163 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1164 // ---------------------------------------------------------------------
1165 /* */
1166 void pkgDPkgPM::Reset()
1167 {
1168 List.erase(List.begin(),List.end());
1169 }
1170 /*}}}*/