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