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>
42 #include <sys/ioctl.h>
50 class pkgDPkgPMPrivate
53 pkgDPkgPMPrivate() : stdin_is_dev_null(false), dpkgbuf_pos(0),
54 term_out(NULL
), history_out(NULL
)
58 bool stdin_is_dev_null
;
59 // the buffer we use for the dpkg status-fd reading
69 // Maps the dpkg "processing" info to human readable names. Entry 0
70 // of each array is the key, entry 1 is the value.
71 const std::pair
<const char *, const char *> PackageProcessingOps
[] = {
72 std::make_pair("install", N_("Installing %s")),
73 std::make_pair("configure", N_("Configuring %s")),
74 std::make_pair("remove", N_("Removing %s")),
75 std::make_pair("purge", N_("Completely removing %s")),
76 std::make_pair("disappear", N_("Noting disappearance of %s")),
77 std::make_pair("trigproc", N_("Running post-installation trigger %s"))
80 const std::pair
<const char *, const char *> * const PackageProcessingOpsBegin
= PackageProcessingOps
;
81 const std::pair
<const char *, const char *> * const PackageProcessingOpsEnd
= PackageProcessingOps
+ sizeof(PackageProcessingOps
) / sizeof(PackageProcessingOps
[0]);
83 // Predicate to test whether an entry in the PackageProcessingOps
84 // array matches a string.
85 class MatchProcessingOp
90 MatchProcessingOp(const char *the_target
)
95 bool operator()(const std::pair
<const char *, const char *> &pair
) const
97 return strcmp(pair
.first
, target
) == 0;
102 /* helper function to ionice the given PID
104 there is no C header for ionice yet - just the syscall interface
105 so we use the binary from util-linux
110 if (!FileExists("/usr/bin/ionice"))
112 pid_t Process
= ExecFork();
116 snprintf(buf
, sizeof(buf
), "-p%d", PID
);
118 Args
[0] = "/usr/bin/ionice";
122 execv(Args
[0], (char **)Args
);
124 return ExecWait(Process
, "ionice");
127 // dpkgChrootDirectory - chrooting for dpkg if needed /*{{{*/
128 static void dpkgChrootDirectory()
130 std::string
const chrootDir
= _config
->FindDir("DPkg::Chroot-Directory");
131 if (chrootDir
== "/")
133 std::cerr
<< "Chrooting into " << chrootDir
<< std::endl
;
134 if (chroot(chrootDir
.c_str()) != 0)
140 // FindNowVersion - Helper to find a Version in "now" state /*{{{*/
141 // ---------------------------------------------------------------------
142 /* This is helpful when a package is no longer installed but has residual
146 pkgCache::VerIterator
FindNowVersion(const pkgCache::PkgIterator
&Pkg
)
148 pkgCache::VerIterator Ver
;
149 for (Ver
= Pkg
.VersionList(); Ver
.end() == false; Ver
++)
151 pkgCache::VerFileIterator Vf
= Ver
.FileList();
152 pkgCache::PkgFileIterator F
= Vf
.File();
153 for (F
= Vf
.File(); F
.end() == false; F
++)
155 if (F
&& F
.Archive())
157 if (strcmp(F
.Archive(), "now"))
166 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
167 // ---------------------------------------------------------------------
169 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
170 : pkgPackageManager(Cache
), PackagesDone(0), PackagesTotal(0)
172 d
= new pkgDPkgPMPrivate();
175 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
176 // ---------------------------------------------------------------------
178 pkgDPkgPM::~pkgDPkgPM()
183 // DPkgPM::Install - Install a package /*{{{*/
184 // ---------------------------------------------------------------------
185 /* Add an install operation to the sequence list */
186 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
188 if (File
.empty() == true || Pkg
.end() == true)
189 return _error
->Error("Internal Error, No file name for %s",Pkg
.Name());
191 // If the filename string begins with DPkg::Chroot-Directory, return the
192 // substr that is within the chroot so dpkg can access it.
193 string
const chrootdir
= _config
->FindDir("DPkg::Chroot-Directory","/");
194 if (chrootdir
!= "/" && File
.find(chrootdir
) == 0)
196 size_t len
= chrootdir
.length();
197 if (chrootdir
.at(len
- 1) == '/')
199 List
.push_back(Item(Item::Install
,Pkg
,File
.substr(len
)));
202 List
.push_back(Item(Item::Install
,Pkg
,File
));
207 // DPkgPM::Configure - Configure a package /*{{{*/
208 // ---------------------------------------------------------------------
209 /* Add a configure operation to the sequence list */
210 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
212 if (Pkg
.end() == true)
215 List
.push_back(Item(Item::Configure
, Pkg
));
217 // Use triggers for config calls if we configure "smart"
218 // as otherwise Pre-Depends will not be satisfied, see #526774
219 if (_config
->FindB("DPkg::TriggersPending", false) == true)
220 List
.push_back(Item(Item::TriggersPending
, PkgIterator()));
225 // DPkgPM::Remove - Remove a package /*{{{*/
226 // ---------------------------------------------------------------------
227 /* Add a remove operation to the sequence list */
228 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
230 if (Pkg
.end() == true)
234 List
.push_back(Item(Item::Purge
,Pkg
));
236 List
.push_back(Item(Item::Remove
,Pkg
));
240 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
241 // ---------------------------------------------------------------------
242 /* This is part of the helper script communication interface, it sends
243 very complete information down to the other end of the pipe.*/
244 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
246 fprintf(F
,"VERSION 2\n");
248 /* Write out all of the configuration directives by walking the
249 configuration tree */
250 const Configuration::Item
*Top
= _config
->Tree(0);
253 if (Top
->Value
.empty() == false)
256 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
257 QuoteString(Top
->Value
,"\n").c_str());
266 while (Top
!= 0 && Top
->Next
== 0)
273 // Write out the package actions in order.
274 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
276 if(I
->Pkg
.end() == true)
279 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
281 fprintf(F
,"%s ",I
->Pkg
.Name());
283 if (I
->Pkg
->CurrentVer
== 0)
286 fprintf(F
,"%s ",I
->Pkg
.CurrentVer().VerStr());
288 // Show the compare operator
290 if (S
.InstallVer
!= 0)
293 if (I
->Pkg
->CurrentVer
!= 0)
294 Comp
= S
.InstVerIter(Cache
).CompareVer(I
->Pkg
.CurrentVer());
301 fprintf(F
,"%s ",S
.InstVerIter(Cache
).VerStr());
306 // Show the filename/operation
307 if (I
->Op
== Item::Install
)
310 if (I
->File
[0] != '/')
311 fprintf(F
,"**ERROR**\n");
313 fprintf(F
,"%s\n",I
->File
.c_str());
315 if (I
->Op
== Item::Configure
)
316 fprintf(F
,"**CONFIGURE**\n");
317 if (I
->Op
== Item::Remove
||
318 I
->Op
== Item::Purge
)
319 fprintf(F
,"**REMOVE**\n");
327 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
328 // ---------------------------------------------------------------------
329 /* This looks for a list of scripts to run from the configuration file
330 each one is run and is fed on standard input a list of all .deb files
331 that are due to be installed. */
332 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
334 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
335 if (Opts
== 0 || Opts
->Child
== 0)
339 unsigned int Count
= 1;
340 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
342 if (Opts
->Value
.empty() == true)
345 // Determine the protocol version
346 string OptSec
= Opts
->Value
;
347 string::size_type Pos
;
348 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
349 Pos
= OptSec
.length();
350 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
352 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
356 if (pipe(Pipes
) != 0)
357 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
358 SetCloseExec(Pipes
[0],true);
359 SetCloseExec(Pipes
[1],true);
361 // Purified Fork for running the script
362 pid_t Process
= ExecFork();
366 dup2(Pipes
[0],STDIN_FILENO
);
367 SetCloseExec(STDOUT_FILENO
,false);
368 SetCloseExec(STDIN_FILENO
,false);
369 SetCloseExec(STDERR_FILENO
,false);
371 dpkgChrootDirectory();
375 Args
[2] = Opts
->Value
.c_str();
377 execv(Args
[0],(char **)Args
);
381 FILE *F
= fdopen(Pipes
[1],"w");
383 return _error
->Errno("fdopen","Faild to open new FD");
385 // Feed it the filenames.
388 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
390 // Only deal with packages to be installed from .deb
391 if (I
->Op
!= Item::Install
)
395 if (I
->File
[0] != '/')
398 /* Feed the filename of each package that is pending install
400 fprintf(F
,"%s\n",I
->File
.c_str());
410 // Clean up the sub process
411 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
412 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
418 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
419 // ---------------------------------------------------------------------
422 void pkgDPkgPM::DoStdin(int master
)
424 unsigned char input_buf
[256] = {0,};
425 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
427 write(master
, input_buf
, len
);
429 d
->stdin_is_dev_null
= true;
432 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
433 // ---------------------------------------------------------------------
435 * read the terminal pty and write log
437 void pkgDPkgPM::DoTerminalPty(int master
)
439 unsigned char term_buf
[1024] = {0,0, };
441 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
442 if(len
== -1 && errno
== EIO
)
444 // this happens when the child is about to exit, we
445 // give it time to actually exit, otherwise we run
446 // into a race so we sleep for half a second.
447 struct timespec sleepfor
= { 0, 500000000 };
448 nanosleep(&sleepfor
, NULL
);
453 write(1, term_buf
, len
);
455 fwrite(term_buf
, len
, sizeof(char), d
->term_out
);
458 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
459 // ---------------------------------------------------------------------
462 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd
, char *line
)
464 bool const Debug
= _config
->FindB("Debug::pkgDPkgProgressReporting",false);
465 // the status we output
466 ostringstream status
;
469 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
472 /* dpkg sends strings like this:
473 'status: <pkg>: <pkg qstate>'
474 errors look like this:
475 '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
476 and conffile-prompt like this
477 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
479 Newer versions of dpkg sent also:
480 'processing: install: pkg'
481 'processing: configure: pkg'
482 'processing: remove: pkg'
483 'processing: purge: pkg'
484 'processing: disappear: pkg'
485 'processing: trigproc: trigger'
489 // dpkg sends multiline error messages sometimes (see
490 // #374195 for a example. we should support this by
491 // either patching dpkg to not send multiline over the
492 // statusfd or by rewriting the code here to deal with
493 // it. for now we just ignore it and not crash
494 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
495 if( list
[0] == NULL
|| list
[1] == NULL
|| list
[2] == NULL
)
498 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
501 const char* const pkg
= list
[1];
502 const char* action
= _strstrip(list
[2]);
504 // 'processing' from dpkg looks like
505 // 'processing: action: pkg'
506 if(strncmp(list
[0], "processing", strlen("processing")) == 0)
509 const char* const pkg_or_trigger
= _strstrip(list
[2]);
510 action
= _strstrip( list
[1]);
511 const std::pair
<const char *, const char *> * const iter
=
512 std::find_if(PackageProcessingOpsBegin
,
513 PackageProcessingOpsEnd
,
514 MatchProcessingOp(action
));
515 if(iter
== PackageProcessingOpsEnd
)
518 std::clog
<< "ignoring unknown action: " << action
<< std::endl
;
521 snprintf(s
, sizeof(s
), _(iter
->second
), pkg_or_trigger
);
523 status
<< "pmstatus:" << pkg_or_trigger
524 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
528 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
530 std::clog
<< "send: '" << status
.str() << "'" << endl
;
532 if (strncmp(action
, "disappear", strlen("disappear")) == 0)
533 handleDisappearAction(pkg_or_trigger
);
537 if(strncmp(action
,"error",strlen("error")) == 0)
539 // urgs, sometime has ":" in its error string so that we
540 // end up with the error message split between list[3]
541 // and list[4], e.g. the message:
542 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
544 if( list
[4] != NULL
)
545 list
[3][strlen(list
[3])] = ':';
547 status
<< "pmerror:" << list
[1]
548 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
552 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
554 std::clog
<< "send: '" << status
.str() << "'" << endl
;
556 WriteApportReport(list
[1], list
[3]);
559 else if(strncmp(action
,"conffile",strlen("conffile")) == 0)
561 status
<< "pmconffile:" << list
[1]
562 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
566 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
568 std::clog
<< "send: '" << status
.str() << "'" << endl
;
572 vector
<struct DpkgState
> const &states
= PackageOps
[pkg
];
573 const char *next_action
= NULL
;
574 if(PackageOpsDone
[pkg
] < states
.size())
575 next_action
= states
[PackageOpsDone
[pkg
]].state
;
576 // check if the package moved to the next dpkg state
577 if(next_action
&& (strcmp(action
, next_action
) == 0))
579 // only read the translation if there is actually a next
581 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
583 snprintf(s
, sizeof(s
), translation
, pkg
);
585 // we moved from one dpkg state to a new one, report that
586 PackageOpsDone
[pkg
]++;
588 // build the status str
589 status
<< "pmstatus:" << pkg
590 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
594 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
596 std::clog
<< "send: '" << status
.str() << "'" << endl
;
599 std::clog
<< "(parsed from dpkg) pkg: " << pkg
600 << " action: " << action
<< endl
;
603 // DPkgPM::handleDisappearAction /*{{{*/
604 void pkgDPkgPM::handleDisappearAction(string
const &pkgname
)
606 // record the package name for display and stuff later
607 disappearedPkgs
.insert(pkgname
);
609 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
610 if (unlikely(Pkg
.end() == true))
612 // the disappeared package was auto-installed - nothing to do
613 if ((Cache
[Pkg
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
615 pkgCache::VerIterator PkgVer
= Cache
[Pkg
].InstVerIter(Cache
);
616 if (unlikely(PkgVer
.end() == true))
618 /* search in the list of dependencies for (Pre)Depends,
619 check if this dependency has a Replaces on our package
620 and if so transfer the manual installed flag to it */
621 for (pkgCache::DepIterator Dep
= PkgVer
.DependsList(); Dep
.end() != true; ++Dep
)
623 if (Dep
->Type
!= pkgCache::Dep::Depends
&&
624 Dep
->Type
!= pkgCache::Dep::PreDepends
)
626 pkgCache::PkgIterator Tar
= Dep
.TargetPkg();
627 if (unlikely(Tar
.end() == true))
629 // the package is already marked as manual
630 if ((Cache
[Tar
].Flags
& pkgCache::Flag::Auto
) != pkgCache::Flag::Auto
)
632 pkgCache::VerIterator TarVer
= Cache
[Tar
].InstVerIter(Cache
);
633 if (TarVer
.end() == true)
635 for (pkgCache::DepIterator Rep
= TarVer
.DependsList(); Rep
.end() != true; ++Rep
)
637 if (Rep
->Type
!= pkgCache::Dep::Replaces
)
639 if (Pkg
!= Rep
.TargetPkg())
641 // okay, they are strongly connected - transfer manual-bit
643 std::clog
<< "transfer manual-bit from disappeared »" << pkgname
<< "« to »" << Tar
.FullName() << "«" << std::endl
;
644 Cache
[Tar
].Flags
&= ~Flag::Auto
;
650 // DPkgPM::DoDpkgStatusFd /*{{{*/
651 // ---------------------------------------------------------------------
654 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
, int OutStatusFd
)
659 len
=read(statusfd
, &d
->dpkgbuf
[d
->dpkgbuf_pos
], sizeof(d
->dpkgbuf
)-d
->dpkgbuf_pos
);
660 d
->dpkgbuf_pos
+= len
;
664 // process line by line if we have a buffer
666 while((q
=(char*)memchr(p
, '\n', d
->dpkgbuf
+d
->dpkgbuf_pos
-p
)) != NULL
)
669 ProcessDpkgStatusLine(OutStatusFd
, p
);
670 p
=q
+1; // continue with next line
673 // now move the unprocessed bits (after the final \n that is now a 0x0)
674 // to the start and update d->dpkgbuf_pos
675 p
= (char*)memrchr(d
->dpkgbuf
, 0, d
->dpkgbuf_pos
);
679 // we are interessted in the first char *after* 0x0
682 // move the unprocessed tail to the start and update pos
683 memmove(d
->dpkgbuf
, p
, p
-d
->dpkgbuf
);
684 d
->dpkgbuf_pos
= d
->dpkgbuf
+d
->dpkgbuf_pos
-p
;
687 // DPkgPM::WriteHistoryTag /*{{{*/
688 void pkgDPkgPM::WriteHistoryTag(string
const &tag
, string value
)
690 size_t const length
= value
.length();
693 // poor mans rstrip(", ")
694 if (value
[length
-2] == ',' && value
[length
-1] == ' ')
695 value
.erase(length
- 2, 2);
696 fprintf(d
->history_out
, "%s: %s\n", tag
.c_str(), value
.c_str());
698 // DPkgPM::OpenLog /*{{{*/
699 bool pkgDPkgPM::OpenLog()
701 string
const logdir
= _config
->FindDir("Dir::Log");
702 if(CreateAPTDirectoryIfNeeded(logdir
, logdir
) == false)
703 // FIXME: use a better string after freeze
704 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
708 time_t const t
= time(NULL
);
709 struct tm
const * const tmp
= localtime(&t
);
710 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
713 string
const logfile_name
= flCombine(logdir
,
714 _config
->Find("Dir::Log::Terminal"));
715 if (!logfile_name
.empty())
717 d
->term_out
= fopen(logfile_name
.c_str(),"a");
718 if (d
->term_out
== NULL
)
719 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name
.c_str());
720 setvbuf(d
->term_out
, NULL
, _IONBF
, 0);
721 SetCloseExec(fileno(d
->term_out
), true);
724 pw
= getpwnam("root");
725 gr
= getgrnam("adm");
726 if (pw
!= NULL
&& gr
!= NULL
)
727 chown(logfile_name
.c_str(), pw
->pw_uid
, gr
->gr_gid
);
728 chmod(logfile_name
.c_str(), 0644);
729 fprintf(d
->term_out
, "\nLog started: %s\n", timestr
);
732 // write your history
733 string
const history_name
= flCombine(logdir
,
734 _config
->Find("Dir::Log::History"));
735 if (!history_name
.empty())
737 d
->history_out
= fopen(history_name
.c_str(),"a");
738 if (d
->history_out
== NULL
)
739 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), history_name
.c_str());
740 chmod(history_name
.c_str(), 0644);
741 fprintf(d
->history_out
, "\nStart-Date: %s\n", timestr
);
742 string remove
, purge
, install
, reinstall
, upgrade
, downgrade
;
743 for (pkgCache::PkgIterator I
= Cache
.PkgBegin(); I
.end() == false; ++I
)
745 enum { CANDIDATE
, CANDIDATE_AUTO
, CURRENT_CANDIDATE
, CURRENT
} infostring
;
747 #define HISTORYINFO(X, Y) { line = &X; infostring = Y; }
748 if (Cache
[I
].NewInstall() == true)
749 HISTORYINFO(install
, CANDIDATE_AUTO
)
750 else if (Cache
[I
].ReInstall() == true)
751 HISTORYINFO(reinstall
, CANDIDATE
)
752 else if (Cache
[I
].Upgrade() == true)
753 HISTORYINFO(upgrade
, CURRENT_CANDIDATE
)
754 else if (Cache
[I
].Downgrade() == true)
755 HISTORYINFO(downgrade
, CURRENT_CANDIDATE
)
756 else if (Cache
[I
].Delete() == true)
757 HISTORYINFO((Cache
[I
].Purge() ? purge
: remove
), CURRENT
)
761 line
->append(I
.FullName(false)).append(" (");
762 switch (infostring
) {
763 case CANDIDATE
: line
->append(Cache
[I
].CandVersion
); break;
765 line
->append(Cache
[I
].CandVersion
);
766 if ((Cache
[I
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
767 line
->append(", automatic");
769 case CURRENT_CANDIDATE
: line
->append(Cache
[I
].CurVersion
).append(", ").append(Cache
[I
].CandVersion
); break;
770 case CURRENT
: line
->append(Cache
[I
].CurVersion
); break;
774 if (_config
->Exists("Commandline::AsString") == true)
775 WriteHistoryTag("Commandline", _config
->Find("Commandline::AsString"));
776 WriteHistoryTag("Install", install
);
777 WriteHistoryTag("Reinstall", reinstall
);
778 WriteHistoryTag("Upgrade", upgrade
);
779 WriteHistoryTag("Downgrade",downgrade
);
780 WriteHistoryTag("Remove",remove
);
781 WriteHistoryTag("Purge",purge
);
782 fflush(d
->history_out
);
788 // DPkg::CloseLog /*{{{*/
789 bool pkgDPkgPM::CloseLog()
792 time_t t
= time(NULL
);
793 struct tm
*tmp
= localtime(&t
);
794 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
798 fprintf(d
->term_out
, "Log ended: ");
799 fprintf(d
->term_out
, "%s", timestr
);
800 fprintf(d
->term_out
, "\n");
807 if (disappearedPkgs
.empty() == false)
810 for (std::set
<std::string
>::const_iterator d
= disappearedPkgs
.begin();
811 d
!= disappearedPkgs
.end(); ++d
)
813 pkgCache::PkgIterator P
= Cache
.FindPkg(*d
);
814 disappear
.append(*d
);
816 disappear
.append(", ");
818 disappear
.append(" (").append(Cache
[P
].CurVersion
).append("), ");
820 WriteHistoryTag("Disappeared", disappear
);
822 if (d
->dpkg_error
.empty() == false)
823 fprintf(d
->history_out
, "Error: %s\n", d
->dpkg_error
.c_str());
824 fprintf(d
->history_out
, "End-Date: %s\n", timestr
);
825 fclose(d
->history_out
);
827 d
->history_out
= NULL
;
833 // This implements a racy version of pselect for those architectures
834 // that don't have a working implementation.
835 // FIXME: Probably can be removed on Lenny+1
836 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
837 fd_set
*exceptfds
, const struct timespec
*timeout
,
838 const sigset_t
*sigmask
)
844 tv
.tv_sec
= timeout
->tv_sec
;
845 tv
.tv_usec
= timeout
->tv_nsec
/1000;
847 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
848 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
849 sigprocmask(SIG_SETMASK
, &origmask
, 0);
853 // DPkgPM::Go - Run the sequence /*{{{*/
854 // ---------------------------------------------------------------------
855 /* This globs the operations and calls dpkg
857 * If it is called with "OutStatusFd" set to a valid file descriptor
858 * apt will report the install progress over this fd. It maps the
859 * dpkg states a package goes through to human readable (and i10n-able)
860 * names and calculates a percentage for each step.
862 bool pkgDPkgPM::Go(int OutStatusFd
)
864 // Generate the base argument list for dpkg
865 std::vector
<const char *> Args
;
866 unsigned long StartSize
= 0;
867 string Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
869 string
const dpkgChrootDir
= _config
->FindDir("DPkg::Chroot-Directory", "/");
870 size_t dpkgChrootLen
= dpkgChrootDir
.length();
871 if (dpkgChrootDir
!= "/" && Tmp
.find(dpkgChrootDir
) == 0)
873 if (dpkgChrootDir
[dpkgChrootLen
- 1] == '/')
875 Tmp
= Tmp
.substr(dpkgChrootLen
);
878 Args
.push_back(Tmp
.c_str());
879 StartSize
+= Tmp
.length();
881 // Stick in any custom dpkg options
882 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
886 for (; Opts
!= 0; Opts
= Opts
->Next
)
888 if (Opts
->Value
.empty() == true)
890 Args
.push_back(Opts
->Value
.c_str());
891 StartSize
+= Opts
->Value
.length();
895 size_t const BaseArgs
= Args
.size();
896 // we need to detect if we can qualify packages with the architecture or not
897 Args
.push_back("--assert-multi-arch");
898 Args
.push_back(NULL
);
900 pid_t dpkgAssertMultiArch
= ExecFork();
901 if (dpkgAssertMultiArch
== 0)
903 dpkgChrootDirectory();
904 // redirect everything to the ultimate sink as we only need the exit-status
905 int const nullfd
= open("/dev/null", O_RDONLY
);
906 dup2(nullfd
, STDIN_FILENO
);
907 dup2(nullfd
, STDOUT_FILENO
);
908 dup2(nullfd
, STDERR_FILENO
);
909 execv(Args
[0], (char**) &Args
[0]);
910 _error
->WarningE("dpkgGo", "Can't detect if dpkg supports multi-arch!");
917 sigset_t original_sigmask
;
919 unsigned int const MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
920 unsigned int const MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
921 bool const NoTriggers
= _config
->FindB("DPkg::NoTriggers", false);
923 if (RunScripts("DPkg::Pre-Invoke") == false)
926 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
929 // support subpressing of triggers processing for special
930 // cases like d-i that runs the triggers handling manually
931 bool const SmartConf
= (_config
->Find("PackageManager::Configure", "all") != "all");
932 bool const TriggersPending
= _config
->FindB("DPkg::TriggersPending", false);
933 if (_config
->FindB("DPkg::ConfigurePending", SmartConf
) == true)
934 List
.push_back(Item(Item::ConfigurePending
, PkgIterator()));
936 // map the dpkg states to the operations that are performed
937 // (this is sorted in the same way as Item::Ops)
938 static const struct DpkgState DpkgStatesOpMap
[][7] = {
941 {"half-installed", N_("Preparing %s")},
942 {"unpacked", N_("Unpacking %s") },
945 // Configure operation
947 {"unpacked",N_("Preparing to configure %s") },
948 {"half-configured", N_("Configuring %s") },
949 { "installed", N_("Installed %s")},
954 {"half-configured", N_("Preparing for removal of %s")},
955 {"half-installed", N_("Removing %s")},
956 {"config-files", N_("Removed %s")},
961 {"config-files", N_("Preparing to completely remove %s")},
962 {"not-installed", N_("Completely removed %s")},
967 // init the PackageOps map, go over the list of packages that
968 // that will be [installed|configured|removed|purged] and add
969 // them to the PackageOps map (the dpkg states it goes through)
970 // and the PackageOpsTranslations (human readable strings)
971 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end(); ++I
)
973 if((*I
).Pkg
.end() == true)
976 string
const name
= (*I
).Pkg
.Name();
977 PackageOpsDone
[name
] = 0;
978 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; ++i
)
980 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
985 d
->stdin_is_dev_null
= false;
990 bool dpkgMultiArch
= false;
991 if (dpkgAssertMultiArch
> 0)
994 while (waitpid(dpkgAssertMultiArch
, &Status
, 0) != dpkgAssertMultiArch
)
998 _error
->WarningE("dpkgGo", _("Waited for %s but it wasn't there"), "dpkg --assert-multi-arch");
1001 if (WIFEXITED(Status
) == true && WEXITSTATUS(Status
) == 0)
1002 dpkgMultiArch
= true;
1005 // this loop is runs once per operation
1006 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();)
1008 // Do all actions with the same Op in one run
1009 vector
<Item
>::const_iterator J
= I
;
1010 if (TriggersPending
== true)
1011 for (; J
!= List
.end(); ++J
)
1015 if (J
->Op
!= Item::TriggersPending
)
1017 vector
<Item
>::const_iterator T
= J
+ 1;
1018 if (T
!= List
.end() && T
->Op
== I
->Op
)
1023 for (; J
!= List
.end() && J
->Op
== I
->Op
; ++J
)
1026 // keep track of allocated strings for multiarch package names
1027 std::vector
<char *> Packages
;
1029 // start with the baseset of arguments
1030 unsigned long Size
= StartSize
;
1031 Args
.erase(Args
.begin() + BaseArgs
, Args
.end());
1033 // Now check if we are within the MaxArgs limit
1035 // this code below is problematic, because it may happen that
1036 // the argument list is split in a way that A depends on B
1037 // and they are in the same "--configure A B" run
1038 // - with the split they may now be configured in different
1039 // runs, using Immediate-Configure-All can help prevent this.
1040 if (J
- I
> (signed)MaxArgs
)
1043 unsigned long const size
= MaxArgs
+ 10;
1045 Packages
.reserve(size
);
1049 unsigned long const size
= (J
- I
) + 10;
1051 Packages
.reserve(size
);
1057 #define ADDARG(X) Args.push_back(X); Size += strlen(X)
1058 #define ADDARGC(X) Args.push_back(X); Size += sizeof(X) - 1
1060 ADDARGC("--status-fd");
1061 char status_fd_buf
[20];
1062 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
1063 ADDARG(status_fd_buf
);
1064 unsigned long const Op
= I
->Op
;
1069 ADDARGC("--force-depends");
1070 ADDARGC("--force-remove-essential");
1071 ADDARGC("--remove");
1075 ADDARGC("--force-depends");
1076 ADDARGC("--force-remove-essential");
1080 case Item::Configure
:
1081 ADDARGC("--configure");
1084 case Item::ConfigurePending
:
1085 ADDARGC("--configure");
1086 ADDARGC("--pending");
1089 case Item::TriggersPending
:
1090 ADDARGC("--triggers-only");
1091 ADDARGC("--pending");
1095 ADDARGC("--unpack");
1096 ADDARGC("--auto-deconfigure");
1100 if (NoTriggers
== true && I
->Op
!= Item::TriggersPending
&&
1101 I
->Op
!= Item::ConfigurePending
)
1103 ADDARGC("--no-triggers");
1107 // Write in the file or package names
1108 if (I
->Op
== Item::Install
)
1110 for (;I
!= J
&& Size
< MaxArgBytes
; ++I
)
1112 if (I
->File
[0] != '/')
1113 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
1114 Args
.push_back(I
->File
.c_str());
1115 Size
+= I
->File
.length();
1120 string
const nativeArch
= _config
->Find("APT::Architecture");
1121 unsigned long const oldSize
= I
->Op
== Item::Configure
? Size
: 0;
1122 for (;I
!= J
&& Size
< MaxArgBytes
; ++I
)
1124 if((*I
).Pkg
.end() == true)
1126 if (I
->Op
== Item::Configure
&& disappearedPkgs
.find(I
->Pkg
.Name()) != disappearedPkgs
.end())
1128 // We keep this here to allow "smooth" transitions from e.g. multiarch dpkg/ubuntu to dpkg/debian
1129 if (dpkgMultiArch
== false && (I
->Pkg
.Arch() == nativeArch
|| !strcmp(I
->Pkg
.Arch(), "all")))
1131 char const * const name
= I
->Pkg
.Name();
1136 pkgCache::VerIterator PkgVer
;
1137 std::string name
= I
->Pkg
.Name();
1138 if (Op
== Item::Remove
|| Op
== Item::Purge
)
1140 PkgVer
= I
->Pkg
.CurrentVer();
1141 if(PkgVer
.end() == true)
1142 PkgVer
= FindNowVersion(I
->Pkg
);
1145 PkgVer
= Cache
[I
->Pkg
].InstVerIter(Cache
);
1146 if (PkgVer
.end() == false)
1147 name
.append(":").append(PkgVer
.Arch());
1149 _error
->Warning("Can not find PkgVer for '%s'", name
.c_str());
1150 char * const fullname
= strdup(name
.c_str());
1151 Packages
.push_back(fullname
);
1155 // skip configure action if all sheduled packages disappeared
1156 if (oldSize
== Size
)
1163 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
1165 for (std::vector
<const char *>::const_iterator a
= Args
.begin();
1166 a
!= Args
.end(); ++a
)
1171 Args
.push_back(NULL
);
1177 /* Mask off sig int/quit. We do this because dpkg also does when
1178 it forks scripts. What happens is that when you hit ctrl-c it sends
1179 it to all processes in the group. Since dpkg ignores the signal
1180 it doesn't die but we do! So we must also ignore it */
1181 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
1182 sighandler_t old_SIGINT
= signal(SIGINT
,SigINT
);
1184 // Check here for any SIGINT
1185 if (pkgPackageManager::SigINTStop
&& (Op
== Item::Remove
|| Op
== Item::Purge
|| Op
== Item::Install
))
1189 // ignore SIGHUP as well (debian #463030)
1190 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
1197 // if tcgetattr does not return zero there was a error
1198 // and we do not do any pty magic
1199 if (tcgetattr(0, &tt
) == 0)
1201 ioctl(0, TIOCGWINSZ
, (char *)&win
);
1202 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
1204 const char *s
= _("Can not write log, openpty() "
1205 "failed (/dev/pts not mounted?)\n");
1206 fprintf(stderr
, "%s",s
);
1208 fprintf(d
->term_out
, "%s",s
);
1209 master
= slave
= -1;
1214 rtt
.c_lflag
&= ~ECHO
;
1215 rtt
.c_lflag
|= ISIG
;
1216 // block SIGTTOU during tcsetattr to prevent a hang if
1217 // the process is a member of the background process group
1218 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
1219 sigemptyset(&sigmask
);
1220 sigaddset(&sigmask
, SIGTTOU
);
1221 sigprocmask(SIG_BLOCK
,&sigmask
, &original_sigmask
);
1222 tcsetattr(0, TCSAFLUSH
, &rtt
);
1223 sigprocmask(SIG_SETMASK
, &original_sigmask
, 0);
1228 _config
->Set("APT::Keep-Fds::",fd
[1]);
1229 // send status information that we are about to fork dpkg
1230 if(OutStatusFd
> 0) {
1231 ostringstream status
;
1232 status
<< "pmstatus:dpkg-exec:"
1233 << (PackagesDone
/float(PackagesTotal
)*100.0)
1234 << ":" << _("Running dpkg")
1236 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
1240 // This is the child
1243 if(slave
>= 0 && master
>= 0)
1246 ioctl(slave
, TIOCSCTTY
, 0);
1253 close(fd
[0]); // close the read end of the pipe
1255 dpkgChrootDirectory();
1257 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
1260 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
1263 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
1266 // Discard everything in stdin before forking dpkg
1267 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
1270 while (read(STDIN_FILENO
,&dummy
,1) == 1);
1272 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
1276 /* No Job Control Stop Env is a magic dpkg var that prevents it
1277 from using sigstop */
1278 putenv((char *)"DPKG_NO_TSTP=yes");
1279 execvp(Args
[0], (char**) &Args
[0]);
1280 cerr
<< "Could not exec dpkg!" << endl
;
1285 if (_config
->FindB("DPkg::UseIoNice", false) == true)
1288 // clear the Keep-Fd again
1289 _config
->Clear("APT::Keep-Fds",fd
[1]);
1294 // we read from dpkg here
1295 int const _dpkgin
= fd
[0];
1296 close(fd
[1]); // close the write end of the pipe
1302 sigemptyset(&sigmask
);
1303 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
1305 /* free vectors (and therefore memory) as we don't need the included data anymore */
1306 for (std::vector
<char *>::const_iterator p
= Packages
.begin();
1307 p
!= Packages
.end(); ++p
)
1311 // the result of the waitpid call
1314 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
1316 // FIXME: move this to a function or something, looks ugly here
1317 // error handling, waitpid returned -1
1320 RunScripts("DPkg::Post-Invoke");
1322 // Restore sig int/quit
1323 signal(SIGQUIT
,old_SIGQUIT
);
1324 signal(SIGINT
,old_SIGINT
);
1326 signal(SIGHUP
,old_SIGHUP
);
1327 return _error
->Errno("waitpid","Couldn't wait for subprocess");
1330 // wait for input or output here
1332 if (master
>= 0 && !d
->stdin_is_dev_null
)
1334 FD_SET(_dpkgin
, &rfds
);
1336 FD_SET(master
, &rfds
);
1339 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
1340 &tv
, &original_sigmask
);
1341 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
1342 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
1343 NULL
, &tv
, &original_sigmask
);
1344 if (select_ret
== 0)
1346 else if (select_ret
< 0 && errno
== EINTR
)
1348 else if (select_ret
< 0)
1350 perror("select() returned error");
1354 if(master
>= 0 && FD_ISSET(master
, &rfds
))
1355 DoTerminalPty(master
);
1356 if(master
>= 0 && FD_ISSET(0, &rfds
))
1358 if(FD_ISSET(_dpkgin
, &rfds
))
1359 DoDpkgStatusFd(_dpkgin
, OutStatusFd
);
1363 // Restore sig int/quit
1364 signal(SIGQUIT
,old_SIGQUIT
);
1365 signal(SIGINT
,old_SIGINT
);
1367 signal(SIGHUP
,old_SIGHUP
);
1371 tcsetattr(0, TCSAFLUSH
, &tt
);
1375 // Check for an error code.
1376 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
1378 // if it was set to "keep-dpkg-runing" then we won't return
1379 // here but keep the loop going and just report it as a error
1381 bool const stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
1384 RunScripts("DPkg::Post-Invoke");
1386 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
1387 strprintf(d
->dpkg_error
, "Sub-process %s received a segmentation fault.",Args
[0]);
1388 else if (WIFEXITED(Status
) != 0)
1389 strprintf(d
->dpkg_error
, "Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
1391 strprintf(d
->dpkg_error
, "Sub-process %s exited unexpectedly",Args
[0]);
1393 if(d
->dpkg_error
.size() > 0)
1394 _error
->Error("%s", d
->dpkg_error
.c_str());
1405 if (pkgPackageManager::SigINTStop
)
1406 _error
->Warning(_("Operation was interrupted before it could finish"));
1408 if (RunScripts("DPkg::Post-Invoke") == false)
1411 if (_config
->FindB("Debug::pkgDPkgPM",false) == false)
1413 std::string
const oldpkgcache
= _config
->FindFile("Dir::cache::pkgcache");
1414 if (oldpkgcache
.empty() == false && RealFileExists(oldpkgcache
) == true &&
1415 unlink(oldpkgcache
.c_str()) == 0)
1417 std::string
const srcpkgcache
= _config
->FindFile("Dir::cache::srcpkgcache");
1418 if (srcpkgcache
.empty() == false && RealFileExists(srcpkgcache
) == true)
1420 _error
->PushToStack();
1421 pkgCacheFile CacheFile
;
1422 CacheFile
.BuildCaches(NULL
, true);
1423 _error
->RevertToStack();
1428 Cache
.writeStateFile(NULL
);
1432 void SigINT(int sig
) {
1433 if (_config
->FindB("APT::Immediate-Configure-All",false))
1434 pkgPackageManager::SigINTStop
= true;
1437 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1438 // ---------------------------------------------------------------------
1440 void pkgDPkgPM::Reset()
1442 List
.erase(List
.begin(),List
.end());
1445 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1446 // ---------------------------------------------------------------------
1448 void pkgDPkgPM::WriteApportReport(const char *pkgpath
, const char *errormsg
)
1450 string pkgname
, reportfile
, srcpkgname
, pkgver
, arch
;
1451 string::size_type pos
;
1454 if (_config
->FindB("Dpkg::ApportFailureReport", true) == false)
1456 std::clog
<< "configured to not write apport reports" << std::endl
;
1460 // only report the first errors
1461 if(pkgFailures
> _config
->FindI("APT::Apport::MaxReports", 3))
1463 std::clog
<< _("No apport report written because MaxReports is reached already") << std::endl
;
1467 // check if its not a follow up error
1468 const char *needle
= dgettext("dpkg", "dependency problems - leaving unconfigured");
1469 if(strstr(errormsg
, needle
) != NULL
) {
1470 std::clog
<< _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl
;
1474 // do not report disk-full failures
1475 if(strstr(errormsg
, strerror(ENOSPC
)) != NULL
) {
1476 std::clog
<< _("No apport report written because the error message indicates a disk full error") << std::endl
;
1480 // do not report out-of-memory failures
1481 if(strstr(errormsg
, strerror(ENOMEM
)) != NULL
||
1482 strstr(errormsg
, "failed to allocate memory") != NULL
) {
1483 std::clog
<< _("No apport report written because the error message indicates a out of memory error") << std::endl
;
1487 // do not report bugs regarding inaccessible local files
1488 if(strstr(errormsg
, strerror(ENOENT
)) != NULL
||
1489 strstr(errormsg
, "cannot access archive") != NULL
) {
1490 std::clog
<< _("No apport report written because the error message indicates an issue on the local system") << std::endl
;
1494 // do not report errors encountered when decompressing packages
1495 if(strstr(errormsg
, "--fsys-tarfile returned error exit status 2") != NULL
) {
1496 std::clog
<< _("No apport report written because the error message indicates an issue on the local system") << std::endl
;
1500 // do not report dpkg I/O errors, this is a format string, so we compare
1501 // the prefix and the suffix of the error with the dpkg error message
1502 vector
<string
> io_errors
;
1503 io_errors
.push_back(string("failed to read on buffer copy for %s"));
1504 io_errors
.push_back(string("failed in write on buffer copy for %s"));
1505 io_errors
.push_back(string("short read on buffer copy for %s"));
1507 for (vector
<string
>::iterator I
= io_errors
.begin(); I
!= io_errors
.end(); I
++)
1509 vector
<string
> list
= VectorizeString(dgettext("dpkg", (*I
).c_str()), '%');
1510 if (list
.size() > 1) {
1511 // we need to split %s, VectorizeString only allows char so we need
1512 // to kill the "s" manually
1513 if (list
[1].size() > 1) {
1514 list
[1].erase(0, 1);
1515 if(strstr(errormsg
, list
[0].c_str()) &&
1516 strstr(errormsg
, list
[1].c_str())) {
1517 std::clog
<< _("No apport report written because the error message indicates a dpkg I/O error") << std::endl
;
1524 // get the pkgname and reportfile
1525 pkgname
= flNotDir(pkgpath
);
1526 pos
= pkgname
.find('_');
1527 if(pos
!= string::npos
)
1528 pkgname
= pkgname
.substr(0, pos
);
1530 // find the package versin and source package name
1531 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
1532 if (Pkg
.end() == true)
1534 pkgCache::VerIterator Ver
= Cache
.GetCandidateVer(Pkg
);
1535 if (Ver
.end() == true)
1537 pkgver
= Ver
.VerStr() == NULL
? "unknown" : Ver
.VerStr();
1538 pkgRecords
Recs(Cache
);
1539 pkgRecords::Parser
&Parse
= Recs
.Lookup(Ver
.FileList());
1540 srcpkgname
= Parse
.SourcePkg();
1541 if(srcpkgname
.empty())
1542 srcpkgname
= pkgname
;
1544 // if the file exists already, we check:
1545 // - if it was reported already (touched by apport).
1546 // If not, we do nothing, otherwise
1547 // we overwrite it. This is the same behaviour as apport
1548 // - if we have a report with the same pkgversion already
1550 reportfile
= flCombine("/var/crash",pkgname
+".0.crash");
1551 if(FileExists(reportfile
))
1556 // check atime/mtime
1557 stat(reportfile
.c_str(), &buf
);
1558 if(buf
.st_mtime
> buf
.st_atime
)
1561 // check if the existing report is the same version
1562 report
= fopen(reportfile
.c_str(),"r");
1563 while(fgets(strbuf
, sizeof(strbuf
), report
) != NULL
)
1565 if(strstr(strbuf
,"Package:") == strbuf
)
1567 char pkgname
[255], version
[255];
1568 if(sscanf(strbuf
, "Package: %s %s", pkgname
, version
) == 2)
1569 if(strcmp(pkgver
.c_str(), version
) == 0)
1579 // now write the report
1580 arch
= _config
->Find("APT::Architecture");
1581 report
= fopen(reportfile
.c_str(),"w");
1584 if(_config
->FindB("DPkgPM::InitialReportOnly",false) == true)
1585 chmod(reportfile
.c_str(), 0);
1587 chmod(reportfile
.c_str(), 0600);
1588 fprintf(report
, "ProblemType: Package\n");
1589 fprintf(report
, "Architecture: %s\n", arch
.c_str());
1590 time_t now
= time(NULL
);
1591 fprintf(report
, "Date: %s" , ctime(&now
));
1592 fprintf(report
, "Package: %s %s\n", pkgname
.c_str(), pkgver
.c_str());
1593 fprintf(report
, "SourcePackage: %s\n", srcpkgname
.c_str());
1594 fprintf(report
, "ErrorMessage:\n %s\n", errormsg
);
1596 // ensure that the log is flushed
1598 fflush(d
->term_out
);
1600 // attach terminal log it if we have it
1601 string logfile_name
= _config
->FindFile("Dir::Log::Terminal");
1602 if (!logfile_name
.empty())
1607 fprintf(report
, "DpkgTerminalLog:\n");
1608 log
= fopen(logfile_name
.c_str(),"r");
1611 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1612 fprintf(report
, " %s", buf
);
1613 fprintf(report
, " \n");
1618 // attach history log it if we have it
1619 string histfile_name
= _config
->FindFile("Dir::Log::History");
1620 if (!histfile_name
.empty())
1625 fprintf(report
, "DpkgHistoryLog:\n");
1626 log
= fopen(histfile_name
.c_str(),"r");
1629 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1630 fprintf(report
, " %s", buf
);
1636 const char *ops_str
[] = {"Install", "Configure","Remove","Purge"};
1637 fprintf(report
, "AptOrdering:\n");
1638 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
1639 fprintf(report
, " %s: %s\n", (*I
).Pkg
.Name(), ops_str
[(*I
).Op
]);
1641 // attach dmesg log (to learn about segfaults)
1642 if (FileExists("/bin/dmesg"))
1647 fprintf(report
, "Dmesg:\n");
1648 log
= popen("/bin/dmesg","r");
1651 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1652 fprintf(report
, " %s", buf
);
1657 // attach df -l log (to learn about filesystem status)
1658 if (FileExists("/bin/df"))
1663 fprintf(report
, "Df:\n");
1664 log
= popen("/bin/df -l","r");
1667 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1668 fprintf(report
, " %s", buf
);