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/dpkgpm.h>
14 #include <apt-pkg/error.h>
15 #include <apt-pkg/configuration.h>
16 #include <apt-pkg/depcache.h>
17 #include <apt-pkg/pkgrecords.h>
18 #include <apt-pkg/strutl.h>
19 #include <apt-pkg/fileutl.h>
20 #include <apt-pkg/cachefile.h>
21 #include <apt-pkg/packagemanager.h>
22 #include <apt-pkg/install-progress.h>
27 #include <sys/select.h>
29 #include <sys/types.h>
45 #include <sys/ioctl.h>
53 class pkgDPkgPMPrivate
56 pkgDPkgPMPrivate() : stdin_is_dev_null(false), dpkgbuf_pos(0),
57 term_out(NULL
), history_out(NULL
),
58 progress(NULL
), master(-1), slave(-1)
65 bool stdin_is_dev_null
;
66 // the buffer we use for the dpkg status-fd reading
72 APT::Progress::PackageManager
*progress
;
81 sigset_t original_sigmask
;
87 // Maps the dpkg "processing" info to human readable names. Entry 0
88 // of each array is the key, entry 1 is the value.
89 const std::pair
<const char *, const char *> PackageProcessingOps
[] = {
90 std::make_pair("install", N_("Installing %s")),
91 std::make_pair("configure", N_("Configuring %s")),
92 std::make_pair("remove", N_("Removing %s")),
93 std::make_pair("purge", N_("Completely removing %s")),
94 std::make_pair("disappear", N_("Noting disappearance of %s")),
95 std::make_pair("trigproc", N_("Running post-installation trigger %s"))
98 const std::pair
<const char *, const char *> * const PackageProcessingOpsBegin
= PackageProcessingOps
;
99 const std::pair
<const char *, const char *> * const PackageProcessingOpsEnd
= PackageProcessingOps
+ sizeof(PackageProcessingOps
) / sizeof(PackageProcessingOps
[0]);
101 // Predicate to test whether an entry in the PackageProcessingOps
102 // array matches a string.
103 class MatchProcessingOp
108 MatchProcessingOp(const char *the_target
)
113 bool operator()(const std::pair
<const char *, const char *> &pair
) const
115 return strcmp(pair
.first
, target
) == 0;
120 /* helper function to ionice the given PID
122 there is no C header for ionice yet - just the syscall interface
123 so we use the binary from util-linux
128 if (!FileExists("/usr/bin/ionice"))
130 pid_t Process
= ExecFork();
134 snprintf(buf
, sizeof(buf
), "-p%d", PID
);
136 Args
[0] = "/usr/bin/ionice";
140 execv(Args
[0], (char **)Args
);
142 return ExecWait(Process
, "ionice");
145 static std::string
getDpkgExecutable()
147 string Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
148 string
const dpkgChrootDir
= _config
->FindDir("DPkg::Chroot-Directory", "/");
149 size_t dpkgChrootLen
= dpkgChrootDir
.length();
150 if (dpkgChrootDir
!= "/" && Tmp
.find(dpkgChrootDir
) == 0)
152 if (dpkgChrootDir
[dpkgChrootLen
- 1] == '/')
154 Tmp
= Tmp
.substr(dpkgChrootLen
);
159 // dpkgChrootDirectory - chrooting for dpkg if needed /*{{{*/
160 static void dpkgChrootDirectory()
162 std::string
const chrootDir
= _config
->FindDir("DPkg::Chroot-Directory");
163 if (chrootDir
== "/")
165 std::cerr
<< "Chrooting into " << chrootDir
<< std::endl
;
166 if (chroot(chrootDir
.c_str()) != 0)
174 // FindNowVersion - Helper to find a Version in "now" state /*{{{*/
175 // ---------------------------------------------------------------------
176 /* This is helpful when a package is no longer installed but has residual
180 pkgCache::VerIterator
FindNowVersion(const pkgCache::PkgIterator
&Pkg
)
182 pkgCache::VerIterator Ver
;
183 for (Ver
= Pkg
.VersionList(); Ver
.end() == false; ++Ver
)
185 pkgCache::VerFileIterator Vf
= Ver
.FileList();
186 pkgCache::PkgFileIterator F
= Vf
.File();
187 for (F
= Vf
.File(); F
.end() == false; ++F
)
189 if (F
&& F
.Archive())
191 if (strcmp(F
.Archive(), "now"))
200 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
201 // ---------------------------------------------------------------------
203 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
204 : pkgPackageManager(Cache
), pkgFailures(0), PackagesDone(0), PackagesTotal(0)
206 d
= new pkgDPkgPMPrivate();
209 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
210 // ---------------------------------------------------------------------
212 pkgDPkgPM::~pkgDPkgPM()
217 // DPkgPM::Install - Install a package /*{{{*/
218 // ---------------------------------------------------------------------
219 /* Add an install operation to the sequence list */
220 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
222 if (File
.empty() == true || Pkg
.end() == true)
223 return _error
->Error("Internal Error, No file name for %s",Pkg
.FullName().c_str());
225 // If the filename string begins with DPkg::Chroot-Directory, return the
226 // substr that is within the chroot so dpkg can access it.
227 string
const chrootdir
= _config
->FindDir("DPkg::Chroot-Directory","/");
228 if (chrootdir
!= "/" && File
.find(chrootdir
) == 0)
230 size_t len
= chrootdir
.length();
231 if (chrootdir
.at(len
- 1) == '/')
233 List
.push_back(Item(Item::Install
,Pkg
,File
.substr(len
)));
236 List
.push_back(Item(Item::Install
,Pkg
,File
));
241 // DPkgPM::Configure - Configure a package /*{{{*/
242 // ---------------------------------------------------------------------
243 /* Add a configure operation to the sequence list */
244 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
246 if (Pkg
.end() == true)
249 List
.push_back(Item(Item::Configure
, Pkg
));
251 // Use triggers for config calls if we configure "smart"
252 // as otherwise Pre-Depends will not be satisfied, see #526774
253 if (_config
->FindB("DPkg::TriggersPending", false) == true)
254 List
.push_back(Item(Item::TriggersPending
, PkgIterator()));
259 // DPkgPM::Remove - Remove a package /*{{{*/
260 // ---------------------------------------------------------------------
261 /* Add a remove operation to the sequence list */
262 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
264 if (Pkg
.end() == true)
268 List
.push_back(Item(Item::Purge
,Pkg
));
270 List
.push_back(Item(Item::Remove
,Pkg
));
274 // DPkgPM::SendPkgInfo - Send info for install-pkgs hook /*{{{*/
275 // ---------------------------------------------------------------------
276 /* This is part of the helper script communication interface, it sends
277 very complete information down to the other end of the pipe.*/
278 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
280 return SendPkgsInfo(F
, 2);
282 bool pkgDPkgPM::SendPkgsInfo(FILE * const F
, unsigned int const &Version
)
284 // This version of APT supports only v3, so don't sent higher versions
286 fprintf(F
,"VERSION %u\n", Version
);
288 fprintf(F
,"VERSION 3\n");
290 /* Write out all of the configuration directives by walking the
291 configuration tree */
292 const Configuration::Item
*Top
= _config
->Tree(0);
295 if (Top
->Value
.empty() == false)
298 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
299 QuoteString(Top
->Value
,"\n").c_str());
308 while (Top
!= 0 && Top
->Next
== 0)
315 // Write out the package actions in order.
316 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
318 if(I
->Pkg
.end() == true)
321 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
323 fprintf(F
,"%s ",I
->Pkg
.Name());
325 // Current version which we are going to replace
326 pkgCache::VerIterator CurVer
= I
->Pkg
.CurrentVer();
327 if (CurVer
.end() == true && (I
->Op
== Item::Remove
|| I
->Op
== Item::Purge
))
328 CurVer
= FindNowVersion(I
->Pkg
);
330 if (CurVer
.end() == true)
335 fprintf(F
, "- - none ");
339 fprintf(F
, "%s ", CurVer
.VerStr());
341 fprintf(F
, "%s %s ", CurVer
.Arch(), CurVer
.MultiArchType());
344 // Show the compare operator between current and install version
345 if (S
.InstallVer
!= 0)
347 pkgCache::VerIterator
const InstVer
= S
.InstVerIter(Cache
);
349 if (CurVer
.end() == false)
350 Comp
= InstVer
.CompareVer(CurVer
);
357 fprintf(F
, "%s ", InstVer
.VerStr());
359 fprintf(F
, "%s %s ", InstVer
.Arch(), InstVer
.MultiArchType());
366 fprintf(F
, "> - - none ");
369 // Show the filename/operation
370 if (I
->Op
== Item::Install
)
373 if (I
->File
[0] != '/')
374 fprintf(F
,"**ERROR**\n");
376 fprintf(F
,"%s\n",I
->File
.c_str());
378 else if (I
->Op
== Item::Configure
)
379 fprintf(F
,"**CONFIGURE**\n");
380 else if (I
->Op
== Item::Remove
||
381 I
->Op
== Item::Purge
)
382 fprintf(F
,"**REMOVE**\n");
390 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
391 // ---------------------------------------------------------------------
392 /* This looks for a list of scripts to run from the configuration file
393 each one is run and is fed on standard input a list of all .deb files
394 that are due to be installed. */
395 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
397 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
398 if (Opts
== 0 || Opts
->Child
== 0)
402 unsigned int Count
= 1;
403 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
405 if (Opts
->Value
.empty() == true)
408 // Determine the protocol version
409 string OptSec
= Opts
->Value
;
410 string::size_type Pos
;
411 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
412 Pos
= OptSec
.length();
413 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
415 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
416 unsigned int InfoFD
= _config
->FindI(OptSec
+ "::InfoFD", STDIN_FILENO
);
419 std::set
<int> KeepFDs
;
420 MergeKeepFdsFromConfiguration(KeepFDs
);
422 if (pipe(Pipes
) != 0)
423 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
424 if (InfoFD
!= (unsigned)Pipes
[0])
425 SetCloseExec(Pipes
[0],true);
427 KeepFDs
.insert(Pipes
[0]);
430 SetCloseExec(Pipes
[1],true);
432 // Purified Fork for running the script
433 pid_t Process
= ExecFork(KeepFDs
);
437 dup2(Pipes
[0], InfoFD
);
438 SetCloseExec(STDOUT_FILENO
,false);
439 SetCloseExec(STDIN_FILENO
,false);
440 SetCloseExec(STDERR_FILENO
,false);
443 strprintf(hookfd
, "%d", InfoFD
);
444 setenv("APT_HOOK_INFO_FD", hookfd
.c_str(), 1);
446 dpkgChrootDirectory();
450 Args
[2] = Opts
->Value
.c_str();
452 execv(Args
[0],(char **)Args
);
456 FILE *F
= fdopen(Pipes
[1],"w");
458 return _error
->Errno("fdopen","Faild to open new FD");
460 // Feed it the filenames.
463 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
465 // Only deal with packages to be installed from .deb
466 if (I
->Op
!= Item::Install
)
470 if (I
->File
[0] != '/')
473 /* Feed the filename of each package that is pending install
475 fprintf(F
,"%s\n",I
->File
.c_str());
481 SendPkgsInfo(F
, Version
);
485 // Clean up the sub process
486 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
487 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
493 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
494 // ---------------------------------------------------------------------
497 void pkgDPkgPM::DoStdin(int master
)
499 unsigned char input_buf
[256] = {0,};
500 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
502 FileFd::Write(master
, input_buf
, len
);
504 d
->stdin_is_dev_null
= true;
507 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
508 // ---------------------------------------------------------------------
510 * read the terminal pty and write log
512 void pkgDPkgPM::DoTerminalPty(int master
)
514 unsigned char term_buf
[1024] = {0,0, };
516 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
517 if(len
== -1 && errno
== EIO
)
519 // this happens when the child is about to exit, we
520 // give it time to actually exit, otherwise we run
521 // into a race so we sleep for half a second.
522 struct timespec sleepfor
= { 0, 500000000 };
523 nanosleep(&sleepfor
, NULL
);
528 FileFd::Write(1, term_buf
, len
);
530 fwrite(term_buf
, len
, sizeof(char), d
->term_out
);
533 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
534 // ---------------------------------------------------------------------
537 void pkgDPkgPM::ProcessDpkgStatusLine(char *line
)
539 bool const Debug
= _config
->FindB("Debug::pkgDPkgProgressReporting",false);
541 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
543 /* dpkg sends strings like this:
544 'status: <pkg>: <pkg qstate>'
545 'status: <pkg>:<arch>: <pkg qstate>'
547 'processing: {install,configure,remove,purge,disappear,trigproc}: pkg'
548 'processing: {install,configure,remove,purge,disappear,trigproc}: trigger'
551 // we need to split on ": " (note the appended space) as the ':' is
552 // part of the pkgname:arch information that dpkg sends
554 // A dpkg error message may contain additional ":" (like
555 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
556 // so we need to ensure to not split too much
557 std::vector
<std::string
> list
= StringSplit(line
, ": ", 4);
561 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
565 // build the (prefix, pkgname, action) tuple, position of this
566 // is different for "processing" or "status" messages
567 std::string prefix
= APT::String::Strip(list
[0]);
570 ostringstream status
;
572 // "processing" has the form "processing: action: pkg or trigger"
573 // with action = ["install", "configure", "remove", "purge", "disappear",
575 if (prefix
== "processing")
577 pkgname
= APT::String::Strip(list
[2]);
578 action
= APT::String::Strip(list
[1]);
580 // "status" has the form: "status: pkg: state"
581 // with state in ["half-installed", "unpacked", "half-configured",
582 // "installed", "config-files", "not-installed"]
583 else if (prefix
== "status")
585 pkgname
= APT::String::Strip(list
[1]);
586 action
= APT::String::Strip(list
[2]);
589 std::clog
<< "unknown prefix '" << prefix
<< "'" << std::endl
;
594 /* handle the special cases first:
596 errors look like this:
597 '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
598 and conffile-prompt like this
599 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
601 if (prefix
== "status")
603 if(action
== "error")
605 d
->progress
->Error(list
[1], PackagesDone
, PackagesTotal
,
608 WriteApportReport(list
[1].c_str(), list
[3].c_str());
611 else if(action
== "conffile")
613 d
->progress
->ConffilePrompt(list
[1], PackagesDone
, PackagesTotal
,
619 // at this point we know that we should have a valid pkgname, so build all
622 // dpkg does not send always send "pkgname:arch" so we add it here
624 if (pkgname
.find(":") == std::string::npos
)
626 // find the package in the group that is in a touched by dpkg
627 // if there are multiple dpkg will send us a full pkgname:arch
628 pkgCache::GrpIterator Grp
= Cache
.FindGrp(pkgname
);
629 if (Grp
.end() == false)
631 pkgCache::PkgIterator P
= Grp
.PackageList();
632 for (; P
.end() != true; P
= Grp
.NextPkg(P
))
634 if(Cache
[P
].Mode
!= pkgDepCache::ModeKeep
)
636 pkgname
= P
.FullName();
643 const char* const pkg
= pkgname
.c_str();
644 std::string short_pkgname
= StringSplit(pkgname
, ":")[0];
645 std::string arch
= "";
646 if (pkgname
.find(":") != string::npos
)
647 arch
= StringSplit(pkgname
, ":")[1];
648 std::string i18n_pkgname
= pkgname
;
649 if (arch
.size() != 0)
650 strprintf(i18n_pkgname
, "%s (%s)", short_pkgname
.c_str(), arch
.c_str());
652 // 'processing' from dpkg looks like
653 // 'processing: action: pkg'
654 if(prefix
== "processing")
656 const std::pair
<const char *, const char *> * const iter
=
657 std::find_if(PackageProcessingOpsBegin
,
658 PackageProcessingOpsEnd
,
659 MatchProcessingOp(action
.c_str()));
660 if(iter
== PackageProcessingOpsEnd
)
663 std::clog
<< "ignoring unknown action: " << action
<< std::endl
;
667 strprintf(msg
, _(iter
->second
), i18n_pkgname
.c_str());
668 d
->progress
->StatusChanged(pkgname
, PackagesDone
, PackagesTotal
, msg
);
670 // FIXME: this needs a muliarch testcase
671 // FIXME2: is "pkgname" here reliable with dpkg only sending us
673 if (action
== "disappear")
674 handleDisappearAction(pkgname
);
678 if (prefix
== "status")
680 vector
<struct DpkgState
> const &states
= PackageOps
[pkg
];
681 const char *next_action
= NULL
;
682 if(PackageOpsDone
[pkg
] < states
.size())
683 next_action
= states
[PackageOpsDone
[pkg
]].state
;
684 // check if the package moved to the next dpkg state
685 if(next_action
&& (action
== next_action
))
687 // only read the translation if there is actually a next
689 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
692 // we moved from one dpkg state to a new one, report that
693 PackageOpsDone
[pkg
]++;
696 strprintf(msg
, translation
, i18n_pkgname
.c_str());
697 d
->progress
->StatusChanged(pkgname
, PackagesDone
, PackagesTotal
, msg
);
701 std::clog
<< "(parsed from dpkg) pkg: " << short_pkgname
702 << " action: " << action
<< endl
;
706 // DPkgPM::handleDisappearAction /*{{{*/
707 void pkgDPkgPM::handleDisappearAction(string
const &pkgname
)
709 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
710 if (unlikely(Pkg
.end() == true))
713 // record the package name for display and stuff later
714 disappearedPkgs
.insert(Pkg
.FullName(true));
716 // the disappeared package was auto-installed - nothing to do
717 if ((Cache
[Pkg
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
719 pkgCache::VerIterator PkgVer
= Cache
[Pkg
].InstVerIter(Cache
);
720 if (unlikely(PkgVer
.end() == true))
722 /* search in the list of dependencies for (Pre)Depends,
723 check if this dependency has a Replaces on our package
724 and if so transfer the manual installed flag to it */
725 for (pkgCache::DepIterator Dep
= PkgVer
.DependsList(); Dep
.end() != true; ++Dep
)
727 if (Dep
->Type
!= pkgCache::Dep::Depends
&&
728 Dep
->Type
!= pkgCache::Dep::PreDepends
)
730 pkgCache::PkgIterator Tar
= Dep
.TargetPkg();
731 if (unlikely(Tar
.end() == true))
733 // the package is already marked as manual
734 if ((Cache
[Tar
].Flags
& pkgCache::Flag::Auto
) != pkgCache::Flag::Auto
)
736 pkgCache::VerIterator TarVer
= Cache
[Tar
].InstVerIter(Cache
);
737 if (TarVer
.end() == true)
739 for (pkgCache::DepIterator Rep
= TarVer
.DependsList(); Rep
.end() != true; ++Rep
)
741 if (Rep
->Type
!= pkgCache::Dep::Replaces
)
743 if (Pkg
!= Rep
.TargetPkg())
745 // okay, they are strongly connected - transfer manual-bit
747 std::clog
<< "transfer manual-bit from disappeared »" << pkgname
<< "« to »" << Tar
.FullName() << "«" << std::endl
;
748 Cache
[Tar
].Flags
&= ~Flag::Auto
;
754 // DPkgPM::DoDpkgStatusFd /*{{{*/
755 // ---------------------------------------------------------------------
758 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
)
763 len
=read(statusfd
, &d
->dpkgbuf
[d
->dpkgbuf_pos
], sizeof(d
->dpkgbuf
)-d
->dpkgbuf_pos
);
764 d
->dpkgbuf_pos
+= len
;
768 // process line by line if we have a buffer
770 while((q
=(char*)memchr(p
, '\n', d
->dpkgbuf
+d
->dpkgbuf_pos
-p
)) != NULL
)
773 ProcessDpkgStatusLine(p
);
774 p
=q
+1; // continue with next line
777 // now move the unprocessed bits (after the final \n that is now a 0x0)
778 // to the start and update d->dpkgbuf_pos
779 p
= (char*)memrchr(d
->dpkgbuf
, 0, d
->dpkgbuf_pos
);
783 // we are interessted in the first char *after* 0x0
786 // move the unprocessed tail to the start and update pos
787 memmove(d
->dpkgbuf
, p
, p
-d
->dpkgbuf
);
788 d
->dpkgbuf_pos
= d
->dpkgbuf
+d
->dpkgbuf_pos
-p
;
791 // DPkgPM::WriteHistoryTag /*{{{*/
792 void pkgDPkgPM::WriteHistoryTag(string
const &tag
, string value
)
794 size_t const length
= value
.length();
797 // poor mans rstrip(", ")
798 if (value
[length
-2] == ',' && value
[length
-1] == ' ')
799 value
.erase(length
- 2, 2);
800 fprintf(d
->history_out
, "%s: %s\n", tag
.c_str(), value
.c_str());
802 // DPkgPM::OpenLog /*{{{*/
803 bool pkgDPkgPM::OpenLog()
805 string
const logdir
= _config
->FindDir("Dir::Log");
806 if(CreateAPTDirectoryIfNeeded(logdir
, logdir
) == false)
807 // FIXME: use a better string after freeze
808 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
812 time_t const t
= time(NULL
);
813 struct tm
const * const tmp
= localtime(&t
);
814 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
817 string
const logfile_name
= flCombine(logdir
,
818 _config
->Find("Dir::Log::Terminal"));
819 if (!logfile_name
.empty())
821 d
->term_out
= fopen(logfile_name
.c_str(),"a");
822 if (d
->term_out
== NULL
)
823 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name
.c_str());
824 setvbuf(d
->term_out
, NULL
, _IONBF
, 0);
825 SetCloseExec(fileno(d
->term_out
), true);
826 if (getuid() == 0) // if we aren't root, we can't chown a file, so don't try it
828 struct passwd
*pw
= getpwnam("root");
829 struct group
*gr
= getgrnam("adm");
830 if (pw
!= NULL
&& gr
!= NULL
&& chown(logfile_name
.c_str(), pw
->pw_uid
, gr
->gr_gid
) != 0)
831 _error
->WarningE("OpenLog", "chown to root:adm of file %s failed", logfile_name
.c_str());
833 if (chmod(logfile_name
.c_str(), 0640) != 0)
834 _error
->WarningE("OpenLog", "chmod 0640 of file %s failed", logfile_name
.c_str());
835 fprintf(d
->term_out
, "\nLog started: %s\n", timestr
);
838 // write your history
839 string
const history_name
= flCombine(logdir
,
840 _config
->Find("Dir::Log::History"));
841 if (!history_name
.empty())
843 d
->history_out
= fopen(history_name
.c_str(),"a");
844 if (d
->history_out
== NULL
)
845 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), history_name
.c_str());
846 SetCloseExec(fileno(d
->history_out
), true);
847 chmod(history_name
.c_str(), 0644);
848 fprintf(d
->history_out
, "\nStart-Date: %s\n", timestr
);
849 string remove
, purge
, install
, reinstall
, upgrade
, downgrade
;
850 for (pkgCache::PkgIterator I
= Cache
.PkgBegin(); I
.end() == false; ++I
)
852 enum { CANDIDATE
, CANDIDATE_AUTO
, CURRENT_CANDIDATE
, CURRENT
} infostring
;
854 #define HISTORYINFO(X, Y) { line = &X; infostring = Y; }
855 if (Cache
[I
].NewInstall() == true)
856 HISTORYINFO(install
, CANDIDATE_AUTO
)
857 else if (Cache
[I
].ReInstall() == true)
858 HISTORYINFO(reinstall
, CANDIDATE
)
859 else if (Cache
[I
].Upgrade() == true)
860 HISTORYINFO(upgrade
, CURRENT_CANDIDATE
)
861 else if (Cache
[I
].Downgrade() == true)
862 HISTORYINFO(downgrade
, CURRENT_CANDIDATE
)
863 else if (Cache
[I
].Delete() == true)
864 HISTORYINFO((Cache
[I
].Purge() ? purge
: remove
), CURRENT
)
868 line
->append(I
.FullName(false)).append(" (");
869 switch (infostring
) {
870 case CANDIDATE
: line
->append(Cache
[I
].CandVersion
); break;
872 line
->append(Cache
[I
].CandVersion
);
873 if ((Cache
[I
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
874 line
->append(", automatic");
876 case CURRENT_CANDIDATE
: line
->append(Cache
[I
].CurVersion
).append(", ").append(Cache
[I
].CandVersion
); break;
877 case CURRENT
: line
->append(Cache
[I
].CurVersion
); break;
881 if (_config
->Exists("Commandline::AsString") == true)
882 WriteHistoryTag("Commandline", _config
->Find("Commandline::AsString"));
883 WriteHistoryTag("Install", install
);
884 WriteHistoryTag("Reinstall", reinstall
);
885 WriteHistoryTag("Upgrade", upgrade
);
886 WriteHistoryTag("Downgrade",downgrade
);
887 WriteHistoryTag("Remove",remove
);
888 WriteHistoryTag("Purge",purge
);
889 fflush(d
->history_out
);
895 // DPkg::CloseLog /*{{{*/
896 bool pkgDPkgPM::CloseLog()
899 time_t t
= time(NULL
);
900 struct tm
*tmp
= localtime(&t
);
901 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
905 fprintf(d
->term_out
, "Log ended: ");
906 fprintf(d
->term_out
, "%s", timestr
);
907 fprintf(d
->term_out
, "\n");
914 if (disappearedPkgs
.empty() == false)
917 for (std::set
<std::string
>::const_iterator d
= disappearedPkgs
.begin();
918 d
!= disappearedPkgs
.end(); ++d
)
920 pkgCache::PkgIterator P
= Cache
.FindPkg(*d
);
921 disappear
.append(*d
);
923 disappear
.append(", ");
925 disappear
.append(" (").append(Cache
[P
].CurVersion
).append("), ");
927 WriteHistoryTag("Disappeared", disappear
);
929 if (d
->dpkg_error
.empty() == false)
930 fprintf(d
->history_out
, "Error: %s\n", d
->dpkg_error
.c_str());
931 fprintf(d
->history_out
, "End-Date: %s\n", timestr
);
932 fclose(d
->history_out
);
934 d
->history_out
= NULL
;
941 // This implements a racy version of pselect for those architectures
942 // that don't have a working implementation.
943 // FIXME: Probably can be removed on Lenny+1
944 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
945 fd_set
*exceptfds
, const struct timespec
*timeout
,
946 const sigset_t
*sigmask
)
952 tv
.tv_sec
= timeout
->tv_sec
;
953 tv
.tv_usec
= timeout
->tv_nsec
/1000;
955 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
956 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
957 sigprocmask(SIG_SETMASK
, &origmask
, 0);
962 // DPkgPM::BuildPackagesProgressMap /*{{{*/
963 void pkgDPkgPM::BuildPackagesProgressMap()
965 // map the dpkg states to the operations that are performed
966 // (this is sorted in the same way as Item::Ops)
967 static const struct DpkgState DpkgStatesOpMap
[][7] = {
970 {"half-installed", N_("Preparing %s")},
971 {"unpacked", N_("Unpacking %s") },
974 // Configure operation
976 {"unpacked",N_("Preparing to configure %s") },
977 {"half-configured", N_("Configuring %s") },
978 { "installed", N_("Installed %s")},
983 {"half-configured", N_("Preparing for removal of %s")},
984 {"half-installed", N_("Removing %s")},
985 {"config-files", N_("Removed %s")},
990 {"config-files", N_("Preparing to completely remove %s")},
991 {"not-installed", N_("Completely removed %s")},
996 // init the PackageOps map, go over the list of packages that
997 // that will be [installed|configured|removed|purged] and add
998 // them to the PackageOps map (the dpkg states it goes through)
999 // and the PackageOpsTranslations (human readable strings)
1000 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end(); ++I
)
1002 if((*I
).Pkg
.end() == true)
1005 string
const name
= (*I
).Pkg
.FullName();
1006 PackageOpsDone
[name
] = 0;
1007 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; ++i
)
1009 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
1015 #if (APT_PKG_MAJOR >= 4 && APT_PKG_MINOR < 13)
1016 bool pkgDPkgPM::Go(int StatusFd
)
1018 APT::Progress::PackageManager
*progress
= NULL
;
1020 progress
= APT::Progress::PackageManagerProgressFactory();
1022 progress
= new APT::Progress::PackageManagerProgressFd(StatusFd
);
1024 return GoNoABIBreak(progress
);
1028 void pkgDPkgPM::StartPtyMagic()
1030 // setup the pty and stuff
1033 // if tcgetattr does not return zero there was a error
1034 // and we do not do any pty magic
1035 _error
->PushToStack();
1036 if (tcgetattr(STDOUT_FILENO
, &d
->tt
) == 0)
1038 ioctl(1, TIOCGWINSZ
, (char *)&win
);
1039 if (openpty(&d
->master
, &d
->slave
, NULL
, &d
->tt
, &win
) < 0)
1041 _error
->Errno("openpty", _("Can not write log (%s)"), _("Is /dev/pts mounted?"));
1042 d
->master
= d
->slave
= -1;
1047 rtt
.c_lflag
&= ~ECHO
;
1048 rtt
.c_lflag
|= ISIG
;
1049 // block SIGTTOU during tcsetattr to prevent a hang if
1050 // the process is a member of the background process group
1051 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
1052 sigemptyset(&d
->sigmask
);
1053 sigaddset(&d
->sigmask
, SIGTTOU
);
1054 sigprocmask(SIG_BLOCK
,&d
->sigmask
, &d
->original_sigmask
);
1055 tcsetattr(0, TCSAFLUSH
, &rtt
);
1056 sigprocmask(SIG_SETMASK
, &d
->original_sigmask
, 0);
1059 // complain only if stdout is either a terminal (but still failed) or is an invalid
1060 // descriptor otherwise we would complain about redirection to e.g. /dev/null as well.
1061 else if (isatty(STDOUT_FILENO
) == 1 || errno
== EBADF
)
1062 _error
->Errno("tcgetattr", _("Can not write log (%s)"), _("Is stdout a terminal?"));
1064 if (_error
->PendingError() == true)
1065 _error
->DumpErrors(std::cerr
);
1066 _error
->RevertToStack();
1069 void pkgDPkgPM::StopPtyMagic()
1075 tcsetattr(0, TCSAFLUSH
, &d
->tt
);
1080 // DPkgPM::Go - Run the sequence /*{{{*/
1081 // ---------------------------------------------------------------------
1082 /* This globs the operations and calls dpkg
1084 * If it is called with a progress object apt will report the install
1085 * progress to this object. It maps the dpkg states a package goes
1086 * through to human readable (and i10n-able)
1087 * names and calculates a percentage for each step.
1089 #if (APT_PKG_MAJOR >= 4 && APT_PKG_MINOR >= 13)
1090 bool pkgDPkgPM::Go(APT::Progress::PackageManager
*progress
)
1092 bool pkgDPkgPM::GoNoABIBreak(APT::Progress::PackageManager
*progress
)
1095 pkgPackageManager::SigINTStop
= false;
1096 d
->progress
= progress
;
1098 // Generate the base argument list for dpkg
1099 unsigned long StartSize
= 0;
1100 std::vector
<const char *> Args
;
1101 std::string DpkgExecutable
= getDpkgExecutable();
1102 Args
.push_back(DpkgExecutable
.c_str());
1103 StartSize
+= DpkgExecutable
.length();
1105 // Stick in any custom dpkg options
1106 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
1110 for (; Opts
!= 0; Opts
= Opts
->Next
)
1112 if (Opts
->Value
.empty() == true)
1114 Args
.push_back(Opts
->Value
.c_str());
1115 StartSize
+= Opts
->Value
.length();
1119 size_t const BaseArgs
= Args
.size();
1120 // we need to detect if we can qualify packages with the architecture or not
1121 Args
.push_back("--assert-multi-arch");
1122 Args
.push_back(NULL
);
1124 pid_t dpkgAssertMultiArch
= ExecFork();
1125 if (dpkgAssertMultiArch
== 0)
1127 dpkgChrootDirectory();
1128 // redirect everything to the ultimate sink as we only need the exit-status
1129 int const nullfd
= open("/dev/null", O_RDONLY
);
1130 dup2(nullfd
, STDIN_FILENO
);
1131 dup2(nullfd
, STDOUT_FILENO
);
1132 dup2(nullfd
, STDERR_FILENO
);
1133 execvp(Args
[0], (char**) &Args
[0]);
1134 _error
->WarningE("dpkgGo", "Can't detect if dpkg supports multi-arch!");
1141 unsigned int const MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
1142 unsigned int const MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
1143 bool const NoTriggers
= _config
->FindB("DPkg::NoTriggers", false);
1145 if (RunScripts("DPkg::Pre-Invoke") == false)
1148 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
1151 // support subpressing of triggers processing for special
1152 // cases like d-i that runs the triggers handling manually
1153 bool const SmartConf
= (_config
->Find("PackageManager::Configure", "all") != "all");
1154 bool const TriggersPending
= _config
->FindB("DPkg::TriggersPending", false);
1155 if (_config
->FindB("DPkg::ConfigurePending", SmartConf
) == true)
1156 List
.push_back(Item(Item::ConfigurePending
, PkgIterator()));
1159 BuildPackagesProgressMap();
1161 d
->stdin_is_dev_null
= false;
1166 bool dpkgMultiArch
= false;
1167 if (dpkgAssertMultiArch
> 0)
1170 while (waitpid(dpkgAssertMultiArch
, &Status
, 0) != dpkgAssertMultiArch
)
1174 _error
->WarningE("dpkgGo", _("Waited for %s but it wasn't there"), "dpkg --assert-multi-arch");
1177 if (WIFEXITED(Status
) == true && WEXITSTATUS(Status
) == 0)
1178 dpkgMultiArch
= true;
1181 // start pty magic before the loop
1184 // Tell the progress that its starting and fork dpkg
1185 d
->progress
->Start();
1187 // this loop is runs once per dpkg operation
1188 vector
<Item
>::const_iterator I
= List
.begin();
1189 while (I
!= List
.end())
1191 // Do all actions with the same Op in one run
1192 vector
<Item
>::const_iterator J
= I
;
1193 if (TriggersPending
== true)
1194 for (; J
!= List
.end(); ++J
)
1198 if (J
->Op
!= Item::TriggersPending
)
1200 vector
<Item
>::const_iterator T
= J
+ 1;
1201 if (T
!= List
.end() && T
->Op
== I
->Op
)
1206 for (; J
!= List
.end() && J
->Op
== I
->Op
; ++J
)
1209 // keep track of allocated strings for multiarch package names
1210 std::vector
<char *> Packages
;
1212 // start with the baseset of arguments
1213 unsigned long Size
= StartSize
;
1214 Args
.erase(Args
.begin() + BaseArgs
, Args
.end());
1216 // Now check if we are within the MaxArgs limit
1218 // this code below is problematic, because it may happen that
1219 // the argument list is split in a way that A depends on B
1220 // and they are in the same "--configure A B" run
1221 // - with the split they may now be configured in different
1222 // runs, using Immediate-Configure-All can help prevent this.
1223 if (J
- I
> (signed)MaxArgs
)
1226 unsigned long const size
= MaxArgs
+ 10;
1228 Packages
.reserve(size
);
1232 unsigned long const size
= (J
- I
) + 10;
1234 Packages
.reserve(size
);
1239 return _error
->Errno("pipe","Failed to create IPC pipe to dpkg");
1241 #define ADDARG(X) Args.push_back(X); Size += strlen(X)
1242 #define ADDARGC(X) Args.push_back(X); Size += sizeof(X) - 1
1244 ADDARGC("--status-fd");
1245 char status_fd_buf
[20];
1246 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
1247 ADDARG(status_fd_buf
);
1248 unsigned long const Op
= I
->Op
;
1253 ADDARGC("--force-depends");
1254 ADDARGC("--force-remove-essential");
1255 ADDARGC("--remove");
1259 ADDARGC("--force-depends");
1260 ADDARGC("--force-remove-essential");
1264 case Item::Configure
:
1265 ADDARGC("--configure");
1268 case Item::ConfigurePending
:
1269 ADDARGC("--configure");
1270 ADDARGC("--pending");
1273 case Item::TriggersPending
:
1274 ADDARGC("--triggers-only");
1275 ADDARGC("--pending");
1279 ADDARGC("--unpack");
1280 ADDARGC("--auto-deconfigure");
1284 if (NoTriggers
== true && I
->Op
!= Item::TriggersPending
&&
1285 I
->Op
!= Item::ConfigurePending
)
1287 ADDARGC("--no-triggers");
1291 // Write in the file or package names
1292 if (I
->Op
== Item::Install
)
1294 for (;I
!= J
&& Size
< MaxArgBytes
; ++I
)
1296 if (I
->File
[0] != '/')
1297 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
1298 Args
.push_back(I
->File
.c_str());
1299 Size
+= I
->File
.length();
1304 string
const nativeArch
= _config
->Find("APT::Architecture");
1305 unsigned long const oldSize
= I
->Op
== Item::Configure
? Size
: 0;
1306 for (;I
!= J
&& Size
< MaxArgBytes
; ++I
)
1308 if((*I
).Pkg
.end() == true)
1310 if (I
->Op
== Item::Configure
&& disappearedPkgs
.find(I
->Pkg
.FullName(true)) != disappearedPkgs
.end())
1312 // We keep this here to allow "smooth" transitions from e.g. multiarch dpkg/ubuntu to dpkg/debian
1313 if (dpkgMultiArch
== false && (I
->Pkg
.Arch() == nativeArch
||
1314 strcmp(I
->Pkg
.Arch(), "all") == 0 ||
1315 strcmp(I
->Pkg
.Arch(), "none") == 0))
1317 char const * const name
= I
->Pkg
.Name();
1322 pkgCache::VerIterator PkgVer
;
1323 std::string name
= I
->Pkg
.Name();
1324 if (Op
== Item::Remove
|| Op
== Item::Purge
)
1326 PkgVer
= I
->Pkg
.CurrentVer();
1327 if(PkgVer
.end() == true)
1328 PkgVer
= FindNowVersion(I
->Pkg
);
1331 PkgVer
= Cache
[I
->Pkg
].InstVerIter(Cache
);
1332 if (strcmp(I
->Pkg
.Arch(), "none") == 0)
1333 ; // never arch-qualify a package without an arch
1334 else if (PkgVer
.end() == false)
1335 name
.append(":").append(PkgVer
.Arch());
1337 _error
->Warning("Can not find PkgVer for '%s'", name
.c_str());
1338 char * const fullname
= strdup(name
.c_str());
1339 Packages
.push_back(fullname
);
1343 // skip configure action if all sheduled packages disappeared
1344 if (oldSize
== Size
)
1351 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
1353 for (std::vector
<const char *>::const_iterator a
= Args
.begin();
1354 a
!= Args
.end(); ++a
)
1359 Args
.push_back(NULL
);
1365 /* Mask off sig int/quit. We do this because dpkg also does when
1366 it forks scripts. What happens is that when you hit ctrl-c it sends
1367 it to all processes in the group. Since dpkg ignores the signal
1368 it doesn't die but we do! So we must also ignore it */
1369 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
1370 sighandler_t old_SIGINT
= signal(SIGINT
,SigINT
);
1372 // Check here for any SIGINT
1373 if (pkgPackageManager::SigINTStop
&& (Op
== Item::Remove
|| Op
== Item::Purge
|| Op
== Item::Install
))
1377 // ignore SIGHUP as well (debian #463030)
1378 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
1381 d
->progress
->StartDpkg();
1382 std::set
<int> KeepFDs
;
1383 KeepFDs
.insert(fd
[1]);
1384 MergeKeepFdsFromConfiguration(KeepFDs
);
1385 pid_t Child
= ExecFork(KeepFDs
);
1388 // This is the child
1389 if(d
->slave
>= 0 && d
->master
>= 0)
1392 ioctl(d
->slave
, TIOCSCTTY
, 0);
1399 close(fd
[0]); // close the read end of the pipe
1401 dpkgChrootDirectory();
1403 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
1406 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
1409 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
1412 // Discard everything in stdin before forking dpkg
1413 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
1416 while (read(STDIN_FILENO
,&dummy
,1) == 1);
1418 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
1422 /* No Job Control Stop Env is a magic dpkg var that prevents it
1423 from using sigstop */
1424 putenv((char *)"DPKG_NO_TSTP=yes");
1425 execvp(Args
[0], (char**) &Args
[0]);
1426 cerr
<< "Could not exec dpkg!" << endl
;
1431 if (_config
->FindB("DPkg::UseIoNice", false) == true)
1437 // we read from dpkg here
1438 int const _dpkgin
= fd
[0];
1439 close(fd
[1]); // close the write end of the pipe
1442 sigemptyset(&d
->sigmask
);
1443 sigprocmask(SIG_BLOCK
,&d
->sigmask
,&d
->original_sigmask
);
1445 /* free vectors (and therefore memory) as we don't need the included data anymore */
1446 for (std::vector
<char *>::const_iterator p
= Packages
.begin();
1447 p
!= Packages
.end(); ++p
)
1451 // the result of the waitpid call
1454 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
1456 // FIXME: move this to a function or something, looks ugly here
1457 // error handling, waitpid returned -1
1460 RunScripts("DPkg::Post-Invoke");
1462 // Restore sig int/quit
1463 signal(SIGQUIT
,old_SIGQUIT
);
1464 signal(SIGINT
,old_SIGINT
);
1466 signal(SIGHUP
,old_SIGHUP
);
1467 return _error
->Errno("waitpid","Couldn't wait for subprocess");
1470 // wait for input or output here
1472 if (d
->master
>= 0 && !d
->stdin_is_dev_null
)
1474 FD_SET(_dpkgin
, &rfds
);
1476 FD_SET(d
->master
, &rfds
);
1478 tv
.tv_nsec
= d
->progress
->GetPulseInterval();
1479 select_ret
= pselect(max(d
->master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
1480 &tv
, &d
->original_sigmask
);
1481 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
1482 select_ret
= racy_pselect(max(d
->master
, _dpkgin
)+1, &rfds
, NULL
,
1483 NULL
, &tv
, &d
->original_sigmask
);
1484 d
->progress
->Pulse();
1485 if (select_ret
== 0)
1487 else if (select_ret
< 0 && errno
== EINTR
)
1489 else if (select_ret
< 0)
1491 perror("select() returned error");
1495 if(d
->master
>= 0 && FD_ISSET(d
->master
, &rfds
))
1496 DoTerminalPty(d
->master
);
1497 if(d
->master
>= 0 && FD_ISSET(0, &rfds
))
1499 if(FD_ISSET(_dpkgin
, &rfds
))
1500 DoDpkgStatusFd(_dpkgin
);
1504 // Restore sig int/quit
1505 signal(SIGQUIT
,old_SIGQUIT
);
1506 signal(SIGINT
,old_SIGINT
);
1508 signal(SIGHUP
,old_SIGHUP
);
1509 // Check for an error code.
1510 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
1512 // if it was set to "keep-dpkg-runing" then we won't return
1513 // here but keep the loop going and just report it as a error
1515 bool const stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
1518 RunScripts("DPkg::Post-Invoke");
1520 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
1521 strprintf(d
->dpkg_error
, "Sub-process %s received a segmentation fault.",Args
[0]);
1522 else if (WIFEXITED(Status
) != 0)
1523 strprintf(d
->dpkg_error
, "Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
1525 strprintf(d
->dpkg_error
, "Sub-process %s exited unexpectedly",Args
[0]);
1527 if(d
->dpkg_error
.size() > 0)
1528 _error
->Error("%s", d
->dpkg_error
.c_str());
1534 d
->progress
->Stop();
1539 // dpkg is done at this point
1540 d
->progress
->Stop();
1544 if (pkgPackageManager::SigINTStop
)
1545 _error
->Warning(_("Operation was interrupted before it could finish"));
1547 if (RunScripts("DPkg::Post-Invoke") == false)
1550 if (_config
->FindB("Debug::pkgDPkgPM",false) == false)
1552 std::string
const oldpkgcache
= _config
->FindFile("Dir::cache::pkgcache");
1553 if (oldpkgcache
.empty() == false && RealFileExists(oldpkgcache
) == true &&
1554 unlink(oldpkgcache
.c_str()) == 0)
1556 std::string
const srcpkgcache
= _config
->FindFile("Dir::cache::srcpkgcache");
1557 if (srcpkgcache
.empty() == false && RealFileExists(srcpkgcache
) == true)
1559 _error
->PushToStack();
1560 pkgCacheFile CacheFile
;
1561 CacheFile
.BuildCaches(NULL
, true);
1562 _error
->RevertToStack();
1567 Cache
.writeStateFile(NULL
);
1571 void SigINT(int sig
) {
1572 pkgPackageManager::SigINTStop
= true;
1575 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1576 // ---------------------------------------------------------------------
1578 void pkgDPkgPM::Reset()
1580 List
.erase(List
.begin(),List
.end());
1583 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1584 // ---------------------------------------------------------------------
1586 void pkgDPkgPM::WriteApportReport(const char *pkgpath
, const char *errormsg
)
1588 // If apport doesn't exist or isn't installed do nothing
1589 // This e.g. prevents messages in 'universes' without apport
1590 pkgCache::PkgIterator apportPkg
= Cache
.FindPkg("apport");
1591 if (apportPkg
.end() == true || apportPkg
->CurrentVer
== 0)
1594 string pkgname
, reportfile
, srcpkgname
, pkgver
, arch
;
1595 string::size_type pos
;
1598 if (_config
->FindB("Dpkg::ApportFailureReport", false) == false)
1600 std::clog
<< "configured to not write apport reports" << std::endl
;
1604 // only report the first errors
1605 if(pkgFailures
> _config
->FindI("APT::Apport::MaxReports", 3))
1607 std::clog
<< _("No apport report written because MaxReports is reached already") << std::endl
;
1611 // check if its not a follow up error
1612 const char *needle
= dgettext("dpkg", "dependency problems - leaving unconfigured");
1613 if(strstr(errormsg
, needle
) != NULL
) {
1614 std::clog
<< _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl
;
1618 // do not report disk-full failures
1619 if(strstr(errormsg
, strerror(ENOSPC
)) != NULL
) {
1620 std::clog
<< _("No apport report written because the error message indicates a disk full error") << std::endl
;
1624 // do not report out-of-memory failures
1625 if(strstr(errormsg
, strerror(ENOMEM
)) != NULL
) {
1626 std::clog
<< _("No apport report written because the error message indicates a out of memory error") << std::endl
;
1630 // do not report dpkg I/O errors
1631 // XXX - this message is localized, but this only matches the English version. This is better than nothing.
1632 if(strstr(errormsg
, "short read in buffer_copy (")) {
1633 std::clog
<< _("No apport report written because the error message indicates a dpkg I/O error") << std::endl
;
1637 // get the pkgname and reportfile
1638 pkgname
= flNotDir(pkgpath
);
1639 pos
= pkgname
.find('_');
1640 if(pos
!= string::npos
)
1641 pkgname
= pkgname
.substr(0, pos
);
1643 // find the package versin and source package name
1644 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
1645 if (Pkg
.end() == true)
1647 pkgCache::VerIterator Ver
= Cache
.GetCandidateVer(Pkg
);
1648 if (Ver
.end() == true)
1650 pkgver
= Ver
.VerStr() == NULL
? "unknown" : Ver
.VerStr();
1651 pkgRecords
Recs(Cache
);
1652 pkgRecords::Parser
&Parse
= Recs
.Lookup(Ver
.FileList());
1653 srcpkgname
= Parse
.SourcePkg();
1654 if(srcpkgname
.empty())
1655 srcpkgname
= pkgname
;
1657 // if the file exists already, we check:
1658 // - if it was reported already (touched by apport).
1659 // If not, we do nothing, otherwise
1660 // we overwrite it. This is the same behaviour as apport
1661 // - if we have a report with the same pkgversion already
1663 reportfile
= flCombine("/var/crash",pkgname
+".0.crash");
1664 if(FileExists(reportfile
))
1669 // check atime/mtime
1670 stat(reportfile
.c_str(), &buf
);
1671 if(buf
.st_mtime
> buf
.st_atime
)
1674 // check if the existing report is the same version
1675 report
= fopen(reportfile
.c_str(),"r");
1676 while(fgets(strbuf
, sizeof(strbuf
), report
) != NULL
)
1678 if(strstr(strbuf
,"Package:") == strbuf
)
1680 char pkgname
[255], version
[255];
1681 if(sscanf(strbuf
, "Package: %254s %254s", pkgname
, version
) == 2)
1682 if(strcmp(pkgver
.c_str(), version
) == 0)
1692 // now write the report
1693 arch
= _config
->Find("APT::Architecture");
1694 report
= fopen(reportfile
.c_str(),"w");
1697 if(_config
->FindB("DPkgPM::InitialReportOnly",false) == true)
1698 chmod(reportfile
.c_str(), 0);
1700 chmod(reportfile
.c_str(), 0600);
1701 fprintf(report
, "ProblemType: Package\n");
1702 fprintf(report
, "Architecture: %s\n", arch
.c_str());
1703 time_t now
= time(NULL
);
1704 fprintf(report
, "Date: %s" , ctime(&now
));
1705 fprintf(report
, "Package: %s %s\n", pkgname
.c_str(), pkgver
.c_str());
1706 fprintf(report
, "SourcePackage: %s\n", srcpkgname
.c_str());
1707 fprintf(report
, "ErrorMessage:\n %s\n", errormsg
);
1709 // ensure that the log is flushed
1711 fflush(d
->term_out
);
1713 // attach terminal log it if we have it
1714 string logfile_name
= _config
->FindFile("Dir::Log::Terminal");
1715 if (!logfile_name
.empty())
1719 fprintf(report
, "DpkgTerminalLog:\n");
1720 log
= fopen(logfile_name
.c_str(),"r");
1724 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1725 fprintf(report
, " %s", buf
);
1731 const char *ops_str
[] = {"Install", "Configure","Remove","Purge"};
1732 fprintf(report
, "AptOrdering:\n");
1733 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
1734 if ((*I
).Pkg
!= NULL
)
1735 fprintf(report
, " %s: %s\n", (*I
).Pkg
.Name(), ops_str
[(*I
).Op
]);
1737 fprintf(report
, " %s: %s\n", "NULL", ops_str
[(*I
).Op
]);
1739 // attach dmesg log (to learn about segfaults)
1740 if (FileExists("/bin/dmesg"))
1742 fprintf(report
, "Dmesg:\n");
1743 FILE *log
= popen("/bin/dmesg","r");
1747 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1748 fprintf(report
, " %s", buf
);
1753 // attach df -l log (to learn about filesystem status)
1754 if (FileExists("/bin/df"))
1757 fprintf(report
, "Df:\n");
1758 FILE *log
= popen("/bin/df -l","r");
1762 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1763 fprintf(report
, " %s", buf
);