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