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"))
166 ssize_t
retry_write(int fd
, const void *buf
, size_t count
)
173 Res
= write(fd
, buf
, count
);
174 if (Res
< 0 && errno
== EINTR
)
178 buf
= (char *)buf
+ Res
;
182 while (Res
> 0 && count
> 0);
186 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
187 // ---------------------------------------------------------------------
189 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
190 : pkgPackageManager(Cache
), PackagesDone(0), PackagesTotal(0)
192 d
= new pkgDPkgPMPrivate();
195 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
196 // ---------------------------------------------------------------------
198 pkgDPkgPM::~pkgDPkgPM()
203 // DPkgPM::Install - Install a package /*{{{*/
204 // ---------------------------------------------------------------------
205 /* Add an install operation to the sequence list */
206 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
208 if (File
.empty() == true || Pkg
.end() == true)
209 return _error
->Error("Internal Error, No file name for %s",Pkg
.Name());
211 // If the filename string begins with DPkg::Chroot-Directory, return the
212 // substr that is within the chroot so dpkg can access it.
213 string
const chrootdir
= _config
->FindDir("DPkg::Chroot-Directory","/");
214 if (chrootdir
!= "/" && File
.find(chrootdir
) == 0)
216 size_t len
= chrootdir
.length();
217 if (chrootdir
.at(len
- 1) == '/')
219 List
.push_back(Item(Item::Install
,Pkg
,File
.substr(len
)));
222 List
.push_back(Item(Item::Install
,Pkg
,File
));
227 // DPkgPM::Configure - Configure a package /*{{{*/
228 // ---------------------------------------------------------------------
229 /* Add a configure operation to the sequence list */
230 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
232 if (Pkg
.end() == true)
235 List
.push_back(Item(Item::Configure
, Pkg
));
237 // Use triggers for config calls if we configure "smart"
238 // as otherwise Pre-Depends will not be satisfied, see #526774
239 if (_config
->FindB("DPkg::TriggersPending", false) == true)
240 List
.push_back(Item(Item::TriggersPending
, PkgIterator()));
245 // DPkgPM::Remove - Remove a package /*{{{*/
246 // ---------------------------------------------------------------------
247 /* Add a remove operation to the sequence list */
248 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
250 if (Pkg
.end() == true)
254 List
.push_back(Item(Item::Purge
,Pkg
));
256 List
.push_back(Item(Item::Remove
,Pkg
));
260 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
261 // ---------------------------------------------------------------------
262 /* This is part of the helper script communication interface, it sends
263 very complete information down to the other end of the pipe.*/
264 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
266 fprintf(F
,"VERSION 2\n");
268 /* Write out all of the configuration directives by walking the
269 configuration tree */
270 const Configuration::Item
*Top
= _config
->Tree(0);
273 if (Top
->Value
.empty() == false)
276 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
277 QuoteString(Top
->Value
,"\n").c_str());
286 while (Top
!= 0 && Top
->Next
== 0)
293 // Write out the package actions in order.
294 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
296 if(I
->Pkg
.end() == true)
299 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
301 fprintf(F
,"%s ",I
->Pkg
.Name());
303 if (I
->Pkg
->CurrentVer
== 0)
306 fprintf(F
,"%s ",I
->Pkg
.CurrentVer().VerStr());
308 // Show the compare operator
310 if (S
.InstallVer
!= 0)
313 if (I
->Pkg
->CurrentVer
!= 0)
314 Comp
= S
.InstVerIter(Cache
).CompareVer(I
->Pkg
.CurrentVer());
321 fprintf(F
,"%s ",S
.InstVerIter(Cache
).VerStr());
326 // Show the filename/operation
327 if (I
->Op
== Item::Install
)
330 if (I
->File
[0] != '/')
331 fprintf(F
,"**ERROR**\n");
333 fprintf(F
,"%s\n",I
->File
.c_str());
335 if (I
->Op
== Item::Configure
)
336 fprintf(F
,"**CONFIGURE**\n");
337 if (I
->Op
== Item::Remove
||
338 I
->Op
== Item::Purge
)
339 fprintf(F
,"**REMOVE**\n");
347 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
348 // ---------------------------------------------------------------------
349 /* This looks for a list of scripts to run from the configuration file
350 each one is run and is fed on standard input a list of all .deb files
351 that are due to be installed. */
352 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
354 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
355 if (Opts
== 0 || Opts
->Child
== 0)
359 unsigned int Count
= 1;
360 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
362 if (Opts
->Value
.empty() == true)
365 // Determine the protocol version
366 string OptSec
= Opts
->Value
;
367 string::size_type Pos
;
368 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
369 Pos
= OptSec
.length();
370 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
372 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
376 if (pipe(Pipes
) != 0)
377 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
378 SetCloseExec(Pipes
[0],true);
379 SetCloseExec(Pipes
[1],true);
381 // Purified Fork for running the script
382 pid_t Process
= ExecFork();
386 dup2(Pipes
[0],STDIN_FILENO
);
387 SetCloseExec(STDOUT_FILENO
,false);
388 SetCloseExec(STDIN_FILENO
,false);
389 SetCloseExec(STDERR_FILENO
,false);
391 dpkgChrootDirectory();
395 Args
[2] = Opts
->Value
.c_str();
397 execv(Args
[0],(char **)Args
);
401 FILE *F
= fdopen(Pipes
[1],"w");
403 return _error
->Errno("fdopen","Faild to open new FD");
405 // Feed it the filenames.
408 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
410 // Only deal with packages to be installed from .deb
411 if (I
->Op
!= Item::Install
)
415 if (I
->File
[0] != '/')
418 /* Feed the filename of each package that is pending install
420 fprintf(F
,"%s\n",I
->File
.c_str());
430 // Clean up the sub process
431 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
432 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
438 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
439 // ---------------------------------------------------------------------
442 void pkgDPkgPM::DoStdin(int master
)
444 unsigned char input_buf
[256] = {0,};
445 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
447 retry_write(master
, input_buf
, len
);
449 d
->stdin_is_dev_null
= true;
452 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
453 // ---------------------------------------------------------------------
455 * read the terminal pty and write log
457 void pkgDPkgPM::DoTerminalPty(int master
)
459 unsigned char term_buf
[1024] = {0,0, };
461 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
462 if(len
== -1 && errno
== EIO
)
464 // this happens when the child is about to exit, we
465 // give it time to actually exit, otherwise we run
466 // into a race so we sleep for half a second.
467 struct timespec sleepfor
= { 0, 500000000 };
468 nanosleep(&sleepfor
, NULL
);
473 retry_write(1, term_buf
, len
);
475 fwrite(term_buf
, len
, sizeof(char), d
->term_out
);
478 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
479 // ---------------------------------------------------------------------
482 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd
, char *line
)
484 bool const Debug
= _config
->FindB("Debug::pkgDPkgProgressReporting",false);
485 // the status we output
486 ostringstream status
;
489 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
492 /* dpkg sends strings like this:
493 'status: <pkg>: <pkg qstate>'
494 errors look like this:
495 '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
496 and conffile-prompt like this
497 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
499 Newer versions of dpkg sent also:
500 'processing: install: pkg'
501 'processing: configure: pkg'
502 'processing: remove: pkg'
503 'processing: purge: pkg'
504 'processing: disappear: pkg'
505 'processing: trigproc: trigger'
509 // dpkg sends multiline error messages sometimes (see
510 // #374195 for a example. we should support this by
511 // either patching dpkg to not send multiline over the
512 // statusfd or by rewriting the code here to deal with
513 // it. for now we just ignore it and not crash
514 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
515 if( list
[0] == NULL
|| list
[1] == NULL
|| list
[2] == NULL
)
518 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
521 const char* const pkg
= list
[1];
522 const char* action
= _strstrip(list
[2]);
524 // 'processing' from dpkg looks like
525 // 'processing: action: pkg'
526 if(strncmp(list
[0], "processing", strlen("processing")) == 0)
529 const char* const pkg_or_trigger
= _strstrip(list
[2]);
530 action
= _strstrip( list
[1]);
531 const std::pair
<const char *, const char *> * const iter
=
532 std::find_if(PackageProcessingOpsBegin
,
533 PackageProcessingOpsEnd
,
534 MatchProcessingOp(action
));
535 if(iter
== PackageProcessingOpsEnd
)
538 std::clog
<< "ignoring unknown action: " << action
<< std::endl
;
541 snprintf(s
, sizeof(s
), _(iter
->second
), pkg_or_trigger
);
543 status
<< "pmstatus:" << pkg_or_trigger
544 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
548 retry_write(OutStatusFd
, status
.str().c_str(), status
.str().size());
550 std::clog
<< "send: '" << status
.str() << "'" << endl
;
552 if (strncmp(action
, "disappear", strlen("disappear")) == 0)
553 handleDisappearAction(pkg_or_trigger
);
557 if(strncmp(action
,"error",strlen("error")) == 0)
559 // urgs, sometime has ":" in its error string so that we
560 // end up with the error message split between list[3]
561 // and list[4], e.g. the message:
562 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
564 if( list
[4] != NULL
)
565 list
[3][strlen(list
[3])] = ':';
567 status
<< "pmerror:" << list
[1]
568 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
572 retry_write(OutStatusFd
, status
.str().c_str(), status
.str().size());
574 std::clog
<< "send: '" << status
.str() << "'" << endl
;
576 WriteApportReport(list
[1], list
[3]);
579 else if(strncmp(action
,"conffile",strlen("conffile")) == 0)
581 status
<< "pmconffile:" << list
[1]
582 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
586 retry_write(OutStatusFd
, status
.str().c_str(), status
.str().size());
588 std::clog
<< "send: '" << status
.str() << "'" << endl
;
592 vector
<struct DpkgState
> const &states
= PackageOps
[pkg
];
593 const char *next_action
= NULL
;
594 if(PackageOpsDone
[pkg
] < states
.size())
595 next_action
= states
[PackageOpsDone
[pkg
]].state
;
596 // check if the package moved to the next dpkg state
597 if(next_action
&& (strcmp(action
, next_action
) == 0))
599 // only read the translation if there is actually a next
601 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
603 snprintf(s
, sizeof(s
), translation
, pkg
);
605 // we moved from one dpkg state to a new one, report that
606 PackageOpsDone
[pkg
]++;
608 // build the status str
609 status
<< "pmstatus:" << pkg
610 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
614 retry_write(OutStatusFd
, status
.str().c_str(), status
.str().size());
616 std::clog
<< "send: '" << status
.str() << "'" << endl
;
619 std::clog
<< "(parsed from dpkg) pkg: " << pkg
620 << " action: " << action
<< endl
;
623 // DPkgPM::handleDisappearAction /*{{{*/
624 void pkgDPkgPM::handleDisappearAction(string
const &pkgname
)
626 // record the package name for display and stuff later
627 disappearedPkgs
.insert(pkgname
);
629 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
630 if (unlikely(Pkg
.end() == true))
632 // the disappeared package was auto-installed - nothing to do
633 if ((Cache
[Pkg
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
635 pkgCache::VerIterator PkgVer
= Cache
[Pkg
].InstVerIter(Cache
);
636 if (unlikely(PkgVer
.end() == true))
638 /* search in the list of dependencies for (Pre)Depends,
639 check if this dependency has a Replaces on our package
640 and if so transfer the manual installed flag to it */
641 for (pkgCache::DepIterator Dep
= PkgVer
.DependsList(); Dep
.end() != true; ++Dep
)
643 if (Dep
->Type
!= pkgCache::Dep::Depends
&&
644 Dep
->Type
!= pkgCache::Dep::PreDepends
)
646 pkgCache::PkgIterator Tar
= Dep
.TargetPkg();
647 if (unlikely(Tar
.end() == true))
649 // the package is already marked as manual
650 if ((Cache
[Tar
].Flags
& pkgCache::Flag::Auto
) != pkgCache::Flag::Auto
)
652 pkgCache::VerIterator TarVer
= Cache
[Tar
].InstVerIter(Cache
);
653 if (TarVer
.end() == true)
655 for (pkgCache::DepIterator Rep
= TarVer
.DependsList(); Rep
.end() != true; ++Rep
)
657 if (Rep
->Type
!= pkgCache::Dep::Replaces
)
659 if (Pkg
!= Rep
.TargetPkg())
661 // okay, they are strongly connected - transfer manual-bit
663 std::clog
<< "transfer manual-bit from disappeared »" << pkgname
<< "« to »" << Tar
.FullName() << "«" << std::endl
;
664 Cache
[Tar
].Flags
&= ~Flag::Auto
;
670 // DPkgPM::DoDpkgStatusFd /*{{{*/
671 // ---------------------------------------------------------------------
674 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
, int OutStatusFd
)
679 len
=read(statusfd
, &d
->dpkgbuf
[d
->dpkgbuf_pos
], sizeof(d
->dpkgbuf
)-d
->dpkgbuf_pos
);
680 d
->dpkgbuf_pos
+= len
;
684 // process line by line if we have a buffer
686 while((q
=(char*)memchr(p
, '\n', d
->dpkgbuf
+d
->dpkgbuf_pos
-p
)) != NULL
)
689 ProcessDpkgStatusLine(OutStatusFd
, p
);
690 p
=q
+1; // continue with next line
693 // now move the unprocessed bits (after the final \n that is now a 0x0)
694 // to the start and update d->dpkgbuf_pos
695 p
= (char*)memrchr(d
->dpkgbuf
, 0, d
->dpkgbuf_pos
);
699 // we are interessted in the first char *after* 0x0
702 // move the unprocessed tail to the start and update pos
703 memmove(d
->dpkgbuf
, p
, p
-d
->dpkgbuf
);
704 d
->dpkgbuf_pos
= d
->dpkgbuf
+d
->dpkgbuf_pos
-p
;
707 // DPkgPM::WriteHistoryTag /*{{{*/
708 void pkgDPkgPM::WriteHistoryTag(string
const &tag
, string value
)
710 size_t const length
= value
.length();
713 // poor mans rstrip(", ")
714 if (value
[length
-2] == ',' && value
[length
-1] == ' ')
715 value
.erase(length
- 2, 2);
716 fprintf(d
->history_out
, "%s: %s\n", tag
.c_str(), value
.c_str());
718 // DPkgPM::OpenLog /*{{{*/
719 bool pkgDPkgPM::OpenLog()
721 string
const logdir
= _config
->FindDir("Dir::Log");
722 if(CreateAPTDirectoryIfNeeded(logdir
, logdir
) == false)
723 // FIXME: use a better string after freeze
724 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
728 time_t const t
= time(NULL
);
729 struct tm
const * const tmp
= localtime(&t
);
730 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
733 string
const logfile_name
= flCombine(logdir
,
734 _config
->Find("Dir::Log::Terminal"));
735 if (!logfile_name
.empty())
737 d
->term_out
= fopen(logfile_name
.c_str(),"a");
738 if (d
->term_out
== NULL
)
739 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name
.c_str());
740 setvbuf(d
->term_out
, NULL
, _IONBF
, 0);
741 SetCloseExec(fileno(d
->term_out
), true);
744 pw
= getpwnam("root");
745 gr
= getgrnam("adm");
746 if (pw
!= NULL
&& gr
!= NULL
)
747 chown(logfile_name
.c_str(), pw
->pw_uid
, gr
->gr_gid
);
748 chmod(logfile_name
.c_str(), 0644);
749 fprintf(d
->term_out
, "\nLog started: %s\n", timestr
);
752 // write your history
753 string
const history_name
= flCombine(logdir
,
754 _config
->Find("Dir::Log::History"));
755 if (!history_name
.empty())
757 d
->history_out
= fopen(history_name
.c_str(),"a");
758 if (d
->history_out
== NULL
)
759 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), history_name
.c_str());
760 chmod(history_name
.c_str(), 0644);
761 fprintf(d
->history_out
, "\nStart-Date: %s\n", timestr
);
762 string remove
, purge
, install
, reinstall
, upgrade
, downgrade
;
763 for (pkgCache::PkgIterator I
= Cache
.PkgBegin(); I
.end() == false; ++I
)
765 enum { CANDIDATE
, CANDIDATE_AUTO
, CURRENT_CANDIDATE
, CURRENT
} infostring
;
767 #define HISTORYINFO(X, Y) { line = &X; infostring = Y; }
768 if (Cache
[I
].NewInstall() == true)
769 HISTORYINFO(install
, CANDIDATE_AUTO
)
770 else if (Cache
[I
].ReInstall() == true)
771 HISTORYINFO(reinstall
, CANDIDATE
)
772 else if (Cache
[I
].Upgrade() == true)
773 HISTORYINFO(upgrade
, CURRENT_CANDIDATE
)
774 else if (Cache
[I
].Downgrade() == true)
775 HISTORYINFO(downgrade
, CURRENT_CANDIDATE
)
776 else if (Cache
[I
].Delete() == true)
777 HISTORYINFO((Cache
[I
].Purge() ? purge
: remove
), CURRENT
)
781 line
->append(I
.FullName(false)).append(" (");
782 switch (infostring
) {
783 case CANDIDATE
: line
->append(Cache
[I
].CandVersion
); break;
785 line
->append(Cache
[I
].CandVersion
);
786 if ((Cache
[I
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
787 line
->append(", automatic");
789 case CURRENT_CANDIDATE
: line
->append(Cache
[I
].CurVersion
).append(", ").append(Cache
[I
].CandVersion
); break;
790 case CURRENT
: line
->append(Cache
[I
].CurVersion
); break;
794 if (_config
->Exists("Commandline::AsString") == true)
795 WriteHistoryTag("Commandline", _config
->Find("Commandline::AsString"));
796 WriteHistoryTag("Install", install
);
797 WriteHistoryTag("Reinstall", reinstall
);
798 WriteHistoryTag("Upgrade", upgrade
);
799 WriteHistoryTag("Downgrade",downgrade
);
800 WriteHistoryTag("Remove",remove
);
801 WriteHistoryTag("Purge",purge
);
802 fflush(d
->history_out
);
808 // DPkg::CloseLog /*{{{*/
809 bool pkgDPkgPM::CloseLog()
812 time_t t
= time(NULL
);
813 struct tm
*tmp
= localtime(&t
);
814 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
818 fprintf(d
->term_out
, "Log ended: ");
819 fprintf(d
->term_out
, "%s", timestr
);
820 fprintf(d
->term_out
, "\n");
827 if (disappearedPkgs
.empty() == false)
830 for (std::set
<std::string
>::const_iterator d
= disappearedPkgs
.begin();
831 d
!= disappearedPkgs
.end(); ++d
)
833 pkgCache::PkgIterator P
= Cache
.FindPkg(*d
);
834 disappear
.append(*d
);
836 disappear
.append(", ");
838 disappear
.append(" (").append(Cache
[P
].CurVersion
).append("), ");
840 WriteHistoryTag("Disappeared", disappear
);
842 if (d
->dpkg_error
.empty() == false)
843 fprintf(d
->history_out
, "Error: %s\n", d
->dpkg_error
.c_str());
844 fprintf(d
->history_out
, "End-Date: %s\n", timestr
);
845 fclose(d
->history_out
);
847 d
->history_out
= NULL
;
853 // This implements a racy version of pselect for those architectures
854 // that don't have a working implementation.
855 // FIXME: Probably can be removed on Lenny+1
856 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
857 fd_set
*exceptfds
, const struct timespec
*timeout
,
858 const sigset_t
*sigmask
)
864 tv
.tv_sec
= timeout
->tv_sec
;
865 tv
.tv_usec
= timeout
->tv_nsec
/1000;
867 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
868 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
869 sigprocmask(SIG_SETMASK
, &origmask
, 0);
873 // DPkgPM::Go - Run the sequence /*{{{*/
874 // ---------------------------------------------------------------------
875 /* This globs the operations and calls dpkg
877 * If it is called with "OutStatusFd" set to a valid file descriptor
878 * apt will report the install progress over this fd. It maps the
879 * dpkg states a package goes through to human readable (and i10n-able)
880 * names and calculates a percentage for each step.
882 bool pkgDPkgPM::Go(int OutStatusFd
)
884 pkgPackageManager::SigINTStop
= false;
886 // Generate the base argument list for dpkg
887 std::vector
<const char *> Args
;
888 unsigned long StartSize
= 0;
889 string Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
891 string
const dpkgChrootDir
= _config
->FindDir("DPkg::Chroot-Directory", "/");
892 size_t dpkgChrootLen
= dpkgChrootDir
.length();
893 if (dpkgChrootDir
!= "/" && Tmp
.find(dpkgChrootDir
) == 0)
895 if (dpkgChrootDir
[dpkgChrootLen
- 1] == '/')
897 Tmp
= Tmp
.substr(dpkgChrootLen
);
900 Args
.push_back(Tmp
.c_str());
901 StartSize
+= Tmp
.length();
903 // Stick in any custom dpkg options
904 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
908 for (; Opts
!= 0; Opts
= Opts
->Next
)
910 if (Opts
->Value
.empty() == true)
912 Args
.push_back(Opts
->Value
.c_str());
913 StartSize
+= Opts
->Value
.length();
917 size_t const BaseArgs
= Args
.size();
918 // we need to detect if we can qualify packages with the architecture or not
919 Args
.push_back("--assert-multi-arch");
920 Args
.push_back(NULL
);
922 pid_t dpkgAssertMultiArch
= ExecFork();
923 if (dpkgAssertMultiArch
== 0)
925 dpkgChrootDirectory();
926 // redirect everything to the ultimate sink as we only need the exit-status
927 int const nullfd
= open("/dev/null", O_RDONLY
);
928 dup2(nullfd
, STDIN_FILENO
);
929 dup2(nullfd
, STDOUT_FILENO
);
930 dup2(nullfd
, STDERR_FILENO
);
931 execvp(Args
[0], (char**) &Args
[0]);
932 _error
->WarningE("dpkgGo", "Can't detect if dpkg supports multi-arch!");
939 sigset_t original_sigmask
;
941 unsigned int const MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
942 unsigned int const MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
943 bool const NoTriggers
= _config
->FindB("DPkg::NoTriggers", false);
945 if (RunScripts("DPkg::Pre-Invoke") == false)
948 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
951 // support subpressing of triggers processing for special
952 // cases like d-i that runs the triggers handling manually
953 bool const SmartConf
= (_config
->Find("PackageManager::Configure", "all") != "all");
954 bool const TriggersPending
= _config
->FindB("DPkg::TriggersPending", false);
955 if (_config
->FindB("DPkg::ConfigurePending", SmartConf
) == true)
956 List
.push_back(Item(Item::ConfigurePending
, PkgIterator()));
958 // map the dpkg states to the operations that are performed
959 // (this is sorted in the same way as Item::Ops)
960 static const struct DpkgState DpkgStatesOpMap
[][7] = {
963 {"half-installed", N_("Preparing %s")},
964 {"unpacked", N_("Unpacking %s") },
967 // Configure operation
969 {"unpacked",N_("Preparing to configure %s") },
970 {"half-configured", N_("Configuring %s") },
971 { "installed", N_("Installed %s")},
976 {"half-configured", N_("Preparing for removal of %s")},
977 {"half-installed", N_("Removing %s")},
978 {"config-files", N_("Removed %s")},
983 {"config-files", N_("Preparing to completely remove %s")},
984 {"not-installed", N_("Completely removed %s")},
989 // init the PackageOps map, go over the list of packages that
990 // that will be [installed|configured|removed|purged] and add
991 // them to the PackageOps map (the dpkg states it goes through)
992 // and the PackageOpsTranslations (human readable strings)
993 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end(); ++I
)
995 if((*I
).Pkg
.end() == true)
998 string
const name
= (*I
).Pkg
.Name();
999 PackageOpsDone
[name
] = 0;
1000 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; ++i
)
1002 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
1007 d
->stdin_is_dev_null
= false;
1012 bool dpkgMultiArch
= false;
1013 if (dpkgAssertMultiArch
> 0)
1016 while (waitpid(dpkgAssertMultiArch
, &Status
, 0) != dpkgAssertMultiArch
)
1020 _error
->WarningE("dpkgGo", _("Waited for %s but it wasn't there"), "dpkg --assert-multi-arch");
1023 if (WIFEXITED(Status
) == true && WEXITSTATUS(Status
) == 0)
1024 dpkgMultiArch
= true;
1027 // this loop is runs once per operation
1028 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();)
1030 // Do all actions with the same Op in one run
1031 vector
<Item
>::const_iterator J
= I
;
1032 if (TriggersPending
== true)
1033 for (; J
!= List
.end(); ++J
)
1037 if (J
->Op
!= Item::TriggersPending
)
1039 vector
<Item
>::const_iterator T
= J
+ 1;
1040 if (T
!= List
.end() && T
->Op
== I
->Op
)
1045 for (; J
!= List
.end() && J
->Op
== I
->Op
; ++J
)
1048 // keep track of allocated strings for multiarch package names
1049 std::vector
<char *> Packages
;
1051 // start with the baseset of arguments
1052 unsigned long Size
= StartSize
;
1053 Args
.erase(Args
.begin() + BaseArgs
, Args
.end());
1055 // Now check if we are within the MaxArgs limit
1057 // this code below is problematic, because it may happen that
1058 // the argument list is split in a way that A depends on B
1059 // and they are in the same "--configure A B" run
1060 // - with the split they may now be configured in different
1061 // runs, using Immediate-Configure-All can help prevent this.
1062 if (J
- I
> (signed)MaxArgs
)
1065 unsigned long const size
= MaxArgs
+ 10;
1067 Packages
.reserve(size
);
1071 unsigned long const size
= (J
- I
) + 10;
1073 Packages
.reserve(size
);
1078 return _error
->Errno("pipe","Failed to create IPC pipe to dpkg");
1080 #define ADDARG(X) Args.push_back(X); Size += strlen(X)
1081 #define ADDARGC(X) Args.push_back(X); Size += sizeof(X) - 1
1083 ADDARGC("--status-fd");
1084 char status_fd_buf
[20];
1085 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
1086 ADDARG(status_fd_buf
);
1087 unsigned long const Op
= I
->Op
;
1092 ADDARGC("--force-depends");
1093 ADDARGC("--force-remove-essential");
1094 ADDARGC("--remove");
1098 ADDARGC("--force-depends");
1099 ADDARGC("--force-remove-essential");
1103 case Item::Configure
:
1104 ADDARGC("--configure");
1107 case Item::ConfigurePending
:
1108 ADDARGC("--configure");
1109 ADDARGC("--pending");
1112 case Item::TriggersPending
:
1113 ADDARGC("--triggers-only");
1114 ADDARGC("--pending");
1118 ADDARGC("--unpack");
1119 ADDARGC("--auto-deconfigure");
1123 if (NoTriggers
== true && I
->Op
!= Item::TriggersPending
&&
1124 I
->Op
!= Item::ConfigurePending
)
1126 ADDARGC("--no-triggers");
1130 // Write in the file or package names
1131 if (I
->Op
== Item::Install
)
1133 for (;I
!= J
&& Size
< MaxArgBytes
; ++I
)
1135 if (I
->File
[0] != '/')
1136 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
1137 Args
.push_back(I
->File
.c_str());
1138 Size
+= I
->File
.length();
1143 string
const nativeArch
= _config
->Find("APT::Architecture");
1144 unsigned long const oldSize
= I
->Op
== Item::Configure
? Size
: 0;
1145 for (;I
!= J
&& Size
< MaxArgBytes
; ++I
)
1147 if((*I
).Pkg
.end() == true)
1149 if (I
->Op
== Item::Configure
&& disappearedPkgs
.find(I
->Pkg
.Name()) != disappearedPkgs
.end())
1151 // We keep this here to allow "smooth" transitions from e.g. multiarch dpkg/ubuntu to dpkg/debian
1152 if (dpkgMultiArch
== false && (I
->Pkg
.Arch() == nativeArch
|| !strcmp(I
->Pkg
.Arch(), "all")))
1154 char const * const name
= I
->Pkg
.Name();
1159 pkgCache::VerIterator PkgVer
;
1160 std::string name
= I
->Pkg
.Name();
1161 if (Op
== Item::Remove
|| Op
== Item::Purge
)
1163 PkgVer
= I
->Pkg
.CurrentVer();
1164 if(PkgVer
.end() == true)
1165 PkgVer
= FindNowVersion(I
->Pkg
);
1168 PkgVer
= Cache
[I
->Pkg
].InstVerIter(Cache
);
1169 if (PkgVer
.end() == false)
1170 name
.append(":").append(PkgVer
.Arch());
1172 _error
->Warning("Can not find PkgVer for '%s'", name
.c_str());
1173 char * const fullname
= strdup(name
.c_str());
1174 Packages
.push_back(fullname
);
1178 // skip configure action if all sheduled packages disappeared
1179 if (oldSize
== Size
)
1186 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
1188 for (std::vector
<const char *>::const_iterator a
= Args
.begin();
1189 a
!= Args
.end(); ++a
)
1194 Args
.push_back(NULL
);
1200 /* Mask off sig int/quit. We do this because dpkg also does when
1201 it forks scripts. What happens is that when you hit ctrl-c it sends
1202 it to all processes in the group. Since dpkg ignores the signal
1203 it doesn't die but we do! So we must also ignore it */
1204 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
1205 sighandler_t old_SIGINT
= signal(SIGINT
,SigINT
);
1207 // Check here for any SIGINT
1208 if (pkgPackageManager::SigINTStop
&& (Op
== Item::Remove
|| Op
== Item::Purge
|| Op
== Item::Install
))
1212 // ignore SIGHUP as well (debian #463030)
1213 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
1220 // if tcgetattr does not return zero there was a error
1221 // and we do not do any pty magic
1222 if (tcgetattr(0, &tt
) == 0)
1224 ioctl(0, TIOCGWINSZ
, (char *)&win
);
1225 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
1227 const char *s
= _("Can not write log, openpty() "
1228 "failed (/dev/pts not mounted?)\n");
1229 fprintf(stderr
, "%s",s
);
1231 fprintf(d
->term_out
, "%s",s
);
1232 master
= slave
= -1;
1237 rtt
.c_lflag
&= ~ECHO
;
1238 rtt
.c_lflag
|= ISIG
;
1239 // block SIGTTOU during tcsetattr to prevent a hang if
1240 // the process is a member of the background process group
1241 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
1242 sigemptyset(&sigmask
);
1243 sigaddset(&sigmask
, SIGTTOU
);
1244 sigprocmask(SIG_BLOCK
,&sigmask
, &original_sigmask
);
1245 tcsetattr(0, TCSAFLUSH
, &rtt
);
1246 sigprocmask(SIG_SETMASK
, &original_sigmask
, 0);
1251 _config
->Set("APT::Keep-Fds::",fd
[1]);
1252 // send status information that we are about to fork dpkg
1253 if(OutStatusFd
> 0) {
1254 ostringstream status
;
1255 status
<< "pmstatus:dpkg-exec:"
1256 << (PackagesDone
/float(PackagesTotal
)*100.0)
1257 << ":" << _("Running dpkg")
1259 retry_write(OutStatusFd
, status
.str().c_str(), status
.str().size());
1263 // This is the child
1266 if(slave
>= 0 && master
>= 0)
1269 ioctl(slave
, TIOCSCTTY
, 0);
1276 close(fd
[0]); // close the read end of the pipe
1278 dpkgChrootDirectory();
1280 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
1283 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
1286 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
1289 // Discard everything in stdin before forking dpkg
1290 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
1293 while (read(STDIN_FILENO
,&dummy
,1) == 1);
1295 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
1299 /* No Job Control Stop Env is a magic dpkg var that prevents it
1300 from using sigstop */
1301 putenv((char *)"DPKG_NO_TSTP=yes");
1302 execvp(Args
[0], (char**) &Args
[0]);
1303 cerr
<< "Could not exec dpkg!" << endl
;
1308 if (_config
->FindB("DPkg::UseIoNice", false) == true)
1311 // clear the Keep-Fd again
1312 _config
->Clear("APT::Keep-Fds",fd
[1]);
1317 // we read from dpkg here
1318 int const _dpkgin
= fd
[0];
1319 close(fd
[1]); // close the write end of the pipe
1325 sigemptyset(&sigmask
);
1326 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
1328 /* free vectors (and therefore memory) as we don't need the included data anymore */
1329 for (std::vector
<char *>::const_iterator p
= Packages
.begin();
1330 p
!= Packages
.end(); ++p
)
1334 // the result of the waitpid call
1337 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
1339 // FIXME: move this to a function or something, looks ugly here
1340 // error handling, waitpid returned -1
1343 RunScripts("DPkg::Post-Invoke");
1345 // Restore sig int/quit
1346 signal(SIGQUIT
,old_SIGQUIT
);
1347 signal(SIGINT
,old_SIGINT
);
1349 signal(SIGHUP
,old_SIGHUP
);
1350 return _error
->Errno("waitpid","Couldn't wait for subprocess");
1353 // wait for input or output here
1355 if (master
>= 0 && !d
->stdin_is_dev_null
)
1357 FD_SET(_dpkgin
, &rfds
);
1359 FD_SET(master
, &rfds
);
1362 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
1363 &tv
, &original_sigmask
);
1364 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
1365 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
1366 NULL
, &tv
, &original_sigmask
);
1367 if (select_ret
== 0)
1369 else if (select_ret
< 0 && errno
== EINTR
)
1371 else if (select_ret
< 0)
1373 perror("select() returned error");
1377 if(master
>= 0 && FD_ISSET(master
, &rfds
))
1378 DoTerminalPty(master
);
1379 if(master
>= 0 && FD_ISSET(0, &rfds
))
1381 if(FD_ISSET(_dpkgin
, &rfds
))
1382 DoDpkgStatusFd(_dpkgin
, OutStatusFd
);
1386 // Restore sig int/quit
1387 signal(SIGQUIT
,old_SIGQUIT
);
1388 signal(SIGINT
,old_SIGINT
);
1390 signal(SIGHUP
,old_SIGHUP
);
1394 tcsetattr(0, TCSAFLUSH
, &tt
);
1398 // Check for an error code.
1399 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
1401 // if it was set to "keep-dpkg-runing" then we won't return
1402 // here but keep the loop going and just report it as a error
1404 bool const stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
1407 RunScripts("DPkg::Post-Invoke");
1409 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
1410 strprintf(d
->dpkg_error
, "Sub-process %s received a segmentation fault.",Args
[0]);
1411 else if (WIFEXITED(Status
) != 0)
1412 strprintf(d
->dpkg_error
, "Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
1414 strprintf(d
->dpkg_error
, "Sub-process %s exited unexpectedly",Args
[0]);
1416 if(d
->dpkg_error
.size() > 0)
1417 _error
->Error("%s", d
->dpkg_error
.c_str());
1428 if (pkgPackageManager::SigINTStop
)
1429 _error
->Warning(_("Operation was interrupted before it could finish"));
1431 if (RunScripts("DPkg::Post-Invoke") == false)
1434 if (_config
->FindB("Debug::pkgDPkgPM",false) == false)
1436 std::string
const oldpkgcache
= _config
->FindFile("Dir::cache::pkgcache");
1437 if (oldpkgcache
.empty() == false && RealFileExists(oldpkgcache
) == true &&
1438 unlink(oldpkgcache
.c_str()) == 0)
1440 std::string
const srcpkgcache
= _config
->FindFile("Dir::cache::srcpkgcache");
1441 if (srcpkgcache
.empty() == false && RealFileExists(srcpkgcache
) == true)
1443 _error
->PushToStack();
1444 pkgCacheFile CacheFile
;
1445 CacheFile
.BuildCaches(NULL
, true);
1446 _error
->RevertToStack();
1451 Cache
.writeStateFile(NULL
);
1455 void SigINT(int sig
) {
1456 pkgPackageManager::SigINTStop
= true;
1459 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1460 // ---------------------------------------------------------------------
1462 void pkgDPkgPM::Reset()
1464 List
.erase(List
.begin(),List
.end());
1467 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1468 // ---------------------------------------------------------------------
1470 void pkgDPkgPM::WriteApportReport(const char *pkgpath
, const char *errormsg
)
1472 // If apport doesn't exist or isn't installed do nothing
1473 // This e.g. prevents messages in 'universes' without apport
1474 pkgCache::PkgIterator apportPkg
= Cache
.FindPkg("apport");
1475 if (apportPkg
.end() == true || apportPkg
->CurrentVer
== 0)
1478 string pkgname
, reportfile
, srcpkgname
, pkgver
, arch
;
1479 string::size_type pos
;
1482 if (_config
->FindB("Dpkg::ApportFailureReport", false) == false)
1484 std::clog
<< "configured to not write apport reports" << std::endl
;
1488 // only report the first errors
1489 if(pkgFailures
> _config
->FindI("APT::Apport::MaxReports", 3))
1491 std::clog
<< _("No apport report written because MaxReports is reached already") << std::endl
;
1495 // check if its not a follow up error
1496 const char *needle
= dgettext("dpkg", "dependency problems - leaving unconfigured");
1497 if(strstr(errormsg
, needle
) != NULL
) {
1498 std::clog
<< _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl
;
1502 // do not report disk-full failures
1503 if(strstr(errormsg
, strerror(ENOSPC
)) != NULL
) {
1504 std::clog
<< _("No apport report written because the error message indicates a disk full error") << std::endl
;
1508 // do not report out-of-memory failures
1509 if(strstr(errormsg
, strerror(ENOMEM
)) != NULL
) {
1510 std::clog
<< _("No apport report written because the error message indicates a out of memory error") << std::endl
;
1514 // do not report dpkg I/O errors
1515 // XXX - this message is localized, but this only matches the English version. This is better than nothing.
1516 if(strstr(errormsg
, "short read in buffer_copy (")) {
1517 std::clog
<< _("No apport report written because the error message indicates a dpkg I/O error") << std::endl
;
1521 // get the pkgname and reportfile
1522 pkgname
= flNotDir(pkgpath
);
1523 pos
= pkgname
.find('_');
1524 if(pos
!= string::npos
)
1525 pkgname
= pkgname
.substr(0, pos
);
1527 // find the package versin and source package name
1528 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
1529 if (Pkg
.end() == true)
1531 pkgCache::VerIterator Ver
= Cache
.GetCandidateVer(Pkg
);
1532 if (Ver
.end() == true)
1534 pkgver
= Ver
.VerStr() == NULL
? "unknown" : Ver
.VerStr();
1535 pkgRecords
Recs(Cache
);
1536 pkgRecords::Parser
&Parse
= Recs
.Lookup(Ver
.FileList());
1537 srcpkgname
= Parse
.SourcePkg();
1538 if(srcpkgname
.empty())
1539 srcpkgname
= pkgname
;
1541 // if the file exists already, we check:
1542 // - if it was reported already (touched by apport).
1543 // If not, we do nothing, otherwise
1544 // we overwrite it. This is the same behaviour as apport
1545 // - if we have a report with the same pkgversion already
1547 reportfile
= flCombine("/var/crash",pkgname
+".0.crash");
1548 if(FileExists(reportfile
))
1553 // check atime/mtime
1554 stat(reportfile
.c_str(), &buf
);
1555 if(buf
.st_mtime
> buf
.st_atime
)
1558 // check if the existing report is the same version
1559 report
= fopen(reportfile
.c_str(),"r");
1560 while(fgets(strbuf
, sizeof(strbuf
), report
) != NULL
)
1562 if(strstr(strbuf
,"Package:") == strbuf
)
1564 char pkgname
[255], version
[255];
1565 if(sscanf(strbuf
, "Package: %254s %254s", pkgname
, version
) == 2)
1566 if(strcmp(pkgver
.c_str(), version
) == 0)
1576 // now write the report
1577 arch
= _config
->Find("APT::Architecture");
1578 report
= fopen(reportfile
.c_str(),"w");
1581 if(_config
->FindB("DPkgPM::InitialReportOnly",false) == true)
1582 chmod(reportfile
.c_str(), 0);
1584 chmod(reportfile
.c_str(), 0600);
1585 fprintf(report
, "ProblemType: Package\n");
1586 fprintf(report
, "Architecture: %s\n", arch
.c_str());
1587 time_t now
= time(NULL
);
1588 fprintf(report
, "Date: %s" , ctime(&now
));
1589 fprintf(report
, "Package: %s %s\n", pkgname
.c_str(), pkgver
.c_str());
1590 fprintf(report
, "SourcePackage: %s\n", srcpkgname
.c_str());
1591 fprintf(report
, "ErrorMessage:\n %s\n", errormsg
);
1593 // ensure that the log is flushed
1595 fflush(d
->term_out
);
1597 // attach terminal log it if we have it
1598 string logfile_name
= _config
->FindFile("Dir::Log::Terminal");
1599 if (!logfile_name
.empty())
1604 fprintf(report
, "DpkgTerminalLog:\n");
1605 log
= fopen(logfile_name
.c_str(),"r");
1608 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1609 fprintf(report
, " %s", buf
);
1615 const char *ops_str
[] = {"Install", "Configure","Remove","Purge"};
1616 fprintf(report
, "AptOrdering:\n");
1617 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
1618 fprintf(report
, " %s: %s\n", (*I
).Pkg
.Name(), ops_str
[(*I
).Op
]);
1620 // attach dmesg log (to learn about segfaults)
1621 if (FileExists("/bin/dmesg"))
1626 fprintf(report
, "Dmesg:\n");
1627 log
= popen("/bin/dmesg","r");
1630 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1631 fprintf(report
, " %s", buf
);
1636 // attach df -l log (to learn about filesystem status)
1637 if (FileExists("/bin/df"))
1642 fprintf(report
, "Df:\n");
1643 log
= popen("/bin/df -l","r");
1646 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1647 fprintf(report
, " %s", buf
);