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>
54 class pkgDPkgPMPrivate
57 pkgDPkgPMPrivate() : stdin_is_dev_null(false), dpkgbuf_pos(0),
58 term_out(NULL
), history_out(NULL
),
59 progress(NULL
), master(-1), slave(-1)
66 bool stdin_is_dev_null
;
67 // the buffer we use for the dpkg status-fd reading
73 APT::Progress::PackageManager
*progress
;
82 sigset_t original_sigmask
;
88 // Maps the dpkg "processing" info to human readable names. Entry 0
89 // of each array is the key, entry 1 is the value.
90 const std::pair
<const char *, const char *> PackageProcessingOps
[] = {
91 std::make_pair("install", N_("Installing %s")),
92 std::make_pair("configure", N_("Configuring %s")),
93 std::make_pair("remove", N_("Removing %s")),
94 std::make_pair("purge", N_("Completely removing %s")),
95 std::make_pair("disappear", N_("Noting disappearance of %s")),
96 std::make_pair("trigproc", N_("Running post-installation trigger %s"))
99 const std::pair
<const char *, const char *> * const PackageProcessingOpsBegin
= PackageProcessingOps
;
100 const std::pair
<const char *, const char *> * const PackageProcessingOpsEnd
= PackageProcessingOps
+ sizeof(PackageProcessingOps
) / sizeof(PackageProcessingOps
[0]);
102 // Predicate to test whether an entry in the PackageProcessingOps
103 // array matches a string.
104 class MatchProcessingOp
109 MatchProcessingOp(const char *the_target
)
114 bool operator()(const std::pair
<const char *, const char *> &pair
) const
116 return strcmp(pair
.first
, target
) == 0;
121 /* helper function to ionice the given PID
123 there is no C header for ionice yet - just the syscall interface
124 so we use the binary from util-linux
129 if (!FileExists("/usr/bin/ionice"))
131 pid_t Process
= ExecFork();
135 snprintf(buf
, sizeof(buf
), "-p%d", PID
);
137 Args
[0] = "/usr/bin/ionice";
141 execv(Args
[0], (char **)Args
);
143 return ExecWait(Process
, "ionice");
146 static std::string
getDpkgExecutable()
148 string Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
149 string
const dpkgChrootDir
= _config
->FindDir("DPkg::Chroot-Directory", "/");
150 size_t dpkgChrootLen
= dpkgChrootDir
.length();
151 if (dpkgChrootDir
!= "/" && Tmp
.find(dpkgChrootDir
) == 0)
153 if (dpkgChrootDir
[dpkgChrootLen
- 1] == '/')
155 Tmp
= Tmp
.substr(dpkgChrootLen
);
160 // dpkgChrootDirectory - chrooting for dpkg if needed /*{{{*/
161 static void dpkgChrootDirectory()
163 std::string
const chrootDir
= _config
->FindDir("DPkg::Chroot-Directory");
164 if (chrootDir
== "/")
166 std::cerr
<< "Chrooting into " << chrootDir
<< std::endl
;
167 if (chroot(chrootDir
.c_str()) != 0)
175 // FindNowVersion - Helper to find a Version in "now" state /*{{{*/
176 // ---------------------------------------------------------------------
177 /* This is helpful when a package is no longer installed but has residual
181 pkgCache::VerIterator
FindNowVersion(const pkgCache::PkgIterator
&Pkg
)
183 pkgCache::VerIterator Ver
;
184 for (Ver
= Pkg
.VersionList(); Ver
.end() == false; ++Ver
)
186 pkgCache::VerFileIterator Vf
= Ver
.FileList();
187 pkgCache::PkgFileIterator F
= Vf
.File();
188 for (F
= Vf
.File(); F
.end() == false; ++F
)
190 if (F
&& F
.Archive())
192 if (strcmp(F
.Archive(), "now"))
201 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
202 // ---------------------------------------------------------------------
204 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
205 : pkgPackageManager(Cache
), pkgFailures(0), PackagesDone(0), PackagesTotal(0)
207 d
= new pkgDPkgPMPrivate();
210 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
211 // ---------------------------------------------------------------------
213 pkgDPkgPM::~pkgDPkgPM()
218 // DPkgPM::Install - Install a package /*{{{*/
219 // ---------------------------------------------------------------------
220 /* Add an install operation to the sequence list */
221 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
223 if (File
.empty() == true || Pkg
.end() == true)
224 return _error
->Error("Internal Error, No file name for %s",Pkg
.FullName().c_str());
226 // If the filename string begins with DPkg::Chroot-Directory, return the
227 // substr that is within the chroot so dpkg can access it.
228 string
const chrootdir
= _config
->FindDir("DPkg::Chroot-Directory","/");
229 if (chrootdir
!= "/" && File
.find(chrootdir
) == 0)
231 size_t len
= chrootdir
.length();
232 if (chrootdir
.at(len
- 1) == '/')
234 List
.push_back(Item(Item::Install
,Pkg
,File
.substr(len
)));
237 List
.push_back(Item(Item::Install
,Pkg
,File
));
242 // DPkgPM::Configure - Configure a package /*{{{*/
243 // ---------------------------------------------------------------------
244 /* Add a configure operation to the sequence list */
245 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
247 if (Pkg
.end() == true)
250 List
.push_back(Item(Item::Configure
, Pkg
));
252 // Use triggers for config calls if we configure "smart"
253 // as otherwise Pre-Depends will not be satisfied, see #526774
254 if (_config
->FindB("DPkg::TriggersPending", false) == true)
255 List
.push_back(Item(Item::TriggersPending
, PkgIterator()));
260 // DPkgPM::Remove - Remove a package /*{{{*/
261 // ---------------------------------------------------------------------
262 /* Add a remove operation to the sequence list */
263 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
265 if (Pkg
.end() == true)
269 List
.push_back(Item(Item::Purge
,Pkg
));
271 List
.push_back(Item(Item::Remove
,Pkg
));
275 // DPkgPM::SendPkgInfo - Send info for install-pkgs hook /*{{{*/
276 // ---------------------------------------------------------------------
277 /* This is part of the helper script communication interface, it sends
278 very complete information down to the other end of the pipe.*/
279 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
281 return SendPkgsInfo(F
, 2);
283 bool pkgDPkgPM::SendPkgsInfo(FILE * const F
, unsigned int const &Version
)
285 // This version of APT supports only v3, so don't sent higher versions
287 fprintf(F
,"VERSION %u\n", Version
);
289 fprintf(F
,"VERSION 3\n");
291 /* Write out all of the configuration directives by walking the
292 configuration tree */
293 const Configuration::Item
*Top
= _config
->Tree(0);
296 if (Top
->Value
.empty() == false)
299 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
300 QuoteString(Top
->Value
,"\n").c_str());
309 while (Top
!= 0 && Top
->Next
== 0)
316 // Write out the package actions in order.
317 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
319 if(I
->Pkg
.end() == true)
322 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
324 fprintf(F
,"%s ",I
->Pkg
.Name());
326 // Current version which we are going to replace
327 pkgCache::VerIterator CurVer
= I
->Pkg
.CurrentVer();
328 if (CurVer
.end() == true && (I
->Op
== Item::Remove
|| I
->Op
== Item::Purge
))
329 CurVer
= FindNowVersion(I
->Pkg
);
331 if (CurVer
.end() == true)
336 fprintf(F
, "- - none ");
340 fprintf(F
, "%s ", CurVer
.VerStr());
342 fprintf(F
, "%s %s ", CurVer
.Arch(), CurVer
.MultiArchType());
345 // Show the compare operator between current and install version
346 if (S
.InstallVer
!= 0)
348 pkgCache::VerIterator
const InstVer
= S
.InstVerIter(Cache
);
350 if (CurVer
.end() == false)
351 Comp
= InstVer
.CompareVer(CurVer
);
358 fprintf(F
, "%s ", InstVer
.VerStr());
360 fprintf(F
, "%s %s ", InstVer
.Arch(), InstVer
.MultiArchType());
367 fprintf(F
, "> - - none ");
370 // Show the filename/operation
371 if (I
->Op
== Item::Install
)
374 if (I
->File
[0] != '/')
375 fprintf(F
,"**ERROR**\n");
377 fprintf(F
,"%s\n",I
->File
.c_str());
379 else if (I
->Op
== Item::Configure
)
380 fprintf(F
,"**CONFIGURE**\n");
381 else if (I
->Op
== Item::Remove
||
382 I
->Op
== Item::Purge
)
383 fprintf(F
,"**REMOVE**\n");
391 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
392 // ---------------------------------------------------------------------
393 /* This looks for a list of scripts to run from the configuration file
394 each one is run and is fed on standard input a list of all .deb files
395 that are due to be installed. */
396 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
398 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
399 if (Opts
== 0 || Opts
->Child
== 0)
403 unsigned int Count
= 1;
404 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
406 if (Opts
->Value
.empty() == true)
409 // Determine the protocol version
410 string OptSec
= Opts
->Value
;
411 string::size_type Pos
;
412 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
413 Pos
= OptSec
.length();
414 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
416 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
417 unsigned int InfoFD
= _config
->FindI(OptSec
+ "::InfoFD", STDIN_FILENO
);
420 std::set
<int> KeepFDs
;
421 MergeKeepFdsFromConfiguration(KeepFDs
);
423 if (pipe(Pipes
) != 0)
424 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
425 if (InfoFD
!= (unsigned)Pipes
[0])
426 SetCloseExec(Pipes
[0],true);
428 KeepFDs
.insert(Pipes
[0]);
431 SetCloseExec(Pipes
[1],true);
433 // Purified Fork for running the script
434 pid_t Process
= ExecFork(KeepFDs
);
438 dup2(Pipes
[0], InfoFD
);
439 SetCloseExec(STDOUT_FILENO
,false);
440 SetCloseExec(STDIN_FILENO
,false);
441 SetCloseExec(STDERR_FILENO
,false);
444 strprintf(hookfd
, "%d", InfoFD
);
445 setenv("APT_HOOK_INFO_FD", hookfd
.c_str(), 1);
447 dpkgChrootDirectory();
451 Args
[2] = Opts
->Value
.c_str();
453 execv(Args
[0],(char **)Args
);
457 FILE *F
= fdopen(Pipes
[1],"w");
459 return _error
->Errno("fdopen","Faild to open new FD");
461 // Feed it the filenames.
464 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
466 // Only deal with packages to be installed from .deb
467 if (I
->Op
!= Item::Install
)
471 if (I
->File
[0] != '/')
474 /* Feed the filename of each package that is pending install
476 fprintf(F
,"%s\n",I
->File
.c_str());
482 SendPkgsInfo(F
, Version
);
486 // Clean up the sub process
487 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
488 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
494 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
495 // ---------------------------------------------------------------------
498 void pkgDPkgPM::DoStdin(int master
)
500 unsigned char input_buf
[256] = {0,};
501 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
503 FileFd::Write(master
, input_buf
, len
);
505 d
->stdin_is_dev_null
= true;
508 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
509 // ---------------------------------------------------------------------
511 * read the terminal pty and write log
513 void pkgDPkgPM::DoTerminalPty(int master
)
515 unsigned char term_buf
[1024] = {0,0, };
517 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
518 if(len
== -1 && errno
== EIO
)
520 // this happens when the child is about to exit, we
521 // give it time to actually exit, otherwise we run
522 // into a race so we sleep for half a second.
523 struct timespec sleepfor
= { 0, 500000000 };
524 nanosleep(&sleepfor
, NULL
);
529 FileFd::Write(1, term_buf
, len
);
531 fwrite(term_buf
, len
, sizeof(char), d
->term_out
);
534 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
535 // ---------------------------------------------------------------------
538 void pkgDPkgPM::ProcessDpkgStatusLine(char *line
)
540 bool const Debug
= _config
->FindB("Debug::pkgDPkgProgressReporting",false);
542 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
544 /* dpkg sends strings like this:
545 'status: <pkg>: <pkg qstate>'
546 'status: <pkg>:<arch>: <pkg qstate>'
548 'processing: {install,configure,remove,purge,disappear,trigproc}: pkg'
549 'processing: {install,configure,remove,purge,disappear,trigproc}: trigger'
552 // we need to split on ": " (note the appended space) as the ':' is
553 // part of the pkgname:arch information that dpkg sends
555 // A dpkg error message may contain additional ":" (like
556 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
557 // so we need to ensure to not split too much
558 std::vector
<std::string
> list
= StringSplit(line
, ": ", 4);
562 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
566 // build the (prefix, pkgname, action) tuple, position of this
567 // is different for "processing" or "status" messages
568 std::string prefix
= APT::String::Strip(list
[0]);
571 ostringstream status
;
573 // "processing" has the form "processing: action: pkg or trigger"
574 // with action = ["install", "configure", "remove", "purge", "disappear",
576 if (prefix
== "processing")
578 pkgname
= APT::String::Strip(list
[2]);
579 action
= APT::String::Strip(list
[1]);
581 // "status" has the form: "status: pkg: state"
582 // with state in ["half-installed", "unpacked", "half-configured",
583 // "installed", "config-files", "not-installed"]
584 else if (prefix
== "status")
586 pkgname
= APT::String::Strip(list
[1]);
587 action
= APT::String::Strip(list
[2]);
590 std::clog
<< "unknown prefix '" << prefix
<< "'" << std::endl
;
595 /* handle the special cases first:
597 errors look like this:
598 '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
599 and conffile-prompt like this
600 'status:/etc/compiz.conf/compiz.conf : conffile-prompt: 'current-conffile' 'new-conffile' useredited distedited
602 if (prefix
== "status")
604 if(action
== "error")
606 d
->progress
->Error(list
[1], PackagesDone
, PackagesTotal
,
609 WriteApportReport(list
[1].c_str(), list
[3].c_str());
612 else if(action
== "conffile-prompt")
614 d
->progress
->ConffilePrompt(list
[1], PackagesDone
, PackagesTotal
,
620 // at this point we know that we should have a valid pkgname, so build all
623 // dpkg does not send always send "pkgname:arch" so we add it here
625 if (pkgname
.find(":") == std::string::npos
)
627 // find the package in the group that is in a touched by dpkg
628 // if there are multiple dpkg will send us a full pkgname:arch
629 pkgCache::GrpIterator Grp
= Cache
.FindGrp(pkgname
);
630 if (Grp
.end() == false)
632 pkgCache::PkgIterator P
= Grp
.PackageList();
633 for (; P
.end() != true; P
= Grp
.NextPkg(P
))
635 if(Cache
[P
].Mode
!= pkgDepCache::ModeKeep
)
637 pkgname
= P
.FullName();
644 const char* const pkg
= pkgname
.c_str();
645 std::string short_pkgname
= StringSplit(pkgname
, ":")[0];
646 std::string arch
= "";
647 if (pkgname
.find(":") != string::npos
)
648 arch
= StringSplit(pkgname
, ":")[1];
649 std::string i18n_pkgname
= pkgname
;
650 if (arch
.size() != 0)
651 strprintf(i18n_pkgname
, "%s (%s)", short_pkgname
.c_str(), arch
.c_str());
653 // 'processing' from dpkg looks like
654 // 'processing: action: pkg'
655 if(prefix
== "processing")
657 const std::pair
<const char *, const char *> * const iter
=
658 std::find_if(PackageProcessingOpsBegin
,
659 PackageProcessingOpsEnd
,
660 MatchProcessingOp(action
.c_str()));
661 if(iter
== PackageProcessingOpsEnd
)
664 std::clog
<< "ignoring unknown action: " << action
<< std::endl
;
668 strprintf(msg
, _(iter
->second
), i18n_pkgname
.c_str());
669 d
->progress
->StatusChanged(pkgname
, PackagesDone
, PackagesTotal
, msg
);
671 // FIXME: this needs a muliarch testcase
672 // FIXME2: is "pkgname" here reliable with dpkg only sending us
674 if (action
== "disappear")
675 handleDisappearAction(pkgname
);
679 if (prefix
== "status")
681 vector
<struct DpkgState
> const &states
= PackageOps
[pkg
];
682 const char *next_action
= NULL
;
683 if(PackageOpsDone
[pkg
] < states
.size())
684 next_action
= states
[PackageOpsDone
[pkg
]].state
;
685 // check if the package moved to the next dpkg state
686 if(next_action
&& (action
== next_action
))
688 // only read the translation if there is actually a next
690 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
693 // we moved from one dpkg state to a new one, report that
694 PackageOpsDone
[pkg
]++;
697 strprintf(msg
, translation
, i18n_pkgname
.c_str());
698 d
->progress
->StatusChanged(pkgname
, PackagesDone
, PackagesTotal
, msg
);
702 std::clog
<< "(parsed from dpkg) pkg: " << short_pkgname
703 << " action: " << action
<< endl
;
707 // DPkgPM::handleDisappearAction /*{{{*/
708 void pkgDPkgPM::handleDisappearAction(string
const &pkgname
)
710 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
711 if (unlikely(Pkg
.end() == true))
714 // record the package name for display and stuff later
715 disappearedPkgs
.insert(Pkg
.FullName(true));
717 // the disappeared package was auto-installed - nothing to do
718 if ((Cache
[Pkg
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
720 pkgCache::VerIterator PkgVer
= Cache
[Pkg
].InstVerIter(Cache
);
721 if (unlikely(PkgVer
.end() == true))
723 /* search in the list of dependencies for (Pre)Depends,
724 check if this dependency has a Replaces on our package
725 and if so transfer the manual installed flag to it */
726 for (pkgCache::DepIterator Dep
= PkgVer
.DependsList(); Dep
.end() != true; ++Dep
)
728 if (Dep
->Type
!= pkgCache::Dep::Depends
&&
729 Dep
->Type
!= pkgCache::Dep::PreDepends
)
731 pkgCache::PkgIterator Tar
= Dep
.TargetPkg();
732 if (unlikely(Tar
.end() == true))
734 // the package is already marked as manual
735 if ((Cache
[Tar
].Flags
& pkgCache::Flag::Auto
) != pkgCache::Flag::Auto
)
737 pkgCache::VerIterator TarVer
= Cache
[Tar
].InstVerIter(Cache
);
738 if (TarVer
.end() == true)
740 for (pkgCache::DepIterator Rep
= TarVer
.DependsList(); Rep
.end() != true; ++Rep
)
742 if (Rep
->Type
!= pkgCache::Dep::Replaces
)
744 if (Pkg
!= Rep
.TargetPkg())
746 // okay, they are strongly connected - transfer manual-bit
748 std::clog
<< "transfer manual-bit from disappeared »" << pkgname
<< "« to »" << Tar
.FullName() << "«" << std::endl
;
749 Cache
[Tar
].Flags
&= ~Flag::Auto
;
755 // DPkgPM::DoDpkgStatusFd /*{{{*/
756 // ---------------------------------------------------------------------
759 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
)
764 len
=read(statusfd
, &d
->dpkgbuf
[d
->dpkgbuf_pos
], sizeof(d
->dpkgbuf
)-d
->dpkgbuf_pos
);
765 d
->dpkgbuf_pos
+= len
;
769 // process line by line if we have a buffer
771 while((q
=(char*)memchr(p
, '\n', d
->dpkgbuf
+d
->dpkgbuf_pos
-p
)) != NULL
)
774 ProcessDpkgStatusLine(p
);
775 p
=q
+1; // continue with next line
778 // now move the unprocessed bits (after the final \n that is now a 0x0)
779 // to the start and update d->dpkgbuf_pos
780 p
= (char*)memrchr(d
->dpkgbuf
, 0, d
->dpkgbuf_pos
);
784 // we are interessted in the first char *after* 0x0
787 // move the unprocessed tail to the start and update pos
788 memmove(d
->dpkgbuf
, p
, p
-d
->dpkgbuf
);
789 d
->dpkgbuf_pos
= d
->dpkgbuf
+d
->dpkgbuf_pos
-p
;
792 // DPkgPM::WriteHistoryTag /*{{{*/
793 void pkgDPkgPM::WriteHistoryTag(string
const &tag
, string value
)
795 size_t const length
= value
.length();
798 // poor mans rstrip(", ")
799 if (value
[length
-2] == ',' && value
[length
-1] == ' ')
800 value
.erase(length
- 2, 2);
801 fprintf(d
->history_out
, "%s: %s\n", tag
.c_str(), value
.c_str());
803 // DPkgPM::OpenLog /*{{{*/
804 bool pkgDPkgPM::OpenLog()
806 string
const logdir
= _config
->FindDir("Dir::Log");
807 if(CreateAPTDirectoryIfNeeded(logdir
, logdir
) == false)
808 // FIXME: use a better string after freeze
809 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
813 time_t const t
= time(NULL
);
814 struct tm
const * const tmp
= localtime(&t
);
815 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
818 string
const logfile_name
= flCombine(logdir
,
819 _config
->Find("Dir::Log::Terminal"));
820 if (!logfile_name
.empty())
822 d
->term_out
= fopen(logfile_name
.c_str(),"a");
823 if (d
->term_out
== NULL
)
824 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name
.c_str());
825 setvbuf(d
->term_out
, NULL
, _IONBF
, 0);
826 SetCloseExec(fileno(d
->term_out
), true);
827 if (getuid() == 0) // if we aren't root, we can't chown a file, so don't try it
829 struct passwd
*pw
= getpwnam("root");
830 struct group
*gr
= getgrnam("adm");
831 if (pw
!= NULL
&& gr
!= NULL
&& chown(logfile_name
.c_str(), pw
->pw_uid
, gr
->gr_gid
) != 0)
832 _error
->WarningE("OpenLog", "chown to root:adm of file %s failed", logfile_name
.c_str());
834 if (chmod(logfile_name
.c_str(), 0640) != 0)
835 _error
->WarningE("OpenLog", "chmod 0640 of file %s failed", logfile_name
.c_str());
836 fprintf(d
->term_out
, "\nLog started: %s\n", timestr
);
839 // write your history
840 string
const history_name
= flCombine(logdir
,
841 _config
->Find("Dir::Log::History"));
842 if (!history_name
.empty())
844 d
->history_out
= fopen(history_name
.c_str(),"a");
845 if (d
->history_out
== NULL
)
846 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), history_name
.c_str());
847 SetCloseExec(fileno(d
->history_out
), true);
848 chmod(history_name
.c_str(), 0644);
849 fprintf(d
->history_out
, "\nStart-Date: %s\n", timestr
);
850 string remove
, purge
, install
, reinstall
, upgrade
, downgrade
;
851 for (pkgCache::PkgIterator I
= Cache
.PkgBegin(); I
.end() == false; ++I
)
853 enum { CANDIDATE
, CANDIDATE_AUTO
, CURRENT_CANDIDATE
, CURRENT
} infostring
;
855 #define HISTORYINFO(X, Y) { line = &X; infostring = Y; }
856 if (Cache
[I
].NewInstall() == true)
857 HISTORYINFO(install
, CANDIDATE_AUTO
)
858 else if (Cache
[I
].ReInstall() == true)
859 HISTORYINFO(reinstall
, CANDIDATE
)
860 else if (Cache
[I
].Upgrade() == true)
861 HISTORYINFO(upgrade
, CURRENT_CANDIDATE
)
862 else if (Cache
[I
].Downgrade() == true)
863 HISTORYINFO(downgrade
, CURRENT_CANDIDATE
)
864 else if (Cache
[I
].Delete() == true)
865 HISTORYINFO((Cache
[I
].Purge() ? purge
: remove
), CURRENT
)
869 line
->append(I
.FullName(false)).append(" (");
870 switch (infostring
) {
871 case CANDIDATE
: line
->append(Cache
[I
].CandVersion
); break;
873 line
->append(Cache
[I
].CandVersion
);
874 if ((Cache
[I
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
875 line
->append(", automatic");
877 case CURRENT_CANDIDATE
: line
->append(Cache
[I
].CurVersion
).append(", ").append(Cache
[I
].CandVersion
); break;
878 case CURRENT
: line
->append(Cache
[I
].CurVersion
); break;
882 if (_config
->Exists("Commandline::AsString") == true)
883 WriteHistoryTag("Commandline", _config
->Find("Commandline::AsString"));
884 WriteHistoryTag("Install", install
);
885 WriteHistoryTag("Reinstall", reinstall
);
886 WriteHistoryTag("Upgrade", upgrade
);
887 WriteHistoryTag("Downgrade",downgrade
);
888 WriteHistoryTag("Remove",remove
);
889 WriteHistoryTag("Purge",purge
);
890 fflush(d
->history_out
);
896 // DPkg::CloseLog /*{{{*/
897 bool pkgDPkgPM::CloseLog()
900 time_t t
= time(NULL
);
901 struct tm
*tmp
= localtime(&t
);
902 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
906 fprintf(d
->term_out
, "Log ended: ");
907 fprintf(d
->term_out
, "%s", timestr
);
908 fprintf(d
->term_out
, "\n");
915 if (disappearedPkgs
.empty() == false)
918 for (std::set
<std::string
>::const_iterator d
= disappearedPkgs
.begin();
919 d
!= disappearedPkgs
.end(); ++d
)
921 pkgCache::PkgIterator P
= Cache
.FindPkg(*d
);
922 disappear
.append(*d
);
924 disappear
.append(", ");
926 disappear
.append(" (").append(Cache
[P
].CurVersion
).append("), ");
928 WriteHistoryTag("Disappeared", disappear
);
930 if (d
->dpkg_error
.empty() == false)
931 fprintf(d
->history_out
, "Error: %s\n", d
->dpkg_error
.c_str());
932 fprintf(d
->history_out
, "End-Date: %s\n", timestr
);
933 fclose(d
->history_out
);
935 d
->history_out
= NULL
;
942 // This implements a racy version of pselect for those architectures
943 // that don't have a working implementation.
944 // FIXME: Probably can be removed on Lenny+1
945 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
946 fd_set
*exceptfds
, const struct timespec
*timeout
,
947 const sigset_t
*sigmask
)
953 tv
.tv_sec
= timeout
->tv_sec
;
954 tv
.tv_usec
= timeout
->tv_nsec
/1000;
956 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
957 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
958 sigprocmask(SIG_SETMASK
, &origmask
, 0);
963 // DPkgPM::BuildPackagesProgressMap /*{{{*/
964 void pkgDPkgPM::BuildPackagesProgressMap()
966 // map the dpkg states to the operations that are performed
967 // (this is sorted in the same way as Item::Ops)
968 static const struct DpkgState DpkgStatesOpMap
[][7] = {
971 {"half-installed", N_("Preparing %s")},
972 {"unpacked", N_("Unpacking %s") },
975 // Configure operation
977 {"unpacked",N_("Preparing to configure %s") },
978 {"half-configured", N_("Configuring %s") },
979 { "installed", N_("Installed %s")},
984 {"half-configured", N_("Preparing for removal of %s")},
985 {"half-installed", N_("Removing %s")},
986 {"config-files", N_("Removed %s")},
991 {"config-files", N_("Preparing to completely remove %s")},
992 {"not-installed", N_("Completely removed %s")},
997 // init the PackageOps map, go over the list of packages that
998 // that will be [installed|configured|removed|purged] and add
999 // them to the PackageOps map (the dpkg states it goes through)
1000 // and the PackageOpsTranslations (human readable strings)
1001 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end(); ++I
)
1003 if((*I
).Pkg
.end() == true)
1006 string
const name
= (*I
).Pkg
.FullName();
1007 PackageOpsDone
[name
] = 0;
1008 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; ++i
)
1010 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
1016 #if (APT_PKG_MAJOR >= 4 && APT_PKG_MINOR < 13)
1017 bool pkgDPkgPM::Go(int StatusFd
)
1019 APT::Progress::PackageManager
*progress
= NULL
;
1021 progress
= APT::Progress::PackageManagerProgressFactory();
1023 progress
= new APT::Progress::PackageManagerProgressFd(StatusFd
);
1025 return GoNoABIBreak(progress
);
1029 void pkgDPkgPM::StartPtyMagic()
1031 // setup the pty and stuff
1034 // if tcgetattr does not return zero there was a error
1035 // and we do not do any pty magic
1036 _error
->PushToStack();
1037 if (tcgetattr(STDOUT_FILENO
, &d
->tt
) == 0)
1039 ioctl(1, TIOCGWINSZ
, (char *)&win
);
1040 if (_config
->FindB("Dpkg::Use-Pty", true) == false)
1042 d
->master
= d
->slave
= -1;
1043 } else if (openpty(&d
->master
, &d
->slave
, NULL
, &d
->tt
, &win
) < 0)
1045 _error
->Errno("openpty", _("Can not write log (%s)"), _("Is /dev/pts mounted?"));
1046 d
->master
= d
->slave
= -1;
1051 rtt
.c_lflag
&= ~ECHO
;
1052 rtt
.c_lflag
|= ISIG
;
1053 // block SIGTTOU during tcsetattr to prevent a hang if
1054 // the process is a member of the background process group
1055 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
1056 sigemptyset(&d
->sigmask
);
1057 sigaddset(&d
->sigmask
, SIGTTOU
);
1058 sigprocmask(SIG_BLOCK
,&d
->sigmask
, &d
->original_sigmask
);
1059 tcsetattr(0, TCSAFLUSH
, &rtt
);
1060 sigprocmask(SIG_SETMASK
, &d
->original_sigmask
, 0);
1063 // complain only if stdout is either a terminal (but still failed) or is an invalid
1064 // descriptor otherwise we would complain about redirection to e.g. /dev/null as well.
1065 else if (isatty(STDOUT_FILENO
) == 1 || errno
== EBADF
)
1066 _error
->Errno("tcgetattr", _("Can not write log (%s)"), _("Is stdout a terminal?"));
1068 if (_error
->PendingError() == true)
1069 _error
->DumpErrors(std::cerr
);
1070 _error
->RevertToStack();
1073 void pkgDPkgPM::StopPtyMagic()
1079 tcsetattr(0, TCSAFLUSH
, &d
->tt
);
1084 // DPkgPM::Go - Run the sequence /*{{{*/
1085 // ---------------------------------------------------------------------
1086 /* This globs the operations and calls dpkg
1088 * If it is called with a progress object apt will report the install
1089 * progress to this object. It maps the dpkg states a package goes
1090 * through to human readable (and i10n-able)
1091 * names and calculates a percentage for each step.
1093 #if (APT_PKG_MAJOR >= 4 && APT_PKG_MINOR >= 13)
1094 bool pkgDPkgPM::Go(APT::Progress::PackageManager
*progress
)
1096 bool pkgDPkgPM::GoNoABIBreak(APT::Progress::PackageManager
*progress
)
1099 pkgPackageManager::SigINTStop
= false;
1100 d
->progress
= progress
;
1102 // Generate the base argument list for dpkg
1103 unsigned long StartSize
= 0;
1104 std::vector
<const char *> Args
;
1105 std::string DpkgExecutable
= getDpkgExecutable();
1106 Args
.push_back(DpkgExecutable
.c_str());
1107 StartSize
+= DpkgExecutable
.length();
1109 // Stick in any custom dpkg options
1110 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
1114 for (; Opts
!= 0; Opts
= Opts
->Next
)
1116 if (Opts
->Value
.empty() == true)
1118 Args
.push_back(Opts
->Value
.c_str());
1119 StartSize
+= Opts
->Value
.length();
1123 size_t const BaseArgs
= Args
.size();
1124 // we need to detect if we can qualify packages with the architecture or not
1125 Args
.push_back("--assert-multi-arch");
1126 Args
.push_back(NULL
);
1128 pid_t dpkgAssertMultiArch
= ExecFork();
1129 if (dpkgAssertMultiArch
== 0)
1131 dpkgChrootDirectory();
1132 // redirect everything to the ultimate sink as we only need the exit-status
1133 int const nullfd
= open("/dev/null", O_RDONLY
);
1134 dup2(nullfd
, STDIN_FILENO
);
1135 dup2(nullfd
, STDOUT_FILENO
);
1136 dup2(nullfd
, STDERR_FILENO
);
1137 execvp(Args
[0], (char**) &Args
[0]);
1138 _error
->WarningE("dpkgGo", "Can't detect if dpkg supports multi-arch!");
1145 unsigned int const MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
1146 unsigned int const MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
1147 bool const NoTriggers
= _config
->FindB("DPkg::NoTriggers", false);
1149 if (RunScripts("DPkg::Pre-Invoke") == false)
1152 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
1155 // support subpressing of triggers processing for special
1156 // cases like d-i that runs the triggers handling manually
1157 bool const SmartConf
= (_config
->Find("PackageManager::Configure", "all") != "all");
1158 bool const TriggersPending
= _config
->FindB("DPkg::TriggersPending", false);
1159 if (_config
->FindB("DPkg::ConfigurePending", SmartConf
) == true)
1160 List
.push_back(Item(Item::ConfigurePending
, PkgIterator()));
1163 BuildPackagesProgressMap();
1165 d
->stdin_is_dev_null
= false;
1170 bool dpkgMultiArch
= false;
1171 if (dpkgAssertMultiArch
> 0)
1174 while (waitpid(dpkgAssertMultiArch
, &Status
, 0) != dpkgAssertMultiArch
)
1178 _error
->WarningE("dpkgGo", _("Waited for %s but it wasn't there"), "dpkg --assert-multi-arch");
1181 if (WIFEXITED(Status
) == true && WEXITSTATUS(Status
) == 0)
1182 dpkgMultiArch
= true;
1185 // start pty magic before the loop
1188 // Tell the progress that its starting and fork dpkg
1189 d
->progress
->Start(d
->master
);
1191 // this loop is runs once per dpkg operation
1192 vector
<Item
>::const_iterator I
= List
.begin();
1193 while (I
!= List
.end())
1195 // Do all actions with the same Op in one run
1196 vector
<Item
>::const_iterator J
= I
;
1197 if (TriggersPending
== true)
1198 for (; J
!= List
.end(); ++J
)
1202 if (J
->Op
!= Item::TriggersPending
)
1204 vector
<Item
>::const_iterator T
= J
+ 1;
1205 if (T
!= List
.end() && T
->Op
== I
->Op
)
1210 for (; J
!= List
.end() && J
->Op
== I
->Op
; ++J
)
1213 // keep track of allocated strings for multiarch package names
1214 std::vector
<char *> Packages
;
1216 // start with the baseset of arguments
1217 unsigned long Size
= StartSize
;
1218 Args
.erase(Args
.begin() + BaseArgs
, Args
.end());
1220 // Now check if we are within the MaxArgs limit
1222 // this code below is problematic, because it may happen that
1223 // the argument list is split in a way that A depends on B
1224 // and they are in the same "--configure A B" run
1225 // - with the split they may now be configured in different
1226 // runs, using Immediate-Configure-All can help prevent this.
1227 if (J
- I
> (signed)MaxArgs
)
1230 unsigned long const size
= MaxArgs
+ 10;
1232 Packages
.reserve(size
);
1236 unsigned long const size
= (J
- I
) + 10;
1238 Packages
.reserve(size
);
1243 return _error
->Errno("pipe","Failed to create IPC pipe to dpkg");
1245 #define ADDARG(X) Args.push_back(X); Size += strlen(X)
1246 #define ADDARGC(X) Args.push_back(X); Size += sizeof(X) - 1
1248 ADDARGC("--status-fd");
1249 char status_fd_buf
[20];
1250 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
1251 ADDARG(status_fd_buf
);
1252 unsigned long const Op
= I
->Op
;
1257 ADDARGC("--force-depends");
1258 ADDARGC("--force-remove-essential");
1259 ADDARGC("--remove");
1263 ADDARGC("--force-depends");
1264 ADDARGC("--force-remove-essential");
1268 case Item::Configure
:
1269 ADDARGC("--configure");
1272 case Item::ConfigurePending
:
1273 ADDARGC("--configure");
1274 ADDARGC("--pending");
1277 case Item::TriggersPending
:
1278 ADDARGC("--triggers-only");
1279 ADDARGC("--pending");
1283 ADDARGC("--unpack");
1284 ADDARGC("--auto-deconfigure");
1288 if (NoTriggers
== true && I
->Op
!= Item::TriggersPending
&&
1289 I
->Op
!= Item::ConfigurePending
)
1291 ADDARGC("--no-triggers");
1295 // Write in the file or package names
1296 if (I
->Op
== Item::Install
)
1298 for (;I
!= J
&& Size
< MaxArgBytes
; ++I
)
1300 if (I
->File
[0] != '/')
1301 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
1302 Args
.push_back(I
->File
.c_str());
1303 Size
+= I
->File
.length();
1308 string
const nativeArch
= _config
->Find("APT::Architecture");
1309 unsigned long const oldSize
= I
->Op
== Item::Configure
? Size
: 0;
1310 for (;I
!= J
&& Size
< MaxArgBytes
; ++I
)
1312 if((*I
).Pkg
.end() == true)
1314 if (I
->Op
== Item::Configure
&& disappearedPkgs
.find(I
->Pkg
.FullName(true)) != disappearedPkgs
.end())
1316 // We keep this here to allow "smooth" transitions from e.g. multiarch dpkg/ubuntu to dpkg/debian
1317 if (dpkgMultiArch
== false && (I
->Pkg
.Arch() == nativeArch
||
1318 strcmp(I
->Pkg
.Arch(), "all") == 0 ||
1319 strcmp(I
->Pkg
.Arch(), "none") == 0))
1321 char const * const name
= I
->Pkg
.Name();
1326 pkgCache::VerIterator PkgVer
;
1327 std::string name
= I
->Pkg
.Name();
1328 if (Op
== Item::Remove
|| Op
== Item::Purge
)
1330 PkgVer
= I
->Pkg
.CurrentVer();
1331 if(PkgVer
.end() == true)
1332 PkgVer
= FindNowVersion(I
->Pkg
);
1335 PkgVer
= Cache
[I
->Pkg
].InstVerIter(Cache
);
1336 if (strcmp(I
->Pkg
.Arch(), "none") == 0)
1337 ; // never arch-qualify a package without an arch
1338 else if (PkgVer
.end() == false)
1339 name
.append(":").append(PkgVer
.Arch());
1341 _error
->Warning("Can not find PkgVer for '%s'", name
.c_str());
1342 char * const fullname
= strdup(name
.c_str());
1343 Packages
.push_back(fullname
);
1347 // skip configure action if all sheduled packages disappeared
1348 if (oldSize
== Size
)
1355 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
1357 for (std::vector
<const char *>::const_iterator a
= Args
.begin();
1358 a
!= Args
.end(); ++a
)
1363 Args
.push_back(NULL
);
1369 /* Mask off sig int/quit. We do this because dpkg also does when
1370 it forks scripts. What happens is that when you hit ctrl-c it sends
1371 it to all processes in the group. Since dpkg ignores the signal
1372 it doesn't die but we do! So we must also ignore it */
1373 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
1374 sighandler_t old_SIGINT
= signal(SIGINT
,SigINT
);
1376 // Check here for any SIGINT
1377 if (pkgPackageManager::SigINTStop
&& (Op
== Item::Remove
|| Op
== Item::Purge
|| Op
== Item::Install
))
1381 // ignore SIGHUP as well (debian #463030)
1382 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
1385 d
->progress
->StartDpkg();
1386 std::set
<int> KeepFDs
;
1387 KeepFDs
.insert(fd
[1]);
1388 MergeKeepFdsFromConfiguration(KeepFDs
);
1389 pid_t Child
= ExecFork(KeepFDs
);
1392 // This is the child
1393 if(d
->slave
>= 0 && d
->master
>= 0)
1396 ioctl(d
->slave
, TIOCSCTTY
, 0);
1403 close(fd
[0]); // close the read end of the pipe
1405 dpkgChrootDirectory();
1407 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
1410 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
1413 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
1416 // Discard everything in stdin before forking dpkg
1417 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
1420 while (read(STDIN_FILENO
,&dummy
,1) == 1);
1422 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
1426 /* No Job Control Stop Env is a magic dpkg var that prevents it
1427 from using sigstop */
1428 putenv((char *)"DPKG_NO_TSTP=yes");
1429 execvp(Args
[0], (char**) &Args
[0]);
1430 cerr
<< "Could not exec dpkg!" << endl
;
1435 if (_config
->FindB("DPkg::UseIoNice", false) == true)
1441 // we read from dpkg here
1442 int const _dpkgin
= fd
[0];
1443 close(fd
[1]); // close the write end of the pipe
1446 sigemptyset(&d
->sigmask
);
1447 sigprocmask(SIG_BLOCK
,&d
->sigmask
,&d
->original_sigmask
);
1449 /* free vectors (and therefore memory) as we don't need the included data anymore */
1450 for (std::vector
<char *>::const_iterator p
= Packages
.begin();
1451 p
!= Packages
.end(); ++p
)
1455 // the result of the waitpid call
1458 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
1460 // FIXME: move this to a function or something, looks ugly here
1461 // error handling, waitpid returned -1
1464 RunScripts("DPkg::Post-Invoke");
1466 // Restore sig int/quit
1467 signal(SIGQUIT
,old_SIGQUIT
);
1468 signal(SIGINT
,old_SIGINT
);
1470 signal(SIGHUP
,old_SIGHUP
);
1471 return _error
->Errno("waitpid","Couldn't wait for subprocess");
1474 // wait for input or output here
1476 if (d
->master
>= 0 && !d
->stdin_is_dev_null
)
1478 FD_SET(_dpkgin
, &rfds
);
1480 FD_SET(d
->master
, &rfds
);
1482 tv
.tv_nsec
= d
->progress
->GetPulseInterval();
1483 select_ret
= pselect(max(d
->master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
1484 &tv
, &d
->original_sigmask
);
1485 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
1486 select_ret
= racy_pselect(max(d
->master
, _dpkgin
)+1, &rfds
, NULL
,
1487 NULL
, &tv
, &d
->original_sigmask
);
1488 d
->progress
->Pulse();
1489 if (select_ret
== 0)
1491 else if (select_ret
< 0 && errno
== EINTR
)
1493 else if (select_ret
< 0)
1495 perror("select() returned error");
1499 if(d
->master
>= 0 && FD_ISSET(d
->master
, &rfds
))
1500 DoTerminalPty(d
->master
);
1501 if(d
->master
>= 0 && FD_ISSET(0, &rfds
))
1503 if(FD_ISSET(_dpkgin
, &rfds
))
1504 DoDpkgStatusFd(_dpkgin
);
1508 // Restore sig int/quit
1509 signal(SIGQUIT
,old_SIGQUIT
);
1510 signal(SIGINT
,old_SIGINT
);
1512 signal(SIGHUP
,old_SIGHUP
);
1513 // Check for an error code.
1514 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
1516 // if it was set to "keep-dpkg-runing" then we won't return
1517 // here but keep the loop going and just report it as a error
1519 bool const stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
1522 RunScripts("DPkg::Post-Invoke");
1524 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
1525 strprintf(d
->dpkg_error
, "Sub-process %s received a segmentation fault.",Args
[0]);
1526 else if (WIFEXITED(Status
) != 0)
1527 strprintf(d
->dpkg_error
, "Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
1529 strprintf(d
->dpkg_error
, "Sub-process %s exited unexpectedly",Args
[0]);
1531 if(d
->dpkg_error
.size() > 0)
1532 _error
->Error("%s", d
->dpkg_error
.c_str());
1538 d
->progress
->Stop();
1543 // dpkg is done at this point
1544 d
->progress
->Stop();
1548 if (pkgPackageManager::SigINTStop
)
1549 _error
->Warning(_("Operation was interrupted before it could finish"));
1551 if (RunScripts("DPkg::Post-Invoke") == false)
1554 if (_config
->FindB("Debug::pkgDPkgPM",false) == false)
1556 std::string
const oldpkgcache
= _config
->FindFile("Dir::cache::pkgcache");
1557 if (oldpkgcache
.empty() == false && RealFileExists(oldpkgcache
) == true &&
1558 unlink(oldpkgcache
.c_str()) == 0)
1560 std::string
const srcpkgcache
= _config
->FindFile("Dir::cache::srcpkgcache");
1561 if (srcpkgcache
.empty() == false && RealFileExists(srcpkgcache
) == true)
1563 _error
->PushToStack();
1564 pkgCacheFile CacheFile
;
1565 CacheFile
.BuildCaches(NULL
, true);
1566 _error
->RevertToStack();
1571 Cache
.writeStateFile(NULL
);
1575 void SigINT(int sig
) {
1576 pkgPackageManager::SigINTStop
= true;
1579 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1580 // ---------------------------------------------------------------------
1582 void pkgDPkgPM::Reset()
1584 List
.erase(List
.begin(),List
.end());
1587 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1588 // ---------------------------------------------------------------------
1590 void pkgDPkgPM::WriteApportReport(const char *pkgpath
, const char *errormsg
)
1592 // If apport doesn't exist or isn't installed do nothing
1593 // This e.g. prevents messages in 'universes' without apport
1594 pkgCache::PkgIterator apportPkg
= Cache
.FindPkg("apport");
1595 if (apportPkg
.end() == true || apportPkg
->CurrentVer
== 0)
1598 string pkgname
, reportfile
, srcpkgname
, pkgver
, arch
;
1599 string::size_type pos
;
1602 if (_config
->FindB("Dpkg::ApportFailureReport", false) == false)
1604 std::clog
<< "configured to not write apport reports" << std::endl
;
1608 // only report the first errors
1609 if(pkgFailures
> _config
->FindI("APT::Apport::MaxReports", 3))
1611 std::clog
<< _("No apport report written because MaxReports is reached already") << std::endl
;
1615 // check if its not a follow up error
1616 const char *needle
= dgettext("dpkg", "dependency problems - leaving unconfigured");
1617 if(strstr(errormsg
, needle
) != NULL
) {
1618 std::clog
<< _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl
;
1622 // do not report disk-full failures
1623 if(strstr(errormsg
, strerror(ENOSPC
)) != NULL
) {
1624 std::clog
<< _("No apport report written because the error message indicates a disk full error") << std::endl
;
1628 // do not report out-of-memory failures
1629 if(strstr(errormsg
, strerror(ENOMEM
)) != NULL
||
1630 strstr(errormsg
, "failed to allocate memory") != NULL
) {
1631 std::clog
<< _("No apport report written because the error message indicates a out of memory error") << std::endl
;
1635 // do not report bugs regarding inaccessible local files
1636 if(strstr(errormsg
, strerror(ENOENT
)) != NULL
||
1637 strstr(errormsg
, "cannot access archive") != NULL
) {
1638 std::clog
<< _("No apport report written because the error message indicates an issue on the local system") << std::endl
;
1642 // do not report errors encountered when decompressing packages
1643 if(strstr(errormsg
, "--fsys-tarfile returned error exit status 2") != NULL
) {
1644 std::clog
<< _("No apport report written because the error message indicates an issue on the local system") << std::endl
;
1648 // do not report dpkg I/O errors, this is a format string, so we compare
1649 // the prefix and the suffix of the error with the dpkg error message
1650 vector
<string
> io_errors
;
1651 io_errors
.push_back(string("failed to read on buffer copy for %s"));
1652 io_errors
.push_back(string("failed in write on buffer copy for %s"));
1653 io_errors
.push_back(string("short read on buffer copy for %s"));
1655 for (vector
<string
>::iterator I
= io_errors
.begin(); I
!= io_errors
.end(); I
++)
1657 vector
<string
> list
= VectorizeString(dgettext("dpkg", (*I
).c_str()), '%');
1658 if (list
.size() > 1) {
1659 // we need to split %s, VectorizeString only allows char so we need
1660 // to kill the "s" manually
1661 if (list
[1].size() > 1) {
1662 list
[1].erase(0, 1);
1663 if(strstr(errormsg
, list
[0].c_str()) &&
1664 strstr(errormsg
, list
[1].c_str())) {
1665 std::clog
<< _("No apport report written because the error message indicates a dpkg I/O error") << std::endl
;
1672 // get the pkgname and reportfile
1673 pkgname
= flNotDir(pkgpath
);
1674 pos
= pkgname
.find('_');
1675 if(pos
!= string::npos
)
1676 pkgname
= pkgname
.substr(0, pos
);
1678 // find the package versin and source package name
1679 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
1680 if (Pkg
.end() == true)
1682 pkgCache::VerIterator Ver
= Cache
.GetCandidateVer(Pkg
);
1683 if (Ver
.end() == true)
1685 pkgver
= Ver
.VerStr() == NULL
? "unknown" : Ver
.VerStr();
1686 pkgRecords
Recs(Cache
);
1687 pkgRecords::Parser
&Parse
= Recs
.Lookup(Ver
.FileList());
1688 srcpkgname
= Parse
.SourcePkg();
1689 if(srcpkgname
.empty())
1690 srcpkgname
= pkgname
;
1692 // if the file exists already, we check:
1693 // - if it was reported already (touched by apport).
1694 // If not, we do nothing, otherwise
1695 // we overwrite it. This is the same behaviour as apport
1696 // - if we have a report with the same pkgversion already
1698 reportfile
= flCombine("/var/crash",pkgname
+".0.crash");
1699 if(FileExists(reportfile
))
1704 // check atime/mtime
1705 stat(reportfile
.c_str(), &buf
);
1706 if(buf
.st_mtime
> buf
.st_atime
)
1709 // check if the existing report is the same version
1710 report
= fopen(reportfile
.c_str(),"r");
1711 while(fgets(strbuf
, sizeof(strbuf
), report
) != NULL
)
1713 if(strstr(strbuf
,"Package:") == strbuf
)
1715 char pkgname
[255], version
[255];
1716 if(sscanf(strbuf
, "Package: %254s %254s", pkgname
, version
) == 2)
1717 if(strcmp(pkgver
.c_str(), version
) == 0)
1727 // now write the report
1728 arch
= _config
->Find("APT::Architecture");
1729 report
= fopen(reportfile
.c_str(),"w");
1732 if(_config
->FindB("DPkgPM::InitialReportOnly",false) == true)
1733 chmod(reportfile
.c_str(), 0);
1735 chmod(reportfile
.c_str(), 0600);
1736 fprintf(report
, "ProblemType: Package\n");
1737 fprintf(report
, "Architecture: %s\n", arch
.c_str());
1738 time_t now
= time(NULL
);
1739 fprintf(report
, "Date: %s" , ctime(&now
));
1740 fprintf(report
, "Package: %s %s\n", pkgname
.c_str(), pkgver
.c_str());
1741 fprintf(report
, "SourcePackage: %s\n", srcpkgname
.c_str());
1742 fprintf(report
, "ErrorMessage:\n %s\n", errormsg
);
1744 // ensure that the log is flushed
1746 fflush(d
->term_out
);
1748 // attach terminal log it if we have it
1749 string logfile_name
= _config
->FindFile("Dir::Log::Terminal");
1750 if (!logfile_name
.empty())
1754 fprintf(report
, "DpkgTerminalLog:\n");
1755 log
= fopen(logfile_name
.c_str(),"r");
1759 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1760 fprintf(report
, " %s", buf
);
1761 fprintf(report
, " \n");
1766 // attach history log it if we have it
1767 string histfile_name
= _config
->FindFile("Dir::Log::History");
1768 if (!histfile_name
.empty())
1773 fprintf(report
, "DpkgHistoryLog:\n");
1774 log
= fopen(histfile_name
.c_str(),"r");
1777 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1778 fprintf(report
, " %s", buf
);
1784 const char *ops_str
[] = {"Install", "Configure","Remove","Purge"};
1785 fprintf(report
, "AptOrdering:\n");
1786 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
1787 if ((*I
).Pkg
!= NULL
)
1788 fprintf(report
, " %s: %s\n", (*I
).Pkg
.Name(), ops_str
[(*I
).Op
]);
1790 fprintf(report
, " %s: %s\n", "NULL", ops_str
[(*I
).Op
]);
1792 // attach dmesg log (to learn about segfaults)
1793 if (FileExists("/bin/dmesg"))
1795 fprintf(report
, "Dmesg:\n");
1796 FILE *log
= popen("/bin/dmesg","r");
1800 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1801 fprintf(report
, " %s", buf
);
1806 // attach df -l log (to learn about filesystem status)
1807 if (FileExists("/bin/df"))
1810 fprintf(report
, "Df:\n");
1811 FILE *log
= popen("/bin/df -l","r");
1815 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1816 fprintf(report
, " %s", buf
);