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), progress(NULL
)
66 bool stdin_is_dev_null
;
67 // the buffer we use for the dpkg status-fd reading
74 float last_reported_progress
;
75 APT::Progress::PackageManager
*progress
;
80 // Maps the dpkg "processing" info to human readable names. Entry 0
81 // of each array is the key, entry 1 is the value.
82 const std::pair
<const char *, const char *> PackageProcessingOps
[] = {
83 std::make_pair("install", N_("Installing %s")),
84 std::make_pair("configure", N_("Configuring %s")),
85 std::make_pair("remove", N_("Removing %s")),
86 std::make_pair("purge", N_("Completely removing %s")),
87 std::make_pair("disappear", N_("Noting disappearance of %s")),
88 std::make_pair("trigproc", N_("Running post-installation trigger %s"))
91 const std::pair
<const char *, const char *> * const PackageProcessingOpsBegin
= PackageProcessingOps
;
92 const std::pair
<const char *, const char *> * const PackageProcessingOpsEnd
= PackageProcessingOps
+ sizeof(PackageProcessingOps
) / sizeof(PackageProcessingOps
[0]);
94 // Predicate to test whether an entry in the PackageProcessingOps
95 // array matches a string.
96 class MatchProcessingOp
101 MatchProcessingOp(const char *the_target
)
106 bool operator()(const std::pair
<const char *, const char *> &pair
) const
108 return strcmp(pair
.first
, target
) == 0;
113 /* helper function to ionice the given PID
115 there is no C header for ionice yet - just the syscall interface
116 so we use the binary from util-linux
121 if (!FileExists("/usr/bin/ionice"))
123 pid_t Process
= ExecFork();
127 snprintf(buf
, sizeof(buf
), "-p%d", PID
);
129 Args
[0] = "/usr/bin/ionice";
133 execv(Args
[0], (char **)Args
);
135 return ExecWait(Process
, "ionice");
138 // dpkgChrootDirectory - chrooting for dpkg if needed /*{{{*/
139 static void dpkgChrootDirectory()
141 std::string
const chrootDir
= _config
->FindDir("DPkg::Chroot-Directory");
142 if (chrootDir
== "/")
144 std::cerr
<< "Chrooting into " << chrootDir
<< std::endl
;
145 if (chroot(chrootDir
.c_str()) != 0)
153 // FindNowVersion - Helper to find a Version in "now" state /*{{{*/
154 // ---------------------------------------------------------------------
155 /* This is helpful when a package is no longer installed but has residual
159 pkgCache::VerIterator
FindNowVersion(const pkgCache::PkgIterator
&Pkg
)
161 pkgCache::VerIterator Ver
;
162 for (Ver
= Pkg
.VersionList(); Ver
.end() == false; ++Ver
)
164 pkgCache::VerFileIterator Vf
= Ver
.FileList();
165 pkgCache::PkgFileIterator F
= Vf
.File();
166 for (F
= Vf
.File(); F
.end() == false; ++F
)
168 if (F
&& F
.Archive())
170 if (strcmp(F
.Archive(), "now"))
179 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
180 // ---------------------------------------------------------------------
182 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
183 : pkgPackageManager(Cache
), PackagesDone(0), PackagesTotal(0)
185 d
= new pkgDPkgPMPrivate();
188 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
189 // ---------------------------------------------------------------------
191 pkgDPkgPM::~pkgDPkgPM()
196 // DPkgPM::Install - Install a package /*{{{*/
197 // ---------------------------------------------------------------------
198 /* Add an install operation to the sequence list */
199 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
201 if (File
.empty() == true || Pkg
.end() == true)
202 return _error
->Error("Internal Error, No file name for %s",Pkg
.FullName().c_str());
204 // If the filename string begins with DPkg::Chroot-Directory, return the
205 // substr that is within the chroot so dpkg can access it.
206 string
const chrootdir
= _config
->FindDir("DPkg::Chroot-Directory","/");
207 if (chrootdir
!= "/" && File
.find(chrootdir
) == 0)
209 size_t len
= chrootdir
.length();
210 if (chrootdir
.at(len
- 1) == '/')
212 List
.push_back(Item(Item::Install
,Pkg
,File
.substr(len
)));
215 List
.push_back(Item(Item::Install
,Pkg
,File
));
220 // DPkgPM::Configure - Configure a package /*{{{*/
221 // ---------------------------------------------------------------------
222 /* Add a configure operation to the sequence list */
223 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
225 if (Pkg
.end() == true)
228 List
.push_back(Item(Item::Configure
, Pkg
));
230 // Use triggers for config calls if we configure "smart"
231 // as otherwise Pre-Depends will not be satisfied, see #526774
232 if (_config
->FindB("DPkg::TriggersPending", false) == true)
233 List
.push_back(Item(Item::TriggersPending
, PkgIterator()));
238 // DPkgPM::Remove - Remove a package /*{{{*/
239 // ---------------------------------------------------------------------
240 /* Add a remove operation to the sequence list */
241 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
243 if (Pkg
.end() == true)
247 List
.push_back(Item(Item::Purge
,Pkg
));
249 List
.push_back(Item(Item::Remove
,Pkg
));
253 // DPkgPM::SendPkgInfo - Send info for install-pkgs hook /*{{{*/
254 // ---------------------------------------------------------------------
255 /* This is part of the helper script communication interface, it sends
256 very complete information down to the other end of the pipe.*/
257 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
259 return SendPkgsInfo(F
, 2);
261 bool pkgDPkgPM::SendPkgsInfo(FILE * const F
, unsigned int const &Version
)
263 // This version of APT supports only v3, so don't sent higher versions
265 fprintf(F
,"VERSION %u\n", Version
);
267 fprintf(F
,"VERSION 3\n");
269 /* Write out all of the configuration directives by walking the
270 configuration tree */
271 const Configuration::Item
*Top
= _config
->Tree(0);
274 if (Top
->Value
.empty() == false)
277 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
278 QuoteString(Top
->Value
,"\n").c_str());
287 while (Top
!= 0 && Top
->Next
== 0)
294 // Write out the package actions in order.
295 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
297 if(I
->Pkg
.end() == true)
300 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
302 fprintf(F
,"%s ",I
->Pkg
.Name());
304 // Current version which we are going to replace
305 pkgCache::VerIterator CurVer
= I
->Pkg
.CurrentVer();
306 if (CurVer
.end() == true && (I
->Op
== Item::Remove
|| I
->Op
== Item::Purge
))
307 CurVer
= FindNowVersion(I
->Pkg
);
309 if (CurVer
.end() == true)
314 fprintf(F
, "- - none ");
318 fprintf(F
, "%s ", CurVer
.VerStr());
320 fprintf(F
, "%s %s ", CurVer
.Arch(), CurVer
.MultiArchType());
323 // Show the compare operator between current and install version
324 if (S
.InstallVer
!= 0)
326 pkgCache::VerIterator
const InstVer
= S
.InstVerIter(Cache
);
328 if (CurVer
.end() == false)
329 Comp
= InstVer
.CompareVer(CurVer
);
336 fprintf(F
, "%s ", InstVer
.VerStr());
338 fprintf(F
, "%s %s ", InstVer
.Arch(), InstVer
.MultiArchType());
345 fprintf(F
, "> - - none ");
348 // Show the filename/operation
349 if (I
->Op
== Item::Install
)
352 if (I
->File
[0] != '/')
353 fprintf(F
,"**ERROR**\n");
355 fprintf(F
,"%s\n",I
->File
.c_str());
357 else if (I
->Op
== Item::Configure
)
358 fprintf(F
,"**CONFIGURE**\n");
359 else if (I
->Op
== Item::Remove
||
360 I
->Op
== Item::Purge
)
361 fprintf(F
,"**REMOVE**\n");
369 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
370 // ---------------------------------------------------------------------
371 /* This looks for a list of scripts to run from the configuration file
372 each one is run and is fed on standard input a list of all .deb files
373 that are due to be installed. */
374 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
376 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
377 if (Opts
== 0 || Opts
->Child
== 0)
381 unsigned int Count
= 1;
382 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
384 if (Opts
->Value
.empty() == true)
387 // Determine the protocol version
388 string OptSec
= Opts
->Value
;
389 string::size_type Pos
;
390 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
391 Pos
= OptSec
.length();
392 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
394 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
395 unsigned int InfoFD
= _config
->FindI(OptSec
+ "::InfoFD", STDIN_FILENO
);
399 if (pipe(Pipes
) != 0)
400 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
401 if (InfoFD
!= (unsigned)Pipes
[0])
402 SetCloseExec(Pipes
[0],true);
404 _config
->Set("APT::Keep-Fds::", Pipes
[0]);
405 SetCloseExec(Pipes
[1],true);
407 // Purified Fork for running the script
408 pid_t Process
= ExecFork();
412 dup2(Pipes
[0], InfoFD
);
413 SetCloseExec(STDOUT_FILENO
,false);
414 SetCloseExec(STDIN_FILENO
,false);
415 SetCloseExec(STDERR_FILENO
,false);
418 strprintf(hookfd
, "%d", InfoFD
);
419 setenv("APT_HOOK_INFO_FD", hookfd
.c_str(), 1);
421 dpkgChrootDirectory();
425 Args
[2] = Opts
->Value
.c_str();
427 execv(Args
[0],(char **)Args
);
430 if (InfoFD
== (unsigned)Pipes
[0])
431 _config
->Clear("APT::Keep-Fds", Pipes
[0]);
433 FILE *F
= fdopen(Pipes
[1],"w");
435 return _error
->Errno("fdopen","Faild to open new FD");
437 // Feed it the filenames.
440 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
442 // Only deal with packages to be installed from .deb
443 if (I
->Op
!= Item::Install
)
447 if (I
->File
[0] != '/')
450 /* Feed the filename of each package that is pending install
452 fprintf(F
,"%s\n",I
->File
.c_str());
458 SendPkgsInfo(F
, Version
);
462 // Clean up the sub process
463 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
464 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
470 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
471 // ---------------------------------------------------------------------
474 void pkgDPkgPM::DoStdin(int master
)
476 unsigned char input_buf
[256] = {0,};
477 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
479 FileFd::Write(master
, input_buf
, len
);
481 d
->stdin_is_dev_null
= true;
484 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
485 // ---------------------------------------------------------------------
487 * read the terminal pty and write log
489 void pkgDPkgPM::DoTerminalPty(int master
)
491 unsigned char term_buf
[1024] = {0,0, };
493 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
494 if(len
== -1 && errno
== EIO
)
496 // this happens when the child is about to exit, we
497 // give it time to actually exit, otherwise we run
498 // into a race so we sleep for half a second.
499 struct timespec sleepfor
= { 0, 500000000 };
500 nanosleep(&sleepfor
, NULL
);
505 FileFd::Write(1, term_buf
, len
);
507 fwrite(term_buf
, len
, sizeof(char), d
->term_out
);
510 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
511 // ---------------------------------------------------------------------
514 void pkgDPkgPM::ProcessDpkgStatusLine(char *line
)
516 bool const Debug
= _config
->FindB("Debug::pkgDPkgProgressReporting",false);
519 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
522 /* dpkg sends strings like this:
523 'status: <pkg>: <pkg qstate>'
524 'status: <pkg>:<arch>: <pkg qstate>'
525 errors look like this:
526 '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
527 and conffile-prompt like this
528 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
530 Newer versions of dpkg sent also:
531 'processing: install: pkg'
532 'processing: configure: pkg'
533 'processing: remove: pkg'
534 'processing: purge: pkg'
535 'processing: disappear: pkg'
536 'processing: trigproc: trigger'
539 // we need to split on ": " (note the appended space) as the ':' is
540 // part of the pkgname:arch information that dpkg sends
542 // A dpkg error message may contain additional ":" (like
543 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
544 // so we need to ensure to not split too much
545 std::vector
<std::string
> list
= StringSplit(line
, ": ", 3);
549 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
552 // dpkg does not send always send "pkgname:arch" so we add it here if needed
553 std::string pkgname
= list
[1];
554 if (pkgname
.find(":") == std::string::npos
)
556 string
const nativeArch
= _config
->Find("APT::Architecture");
557 pkgname
= pkgname
+ ":" + nativeArch
;
559 const char* const pkg
= pkgname
.c_str();
560 const char* action
= list
[2].c_str();
562 // 'processing' from dpkg looks like
563 // 'processing: action: pkg'
564 if(strncmp(list
[0].c_str(), "processing", strlen("processing")) == 0)
566 const char* const pkg_or_trigger
= list
[2].c_str();
567 action
= list
[1].c_str();
568 const std::pair
<const char *, const char *> * const iter
=
569 std::find_if(PackageProcessingOpsBegin
,
570 PackageProcessingOpsEnd
,
571 MatchProcessingOp(action
));
572 if(iter
== PackageProcessingOpsEnd
)
575 std::clog
<< "ignoring unknown action: " << action
<< std::endl
;
578 std::string pkg_action
;
579 strprintf(pkg_action
, _(iter
->second
), pkg_or_trigger
);
581 d
->progress
->StatusChanged(pkg_or_trigger
, PackagesDone
, PackagesTotal
,
583 if (strncmp(action
, "disappear", strlen("disappear")) == 0)
584 handleDisappearAction(pkg_or_trigger
);
588 if(strncmp(action
,"error",strlen("error")) == 0)
590 d
->progress
->Error(list
[1], PackagesDone
, PackagesTotal
, list
[3]);
592 WriteApportReport(list
[1].c_str(), list
[3].c_str());
595 else if(strncmp(action
,"conffile",strlen("conffile")) == 0)
597 d
->progress
->ConffilePrompt(list
[1], PackagesDone
, PackagesTotal
,
602 vector
<struct DpkgState
> const &states
= PackageOps
[pkg
];
603 const char *next_action
= NULL
;
604 if(PackageOpsDone
[pkg
] < states
.size())
605 next_action
= states
[PackageOpsDone
[pkg
]].state
;
606 // check if the package moved to the next dpkg state
607 if(next_action
&& (strcmp(action
, next_action
) == 0))
609 // only read the translation if there is actually a next
611 std::string translation
;
612 strprintf(translation
, _(states
[PackageOpsDone
[pkg
]].str
), pkg
);
614 // we moved from one dpkg state to a new one, report that
615 PackageOpsDone
[pkg
]++;
617 // and send to the progress
618 d
->progress
->StatusChanged(pkg
, PackagesDone
, PackagesTotal
,
622 std::clog
<< "(parsed from dpkg) pkg: " << pkg
623 << " action: " << action
<< endl
;
626 // DPkgPM::handleDisappearAction /*{{{*/
627 void pkgDPkgPM::handleDisappearAction(string
const &pkgname
)
629 // record the package name for display and stuff later
630 disappearedPkgs
.insert(pkgname
);
632 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
633 if (unlikely(Pkg
.end() == true))
635 // the disappeared package was auto-installed - nothing to do
636 if ((Cache
[Pkg
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
638 pkgCache::VerIterator PkgVer
= Cache
[Pkg
].InstVerIter(Cache
);
639 if (unlikely(PkgVer
.end() == true))
641 /* search in the list of dependencies for (Pre)Depends,
642 check if this dependency has a Replaces on our package
643 and if so transfer the manual installed flag to it */
644 for (pkgCache::DepIterator Dep
= PkgVer
.DependsList(); Dep
.end() != true; ++Dep
)
646 if (Dep
->Type
!= pkgCache::Dep::Depends
&&
647 Dep
->Type
!= pkgCache::Dep::PreDepends
)
649 pkgCache::PkgIterator Tar
= Dep
.TargetPkg();
650 if (unlikely(Tar
.end() == true))
652 // the package is already marked as manual
653 if ((Cache
[Tar
].Flags
& pkgCache::Flag::Auto
) != pkgCache::Flag::Auto
)
655 pkgCache::VerIterator TarVer
= Cache
[Tar
].InstVerIter(Cache
);
656 if (TarVer
.end() == true)
658 for (pkgCache::DepIterator Rep
= TarVer
.DependsList(); Rep
.end() != true; ++Rep
)
660 if (Rep
->Type
!= pkgCache::Dep::Replaces
)
662 if (Pkg
!= Rep
.TargetPkg())
664 // okay, they are strongly connected - transfer manual-bit
666 std::clog
<< "transfer manual-bit from disappeared »" << pkgname
<< "« to »" << Tar
.FullName() << "«" << std::endl
;
667 Cache
[Tar
].Flags
&= ~Flag::Auto
;
673 // DPkgPM::DoDpkgStatusFd /*{{{*/
674 // ---------------------------------------------------------------------
677 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
)
682 len
=read(statusfd
, &d
->dpkgbuf
[d
->dpkgbuf_pos
], sizeof(d
->dpkgbuf
)-d
->dpkgbuf_pos
);
683 d
->dpkgbuf_pos
+= len
;
687 // process line by line if we have a buffer
689 while((q
=(char*)memchr(p
, '\n', d
->dpkgbuf
+d
->dpkgbuf_pos
-p
)) != NULL
)
692 ProcessDpkgStatusLine(p
);
693 p
=q
+1; // continue with next line
696 // now move the unprocessed bits (after the final \n that is now a 0x0)
697 // to the start and update d->dpkgbuf_pos
698 p
= (char*)memrchr(d
->dpkgbuf
, 0, d
->dpkgbuf_pos
);
702 // we are interessted in the first char *after* 0x0
705 // move the unprocessed tail to the start and update pos
706 memmove(d
->dpkgbuf
, p
, p
-d
->dpkgbuf
);
707 d
->dpkgbuf_pos
= d
->dpkgbuf
+d
->dpkgbuf_pos
-p
;
710 // DPkgPM::WriteHistoryTag /*{{{*/
711 void pkgDPkgPM::WriteHistoryTag(string
const &tag
, string value
)
713 size_t const length
= value
.length();
716 // poor mans rstrip(", ")
717 if (value
[length
-2] == ',' && value
[length
-1] == ' ')
718 value
.erase(length
- 2, 2);
719 fprintf(d
->history_out
, "%s: %s\n", tag
.c_str(), value
.c_str());
721 // DPkgPM::OpenLog /*{{{*/
722 bool pkgDPkgPM::OpenLog()
724 string
const logdir
= _config
->FindDir("Dir::Log");
725 if(CreateAPTDirectoryIfNeeded(logdir
, logdir
) == false)
726 // FIXME: use a better string after freeze
727 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
731 time_t const t
= time(NULL
);
732 struct tm
const * const tmp
= localtime(&t
);
733 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
736 string
const logfile_name
= flCombine(logdir
,
737 _config
->Find("Dir::Log::Terminal"));
738 if (!logfile_name
.empty())
740 d
->term_out
= fopen(logfile_name
.c_str(),"a");
741 if (d
->term_out
== NULL
)
742 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name
.c_str());
743 setvbuf(d
->term_out
, NULL
, _IONBF
, 0);
744 SetCloseExec(fileno(d
->term_out
), true);
745 if (getuid() == 0) // if we aren't root, we can't chown a file, so don't try it
747 struct passwd
*pw
= getpwnam("root");
748 struct group
*gr
= getgrnam("adm");
749 if (pw
!= NULL
&& gr
!= NULL
&& chown(logfile_name
.c_str(), pw
->pw_uid
, gr
->gr_gid
) != 0)
750 _error
->WarningE("OpenLog", "chown to root:adm of file %s failed", logfile_name
.c_str());
752 if (chmod(logfile_name
.c_str(), 0640) != 0)
753 _error
->WarningE("OpenLog", "chmod 0640 of file %s failed", logfile_name
.c_str());
754 fprintf(d
->term_out
, "\nLog started: %s\n", timestr
);
757 // write your history
758 string
const history_name
= flCombine(logdir
,
759 _config
->Find("Dir::Log::History"));
760 if (!history_name
.empty())
762 d
->history_out
= fopen(history_name
.c_str(),"a");
763 if (d
->history_out
== NULL
)
764 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), history_name
.c_str());
765 SetCloseExec(fileno(d
->history_out
), true);
766 chmod(history_name
.c_str(), 0644);
767 fprintf(d
->history_out
, "\nStart-Date: %s\n", timestr
);
768 string remove
, purge
, install
, reinstall
, upgrade
, downgrade
;
769 for (pkgCache::PkgIterator I
= Cache
.PkgBegin(); I
.end() == false; ++I
)
771 enum { CANDIDATE
, CANDIDATE_AUTO
, CURRENT_CANDIDATE
, CURRENT
} infostring
;
773 #define HISTORYINFO(X, Y) { line = &X; infostring = Y; }
774 if (Cache
[I
].NewInstall() == true)
775 HISTORYINFO(install
, CANDIDATE_AUTO
)
776 else if (Cache
[I
].ReInstall() == true)
777 HISTORYINFO(reinstall
, CANDIDATE
)
778 else if (Cache
[I
].Upgrade() == true)
779 HISTORYINFO(upgrade
, CURRENT_CANDIDATE
)
780 else if (Cache
[I
].Downgrade() == true)
781 HISTORYINFO(downgrade
, CURRENT_CANDIDATE
)
782 else if (Cache
[I
].Delete() == true)
783 HISTORYINFO((Cache
[I
].Purge() ? purge
: remove
), CURRENT
)
787 line
->append(I
.FullName(false)).append(" (");
788 switch (infostring
) {
789 case CANDIDATE
: line
->append(Cache
[I
].CandVersion
); break;
791 line
->append(Cache
[I
].CandVersion
);
792 if ((Cache
[I
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
793 line
->append(", automatic");
795 case CURRENT_CANDIDATE
: line
->append(Cache
[I
].CurVersion
).append(", ").append(Cache
[I
].CandVersion
); break;
796 case CURRENT
: line
->append(Cache
[I
].CurVersion
); break;
800 if (_config
->Exists("Commandline::AsString") == true)
801 WriteHistoryTag("Commandline", _config
->Find("Commandline::AsString"));
802 WriteHistoryTag("Install", install
);
803 WriteHistoryTag("Reinstall", reinstall
);
804 WriteHistoryTag("Upgrade", upgrade
);
805 WriteHistoryTag("Downgrade",downgrade
);
806 WriteHistoryTag("Remove",remove
);
807 WriteHistoryTag("Purge",purge
);
808 fflush(d
->history_out
);
814 // DPkg::CloseLog /*{{{*/
815 bool pkgDPkgPM::CloseLog()
818 time_t t
= time(NULL
);
819 struct tm
*tmp
= localtime(&t
);
820 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
824 fprintf(d
->term_out
, "Log ended: ");
825 fprintf(d
->term_out
, "%s", timestr
);
826 fprintf(d
->term_out
, "\n");
833 if (disappearedPkgs
.empty() == false)
836 for (std::set
<std::string
>::const_iterator d
= disappearedPkgs
.begin();
837 d
!= disappearedPkgs
.end(); ++d
)
839 pkgCache::PkgIterator P
= Cache
.FindPkg(*d
);
840 disappear
.append(*d
);
842 disappear
.append(", ");
844 disappear
.append(" (").append(Cache
[P
].CurVersion
).append("), ");
846 WriteHistoryTag("Disappeared", disappear
);
848 if (d
->dpkg_error
.empty() == false)
849 fprintf(d
->history_out
, "Error: %s\n", d
->dpkg_error
.c_str());
850 fprintf(d
->history_out
, "End-Date: %s\n", timestr
);
851 fclose(d
->history_out
);
853 d
->history_out
= NULL
;
858 // This implements a racy version of pselect for those architectures
859 // that don't have a working implementation.
860 // FIXME: Probably can be removed on Lenny+1
861 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
862 fd_set
*exceptfds
, const struct timespec
*timeout
,
863 const sigset_t
*sigmask
)
869 tv
.tv_sec
= timeout
->tv_sec
;
870 tv
.tv_usec
= timeout
->tv_nsec
/1000;
872 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
873 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
874 sigprocmask(SIG_SETMASK
, &origmask
, 0);
880 // DPkgPM::Go - Run the sequence /*{{{*/
881 // ---------------------------------------------------------------------
882 /* This globs the operations and calls dpkg
884 * If it is called with a progress object apt will report the install
885 * progress to this object. It maps the dpkg states a package goes
886 * through to human readable (and i10n-able)
887 * names and calculates a percentage for each step.
889 bool pkgDPkgPM::Go(APT::Progress::PackageManager
*progress
)
891 pkgPackageManager::SigINTStop
= false;
892 d
->progress
= progress
;
894 // Generate the base argument list for dpkg
895 std::vector
<const char *> Args
;
896 unsigned long StartSize
= 0;
897 string Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
899 string
const dpkgChrootDir
= _config
->FindDir("DPkg::Chroot-Directory", "/");
900 size_t dpkgChrootLen
= dpkgChrootDir
.length();
901 if (dpkgChrootDir
!= "/" && Tmp
.find(dpkgChrootDir
) == 0)
903 if (dpkgChrootDir
[dpkgChrootLen
- 1] == '/')
905 Tmp
= Tmp
.substr(dpkgChrootLen
);
908 Args
.push_back(Tmp
.c_str());
909 StartSize
+= Tmp
.length();
911 // Stick in any custom dpkg options
912 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
916 for (; Opts
!= 0; Opts
= Opts
->Next
)
918 if (Opts
->Value
.empty() == true)
920 Args
.push_back(Opts
->Value
.c_str());
921 StartSize
+= Opts
->Value
.length();
925 size_t const BaseArgs
= Args
.size();
926 // we need to detect if we can qualify packages with the architecture or not
927 Args
.push_back("--assert-multi-arch");
928 Args
.push_back(NULL
);
930 pid_t dpkgAssertMultiArch
= ExecFork();
931 if (dpkgAssertMultiArch
== 0)
933 dpkgChrootDirectory();
934 // redirect everything to the ultimate sink as we only need the exit-status
935 int const nullfd
= open("/dev/null", O_RDONLY
);
936 dup2(nullfd
, STDIN_FILENO
);
937 dup2(nullfd
, STDOUT_FILENO
);
938 dup2(nullfd
, STDERR_FILENO
);
939 execvp(Args
[0], (char**) &Args
[0]);
940 _error
->WarningE("dpkgGo", "Can't detect if dpkg supports multi-arch!");
947 sigset_t original_sigmask
;
949 unsigned int const MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
950 unsigned int const MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
951 bool const NoTriggers
= _config
->FindB("DPkg::NoTriggers", false);
953 if (RunScripts("DPkg::Pre-Invoke") == false)
956 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
959 // support subpressing of triggers processing for special
960 // cases like d-i that runs the triggers handling manually
961 bool const SmartConf
= (_config
->Find("PackageManager::Configure", "all") != "all");
962 bool const TriggersPending
= _config
->FindB("DPkg::TriggersPending", false);
963 if (_config
->FindB("DPkg::ConfigurePending", SmartConf
) == true)
964 List
.push_back(Item(Item::ConfigurePending
, PkgIterator()));
966 // map the dpkg states to the operations that are performed
967 // (this is sorted in the same way as Item::Ops)
968 static const struct DpkgState DpkgStatesOpMap
[][7] = {
971 {"half-installed", N_("Preparing %s")},
972 {"unpacked", N_("Unpacking %s") },
975 // Configure operation
977 {"unpacked",N_("Preparing to configure %s") },
978 {"half-configured", N_("Configuring %s") },
979 { "installed", N_("Installed %s")},
984 {"half-configured", N_("Preparing for removal of %s")},
985 {"half-installed", N_("Removing %s")},
986 {"config-files", N_("Removed %s")},
991 {"config-files", N_("Preparing to completely remove %s")},
992 {"not-installed", N_("Completely removed %s")},
997 // init the PackageOps map, go over the list of packages that
998 // that will be [installed|configured|removed|purged] and add
999 // them to the PackageOps map (the dpkg states it goes through)
1000 // and the PackageOpsTranslations (human readable strings)
1001 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end(); ++I
)
1003 if((*I
).Pkg
.end() == true)
1006 string
const name
= (*I
).Pkg
.FullName();
1007 PackageOpsDone
[name
] = 0;
1008 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; ++i
)
1010 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
1015 d
->stdin_is_dev_null
= false;
1020 bool dpkgMultiArch
= false;
1021 if (dpkgAssertMultiArch
> 0)
1024 while (waitpid(dpkgAssertMultiArch
, &Status
, 0) != dpkgAssertMultiArch
)
1028 _error
->WarningE("dpkgGo", _("Waited for %s but it wasn't there"), "dpkg --assert-multi-arch");
1031 if (WIFEXITED(Status
) == true && WEXITSTATUS(Status
) == 0)
1032 dpkgMultiArch
= true;
1035 // this loop is runs once per operation
1036 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();)
1038 // Do all actions with the same Op in one run
1039 vector
<Item
>::const_iterator J
= I
;
1040 if (TriggersPending
== true)
1041 for (; J
!= List
.end(); ++J
)
1045 if (J
->Op
!= Item::TriggersPending
)
1047 vector
<Item
>::const_iterator T
= J
+ 1;
1048 if (T
!= List
.end() && T
->Op
== I
->Op
)
1053 for (; J
!= List
.end() && J
->Op
== I
->Op
; ++J
)
1056 // keep track of allocated strings for multiarch package names
1057 std::vector
<char *> Packages
;
1059 // start with the baseset of arguments
1060 unsigned long Size
= StartSize
;
1061 Args
.erase(Args
.begin() + BaseArgs
, Args
.end());
1063 // Now check if we are within the MaxArgs limit
1065 // this code below is problematic, because it may happen that
1066 // the argument list is split in a way that A depends on B
1067 // and they are in the same "--configure A B" run
1068 // - with the split they may now be configured in different
1069 // runs, using Immediate-Configure-All can help prevent this.
1070 if (J
- I
> (signed)MaxArgs
)
1073 unsigned long const size
= MaxArgs
+ 10;
1075 Packages
.reserve(size
);
1079 unsigned long const size
= (J
- I
) + 10;
1081 Packages
.reserve(size
);
1086 return _error
->Errno("pipe","Failed to create IPC pipe to dpkg");
1088 #define ADDARG(X) Args.push_back(X); Size += strlen(X)
1089 #define ADDARGC(X) Args.push_back(X); Size += sizeof(X) - 1
1091 ADDARGC("--status-fd");
1092 char status_fd_buf
[20];
1093 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
1094 ADDARG(status_fd_buf
);
1095 unsigned long const Op
= I
->Op
;
1100 ADDARGC("--force-depends");
1101 ADDARGC("--force-remove-essential");
1102 ADDARGC("--remove");
1106 ADDARGC("--force-depends");
1107 ADDARGC("--force-remove-essential");
1111 case Item::Configure
:
1112 ADDARGC("--configure");
1115 case Item::ConfigurePending
:
1116 ADDARGC("--configure");
1117 ADDARGC("--pending");
1120 case Item::TriggersPending
:
1121 ADDARGC("--triggers-only");
1122 ADDARGC("--pending");
1126 ADDARGC("--unpack");
1127 ADDARGC("--auto-deconfigure");
1131 if (NoTriggers
== true && I
->Op
!= Item::TriggersPending
&&
1132 I
->Op
!= Item::ConfigurePending
)
1134 ADDARGC("--no-triggers");
1138 // Write in the file or package names
1139 if (I
->Op
== Item::Install
)
1141 for (;I
!= J
&& Size
< MaxArgBytes
; ++I
)
1143 if (I
->File
[0] != '/')
1144 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
1145 Args
.push_back(I
->File
.c_str());
1146 Size
+= I
->File
.length();
1151 string
const nativeArch
= _config
->Find("APT::Architecture");
1152 unsigned long const oldSize
= I
->Op
== Item::Configure
? Size
: 0;
1153 for (;I
!= J
&& Size
< MaxArgBytes
; ++I
)
1155 if((*I
).Pkg
.end() == true)
1157 if (I
->Op
== Item::Configure
&& disappearedPkgs
.find(I
->Pkg
.Name()) != disappearedPkgs
.end())
1159 // We keep this here to allow "smooth" transitions from e.g. multiarch dpkg/ubuntu to dpkg/debian
1160 if (dpkgMultiArch
== false && (I
->Pkg
.Arch() == nativeArch
||
1161 strcmp(I
->Pkg
.Arch(), "all") == 0 ||
1162 strcmp(I
->Pkg
.Arch(), "none") == 0))
1164 char const * const name
= I
->Pkg
.Name();
1169 pkgCache::VerIterator PkgVer
;
1170 std::string name
= I
->Pkg
.Name();
1171 if (Op
== Item::Remove
|| Op
== Item::Purge
)
1173 PkgVer
= I
->Pkg
.CurrentVer();
1174 if(PkgVer
.end() == true)
1175 PkgVer
= FindNowVersion(I
->Pkg
);
1178 PkgVer
= Cache
[I
->Pkg
].InstVerIter(Cache
);
1179 if (strcmp(I
->Pkg
.Arch(), "none") == 0)
1180 ; // never arch-qualify a package without an arch
1181 else if (PkgVer
.end() == false)
1182 name
.append(":").append(PkgVer
.Arch());
1184 _error
->Warning("Can not find PkgVer for '%s'", name
.c_str());
1185 char * const fullname
= strdup(name
.c_str());
1186 Packages
.push_back(fullname
);
1190 // skip configure action if all sheduled packages disappeared
1191 if (oldSize
== Size
)
1198 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
1200 for (std::vector
<const char *>::const_iterator a
= Args
.begin();
1201 a
!= Args
.end(); ++a
)
1206 Args
.push_back(NULL
);
1212 /* Mask off sig int/quit. We do this because dpkg also does when
1213 it forks scripts. What happens is that when you hit ctrl-c it sends
1214 it to all processes in the group. Since dpkg ignores the signal
1215 it doesn't die but we do! So we must also ignore it */
1216 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
1217 sighandler_t old_SIGINT
= signal(SIGINT
,SigINT
);
1219 // Check here for any SIGINT
1220 if (pkgPackageManager::SigINTStop
&& (Op
== Item::Remove
|| Op
== Item::Purge
|| Op
== Item::Install
))
1224 // ignore SIGHUP as well (debian #463030)
1225 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
1232 // if tcgetattr does not return zero there was a error
1233 // and we do not do any pty magic
1234 _error
->PushToStack();
1235 if (tcgetattr(STDOUT_FILENO
, &tt
) == 0)
1237 ioctl(STDOUT_FILENO
, TIOCGWINSZ
, (char *)&win
);
1238 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
1240 _error
->Errno("openpty", _("Can not write log (%s)"), _("Is /dev/pts mounted?"));
1241 master
= slave
= -1;
1246 rtt
.c_lflag
&= ~ECHO
;
1247 rtt
.c_lflag
|= ISIG
;
1248 // block SIGTTOU during tcsetattr to prevent a hang if
1249 // the process is a member of the background process group
1250 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
1251 sigemptyset(&sigmask
);
1252 sigaddset(&sigmask
, SIGTTOU
);
1253 sigprocmask(SIG_BLOCK
,&sigmask
, &original_sigmask
);
1254 tcsetattr(0, TCSAFLUSH
, &rtt
);
1255 sigprocmask(SIG_SETMASK
, &original_sigmask
, 0);
1258 // complain only if stdout is either a terminal (but still failed) or is an invalid
1259 // descriptor otherwise we would complain about redirection to e.g. /dev/null as well.
1260 else if (isatty(STDOUT_FILENO
) == 1 || errno
== EBADF
)
1261 _error
->Errno("tcgetattr", _("Can not write log (%s)"), _("Is stdout a terminal?"));
1263 if (_error
->PendingError() == true)
1264 _error
->DumpErrors(std::cerr
);
1265 _error
->RevertToStack();
1269 d
->progress
->Started();
1272 // This is the child
1276 if(slave
>= 0 && master
>= 0)
1279 ioctl(slave
, TIOCSCTTY
, 0);
1286 close(fd
[0]); // close the read end of the pipe
1288 dpkgChrootDirectory();
1290 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
1293 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
1296 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
1299 // Discard everything in stdin before forking dpkg
1300 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
1303 while (read(STDIN_FILENO
,&dummy
,1) == 1);
1305 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
1309 /* No Job Control Stop Env is a magic dpkg var that prevents it
1310 from using sigstop */
1311 putenv((char *)"DPKG_NO_TSTP=yes");
1312 execvp(Args
[0], (char**) &Args
[0]);
1313 cerr
<< "Could not exec dpkg!" << endl
;
1318 if (_config
->FindB("DPkg::UseIoNice", false) == true)
1324 // we read from dpkg here
1325 int const _dpkgin
= fd
[0];
1326 close(fd
[1]); // close the write end of the pipe
1332 sigemptyset(&sigmask
);
1333 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
1335 /* free vectors (and therefore memory) as we don't need the included data anymore */
1336 for (std::vector
<char *>::const_iterator p
= Packages
.begin();
1337 p
!= Packages
.end(); ++p
)
1341 // the result of the waitpid call
1344 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
1346 // FIXME: move this to a function or something, looks ugly here
1347 // error handling, waitpid returned -1
1350 RunScripts("DPkg::Post-Invoke");
1352 // Restore sig int/quit
1353 signal(SIGQUIT
,old_SIGQUIT
);
1354 signal(SIGINT
,old_SIGINT
);
1356 signal(SIGHUP
,old_SIGHUP
);
1357 return _error
->Errno("waitpid","Couldn't wait for subprocess");
1360 // wait for input or output here
1362 if (master
>= 0 && !d
->stdin_is_dev_null
)
1364 FD_SET(_dpkgin
, &rfds
);
1366 FD_SET(master
, &rfds
);
1369 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
1370 &tv
, &original_sigmask
);
1371 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
1372 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
1373 NULL
, &tv
, &original_sigmask
);
1374 if (select_ret
== 0)
1376 else if (select_ret
< 0 && errno
== EINTR
)
1378 else if (select_ret
< 0)
1380 perror("select() returned error");
1384 if(master
>= 0 && FD_ISSET(master
, &rfds
))
1385 DoTerminalPty(master
);
1386 if(master
>= 0 && FD_ISSET(0, &rfds
))
1388 if(FD_ISSET(_dpkgin
, &rfds
))
1389 DoDpkgStatusFd(_dpkgin
);
1393 // Restore sig int/quit
1394 signal(SIGQUIT
,old_SIGQUIT
);
1395 signal(SIGINT
,old_SIGINT
);
1397 signal(SIGHUP
,old_SIGHUP
);
1399 // tell the progress
1400 d
->progress
->Finished();
1404 tcsetattr(0, TCSAFLUSH
, &tt
);
1408 // Check for an error code.
1409 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
1411 // if it was set to "keep-dpkg-runing" then we won't return
1412 // here but keep the loop going and just report it as a error
1414 bool const stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
1417 RunScripts("DPkg::Post-Invoke");
1419 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
1420 strprintf(d
->dpkg_error
, "Sub-process %s received a segmentation fault.",Args
[0]);
1421 else if (WIFEXITED(Status
) != 0)
1422 strprintf(d
->dpkg_error
, "Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
1424 strprintf(d
->dpkg_error
, "Sub-process %s exited unexpectedly",Args
[0]);
1426 if(d
->dpkg_error
.size() > 0)
1427 _error
->Error("%s", d
->dpkg_error
.c_str());
1438 // dpkg is done at this point
1439 d
->progress
->StatusChanged("", PackagesDone
, PackagesTotal
, "");
1441 if (pkgPackageManager::SigINTStop
)
1442 _error
->Warning(_("Operation was interrupted before it could finish"));
1444 if (RunScripts("DPkg::Post-Invoke") == false)
1447 if (_config
->FindB("Debug::pkgDPkgPM",false) == false)
1449 std::string
const oldpkgcache
= _config
->FindFile("Dir::cache::pkgcache");
1450 if (oldpkgcache
.empty() == false && RealFileExists(oldpkgcache
) == true &&
1451 unlink(oldpkgcache
.c_str()) == 0)
1453 std::string
const srcpkgcache
= _config
->FindFile("Dir::cache::srcpkgcache");
1454 if (srcpkgcache
.empty() == false && RealFileExists(srcpkgcache
) == true)
1456 _error
->PushToStack();
1457 pkgCacheFile CacheFile
;
1458 CacheFile
.BuildCaches(NULL
, true);
1459 _error
->RevertToStack();
1464 Cache
.writeStateFile(NULL
);
1468 void SigINT(int sig
) {
1469 pkgPackageManager::SigINTStop
= true;
1472 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1473 // ---------------------------------------------------------------------
1475 void pkgDPkgPM::Reset()
1477 List
.erase(List
.begin(),List
.end());
1480 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1481 // ---------------------------------------------------------------------
1483 void pkgDPkgPM::WriteApportReport(const char *pkgpath
, const char *errormsg
)
1485 // If apport doesn't exist or isn't installed do nothing
1486 // This e.g. prevents messages in 'universes' without apport
1487 pkgCache::PkgIterator apportPkg
= Cache
.FindPkg("apport");
1488 if (apportPkg
.end() == true || apportPkg
->CurrentVer
== 0)
1491 string pkgname
, reportfile
, srcpkgname
, pkgver
, arch
;
1492 string::size_type pos
;
1495 if (_config
->FindB("Dpkg::ApportFailureReport", false) == false)
1497 std::clog
<< "configured to not write apport reports" << std::endl
;
1501 // only report the first errors
1502 if(pkgFailures
> _config
->FindI("APT::Apport::MaxReports", 3))
1504 std::clog
<< _("No apport report written because MaxReports is reached already") << std::endl
;
1508 // check if its not a follow up error
1509 const char *needle
= dgettext("dpkg", "dependency problems - leaving unconfigured");
1510 if(strstr(errormsg
, needle
) != NULL
) {
1511 std::clog
<< _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl
;
1515 // do not report disk-full failures
1516 if(strstr(errormsg
, strerror(ENOSPC
)) != NULL
) {
1517 std::clog
<< _("No apport report written because the error message indicates a disk full error") << std::endl
;
1521 // do not report out-of-memory failures
1522 if(strstr(errormsg
, strerror(ENOMEM
)) != NULL
) {
1523 std::clog
<< _("No apport report written because the error message indicates a out of memory error") << std::endl
;
1527 // do not report dpkg I/O errors
1528 // XXX - this message is localized, but this only matches the English version. This is better than nothing.
1529 if(strstr(errormsg
, "short read in buffer_copy (")) {
1530 std::clog
<< _("No apport report written because the error message indicates a dpkg I/O error") << std::endl
;
1534 // get the pkgname and reportfile
1535 pkgname
= flNotDir(pkgpath
);
1536 pos
= pkgname
.find('_');
1537 if(pos
!= string::npos
)
1538 pkgname
= pkgname
.substr(0, pos
);
1540 // find the package versin and source package name
1541 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
1542 if (Pkg
.end() == true)
1544 pkgCache::VerIterator Ver
= Cache
.GetCandidateVer(Pkg
);
1545 if (Ver
.end() == true)
1547 pkgver
= Ver
.VerStr() == NULL
? "unknown" : Ver
.VerStr();
1548 pkgRecords
Recs(Cache
);
1549 pkgRecords::Parser
&Parse
= Recs
.Lookup(Ver
.FileList());
1550 srcpkgname
= Parse
.SourcePkg();
1551 if(srcpkgname
.empty())
1552 srcpkgname
= pkgname
;
1554 // if the file exists already, we check:
1555 // - if it was reported already (touched by apport).
1556 // If not, we do nothing, otherwise
1557 // we overwrite it. This is the same behaviour as apport
1558 // - if we have a report with the same pkgversion already
1560 reportfile
= flCombine("/var/crash",pkgname
+".0.crash");
1561 if(FileExists(reportfile
))
1566 // check atime/mtime
1567 stat(reportfile
.c_str(), &buf
);
1568 if(buf
.st_mtime
> buf
.st_atime
)
1571 // check if the existing report is the same version
1572 report
= fopen(reportfile
.c_str(),"r");
1573 while(fgets(strbuf
, sizeof(strbuf
), report
) != NULL
)
1575 if(strstr(strbuf
,"Package:") == strbuf
)
1577 char pkgname
[255], version
[255];
1578 if(sscanf(strbuf
, "Package: %254s %254s", pkgname
, version
) == 2)
1579 if(strcmp(pkgver
.c_str(), version
) == 0)
1589 // now write the report
1590 arch
= _config
->Find("APT::Architecture");
1591 report
= fopen(reportfile
.c_str(),"w");
1594 if(_config
->FindB("DPkgPM::InitialReportOnly",false) == true)
1595 chmod(reportfile
.c_str(), 0);
1597 chmod(reportfile
.c_str(), 0600);
1598 fprintf(report
, "ProblemType: Package\n");
1599 fprintf(report
, "Architecture: %s\n", arch
.c_str());
1600 time_t now
= time(NULL
);
1601 fprintf(report
, "Date: %s" , ctime(&now
));
1602 fprintf(report
, "Package: %s %s\n", pkgname
.c_str(), pkgver
.c_str());
1603 fprintf(report
, "SourcePackage: %s\n", srcpkgname
.c_str());
1604 fprintf(report
, "ErrorMessage:\n %s\n", errormsg
);
1606 // ensure that the log is flushed
1608 fflush(d
->term_out
);
1610 // attach terminal log it if we have it
1611 string logfile_name
= _config
->FindFile("Dir::Log::Terminal");
1612 if (!logfile_name
.empty())
1616 fprintf(report
, "DpkgTerminalLog:\n");
1617 log
= fopen(logfile_name
.c_str(),"r");
1621 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1622 fprintf(report
, " %s", buf
);
1628 const char *ops_str
[] = {"Install", "Configure","Remove","Purge"};
1629 fprintf(report
, "AptOrdering:\n");
1630 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
1631 if ((*I
).Pkg
!= NULL
)
1632 fprintf(report
, " %s: %s\n", (*I
).Pkg
.Name(), ops_str
[(*I
).Op
]);
1634 fprintf(report
, " %s: %s\n", "NULL", ops_str
[(*I
).Op
]);
1636 // attach dmesg log (to learn about segfaults)
1637 if (FileExists("/bin/dmesg"))
1639 fprintf(report
, "Dmesg:\n");
1640 FILE *log
= popen("/bin/dmesg","r");
1644 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1645 fprintf(report
, " %s", buf
);
1650 // attach df -l log (to learn about filesystem status)
1651 if (FileExists("/bin/df"))
1654 fprintf(report
, "Df:\n");
1655 FILE *log
= popen("/bin/df -l","r");
1659 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1660 fprintf(report
, " %s", buf
);