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>
23 #include <apt-private/private-progress.h>
28 #include <sys/select.h>
30 #include <sys/types.h>
46 #include <sys/ioctl.h>
54 class pkgDPkgPMPrivate
57 pkgDPkgPMPrivate() : stdin_is_dev_null(false), dpkgbuf_pos(0),
58 term_out(NULL
), history_out(NULL
),
66 bool stdin_is_dev_null
;
67 // the buffer we use for the dpkg status-fd reading
73 APT::Progress::PackageManager
*progress
;
78 // Maps the dpkg "processing" info to human readable names. Entry 0
79 // of each array is the key, entry 1 is the value.
80 const std::pair
<const char *, const char *> PackageProcessingOps
[] = {
81 std::make_pair("install", N_("Installing %s")),
82 std::make_pair("configure", N_("Configuring %s")),
83 std::make_pair("remove", N_("Removing %s")),
84 std::make_pair("purge", N_("Completely removing %s")),
85 std::make_pair("disappear", N_("Noting disappearance of %s")),
86 std::make_pair("trigproc", N_("Running post-installation trigger %s"))
89 const std::pair
<const char *, const char *> * const PackageProcessingOpsBegin
= PackageProcessingOps
;
90 const std::pair
<const char *, const char *> * const PackageProcessingOpsEnd
= PackageProcessingOps
+ sizeof(PackageProcessingOps
) / sizeof(PackageProcessingOps
[0]);
92 // Predicate to test whether an entry in the PackageProcessingOps
93 // array matches a string.
94 class MatchProcessingOp
99 MatchProcessingOp(const char *the_target
)
104 bool operator()(const std::pair
<const char *, const char *> &pair
) const
106 return strcmp(pair
.first
, target
) == 0;
111 /* helper function to ionice the given PID
113 there is no C header for ionice yet - just the syscall interface
114 so we use the binary from util-linux
119 if (!FileExists("/usr/bin/ionice"))
121 pid_t Process
= ExecFork();
125 snprintf(buf
, sizeof(buf
), "-p%d", PID
);
127 Args
[0] = "/usr/bin/ionice";
131 execv(Args
[0], (char **)Args
);
133 return ExecWait(Process
, "ionice");
136 // dpkgChrootDirectory - chrooting for dpkg if needed /*{{{*/
137 static void dpkgChrootDirectory()
139 std::string
const chrootDir
= _config
->FindDir("DPkg::Chroot-Directory");
140 if (chrootDir
== "/")
142 std::cerr
<< "Chrooting into " << chrootDir
<< std::endl
;
143 if (chroot(chrootDir
.c_str()) != 0)
151 // FindNowVersion - Helper to find a Version in "now" state /*{{{*/
152 // ---------------------------------------------------------------------
153 /* This is helpful when a package is no longer installed but has residual
157 pkgCache::VerIterator
FindNowVersion(const pkgCache::PkgIterator
&Pkg
)
159 pkgCache::VerIterator Ver
;
160 for (Ver
= Pkg
.VersionList(); Ver
.end() == false; ++Ver
)
162 pkgCache::VerFileIterator Vf
= Ver
.FileList();
163 pkgCache::PkgFileIterator F
= Vf
.File();
164 for (F
= Vf
.File(); F
.end() == false; ++F
)
166 if (F
&& F
.Archive())
168 if (strcmp(F
.Archive(), "now"))
177 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
178 // ---------------------------------------------------------------------
180 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
181 : pkgPackageManager(Cache
), PackagesDone(0), PackagesTotal(0)
183 d
= new pkgDPkgPMPrivate();
186 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
187 // ---------------------------------------------------------------------
189 pkgDPkgPM::~pkgDPkgPM()
194 // DPkgPM::Install - Install a package /*{{{*/
195 // ---------------------------------------------------------------------
196 /* Add an install operation to the sequence list */
197 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
199 if (File
.empty() == true || Pkg
.end() == true)
200 return _error
->Error("Internal Error, No file name for %s",Pkg
.FullName().c_str());
202 // If the filename string begins with DPkg::Chroot-Directory, return the
203 // substr that is within the chroot so dpkg can access it.
204 string
const chrootdir
= _config
->FindDir("DPkg::Chroot-Directory","/");
205 if (chrootdir
!= "/" && File
.find(chrootdir
) == 0)
207 size_t len
= chrootdir
.length();
208 if (chrootdir
.at(len
- 1) == '/')
210 List
.push_back(Item(Item::Install
,Pkg
,File
.substr(len
)));
213 List
.push_back(Item(Item::Install
,Pkg
,File
));
218 // DPkgPM::Configure - Configure a package /*{{{*/
219 // ---------------------------------------------------------------------
220 /* Add a configure operation to the sequence list */
221 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
223 if (Pkg
.end() == true)
226 List
.push_back(Item(Item::Configure
, Pkg
));
228 // Use triggers for config calls if we configure "smart"
229 // as otherwise Pre-Depends will not be satisfied, see #526774
230 if (_config
->FindB("DPkg::TriggersPending", false) == true)
231 List
.push_back(Item(Item::TriggersPending
, PkgIterator()));
236 // DPkgPM::Remove - Remove a package /*{{{*/
237 // ---------------------------------------------------------------------
238 /* Add a remove operation to the sequence list */
239 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
241 if (Pkg
.end() == true)
245 List
.push_back(Item(Item::Purge
,Pkg
));
247 List
.push_back(Item(Item::Remove
,Pkg
));
251 // DPkgPM::SendPkgInfo - Send info for install-pkgs hook /*{{{*/
252 // ---------------------------------------------------------------------
253 /* This is part of the helper script communication interface, it sends
254 very complete information down to the other end of the pipe.*/
255 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
257 return SendPkgsInfo(F
, 2);
259 bool pkgDPkgPM::SendPkgsInfo(FILE * const F
, unsigned int const &Version
)
261 // This version of APT supports only v3, so don't sent higher versions
263 fprintf(F
,"VERSION %u\n", Version
);
265 fprintf(F
,"VERSION 3\n");
267 /* Write out all of the configuration directives by walking the
268 configuration tree */
269 const Configuration::Item
*Top
= _config
->Tree(0);
272 if (Top
->Value
.empty() == false)
275 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
276 QuoteString(Top
->Value
,"\n").c_str());
285 while (Top
!= 0 && Top
->Next
== 0)
292 // Write out the package actions in order.
293 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
295 if(I
->Pkg
.end() == true)
298 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
300 fprintf(F
,"%s ",I
->Pkg
.Name());
302 // Current version which we are going to replace
303 pkgCache::VerIterator CurVer
= I
->Pkg
.CurrentVer();
304 if (CurVer
.end() == true && (I
->Op
== Item::Remove
|| I
->Op
== Item::Purge
))
305 CurVer
= FindNowVersion(I
->Pkg
);
307 if (CurVer
.end() == true)
312 fprintf(F
, "- - none ");
316 fprintf(F
, "%s ", CurVer
.VerStr());
318 fprintf(F
, "%s %s ", CurVer
.Arch(), CurVer
.MultiArchType());
321 // Show the compare operator between current and install version
322 if (S
.InstallVer
!= 0)
324 pkgCache::VerIterator
const InstVer
= S
.InstVerIter(Cache
);
326 if (CurVer
.end() == false)
327 Comp
= InstVer
.CompareVer(CurVer
);
334 fprintf(F
, "%s ", InstVer
.VerStr());
336 fprintf(F
, "%s %s ", InstVer
.Arch(), InstVer
.MultiArchType());
343 fprintf(F
, "> - - none ");
346 // Show the filename/operation
347 if (I
->Op
== Item::Install
)
350 if (I
->File
[0] != '/')
351 fprintf(F
,"**ERROR**\n");
353 fprintf(F
,"%s\n",I
->File
.c_str());
355 else if (I
->Op
== Item::Configure
)
356 fprintf(F
,"**CONFIGURE**\n");
357 else if (I
->Op
== Item::Remove
||
358 I
->Op
== Item::Purge
)
359 fprintf(F
,"**REMOVE**\n");
367 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
368 // ---------------------------------------------------------------------
369 /* This looks for a list of scripts to run from the configuration file
370 each one is run and is fed on standard input a list of all .deb files
371 that are due to be installed. */
372 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
374 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
375 if (Opts
== 0 || Opts
->Child
== 0)
379 unsigned int Count
= 1;
380 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
382 if (Opts
->Value
.empty() == true)
385 // Determine the protocol version
386 string OptSec
= Opts
->Value
;
387 string::size_type Pos
;
388 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
389 Pos
= OptSec
.length();
390 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
392 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
393 unsigned int InfoFD
= _config
->FindI(OptSec
+ "::InfoFD", STDIN_FILENO
);
397 if (pipe(Pipes
) != 0)
398 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
399 if (InfoFD
!= (unsigned)Pipes
[0])
400 SetCloseExec(Pipes
[0],true);
402 _config
->Set("APT::Keep-Fds::", Pipes
[0]);
403 SetCloseExec(Pipes
[1],true);
405 // Purified Fork for running the script
406 pid_t Process
= ExecFork();
410 dup2(Pipes
[0], InfoFD
);
411 SetCloseExec(STDOUT_FILENO
,false);
412 SetCloseExec(STDIN_FILENO
,false);
413 SetCloseExec(STDERR_FILENO
,false);
416 strprintf(hookfd
, "%d", InfoFD
);
417 setenv("APT_HOOK_INFO_FD", hookfd
.c_str(), 1);
419 dpkgChrootDirectory();
423 Args
[2] = Opts
->Value
.c_str();
425 execv(Args
[0],(char **)Args
);
428 if (InfoFD
== (unsigned)Pipes
[0])
429 _config
->Clear("APT::Keep-Fds", Pipes
[0]);
431 FILE *F
= fdopen(Pipes
[1],"w");
433 return _error
->Errno("fdopen","Faild to open new FD");
435 // Feed it the filenames.
438 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
440 // Only deal with packages to be installed from .deb
441 if (I
->Op
!= Item::Install
)
445 if (I
->File
[0] != '/')
448 /* Feed the filename of each package that is pending install
450 fprintf(F
,"%s\n",I
->File
.c_str());
456 SendPkgsInfo(F
, Version
);
460 // Clean up the sub process
461 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
462 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
468 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
469 // ---------------------------------------------------------------------
472 void pkgDPkgPM::DoStdin(int master
)
474 unsigned char input_buf
[256] = {0,};
475 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
477 FileFd::Write(master
, input_buf
, len
);
479 d
->stdin_is_dev_null
= true;
482 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
483 // ---------------------------------------------------------------------
485 * read the terminal pty and write log
487 void pkgDPkgPM::DoTerminalPty(int master
)
489 unsigned char term_buf
[1024] = {0,0, };
491 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
492 if(len
== -1 && errno
== EIO
)
494 // this happens when the child is about to exit, we
495 // give it time to actually exit, otherwise we run
496 // into a race so we sleep for half a second.
497 struct timespec sleepfor
= { 0, 500000000 };
498 nanosleep(&sleepfor
, NULL
);
503 FileFd::Write(1, term_buf
, len
);
505 fwrite(term_buf
, len
, sizeof(char), d
->term_out
);
508 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
509 // ---------------------------------------------------------------------
512 void pkgDPkgPM::ProcessDpkgStatusLine(char *line
)
514 bool const Debug
= _config
->FindB("Debug::pkgDPkgProgressReporting",false);
516 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
518 /* dpkg sends strings like this:
519 'status: <pkg>: <pkg qstate>'
520 'status: <pkg>:<arch>: <pkg qstate>'
522 'processing: {install,configure,remove,purge,disappear,trigproc}: pkg'
523 'processing: {install,configure,remove,purge,disappear,trigproc}: trigger'
526 // we need to split on ": " (note the appended space) as the ':' is
527 // part of the pkgname:arch information that dpkg sends
529 // A dpkg error message may contain additional ":" (like
530 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
531 // so we need to ensure to not split too much
532 std::vector
<std::string
> list
= StringSplit(line
, ": ", 4);
536 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
540 // build the (prefix, pkgname, action) tuple, position of this
541 // is different for "processing" or "status" messages
542 std::string prefix
= APT::String::Strip(list
[0]);
545 ostringstream status
;
547 // "processing" has the form "processing: action: pkg or trigger"
548 // with action = ["install", "configure", "remove", "purge", "disappear",
550 if (prefix
== "processing")
552 pkgname
= APT::String::Strip(list
[2]);
553 action
= APT::String::Strip(list
[1]);
555 // this is what we support in the processing stage
556 if(action
!= "install" && action
!= "configure" &&
557 action
!= "remove" && action
!= "purge" && action
!= "purge")
560 std::clog
<< "ignoring processing action: '" << action
565 // "status" has the form: "status: pkg: state"
566 // with state in ["half-installed", "unpacked", "half-configured",
567 // "installed", "config-files", "not-installed"]
568 else if (prefix
== "status")
570 pkgname
= APT::String::Strip(list
[1]);
571 action
= APT::String::Strip(list
[2]);
574 std::clog
<< "unknown prefix '" << prefix
<< "'" << std::endl
;
579 /* handle the special cases first:
581 errors look like this:
582 '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
583 and conffile-prompt like this
584 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
586 if (prefix
== "status")
588 if(action
== "error")
590 d
->progress
->Error(list
[1], PackagesDone
, PackagesTotal
,
593 WriteApportReport(list
[1].c_str(), list
[3].c_str());
596 else if(action
== "conffile")
598 d
->progress
->ConffilePrompt(list
[1], PackagesDone
, PackagesTotal
,
604 // at this point we know that we should have a valid pkgname, so build all
607 // dpkg does not send always send "pkgname:arch" so we add it here
609 if (pkgname
.find(":") == std::string::npos
)
611 // find the package in the group that is in a touched by dpkg
612 // if there are multiple dpkg will send us a full pkgname:arch
613 pkgCache::GrpIterator Grp
= Cache
.FindGrp(pkgname
);
614 if (Grp
.end() == false)
616 pkgCache::PkgIterator P
= Grp
.PackageList();
617 for (; P
.end() != true; P
= Grp
.NextPkg(P
))
619 if(Cache
[P
].Mode
!= pkgDepCache::ModeKeep
)
621 pkgname
= P
.FullName();
628 const char* const pkg
= pkgname
.c_str();
629 std::string short_pkgname
= StringSplit(pkgname
, ":")[0];
630 std::string arch
= "";
631 if (pkgname
.find(":") != string::npos
)
632 arch
= StringSplit(pkgname
, ":")[1];
633 std::string i18n_pkgname
= pkgname
;
634 if (arch
.size() != 0)
635 strprintf(i18n_pkgname
, "%s (%s)", short_pkgname
.c_str(), arch
.c_str());
637 // 'processing' from dpkg looks like
638 // 'processing: action: pkg'
639 if(prefix
== "processing")
641 const std::pair
<const char *, const char *> * const iter
=
642 std::find_if(PackageProcessingOpsBegin
,
643 PackageProcessingOpsEnd
,
644 MatchProcessingOp(action
.c_str()));
645 if(iter
== PackageProcessingOpsEnd
)
648 std::clog
<< "ignoring unknown action: " << action
<< std::endl
;
652 strprintf(msg
, _(iter
->second
), i18n_pkgname
.c_str());
653 d
->progress
->StatusChanged(pkgname
, PackagesDone
, PackagesTotal
, msg
);
655 // FIXME: this needs a muliarch testcase
656 // FIXME2: is "pkgname" here reliable with dpkg only sending us
658 if (action
== "disappear")
659 handleDisappearAction(pkgname
);
663 if (prefix
== "status")
665 vector
<struct DpkgState
> const &states
= PackageOps
[pkg
];
666 const char *next_action
= NULL
;
667 if(PackageOpsDone
[pkg
] < states
.size())
668 next_action
= states
[PackageOpsDone
[pkg
]].state
;
669 // check if the package moved to the next dpkg state
670 if(next_action
&& (action
== next_action
))
672 // only read the translation if there is actually a next
674 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
677 // we moved from one dpkg state to a new one, report that
678 PackageOpsDone
[pkg
]++;
681 strprintf(msg
, translation
, i18n_pkgname
.c_str());
682 d
->progress
->StatusChanged(pkgname
, PackagesDone
, PackagesTotal
, msg
);
686 std::clog
<< "(parsed from dpkg) pkg: " << short_pkgname
687 << " action: " << action
<< endl
;
691 // DPkgPM::handleDisappearAction /*{{{*/
692 void pkgDPkgPM::handleDisappearAction(string
const &pkgname
)
694 // record the package name for display and stuff later
695 disappearedPkgs
.insert(pkgname
);
697 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
698 if (unlikely(Pkg
.end() == true))
700 // the disappeared package was auto-installed - nothing to do
701 if ((Cache
[Pkg
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
703 pkgCache::VerIterator PkgVer
= Cache
[Pkg
].InstVerIter(Cache
);
704 if (unlikely(PkgVer
.end() == true))
706 /* search in the list of dependencies for (Pre)Depends,
707 check if this dependency has a Replaces on our package
708 and if so transfer the manual installed flag to it */
709 for (pkgCache::DepIterator Dep
= PkgVer
.DependsList(); Dep
.end() != true; ++Dep
)
711 if (Dep
->Type
!= pkgCache::Dep::Depends
&&
712 Dep
->Type
!= pkgCache::Dep::PreDepends
)
714 pkgCache::PkgIterator Tar
= Dep
.TargetPkg();
715 if (unlikely(Tar
.end() == true))
717 // the package is already marked as manual
718 if ((Cache
[Tar
].Flags
& pkgCache::Flag::Auto
) != pkgCache::Flag::Auto
)
720 pkgCache::VerIterator TarVer
= Cache
[Tar
].InstVerIter(Cache
);
721 if (TarVer
.end() == true)
723 for (pkgCache::DepIterator Rep
= TarVer
.DependsList(); Rep
.end() != true; ++Rep
)
725 if (Rep
->Type
!= pkgCache::Dep::Replaces
)
727 if (Pkg
!= Rep
.TargetPkg())
729 // okay, they are strongly connected - transfer manual-bit
731 std::clog
<< "transfer manual-bit from disappeared »" << pkgname
<< "« to »" << Tar
.FullName() << "«" << std::endl
;
732 Cache
[Tar
].Flags
&= ~Flag::Auto
;
738 // DPkgPM::DoDpkgStatusFd /*{{{*/
739 // ---------------------------------------------------------------------
742 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
)
747 len
=read(statusfd
, &d
->dpkgbuf
[d
->dpkgbuf_pos
], sizeof(d
->dpkgbuf
)-d
->dpkgbuf_pos
);
748 d
->dpkgbuf_pos
+= len
;
752 // process line by line if we have a buffer
754 while((q
=(char*)memchr(p
, '\n', d
->dpkgbuf
+d
->dpkgbuf_pos
-p
)) != NULL
)
757 ProcessDpkgStatusLine(p
);
758 p
=q
+1; // continue with next line
761 // now move the unprocessed bits (after the final \n that is now a 0x0)
762 // to the start and update d->dpkgbuf_pos
763 p
= (char*)memrchr(d
->dpkgbuf
, 0, d
->dpkgbuf_pos
);
767 // we are interessted in the first char *after* 0x0
770 // move the unprocessed tail to the start and update pos
771 memmove(d
->dpkgbuf
, p
, p
-d
->dpkgbuf
);
772 d
->dpkgbuf_pos
= d
->dpkgbuf
+d
->dpkgbuf_pos
-p
;
775 // DPkgPM::WriteHistoryTag /*{{{*/
776 void pkgDPkgPM::WriteHistoryTag(string
const &tag
, string value
)
778 size_t const length
= value
.length();
781 // poor mans rstrip(", ")
782 if (value
[length
-2] == ',' && value
[length
-1] == ' ')
783 value
.erase(length
- 2, 2);
784 fprintf(d
->history_out
, "%s: %s\n", tag
.c_str(), value
.c_str());
786 // DPkgPM::OpenLog /*{{{*/
787 bool pkgDPkgPM::OpenLog()
789 string
const logdir
= _config
->FindDir("Dir::Log");
790 if(CreateAPTDirectoryIfNeeded(logdir
, logdir
) == false)
791 // FIXME: use a better string after freeze
792 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
796 time_t const t
= time(NULL
);
797 struct tm
const * const tmp
= localtime(&t
);
798 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
801 string
const logfile_name
= flCombine(logdir
,
802 _config
->Find("Dir::Log::Terminal"));
803 if (!logfile_name
.empty())
805 d
->term_out
= fopen(logfile_name
.c_str(),"a");
806 if (d
->term_out
== NULL
)
807 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name
.c_str());
808 setvbuf(d
->term_out
, NULL
, _IONBF
, 0);
809 SetCloseExec(fileno(d
->term_out
), true);
810 if (getuid() == 0) // if we aren't root, we can't chown a file, so don't try it
812 struct passwd
*pw
= getpwnam("root");
813 struct group
*gr
= getgrnam("adm");
814 if (pw
!= NULL
&& gr
!= NULL
&& chown(logfile_name
.c_str(), pw
->pw_uid
, gr
->gr_gid
) != 0)
815 _error
->WarningE("OpenLog", "chown to root:adm of file %s failed", logfile_name
.c_str());
817 if (chmod(logfile_name
.c_str(), 0640) != 0)
818 _error
->WarningE("OpenLog", "chmod 0640 of file %s failed", logfile_name
.c_str());
819 fprintf(d
->term_out
, "\nLog started: %s\n", timestr
);
822 // write your history
823 string
const history_name
= flCombine(logdir
,
824 _config
->Find("Dir::Log::History"));
825 if (!history_name
.empty())
827 d
->history_out
= fopen(history_name
.c_str(),"a");
828 if (d
->history_out
== NULL
)
829 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), history_name
.c_str());
830 SetCloseExec(fileno(d
->history_out
), true);
831 chmod(history_name
.c_str(), 0644);
832 fprintf(d
->history_out
, "\nStart-Date: %s\n", timestr
);
833 string remove
, purge
, install
, reinstall
, upgrade
, downgrade
;
834 for (pkgCache::PkgIterator I
= Cache
.PkgBegin(); I
.end() == false; ++I
)
836 enum { CANDIDATE
, CANDIDATE_AUTO
, CURRENT_CANDIDATE
, CURRENT
} infostring
;
838 #define HISTORYINFO(X, Y) { line = &X; infostring = Y; }
839 if (Cache
[I
].NewInstall() == true)
840 HISTORYINFO(install
, CANDIDATE_AUTO
)
841 else if (Cache
[I
].ReInstall() == true)
842 HISTORYINFO(reinstall
, CANDIDATE
)
843 else if (Cache
[I
].Upgrade() == true)
844 HISTORYINFO(upgrade
, CURRENT_CANDIDATE
)
845 else if (Cache
[I
].Downgrade() == true)
846 HISTORYINFO(downgrade
, CURRENT_CANDIDATE
)
847 else if (Cache
[I
].Delete() == true)
848 HISTORYINFO((Cache
[I
].Purge() ? purge
: remove
), CURRENT
)
852 line
->append(I
.FullName(false)).append(" (");
853 switch (infostring
) {
854 case CANDIDATE
: line
->append(Cache
[I
].CandVersion
); break;
856 line
->append(Cache
[I
].CandVersion
);
857 if ((Cache
[I
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
858 line
->append(", automatic");
860 case CURRENT_CANDIDATE
: line
->append(Cache
[I
].CurVersion
).append(", ").append(Cache
[I
].CandVersion
); break;
861 case CURRENT
: line
->append(Cache
[I
].CurVersion
); break;
865 if (_config
->Exists("Commandline::AsString") == true)
866 WriteHistoryTag("Commandline", _config
->Find("Commandline::AsString"));
867 WriteHistoryTag("Install", install
);
868 WriteHistoryTag("Reinstall", reinstall
);
869 WriteHistoryTag("Upgrade", upgrade
);
870 WriteHistoryTag("Downgrade",downgrade
);
871 WriteHistoryTag("Remove",remove
);
872 WriteHistoryTag("Purge",purge
);
873 fflush(d
->history_out
);
879 // DPkg::CloseLog /*{{{*/
880 bool pkgDPkgPM::CloseLog()
883 time_t t
= time(NULL
);
884 struct tm
*tmp
= localtime(&t
);
885 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
889 fprintf(d
->term_out
, "Log ended: ");
890 fprintf(d
->term_out
, "%s", timestr
);
891 fprintf(d
->term_out
, "\n");
898 if (disappearedPkgs
.empty() == false)
901 for (std::set
<std::string
>::const_iterator d
= disappearedPkgs
.begin();
902 d
!= disappearedPkgs
.end(); ++d
)
904 pkgCache::PkgIterator P
= Cache
.FindPkg(*d
);
905 disappear
.append(*d
);
907 disappear
.append(", ");
909 disappear
.append(" (").append(Cache
[P
].CurVersion
).append("), ");
911 WriteHistoryTag("Disappeared", disappear
);
913 if (d
->dpkg_error
.empty() == false)
914 fprintf(d
->history_out
, "Error: %s\n", d
->dpkg_error
.c_str());
915 fprintf(d
->history_out
, "End-Date: %s\n", timestr
);
916 fclose(d
->history_out
);
918 d
->history_out
= NULL
;
925 // This implements a racy version of pselect for those architectures
926 // that don't have a working implementation.
927 // FIXME: Probably can be removed on Lenny+1
928 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
929 fd_set
*exceptfds
, const struct timespec
*timeout
,
930 const sigset_t
*sigmask
)
936 tv
.tv_sec
= timeout
->tv_sec
;
937 tv
.tv_usec
= timeout
->tv_nsec
/1000;
939 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
940 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
941 sigprocmask(SIG_SETMASK
, &origmask
, 0);
945 // DPkgPM::Go - Run the sequence /*{{{*/
946 // ---------------------------------------------------------------------
947 /* This globs the operations and calls dpkg
949 * If it is called with a progress object apt will report the install
950 * progress to this object. It maps the dpkg states a package goes
951 * through to human readable (and i10n-able)
952 * names and calculates a percentage for each step.
954 bool pkgDPkgPM::Go(APT::Progress::PackageManager
*progress
)
956 pkgPackageManager::SigINTStop
= false;
957 d
->progress
= progress
;
959 // Generate the base argument list for dpkg
960 std::vector
<const char *> Args
;
961 unsigned long StartSize
= 0;
962 string Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
964 string
const dpkgChrootDir
= _config
->FindDir("DPkg::Chroot-Directory", "/");
965 size_t dpkgChrootLen
= dpkgChrootDir
.length();
966 if (dpkgChrootDir
!= "/" && Tmp
.find(dpkgChrootDir
) == 0)
968 if (dpkgChrootDir
[dpkgChrootLen
- 1] == '/')
970 Tmp
= Tmp
.substr(dpkgChrootLen
);
973 Args
.push_back(Tmp
.c_str());
974 StartSize
+= Tmp
.length();
976 // Stick in any custom dpkg options
977 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
981 for (; Opts
!= 0; Opts
= Opts
->Next
)
983 if (Opts
->Value
.empty() == true)
985 Args
.push_back(Opts
->Value
.c_str());
986 StartSize
+= Opts
->Value
.length();
990 size_t const BaseArgs
= Args
.size();
991 // we need to detect if we can qualify packages with the architecture or not
992 Args
.push_back("--assert-multi-arch");
993 Args
.push_back(NULL
);
995 pid_t dpkgAssertMultiArch
= ExecFork();
996 if (dpkgAssertMultiArch
== 0)
998 dpkgChrootDirectory();
999 // redirect everything to the ultimate sink as we only need the exit-status
1000 int const nullfd
= open("/dev/null", O_RDONLY
);
1001 dup2(nullfd
, STDIN_FILENO
);
1002 dup2(nullfd
, STDOUT_FILENO
);
1003 dup2(nullfd
, STDERR_FILENO
);
1004 execvp(Args
[0], (char**) &Args
[0]);
1005 _error
->WarningE("dpkgGo", "Can't detect if dpkg supports multi-arch!");
1012 sigset_t original_sigmask
;
1014 unsigned int const MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
1015 unsigned int const MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
1016 bool const NoTriggers
= _config
->FindB("DPkg::NoTriggers", false);
1018 if (RunScripts("DPkg::Pre-Invoke") == false)
1021 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
1024 // support subpressing of triggers processing for special
1025 // cases like d-i that runs the triggers handling manually
1026 bool const SmartConf
= (_config
->Find("PackageManager::Configure", "all") != "all");
1027 bool const TriggersPending
= _config
->FindB("DPkg::TriggersPending", false);
1028 if (_config
->FindB("DPkg::ConfigurePending", SmartConf
) == true)
1029 List
.push_back(Item(Item::ConfigurePending
, PkgIterator()));
1031 // map the dpkg states to the operations that are performed
1032 // (this is sorted in the same way as Item::Ops)
1033 static const struct DpkgState DpkgStatesOpMap
[][7] = {
1034 // Install operation
1036 {"half-installed", N_("Preparing %s")},
1037 {"unpacked", N_("Unpacking %s") },
1040 // Configure operation
1042 {"unpacked",N_("Preparing to configure %s") },
1043 {"half-configured", N_("Configuring %s") },
1044 { "installed", N_("Installed %s")},
1049 {"half-configured", N_("Preparing for removal of %s")},
1050 {"half-installed", N_("Removing %s")},
1051 {"config-files", N_("Removed %s")},
1056 {"config-files", N_("Preparing to completely remove %s")},
1057 {"not-installed", N_("Completely removed %s")},
1062 // init the PackageOps map, go over the list of packages that
1063 // that will be [installed|configured|removed|purged] and add
1064 // them to the PackageOps map (the dpkg states it goes through)
1065 // and the PackageOpsTranslations (human readable strings)
1066 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end(); ++I
)
1068 if((*I
).Pkg
.end() == true)
1071 string
const name
= (*I
).Pkg
.FullName();
1072 PackageOpsDone
[name
] = 0;
1073 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; ++i
)
1075 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
1080 d
->stdin_is_dev_null
= false;
1085 bool dpkgMultiArch
= false;
1086 if (dpkgAssertMultiArch
> 0)
1089 while (waitpid(dpkgAssertMultiArch
, &Status
, 0) != dpkgAssertMultiArch
)
1093 _error
->WarningE("dpkgGo", _("Waited for %s but it wasn't there"), "dpkg --assert-multi-arch");
1096 if (WIFEXITED(Status
) == true && WEXITSTATUS(Status
) == 0)
1097 dpkgMultiArch
= true;
1100 // this loop is runs once per operation
1101 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();)
1103 // Do all actions with the same Op in one run
1104 vector
<Item
>::const_iterator J
= I
;
1105 if (TriggersPending
== true)
1106 for (; J
!= List
.end(); ++J
)
1110 if (J
->Op
!= Item::TriggersPending
)
1112 vector
<Item
>::const_iterator T
= J
+ 1;
1113 if (T
!= List
.end() && T
->Op
== I
->Op
)
1118 for (; J
!= List
.end() && J
->Op
== I
->Op
; ++J
)
1121 // keep track of allocated strings for multiarch package names
1122 std::vector
<char *> Packages
;
1124 // start with the baseset of arguments
1125 unsigned long Size
= StartSize
;
1126 Args
.erase(Args
.begin() + BaseArgs
, Args
.end());
1128 // Now check if we are within the MaxArgs limit
1130 // this code below is problematic, because it may happen that
1131 // the argument list is split in a way that A depends on B
1132 // and they are in the same "--configure A B" run
1133 // - with the split they may now be configured in different
1134 // runs, using Immediate-Configure-All can help prevent this.
1135 if (J
- I
> (signed)MaxArgs
)
1138 unsigned long const size
= MaxArgs
+ 10;
1140 Packages
.reserve(size
);
1144 unsigned long const size
= (J
- I
) + 10;
1146 Packages
.reserve(size
);
1151 return _error
->Errno("pipe","Failed to create IPC pipe to dpkg");
1153 #define ADDARG(X) Args.push_back(X); Size += strlen(X)
1154 #define ADDARGC(X) Args.push_back(X); Size += sizeof(X) - 1
1156 ADDARGC("--status-fd");
1157 char status_fd_buf
[20];
1158 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
1159 ADDARG(status_fd_buf
);
1160 unsigned long const Op
= I
->Op
;
1165 ADDARGC("--force-depends");
1166 ADDARGC("--force-remove-essential");
1167 ADDARGC("--remove");
1171 ADDARGC("--force-depends");
1172 ADDARGC("--force-remove-essential");
1176 case Item::Configure
:
1177 ADDARGC("--configure");
1180 case Item::ConfigurePending
:
1181 ADDARGC("--configure");
1182 ADDARGC("--pending");
1185 case Item::TriggersPending
:
1186 ADDARGC("--triggers-only");
1187 ADDARGC("--pending");
1191 ADDARGC("--unpack");
1192 ADDARGC("--auto-deconfigure");
1196 if (NoTriggers
== true && I
->Op
!= Item::TriggersPending
&&
1197 I
->Op
!= Item::ConfigurePending
)
1199 ADDARGC("--no-triggers");
1203 // Write in the file or package names
1204 if (I
->Op
== Item::Install
)
1206 for (;I
!= J
&& Size
< MaxArgBytes
; ++I
)
1208 if (I
->File
[0] != '/')
1209 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
1210 Args
.push_back(I
->File
.c_str());
1211 Size
+= I
->File
.length();
1216 string
const nativeArch
= _config
->Find("APT::Architecture");
1217 unsigned long const oldSize
= I
->Op
== Item::Configure
? Size
: 0;
1218 for (;I
!= J
&& Size
< MaxArgBytes
; ++I
)
1220 if((*I
).Pkg
.end() == true)
1222 if (I
->Op
== Item::Configure
&& disappearedPkgs
.find(I
->Pkg
.Name()) != disappearedPkgs
.end())
1224 // We keep this here to allow "smooth" transitions from e.g. multiarch dpkg/ubuntu to dpkg/debian
1225 if (dpkgMultiArch
== false && (I
->Pkg
.Arch() == nativeArch
||
1226 strcmp(I
->Pkg
.Arch(), "all") == 0 ||
1227 strcmp(I
->Pkg
.Arch(), "none") == 0))
1229 char const * const name
= I
->Pkg
.Name();
1234 pkgCache::VerIterator PkgVer
;
1235 std::string name
= I
->Pkg
.Name();
1236 if (Op
== Item::Remove
|| Op
== Item::Purge
)
1238 PkgVer
= I
->Pkg
.CurrentVer();
1239 if(PkgVer
.end() == true)
1240 PkgVer
= FindNowVersion(I
->Pkg
);
1243 PkgVer
= Cache
[I
->Pkg
].InstVerIter(Cache
);
1244 if (strcmp(I
->Pkg
.Arch(), "none") == 0)
1245 ; // never arch-qualify a package without an arch
1246 else if (PkgVer
.end() == false)
1247 name
.append(":").append(PkgVer
.Arch());
1249 _error
->Warning("Can not find PkgVer for '%s'", name
.c_str());
1250 char * const fullname
= strdup(name
.c_str());
1251 Packages
.push_back(fullname
);
1255 // skip configure action if all sheduled packages disappeared
1256 if (oldSize
== Size
)
1263 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
1265 for (std::vector
<const char *>::const_iterator a
= Args
.begin();
1266 a
!= Args
.end(); ++a
)
1271 Args
.push_back(NULL
);
1277 /* Mask off sig int/quit. We do this because dpkg also does when
1278 it forks scripts. What happens is that when you hit ctrl-c it sends
1279 it to all processes in the group. Since dpkg ignores the signal
1280 it doesn't die but we do! So we must also ignore it */
1281 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
1282 sighandler_t old_SIGINT
= signal(SIGINT
,SigINT
);
1284 // Check here for any SIGINT
1285 if (pkgPackageManager::SigINTStop
&& (Op
== Item::Remove
|| Op
== Item::Purge
|| Op
== Item::Install
))
1289 // ignore SIGHUP as well (debian #463030)
1290 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
1297 // if tcgetattr does not return zero there was a error
1298 // and we do not do any pty magic
1299 _error
->PushToStack();
1300 if (tcgetattr(STDOUT_FILENO
, &tt
) == 0)
1302 ioctl(STDOUT_FILENO
, TIOCGWINSZ
, (char *)&win
);
1303 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
1305 _error
->Errno("openpty", _("Can not write log (%s)"), _("Is /dev/pts mounted?"));
1306 master
= slave
= -1;
1311 rtt
.c_lflag
&= ~ECHO
;
1312 rtt
.c_lflag
|= ISIG
;
1313 // block SIGTTOU during tcsetattr to prevent a hang if
1314 // the process is a member of the background process group
1315 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
1316 sigemptyset(&sigmask
);
1317 sigaddset(&sigmask
, SIGTTOU
);
1318 sigprocmask(SIG_BLOCK
,&sigmask
, &original_sigmask
);
1319 tcsetattr(0, TCSAFLUSH
, &rtt
);
1320 sigprocmask(SIG_SETMASK
, &original_sigmask
, 0);
1323 // complain only if stdout is either a terminal (but still failed) or is an invalid
1324 // descriptor otherwise we would complain about redirection to e.g. /dev/null as well.
1325 else if (isatty(STDOUT_FILENO
) == 1 || errno
== EBADF
)
1326 _error
->Errno("tcgetattr", _("Can not write log (%s)"), _("Is stdout a terminal?"));
1328 if (_error
->PendingError() == true)
1329 _error
->DumpErrors(std::cerr
);
1330 _error
->RevertToStack();
1332 // this is the dpkg status-fd, we need to keep it
1333 _config
->Set("APT::Keep-Fds::",fd
[1]);
1335 // Tell the progress that its starting and fork dpkg
1336 // FIXME: this is called once per dpkg run which is *too often*
1337 d
->progress
->Start();
1339 pid_t Child
= ExecFork();
1340 // This is the child
1344 if(slave
>= 0 && master
>= 0)
1347 ioctl(slave
, TIOCSCTTY
, 0);
1354 close(fd
[0]); // close the read end of the pipe
1356 dpkgChrootDirectory();
1358 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
1361 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
1364 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
1367 // Discard everything in stdin before forking dpkg
1368 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
1371 while (read(STDIN_FILENO
,&dummy
,1) == 1);
1373 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
1376 /* No Job Control Stop Env is a magic dpkg var that prevents it
1377 from using sigstop */
1378 putenv((char *)"DPKG_NO_TSTP=yes");
1379 execvp(Args
[0], (char**) &Args
[0]);
1380 cerr
<< "Could not exec dpkg!" << endl
;
1385 if (_config
->FindB("DPkg::UseIoNice", false) == true)
1388 // clear the Keep-Fd again
1389 _config
->Clear("APT::Keep-Fds",fd
[1]);
1394 // we read from dpkg here
1395 int const _dpkgin
= fd
[0];
1396 close(fd
[1]); // close the write end of the pipe
1402 sigemptyset(&sigmask
);
1403 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
1405 /* free vectors (and therefore memory) as we don't need the included data anymore */
1406 for (std::vector
<char *>::const_iterator p
= Packages
.begin();
1407 p
!= Packages
.end(); ++p
)
1411 // the result of the waitpid call
1414 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
1416 // FIXME: move this to a function or something, looks ugly here
1417 // error handling, waitpid returned -1
1420 RunScripts("DPkg::Post-Invoke");
1422 // Restore sig int/quit
1423 signal(SIGQUIT
,old_SIGQUIT
);
1424 signal(SIGINT
,old_SIGINT
);
1426 signal(SIGHUP
,old_SIGHUP
);
1427 return _error
->Errno("waitpid","Couldn't wait for subprocess");
1430 // wait for input or output here
1432 if (master
>= 0 && !d
->stdin_is_dev_null
)
1434 FD_SET(_dpkgin
, &rfds
);
1436 FD_SET(master
, &rfds
);
1438 tv
.tv_nsec
= d
->progress
->GetPulseInterval();
1439 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
1440 &tv
, &original_sigmask
);
1441 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
1442 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
1443 NULL
, &tv
, &original_sigmask
);
1445 d
->progress
->Pulse();
1447 if (select_ret
== 0)
1449 else if (select_ret
< 0 && errno
== EINTR
)
1451 else if (select_ret
< 0)
1453 perror("select() returned error");
1457 if(master
>= 0 && FD_ISSET(master
, &rfds
))
1458 DoTerminalPty(master
);
1459 if(master
>= 0 && FD_ISSET(0, &rfds
))
1461 if(FD_ISSET(_dpkgin
, &rfds
))
1462 DoDpkgStatusFd(_dpkgin
);
1466 // Restore sig int/quit
1467 signal(SIGQUIT
,old_SIGQUIT
);
1468 signal(SIGINT
,old_SIGINT
);
1470 signal(SIGHUP
,old_SIGHUP
);
1474 tcsetattr(0, TCSAFLUSH
, &tt
);
1478 // Check for an error code.
1479 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
1481 // if it was set to "keep-dpkg-runing" then we won't return
1482 // here but keep the loop going and just report it as a error
1484 bool const stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
1487 RunScripts("DPkg::Post-Invoke");
1489 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
1490 strprintf(d
->dpkg_error
, "Sub-process %s received a segmentation fault.",Args
[0]);
1491 else if (WIFEXITED(Status
) != 0)
1492 strprintf(d
->dpkg_error
, "Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
1494 strprintf(d
->dpkg_error
, "Sub-process %s exited unexpectedly",Args
[0]);
1496 if(d
->dpkg_error
.size() > 0)
1497 _error
->Error("%s", d
->dpkg_error
.c_str());
1502 d
->progress
->Stop();
1509 // dpkg is done at this point
1510 d
->progress
->Stop();
1512 if (pkgPackageManager::SigINTStop
)
1513 _error
->Warning(_("Operation was interrupted before it could finish"));
1515 if (RunScripts("DPkg::Post-Invoke") == false)
1518 if (_config
->FindB("Debug::pkgDPkgPM",false) == false)
1520 std::string
const oldpkgcache
= _config
->FindFile("Dir::cache::pkgcache");
1521 if (oldpkgcache
.empty() == false && RealFileExists(oldpkgcache
) == true &&
1522 unlink(oldpkgcache
.c_str()) == 0)
1524 std::string
const srcpkgcache
= _config
->FindFile("Dir::cache::srcpkgcache");
1525 if (srcpkgcache
.empty() == false && RealFileExists(srcpkgcache
) == true)
1527 _error
->PushToStack();
1528 pkgCacheFile CacheFile
;
1529 CacheFile
.BuildCaches(NULL
, true);
1530 _error
->RevertToStack();
1535 Cache
.writeStateFile(NULL
);
1539 void SigINT(int sig
) {
1540 pkgPackageManager::SigINTStop
= true;
1543 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1544 // ---------------------------------------------------------------------
1546 void pkgDPkgPM::Reset()
1548 List
.erase(List
.begin(),List
.end());
1551 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1552 // ---------------------------------------------------------------------
1554 void pkgDPkgPM::WriteApportReport(const char *pkgpath
, const char *errormsg
)
1556 // If apport doesn't exist or isn't installed do nothing
1557 // This e.g. prevents messages in 'universes' without apport
1558 pkgCache::PkgIterator apportPkg
= Cache
.FindPkg("apport");
1559 if (apportPkg
.end() == true || apportPkg
->CurrentVer
== 0)
1562 string pkgname
, reportfile
, srcpkgname
, pkgver
, arch
;
1563 string::size_type pos
;
1566 if (_config
->FindB("Dpkg::ApportFailureReport", false) == false)
1568 std::clog
<< "configured to not write apport reports" << std::endl
;
1572 // only report the first errors
1573 if(pkgFailures
> _config
->FindI("APT::Apport::MaxReports", 3))
1575 std::clog
<< _("No apport report written because MaxReports is reached already") << std::endl
;
1579 // check if its not a follow up error
1580 const char *needle
= dgettext("dpkg", "dependency problems - leaving unconfigured");
1581 if(strstr(errormsg
, needle
) != NULL
) {
1582 std::clog
<< _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl
;
1586 // do not report disk-full failures
1587 if(strstr(errormsg
, strerror(ENOSPC
)) != NULL
) {
1588 std::clog
<< _("No apport report written because the error message indicates a disk full error") << std::endl
;
1592 // do not report out-of-memory failures
1593 if(strstr(errormsg
, strerror(ENOMEM
)) != NULL
) {
1594 std::clog
<< _("No apport report written because the error message indicates a out of memory error") << std::endl
;
1598 // do not report dpkg I/O errors
1599 // XXX - this message is localized, but this only matches the English version. This is better than nothing.
1600 if(strstr(errormsg
, "short read in buffer_copy (")) {
1601 std::clog
<< _("No apport report written because the error message indicates a dpkg I/O error") << std::endl
;
1605 // get the pkgname and reportfile
1606 pkgname
= flNotDir(pkgpath
);
1607 pos
= pkgname
.find('_');
1608 if(pos
!= string::npos
)
1609 pkgname
= pkgname
.substr(0, pos
);
1611 // find the package versin and source package name
1612 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
1613 if (Pkg
.end() == true)
1615 pkgCache::VerIterator Ver
= Cache
.GetCandidateVer(Pkg
);
1616 if (Ver
.end() == true)
1618 pkgver
= Ver
.VerStr() == NULL
? "unknown" : Ver
.VerStr();
1619 pkgRecords
Recs(Cache
);
1620 pkgRecords::Parser
&Parse
= Recs
.Lookup(Ver
.FileList());
1621 srcpkgname
= Parse
.SourcePkg();
1622 if(srcpkgname
.empty())
1623 srcpkgname
= pkgname
;
1625 // if the file exists already, we check:
1626 // - if it was reported already (touched by apport).
1627 // If not, we do nothing, otherwise
1628 // we overwrite it. This is the same behaviour as apport
1629 // - if we have a report with the same pkgversion already
1631 reportfile
= flCombine("/var/crash",pkgname
+".0.crash");
1632 if(FileExists(reportfile
))
1637 // check atime/mtime
1638 stat(reportfile
.c_str(), &buf
);
1639 if(buf
.st_mtime
> buf
.st_atime
)
1642 // check if the existing report is the same version
1643 report
= fopen(reportfile
.c_str(),"r");
1644 while(fgets(strbuf
, sizeof(strbuf
), report
) != NULL
)
1646 if(strstr(strbuf
,"Package:") == strbuf
)
1648 char pkgname
[255], version
[255];
1649 if(sscanf(strbuf
, "Package: %254s %254s", pkgname
, version
) == 2)
1650 if(strcmp(pkgver
.c_str(), version
) == 0)
1660 // now write the report
1661 arch
= _config
->Find("APT::Architecture");
1662 report
= fopen(reportfile
.c_str(),"w");
1665 if(_config
->FindB("DPkgPM::InitialReportOnly",false) == true)
1666 chmod(reportfile
.c_str(), 0);
1668 chmod(reportfile
.c_str(), 0600);
1669 fprintf(report
, "ProblemType: Package\n");
1670 fprintf(report
, "Architecture: %s\n", arch
.c_str());
1671 time_t now
= time(NULL
);
1672 fprintf(report
, "Date: %s" , ctime(&now
));
1673 fprintf(report
, "Package: %s %s\n", pkgname
.c_str(), pkgver
.c_str());
1674 fprintf(report
, "SourcePackage: %s\n", srcpkgname
.c_str());
1675 fprintf(report
, "ErrorMessage:\n %s\n", errormsg
);
1677 // ensure that the log is flushed
1679 fflush(d
->term_out
);
1681 // attach terminal log it if we have it
1682 string logfile_name
= _config
->FindFile("Dir::Log::Terminal");
1683 if (!logfile_name
.empty())
1687 fprintf(report
, "DpkgTerminalLog:\n");
1688 log
= fopen(logfile_name
.c_str(),"r");
1692 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1693 fprintf(report
, " %s", buf
);
1699 const char *ops_str
[] = {"Install", "Configure","Remove","Purge"};
1700 fprintf(report
, "AptOrdering:\n");
1701 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
1702 if ((*I
).Pkg
!= NULL
)
1703 fprintf(report
, " %s: %s\n", (*I
).Pkg
.Name(), ops_str
[(*I
).Op
]);
1705 fprintf(report
, " %s: %s\n", "NULL", ops_str
[(*I
).Op
]);
1707 // attach dmesg log (to learn about segfaults)
1708 if (FileExists("/bin/dmesg"))
1710 fprintf(report
, "Dmesg:\n");
1711 FILE *log
= popen("/bin/dmesg","r");
1715 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1716 fprintf(report
, " %s", buf
);
1721 // attach df -l log (to learn about filesystem status)
1722 if (FileExists("/bin/df"))
1725 fprintf(report
, "Df:\n");
1726 FILE *log
= popen("/bin/df -l","r");
1730 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1731 fprintf(report
, " %s", buf
);