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() : dpkgbuf_pos(0), term_out(NULL
), history_out(NULL
)
57 bool stdin_is_dev_null
;
58 // the buffer we use for the dpkg status-fd reading
68 // Maps the dpkg "processing" info to human readable names. Entry 0
69 // of each array is the key, entry 1 is the value.
70 const std::pair
<const char *, const char *> PackageProcessingOps
[] = {
71 std::make_pair("install", N_("Installing %s")),
72 std::make_pair("configure", N_("Configuring %s")),
73 std::make_pair("remove", N_("Removing %s")),
74 std::make_pair("purge", N_("Completely removing %s")),
75 std::make_pair("disappear", N_("Noting disappearance of %s")),
76 std::make_pair("trigproc", N_("Running post-installation trigger %s"))
79 const std::pair
<const char *, const char *> * const PackageProcessingOpsBegin
= PackageProcessingOps
;
80 const std::pair
<const char *, const char *> * const PackageProcessingOpsEnd
= PackageProcessingOps
+ sizeof(PackageProcessingOps
) / sizeof(PackageProcessingOps
[0]);
82 // Predicate to test whether an entry in the PackageProcessingOps
83 // array matches a string.
84 class MatchProcessingOp
89 MatchProcessingOp(const char *the_target
)
94 bool operator()(const std::pair
<const char *, const char *> &pair
) const
96 return strcmp(pair
.first
, target
) == 0;
101 /* helper function to ionice the given PID
103 there is no C header for ionice yet - just the syscall interface
104 so we use the binary from util-linux
109 if (!FileExists("/usr/bin/ionice"))
111 pid_t Process
= ExecFork();
115 snprintf(buf
, sizeof(buf
), "-p%d", PID
);
117 Args
[0] = "/usr/bin/ionice";
121 execv(Args
[0], (char **)Args
);
123 return ExecWait(Process
, "ionice");
126 // dpkgChrootDirectory - chrooting for dpkg if needed /*{{{*/
127 static void dpkgChrootDirectory()
129 std::string
const chrootDir
= _config
->FindDir("DPkg::Chroot-Directory");
130 if (chrootDir
== "/")
132 std::cerr
<< "Chrooting into " << chrootDir
<< std::endl
;
133 if (chroot(chrootDir
.c_str()) != 0)
139 // FindNowVersion - Helper to find a Version in "now" state /*{{{*/
140 // ---------------------------------------------------------------------
141 /* This is helpful when a package is no longer installed but has residual
145 pkgCache::VerIterator
FindNowVersion(const pkgCache::PkgIterator
&Pkg
)
147 pkgCache::VerIterator Ver
;
148 for (Ver
= Pkg
.VersionList(); Ver
.end() == false; Ver
++)
150 pkgCache::VerFileIterator Vf
= Ver
.FileList();
151 pkgCache::PkgFileIterator F
= Vf
.File();
152 for (F
= Vf
.File(); F
.end() == false; F
++)
154 if (F
&& F
.Archive())
156 if (strcmp(F
.Archive(), "now"))
165 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
166 // ---------------------------------------------------------------------
168 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
169 : pkgPackageManager(Cache
), PackagesDone(0), PackagesTotal(0)
171 d
= new pkgDPkgPMPrivate();
174 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
175 // ---------------------------------------------------------------------
177 pkgDPkgPM::~pkgDPkgPM()
182 // DPkgPM::Install - Install a package /*{{{*/
183 // ---------------------------------------------------------------------
184 /* Add an install operation to the sequence list */
185 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
187 if (File
.empty() == true || Pkg
.end() == true)
188 return _error
->Error("Internal Error, No file name for %s",Pkg
.Name());
190 // If the filename string begins with DPkg::Chroot-Directory, return the
191 // substr that is within the chroot so dpkg can access it.
192 string
const chrootdir
= _config
->FindDir("DPkg::Chroot-Directory","/");
193 if (chrootdir
!= "/" && File
.find(chrootdir
) == 0)
195 size_t len
= chrootdir
.length();
196 if (chrootdir
.at(len
- 1) == '/')
198 List
.push_back(Item(Item::Install
,Pkg
,File
.substr(len
)));
201 List
.push_back(Item(Item::Install
,Pkg
,File
));
206 // DPkgPM::Configure - Configure a package /*{{{*/
207 // ---------------------------------------------------------------------
208 /* Add a configure operation to the sequence list */
209 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
211 if (Pkg
.end() == true)
214 List
.push_back(Item(Item::Configure
, Pkg
));
216 // Use triggers for config calls if we configure "smart"
217 // as otherwise Pre-Depends will not be satisfied, see #526774
218 if (_config
->FindB("DPkg::TriggersPending", false) == true)
219 List
.push_back(Item(Item::TriggersPending
, PkgIterator()));
224 // DPkgPM::Remove - Remove a package /*{{{*/
225 // ---------------------------------------------------------------------
226 /* Add a remove operation to the sequence list */
227 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
229 if (Pkg
.end() == true)
233 List
.push_back(Item(Item::Purge
,Pkg
));
235 List
.push_back(Item(Item::Remove
,Pkg
));
239 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
240 // ---------------------------------------------------------------------
241 /* This is part of the helper script communication interface, it sends
242 very complete information down to the other end of the pipe.*/
243 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
245 fprintf(F
,"VERSION 2\n");
247 /* Write out all of the configuration directives by walking the
248 configuration tree */
249 const Configuration::Item
*Top
= _config
->Tree(0);
252 if (Top
->Value
.empty() == false)
255 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
256 QuoteString(Top
->Value
,"\n").c_str());
265 while (Top
!= 0 && Top
->Next
== 0)
272 // Write out the package actions in order.
273 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
275 if(I
->Pkg
.end() == true)
278 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
280 fprintf(F
,"%s ",I
->Pkg
.Name());
282 if (I
->Pkg
->CurrentVer
== 0)
285 fprintf(F
,"%s ",I
->Pkg
.CurrentVer().VerStr());
287 // Show the compare operator
289 if (S
.InstallVer
!= 0)
292 if (I
->Pkg
->CurrentVer
!= 0)
293 Comp
= S
.InstVerIter(Cache
).CompareVer(I
->Pkg
.CurrentVer());
300 fprintf(F
,"%s ",S
.InstVerIter(Cache
).VerStr());
305 // Show the filename/operation
306 if (I
->Op
== Item::Install
)
309 if (I
->File
[0] != '/')
310 fprintf(F
,"**ERROR**\n");
312 fprintf(F
,"%s\n",I
->File
.c_str());
314 if (I
->Op
== Item::Configure
)
315 fprintf(F
,"**CONFIGURE**\n");
316 if (I
->Op
== Item::Remove
||
317 I
->Op
== Item::Purge
)
318 fprintf(F
,"**REMOVE**\n");
326 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
327 // ---------------------------------------------------------------------
328 /* This looks for a list of scripts to run from the configuration file
329 each one is run and is fed on standard input a list of all .deb files
330 that are due to be installed. */
331 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
333 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
334 if (Opts
== 0 || Opts
->Child
== 0)
338 unsigned int Count
= 1;
339 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
341 if (Opts
->Value
.empty() == true)
344 // Determine the protocol version
345 string OptSec
= Opts
->Value
;
346 string::size_type Pos
;
347 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
348 Pos
= OptSec
.length();
349 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
351 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
355 if (pipe(Pipes
) != 0)
356 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
357 SetCloseExec(Pipes
[0],true);
358 SetCloseExec(Pipes
[1],true);
360 // Purified Fork for running the script
361 pid_t Process
= ExecFork();
365 dup2(Pipes
[0],STDIN_FILENO
);
366 SetCloseExec(STDOUT_FILENO
,false);
367 SetCloseExec(STDIN_FILENO
,false);
368 SetCloseExec(STDERR_FILENO
,false);
370 dpkgChrootDirectory();
374 Args
[2] = Opts
->Value
.c_str();
376 execv(Args
[0],(char **)Args
);
380 FILE *F
= fdopen(Pipes
[1],"w");
382 return _error
->Errno("fdopen","Faild to open new FD");
384 // Feed it the filenames.
387 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
389 // Only deal with packages to be installed from .deb
390 if (I
->Op
!= Item::Install
)
394 if (I
->File
[0] != '/')
397 /* Feed the filename of each package that is pending install
399 fprintf(F
,"%s\n",I
->File
.c_str());
409 // Clean up the sub process
410 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
411 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
417 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
418 // ---------------------------------------------------------------------
421 void pkgDPkgPM::DoStdin(int master
)
423 unsigned char input_buf
[256] = {0,};
424 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
426 write(master
, input_buf
, len
);
428 d
->stdin_is_dev_null
= true;
431 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
432 // ---------------------------------------------------------------------
434 * read the terminal pty and write log
436 void pkgDPkgPM::DoTerminalPty(int master
)
438 unsigned char term_buf
[1024] = {0,0, };
440 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
441 if(len
== -1 && errno
== EIO
)
443 // this happens when the child is about to exit, we
444 // give it time to actually exit, otherwise we run
445 // into a race so we sleep for half a second.
446 struct timespec sleepfor
= { 0, 500000000 };
447 nanosleep(&sleepfor
, NULL
);
452 write(1, term_buf
, len
);
454 fwrite(term_buf
, len
, sizeof(char), d
->term_out
);
457 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
458 // ---------------------------------------------------------------------
461 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd
, char *line
)
463 bool const Debug
= _config
->FindB("Debug::pkgDPkgProgressReporting",false);
464 // the status we output
465 ostringstream status
;
468 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
471 /* dpkg sends strings like this:
472 'status: <pkg>: <pkg qstate>'
473 errors look like this:
474 '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
475 and conffile-prompt like this
476 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
478 Newer versions of dpkg sent also:
479 'processing: install: pkg'
480 'processing: configure: pkg'
481 'processing: remove: pkg'
482 'processing: purge: pkg'
483 'processing: disappear: pkg'
484 'processing: trigproc: trigger'
488 // dpkg sends multiline error messages sometimes (see
489 // #374195 for a example. we should support this by
490 // either patching dpkg to not send multiline over the
491 // statusfd or by rewriting the code here to deal with
492 // it. for now we just ignore it and not crash
493 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
494 if( list
[0] == NULL
|| list
[1] == NULL
|| list
[2] == NULL
)
497 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
500 const char* const pkg
= list
[1];
501 const char* action
= _strstrip(list
[2]);
503 // 'processing' from dpkg looks like
504 // 'processing: action: pkg'
505 if(strncmp(list
[0], "processing", strlen("processing")) == 0)
508 const char* const pkg_or_trigger
= _strstrip(list
[2]);
509 action
= _strstrip( list
[1]);
510 const std::pair
<const char *, const char *> * const iter
=
511 std::find_if(PackageProcessingOpsBegin
,
512 PackageProcessingOpsEnd
,
513 MatchProcessingOp(action
));
514 if(iter
== PackageProcessingOpsEnd
)
517 std::clog
<< "ignoring unknown action: " << action
<< std::endl
;
520 snprintf(s
, sizeof(s
), _(iter
->second
), pkg_or_trigger
);
522 status
<< "pmstatus:" << pkg_or_trigger
523 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
527 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
529 std::clog
<< "send: '" << status
.str() << "'" << endl
;
531 if (strncmp(action
, "disappear", strlen("disappear")) == 0)
532 handleDisappearAction(pkg_or_trigger
);
536 if(strncmp(action
,"error",strlen("error")) == 0)
538 // urgs, sometime has ":" in its error string so that we
539 // end up with the error message split between list[3]
540 // and list[4], e.g. the message:
541 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
543 if( list
[4] != NULL
)
544 list
[3][strlen(list
[3])] = ':';
546 status
<< "pmerror:" << list
[1]
547 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
551 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
553 std::clog
<< "send: '" << status
.str() << "'" << endl
;
555 WriteApportReport(list
[1], list
[3]);
558 else if(strncmp(action
,"conffile",strlen("conffile")) == 0)
560 status
<< "pmconffile:" << list
[1]
561 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
565 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
567 std::clog
<< "send: '" << status
.str() << "'" << endl
;
571 vector
<struct DpkgState
> const &states
= PackageOps
[pkg
];
572 const char *next_action
= NULL
;
573 if(PackageOpsDone
[pkg
] < states
.size())
574 next_action
= states
[PackageOpsDone
[pkg
]].state
;
575 // check if the package moved to the next dpkg state
576 if(next_action
&& (strcmp(action
, next_action
) == 0))
578 // only read the translation if there is actually a next
580 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
582 snprintf(s
, sizeof(s
), translation
, pkg
);
584 // we moved from one dpkg state to a new one, report that
585 PackageOpsDone
[pkg
]++;
587 // build the status str
588 status
<< "pmstatus:" << pkg
589 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
593 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
595 std::clog
<< "send: '" << status
.str() << "'" << endl
;
598 std::clog
<< "(parsed from dpkg) pkg: " << pkg
599 << " action: " << action
<< endl
;
602 // DPkgPM::handleDisappearAction /*{{{*/
603 void pkgDPkgPM::handleDisappearAction(string
const &pkgname
)
605 // record the package name for display and stuff later
606 disappearedPkgs
.insert(pkgname
);
608 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
609 if (unlikely(Pkg
.end() == true))
611 // the disappeared package was auto-installed - nothing to do
612 if ((Cache
[Pkg
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
614 pkgCache::VerIterator PkgVer
= Cache
[Pkg
].InstVerIter(Cache
);
615 if (unlikely(PkgVer
.end() == true))
617 /* search in the list of dependencies for (Pre)Depends,
618 check if this dependency has a Replaces on our package
619 and if so transfer the manual installed flag to it */
620 for (pkgCache::DepIterator Dep
= PkgVer
.DependsList(); Dep
.end() != true; ++Dep
)
622 if (Dep
->Type
!= pkgCache::Dep::Depends
&&
623 Dep
->Type
!= pkgCache::Dep::PreDepends
)
625 pkgCache::PkgIterator Tar
= Dep
.TargetPkg();
626 if (unlikely(Tar
.end() == true))
628 // the package is already marked as manual
629 if ((Cache
[Tar
].Flags
& pkgCache::Flag::Auto
) != pkgCache::Flag::Auto
)
631 pkgCache::VerIterator TarVer
= Cache
[Tar
].InstVerIter(Cache
);
632 if (TarVer
.end() == true)
634 for (pkgCache::DepIterator Rep
= TarVer
.DependsList(); Rep
.end() != true; ++Rep
)
636 if (Rep
->Type
!= pkgCache::Dep::Replaces
)
638 if (Pkg
!= Rep
.TargetPkg())
640 // okay, they are strongly connected - transfer manual-bit
642 std::clog
<< "transfer manual-bit from disappeared »" << pkgname
<< "« to »" << Tar
.FullName() << "«" << std::endl
;
643 Cache
[Tar
].Flags
&= ~Flag::Auto
;
649 // DPkgPM::DoDpkgStatusFd /*{{{*/
650 // ---------------------------------------------------------------------
653 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
, int OutStatusFd
)
658 len
=read(statusfd
, &d
->dpkgbuf
[d
->dpkgbuf_pos
], sizeof(d
->dpkgbuf
)-d
->dpkgbuf_pos
);
659 d
->dpkgbuf_pos
+= len
;
663 // process line by line if we have a buffer
665 while((q
=(char*)memchr(p
, '\n', d
->dpkgbuf
+d
->dpkgbuf_pos
-p
)) != NULL
)
668 ProcessDpkgStatusLine(OutStatusFd
, p
);
669 p
=q
+1; // continue with next line
672 // now move the unprocessed bits (after the final \n that is now a 0x0)
673 // to the start and update d->dpkgbuf_pos
674 p
= (char*)memrchr(d
->dpkgbuf
, 0, d
->dpkgbuf_pos
);
678 // we are interessted in the first char *after* 0x0
681 // move the unprocessed tail to the start and update pos
682 memmove(d
->dpkgbuf
, p
, p
-d
->dpkgbuf
);
683 d
->dpkgbuf_pos
= d
->dpkgbuf
+d
->dpkgbuf_pos
-p
;
686 // DPkgPM::WriteHistoryTag /*{{{*/
687 void pkgDPkgPM::WriteHistoryTag(string
const &tag
, string value
)
689 size_t const length
= value
.length();
692 // poor mans rstrip(", ")
693 if (value
[length
-2] == ',' && value
[length
-1] == ' ')
694 value
.erase(length
- 2, 2);
695 fprintf(d
->history_out
, "%s: %s\n", tag
.c_str(), value
.c_str());
697 // DPkgPM::OpenLog /*{{{*/
698 bool pkgDPkgPM::OpenLog()
700 string
const logdir
= _config
->FindDir("Dir::Log");
701 if(CreateAPTDirectoryIfNeeded(logdir
, logdir
) == false)
702 // FIXME: use a better string after freeze
703 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
707 time_t const t
= time(NULL
);
708 struct tm
const * const tmp
= localtime(&t
);
709 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
712 string
const logfile_name
= flCombine(logdir
,
713 _config
->Find("Dir::Log::Terminal"));
714 if (!logfile_name
.empty())
716 d
->term_out
= fopen(logfile_name
.c_str(),"a");
717 if (d
->term_out
== NULL
)
718 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name
.c_str());
719 setvbuf(d
->term_out
, NULL
, _IONBF
, 0);
720 SetCloseExec(fileno(d
->term_out
), true);
723 pw
= getpwnam("root");
724 gr
= getgrnam("adm");
725 if (pw
!= NULL
&& gr
!= NULL
)
726 chown(logfile_name
.c_str(), pw
->pw_uid
, gr
->gr_gid
);
727 chmod(logfile_name
.c_str(), 0644);
728 fprintf(d
->term_out
, "\nLog started: %s\n", timestr
);
731 // write your history
732 string
const history_name
= flCombine(logdir
,
733 _config
->Find("Dir::Log::History"));
734 if (!history_name
.empty())
736 d
->history_out
= fopen(history_name
.c_str(),"a");
737 if (d
->history_out
== NULL
)
738 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), history_name
.c_str());
739 chmod(history_name
.c_str(), 0644);
740 fprintf(d
->history_out
, "\nStart-Date: %s\n", timestr
);
741 string remove
, purge
, install
, reinstall
, upgrade
, downgrade
;
742 for (pkgCache::PkgIterator I
= Cache
.PkgBegin(); I
.end() == false; ++I
)
744 enum { CANDIDATE
, CANDIDATE_AUTO
, CURRENT_CANDIDATE
, CURRENT
} infostring
;
746 #define HISTORYINFO(X, Y) { line = &X; infostring = Y; }
747 if (Cache
[I
].NewInstall() == true)
748 HISTORYINFO(install
, CANDIDATE_AUTO
)
749 else if (Cache
[I
].ReInstall() == true)
750 HISTORYINFO(reinstall
, CANDIDATE
)
751 else if (Cache
[I
].Upgrade() == true)
752 HISTORYINFO(upgrade
, CURRENT_CANDIDATE
)
753 else if (Cache
[I
].Downgrade() == true)
754 HISTORYINFO(downgrade
, CURRENT_CANDIDATE
)
755 else if (Cache
[I
].Delete() == true)
756 HISTORYINFO((Cache
[I
].Purge() ? purge
: remove
), CURRENT
)
760 line
->append(I
.FullName(false)).append(" (");
761 switch (infostring
) {
762 case CANDIDATE
: line
->append(Cache
[I
].CandVersion
); break;
764 line
->append(Cache
[I
].CandVersion
);
765 if ((Cache
[I
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
766 line
->append(", automatic");
768 case CURRENT_CANDIDATE
: line
->append(Cache
[I
].CurVersion
).append(", ").append(Cache
[I
].CandVersion
); break;
769 case CURRENT
: line
->append(Cache
[I
].CurVersion
); break;
773 if (_config
->Exists("Commandline::AsString") == true)
774 WriteHistoryTag("Commandline", _config
->Find("Commandline::AsString"));
775 WriteHistoryTag("Install", install
);
776 WriteHistoryTag("Reinstall", reinstall
);
777 WriteHistoryTag("Upgrade", upgrade
);
778 WriteHistoryTag("Downgrade",downgrade
);
779 WriteHistoryTag("Remove",remove
);
780 WriteHistoryTag("Purge",purge
);
781 fflush(d
->history_out
);
787 // DPkg::CloseLog /*{{{*/
788 bool pkgDPkgPM::CloseLog()
791 time_t t
= time(NULL
);
792 struct tm
*tmp
= localtime(&t
);
793 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
797 fprintf(d
->term_out
, "Log ended: ");
798 fprintf(d
->term_out
, "%s", timestr
);
799 fprintf(d
->term_out
, "\n");
806 if (disappearedPkgs
.empty() == false)
809 for (std::set
<std::string
>::const_iterator d
= disappearedPkgs
.begin();
810 d
!= disappearedPkgs
.end(); ++d
)
812 pkgCache::PkgIterator P
= Cache
.FindPkg(*d
);
813 disappear
.append(*d
);
815 disappear
.append(", ");
817 disappear
.append(" (").append(Cache
[P
].CurVersion
).append("), ");
819 WriteHistoryTag("Disappeared", disappear
);
821 if (d
->dpkg_error
.empty() == false)
822 fprintf(d
->history_out
, "Error: %s\n", d
->dpkg_error
.c_str());
823 fprintf(d
->history_out
, "End-Date: %s\n", timestr
);
824 fclose(d
->history_out
);
826 d
->history_out
= NULL
;
832 // This implements a racy version of pselect for those architectures
833 // that don't have a working implementation.
834 // FIXME: Probably can be removed on Lenny+1
835 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
836 fd_set
*exceptfds
, const struct timespec
*timeout
,
837 const sigset_t
*sigmask
)
843 tv
.tv_sec
= timeout
->tv_sec
;
844 tv
.tv_usec
= timeout
->tv_nsec
/1000;
846 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
847 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
848 sigprocmask(SIG_SETMASK
, &origmask
, 0);
852 // DPkgPM::Go - Run the sequence /*{{{*/
853 // ---------------------------------------------------------------------
854 /* This globs the operations and calls dpkg
856 * If it is called with "OutStatusFd" set to a valid file descriptor
857 * apt will report the install progress over this fd. It maps the
858 * dpkg states a package goes through to human readable (and i10n-able)
859 * names and calculates a percentage for each step.
861 bool pkgDPkgPM::Go(int OutStatusFd
)
863 pkgPackageManager::SigINTStop
= false;
865 // Generate the base argument list for dpkg
866 std::vector
<const char *> Args
;
867 unsigned long StartSize
= 0;
868 string Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
870 string
const dpkgChrootDir
= _config
->FindDir("DPkg::Chroot-Directory", "/");
871 size_t dpkgChrootLen
= dpkgChrootDir
.length();
872 if (dpkgChrootDir
!= "/" && Tmp
.find(dpkgChrootDir
) == 0)
874 if (dpkgChrootDir
[dpkgChrootLen
- 1] == '/')
876 Tmp
= Tmp
.substr(dpkgChrootLen
);
879 Args
.push_back(Tmp
.c_str());
880 StartSize
+= Tmp
.length();
882 // Stick in any custom dpkg options
883 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
887 for (; Opts
!= 0; Opts
= Opts
->Next
)
889 if (Opts
->Value
.empty() == true)
891 Args
.push_back(Opts
->Value
.c_str());
892 StartSize
+= Opts
->Value
.length();
896 size_t const BaseArgs
= Args
.size();
897 // we need to detect if we can qualify packages with the architecture or not
898 Args
.push_back("--assert-multi-arch");
899 Args
.push_back(NULL
);
901 pid_t dpkgAssertMultiArch
= ExecFork();
902 if (dpkgAssertMultiArch
== 0)
904 dpkgChrootDirectory();
905 // redirect everything to the ultimate sink as we only need the exit-status
906 int const nullfd
= open("/dev/null", O_RDONLY
);
907 dup2(nullfd
, STDIN_FILENO
);
908 dup2(nullfd
, STDOUT_FILENO
);
909 dup2(nullfd
, STDERR_FILENO
);
910 execvp(Args
[0], (char**) &Args
[0]);
911 _error
->WarningE("dpkgGo", "Can't detect if dpkg supports multi-arch!");
918 sigset_t original_sigmask
;
920 unsigned int const MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
921 unsigned int const MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
922 bool const NoTriggers
= _config
->FindB("DPkg::NoTriggers", false);
924 if (RunScripts("DPkg::Pre-Invoke") == false)
927 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
930 // support subpressing of triggers processing for special
931 // cases like d-i that runs the triggers handling manually
932 bool const SmartConf
= (_config
->Find("PackageManager::Configure", "all") != "all");
933 bool const TriggersPending
= _config
->FindB("DPkg::TriggersPending", false);
934 if (_config
->FindB("DPkg::ConfigurePending", SmartConf
) == true)
935 List
.push_back(Item(Item::ConfigurePending
, PkgIterator()));
937 // map the dpkg states to the operations that are performed
938 // (this is sorted in the same way as Item::Ops)
939 static const struct DpkgState DpkgStatesOpMap
[][7] = {
942 {"half-installed", N_("Preparing %s")},
943 {"unpacked", N_("Unpacking %s") },
946 // Configure operation
948 {"unpacked",N_("Preparing to configure %s") },
949 {"half-configured", N_("Configuring %s") },
950 { "installed", N_("Installed %s")},
955 {"half-configured", N_("Preparing for removal of %s")},
956 {"half-installed", N_("Removing %s")},
957 {"config-files", N_("Removed %s")},
962 {"config-files", N_("Preparing to completely remove %s")},
963 {"not-installed", N_("Completely removed %s")},
968 // init the PackageOps map, go over the list of packages that
969 // that will be [installed|configured|removed|purged] and add
970 // them to the PackageOps map (the dpkg states it goes through)
971 // and the PackageOpsTranslations (human readable strings)
972 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end(); ++I
)
974 if((*I
).Pkg
.end() == true)
977 string
const name
= (*I
).Pkg
.Name();
978 PackageOpsDone
[name
] = 0;
979 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; ++i
)
981 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
986 d
->stdin_is_dev_null
= false;
991 bool dpkgMultiArch
= false;
992 if (dpkgAssertMultiArch
> 0)
995 while (waitpid(dpkgAssertMultiArch
, &Status
, 0) != dpkgAssertMultiArch
)
999 _error
->WarningE("dpkgGo", _("Waited for %s but it wasn't there"), "dpkg --assert-multi-arch");
1002 if (WIFEXITED(Status
) == true && WEXITSTATUS(Status
) == 0)
1003 dpkgMultiArch
= true;
1006 // this loop is runs once per operation
1007 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();)
1009 // Do all actions with the same Op in one run
1010 vector
<Item
>::const_iterator J
= I
;
1011 if (TriggersPending
== true)
1012 for (; J
!= List
.end(); ++J
)
1016 if (J
->Op
!= Item::TriggersPending
)
1018 vector
<Item
>::const_iterator T
= J
+ 1;
1019 if (T
!= List
.end() && T
->Op
== I
->Op
)
1024 for (; J
!= List
.end() && J
->Op
== I
->Op
; ++J
)
1027 // keep track of allocated strings for multiarch package names
1028 std::vector
<char *> Packages
;
1030 // start with the baseset of arguments
1031 unsigned long Size
= StartSize
;
1032 Args
.erase(Args
.begin() + BaseArgs
, Args
.end());
1034 // Now check if we are within the MaxArgs limit
1036 // this code below is problematic, because it may happen that
1037 // the argument list is split in a way that A depends on B
1038 // and they are in the same "--configure A B" run
1039 // - with the split they may now be configured in different
1040 // runs, using Immediate-Configure-All can help prevent this.
1041 if (J
- I
> (signed)MaxArgs
)
1044 unsigned long const size
= MaxArgs
+ 10;
1046 Packages
.reserve(size
);
1050 unsigned long const size
= (J
- I
) + 10;
1052 Packages
.reserve(size
);
1058 #define ADDARG(X) Args.push_back(X); Size += strlen(X)
1059 #define ADDARGC(X) Args.push_back(X); Size += sizeof(X) - 1
1061 ADDARGC("--status-fd");
1062 char status_fd_buf
[20];
1063 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
1064 ADDARG(status_fd_buf
);
1065 unsigned long const Op
= I
->Op
;
1070 ADDARGC("--force-depends");
1071 ADDARGC("--force-remove-essential");
1072 ADDARGC("--remove");
1076 ADDARGC("--force-depends");
1077 ADDARGC("--force-remove-essential");
1081 case Item::Configure
:
1082 ADDARGC("--configure");
1085 case Item::ConfigurePending
:
1086 ADDARGC("--configure");
1087 ADDARGC("--pending");
1090 case Item::TriggersPending
:
1091 ADDARGC("--triggers-only");
1092 ADDARGC("--pending");
1096 ADDARGC("--unpack");
1097 ADDARGC("--auto-deconfigure");
1101 if (NoTriggers
== true && I
->Op
!= Item::TriggersPending
&&
1102 I
->Op
!= Item::ConfigurePending
)
1104 ADDARGC("--no-triggers");
1108 // Write in the file or package names
1109 if (I
->Op
== Item::Install
)
1111 for (;I
!= J
&& Size
< MaxArgBytes
; ++I
)
1113 if (I
->File
[0] != '/')
1114 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
1115 Args
.push_back(I
->File
.c_str());
1116 Size
+= I
->File
.length();
1121 string
const nativeArch
= _config
->Find("APT::Architecture");
1122 unsigned long const oldSize
= I
->Op
== Item::Configure
? Size
: 0;
1123 for (;I
!= J
&& Size
< MaxArgBytes
; ++I
)
1125 if((*I
).Pkg
.end() == true)
1127 if (I
->Op
== Item::Configure
&& disappearedPkgs
.find(I
->Pkg
.Name()) != disappearedPkgs
.end())
1129 // We keep this here to allow "smooth" transitions from e.g. multiarch dpkg/ubuntu to dpkg/debian
1130 if (dpkgMultiArch
== false && (I
->Pkg
.Arch() == nativeArch
|| !strcmp(I
->Pkg
.Arch(), "all")))
1132 char const * const name
= I
->Pkg
.Name();
1137 pkgCache::VerIterator PkgVer
;
1138 std::string name
= I
->Pkg
.Name();
1139 if (Op
== Item::Remove
|| Op
== Item::Purge
)
1141 PkgVer
= I
->Pkg
.CurrentVer();
1142 if(PkgVer
.end() == true)
1143 PkgVer
= FindNowVersion(I
->Pkg
);
1146 PkgVer
= Cache
[I
->Pkg
].InstVerIter(Cache
);
1147 if (PkgVer
.end() == false)
1148 name
.append(":").append(PkgVer
.Arch());
1150 _error
->Warning("Can not find PkgVer for '%s'", name
.c_str());
1151 char * const fullname
= strdup(name
.c_str());
1152 Packages
.push_back(fullname
);
1156 // skip configure action if all sheduled packages disappeared
1157 if (oldSize
== Size
)
1164 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
1166 for (std::vector
<const char *>::const_iterator a
= Args
.begin();
1167 a
!= Args
.end(); ++a
)
1172 Args
.push_back(NULL
);
1178 /* Mask off sig int/quit. We do this because dpkg also does when
1179 it forks scripts. What happens is that when you hit ctrl-c it sends
1180 it to all processes in the group. Since dpkg ignores the signal
1181 it doesn't die but we do! So we must also ignore it */
1182 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
1183 sighandler_t old_SIGINT
= signal(SIGINT
,SigINT
);
1185 // Check here for any SIGINT
1186 if (pkgPackageManager::SigINTStop
&& (Op
== Item::Remove
|| Op
== Item::Purge
|| Op
== Item::Install
))
1190 // ignore SIGHUP as well (debian #463030)
1191 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
1198 // if tcgetattr does not return zero there was a error
1199 // and we do not do any pty magic
1200 if (tcgetattr(0, &tt
) == 0)
1202 ioctl(0, TIOCGWINSZ
, (char *)&win
);
1203 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
1205 const char *s
= _("Can not write log, openpty() "
1206 "failed (/dev/pts not mounted?)\n");
1207 fprintf(stderr
, "%s",s
);
1209 fprintf(d
->term_out
, "%s",s
);
1210 master
= slave
= -1;
1215 rtt
.c_lflag
&= ~ECHO
;
1216 rtt
.c_lflag
|= ISIG
;
1217 // block SIGTTOU during tcsetattr to prevent a hang if
1218 // the process is a member of the background process group
1219 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
1220 sigemptyset(&sigmask
);
1221 sigaddset(&sigmask
, SIGTTOU
);
1222 sigprocmask(SIG_BLOCK
,&sigmask
, &original_sigmask
);
1223 tcsetattr(0, TCSAFLUSH
, &rtt
);
1224 sigprocmask(SIG_SETMASK
, &original_sigmask
, 0);
1229 _config
->Set("APT::Keep-Fds::",fd
[1]);
1230 // send status information that we are about to fork dpkg
1231 if(OutStatusFd
> 0) {
1232 ostringstream status
;
1233 status
<< "pmstatus:dpkg-exec:"
1234 << (PackagesDone
/float(PackagesTotal
)*100.0)
1235 << ":" << _("Running dpkg")
1237 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
1241 // This is the child
1244 if(slave
>= 0 && master
>= 0)
1247 ioctl(slave
, TIOCSCTTY
, 0);
1254 close(fd
[0]); // close the read end of the pipe
1256 dpkgChrootDirectory();
1258 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
1261 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
1264 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
1267 // Discard everything in stdin before forking dpkg
1268 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
1271 while (read(STDIN_FILENO
,&dummy
,1) == 1);
1273 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
1277 /* No Job Control Stop Env is a magic dpkg var that prevents it
1278 from using sigstop */
1279 putenv((char *)"DPKG_NO_TSTP=yes");
1280 execvp(Args
[0], (char**) &Args
[0]);
1281 cerr
<< "Could not exec dpkg!" << endl
;
1286 if (_config
->FindB("DPkg::UseIoNice", false) == true)
1289 // clear the Keep-Fd again
1290 _config
->Clear("APT::Keep-Fds",fd
[1]);
1295 // we read from dpkg here
1296 int const _dpkgin
= fd
[0];
1297 close(fd
[1]); // close the write end of the pipe
1303 sigemptyset(&sigmask
);
1304 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
1306 /* free vectors (and therefore memory) as we don't need the included data anymore */
1307 for (std::vector
<char *>::const_iterator p
= Packages
.begin();
1308 p
!= Packages
.end(); ++p
)
1312 // the result of the waitpid call
1315 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
1317 // FIXME: move this to a function or something, looks ugly here
1318 // error handling, waitpid returned -1
1321 RunScripts("DPkg::Post-Invoke");
1323 // Restore sig int/quit
1324 signal(SIGQUIT
,old_SIGQUIT
);
1325 signal(SIGINT
,old_SIGINT
);
1327 signal(SIGHUP
,old_SIGHUP
);
1328 return _error
->Errno("waitpid","Couldn't wait for subprocess");
1331 // wait for input or output here
1333 if (master
>= 0 && !d
->stdin_is_dev_null
)
1335 FD_SET(_dpkgin
, &rfds
);
1337 FD_SET(master
, &rfds
);
1340 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
1341 &tv
, &original_sigmask
);
1342 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
1343 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
1344 NULL
, &tv
, &original_sigmask
);
1345 if (select_ret
== 0)
1347 else if (select_ret
< 0 && errno
== EINTR
)
1349 else if (select_ret
< 0)
1351 perror("select() returned error");
1355 if(master
>= 0 && FD_ISSET(master
, &rfds
))
1356 DoTerminalPty(master
);
1357 if(master
>= 0 && FD_ISSET(0, &rfds
))
1359 if(FD_ISSET(_dpkgin
, &rfds
))
1360 DoDpkgStatusFd(_dpkgin
, OutStatusFd
);
1364 // Restore sig int/quit
1365 signal(SIGQUIT
,old_SIGQUIT
);
1366 signal(SIGINT
,old_SIGINT
);
1368 signal(SIGHUP
,old_SIGHUP
);
1372 tcsetattr(0, TCSAFLUSH
, &tt
);
1376 // Check for an error code.
1377 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
1379 // if it was set to "keep-dpkg-runing" then we won't return
1380 // here but keep the loop going and just report it as a error
1382 bool const stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
1385 RunScripts("DPkg::Post-Invoke");
1387 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
1388 strprintf(d
->dpkg_error
, "Sub-process %s received a segmentation fault.",Args
[0]);
1389 else if (WIFEXITED(Status
) != 0)
1390 strprintf(d
->dpkg_error
, "Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
1392 strprintf(d
->dpkg_error
, "Sub-process %s exited unexpectedly",Args
[0]);
1394 if(d
->dpkg_error
.size() > 0)
1395 _error
->Error("%s", d
->dpkg_error
.c_str());
1406 if (pkgPackageManager::SigINTStop
)
1407 _error
->Warning(_("Operation was interrupted before it could finish"));
1409 if (RunScripts("DPkg::Post-Invoke") == false)
1412 if (_config
->FindB("Debug::pkgDPkgPM",false) == false)
1414 std::string
const oldpkgcache
= _config
->FindFile("Dir::cache::pkgcache");
1415 if (oldpkgcache
.empty() == false && RealFileExists(oldpkgcache
) == true &&
1416 unlink(oldpkgcache
.c_str()) == 0)
1418 std::string
const srcpkgcache
= _config
->FindFile("Dir::cache::srcpkgcache");
1419 if (srcpkgcache
.empty() == false && RealFileExists(srcpkgcache
) == true)
1421 _error
->PushToStack();
1422 pkgCacheFile CacheFile
;
1423 CacheFile
.BuildCaches(NULL
, true);
1424 _error
->RevertToStack();
1429 Cache
.writeStateFile(NULL
);
1433 void SigINT(int sig
) {
1434 pkgPackageManager::SigINTStop
= true;
1437 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1438 // ---------------------------------------------------------------------
1440 void pkgDPkgPM::Reset()
1442 List
.erase(List
.begin(),List
.end());
1445 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1446 // ---------------------------------------------------------------------
1448 void pkgDPkgPM::WriteApportReport(const char *pkgpath
, const char *errormsg
)
1450 // If apport doesn't exist or isn't installed do nothing
1451 // This e.g. prevents messages in 'universes' without apport
1452 pkgCache::PkgIterator apportPkg
= Cache
.FindPkg("apport");
1453 if (apportPkg
.end() == true || apportPkg
->CurrentVer
== 0)
1456 string pkgname
, reportfile
, srcpkgname
, pkgver
, arch
;
1457 string::size_type pos
;
1460 if (_config
->FindB("Dpkg::ApportFailureReport", false) == false)
1462 std::clog
<< "configured to not write apport reports" << std::endl
;
1466 // only report the first errors
1467 if(pkgFailures
> _config
->FindI("APT::Apport::MaxReports", 3))
1469 std::clog
<< _("No apport report written because MaxReports is reached already") << std::endl
;
1473 // check if its not a follow up error
1474 const char *needle
= dgettext("dpkg", "dependency problems - leaving unconfigured");
1475 if(strstr(errormsg
, needle
) != NULL
) {
1476 std::clog
<< _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl
;
1480 // do not report disk-full failures
1481 if(strstr(errormsg
, strerror(ENOSPC
)) != NULL
) {
1482 std::clog
<< _("No apport report written because the error message indicates a disk full error") << std::endl
;
1486 // do not report out-of-memory failures
1487 if(strstr(errormsg
, strerror(ENOMEM
)) != NULL
) {
1488 std::clog
<< _("No apport report written because the error message indicates a out of memory error") << std::endl
;
1492 // do not report dpkg I/O errors
1493 // XXX - this message is localized, but this only matches the English version. This is better than nothing.
1494 if(strstr(errormsg
, "short read in buffer_copy (")) {
1495 std::clog
<< _("No apport report written because the error message indicates a dpkg I/O error") << std::endl
;
1499 // get the pkgname and reportfile
1500 pkgname
= flNotDir(pkgpath
);
1501 pos
= pkgname
.find('_');
1502 if(pos
!= string::npos
)
1503 pkgname
= pkgname
.substr(0, pos
);
1505 // find the package versin and source package name
1506 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
1507 if (Pkg
.end() == true)
1509 pkgCache::VerIterator Ver
= Cache
.GetCandidateVer(Pkg
);
1510 if (Ver
.end() == true)
1512 pkgver
= Ver
.VerStr() == NULL
? "unknown" : Ver
.VerStr();
1513 pkgRecords
Recs(Cache
);
1514 pkgRecords::Parser
&Parse
= Recs
.Lookup(Ver
.FileList());
1515 srcpkgname
= Parse
.SourcePkg();
1516 if(srcpkgname
.empty())
1517 srcpkgname
= pkgname
;
1519 // if the file exists already, we check:
1520 // - if it was reported already (touched by apport).
1521 // If not, we do nothing, otherwise
1522 // we overwrite it. This is the same behaviour as apport
1523 // - if we have a report with the same pkgversion already
1525 reportfile
= flCombine("/var/crash",pkgname
+".0.crash");
1526 if(FileExists(reportfile
))
1531 // check atime/mtime
1532 stat(reportfile
.c_str(), &buf
);
1533 if(buf
.st_mtime
> buf
.st_atime
)
1536 // check if the existing report is the same version
1537 report
= fopen(reportfile
.c_str(),"r");
1538 while(fgets(strbuf
, sizeof(strbuf
), report
) != NULL
)
1540 if(strstr(strbuf
,"Package:") == strbuf
)
1542 char pkgname
[255], version
[255];
1543 if(sscanf(strbuf
, "Package: %s %s", pkgname
, version
) == 2)
1544 if(strcmp(pkgver
.c_str(), version
) == 0)
1554 // now write the report
1555 arch
= _config
->Find("APT::Architecture");
1556 report
= fopen(reportfile
.c_str(),"w");
1559 if(_config
->FindB("DPkgPM::InitialReportOnly",false) == true)
1560 chmod(reportfile
.c_str(), 0);
1562 chmod(reportfile
.c_str(), 0600);
1563 fprintf(report
, "ProblemType: Package\n");
1564 fprintf(report
, "Architecture: %s\n", arch
.c_str());
1565 time_t now
= time(NULL
);
1566 fprintf(report
, "Date: %s" , ctime(&now
));
1567 fprintf(report
, "Package: %s %s\n", pkgname
.c_str(), pkgver
.c_str());
1568 fprintf(report
, "SourcePackage: %s\n", srcpkgname
.c_str());
1569 fprintf(report
, "ErrorMessage:\n %s\n", errormsg
);
1571 // ensure that the log is flushed
1573 fflush(d
->term_out
);
1575 // attach terminal log it if we have it
1576 string logfile_name
= _config
->FindFile("Dir::Log::Terminal");
1577 if (!logfile_name
.empty())
1582 fprintf(report
, "DpkgTerminalLog:\n");
1583 log
= fopen(logfile_name
.c_str(),"r");
1586 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1587 fprintf(report
, " %s", buf
);
1593 const char *ops_str
[] = {"Install", "Configure","Remove","Purge"};
1594 fprintf(report
, "AptOrdering:\n");
1595 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
1596 fprintf(report
, " %s: %s\n", (*I
).Pkg
.Name(), ops_str
[(*I
).Op
]);
1598 // attach dmesg log (to learn about segfaults)
1599 if (FileExists("/bin/dmesg"))
1604 fprintf(report
, "Dmesg:\n");
1605 log
= popen("/bin/dmesg","r");
1608 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1609 fprintf(report
, " %s", buf
);
1614 // attach df -l log (to learn about filesystem status)
1615 if (FileExists("/bin/df"))
1620 fprintf(report
, "Df:\n");
1621 log
= popen("/bin/df -l","r");
1624 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1625 fprintf(report
, " %s", buf
);