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 ##################################################################### */
13 #include <apt-pkg/cachefile.h>
14 #include <apt-pkg/configuration.h>
15 #include <apt-pkg/depcache.h>
16 #include <apt-pkg/dpkgpm.h>
17 #include <apt-pkg/error.h>
18 #include <apt-pkg/fileutl.h>
19 #include <apt-pkg/install-progress.h>
20 #include <apt-pkg/packagemanager.h>
21 #include <apt-pkg/pkgrecords.h>
22 #include <apt-pkg/strutl.h>
23 #include <apt-pkg/cacheiterators.h>
24 #include <apt-pkg/macros.h>
25 #include <apt-pkg/pkgcache.h>
36 #include <sys/ioctl.h>
37 #include <sys/select.h>
58 class pkgDPkgPMPrivate
61 pkgDPkgPMPrivate() : stdin_is_dev_null(false), dpkgbuf_pos(0),
62 term_out(NULL
), history_out(NULL
),
63 progress(NULL
), master(-1), slave(-1)
70 bool stdin_is_dev_null
;
71 // the buffer we use for the dpkg status-fd reading
77 APT::Progress::PackageManager
*progress
;
86 sigset_t original_sigmask
;
92 // Maps the dpkg "processing" info to human readable names. Entry 0
93 // of each array is the key, entry 1 is the value.
94 const std::pair
<const char *, const char *> PackageProcessingOps
[] = {
95 std::make_pair("install", N_("Installing %s")),
96 std::make_pair("configure", N_("Configuring %s")),
97 std::make_pair("remove", N_("Removing %s")),
98 std::make_pair("purge", N_("Completely removing %s")),
99 std::make_pair("disappear", N_("Noting disappearance of %s")),
100 std::make_pair("trigproc", N_("Running post-installation trigger %s"))
103 const std::pair
<const char *, const char *> * const PackageProcessingOpsBegin
= PackageProcessingOps
;
104 const std::pair
<const char *, const char *> * const PackageProcessingOpsEnd
= PackageProcessingOps
+ sizeof(PackageProcessingOps
) / sizeof(PackageProcessingOps
[0]);
106 // Predicate to test whether an entry in the PackageProcessingOps
107 // array matches a string.
108 class MatchProcessingOp
113 MatchProcessingOp(const char *the_target
)
118 bool operator()(const std::pair
<const char *, const char *> &pair
) const
120 return strcmp(pair
.first
, target
) == 0;
125 /* helper function to ionice the given PID
127 there is no C header for ionice yet - just the syscall interface
128 so we use the binary from util-linux
133 if (!FileExists("/usr/bin/ionice"))
135 pid_t Process
= ExecFork();
139 snprintf(buf
, sizeof(buf
), "-p%d", PID
);
141 Args
[0] = "/usr/bin/ionice";
145 execv(Args
[0], (char **)Args
);
147 return ExecWait(Process
, "ionice");
150 static std::string
getDpkgExecutable()
152 string Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
153 string
const dpkgChrootDir
= _config
->FindDir("DPkg::Chroot-Directory", "/");
154 size_t dpkgChrootLen
= dpkgChrootDir
.length();
155 if (dpkgChrootDir
!= "/" && Tmp
.find(dpkgChrootDir
) == 0)
157 if (dpkgChrootDir
[dpkgChrootLen
- 1] == '/')
159 Tmp
= Tmp
.substr(dpkgChrootLen
);
164 // dpkgChrootDirectory - chrooting for dpkg if needed /*{{{*/
165 static void dpkgChrootDirectory()
167 std::string
const chrootDir
= _config
->FindDir("DPkg::Chroot-Directory");
168 if (chrootDir
== "/")
170 std::cerr
<< "Chrooting into " << chrootDir
<< std::endl
;
171 if (chroot(chrootDir
.c_str()) != 0)
179 // FindNowVersion - Helper to find a Version in "now" state /*{{{*/
180 // ---------------------------------------------------------------------
181 /* This is helpful when a package is no longer installed but has residual
185 pkgCache::VerIterator
FindNowVersion(const pkgCache::PkgIterator
&Pkg
)
187 pkgCache::VerIterator Ver
;
188 for (Ver
= Pkg
.VersionList(); Ver
.end() == false; ++Ver
)
190 pkgCache::VerFileIterator Vf
= Ver
.FileList();
191 pkgCache::PkgFileIterator F
= Vf
.File();
192 for (F
= Vf
.File(); F
.end() == false; ++F
)
194 if (F
&& F
.Archive())
196 if (strcmp(F
.Archive(), "now"))
205 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
206 // ---------------------------------------------------------------------
208 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
209 : pkgPackageManager(Cache
), pkgFailures(0), PackagesDone(0), PackagesTotal(0)
211 d
= new pkgDPkgPMPrivate();
214 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
215 // ---------------------------------------------------------------------
217 pkgDPkgPM::~pkgDPkgPM()
222 // DPkgPM::Install - Install a package /*{{{*/
223 // ---------------------------------------------------------------------
224 /* Add an install operation to the sequence list */
225 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
227 if (File
.empty() == true || Pkg
.end() == true)
228 return _error
->Error("Internal Error, No file name for %s",Pkg
.FullName().c_str());
230 // If the filename string begins with DPkg::Chroot-Directory, return the
231 // substr that is within the chroot so dpkg can access it.
232 string
const chrootdir
= _config
->FindDir("DPkg::Chroot-Directory","/");
233 if (chrootdir
!= "/" && File
.find(chrootdir
) == 0)
235 size_t len
= chrootdir
.length();
236 if (chrootdir
.at(len
- 1) == '/')
238 List
.push_back(Item(Item::Install
,Pkg
,File
.substr(len
)));
241 List
.push_back(Item(Item::Install
,Pkg
,File
));
246 // DPkgPM::Configure - Configure a package /*{{{*/
247 // ---------------------------------------------------------------------
248 /* Add a configure operation to the sequence list */
249 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
251 if (Pkg
.end() == true)
254 List
.push_back(Item(Item::Configure
, Pkg
));
256 // Use triggers for config calls if we configure "smart"
257 // as otherwise Pre-Depends will not be satisfied, see #526774
258 if (_config
->FindB("DPkg::TriggersPending", false) == true)
259 List
.push_back(Item(Item::TriggersPending
, PkgIterator()));
264 // DPkgPM::Remove - Remove a package /*{{{*/
265 // ---------------------------------------------------------------------
266 /* Add a remove operation to the sequence list */
267 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
269 if (Pkg
.end() == true)
273 List
.push_back(Item(Item::Purge
,Pkg
));
275 List
.push_back(Item(Item::Remove
,Pkg
));
279 // DPkgPM::SendPkgInfo - Send info for install-pkgs hook /*{{{*/
280 // ---------------------------------------------------------------------
281 /* This is part of the helper script communication interface, it sends
282 very complete information down to the other end of the pipe.*/
283 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
285 return SendPkgsInfo(F
, 2);
287 bool pkgDPkgPM::SendPkgsInfo(FILE * const F
, unsigned int const &Version
)
289 // This version of APT supports only v3, so don't sent higher versions
291 fprintf(F
,"VERSION %u\n", Version
);
293 fprintf(F
,"VERSION 3\n");
295 /* Write out all of the configuration directives by walking the
296 configuration tree */
297 const Configuration::Item
*Top
= _config
->Tree(0);
300 if (Top
->Value
.empty() == false)
303 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
304 QuoteString(Top
->Value
,"\n").c_str());
313 while (Top
!= 0 && Top
->Next
== 0)
320 // Write out the package actions in order.
321 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
323 if(I
->Pkg
.end() == true)
326 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
328 fprintf(F
,"%s ",I
->Pkg
.Name());
330 // Current version which we are going to replace
331 pkgCache::VerIterator CurVer
= I
->Pkg
.CurrentVer();
332 if (CurVer
.end() == true && (I
->Op
== Item::Remove
|| I
->Op
== Item::Purge
))
333 CurVer
= FindNowVersion(I
->Pkg
);
335 if (CurVer
.end() == true)
340 fprintf(F
, "- - none ");
344 fprintf(F
, "%s ", CurVer
.VerStr());
346 fprintf(F
, "%s %s ", CurVer
.Arch(), CurVer
.MultiArchType());
349 // Show the compare operator between current and install version
350 if (S
.InstallVer
!= 0)
352 pkgCache::VerIterator
const InstVer
= S
.InstVerIter(Cache
);
354 if (CurVer
.end() == false)
355 Comp
= InstVer
.CompareVer(CurVer
);
362 fprintf(F
, "%s ", InstVer
.VerStr());
364 fprintf(F
, "%s %s ", InstVer
.Arch(), InstVer
.MultiArchType());
371 fprintf(F
, "> - - none ");
374 // Show the filename/operation
375 if (I
->Op
== Item::Install
)
378 if (I
->File
[0] != '/')
379 fprintf(F
,"**ERROR**\n");
381 fprintf(F
,"%s\n",I
->File
.c_str());
383 else if (I
->Op
== Item::Configure
)
384 fprintf(F
,"**CONFIGURE**\n");
385 else if (I
->Op
== Item::Remove
||
386 I
->Op
== Item::Purge
)
387 fprintf(F
,"**REMOVE**\n");
395 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
396 // ---------------------------------------------------------------------
397 /* This looks for a list of scripts to run from the configuration file
398 each one is run and is fed on standard input a list of all .deb files
399 that are due to be installed. */
400 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
404 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
405 if (Opts
== 0 || Opts
->Child
== 0)
409 sighandler_t old_sigpipe
= signal(SIGPIPE
, SIG_IGN
);
411 unsigned int Count
= 1;
412 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
414 if (Opts
->Value
.empty() == true)
417 if(_config
->FindB("Debug::RunScripts", false) == true)
418 std::clog
<< "Running external script with list of all .deb file: '"
419 << Opts
->Value
<< "'" << std::endl
;
421 // Determine the protocol version
422 string OptSec
= Opts
->Value
;
423 string::size_type Pos
;
424 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
425 Pos
= OptSec
.length();
426 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
428 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
429 unsigned int InfoFD
= _config
->FindI(OptSec
+ "::InfoFD", STDIN_FILENO
);
432 std::set
<int> KeepFDs
;
433 MergeKeepFdsFromConfiguration(KeepFDs
);
435 if (pipe(Pipes
) != 0) {
436 result
= _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
439 if (InfoFD
!= (unsigned)Pipes
[0])
440 SetCloseExec(Pipes
[0],true);
442 KeepFDs
.insert(Pipes
[0]);
445 SetCloseExec(Pipes
[1],true);
447 // Purified Fork for running the script
448 pid_t Process
= ExecFork(KeepFDs
);
452 dup2(Pipes
[0], InfoFD
);
453 SetCloseExec(STDOUT_FILENO
,false);
454 SetCloseExec(STDIN_FILENO
,false);
455 SetCloseExec(STDERR_FILENO
,false);
458 strprintf(hookfd
, "%d", InfoFD
);
459 setenv("APT_HOOK_INFO_FD", hookfd
.c_str(), 1);
461 dpkgChrootDirectory();
465 Args
[2] = Opts
->Value
.c_str();
467 execv(Args
[0],(char **)Args
);
471 FILE *F
= fdopen(Pipes
[1],"w");
473 result
= _error
->Errno("fdopen","Faild to open new FD");
477 // Feed it the filenames.
480 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
482 // Only deal with packages to be installed from .deb
483 if (I
->Op
!= Item::Install
)
487 if (I
->File
[0] != '/')
490 /* Feed the filename of each package that is pending install
492 fprintf(F
,"%s\n",I
->File
.c_str());
498 SendPkgsInfo(F
, Version
);
502 // Clean up the sub process
503 if (ExecWait(Process
,Opts
->Value
.c_str()) == false) {
504 result
= _error
->Error("Failure running script %s",Opts
->Value
.c_str());
508 signal(SIGPIPE
, old_sigpipe
);
513 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
514 // ---------------------------------------------------------------------
517 void pkgDPkgPM::DoStdin(int master
)
519 unsigned char input_buf
[256] = {0,};
520 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
522 FileFd::Write(master
, input_buf
, len
);
524 d
->stdin_is_dev_null
= true;
527 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
528 // ---------------------------------------------------------------------
530 * read the terminal pty and write log
532 void pkgDPkgPM::DoTerminalPty(int master
)
534 unsigned char term_buf
[1024] = {0,0, };
536 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
537 if(len
== -1 && errno
== EIO
)
539 // this happens when the child is about to exit, we
540 // give it time to actually exit, otherwise we run
541 // into a race so we sleep for half a second.
542 struct timespec sleepfor
= { 0, 500000000 };
543 nanosleep(&sleepfor
, NULL
);
548 FileFd::Write(1, term_buf
, len
);
550 fwrite(term_buf
, len
, sizeof(char), d
->term_out
);
553 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
554 // ---------------------------------------------------------------------
557 void pkgDPkgPM::ProcessDpkgStatusLine(char *line
)
559 bool const Debug
= _config
->FindB("Debug::pkgDPkgProgressReporting",false);
561 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
563 /* dpkg sends strings like this:
564 'status: <pkg>: <pkg qstate>'
565 'status: <pkg>:<arch>: <pkg qstate>'
567 'processing: {install,upgrade,configure,remove,purge,disappear,trigproc}: pkg'
568 'processing: {install,upgrade,configure,remove,purge,disappear,trigproc}: trigger'
571 // we need to split on ": " (note the appended space) as the ':' is
572 // part of the pkgname:arch information that dpkg sends
574 // A dpkg error message may contain additional ":" (like
575 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
576 // so we need to ensure to not split too much
577 std::vector
<std::string
> list
= StringSplit(line
, ": ", 4);
581 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
585 // build the (prefix, pkgname, action) tuple, position of this
586 // is different for "processing" or "status" messages
587 std::string prefix
= APT::String::Strip(list
[0]);
591 // "processing" has the form "processing: action: pkg or trigger"
592 // with action = ["install", "upgrade", "configure", "remove", "purge",
593 // "disappear", "trigproc"]
594 if (prefix
== "processing")
596 pkgname
= APT::String::Strip(list
[2]);
597 action
= APT::String::Strip(list
[1]);
598 // we don't care for the difference (as dpkg doesn't really either)
599 if (action
== "upgrade")
602 // "status" has the form: "status: pkg: state"
603 // with state in ["half-installed", "unpacked", "half-configured",
604 // "installed", "config-files", "not-installed"]
605 else if (prefix
== "status")
607 pkgname
= APT::String::Strip(list
[1]);
608 action
= APT::String::Strip(list
[2]);
611 std::clog
<< "unknown prefix '" << prefix
<< "'" << std::endl
;
616 /* handle the special cases first:
618 errors look like this:
619 '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
620 and conffile-prompt like this
621 'status:/etc/compiz.conf/compiz.conf : conffile-prompt: 'current-conffile' 'new-conffile' useredited distedited
623 if (prefix
== "status")
625 if(action
== "error")
627 d
->progress
->Error(pkgname
, PackagesDone
, PackagesTotal
,
630 WriteApportReport(pkgname
.c_str(), list
[3].c_str());
633 else if(action
== "conffile-prompt")
635 d
->progress
->ConffilePrompt(pkgname
, PackagesDone
, PackagesTotal
,
641 // at this point we know that we should have a valid pkgname, so build all
644 // dpkg does not always send "pkgname:arch" so we add it here if needed
645 if (pkgname
.find(":") == std::string::npos
)
647 // find the package in the group that is touched by dpkg
648 // if there are multiple pkgs dpkg would send us a full pkgname:arch
649 pkgCache::GrpIterator Grp
= Cache
.FindGrp(pkgname
);
650 if (Grp
.end() == false)
652 pkgCache::PkgIterator P
= Grp
.PackageList();
653 for (; P
.end() != true; P
= Grp
.NextPkg(P
))
655 if(Cache
[P
].Keep() == false || Cache
[P
].ReInstall() == true)
657 pkgname
= P
.FullName();
664 const char* const pkg
= pkgname
.c_str();
665 std::string short_pkgname
= StringSplit(pkgname
, ":")[0];
666 std::string arch
= "";
667 if (pkgname
.find(":") != string::npos
)
668 arch
= StringSplit(pkgname
, ":")[1];
669 std::string i18n_pkgname
= pkgname
;
670 if (arch
.size() != 0)
671 strprintf(i18n_pkgname
, "%s (%s)", short_pkgname
.c_str(), arch
.c_str());
673 // 'processing' from dpkg looks like
674 // 'processing: action: pkg'
675 if(prefix
== "processing")
677 const std::pair
<const char *, const char *> * const iter
=
678 std::find_if(PackageProcessingOpsBegin
,
679 PackageProcessingOpsEnd
,
680 MatchProcessingOp(action
.c_str()));
681 if(iter
== PackageProcessingOpsEnd
)
684 std::clog
<< "ignoring unknown action: " << action
<< std::endl
;
688 strprintf(msg
, _(iter
->second
), i18n_pkgname
.c_str());
689 d
->progress
->StatusChanged(pkgname
, PackagesDone
, PackagesTotal
, msg
);
691 // FIXME: this needs a muliarch testcase
692 // FIXME2: is "pkgname" here reliable with dpkg only sending us
694 if (action
== "disappear")
695 handleDisappearAction(pkgname
);
699 if (prefix
== "status")
701 vector
<struct DpkgState
> const &states
= PackageOps
[pkg
];
702 if(PackageOpsDone
[pkg
] < states
.size())
704 char const * const next_action
= states
[PackageOpsDone
[pkg
]].state
;
705 if (next_action
&& Debug
== true)
706 std::clog
<< "(parsed from dpkg) pkg: " << short_pkgname
707 << " action: " << action
<< " (expected: '" << next_action
<< "' "
708 << PackageOpsDone
[pkg
] << " of " << states
.size() << ")" << endl
;
710 // check if the package moved to the next dpkg state
711 if(next_action
&& (action
== next_action
))
713 // only read the translation if there is actually a next action
714 char const * const translation
= _(states
[PackageOpsDone
[pkg
]].str
);
716 // we moved from one dpkg state to a new one, report that
717 ++PackageOpsDone
[pkg
];
721 strprintf(msg
, translation
, i18n_pkgname
.c_str());
722 d
->progress
->StatusChanged(pkgname
, PackagesDone
, PackagesTotal
, msg
);
728 // DPkgPM::handleDisappearAction /*{{{*/
729 void pkgDPkgPM::handleDisappearAction(string
const &pkgname
)
731 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
732 if (unlikely(Pkg
.end() == true))
735 // record the package name for display and stuff later
736 disappearedPkgs
.insert(Pkg
.FullName(true));
738 // the disappeared package was auto-installed - nothing to do
739 if ((Cache
[Pkg
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
741 pkgCache::VerIterator PkgVer
= Cache
[Pkg
].InstVerIter(Cache
);
742 if (unlikely(PkgVer
.end() == true))
744 /* search in the list of dependencies for (Pre)Depends,
745 check if this dependency has a Replaces on our package
746 and if so transfer the manual installed flag to it */
747 for (pkgCache::DepIterator Dep
= PkgVer
.DependsList(); Dep
.end() != true; ++Dep
)
749 if (Dep
->Type
!= pkgCache::Dep::Depends
&&
750 Dep
->Type
!= pkgCache::Dep::PreDepends
)
752 pkgCache::PkgIterator Tar
= Dep
.TargetPkg();
753 if (unlikely(Tar
.end() == true))
755 // the package is already marked as manual
756 if ((Cache
[Tar
].Flags
& pkgCache::Flag::Auto
) != pkgCache::Flag::Auto
)
758 pkgCache::VerIterator TarVer
= Cache
[Tar
].InstVerIter(Cache
);
759 if (TarVer
.end() == true)
761 for (pkgCache::DepIterator Rep
= TarVer
.DependsList(); Rep
.end() != true; ++Rep
)
763 if (Rep
->Type
!= pkgCache::Dep::Replaces
)
765 if (Pkg
!= Rep
.TargetPkg())
767 // okay, they are strongly connected - transfer manual-bit
769 std::clog
<< "transfer manual-bit from disappeared »" << pkgname
<< "« to »" << Tar
.FullName() << "«" << std::endl
;
770 Cache
[Tar
].Flags
&= ~Flag::Auto
;
776 // DPkgPM::DoDpkgStatusFd /*{{{*/
777 // ---------------------------------------------------------------------
780 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
)
785 len
=read(statusfd
, &d
->dpkgbuf
[d
->dpkgbuf_pos
], sizeof(d
->dpkgbuf
)-d
->dpkgbuf_pos
);
786 d
->dpkgbuf_pos
+= len
;
790 // process line by line if we have a buffer
792 while((q
=(char*)memchr(p
, '\n', d
->dpkgbuf
+d
->dpkgbuf_pos
-p
)) != NULL
)
795 ProcessDpkgStatusLine(p
);
796 p
=q
+1; // continue with next line
799 // now move the unprocessed bits (after the final \n that is now a 0x0)
800 // to the start and update d->dpkgbuf_pos
801 p
= (char*)memrchr(d
->dpkgbuf
, 0, d
->dpkgbuf_pos
);
805 // we are interessted in the first char *after* 0x0
808 // move the unprocessed tail to the start and update pos
809 memmove(d
->dpkgbuf
, p
, p
-d
->dpkgbuf
);
810 d
->dpkgbuf_pos
= d
->dpkgbuf
+d
->dpkgbuf_pos
-p
;
813 // DPkgPM::WriteHistoryTag /*{{{*/
814 void pkgDPkgPM::WriteHistoryTag(string
const &tag
, string value
)
816 size_t const length
= value
.length();
819 // poor mans rstrip(", ")
820 if (value
[length
-2] == ',' && value
[length
-1] == ' ')
821 value
.erase(length
- 2, 2);
822 fprintf(d
->history_out
, "%s: %s\n", tag
.c_str(), value
.c_str());
824 // DPkgPM::OpenLog /*{{{*/
825 bool pkgDPkgPM::OpenLog()
827 string
const logdir
= _config
->FindDir("Dir::Log");
828 if(CreateAPTDirectoryIfNeeded(logdir
, logdir
) == false)
829 // FIXME: use a better string after freeze
830 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
834 time_t const t
= time(NULL
);
835 struct tm
const * const tmp
= localtime(&t
);
836 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
839 string
const logfile_name
= flCombine(logdir
,
840 _config
->Find("Dir::Log::Terminal"));
841 if (!logfile_name
.empty())
843 d
->term_out
= fopen(logfile_name
.c_str(),"a");
844 if (d
->term_out
== NULL
)
845 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name
.c_str());
846 setvbuf(d
->term_out
, NULL
, _IONBF
, 0);
847 SetCloseExec(fileno(d
->term_out
), true);
848 if (getuid() == 0) // if we aren't root, we can't chown a file, so don't try it
850 struct passwd
*pw
= getpwnam("root");
851 struct group
*gr
= getgrnam("adm");
852 if (pw
!= NULL
&& gr
!= NULL
&& chown(logfile_name
.c_str(), pw
->pw_uid
, gr
->gr_gid
) != 0)
853 _error
->WarningE("OpenLog", "chown to root:adm of file %s failed", logfile_name
.c_str());
855 if (chmod(logfile_name
.c_str(), 0640) != 0)
856 _error
->WarningE("OpenLog", "chmod 0640 of file %s failed", logfile_name
.c_str());
857 fprintf(d
->term_out
, "\nLog started: %s\n", timestr
);
860 // write your history
861 string
const history_name
= flCombine(logdir
,
862 _config
->Find("Dir::Log::History"));
863 if (!history_name
.empty())
865 d
->history_out
= fopen(history_name
.c_str(),"a");
866 if (d
->history_out
== NULL
)
867 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), history_name
.c_str());
868 SetCloseExec(fileno(d
->history_out
), true);
869 chmod(history_name
.c_str(), 0644);
870 fprintf(d
->history_out
, "\nStart-Date: %s\n", timestr
);
871 string remove
, purge
, install
, reinstall
, upgrade
, downgrade
;
872 for (pkgCache::PkgIterator I
= Cache
.PkgBegin(); I
.end() == false; ++I
)
874 enum { CANDIDATE
, CANDIDATE_AUTO
, CURRENT_CANDIDATE
, CURRENT
} infostring
;
876 #define HISTORYINFO(X, Y) { line = &X; infostring = Y; }
877 if (Cache
[I
].NewInstall() == true)
878 HISTORYINFO(install
, CANDIDATE_AUTO
)
879 else if (Cache
[I
].ReInstall() == true)
880 HISTORYINFO(reinstall
, CANDIDATE
)
881 else if (Cache
[I
].Upgrade() == true)
882 HISTORYINFO(upgrade
, CURRENT_CANDIDATE
)
883 else if (Cache
[I
].Downgrade() == true)
884 HISTORYINFO(downgrade
, CURRENT_CANDIDATE
)
885 else if (Cache
[I
].Delete() == true)
886 HISTORYINFO((Cache
[I
].Purge() ? purge
: remove
), CURRENT
)
890 line
->append(I
.FullName(false)).append(" (");
891 switch (infostring
) {
892 case CANDIDATE
: line
->append(Cache
[I
].CandVersion
); break;
894 line
->append(Cache
[I
].CandVersion
);
895 if ((Cache
[I
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
896 line
->append(", automatic");
898 case CURRENT_CANDIDATE
: line
->append(Cache
[I
].CurVersion
).append(", ").append(Cache
[I
].CandVersion
); break;
899 case CURRENT
: line
->append(Cache
[I
].CurVersion
); break;
903 if (_config
->Exists("Commandline::AsString") == true)
904 WriteHistoryTag("Commandline", _config
->Find("Commandline::AsString"));
905 WriteHistoryTag("Install", install
);
906 WriteHistoryTag("Reinstall", reinstall
);
907 WriteHistoryTag("Upgrade", upgrade
);
908 WriteHistoryTag("Downgrade",downgrade
);
909 WriteHistoryTag("Remove",remove
);
910 WriteHistoryTag("Purge",purge
);
911 fflush(d
->history_out
);
917 // DPkg::CloseLog /*{{{*/
918 bool pkgDPkgPM::CloseLog()
921 time_t t
= time(NULL
);
922 struct tm
*tmp
= localtime(&t
);
923 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
927 fprintf(d
->term_out
, "Log ended: ");
928 fprintf(d
->term_out
, "%s", timestr
);
929 fprintf(d
->term_out
, "\n");
936 if (disappearedPkgs
.empty() == false)
939 for (std::set
<std::string
>::const_iterator d
= disappearedPkgs
.begin();
940 d
!= disappearedPkgs
.end(); ++d
)
942 pkgCache::PkgIterator P
= Cache
.FindPkg(*d
);
943 disappear
.append(*d
);
945 disappear
.append(", ");
947 disappear
.append(" (").append(Cache
[P
].CurVersion
).append("), ");
949 WriteHistoryTag("Disappeared", disappear
);
951 if (d
->dpkg_error
.empty() == false)
952 fprintf(d
->history_out
, "Error: %s\n", d
->dpkg_error
.c_str());
953 fprintf(d
->history_out
, "End-Date: %s\n", timestr
);
954 fclose(d
->history_out
);
956 d
->history_out
= NULL
;
963 // This implements a racy version of pselect for those architectures
964 // that don't have a working implementation.
965 // FIXME: Probably can be removed on Lenny+1
966 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
967 fd_set
*exceptfds
, const struct timespec
*timeout
,
968 const sigset_t
*sigmask
)
974 tv
.tv_sec
= timeout
->tv_sec
;
975 tv
.tv_usec
= timeout
->tv_nsec
/1000;
977 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
978 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
979 sigprocmask(SIG_SETMASK
, &origmask
, 0);
984 // DPkgPM::BuildPackagesProgressMap /*{{{*/
985 void pkgDPkgPM::BuildPackagesProgressMap()
987 // map the dpkg states to the operations that are performed
988 // (this is sorted in the same way as Item::Ops)
989 static const struct DpkgState DpkgStatesOpMap
[][7] = {
992 {"half-installed", N_("Preparing %s")},
993 {"unpacked", N_("Unpacking %s") },
996 // Configure operation
998 {"unpacked",N_("Preparing to configure %s") },
999 {"half-configured", N_("Configuring %s") },
1000 { "installed", N_("Installed %s")},
1005 {"half-configured", N_("Preparing for removal of %s")},
1006 {"half-installed", N_("Removing %s")},
1007 {"config-files", N_("Removed %s")},
1012 {"config-files", N_("Preparing to completely remove %s")},
1013 {"not-installed", N_("Completely removed %s")},
1018 // init the PackageOps map, go over the list of packages that
1019 // that will be [installed|configured|removed|purged] and add
1020 // them to the PackageOps map (the dpkg states it goes through)
1021 // and the PackageOpsTranslations (human readable strings)
1022 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end(); ++I
)
1024 if((*I
).Pkg
.end() == true)
1027 string
const name
= (*I
).Pkg
.FullName();
1028 PackageOpsDone
[name
] = 0;
1029 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; ++i
)
1031 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
1037 #if (APT_PKG_MAJOR >= 4 && APT_PKG_MINOR < 13)
1038 bool pkgDPkgPM::Go(int StatusFd
)
1040 APT::Progress::PackageManager
*progress
= NULL
;
1042 progress
= APT::Progress::PackageManagerProgressFactory();
1044 progress
= new APT::Progress::PackageManagerProgressFd(StatusFd
);
1046 return GoNoABIBreak(progress
);
1050 void pkgDPkgPM::StartPtyMagic()
1052 if (_config
->FindB("Dpkg::Use-Pty", true) == false)
1054 d
->master
= d
->slave
= -1;
1058 // setup the pty and stuff
1061 // if tcgetattr for both stdin/stdout returns 0 (no error)
1062 // we do the pty magic
1063 _error
->PushToStack();
1064 if (tcgetattr(STDIN_FILENO
, &d
->tt
) == 0 &&
1065 tcgetattr(STDOUT_FILENO
, &d
->tt
) == 0)
1067 if (ioctl(STDOUT_FILENO
, TIOCGWINSZ
, (char *)&win
) < 0)
1069 _error
->Errno("ioctl", _("ioctl(TIOCGWINSZ) failed"));
1070 } else if (openpty(&d
->master
, &d
->slave
, NULL
, &d
->tt
, &win
) < 0)
1072 _error
->Errno("openpty", _("Can not write log (%s)"), _("Is /dev/pts mounted?"));
1073 d
->master
= d
->slave
= -1;
1078 rtt
.c_lflag
&= ~ECHO
;
1079 rtt
.c_lflag
|= ISIG
;
1080 // block SIGTTOU during tcsetattr to prevent a hang if
1081 // the process is a member of the background process group
1082 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
1083 sigemptyset(&d
->sigmask
);
1084 sigaddset(&d
->sigmask
, SIGTTOU
);
1085 sigprocmask(SIG_BLOCK
,&d
->sigmask
, &d
->original_sigmask
);
1086 tcsetattr(0, TCSAFLUSH
, &rtt
);
1087 sigprocmask(SIG_SETMASK
, &d
->original_sigmask
, 0);
1090 // complain only if stdout is either a terminal (but still failed) or is an invalid
1091 // descriptor otherwise we would complain about redirection to e.g. /dev/null as well.
1092 else if (isatty(STDOUT_FILENO
) == 1 || errno
== EBADF
)
1093 _error
->Errno("tcgetattr", _("Can not write log (%s)"), _("Is stdout a terminal?"));
1095 if (_error
->PendingError() == true)
1096 _error
->DumpErrors(std::cerr
);
1097 _error
->RevertToStack();
1100 void pkgDPkgPM::StopPtyMagic()
1106 tcsetattr(0, TCSAFLUSH
, &d
->tt
);
1111 // DPkgPM::Go - Run the sequence /*{{{*/
1112 // ---------------------------------------------------------------------
1113 /* This globs the operations and calls dpkg
1115 * If it is called with a progress object apt will report the install
1116 * progress to this object. It maps the dpkg states a package goes
1117 * through to human readable (and i10n-able)
1118 * names and calculates a percentage for each step.
1120 #if (APT_PKG_MAJOR >= 4 && APT_PKG_MINOR >= 13)
1121 bool pkgDPkgPM::Go(APT::Progress::PackageManager
*progress
)
1123 bool pkgDPkgPM::GoNoABIBreak(APT::Progress::PackageManager
*progress
)
1126 pkgPackageManager::SigINTStop
= false;
1127 d
->progress
= progress
;
1129 // Generate the base argument list for dpkg
1130 unsigned long StartSize
= 0;
1131 std::vector
<const char *> Args
;
1132 std::string DpkgExecutable
= getDpkgExecutable();
1133 Args
.push_back(DpkgExecutable
.c_str());
1134 StartSize
+= DpkgExecutable
.length();
1136 // Stick in any custom dpkg options
1137 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
1141 for (; Opts
!= 0; Opts
= Opts
->Next
)
1143 if (Opts
->Value
.empty() == true)
1145 Args
.push_back(Opts
->Value
.c_str());
1146 StartSize
+= Opts
->Value
.length();
1150 size_t const BaseArgs
= Args
.size();
1151 // we need to detect if we can qualify packages with the architecture or not
1152 Args
.push_back("--assert-multi-arch");
1153 Args
.push_back(NULL
);
1155 pid_t dpkgAssertMultiArch
= ExecFork();
1156 if (dpkgAssertMultiArch
== 0)
1158 dpkgChrootDirectory();
1159 // redirect everything to the ultimate sink as we only need the exit-status
1160 int const nullfd
= open("/dev/null", O_RDONLY
);
1161 dup2(nullfd
, STDIN_FILENO
);
1162 dup2(nullfd
, STDOUT_FILENO
);
1163 dup2(nullfd
, STDERR_FILENO
);
1164 execvp(Args
[0], (char**) &Args
[0]);
1165 _error
->WarningE("dpkgGo", "Can't detect if dpkg supports multi-arch!");
1172 unsigned int const MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
1173 unsigned int const MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
1174 bool const NoTriggers
= _config
->FindB("DPkg::NoTriggers", false);
1176 if (RunScripts("DPkg::Pre-Invoke") == false)
1179 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
1182 // support subpressing of triggers processing for special
1183 // cases like d-i that runs the triggers handling manually
1184 bool const SmartConf
= (_config
->Find("PackageManager::Configure", "all") != "all");
1185 bool const TriggersPending
= _config
->FindB("DPkg::TriggersPending", false);
1186 if (_config
->FindB("DPkg::ConfigurePending", SmartConf
) == true)
1187 List
.push_back(Item(Item::ConfigurePending
, PkgIterator()));
1190 BuildPackagesProgressMap();
1192 d
->stdin_is_dev_null
= false;
1197 bool dpkgMultiArch
= false;
1198 if (dpkgAssertMultiArch
> 0)
1201 while (waitpid(dpkgAssertMultiArch
, &Status
, 0) != dpkgAssertMultiArch
)
1205 _error
->WarningE("dpkgGo", _("Waited for %s but it wasn't there"), "dpkg --assert-multi-arch");
1208 if (WIFEXITED(Status
) == true && WEXITSTATUS(Status
) == 0)
1209 dpkgMultiArch
= true;
1212 // start pty magic before the loop
1215 // Tell the progress that its starting and fork dpkg
1216 d
->progress
->Start(d
->master
);
1218 // this loop is runs once per dpkg operation
1219 vector
<Item
>::const_iterator I
= List
.begin();
1220 while (I
!= List
.end())
1222 // Do all actions with the same Op in one run
1223 vector
<Item
>::const_iterator J
= I
;
1224 if (TriggersPending
== true)
1225 for (; J
!= List
.end(); ++J
)
1229 if (J
->Op
!= Item::TriggersPending
)
1231 vector
<Item
>::const_iterator T
= J
+ 1;
1232 if (T
!= List
.end() && T
->Op
== I
->Op
)
1237 for (; J
!= List
.end() && J
->Op
== I
->Op
; ++J
)
1240 // keep track of allocated strings for multiarch package names
1241 std::vector
<char *> Packages
;
1243 // start with the baseset of arguments
1244 unsigned long Size
= StartSize
;
1245 Args
.erase(Args
.begin() + BaseArgs
, Args
.end());
1247 // Now check if we are within the MaxArgs limit
1249 // this code below is problematic, because it may happen that
1250 // the argument list is split in a way that A depends on B
1251 // and they are in the same "--configure A B" run
1252 // - with the split they may now be configured in different
1253 // runs, using Immediate-Configure-All can help prevent this.
1254 if (J
- I
> (signed)MaxArgs
)
1257 unsigned long const size
= MaxArgs
+ 10;
1259 Packages
.reserve(size
);
1263 unsigned long const size
= (J
- I
) + 10;
1265 Packages
.reserve(size
);
1270 return _error
->Errno("pipe","Failed to create IPC pipe to dpkg");
1272 #define ADDARG(X) Args.push_back(X); Size += strlen(X)
1273 #define ADDARGC(X) Args.push_back(X); Size += sizeof(X) - 1
1275 ADDARGC("--status-fd");
1276 char status_fd_buf
[20];
1277 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
1278 ADDARG(status_fd_buf
);
1279 unsigned long const Op
= I
->Op
;
1284 ADDARGC("--force-depends");
1285 ADDARGC("--force-remove-essential");
1286 ADDARGC("--remove");
1290 ADDARGC("--force-depends");
1291 ADDARGC("--force-remove-essential");
1295 case Item::Configure
:
1296 ADDARGC("--configure");
1299 case Item::ConfigurePending
:
1300 ADDARGC("--configure");
1301 ADDARGC("--pending");
1304 case Item::TriggersPending
:
1305 ADDARGC("--triggers-only");
1306 ADDARGC("--pending");
1310 ADDARGC("--unpack");
1311 ADDARGC("--auto-deconfigure");
1315 if (NoTriggers
== true && I
->Op
!= Item::TriggersPending
&&
1316 I
->Op
!= Item::ConfigurePending
)
1318 ADDARGC("--no-triggers");
1322 // Write in the file or package names
1323 if (I
->Op
== Item::Install
)
1325 for (;I
!= J
&& Size
< MaxArgBytes
; ++I
)
1327 if (I
->File
[0] != '/')
1328 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
1329 Args
.push_back(I
->File
.c_str());
1330 Size
+= I
->File
.length();
1335 string
const nativeArch
= _config
->Find("APT::Architecture");
1336 unsigned long const oldSize
= I
->Op
== Item::Configure
? Size
: 0;
1337 for (;I
!= J
&& Size
< MaxArgBytes
; ++I
)
1339 if((*I
).Pkg
.end() == true)
1341 if (I
->Op
== Item::Configure
&& disappearedPkgs
.find(I
->Pkg
.FullName(true)) != disappearedPkgs
.end())
1343 // We keep this here to allow "smooth" transitions from e.g. multiarch dpkg/ubuntu to dpkg/debian
1344 if (dpkgMultiArch
== false && (I
->Pkg
.Arch() == nativeArch
||
1345 strcmp(I
->Pkg
.Arch(), "all") == 0 ||
1346 strcmp(I
->Pkg
.Arch(), "none") == 0))
1348 char const * const name
= I
->Pkg
.Name();
1353 pkgCache::VerIterator PkgVer
;
1354 std::string name
= I
->Pkg
.Name();
1355 if (Op
== Item::Remove
|| Op
== Item::Purge
)
1357 PkgVer
= I
->Pkg
.CurrentVer();
1358 if(PkgVer
.end() == true)
1359 PkgVer
= FindNowVersion(I
->Pkg
);
1362 PkgVer
= Cache
[I
->Pkg
].InstVerIter(Cache
);
1363 if (strcmp(I
->Pkg
.Arch(), "none") == 0)
1364 ; // never arch-qualify a package without an arch
1365 else if (PkgVer
.end() == false)
1366 name
.append(":").append(PkgVer
.Arch());
1368 _error
->Warning("Can not find PkgVer for '%s'", name
.c_str());
1369 char * const fullname
= strdup(name
.c_str());
1370 Packages
.push_back(fullname
);
1374 // skip configure action if all sheduled packages disappeared
1375 if (oldSize
== Size
)
1382 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
1384 for (std::vector
<const char *>::const_iterator a
= Args
.begin();
1385 a
!= Args
.end(); ++a
)
1390 Args
.push_back(NULL
);
1396 /* Mask off sig int/quit. We do this because dpkg also does when
1397 it forks scripts. What happens is that when you hit ctrl-c it sends
1398 it to all processes in the group. Since dpkg ignores the signal
1399 it doesn't die but we do! So we must also ignore it */
1400 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
1401 sighandler_t old_SIGINT
= signal(SIGINT
,SigINT
);
1403 // Check here for any SIGINT
1404 if (pkgPackageManager::SigINTStop
&& (Op
== Item::Remove
|| Op
== Item::Purge
|| Op
== Item::Install
))
1408 // ignore SIGHUP as well (debian #463030)
1409 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
1412 d
->progress
->StartDpkg();
1413 std::set
<int> KeepFDs
;
1414 KeepFDs
.insert(fd
[1]);
1415 MergeKeepFdsFromConfiguration(KeepFDs
);
1416 pid_t Child
= ExecFork(KeepFDs
);
1419 // This is the child
1420 if(d
->slave
>= 0 && d
->master
>= 0)
1423 int res
= ioctl(d
->slave
, TIOCSCTTY
, 0);
1425 std::cerr
<< "ioctl(TIOCSCTTY) failed for fd: "
1426 << d
->slave
<< std::endl
;
1435 close(fd
[0]); // close the read end of the pipe
1437 dpkgChrootDirectory();
1439 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
1442 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
1446 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
1449 // Discard everything in stdin before forking dpkg
1450 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
1453 while (read(STDIN_FILENO
,&dummy
,1) == 1);
1455 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
1459 /* No Job Control Stop Env is a magic dpkg var that prevents it
1460 from using sigstop */
1461 putenv((char *)"DPKG_NO_TSTP=yes");
1462 execvp(Args
[0], (char**) &Args
[0]);
1463 cerr
<< "Could not exec dpkg!" << endl
;
1468 if (_config
->FindB("DPkg::UseIoNice", false) == true)
1474 // we read from dpkg here
1475 int const _dpkgin
= fd
[0];
1476 close(fd
[1]); // close the write end of the pipe
1479 sigemptyset(&d
->sigmask
);
1480 sigprocmask(SIG_BLOCK
,&d
->sigmask
,&d
->original_sigmask
);
1482 /* free vectors (and therefore memory) as we don't need the included data anymore */
1483 for (std::vector
<char *>::const_iterator p
= Packages
.begin();
1484 p
!= Packages
.end(); ++p
)
1488 // the result of the waitpid call
1491 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
1493 // FIXME: move this to a function or something, looks ugly here
1494 // error handling, waitpid returned -1
1497 RunScripts("DPkg::Post-Invoke");
1499 // Restore sig int/quit
1500 signal(SIGQUIT
,old_SIGQUIT
);
1501 signal(SIGINT
,old_SIGINT
);
1503 signal(SIGHUP
,old_SIGHUP
);
1504 return _error
->Errno("waitpid","Couldn't wait for subprocess");
1507 // wait for input or output here
1509 if (d
->master
>= 0 && !d
->stdin_is_dev_null
)
1511 FD_SET(_dpkgin
, &rfds
);
1513 FD_SET(d
->master
, &rfds
);
1515 tv
.tv_nsec
= d
->progress
->GetPulseInterval();
1516 select_ret
= pselect(max(d
->master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
1517 &tv
, &d
->original_sigmask
);
1518 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
1519 select_ret
= racy_pselect(max(d
->master
, _dpkgin
)+1, &rfds
, NULL
,
1520 NULL
, &tv
, &d
->original_sigmask
);
1521 d
->progress
->Pulse();
1522 if (select_ret
== 0)
1524 else if (select_ret
< 0 && errno
== EINTR
)
1526 else if (select_ret
< 0)
1528 perror("select() returned error");
1532 if(d
->master
>= 0 && FD_ISSET(d
->master
, &rfds
))
1533 DoTerminalPty(d
->master
);
1534 if(d
->master
>= 0 && FD_ISSET(0, &rfds
))
1536 if(FD_ISSET(_dpkgin
, &rfds
))
1537 DoDpkgStatusFd(_dpkgin
);
1541 // Restore sig int/quit
1542 signal(SIGQUIT
,old_SIGQUIT
);
1543 signal(SIGINT
,old_SIGINT
);
1545 signal(SIGHUP
,old_SIGHUP
);
1546 // Check for an error code.
1547 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
1549 // if it was set to "keep-dpkg-runing" then we won't return
1550 // here but keep the loop going and just report it as a error
1552 bool const stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
1554 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
1555 strprintf(d
->dpkg_error
, "Sub-process %s received a segmentation fault.",Args
[0]);
1556 else if (WIFEXITED(Status
) != 0)
1557 strprintf(d
->dpkg_error
, "Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
1559 strprintf(d
->dpkg_error
, "Sub-process %s exited unexpectedly",Args
[0]);
1560 _error
->Error("%s", d
->dpkg_error
.c_str());
1566 // dpkg is done at this point
1567 d
->progress
->Stop();
1571 if (pkgPackageManager::SigINTStop
)
1572 _error
->Warning(_("Operation was interrupted before it could finish"));
1574 if (RunScripts("DPkg::Post-Invoke") == false)
1577 if (_config
->FindB("Debug::pkgDPkgPM",false) == false)
1579 std::string
const oldpkgcache
= _config
->FindFile("Dir::cache::pkgcache");
1580 if (oldpkgcache
.empty() == false && RealFileExists(oldpkgcache
) == true &&
1581 unlink(oldpkgcache
.c_str()) == 0)
1583 std::string
const srcpkgcache
= _config
->FindFile("Dir::cache::srcpkgcache");
1584 if (srcpkgcache
.empty() == false && RealFileExists(srcpkgcache
) == true)
1586 _error
->PushToStack();
1587 pkgCacheFile CacheFile
;
1588 CacheFile
.BuildCaches(NULL
, true);
1589 _error
->RevertToStack();
1594 Cache
.writeStateFile(NULL
);
1595 return d
->dpkg_error
.empty();
1598 void SigINT(int /*sig*/) {
1599 pkgPackageManager::SigINTStop
= true;
1602 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1603 // ---------------------------------------------------------------------
1605 void pkgDPkgPM::Reset()
1607 List
.erase(List
.begin(),List
.end());
1610 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1611 // ---------------------------------------------------------------------
1613 void pkgDPkgPM::WriteApportReport(const char *pkgpath
, const char *errormsg
)
1615 // If apport doesn't exist or isn't installed do nothing
1616 // This e.g. prevents messages in 'universes' without apport
1617 pkgCache::PkgIterator apportPkg
= Cache
.FindPkg("apport");
1618 if (apportPkg
.end() == true || apportPkg
->CurrentVer
== 0)
1621 string pkgname
, reportfile
, srcpkgname
, pkgver
, arch
;
1622 string::size_type pos
;
1625 if (_config
->FindB("Dpkg::ApportFailureReport", true) == false)
1627 std::clog
<< "configured to not write apport reports" << std::endl
;
1631 // only report the first errors
1632 if(pkgFailures
> _config
->FindI("APT::Apport::MaxReports", 3))
1634 std::clog
<< _("No apport report written because MaxReports is reached already") << std::endl
;
1638 // check if its not a follow up error
1639 const char *needle
= dgettext("dpkg", "dependency problems - leaving unconfigured");
1640 if(strstr(errormsg
, needle
) != NULL
) {
1641 std::clog
<< _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl
;
1645 // do not report disk-full failures
1646 if(strstr(errormsg
, strerror(ENOSPC
)) != NULL
) {
1647 std::clog
<< _("No apport report written because the error message indicates a disk full error") << std::endl
;
1651 // do not report out-of-memory failures
1652 if(strstr(errormsg
, strerror(ENOMEM
)) != NULL
||
1653 strstr(errormsg
, "failed to allocate memory") != NULL
) {
1654 std::clog
<< _("No apport report written because the error message indicates a out of memory error") << std::endl
;
1658 // do not report bugs regarding inaccessible local files
1659 if(strstr(errormsg
, strerror(ENOENT
)) != NULL
||
1660 strstr(errormsg
, "cannot access archive") != NULL
) {
1661 std::clog
<< _("No apport report written because the error message indicates an issue on the local system") << std::endl
;
1665 // do not report errors encountered when decompressing packages
1666 if(strstr(errormsg
, "--fsys-tarfile returned error exit status 2") != NULL
) {
1667 std::clog
<< _("No apport report written because the error message indicates an issue on the local system") << std::endl
;
1671 // do not report dpkg I/O errors, this is a format string, so we compare
1672 // the prefix and the suffix of the error with the dpkg error message
1673 vector
<string
> io_errors
;
1674 io_errors
.push_back(string("failed to read"));
1675 io_errors
.push_back(string("failed to write"));
1676 io_errors
.push_back(string("failed to seek"));
1677 io_errors
.push_back(string("unexpected end of file or stream"));
1679 for (vector
<string
>::iterator I
= io_errors
.begin(); I
!= io_errors
.end(); ++I
)
1681 vector
<string
> list
= VectorizeString(dgettext("dpkg", (*I
).c_str()), '%');
1682 if (list
.size() > 1) {
1683 // we need to split %s, VectorizeString only allows char so we need
1684 // to kill the "s" manually
1685 if (list
[1].size() > 1) {
1686 list
[1].erase(0, 1);
1687 if(strstr(errormsg
, list
[0].c_str()) &&
1688 strstr(errormsg
, list
[1].c_str())) {
1689 std::clog
<< _("No apport report written because the error message indicates a dpkg I/O error") << std::endl
;
1696 // get the pkgname and reportfile
1697 pkgname
= flNotDir(pkgpath
);
1698 pos
= pkgname
.find('_');
1699 if(pos
!= string::npos
)
1700 pkgname
= pkgname
.substr(0, pos
);
1702 // find the package versin and source package name
1703 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
1704 if (Pkg
.end() == true)
1706 pkgCache::VerIterator Ver
= Cache
.GetCandidateVer(Pkg
);
1707 if (Ver
.end() == true)
1709 pkgver
= Ver
.VerStr() == NULL
? "unknown" : Ver
.VerStr();
1710 pkgRecords
Recs(Cache
);
1711 pkgRecords::Parser
&Parse
= Recs
.Lookup(Ver
.FileList());
1712 srcpkgname
= Parse
.SourcePkg();
1713 if(srcpkgname
.empty())
1714 srcpkgname
= pkgname
;
1716 // if the file exists already, we check:
1717 // - if it was reported already (touched by apport).
1718 // If not, we do nothing, otherwise
1719 // we overwrite it. This is the same behaviour as apport
1720 // - if we have a report with the same pkgversion already
1722 reportfile
= flCombine("/var/crash",pkgname
+".0.crash");
1723 if(FileExists(reportfile
))
1728 // check atime/mtime
1729 stat(reportfile
.c_str(), &buf
);
1730 if(buf
.st_mtime
> buf
.st_atime
)
1733 // check if the existing report is the same version
1734 report
= fopen(reportfile
.c_str(),"r");
1735 while(fgets(strbuf
, sizeof(strbuf
), report
) != NULL
)
1737 if(strstr(strbuf
,"Package:") == strbuf
)
1739 char pkgname
[255], version
[255];
1740 if(sscanf(strbuf
, "Package: %254s %254s", pkgname
, version
) == 2)
1741 if(strcmp(pkgver
.c_str(), version
) == 0)
1751 // now write the report
1752 arch
= _config
->Find("APT::Architecture");
1753 report
= fopen(reportfile
.c_str(),"w");
1756 if(_config
->FindB("DPkgPM::InitialReportOnly",false) == true)
1757 chmod(reportfile
.c_str(), 0);
1759 chmod(reportfile
.c_str(), 0600);
1760 fprintf(report
, "ProblemType: Package\n");
1761 fprintf(report
, "Architecture: %s\n", arch
.c_str());
1762 time_t now
= time(NULL
);
1763 fprintf(report
, "Date: %s" , ctime(&now
));
1764 fprintf(report
, "Package: %s %s\n", pkgname
.c_str(), pkgver
.c_str());
1765 fprintf(report
, "SourcePackage: %s\n", srcpkgname
.c_str());
1766 fprintf(report
, "ErrorMessage:\n %s\n", errormsg
);
1768 // ensure that the log is flushed
1770 fflush(d
->term_out
);
1772 // attach terminal log it if we have it
1773 string logfile_name
= _config
->FindFile("Dir::Log::Terminal");
1774 if (!logfile_name
.empty())
1778 fprintf(report
, "DpkgTerminalLog:\n");
1779 log
= fopen(logfile_name
.c_str(),"r");
1783 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1784 fprintf(report
, " %s", buf
);
1785 fprintf(report
, " \n");
1790 // attach history log it if we have it
1791 string histfile_name
= _config
->FindFile("Dir::Log::History");
1792 if (!histfile_name
.empty())
1794 fprintf(report
, "DpkgHistoryLog:\n");
1795 FILE* log
= fopen(histfile_name
.c_str(),"r");
1799 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1800 fprintf(report
, " %s", buf
);
1806 const char *ops_str
[] = {"Install", "Configure","Remove","Purge"};
1807 fprintf(report
, "AptOrdering:\n");
1808 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
1809 if ((*I
).Pkg
!= NULL
)
1810 fprintf(report
, " %s: %s\n", (*I
).Pkg
.Name(), ops_str
[(*I
).Op
]);
1812 fprintf(report
, " %s: %s\n", "NULL", ops_str
[(*I
).Op
]);
1814 // attach dmesg log (to learn about segfaults)
1815 if (FileExists("/bin/dmesg"))
1817 fprintf(report
, "Dmesg:\n");
1818 FILE *log
= popen("/bin/dmesg","r");
1822 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1823 fprintf(report
, " %s", buf
);
1828 // attach df -l log (to learn about filesystem status)
1829 if (FileExists("/bin/df"))
1832 fprintf(report
, "Df:\n");
1833 FILE *log
= popen("/bin/df -l","r");
1837 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1838 fprintf(report
, " %s", buf
);