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/iprogress.h>
27 #include <sys/select.h>
29 #include <sys/types.h>
45 #include <sys/ioctl.h>
53 class pkgDPkgPMPrivate
56 pkgDPkgPMPrivate() : stdin_is_dev_null(false), dpkgbuf_pos(0),
57 term_out(NULL
), history_out(NULL
),
58 last_reported_progress(0.0)
61 if(_config
->FindB("Dpkg::Progress-Fancy", false) == true)
62 progress
= new APT::Progress::PackageManagerFancy();
63 else if (_config
->FindB("Dpkg::Progress",
64 _config
->FindB("DpkgPM::Progress", false)) == true)
65 progress
= new APT::Progress::PackageManagerText();
67 progress
= new APT::Progress::PackageManager();
74 bool stdin_is_dev_null
;
75 // the buffer we use for the dpkg status-fd reading
82 float last_reported_progress
;
83 APT::Progress::PackageManager
*progress
;
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 // dpkgChrootDirectory - chrooting for dpkg if needed /*{{{*/
147 static void dpkgChrootDirectory()
149 std::string
const chrootDir
= _config
->FindDir("DPkg::Chroot-Directory");
150 if (chrootDir
== "/")
152 std::cerr
<< "Chrooting into " << chrootDir
<< std::endl
;
153 if (chroot(chrootDir
.c_str()) != 0)
161 // FindNowVersion - Helper to find a Version in "now" state /*{{{*/
162 // ---------------------------------------------------------------------
163 /* This is helpful when a package is no longer installed but has residual
167 pkgCache::VerIterator
FindNowVersion(const pkgCache::PkgIterator
&Pkg
)
169 pkgCache::VerIterator Ver
;
170 for (Ver
= Pkg
.VersionList(); Ver
.end() == false; ++Ver
)
172 pkgCache::VerFileIterator Vf
= Ver
.FileList();
173 pkgCache::PkgFileIterator F
= Vf
.File();
174 for (F
= Vf
.File(); F
.end() == false; ++F
)
176 if (F
&& F
.Archive())
178 if (strcmp(F
.Archive(), "now"))
187 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
188 // ---------------------------------------------------------------------
190 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
191 : pkgPackageManager(Cache
), PackagesDone(0), PackagesTotal(0)
193 d
= new pkgDPkgPMPrivate();
196 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
197 // ---------------------------------------------------------------------
199 pkgDPkgPM::~pkgDPkgPM()
204 // DPkgPM::Install - Install a package /*{{{*/
205 // ---------------------------------------------------------------------
206 /* Add an install operation to the sequence list */
207 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
209 if (File
.empty() == true || Pkg
.end() == true)
210 return _error
->Error("Internal Error, No file name for %s",Pkg
.FullName().c_str());
212 // If the filename string begins with DPkg::Chroot-Directory, return the
213 // substr that is within the chroot so dpkg can access it.
214 string
const chrootdir
= _config
->FindDir("DPkg::Chroot-Directory","/");
215 if (chrootdir
!= "/" && File
.find(chrootdir
) == 0)
217 size_t len
= chrootdir
.length();
218 if (chrootdir
.at(len
- 1) == '/')
220 List
.push_back(Item(Item::Install
,Pkg
,File
.substr(len
)));
223 List
.push_back(Item(Item::Install
,Pkg
,File
));
228 // DPkgPM::Configure - Configure a package /*{{{*/
229 // ---------------------------------------------------------------------
230 /* Add a configure operation to the sequence list */
231 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
233 if (Pkg
.end() == true)
236 List
.push_back(Item(Item::Configure
, Pkg
));
238 // Use triggers for config calls if we configure "smart"
239 // as otherwise Pre-Depends will not be satisfied, see #526774
240 if (_config
->FindB("DPkg::TriggersPending", false) == true)
241 List
.push_back(Item(Item::TriggersPending
, PkgIterator()));
246 // DPkgPM::Remove - Remove a package /*{{{*/
247 // ---------------------------------------------------------------------
248 /* Add a remove operation to the sequence list */
249 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
251 if (Pkg
.end() == true)
255 List
.push_back(Item(Item::Purge
,Pkg
));
257 List
.push_back(Item(Item::Remove
,Pkg
));
261 // DPkgPM::SendPkgInfo - Send info for install-pkgs hook /*{{{*/
262 // ---------------------------------------------------------------------
263 /* This is part of the helper script communication interface, it sends
264 very complete information down to the other end of the pipe.*/
265 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
267 return SendPkgsInfo(F
, 2);
269 bool pkgDPkgPM::SendPkgsInfo(FILE * const F
, unsigned int const &Version
)
271 // This version of APT supports only v3, so don't sent higher versions
273 fprintf(F
,"VERSION %u\n", Version
);
275 fprintf(F
,"VERSION 3\n");
277 /* Write out all of the configuration directives by walking the
278 configuration tree */
279 const Configuration::Item
*Top
= _config
->Tree(0);
282 if (Top
->Value
.empty() == false)
285 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
286 QuoteString(Top
->Value
,"\n").c_str());
295 while (Top
!= 0 && Top
->Next
== 0)
302 // Write out the package actions in order.
303 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
305 if(I
->Pkg
.end() == true)
308 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
310 fprintf(F
,"%s ",I
->Pkg
.Name());
312 // Current version which we are going to replace
313 pkgCache::VerIterator CurVer
= I
->Pkg
.CurrentVer();
314 if (CurVer
.end() == true && (I
->Op
== Item::Remove
|| I
->Op
== Item::Purge
))
315 CurVer
= FindNowVersion(I
->Pkg
);
317 if (CurVer
.end() == true)
322 fprintf(F
, "- - none ");
326 fprintf(F
, "%s ", CurVer
.VerStr());
328 fprintf(F
, "%s %s ", CurVer
.Arch(), CurVer
.MultiArchType());
331 // Show the compare operator between current and install version
332 if (S
.InstallVer
!= 0)
334 pkgCache::VerIterator
const InstVer
= S
.InstVerIter(Cache
);
336 if (CurVer
.end() == false)
337 Comp
= InstVer
.CompareVer(CurVer
);
344 fprintf(F
, "%s ", InstVer
.VerStr());
346 fprintf(F
, "%s %s ", InstVer
.Arch(), InstVer
.MultiArchType());
353 fprintf(F
, "> - - none ");
356 // Show the filename/operation
357 if (I
->Op
== Item::Install
)
360 if (I
->File
[0] != '/')
361 fprintf(F
,"**ERROR**\n");
363 fprintf(F
,"%s\n",I
->File
.c_str());
365 else if (I
->Op
== Item::Configure
)
366 fprintf(F
,"**CONFIGURE**\n");
367 else if (I
->Op
== Item::Remove
||
368 I
->Op
== Item::Purge
)
369 fprintf(F
,"**REMOVE**\n");
377 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
378 // ---------------------------------------------------------------------
379 /* This looks for a list of scripts to run from the configuration file
380 each one is run and is fed on standard input a list of all .deb files
381 that are due to be installed. */
382 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
384 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
385 if (Opts
== 0 || Opts
->Child
== 0)
389 unsigned int Count
= 1;
390 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
392 if (Opts
->Value
.empty() == true)
395 // Determine the protocol version
396 string OptSec
= Opts
->Value
;
397 string::size_type Pos
;
398 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
399 Pos
= OptSec
.length();
400 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
402 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
403 unsigned int InfoFD
= _config
->FindI(OptSec
+ "::InfoFD", STDIN_FILENO
);
407 if (pipe(Pipes
) != 0)
408 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
409 if (InfoFD
!= (unsigned)Pipes
[0])
410 SetCloseExec(Pipes
[0],true);
412 _config
->Set("APT::Keep-Fds::", Pipes
[0]);
413 SetCloseExec(Pipes
[1],true);
415 // Purified Fork for running the script
416 pid_t Process
= ExecFork();
420 dup2(Pipes
[0], InfoFD
);
421 SetCloseExec(STDOUT_FILENO
,false);
422 SetCloseExec(STDIN_FILENO
,false);
423 SetCloseExec(STDERR_FILENO
,false);
426 strprintf(hookfd
, "%d", InfoFD
);
427 setenv("APT_HOOK_INFO_FD", hookfd
.c_str(), 1);
429 dpkgChrootDirectory();
433 Args
[2] = Opts
->Value
.c_str();
435 execv(Args
[0],(char **)Args
);
438 if (InfoFD
== (unsigned)Pipes
[0])
439 _config
->Clear("APT::Keep-Fds", Pipes
[0]);
441 FILE *F
= fdopen(Pipes
[1],"w");
443 return _error
->Errno("fdopen","Faild to open new FD");
445 // Feed it the filenames.
448 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
450 // Only deal with packages to be installed from .deb
451 if (I
->Op
!= Item::Install
)
455 if (I
->File
[0] != '/')
458 /* Feed the filename of each package that is pending install
460 fprintf(F
,"%s\n",I
->File
.c_str());
466 SendPkgsInfo(F
, Version
);
470 // Clean up the sub process
471 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
472 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
478 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
479 // ---------------------------------------------------------------------
482 void pkgDPkgPM::DoStdin(int master
)
484 unsigned char input_buf
[256] = {0,};
485 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
487 FileFd::Write(master
, input_buf
, len
);
489 d
->stdin_is_dev_null
= true;
492 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
493 // ---------------------------------------------------------------------
495 * read the terminal pty and write log
497 void pkgDPkgPM::DoTerminalPty(int master
)
499 unsigned char term_buf
[1024] = {0,0, };
501 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
502 if(len
== -1 && errno
== EIO
)
504 // this happens when the child is about to exit, we
505 // give it time to actually exit, otherwise we run
506 // into a race so we sleep for half a second.
507 struct timespec sleepfor
= { 0, 500000000 };
508 nanosleep(&sleepfor
, NULL
);
513 FileFd::Write(1, term_buf
, len
);
515 fwrite(term_buf
, len
, sizeof(char), d
->term_out
);
518 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
519 // ---------------------------------------------------------------------
522 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd
, char *line
)
524 bool const Debug
= _config
->FindB("Debug::pkgDPkgProgressReporting",false);
525 // the status we output
526 ostringstream status
;
529 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
532 /* dpkg sends strings like this:
533 'status: <pkg>: <pkg qstate>'
534 'status: <pkg>:<arch>: <pkg qstate>'
535 errors look like this:
536 '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
537 and conffile-prompt like this
538 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
540 Newer versions of dpkg sent also:
541 'processing: install: pkg'
542 'processing: configure: pkg'
543 'processing: remove: pkg'
544 'processing: purge: pkg'
545 'processing: disappear: pkg'
546 'processing: trigproc: trigger'
549 // we need to split on ": " (note the appended space) as the ':' is
550 // part of the pkgname:arch information that dpkg sends
552 // A dpkg error message may contain additional ":" (like
553 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
554 // so we need to ensure to not split too much
555 std::vector
<std::string
> list
= StringSplit(line
, ": ", 3);
559 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
562 // dpkg does not send always send "pkgname:arch" so we add it here if needed
563 std::string pkgname
= list
[1];
564 if (pkgname
.find(":") == std::string::npos
)
566 string
const nativeArch
= _config
->Find("APT::Architecture");
567 pkgname
= pkgname
+ ":" + nativeArch
;
569 const char* const pkg
= pkgname
.c_str();
570 const char* action
= list
[2].c_str();
572 // 'processing' from dpkg looks like
573 // 'processing: action: pkg'
574 if(strncmp(list
[0].c_str(), "processing", strlen("processing")) == 0)
577 const char* const pkg_or_trigger
= list
[2].c_str();
578 action
= list
[1].c_str();
579 const std::pair
<const char *, const char *> * const iter
=
580 std::find_if(PackageProcessingOpsBegin
,
581 PackageProcessingOpsEnd
,
582 MatchProcessingOp(action
));
583 if(iter
== PackageProcessingOpsEnd
)
586 std::clog
<< "ignoring unknown action: " << action
<< std::endl
;
589 snprintf(s
, sizeof(s
), _(iter
->second
), pkg_or_trigger
);
591 status
<< "pmstatus:" << pkg_or_trigger
592 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
596 FileFd::Write(OutStatusFd
, status
.str().c_str(), status
.str().size());
598 std::clog
<< "send: '" << status
.str() << "'" << endl
;
600 if (strncmp(action
, "disappear", strlen("disappear")) == 0)
601 handleDisappearAction(pkg_or_trigger
);
605 if(strncmp(action
,"error",strlen("error")) == 0)
607 status
<< "pmerror:" << 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
;
616 WriteApportReport(list
[1].c_str(), list
[3].c_str());
619 else if(strncmp(action
,"conffile",strlen("conffile")) == 0)
621 status
<< "pmconffile:" << list
[1]
622 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
626 FileFd::Write(OutStatusFd
, status
.str().c_str(), status
.str().size());
628 std::clog
<< "send: '" << status
.str() << "'" << endl
;
632 vector
<struct DpkgState
> const &states
= PackageOps
[pkg
];
633 const char *next_action
= NULL
;
634 if(PackageOpsDone
[pkg
] < states
.size())
635 next_action
= states
[PackageOpsDone
[pkg
]].state
;
636 // check if the package moved to the next dpkg state
637 if(next_action
&& (strcmp(action
, next_action
) == 0))
639 // only read the translation if there is actually a next
641 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
643 snprintf(s
, sizeof(s
), translation
, pkg
);
645 // we moved from one dpkg state to a new one, report that
646 PackageOpsDone
[pkg
]++;
648 // build the status str
649 status
<< "pmstatus:" << pkg
650 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
653 d
->progress
->StatusChanged(pkg
, PackagesDone
, PackagesTotal
);
656 FileFd::Write(OutStatusFd
, status
.str().c_str(), status
.str().size());
658 std::clog
<< "send: '" << status
.str() << "'" << endl
;
661 std::clog
<< "(parsed from dpkg) pkg: " << pkg
662 << " action: " << action
<< endl
;
665 // DPkgPM::handleDisappearAction /*{{{*/
666 void pkgDPkgPM::handleDisappearAction(string
const &pkgname
)
668 // record the package name for display and stuff later
669 disappearedPkgs
.insert(pkgname
);
671 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
672 if (unlikely(Pkg
.end() == true))
674 // the disappeared package was auto-installed - nothing to do
675 if ((Cache
[Pkg
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
677 pkgCache::VerIterator PkgVer
= Cache
[Pkg
].InstVerIter(Cache
);
678 if (unlikely(PkgVer
.end() == true))
680 /* search in the list of dependencies for (Pre)Depends,
681 check if this dependency has a Replaces on our package
682 and if so transfer the manual installed flag to it */
683 for (pkgCache::DepIterator Dep
= PkgVer
.DependsList(); Dep
.end() != true; ++Dep
)
685 if (Dep
->Type
!= pkgCache::Dep::Depends
&&
686 Dep
->Type
!= pkgCache::Dep::PreDepends
)
688 pkgCache::PkgIterator Tar
= Dep
.TargetPkg();
689 if (unlikely(Tar
.end() == true))
691 // the package is already marked as manual
692 if ((Cache
[Tar
].Flags
& pkgCache::Flag::Auto
) != pkgCache::Flag::Auto
)
694 pkgCache::VerIterator TarVer
= Cache
[Tar
].InstVerIter(Cache
);
695 if (TarVer
.end() == true)
697 for (pkgCache::DepIterator Rep
= TarVer
.DependsList(); Rep
.end() != true; ++Rep
)
699 if (Rep
->Type
!= pkgCache::Dep::Replaces
)
701 if (Pkg
!= Rep
.TargetPkg())
703 // okay, they are strongly connected - transfer manual-bit
705 std::clog
<< "transfer manual-bit from disappeared »" << pkgname
<< "« to »" << Tar
.FullName() << "«" << std::endl
;
706 Cache
[Tar
].Flags
&= ~Flag::Auto
;
712 // DPkgPM::DoDpkgStatusFd /*{{{*/
713 // ---------------------------------------------------------------------
716 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
, int OutStatusFd
)
721 len
=read(statusfd
, &d
->dpkgbuf
[d
->dpkgbuf_pos
], sizeof(d
->dpkgbuf
)-d
->dpkgbuf_pos
);
722 d
->dpkgbuf_pos
+= len
;
726 // process line by line if we have a buffer
728 while((q
=(char*)memchr(p
, '\n', d
->dpkgbuf
+d
->dpkgbuf_pos
-p
)) != NULL
)
731 ProcessDpkgStatusLine(OutStatusFd
, p
);
732 p
=q
+1; // continue with next line
735 // now move the unprocessed bits (after the final \n that is now a 0x0)
736 // to the start and update d->dpkgbuf_pos
737 p
= (char*)memrchr(d
->dpkgbuf
, 0, d
->dpkgbuf_pos
);
741 // we are interessted in the first char *after* 0x0
744 // move the unprocessed tail to the start and update pos
745 memmove(d
->dpkgbuf
, p
, p
-d
->dpkgbuf
);
746 d
->dpkgbuf_pos
= d
->dpkgbuf
+d
->dpkgbuf_pos
-p
;
749 // DPkgPM::WriteHistoryTag /*{{{*/
750 void pkgDPkgPM::WriteHistoryTag(string
const &tag
, string value
)
752 size_t const length
= value
.length();
755 // poor mans rstrip(", ")
756 if (value
[length
-2] == ',' && value
[length
-1] == ' ')
757 value
.erase(length
- 2, 2);
758 fprintf(d
->history_out
, "%s: %s\n", tag
.c_str(), value
.c_str());
760 // DPkgPM::OpenLog /*{{{*/
761 bool pkgDPkgPM::OpenLog()
763 string
const logdir
= _config
->FindDir("Dir::Log");
764 if(CreateAPTDirectoryIfNeeded(logdir
, logdir
) == false)
765 // FIXME: use a better string after freeze
766 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
770 time_t const t
= time(NULL
);
771 struct tm
const * const tmp
= localtime(&t
);
772 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
775 string
const logfile_name
= flCombine(logdir
,
776 _config
->Find("Dir::Log::Terminal"));
777 if (!logfile_name
.empty())
779 d
->term_out
= fopen(logfile_name
.c_str(),"a");
780 if (d
->term_out
== NULL
)
781 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name
.c_str());
782 setvbuf(d
->term_out
, NULL
, _IONBF
, 0);
783 SetCloseExec(fileno(d
->term_out
), true);
784 if (getuid() == 0) // if we aren't root, we can't chown a file, so don't try it
786 struct passwd
*pw
= getpwnam("root");
787 struct group
*gr
= getgrnam("adm");
788 if (pw
!= NULL
&& gr
!= NULL
&& chown(logfile_name
.c_str(), pw
->pw_uid
, gr
->gr_gid
) != 0)
789 _error
->WarningE("OpenLog", "chown to root:adm of file %s failed", logfile_name
.c_str());
791 if (chmod(logfile_name
.c_str(), 0640) != 0)
792 _error
->WarningE("OpenLog", "chmod 0640 of file %s failed", logfile_name
.c_str());
793 fprintf(d
->term_out
, "\nLog started: %s\n", timestr
);
796 // write your history
797 string
const history_name
= flCombine(logdir
,
798 _config
->Find("Dir::Log::History"));
799 if (!history_name
.empty())
801 d
->history_out
= fopen(history_name
.c_str(),"a");
802 if (d
->history_out
== NULL
)
803 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), history_name
.c_str());
804 SetCloseExec(fileno(d
->history_out
), true);
805 chmod(history_name
.c_str(), 0644);
806 fprintf(d
->history_out
, "\nStart-Date: %s\n", timestr
);
807 string remove
, purge
, install
, reinstall
, upgrade
, downgrade
;
808 for (pkgCache::PkgIterator I
= Cache
.PkgBegin(); I
.end() == false; ++I
)
810 enum { CANDIDATE
, CANDIDATE_AUTO
, CURRENT_CANDIDATE
, CURRENT
} infostring
;
812 #define HISTORYINFO(X, Y) { line = &X; infostring = Y; }
813 if (Cache
[I
].NewInstall() == true)
814 HISTORYINFO(install
, CANDIDATE_AUTO
)
815 else if (Cache
[I
].ReInstall() == true)
816 HISTORYINFO(reinstall
, CANDIDATE
)
817 else if (Cache
[I
].Upgrade() == true)
818 HISTORYINFO(upgrade
, CURRENT_CANDIDATE
)
819 else if (Cache
[I
].Downgrade() == true)
820 HISTORYINFO(downgrade
, CURRENT_CANDIDATE
)
821 else if (Cache
[I
].Delete() == true)
822 HISTORYINFO((Cache
[I
].Purge() ? purge
: remove
), CURRENT
)
826 line
->append(I
.FullName(false)).append(" (");
827 switch (infostring
) {
828 case CANDIDATE
: line
->append(Cache
[I
].CandVersion
); break;
830 line
->append(Cache
[I
].CandVersion
);
831 if ((Cache
[I
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
832 line
->append(", automatic");
834 case CURRENT_CANDIDATE
: line
->append(Cache
[I
].CurVersion
).append(", ").append(Cache
[I
].CandVersion
); break;
835 case CURRENT
: line
->append(Cache
[I
].CurVersion
); break;
839 if (_config
->Exists("Commandline::AsString") == true)
840 WriteHistoryTag("Commandline", _config
->Find("Commandline::AsString"));
841 WriteHistoryTag("Install", install
);
842 WriteHistoryTag("Reinstall", reinstall
);
843 WriteHistoryTag("Upgrade", upgrade
);
844 WriteHistoryTag("Downgrade",downgrade
);
845 WriteHistoryTag("Remove",remove
);
846 WriteHistoryTag("Purge",purge
);
847 fflush(d
->history_out
);
853 // DPkg::CloseLog /*{{{*/
854 bool pkgDPkgPM::CloseLog()
857 time_t t
= time(NULL
);
858 struct tm
*tmp
= localtime(&t
);
859 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
863 fprintf(d
->term_out
, "Log ended: ");
864 fprintf(d
->term_out
, "%s", timestr
);
865 fprintf(d
->term_out
, "\n");
872 if (disappearedPkgs
.empty() == false)
875 for (std::set
<std::string
>::const_iterator d
= disappearedPkgs
.begin();
876 d
!= disappearedPkgs
.end(); ++d
)
878 pkgCache::PkgIterator P
= Cache
.FindPkg(*d
);
879 disappear
.append(*d
);
881 disappear
.append(", ");
883 disappear
.append(" (").append(Cache
[P
].CurVersion
).append("), ");
885 WriteHistoryTag("Disappeared", disappear
);
887 if (d
->dpkg_error
.empty() == false)
888 fprintf(d
->history_out
, "Error: %s\n", d
->dpkg_error
.c_str());
889 fprintf(d
->history_out
, "End-Date: %s\n", timestr
);
890 fclose(d
->history_out
);
892 d
->history_out
= NULL
;
897 // This implements a racy version of pselect for those architectures
898 // that don't have a working implementation.
899 // FIXME: Probably can be removed on Lenny+1
900 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
901 fd_set
*exceptfds
, const struct timespec
*timeout
,
902 const sigset_t
*sigmask
)
908 tv
.tv_sec
= timeout
->tv_sec
;
909 tv
.tv_usec
= timeout
->tv_nsec
/1000;
911 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
912 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
913 sigprocmask(SIG_SETMASK
, &origmask
, 0);
919 // DPkgPM::Go - Run the sequence /*{{{*/
920 // ---------------------------------------------------------------------
921 /* This globs the operations and calls dpkg
923 * If it is called with "OutStatusFd" set to a valid file descriptor
924 * apt will report the install progress over this fd. It maps the
925 * dpkg states a package goes through to human readable (and i10n-able)
926 * names and calculates a percentage for each step.
928 bool pkgDPkgPM::Go(int OutStatusFd
)
930 pkgPackageManager::SigINTStop
= false;
932 // Generate the base argument list for dpkg
933 std::vector
<const char *> Args
;
934 unsigned long StartSize
= 0;
935 string Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
937 string
const dpkgChrootDir
= _config
->FindDir("DPkg::Chroot-Directory", "/");
938 size_t dpkgChrootLen
= dpkgChrootDir
.length();
939 if (dpkgChrootDir
!= "/" && Tmp
.find(dpkgChrootDir
) == 0)
941 if (dpkgChrootDir
[dpkgChrootLen
- 1] == '/')
943 Tmp
= Tmp
.substr(dpkgChrootLen
);
946 Args
.push_back(Tmp
.c_str());
947 StartSize
+= Tmp
.length();
949 // Stick in any custom dpkg options
950 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
954 for (; Opts
!= 0; Opts
= Opts
->Next
)
956 if (Opts
->Value
.empty() == true)
958 Args
.push_back(Opts
->Value
.c_str());
959 StartSize
+= Opts
->Value
.length();
963 size_t const BaseArgs
= Args
.size();
964 // we need to detect if we can qualify packages with the architecture or not
965 Args
.push_back("--assert-multi-arch");
966 Args
.push_back(NULL
);
968 pid_t dpkgAssertMultiArch
= ExecFork();
969 if (dpkgAssertMultiArch
== 0)
971 dpkgChrootDirectory();
972 // redirect everything to the ultimate sink as we only need the exit-status
973 int const nullfd
= open("/dev/null", O_RDONLY
);
974 dup2(nullfd
, STDIN_FILENO
);
975 dup2(nullfd
, STDOUT_FILENO
);
976 dup2(nullfd
, STDERR_FILENO
);
977 execvp(Args
[0], (char**) &Args
[0]);
978 _error
->WarningE("dpkgGo", "Can't detect if dpkg supports multi-arch!");
985 sigset_t original_sigmask
;
987 unsigned int const MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
988 unsigned int const MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
989 bool const NoTriggers
= _config
->FindB("DPkg::NoTriggers", false);
991 if (RunScripts("DPkg::Pre-Invoke") == false)
994 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
997 // support subpressing of triggers processing for special
998 // cases like d-i that runs the triggers handling manually
999 bool const SmartConf
= (_config
->Find("PackageManager::Configure", "all") != "all");
1000 bool const TriggersPending
= _config
->FindB("DPkg::TriggersPending", false);
1001 if (_config
->FindB("DPkg::ConfigurePending", SmartConf
) == true)
1002 List
.push_back(Item(Item::ConfigurePending
, PkgIterator()));
1004 // map the dpkg states to the operations that are performed
1005 // (this is sorted in the same way as Item::Ops)
1006 static const struct DpkgState DpkgStatesOpMap
[][7] = {
1007 // Install operation
1009 {"half-installed", N_("Preparing %s")},
1010 {"unpacked", N_("Unpacking %s") },
1013 // Configure operation
1015 {"unpacked",N_("Preparing to configure %s") },
1016 {"half-configured", N_("Configuring %s") },
1017 { "installed", N_("Installed %s")},
1022 {"half-configured", N_("Preparing for removal of %s")},
1023 {"half-installed", N_("Removing %s")},
1024 {"config-files", N_("Removed %s")},
1029 {"config-files", N_("Preparing to completely remove %s")},
1030 {"not-installed", N_("Completely removed %s")},
1035 // init the PackageOps map, go over the list of packages that
1036 // that will be [installed|configured|removed|purged] and add
1037 // them to the PackageOps map (the dpkg states it goes through)
1038 // and the PackageOpsTranslations (human readable strings)
1039 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end(); ++I
)
1041 if((*I
).Pkg
.end() == true)
1044 string
const name
= (*I
).Pkg
.FullName();
1045 PackageOpsDone
[name
] = 0;
1046 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; ++i
)
1048 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
1053 d
->stdin_is_dev_null
= false;
1058 bool dpkgMultiArch
= false;
1059 if (dpkgAssertMultiArch
> 0)
1062 while (waitpid(dpkgAssertMultiArch
, &Status
, 0) != dpkgAssertMultiArch
)
1066 _error
->WarningE("dpkgGo", _("Waited for %s but it wasn't there"), "dpkg --assert-multi-arch");
1069 if (WIFEXITED(Status
) == true && WEXITSTATUS(Status
) == 0)
1070 dpkgMultiArch
= true;
1073 // this loop is runs once per operation
1074 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();)
1076 // Do all actions with the same Op in one run
1077 vector
<Item
>::const_iterator J
= I
;
1078 if (TriggersPending
== true)
1079 for (; J
!= List
.end(); ++J
)
1083 if (J
->Op
!= Item::TriggersPending
)
1085 vector
<Item
>::const_iterator T
= J
+ 1;
1086 if (T
!= List
.end() && T
->Op
== I
->Op
)
1091 for (; J
!= List
.end() && J
->Op
== I
->Op
; ++J
)
1094 // keep track of allocated strings for multiarch package names
1095 std::vector
<char *> Packages
;
1097 // start with the baseset of arguments
1098 unsigned long Size
= StartSize
;
1099 Args
.erase(Args
.begin() + BaseArgs
, Args
.end());
1101 // Now check if we are within the MaxArgs limit
1103 // this code below is problematic, because it may happen that
1104 // the argument list is split in a way that A depends on B
1105 // and they are in the same "--configure A B" run
1106 // - with the split they may now be configured in different
1107 // runs, using Immediate-Configure-All can help prevent this.
1108 if (J
- I
> (signed)MaxArgs
)
1111 unsigned long const size
= MaxArgs
+ 10;
1113 Packages
.reserve(size
);
1117 unsigned long const size
= (J
- I
) + 10;
1119 Packages
.reserve(size
);
1124 return _error
->Errno("pipe","Failed to create IPC pipe to dpkg");
1126 #define ADDARG(X) Args.push_back(X); Size += strlen(X)
1127 #define ADDARGC(X) Args.push_back(X); Size += sizeof(X) - 1
1129 ADDARGC("--status-fd");
1130 char status_fd_buf
[20];
1131 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
1132 ADDARG(status_fd_buf
);
1133 unsigned long const Op
= I
->Op
;
1138 ADDARGC("--force-depends");
1139 ADDARGC("--force-remove-essential");
1140 ADDARGC("--remove");
1144 ADDARGC("--force-depends");
1145 ADDARGC("--force-remove-essential");
1149 case Item::Configure
:
1150 ADDARGC("--configure");
1153 case Item::ConfigurePending
:
1154 ADDARGC("--configure");
1155 ADDARGC("--pending");
1158 case Item::TriggersPending
:
1159 ADDARGC("--triggers-only");
1160 ADDARGC("--pending");
1164 ADDARGC("--unpack");
1165 ADDARGC("--auto-deconfigure");
1169 if (NoTriggers
== true && I
->Op
!= Item::TriggersPending
&&
1170 I
->Op
!= Item::ConfigurePending
)
1172 ADDARGC("--no-triggers");
1176 // Write in the file or package names
1177 if (I
->Op
== Item::Install
)
1179 for (;I
!= J
&& Size
< MaxArgBytes
; ++I
)
1181 if (I
->File
[0] != '/')
1182 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
1183 Args
.push_back(I
->File
.c_str());
1184 Size
+= I
->File
.length();
1189 string
const nativeArch
= _config
->Find("APT::Architecture");
1190 unsigned long const oldSize
= I
->Op
== Item::Configure
? Size
: 0;
1191 for (;I
!= J
&& Size
< MaxArgBytes
; ++I
)
1193 if((*I
).Pkg
.end() == true)
1195 if (I
->Op
== Item::Configure
&& disappearedPkgs
.find(I
->Pkg
.Name()) != disappearedPkgs
.end())
1197 // We keep this here to allow "smooth" transitions from e.g. multiarch dpkg/ubuntu to dpkg/debian
1198 if (dpkgMultiArch
== false && (I
->Pkg
.Arch() == nativeArch
||
1199 strcmp(I
->Pkg
.Arch(), "all") == 0 ||
1200 strcmp(I
->Pkg
.Arch(), "none") == 0))
1202 char const * const name
= I
->Pkg
.Name();
1207 pkgCache::VerIterator PkgVer
;
1208 std::string name
= I
->Pkg
.Name();
1209 if (Op
== Item::Remove
|| Op
== Item::Purge
)
1211 PkgVer
= I
->Pkg
.CurrentVer();
1212 if(PkgVer
.end() == true)
1213 PkgVer
= FindNowVersion(I
->Pkg
);
1216 PkgVer
= Cache
[I
->Pkg
].InstVerIter(Cache
);
1217 if (strcmp(I
->Pkg
.Arch(), "none") == 0)
1218 ; // never arch-qualify a package without an arch
1219 else if (PkgVer
.end() == false)
1220 name
.append(":").append(PkgVer
.Arch());
1222 _error
->Warning("Can not find PkgVer for '%s'", name
.c_str());
1223 char * const fullname
= strdup(name
.c_str());
1224 Packages
.push_back(fullname
);
1228 // skip configure action if all sheduled packages disappeared
1229 if (oldSize
== Size
)
1236 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
1238 for (std::vector
<const char *>::const_iterator a
= Args
.begin();
1239 a
!= Args
.end(); ++a
)
1244 Args
.push_back(NULL
);
1250 /* Mask off sig int/quit. We do this because dpkg also does when
1251 it forks scripts. What happens is that when you hit ctrl-c it sends
1252 it to all processes in the group. Since dpkg ignores the signal
1253 it doesn't die but we do! So we must also ignore it */
1254 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
1255 sighandler_t old_SIGINT
= signal(SIGINT
,SigINT
);
1257 // Check here for any SIGINT
1258 if (pkgPackageManager::SigINTStop
&& (Op
== Item::Remove
|| Op
== Item::Purge
|| Op
== Item::Install
))
1262 // ignore SIGHUP as well (debian #463030)
1263 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
1270 // if tcgetattr does not return zero there was a error
1271 // and we do not do any pty magic
1272 _error
->PushToStack();
1273 if (tcgetattr(STDOUT_FILENO
, &tt
) == 0)
1275 ioctl(STDOUT_FILENO
, TIOCGWINSZ
, (char *)&win
);
1276 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
1278 _error
->Errno("openpty", _("Can not write log (%s)"), _("Is /dev/pts mounted?"));
1279 master
= slave
= -1;
1284 rtt
.c_lflag
&= ~ECHO
;
1285 rtt
.c_lflag
|= ISIG
;
1286 // block SIGTTOU during tcsetattr to prevent a hang if
1287 // the process is a member of the background process group
1288 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
1289 sigemptyset(&sigmask
);
1290 sigaddset(&sigmask
, SIGTTOU
);
1291 sigprocmask(SIG_BLOCK
,&sigmask
, &original_sigmask
);
1292 tcsetattr(0, TCSAFLUSH
, &rtt
);
1293 sigprocmask(SIG_SETMASK
, &original_sigmask
, 0);
1296 // complain only if stdout is either a terminal (but still failed) or is an invalid
1297 // descriptor otherwise we would complain about redirection to e.g. /dev/null as well.
1298 else if (isatty(STDOUT_FILENO
) == 1 || errno
== EBADF
)
1299 _error
->Errno("tcgetattr", _("Can not write log (%s)"), _("Is stdout a terminal?"));
1301 if (_error
->PendingError() == true)
1302 _error
->DumpErrors(std::cerr
);
1303 _error
->RevertToStack();
1307 _config
->Set("APT::Keep-Fds::",fd
[1]);
1308 // send status information that we are about to fork dpkg
1309 if(OutStatusFd
> 0) {
1310 ostringstream status
;
1311 status
<< "pmstatus:dpkg-exec:"
1312 << (PackagesDone
/float(PackagesTotal
)*100.0)
1313 << ":" << _("Running dpkg")
1315 FileFd::Write(OutStatusFd
, status
.str().c_str(), status
.str().size());
1319 // This is the child
1323 if(slave
>= 0 && master
>= 0)
1326 ioctl(slave
, TIOCSCTTY
, 0);
1333 close(fd
[0]); // close the read end of the pipe
1335 dpkgChrootDirectory();
1337 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
1340 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
1343 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
1346 // Discard everything in stdin before forking dpkg
1347 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
1350 while (read(STDIN_FILENO
,&dummy
,1) == 1);
1352 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
1356 /* No Job Control Stop Env is a magic dpkg var that prevents it
1357 from using sigstop */
1358 putenv((char *)"DPKG_NO_TSTP=yes");
1359 execvp(Args
[0], (char**) &Args
[0]);
1360 cerr
<< "Could not exec dpkg!" << endl
;
1363 d
->progress
->Started();
1366 if (_config
->FindB("DPkg::UseIoNice", false) == true)
1369 // clear the Keep-Fd again
1370 _config
->Clear("APT::Keep-Fds",fd
[1]);
1375 // we read from dpkg here
1376 int const _dpkgin
= fd
[0];
1377 close(fd
[1]); // close the write end of the pipe
1383 sigemptyset(&sigmask
);
1384 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
1386 /* free vectors (and therefore memory) as we don't need the included data anymore */
1387 for (std::vector
<char *>::const_iterator p
= Packages
.begin();
1388 p
!= Packages
.end(); ++p
)
1392 // the result of the waitpid call
1395 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
1397 // FIXME: move this to a function or something, looks ugly here
1398 // error handling, waitpid returned -1
1401 RunScripts("DPkg::Post-Invoke");
1403 // Restore sig int/quit
1404 signal(SIGQUIT
,old_SIGQUIT
);
1405 signal(SIGINT
,old_SIGINT
);
1407 signal(SIGHUP
,old_SIGHUP
);
1408 return _error
->Errno("waitpid","Couldn't wait for subprocess");
1411 // wait for input or output here
1413 if (master
>= 0 && !d
->stdin_is_dev_null
)
1415 FD_SET(_dpkgin
, &rfds
);
1417 FD_SET(master
, &rfds
);
1420 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
1421 &tv
, &original_sigmask
);
1422 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
1423 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
1424 NULL
, &tv
, &original_sigmask
);
1425 if (select_ret
== 0)
1427 else if (select_ret
< 0 && errno
== EINTR
)
1429 else if (select_ret
< 0)
1431 perror("select() returned error");
1435 if(master
>= 0 && FD_ISSET(master
, &rfds
))
1436 DoTerminalPty(master
);
1437 if(master
>= 0 && FD_ISSET(0, &rfds
))
1439 if(FD_ISSET(_dpkgin
, &rfds
))
1440 DoDpkgStatusFd(_dpkgin
, OutStatusFd
);
1444 // Restore sig int/quit
1445 signal(SIGQUIT
,old_SIGQUIT
);
1446 signal(SIGINT
,old_SIGINT
);
1448 signal(SIGHUP
,old_SIGHUP
);
1450 // tell the progress
1451 d
->progress
->Finished();
1455 tcsetattr(0, TCSAFLUSH
, &tt
);
1459 // Check for an error code.
1460 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
1462 // if it was set to "keep-dpkg-runing" then we won't return
1463 // here but keep the loop going and just report it as a error
1465 bool const stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
1468 RunScripts("DPkg::Post-Invoke");
1470 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
1471 strprintf(d
->dpkg_error
, "Sub-process %s received a segmentation fault.",Args
[0]);
1472 else if (WIFEXITED(Status
) != 0)
1473 strprintf(d
->dpkg_error
, "Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
1475 strprintf(d
->dpkg_error
, "Sub-process %s exited unexpectedly",Args
[0]);
1477 if(d
->dpkg_error
.size() > 0)
1478 _error
->Error("%s", d
->dpkg_error
.c_str());
1489 // dpkg is done at this point
1490 d
->progress
->StatusChanged("", PackagesDone
, PackagesTotal
);
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
);