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
), 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
);
420 if (pipe(Pipes
) != 0)
421 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
422 if (InfoFD
!= (unsigned)Pipes
[0])
423 SetCloseExec(Pipes
[0],true);
425 _config
->Set("APT::Keep-Fds::", Pipes
[0]);
426 SetCloseExec(Pipes
[1],true);
428 // Purified Fork for running the script
429 pid_t Process
= ExecFork();
433 dup2(Pipes
[0], InfoFD
);
434 SetCloseExec(STDOUT_FILENO
,false);
435 SetCloseExec(STDIN_FILENO
,false);
436 SetCloseExec(STDERR_FILENO
,false);
439 strprintf(hookfd
, "%d", InfoFD
);
440 setenv("APT_HOOK_INFO_FD", hookfd
.c_str(), 1);
442 dpkgChrootDirectory();
446 Args
[2] = Opts
->Value
.c_str();
448 execv(Args
[0],(char **)Args
);
451 if (InfoFD
== (unsigned)Pipes
[0])
452 _config
->Clear("APT::Keep-Fds", Pipes
[0]);
454 FILE *F
= fdopen(Pipes
[1],"w");
456 return _error
->Errno("fdopen","Faild to open new FD");
458 // Feed it the filenames.
461 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
463 // Only deal with packages to be installed from .deb
464 if (I
->Op
!= Item::Install
)
468 if (I
->File
[0] != '/')
471 /* Feed the filename of each package that is pending install
473 fprintf(F
,"%s\n",I
->File
.c_str());
479 SendPkgsInfo(F
, Version
);
483 // Clean up the sub process
484 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
485 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
491 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
492 // ---------------------------------------------------------------------
495 void pkgDPkgPM::DoStdin(int master
)
497 unsigned char input_buf
[256] = {0,};
498 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
500 FileFd::Write(master
, input_buf
, len
);
502 d
->stdin_is_dev_null
= true;
505 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
506 // ---------------------------------------------------------------------
508 * read the terminal pty and write log
510 void pkgDPkgPM::DoTerminalPty(int master
)
512 unsigned char term_buf
[1024] = {0,0, };
514 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
515 if(len
== -1 && errno
== EIO
)
517 // this happens when the child is about to exit, we
518 // give it time to actually exit, otherwise we run
519 // into a race so we sleep for half a second.
520 struct timespec sleepfor
= { 0, 500000000 };
521 nanosleep(&sleepfor
, NULL
);
526 FileFd::Write(1, term_buf
, len
);
528 fwrite(term_buf
, len
, sizeof(char), d
->term_out
);
531 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
532 // ---------------------------------------------------------------------
535 void pkgDPkgPM::ProcessDpkgStatusLine(char *line
)
537 bool const Debug
= _config
->FindB("Debug::pkgDPkgProgressReporting",false);
539 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
541 /* dpkg sends strings like this:
542 'status: <pkg>: <pkg qstate>'
543 'status: <pkg>:<arch>: <pkg qstate>'
545 'processing: {install,configure,remove,purge,disappear,trigproc}: pkg'
546 'processing: {install,configure,remove,purge,disappear,trigproc}: trigger'
549 // we need to split on ": " (note the appended space) as the ':' is
550 // part of the pkgname:arch information that dpkg sends
552 // A dpkg error message may contain additional ":" (like
553 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
554 // so we need to ensure to not split too much
555 std::vector
<std::string
> list
= StringSplit(line
, ": ", 4);
559 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
563 // build the (prefix, pkgname, action) tuple, position of this
564 // is different for "processing" or "status" messages
565 std::string prefix
= APT::String::Strip(list
[0]);
568 ostringstream status
;
570 // "processing" has the form "processing: action: pkg or trigger"
571 // with action = ["install", "configure", "remove", "purge", "disappear",
573 if (prefix
== "processing")
575 pkgname
= APT::String::Strip(list
[2]);
576 action
= APT::String::Strip(list
[1]);
578 // "status" has the form: "status: pkg: state"
579 // with state in ["half-installed", "unpacked", "half-configured",
580 // "installed", "config-files", "not-installed"]
581 else if (prefix
== "status")
583 pkgname
= APT::String::Strip(list
[1]);
584 action
= APT::String::Strip(list
[2]);
587 std::clog
<< "unknown prefix '" << prefix
<< "'" << std::endl
;
592 /* handle the special cases first:
594 errors look like this:
595 '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
596 and conffile-prompt like this
597 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
599 if (prefix
== "status")
601 if(action
== "error")
603 d
->progress
->Error(list
[1], PackagesDone
, PackagesTotal
,
606 WriteApportReport(list
[1].c_str(), list
[3].c_str());
609 else if(action
== "conffile")
611 d
->progress
->ConffilePrompt(list
[1], PackagesDone
, PackagesTotal
,
617 // at this point we know that we should have a valid pkgname, so build all
620 // dpkg does not send always send "pkgname:arch" so we add it here
622 if (pkgname
.find(":") == std::string::npos
)
624 // find the package in the group that is in a touched by dpkg
625 // if there are multiple dpkg will send us a full pkgname:arch
626 pkgCache::GrpIterator Grp
= Cache
.FindGrp(pkgname
);
627 if (Grp
.end() == false)
629 pkgCache::PkgIterator P
= Grp
.PackageList();
630 for (; P
.end() != true; P
= Grp
.NextPkg(P
))
632 if(Cache
[P
].Mode
!= pkgDepCache::ModeKeep
)
634 pkgname
= P
.FullName();
641 const char* const pkg
= pkgname
.c_str();
642 std::string short_pkgname
= StringSplit(pkgname
, ":")[0];
643 std::string arch
= "";
644 if (pkgname
.find(":") != string::npos
)
645 arch
= StringSplit(pkgname
, ":")[1];
646 std::string i18n_pkgname
= pkgname
;
647 if (arch
.size() != 0)
648 strprintf(i18n_pkgname
, "%s (%s)", short_pkgname
.c_str(), arch
.c_str());
650 // 'processing' from dpkg looks like
651 // 'processing: action: pkg'
652 if(prefix
== "processing")
654 const std::pair
<const char *, const char *> * const iter
=
655 std::find_if(PackageProcessingOpsBegin
,
656 PackageProcessingOpsEnd
,
657 MatchProcessingOp(action
.c_str()));
658 if(iter
== PackageProcessingOpsEnd
)
661 std::clog
<< "ignoring unknown action: " << action
<< std::endl
;
665 strprintf(msg
, _(iter
->second
), i18n_pkgname
.c_str());
666 d
->progress
->StatusChanged(pkgname
, PackagesDone
, PackagesTotal
, msg
);
668 // FIXME: this needs a muliarch testcase
669 // FIXME2: is "pkgname" here reliable with dpkg only sending us
671 if (action
== "disappear")
672 handleDisappearAction(pkgname
);
676 if (prefix
== "status")
678 vector
<struct DpkgState
> const &states
= PackageOps
[pkg
];
679 const char *next_action
= NULL
;
680 if(PackageOpsDone
[pkg
] < states
.size())
681 next_action
= states
[PackageOpsDone
[pkg
]].state
;
682 // check if the package moved to the next dpkg state
683 if(next_action
&& (action
== next_action
))
685 // only read the translation if there is actually a next
687 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
690 // we moved from one dpkg state to a new one, report that
691 PackageOpsDone
[pkg
]++;
694 strprintf(msg
, translation
, i18n_pkgname
.c_str());
695 d
->progress
->StatusChanged(pkgname
, PackagesDone
, PackagesTotal
, msg
);
699 std::clog
<< "(parsed from dpkg) pkg: " << short_pkgname
700 << " action: " << action
<< endl
;
704 // DPkgPM::handleDisappearAction /*{{{*/
705 void pkgDPkgPM::handleDisappearAction(string
const &pkgname
)
707 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
708 if (unlikely(Pkg
.end() == true))
711 // record the package name for display and stuff later
712 disappearedPkgs
.insert(Pkg
.FullName(true));
714 // the disappeared package was auto-installed - nothing to do
715 if ((Cache
[Pkg
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
717 pkgCache::VerIterator PkgVer
= Cache
[Pkg
].InstVerIter(Cache
);
718 if (unlikely(PkgVer
.end() == true))
720 /* search in the list of dependencies for (Pre)Depends,
721 check if this dependency has a Replaces on our package
722 and if so transfer the manual installed flag to it */
723 for (pkgCache::DepIterator Dep
= PkgVer
.DependsList(); Dep
.end() != true; ++Dep
)
725 if (Dep
->Type
!= pkgCache::Dep::Depends
&&
726 Dep
->Type
!= pkgCache::Dep::PreDepends
)
728 pkgCache::PkgIterator Tar
= Dep
.TargetPkg();
729 if (unlikely(Tar
.end() == true))
731 // the package is already marked as manual
732 if ((Cache
[Tar
].Flags
& pkgCache::Flag::Auto
) != pkgCache::Flag::Auto
)
734 pkgCache::VerIterator TarVer
= Cache
[Tar
].InstVerIter(Cache
);
735 if (TarVer
.end() == true)
737 for (pkgCache::DepIterator Rep
= TarVer
.DependsList(); Rep
.end() != true; ++Rep
)
739 if (Rep
->Type
!= pkgCache::Dep::Replaces
)
741 if (Pkg
!= Rep
.TargetPkg())
743 // okay, they are strongly connected - transfer manual-bit
745 std::clog
<< "transfer manual-bit from disappeared »" << pkgname
<< "« to »" << Tar
.FullName() << "«" << std::endl
;
746 Cache
[Tar
].Flags
&= ~Flag::Auto
;
752 // DPkgPM::DoDpkgStatusFd /*{{{*/
753 // ---------------------------------------------------------------------
756 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
)
761 len
=read(statusfd
, &d
->dpkgbuf
[d
->dpkgbuf_pos
], sizeof(d
->dpkgbuf
)-d
->dpkgbuf_pos
);
762 d
->dpkgbuf_pos
+= len
;
766 // process line by line if we have a buffer
768 while((q
=(char*)memchr(p
, '\n', d
->dpkgbuf
+d
->dpkgbuf_pos
-p
)) != NULL
)
771 ProcessDpkgStatusLine(p
);
772 p
=q
+1; // continue with next line
775 // now move the unprocessed bits (after the final \n that is now a 0x0)
776 // to the start and update d->dpkgbuf_pos
777 p
= (char*)memrchr(d
->dpkgbuf
, 0, d
->dpkgbuf_pos
);
781 // we are interessted in the first char *after* 0x0
784 // move the unprocessed tail to the start and update pos
785 memmove(d
->dpkgbuf
, p
, p
-d
->dpkgbuf
);
786 d
->dpkgbuf_pos
= d
->dpkgbuf
+d
->dpkgbuf_pos
-p
;
789 // DPkgPM::WriteHistoryTag /*{{{*/
790 void pkgDPkgPM::WriteHistoryTag(string
const &tag
, string value
)
792 size_t const length
= value
.length();
795 // poor mans rstrip(", ")
796 if (value
[length
-2] == ',' && value
[length
-1] == ' ')
797 value
.erase(length
- 2, 2);
798 fprintf(d
->history_out
, "%s: %s\n", tag
.c_str(), value
.c_str());
800 // DPkgPM::OpenLog /*{{{*/
801 bool pkgDPkgPM::OpenLog()
803 string
const logdir
= _config
->FindDir("Dir::Log");
804 if(CreateAPTDirectoryIfNeeded(logdir
, logdir
) == false)
805 // FIXME: use a better string after freeze
806 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
810 time_t const t
= time(NULL
);
811 struct tm
const * const tmp
= localtime(&t
);
812 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
815 string
const logfile_name
= flCombine(logdir
,
816 _config
->Find("Dir::Log::Terminal"));
817 if (!logfile_name
.empty())
819 d
->term_out
= fopen(logfile_name
.c_str(),"a");
820 if (d
->term_out
== NULL
)
821 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name
.c_str());
822 setvbuf(d
->term_out
, NULL
, _IONBF
, 0);
823 SetCloseExec(fileno(d
->term_out
), true);
824 if (getuid() == 0) // if we aren't root, we can't chown a file, so don't try it
826 struct passwd
*pw
= getpwnam("root");
827 struct group
*gr
= getgrnam("adm");
828 if (pw
!= NULL
&& gr
!= NULL
&& chown(logfile_name
.c_str(), pw
->pw_uid
, gr
->gr_gid
) != 0)
829 _error
->WarningE("OpenLog", "chown to root:adm of file %s failed", logfile_name
.c_str());
831 if (chmod(logfile_name
.c_str(), 0640) != 0)
832 _error
->WarningE("OpenLog", "chmod 0640 of file %s failed", logfile_name
.c_str());
833 fprintf(d
->term_out
, "\nLog started: %s\n", timestr
);
836 // write your history
837 string
const history_name
= flCombine(logdir
,
838 _config
->Find("Dir::Log::History"));
839 if (!history_name
.empty())
841 d
->history_out
= fopen(history_name
.c_str(),"a");
842 if (d
->history_out
== NULL
)
843 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), history_name
.c_str());
844 SetCloseExec(fileno(d
->history_out
), true);
845 chmod(history_name
.c_str(), 0644);
846 fprintf(d
->history_out
, "\nStart-Date: %s\n", timestr
);
847 string remove
, purge
, install
, reinstall
, upgrade
, downgrade
;
848 for (pkgCache::PkgIterator I
= Cache
.PkgBegin(); I
.end() == false; ++I
)
850 enum { CANDIDATE
, CANDIDATE_AUTO
, CURRENT_CANDIDATE
, CURRENT
} infostring
;
852 #define HISTORYINFO(X, Y) { line = &X; infostring = Y; }
853 if (Cache
[I
].NewInstall() == true)
854 HISTORYINFO(install
, CANDIDATE_AUTO
)
855 else if (Cache
[I
].ReInstall() == true)
856 HISTORYINFO(reinstall
, CANDIDATE
)
857 else if (Cache
[I
].Upgrade() == true)
858 HISTORYINFO(upgrade
, CURRENT_CANDIDATE
)
859 else if (Cache
[I
].Downgrade() == true)
860 HISTORYINFO(downgrade
, CURRENT_CANDIDATE
)
861 else if (Cache
[I
].Delete() == true)
862 HISTORYINFO((Cache
[I
].Purge() ? purge
: remove
), CURRENT
)
866 line
->append(I
.FullName(false)).append(" (");
867 switch (infostring
) {
868 case CANDIDATE
: line
->append(Cache
[I
].CandVersion
); break;
870 line
->append(Cache
[I
].CandVersion
);
871 if ((Cache
[I
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
872 line
->append(", automatic");
874 case CURRENT_CANDIDATE
: line
->append(Cache
[I
].CurVersion
).append(", ").append(Cache
[I
].CandVersion
); break;
875 case CURRENT
: line
->append(Cache
[I
].CurVersion
); break;
879 if (_config
->Exists("Commandline::AsString") == true)
880 WriteHistoryTag("Commandline", _config
->Find("Commandline::AsString"));
881 WriteHistoryTag("Install", install
);
882 WriteHistoryTag("Reinstall", reinstall
);
883 WriteHistoryTag("Upgrade", upgrade
);
884 WriteHistoryTag("Downgrade",downgrade
);
885 WriteHistoryTag("Remove",remove
);
886 WriteHistoryTag("Purge",purge
);
887 fflush(d
->history_out
);
893 // DPkg::CloseLog /*{{{*/
894 bool pkgDPkgPM::CloseLog()
897 time_t t
= time(NULL
);
898 struct tm
*tmp
= localtime(&t
);
899 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
903 fprintf(d
->term_out
, "Log ended: ");
904 fprintf(d
->term_out
, "%s", timestr
);
905 fprintf(d
->term_out
, "\n");
912 if (disappearedPkgs
.empty() == false)
915 for (std::set
<std::string
>::const_iterator d
= disappearedPkgs
.begin();
916 d
!= disappearedPkgs
.end(); ++d
)
918 pkgCache::PkgIterator P
= Cache
.FindPkg(*d
);
919 disappear
.append(*d
);
921 disappear
.append(", ");
923 disappear
.append(" (").append(Cache
[P
].CurVersion
).append("), ");
925 WriteHistoryTag("Disappeared", disappear
);
927 if (d
->dpkg_error
.empty() == false)
928 fprintf(d
->history_out
, "Error: %s\n", d
->dpkg_error
.c_str());
929 fprintf(d
->history_out
, "End-Date: %s\n", timestr
);
930 fclose(d
->history_out
);
932 d
->history_out
= NULL
;
939 // This implements a racy version of pselect for those architectures
940 // that don't have a working implementation.
941 // FIXME: Probably can be removed on Lenny+1
942 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
943 fd_set
*exceptfds
, const struct timespec
*timeout
,
944 const sigset_t
*sigmask
)
950 tv
.tv_sec
= timeout
->tv_sec
;
951 tv
.tv_usec
= timeout
->tv_nsec
/1000;
953 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
954 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
955 sigprocmask(SIG_SETMASK
, &origmask
, 0);
960 // DPkgPM::BuildPackagesProgressMap /*{{{*/
961 void pkgDPkgPM::BuildPackagesProgressMap()
963 // map the dpkg states to the operations that are performed
964 // (this is sorted in the same way as Item::Ops)
965 static const struct DpkgState DpkgStatesOpMap
[][7] = {
968 {"half-installed", N_("Preparing %s")},
969 {"unpacked", N_("Unpacking %s") },
972 // Configure operation
974 {"unpacked",N_("Preparing to configure %s") },
975 {"half-configured", N_("Configuring %s") },
976 { "installed", N_("Installed %s")},
981 {"half-configured", N_("Preparing for removal of %s")},
982 {"half-installed", N_("Removing %s")},
983 {"config-files", N_("Removed %s")},
988 {"config-files", N_("Preparing to completely remove %s")},
989 {"not-installed", N_("Completely removed %s")},
994 // init the PackageOps map, go over the list of packages that
995 // that will be [installed|configured|removed|purged] and add
996 // them to the PackageOps map (the dpkg states it goes through)
997 // and the PackageOpsTranslations (human readable strings)
998 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end(); ++I
)
1000 if((*I
).Pkg
.end() == true)
1003 string
const name
= (*I
).Pkg
.FullName();
1004 PackageOpsDone
[name
] = 0;
1005 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; ++i
)
1007 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
1013 #if (APT_PKG_MAJOR >= 4 && APT_PKG_MINOR < 13)
1014 bool pkgDPkgPM::Go(int StatusFd
)
1016 APT::Progress::PackageManager
*progress
= NULL
;
1018 progress
= APT::Progress::PackageManagerProgressFactory();
1020 progress
= new APT::Progress::PackageManagerProgressFd(StatusFd
);
1022 return GoNoABIBreak(progress
);
1026 void pkgDPkgPM::StartPtyMagic()
1028 // setup the pty and stuff
1031 // if tcgetattr does not return zero there was a error
1032 // and we do not do any pty magic
1033 _error
->PushToStack();
1034 if (tcgetattr(STDOUT_FILENO
, &d
->tt
) == 0)
1036 ioctl(1, TIOCGWINSZ
, (char *)&win
);
1037 if (openpty(&d
->master
, &d
->slave
, NULL
, &d
->tt
, &win
) < 0)
1039 _error
->Errno("openpty", _("Can not write log (%s)"), _("Is /dev/pts mounted?"));
1040 d
->master
= d
->slave
= -1;
1045 rtt
.c_lflag
&= ~ECHO
;
1046 rtt
.c_lflag
|= ISIG
;
1047 // block SIGTTOU during tcsetattr to prevent a hang if
1048 // the process is a member of the background process group
1049 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
1050 sigemptyset(&d
->sigmask
);
1051 sigaddset(&d
->sigmask
, SIGTTOU
);
1052 sigprocmask(SIG_BLOCK
,&d
->sigmask
, &d
->original_sigmask
);
1053 tcsetattr(0, TCSAFLUSH
, &rtt
);
1054 sigprocmask(SIG_SETMASK
, &d
->original_sigmask
, 0);
1057 // complain only if stdout is either a terminal (but still failed) or is an invalid
1058 // descriptor otherwise we would complain about redirection to e.g. /dev/null as well.
1059 else if (isatty(STDOUT_FILENO
) == 1 || errno
== EBADF
)
1060 _error
->Errno("tcgetattr", _("Can not write log (%s)"), _("Is stdout a terminal?"));
1062 if (_error
->PendingError() == true)
1063 _error
->DumpErrors(std::cerr
);
1064 _error
->RevertToStack();
1067 void pkgDPkgPM::StopPtyMagic()
1073 tcsetattr(0, TCSAFLUSH
, &d
->tt
);
1078 // DPkgPM::Go - Run the sequence /*{{{*/
1079 // ---------------------------------------------------------------------
1080 /* This globs the operations and calls dpkg
1082 * If it is called with a progress object apt will report the install
1083 * progress to this object. It maps the dpkg states a package goes
1084 * through to human readable (and i10n-able)
1085 * names and calculates a percentage for each step.
1087 #if (APT_PKG_MAJOR >= 4 && APT_PKG_MINOR >= 13)
1088 bool pkgDPkgPM::Go(APT::Progress::PackageManager
*progress
)
1090 bool pkgDPkgPM::GoNoABIBreak(APT::Progress::PackageManager
*progress
)
1093 pkgPackageManager::SigINTStop
= false;
1094 d
->progress
= progress
;
1096 // Generate the base argument list for dpkg
1097 unsigned long StartSize
= 0;
1098 std::vector
<const char *> Args
;
1099 std::string DpkgExecutable
= getDpkgExecutable();
1100 Args
.push_back(DpkgExecutable
.c_str());
1101 StartSize
+= DpkgExecutable
.length();
1103 // Stick in any custom dpkg options
1104 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
1108 for (; Opts
!= 0; Opts
= Opts
->Next
)
1110 if (Opts
->Value
.empty() == true)
1112 Args
.push_back(Opts
->Value
.c_str());
1113 StartSize
+= Opts
->Value
.length();
1117 size_t const BaseArgs
= Args
.size();
1118 // we need to detect if we can qualify packages with the architecture or not
1119 Args
.push_back("--assert-multi-arch");
1120 Args
.push_back(NULL
);
1122 pid_t dpkgAssertMultiArch
= ExecFork();
1123 if (dpkgAssertMultiArch
== 0)
1125 dpkgChrootDirectory();
1126 // redirect everything to the ultimate sink as we only need the exit-status
1127 int const nullfd
= open("/dev/null", O_RDONLY
);
1128 dup2(nullfd
, STDIN_FILENO
);
1129 dup2(nullfd
, STDOUT_FILENO
);
1130 dup2(nullfd
, STDERR_FILENO
);
1131 execvp(Args
[0], (char**) &Args
[0]);
1132 _error
->WarningE("dpkgGo", "Can't detect if dpkg supports multi-arch!");
1139 unsigned int const MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
1140 unsigned int const MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
1141 bool const NoTriggers
= _config
->FindB("DPkg::NoTriggers", false);
1143 if (RunScripts("DPkg::Pre-Invoke") == false)
1146 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
1149 // support subpressing of triggers processing for special
1150 // cases like d-i that runs the triggers handling manually
1151 bool const SmartConf
= (_config
->Find("PackageManager::Configure", "all") != "all");
1152 bool const TriggersPending
= _config
->FindB("DPkg::TriggersPending", false);
1153 if (_config
->FindB("DPkg::ConfigurePending", SmartConf
) == true)
1154 List
.push_back(Item(Item::ConfigurePending
, PkgIterator()));
1157 BuildPackagesProgressMap();
1159 d
->stdin_is_dev_null
= false;
1164 bool dpkgMultiArch
= false;
1165 if (dpkgAssertMultiArch
> 0)
1168 while (waitpid(dpkgAssertMultiArch
, &Status
, 0) != dpkgAssertMultiArch
)
1172 _error
->WarningE("dpkgGo", _("Waited for %s but it wasn't there"), "dpkg --assert-multi-arch");
1175 if (WIFEXITED(Status
) == true && WEXITSTATUS(Status
) == 0)
1176 dpkgMultiArch
= true;
1179 // start pty magic before the loop
1182 // Tell the progress that its starting and fork dpkg
1183 d
->progress
->Start();
1185 // this loop is runs once per dpkg operation
1186 vector
<Item
>::const_iterator I
= List
.begin();
1187 while (I
!= List
.end())
1189 // Do all actions with the same Op in one run
1190 vector
<Item
>::const_iterator J
= I
;
1191 if (TriggersPending
== true)
1192 for (; J
!= List
.end(); ++J
)
1196 if (J
->Op
!= Item::TriggersPending
)
1198 vector
<Item
>::const_iterator T
= J
+ 1;
1199 if (T
!= List
.end() && T
->Op
== I
->Op
)
1204 for (; J
!= List
.end() && J
->Op
== I
->Op
; ++J
)
1207 // keep track of allocated strings for multiarch package names
1208 std::vector
<char *> Packages
;
1210 // start with the baseset of arguments
1211 unsigned long Size
= StartSize
;
1212 Args
.erase(Args
.begin() + BaseArgs
, Args
.end());
1214 // Now check if we are within the MaxArgs limit
1216 // this code below is problematic, because it may happen that
1217 // the argument list is split in a way that A depends on B
1218 // and they are in the same "--configure A B" run
1219 // - with the split they may now be configured in different
1220 // runs, using Immediate-Configure-All can help prevent this.
1221 if (J
- I
> (signed)MaxArgs
)
1224 unsigned long const size
= MaxArgs
+ 10;
1226 Packages
.reserve(size
);
1230 unsigned long const size
= (J
- I
) + 10;
1232 Packages
.reserve(size
);
1237 return _error
->Errno("pipe","Failed to create IPC pipe to dpkg");
1239 #define ADDARG(X) Args.push_back(X); Size += strlen(X)
1240 #define ADDARGC(X) Args.push_back(X); Size += sizeof(X) - 1
1242 ADDARGC("--status-fd");
1243 char status_fd_buf
[20];
1244 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
1245 ADDARG(status_fd_buf
);
1246 unsigned long const Op
= I
->Op
;
1251 ADDARGC("--force-depends");
1252 ADDARGC("--force-remove-essential");
1253 ADDARGC("--remove");
1257 ADDARGC("--force-depends");
1258 ADDARGC("--force-remove-essential");
1262 case Item::Configure
:
1263 ADDARGC("--configure");
1266 case Item::ConfigurePending
:
1267 ADDARGC("--configure");
1268 ADDARGC("--pending");
1271 case Item::TriggersPending
:
1272 ADDARGC("--triggers-only");
1273 ADDARGC("--pending");
1277 ADDARGC("--unpack");
1278 ADDARGC("--auto-deconfigure");
1282 if (NoTriggers
== true && I
->Op
!= Item::TriggersPending
&&
1283 I
->Op
!= Item::ConfigurePending
)
1285 ADDARGC("--no-triggers");
1289 // Write in the file or package names
1290 if (I
->Op
== Item::Install
)
1292 for (;I
!= J
&& Size
< MaxArgBytes
; ++I
)
1294 if (I
->File
[0] != '/')
1295 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
1296 Args
.push_back(I
->File
.c_str());
1297 Size
+= I
->File
.length();
1302 string
const nativeArch
= _config
->Find("APT::Architecture");
1303 unsigned long const oldSize
= I
->Op
== Item::Configure
? Size
: 0;
1304 for (;I
!= J
&& Size
< MaxArgBytes
; ++I
)
1306 if((*I
).Pkg
.end() == true)
1308 if (I
->Op
== Item::Configure
&& disappearedPkgs
.find(I
->Pkg
.FullName(true)) != disappearedPkgs
.end())
1310 // We keep this here to allow "smooth" transitions from e.g. multiarch dpkg/ubuntu to dpkg/debian
1311 if (dpkgMultiArch
== false && (I
->Pkg
.Arch() == nativeArch
||
1312 strcmp(I
->Pkg
.Arch(), "all") == 0 ||
1313 strcmp(I
->Pkg
.Arch(), "none") == 0))
1315 char const * const name
= I
->Pkg
.Name();
1320 pkgCache::VerIterator PkgVer
;
1321 std::string name
= I
->Pkg
.Name();
1322 if (Op
== Item::Remove
|| Op
== Item::Purge
)
1324 PkgVer
= I
->Pkg
.CurrentVer();
1325 if(PkgVer
.end() == true)
1326 PkgVer
= FindNowVersion(I
->Pkg
);
1329 PkgVer
= Cache
[I
->Pkg
].InstVerIter(Cache
);
1330 if (strcmp(I
->Pkg
.Arch(), "none") == 0)
1331 ; // never arch-qualify a package without an arch
1332 else if (PkgVer
.end() == false)
1333 name
.append(":").append(PkgVer
.Arch());
1335 _error
->Warning("Can not find PkgVer for '%s'", name
.c_str());
1336 char * const fullname
= strdup(name
.c_str());
1337 Packages
.push_back(fullname
);
1341 // skip configure action if all sheduled packages disappeared
1342 if (oldSize
== Size
)
1349 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
1351 for (std::vector
<const char *>::const_iterator a
= Args
.begin();
1352 a
!= Args
.end(); ++a
)
1357 Args
.push_back(NULL
);
1363 /* Mask off sig int/quit. We do this because dpkg also does when
1364 it forks scripts. What happens is that when you hit ctrl-c it sends
1365 it to all processes in the group. Since dpkg ignores the signal
1366 it doesn't die but we do! So we must also ignore it */
1367 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
1368 sighandler_t old_SIGINT
= signal(SIGINT
,SigINT
);
1370 // Check here for any SIGINT
1371 if (pkgPackageManager::SigINTStop
&& (Op
== Item::Remove
|| Op
== Item::Purge
|| Op
== Item::Install
))
1375 // ignore SIGHUP as well (debian #463030)
1376 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
1378 pid_t Child
= ExecFork();
1379 // This is the child
1383 if(d
->slave
>= 0 && d
->master
>= 0)
1386 ioctl(d
->slave
, TIOCSCTTY
, 0);
1393 close(fd
[0]); // close the read end of the pipe
1395 dpkgChrootDirectory();
1397 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
1400 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
1403 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
1406 // Discard everything in stdin before forking dpkg
1407 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
1410 while (read(STDIN_FILENO
,&dummy
,1) == 1);
1412 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
1416 /* No Job Control Stop Env is a magic dpkg var that prevents it
1417 from using sigstop */
1418 putenv((char *)"DPKG_NO_TSTP=yes");
1419 execvp(Args
[0], (char**) &Args
[0]);
1420 cerr
<< "Could not exec dpkg!" << endl
;
1425 if (_config
->FindB("DPkg::UseIoNice", false) == true)
1428 // clear the Keep-Fd again
1429 _config
->Clear("APT::Keep-Fds",fd
[1]);
1434 // we read from dpkg here
1435 int const _dpkgin
= fd
[0];
1436 close(fd
[1]); // close the write end of the pipe
1439 sigemptyset(&d
->sigmask
);
1440 sigprocmask(SIG_BLOCK
,&d
->sigmask
,&d
->original_sigmask
);
1442 /* free vectors (and therefore memory) as we don't need the included data anymore */
1443 for (std::vector
<char *>::const_iterator p
= Packages
.begin();
1444 p
!= Packages
.end(); ++p
)
1448 // the result of the waitpid call
1451 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
1453 // FIXME: move this to a function or something, looks ugly here
1454 // error handling, waitpid returned -1
1457 RunScripts("DPkg::Post-Invoke");
1459 // Restore sig int/quit
1460 signal(SIGQUIT
,old_SIGQUIT
);
1461 signal(SIGINT
,old_SIGINT
);
1463 signal(SIGHUP
,old_SIGHUP
);
1464 return _error
->Errno("waitpid","Couldn't wait for subprocess");
1467 // wait for input or output here
1469 if (d
->master
>= 0 && !d
->stdin_is_dev_null
)
1471 FD_SET(_dpkgin
, &rfds
);
1473 FD_SET(d
->master
, &rfds
);
1476 select_ret
= pselect(max(d
->master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
1477 &tv
, &d
->original_sigmask
);
1478 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
1479 select_ret
= racy_pselect(max(d
->master
, _dpkgin
)+1, &rfds
, NULL
,
1480 NULL
, &tv
, &d
->original_sigmask
);
1481 if (select_ret
== 0)
1483 else if (select_ret
< 0 && errno
== EINTR
)
1485 else if (select_ret
< 0)
1487 perror("select() returned error");
1491 if(d
->master
>= 0 && FD_ISSET(d
->master
, &rfds
))
1492 DoTerminalPty(d
->master
);
1493 if(d
->master
>= 0 && FD_ISSET(0, &rfds
))
1495 if(FD_ISSET(_dpkgin
, &rfds
))
1496 DoDpkgStatusFd(_dpkgin
);
1500 // Restore sig int/quit
1501 signal(SIGQUIT
,old_SIGQUIT
);
1502 signal(SIGINT
,old_SIGINT
);
1504 signal(SIGHUP
,old_SIGHUP
);
1505 // Check for an error code.
1506 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
1508 // if it was set to "keep-dpkg-runing" then we won't return
1509 // here but keep the loop going and just report it as a error
1511 bool const stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
1514 RunScripts("DPkg::Post-Invoke");
1516 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
1517 strprintf(d
->dpkg_error
, "Sub-process %s received a segmentation fault.",Args
[0]);
1518 else if (WIFEXITED(Status
) != 0)
1519 strprintf(d
->dpkg_error
, "Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
1521 strprintf(d
->dpkg_error
, "Sub-process %s exited unexpectedly",Args
[0]);
1523 if(d
->dpkg_error
.size() > 0)
1524 _error
->Error("%s", d
->dpkg_error
.c_str());
1529 d
->progress
->Stop();
1534 // dpkg is done at this point
1535 d
->progress
->Stop();
1539 if (pkgPackageManager::SigINTStop
)
1540 _error
->Warning(_("Operation was interrupted before it could finish"));
1542 if (RunScripts("DPkg::Post-Invoke") == false)
1545 if (_config
->FindB("Debug::pkgDPkgPM",false) == false)
1547 std::string
const oldpkgcache
= _config
->FindFile("Dir::cache::pkgcache");
1548 if (oldpkgcache
.empty() == false && RealFileExists(oldpkgcache
) == true &&
1549 unlink(oldpkgcache
.c_str()) == 0)
1551 std::string
const srcpkgcache
= _config
->FindFile("Dir::cache::srcpkgcache");
1552 if (srcpkgcache
.empty() == false && RealFileExists(srcpkgcache
) == true)
1554 _error
->PushToStack();
1555 pkgCacheFile CacheFile
;
1556 CacheFile
.BuildCaches(NULL
, true);
1557 _error
->RevertToStack();
1562 Cache
.writeStateFile(NULL
);
1566 void SigINT(int sig
) {
1567 pkgPackageManager::SigINTStop
= true;
1570 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1571 // ---------------------------------------------------------------------
1573 void pkgDPkgPM::Reset()
1575 List
.erase(List
.begin(),List
.end());
1578 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1579 // ---------------------------------------------------------------------
1581 void pkgDPkgPM::WriteApportReport(const char *pkgpath
, const char *errormsg
)
1583 // If apport doesn't exist or isn't installed do nothing
1584 // This e.g. prevents messages in 'universes' without apport
1585 pkgCache::PkgIterator apportPkg
= Cache
.FindPkg("apport");
1586 if (apportPkg
.end() == true || apportPkg
->CurrentVer
== 0)
1589 string pkgname
, reportfile
, srcpkgname
, pkgver
, arch
;
1590 string::size_type pos
;
1593 if (_config
->FindB("Dpkg::ApportFailureReport", false) == false)
1595 std::clog
<< "configured to not write apport reports" << std::endl
;
1599 // only report the first errors
1600 if(pkgFailures
> _config
->FindI("APT::Apport::MaxReports", 3))
1602 std::clog
<< _("No apport report written because MaxReports is reached already") << std::endl
;
1606 // check if its not a follow up error
1607 const char *needle
= dgettext("dpkg", "dependency problems - leaving unconfigured");
1608 if(strstr(errormsg
, needle
) != NULL
) {
1609 std::clog
<< _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl
;
1613 // do not report disk-full failures
1614 if(strstr(errormsg
, strerror(ENOSPC
)) != NULL
) {
1615 std::clog
<< _("No apport report written because the error message indicates a disk full error") << std::endl
;
1619 // do not report out-of-memory failures
1620 if(strstr(errormsg
, strerror(ENOMEM
)) != NULL
) {
1621 std::clog
<< _("No apport report written because the error message indicates a out of memory error") << std::endl
;
1625 // do not report dpkg I/O errors
1626 // XXX - this message is localized, but this only matches the English version. This is better than nothing.
1627 if(strstr(errormsg
, "short read in buffer_copy (")) {
1628 std::clog
<< _("No apport report written because the error message indicates a dpkg I/O error") << std::endl
;
1632 // get the pkgname and reportfile
1633 pkgname
= flNotDir(pkgpath
);
1634 pos
= pkgname
.find('_');
1635 if(pos
!= string::npos
)
1636 pkgname
= pkgname
.substr(0, pos
);
1638 // find the package versin and source package name
1639 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
1640 if (Pkg
.end() == true)
1642 pkgCache::VerIterator Ver
= Cache
.GetCandidateVer(Pkg
);
1643 if (Ver
.end() == true)
1645 pkgver
= Ver
.VerStr() == NULL
? "unknown" : Ver
.VerStr();
1646 pkgRecords
Recs(Cache
);
1647 pkgRecords::Parser
&Parse
= Recs
.Lookup(Ver
.FileList());
1648 srcpkgname
= Parse
.SourcePkg();
1649 if(srcpkgname
.empty())
1650 srcpkgname
= pkgname
;
1652 // if the file exists already, we check:
1653 // - if it was reported already (touched by apport).
1654 // If not, we do nothing, otherwise
1655 // we overwrite it. This is the same behaviour as apport
1656 // - if we have a report with the same pkgversion already
1658 reportfile
= flCombine("/var/crash",pkgname
+".0.crash");
1659 if(FileExists(reportfile
))
1664 // check atime/mtime
1665 stat(reportfile
.c_str(), &buf
);
1666 if(buf
.st_mtime
> buf
.st_atime
)
1669 // check if the existing report is the same version
1670 report
= fopen(reportfile
.c_str(),"r");
1671 while(fgets(strbuf
, sizeof(strbuf
), report
) != NULL
)
1673 if(strstr(strbuf
,"Package:") == strbuf
)
1675 char pkgname
[255], version
[255];
1676 if(sscanf(strbuf
, "Package: %254s %254s", pkgname
, version
) == 2)
1677 if(strcmp(pkgver
.c_str(), version
) == 0)
1687 // now write the report
1688 arch
= _config
->Find("APT::Architecture");
1689 report
= fopen(reportfile
.c_str(),"w");
1692 if(_config
->FindB("DPkgPM::InitialReportOnly",false) == true)
1693 chmod(reportfile
.c_str(), 0);
1695 chmod(reportfile
.c_str(), 0600);
1696 fprintf(report
, "ProblemType: Package\n");
1697 fprintf(report
, "Architecture: %s\n", arch
.c_str());
1698 time_t now
= time(NULL
);
1699 fprintf(report
, "Date: %s" , ctime(&now
));
1700 fprintf(report
, "Package: %s %s\n", pkgname
.c_str(), pkgver
.c_str());
1701 fprintf(report
, "SourcePackage: %s\n", srcpkgname
.c_str());
1702 fprintf(report
, "ErrorMessage:\n %s\n", errormsg
);
1704 // ensure that the log is flushed
1706 fflush(d
->term_out
);
1708 // attach terminal log it if we have it
1709 string logfile_name
= _config
->FindFile("Dir::Log::Terminal");
1710 if (!logfile_name
.empty())
1714 fprintf(report
, "DpkgTerminalLog:\n");
1715 log
= fopen(logfile_name
.c_str(),"r");
1719 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1720 fprintf(report
, " %s", buf
);
1726 const char *ops_str
[] = {"Install", "Configure","Remove","Purge"};
1727 fprintf(report
, "AptOrdering:\n");
1728 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
1729 if ((*I
).Pkg
!= NULL
)
1730 fprintf(report
, " %s: %s\n", (*I
).Pkg
.Name(), ops_str
[(*I
).Op
]);
1732 fprintf(report
, " %s: %s\n", "NULL", ops_str
[(*I
).Op
]);
1734 // attach dmesg log (to learn about segfaults)
1735 if (FileExists("/bin/dmesg"))
1737 fprintf(report
, "Dmesg:\n");
1738 FILE *log
= popen("/bin/dmesg","r");
1742 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1743 fprintf(report
, " %s", buf
);
1748 // attach df -l log (to learn about filesystem status)
1749 if (FileExists("/bin/df"))
1752 fprintf(report
, "Df:\n");
1753 FILE *log
= popen("/bin/df -l","r");
1757 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1758 fprintf(report
, " %s", buf
);