1 // -*- mode: cpp; mode: fold -*-
3 // $Id: dpkgpm.cc,v 1.28 2004/01/27 02:25:01 mdz Exp $
4 /* ######################################################################
6 DPKG Package Manager - Provide an interface to dpkg
8 ##################################################################### */
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>
22 #include <sys/select.h>
23 #include <sys/types.h>
33 #include <sys/ioctl.h>
44 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
45 // ---------------------------------------------------------------------
47 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
48 : pkgPackageManager(Cache
), dpkgbuf_pos(0), PackagesDone(0),
49 PackagesTotal(0), term_out(NULL
)
53 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
54 // ---------------------------------------------------------------------
56 pkgDPkgPM::~pkgDPkgPM()
60 // DPkgPM::Install - Install a package /*{{{*/
61 // ---------------------------------------------------------------------
62 /* Add an install operation to the sequence list */
63 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
65 if (File
.empty() == true || Pkg
.end() == true)
66 return _error
->Error("Internal Error, No file name for %s",Pkg
.Name());
68 List
.push_back(Item(Item::Install
,Pkg
,File
));
72 // DPkgPM::Configure - Configure a package /*{{{*/
73 // ---------------------------------------------------------------------
74 /* Add a configure operation to the sequence list */
75 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
77 if (Pkg
.end() == true)
80 List
.push_back(Item(Item::Configure
,Pkg
));
84 // DPkgPM::Remove - Remove a package /*{{{*/
85 // ---------------------------------------------------------------------
86 /* Add a remove operation to the sequence list */
87 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
89 if (Pkg
.end() == true)
93 List
.push_back(Item(Item::Purge
,Pkg
));
95 List
.push_back(Item(Item::Remove
,Pkg
));
99 // DPkgPM::RunScripts - Run a set of scripts /*{{{*/
100 // ---------------------------------------------------------------------
101 /* This looks for a list of script sto run from the configuration file,
102 each one is run with system from a forked child. */
103 bool pkgDPkgPM::RunScripts(const char *Cnf
)
105 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
106 if (Opts
== 0 || Opts
->Child
== 0)
110 // Fork for running the system calls
111 pid_t Child
= ExecFork();
116 if (chdir("/tmp/") != 0)
119 unsigned int Count
= 1;
120 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
122 if (Opts
->Value
.empty() == true)
125 if (system(Opts
->Value
.c_str()) != 0)
131 // Wait for the child
133 while (waitpid(Child
,&Status
,0) != Child
)
137 return _error
->Errno("waitpid","Couldn't wait for subprocess");
140 // Restore sig int/quit
141 signal(SIGQUIT
,SIG_DFL
);
142 signal(SIGINT
,SIG_DFL
);
144 // Check for an error code.
145 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
147 unsigned int Count
= WEXITSTATUS(Status
);
151 for (; Opts
!= 0 && Count
!= 1; Opts
= Opts
->Next
, Count
--);
152 _error
->Error("Problem executing scripts %s '%s'",Cnf
,Opts
->Value
.c_str());
155 return _error
->Error("Sub-process returned an error code");
161 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
162 // ---------------------------------------------------------------------
163 /* This is part of the helper script communication interface, it sends
164 very complete information down to the other end of the pipe.*/
165 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
167 fprintf(F
,"VERSION 2\n");
169 /* Write out all of the configuration directives by walking the
170 configuration tree */
171 const Configuration::Item
*Top
= _config
->Tree(0);
174 if (Top
->Value
.empty() == false)
177 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
178 QuoteString(Top
->Value
,"\n").c_str());
187 while (Top
!= 0 && Top
->Next
== 0)
194 // Write out the package actions in order.
195 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
197 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
199 fprintf(F
,"%s ",I
->Pkg
.Name());
201 if (I
->Pkg
->CurrentVer
== 0)
204 fprintf(F
,"%s ",I
->Pkg
.CurrentVer().VerStr());
206 // Show the compare operator
208 if (S
.InstallVer
!= 0)
211 if (I
->Pkg
->CurrentVer
!= 0)
212 Comp
= S
.InstVerIter(Cache
).CompareVer(I
->Pkg
.CurrentVer());
219 fprintf(F
,"%s ",S
.InstVerIter(Cache
).VerStr());
224 // Show the filename/operation
225 if (I
->Op
== Item::Install
)
228 if (I
->File
[0] != '/')
229 fprintf(F
,"**ERROR**\n");
231 fprintf(F
,"%s\n",I
->File
.c_str());
233 if (I
->Op
== Item::Configure
)
234 fprintf(F
,"**CONFIGURE**\n");
235 if (I
->Op
== Item::Remove
||
236 I
->Op
== Item::Purge
)
237 fprintf(F
,"**REMOVE**\n");
245 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
246 // ---------------------------------------------------------------------
247 /* This looks for a list of scripts to run from the configuration file
248 each one is run and is fed on standard input a list of all .deb files
249 that are due to be installed. */
250 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
252 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
253 if (Opts
== 0 || Opts
->Child
== 0)
257 unsigned int Count
= 1;
258 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
260 if (Opts
->Value
.empty() == true)
263 // Determine the protocol version
264 string OptSec
= Opts
->Value
;
265 string::size_type Pos
;
266 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
267 Pos
= OptSec
.length();
268 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
270 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
274 if (pipe(Pipes
) != 0)
275 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
276 SetCloseExec(Pipes
[0],true);
277 SetCloseExec(Pipes
[1],true);
279 // Purified Fork for running the script
280 pid_t Process
= ExecFork();
284 dup2(Pipes
[0],STDIN_FILENO
);
285 SetCloseExec(STDOUT_FILENO
,false);
286 SetCloseExec(STDIN_FILENO
,false);
287 SetCloseExec(STDERR_FILENO
,false);
292 Args
[2] = Opts
->Value
.c_str();
294 execv(Args
[0],(char **)Args
);
298 FILE *F
= fdopen(Pipes
[1],"w");
300 return _error
->Errno("fdopen","Faild to open new FD");
302 // Feed it the filenames.
306 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
308 // Only deal with packages to be installed from .deb
309 if (I
->Op
!= Item::Install
)
313 if (I
->File
[0] != '/')
316 /* Feed the filename of each package that is pending install
318 fprintf(F
,"%s\n",I
->File
.c_str());
327 Die
= !SendV2Pkgs(F
);
331 // Clean up the sub process
332 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
333 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
340 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
341 // ---------------------------------------------------------------------
344 void pkgDPkgPM::DoStdin(int master
)
346 char input_buf
[256] = {0,};
347 int len
= read(0, input_buf
, sizeof(input_buf
));
348 write(master
, input_buf
, len
);
351 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
352 // ---------------------------------------------------------------------
354 * read the terminal pty and write log
356 void pkgDPkgPM::DoTerminalPty(int master
)
358 char term_buf
[1024] = {0,};
360 int len
=read(master
, term_buf
, sizeof(term_buf
));
361 if(len
== -1 && errno
== EIO
)
363 // this happens when the child is about to exit, we
364 // give it time to actually exit, otherwise we run
371 write(1, term_buf
, len
);
373 fwrite(term_buf
, len
, sizeof(char), term_out
);
376 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
377 // ---------------------------------------------------------------------
380 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd
, char *line
)
382 // the status we output
383 ostringstream status
;
385 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
386 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
389 /* dpkg sends strings like this:
390 'status: <pkg>: <pkg qstate>'
391 errors look like this:
392 '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
393 and conffile-prompt like this
394 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
398 // dpkg sends multiline error messages sometimes (see
399 // #374195 for a example. we should support this by
400 // either patching dpkg to not send multiline over the
401 // statusfd or by rewriting the code here to deal with
402 // it. for now we just ignore it and not crash
403 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
404 if( list
[0] == NULL
|| list
[1] == NULL
|| list
[2] == NULL
)
406 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
407 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
411 char *action
= _strstrip(list
[2]);
413 if(strncmp(action
,"error",strlen("error")) == 0)
415 status
<< "pmerror:" << list
[1]
416 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
420 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
421 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
422 std::clog
<< "send: '" << status
.str() << "'" << endl
;
424 WriteApportReport(list
[1], list
[3]);
427 if(strncmp(action
,"conffile",strlen("conffile")) == 0)
429 status
<< "pmconffile:" << list
[1]
430 << ":" << (PackagesDone
/float(PackagesTotal
)*100.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
;
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))
447 // only read the translation if there is actually a next
449 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
451 snprintf(s
, sizeof(s
), translation
, pkg
);
453 // we moved from one dpkg state to a new one, report that
454 PackageOpsDone
[pkg
]++;
456 // build the status str
457 status
<< "pmstatus:" << pkg
458 << ":" << (PackagesDone
/float(PackagesTotal
)*100.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
;
466 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
467 std::clog
<< "(parsed from dpkg) pkg: " << pkg
468 << " action: " << action
<< endl
;
471 // DPkgPM::DoDpkgStatusFd /*{{{*/
472 // ---------------------------------------------------------------------
475 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
, int OutStatusFd
)
480 len
=read(statusfd
, &dpkgbuf
[dpkgbuf_pos
], sizeof(dpkgbuf
)-dpkgbuf_pos
);
485 // process line by line if we have a buffer
487 while((q
=(char*)memchr(p
, '\n', dpkgbuf
+dpkgbuf_pos
-p
)) != NULL
)
490 ProcessDpkgStatusLine(OutStatusFd
, p
);
491 p
=q
+1; // continue with next line
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
);
500 // we are interessted in the first char *after* 0x0
503 // move the unprocessed tail to the start and update pos
504 memmove(dpkgbuf
, p
, p
-dpkgbuf
);
505 dpkgbuf_pos
= dpkgbuf
+dpkgbuf_pos
-p
;
509 bool pkgDPkgPM::OpenLog()
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())
518 term_out
= fopen(logfile_name
.c_str(),"a");
519 chmod(logfile_name
.c_str(), 0600);
520 // output current time
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");
532 bool pkgDPkgPM::CloseLog()
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");
550 // DPkgPM::Go - Run the sequence /*{{{*/
551 // ---------------------------------------------------------------------
552 /* This globs the operations and calls dpkg
554 * If it is called with "OutStatusFd" set to a valid file descriptor
555 * apt will report the install progress over this fd. It maps the
556 * dpkg states a package goes through to human readable (and i10n-able)
557 * names and calculates a percentage for each step.
559 bool pkgDPkgPM::Go(int OutStatusFd
)
561 unsigned int MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
562 unsigned int MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
564 if (RunScripts("DPkg::Pre-Invoke") == false)
567 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
570 // map the dpkg states to the operations that are performed
571 // (this is sorted in the same way as Item::Ops)
572 static const struct DpkgState DpkgStatesOpMap
[][7] = {
575 {"half-installed", N_("Preparing %s")},
576 {"unpacked", N_("Unpacking %s") },
579 // Configure operation
581 {"unpacked",N_("Preparing to configure %s") },
582 {"half-configured", N_("Configuring %s") },
584 {"triggers-awaited", N_("Processing triggers for %s") },
585 {"triggers-pending", N_("Processing triggers for %s") },
587 { "installed", N_("Installed %s")},
592 {"half-configured", N_("Preparing for removal of %s")},
594 {"triggers-awaited", N_("Preparing for removal of %s")},
595 {"triggers-pending", N_("Preparing for removal of %s")},
597 {"half-installed", N_("Removing %s")},
598 {"config-files", N_("Removed %s")},
603 {"config-files", N_("Preparing to completely remove %s")},
604 {"not-installed", N_("Completely removed %s")},
609 // init the PackageOps map, go over the list of packages that
610 // that will be [installed|configured|removed|purged] and add
611 // them to the PackageOps map (the dpkg states it goes through)
612 // and the PackageOpsTranslations (human readable strings)
613 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end();I
++)
615 string name
= (*I
).Pkg
.Name();
616 PackageOpsDone
[name
] = 0;
617 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; i
++)
619 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
627 // this loop is runs once per operation
628 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end();)
630 vector
<Item
>::iterator J
= I
;
631 for (; J
!= List
.end() && J
->Op
== I
->Op
; J
++);
633 // Generate the argument list
634 const char *Args
[MaxArgs
+ 50];
635 if (J
- I
> (signed)MaxArgs
)
639 unsigned long Size
= 0;
640 string Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
641 Args
[n
++] = Tmp
.c_str();
642 Size
+= strlen(Args
[n
-1]);
644 // Stick in any custom dpkg options
645 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
649 for (; Opts
!= 0; Opts
= Opts
->Next
)
651 if (Opts
->Value
.empty() == true)
653 Args
[n
++] = Opts
->Value
.c_str();
654 Size
+= Opts
->Value
.length();
658 char status_fd_buf
[20];
662 Args
[n
++] = "--status-fd";
663 Size
+= strlen(Args
[n
-1]);
664 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
665 Args
[n
++] = status_fd_buf
;
666 Size
+= strlen(Args
[n
-1]);
671 Args
[n
++] = "--force-depends";
672 Size
+= strlen(Args
[n
-1]);
673 Args
[n
++] = "--force-remove-essential";
674 Size
+= strlen(Args
[n
-1]);
675 Args
[n
++] = "--remove";
676 Size
+= strlen(Args
[n
-1]);
680 Args
[n
++] = "--force-depends";
681 Size
+= strlen(Args
[n
-1]);
682 Args
[n
++] = "--force-remove-essential";
683 Size
+= strlen(Args
[n
-1]);
684 Args
[n
++] = "--purge";
685 Size
+= strlen(Args
[n
-1]);
688 case Item::Configure
:
689 Args
[n
++] = "--configure";
690 Size
+= strlen(Args
[n
-1]);
694 Args
[n
++] = "--unpack";
695 Size
+= strlen(Args
[n
-1]);
696 Args
[n
++] = "--auto-deconfigure";
697 Size
+= strlen(Args
[n
-1]);
701 // Write in the file or package names
702 if (I
->Op
== Item::Install
)
704 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
706 if (I
->File
[0] != '/')
707 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
708 Args
[n
++] = I
->File
.c_str();
709 Size
+= strlen(Args
[n
-1]);
714 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
716 Args
[n
++] = I
->Pkg
.Name();
717 Size
+= strlen(Args
[n
-1]);
723 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
725 for (unsigned int k
= 0; k
!= n
; k
++)
726 clog
<< Args
[k
] << ' ';
735 /* Mask off sig int/quit. We do this because dpkg also does when
736 it forks scripts. What happens is that when you hit ctrl-c it sends
737 it to all processes in the group. Since dpkg ignores the signal
738 it doesn't die but we do! So we must also ignore it */
739 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
740 sighandler_t old_SIGINT
= signal(SIGINT
,SIG_IGN
);
747 // FIXME: setup sensible signal handling (*ick*)
749 ioctl(0, TIOCGWINSZ
, (char *)&win
);
750 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
752 const char *s
= _("Can not write log, openpty() "
753 "failed (/dev/pts not mounted?)\n");
754 fprintf(stderr
, "%s",s
);
755 fprintf(term_out
, "%s",s
);
761 rtt
.c_lflag
&= ~ECHO
;
762 tcsetattr(0, TCSAFLUSH
, &rtt
);
767 _config
->Set("APT::Keep-Fds::",fd
[1]);
773 if(slave
>= 0 && master
>= 0)
776 ioctl(slave
, TIOCSCTTY
, 0);
783 close(fd
[0]); // close the read end of the pipe
785 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
788 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
791 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
794 // Discard everything in stdin before forking dpkg
795 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
798 while (read(STDIN_FILENO
,&dummy
,1) == 1);
800 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
805 /* No Job Control Stop Env is a magic dpkg var that prevents it
806 from using sigstop */
807 putenv("DPKG_NO_TSTP=yes");
808 execvp(Args
[0],(char **)Args
);
809 cerr
<< "Could not exec dpkg!" << endl
;
813 // clear the Keep-Fd again
814 _config
->Clear("APT::Keep-Fds",fd
[1]);
819 // we read from dpkg here
821 close(fd
[1]); // close the write end of the pipe
823 // the result of the waitpid call
832 sigset_t original_sigmask
;
833 sigemptyset(&sigmask
);
834 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
837 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
839 // FIXME: move this to a function or something, looks ugly here
840 // error handling, waitpid returned -1
843 RunScripts("DPkg::Post-Invoke");
845 // Restore sig int/quit
846 signal(SIGQUIT
,old_SIGQUIT
);
847 signal(SIGINT
,old_SIGINT
);
848 return _error
->Errno("waitpid","Couldn't wait for subprocess");
851 // wait for input or output here
854 FD_SET(_dpkgin
, &rfds
);
856 FD_SET(master
, &rfds
);
859 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
860 &tv
, &original_sigmask
);
863 else if (select_ret
< 0 && errno
== EINTR
)
865 else if (select_ret
< 0)
867 perror("select() returned error");
871 if(master
>= 0 && FD_ISSET(master
, &rfds
))
872 DoTerminalPty(master
);
873 if(master
>= 0 && FD_ISSET(0, &rfds
))
875 if(FD_ISSET(_dpkgin
, &rfds
))
876 DoDpkgStatusFd(_dpkgin
, OutStatusFd
);
880 // Restore sig int/quit
881 signal(SIGQUIT
,old_SIGQUIT
);
882 signal(SIGINT
,old_SIGINT
);
886 tcsetattr(0, TCSAFLUSH
, &tt
);
890 // Check for an error code.
891 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
893 // if it was set to "keep-dpkg-runing" then we won't return
894 // here but keep the loop going and just report it as a error
896 bool stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
899 RunScripts("DPkg::Post-Invoke");
901 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
902 _error
->Error("Sub-process %s received a segmentation fault.",Args
[0]);
903 else if (WIFEXITED(Status
) != 0)
904 _error
->Error("Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
906 _error
->Error("Sub-process %s exited unexpectedly",Args
[0]);
917 if (RunScripts("DPkg::Post-Invoke") == false)
922 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
923 // ---------------------------------------------------------------------
925 void pkgDPkgPM::Reset()
927 List
.erase(List
.begin(),List
.end());
930 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
931 // ---------------------------------------------------------------------
933 void pkgDPkgPM::WriteApportReport(const char *pkgpath
, const char *errormsg
)
935 string pkgname
, reportfile
, srcpkgname
, pkgver
, arch
;
936 string::size_type pos
;
939 if (_config
->FindB("Dpkg::ApportFailureReport",true) == false)
942 // only report the first error if we are in StopOnError=false mode
943 // to prevent bogus reports
944 if((_config
->FindB("Dpkg::StopOnError",true) == false) && pkgFailures
> 1)
947 // get the pkgname and reportfile
948 pkgname
= flNotDir(pkgpath
);
949 pos
= pkgname
.find('_');
950 if(pos
!= string::npos
)
951 pkgname
= pkgname
.substr(0, pos
);
953 // find the package versin and source package name
954 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
955 if (Pkg
.end() == true)
957 pkgCache::VerIterator Ver
= Cache
.GetCandidateVer(Pkg
);
958 if (Ver
.end() == true)
960 pkgver
= Ver
.VerStr() == NULL
? "unknown" : Ver
.VerStr();
961 pkgRecords
Recs(Cache
);
962 pkgRecords::Parser
&Parse
= Recs
.Lookup(Ver
.FileList());
963 srcpkgname
= Parse
.SourcePkg();
964 if(srcpkgname
.empty())
965 srcpkgname
= pkgname
;
967 // if the file exists already, we check:
968 // - if it was reported already (touched by apport).
969 // If not, we do nothing, otherwise
970 // we overwrite it. This is the same behaviour as apport
971 // - if we have a report with the same pkgversion already
973 reportfile
= flCombine("/var/crash",pkgname
+".0.crash");
974 if(FileExists(reportfile
))
980 stat(reportfile
.c_str(), &buf
);
981 if(buf
.st_mtime
> buf
.st_atime
)
984 // check if the existing report is the same version
985 report
= fopen(reportfile
.c_str(),"r");
986 while(fgets(strbuf
, sizeof(strbuf
), report
) != NULL
)
988 if(strstr(strbuf
,"Package:") == strbuf
)
990 char pkgname
[255], version
[255];
991 if(sscanf(strbuf
, "Package: %s %s", pkgname
, version
) == 2)
992 if(strcmp(pkgver
.c_str(), version
) == 0)
1002 // now write the report
1003 arch
= _config
->Find("APT::Architecture");
1004 report
= fopen(reportfile
.c_str(),"w");
1007 if(_config
->FindB("DPkgPM::InitialReportOnly",false) == true)
1008 chmod(reportfile
.c_str(), 0);
1010 chmod(reportfile
.c_str(), 0600);
1011 fprintf(report
, "ProblemType: Package\n");
1012 fprintf(report
, "Architecture: %s\n", arch
.c_str());
1013 time_t now
= time(NULL
);
1014 fprintf(report
, "Date: %s" , ctime(&now
));
1015 fprintf(report
, "Package: %s %s\n", pkgname
.c_str(), pkgver
.c_str());
1016 fprintf(report
, "SourcePackage: %s\n", srcpkgname
.c_str());
1017 fprintf(report
, "ErrorMessage:\n %s\n", errormsg
);
1019 // ensure that the log is flushed
1023 // attach terminal log it if we have it
1024 string logfile_name
= _config
->FindFile("Dir::Log::Terminal");
1025 if (!logfile_name
.empty())
1030 fprintf(report
, "DpkgTerminalLog:\n");
1031 log
= fopen(logfile_name
.c_str(),"r");
1034 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1035 fprintf(report
, " %s", buf
);