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