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>
26 #include <sys/select.h>
28 #include <sys/types.h>
44 #include <sys/ioctl.h>
52 class pkgDPkgPMPrivate
55 pkgDPkgPMPrivate() : stdin_is_dev_null(false), dpkgbuf_pos(0),
56 term_out(NULL
), history_out(NULL
),
57 last_reported_progress(0.0)
61 bool stdin_is_dev_null
;
62 // the buffer we use for the dpkg status-fd reading
69 float last_reported_progress
;
74 // Maps the dpkg "processing" info to human readable names. Entry 0
75 // of each array is the key, entry 1 is the value.
76 const std::pair
<const char *, const char *> PackageProcessingOps
[] = {
77 std::make_pair("install", N_("Installing %s")),
78 std::make_pair("configure", N_("Configuring %s")),
79 std::make_pair("remove", N_("Removing %s")),
80 std::make_pair("purge", N_("Completely removing %s")),
81 std::make_pair("disappear", N_("Noting disappearance of %s")),
82 std::make_pair("trigproc", N_("Running post-installation trigger %s"))
85 const std::pair
<const char *, const char *> * const PackageProcessingOpsBegin
= PackageProcessingOps
;
86 const std::pair
<const char *, const char *> * const PackageProcessingOpsEnd
= PackageProcessingOps
+ sizeof(PackageProcessingOps
) / sizeof(PackageProcessingOps
[0]);
88 // Predicate to test whether an entry in the PackageProcessingOps
89 // array matches a string.
90 class MatchProcessingOp
95 MatchProcessingOp(const char *the_target
)
100 bool operator()(const std::pair
<const char *, const char *> &pair
) const
102 return strcmp(pair
.first
, target
) == 0;
107 /* helper function to ionice the given PID
109 there is no C header for ionice yet - just the syscall interface
110 so we use the binary from util-linux
115 if (!FileExists("/usr/bin/ionice"))
117 pid_t Process
= ExecFork();
121 snprintf(buf
, sizeof(buf
), "-p%d", PID
);
123 Args
[0] = "/usr/bin/ionice";
127 execv(Args
[0], (char **)Args
);
129 return ExecWait(Process
, "ionice");
132 // dpkgChrootDirectory - chrooting for dpkg if needed /*{{{*/
133 static void dpkgChrootDirectory()
135 std::string
const chrootDir
= _config
->FindDir("DPkg::Chroot-Directory");
136 if (chrootDir
== "/")
138 std::cerr
<< "Chrooting into " << chrootDir
<< std::endl
;
139 if (chroot(chrootDir
.c_str()) != 0)
147 // FindNowVersion - Helper to find a Version in "now" state /*{{{*/
148 // ---------------------------------------------------------------------
149 /* This is helpful when a package is no longer installed but has residual
153 pkgCache::VerIterator
FindNowVersion(const pkgCache::PkgIterator
&Pkg
)
155 pkgCache::VerIterator Ver
;
156 for (Ver
= Pkg
.VersionList(); Ver
.end() == false; ++Ver
)
158 pkgCache::VerFileIterator Vf
= Ver
.FileList();
159 pkgCache::PkgFileIterator F
= Vf
.File();
160 for (F
= Vf
.File(); F
.end() == false; ++F
)
162 if (F
&& F
.Archive())
164 if (strcmp(F
.Archive(), "now"))
173 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
174 // ---------------------------------------------------------------------
176 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
177 : pkgPackageManager(Cache
), PackagesDone(0), PackagesTotal(0)
179 d
= new pkgDPkgPMPrivate();
182 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
183 // ---------------------------------------------------------------------
185 pkgDPkgPM::~pkgDPkgPM()
190 // DPkgPM::Install - Install a package /*{{{*/
191 // ---------------------------------------------------------------------
192 /* Add an install operation to the sequence list */
193 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
195 if (File
.empty() == true || Pkg
.end() == true)
196 return _error
->Error("Internal Error, No file name for %s",Pkg
.FullName().c_str());
198 // If the filename string begins with DPkg::Chroot-Directory, return the
199 // substr that is within the chroot so dpkg can access it.
200 string
const chrootdir
= _config
->FindDir("DPkg::Chroot-Directory","/");
201 if (chrootdir
!= "/" && File
.find(chrootdir
) == 0)
203 size_t len
= chrootdir
.length();
204 if (chrootdir
.at(len
- 1) == '/')
206 List
.push_back(Item(Item::Install
,Pkg
,File
.substr(len
)));
209 List
.push_back(Item(Item::Install
,Pkg
,File
));
214 // DPkgPM::Configure - Configure a package /*{{{*/
215 // ---------------------------------------------------------------------
216 /* Add a configure operation to the sequence list */
217 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
219 if (Pkg
.end() == true)
222 List
.push_back(Item(Item::Configure
, Pkg
));
224 // Use triggers for config calls if we configure "smart"
225 // as otherwise Pre-Depends will not be satisfied, see #526774
226 if (_config
->FindB("DPkg::TriggersPending", false) == true)
227 List
.push_back(Item(Item::TriggersPending
, PkgIterator()));
232 // DPkgPM::Remove - Remove a package /*{{{*/
233 // ---------------------------------------------------------------------
234 /* Add a remove operation to the sequence list */
235 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
237 if (Pkg
.end() == true)
241 List
.push_back(Item(Item::Purge
,Pkg
));
243 List
.push_back(Item(Item::Remove
,Pkg
));
247 // DPkgPM::SendPkgInfo - Send info for install-pkgs hook /*{{{*/
248 // ---------------------------------------------------------------------
249 /* This is part of the helper script communication interface, it sends
250 very complete information down to the other end of the pipe.*/
251 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
253 return SendPkgsInfo(F
, 2);
255 bool pkgDPkgPM::SendPkgsInfo(FILE * const F
, unsigned int const &Version
)
257 // This version of APT supports only v3, so don't sent higher versions
259 fprintf(F
,"VERSION %u\n", Version
);
261 fprintf(F
,"VERSION 3\n");
263 /* Write out all of the configuration directives by walking the
264 configuration tree */
265 const Configuration::Item
*Top
= _config
->Tree(0);
268 if (Top
->Value
.empty() == false)
271 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
272 QuoteString(Top
->Value
,"\n").c_str());
281 while (Top
!= 0 && Top
->Next
== 0)
288 // Write out the package actions in order.
289 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
291 if(I
->Pkg
.end() == true)
294 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
296 fprintf(F
,"%s ",I
->Pkg
.Name());
298 // Current version which we are going to replace
299 pkgCache::VerIterator CurVer
= I
->Pkg
.CurrentVer();
300 if (CurVer
.end() == true && (I
->Op
== Item::Remove
|| I
->Op
== Item::Purge
))
301 CurVer
= FindNowVersion(I
->Pkg
);
303 if (CurVer
.end() == true)
308 fprintf(F
, "- - none ");
312 fprintf(F
, "%s ", CurVer
.VerStr());
314 fprintf(F
, "%s %s ", CurVer
.Arch(), CurVer
.MultiArchType());
317 // Show the compare operator between current and install version
318 if (S
.InstallVer
!= 0)
320 pkgCache::VerIterator
const InstVer
= S
.InstVerIter(Cache
);
322 if (CurVer
.end() == false)
323 Comp
= InstVer
.CompareVer(CurVer
);
330 fprintf(F
, "%s ", InstVer
.VerStr());
332 fprintf(F
, "%s %s ", InstVer
.Arch(), InstVer
.MultiArchType());
339 fprintf(F
, "> - - none ");
342 // Show the filename/operation
343 if (I
->Op
== Item::Install
)
346 if (I
->File
[0] != '/')
347 fprintf(F
,"**ERROR**\n");
349 fprintf(F
,"%s\n",I
->File
.c_str());
351 else if (I
->Op
== Item::Configure
)
352 fprintf(F
,"**CONFIGURE**\n");
353 else if (I
->Op
== Item::Remove
||
354 I
->Op
== Item::Purge
)
355 fprintf(F
,"**REMOVE**\n");
363 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
364 // ---------------------------------------------------------------------
365 /* This looks for a list of scripts to run from the configuration file
366 each one is run and is fed on standard input a list of all .deb files
367 that are due to be installed. */
368 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
370 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
371 if (Opts
== 0 || Opts
->Child
== 0)
375 unsigned int Count
= 1;
376 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
378 if (Opts
->Value
.empty() == true)
381 // Determine the protocol version
382 string OptSec
= Opts
->Value
;
383 string::size_type Pos
;
384 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
385 Pos
= OptSec
.length();
386 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
388 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
389 unsigned int InfoFD
= _config
->FindI(OptSec
+ "::InfoFD", STDIN_FILENO
);
393 if (pipe(Pipes
) != 0)
394 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
395 if (InfoFD
!= (unsigned)Pipes
[0])
396 SetCloseExec(Pipes
[0],true);
398 _config
->Set("APT::Keep-Fds::", Pipes
[0]);
399 SetCloseExec(Pipes
[1],true);
401 // Purified Fork for running the script
402 pid_t Process
= ExecFork();
406 dup2(Pipes
[0], InfoFD
);
407 SetCloseExec(STDOUT_FILENO
,false);
408 SetCloseExec(STDIN_FILENO
,false);
409 SetCloseExec(STDERR_FILENO
,false);
412 strprintf(hookfd
, "%d", InfoFD
);
413 setenv("APT_HOOK_INFO_FD", hookfd
.c_str(), 1);
415 dpkgChrootDirectory();
419 Args
[2] = Opts
->Value
.c_str();
421 execv(Args
[0],(char **)Args
);
424 if (InfoFD
== (unsigned)Pipes
[0])
425 _config
->Clear("APT::Keep-Fds", Pipes
[0]);
427 FILE *F
= fdopen(Pipes
[1],"w");
429 return _error
->Errno("fdopen","Faild to open new FD");
431 // Feed it the filenames.
434 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
436 // Only deal with packages to be installed from .deb
437 if (I
->Op
!= Item::Install
)
441 if (I
->File
[0] != '/')
444 /* Feed the filename of each package that is pending install
446 fprintf(F
,"%s\n",I
->File
.c_str());
452 SendPkgsInfo(F
, Version
);
456 // Clean up the sub process
457 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
458 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
464 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
465 // ---------------------------------------------------------------------
468 void pkgDPkgPM::DoStdin(int master
)
470 unsigned char input_buf
[256] = {0,};
471 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
473 FileFd::Write(master
, input_buf
, len
);
475 d
->stdin_is_dev_null
= true;
478 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
479 // ---------------------------------------------------------------------
481 * read the terminal pty and write log
483 void pkgDPkgPM::DoTerminalPty(int master
)
485 unsigned char term_buf
[1024] = {0,0, };
487 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
488 if(len
== -1 && errno
== EIO
)
490 // this happens when the child is about to exit, we
491 // give it time to actually exit, otherwise we run
492 // into a race so we sleep for half a second.
493 struct timespec sleepfor
= { 0, 500000000 };
494 nanosleep(&sleepfor
, NULL
);
499 FileFd::Write(1, term_buf
, len
);
501 fwrite(term_buf
, len
, sizeof(char), d
->term_out
);
504 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
505 // ---------------------------------------------------------------------
508 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd
, char *line
)
510 bool const Debug
= _config
->FindB("Debug::pkgDPkgProgressReporting",false);
511 // the status we output
512 ostringstream status
;
515 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
518 /* dpkg sends strings like this:
519 'status: <pkg>: <pkg qstate>'
520 'status: <pkg>:<arch>: <pkg qstate>'
521 errors look like this:
522 '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
523 and conffile-prompt like this
524 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
526 Newer versions of dpkg sent also:
527 'processing: install: pkg'
528 'processing: configure: pkg'
529 'processing: remove: pkg'
530 'processing: purge: pkg'
531 'processing: disappear: pkg'
532 'processing: trigproc: trigger'
535 // we need to split on ": " (note the appended space) as the ':' is
536 // part of the pkgname:arch information that dpkg sends
538 // A dpkg error message may contain additional ":" (like
539 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
540 // so we need to ensure to not split too much
541 std::vector
<std::string
> list
= StringSplit(line
, ": ", 3);
545 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
548 // dpkg does not send always send "pkgname:arch" so we add it here if needed
549 std::string pkgname
= list
[1];
550 if (pkgname
.find(":") == std::string::npos
)
552 string
const nativeArch
= _config
->Find("APT::Architecture");
553 pkgname
= pkgname
+ ":" + nativeArch
;
555 const char* const pkg
= pkgname
.c_str();
556 const char* action
= list
[2].c_str();
558 // 'processing' from dpkg looks like
559 // 'processing: action: pkg'
560 if(strncmp(list
[0].c_str(), "processing", strlen("processing")) == 0)
563 const char* const pkg_or_trigger
= list
[2].c_str();
564 action
= list
[1].c_str();
565 const std::pair
<const char *, const char *> * const iter
=
566 std::find_if(PackageProcessingOpsBegin
,
567 PackageProcessingOpsEnd
,
568 MatchProcessingOp(action
));
569 if(iter
== PackageProcessingOpsEnd
)
572 std::clog
<< "ignoring unknown action: " << action
<< std::endl
;
575 snprintf(s
, sizeof(s
), _(iter
->second
), pkg_or_trigger
);
577 status
<< "pmstatus:" << pkg_or_trigger
578 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
582 FileFd::Write(OutStatusFd
, status
.str().c_str(), status
.str().size());
584 std::clog
<< "send: '" << status
.str() << "'" << endl
;
586 if (strncmp(action
, "disappear", strlen("disappear")) == 0)
587 handleDisappearAction(pkg_or_trigger
);
591 if(strncmp(action
,"error",strlen("error")) == 0)
593 status
<< "pmerror:" << list
[1]
594 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
598 FileFd::Write(OutStatusFd
, status
.str().c_str(), status
.str().size());
600 std::clog
<< "send: '" << status
.str() << "'" << endl
;
602 WriteApportReport(list
[1].c_str(), list
[3].c_str());
605 else if(strncmp(action
,"conffile",strlen("conffile")) == 0)
607 status
<< "pmconffile:" << list
[1]
608 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
612 FileFd::Write(OutStatusFd
, status
.str().c_str(), status
.str().size());
614 std::clog
<< "send: '" << status
.str() << "'" << endl
;
618 vector
<struct DpkgState
> const &states
= PackageOps
[pkg
];
619 const char *next_action
= NULL
;
620 if(PackageOpsDone
[pkg
] < states
.size())
621 next_action
= states
[PackageOpsDone
[pkg
]].state
;
622 // check if the package moved to the next dpkg state
623 if(next_action
&& (strcmp(action
, next_action
) == 0))
625 // only read the translation if there is actually a next
627 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
629 snprintf(s
, sizeof(s
), translation
, pkg
);
631 // we moved from one dpkg state to a new one, report that
632 PackageOpsDone
[pkg
]++;
634 // build the status str
635 status
<< "pmstatus:" << pkg
636 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
639 if(_config
->FindB("DPkgPM::Progress", false) == true)
640 SendTerminalProgress(PackagesDone
/float(PackagesTotal
)*100.0);
643 FileFd::Write(OutStatusFd
, status
.str().c_str(), status
.str().size());
645 std::clog
<< "send: '" << status
.str() << "'" << endl
;
648 std::clog
<< "(parsed from dpkg) pkg: " << pkg
649 << " action: " << action
<< endl
;
652 // DPkgPM::handleDisappearAction /*{{{*/
653 void pkgDPkgPM::handleDisappearAction(string
const &pkgname
)
655 // record the package name for display and stuff later
656 disappearedPkgs
.insert(pkgname
);
658 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
659 if (unlikely(Pkg
.end() == true))
661 // the disappeared package was auto-installed - nothing to do
662 if ((Cache
[Pkg
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
664 pkgCache::VerIterator PkgVer
= Cache
[Pkg
].InstVerIter(Cache
);
665 if (unlikely(PkgVer
.end() == true))
667 /* search in the list of dependencies for (Pre)Depends,
668 check if this dependency has a Replaces on our package
669 and if so transfer the manual installed flag to it */
670 for (pkgCache::DepIterator Dep
= PkgVer
.DependsList(); Dep
.end() != true; ++Dep
)
672 if (Dep
->Type
!= pkgCache::Dep::Depends
&&
673 Dep
->Type
!= pkgCache::Dep::PreDepends
)
675 pkgCache::PkgIterator Tar
= Dep
.TargetPkg();
676 if (unlikely(Tar
.end() == true))
678 // the package is already marked as manual
679 if ((Cache
[Tar
].Flags
& pkgCache::Flag::Auto
) != pkgCache::Flag::Auto
)
681 pkgCache::VerIterator TarVer
= Cache
[Tar
].InstVerIter(Cache
);
682 if (TarVer
.end() == true)
684 for (pkgCache::DepIterator Rep
= TarVer
.DependsList(); Rep
.end() != true; ++Rep
)
686 if (Rep
->Type
!= pkgCache::Dep::Replaces
)
688 if (Pkg
!= Rep
.TargetPkg())
690 // okay, they are strongly connected - transfer manual-bit
692 std::clog
<< "transfer manual-bit from disappeared »" << pkgname
<< "« to »" << Tar
.FullName() << "«" << std::endl
;
693 Cache
[Tar
].Flags
&= ~Flag::Auto
;
699 // DPkgPM::DoDpkgStatusFd /*{{{*/
700 // ---------------------------------------------------------------------
703 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
, int OutStatusFd
)
708 len
=read(statusfd
, &d
->dpkgbuf
[d
->dpkgbuf_pos
], sizeof(d
->dpkgbuf
)-d
->dpkgbuf_pos
);
709 d
->dpkgbuf_pos
+= len
;
713 // process line by line if we have a buffer
715 while((q
=(char*)memchr(p
, '\n', d
->dpkgbuf
+d
->dpkgbuf_pos
-p
)) != NULL
)
718 ProcessDpkgStatusLine(OutStatusFd
, p
);
719 p
=q
+1; // continue with next line
722 // now move the unprocessed bits (after the final \n that is now a 0x0)
723 // to the start and update d->dpkgbuf_pos
724 p
= (char*)memrchr(d
->dpkgbuf
, 0, d
->dpkgbuf_pos
);
728 // we are interessted in the first char *after* 0x0
731 // move the unprocessed tail to the start and update pos
732 memmove(d
->dpkgbuf
, p
, p
-d
->dpkgbuf
);
733 d
->dpkgbuf_pos
= d
->dpkgbuf
+d
->dpkgbuf_pos
-p
;
736 // DPkgPM::WriteHistoryTag /*{{{*/
737 void pkgDPkgPM::WriteHistoryTag(string
const &tag
, string value
)
739 size_t const length
= value
.length();
742 // poor mans rstrip(", ")
743 if (value
[length
-2] == ',' && value
[length
-1] == ' ')
744 value
.erase(length
- 2, 2);
745 fprintf(d
->history_out
, "%s: %s\n", tag
.c_str(), value
.c_str());
747 // DPkgPM::OpenLog /*{{{*/
748 bool pkgDPkgPM::OpenLog()
750 string
const logdir
= _config
->FindDir("Dir::Log");
751 if(CreateAPTDirectoryIfNeeded(logdir
, logdir
) == false)
752 // FIXME: use a better string after freeze
753 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
757 time_t const t
= time(NULL
);
758 struct tm
const * const tmp
= localtime(&t
);
759 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
762 string
const logfile_name
= flCombine(logdir
,
763 _config
->Find("Dir::Log::Terminal"));
764 if (!logfile_name
.empty())
766 d
->term_out
= fopen(logfile_name
.c_str(),"a");
767 if (d
->term_out
== NULL
)
768 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name
.c_str());
769 setvbuf(d
->term_out
, NULL
, _IONBF
, 0);
770 SetCloseExec(fileno(d
->term_out
), true);
771 if (getuid() == 0) // if we aren't root, we can't chown a file, so don't try it
773 struct passwd
*pw
= getpwnam("root");
774 struct group
*gr
= getgrnam("adm");
775 if (pw
!= NULL
&& gr
!= NULL
&& chown(logfile_name
.c_str(), pw
->pw_uid
, gr
->gr_gid
) != 0)
776 _error
->WarningE("OpenLog", "chown to root:adm of file %s failed", logfile_name
.c_str());
778 if (chmod(logfile_name
.c_str(), 0640) != 0)
779 _error
->WarningE("OpenLog", "chmod 0640 of file %s failed", logfile_name
.c_str());
780 fprintf(d
->term_out
, "\nLog started: %s\n", timestr
);
783 // write your history
784 string
const history_name
= flCombine(logdir
,
785 _config
->Find("Dir::Log::History"));
786 if (!history_name
.empty())
788 d
->history_out
= fopen(history_name
.c_str(),"a");
789 if (d
->history_out
== NULL
)
790 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), history_name
.c_str());
791 SetCloseExec(fileno(d
->history_out
), true);
792 chmod(history_name
.c_str(), 0644);
793 fprintf(d
->history_out
, "\nStart-Date: %s\n", timestr
);
794 string remove
, purge
, install
, reinstall
, upgrade
, downgrade
;
795 for (pkgCache::PkgIterator I
= Cache
.PkgBegin(); I
.end() == false; ++I
)
797 enum { CANDIDATE
, CANDIDATE_AUTO
, CURRENT_CANDIDATE
, CURRENT
} infostring
;
799 #define HISTORYINFO(X, Y) { line = &X; infostring = Y; }
800 if (Cache
[I
].NewInstall() == true)
801 HISTORYINFO(install
, CANDIDATE_AUTO
)
802 else if (Cache
[I
].ReInstall() == true)
803 HISTORYINFO(reinstall
, CANDIDATE
)
804 else if (Cache
[I
].Upgrade() == true)
805 HISTORYINFO(upgrade
, CURRENT_CANDIDATE
)
806 else if (Cache
[I
].Downgrade() == true)
807 HISTORYINFO(downgrade
, CURRENT_CANDIDATE
)
808 else if (Cache
[I
].Delete() == true)
809 HISTORYINFO((Cache
[I
].Purge() ? purge
: remove
), CURRENT
)
813 line
->append(I
.FullName(false)).append(" (");
814 switch (infostring
) {
815 case CANDIDATE
: line
->append(Cache
[I
].CandVersion
); break;
817 line
->append(Cache
[I
].CandVersion
);
818 if ((Cache
[I
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
819 line
->append(", automatic");
821 case CURRENT_CANDIDATE
: line
->append(Cache
[I
].CurVersion
).append(", ").append(Cache
[I
].CandVersion
); break;
822 case CURRENT
: line
->append(Cache
[I
].CurVersion
); break;
826 if (_config
->Exists("Commandline::AsString") == true)
827 WriteHistoryTag("Commandline", _config
->Find("Commandline::AsString"));
828 WriteHistoryTag("Install", install
);
829 WriteHistoryTag("Reinstall", reinstall
);
830 WriteHistoryTag("Upgrade", upgrade
);
831 WriteHistoryTag("Downgrade",downgrade
);
832 WriteHistoryTag("Remove",remove
);
833 WriteHistoryTag("Purge",purge
);
834 fflush(d
->history_out
);
840 // DPkg::CloseLog /*{{{*/
841 bool pkgDPkgPM::CloseLog()
844 time_t t
= time(NULL
);
845 struct tm
*tmp
= localtime(&t
);
846 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
850 fprintf(d
->term_out
, "Log ended: ");
851 fprintf(d
->term_out
, "%s", timestr
);
852 fprintf(d
->term_out
, "\n");
859 if (disappearedPkgs
.empty() == false)
862 for (std::set
<std::string
>::const_iterator d
= disappearedPkgs
.begin();
863 d
!= disappearedPkgs
.end(); ++d
)
865 pkgCache::PkgIterator P
= Cache
.FindPkg(*d
);
866 disappear
.append(*d
);
868 disappear
.append(", ");
870 disappear
.append(" (").append(Cache
[P
].CurVersion
).append("), ");
872 WriteHistoryTag("Disappeared", disappear
);
874 if (d
->dpkg_error
.empty() == false)
875 fprintf(d
->history_out
, "Error: %s\n", d
->dpkg_error
.c_str());
876 fprintf(d
->history_out
, "End-Date: %s\n", timestr
);
877 fclose(d
->history_out
);
879 d
->history_out
= NULL
;
884 // DPkgPM::SendTerminalProgress /*{{{*/
885 // ---------------------------------------------------------------------
886 /* Send progress info to the terminal
888 void pkgDPkgPM::SendTerminalProgress(float percentage
)
890 int reporting_steps
= _config
->FindI("DpkgPM::Reporting-Steps", 1);
892 if(percentage
< (d
->last_reported_progress
+ reporting_steps
))
895 // FIXME: use colors too
897 << "Progress: [" << std::setw(3) << int(percentage
) << "%]"
899 d
->last_reported_progress
= percentage
;
903 // This implements a racy version of pselect for those architectures
904 // that don't have a working implementation.
905 // FIXME: Probably can be removed on Lenny+1
906 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
907 fd_set
*exceptfds
, const struct timespec
*timeout
,
908 const sigset_t
*sigmask
)
914 tv
.tv_sec
= timeout
->tv_sec
;
915 tv
.tv_usec
= timeout
->tv_nsec
/1000;
917 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
918 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
919 sigprocmask(SIG_SETMASK
, &origmask
, 0);
923 // DPkgPM::Go - Run the sequence /*{{{*/
924 // ---------------------------------------------------------------------
925 /* This globs the operations and calls dpkg
927 * If it is called with "OutStatusFd" set to a valid file descriptor
928 * apt will report the install progress over this fd. It maps the
929 * dpkg states a package goes through to human readable (and i10n-able)
930 * names and calculates a percentage for each step.
932 bool pkgDPkgPM::Go(int OutStatusFd
)
934 pkgPackageManager::SigINTStop
= false;
936 // Generate the base argument list for dpkg
937 std::vector
<const char *> Args
;
938 unsigned long StartSize
= 0;
939 string Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
941 string
const dpkgChrootDir
= _config
->FindDir("DPkg::Chroot-Directory", "/");
942 size_t dpkgChrootLen
= dpkgChrootDir
.length();
943 if (dpkgChrootDir
!= "/" && Tmp
.find(dpkgChrootDir
) == 0)
945 if (dpkgChrootDir
[dpkgChrootLen
- 1] == '/')
947 Tmp
= Tmp
.substr(dpkgChrootLen
);
950 Args
.push_back(Tmp
.c_str());
951 StartSize
+= Tmp
.length();
953 // Stick in any custom dpkg options
954 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
958 for (; Opts
!= 0; Opts
= Opts
->Next
)
960 if (Opts
->Value
.empty() == true)
962 Args
.push_back(Opts
->Value
.c_str());
963 StartSize
+= Opts
->Value
.length();
967 size_t const BaseArgs
= Args
.size();
968 // we need to detect if we can qualify packages with the architecture or not
969 Args
.push_back("--assert-multi-arch");
970 Args
.push_back(NULL
);
972 pid_t dpkgAssertMultiArch
= ExecFork();
973 if (dpkgAssertMultiArch
== 0)
975 dpkgChrootDirectory();
976 // redirect everything to the ultimate sink as we only need the exit-status
977 int const nullfd
= open("/dev/null", O_RDONLY
);
978 dup2(nullfd
, STDIN_FILENO
);
979 dup2(nullfd
, STDOUT_FILENO
);
980 dup2(nullfd
, STDERR_FILENO
);
981 execvp(Args
[0], (char**) &Args
[0]);
982 _error
->WarningE("dpkgGo", "Can't detect if dpkg supports multi-arch!");
989 sigset_t original_sigmask
;
991 unsigned int const MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
992 unsigned int const MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
993 bool const NoTriggers
= _config
->FindB("DPkg::NoTriggers", false);
995 if (RunScripts("DPkg::Pre-Invoke") == false)
998 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
1001 // support subpressing of triggers processing for special
1002 // cases like d-i that runs the triggers handling manually
1003 bool const SmartConf
= (_config
->Find("PackageManager::Configure", "all") != "all");
1004 bool const TriggersPending
= _config
->FindB("DPkg::TriggersPending", false);
1005 if (_config
->FindB("DPkg::ConfigurePending", SmartConf
) == true)
1006 List
.push_back(Item(Item::ConfigurePending
, PkgIterator()));
1008 // map the dpkg states to the operations that are performed
1009 // (this is sorted in the same way as Item::Ops)
1010 static const struct DpkgState DpkgStatesOpMap
[][7] = {
1011 // Install operation
1013 {"half-installed", N_("Preparing %s")},
1014 {"unpacked", N_("Unpacking %s") },
1017 // Configure operation
1019 {"unpacked",N_("Preparing to configure %s") },
1020 {"half-configured", N_("Configuring %s") },
1021 { "installed", N_("Installed %s")},
1026 {"half-configured", N_("Preparing for removal of %s")},
1027 {"half-installed", N_("Removing %s")},
1028 {"config-files", N_("Removed %s")},
1033 {"config-files", N_("Preparing to completely remove %s")},
1034 {"not-installed", N_("Completely removed %s")},
1039 // init the PackageOps map, go over the list of packages that
1040 // that will be [installed|configured|removed|purged] and add
1041 // them to the PackageOps map (the dpkg states it goes through)
1042 // and the PackageOpsTranslations (human readable strings)
1043 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end(); ++I
)
1045 if((*I
).Pkg
.end() == true)
1048 string
const name
= (*I
).Pkg
.FullName();
1049 PackageOpsDone
[name
] = 0;
1050 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; ++i
)
1052 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
1057 d
->stdin_is_dev_null
= false;
1062 bool dpkgMultiArch
= false;
1063 if (dpkgAssertMultiArch
> 0)
1066 while (waitpid(dpkgAssertMultiArch
, &Status
, 0) != dpkgAssertMultiArch
)
1070 _error
->WarningE("dpkgGo", _("Waited for %s but it wasn't there"), "dpkg --assert-multi-arch");
1073 if (WIFEXITED(Status
) == true && WEXITSTATUS(Status
) == 0)
1074 dpkgMultiArch
= true;
1077 // this loop is runs once per operation
1078 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();)
1080 // Do all actions with the same Op in one run
1081 vector
<Item
>::const_iterator J
= I
;
1082 if (TriggersPending
== true)
1083 for (; J
!= List
.end(); ++J
)
1087 if (J
->Op
!= Item::TriggersPending
)
1089 vector
<Item
>::const_iterator T
= J
+ 1;
1090 if (T
!= List
.end() && T
->Op
== I
->Op
)
1095 for (; J
!= List
.end() && J
->Op
== I
->Op
; ++J
)
1098 // keep track of allocated strings for multiarch package names
1099 std::vector
<char *> Packages
;
1101 // start with the baseset of arguments
1102 unsigned long Size
= StartSize
;
1103 Args
.erase(Args
.begin() + BaseArgs
, Args
.end());
1105 // Now check if we are within the MaxArgs limit
1107 // this code below is problematic, because it may happen that
1108 // the argument list is split in a way that A depends on B
1109 // and they are in the same "--configure A B" run
1110 // - with the split they may now be configured in different
1111 // runs, using Immediate-Configure-All can help prevent this.
1112 if (J
- I
> (signed)MaxArgs
)
1115 unsigned long const size
= MaxArgs
+ 10;
1117 Packages
.reserve(size
);
1121 unsigned long const size
= (J
- I
) + 10;
1123 Packages
.reserve(size
);
1128 return _error
->Errno("pipe","Failed to create IPC pipe to dpkg");
1130 #define ADDARG(X) Args.push_back(X); Size += strlen(X)
1131 #define ADDARGC(X) Args.push_back(X); Size += sizeof(X) - 1
1133 ADDARGC("--status-fd");
1134 char status_fd_buf
[20];
1135 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
1136 ADDARG(status_fd_buf
);
1137 unsigned long const Op
= I
->Op
;
1142 ADDARGC("--force-depends");
1143 ADDARGC("--force-remove-essential");
1144 ADDARGC("--remove");
1148 ADDARGC("--force-depends");
1149 ADDARGC("--force-remove-essential");
1153 case Item::Configure
:
1154 ADDARGC("--configure");
1157 case Item::ConfigurePending
:
1158 ADDARGC("--configure");
1159 ADDARGC("--pending");
1162 case Item::TriggersPending
:
1163 ADDARGC("--triggers-only");
1164 ADDARGC("--pending");
1168 ADDARGC("--unpack");
1169 ADDARGC("--auto-deconfigure");
1173 if (NoTriggers
== true && I
->Op
!= Item::TriggersPending
&&
1174 I
->Op
!= Item::ConfigurePending
)
1176 ADDARGC("--no-triggers");
1180 // Write in the file or package names
1181 if (I
->Op
== Item::Install
)
1183 for (;I
!= J
&& Size
< MaxArgBytes
; ++I
)
1185 if (I
->File
[0] != '/')
1186 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
1187 Args
.push_back(I
->File
.c_str());
1188 Size
+= I
->File
.length();
1193 string
const nativeArch
= _config
->Find("APT::Architecture");
1194 unsigned long const oldSize
= I
->Op
== Item::Configure
? Size
: 0;
1195 for (;I
!= J
&& Size
< MaxArgBytes
; ++I
)
1197 if((*I
).Pkg
.end() == true)
1199 if (I
->Op
== Item::Configure
&& disappearedPkgs
.find(I
->Pkg
.Name()) != disappearedPkgs
.end())
1201 // We keep this here to allow "smooth" transitions from e.g. multiarch dpkg/ubuntu to dpkg/debian
1202 if (dpkgMultiArch
== false && (I
->Pkg
.Arch() == nativeArch
||
1203 strcmp(I
->Pkg
.Arch(), "all") == 0 ||
1204 strcmp(I
->Pkg
.Arch(), "none") == 0))
1206 char const * const name
= I
->Pkg
.Name();
1211 pkgCache::VerIterator PkgVer
;
1212 std::string name
= I
->Pkg
.Name();
1213 if (Op
== Item::Remove
|| Op
== Item::Purge
)
1215 PkgVer
= I
->Pkg
.CurrentVer();
1216 if(PkgVer
.end() == true)
1217 PkgVer
= FindNowVersion(I
->Pkg
);
1220 PkgVer
= Cache
[I
->Pkg
].InstVerIter(Cache
);
1221 if (strcmp(I
->Pkg
.Arch(), "none") == 0)
1222 ; // never arch-qualify a package without an arch
1223 else if (PkgVer
.end() == false)
1224 name
.append(":").append(PkgVer
.Arch());
1226 _error
->Warning("Can not find PkgVer for '%s'", name
.c_str());
1227 char * const fullname
= strdup(name
.c_str());
1228 Packages
.push_back(fullname
);
1232 // skip configure action if all sheduled packages disappeared
1233 if (oldSize
== Size
)
1240 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
1242 for (std::vector
<const char *>::const_iterator a
= Args
.begin();
1243 a
!= Args
.end(); ++a
)
1248 Args
.push_back(NULL
);
1254 /* Mask off sig int/quit. We do this because dpkg also does when
1255 it forks scripts. What happens is that when you hit ctrl-c it sends
1256 it to all processes in the group. Since dpkg ignores the signal
1257 it doesn't die but we do! So we must also ignore it */
1258 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
1259 sighandler_t old_SIGINT
= signal(SIGINT
,SigINT
);
1261 // Check here for any SIGINT
1262 if (pkgPackageManager::SigINTStop
&& (Op
== Item::Remove
|| Op
== Item::Purge
|| Op
== Item::Install
))
1266 // ignore SIGHUP as well (debian #463030)
1267 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
1274 // if tcgetattr does not return zero there was a error
1275 // and we do not do any pty magic
1276 _error
->PushToStack();
1277 if (tcgetattr(STDOUT_FILENO
, &tt
) == 0)
1279 ioctl(0, TIOCGWINSZ
, (char *)&win
);
1280 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
1282 _error
->Errno("openpty", _("Can not write log (%s)"), _("Is /dev/pts mounted?"));
1283 master
= slave
= -1;
1288 rtt
.c_lflag
&= ~ECHO
;
1289 rtt
.c_lflag
|= ISIG
;
1290 // block SIGTTOU during tcsetattr to prevent a hang if
1291 // the process is a member of the background process group
1292 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
1293 sigemptyset(&sigmask
);
1294 sigaddset(&sigmask
, SIGTTOU
);
1295 sigprocmask(SIG_BLOCK
,&sigmask
, &original_sigmask
);
1296 tcsetattr(0, TCSAFLUSH
, &rtt
);
1297 sigprocmask(SIG_SETMASK
, &original_sigmask
, 0);
1300 // complain only if stdout is either a terminal (but still failed) or is an invalid
1301 // descriptor otherwise we would complain about redirection to e.g. /dev/null as well.
1302 else if (isatty(STDOUT_FILENO
) == 1 || errno
== EBADF
)
1303 _error
->Errno("tcgetattr", _("Can not write log (%s)"), _("Is stdout a terminal?"));
1305 if (_error
->PendingError() == true)
1306 _error
->DumpErrors(std::cerr
);
1307 _error
->RevertToStack();
1311 _config
->Set("APT::Keep-Fds::",fd
[1]);
1312 // send status information that we are about to fork dpkg
1313 if(OutStatusFd
> 0) {
1314 ostringstream status
;
1315 status
<< "pmstatus:dpkg-exec:"
1316 << (PackagesDone
/float(PackagesTotal
)*100.0)
1317 << ":" << _("Running dpkg")
1319 FileFd::Write(OutStatusFd
, status
.str().c_str(), status
.str().size());
1323 // This is the child
1326 if(slave
>= 0 && master
>= 0)
1329 ioctl(slave
, TIOCSCTTY
, 0);
1336 close(fd
[0]); // close the read end of the pipe
1338 dpkgChrootDirectory();
1340 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
1343 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
1346 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
1349 // Discard everything in stdin before forking dpkg
1350 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
1353 while (read(STDIN_FILENO
,&dummy
,1) == 1);
1355 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
1359 /* No Job Control Stop Env is a magic dpkg var that prevents it
1360 from using sigstop */
1361 putenv((char *)"DPKG_NO_TSTP=yes");
1362 execvp(Args
[0], (char**) &Args
[0]);
1363 cerr
<< "Could not exec dpkg!" << endl
;
1368 if (_config
->FindB("DPkg::UseIoNice", false) == true)
1371 // clear the Keep-Fd again
1372 _config
->Clear("APT::Keep-Fds",fd
[1]);
1377 // we read from dpkg here
1378 int const _dpkgin
= fd
[0];
1379 close(fd
[1]); // close the write end of the pipe
1385 sigemptyset(&sigmask
);
1386 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
1388 /* free vectors (and therefore memory) as we don't need the included data anymore */
1389 for (std::vector
<char *>::const_iterator p
= Packages
.begin();
1390 p
!= Packages
.end(); ++p
)
1394 // the result of the waitpid call
1397 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
1399 // FIXME: move this to a function or something, looks ugly here
1400 // error handling, waitpid returned -1
1403 RunScripts("DPkg::Post-Invoke");
1405 // Restore sig int/quit
1406 signal(SIGQUIT
,old_SIGQUIT
);
1407 signal(SIGINT
,old_SIGINT
);
1409 signal(SIGHUP
,old_SIGHUP
);
1410 return _error
->Errno("waitpid","Couldn't wait for subprocess");
1413 // wait for input or output here
1415 if (master
>= 0 && !d
->stdin_is_dev_null
)
1417 FD_SET(_dpkgin
, &rfds
);
1419 FD_SET(master
, &rfds
);
1422 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
1423 &tv
, &original_sigmask
);
1424 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
1425 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
1426 NULL
, &tv
, &original_sigmask
);
1427 if (select_ret
== 0)
1429 else if (select_ret
< 0 && errno
== EINTR
)
1431 else if (select_ret
< 0)
1433 perror("select() returned error");
1437 if(master
>= 0 && FD_ISSET(master
, &rfds
))
1438 DoTerminalPty(master
);
1439 if(master
>= 0 && FD_ISSET(0, &rfds
))
1441 if(FD_ISSET(_dpkgin
, &rfds
))
1442 DoDpkgStatusFd(_dpkgin
, OutStatusFd
);
1446 // Restore sig int/quit
1447 signal(SIGQUIT
,old_SIGQUIT
);
1448 signal(SIGINT
,old_SIGINT
);
1450 signal(SIGHUP
,old_SIGHUP
);
1454 tcsetattr(0, TCSAFLUSH
, &tt
);
1458 // Check for an error code.
1459 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
1461 // if it was set to "keep-dpkg-runing" then we won't return
1462 // here but keep the loop going and just report it as a error
1464 bool const stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
1467 RunScripts("DPkg::Post-Invoke");
1469 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
1470 strprintf(d
->dpkg_error
, "Sub-process %s received a segmentation fault.",Args
[0]);
1471 else if (WIFEXITED(Status
) != 0)
1472 strprintf(d
->dpkg_error
, "Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
1474 strprintf(d
->dpkg_error
, "Sub-process %s exited unexpectedly",Args
[0]);
1476 if(d
->dpkg_error
.size() > 0)
1477 _error
->Error("%s", d
->dpkg_error
.c_str());
1488 // dpkg is done at this point
1489 if(_config
->FindB("DPkgPM::Progress", false) == true)
1490 SendTerminalProgress(100);
1492 if (pkgPackageManager::SigINTStop
)
1493 _error
->Warning(_("Operation was interrupted before it could finish"));
1495 if (RunScripts("DPkg::Post-Invoke") == false)
1498 if (_config
->FindB("Debug::pkgDPkgPM",false) == false)
1500 std::string
const oldpkgcache
= _config
->FindFile("Dir::cache::pkgcache");
1501 if (oldpkgcache
.empty() == false && RealFileExists(oldpkgcache
) == true &&
1502 unlink(oldpkgcache
.c_str()) == 0)
1504 std::string
const srcpkgcache
= _config
->FindFile("Dir::cache::srcpkgcache");
1505 if (srcpkgcache
.empty() == false && RealFileExists(srcpkgcache
) == true)
1507 _error
->PushToStack();
1508 pkgCacheFile CacheFile
;
1509 CacheFile
.BuildCaches(NULL
, true);
1510 _error
->RevertToStack();
1515 Cache
.writeStateFile(NULL
);
1519 void SigINT(int sig
) {
1520 pkgPackageManager::SigINTStop
= true;
1523 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1524 // ---------------------------------------------------------------------
1526 void pkgDPkgPM::Reset()
1528 List
.erase(List
.begin(),List
.end());
1531 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1532 // ---------------------------------------------------------------------
1534 void pkgDPkgPM::WriteApportReport(const char *pkgpath
, const char *errormsg
)
1536 // If apport doesn't exist or isn't installed do nothing
1537 // This e.g. prevents messages in 'universes' without apport
1538 pkgCache::PkgIterator apportPkg
= Cache
.FindPkg("apport");
1539 if (apportPkg
.end() == true || apportPkg
->CurrentVer
== 0)
1542 string pkgname
, reportfile
, srcpkgname
, pkgver
, arch
;
1543 string::size_type pos
;
1546 if (_config
->FindB("Dpkg::ApportFailureReport", false) == false)
1548 std::clog
<< "configured to not write apport reports" << std::endl
;
1552 // only report the first errors
1553 if(pkgFailures
> _config
->FindI("APT::Apport::MaxReports", 3))
1555 std::clog
<< _("No apport report written because MaxReports is reached already") << std::endl
;
1559 // check if its not a follow up error
1560 const char *needle
= dgettext("dpkg", "dependency problems - leaving unconfigured");
1561 if(strstr(errormsg
, needle
) != NULL
) {
1562 std::clog
<< _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl
;
1566 // do not report disk-full failures
1567 if(strstr(errormsg
, strerror(ENOSPC
)) != NULL
) {
1568 std::clog
<< _("No apport report written because the error message indicates a disk full error") << std::endl
;
1572 // do not report out-of-memory failures
1573 if(strstr(errormsg
, strerror(ENOMEM
)) != NULL
) {
1574 std::clog
<< _("No apport report written because the error message indicates a out of memory error") << std::endl
;
1578 // do not report dpkg I/O errors
1579 // XXX - this message is localized, but this only matches the English version. This is better than nothing.
1580 if(strstr(errormsg
, "short read in buffer_copy (")) {
1581 std::clog
<< _("No apport report written because the error message indicates a dpkg I/O error") << std::endl
;
1585 // get the pkgname and reportfile
1586 pkgname
= flNotDir(pkgpath
);
1587 pos
= pkgname
.find('_');
1588 if(pos
!= string::npos
)
1589 pkgname
= pkgname
.substr(0, pos
);
1591 // find the package versin and source package name
1592 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
1593 if (Pkg
.end() == true)
1595 pkgCache::VerIterator Ver
= Cache
.GetCandidateVer(Pkg
);
1596 if (Ver
.end() == true)
1598 pkgver
= Ver
.VerStr() == NULL
? "unknown" : Ver
.VerStr();
1599 pkgRecords
Recs(Cache
);
1600 pkgRecords::Parser
&Parse
= Recs
.Lookup(Ver
.FileList());
1601 srcpkgname
= Parse
.SourcePkg();
1602 if(srcpkgname
.empty())
1603 srcpkgname
= pkgname
;
1605 // if the file exists already, we check:
1606 // - if it was reported already (touched by apport).
1607 // If not, we do nothing, otherwise
1608 // we overwrite it. This is the same behaviour as apport
1609 // - if we have a report with the same pkgversion already
1611 reportfile
= flCombine("/var/crash",pkgname
+".0.crash");
1612 if(FileExists(reportfile
))
1617 // check atime/mtime
1618 stat(reportfile
.c_str(), &buf
);
1619 if(buf
.st_mtime
> buf
.st_atime
)
1622 // check if the existing report is the same version
1623 report
= fopen(reportfile
.c_str(),"r");
1624 while(fgets(strbuf
, sizeof(strbuf
), report
) != NULL
)
1626 if(strstr(strbuf
,"Package:") == strbuf
)
1628 char pkgname
[255], version
[255];
1629 if(sscanf(strbuf
, "Package: %254s %254s", pkgname
, version
) == 2)
1630 if(strcmp(pkgver
.c_str(), version
) == 0)
1640 // now write the report
1641 arch
= _config
->Find("APT::Architecture");
1642 report
= fopen(reportfile
.c_str(),"w");
1645 if(_config
->FindB("DPkgPM::InitialReportOnly",false) == true)
1646 chmod(reportfile
.c_str(), 0);
1648 chmod(reportfile
.c_str(), 0600);
1649 fprintf(report
, "ProblemType: Package\n");
1650 fprintf(report
, "Architecture: %s\n", arch
.c_str());
1651 time_t now
= time(NULL
);
1652 fprintf(report
, "Date: %s" , ctime(&now
));
1653 fprintf(report
, "Package: %s %s\n", pkgname
.c_str(), pkgver
.c_str());
1654 fprintf(report
, "SourcePackage: %s\n", srcpkgname
.c_str());
1655 fprintf(report
, "ErrorMessage:\n %s\n", errormsg
);
1657 // ensure that the log is flushed
1659 fflush(d
->term_out
);
1661 // attach terminal log it if we have it
1662 string logfile_name
= _config
->FindFile("Dir::Log::Terminal");
1663 if (!logfile_name
.empty())
1667 fprintf(report
, "DpkgTerminalLog:\n");
1668 log
= fopen(logfile_name
.c_str(),"r");
1672 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1673 fprintf(report
, " %s", buf
);
1679 const char *ops_str
[] = {"Install", "Configure","Remove","Purge"};
1680 fprintf(report
, "AptOrdering:\n");
1681 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
1682 if ((*I
).Pkg
!= NULL
)
1683 fprintf(report
, " %s: %s\n", (*I
).Pkg
.Name(), ops_str
[(*I
).Op
]);
1685 fprintf(report
, " %s: %s\n", "NULL", ops_str
[(*I
).Op
]);
1687 // attach dmesg log (to learn about segfaults)
1688 if (FileExists("/bin/dmesg"))
1690 fprintf(report
, "Dmesg:\n");
1691 FILE *log
= popen("/bin/dmesg","r");
1695 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1696 fprintf(report
, " %s", buf
);
1701 // attach df -l log (to learn about filesystem status)
1702 if (FileExists("/bin/df"))
1705 fprintf(report
, "Df:\n");
1706 FILE *log
= popen("/bin/df -l","r");
1710 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1711 fprintf(report
, " %s", buf
);