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>
18 #include <apt-pkg/fileutl.h>
23 #include <sys/select.h>
24 #include <sys/types.h>
35 #include <sys/ioctl.h>
46 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
47 // ---------------------------------------------------------------------
49 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
50 : pkgPackageManager(Cache
), dpkgbuf_pos(0),
51 term_out(NULL
), PackagesDone(0), PackagesTotal(0), pkgFailures(0)
55 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
56 // ---------------------------------------------------------------------
58 pkgDPkgPM::~pkgDPkgPM()
62 // DPkgPM::Install - Install a package /*{{{*/
63 // ---------------------------------------------------------------------
64 /* Add an install operation to the sequence list */
65 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
67 if (File
.empty() == true || Pkg
.end() == true)
68 return _error
->Error("Internal Error, No file name for %s",Pkg
.Name());
70 List
.push_back(Item(Item::Install
,Pkg
,File
));
74 // DPkgPM::Configure - Configure a package /*{{{*/
75 // ---------------------------------------------------------------------
76 /* Add a configure operation to the sequence list */
77 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
79 if (Pkg
.end() == true)
82 List
.push_back(Item(Item::Configure
,Pkg
));
86 // DPkgPM::Remove - Remove a package /*{{{*/
87 // ---------------------------------------------------------------------
88 /* Add a remove operation to the sequence list */
89 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
91 if (Pkg
.end() == true)
95 List
.push_back(Item(Item::Purge
,Pkg
));
97 List
.push_back(Item(Item::Remove
,Pkg
));
101 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
102 // ---------------------------------------------------------------------
103 /* This is part of the helper script communication interface, it sends
104 very complete information down to the other end of the pipe.*/
105 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
107 fprintf(F
,"VERSION 2\n");
109 /* Write out all of the configuration directives by walking the
110 configuration tree */
111 const Configuration::Item
*Top
= _config
->Tree(0);
114 if (Top
->Value
.empty() == false)
117 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
118 QuoteString(Top
->Value
,"\n").c_str());
127 while (Top
!= 0 && Top
->Next
== 0)
134 // Write out the package actions in order.
135 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
137 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
139 fprintf(F
,"%s ",I
->Pkg
.Name());
141 if (I
->Pkg
->CurrentVer
== 0)
144 fprintf(F
,"%s ",I
->Pkg
.CurrentVer().VerStr());
146 // Show the compare operator
148 if (S
.InstallVer
!= 0)
151 if (I
->Pkg
->CurrentVer
!= 0)
152 Comp
= S
.InstVerIter(Cache
).CompareVer(I
->Pkg
.CurrentVer());
159 fprintf(F
,"%s ",S
.InstVerIter(Cache
).VerStr());
164 // Show the filename/operation
165 if (I
->Op
== Item::Install
)
168 if (I
->File
[0] != '/')
169 fprintf(F
,"**ERROR**\n");
171 fprintf(F
,"%s\n",I
->File
.c_str());
173 if (I
->Op
== Item::Configure
)
174 fprintf(F
,"**CONFIGURE**\n");
175 if (I
->Op
== Item::Remove
||
176 I
->Op
== Item::Purge
)
177 fprintf(F
,"**REMOVE**\n");
185 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
186 // ---------------------------------------------------------------------
187 /* This looks for a list of scripts to run from the configuration file
188 each one is run and is fed on standard input a list of all .deb files
189 that are due to be installed. */
190 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
192 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
193 if (Opts
== 0 || Opts
->Child
== 0)
197 unsigned int Count
= 1;
198 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
200 if (Opts
->Value
.empty() == true)
203 // Determine the protocol version
204 string OptSec
= Opts
->Value
;
205 string::size_type Pos
;
206 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
207 Pos
= OptSec
.length();
208 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
210 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
214 if (pipe(Pipes
) != 0)
215 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
216 SetCloseExec(Pipes
[0],true);
217 SetCloseExec(Pipes
[1],true);
219 // Purified Fork for running the script
220 pid_t Process
= ExecFork();
224 dup2(Pipes
[0],STDIN_FILENO
);
225 SetCloseExec(STDOUT_FILENO
,false);
226 SetCloseExec(STDIN_FILENO
,false);
227 SetCloseExec(STDERR_FILENO
,false);
232 Args
[2] = Opts
->Value
.c_str();
234 execv(Args
[0],(char **)Args
);
238 FILE *F
= fdopen(Pipes
[1],"w");
240 return _error
->Errno("fdopen","Faild to open new FD");
242 // Feed it the filenames.
246 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
248 // Only deal with packages to be installed from .deb
249 if (I
->Op
!= Item::Install
)
253 if (I
->File
[0] != '/')
256 /* Feed the filename of each package that is pending install
258 fprintf(F
,"%s\n",I
->File
.c_str());
267 Die
= !SendV2Pkgs(F
);
271 // Clean up the sub process
272 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
273 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
279 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
280 // ---------------------------------------------------------------------
283 void pkgDPkgPM::DoStdin(int master
)
285 unsigned char input_buf
[256] = {0,};
286 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
288 write(master
, input_buf
, len
);
290 stdin_is_dev_null
= true;
293 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
294 // ---------------------------------------------------------------------
296 * read the terminal pty and write log
298 void pkgDPkgPM::DoTerminalPty(int master
)
300 unsigned char term_buf
[1024] = {0,0, };
302 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
303 if(len
== -1 && errno
== EIO
)
305 // this happens when the child is about to exit, we
306 // give it time to actually exit, otherwise we run
313 write(1, term_buf
, len
);
315 fwrite(term_buf
, len
, sizeof(char), term_out
);
318 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
319 // ---------------------------------------------------------------------
322 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd
, char *line
)
324 // the status we output
325 ostringstream status
;
327 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
328 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
331 /* dpkg sends strings like this:
332 'status: <pkg>: <pkg qstate>'
333 errors look like this:
334 '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
335 and conffile-prompt like this
336 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
338 Newer versions of dpkg sent also:
339 'processing: install: pkg'
340 'processing: configure: pkg'
341 'processing: remove: pkg'
342 'processing: trigproc: trigger'
346 // dpkg sends multiline error messages sometimes (see
347 // #374195 for a example. we should support this by
348 // either patching dpkg to not send multiline over the
349 // statusfd or by rewriting the code here to deal with
350 // it. for now we just ignore it and not crash
351 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
352 if( list
[0] == NULL
|| list
[1] == NULL
|| list
[2] == NULL
)
354 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
355 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
359 char *action
= _strstrip(list
[2]);
361 // 'processing' from dpkg looks like
362 // 'processing: action: pkg'
363 if(strncmp(list
[0], "processing", strlen("processing")) == 0)
366 map
<string
,string
>::iterator iter
;
367 char *pkg_or_trigger
= _strstrip(list
[2]);
368 action
=_strstrip( list
[1]);
369 iter
= PackageProcessingOps
.find(action
);
370 if(iter
== PackageProcessingOps
.end())
372 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
373 std::clog
<< "ignoring unknwon action: " << action
<< std::endl
;
376 snprintf(s
, sizeof(s
), _(iter
->second
.c_str()), pkg_or_trigger
);
378 status
<< "pmstatus:" << pkg_or_trigger
379 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
383 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
384 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
385 std::clog
<< "send: '" << status
.str() << "'" << endl
;
389 if(strncmp(action
,"error",strlen("error")) == 0)
391 // urgs, sometime has ":" in its error string so that we
392 // end up with the error message split between list[3]
393 // and list[4], e.g. the message:
394 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
396 if( list
[4] != NULL
)
397 list
[3][strlen(list
[3])] = ':';
399 status
<< "pmerror:" << list
[1]
400 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
404 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
405 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
406 std::clog
<< "send: '" << status
.str() << "'" << endl
;
408 WriteApportReport(list
[1], list
[3]);
411 if(strncmp(action
,"conffile",strlen("conffile")) == 0)
413 status
<< "pmconffile:" << list
[1]
414 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
418 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
419 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
420 std::clog
<< "send: '" << status
.str() << "'" << endl
;
424 vector
<struct DpkgState
> &states
= PackageOps
[pkg
];
425 const char *next_action
= NULL
;
426 if(PackageOpsDone
[pkg
] < states
.size())
427 next_action
= states
[PackageOpsDone
[pkg
]].state
;
428 // check if the package moved to the next dpkg state
429 if(next_action
&& (strcmp(action
, next_action
) == 0))
431 // only read the translation if there is actually a next
433 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
435 snprintf(s
, sizeof(s
), translation
, pkg
);
437 // we moved from one dpkg state to a new one, report that
438 PackageOpsDone
[pkg
]++;
440 // build the status str
441 status
<< "pmstatus:" << pkg
442 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
446 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
447 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
448 std::clog
<< "send: '" << status
.str() << "'" << endl
;
450 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
451 std::clog
<< "(parsed from dpkg) pkg: " << pkg
452 << " action: " << action
<< endl
;
455 // DPkgPM::DoDpkgStatusFd /*{{{*/
456 // ---------------------------------------------------------------------
459 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
, int OutStatusFd
)
464 len
=read(statusfd
, &dpkgbuf
[dpkgbuf_pos
], sizeof(dpkgbuf
)-dpkgbuf_pos
);
469 // process line by line if we have a buffer
471 while((q
=(char*)memchr(p
, '\n', dpkgbuf
+dpkgbuf_pos
-p
)) != NULL
)
474 ProcessDpkgStatusLine(OutStatusFd
, p
);
475 p
=q
+1; // continue with next line
478 // now move the unprocessed bits (after the final \n that is now a 0x0)
479 // to the start and update dpkgbuf_pos
480 p
= (char*)memrchr(dpkgbuf
, 0, dpkgbuf_pos
);
484 // we are interessted in the first char *after* 0x0
487 // move the unprocessed tail to the start and update pos
488 memmove(dpkgbuf
, p
, p
-dpkgbuf
);
489 dpkgbuf_pos
= dpkgbuf
+dpkgbuf_pos
-p
;
493 bool pkgDPkgPM::OpenLog()
495 string logdir
= _config
->FindDir("Dir::Log");
496 if(not FileExists(logdir
))
497 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
498 string logfile_name
= flCombine(logdir
,
499 _config
->Find("Dir::Log::Terminal"));
500 if (!logfile_name
.empty())
502 term_out
= fopen(logfile_name
.c_str(),"a");
503 chmod(logfile_name
.c_str(), 0600);
504 // output current time
506 time_t t
= time(NULL
);
507 struct tm
*tmp
= localtime(&t
);
508 strftime(outstr
, sizeof(outstr
), "%F %T", tmp
);
509 fprintf(term_out
, "\nLog started: ");
510 fprintf(term_out
, "%s", outstr
);
511 fprintf(term_out
, "\n");
516 bool pkgDPkgPM::CloseLog()
521 time_t t
= time(NULL
);
522 struct tm
*tmp
= localtime(&t
);
523 strftime(outstr
, sizeof(outstr
), "%F %T", tmp
);
524 fprintf(term_out
, "Log ended: ");
525 fprintf(term_out
, "%s", outstr
);
526 fprintf(term_out
, "\n");
534 // This implements a racy version of pselect for those architectures
535 // that don't have a working implementation.
536 // FIXME: Probably can be removed on Lenny+1
537 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
538 fd_set
*exceptfds
, const struct timespec
*timeout
,
539 const sigset_t
*sigmask
)
545 tv
.tv_sec
= timeout
->tv_sec
;
546 tv
.tv_usec
= timeout
->tv_nsec
/1000;
548 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
549 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
550 sigprocmask(SIG_SETMASK
, &origmask
, 0);
555 // DPkgPM::Go - Run the sequence /*{{{*/
556 // ---------------------------------------------------------------------
557 /* This globs the operations and calls dpkg
559 * If it is called with "OutStatusFd" set to a valid file descriptor
560 * apt will report the install progress over this fd. It maps the
561 * dpkg states a package goes through to human readable (and i10n-able)
562 * names and calculates a percentage for each step.
564 bool pkgDPkgPM::Go(int OutStatusFd
)
569 sigset_t original_sigmask
;
571 unsigned int MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
572 unsigned int MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
573 bool NoTriggers
= _config
->FindB("DPkg::NoTriggers",false);
575 if (RunScripts("DPkg::Pre-Invoke") == false)
578 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
581 // map the dpkg states to the operations that are performed
582 // (this is sorted in the same way as Item::Ops)
583 static const struct DpkgState DpkgStatesOpMap
[][7] = {
586 {"half-installed", N_("Preparing %s")},
587 {"unpacked", N_("Unpacking %s") },
590 // Configure operation
592 {"unpacked",N_("Preparing to configure %s") },
593 {"half-configured", N_("Configuring %s") },
595 {"triggers-awaited", N_("Processing triggers for %s") },
596 {"triggers-pending", N_("Processing triggers for %s") },
598 { "installed", N_("Installed %s")},
603 {"half-configured", N_("Preparing for removal of %s")},
605 {"triggers-awaited", N_("Preparing for removal of %s")},
606 {"triggers-pending", N_("Preparing for removal of %s")},
608 {"half-installed", N_("Removing %s")},
609 {"config-files", N_("Removed %s")},
614 {"config-files", N_("Preparing to completely remove %s")},
615 {"not-installed", N_("Completely removed %s")},
620 // populate the "processing" map
621 PackageProcessingOps
.insert( make_pair("install",N_("Installing %s")) );
622 PackageProcessingOps
.insert( make_pair("configure",N_("Configuring %s")) );
623 PackageProcessingOps
.insert( make_pair("remove",N_("Removing %s")) );
624 PackageProcessingOps
.insert( make_pair("trigproc",N_("Running post-installation trigger %s")) );
626 // init the PackageOps map, go over the list of packages that
627 // that will be [installed|configured|removed|purged] and add
628 // them to the PackageOps map (the dpkg states it goes through)
629 // and the PackageOpsTranslations (human readable strings)
630 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end();I
++)
632 string name
= (*I
).Pkg
.Name();
633 PackageOpsDone
[name
] = 0;
634 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; i
++)
636 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
641 stdin_is_dev_null
= false;
646 // this loop is runs once per operation
647 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end();)
649 vector
<Item
>::iterator J
= I
;
650 for (; J
!= List
.end() && J
->Op
== I
->Op
; J
++);
652 // Generate the argument list
653 const char *Args
[MaxArgs
+ 50];
654 if (J
- I
> (signed)MaxArgs
)
658 unsigned long Size
= 0;
659 string Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
660 Args
[n
++] = Tmp
.c_str();
661 Size
+= strlen(Args
[n
-1]);
663 // Stick in any custom dpkg options
664 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
668 for (; Opts
!= 0; Opts
= Opts
->Next
)
670 if (Opts
->Value
.empty() == true)
672 Args
[n
++] = Opts
->Value
.c_str();
673 Size
+= Opts
->Value
.length();
677 char status_fd_buf
[20];
681 Args
[n
++] = "--status-fd";
682 Size
+= strlen(Args
[n
-1]);
683 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
684 Args
[n
++] = status_fd_buf
;
685 Size
+= strlen(Args
[n
-1]);
690 Args
[n
++] = "--force-depends";
691 Size
+= strlen(Args
[n
-1]);
692 Args
[n
++] = "--force-remove-essential";
693 Size
+= strlen(Args
[n
-1]);
694 Args
[n
++] = "--remove";
695 Size
+= strlen(Args
[n
-1]);
699 Args
[n
++] = "--force-depends";
700 Size
+= strlen(Args
[n
-1]);
701 Args
[n
++] = "--force-remove-essential";
702 Size
+= strlen(Args
[n
-1]);
703 Args
[n
++] = "--purge";
704 Size
+= strlen(Args
[n
-1]);
707 case Item::Configure
:
708 Args
[n
++] = "--configure";
710 Args
[n
++] = "--no-triggers";
711 Size
+= strlen(Args
[n
-1]);
715 Args
[n
++] = "--unpack";
716 Size
+= strlen(Args
[n
-1]);
717 Args
[n
++] = "--auto-deconfigure";
718 Size
+= strlen(Args
[n
-1]);
722 // Write in the file or package names
723 if (I
->Op
== Item::Install
)
725 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
727 if (I
->File
[0] != '/')
728 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
729 Args
[n
++] = I
->File
.c_str();
730 Size
+= strlen(Args
[n
-1]);
735 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
737 Args
[n
++] = I
->Pkg
.Name();
738 Size
+= strlen(Args
[n
-1]);
744 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
746 for (unsigned int k
= 0; k
!= n
; k
++)
747 clog
<< Args
[k
] << ' ';
756 /* Mask off sig int/quit. We do this because dpkg also does when
757 it forks scripts. What happens is that when you hit ctrl-c it sends
758 it to all processes in the group. Since dpkg ignores the signal
759 it doesn't die but we do! So we must also ignore it */
760 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
761 sighandler_t old_SIGINT
= signal(SIGINT
,SIG_IGN
);
764 struct termios tt_out
;
769 // FIXME: setup sensible signal handling (*ick*)
771 tcgetattr(1, &tt_out
);
772 ioctl(0, TIOCGWINSZ
, (char *)&win
);
773 if (openpty(&master
, &slave
, NULL
, &tt_out
, &win
) < 0)
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
);
784 rtt
.c_lflag
&= ~ECHO
;
785 // block SIGTTOU during tcsetattr to prevent a hang if
786 // the process is a member of the background process group
787 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
788 sigemptyset(&sigmask
);
789 sigaddset(&sigmask
, SIGTTOU
);
790 sigprocmask(SIG_BLOCK
,&sigmask
, &original_sigmask
);
791 tcsetattr(0, TCSAFLUSH
, &rtt
);
792 sigprocmask(SIG_SETMASK
, &original_sigmask
, 0);
797 _config
->Set("APT::Keep-Fds::",fd
[1]);
803 if(slave
>= 0 && master
>= 0)
806 ioctl(slave
, TIOCSCTTY
, 0);
813 close(fd
[0]); // close the read end of the pipe
815 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
818 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
821 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
824 // Discard everything in stdin before forking dpkg
825 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
828 while (read(STDIN_FILENO
,&dummy
,1) == 1);
830 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
835 /* No Job Control Stop Env is a magic dpkg var that prevents it
836 from using sigstop */
837 putenv((char *)"DPKG_NO_TSTP=yes");
838 execvp(Args
[0],(char **)Args
);
839 cerr
<< "Could not exec dpkg!" << endl
;
843 // clear the Keep-Fd again
844 _config
->Clear("APT::Keep-Fds",fd
[1]);
849 // we read from dpkg here
851 close(fd
[1]); // close the write end of the pipe
853 // the result of the waitpid call
859 sigemptyset(&sigmask
);
860 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
863 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
865 // FIXME: move this to a function or something, looks ugly here
866 // error handling, waitpid returned -1
869 RunScripts("DPkg::Post-Invoke");
871 // Restore sig int/quit
872 signal(SIGQUIT
,old_SIGQUIT
);
873 signal(SIGINT
,old_SIGINT
);
874 return _error
->Errno("waitpid","Couldn't wait for subprocess");
876 // wait for input or output here
878 if (!stdin_is_dev_null
)
880 FD_SET(_dpkgin
, &rfds
);
882 FD_SET(master
, &rfds
);
885 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
886 &tv
, &original_sigmask
);
887 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
888 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
889 NULL
, &tv
, &original_sigmask
);
892 else if (select_ret
< 0 && errno
== EINTR
)
894 else if (select_ret
< 0)
896 perror("select() returned error");
900 if(master
>= 0 && FD_ISSET(master
, &rfds
))
901 DoTerminalPty(master
);
902 if(master
>= 0 && FD_ISSET(0, &rfds
))
904 if(FD_ISSET(_dpkgin
, &rfds
))
905 DoDpkgStatusFd(_dpkgin
, OutStatusFd
);
909 // Restore sig int/quit
910 signal(SIGQUIT
,old_SIGQUIT
);
911 signal(SIGINT
,old_SIGINT
);
915 tcsetattr(0, TCSAFLUSH
, &tt
);
919 // Check for an error code.
920 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
922 // if it was set to "keep-dpkg-runing" then we won't return
923 // here but keep the loop going and just report it as a error
925 bool stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
928 RunScripts("DPkg::Post-Invoke");
930 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
931 _error
->Error("Sub-process %s received a segmentation fault.",Args
[0]);
932 else if (WIFEXITED(Status
) != 0)
933 _error
->Error("Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
935 _error
->Error("Sub-process %s exited unexpectedly",Args
[0]);
946 if (RunScripts("DPkg::Post-Invoke") == false)
951 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
952 // ---------------------------------------------------------------------
954 void pkgDPkgPM::Reset()
956 List
.erase(List
.begin(),List
.end());
959 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
960 // ---------------------------------------------------------------------
962 void pkgDPkgPM::WriteApportReport(const char *pkgpath
, const char *errormsg
)
964 string pkgname
, reportfile
, srcpkgname
, pkgver
, arch
;
965 string::size_type pos
;
968 if (_config
->FindB("Dpkg::ApportFailureReport",true) == false)
970 std::clog
<< "configured to not write apport reports" << std::endl
;
974 // only report the first errors
975 if(pkgFailures
> _config
->FindI("APT::Apport::MaxReports", 3))
977 std::clog
<< _("No apport report written because MaxReports is reached already") << std::endl
;
981 // check if its not a follow up error
982 const char *needle
= dgettext("dpkg", "dependency problems - leaving unconfigured");
983 if(strstr(errormsg
, needle
) != NULL
) {
984 std::clog
<< _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl
;
988 // do not report disk-full failures
989 if(strstr(errormsg
, strerror(ENOSPC
)) != NULL
) {
990 std::clog
<< _("No apport report written because the error message indicates a disk full error") << std::endl
;
994 // get the pkgname and reportfile
995 pkgname
= flNotDir(pkgpath
);
996 pos
= pkgname
.find('_');
997 if(pos
!= string::npos
)
998 pkgname
= pkgname
.substr(0, pos
);
1000 // find the package versin and source package name
1001 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
1002 if (Pkg
.end() == true)
1004 pkgCache::VerIterator Ver
= Cache
.GetCandidateVer(Pkg
);
1005 if (Ver
.end() == true)
1007 pkgver
= Ver
.VerStr() == NULL
? "unknown" : Ver
.VerStr();
1008 pkgRecords
Recs(Cache
);
1009 pkgRecords::Parser
&Parse
= Recs
.Lookup(Ver
.FileList());
1010 srcpkgname
= Parse
.SourcePkg();
1011 if(srcpkgname
.empty())
1012 srcpkgname
= pkgname
;
1014 // if the file exists already, we check:
1015 // - if it was reported already (touched by apport).
1016 // If not, we do nothing, otherwise
1017 // we overwrite it. This is the same behaviour as apport
1018 // - if we have a report with the same pkgversion already
1020 reportfile
= flCombine("/var/crash",pkgname
+".0.crash");
1021 if(FileExists(reportfile
))
1026 // check atime/mtime
1027 stat(reportfile
.c_str(), &buf
);
1028 if(buf
.st_mtime
> buf
.st_atime
)
1031 // check if the existing report is the same version
1032 report
= fopen(reportfile
.c_str(),"r");
1033 while(fgets(strbuf
, sizeof(strbuf
), report
) != NULL
)
1035 if(strstr(strbuf
,"Package:") == strbuf
)
1037 char pkgname
[255], version
[255];
1038 if(sscanf(strbuf
, "Package: %s %s", pkgname
, version
) == 2)
1039 if(strcmp(pkgver
.c_str(), version
) == 0)
1049 // now write the report
1050 arch
= _config
->Find("APT::Architecture");
1051 report
= fopen(reportfile
.c_str(),"w");
1054 if(_config
->FindB("DPkgPM::InitialReportOnly",false) == true)
1055 chmod(reportfile
.c_str(), 0);
1057 chmod(reportfile
.c_str(), 0600);
1058 fprintf(report
, "ProblemType: Package\n");
1059 fprintf(report
, "Architecture: %s\n", arch
.c_str());
1060 time_t now
= time(NULL
);
1061 fprintf(report
, "Date: %s" , ctime(&now
));
1062 fprintf(report
, "Package: %s %s\n", pkgname
.c_str(), pkgver
.c_str());
1063 fprintf(report
, "SourcePackage: %s\n", srcpkgname
.c_str());
1064 fprintf(report
, "ErrorMessage:\n %s\n", errormsg
);
1066 // ensure that the log is flushed
1070 // attach terminal log it if we have it
1071 string logfile_name
= _config
->FindFile("Dir::Log::Terminal");
1072 if (!logfile_name
.empty())
1077 fprintf(report
, "DpkgTerminalLog:\n");
1078 log
= fopen(logfile_name
.c_str(),"r");
1081 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1082 fprintf(report
, " %s", buf
);