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