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)
141 // FindNowVersion - Helper to find a Version in "now" state /*{{{*/
142 // ---------------------------------------------------------------------
143 /* This is helpful when a package is no longer installed but has residual
147 pkgCache::VerIterator
FindNowVersion(const pkgCache::PkgIterator
&Pkg
)
149 pkgCache::VerIterator Ver
;
150 for (Ver
= Pkg
.VersionList(); Ver
.end() == false; Ver
++)
152 pkgCache::VerFileIterator Vf
= Ver
.FileList();
153 pkgCache::PkgFileIterator F
= Vf
.File();
154 for (F
= Vf
.File(); F
.end() == false; F
++)
156 if (F
&& F
.Archive())
158 if (strcmp(F
.Archive(), "now"))
167 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
168 // ---------------------------------------------------------------------
170 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
171 : pkgPackageManager(Cache
), PackagesDone(0), PackagesTotal(0)
173 d
= new pkgDPkgPMPrivate();
176 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
177 // ---------------------------------------------------------------------
179 pkgDPkgPM::~pkgDPkgPM()
184 // DPkgPM::Install - Install a package /*{{{*/
185 // ---------------------------------------------------------------------
186 /* Add an install operation to the sequence list */
187 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
189 if (File
.empty() == true || Pkg
.end() == true)
190 return _error
->Error("Internal Error, No file name for %s",Pkg
.FullName().c_str());
192 // If the filename string begins with DPkg::Chroot-Directory, return the
193 // substr that is within the chroot so dpkg can access it.
194 string
const chrootdir
= _config
->FindDir("DPkg::Chroot-Directory","/");
195 if (chrootdir
!= "/" && File
.find(chrootdir
) == 0)
197 size_t len
= chrootdir
.length();
198 if (chrootdir
.at(len
- 1) == '/')
200 List
.push_back(Item(Item::Install
,Pkg
,File
.substr(len
)));
203 List
.push_back(Item(Item::Install
,Pkg
,File
));
208 // DPkgPM::Configure - Configure a package /*{{{*/
209 // ---------------------------------------------------------------------
210 /* Add a configure operation to the sequence list */
211 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
213 if (Pkg
.end() == true)
216 List
.push_back(Item(Item::Configure
, Pkg
));
218 // Use triggers for config calls if we configure "smart"
219 // as otherwise Pre-Depends will not be satisfied, see #526774
220 if (_config
->FindB("DPkg::TriggersPending", false) == true)
221 List
.push_back(Item(Item::TriggersPending
, PkgIterator()));
226 // DPkgPM::Remove - Remove a package /*{{{*/
227 // ---------------------------------------------------------------------
228 /* Add a remove operation to the sequence list */
229 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
231 if (Pkg
.end() == true)
235 List
.push_back(Item(Item::Purge
,Pkg
));
237 List
.push_back(Item(Item::Remove
,Pkg
));
241 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
242 // ---------------------------------------------------------------------
243 /* This is part of the helper script communication interface, it sends
244 very complete information down to the other end of the pipe.*/
245 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
247 fprintf(F
,"VERSION 2\n");
249 /* Write out all of the configuration directives by walking the
250 configuration tree */
251 const Configuration::Item
*Top
= _config
->Tree(0);
254 if (Top
->Value
.empty() == false)
257 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
258 QuoteString(Top
->Value
,"\n").c_str());
267 while (Top
!= 0 && Top
->Next
== 0)
274 // Write out the package actions in order.
275 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
277 if(I
->Pkg
.end() == true)
280 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
282 fprintf(F
,"%s ",I
->Pkg
.Name());
284 if (I
->Pkg
->CurrentVer
== 0)
287 fprintf(F
,"%s ",I
->Pkg
.CurrentVer().VerStr());
289 // Show the compare operator
291 if (S
.InstallVer
!= 0)
294 if (I
->Pkg
->CurrentVer
!= 0)
295 Comp
= S
.InstVerIter(Cache
).CompareVer(I
->Pkg
.CurrentVer());
302 fprintf(F
,"%s ",S
.InstVerIter(Cache
).VerStr());
307 // Show the filename/operation
308 if (I
->Op
== Item::Install
)
311 if (I
->File
[0] != '/')
312 fprintf(F
,"**ERROR**\n");
314 fprintf(F
,"%s\n",I
->File
.c_str());
316 if (I
->Op
== Item::Configure
)
317 fprintf(F
,"**CONFIGURE**\n");
318 if (I
->Op
== Item::Remove
||
319 I
->Op
== Item::Purge
)
320 fprintf(F
,"**REMOVE**\n");
328 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
329 // ---------------------------------------------------------------------
330 /* This looks for a list of scripts to run from the configuration file
331 each one is run and is fed on standard input a list of all .deb files
332 that are due to be installed. */
333 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
335 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
336 if (Opts
== 0 || Opts
->Child
== 0)
340 unsigned int Count
= 1;
341 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
343 if (Opts
->Value
.empty() == true)
346 // Determine the protocol version
347 string OptSec
= Opts
->Value
;
348 string::size_type Pos
;
349 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
350 Pos
= OptSec
.length();
351 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
353 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
357 if (pipe(Pipes
) != 0)
358 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
359 SetCloseExec(Pipes
[0],true);
360 SetCloseExec(Pipes
[1],true);
362 // Purified Fork for running the script
363 pid_t Process
= ExecFork();
367 dup2(Pipes
[0],STDIN_FILENO
);
368 SetCloseExec(STDOUT_FILENO
,false);
369 SetCloseExec(STDIN_FILENO
,false);
370 SetCloseExec(STDERR_FILENO
,false);
372 dpkgChrootDirectory();
376 Args
[2] = Opts
->Value
.c_str();
378 execv(Args
[0],(char **)Args
);
382 FILE *F
= fdopen(Pipes
[1],"w");
384 return _error
->Errno("fdopen","Faild to open new FD");
386 // Feed it the filenames.
389 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
391 // Only deal with packages to be installed from .deb
392 if (I
->Op
!= Item::Install
)
396 if (I
->File
[0] != '/')
399 /* Feed the filename of each package that is pending install
401 fprintf(F
,"%s\n",I
->File
.c_str());
411 // Clean up the sub process
412 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
413 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
419 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
420 // ---------------------------------------------------------------------
423 void pkgDPkgPM::DoStdin(int master
)
425 unsigned char input_buf
[256] = {0,};
426 ssize_t len
= read(STDIN_FILENO
, input_buf
, sizeof(input_buf
));
428 FileFd::Write(master
, input_buf
, len
);
430 d
->stdin_is_dev_null
= true;
433 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
434 // ---------------------------------------------------------------------
436 * read the terminal pty and write log
438 void pkgDPkgPM::DoTerminalPty(int master
)
440 unsigned char term_buf
[1024] = {0,0, };
442 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
443 if(len
== -1 && errno
== EIO
)
445 // this happens when the child is about to exit, we
446 // give it time to actually exit, otherwise we run
447 // into a race so we sleep for half a second.
448 struct timespec sleepfor
= { 0, 500000000 };
449 nanosleep(&sleepfor
, NULL
);
454 FileFd::Write(1, term_buf
, len
);
456 fwrite(term_buf
, len
, sizeof(char), d
->term_out
);
459 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
460 // ---------------------------------------------------------------------
463 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd
, char *line
)
465 bool const Debug
= _config
->FindB("Debug::pkgDPkgProgressReporting",false);
466 // the status we output
467 ostringstream status
;
470 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
473 /* dpkg sends strings like this:
474 'status: <pkg>: <pkg qstate>'
475 errors look like this:
476 '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
477 and conffile-prompt like this
478 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
480 Newer versions of dpkg sent also:
481 'processing: install: pkg'
482 'processing: configure: pkg'
483 'processing: remove: pkg'
484 'processing: purge: pkg'
485 'processing: disappear: pkg'
486 'processing: trigproc: trigger'
490 // dpkg sends multiline error messages sometimes (see
491 // #374195 for a example. we should support this by
492 // either patching dpkg to not send multiline over the
493 // statusfd or by rewriting the code here to deal with
494 // it. for now we just ignore it and not crash
495 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
496 if( list
[0] == NULL
|| list
[1] == NULL
|| list
[2] == NULL
)
499 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
502 const char* const pkg
= list
[1];
503 const char* action
= _strstrip(list
[2]);
505 // 'processing' from dpkg looks like
506 // 'processing: action: pkg'
507 if(strncmp(list
[0], "processing", strlen("processing")) == 0)
510 const char* const pkg_or_trigger
= _strstrip(list
[2]);
511 action
= _strstrip( list
[1]);
512 const std::pair
<const char *, const char *> * const iter
=
513 std::find_if(PackageProcessingOpsBegin
,
514 PackageProcessingOpsEnd
,
515 MatchProcessingOp(action
));
516 if(iter
== PackageProcessingOpsEnd
)
519 std::clog
<< "ignoring unknown action: " << action
<< std::endl
;
522 snprintf(s
, sizeof(s
), _(iter
->second
), pkg_or_trigger
);
524 status
<< "pmstatus:" << pkg_or_trigger
525 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
529 FileFd::Write(OutStatusFd
, status
.str().c_str(), status
.str().size());
531 std::clog
<< "send: '" << status
.str() << "'" << endl
;
533 if (strncmp(action
, "disappear", strlen("disappear")) == 0)
534 handleDisappearAction(pkg_or_trigger
);
538 if(strncmp(action
,"error",strlen("error")) == 0)
540 // urgs, sometime has ":" in its error string so that we
541 // end up with the error message split between list[3]
542 // and list[4], e.g. the message:
543 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
545 if( list
[4] != NULL
)
546 list
[3][strlen(list
[3])] = ':';
548 status
<< "pmerror:" << list
[1]
549 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
553 FileFd::Write(OutStatusFd
, status
.str().c_str(), status
.str().size());
555 std::clog
<< "send: '" << status
.str() << "'" << endl
;
557 WriteApportReport(list
[1], list
[3]);
560 else if(strncmp(action
,"conffile",strlen("conffile")) == 0)
562 status
<< "pmconffile:" << list
[1]
563 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
567 FileFd::Write(OutStatusFd
, status
.str().c_str(), status
.str().size());
569 std::clog
<< "send: '" << status
.str() << "'" << endl
;
573 vector
<struct DpkgState
> const &states
= PackageOps
[pkg
];
574 const char *next_action
= NULL
;
575 if(PackageOpsDone
[pkg
] < states
.size())
576 next_action
= states
[PackageOpsDone
[pkg
]].state
;
577 // check if the package moved to the next dpkg state
578 if(next_action
&& (strcmp(action
, next_action
) == 0))
580 // only read the translation if there is actually a next
582 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
584 snprintf(s
, sizeof(s
), translation
, pkg
);
586 // we moved from one dpkg state to a new one, report that
587 PackageOpsDone
[pkg
]++;
589 // build the status str
590 status
<< "pmstatus:" << pkg
591 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
595 FileFd::Write(OutStatusFd
, status
.str().c_str(), status
.str().size());
597 std::clog
<< "send: '" << status
.str() << "'" << endl
;
600 std::clog
<< "(parsed from dpkg) pkg: " << pkg
601 << " action: " << action
<< endl
;
604 // DPkgPM::handleDisappearAction /*{{{*/
605 void pkgDPkgPM::handleDisappearAction(string
const &pkgname
)
607 // record the package name for display and stuff later
608 disappearedPkgs
.insert(pkgname
);
610 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
611 if (unlikely(Pkg
.end() == true))
613 // the disappeared package was auto-installed - nothing to do
614 if ((Cache
[Pkg
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
616 pkgCache::VerIterator PkgVer
= Cache
[Pkg
].InstVerIter(Cache
);
617 if (unlikely(PkgVer
.end() == true))
619 /* search in the list of dependencies for (Pre)Depends,
620 check if this dependency has a Replaces on our package
621 and if so transfer the manual installed flag to it */
622 for (pkgCache::DepIterator Dep
= PkgVer
.DependsList(); Dep
.end() != true; ++Dep
)
624 if (Dep
->Type
!= pkgCache::Dep::Depends
&&
625 Dep
->Type
!= pkgCache::Dep::PreDepends
)
627 pkgCache::PkgIterator Tar
= Dep
.TargetPkg();
628 if (unlikely(Tar
.end() == true))
630 // the package is already marked as manual
631 if ((Cache
[Tar
].Flags
& pkgCache::Flag::Auto
) != pkgCache::Flag::Auto
)
633 pkgCache::VerIterator TarVer
= Cache
[Tar
].InstVerIter(Cache
);
634 if (TarVer
.end() == true)
636 for (pkgCache::DepIterator Rep
= TarVer
.DependsList(); Rep
.end() != true; ++Rep
)
638 if (Rep
->Type
!= pkgCache::Dep::Replaces
)
640 if (Pkg
!= Rep
.TargetPkg())
642 // okay, they are strongly connected - transfer manual-bit
644 std::clog
<< "transfer manual-bit from disappeared »" << pkgname
<< "« to »" << Tar
.FullName() << "«" << std::endl
;
645 Cache
[Tar
].Flags
&= ~Flag::Auto
;
651 // DPkgPM::DoDpkgStatusFd /*{{{*/
652 // ---------------------------------------------------------------------
655 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
, int OutStatusFd
)
660 len
=read(statusfd
, &d
->dpkgbuf
[d
->dpkgbuf_pos
], sizeof(d
->dpkgbuf
)-d
->dpkgbuf_pos
);
661 d
->dpkgbuf_pos
+= len
;
665 // process line by line if we have a buffer
667 while((q
=(char*)memchr(p
, '\n', d
->dpkgbuf
+d
->dpkgbuf_pos
-p
)) != NULL
)
670 ProcessDpkgStatusLine(OutStatusFd
, p
);
671 p
=q
+1; // continue with next line
674 // now move the unprocessed bits (after the final \n that is now a 0x0)
675 // to the start and update d->dpkgbuf_pos
676 p
= (char*)memrchr(d
->dpkgbuf
, 0, d
->dpkgbuf_pos
);
680 // we are interessted in the first char *after* 0x0
683 // move the unprocessed tail to the start and update pos
684 memmove(d
->dpkgbuf
, p
, p
-d
->dpkgbuf
);
685 d
->dpkgbuf_pos
= d
->dpkgbuf
+d
->dpkgbuf_pos
-p
;
688 // DPkgPM::WriteHistoryTag /*{{{*/
689 void pkgDPkgPM::WriteHistoryTag(string
const &tag
, string value
)
691 size_t const length
= value
.length();
694 // poor mans rstrip(", ")
695 if (value
[length
-2] == ',' && value
[length
-1] == ' ')
696 value
.erase(length
- 2, 2);
697 fprintf(d
->history_out
, "%s: %s\n", tag
.c_str(), value
.c_str());
699 // DPkgPM::OpenLog /*{{{*/
700 bool pkgDPkgPM::OpenLog()
702 string
const logdir
= _config
->FindDir("Dir::Log");
703 if(CreateAPTDirectoryIfNeeded(logdir
, logdir
) == false)
704 // FIXME: use a better string after freeze
705 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
709 time_t const t
= time(NULL
);
710 struct tm
const * const tmp
= localtime(&t
);
711 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
714 string
const logfile_name
= flCombine(logdir
,
715 _config
->Find("Dir::Log::Terminal"));
716 if (!logfile_name
.empty())
718 d
->term_out
= fopen(logfile_name
.c_str(),"a");
719 if (d
->term_out
== NULL
)
720 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name
.c_str());
721 setvbuf(d
->term_out
, NULL
, _IONBF
, 0);
722 SetCloseExec(fileno(d
->term_out
), true);
725 pw
= getpwnam("root");
726 gr
= getgrnam("adm");
727 if (pw
!= NULL
&& gr
!= NULL
)
728 chown(logfile_name
.c_str(), pw
->pw_uid
, gr
->gr_gid
);
729 chmod(logfile_name
.c_str(), 0640);
730 fprintf(d
->term_out
, "\nLog started: %s\n", timestr
);
733 // write your history
734 string
const history_name
= flCombine(logdir
,
735 _config
->Find("Dir::Log::History"));
736 if (!history_name
.empty())
738 d
->history_out
= fopen(history_name
.c_str(),"a");
739 if (d
->history_out
== NULL
)
740 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), history_name
.c_str());
741 SetCloseExec(fileno(d
->history_out
), true);
742 chmod(history_name
.c_str(), 0644);
743 fprintf(d
->history_out
, "\nStart-Date: %s\n", timestr
);
744 string remove
, purge
, install
, reinstall
, upgrade
, downgrade
;
745 for (pkgCache::PkgIterator I
= Cache
.PkgBegin(); I
.end() == false; ++I
)
747 enum { CANDIDATE
, CANDIDATE_AUTO
, CURRENT_CANDIDATE
, CURRENT
} infostring
;
749 #define HISTORYINFO(X, Y) { line = &X; infostring = Y; }
750 if (Cache
[I
].NewInstall() == true)
751 HISTORYINFO(install
, CANDIDATE_AUTO
)
752 else if (Cache
[I
].ReInstall() == true)
753 HISTORYINFO(reinstall
, CANDIDATE
)
754 else if (Cache
[I
].Upgrade() == true)
755 HISTORYINFO(upgrade
, CURRENT_CANDIDATE
)
756 else if (Cache
[I
].Downgrade() == true)
757 HISTORYINFO(downgrade
, CURRENT_CANDIDATE
)
758 else if (Cache
[I
].Delete() == true)
759 HISTORYINFO((Cache
[I
].Purge() ? purge
: remove
), CURRENT
)
763 line
->append(I
.FullName(false)).append(" (");
764 switch (infostring
) {
765 case CANDIDATE
: line
->append(Cache
[I
].CandVersion
); break;
767 line
->append(Cache
[I
].CandVersion
);
768 if ((Cache
[I
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
769 line
->append(", automatic");
771 case CURRENT_CANDIDATE
: line
->append(Cache
[I
].CurVersion
).append(", ").append(Cache
[I
].CandVersion
); break;
772 case CURRENT
: line
->append(Cache
[I
].CurVersion
); break;
776 if (_config
->Exists("Commandline::AsString") == true)
777 WriteHistoryTag("Commandline", _config
->Find("Commandline::AsString"));
778 WriteHistoryTag("Install", install
);
779 WriteHistoryTag("Reinstall", reinstall
);
780 WriteHistoryTag("Upgrade", upgrade
);
781 WriteHistoryTag("Downgrade",downgrade
);
782 WriteHistoryTag("Remove",remove
);
783 WriteHistoryTag("Purge",purge
);
784 fflush(d
->history_out
);
790 // DPkg::CloseLog /*{{{*/
791 bool pkgDPkgPM::CloseLog()
794 time_t t
= time(NULL
);
795 struct tm
*tmp
= localtime(&t
);
796 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
800 fprintf(d
->term_out
, "Log ended: ");
801 fprintf(d
->term_out
, "%s", timestr
);
802 fprintf(d
->term_out
, "\n");
809 if (disappearedPkgs
.empty() == false)
812 for (std::set
<std::string
>::const_iterator d
= disappearedPkgs
.begin();
813 d
!= disappearedPkgs
.end(); ++d
)
815 pkgCache::PkgIterator P
= Cache
.FindPkg(*d
);
816 disappear
.append(*d
);
818 disappear
.append(", ");
820 disappear
.append(" (").append(Cache
[P
].CurVersion
).append("), ");
822 WriteHistoryTag("Disappeared", disappear
);
824 if (d
->dpkg_error
.empty() == false)
825 fprintf(d
->history_out
, "Error: %s\n", d
->dpkg_error
.c_str());
826 fprintf(d
->history_out
, "End-Date: %s\n", timestr
);
827 fclose(d
->history_out
);
829 d
->history_out
= NULL
;
835 // This implements a racy version of pselect for those architectures
836 // that don't have a working implementation.
837 // FIXME: Probably can be removed on Lenny+1
838 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
839 fd_set
*exceptfds
, const struct timespec
*timeout
,
840 const sigset_t
*sigmask
)
846 tv
.tv_sec
= timeout
->tv_sec
;
847 tv
.tv_usec
= timeout
->tv_nsec
/1000;
849 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
850 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
851 sigprocmask(SIG_SETMASK
, &origmask
, 0);
855 // DPkgPM::Go - Run the sequence /*{{{*/
856 // ---------------------------------------------------------------------
857 /* This globs the operations and calls dpkg
859 * If it is called with "OutStatusFd" set to a valid file descriptor
860 * apt will report the install progress over this fd. It maps the
861 * dpkg states a package goes through to human readable (and i10n-able)
862 * names and calculates a percentage for each step.
864 bool pkgDPkgPM::Go(int OutStatusFd
)
866 pkgPackageManager::SigINTStop
= false;
868 // Generate the base argument list for dpkg
869 std::vector
<const char *> Args
;
870 unsigned long StartSize
= 0;
871 string Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
873 string
const dpkgChrootDir
= _config
->FindDir("DPkg::Chroot-Directory", "/");
874 size_t dpkgChrootLen
= dpkgChrootDir
.length();
875 if (dpkgChrootDir
!= "/" && Tmp
.find(dpkgChrootDir
) == 0)
877 if (dpkgChrootDir
[dpkgChrootLen
- 1] == '/')
879 Tmp
= Tmp
.substr(dpkgChrootLen
);
882 Args
.push_back(Tmp
.c_str());
883 StartSize
+= Tmp
.length();
885 // Stick in any custom dpkg options
886 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
890 for (; Opts
!= 0; Opts
= Opts
->Next
)
892 if (Opts
->Value
.empty() == true)
894 Args
.push_back(Opts
->Value
.c_str());
895 StartSize
+= Opts
->Value
.length();
899 size_t const BaseArgs
= Args
.size();
900 // we need to detect if we can qualify packages with the architecture or not
901 Args
.push_back("--assert-multi-arch");
902 Args
.push_back(NULL
);
904 pid_t dpkgAssertMultiArch
= ExecFork();
905 if (dpkgAssertMultiArch
== 0)
907 dpkgChrootDirectory();
908 // redirect everything to the ultimate sink as we only need the exit-status
909 int const nullfd
= open("/dev/null", O_RDONLY
);
910 dup2(nullfd
, STDIN_FILENO
);
911 dup2(nullfd
, STDOUT_FILENO
);
912 dup2(nullfd
, STDERR_FILENO
);
913 execvp(Args
[0], (char**) &Args
[0]);
914 _error
->WarningE("dpkgGo", "Can't detect if dpkg supports multi-arch!");
921 sigset_t original_sigmask
;
923 unsigned int const MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
924 unsigned int const MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
925 bool const NoTriggers
= _config
->FindB("DPkg::NoTriggers", false);
927 if (RunScripts("DPkg::Pre-Invoke") == false)
930 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
933 // support subpressing of triggers processing for special
934 // cases like d-i that runs the triggers handling manually
935 bool const SmartConf
= (_config
->Find("PackageManager::Configure", "all") != "all");
936 bool const TriggersPending
= _config
->FindB("DPkg::TriggersPending", false);
937 if (_config
->FindB("DPkg::ConfigurePending", SmartConf
) == true)
938 List
.push_back(Item(Item::ConfigurePending
, PkgIterator()));
940 // map the dpkg states to the operations that are performed
941 // (this is sorted in the same way as Item::Ops)
942 static const struct DpkgState DpkgStatesOpMap
[][7] = {
945 {"half-installed", N_("Preparing %s")},
946 {"unpacked", N_("Unpacking %s") },
949 // Configure operation
951 {"unpacked",N_("Preparing to configure %s") },
952 {"half-configured", N_("Configuring %s") },
953 { "installed", N_("Installed %s")},
958 {"half-configured", N_("Preparing for removal of %s")},
959 {"half-installed", N_("Removing %s")},
960 {"config-files", N_("Removed %s")},
965 {"config-files", N_("Preparing to completely remove %s")},
966 {"not-installed", N_("Completely removed %s")},
971 // init the PackageOps map, go over the list of packages that
972 // that will be [installed|configured|removed|purged] and add
973 // them to the PackageOps map (the dpkg states it goes through)
974 // and the PackageOpsTranslations (human readable strings)
975 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end(); ++I
)
977 if((*I
).Pkg
.end() == true)
980 string
const name
= (*I
).Pkg
.Name();
981 PackageOpsDone
[name
] = 0;
982 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; ++i
)
984 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
989 d
->stdin_is_dev_null
= false;
994 bool dpkgMultiArch
= false;
995 if (dpkgAssertMultiArch
> 0)
998 while (waitpid(dpkgAssertMultiArch
, &Status
, 0) != dpkgAssertMultiArch
)
1002 _error
->WarningE("dpkgGo", _("Waited for %s but it wasn't there"), "dpkg --assert-multi-arch");
1005 if (WIFEXITED(Status
) == true && WEXITSTATUS(Status
) == 0)
1006 dpkgMultiArch
= true;
1009 // this loop is runs once per operation
1010 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();)
1012 // Do all actions with the same Op in one run
1013 vector
<Item
>::const_iterator J
= I
;
1014 if (TriggersPending
== true)
1015 for (; J
!= List
.end(); ++J
)
1019 if (J
->Op
!= Item::TriggersPending
)
1021 vector
<Item
>::const_iterator T
= J
+ 1;
1022 if (T
!= List
.end() && T
->Op
== I
->Op
)
1027 for (; J
!= List
.end() && J
->Op
== I
->Op
; ++J
)
1030 // keep track of allocated strings for multiarch package names
1031 std::vector
<char *> Packages
;
1033 // start with the baseset of arguments
1034 unsigned long Size
= StartSize
;
1035 Args
.erase(Args
.begin() + BaseArgs
, Args
.end());
1037 // Now check if we are within the MaxArgs limit
1039 // this code below is problematic, because it may happen that
1040 // the argument list is split in a way that A depends on B
1041 // and they are in the same "--configure A B" run
1042 // - with the split they may now be configured in different
1043 // runs, using Immediate-Configure-All can help prevent this.
1044 if (J
- I
> (signed)MaxArgs
)
1047 unsigned long const size
= MaxArgs
+ 10;
1049 Packages
.reserve(size
);
1053 unsigned long const size
= (J
- I
) + 10;
1055 Packages
.reserve(size
);
1060 return _error
->Errno("pipe","Failed to create IPC pipe to dpkg");
1062 #define ADDARG(X) Args.push_back(X); Size += strlen(X)
1063 #define ADDARGC(X) Args.push_back(X); Size += sizeof(X) - 1
1065 ADDARGC("--status-fd");
1066 char status_fd_buf
[20];
1067 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
1068 ADDARG(status_fd_buf
);
1069 unsigned long const Op
= I
->Op
;
1074 ADDARGC("--force-depends");
1075 ADDARGC("--force-remove-essential");
1076 ADDARGC("--remove");
1080 ADDARGC("--force-depends");
1081 ADDARGC("--force-remove-essential");
1085 case Item::Configure
:
1086 ADDARGC("--configure");
1089 case Item::ConfigurePending
:
1090 ADDARGC("--configure");
1091 ADDARGC("--pending");
1094 case Item::TriggersPending
:
1095 ADDARGC("--triggers-only");
1096 ADDARGC("--pending");
1100 ADDARGC("--unpack");
1101 ADDARGC("--auto-deconfigure");
1105 if (NoTriggers
== true && I
->Op
!= Item::TriggersPending
&&
1106 I
->Op
!= Item::ConfigurePending
)
1108 ADDARGC("--no-triggers");
1112 // Write in the file or package names
1113 if (I
->Op
== Item::Install
)
1115 for (;I
!= J
&& Size
< MaxArgBytes
; ++I
)
1117 if (I
->File
[0] != '/')
1118 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
1119 Args
.push_back(I
->File
.c_str());
1120 Size
+= I
->File
.length();
1125 string
const nativeArch
= _config
->Find("APT::Architecture");
1126 unsigned long const oldSize
= I
->Op
== Item::Configure
? Size
: 0;
1127 for (;I
!= J
&& Size
< MaxArgBytes
; ++I
)
1129 if((*I
).Pkg
.end() == true)
1131 if (I
->Op
== Item::Configure
&& disappearedPkgs
.find(I
->Pkg
.Name()) != disappearedPkgs
.end())
1133 // We keep this here to allow "smooth" transitions from e.g. multiarch dpkg/ubuntu to dpkg/debian
1134 if (dpkgMultiArch
== false && (I
->Pkg
.Arch() == nativeArch
||
1135 strcmp(I
->Pkg
.Arch(), "all") == 0 ||
1136 strcmp(I
->Pkg
.Arch(), "none") == 0))
1138 char const * const name
= I
->Pkg
.Name();
1143 pkgCache::VerIterator PkgVer
;
1144 std::string name
= I
->Pkg
.Name();
1145 if (Op
== Item::Remove
|| Op
== Item::Purge
)
1147 PkgVer
= I
->Pkg
.CurrentVer();
1148 if(PkgVer
.end() == true)
1149 PkgVer
= FindNowVersion(I
->Pkg
);
1152 PkgVer
= Cache
[I
->Pkg
].InstVerIter(Cache
);
1153 if (strcmp(I
->Pkg
.Arch(), "none") == 0)
1154 ; // never arch-qualify a package without an arch
1155 else if (PkgVer
.end() == false)
1156 name
.append(":").append(PkgVer
.Arch());
1158 _error
->Warning("Can not find PkgVer for '%s'", name
.c_str());
1159 char * const fullname
= strdup(name
.c_str());
1160 Packages
.push_back(fullname
);
1164 // skip configure action if all sheduled packages disappeared
1165 if (oldSize
== Size
)
1172 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
1174 for (std::vector
<const char *>::const_iterator a
= Args
.begin();
1175 a
!= Args
.end(); ++a
)
1180 Args
.push_back(NULL
);
1186 /* Mask off sig int/quit. We do this because dpkg also does when
1187 it forks scripts. What happens is that when you hit ctrl-c it sends
1188 it to all processes in the group. Since dpkg ignores the signal
1189 it doesn't die but we do! So we must also ignore it */
1190 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
1191 sighandler_t old_SIGINT
= signal(SIGINT
,SigINT
);
1193 // Check here for any SIGINT
1194 if (pkgPackageManager::SigINTStop
&& (Op
== Item::Remove
|| Op
== Item::Purge
|| Op
== Item::Install
))
1198 // ignore SIGHUP as well (debian #463030)
1199 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
1206 // if tcgetattr does not return zero there was a error
1207 // and we do not do any pty magic
1208 if (tcgetattr(STDOUT_FILENO
, &tt
) == 0)
1210 ioctl(0, TIOCGWINSZ
, (char *)&win
);
1211 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
1213 const char *s
= _("Can not write log, openpty() "
1214 "failed (/dev/pts not mounted?)\n");
1215 fprintf(stderr
, "%s",s
);
1217 fprintf(d
->term_out
, "%s",s
);
1218 master
= slave
= -1;
1223 rtt
.c_lflag
&= ~ECHO
;
1224 rtt
.c_lflag
|= ISIG
;
1225 // block SIGTTOU during tcsetattr to prevent a hang if
1226 // the process is a member of the background process group
1227 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
1228 sigemptyset(&sigmask
);
1229 sigaddset(&sigmask
, SIGTTOU
);
1230 sigprocmask(SIG_BLOCK
,&sigmask
, &original_sigmask
);
1231 tcsetattr(0, TCSAFLUSH
, &rtt
);
1232 sigprocmask(SIG_SETMASK
, &original_sigmask
, 0);
1235 const char *s
= _("Can not write log, tcgetattr() failed for stdout");
1236 fprintf(stderr
, "%s", s
);
1238 fprintf(d
->term_out
, "%s",s
);
1242 _config
->Set("APT::Keep-Fds::",fd
[1]);
1243 // send status information that we are about to fork dpkg
1244 if(OutStatusFd
> 0) {
1245 ostringstream status
;
1246 status
<< "pmstatus:dpkg-exec:"
1247 << (PackagesDone
/float(PackagesTotal
)*100.0)
1248 << ":" << _("Running dpkg")
1250 FileFd::Write(OutStatusFd
, status
.str().c_str(), status
.str().size());
1254 // This is the child
1257 if(slave
>= 0 && master
>= 0)
1260 ioctl(slave
, TIOCSCTTY
, 0);
1267 close(fd
[0]); // close the read end of the pipe
1269 dpkgChrootDirectory();
1271 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
1274 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
1277 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
1280 // Discard everything in stdin before forking dpkg
1281 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
1284 while (read(STDIN_FILENO
,&dummy
,1) == 1);
1286 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
1290 /* No Job Control Stop Env is a magic dpkg var that prevents it
1291 from using sigstop */
1292 putenv((char *)"DPKG_NO_TSTP=yes");
1293 execvp(Args
[0], (char**) &Args
[0]);
1294 cerr
<< "Could not exec dpkg!" << endl
;
1299 if (_config
->FindB("DPkg::UseIoNice", false) == true)
1302 // clear the Keep-Fd again
1303 _config
->Clear("APT::Keep-Fds",fd
[1]);
1308 // we read from dpkg here
1309 int const _dpkgin
= fd
[0];
1310 close(fd
[1]); // close the write end of the pipe
1316 sigemptyset(&sigmask
);
1317 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
1319 /* free vectors (and therefore memory) as we don't need the included data anymore */
1320 for (std::vector
<char *>::const_iterator p
= Packages
.begin();
1321 p
!= Packages
.end(); ++p
)
1325 // the result of the waitpid call
1328 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
1330 // FIXME: move this to a function or something, looks ugly here
1331 // error handling, waitpid returned -1
1334 RunScripts("DPkg::Post-Invoke");
1336 // Restore sig int/quit
1337 signal(SIGQUIT
,old_SIGQUIT
);
1338 signal(SIGINT
,old_SIGINT
);
1340 signal(SIGHUP
,old_SIGHUP
);
1341 return _error
->Errno("waitpid","Couldn't wait for subprocess");
1344 // wait for input or output here
1346 if (master
>= 0 && !d
->stdin_is_dev_null
)
1348 FD_SET(_dpkgin
, &rfds
);
1350 FD_SET(master
, &rfds
);
1353 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
1354 &tv
, &original_sigmask
);
1355 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
1356 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
1357 NULL
, &tv
, &original_sigmask
);
1358 if (select_ret
== 0)
1360 else if (select_ret
< 0 && errno
== EINTR
)
1362 else if (select_ret
< 0)
1364 perror("select() returned error");
1368 if(master
>= 0 && FD_ISSET(master
, &rfds
))
1369 DoTerminalPty(master
);
1370 if(master
>= 0 && FD_ISSET(0, &rfds
))
1372 if(FD_ISSET(_dpkgin
, &rfds
))
1373 DoDpkgStatusFd(_dpkgin
, OutStatusFd
);
1377 // Restore sig int/quit
1378 signal(SIGQUIT
,old_SIGQUIT
);
1379 signal(SIGINT
,old_SIGINT
);
1381 signal(SIGHUP
,old_SIGHUP
);
1385 tcsetattr(0, TCSAFLUSH
, &tt
);
1389 // Check for an error code.
1390 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
1392 // if it was set to "keep-dpkg-runing" then we won't return
1393 // here but keep the loop going and just report it as a error
1395 bool const stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
1398 RunScripts("DPkg::Post-Invoke");
1400 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
1401 strprintf(d
->dpkg_error
, "Sub-process %s received a segmentation fault.",Args
[0]);
1402 else if (WIFEXITED(Status
) != 0)
1403 strprintf(d
->dpkg_error
, "Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
1405 strprintf(d
->dpkg_error
, "Sub-process %s exited unexpectedly",Args
[0]);
1407 if(d
->dpkg_error
.size() > 0)
1408 _error
->Error("%s", d
->dpkg_error
.c_str());
1419 if (pkgPackageManager::SigINTStop
)
1420 _error
->Warning(_("Operation was interrupted before it could finish"));
1422 if (RunScripts("DPkg::Post-Invoke") == false)
1425 if (_config
->FindB("Debug::pkgDPkgPM",false) == false)
1427 std::string
const oldpkgcache
= _config
->FindFile("Dir::cache::pkgcache");
1428 if (oldpkgcache
.empty() == false && RealFileExists(oldpkgcache
) == true &&
1429 unlink(oldpkgcache
.c_str()) == 0)
1431 std::string
const srcpkgcache
= _config
->FindFile("Dir::cache::srcpkgcache");
1432 if (srcpkgcache
.empty() == false && RealFileExists(srcpkgcache
) == true)
1434 _error
->PushToStack();
1435 pkgCacheFile CacheFile
;
1436 CacheFile
.BuildCaches(NULL
, true);
1437 _error
->RevertToStack();
1442 Cache
.writeStateFile(NULL
);
1446 void SigINT(int sig
) {
1447 pkgPackageManager::SigINTStop
= true;
1450 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1451 // ---------------------------------------------------------------------
1453 void pkgDPkgPM::Reset()
1455 List
.erase(List
.begin(),List
.end());
1458 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1459 // ---------------------------------------------------------------------
1461 void pkgDPkgPM::WriteApportReport(const char *pkgpath
, const char *errormsg
)
1463 // If apport doesn't exist or isn't installed do nothing
1464 // This e.g. prevents messages in 'universes' without apport
1465 pkgCache::PkgIterator apportPkg
= Cache
.FindPkg("apport");
1466 if (apportPkg
.end() == true || apportPkg
->CurrentVer
== 0)
1469 string pkgname
, reportfile
, srcpkgname
, pkgver
, arch
;
1470 string::size_type pos
;
1473 if (_config
->FindB("Dpkg::ApportFailureReport", false) == false)
1475 std::clog
<< "configured to not write apport reports" << std::endl
;
1479 // only report the first errors
1480 if(pkgFailures
> _config
->FindI("APT::Apport::MaxReports", 3))
1482 std::clog
<< _("No apport report written because MaxReports is reached already") << std::endl
;
1486 // check if its not a follow up error
1487 const char *needle
= dgettext("dpkg", "dependency problems - leaving unconfigured");
1488 if(strstr(errormsg
, needle
) != NULL
) {
1489 std::clog
<< _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl
;
1493 // do not report disk-full failures
1494 if(strstr(errormsg
, strerror(ENOSPC
)) != NULL
) {
1495 std::clog
<< _("No apport report written because the error message indicates a disk full error") << std::endl
;
1499 // do not report out-of-memory failures
1500 if(strstr(errormsg
, strerror(ENOMEM
)) != NULL
) {
1501 std::clog
<< _("No apport report written because the error message indicates a out of memory error") << std::endl
;
1505 // do not report dpkg I/O errors
1506 // XXX - this message is localized, but this only matches the English version. This is better than nothing.
1507 if(strstr(errormsg
, "short read in buffer_copy (")) {
1508 std::clog
<< _("No apport report written because the error message indicates a dpkg I/O error") << std::endl
;
1512 // get the pkgname and reportfile
1513 pkgname
= flNotDir(pkgpath
);
1514 pos
= pkgname
.find('_');
1515 if(pos
!= string::npos
)
1516 pkgname
= pkgname
.substr(0, pos
);
1518 // find the package versin and source package name
1519 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
1520 if (Pkg
.end() == true)
1522 pkgCache::VerIterator Ver
= Cache
.GetCandidateVer(Pkg
);
1523 if (Ver
.end() == true)
1525 pkgver
= Ver
.VerStr() == NULL
? "unknown" : Ver
.VerStr();
1526 pkgRecords
Recs(Cache
);
1527 pkgRecords::Parser
&Parse
= Recs
.Lookup(Ver
.FileList());
1528 srcpkgname
= Parse
.SourcePkg();
1529 if(srcpkgname
.empty())
1530 srcpkgname
= pkgname
;
1532 // if the file exists already, we check:
1533 // - if it was reported already (touched by apport).
1534 // If not, we do nothing, otherwise
1535 // we overwrite it. This is the same behaviour as apport
1536 // - if we have a report with the same pkgversion already
1538 reportfile
= flCombine("/var/crash",pkgname
+".0.crash");
1539 if(FileExists(reportfile
))
1544 // check atime/mtime
1545 stat(reportfile
.c_str(), &buf
);
1546 if(buf
.st_mtime
> buf
.st_atime
)
1549 // check if the existing report is the same version
1550 report
= fopen(reportfile
.c_str(),"r");
1551 while(fgets(strbuf
, sizeof(strbuf
), report
) != NULL
)
1553 if(strstr(strbuf
,"Package:") == strbuf
)
1555 char pkgname
[255], version
[255];
1556 if(sscanf(strbuf
, "Package: %254s %254s", pkgname
, version
) == 2)
1557 if(strcmp(pkgver
.c_str(), version
) == 0)
1567 // now write the report
1568 arch
= _config
->Find("APT::Architecture");
1569 report
= fopen(reportfile
.c_str(),"w");
1572 if(_config
->FindB("DPkgPM::InitialReportOnly",false) == true)
1573 chmod(reportfile
.c_str(), 0);
1575 chmod(reportfile
.c_str(), 0600);
1576 fprintf(report
, "ProblemType: Package\n");
1577 fprintf(report
, "Architecture: %s\n", arch
.c_str());
1578 time_t now
= time(NULL
);
1579 fprintf(report
, "Date: %s" , ctime(&now
));
1580 fprintf(report
, "Package: %s %s\n", pkgname
.c_str(), pkgver
.c_str());
1581 fprintf(report
, "SourcePackage: %s\n", srcpkgname
.c_str());
1582 fprintf(report
, "ErrorMessage:\n %s\n", errormsg
);
1584 // ensure that the log is flushed
1586 fflush(d
->term_out
);
1588 // attach terminal log it if we have it
1589 string logfile_name
= _config
->FindFile("Dir::Log::Terminal");
1590 if (!logfile_name
.empty())
1595 fprintf(report
, "DpkgTerminalLog:\n");
1596 log
= fopen(logfile_name
.c_str(),"r");
1599 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1600 fprintf(report
, " %s", buf
);
1606 const char *ops_str
[] = {"Install", "Configure","Remove","Purge"};
1607 fprintf(report
, "AptOrdering:\n");
1608 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
1609 if ((*I
).Pkg
!= NULL
)
1610 fprintf(report
, " %s: %s\n", (*I
).Pkg
.Name(), ops_str
[(*I
).Op
]);
1612 fprintf(report
, " %s: %s\n", "NULL", ops_str
[(*I
).Op
]);
1614 // attach dmesg log (to learn about segfaults)
1615 if (FileExists("/bin/dmesg"))
1620 fprintf(report
, "Dmesg:\n");
1621 log
= popen("/bin/dmesg","r");
1624 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1625 fprintf(report
, " %s", buf
);
1630 // attach df -l log (to learn about filesystem status)
1631 if (FileExists("/bin/df"))
1636 fprintf(report
, "Df:\n");
1637 log
= popen("/bin/df -l","r");
1640 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1641 fprintf(report
, " %s", buf
);