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