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>
37 #include <sys/ioctl.h>
48 // Maps the dpkg "processing" info to human readable names. Entry 0
49 // of each array is the key, entry 1 is the value.
50 const std::pair
<const char *, const char *> PackageProcessingOps
[] = {
51 std::make_pair("install", N_("Installing %s")),
52 std::make_pair("configure", N_("Configuring %s")),
53 std::make_pair("remove", N_("Removing %s")),
54 std::make_pair("trigproc", N_("Running post-installation trigger %s"))
57 const std::pair
<const char *, const char *> * const PackageProcessingOpsBegin
= PackageProcessingOps
;
58 const std::pair
<const char *, const char *> * const PackageProcessingOpsEnd
= PackageProcessingOps
+ sizeof(PackageProcessingOps
) / sizeof(PackageProcessingOps
[0]);
60 // Predicate to test whether an entry in the PackageProcessingOps
61 // array matches a string.
62 class MatchProcessingOp
67 MatchProcessingOp(const char *the_target
)
72 bool operator()(const std::pair
<const char *, const char *> &pair
) const
74 return strcmp(pair
.first
, target
) == 0;
79 /* helper function to ionice the given PID
81 there is no C header for ionice yet - just the syscall interface
82 so we use the binary from util-linux
87 if (!FileExists("/usr/bin/ionice"))
89 pid_t Process
= ExecFork();
93 snprintf(buf
, sizeof(buf
), "-p%d", PID
);
95 Args
[0] = "/usr/bin/ionice";
99 execv(Args
[0], (char **)Args
);
101 return ExecWait(Process
, "ionice");
104 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
105 // ---------------------------------------------------------------------
107 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
108 : pkgPackageManager(Cache
), dpkgbuf_pos(0),
109 term_out(NULL
), PackagesDone(0), PackagesTotal(0), pkgFailures(0)
113 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
114 // ---------------------------------------------------------------------
116 pkgDPkgPM::~pkgDPkgPM()
120 // DPkgPM::Install - Install a package /*{{{*/
121 // ---------------------------------------------------------------------
122 /* Add an install operation to the sequence list */
123 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
125 if (File
.empty() == true || Pkg
.end() == true)
126 return _error
->Error("Internal Error, No file name for %s",Pkg
.Name());
128 List
.push_back(Item(Item::Install
,Pkg
,File
));
132 // DPkgPM::Configure - Configure a package /*{{{*/
133 // ---------------------------------------------------------------------
134 /* Add a configure operation to the sequence list */
135 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
137 if (Pkg
.end() == true)
140 List
.push_back(Item(Item::Configure
, Pkg
));
142 // Use triggers for config calls if we configure "smart"
143 // as otherwise Pre-Depends will not be satisfied, see #526774
144 if (_config
->FindB("DPkg::TriggersPending", false) == true)
145 List
.push_back(Item(Item::TriggersPending
, PkgIterator()));
150 // DPkgPM::Remove - Remove a package /*{{{*/
151 // ---------------------------------------------------------------------
152 /* Add a remove operation to the sequence list */
153 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
155 if (Pkg
.end() == true)
159 List
.push_back(Item(Item::Purge
,Pkg
));
161 List
.push_back(Item(Item::Remove
,Pkg
));
165 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
166 // ---------------------------------------------------------------------
167 /* This is part of the helper script communication interface, it sends
168 very complete information down to the other end of the pipe.*/
169 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
171 fprintf(F
,"VERSION 2\n");
173 /* Write out all of the configuration directives by walking the
174 configuration tree */
175 const Configuration::Item
*Top
= _config
->Tree(0);
178 if (Top
->Value
.empty() == false)
181 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
182 QuoteString(Top
->Value
,"\n").c_str());
191 while (Top
!= 0 && Top
->Next
== 0)
198 // Write out the package actions in order.
199 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
201 if(I
->Pkg
.end() == true)
204 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
206 fprintf(F
,"%s ",I
->Pkg
.Name());
208 if (I
->Pkg
->CurrentVer
== 0)
211 fprintf(F
,"%s ",I
->Pkg
.CurrentVer().VerStr());
213 // Show the compare operator
215 if (S
.InstallVer
!= 0)
218 if (I
->Pkg
->CurrentVer
!= 0)
219 Comp
= S
.InstVerIter(Cache
).CompareVer(I
->Pkg
.CurrentVer());
226 fprintf(F
,"%s ",S
.InstVerIter(Cache
).VerStr());
231 // Show the filename/operation
232 if (I
->Op
== Item::Install
)
235 if (I
->File
[0] != '/')
236 fprintf(F
,"**ERROR**\n");
238 fprintf(F
,"%s\n",I
->File
.c_str());
240 if (I
->Op
== Item::Configure
)
241 fprintf(F
,"**CONFIGURE**\n");
242 if (I
->Op
== Item::Remove
||
243 I
->Op
== Item::Purge
)
244 fprintf(F
,"**REMOVE**\n");
252 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
253 // ---------------------------------------------------------------------
254 /* This looks for a list of scripts to run from the configuration file
255 each one is run and is fed on standard input a list of all .deb files
256 that are due to be installed. */
257 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
259 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
260 if (Opts
== 0 || Opts
->Child
== 0)
264 unsigned int Count
= 1;
265 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
267 if (Opts
->Value
.empty() == true)
270 // Determine the protocol version
271 string OptSec
= Opts
->Value
;
272 string::size_type Pos
;
273 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
274 Pos
= OptSec
.length();
275 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
277 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
281 if (pipe(Pipes
) != 0)
282 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
283 SetCloseExec(Pipes
[0],true);
284 SetCloseExec(Pipes
[1],true);
286 // Purified Fork for running the script
287 pid_t Process
= ExecFork();
291 dup2(Pipes
[0],STDIN_FILENO
);
292 SetCloseExec(STDOUT_FILENO
,false);
293 SetCloseExec(STDIN_FILENO
,false);
294 SetCloseExec(STDERR_FILENO
,false);
299 Args
[2] = Opts
->Value
.c_str();
301 execv(Args
[0],(char **)Args
);
305 FILE *F
= fdopen(Pipes
[1],"w");
307 return _error
->Errno("fdopen","Faild to open new FD");
309 // Feed it the filenames.
313 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
315 // Only deal with packages to be installed from .deb
316 if (I
->Op
!= Item::Install
)
320 if (I
->File
[0] != '/')
323 /* Feed the filename of each package that is pending install
325 fprintf(F
,"%s\n",I
->File
.c_str());
334 Die
= !SendV2Pkgs(F
);
338 // Clean up the sub process
339 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
340 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
346 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
347 // ---------------------------------------------------------------------
350 void pkgDPkgPM::DoStdin(int master
)
352 unsigned char input_buf
[256] = {0,};
353 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
355 write(master
, input_buf
, len
);
357 stdin_is_dev_null
= true;
360 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
361 // ---------------------------------------------------------------------
363 * read the terminal pty and write log
365 void pkgDPkgPM::DoTerminalPty(int master
)
367 unsigned char term_buf
[1024] = {0,0, };
369 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
370 if(len
== -1 && errno
== EIO
)
372 // this happens when the child is about to exit, we
373 // give it time to actually exit, otherwise we run
380 write(1, term_buf
, len
);
382 fwrite(term_buf
, len
, sizeof(char), term_out
);
385 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
386 // ---------------------------------------------------------------------
389 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd
, char *line
)
391 bool const Debug
= _config
->FindB("Debug::pkgDPkgProgressReporting",false);
392 // the status we output
393 ostringstream status
;
396 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
399 /* dpkg sends strings like this:
400 'status: <pkg>: <pkg qstate>'
401 errors look like this:
402 '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
403 and conffile-prompt like this
404 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
406 Newer versions of dpkg sent also:
407 'processing: install: pkg'
408 'processing: configure: pkg'
409 'processing: remove: pkg'
410 'processing: purge: pkg' - but for apt is it a ignored "unknown" action
411 'processing: trigproc: trigger'
415 // dpkg sends multiline error messages sometimes (see
416 // #374195 for a example. we should support this by
417 // either patching dpkg to not send multiline over the
418 // statusfd or by rewriting the code here to deal with
419 // it. for now we just ignore it and not crash
420 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
421 if( list
[0] == NULL
|| list
[1] == NULL
|| list
[2] == NULL
)
424 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
427 const char* const pkg
= list
[1];
428 const char* action
= _strstrip(list
[2]);
430 // 'processing' from dpkg looks like
431 // 'processing: action: pkg'
432 if(strncmp(list
[0], "processing", strlen("processing")) == 0)
435 const char* const pkg_or_trigger
= _strstrip(list
[2]);
436 action
= _strstrip( list
[1]);
437 const std::pair
<const char *, const char *> * const iter
=
438 std::find_if(PackageProcessingOpsBegin
,
439 PackageProcessingOpsEnd
,
440 MatchProcessingOp(action
));
441 if(iter
== PackageProcessingOpsEnd
)
444 std::clog
<< "ignoring unknown action: " << action
<< std::endl
;
447 snprintf(s
, sizeof(s
), _(iter
->second
), pkg_or_trigger
);
449 status
<< "pmstatus:" << pkg_or_trigger
450 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
454 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
456 std::clog
<< "send: '" << status
.str() << "'" << endl
;
460 if(strncmp(action
,"error",strlen("error")) == 0)
462 // urgs, sometime has ":" in its error string so that we
463 // end up with the error message split between list[3]
464 // and list[4], e.g. the message:
465 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
467 if( list
[4] != NULL
)
468 list
[3][strlen(list
[3])] = ':';
470 status
<< "pmerror:" << list
[1]
471 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
475 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
477 std::clog
<< "send: '" << status
.str() << "'" << endl
;
479 WriteApportReport(list
[1], list
[3]);
482 else if(strncmp(action
,"conffile",strlen("conffile")) == 0)
484 status
<< "pmconffile:" << list
[1]
485 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
489 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
491 std::clog
<< "send: '" << status
.str() << "'" << endl
;
495 vector
<struct DpkgState
> const &states
= PackageOps
[pkg
];
496 const char *next_action
= NULL
;
497 if(PackageOpsDone
[pkg
] < states
.size())
498 next_action
= states
[PackageOpsDone
[pkg
]].state
;
499 // check if the package moved to the next dpkg state
500 if(next_action
&& (strcmp(action
, next_action
) == 0))
502 // only read the translation if there is actually a next
504 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
506 snprintf(s
, sizeof(s
), translation
, pkg
);
508 // we moved from one dpkg state to a new one, report that
509 PackageOpsDone
[pkg
]++;
511 // build the status str
512 status
<< "pmstatus:" << pkg
513 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
517 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
519 std::clog
<< "send: '" << status
.str() << "'" << endl
;
522 std::clog
<< "(parsed from dpkg) pkg: " << pkg
523 << " action: " << action
<< endl
;
526 // DPkgPM::DoDpkgStatusFd /*{{{*/
527 // ---------------------------------------------------------------------
530 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
, int OutStatusFd
)
535 len
=read(statusfd
, &dpkgbuf
[dpkgbuf_pos
], sizeof(dpkgbuf
)-dpkgbuf_pos
);
540 // process line by line if we have a buffer
542 while((q
=(char*)memchr(p
, '\n', dpkgbuf
+dpkgbuf_pos
-p
)) != NULL
)
545 ProcessDpkgStatusLine(OutStatusFd
, p
);
546 p
=q
+1; // continue with next line
549 // now move the unprocessed bits (after the final \n that is now a 0x0)
550 // to the start and update dpkgbuf_pos
551 p
= (char*)memrchr(dpkgbuf
, 0, dpkgbuf_pos
);
555 // we are interessted in the first char *after* 0x0
558 // move the unprocessed tail to the start and update pos
559 memmove(dpkgbuf
, p
, p
-dpkgbuf
);
560 dpkgbuf_pos
= dpkgbuf
+dpkgbuf_pos
-p
;
563 // DPkgPM::OpenLog /*{{{*/
564 bool pkgDPkgPM::OpenLog()
566 string logdir
= _config
->FindDir("Dir::Log");
567 if(not FileExists(logdir
))
568 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
569 string logfile_name
= flCombine(logdir
,
570 _config
->Find("Dir::Log::Terminal"));
571 if (!logfile_name
.empty())
573 term_out
= fopen(logfile_name
.c_str(),"a");
574 chmod(logfile_name
.c_str(), 0600);
575 // output current time
577 time_t t
= time(NULL
);
578 struct tm
*tmp
= localtime(&t
);
579 strftime(outstr
, sizeof(outstr
), "%F %T", tmp
);
580 fprintf(term_out
, "\nLog started: ");
581 fprintf(term_out
, "%s", outstr
);
582 fprintf(term_out
, "\n");
587 // DPkg::CloseLog /*{{{*/
588 bool pkgDPkgPM::CloseLog()
593 time_t t
= time(NULL
);
594 struct tm
*tmp
= localtime(&t
);
595 strftime(outstr
, sizeof(outstr
), "%F %T", tmp
);
596 fprintf(term_out
, "Log ended: ");
597 fprintf(term_out
, "%s", outstr
);
598 fprintf(term_out
, "\n");
606 // This implements a racy version of pselect for those architectures
607 // that don't have a working implementation.
608 // FIXME: Probably can be removed on Lenny+1
609 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
610 fd_set
*exceptfds
, const struct timespec
*timeout
,
611 const sigset_t
*sigmask
)
617 tv
.tv_sec
= timeout
->tv_sec
;
618 tv
.tv_usec
= timeout
->tv_nsec
/1000;
620 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
621 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
622 sigprocmask(SIG_SETMASK
, &origmask
, 0);
626 // DPkgPM::Go - Run the sequence /*{{{*/
627 // ---------------------------------------------------------------------
628 /* This globs the operations and calls dpkg
630 * If it is called with "OutStatusFd" set to a valid file descriptor
631 * apt will report the install progress over this fd. It maps the
632 * dpkg states a package goes through to human readable (and i10n-able)
633 * names and calculates a percentage for each step.
635 bool pkgDPkgPM::Go(int OutStatusFd
)
640 sigset_t original_sigmask
;
642 unsigned int const MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
643 unsigned int const MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
644 bool const NoTriggers
= _config
->FindB("DPkg::NoTriggers", false);
646 if (RunScripts("DPkg::Pre-Invoke") == false)
649 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
652 // support subpressing of triggers processing for special
653 // cases like d-i that runs the triggers handling manually
654 bool const SmartConf
= (_config
->Find("PackageManager::Configure", "all") != "all");
655 if (_config
->FindB("DPkg::ConfigurePending", SmartConf
) == true)
656 List
.push_back(Item(Item::ConfigurePending
, PkgIterator()));
658 // map the dpkg states to the operations that are performed
659 // (this is sorted in the same way as Item::Ops)
660 static const struct DpkgState DpkgStatesOpMap
[][7] = {
663 {"half-installed", N_("Preparing %s")},
664 {"unpacked", N_("Unpacking %s") },
667 // Configure operation
669 {"unpacked",N_("Preparing to configure %s") },
670 {"half-configured", N_("Configuring %s") },
671 { "installed", N_("Installed %s")},
676 {"half-configured", N_("Preparing for removal of %s")},
677 {"half-installed", N_("Removing %s")},
678 {"config-files", N_("Removed %s")},
683 {"config-files", N_("Preparing to completely remove %s")},
684 {"not-installed", N_("Completely removed %s")},
689 // init the PackageOps map, go over the list of packages that
690 // that will be [installed|configured|removed|purged] and add
691 // them to the PackageOps map (the dpkg states it goes through)
692 // and the PackageOpsTranslations (human readable strings)
693 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();I
++)
695 if((*I
).Pkg
.end() == true)
698 string
const name
= (*I
).Pkg
.Name();
699 PackageOpsDone
[name
] = 0;
700 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; i
++)
702 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
707 stdin_is_dev_null
= false;
712 // this loop is runs once per operation
713 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();)
715 vector
<Item
>::const_iterator J
= I
;
716 for (; J
!= List
.end() && J
->Op
== I
->Op
; J
++)
719 // Generate the argument list
720 const char *Args
[MaxArgs
+ 50];
722 // Now check if we are within the MaxArgs limit
724 // this code below is problematic, because it may happen that
725 // the argument list is split in a way that A depends on B
726 // and they are in the same "--configure A B" run
727 // - with the split they may now be configured in different
729 if (J
- I
> (signed)MaxArgs
)
733 unsigned long Size
= 0;
734 string
const Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
735 Args
[n
++] = Tmp
.c_str();
736 Size
+= strlen(Args
[n
-1]);
738 // Stick in any custom dpkg options
739 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
743 for (; Opts
!= 0; Opts
= Opts
->Next
)
745 if (Opts
->Value
.empty() == true)
747 Args
[n
++] = Opts
->Value
.c_str();
748 Size
+= Opts
->Value
.length();
752 char status_fd_buf
[20];
756 Args
[n
++] = "--status-fd";
757 Size
+= strlen(Args
[n
-1]);
758 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
759 Args
[n
++] = status_fd_buf
;
760 Size
+= strlen(Args
[n
-1]);
765 Args
[n
++] = "--force-depends";
766 Size
+= strlen(Args
[n
-1]);
767 Args
[n
++] = "--force-remove-essential";
768 Size
+= strlen(Args
[n
-1]);
769 Args
[n
++] = "--remove";
770 Size
+= strlen(Args
[n
-1]);
774 Args
[n
++] = "--force-depends";
775 Size
+= strlen(Args
[n
-1]);
776 Args
[n
++] = "--force-remove-essential";
777 Size
+= strlen(Args
[n
-1]);
778 Args
[n
++] = "--purge";
779 Size
+= strlen(Args
[n
-1]);
782 case Item::Configure
:
783 Args
[n
++] = "--configure";
784 Size
+= strlen(Args
[n
-1]);
787 case Item::ConfigurePending
:
788 Args
[n
++] = "--configure";
789 Size
+= strlen(Args
[n
-1]);
790 Args
[n
++] = "--pending";
791 Size
+= strlen(Args
[n
-1]);
794 case Item::TriggersPending
:
795 Args
[n
++] = "--triggers-only";
796 Size
+= strlen(Args
[n
-1]);
797 Args
[n
++] = "--pending";
798 Size
+= strlen(Args
[n
-1]);
802 Args
[n
++] = "--unpack";
803 Size
+= strlen(Args
[n
-1]);
804 Args
[n
++] = "--auto-deconfigure";
805 Size
+= strlen(Args
[n
-1]);
809 if (NoTriggers
== true && I
->Op
!= Item::TriggersPending
&&
810 I
->Op
!= Item::ConfigurePending
)
812 Args
[n
++] = "--no-triggers";
813 Size
+= strlen(Args
[n
-1]);
816 // Write in the file or package names
817 if (I
->Op
== Item::Install
)
819 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
821 if (I
->File
[0] != '/')
822 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
823 Args
[n
++] = I
->File
.c_str();
824 Size
+= strlen(Args
[n
-1]);
829 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
831 if((*I
).Pkg
.end() == true)
833 Args
[n
++] = I
->Pkg
.Name();
834 Size
+= strlen(Args
[n
-1]);
840 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
842 for (unsigned int k
= 0; k
!= n
; k
++)
843 clog
<< Args
[k
] << ' ';
852 /* Mask off sig int/quit. We do this because dpkg also does when
853 it forks scripts. What happens is that when you hit ctrl-c it sends
854 it to all processes in the group. Since dpkg ignores the signal
855 it doesn't die but we do! So we must also ignore it */
856 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
857 sighandler_t old_SIGINT
= signal(SIGINT
,SIG_IGN
);
859 // ignore SIGHUP as well (debian #463030)
860 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
867 // if tcgetattr does not return zero there was a error
868 // and we do not do any pty magic
869 if (tcgetattr(0, &tt
) == 0)
871 ioctl(0, TIOCGWINSZ
, (char *)&win
);
872 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
874 const char *s
= _("Can not write log, openpty() "
875 "failed (/dev/pts not mounted?)\n");
876 fprintf(stderr
, "%s",s
);
877 fprintf(term_out
, "%s",s
);
883 rtt
.c_lflag
&= ~ECHO
;
884 // block SIGTTOU during tcsetattr to prevent a hang if
885 // the process is a member of the background process group
886 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
887 sigemptyset(&sigmask
);
888 sigaddset(&sigmask
, SIGTTOU
);
889 sigprocmask(SIG_BLOCK
,&sigmask
, &original_sigmask
);
890 tcsetattr(0, TCSAFLUSH
, &rtt
);
891 sigprocmask(SIG_SETMASK
, &original_sigmask
, 0);
897 _config
->Set("APT::Keep-Fds::",fd
[1]);
898 // send status information that we are about to fork dpkg
899 if(OutStatusFd
> 0) {
900 ostringstream status
;
901 status
<< "pmstatus:dpkg-exec:"
902 << (PackagesDone
/float(PackagesTotal
)*100.0)
903 << ":" << _("Running dpkg")
905 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
912 if(slave
>= 0 && master
>= 0)
915 ioctl(slave
, TIOCSCTTY
, 0);
922 close(fd
[0]); // close the read end of the pipe
924 if (_config
->FindDir("DPkg::Chroot-Directory","/") != "/")
926 std::cerr
<< "Chrooting into "
927 << _config
->FindDir("DPkg::Chroot-Directory")
929 if (chroot(_config
->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
933 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
936 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
939 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
942 // Discard everything in stdin before forking dpkg
943 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
946 while (read(STDIN_FILENO
,&dummy
,1) == 1);
948 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
952 /* No Job Control Stop Env is a magic dpkg var that prevents it
953 from using sigstop */
954 putenv((char *)"DPKG_NO_TSTP=yes");
955 execvp(Args
[0],(char **)Args
);
956 cerr
<< "Could not exec dpkg!" << endl
;
961 if (_config
->FindB("DPkg::UseIoNice", false) == true)
964 // clear the Keep-Fd again
965 _config
->Clear("APT::Keep-Fds",fd
[1]);
970 // we read from dpkg here
971 int const _dpkgin
= fd
[0];
972 close(fd
[1]); // close the write end of the pipe
978 sigemptyset(&sigmask
);
979 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
981 // the result of the waitpid call
984 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
986 // FIXME: move this to a function or something, looks ugly here
987 // error handling, waitpid returned -1
990 RunScripts("DPkg::Post-Invoke");
992 // Restore sig int/quit
993 signal(SIGQUIT
,old_SIGQUIT
);
994 signal(SIGINT
,old_SIGINT
);
995 signal(SIGHUP
,old_SIGHUP
);
996 return _error
->Errno("waitpid","Couldn't wait for subprocess");
998 // wait for input or output here
1000 if (!stdin_is_dev_null
)
1002 FD_SET(_dpkgin
, &rfds
);
1004 FD_SET(master
, &rfds
);
1007 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
1008 &tv
, &original_sigmask
);
1009 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
1010 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
1011 NULL
, &tv
, &original_sigmask
);
1012 if (select_ret
== 0)
1014 else if (select_ret
< 0 && errno
== EINTR
)
1016 else if (select_ret
< 0)
1018 perror("select() returned error");
1022 if(master
>= 0 && FD_ISSET(master
, &rfds
))
1023 DoTerminalPty(master
);
1024 if(master
>= 0 && FD_ISSET(0, &rfds
))
1026 if(FD_ISSET(_dpkgin
, &rfds
))
1027 DoDpkgStatusFd(_dpkgin
, OutStatusFd
);
1031 // Restore sig int/quit
1032 signal(SIGQUIT
,old_SIGQUIT
);
1033 signal(SIGINT
,old_SIGINT
);
1034 signal(SIGHUP
,old_SIGHUP
);
1038 tcsetattr(0, TCSAFLUSH
, &tt
);
1042 // Check for an error code.
1043 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
1045 // if it was set to "keep-dpkg-runing" then we won't return
1046 // here but keep the loop going and just report it as a error
1048 bool const stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
1051 RunScripts("DPkg::Post-Invoke");
1053 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
1054 _error
->Error("Sub-process %s received a segmentation fault.",Args
[0]);
1055 else if (WIFEXITED(Status
) != 0)
1056 _error
->Error("Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
1058 _error
->Error("Sub-process %s exited unexpectedly",Args
[0]);
1069 if (RunScripts("DPkg::Post-Invoke") == false)
1072 Cache
.writeStateFile(NULL
);
1076 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1077 // ---------------------------------------------------------------------
1079 void pkgDPkgPM::Reset()
1081 List
.erase(List
.begin(),List
.end());
1084 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1085 // ---------------------------------------------------------------------
1087 void pkgDPkgPM::WriteApportReport(const char *pkgpath
, const char *errormsg
)
1089 string pkgname
, reportfile
, srcpkgname
, pkgver
, arch
;
1090 string::size_type pos
;
1093 if (_config
->FindB("Dpkg::ApportFailureReport",true) == false)
1095 std::clog
<< "configured to not write apport reports" << std::endl
;
1099 // only report the first errors
1100 if(pkgFailures
> _config
->FindI("APT::Apport::MaxReports", 3))
1102 std::clog
<< _("No apport report written because MaxReports is reached already") << std::endl
;
1106 // check if its not a follow up error
1107 const char *needle
= dgettext("dpkg", "dependency problems - leaving unconfigured");
1108 if(strstr(errormsg
, needle
) != NULL
) {
1109 std::clog
<< _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl
;
1113 // do not report disk-full failures
1114 if(strstr(errormsg
, strerror(ENOSPC
)) != NULL
) {
1115 std::clog
<< _("No apport report written because the error message indicates a disk full error") << std::endl
;
1119 // do not report out-of-memory failures
1120 if(strstr(errormsg
, strerror(ENOMEM
)) != NULL
) {
1121 std::clog
<< _("No apport report written because the error message indicates a out of memory error") << std::endl
;
1125 // do not report dpkg I/O errors
1126 // XXX - this message is localized, but this only matches the English version. This is better than nothing.
1127 if(strstr(errormsg
, "short read in buffer_copy (")) {
1128 std::clog
<< _("No apport report written because the error message indicates a dpkg I/O error") << std::endl
;
1132 // get the pkgname and reportfile
1133 pkgname
= flNotDir(pkgpath
);
1134 pos
= pkgname
.find('_');
1135 if(pos
!= string::npos
)
1136 pkgname
= pkgname
.substr(0, pos
);
1138 // find the package versin and source package name
1139 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
1140 if (Pkg
.end() == true)
1142 pkgCache::VerIterator Ver
= Cache
.GetCandidateVer(Pkg
);
1143 if (Ver
.end() == true)
1145 pkgver
= Ver
.VerStr() == NULL
? "unknown" : Ver
.VerStr();
1146 pkgRecords
Recs(Cache
);
1147 pkgRecords::Parser
&Parse
= Recs
.Lookup(Ver
.FileList());
1148 srcpkgname
= Parse
.SourcePkg();
1149 if(srcpkgname
.empty())
1150 srcpkgname
= pkgname
;
1152 // if the file exists already, we check:
1153 // - if it was reported already (touched by apport).
1154 // If not, we do nothing, otherwise
1155 // we overwrite it. This is the same behaviour as apport
1156 // - if we have a report with the same pkgversion already
1158 reportfile
= flCombine("/var/crash",pkgname
+".0.crash");
1159 if(FileExists(reportfile
))
1164 // check atime/mtime
1165 stat(reportfile
.c_str(), &buf
);
1166 if(buf
.st_mtime
> buf
.st_atime
)
1169 // check if the existing report is the same version
1170 report
= fopen(reportfile
.c_str(),"r");
1171 while(fgets(strbuf
, sizeof(strbuf
), report
) != NULL
)
1173 if(strstr(strbuf
,"Package:") == strbuf
)
1175 char pkgname
[255], version
[255];
1176 if(sscanf(strbuf
, "Package: %s %s", pkgname
, version
) == 2)
1177 if(strcmp(pkgver
.c_str(), version
) == 0)
1187 // now write the report
1188 arch
= _config
->Find("APT::Architecture");
1189 report
= fopen(reportfile
.c_str(),"w");
1192 if(_config
->FindB("DPkgPM::InitialReportOnly",false) == true)
1193 chmod(reportfile
.c_str(), 0);
1195 chmod(reportfile
.c_str(), 0600);
1196 fprintf(report
, "ProblemType: Package\n");
1197 fprintf(report
, "Architecture: %s\n", arch
.c_str());
1198 time_t now
= time(NULL
);
1199 fprintf(report
, "Date: %s" , ctime(&now
));
1200 fprintf(report
, "Package: %s %s\n", pkgname
.c_str(), pkgver
.c_str());
1201 fprintf(report
, "SourcePackage: %s\n", srcpkgname
.c_str());
1202 fprintf(report
, "ErrorMessage:\n %s\n", errormsg
);
1204 // ensure that the log is flushed
1208 // attach terminal log it if we have it
1209 string logfile_name
= _config
->FindFile("Dir::Log::Terminal");
1210 if (!logfile_name
.empty())
1215 fprintf(report
, "DpkgTerminalLog:\n");
1216 log
= fopen(logfile_name
.c_str(),"r");
1219 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1220 fprintf(report
, " %s", buf
);
1226 const char *ops_str
[] = {"Install", "Configure","Remove","Purge"};
1227 fprintf(report
, "AptOrdering:\n");
1228 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
1229 fprintf(report
, " %s: %s\n", (*I
).Pkg
.Name(), ops_str
[(*I
).Op
]);
1231 // attach dmesg log (to learn about segfaults)
1232 if (FileExists("/bin/dmesg"))
1237 fprintf(report
, "Dmesg:\n");
1238 log
= popen("/bin/dmesg","r");
1241 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1242 fprintf(report
, " %s", buf
);
1247 // attach df -l log (to learn about filesystem status)
1248 if (FileExists("/bin/df"))
1253 fprintf(report
, "Df:\n");
1254 log
= popen("/bin/df -l","r");
1257 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1258 fprintf(report
, " %s", buf
);