]> git.saurik.com Git - apt.git/blob - apt-pkg/deb/dpkgpm.cc
add missing changelog entry
[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),
48 term_out(NULL), PackagesDone(0), PackagesTotal(0)
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 unsigned char input_buf[256] = {0,};
346 ssize_t len = read(0, input_buf, sizeof(input_buf));
347 if (len)
348 write(master, input_buf, len);
349 else
350 stdin_is_dev_null = true;
351 }
352 /*}}}*/
353 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
354 // ---------------------------------------------------------------------
355 /*
356 * read the terminal pty and write log
357 */
358 void pkgDPkgPM::DoTerminalPty(int master)
359 {
360 unsigned char term_buf[1024] = {0,0, };
361
362 ssize_t len=read(master, term_buf, sizeof(term_buf));
363 if(len == -1 && errno == EIO)
364 {
365 // this happens when the child is about to exit, we
366 // give it time to actually exit, otherwise we run
367 // into a race
368 usleep(500000);
369 return;
370 }
371 if(len <= 0)
372 return;
373 write(1, term_buf, len);
374 if(term_out)
375 fwrite(term_buf, len, sizeof(char), term_out);
376 }
377 /*}}}*/
378 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
379 // ---------------------------------------------------------------------
380 /*
381 */
382 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd, char *line)
383 {
384 // the status we output
385 ostringstream status;
386
387 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
388 std::clog << "got from dpkg '" << line << "'" << std::endl;
389
390
391 /* dpkg sends strings like this:
392 'status: <pkg>: <pkg qstate>'
393 errors look like this:
394 '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
395 and conffile-prompt like this
396 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
397
398 */
399 char* list[5];
400 // dpkg sends multiline error messages sometimes (see
401 // #374195 for a example. we should support this by
402 // either patching dpkg to not send multiline over the
403 // statusfd or by rewriting the code here to deal with
404 // it. for now we just ignore it and not crash
405 TokSplitString(':', line, list, sizeof(list)/sizeof(list[0]));
406 if( list[0] == NULL || list[1] == NULL || list[2] == NULL)
407 {
408 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
409 std::clog << "ignoring line: not enough ':'" << std::endl;
410 return;
411 }
412 char *pkg = list[1];
413 char *action = _strstrip(list[2]);
414
415 if(strncmp(action,"error",strlen("error")) == 0)
416 {
417 status << "pmerror:" << list[1]
418 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
419 << ":" << list[3]
420 << endl;
421 if(OutStatusFd > 0)
422 write(OutStatusFd, status.str().c_str(), status.str().size());
423 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
424 std::clog << "send: '" << status.str() << "'" << endl;
425 return;
426 }
427 if(strncmp(action,"conffile",strlen("conffile")) == 0)
428 {
429 status << "pmconffile:" << list[1]
430 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
431 << ":" << list[3]
432 << endl;
433 if(OutStatusFd > 0)
434 write(OutStatusFd, status.str().c_str(), status.str().size());
435 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
436 std::clog << "send: '" << status.str() << "'" << endl;
437 return;
438 }
439
440 vector<struct DpkgState> &states = PackageOps[pkg];
441 const char *next_action = NULL;
442 if(PackageOpsDone[pkg] < states.size())
443 next_action = states[PackageOpsDone[pkg]].state;
444 // check if the package moved to the next dpkg state
445 if(next_action && (strcmp(action, next_action) == 0))
446 {
447 // only read the translation if there is actually a next
448 // action
449 const char *translation = _(states[PackageOpsDone[pkg]].str);
450 char s[200];
451 snprintf(s, sizeof(s), translation, pkg);
452
453 // we moved from one dpkg state to a new one, report that
454 PackageOpsDone[pkg]++;
455 PackagesDone++;
456 // build the status str
457 status << "pmstatus:" << pkg
458 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
459 << ":" << s
460 << endl;
461 if(OutStatusFd > 0)
462 write(OutStatusFd, status.str().c_str(), status.str().size());
463 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
464 std::clog << "send: '" << status.str() << "'" << endl;
465 }
466 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
467 std::clog << "(parsed from dpkg) pkg: " << pkg
468 << " action: " << action << endl;
469 }
470
471 // DPkgPM::DoDpkgStatusFd /*{{{*/
472 // ---------------------------------------------------------------------
473 /*
474 */
475 void pkgDPkgPM::DoDpkgStatusFd(int statusfd, int OutStatusFd)
476 {
477 char *p, *q;
478 int len;
479
480 len=read(statusfd, &dpkgbuf[dpkgbuf_pos], sizeof(dpkgbuf)-dpkgbuf_pos);
481 dpkgbuf_pos += len;
482 if(len <= 0)
483 return;
484
485 // process line by line if we have a buffer
486 p = q = dpkgbuf;
487 while((q=(char*)memchr(p, '\n', dpkgbuf+dpkgbuf_pos-p)) != NULL)
488 {
489 *q = 0;
490 ProcessDpkgStatusLine(OutStatusFd, p);
491 p=q+1; // continue with next line
492 }
493
494 // now move the unprocessed bits (after the final \n that is now a 0x0)
495 // to the start and update dpkgbuf_pos
496 p = (char*)memrchr(dpkgbuf, 0, dpkgbuf_pos);
497 if(p == NULL)
498 return;
499
500 // we are interessted in the first char *after* 0x0
501 p++;
502
503 // move the unprocessed tail to the start and update pos
504 memmove(dpkgbuf, p, p-dpkgbuf);
505 dpkgbuf_pos = dpkgbuf+dpkgbuf_pos-p;
506 }
507 /*}}}*/
508
509 bool pkgDPkgPM::OpenLog()
510 {
511 string logdir = _config->FindDir("Dir::Log");
512 if(not FileExists(logdir))
513 return _error->Error(_("Directory '%s' missing"), logdir.c_str());
514 string logfile_name = flCombine(logdir,
515 _config->Find("Dir::Log::Terminal"));
516 if (!logfile_name.empty())
517 {
518 term_out = fopen(logfile_name.c_str(),"a");
519 chmod(logfile_name.c_str(), 0600);
520 // output current time
521 char outstr[200];
522 time_t t = time(NULL);
523 struct tm *tmp = localtime(&t);
524 strftime(outstr, sizeof(outstr), "%F %T", tmp);
525 fprintf(term_out, "\nLog started: ");
526 fprintf(term_out, outstr);
527 fprintf(term_out, "\n");
528 }
529 return true;
530 }
531
532 bool pkgDPkgPM::CloseLog()
533 {
534 if(term_out)
535 {
536 char outstr[200];
537 time_t t = time(NULL);
538 struct tm *tmp = localtime(&t);
539 strftime(outstr, sizeof(outstr), "%F %T", tmp);
540 fprintf(term_out, "Log ended: ");
541 fprintf(term_out, outstr);
542 fprintf(term_out, "\n");
543 fclose(term_out);
544 }
545 term_out = NULL;
546 return true;
547 }
548
549 /*{{{*/
550 // This implements a racy version of pselect for those architectures
551 // that don't have a working implementation.
552 // FIXME: Probably can be removed on Lenny+1
553 static int racy_pselect(int nfds, fd_set *readfds, fd_set *writefds,
554 fd_set *exceptfds, const struct timespec *timeout,
555 const sigset_t *sigmask)
556 {
557 sigset_t origmask;
558 struct timeval tv;
559 int retval;
560
561 tv.tv_sec = timeout->tv_sec;
562 tv.tv_usec = timeout->tv_nsec/1000;
563
564 sigprocmask(SIG_SETMASK, sigmask, &origmask);
565 retval = select(nfds, readfds, writefds, exceptfds, &tv);
566 sigprocmask(SIG_SETMASK, &origmask, 0);
567 return retval;
568 }
569 /*}}}*/
570
571 // DPkgPM::Go - Run the sequence /*{{{*/
572 // ---------------------------------------------------------------------
573 /* This globs the operations and calls dpkg
574 *
575 * If it is called with "OutStatusFd" set to a valid file descriptor
576 * apt will report the install progress over this fd. It maps the
577 * dpkg states a package goes through to human readable (and i10n-able)
578 * names and calculates a percentage for each step.
579 */
580 bool pkgDPkgPM::Go(int OutStatusFd)
581 {
582 unsigned int MaxArgs = _config->FindI("Dpkg::MaxArgs",8*1024);
583 unsigned int MaxArgBytes = _config->FindI("Dpkg::MaxArgBytes",32*1024);
584
585 if (RunScripts("DPkg::Pre-Invoke") == false)
586 return false;
587
588 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
589 return false;
590
591 // map the dpkg states to the operations that are performed
592 // (this is sorted in the same way as Item::Ops)
593 static const struct DpkgState DpkgStatesOpMap[][7] = {
594 // Install operation
595 {
596 {"half-installed", N_("Preparing %s")},
597 {"unpacked", N_("Unpacking %s") },
598 {NULL, NULL}
599 },
600 // Configure operation
601 {
602 {"unpacked",N_("Preparing to configure %s") },
603 {"half-configured", N_("Configuring %s") },
604 #if 0
605 {"triggers-awaited", N_("Processing triggers for %s") },
606 {"triggers-pending", N_("Processing triggers for %s") },
607 #endif
608 { "installed", N_("Installed %s")},
609 {NULL, NULL}
610 },
611 // Remove operation
612 {
613 {"half-configured", N_("Preparing for removal of %s")},
614 #if 0
615 {"triggers-awaited", N_("Preparing for removal of %s")},
616 {"triggers-pending", N_("Preparing for removal of %s")},
617 #endif
618 {"half-installed", N_("Removing %s")},
619 {"config-files", N_("Removed %s")},
620 {NULL, NULL}
621 },
622 // Purge operation
623 {
624 {"config-files", N_("Preparing to completely remove %s")},
625 {"not-installed", N_("Completely removed %s")},
626 {NULL, NULL}
627 },
628 };
629
630 // init the PackageOps map, go over the list of packages that
631 // that will be [installed|configured|removed|purged] and add
632 // them to the PackageOps map (the dpkg states it goes through)
633 // and the PackageOpsTranslations (human readable strings)
634 for (vector<Item>::iterator I = List.begin(); I != List.end();I++)
635 {
636 string name = (*I).Pkg.Name();
637 PackageOpsDone[name] = 0;
638 for(int i=0; (DpkgStatesOpMap[(*I).Op][i]).state != NULL; i++)
639 {
640 PackageOps[name].push_back(DpkgStatesOpMap[(*I).Op][i]);
641 PackagesTotal++;
642 }
643 }
644
645 stdin_is_dev_null = false;
646
647 // create log
648 OpenLog();
649
650 // this loop is runs once per operation
651 for (vector<Item>::iterator I = List.begin(); I != List.end();)
652 {
653 vector<Item>::iterator J = I;
654 for (; J != List.end() && J->Op == I->Op; J++);
655
656 // Generate the argument list
657 const char *Args[MaxArgs + 50];
658 if (J - I > (signed)MaxArgs)
659 J = I + MaxArgs;
660
661 unsigned int n = 0;
662 unsigned long Size = 0;
663 string Tmp = _config->Find("Dir::Bin::dpkg","dpkg");
664 Args[n++] = Tmp.c_str();
665 Size += strlen(Args[n-1]);
666
667 // Stick in any custom dpkg options
668 Configuration::Item const *Opts = _config->Tree("DPkg::Options");
669 if (Opts != 0)
670 {
671 Opts = Opts->Child;
672 for (; Opts != 0; Opts = Opts->Next)
673 {
674 if (Opts->Value.empty() == true)
675 continue;
676 Args[n++] = Opts->Value.c_str();
677 Size += Opts->Value.length();
678 }
679 }
680
681 char status_fd_buf[20];
682 int fd[2];
683 pipe(fd);
684
685 Args[n++] = "--status-fd";
686 Size += strlen(Args[n-1]);
687 snprintf(status_fd_buf,sizeof(status_fd_buf),"%i", fd[1]);
688 Args[n++] = status_fd_buf;
689 Size += strlen(Args[n-1]);
690
691 switch (I->Op)
692 {
693 case Item::Remove:
694 Args[n++] = "--force-depends";
695 Size += strlen(Args[n-1]);
696 Args[n++] = "--force-remove-essential";
697 Size += strlen(Args[n-1]);
698 Args[n++] = "--remove";
699 Size += strlen(Args[n-1]);
700 break;
701
702 case Item::Purge:
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++] = "--purge";
708 Size += strlen(Args[n-1]);
709 break;
710
711 case Item::Configure:
712 Args[n++] = "--configure";
713 Size += strlen(Args[n-1]);
714 break;
715
716 case Item::Install:
717 Args[n++] = "--unpack";
718 Size += strlen(Args[n-1]);
719 Args[n++] = "--auto-deconfigure";
720 Size += strlen(Args[n-1]);
721 break;
722 }
723
724 // Write in the file or package names
725 if (I->Op == Item::Install)
726 {
727 for (;I != J && Size < MaxArgBytes; I++)
728 {
729 if (I->File[0] != '/')
730 return _error->Error("Internal Error, Pathname to install is not absolute '%s'",I->File.c_str());
731 Args[n++] = I->File.c_str();
732 Size += strlen(Args[n-1]);
733 }
734 }
735 else
736 {
737 for (;I != J && Size < MaxArgBytes; I++)
738 {
739 Args[n++] = I->Pkg.Name();
740 Size += strlen(Args[n-1]);
741 }
742 }
743 Args[n] = 0;
744 J = I;
745
746 if (_config->FindB("Debug::pkgDPkgPM",false) == true)
747 {
748 for (unsigned int k = 0; k != n; k++)
749 clog << Args[k] << ' ';
750 clog << endl;
751 continue;
752 }
753
754 cout << flush;
755 clog << flush;
756 cerr << flush;
757
758 /* Mask off sig int/quit. We do this because dpkg also does when
759 it forks scripts. What happens is that when you hit ctrl-c it sends
760 it to all processes in the group. Since dpkg ignores the signal
761 it doesn't die but we do! So we must also ignore it */
762 sighandler_t old_SIGQUIT = signal(SIGQUIT,SIG_IGN);
763 sighandler_t old_SIGINT = signal(SIGINT,SIG_IGN);
764
765 struct termios tt;
766 struct winsize win;
767 int master;
768 int slave;
769
770 // FIXME: setup sensible signal handling (*ick*)
771 tcgetattr(0, &tt);
772 ioctl(0, TIOCGWINSZ, (char *)&win);
773 if (openpty(&master, &slave, NULL, &tt, &win) < 0)
774 {
775 const char *s = _("Can not write log, openpty() "
776 "failed (/dev/pts not mounted?)\n");
777 fprintf(stderr, "%s",s);
778 fprintf(term_out, "%s",s);
779 master = slave = -1;
780 } else {
781 struct termios rtt;
782 rtt = tt;
783 cfmakeraw(&rtt);
784 rtt.c_lflag &= ~ECHO;
785 tcsetattr(0, TCSAFLUSH, &rtt);
786 }
787
788 // Fork dpkg
789 pid_t Child;
790 _config->Set("APT::Keep-Fds::",fd[1]);
791 Child = ExecFork();
792
793 // This is the child
794 if (Child == 0)
795 {
796 if(slave >= 0 && master >= 0)
797 {
798 setsid();
799 ioctl(slave, TIOCSCTTY, 0);
800 close(master);
801 dup2(slave, 0);
802 dup2(slave, 1);
803 dup2(slave, 2);
804 close(slave);
805 }
806 close(fd[0]); // close the read end of the pipe
807
808 if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
809 _exit(100);
810
811 if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
812 {
813 int Flags,dummy;
814 if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
815 _exit(100);
816
817 // Discard everything in stdin before forking dpkg
818 if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
819 _exit(100);
820
821 while (read(STDIN_FILENO,&dummy,1) == 1);
822
823 if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
824 _exit(100);
825 }
826
827
828 /* No Job Control Stop Env is a magic dpkg var that prevents it
829 from using sigstop */
830 putenv((char *)"DPKG_NO_TSTP=yes");
831 execvp(Args[0],(char **)Args);
832 cerr << "Could not exec dpkg!" << endl;
833 _exit(100);
834 }
835
836 // clear the Keep-Fd again
837 _config->Clear("APT::Keep-Fds",fd[1]);
838
839 // Wait for dpkg
840 int Status = 0;
841
842 // we read from dpkg here
843 int _dpkgin = fd[0];
844 close(fd[1]); // close the write end of the pipe
845
846 // the result of the waitpid call
847 int res;
848 if(slave > 0)
849 close(slave);
850
851 // setups fds
852 fd_set rfds;
853 struct timespec tv;
854 sigset_t sigmask;
855 sigset_t original_sigmask;
856 sigemptyset(&sigmask);
857 sigprocmask(SIG_BLOCK,&sigmask,&original_sigmask);
858
859 int select_ret;
860 while ((res=waitpid(Child,&Status, WNOHANG)) != Child) {
861 if(res < 0) {
862 // FIXME: move this to a function or something, looks ugly here
863 // error handling, waitpid returned -1
864 if (errno == EINTR)
865 continue;
866 RunScripts("DPkg::Post-Invoke");
867
868 // Restore sig int/quit
869 signal(SIGQUIT,old_SIGQUIT);
870 signal(SIGINT,old_SIGINT);
871 return _error->Errno("waitpid","Couldn't wait for subprocess");
872 }
873
874 // wait for input or output here
875 FD_ZERO(&rfds);
876 if (!stdin_is_dev_null)
877 FD_SET(0, &rfds);
878 FD_SET(_dpkgin, &rfds);
879 if(master >= 0)
880 FD_SET(master, &rfds);
881 tv.tv_sec = 1;
882 tv.tv_nsec = 0;
883 select_ret = pselect(max(master, _dpkgin)+1, &rfds, NULL, NULL,
884 &tv, &original_sigmask);
885 if (select_ret < 0 && (errno == EINVAL || errno == ENOSYS))
886 select_ret = racy_pselect(max(master, _dpkgin)+1, &rfds, NULL,
887 NULL, &tv, &original_sigmask);
888 if (select_ret == 0)
889 continue;
890 else if (select_ret < 0 && errno == EINTR)
891 continue;
892 else if (select_ret < 0)
893 {
894 perror("select() returned error");
895 continue;
896 }
897
898 if(master >= 0 && FD_ISSET(master, &rfds))
899 DoTerminalPty(master);
900 if(master >= 0 && FD_ISSET(0, &rfds))
901 DoStdin(master);
902 if(FD_ISSET(_dpkgin, &rfds))
903 DoDpkgStatusFd(_dpkgin, OutStatusFd);
904 }
905 close(_dpkgin);
906
907 // Restore sig int/quit
908 signal(SIGQUIT,old_SIGQUIT);
909 signal(SIGINT,old_SIGINT);
910
911 if(master >= 0)
912 {
913 tcsetattr(0, TCSAFLUSH, &tt);
914 close(master);
915 }
916
917 // Check for an error code.
918 if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
919 {
920 // if it was set to "keep-dpkg-runing" then we won't return
921 // here but keep the loop going and just report it as a error
922 // for later
923 bool stopOnError = _config->FindB("Dpkg::StopOnError",true);
924
925 if(stopOnError)
926 RunScripts("DPkg::Post-Invoke");
927
928 if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
929 _error->Error("Sub-process %s received a segmentation fault.",Args[0]);
930 else if (WIFEXITED(Status) != 0)
931 _error->Error("Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
932 else
933 _error->Error("Sub-process %s exited unexpectedly",Args[0]);
934
935 if(stopOnError)
936 {
937 CloseLog();
938 return false;
939 }
940 }
941 }
942 CloseLog();
943
944 if (RunScripts("DPkg::Post-Invoke") == false)
945 return false;
946 return true;
947 }
948 /*}}}*/
949 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
950 // ---------------------------------------------------------------------
951 /* */
952 void pkgDPkgPM::Reset()
953 {
954 List.erase(List.begin(),List.end());
955 }
956 /*}}}*/