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