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>
43 #include <sys/ioctl.h>
51 class pkgDPkgPMPrivate
54 pkgDPkgPMPrivate() : stdin_is_dev_null(false), dpkgbuf_pos(0),
55 term_out(NULL
), history_out(NULL
)
59 bool stdin_is_dev_null
;
60 // the buffer we use for the dpkg status-fd reading
70 // Maps the dpkg "processing" info to human readable names. Entry 0
71 // of each array is the key, entry 1 is the value.
72 const std::pair
<const char *, const char *> PackageProcessingOps
[] = {
73 std::make_pair("install", N_("Installing %s")),
74 std::make_pair("configure", N_("Configuring %s")),
75 std::make_pair("remove", N_("Removing %s")),
76 std::make_pair("purge", N_("Completely removing %s")),
77 std::make_pair("disappear", N_("Noting disappearance of %s")),
78 std::make_pair("trigproc", N_("Running post-installation trigger %s"))
81 const std::pair
<const char *, const char *> * const PackageProcessingOpsBegin
= PackageProcessingOps
;
82 const std::pair
<const char *, const char *> * const PackageProcessingOpsEnd
= PackageProcessingOps
+ sizeof(PackageProcessingOps
) / sizeof(PackageProcessingOps
[0]);
84 // Predicate to test whether an entry in the PackageProcessingOps
85 // array matches a string.
86 class MatchProcessingOp
91 MatchProcessingOp(const char *the_target
)
96 bool operator()(const std::pair
<const char *, const char *> &pair
) const
98 return strcmp(pair
.first
, target
) == 0;
103 /* helper function to ionice the given PID
105 there is no C header for ionice yet - just the syscall interface
106 so we use the binary from util-linux
111 if (!FileExists("/usr/bin/ionice"))
113 pid_t Process
= ExecFork();
117 snprintf(buf
, sizeof(buf
), "-p%d", PID
);
119 Args
[0] = "/usr/bin/ionice";
123 execv(Args
[0], (char **)Args
);
125 return ExecWait(Process
, "ionice");
128 // dpkgChrootDirectory - chrooting for dpkg if needed /*{{{*/
129 static void dpkgChrootDirectory()
131 std::string
const chrootDir
= _config
->FindDir("DPkg::Chroot-Directory");
132 if (chrootDir
== "/")
134 std::cerr
<< "Chrooting into " << chrootDir
<< std::endl
;
135 if (chroot(chrootDir
.c_str()) != 0)
142 // FindNowVersion - Helper to find a Version in "now" state /*{{{*/
143 // ---------------------------------------------------------------------
144 /* This is helpful when a package is no longer installed but has residual
148 pkgCache::VerIterator
FindNowVersion(const pkgCache::PkgIterator
&Pkg
)
150 pkgCache::VerIterator Ver
;
151 for (Ver
= Pkg
.VersionList(); Ver
.end() == false; ++Ver
)
153 pkgCache::VerFileIterator Vf
= Ver
.FileList();
154 pkgCache::PkgFileIterator F
= Vf
.File();
155 for (F
= Vf
.File(); F
.end() == false; ++F
)
157 if (F
&& F
.Archive())
159 if (strcmp(F
.Archive(), "now"))
168 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
169 // ---------------------------------------------------------------------
171 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
172 : pkgPackageManager(Cache
), PackagesDone(0), PackagesTotal(0)
174 d
= new pkgDPkgPMPrivate();
177 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
178 // ---------------------------------------------------------------------
180 pkgDPkgPM::~pkgDPkgPM()
185 // DPkgPM::Install - Install a package /*{{{*/
186 // ---------------------------------------------------------------------
187 /* Add an install operation to the sequence list */
188 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
190 if (File
.empty() == true || Pkg
.end() == true)
191 return _error
->Error("Internal Error, No file name for %s",Pkg
.FullName().c_str());
193 // If the filename string begins with DPkg::Chroot-Directory, return the
194 // substr that is within the chroot so dpkg can access it.
195 string
const chrootdir
= _config
->FindDir("DPkg::Chroot-Directory","/");
196 if (chrootdir
!= "/" && File
.find(chrootdir
) == 0)
198 size_t len
= chrootdir
.length();
199 if (chrootdir
.at(len
- 1) == '/')
201 List
.push_back(Item(Item::Install
,Pkg
,File
.substr(len
)));
204 List
.push_back(Item(Item::Install
,Pkg
,File
));
209 // DPkgPM::Configure - Configure a package /*{{{*/
210 // ---------------------------------------------------------------------
211 /* Add a configure operation to the sequence list */
212 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
214 if (Pkg
.end() == true)
217 List
.push_back(Item(Item::Configure
, Pkg
));
219 // Use triggers for config calls if we configure "smart"
220 // as otherwise Pre-Depends will not be satisfied, see #526774
221 if (_config
->FindB("DPkg::TriggersPending", false) == true)
222 List
.push_back(Item(Item::TriggersPending
, PkgIterator()));
227 // DPkgPM::Remove - Remove a package /*{{{*/
228 // ---------------------------------------------------------------------
229 /* Add a remove operation to the sequence list */
230 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
232 if (Pkg
.end() == true)
236 List
.push_back(Item(Item::Purge
,Pkg
));
238 List
.push_back(Item(Item::Remove
,Pkg
));
242 // DPkgPM::SendPkgInfo - Send info for install-pkgs hook /*{{{*/
243 // ---------------------------------------------------------------------
244 /* This is part of the helper script communication interface, it sends
245 very complete information down to the other end of the pipe.*/
246 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
248 return SendPkgsInfo(F
, 2);
250 bool pkgDPkgPM::SendPkgsInfo(FILE * const F
, unsigned int const &Version
)
252 // This version of APT supports only v3, so don't sent higher versions
254 fprintf(F
,"VERSION %u\n", Version
);
256 fprintf(F
,"VERSION 3\n");
258 /* Write out all of the configuration directives by walking the
259 configuration tree */
260 const Configuration::Item
*Top
= _config
->Tree(0);
263 if (Top
->Value
.empty() == false)
266 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
267 QuoteString(Top
->Value
,"\n").c_str());
276 while (Top
!= 0 && Top
->Next
== 0)
283 // Write out the package actions in order.
284 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
286 if(I
->Pkg
.end() == true)
289 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
291 fprintf(F
,"%s ",I
->Pkg
.Name());
293 // Current version which we are going to replace
294 pkgCache::VerIterator CurVer
= I
->Pkg
.CurrentVer();
295 if (CurVer
.end() == true && (I
->Op
== Item::Remove
|| I
->Op
== Item::Purge
))
296 CurVer
= FindNowVersion(I
->Pkg
);
298 if (CurVer
.end() == true)
303 fprintf(F
, "- - none ");
307 fprintf(F
, "%s ", CurVer
.VerStr());
309 fprintf(F
, "%s %s ", CurVer
.Arch(), CurVer
.MultiArchType());
312 // Show the compare operator between current and install version
313 if (S
.InstallVer
!= 0)
315 pkgCache::VerIterator
const InstVer
= S
.InstVerIter(Cache
);
317 if (CurVer
.end() == false)
318 Comp
= InstVer
.CompareVer(CurVer
);
325 fprintf(F
, "%s ", InstVer
.VerStr());
327 fprintf(F
, "%s %s ", InstVer
.Arch(), InstVer
.MultiArchType());
334 fprintf(F
, "> - - none ");
337 // Show the filename/operation
338 if (I
->Op
== Item::Install
)
341 if (I
->File
[0] != '/')
342 fprintf(F
,"**ERROR**\n");
344 fprintf(F
,"%s\n",I
->File
.c_str());
346 else if (I
->Op
== Item::Configure
)
347 fprintf(F
,"**CONFIGURE**\n");
348 else if (I
->Op
== Item::Remove
||
349 I
->Op
== Item::Purge
)
350 fprintf(F
,"**REMOVE**\n");
358 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
359 // ---------------------------------------------------------------------
360 /* This looks for a list of scripts to run from the configuration file
361 each one is run and is fed on standard input a list of all .deb files
362 that are due to be installed. */
363 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
365 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
366 if (Opts
== 0 || Opts
->Child
== 0)
370 unsigned int Count
= 1;
371 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
373 if (Opts
->Value
.empty() == true)
376 // Determine the protocol version
377 string OptSec
= Opts
->Value
;
378 string::size_type Pos
;
379 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
380 Pos
= OptSec
.length();
381 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
383 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
387 if (pipe(Pipes
) != 0)
388 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
389 SetCloseExec(Pipes
[0],true);
390 SetCloseExec(Pipes
[1],true);
392 // Purified Fork for running the script
393 pid_t Process
= ExecFork();
397 dup2(Pipes
[0],STDIN_FILENO
);
398 SetCloseExec(STDOUT_FILENO
,false);
399 SetCloseExec(STDIN_FILENO
,false);
400 SetCloseExec(STDERR_FILENO
,false);
402 dpkgChrootDirectory();
406 Args
[2] = Opts
->Value
.c_str();
408 execv(Args
[0],(char **)Args
);
412 FILE *F
= fdopen(Pipes
[1],"w");
414 return _error
->Errno("fdopen","Faild to open new FD");
416 // Feed it the filenames.
419 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
421 // Only deal with packages to be installed from .deb
422 if (I
->Op
!= Item::Install
)
426 if (I
->File
[0] != '/')
429 /* Feed the filename of each package that is pending install
431 fprintf(F
,"%s\n",I
->File
.c_str());
437 SendPkgsInfo(F
, Version
);
441 // Clean up the sub process
442 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
443 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
449 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
450 // ---------------------------------------------------------------------
453 void pkgDPkgPM::DoStdin(int master
)
455 unsigned char input_buf
[256] = {0,};
456 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
458 FileFd::Write(master
, input_buf
, len
);
460 d
->stdin_is_dev_null
= true;
463 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
464 // ---------------------------------------------------------------------
466 * read the terminal pty and write log
468 void pkgDPkgPM::DoTerminalPty(int master
)
470 unsigned char term_buf
[1024] = {0,0, };
472 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
473 if(len
== -1 && errno
== EIO
)
475 // this happens when the child is about to exit, we
476 // give it time to actually exit, otherwise we run
477 // into a race so we sleep for half a second.
478 struct timespec sleepfor
= { 0, 500000000 };
479 nanosleep(&sleepfor
, NULL
);
484 FileFd::Write(1, term_buf
, len
);
486 fwrite(term_buf
, len
, sizeof(char), d
->term_out
);
489 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
490 // ---------------------------------------------------------------------
493 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd
, char *line
)
495 bool const Debug
= _config
->FindB("Debug::pkgDPkgProgressReporting",false);
496 // the status we output
497 ostringstream status
;
500 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
503 /* dpkg sends strings like this:
504 'status: <pkg>: <pkg qstate>'
505 errors look like this:
506 '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
507 and conffile-prompt like this
508 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
510 Newer versions of dpkg sent also:
511 'processing: install: pkg'
512 'processing: configure: pkg'
513 'processing: remove: pkg'
514 'processing: purge: pkg'
515 'processing: disappear: pkg'
516 'processing: trigproc: trigger'
520 // dpkg sends multiline error messages sometimes (see
521 // #374195 for a example. we should support this by
522 // either patching dpkg to not send multiline over the
523 // statusfd or by rewriting the code here to deal with
524 // it. for now we just ignore it and not crash
525 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
526 if( list
[0] == NULL
|| list
[1] == NULL
|| list
[2] == NULL
)
529 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
532 const char* const pkg
= list
[1];
533 const char* action
= _strstrip(list
[2]);
535 // 'processing' from dpkg looks like
536 // 'processing: action: pkg'
537 if(strncmp(list
[0], "processing", strlen("processing")) == 0)
540 const char* const pkg_or_trigger
= _strstrip(list
[2]);
541 action
= _strstrip( list
[1]);
542 const std::pair
<const char *, const char *> * const iter
=
543 std::find_if(PackageProcessingOpsBegin
,
544 PackageProcessingOpsEnd
,
545 MatchProcessingOp(action
));
546 if(iter
== PackageProcessingOpsEnd
)
549 std::clog
<< "ignoring unknown action: " << action
<< std::endl
;
552 snprintf(s
, sizeof(s
), _(iter
->second
), pkg_or_trigger
);
554 status
<< "pmstatus:" << pkg_or_trigger
555 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
559 FileFd::Write(OutStatusFd
, status
.str().c_str(), status
.str().size());
561 std::clog
<< "send: '" << status
.str() << "'" << endl
;
563 if (strncmp(action
, "disappear", strlen("disappear")) == 0)
564 handleDisappearAction(pkg_or_trigger
);
568 if(strncmp(action
,"error",strlen("error")) == 0)
570 // urgs, sometime has ":" in its error string so that we
571 // end up with the error message split between list[3]
572 // and list[4], e.g. the message:
573 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
575 if( list
[4] != NULL
)
576 list
[3][strlen(list
[3])] = ':';
578 status
<< "pmerror:" << list
[1]
579 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
583 FileFd::Write(OutStatusFd
, status
.str().c_str(), status
.str().size());
585 std::clog
<< "send: '" << status
.str() << "'" << endl
;
587 WriteApportReport(list
[1], list
[3]);
590 else if(strncmp(action
,"conffile",strlen("conffile")) == 0)
592 status
<< "pmconffile:" << list
[1]
593 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
597 FileFd::Write(OutStatusFd
, status
.str().c_str(), status
.str().size());
599 std::clog
<< "send: '" << status
.str() << "'" << endl
;
603 vector
<struct DpkgState
> const &states
= PackageOps
[pkg
];
604 const char *next_action
= NULL
;
605 if(PackageOpsDone
[pkg
] < states
.size())
606 next_action
= states
[PackageOpsDone
[pkg
]].state
;
607 // check if the package moved to the next dpkg state
608 if(next_action
&& (strcmp(action
, next_action
) == 0))
610 // only read the translation if there is actually a next
612 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
614 snprintf(s
, sizeof(s
), translation
, pkg
);
616 // we moved from one dpkg state to a new one, report that
617 PackageOpsDone
[pkg
]++;
619 // build the status str
620 status
<< "pmstatus:" << pkg
621 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
625 FileFd::Write(OutStatusFd
, status
.str().c_str(), status
.str().size());
627 std::clog
<< "send: '" << status
.str() << "'" << endl
;
630 std::clog
<< "(parsed from dpkg) pkg: " << pkg
631 << " action: " << action
<< endl
;
634 // DPkgPM::handleDisappearAction /*{{{*/
635 void pkgDPkgPM::handleDisappearAction(string
const &pkgname
)
637 // record the package name for display and stuff later
638 disappearedPkgs
.insert(pkgname
);
640 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
641 if (unlikely(Pkg
.end() == true))
643 // the disappeared package was auto-installed - nothing to do
644 if ((Cache
[Pkg
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
646 pkgCache::VerIterator PkgVer
= Cache
[Pkg
].InstVerIter(Cache
);
647 if (unlikely(PkgVer
.end() == true))
649 /* search in the list of dependencies for (Pre)Depends,
650 check if this dependency has a Replaces on our package
651 and if so transfer the manual installed flag to it */
652 for (pkgCache::DepIterator Dep
= PkgVer
.DependsList(); Dep
.end() != true; ++Dep
)
654 if (Dep
->Type
!= pkgCache::Dep::Depends
&&
655 Dep
->Type
!= pkgCache::Dep::PreDepends
)
657 pkgCache::PkgIterator Tar
= Dep
.TargetPkg();
658 if (unlikely(Tar
.end() == true))
660 // the package is already marked as manual
661 if ((Cache
[Tar
].Flags
& pkgCache::Flag::Auto
) != pkgCache::Flag::Auto
)
663 pkgCache::VerIterator TarVer
= Cache
[Tar
].InstVerIter(Cache
);
664 if (TarVer
.end() == true)
666 for (pkgCache::DepIterator Rep
= TarVer
.DependsList(); Rep
.end() != true; ++Rep
)
668 if (Rep
->Type
!= pkgCache::Dep::Replaces
)
670 if (Pkg
!= Rep
.TargetPkg())
672 // okay, they are strongly connected - transfer manual-bit
674 std::clog
<< "transfer manual-bit from disappeared »" << pkgname
<< "« to »" << Tar
.FullName() << "«" << std::endl
;
675 Cache
[Tar
].Flags
&= ~Flag::Auto
;
681 // DPkgPM::DoDpkgStatusFd /*{{{*/
682 // ---------------------------------------------------------------------
685 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
, int OutStatusFd
)
690 len
=read(statusfd
, &d
->dpkgbuf
[d
->dpkgbuf_pos
], sizeof(d
->dpkgbuf
)-d
->dpkgbuf_pos
);
691 d
->dpkgbuf_pos
+= len
;
695 // process line by line if we have a buffer
697 while((q
=(char*)memchr(p
, '\n', d
->dpkgbuf
+d
->dpkgbuf_pos
-p
)) != NULL
)
700 ProcessDpkgStatusLine(OutStatusFd
, p
);
701 p
=q
+1; // continue with next line
704 // now move the unprocessed bits (after the final \n that is now a 0x0)
705 // to the start and update d->dpkgbuf_pos
706 p
= (char*)memrchr(d
->dpkgbuf
, 0, d
->dpkgbuf_pos
);
710 // we are interessted in the first char *after* 0x0
713 // move the unprocessed tail to the start and update pos
714 memmove(d
->dpkgbuf
, p
, p
-d
->dpkgbuf
);
715 d
->dpkgbuf_pos
= d
->dpkgbuf
+d
->dpkgbuf_pos
-p
;
718 // DPkgPM::WriteHistoryTag /*{{{*/
719 void pkgDPkgPM::WriteHistoryTag(string
const &tag
, string value
)
721 size_t const length
= value
.length();
724 // poor mans rstrip(", ")
725 if (value
[length
-2] == ',' && value
[length
-1] == ' ')
726 value
.erase(length
- 2, 2);
727 fprintf(d
->history_out
, "%s: %s\n", tag
.c_str(), value
.c_str());
729 // DPkgPM::OpenLog /*{{{*/
730 bool pkgDPkgPM::OpenLog()
732 string
const logdir
= _config
->FindDir("Dir::Log");
733 if(CreateAPTDirectoryIfNeeded(logdir
, logdir
) == false)
734 // FIXME: use a better string after freeze
735 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
739 time_t const t
= time(NULL
);
740 struct tm
const * const tmp
= localtime(&t
);
741 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
744 string
const logfile_name
= flCombine(logdir
,
745 _config
->Find("Dir::Log::Terminal"));
746 if (!logfile_name
.empty())
748 d
->term_out
= fopen(logfile_name
.c_str(),"a");
749 if (d
->term_out
== NULL
)
750 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name
.c_str());
751 setvbuf(d
->term_out
, NULL
, _IONBF
, 0);
752 SetCloseExec(fileno(d
->term_out
), true);
755 pw
= getpwnam("root");
756 gr
= getgrnam("adm");
757 if (pw
!= NULL
&& gr
!= NULL
)
758 chown(logfile_name
.c_str(), pw
->pw_uid
, gr
->gr_gid
);
759 chmod(logfile_name
.c_str(), 0640);
760 fprintf(d
->term_out
, "\nLog started: %s\n", timestr
);
763 // write your history
764 string
const history_name
= flCombine(logdir
,
765 _config
->Find("Dir::Log::History"));
766 if (!history_name
.empty())
768 d
->history_out
= fopen(history_name
.c_str(),"a");
769 if (d
->history_out
== NULL
)
770 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), history_name
.c_str());
771 SetCloseExec(fileno(d
->history_out
), true);
772 chmod(history_name
.c_str(), 0644);
773 fprintf(d
->history_out
, "\nStart-Date: %s\n", timestr
);
774 string remove
, purge
, install
, reinstall
, upgrade
, downgrade
;
775 for (pkgCache::PkgIterator I
= Cache
.PkgBegin(); I
.end() == false; ++I
)
777 enum { CANDIDATE
, CANDIDATE_AUTO
, CURRENT_CANDIDATE
, CURRENT
} infostring
;
779 #define HISTORYINFO(X, Y) { line = &X; infostring = Y; }
780 if (Cache
[I
].NewInstall() == true)
781 HISTORYINFO(install
, CANDIDATE_AUTO
)
782 else if (Cache
[I
].ReInstall() == true)
783 HISTORYINFO(reinstall
, CANDIDATE
)
784 else if (Cache
[I
].Upgrade() == true)
785 HISTORYINFO(upgrade
, CURRENT_CANDIDATE
)
786 else if (Cache
[I
].Downgrade() == true)
787 HISTORYINFO(downgrade
, CURRENT_CANDIDATE
)
788 else if (Cache
[I
].Delete() == true)
789 HISTORYINFO((Cache
[I
].Purge() ? purge
: remove
), CURRENT
)
793 line
->append(I
.FullName(false)).append(" (");
794 switch (infostring
) {
795 case CANDIDATE
: line
->append(Cache
[I
].CandVersion
); break;
797 line
->append(Cache
[I
].CandVersion
);
798 if ((Cache
[I
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
799 line
->append(", automatic");
801 case CURRENT_CANDIDATE
: line
->append(Cache
[I
].CurVersion
).append(", ").append(Cache
[I
].CandVersion
); break;
802 case CURRENT
: line
->append(Cache
[I
].CurVersion
); break;
806 if (_config
->Exists("Commandline::AsString") == true)
807 WriteHistoryTag("Commandline", _config
->Find("Commandline::AsString"));
808 WriteHistoryTag("Install", install
);
809 WriteHistoryTag("Reinstall", reinstall
);
810 WriteHistoryTag("Upgrade", upgrade
);
811 WriteHistoryTag("Downgrade",downgrade
);
812 WriteHistoryTag("Remove",remove
);
813 WriteHistoryTag("Purge",purge
);
814 fflush(d
->history_out
);
820 // DPkg::CloseLog /*{{{*/
821 bool pkgDPkgPM::CloseLog()
824 time_t t
= time(NULL
);
825 struct tm
*tmp
= localtime(&t
);
826 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
830 fprintf(d
->term_out
, "Log ended: ");
831 fprintf(d
->term_out
, "%s", timestr
);
832 fprintf(d
->term_out
, "\n");
839 if (disappearedPkgs
.empty() == false)
842 for (std::set
<std::string
>::const_iterator d
= disappearedPkgs
.begin();
843 d
!= disappearedPkgs
.end(); ++d
)
845 pkgCache::PkgIterator P
= Cache
.FindPkg(*d
);
846 disappear
.append(*d
);
848 disappear
.append(", ");
850 disappear
.append(" (").append(Cache
[P
].CurVersion
).append("), ");
852 WriteHistoryTag("Disappeared", disappear
);
854 if (d
->dpkg_error
.empty() == false)
855 fprintf(d
->history_out
, "Error: %s\n", d
->dpkg_error
.c_str());
856 fprintf(d
->history_out
, "End-Date: %s\n", timestr
);
857 fclose(d
->history_out
);
859 d
->history_out
= NULL
;
865 // This implements a racy version of pselect for those architectures
866 // that don't have a working implementation.
867 // FIXME: Probably can be removed on Lenny+1
868 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
869 fd_set
*exceptfds
, const struct timespec
*timeout
,
870 const sigset_t
*sigmask
)
876 tv
.tv_sec
= timeout
->tv_sec
;
877 tv
.tv_usec
= timeout
->tv_nsec
/1000;
879 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
880 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
881 sigprocmask(SIG_SETMASK
, &origmask
, 0);
885 // DPkgPM::Go - Run the sequence /*{{{*/
886 // ---------------------------------------------------------------------
887 /* This globs the operations and calls dpkg
889 * If it is called with "OutStatusFd" set to a valid file descriptor
890 * apt will report the install progress over this fd. It maps the
891 * dpkg states a package goes through to human readable (and i10n-able)
892 * names and calculates a percentage for each step.
894 bool pkgDPkgPM::Go(int OutStatusFd
)
896 pkgPackageManager::SigINTStop
= false;
898 // Generate the base argument list for dpkg
899 std::vector
<const char *> Args
;
900 unsigned long StartSize
= 0;
901 string Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
903 string
const dpkgChrootDir
= _config
->FindDir("DPkg::Chroot-Directory", "/");
904 size_t dpkgChrootLen
= dpkgChrootDir
.length();
905 if (dpkgChrootDir
!= "/" && Tmp
.find(dpkgChrootDir
) == 0)
907 if (dpkgChrootDir
[dpkgChrootLen
- 1] == '/')
909 Tmp
= Tmp
.substr(dpkgChrootLen
);
912 Args
.push_back(Tmp
.c_str());
913 StartSize
+= Tmp
.length();
915 // Stick in any custom dpkg options
916 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
920 for (; Opts
!= 0; Opts
= Opts
->Next
)
922 if (Opts
->Value
.empty() == true)
924 Args
.push_back(Opts
->Value
.c_str());
925 StartSize
+= Opts
->Value
.length();
929 size_t const BaseArgs
= Args
.size();
930 // we need to detect if we can qualify packages with the architecture or not
931 Args
.push_back("--assert-multi-arch");
932 Args
.push_back(NULL
);
934 pid_t dpkgAssertMultiArch
= ExecFork();
935 if (dpkgAssertMultiArch
== 0)
937 dpkgChrootDirectory();
938 // redirect everything to the ultimate sink as we only need the exit-status
939 int const nullfd
= open("/dev/null", O_RDONLY
);
940 dup2(nullfd
, STDIN_FILENO
);
941 dup2(nullfd
, STDOUT_FILENO
);
942 dup2(nullfd
, STDERR_FILENO
);
943 execvp(Args
[0], (char**) &Args
[0]);
944 _error
->WarningE("dpkgGo", "Can't detect if dpkg supports multi-arch!");
951 sigset_t original_sigmask
;
953 unsigned int const MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
954 unsigned int const MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
955 bool const NoTriggers
= _config
->FindB("DPkg::NoTriggers", false);
957 if (RunScripts("DPkg::Pre-Invoke") == false)
960 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
963 // support subpressing of triggers processing for special
964 // cases like d-i that runs the triggers handling manually
965 bool const SmartConf
= (_config
->Find("PackageManager::Configure", "all") != "all");
966 bool const TriggersPending
= _config
->FindB("DPkg::TriggersPending", false);
967 if (_config
->FindB("DPkg::ConfigurePending", SmartConf
) == true)
968 List
.push_back(Item(Item::ConfigurePending
, PkgIterator()));
970 // map the dpkg states to the operations that are performed
971 // (this is sorted in the same way as Item::Ops)
972 static const struct DpkgState DpkgStatesOpMap
[][7] = {
975 {"half-installed", N_("Preparing %s")},
976 {"unpacked", N_("Unpacking %s") },
979 // Configure operation
981 {"unpacked",N_("Preparing to configure %s") },
982 {"half-configured", N_("Configuring %s") },
983 { "installed", N_("Installed %s")},
988 {"half-configured", N_("Preparing for removal of %s")},
989 {"half-installed", N_("Removing %s")},
990 {"config-files", N_("Removed %s")},
995 {"config-files", N_("Preparing to completely remove %s")},
996 {"not-installed", N_("Completely removed %s")},
1001 // init the PackageOps map, go over the list of packages that
1002 // that will be [installed|configured|removed|purged] and add
1003 // them to the PackageOps map (the dpkg states it goes through)
1004 // and the PackageOpsTranslations (human readable strings)
1005 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end(); ++I
)
1007 if((*I
).Pkg
.end() == true)
1010 string
const name
= (*I
).Pkg
.Name();
1011 PackageOpsDone
[name
] = 0;
1012 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; ++i
)
1014 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
1019 d
->stdin_is_dev_null
= false;
1024 bool dpkgMultiArch
= false;
1025 if (dpkgAssertMultiArch
> 0)
1028 while (waitpid(dpkgAssertMultiArch
, &Status
, 0) != dpkgAssertMultiArch
)
1032 _error
->WarningE("dpkgGo", _("Waited for %s but it wasn't there"), "dpkg --assert-multi-arch");
1035 if (WIFEXITED(Status
) == true && WEXITSTATUS(Status
) == 0)
1036 dpkgMultiArch
= true;
1039 // this loop is runs once per operation
1040 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();)
1042 // Do all actions with the same Op in one run
1043 vector
<Item
>::const_iterator J
= I
;
1044 if (TriggersPending
== true)
1045 for (; J
!= List
.end(); ++J
)
1049 if (J
->Op
!= Item::TriggersPending
)
1051 vector
<Item
>::const_iterator T
= J
+ 1;
1052 if (T
!= List
.end() && T
->Op
== I
->Op
)
1057 for (; J
!= List
.end() && J
->Op
== I
->Op
; ++J
)
1060 // keep track of allocated strings for multiarch package names
1061 std::vector
<char *> Packages
;
1063 // start with the baseset of arguments
1064 unsigned long Size
= StartSize
;
1065 Args
.erase(Args
.begin() + BaseArgs
, Args
.end());
1067 // Now check if we are within the MaxArgs limit
1069 // this code below is problematic, because it may happen that
1070 // the argument list is split in a way that A depends on B
1071 // and they are in the same "--configure A B" run
1072 // - with the split they may now be configured in different
1073 // runs, using Immediate-Configure-All can help prevent this.
1074 if (J
- I
> (signed)MaxArgs
)
1077 unsigned long const size
= MaxArgs
+ 10;
1079 Packages
.reserve(size
);
1083 unsigned long const size
= (J
- I
) + 10;
1085 Packages
.reserve(size
);
1090 return _error
->Errno("pipe","Failed to create IPC pipe to dpkg");
1092 #define ADDARG(X) Args.push_back(X); Size += strlen(X)
1093 #define ADDARGC(X) Args.push_back(X); Size += sizeof(X) - 1
1095 ADDARGC("--status-fd");
1096 char status_fd_buf
[20];
1097 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
1098 ADDARG(status_fd_buf
);
1099 unsigned long const Op
= I
->Op
;
1104 ADDARGC("--force-depends");
1105 ADDARGC("--force-remove-essential");
1106 ADDARGC("--remove");
1110 ADDARGC("--force-depends");
1111 ADDARGC("--force-remove-essential");
1115 case Item::Configure
:
1116 ADDARGC("--configure");
1119 case Item::ConfigurePending
:
1120 ADDARGC("--configure");
1121 ADDARGC("--pending");
1124 case Item::TriggersPending
:
1125 ADDARGC("--triggers-only");
1126 ADDARGC("--pending");
1130 ADDARGC("--unpack");
1131 ADDARGC("--auto-deconfigure");
1135 if (NoTriggers
== true && I
->Op
!= Item::TriggersPending
&&
1136 I
->Op
!= Item::ConfigurePending
)
1138 ADDARGC("--no-triggers");
1142 // Write in the file or package names
1143 if (I
->Op
== Item::Install
)
1145 for (;I
!= J
&& Size
< MaxArgBytes
; ++I
)
1147 if (I
->File
[0] != '/')
1148 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
1149 Args
.push_back(I
->File
.c_str());
1150 Size
+= I
->File
.length();
1155 string
const nativeArch
= _config
->Find("APT::Architecture");
1156 unsigned long const oldSize
= I
->Op
== Item::Configure
? Size
: 0;
1157 for (;I
!= J
&& Size
< MaxArgBytes
; ++I
)
1159 if((*I
).Pkg
.end() == true)
1161 if (I
->Op
== Item::Configure
&& disappearedPkgs
.find(I
->Pkg
.Name()) != disappearedPkgs
.end())
1163 // We keep this here to allow "smooth" transitions from e.g. multiarch dpkg/ubuntu to dpkg/debian
1164 if (dpkgMultiArch
== false && (I
->Pkg
.Arch() == nativeArch
||
1165 strcmp(I
->Pkg
.Arch(), "all") == 0 ||
1166 strcmp(I
->Pkg
.Arch(), "none") == 0))
1168 char const * const name
= I
->Pkg
.Name();
1173 pkgCache::VerIterator PkgVer
;
1174 std::string name
= I
->Pkg
.Name();
1175 if (Op
== Item::Remove
|| Op
== Item::Purge
)
1177 PkgVer
= I
->Pkg
.CurrentVer();
1178 if(PkgVer
.end() == true)
1179 PkgVer
= FindNowVersion(I
->Pkg
);
1182 PkgVer
= Cache
[I
->Pkg
].InstVerIter(Cache
);
1183 if (strcmp(I
->Pkg
.Arch(), "none") == 0)
1184 ; // never arch-qualify a package without an arch
1185 else if (PkgVer
.end() == false)
1186 name
.append(":").append(PkgVer
.Arch());
1188 _error
->Warning("Can not find PkgVer for '%s'", name
.c_str());
1189 char * const fullname
= strdup(name
.c_str());
1190 Packages
.push_back(fullname
);
1194 // skip configure action if all sheduled packages disappeared
1195 if (oldSize
== Size
)
1202 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
1204 for (std::vector
<const char *>::const_iterator a
= Args
.begin();
1205 a
!= Args
.end(); ++a
)
1210 Args
.push_back(NULL
);
1216 /* Mask off sig int/quit. We do this because dpkg also does when
1217 it forks scripts. What happens is that when you hit ctrl-c it sends
1218 it to all processes in the group. Since dpkg ignores the signal
1219 it doesn't die but we do! So we must also ignore it */
1220 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
1221 sighandler_t old_SIGINT
= signal(SIGINT
,SigINT
);
1223 // Check here for any SIGINT
1224 if (pkgPackageManager::SigINTStop
&& (Op
== Item::Remove
|| Op
== Item::Purge
|| Op
== Item::Install
))
1228 // ignore SIGHUP as well (debian #463030)
1229 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
1236 // if tcgetattr does not return zero there was a error
1237 // and we do not do any pty magic
1238 if (tcgetattr(0, &tt
) == 0)
1240 ioctl(0, TIOCGWINSZ
, (char *)&win
);
1241 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
1243 const char *s
= _("Can not write log, openpty() "
1244 "failed (/dev/pts not mounted?)\n");
1245 fprintf(stderr
, "%s",s
);
1247 fprintf(d
->term_out
, "%s",s
);
1248 master
= slave
= -1;
1253 rtt
.c_lflag
&= ~ECHO
;
1254 rtt
.c_lflag
|= ISIG
;
1255 // block SIGTTOU during tcsetattr to prevent a hang if
1256 // the process is a member of the background process group
1257 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
1258 sigemptyset(&sigmask
);
1259 sigaddset(&sigmask
, SIGTTOU
);
1260 sigprocmask(SIG_BLOCK
,&sigmask
, &original_sigmask
);
1261 tcsetattr(0, TCSAFLUSH
, &rtt
);
1262 sigprocmask(SIG_SETMASK
, &original_sigmask
, 0);
1267 _config
->Set("APT::Keep-Fds::",fd
[1]);
1268 // send status information that we are about to fork dpkg
1269 if(OutStatusFd
> 0) {
1270 ostringstream status
;
1271 status
<< "pmstatus:dpkg-exec:"
1272 << (PackagesDone
/float(PackagesTotal
)*100.0)
1273 << ":" << _("Running dpkg")
1275 FileFd::Write(OutStatusFd
, status
.str().c_str(), status
.str().size());
1279 // This is the child
1282 if(slave
>= 0 && master
>= 0)
1285 ioctl(slave
, TIOCSCTTY
, 0);
1292 close(fd
[0]); // close the read end of the pipe
1294 dpkgChrootDirectory();
1296 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
1299 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
1302 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
1305 // Discard everything in stdin before forking dpkg
1306 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
1309 while (read(STDIN_FILENO
,&dummy
,1) == 1);
1311 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
1315 /* No Job Control Stop Env is a magic dpkg var that prevents it
1316 from using sigstop */
1317 putenv((char *)"DPKG_NO_TSTP=yes");
1318 execvp(Args
[0], (char**) &Args
[0]);
1319 cerr
<< "Could not exec dpkg!" << endl
;
1324 if (_config
->FindB("DPkg::UseIoNice", false) == true)
1327 // clear the Keep-Fd again
1328 _config
->Clear("APT::Keep-Fds",fd
[1]);
1333 // we read from dpkg here
1334 int const _dpkgin
= fd
[0];
1335 close(fd
[1]); // close the write end of the pipe
1341 sigemptyset(&sigmask
);
1342 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
1344 /* free vectors (and therefore memory) as we don't need the included data anymore */
1345 for (std::vector
<char *>::const_iterator p
= Packages
.begin();
1346 p
!= Packages
.end(); ++p
)
1350 // the result of the waitpid call
1353 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
1355 // FIXME: move this to a function or something, looks ugly here
1356 // error handling, waitpid returned -1
1359 RunScripts("DPkg::Post-Invoke");
1361 // Restore sig int/quit
1362 signal(SIGQUIT
,old_SIGQUIT
);
1363 signal(SIGINT
,old_SIGINT
);
1365 signal(SIGHUP
,old_SIGHUP
);
1366 return _error
->Errno("waitpid","Couldn't wait for subprocess");
1369 // wait for input or output here
1371 if (master
>= 0 && !d
->stdin_is_dev_null
)
1373 FD_SET(_dpkgin
, &rfds
);
1375 FD_SET(master
, &rfds
);
1378 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
1379 &tv
, &original_sigmask
);
1380 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
1381 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
1382 NULL
, &tv
, &original_sigmask
);
1383 if (select_ret
== 0)
1385 else if (select_ret
< 0 && errno
== EINTR
)
1387 else if (select_ret
< 0)
1389 perror("select() returned error");
1393 if(master
>= 0 && FD_ISSET(master
, &rfds
))
1394 DoTerminalPty(master
);
1395 if(master
>= 0 && FD_ISSET(0, &rfds
))
1397 if(FD_ISSET(_dpkgin
, &rfds
))
1398 DoDpkgStatusFd(_dpkgin
, OutStatusFd
);
1402 // Restore sig int/quit
1403 signal(SIGQUIT
,old_SIGQUIT
);
1404 signal(SIGINT
,old_SIGINT
);
1406 signal(SIGHUP
,old_SIGHUP
);
1410 tcsetattr(0, TCSAFLUSH
, &tt
);
1414 // Check for an error code.
1415 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
1417 // if it was set to "keep-dpkg-runing" then we won't return
1418 // here but keep the loop going and just report it as a error
1420 bool const stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
1423 RunScripts("DPkg::Post-Invoke");
1425 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
1426 strprintf(d
->dpkg_error
, "Sub-process %s received a segmentation fault.",Args
[0]);
1427 else if (WIFEXITED(Status
) != 0)
1428 strprintf(d
->dpkg_error
, "Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
1430 strprintf(d
->dpkg_error
, "Sub-process %s exited unexpectedly",Args
[0]);
1432 if(d
->dpkg_error
.size() > 0)
1433 _error
->Error("%s", d
->dpkg_error
.c_str());
1444 if (pkgPackageManager::SigINTStop
)
1445 _error
->Warning(_("Operation was interrupted before it could finish"));
1447 if (RunScripts("DPkg::Post-Invoke") == false)
1450 if (_config
->FindB("Debug::pkgDPkgPM",false) == false)
1452 std::string
const oldpkgcache
= _config
->FindFile("Dir::cache::pkgcache");
1453 if (oldpkgcache
.empty() == false && RealFileExists(oldpkgcache
) == true &&
1454 unlink(oldpkgcache
.c_str()) == 0)
1456 std::string
const srcpkgcache
= _config
->FindFile("Dir::cache::srcpkgcache");
1457 if (srcpkgcache
.empty() == false && RealFileExists(srcpkgcache
) == true)
1459 _error
->PushToStack();
1460 pkgCacheFile CacheFile
;
1461 CacheFile
.BuildCaches(NULL
, true);
1462 _error
->RevertToStack();
1467 Cache
.writeStateFile(NULL
);
1471 void SigINT(int sig
) {
1472 pkgPackageManager::SigINTStop
= true;
1475 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1476 // ---------------------------------------------------------------------
1478 void pkgDPkgPM::Reset()
1480 List
.erase(List
.begin(),List
.end());
1483 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1484 // ---------------------------------------------------------------------
1486 void pkgDPkgPM::WriteApportReport(const char *pkgpath
, const char *errormsg
)
1488 // If apport doesn't exist or isn't installed do nothing
1489 // This e.g. prevents messages in 'universes' without apport
1490 pkgCache::PkgIterator apportPkg
= Cache
.FindPkg("apport");
1491 if (apportPkg
.end() == true || apportPkg
->CurrentVer
== 0)
1494 string pkgname
, reportfile
, srcpkgname
, pkgver
, arch
;
1495 string::size_type pos
;
1498 if (_config
->FindB("Dpkg::ApportFailureReport", false) == false)
1500 std::clog
<< "configured to not write apport reports" << std::endl
;
1504 // only report the first errors
1505 if(pkgFailures
> _config
->FindI("APT::Apport::MaxReports", 3))
1507 std::clog
<< _("No apport report written because MaxReports is reached already") << std::endl
;
1511 // check if its not a follow up error
1512 const char *needle
= dgettext("dpkg", "dependency problems - leaving unconfigured");
1513 if(strstr(errormsg
, needle
) != NULL
) {
1514 std::clog
<< _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl
;
1518 // do not report disk-full failures
1519 if(strstr(errormsg
, strerror(ENOSPC
)) != NULL
) {
1520 std::clog
<< _("No apport report written because the error message indicates a disk full error") << std::endl
;
1524 // do not report out-of-memory failures
1525 if(strstr(errormsg
, strerror(ENOMEM
)) != NULL
) {
1526 std::clog
<< _("No apport report written because the error message indicates a out of memory error") << std::endl
;
1530 // do not report dpkg I/O errors
1531 // XXX - this message is localized, but this only matches the English version. This is better than nothing.
1532 if(strstr(errormsg
, "short read in buffer_copy (")) {
1533 std::clog
<< _("No apport report written because the error message indicates a dpkg I/O error") << std::endl
;
1537 // get the pkgname and reportfile
1538 pkgname
= flNotDir(pkgpath
);
1539 pos
= pkgname
.find('_');
1540 if(pos
!= string::npos
)
1541 pkgname
= pkgname
.substr(0, pos
);
1543 // find the package versin and source package name
1544 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
1545 if (Pkg
.end() == true)
1547 pkgCache::VerIterator Ver
= Cache
.GetCandidateVer(Pkg
);
1548 if (Ver
.end() == true)
1550 pkgver
= Ver
.VerStr() == NULL
? "unknown" : Ver
.VerStr();
1551 pkgRecords
Recs(Cache
);
1552 pkgRecords::Parser
&Parse
= Recs
.Lookup(Ver
.FileList());
1553 srcpkgname
= Parse
.SourcePkg();
1554 if(srcpkgname
.empty())
1555 srcpkgname
= pkgname
;
1557 // if the file exists already, we check:
1558 // - if it was reported already (touched by apport).
1559 // If not, we do nothing, otherwise
1560 // we overwrite it. This is the same behaviour as apport
1561 // - if we have a report with the same pkgversion already
1563 reportfile
= flCombine("/var/crash",pkgname
+".0.crash");
1564 if(FileExists(reportfile
))
1569 // check atime/mtime
1570 stat(reportfile
.c_str(), &buf
);
1571 if(buf
.st_mtime
> buf
.st_atime
)
1574 // check if the existing report is the same version
1575 report
= fopen(reportfile
.c_str(),"r");
1576 while(fgets(strbuf
, sizeof(strbuf
), report
) != NULL
)
1578 if(strstr(strbuf
,"Package:") == strbuf
)
1580 char pkgname
[255], version
[255];
1581 if(sscanf(strbuf
, "Package: %254s %254s", pkgname
, version
) == 2)
1582 if(strcmp(pkgver
.c_str(), version
) == 0)
1592 // now write the report
1593 arch
= _config
->Find("APT::Architecture");
1594 report
= fopen(reportfile
.c_str(),"w");
1597 if(_config
->FindB("DPkgPM::InitialReportOnly",false) == true)
1598 chmod(reportfile
.c_str(), 0);
1600 chmod(reportfile
.c_str(), 0600);
1601 fprintf(report
, "ProblemType: Package\n");
1602 fprintf(report
, "Architecture: %s\n", arch
.c_str());
1603 time_t now
= time(NULL
);
1604 fprintf(report
, "Date: %s" , ctime(&now
));
1605 fprintf(report
, "Package: %s %s\n", pkgname
.c_str(), pkgver
.c_str());
1606 fprintf(report
, "SourcePackage: %s\n", srcpkgname
.c_str());
1607 fprintf(report
, "ErrorMessage:\n %s\n", errormsg
);
1609 // ensure that the log is flushed
1611 fflush(d
->term_out
);
1613 // attach terminal log it if we have it
1614 string logfile_name
= _config
->FindFile("Dir::Log::Terminal");
1615 if (!logfile_name
.empty())
1619 fprintf(report
, "DpkgTerminalLog:\n");
1620 log
= fopen(logfile_name
.c_str(),"r");
1624 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1625 fprintf(report
, " %s", buf
);
1631 const char *ops_str
[] = {"Install", "Configure","Remove","Purge"};
1632 fprintf(report
, "AptOrdering:\n");
1633 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
1634 if ((*I
).Pkg
!= NULL
)
1635 fprintf(report
, " %s: %s\n", (*I
).Pkg
.Name(), ops_str
[(*I
).Op
]);
1637 fprintf(report
, " %s: %s\n", "NULL", ops_str
[(*I
).Op
]);
1639 // attach dmesg log (to learn about segfaults)
1640 if (FileExists("/bin/dmesg"))
1642 fprintf(report
, "Dmesg:\n");
1643 FILE *log
= popen("/bin/dmesg","r");
1647 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1648 fprintf(report
, " %s", buf
);
1653 // attach df -l log (to learn about filesystem status)
1654 if (FileExists("/bin/df"))
1657 fprintf(report
, "Df:\n");
1658 FILE *log
= popen("/bin/df -l","r");
1662 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1663 fprintf(report
, " %s", buf
);