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
),
65 bool stdin_is_dev_null
;
66 // the buffer we use for the dpkg status-fd reading
72 APT::Progress::PackageManager
*progress
;
77 // Maps the dpkg "processing" info to human readable names. Entry 0
78 // of each array is the key, entry 1 is the value.
79 const std::pair
<const char *, const char *> PackageProcessingOps
[] = {
80 std::make_pair("install", N_("Installing %s")),
81 std::make_pair("configure", N_("Configuring %s")),
82 std::make_pair("remove", N_("Removing %s")),
83 std::make_pair("purge", N_("Completely removing %s")),
84 std::make_pair("disappear", N_("Noting disappearance of %s")),
85 std::make_pair("trigproc", N_("Running post-installation trigger %s"))
88 const std::pair
<const char *, const char *> * const PackageProcessingOpsBegin
= PackageProcessingOps
;
89 const std::pair
<const char *, const char *> * const PackageProcessingOpsEnd
= PackageProcessingOps
+ sizeof(PackageProcessingOps
) / sizeof(PackageProcessingOps
[0]);
91 // Predicate to test whether an entry in the PackageProcessingOps
92 // array matches a string.
93 class MatchProcessingOp
98 MatchProcessingOp(const char *the_target
)
103 bool operator()(const std::pair
<const char *, const char *> &pair
) const
105 return strcmp(pair
.first
, target
) == 0;
110 /* helper function to ionice the given PID
112 there is no C header for ionice yet - just the syscall interface
113 so we use the binary from util-linux
118 if (!FileExists("/usr/bin/ionice"))
120 pid_t Process
= ExecFork();
124 snprintf(buf
, sizeof(buf
), "-p%d", PID
);
126 Args
[0] = "/usr/bin/ionice";
130 execv(Args
[0], (char **)Args
);
132 return ExecWait(Process
, "ionice");
135 // dpkgChrootDirectory - chrooting for dpkg if needed /*{{{*/
136 static void dpkgChrootDirectory()
138 std::string
const chrootDir
= _config
->FindDir("DPkg::Chroot-Directory");
139 if (chrootDir
== "/")
141 std::cerr
<< "Chrooting into " << chrootDir
<< std::endl
;
142 if (chroot(chrootDir
.c_str()) != 0)
150 // FindNowVersion - Helper to find a Version in "now" state /*{{{*/
151 // ---------------------------------------------------------------------
152 /* This is helpful when a package is no longer installed but has residual
156 pkgCache::VerIterator
FindNowVersion(const pkgCache::PkgIterator
&Pkg
)
158 pkgCache::VerIterator Ver
;
159 for (Ver
= Pkg
.VersionList(); Ver
.end() == false; ++Ver
)
161 pkgCache::VerFileIterator Vf
= Ver
.FileList();
162 pkgCache::PkgFileIterator F
= Vf
.File();
163 for (F
= Vf
.File(); F
.end() == false; ++F
)
165 if (F
&& F
.Archive())
167 if (strcmp(F
.Archive(), "now"))
176 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
177 // ---------------------------------------------------------------------
179 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
180 : pkgPackageManager(Cache
), PackagesDone(0), PackagesTotal(0)
182 d
= new pkgDPkgPMPrivate();
185 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
186 // ---------------------------------------------------------------------
188 pkgDPkgPM::~pkgDPkgPM()
193 // DPkgPM::Install - Install a package /*{{{*/
194 // ---------------------------------------------------------------------
195 /* Add an install operation to the sequence list */
196 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
198 if (File
.empty() == true || Pkg
.end() == true)
199 return _error
->Error("Internal Error, No file name for %s",Pkg
.FullName().c_str());
201 // If the filename string begins with DPkg::Chroot-Directory, return the
202 // substr that is within the chroot so dpkg can access it.
203 string
const chrootdir
= _config
->FindDir("DPkg::Chroot-Directory","/");
204 if (chrootdir
!= "/" && File
.find(chrootdir
) == 0)
206 size_t len
= chrootdir
.length();
207 if (chrootdir
.at(len
- 1) == '/')
209 List
.push_back(Item(Item::Install
,Pkg
,File
.substr(len
)));
212 List
.push_back(Item(Item::Install
,Pkg
,File
));
217 // DPkgPM::Configure - Configure a package /*{{{*/
218 // ---------------------------------------------------------------------
219 /* Add a configure operation to the sequence list */
220 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
222 if (Pkg
.end() == true)
225 List
.push_back(Item(Item::Configure
, Pkg
));
227 // Use triggers for config calls if we configure "smart"
228 // as otherwise Pre-Depends will not be satisfied, see #526774
229 if (_config
->FindB("DPkg::TriggersPending", false) == true)
230 List
.push_back(Item(Item::TriggersPending
, PkgIterator()));
235 // DPkgPM::Remove - Remove a package /*{{{*/
236 // ---------------------------------------------------------------------
237 /* Add a remove operation to the sequence list */
238 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
240 if (Pkg
.end() == true)
244 List
.push_back(Item(Item::Purge
,Pkg
));
246 List
.push_back(Item(Item::Remove
,Pkg
));
250 // DPkgPM::SendPkgInfo - Send info for install-pkgs hook /*{{{*/
251 // ---------------------------------------------------------------------
252 /* This is part of the helper script communication interface, it sends
253 very complete information down to the other end of the pipe.*/
254 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
256 return SendPkgsInfo(F
, 2);
258 bool pkgDPkgPM::SendPkgsInfo(FILE * const F
, unsigned int const &Version
)
260 // This version of APT supports only v3, so don't sent higher versions
262 fprintf(F
,"VERSION %u\n", Version
);
264 fprintf(F
,"VERSION 3\n");
266 /* Write out all of the configuration directives by walking the
267 configuration tree */
268 const Configuration::Item
*Top
= _config
->Tree(0);
271 if (Top
->Value
.empty() == false)
274 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
275 QuoteString(Top
->Value
,"\n").c_str());
284 while (Top
!= 0 && Top
->Next
== 0)
291 // Write out the package actions in order.
292 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
294 if(I
->Pkg
.end() == true)
297 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
299 fprintf(F
,"%s ",I
->Pkg
.Name());
301 // Current version which we are going to replace
302 pkgCache::VerIterator CurVer
= I
->Pkg
.CurrentVer();
303 if (CurVer
.end() == true && (I
->Op
== Item::Remove
|| I
->Op
== Item::Purge
))
304 CurVer
= FindNowVersion(I
->Pkg
);
306 if (CurVer
.end() == true)
311 fprintf(F
, "- - none ");
315 fprintf(F
, "%s ", CurVer
.VerStr());
317 fprintf(F
, "%s %s ", CurVer
.Arch(), CurVer
.MultiArchType());
320 // Show the compare operator between current and install version
321 if (S
.InstallVer
!= 0)
323 pkgCache::VerIterator
const InstVer
= S
.InstVerIter(Cache
);
325 if (CurVer
.end() == false)
326 Comp
= InstVer
.CompareVer(CurVer
);
333 fprintf(F
, "%s ", InstVer
.VerStr());
335 fprintf(F
, "%s %s ", InstVer
.Arch(), InstVer
.MultiArchType());
342 fprintf(F
, "> - - none ");
345 // Show the filename/operation
346 if (I
->Op
== Item::Install
)
349 if (I
->File
[0] != '/')
350 fprintf(F
,"**ERROR**\n");
352 fprintf(F
,"%s\n",I
->File
.c_str());
354 else if (I
->Op
== Item::Configure
)
355 fprintf(F
,"**CONFIGURE**\n");
356 else if (I
->Op
== Item::Remove
||
357 I
->Op
== Item::Purge
)
358 fprintf(F
,"**REMOVE**\n");
366 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
367 // ---------------------------------------------------------------------
368 /* This looks for a list of scripts to run from the configuration file
369 each one is run and is fed on standard input a list of all .deb files
370 that are due to be installed. */
371 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
373 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
374 if (Opts
== 0 || Opts
->Child
== 0)
378 unsigned int Count
= 1;
379 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
381 if (Opts
->Value
.empty() == true)
384 // Determine the protocol version
385 string OptSec
= Opts
->Value
;
386 string::size_type Pos
;
387 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
388 Pos
= OptSec
.length();
389 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
391 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
392 unsigned int InfoFD
= _config
->FindI(OptSec
+ "::InfoFD", STDIN_FILENO
);
396 if (pipe(Pipes
) != 0)
397 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
398 if (InfoFD
!= (unsigned)Pipes
[0])
399 SetCloseExec(Pipes
[0],true);
401 _config
->Set("APT::Keep-Fds::", Pipes
[0]);
402 SetCloseExec(Pipes
[1],true);
404 // Purified Fork for running the script
405 pid_t Process
= ExecFork();
409 dup2(Pipes
[0], InfoFD
);
410 SetCloseExec(STDOUT_FILENO
,false);
411 SetCloseExec(STDIN_FILENO
,false);
412 SetCloseExec(STDERR_FILENO
,false);
415 strprintf(hookfd
, "%d", InfoFD
);
416 setenv("APT_HOOK_INFO_FD", hookfd
.c_str(), 1);
418 dpkgChrootDirectory();
422 Args
[2] = Opts
->Value
.c_str();
424 execv(Args
[0],(char **)Args
);
427 if (InfoFD
== (unsigned)Pipes
[0])
428 _config
->Clear("APT::Keep-Fds", Pipes
[0]);
430 FILE *F
= fdopen(Pipes
[1],"w");
432 return _error
->Errno("fdopen","Faild to open new FD");
434 // Feed it the filenames.
437 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
439 // Only deal with packages to be installed from .deb
440 if (I
->Op
!= Item::Install
)
444 if (I
->File
[0] != '/')
447 /* Feed the filename of each package that is pending install
449 fprintf(F
,"%s\n",I
->File
.c_str());
455 SendPkgsInfo(F
, Version
);
459 // Clean up the sub process
460 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
461 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
467 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
468 // ---------------------------------------------------------------------
471 void pkgDPkgPM::DoStdin(int master
)
473 unsigned char input_buf
[256] = {0,};
474 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
476 FileFd::Write(master
, input_buf
, len
);
478 d
->stdin_is_dev_null
= true;
481 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
482 // ---------------------------------------------------------------------
484 * read the terminal pty and write log
486 void pkgDPkgPM::DoTerminalPty(int master
)
488 unsigned char term_buf
[1024] = {0,0, };
490 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
491 if(len
== -1 && errno
== EIO
)
493 // this happens when the child is about to exit, we
494 // give it time to actually exit, otherwise we run
495 // into a race so we sleep for half a second.
496 struct timespec sleepfor
= { 0, 500000000 };
497 nanosleep(&sleepfor
, NULL
);
502 FileFd::Write(1, term_buf
, len
);
504 fwrite(term_buf
, len
, sizeof(char), d
->term_out
);
507 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
508 // ---------------------------------------------------------------------
511 void pkgDPkgPM::ProcessDpkgStatusLine(char *line
)
513 bool const Debug
= _config
->FindB("Debug::pkgDPkgProgressReporting",false);
515 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
517 /* dpkg sends strings like this:
518 'status: <pkg>: <pkg qstate>'
519 'status: <pkg>:<arch>: <pkg qstate>'
521 'processing: {install,configure,remove,purge,disappear,trigproc}: pkg'
522 'processing: {install,configure,remove,purge,disappear,trigproc}: trigger'
525 // we need to split on ": " (note the appended space) as the ':' is
526 // part of the pkgname:arch information that dpkg sends
528 // A dpkg error message may contain additional ":" (like
529 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
530 // so we need to ensure to not split too much
531 std::vector
<std::string
> list
= StringSplit(line
, ": ", 4);
535 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
539 // build the (prefix, pkgname, action) tuple, position of this
540 // is different for "processing" or "status" messages
541 std::string prefix
= APT::String::Strip(list
[0]);
544 ostringstream status
;
546 // "processing" has the form "processing: action: pkg or trigger"
547 // with action = ["install", "configure", "remove", "purge", "disappear",
549 if (prefix
== "processing")
551 pkgname
= APT::String::Strip(list
[2]);
552 action
= APT::String::Strip(list
[1]);
554 // "status" has the form: "status: pkg: state"
555 // with state in ["half-installed", "unpacked", "half-configured",
556 // "installed", "config-files", "not-installed"]
557 else if (prefix
== "status")
559 pkgname
= APT::String::Strip(list
[1]);
560 action
= APT::String::Strip(list
[2]);
563 std::clog
<< "unknown prefix '" << prefix
<< "'" << std::endl
;
568 /* handle the special cases first:
570 errors look like this:
571 '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
572 and conffile-prompt like this
573 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
575 if (prefix
== "status")
577 if(action
== "error")
579 d
->progress
->Error(list
[1], PackagesDone
, PackagesTotal
,
582 WriteApportReport(list
[1].c_str(), list
[3].c_str());
585 else if(action
== "conffile")
587 d
->progress
->ConffilePrompt(list
[1], PackagesDone
, PackagesTotal
,
593 // at this point we know that we should have a valid pkgname, so build all
596 // dpkg does not send always send "pkgname:arch" so we add it here
598 if (pkgname
.find(":") == std::string::npos
)
600 // find the package in the group that is in a touched by dpkg
601 // if there are multiple dpkg will send us a full pkgname:arch
602 pkgCache::GrpIterator Grp
= Cache
.FindGrp(pkgname
);
603 if (Grp
.end() == false)
605 pkgCache::PkgIterator P
= Grp
.PackageList();
606 for (; P
.end() != true; P
= Grp
.NextPkg(P
))
608 if(Cache
[P
].Mode
!= pkgDepCache::ModeKeep
)
610 pkgname
= P
.FullName();
617 const char* const pkg
= pkgname
.c_str();
618 std::string short_pkgname
= StringSplit(pkgname
, ":")[0];
619 std::string arch
= "";
620 if (pkgname
.find(":") != string::npos
)
621 arch
= StringSplit(pkgname
, ":")[1];
622 std::string i18n_pkgname
= pkgname
;
623 if (arch
.size() != 0)
624 strprintf(i18n_pkgname
, "%s (%s)", short_pkgname
.c_str(), arch
.c_str());
626 // 'processing' from dpkg looks like
627 // 'processing: action: pkg'
628 if(prefix
== "processing")
630 const std::pair
<const char *, const char *> * const iter
=
631 std::find_if(PackageProcessingOpsBegin
,
632 PackageProcessingOpsEnd
,
633 MatchProcessingOp(action
.c_str()));
634 if(iter
== PackageProcessingOpsEnd
)
637 std::clog
<< "ignoring unknown action: " << action
<< std::endl
;
641 strprintf(msg
, _(iter
->second
), i18n_pkgname
.c_str());
642 d
->progress
->StatusChanged(pkgname
, PackagesDone
, PackagesTotal
, msg
);
644 // FIXME: this needs a muliarch testcase
645 // FIXME2: is "pkgname" here reliable with dpkg only sending us
647 if (action
== "disappear")
648 handleDisappearAction(pkgname
);
652 if (prefix
== "status")
654 vector
<struct DpkgState
> const &states
= PackageOps
[pkg
];
655 const char *next_action
= NULL
;
656 if(PackageOpsDone
[pkg
] < states
.size())
657 next_action
= states
[PackageOpsDone
[pkg
]].state
;
658 // check if the package moved to the next dpkg state
659 if(next_action
&& (action
== next_action
))
661 // only read the translation if there is actually a next
663 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
666 // we moved from one dpkg state to a new one, report that
667 PackageOpsDone
[pkg
]++;
670 strprintf(msg
, translation
, i18n_pkgname
.c_str());
671 d
->progress
->StatusChanged(pkgname
, PackagesDone
, PackagesTotal
, msg
);
675 std::clog
<< "(parsed from dpkg) pkg: " << short_pkgname
676 << " action: " << action
<< endl
;
680 // DPkgPM::handleDisappearAction /*{{{*/
681 void pkgDPkgPM::handleDisappearAction(string
const &pkgname
)
683 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
684 if (unlikely(Pkg
.end() == true))
687 // record the package name for display and stuff later
688 disappearedPkgs
.insert(Pkg
.FullName(true));
690 // the disappeared package was auto-installed - nothing to do
691 if ((Cache
[Pkg
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
693 pkgCache::VerIterator PkgVer
= Cache
[Pkg
].InstVerIter(Cache
);
694 if (unlikely(PkgVer
.end() == true))
696 /* search in the list of dependencies for (Pre)Depends,
697 check if this dependency has a Replaces on our package
698 and if so transfer the manual installed flag to it */
699 for (pkgCache::DepIterator Dep
= PkgVer
.DependsList(); Dep
.end() != true; ++Dep
)
701 if (Dep
->Type
!= pkgCache::Dep::Depends
&&
702 Dep
->Type
!= pkgCache::Dep::PreDepends
)
704 pkgCache::PkgIterator Tar
= Dep
.TargetPkg();
705 if (unlikely(Tar
.end() == true))
707 // the package is already marked as manual
708 if ((Cache
[Tar
].Flags
& pkgCache::Flag::Auto
) != pkgCache::Flag::Auto
)
710 pkgCache::VerIterator TarVer
= Cache
[Tar
].InstVerIter(Cache
);
711 if (TarVer
.end() == true)
713 for (pkgCache::DepIterator Rep
= TarVer
.DependsList(); Rep
.end() != true; ++Rep
)
715 if (Rep
->Type
!= pkgCache::Dep::Replaces
)
717 if (Pkg
!= Rep
.TargetPkg())
719 // okay, they are strongly connected - transfer manual-bit
721 std::clog
<< "transfer manual-bit from disappeared »" << pkgname
<< "« to »" << Tar
.FullName() << "«" << std::endl
;
722 Cache
[Tar
].Flags
&= ~Flag::Auto
;
728 // DPkgPM::DoDpkgStatusFd /*{{{*/
729 // ---------------------------------------------------------------------
732 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
)
737 len
=read(statusfd
, &d
->dpkgbuf
[d
->dpkgbuf_pos
], sizeof(d
->dpkgbuf
)-d
->dpkgbuf_pos
);
738 d
->dpkgbuf_pos
+= len
;
742 // process line by line if we have a buffer
744 while((q
=(char*)memchr(p
, '\n', d
->dpkgbuf
+d
->dpkgbuf_pos
-p
)) != NULL
)
747 ProcessDpkgStatusLine(p
);
748 p
=q
+1; // continue with next line
751 // now move the unprocessed bits (after the final \n that is now a 0x0)
752 // to the start and update d->dpkgbuf_pos
753 p
= (char*)memrchr(d
->dpkgbuf
, 0, d
->dpkgbuf_pos
);
757 // we are interessted in the first char *after* 0x0
760 // move the unprocessed tail to the start and update pos
761 memmove(d
->dpkgbuf
, p
, p
-d
->dpkgbuf
);
762 d
->dpkgbuf_pos
= d
->dpkgbuf
+d
->dpkgbuf_pos
-p
;
765 // DPkgPM::WriteHistoryTag /*{{{*/
766 void pkgDPkgPM::WriteHistoryTag(string
const &tag
, string value
)
768 size_t const length
= value
.length();
771 // poor mans rstrip(", ")
772 if (value
[length
-2] == ',' && value
[length
-1] == ' ')
773 value
.erase(length
- 2, 2);
774 fprintf(d
->history_out
, "%s: %s\n", tag
.c_str(), value
.c_str());
776 // DPkgPM::OpenLog /*{{{*/
777 bool pkgDPkgPM::OpenLog()
779 string
const logdir
= _config
->FindDir("Dir::Log");
780 if(CreateAPTDirectoryIfNeeded(logdir
, logdir
) == false)
781 // FIXME: use a better string after freeze
782 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
786 time_t const t
= time(NULL
);
787 struct tm
const * const tmp
= localtime(&t
);
788 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
791 string
const logfile_name
= flCombine(logdir
,
792 _config
->Find("Dir::Log::Terminal"));
793 if (!logfile_name
.empty())
795 d
->term_out
= fopen(logfile_name
.c_str(),"a");
796 if (d
->term_out
== NULL
)
797 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name
.c_str());
798 setvbuf(d
->term_out
, NULL
, _IONBF
, 0);
799 SetCloseExec(fileno(d
->term_out
), true);
800 if (getuid() == 0) // if we aren't root, we can't chown a file, so don't try it
802 struct passwd
*pw
= getpwnam("root");
803 struct group
*gr
= getgrnam("adm");
804 if (pw
!= NULL
&& gr
!= NULL
&& chown(logfile_name
.c_str(), pw
->pw_uid
, gr
->gr_gid
) != 0)
805 _error
->WarningE("OpenLog", "chown to root:adm of file %s failed", logfile_name
.c_str());
807 if (chmod(logfile_name
.c_str(), 0640) != 0)
808 _error
->WarningE("OpenLog", "chmod 0640 of file %s failed", logfile_name
.c_str());
809 fprintf(d
->term_out
, "\nLog started: %s\n", timestr
);
812 // write your history
813 string
const history_name
= flCombine(logdir
,
814 _config
->Find("Dir::Log::History"));
815 if (!history_name
.empty())
817 d
->history_out
= fopen(history_name
.c_str(),"a");
818 if (d
->history_out
== NULL
)
819 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), history_name
.c_str());
820 SetCloseExec(fileno(d
->history_out
), true);
821 chmod(history_name
.c_str(), 0644);
822 fprintf(d
->history_out
, "\nStart-Date: %s\n", timestr
);
823 string remove
, purge
, install
, reinstall
, upgrade
, downgrade
;
824 for (pkgCache::PkgIterator I
= Cache
.PkgBegin(); I
.end() == false; ++I
)
826 enum { CANDIDATE
, CANDIDATE_AUTO
, CURRENT_CANDIDATE
, CURRENT
} infostring
;
828 #define HISTORYINFO(X, Y) { line = &X; infostring = Y; }
829 if (Cache
[I
].NewInstall() == true)
830 HISTORYINFO(install
, CANDIDATE_AUTO
)
831 else if (Cache
[I
].ReInstall() == true)
832 HISTORYINFO(reinstall
, CANDIDATE
)
833 else if (Cache
[I
].Upgrade() == true)
834 HISTORYINFO(upgrade
, CURRENT_CANDIDATE
)
835 else if (Cache
[I
].Downgrade() == true)
836 HISTORYINFO(downgrade
, CURRENT_CANDIDATE
)
837 else if (Cache
[I
].Delete() == true)
838 HISTORYINFO((Cache
[I
].Purge() ? purge
: remove
), CURRENT
)
842 line
->append(I
.FullName(false)).append(" (");
843 switch (infostring
) {
844 case CANDIDATE
: line
->append(Cache
[I
].CandVersion
); break;
846 line
->append(Cache
[I
].CandVersion
);
847 if ((Cache
[I
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
848 line
->append(", automatic");
850 case CURRENT_CANDIDATE
: line
->append(Cache
[I
].CurVersion
).append(", ").append(Cache
[I
].CandVersion
); break;
851 case CURRENT
: line
->append(Cache
[I
].CurVersion
); break;
855 if (_config
->Exists("Commandline::AsString") == true)
856 WriteHistoryTag("Commandline", _config
->Find("Commandline::AsString"));
857 WriteHistoryTag("Install", install
);
858 WriteHistoryTag("Reinstall", reinstall
);
859 WriteHistoryTag("Upgrade", upgrade
);
860 WriteHistoryTag("Downgrade",downgrade
);
861 WriteHistoryTag("Remove",remove
);
862 WriteHistoryTag("Purge",purge
);
863 fflush(d
->history_out
);
869 // DPkg::CloseLog /*{{{*/
870 bool pkgDPkgPM::CloseLog()
873 time_t t
= time(NULL
);
874 struct tm
*tmp
= localtime(&t
);
875 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
879 fprintf(d
->term_out
, "Log ended: ");
880 fprintf(d
->term_out
, "%s", timestr
);
881 fprintf(d
->term_out
, "\n");
888 if (disappearedPkgs
.empty() == false)
891 for (std::set
<std::string
>::const_iterator d
= disappearedPkgs
.begin();
892 d
!= disappearedPkgs
.end(); ++d
)
894 pkgCache::PkgIterator P
= Cache
.FindPkg(*d
);
895 disappear
.append(*d
);
897 disappear
.append(", ");
899 disappear
.append(" (").append(Cache
[P
].CurVersion
).append("), ");
901 WriteHistoryTag("Disappeared", disappear
);
903 if (d
->dpkg_error
.empty() == false)
904 fprintf(d
->history_out
, "Error: %s\n", d
->dpkg_error
.c_str());
905 fprintf(d
->history_out
, "End-Date: %s\n", timestr
);
906 fclose(d
->history_out
);
908 d
->history_out
= NULL
;
915 // This implements a racy version of pselect for those architectures
916 // that don't have a working implementation.
917 // FIXME: Probably can be removed on Lenny+1
918 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
919 fd_set
*exceptfds
, const struct timespec
*timeout
,
920 const sigset_t
*sigmask
)
926 tv
.tv_sec
= timeout
->tv_sec
;
927 tv
.tv_usec
= timeout
->tv_nsec
/1000;
929 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
930 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
931 sigprocmask(SIG_SETMASK
, &origmask
, 0);
935 // DPkgPM::Go - Run the sequence /*{{{*/
936 // ---------------------------------------------------------------------
937 /* This globs the operations and calls dpkg
939 * If it is called with a progress object apt will report the install
940 * progress to this object. It maps the dpkg states a package goes
941 * through to human readable (and i10n-able)
942 * names and calculates a percentage for each step.
944 bool pkgDPkgPM::Go(APT::Progress::PackageManager
*progress
)
946 pkgPackageManager::SigINTStop
= false;
947 d
->progress
= progress
;
949 // Generate the base argument list for dpkg
950 std::vector
<const char *> Args
;
951 unsigned long StartSize
= 0;
952 string Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
954 string
const dpkgChrootDir
= _config
->FindDir("DPkg::Chroot-Directory", "/");
955 size_t dpkgChrootLen
= dpkgChrootDir
.length();
956 if (dpkgChrootDir
!= "/" && Tmp
.find(dpkgChrootDir
) == 0)
958 if (dpkgChrootDir
[dpkgChrootLen
- 1] == '/')
960 Tmp
= Tmp
.substr(dpkgChrootLen
);
963 Args
.push_back(Tmp
.c_str());
964 StartSize
+= Tmp
.length();
966 // Stick in any custom dpkg options
967 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
971 for (; Opts
!= 0; Opts
= Opts
->Next
)
973 if (Opts
->Value
.empty() == true)
975 Args
.push_back(Opts
->Value
.c_str());
976 StartSize
+= Opts
->Value
.length();
980 size_t const BaseArgs
= Args
.size();
981 // we need to detect if we can qualify packages with the architecture or not
982 Args
.push_back("--assert-multi-arch");
983 Args
.push_back(NULL
);
985 pid_t dpkgAssertMultiArch
= ExecFork();
986 if (dpkgAssertMultiArch
== 0)
988 dpkgChrootDirectory();
989 // redirect everything to the ultimate sink as we only need the exit-status
990 int const nullfd
= open("/dev/null", O_RDONLY
);
991 dup2(nullfd
, STDIN_FILENO
);
992 dup2(nullfd
, STDOUT_FILENO
);
993 dup2(nullfd
, STDERR_FILENO
);
994 execvp(Args
[0], (char**) &Args
[0]);
995 _error
->WarningE("dpkgGo", "Can't detect if dpkg supports multi-arch!");
1002 sigset_t original_sigmask
;
1004 unsigned int const MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
1005 unsigned int const MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
1006 bool const NoTriggers
= _config
->FindB("DPkg::NoTriggers", false);
1008 if (RunScripts("DPkg::Pre-Invoke") == false)
1011 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
1014 // support subpressing of triggers processing for special
1015 // cases like d-i that runs the triggers handling manually
1016 bool const SmartConf
= (_config
->Find("PackageManager::Configure", "all") != "all");
1017 bool const TriggersPending
= _config
->FindB("DPkg::TriggersPending", false);
1018 if (_config
->FindB("DPkg::ConfigurePending", SmartConf
) == true)
1019 List
.push_back(Item(Item::ConfigurePending
, PkgIterator()));
1021 // map the dpkg states to the operations that are performed
1022 // (this is sorted in the same way as Item::Ops)
1023 static const struct DpkgState DpkgStatesOpMap
[][7] = {
1024 // Install operation
1026 {"half-installed", N_("Preparing %s")},
1027 {"unpacked", N_("Unpacking %s") },
1030 // Configure operation
1032 {"unpacked",N_("Preparing to configure %s") },
1033 {"half-configured", N_("Configuring %s") },
1034 { "installed", N_("Installed %s")},
1039 {"half-configured", N_("Preparing for removal of %s")},
1040 {"half-installed", N_("Removing %s")},
1041 {"config-files", N_("Removed %s")},
1046 {"config-files", N_("Preparing to completely remove %s")},
1047 {"not-installed", N_("Completely removed %s")},
1052 // init the PackageOps map, go over the list of packages that
1053 // that will be [installed|configured|removed|purged] and add
1054 // them to the PackageOps map (the dpkg states it goes through)
1055 // and the PackageOpsTranslations (human readable strings)
1056 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end(); ++I
)
1058 if((*I
).Pkg
.end() == true)
1061 string
const name
= (*I
).Pkg
.FullName();
1062 PackageOpsDone
[name
] = 0;
1063 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; ++i
)
1065 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
1070 d
->stdin_is_dev_null
= false;
1075 bool dpkgMultiArch
= false;
1076 if (dpkgAssertMultiArch
> 0)
1079 while (waitpid(dpkgAssertMultiArch
, &Status
, 0) != dpkgAssertMultiArch
)
1083 _error
->WarningE("dpkgGo", _("Waited for %s but it wasn't there"), "dpkg --assert-multi-arch");
1086 if (WIFEXITED(Status
) == true && WEXITSTATUS(Status
) == 0)
1087 dpkgMultiArch
= true;
1090 // go over each item
1091 vector
<Item
>::const_iterator I
= List
.begin();
1092 while (I
!= List
.end())
1094 // Do all actions with the same Op in one run
1095 vector
<Item
>::const_iterator J
= I
;
1096 if (TriggersPending
== true)
1097 for (; J
!= List
.end(); ++J
)
1101 if (J
->Op
!= Item::TriggersPending
)
1103 vector
<Item
>::const_iterator T
= J
+ 1;
1104 if (T
!= List
.end() && T
->Op
== I
->Op
)
1109 for (; J
!= List
.end() && J
->Op
== I
->Op
; ++J
)
1112 // keep track of allocated strings for multiarch package names
1113 std::vector
<char *> Packages
;
1115 // start with the baseset of arguments
1116 unsigned long Size
= StartSize
;
1117 Args
.erase(Args
.begin() + BaseArgs
, Args
.end());
1119 // Now check if we are within the MaxArgs limit
1121 // this code below is problematic, because it may happen that
1122 // the argument list is split in a way that A depends on B
1123 // and they are in the same "--configure A B" run
1124 // - with the split they may now be configured in different
1125 // runs, using Immediate-Configure-All can help prevent this.
1126 if (J
- I
> (signed)MaxArgs
)
1129 unsigned long const size
= MaxArgs
+ 10;
1131 Packages
.reserve(size
);
1135 unsigned long const size
= (J
- I
) + 10;
1137 Packages
.reserve(size
);
1142 return _error
->Errno("pipe","Failed to create IPC pipe to dpkg");
1144 #define ADDARG(X) Args.push_back(X); Size += strlen(X)
1145 #define ADDARGC(X) Args.push_back(X); Size += sizeof(X) - 1
1147 ADDARGC("--status-fd");
1148 char status_fd_buf
[20];
1149 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
1150 ADDARG(status_fd_buf
);
1151 unsigned long const Op
= I
->Op
;
1156 ADDARGC("--force-depends");
1157 ADDARGC("--force-remove-essential");
1158 ADDARGC("--remove");
1162 ADDARGC("--force-depends");
1163 ADDARGC("--force-remove-essential");
1167 case Item::Configure
:
1168 ADDARGC("--configure");
1171 case Item::ConfigurePending
:
1172 ADDARGC("--configure");
1173 ADDARGC("--pending");
1176 case Item::TriggersPending
:
1177 ADDARGC("--triggers-only");
1178 ADDARGC("--pending");
1182 ADDARGC("--unpack");
1183 ADDARGC("--auto-deconfigure");
1187 if (NoTriggers
== true && I
->Op
!= Item::TriggersPending
&&
1188 I
->Op
!= Item::ConfigurePending
)
1190 ADDARGC("--no-triggers");
1194 // Write in the file or package names
1195 if (I
->Op
== Item::Install
)
1197 for (;I
!= J
&& Size
< MaxArgBytes
; ++I
)
1199 if (I
->File
[0] != '/')
1200 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
1201 Args
.push_back(I
->File
.c_str());
1202 Size
+= I
->File
.length();
1207 string
const nativeArch
= _config
->Find("APT::Architecture");
1208 unsigned long const oldSize
= I
->Op
== Item::Configure
? Size
: 0;
1209 for (;I
!= J
&& Size
< MaxArgBytes
; ++I
)
1211 if((*I
).Pkg
.end() == true)
1213 if (I
->Op
== Item::Configure
&& disappearedPkgs
.find(I
->Pkg
.FullName(true)) != disappearedPkgs
.end())
1215 // We keep this here to allow "smooth" transitions from e.g. multiarch dpkg/ubuntu to dpkg/debian
1216 if (dpkgMultiArch
== false && (I
->Pkg
.Arch() == nativeArch
||
1217 strcmp(I
->Pkg
.Arch(), "all") == 0 ||
1218 strcmp(I
->Pkg
.Arch(), "none") == 0))
1220 char const * const name
= I
->Pkg
.Name();
1225 pkgCache::VerIterator PkgVer
;
1226 std::string name
= I
->Pkg
.Name();
1227 if (Op
== Item::Remove
|| Op
== Item::Purge
)
1229 PkgVer
= I
->Pkg
.CurrentVer();
1230 if(PkgVer
.end() == true)
1231 PkgVer
= FindNowVersion(I
->Pkg
);
1234 PkgVer
= Cache
[I
->Pkg
].InstVerIter(Cache
);
1235 if (strcmp(I
->Pkg
.Arch(), "none") == 0)
1236 ; // never arch-qualify a package without an arch
1237 else if (PkgVer
.end() == false)
1238 name
.append(":").append(PkgVer
.Arch());
1240 _error
->Warning("Can not find PkgVer for '%s'", name
.c_str());
1241 char * const fullname
= strdup(name
.c_str());
1242 Packages
.push_back(fullname
);
1246 // skip configure action if all sheduled packages disappeared
1247 if (oldSize
== Size
)
1254 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
1256 for (std::vector
<const char *>::const_iterator a
= Args
.begin();
1257 a
!= Args
.end(); ++a
)
1262 Args
.push_back(NULL
);
1268 /* Mask off sig int/quit. We do this because dpkg also does when
1269 it forks scripts. What happens is that when you hit ctrl-c it sends
1270 it to all processes in the group. Since dpkg ignores the signal
1271 it doesn't die but we do! So we must also ignore it */
1272 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
1273 sighandler_t old_SIGINT
= signal(SIGINT
,SigINT
);
1275 // Check here for any SIGINT
1276 if (pkgPackageManager::SigINTStop
&& (Op
== Item::Remove
|| Op
== Item::Purge
|| Op
== Item::Install
))
1280 // ignore SIGHUP as well (debian #463030)
1281 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
1288 // if tcgetattr does not return zero there was a error
1289 // and we do not do any pty magic
1290 _error
->PushToStack();
1291 if (tcgetattr(STDOUT_FILENO
, &tt
) == 0)
1293 ioctl(STDOUT_FILENO
, TIOCGWINSZ
, (char *)&win
);
1294 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
1296 _error
->Errno("openpty", _("Can not write log (%s)"), _("Is /dev/pts mounted?"));
1297 master
= slave
= -1;
1302 rtt
.c_lflag
&= ~ECHO
;
1303 rtt
.c_lflag
|= ISIG
;
1304 // block SIGTTOU during tcsetattr to prevent a hang if
1305 // the process is a member of the background process group
1306 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
1307 sigemptyset(&sigmask
);
1308 sigaddset(&sigmask
, SIGTTOU
);
1309 sigprocmask(SIG_BLOCK
,&sigmask
, &original_sigmask
);
1310 tcsetattr(0, TCSAFLUSH
, &rtt
);
1311 sigprocmask(SIG_SETMASK
, &original_sigmask
, 0);
1314 // complain only if stdout is either a terminal (but still failed) or is an invalid
1315 // descriptor otherwise we would complain about redirection to e.g. /dev/null as well.
1316 else if (isatty(STDOUT_FILENO
) == 1 || errno
== EBADF
)
1317 _error
->Errno("tcgetattr", _("Can not write log (%s)"), _("Is stdout a terminal?"));
1319 if (_error
->PendingError() == true)
1320 _error
->DumpErrors(std::cerr
);
1321 _error
->RevertToStack();
1323 // this is the dpkg status-fd, we need to keep it
1324 _config
->Set("APT::Keep-Fds::",fd
[1]);
1326 // Tell the progress that its starting and fork dpkg
1327 // FIXME: this is called once per dpkg run which is *too often*
1328 d
->progress
->Start();
1330 pid_t Child
= ExecFork();
1331 // This is the child
1335 if(slave
>= 0 && master
>= 0)
1338 ioctl(slave
, TIOCSCTTY
, 0);
1345 close(fd
[0]); // close the read end of the pipe
1347 dpkgChrootDirectory();
1349 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
1352 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
1355 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
1358 // Discard everything in stdin before forking dpkg
1359 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
1362 while (read(STDIN_FILENO
,&dummy
,1) == 1);
1364 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
1367 /* No Job Control Stop Env is a magic dpkg var that prevents it
1368 from using sigstop */
1369 putenv((char *)"DPKG_NO_TSTP=yes");
1370 execvp(Args
[0], (char**) &Args
[0]);
1371 cerr
<< "Could not exec dpkg!" << endl
;
1376 if (_config
->FindB("DPkg::UseIoNice", false) == true)
1379 // clear the Keep-Fd again
1380 _config
->Clear("APT::Keep-Fds",fd
[1]);
1385 // we read from dpkg here
1386 int const _dpkgin
= fd
[0];
1387 close(fd
[1]); // close the write end of the pipe
1393 sigemptyset(&sigmask
);
1394 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
1396 /* free vectors (and therefore memory) as we don't need the included data anymore */
1397 for (std::vector
<char *>::const_iterator p
= Packages
.begin();
1398 p
!= Packages
.end(); ++p
)
1402 // the result of the waitpid call
1405 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
1407 // FIXME: move this to a function or something, looks ugly here
1408 // error handling, waitpid returned -1
1411 RunScripts("DPkg::Post-Invoke");
1413 // Restore sig int/quit
1414 signal(SIGQUIT
,old_SIGQUIT
);
1415 signal(SIGINT
,old_SIGINT
);
1417 signal(SIGHUP
,old_SIGHUP
);
1418 return _error
->Errno("waitpid","Couldn't wait for subprocess");
1421 // wait for input or output here
1423 if (master
>= 0 && !d
->stdin_is_dev_null
)
1425 FD_SET(_dpkgin
, &rfds
);
1427 FD_SET(master
, &rfds
);
1429 tv
.tv_nsec
= d
->progress
->GetPulseInterval();
1430 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
1431 &tv
, &original_sigmask
);
1432 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
1433 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
1434 NULL
, &tv
, &original_sigmask
);
1436 d
->progress
->Pulse();
1438 if (select_ret
== 0)
1440 else if (select_ret
< 0 && errno
== EINTR
)
1442 else if (select_ret
< 0)
1444 perror("select() returned error");
1448 if(master
>= 0 && FD_ISSET(master
, &rfds
))
1449 DoTerminalPty(master
);
1450 if(master
>= 0 && FD_ISSET(0, &rfds
))
1452 if(FD_ISSET(_dpkgin
, &rfds
))
1453 DoDpkgStatusFd(_dpkgin
);
1457 // Restore sig int/quit
1458 signal(SIGQUIT
,old_SIGQUIT
);
1459 signal(SIGINT
,old_SIGINT
);
1461 signal(SIGHUP
,old_SIGHUP
);
1465 tcsetattr(0, TCSAFLUSH
, &tt
);
1469 // Check for an error code.
1470 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
1472 // if it was set to "keep-dpkg-runing" then we won't return
1473 // here but keep the loop going and just report it as a error
1475 bool const stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
1478 RunScripts("DPkg::Post-Invoke");
1480 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
1481 strprintf(d
->dpkg_error
, "Sub-process %s received a segmentation fault.",Args
[0]);
1482 else if (WIFEXITED(Status
) != 0)
1483 strprintf(d
->dpkg_error
, "Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
1485 strprintf(d
->dpkg_error
, "Sub-process %s exited unexpectedly",Args
[0]);
1487 if(d
->dpkg_error
.size() > 0)
1488 _error
->Error("%s", d
->dpkg_error
.c_str());
1493 d
->progress
->Stop();
1500 // dpkg is done at this point
1501 d
->progress
->Stop();
1503 if (pkgPackageManager::SigINTStop
)
1504 _error
->Warning(_("Operation was interrupted before it could finish"));
1506 if (RunScripts("DPkg::Post-Invoke") == false)
1509 if (_config
->FindB("Debug::pkgDPkgPM",false) == false)
1511 std::string
const oldpkgcache
= _config
->FindFile("Dir::cache::pkgcache");
1512 if (oldpkgcache
.empty() == false && RealFileExists(oldpkgcache
) == true &&
1513 unlink(oldpkgcache
.c_str()) == 0)
1515 std::string
const srcpkgcache
= _config
->FindFile("Dir::cache::srcpkgcache");
1516 if (srcpkgcache
.empty() == false && RealFileExists(srcpkgcache
) == true)
1518 _error
->PushToStack();
1519 pkgCacheFile CacheFile
;
1520 CacheFile
.BuildCaches(NULL
, true);
1521 _error
->RevertToStack();
1526 Cache
.writeStateFile(NULL
);
1530 void SigINT(int sig
) {
1531 pkgPackageManager::SigINTStop
= true;
1534 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1535 // ---------------------------------------------------------------------
1537 void pkgDPkgPM::Reset()
1539 List
.erase(List
.begin(),List
.end());
1542 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1543 // ---------------------------------------------------------------------
1545 void pkgDPkgPM::WriteApportReport(const char *pkgpath
, const char *errormsg
)
1547 // If apport doesn't exist or isn't installed do nothing
1548 // This e.g. prevents messages in 'universes' without apport
1549 pkgCache::PkgIterator apportPkg
= Cache
.FindPkg("apport");
1550 if (apportPkg
.end() == true || apportPkg
->CurrentVer
== 0)
1553 string pkgname
, reportfile
, srcpkgname
, pkgver
, arch
;
1554 string::size_type pos
;
1557 if (_config
->FindB("Dpkg::ApportFailureReport", false) == false)
1559 std::clog
<< "configured to not write apport reports" << std::endl
;
1563 // only report the first errors
1564 if(pkgFailures
> _config
->FindI("APT::Apport::MaxReports", 3))
1566 std::clog
<< _("No apport report written because MaxReports is reached already") << std::endl
;
1570 // check if its not a follow up error
1571 const char *needle
= dgettext("dpkg", "dependency problems - leaving unconfigured");
1572 if(strstr(errormsg
, needle
) != NULL
) {
1573 std::clog
<< _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl
;
1577 // do not report disk-full failures
1578 if(strstr(errormsg
, strerror(ENOSPC
)) != NULL
) {
1579 std::clog
<< _("No apport report written because the error message indicates a disk full error") << std::endl
;
1583 // do not report out-of-memory failures
1584 if(strstr(errormsg
, strerror(ENOMEM
)) != NULL
) {
1585 std::clog
<< _("No apport report written because the error message indicates a out of memory error") << std::endl
;
1589 // do not report dpkg I/O errors
1590 // XXX - this message is localized, but this only matches the English version. This is better than nothing.
1591 if(strstr(errormsg
, "short read in buffer_copy (")) {
1592 std::clog
<< _("No apport report written because the error message indicates a dpkg I/O error") << std::endl
;
1596 // get the pkgname and reportfile
1597 pkgname
= flNotDir(pkgpath
);
1598 pos
= pkgname
.find('_');
1599 if(pos
!= string::npos
)
1600 pkgname
= pkgname
.substr(0, pos
);
1602 // find the package versin and source package name
1603 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
1604 if (Pkg
.end() == true)
1606 pkgCache::VerIterator Ver
= Cache
.GetCandidateVer(Pkg
);
1607 if (Ver
.end() == true)
1609 pkgver
= Ver
.VerStr() == NULL
? "unknown" : Ver
.VerStr();
1610 pkgRecords
Recs(Cache
);
1611 pkgRecords::Parser
&Parse
= Recs
.Lookup(Ver
.FileList());
1612 srcpkgname
= Parse
.SourcePkg();
1613 if(srcpkgname
.empty())
1614 srcpkgname
= pkgname
;
1616 // if the file exists already, we check:
1617 // - if it was reported already (touched by apport).
1618 // If not, we do nothing, otherwise
1619 // we overwrite it. This is the same behaviour as apport
1620 // - if we have a report with the same pkgversion already
1622 reportfile
= flCombine("/var/crash",pkgname
+".0.crash");
1623 if(FileExists(reportfile
))
1628 // check atime/mtime
1629 stat(reportfile
.c_str(), &buf
);
1630 if(buf
.st_mtime
> buf
.st_atime
)
1633 // check if the existing report is the same version
1634 report
= fopen(reportfile
.c_str(),"r");
1635 while(fgets(strbuf
, sizeof(strbuf
), report
) != NULL
)
1637 if(strstr(strbuf
,"Package:") == strbuf
)
1639 char pkgname
[255], version
[255];
1640 if(sscanf(strbuf
, "Package: %254s %254s", pkgname
, version
) == 2)
1641 if(strcmp(pkgver
.c_str(), version
) == 0)
1651 // now write the report
1652 arch
= _config
->Find("APT::Architecture");
1653 report
= fopen(reportfile
.c_str(),"w");
1656 if(_config
->FindB("DPkgPM::InitialReportOnly",false) == true)
1657 chmod(reportfile
.c_str(), 0);
1659 chmod(reportfile
.c_str(), 0600);
1660 fprintf(report
, "ProblemType: Package\n");
1661 fprintf(report
, "Architecture: %s\n", arch
.c_str());
1662 time_t now
= time(NULL
);
1663 fprintf(report
, "Date: %s" , ctime(&now
));
1664 fprintf(report
, "Package: %s %s\n", pkgname
.c_str(), pkgver
.c_str());
1665 fprintf(report
, "SourcePackage: %s\n", srcpkgname
.c_str());
1666 fprintf(report
, "ErrorMessage:\n %s\n", errormsg
);
1668 // ensure that the log is flushed
1670 fflush(d
->term_out
);
1672 // attach terminal log it if we have it
1673 string logfile_name
= _config
->FindFile("Dir::Log::Terminal");
1674 if (!logfile_name
.empty())
1678 fprintf(report
, "DpkgTerminalLog:\n");
1679 log
= fopen(logfile_name
.c_str(),"r");
1683 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1684 fprintf(report
, " %s", buf
);
1690 const char *ops_str
[] = {"Install", "Configure","Remove","Purge"};
1691 fprintf(report
, "AptOrdering:\n");
1692 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
1693 if ((*I
).Pkg
!= NULL
)
1694 fprintf(report
, " %s: %s\n", (*I
).Pkg
.Name(), ops_str
[(*I
).Op
]);
1696 fprintf(report
, " %s: %s\n", "NULL", ops_str
[(*I
).Op
]);
1698 // attach dmesg log (to learn about segfaults)
1699 if (FileExists("/bin/dmesg"))
1701 fprintf(report
, "Dmesg:\n");
1702 FILE *log
= popen("/bin/dmesg","r");
1706 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1707 fprintf(report
, " %s", buf
);
1712 // attach df -l log (to learn about filesystem status)
1713 if (FileExists("/bin/df"))
1716 fprintf(report
, "Df:\n");
1717 FILE *log
= popen("/bin/df -l","r");
1721 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1722 fprintf(report
, " %s", buf
);