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 retry_write(int fd
, const void *buf
, size_t count
)
174 Res
= write(fd
, buf
, count
);
175 if (Res
< 0 && errno
== EINTR
)
179 buf
= (char *)buf
+ Res
;
183 while (Res
> 0 && count
> 0);
187 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
188 // ---------------------------------------------------------------------
190 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
191 : pkgPackageManager(Cache
), PackagesDone(0), PackagesTotal(0)
193 d
= new pkgDPkgPMPrivate();
196 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
197 // ---------------------------------------------------------------------
199 pkgDPkgPM::~pkgDPkgPM()
204 // DPkgPM::Install - Install a package /*{{{*/
205 // ---------------------------------------------------------------------
206 /* Add an install operation to the sequence list */
207 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
209 if (File
.empty() == true || Pkg
.end() == true)
210 return _error
->Error("Internal Error, No file name for %s",Pkg
.Name());
212 // If the filename string begins with DPkg::Chroot-Directory, return the
213 // substr that is within the chroot so dpkg can access it.
214 string
const chrootdir
= _config
->FindDir("DPkg::Chroot-Directory","/");
215 if (chrootdir
!= "/" && File
.find(chrootdir
) == 0)
217 size_t len
= chrootdir
.length();
218 if (chrootdir
.at(len
- 1) == '/')
220 List
.push_back(Item(Item::Install
,Pkg
,File
.substr(len
)));
223 List
.push_back(Item(Item::Install
,Pkg
,File
));
228 // DPkgPM::Configure - Configure a package /*{{{*/
229 // ---------------------------------------------------------------------
230 /* Add a configure operation to the sequence list */
231 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
233 if (Pkg
.end() == true)
236 List
.push_back(Item(Item::Configure
, Pkg
));
238 // Use triggers for config calls if we configure "smart"
239 // as otherwise Pre-Depends will not be satisfied, see #526774
240 if (_config
->FindB("DPkg::TriggersPending", false) == true)
241 List
.push_back(Item(Item::TriggersPending
, PkgIterator()));
246 // DPkgPM::Remove - Remove a package /*{{{*/
247 // ---------------------------------------------------------------------
248 /* Add a remove operation to the sequence list */
249 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
251 if (Pkg
.end() == true)
255 List
.push_back(Item(Item::Purge
,Pkg
));
257 List
.push_back(Item(Item::Remove
,Pkg
));
261 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
262 // ---------------------------------------------------------------------
263 /* This is part of the helper script communication interface, it sends
264 very complete information down to the other end of the pipe.*/
265 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
267 fprintf(F
,"VERSION 2\n");
269 /* Write out all of the configuration directives by walking the
270 configuration tree */
271 const Configuration::Item
*Top
= _config
->Tree(0);
274 if (Top
->Value
.empty() == false)
277 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
278 QuoteString(Top
->Value
,"\n").c_str());
287 while (Top
!= 0 && Top
->Next
== 0)
294 // Write out the package actions in order.
295 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
297 if(I
->Pkg
.end() == true)
300 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
302 fprintf(F
,"%s ",I
->Pkg
.Name());
304 if (I
->Pkg
->CurrentVer
== 0)
307 fprintf(F
,"%s ",I
->Pkg
.CurrentVer().VerStr());
309 // Show the compare operator
311 if (S
.InstallVer
!= 0)
314 if (I
->Pkg
->CurrentVer
!= 0)
315 Comp
= S
.InstVerIter(Cache
).CompareVer(I
->Pkg
.CurrentVer());
322 fprintf(F
,"%s ",S
.InstVerIter(Cache
).VerStr());
327 // Show the filename/operation
328 if (I
->Op
== Item::Install
)
331 if (I
->File
[0] != '/')
332 fprintf(F
,"**ERROR**\n");
334 fprintf(F
,"%s\n",I
->File
.c_str());
336 if (I
->Op
== Item::Configure
)
337 fprintf(F
,"**CONFIGURE**\n");
338 if (I
->Op
== Item::Remove
||
339 I
->Op
== Item::Purge
)
340 fprintf(F
,"**REMOVE**\n");
348 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
349 // ---------------------------------------------------------------------
350 /* This looks for a list of scripts to run from the configuration file
351 each one is run and is fed on standard input a list of all .deb files
352 that are due to be installed. */
353 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
355 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
356 if (Opts
== 0 || Opts
->Child
== 0)
360 unsigned int Count
= 1;
361 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
363 if (Opts
->Value
.empty() == true)
366 // Determine the protocol version
367 string OptSec
= Opts
->Value
;
368 string::size_type Pos
;
369 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
370 Pos
= OptSec
.length();
371 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
373 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
377 if (pipe(Pipes
) != 0)
378 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
379 SetCloseExec(Pipes
[0],true);
380 SetCloseExec(Pipes
[1],true);
382 // Purified Fork for running the script
383 pid_t Process
= ExecFork();
387 dup2(Pipes
[0],STDIN_FILENO
);
388 SetCloseExec(STDOUT_FILENO
,false);
389 SetCloseExec(STDIN_FILENO
,false);
390 SetCloseExec(STDERR_FILENO
,false);
392 dpkgChrootDirectory();
396 Args
[2] = Opts
->Value
.c_str();
398 execv(Args
[0],(char **)Args
);
402 FILE *F
= fdopen(Pipes
[1],"w");
404 return _error
->Errno("fdopen","Faild to open new FD");
406 // Feed it the filenames.
409 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
411 // Only deal with packages to be installed from .deb
412 if (I
->Op
!= Item::Install
)
416 if (I
->File
[0] != '/')
419 /* Feed the filename of each package that is pending install
421 fprintf(F
,"%s\n",I
->File
.c_str());
431 // Clean up the sub process
432 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
433 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
439 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
440 // ---------------------------------------------------------------------
443 void pkgDPkgPM::DoStdin(int master
)
445 unsigned char input_buf
[256] = {0,};
446 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
448 retry_write(master
, input_buf
, len
);
450 d
->stdin_is_dev_null
= true;
453 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
454 // ---------------------------------------------------------------------
456 * read the terminal pty and write log
458 void pkgDPkgPM::DoTerminalPty(int master
)
460 unsigned char term_buf
[1024] = {0,0, };
462 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
463 if(len
== -1 && errno
== EIO
)
465 // this happens when the child is about to exit, we
466 // give it time to actually exit, otherwise we run
467 // into a race so we sleep for half a second.
468 struct timespec sleepfor
= { 0, 500000000 };
469 nanosleep(&sleepfor
, NULL
);
474 retry_write(1, term_buf
, len
);
476 fwrite(term_buf
, len
, sizeof(char), d
->term_out
);
479 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
480 // ---------------------------------------------------------------------
483 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd
, char *line
)
485 bool const Debug
= _config
->FindB("Debug::pkgDPkgProgressReporting",false);
486 // the status we output
487 ostringstream status
;
490 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
493 /* dpkg sends strings like this:
494 'status: <pkg>: <pkg qstate>'
495 errors look like this:
496 '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
497 and conffile-prompt like this
498 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
500 Newer versions of dpkg sent also:
501 'processing: install: pkg'
502 'processing: configure: pkg'
503 'processing: remove: pkg'
504 'processing: purge: pkg'
505 'processing: disappear: pkg'
506 'processing: trigproc: trigger'
510 // dpkg sends multiline error messages sometimes (see
511 // #374195 for a example. we should support this by
512 // either patching dpkg to not send multiline over the
513 // statusfd or by rewriting the code here to deal with
514 // it. for now we just ignore it and not crash
515 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
516 if( list
[0] == NULL
|| list
[1] == NULL
|| list
[2] == NULL
)
519 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
522 const char* const pkg
= list
[1];
523 const char* action
= _strstrip(list
[2]);
525 // 'processing' from dpkg looks like
526 // 'processing: action: pkg'
527 if(strncmp(list
[0], "processing", strlen("processing")) == 0)
530 const char* const pkg_or_trigger
= _strstrip(list
[2]);
531 action
= _strstrip( list
[1]);
532 const std::pair
<const char *, const char *> * const iter
=
533 std::find_if(PackageProcessingOpsBegin
,
534 PackageProcessingOpsEnd
,
535 MatchProcessingOp(action
));
536 if(iter
== PackageProcessingOpsEnd
)
539 std::clog
<< "ignoring unknown action: " << action
<< std::endl
;
542 snprintf(s
, sizeof(s
), _(iter
->second
), pkg_or_trigger
);
544 status
<< "pmstatus:" << pkg_or_trigger
545 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
549 retry_write(OutStatusFd
, status
.str().c_str(), status
.str().size());
551 std::clog
<< "send: '" << status
.str() << "'" << endl
;
553 if (strncmp(action
, "disappear", strlen("disappear")) == 0)
554 handleDisappearAction(pkg_or_trigger
);
558 if(strncmp(action
,"error",strlen("error")) == 0)
560 // urgs, sometime has ":" in its error string so that we
561 // end up with the error message split between list[3]
562 // and list[4], e.g. the message:
563 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
565 if( list
[4] != NULL
)
566 list
[3][strlen(list
[3])] = ':';
568 status
<< "pmerror:" << list
[1]
569 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
573 retry_write(OutStatusFd
, status
.str().c_str(), status
.str().size());
575 std::clog
<< "send: '" << status
.str() << "'" << endl
;
577 WriteApportReport(list
[1], list
[3]);
580 else if(strncmp(action
,"conffile",strlen("conffile")) == 0)
582 status
<< "pmconffile:" << list
[1]
583 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
587 retry_write(OutStatusFd
, status
.str().c_str(), status
.str().size());
589 std::clog
<< "send: '" << status
.str() << "'" << endl
;
593 vector
<struct DpkgState
> const &states
= PackageOps
[pkg
];
594 const char *next_action
= NULL
;
595 if(PackageOpsDone
[pkg
] < states
.size())
596 next_action
= states
[PackageOpsDone
[pkg
]].state
;
597 // check if the package moved to the next dpkg state
598 if(next_action
&& (strcmp(action
, next_action
) == 0))
600 // only read the translation if there is actually a next
602 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
604 snprintf(s
, sizeof(s
), translation
, pkg
);
606 // we moved from one dpkg state to a new one, report that
607 PackageOpsDone
[pkg
]++;
609 // build the status str
610 status
<< "pmstatus:" << pkg
611 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
615 retry_write(OutStatusFd
, status
.str().c_str(), status
.str().size());
617 std::clog
<< "send: '" << status
.str() << "'" << endl
;
620 std::clog
<< "(parsed from dpkg) pkg: " << pkg
621 << " action: " << action
<< endl
;
624 // DPkgPM::handleDisappearAction /*{{{*/
625 void pkgDPkgPM::handleDisappearAction(string
const &pkgname
)
627 // record the package name for display and stuff later
628 disappearedPkgs
.insert(pkgname
);
630 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
631 if (unlikely(Pkg
.end() == true))
633 // the disappeared package was auto-installed - nothing to do
634 if ((Cache
[Pkg
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
636 pkgCache::VerIterator PkgVer
= Cache
[Pkg
].InstVerIter(Cache
);
637 if (unlikely(PkgVer
.end() == true))
639 /* search in the list of dependencies for (Pre)Depends,
640 check if this dependency has a Replaces on our package
641 and if so transfer the manual installed flag to it */
642 for (pkgCache::DepIterator Dep
= PkgVer
.DependsList(); Dep
.end() != true; ++Dep
)
644 if (Dep
->Type
!= pkgCache::Dep::Depends
&&
645 Dep
->Type
!= pkgCache::Dep::PreDepends
)
647 pkgCache::PkgIterator Tar
= Dep
.TargetPkg();
648 if (unlikely(Tar
.end() == true))
650 // the package is already marked as manual
651 if ((Cache
[Tar
].Flags
& pkgCache::Flag::Auto
) != pkgCache::Flag::Auto
)
653 pkgCache::VerIterator TarVer
= Cache
[Tar
].InstVerIter(Cache
);
654 if (TarVer
.end() == true)
656 for (pkgCache::DepIterator Rep
= TarVer
.DependsList(); Rep
.end() != true; ++Rep
)
658 if (Rep
->Type
!= pkgCache::Dep::Replaces
)
660 if (Pkg
!= Rep
.TargetPkg())
662 // okay, they are strongly connected - transfer manual-bit
664 std::clog
<< "transfer manual-bit from disappeared »" << pkgname
<< "« to »" << Tar
.FullName() << "«" << std::endl
;
665 Cache
[Tar
].Flags
&= ~Flag::Auto
;
671 // DPkgPM::DoDpkgStatusFd /*{{{*/
672 // ---------------------------------------------------------------------
675 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
, int OutStatusFd
)
680 len
=read(statusfd
, &d
->dpkgbuf
[d
->dpkgbuf_pos
], sizeof(d
->dpkgbuf
)-d
->dpkgbuf_pos
);
681 d
->dpkgbuf_pos
+= len
;
685 // process line by line if we have a buffer
687 while((q
=(char*)memchr(p
, '\n', d
->dpkgbuf
+d
->dpkgbuf_pos
-p
)) != NULL
)
690 ProcessDpkgStatusLine(OutStatusFd
, p
);
691 p
=q
+1; // continue with next line
694 // now move the unprocessed bits (after the final \n that is now a 0x0)
695 // to the start and update d->dpkgbuf_pos
696 p
= (char*)memrchr(d
->dpkgbuf
, 0, d
->dpkgbuf_pos
);
700 // we are interessted in the first char *after* 0x0
703 // move the unprocessed tail to the start and update pos
704 memmove(d
->dpkgbuf
, p
, p
-d
->dpkgbuf
);
705 d
->dpkgbuf_pos
= d
->dpkgbuf
+d
->dpkgbuf_pos
-p
;
708 // DPkgPM::WriteHistoryTag /*{{{*/
709 void pkgDPkgPM::WriteHistoryTag(string
const &tag
, string value
)
711 size_t const length
= value
.length();
714 // poor mans rstrip(", ")
715 if (value
[length
-2] == ',' && value
[length
-1] == ' ')
716 value
.erase(length
- 2, 2);
717 fprintf(d
->history_out
, "%s: %s\n", tag
.c_str(), value
.c_str());
719 // DPkgPM::OpenLog /*{{{*/
720 bool pkgDPkgPM::OpenLog()
722 string
const logdir
= _config
->FindDir("Dir::Log");
723 if(CreateAPTDirectoryIfNeeded(logdir
, logdir
) == false)
724 // FIXME: use a better string after freeze
725 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
729 time_t const t
= time(NULL
);
730 struct tm
const * const tmp
= localtime(&t
);
731 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
734 string
const logfile_name
= flCombine(logdir
,
735 _config
->Find("Dir::Log::Terminal"));
736 if (!logfile_name
.empty())
738 d
->term_out
= fopen(logfile_name
.c_str(),"a");
739 if (d
->term_out
== NULL
)
740 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name
.c_str());
741 setvbuf(d
->term_out
, NULL
, _IONBF
, 0);
742 SetCloseExec(fileno(d
->term_out
), true);
745 pw
= getpwnam("root");
746 gr
= getgrnam("adm");
747 if (pw
!= NULL
&& gr
!= NULL
)
748 chown(logfile_name
.c_str(), pw
->pw_uid
, gr
->gr_gid
);
749 chmod(logfile_name
.c_str(), 0644);
750 fprintf(d
->term_out
, "\nLog started: %s\n", timestr
);
753 // write your history
754 string
const history_name
= flCombine(logdir
,
755 _config
->Find("Dir::Log::History"));
756 if (!history_name
.empty())
758 d
->history_out
= fopen(history_name
.c_str(),"a");
759 if (d
->history_out
== NULL
)
760 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), history_name
.c_str());
761 chmod(history_name
.c_str(), 0644);
762 fprintf(d
->history_out
, "\nStart-Date: %s\n", timestr
);
763 string remove
, purge
, install
, reinstall
, upgrade
, downgrade
;
764 for (pkgCache::PkgIterator I
= Cache
.PkgBegin(); I
.end() == false; ++I
)
766 enum { CANDIDATE
, CANDIDATE_AUTO
, CURRENT_CANDIDATE
, CURRENT
} infostring
;
768 #define HISTORYINFO(X, Y) { line = &X; infostring = Y; }
769 if (Cache
[I
].NewInstall() == true)
770 HISTORYINFO(install
, CANDIDATE_AUTO
)
771 else if (Cache
[I
].ReInstall() == true)
772 HISTORYINFO(reinstall
, CANDIDATE
)
773 else if (Cache
[I
].Upgrade() == true)
774 HISTORYINFO(upgrade
, CURRENT_CANDIDATE
)
775 else if (Cache
[I
].Downgrade() == true)
776 HISTORYINFO(downgrade
, CURRENT_CANDIDATE
)
777 else if (Cache
[I
].Delete() == true)
778 HISTORYINFO((Cache
[I
].Purge() ? purge
: remove
), CURRENT
)
782 line
->append(I
.FullName(false)).append(" (");
783 switch (infostring
) {
784 case CANDIDATE
: line
->append(Cache
[I
].CandVersion
); break;
786 line
->append(Cache
[I
].CandVersion
);
787 if ((Cache
[I
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
788 line
->append(", automatic");
790 case CURRENT_CANDIDATE
: line
->append(Cache
[I
].CurVersion
).append(", ").append(Cache
[I
].CandVersion
); break;
791 case CURRENT
: line
->append(Cache
[I
].CurVersion
); break;
795 if (_config
->Exists("Commandline::AsString") == true)
796 WriteHistoryTag("Commandline", _config
->Find("Commandline::AsString"));
797 WriteHistoryTag("Install", install
);
798 WriteHistoryTag("Reinstall", reinstall
);
799 WriteHistoryTag("Upgrade", upgrade
);
800 WriteHistoryTag("Downgrade",downgrade
);
801 WriteHistoryTag("Remove",remove
);
802 WriteHistoryTag("Purge",purge
);
803 fflush(d
->history_out
);
809 // DPkg::CloseLog /*{{{*/
810 bool pkgDPkgPM::CloseLog()
813 time_t t
= time(NULL
);
814 struct tm
*tmp
= localtime(&t
);
815 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
819 fprintf(d
->term_out
, "Log ended: ");
820 fprintf(d
->term_out
, "%s", timestr
);
821 fprintf(d
->term_out
, "\n");
828 if (disappearedPkgs
.empty() == false)
831 for (std::set
<std::string
>::const_iterator d
= disappearedPkgs
.begin();
832 d
!= disappearedPkgs
.end(); ++d
)
834 pkgCache::PkgIterator P
= Cache
.FindPkg(*d
);
835 disappear
.append(*d
);
837 disappear
.append(", ");
839 disappear
.append(" (").append(Cache
[P
].CurVersion
).append("), ");
841 WriteHistoryTag("Disappeared", disappear
);
843 if (d
->dpkg_error
.empty() == false)
844 fprintf(d
->history_out
, "Error: %s\n", d
->dpkg_error
.c_str());
845 fprintf(d
->history_out
, "End-Date: %s\n", timestr
);
846 fclose(d
->history_out
);
848 d
->history_out
= NULL
;
854 // This implements a racy version of pselect for those architectures
855 // that don't have a working implementation.
856 // FIXME: Probably can be removed on Lenny+1
857 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
858 fd_set
*exceptfds
, const struct timespec
*timeout
,
859 const sigset_t
*sigmask
)
865 tv
.tv_sec
= timeout
->tv_sec
;
866 tv
.tv_usec
= timeout
->tv_nsec
/1000;
868 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
869 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
870 sigprocmask(SIG_SETMASK
, &origmask
, 0);
874 // DPkgPM::Go - Run the sequence /*{{{*/
875 // ---------------------------------------------------------------------
876 /* This globs the operations and calls dpkg
878 * If it is called with "OutStatusFd" set to a valid file descriptor
879 * apt will report the install progress over this fd. It maps the
880 * dpkg states a package goes through to human readable (and i10n-able)
881 * names and calculates a percentage for each step.
883 bool pkgDPkgPM::Go(int OutStatusFd
)
885 pkgPackageManager::SigINTStop
= false;
887 // Generate the base argument list for dpkg
888 std::vector
<const char *> Args
;
889 unsigned long StartSize
= 0;
890 string Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
892 string
const dpkgChrootDir
= _config
->FindDir("DPkg::Chroot-Directory", "/");
893 size_t dpkgChrootLen
= dpkgChrootDir
.length();
894 if (dpkgChrootDir
!= "/" && Tmp
.find(dpkgChrootDir
) == 0)
896 if (dpkgChrootDir
[dpkgChrootLen
- 1] == '/')
898 Tmp
= Tmp
.substr(dpkgChrootLen
);
901 Args
.push_back(Tmp
.c_str());
902 StartSize
+= Tmp
.length();
904 // Stick in any custom dpkg options
905 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
909 for (; Opts
!= 0; Opts
= Opts
->Next
)
911 if (Opts
->Value
.empty() == true)
913 Args
.push_back(Opts
->Value
.c_str());
914 StartSize
+= Opts
->Value
.length();
918 size_t const BaseArgs
= Args
.size();
919 // we need to detect if we can qualify packages with the architecture or not
920 Args
.push_back("--assert-multi-arch");
921 Args
.push_back(NULL
);
923 pid_t dpkgAssertMultiArch
= ExecFork();
924 if (dpkgAssertMultiArch
== 0)
926 dpkgChrootDirectory();
927 // redirect everything to the ultimate sink as we only need the exit-status
928 int const nullfd
= open("/dev/null", O_RDONLY
);
929 dup2(nullfd
, STDIN_FILENO
);
930 dup2(nullfd
, STDOUT_FILENO
);
931 dup2(nullfd
, STDERR_FILENO
);
932 execvp(Args
[0], (char**) &Args
[0]);
933 _error
->WarningE("dpkgGo", "Can't detect if dpkg supports multi-arch!");
940 sigset_t original_sigmask
;
942 unsigned int const MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
943 unsigned int const MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
944 bool const NoTriggers
= _config
->FindB("DPkg::NoTriggers", false);
946 if (RunScripts("DPkg::Pre-Invoke") == false)
949 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
952 // support subpressing of triggers processing for special
953 // cases like d-i that runs the triggers handling manually
954 bool const SmartConf
= (_config
->Find("PackageManager::Configure", "all") != "all");
955 bool const TriggersPending
= _config
->FindB("DPkg::TriggersPending", false);
956 if (_config
->FindB("DPkg::ConfigurePending", SmartConf
) == true)
957 List
.push_back(Item(Item::ConfigurePending
, PkgIterator()));
959 // map the dpkg states to the operations that are performed
960 // (this is sorted in the same way as Item::Ops)
961 static const struct DpkgState DpkgStatesOpMap
[][7] = {
964 {"half-installed", N_("Preparing %s")},
965 {"unpacked", N_("Unpacking %s") },
968 // Configure operation
970 {"unpacked",N_("Preparing to configure %s") },
971 {"half-configured", N_("Configuring %s") },
972 { "installed", N_("Installed %s")},
977 {"half-configured", N_("Preparing for removal of %s")},
978 {"half-installed", N_("Removing %s")},
979 {"config-files", N_("Removed %s")},
984 {"config-files", N_("Preparing to completely remove %s")},
985 {"not-installed", N_("Completely removed %s")},
990 // init the PackageOps map, go over the list of packages that
991 // that will be [installed|configured|removed|purged] and add
992 // them to the PackageOps map (the dpkg states it goes through)
993 // and the PackageOpsTranslations (human readable strings)
994 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end(); ++I
)
996 if((*I
).Pkg
.end() == true)
999 string
const name
= (*I
).Pkg
.Name();
1000 PackageOpsDone
[name
] = 0;
1001 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; ++i
)
1003 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
1008 d
->stdin_is_dev_null
= false;
1013 bool dpkgMultiArch
= false;
1014 if (dpkgAssertMultiArch
> 0)
1017 while (waitpid(dpkgAssertMultiArch
, &Status
, 0) != dpkgAssertMultiArch
)
1021 _error
->WarningE("dpkgGo", _("Waited for %s but it wasn't there"), "dpkg --assert-multi-arch");
1024 if (WIFEXITED(Status
) == true && WEXITSTATUS(Status
) == 0)
1025 dpkgMultiArch
= true;
1028 // this loop is runs once per operation
1029 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();)
1031 // Do all actions with the same Op in one run
1032 vector
<Item
>::const_iterator J
= I
;
1033 if (TriggersPending
== true)
1034 for (; J
!= List
.end(); ++J
)
1038 if (J
->Op
!= Item::TriggersPending
)
1040 vector
<Item
>::const_iterator T
= J
+ 1;
1041 if (T
!= List
.end() && T
->Op
== I
->Op
)
1046 for (; J
!= List
.end() && J
->Op
== I
->Op
; ++J
)
1049 // keep track of allocated strings for multiarch package names
1050 std::vector
<char *> Packages
;
1052 // start with the baseset of arguments
1053 unsigned long Size
= StartSize
;
1054 Args
.erase(Args
.begin() + BaseArgs
, Args
.end());
1056 // Now check if we are within the MaxArgs limit
1058 // this code below is problematic, because it may happen that
1059 // the argument list is split in a way that A depends on B
1060 // and they are in the same "--configure A B" run
1061 // - with the split they may now be configured in different
1062 // runs, using Immediate-Configure-All can help prevent this.
1063 if (J
- I
> (signed)MaxArgs
)
1066 unsigned long const size
= MaxArgs
+ 10;
1068 Packages
.reserve(size
);
1072 unsigned long const size
= (J
- I
) + 10;
1074 Packages
.reserve(size
);
1079 return _error
->Errno("pipe","Failed to create IPC pipe to dpkg");
1081 #define ADDARG(X) Args.push_back(X); Size += strlen(X)
1082 #define ADDARGC(X) Args.push_back(X); Size += sizeof(X) - 1
1084 ADDARGC("--status-fd");
1085 char status_fd_buf
[20];
1086 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
1087 ADDARG(status_fd_buf
);
1088 unsigned long const Op
= I
->Op
;
1093 ADDARGC("--force-depends");
1094 ADDARGC("--force-remove-essential");
1095 ADDARGC("--remove");
1099 ADDARGC("--force-depends");
1100 ADDARGC("--force-remove-essential");
1104 case Item::Configure
:
1105 ADDARGC("--configure");
1108 case Item::ConfigurePending
:
1109 ADDARGC("--configure");
1110 ADDARGC("--pending");
1113 case Item::TriggersPending
:
1114 ADDARGC("--triggers-only");
1115 ADDARGC("--pending");
1119 ADDARGC("--unpack");
1120 ADDARGC("--auto-deconfigure");
1124 if (NoTriggers
== true && I
->Op
!= Item::TriggersPending
&&
1125 I
->Op
!= Item::ConfigurePending
)
1127 ADDARGC("--no-triggers");
1131 // Write in the file or package names
1132 if (I
->Op
== Item::Install
)
1134 for (;I
!= J
&& Size
< MaxArgBytes
; ++I
)
1136 if (I
->File
[0] != '/')
1137 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
1138 Args
.push_back(I
->File
.c_str());
1139 Size
+= I
->File
.length();
1144 string
const nativeArch
= _config
->Find("APT::Architecture");
1145 unsigned long const oldSize
= I
->Op
== Item::Configure
? Size
: 0;
1146 for (;I
!= J
&& Size
< MaxArgBytes
; ++I
)
1148 if((*I
).Pkg
.end() == true)
1150 if (I
->Op
== Item::Configure
&& disappearedPkgs
.find(I
->Pkg
.Name()) != disappearedPkgs
.end())
1152 // We keep this here to allow "smooth" transitions from e.g. multiarch dpkg/ubuntu to dpkg/debian
1153 if (dpkgMultiArch
== false && (I
->Pkg
.Arch() == nativeArch
|| !strcmp(I
->Pkg
.Arch(), "all")))
1155 char const * const name
= I
->Pkg
.Name();
1160 pkgCache::VerIterator PkgVer
;
1161 std::string name
= I
->Pkg
.Name();
1162 if (Op
== Item::Remove
|| Op
== Item::Purge
)
1164 PkgVer
= I
->Pkg
.CurrentVer();
1165 if(PkgVer
.end() == true)
1166 PkgVer
= FindNowVersion(I
->Pkg
);
1169 PkgVer
= Cache
[I
->Pkg
].InstVerIter(Cache
);
1170 if (PkgVer
.end() == false)
1171 name
.append(":").append(PkgVer
.Arch());
1173 _error
->Warning("Can not find PkgVer for '%s'", name
.c_str());
1174 char * const fullname
= strdup(name
.c_str());
1175 Packages
.push_back(fullname
);
1179 // skip configure action if all sheduled packages disappeared
1180 if (oldSize
== Size
)
1187 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
1189 for (std::vector
<const char *>::const_iterator a
= Args
.begin();
1190 a
!= Args
.end(); ++a
)
1195 Args
.push_back(NULL
);
1201 /* Mask off sig int/quit. We do this because dpkg also does when
1202 it forks scripts. What happens is that when you hit ctrl-c it sends
1203 it to all processes in the group. Since dpkg ignores the signal
1204 it doesn't die but we do! So we must also ignore it */
1205 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
1206 sighandler_t old_SIGINT
= signal(SIGINT
,SigINT
);
1208 // Check here for any SIGINT
1209 if (pkgPackageManager::SigINTStop
&& (Op
== Item::Remove
|| Op
== Item::Purge
|| Op
== Item::Install
))
1213 // ignore SIGHUP as well (debian #463030)
1214 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
1221 // if tcgetattr does not return zero there was a error
1222 // and we do not do any pty magic
1223 if (tcgetattr(0, &tt
) == 0)
1225 ioctl(0, TIOCGWINSZ
, (char *)&win
);
1226 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
1228 const char *s
= _("Can not write log, openpty() "
1229 "failed (/dev/pts not mounted?)\n");
1230 fprintf(stderr
, "%s",s
);
1232 fprintf(d
->term_out
, "%s",s
);
1233 master
= slave
= -1;
1238 rtt
.c_lflag
&= ~ECHO
;
1239 rtt
.c_lflag
|= ISIG
;
1240 // block SIGTTOU during tcsetattr to prevent a hang if
1241 // the process is a member of the background process group
1242 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
1243 sigemptyset(&sigmask
);
1244 sigaddset(&sigmask
, SIGTTOU
);
1245 sigprocmask(SIG_BLOCK
,&sigmask
, &original_sigmask
);
1246 tcsetattr(0, TCSAFLUSH
, &rtt
);
1247 sigprocmask(SIG_SETMASK
, &original_sigmask
, 0);
1252 _config
->Set("APT::Keep-Fds::",fd
[1]);
1253 // send status information that we are about to fork dpkg
1254 if(OutStatusFd
> 0) {
1255 ostringstream status
;
1256 status
<< "pmstatus:dpkg-exec:"
1257 << (PackagesDone
/float(PackagesTotal
)*100.0)
1258 << ":" << _("Running dpkg")
1260 retry_write(OutStatusFd
, status
.str().c_str(), status
.str().size());
1264 // This is the child
1267 if(slave
>= 0 && master
>= 0)
1270 ioctl(slave
, TIOCSCTTY
, 0);
1277 close(fd
[0]); // close the read end of the pipe
1279 dpkgChrootDirectory();
1281 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
1284 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
1287 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
1290 // Discard everything in stdin before forking dpkg
1291 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
1294 while (read(STDIN_FILENO
,&dummy
,1) == 1);
1296 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
1300 /* No Job Control Stop Env is a magic dpkg var that prevents it
1301 from using sigstop */
1302 putenv((char *)"DPKG_NO_TSTP=yes");
1303 execvp(Args
[0], (char**) &Args
[0]);
1304 cerr
<< "Could not exec dpkg!" << endl
;
1309 if (_config
->FindB("DPkg::UseIoNice", false) == true)
1312 // clear the Keep-Fd again
1313 _config
->Clear("APT::Keep-Fds",fd
[1]);
1318 // we read from dpkg here
1319 int const _dpkgin
= fd
[0];
1320 close(fd
[1]); // close the write end of the pipe
1326 sigemptyset(&sigmask
);
1327 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
1329 /* free vectors (and therefore memory) as we don't need the included data anymore */
1330 for (std::vector
<char *>::const_iterator p
= Packages
.begin();
1331 p
!= Packages
.end(); ++p
)
1335 // the result of the waitpid call
1338 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
1340 // FIXME: move this to a function or something, looks ugly here
1341 // error handling, waitpid returned -1
1344 RunScripts("DPkg::Post-Invoke");
1346 // Restore sig int/quit
1347 signal(SIGQUIT
,old_SIGQUIT
);
1348 signal(SIGINT
,old_SIGINT
);
1350 signal(SIGHUP
,old_SIGHUP
);
1351 return _error
->Errno("waitpid","Couldn't wait for subprocess");
1354 // wait for input or output here
1356 if (master
>= 0 && !d
->stdin_is_dev_null
)
1358 FD_SET(_dpkgin
, &rfds
);
1360 FD_SET(master
, &rfds
);
1363 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
1364 &tv
, &original_sigmask
);
1365 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
1366 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
1367 NULL
, &tv
, &original_sigmask
);
1368 if (select_ret
== 0)
1370 else if (select_ret
< 0 && errno
== EINTR
)
1372 else if (select_ret
< 0)
1374 perror("select() returned error");
1378 if(master
>= 0 && FD_ISSET(master
, &rfds
))
1379 DoTerminalPty(master
);
1380 if(master
>= 0 && FD_ISSET(0, &rfds
))
1382 if(FD_ISSET(_dpkgin
, &rfds
))
1383 DoDpkgStatusFd(_dpkgin
, OutStatusFd
);
1387 // Restore sig int/quit
1388 signal(SIGQUIT
,old_SIGQUIT
);
1389 signal(SIGINT
,old_SIGINT
);
1391 signal(SIGHUP
,old_SIGHUP
);
1395 tcsetattr(0, TCSAFLUSH
, &tt
);
1399 // Check for an error code.
1400 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
1402 // if it was set to "keep-dpkg-runing" then we won't return
1403 // here but keep the loop going and just report it as a error
1405 bool const stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
1408 RunScripts("DPkg::Post-Invoke");
1410 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
1411 strprintf(d
->dpkg_error
, "Sub-process %s received a segmentation fault.",Args
[0]);
1412 else if (WIFEXITED(Status
) != 0)
1413 strprintf(d
->dpkg_error
, "Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
1415 strprintf(d
->dpkg_error
, "Sub-process %s exited unexpectedly",Args
[0]);
1417 if(d
->dpkg_error
.size() > 0)
1418 _error
->Error("%s", d
->dpkg_error
.c_str());
1429 if (pkgPackageManager::SigINTStop
)
1430 _error
->Warning(_("Operation was interrupted before it could finish"));
1432 if (RunScripts("DPkg::Post-Invoke") == false)
1435 if (_config
->FindB("Debug::pkgDPkgPM",false) == false)
1437 std::string
const oldpkgcache
= _config
->FindFile("Dir::cache::pkgcache");
1438 if (oldpkgcache
.empty() == false && RealFileExists(oldpkgcache
) == true &&
1439 unlink(oldpkgcache
.c_str()) == 0)
1441 std::string
const srcpkgcache
= _config
->FindFile("Dir::cache::srcpkgcache");
1442 if (srcpkgcache
.empty() == false && RealFileExists(srcpkgcache
) == true)
1444 _error
->PushToStack();
1445 pkgCacheFile CacheFile
;
1446 CacheFile
.BuildCaches(NULL
, true);
1447 _error
->RevertToStack();
1452 Cache
.writeStateFile(NULL
);
1456 void SigINT(int sig
) {
1457 pkgPackageManager::SigINTStop
= true;
1460 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1461 // ---------------------------------------------------------------------
1463 void pkgDPkgPM::Reset()
1465 List
.erase(List
.begin(),List
.end());
1468 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1469 // ---------------------------------------------------------------------
1471 void pkgDPkgPM::WriteApportReport(const char *pkgpath
, const char *errormsg
)
1473 // If apport doesn't exist or isn't installed do nothing
1474 // This e.g. prevents messages in 'universes' without apport
1475 pkgCache::PkgIterator apportPkg
= Cache
.FindPkg("apport");
1476 if (apportPkg
.end() == true || apportPkg
->CurrentVer
== 0)
1479 string pkgname
, reportfile
, srcpkgname
, pkgver
, arch
;
1480 string::size_type pos
;
1483 if (_config
->FindB("Dpkg::ApportFailureReport", false) == false)
1485 std::clog
<< "configured to not write apport reports" << std::endl
;
1489 // only report the first errors
1490 if(pkgFailures
> _config
->FindI("APT::Apport::MaxReports", 3))
1492 std::clog
<< _("No apport report written because MaxReports is reached already") << std::endl
;
1496 // check if its not a follow up error
1497 const char *needle
= dgettext("dpkg", "dependency problems - leaving unconfigured");
1498 if(strstr(errormsg
, needle
) != NULL
) {
1499 std::clog
<< _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl
;
1503 // do not report disk-full failures
1504 if(strstr(errormsg
, strerror(ENOSPC
)) != NULL
) {
1505 std::clog
<< _("No apport report written because the error message indicates a disk full error") << std::endl
;
1509 // do not report out-of-memory failures
1510 if(strstr(errormsg
, strerror(ENOMEM
)) != NULL
) {
1511 std::clog
<< _("No apport report written because the error message indicates a out of memory error") << std::endl
;
1515 // do not report dpkg I/O errors
1516 // XXX - this message is localized, but this only matches the English version. This is better than nothing.
1517 if(strstr(errormsg
, "short read in buffer_copy (")) {
1518 std::clog
<< _("No apport report written because the error message indicates a dpkg I/O error") << std::endl
;
1522 // get the pkgname and reportfile
1523 pkgname
= flNotDir(pkgpath
);
1524 pos
= pkgname
.find('_');
1525 if(pos
!= string::npos
)
1526 pkgname
= pkgname
.substr(0, pos
);
1528 // find the package versin and source package name
1529 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
1530 if (Pkg
.end() == true)
1532 pkgCache::VerIterator Ver
= Cache
.GetCandidateVer(Pkg
);
1533 if (Ver
.end() == true)
1535 pkgver
= Ver
.VerStr() == NULL
? "unknown" : Ver
.VerStr();
1536 pkgRecords
Recs(Cache
);
1537 pkgRecords::Parser
&Parse
= Recs
.Lookup(Ver
.FileList());
1538 srcpkgname
= Parse
.SourcePkg();
1539 if(srcpkgname
.empty())
1540 srcpkgname
= pkgname
;
1542 // if the file exists already, we check:
1543 // - if it was reported already (touched by apport).
1544 // If not, we do nothing, otherwise
1545 // we overwrite it. This is the same behaviour as apport
1546 // - if we have a report with the same pkgversion already
1548 reportfile
= flCombine("/var/crash",pkgname
+".0.crash");
1549 if(FileExists(reportfile
))
1554 // check atime/mtime
1555 stat(reportfile
.c_str(), &buf
);
1556 if(buf
.st_mtime
> buf
.st_atime
)
1559 // check if the existing report is the same version
1560 report
= fopen(reportfile
.c_str(),"r");
1561 while(fgets(strbuf
, sizeof(strbuf
), report
) != NULL
)
1563 if(strstr(strbuf
,"Package:") == strbuf
)
1565 char pkgname
[255], version
[255];
1566 if(sscanf(strbuf
, "Package: %254s %254s", pkgname
, version
) == 2)
1567 if(strcmp(pkgver
.c_str(), version
) == 0)
1577 // now write the report
1578 arch
= _config
->Find("APT::Architecture");
1579 report
= fopen(reportfile
.c_str(),"w");
1582 if(_config
->FindB("DPkgPM::InitialReportOnly",false) == true)
1583 chmod(reportfile
.c_str(), 0);
1585 chmod(reportfile
.c_str(), 0600);
1586 fprintf(report
, "ProblemType: Package\n");
1587 fprintf(report
, "Architecture: %s\n", arch
.c_str());
1588 time_t now
= time(NULL
);
1589 fprintf(report
, "Date: %s" , ctime(&now
));
1590 fprintf(report
, "Package: %s %s\n", pkgname
.c_str(), pkgver
.c_str());
1591 fprintf(report
, "SourcePackage: %s\n", srcpkgname
.c_str());
1592 fprintf(report
, "ErrorMessage:\n %s\n", errormsg
);
1594 // ensure that the log is flushed
1596 fflush(d
->term_out
);
1598 // attach terminal log it if we have it
1599 string logfile_name
= _config
->FindFile("Dir::Log::Terminal");
1600 if (!logfile_name
.empty())
1605 fprintf(report
, "DpkgTerminalLog:\n");
1606 log
= fopen(logfile_name
.c_str(),"r");
1609 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1610 fprintf(report
, " %s", buf
);
1616 const char *ops_str
[] = {"Install", "Configure","Remove","Purge"};
1617 fprintf(report
, "AptOrdering:\n");
1618 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
1619 fprintf(report
, " %s: %s\n", (*I
).Pkg
.Name(), ops_str
[(*I
).Op
]);
1621 // attach dmesg log (to learn about segfaults)
1622 if (FileExists("/bin/dmesg"))
1627 fprintf(report
, "Dmesg:\n");
1628 log
= popen("/bin/dmesg","r");
1631 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1632 fprintf(report
, " %s", buf
);
1637 // attach df -l log (to learn about filesystem status)
1638 if (FileExists("/bin/df"))
1643 fprintf(report
, "Df:\n");
1644 log
= popen("/bin/df -l","r");
1647 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1648 fprintf(report
, " %s", buf
);