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 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
127 // ---------------------------------------------------------------------
129 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
130 : pkgPackageManager(Cache
), PackagesDone(0), PackagesTotal(0)
132 d
= new pkgDPkgPMPrivate();
135 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
136 // ---------------------------------------------------------------------
138 pkgDPkgPM::~pkgDPkgPM()
143 // DPkgPM::Install - Install a package /*{{{*/
144 // ---------------------------------------------------------------------
145 /* Add an install operation to the sequence list */
146 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
148 if (File
.empty() == true || Pkg
.end() == true)
149 return _error
->Error("Internal Error, No file name for %s",Pkg
.Name());
151 // If the filename string begins with DPkg::Chroot-Directory, return the
152 // substr that is within the chroot so dpkg can access it.
153 string
const chrootdir
= _config
->FindDir("DPkg::Chroot-Directory","/");
154 if (chrootdir
!= "/" && File
.find(chrootdir
) == 0)
156 size_t len
= chrootdir
.length();
157 if (chrootdir
.at(len
- 1) == '/')
159 List
.push_back(Item(Item::Install
,Pkg
,File
.substr(len
)));
162 List
.push_back(Item(Item::Install
,Pkg
,File
));
167 // DPkgPM::Configure - Configure a package /*{{{*/
168 // ---------------------------------------------------------------------
169 /* Add a configure operation to the sequence list */
170 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
172 if (Pkg
.end() == true)
175 List
.push_back(Item(Item::Configure
, Pkg
));
177 // Use triggers for config calls if we configure "smart"
178 // as otherwise Pre-Depends will not be satisfied, see #526774
179 if (_config
->FindB("DPkg::TriggersPending", false) == true)
180 List
.push_back(Item(Item::TriggersPending
, PkgIterator()));
185 // DPkgPM::Remove - Remove a package /*{{{*/
186 // ---------------------------------------------------------------------
187 /* Add a remove operation to the sequence list */
188 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
190 if (Pkg
.end() == true)
194 List
.push_back(Item(Item::Purge
,Pkg
));
196 List
.push_back(Item(Item::Remove
,Pkg
));
200 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
201 // ---------------------------------------------------------------------
202 /* This is part of the helper script communication interface, it sends
203 very complete information down to the other end of the pipe.*/
204 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
206 fprintf(F
,"VERSION 2\n");
208 /* Write out all of the configuration directives by walking the
209 configuration tree */
210 const Configuration::Item
*Top
= _config
->Tree(0);
213 if (Top
->Value
.empty() == false)
216 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
217 QuoteString(Top
->Value
,"\n").c_str());
226 while (Top
!= 0 && Top
->Next
== 0)
233 // Write out the package actions in order.
234 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
236 if(I
->Pkg
.end() == true)
239 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
241 fprintf(F
,"%s ",I
->Pkg
.Name());
243 if (I
->Pkg
->CurrentVer
== 0)
246 fprintf(F
,"%s ",I
->Pkg
.CurrentVer().VerStr());
248 // Show the compare operator
250 if (S
.InstallVer
!= 0)
253 if (I
->Pkg
->CurrentVer
!= 0)
254 Comp
= S
.InstVerIter(Cache
).CompareVer(I
->Pkg
.CurrentVer());
261 fprintf(F
,"%s ",S
.InstVerIter(Cache
).VerStr());
266 // Show the filename/operation
267 if (I
->Op
== Item::Install
)
270 if (I
->File
[0] != '/')
271 fprintf(F
,"**ERROR**\n");
273 fprintf(F
,"%s\n",I
->File
.c_str());
275 if (I
->Op
== Item::Configure
)
276 fprintf(F
,"**CONFIGURE**\n");
277 if (I
->Op
== Item::Remove
||
278 I
->Op
== Item::Purge
)
279 fprintf(F
,"**REMOVE**\n");
287 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
288 // ---------------------------------------------------------------------
289 /* This looks for a list of scripts to run from the configuration file
290 each one is run and is fed on standard input a list of all .deb files
291 that are due to be installed. */
292 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
294 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
295 if (Opts
== 0 || Opts
->Child
== 0)
299 unsigned int Count
= 1;
300 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
302 if (Opts
->Value
.empty() == true)
305 // Determine the protocol version
306 string OptSec
= Opts
->Value
;
307 string::size_type Pos
;
308 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
309 Pos
= OptSec
.length();
310 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
312 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
316 if (pipe(Pipes
) != 0)
317 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
318 SetCloseExec(Pipes
[0],true);
319 SetCloseExec(Pipes
[1],true);
321 // Purified Fork for running the script
322 pid_t Process
= ExecFork();
326 dup2(Pipes
[0],STDIN_FILENO
);
327 SetCloseExec(STDOUT_FILENO
,false);
328 SetCloseExec(STDIN_FILENO
,false);
329 SetCloseExec(STDERR_FILENO
,false);
331 if (_config
->FindDir("DPkg::Chroot-Directory","/") != "/")
333 std::cerr
<< "Chrooting into "
334 << _config
->FindDir("DPkg::Chroot-Directory")
336 if (chroot(_config
->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
343 Args
[2] = Opts
->Value
.c_str();
345 execv(Args
[0],(char **)Args
);
349 FILE *F
= fdopen(Pipes
[1],"w");
351 return _error
->Errno("fdopen","Faild to open new FD");
353 // Feed it the filenames.
356 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
358 // Only deal with packages to be installed from .deb
359 if (I
->Op
!= Item::Install
)
363 if (I
->File
[0] != '/')
366 /* Feed the filename of each package that is pending install
368 fprintf(F
,"%s\n",I
->File
.c_str());
378 // Clean up the sub process
379 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
380 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
386 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
387 // ---------------------------------------------------------------------
390 void pkgDPkgPM::DoStdin(int master
)
392 unsigned char input_buf
[256] = {0,};
393 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
395 write(master
, input_buf
, len
);
397 d
->stdin_is_dev_null
= true;
400 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
401 // ---------------------------------------------------------------------
403 * read the terminal pty and write log
405 void pkgDPkgPM::DoTerminalPty(int master
)
407 unsigned char term_buf
[1024] = {0,0, };
409 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
410 if(len
== -1 && errno
== EIO
)
412 // this happens when the child is about to exit, we
413 // give it time to actually exit, otherwise we run
414 // into a race so we sleep for half a second.
415 struct timespec sleepfor
= { 0, 500000000 };
416 nanosleep(&sleepfor
, NULL
);
421 write(1, term_buf
, len
);
423 fwrite(term_buf
, len
, sizeof(char), d
->term_out
);
426 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
427 // ---------------------------------------------------------------------
430 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd
, char *line
)
432 bool const Debug
= _config
->FindB("Debug::pkgDPkgProgressReporting",false);
433 // the status we output
434 ostringstream status
;
437 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
440 /* dpkg sends strings like this:
441 'status: <pkg>: <pkg qstate>'
442 errors look like this:
443 '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
444 and conffile-prompt like this
445 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
447 Newer versions of dpkg sent also:
448 'processing: install: pkg'
449 'processing: configure: pkg'
450 'processing: remove: pkg'
451 'processing: purge: pkg'
452 'processing: disappear: pkg'
453 'processing: trigproc: trigger'
457 // dpkg sends multiline error messages sometimes (see
458 // #374195 for a example. we should support this by
459 // either patching dpkg to not send multiline over the
460 // statusfd or by rewriting the code here to deal with
461 // it. for now we just ignore it and not crash
462 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
463 if( list
[0] == NULL
|| list
[1] == NULL
|| list
[2] == NULL
)
466 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
469 const char* const pkg
= list
[1];
470 const char* action
= _strstrip(list
[2]);
472 // 'processing' from dpkg looks like
473 // 'processing: action: pkg'
474 if(strncmp(list
[0], "processing", strlen("processing")) == 0)
477 const char* const pkg_or_trigger
= _strstrip(list
[2]);
478 action
= _strstrip( list
[1]);
479 const std::pair
<const char *, const char *> * const iter
=
480 std::find_if(PackageProcessingOpsBegin
,
481 PackageProcessingOpsEnd
,
482 MatchProcessingOp(action
));
483 if(iter
== PackageProcessingOpsEnd
)
486 std::clog
<< "ignoring unknown action: " << action
<< std::endl
;
489 snprintf(s
, sizeof(s
), _(iter
->second
), pkg_or_trigger
);
491 status
<< "pmstatus:" << pkg_or_trigger
492 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
496 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
498 std::clog
<< "send: '" << status
.str() << "'" << endl
;
500 if (strncmp(action
, "disappear", strlen("disappear")) == 0)
501 handleDisappearAction(pkg_or_trigger
);
505 if(strncmp(action
,"error",strlen("error")) == 0)
507 // urgs, sometime has ":" in its error string so that we
508 // end up with the error message split between list[3]
509 // and list[4], e.g. the message:
510 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
512 if( list
[4] != NULL
)
513 list
[3][strlen(list
[3])] = ':';
515 status
<< "pmerror:" << list
[1]
516 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
520 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
522 std::clog
<< "send: '" << status
.str() << "'" << endl
;
524 WriteApportReport(list
[1], list
[3]);
527 else if(strncmp(action
,"conffile",strlen("conffile")) == 0)
529 status
<< "pmconffile:" << list
[1]
530 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
534 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
536 std::clog
<< "send: '" << status
.str() << "'" << endl
;
540 vector
<struct DpkgState
> const &states
= PackageOps
[pkg
];
541 const char *next_action
= NULL
;
542 if(PackageOpsDone
[pkg
] < states
.size())
543 next_action
= states
[PackageOpsDone
[pkg
]].state
;
544 // check if the package moved to the next dpkg state
545 if(next_action
&& (strcmp(action
, next_action
) == 0))
547 // only read the translation if there is actually a next
549 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
551 snprintf(s
, sizeof(s
), translation
, pkg
);
553 // we moved from one dpkg state to a new one, report that
554 PackageOpsDone
[pkg
]++;
556 // build the status str
557 status
<< "pmstatus:" << pkg
558 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
562 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
564 std::clog
<< "send: '" << status
.str() << "'" << endl
;
567 std::clog
<< "(parsed from dpkg) pkg: " << pkg
568 << " action: " << action
<< endl
;
571 // DPkgPM::handleDisappearAction /*{{{*/
572 void pkgDPkgPM::handleDisappearAction(string
const &pkgname
)
574 // record the package name for display and stuff later
575 disappearedPkgs
.insert(pkgname
);
577 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
578 if (unlikely(Pkg
.end() == true))
580 // the disappeared package was auto-installed - nothing to do
581 if ((Cache
[Pkg
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
583 pkgCache::VerIterator PkgVer
= Cache
[Pkg
].InstVerIter(Cache
);
584 if (unlikely(PkgVer
.end() == true))
586 /* search in the list of dependencies for (Pre)Depends,
587 check if this dependency has a Replaces on our package
588 and if so transfer the manual installed flag to it */
589 for (pkgCache::DepIterator Dep
= PkgVer
.DependsList(); Dep
.end() != true; ++Dep
)
591 if (Dep
->Type
!= pkgCache::Dep::Depends
&&
592 Dep
->Type
!= pkgCache::Dep::PreDepends
)
594 pkgCache::PkgIterator Tar
= Dep
.TargetPkg();
595 if (unlikely(Tar
.end() == true))
597 // the package is already marked as manual
598 if ((Cache
[Tar
].Flags
& pkgCache::Flag::Auto
) != pkgCache::Flag::Auto
)
600 pkgCache::VerIterator TarVer
= Cache
[Tar
].InstVerIter(Cache
);
601 if (TarVer
.end() == true)
603 for (pkgCache::DepIterator Rep
= TarVer
.DependsList(); Rep
.end() != true; ++Rep
)
605 if (Rep
->Type
!= pkgCache::Dep::Replaces
)
607 if (Pkg
!= Rep
.TargetPkg())
609 // okay, they are strongly connected - transfer manual-bit
611 std::clog
<< "transfer manual-bit from disappeared »" << pkgname
<< "« to »" << Tar
.FullName() << "«" << std::endl
;
612 Cache
[Tar
].Flags
&= ~Flag::Auto
;
618 // DPkgPM::DoDpkgStatusFd /*{{{*/
619 // ---------------------------------------------------------------------
622 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
, int OutStatusFd
)
627 len
=read(statusfd
, &d
->dpkgbuf
[d
->dpkgbuf_pos
], sizeof(d
->dpkgbuf
)-d
->dpkgbuf_pos
);
628 d
->dpkgbuf_pos
+= len
;
632 // process line by line if we have a buffer
634 while((q
=(char*)memchr(p
, '\n', d
->dpkgbuf
+d
->dpkgbuf_pos
-p
)) != NULL
)
637 ProcessDpkgStatusLine(OutStatusFd
, p
);
638 p
=q
+1; // continue with next line
641 // now move the unprocessed bits (after the final \n that is now a 0x0)
642 // to the start and update d->dpkgbuf_pos
643 p
= (char*)memrchr(d
->dpkgbuf
, 0, d
->dpkgbuf_pos
);
647 // we are interessted in the first char *after* 0x0
650 // move the unprocessed tail to the start and update pos
651 memmove(d
->dpkgbuf
, p
, p
-d
->dpkgbuf
);
652 d
->dpkgbuf_pos
= d
->dpkgbuf
+d
->dpkgbuf_pos
-p
;
655 // DPkgPM::WriteHistoryTag /*{{{*/
656 void pkgDPkgPM::WriteHistoryTag(string
const &tag
, string value
)
658 size_t const length
= value
.length();
661 // poor mans rstrip(", ")
662 if (value
[length
-2] == ',' && value
[length
-1] == ' ')
663 value
.erase(length
- 2, 2);
664 fprintf(d
->history_out
, "%s: %s\n", tag
.c_str(), value
.c_str());
666 // DPkgPM::OpenLog /*{{{*/
667 bool pkgDPkgPM::OpenLog()
669 string
const logdir
= _config
->FindDir("Dir::Log");
670 if(CreateAPTDirectoryIfNeeded(logdir
, logdir
) == false)
671 // FIXME: use a better string after freeze
672 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
676 time_t const t
= time(NULL
);
677 struct tm
const * const tmp
= localtime(&t
);
678 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
681 string
const logfile_name
= flCombine(logdir
,
682 _config
->Find("Dir::Log::Terminal"));
683 if (!logfile_name
.empty())
685 d
->term_out
= fopen(logfile_name
.c_str(),"a");
686 if (d
->term_out
== NULL
)
687 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name
.c_str());
688 setvbuf(d
->term_out
, NULL
, _IONBF
, 0);
689 SetCloseExec(fileno(d
->term_out
), true);
692 pw
= getpwnam("root");
693 gr
= getgrnam("adm");
694 if (pw
!= NULL
&& gr
!= NULL
)
695 chown(logfile_name
.c_str(), pw
->pw_uid
, gr
->gr_gid
);
696 chmod(logfile_name
.c_str(), 0644);
697 fprintf(d
->term_out
, "\nLog started: %s\n", timestr
);
700 // write your history
701 string
const history_name
= flCombine(logdir
,
702 _config
->Find("Dir::Log::History"));
703 if (!history_name
.empty())
705 d
->history_out
= fopen(history_name
.c_str(),"a");
706 if (d
->history_out
== NULL
)
707 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), history_name
.c_str());
708 chmod(history_name
.c_str(), 0644);
709 fprintf(d
->history_out
, "\nStart-Date: %s\n", timestr
);
710 string remove
, purge
, install
, reinstall
, upgrade
, downgrade
;
711 for (pkgCache::PkgIterator I
= Cache
.PkgBegin(); I
.end() == false; ++I
)
713 enum { CANDIDATE
, CANDIDATE_AUTO
, CURRENT_CANDIDATE
, CURRENT
} infostring
;
715 #define HISTORYINFO(X, Y) { line = &X; infostring = Y; }
716 if (Cache
[I
].NewInstall() == true)
717 HISTORYINFO(install
, CANDIDATE_AUTO
)
718 else if (Cache
[I
].ReInstall() == true)
719 HISTORYINFO(reinstall
, CANDIDATE
)
720 else if (Cache
[I
].Upgrade() == true)
721 HISTORYINFO(upgrade
, CURRENT_CANDIDATE
)
722 else if (Cache
[I
].Downgrade() == true)
723 HISTORYINFO(downgrade
, CURRENT_CANDIDATE
)
724 else if (Cache
[I
].Delete() == true)
725 HISTORYINFO((Cache
[I
].Purge() ? purge
: remove
), CURRENT
)
729 line
->append(I
.FullName(false)).append(" (");
730 switch (infostring
) {
731 case CANDIDATE
: line
->append(Cache
[I
].CandVersion
); break;
733 line
->append(Cache
[I
].CandVersion
);
734 if ((Cache
[I
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
735 line
->append(", automatic");
737 case CURRENT_CANDIDATE
: line
->append(Cache
[I
].CurVersion
).append(", ").append(Cache
[I
].CandVersion
); break;
738 case CURRENT
: line
->append(Cache
[I
].CurVersion
); break;
742 if (_config
->Exists("Commandline::AsString") == true)
743 WriteHistoryTag("Commandline", _config
->Find("Commandline::AsString"));
744 WriteHistoryTag("Install", install
);
745 WriteHistoryTag("Reinstall", reinstall
);
746 WriteHistoryTag("Upgrade", upgrade
);
747 WriteHistoryTag("Downgrade",downgrade
);
748 WriteHistoryTag("Remove",remove
);
749 WriteHistoryTag("Purge",purge
);
750 fflush(d
->history_out
);
756 // DPkg::CloseLog /*{{{*/
757 bool pkgDPkgPM::CloseLog()
760 time_t t
= time(NULL
);
761 struct tm
*tmp
= localtime(&t
);
762 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
766 fprintf(d
->term_out
, "Log ended: ");
767 fprintf(d
->term_out
, "%s", timestr
);
768 fprintf(d
->term_out
, "\n");
775 if (disappearedPkgs
.empty() == false)
778 for (std::set
<std::string
>::const_iterator d
= disappearedPkgs
.begin();
779 d
!= disappearedPkgs
.end(); ++d
)
781 pkgCache::PkgIterator P
= Cache
.FindPkg(*d
);
782 disappear
.append(*d
);
784 disappear
.append(", ");
786 disappear
.append(" (").append(Cache
[P
].CurVersion
).append("), ");
788 WriteHistoryTag("Disappeared", disappear
);
790 if (d
->dpkg_error
.empty() == false)
791 fprintf(d
->history_out
, "Error: %s\n", d
->dpkg_error
.c_str());
792 fprintf(d
->history_out
, "End-Date: %s\n", timestr
);
793 fclose(d
->history_out
);
795 d
->history_out
= NULL
;
801 // This implements a racy version of pselect for those architectures
802 // that don't have a working implementation.
803 // FIXME: Probably can be removed on Lenny+1
804 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
805 fd_set
*exceptfds
, const struct timespec
*timeout
,
806 const sigset_t
*sigmask
)
812 tv
.tv_sec
= timeout
->tv_sec
;
813 tv
.tv_usec
= timeout
->tv_nsec
/1000;
815 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
816 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
817 sigprocmask(SIG_SETMASK
, &origmask
, 0);
821 // DPkgPM::Go - Run the sequence /*{{{*/
822 // ---------------------------------------------------------------------
823 /* This globs the operations and calls dpkg
825 * If it is called with "OutStatusFd" set to a valid file descriptor
826 * apt will report the install progress over this fd. It maps the
827 * dpkg states a package goes through to human readable (and i10n-able)
828 * names and calculates a percentage for each step.
830 bool pkgDPkgPM::Go(int OutStatusFd
)
835 sigset_t original_sigmask
;
837 unsigned int const MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
838 unsigned int const MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
839 bool const NoTriggers
= _config
->FindB("DPkg::NoTriggers", false);
841 if (RunScripts("DPkg::Pre-Invoke") == false)
844 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
847 // support subpressing of triggers processing for special
848 // cases like d-i that runs the triggers handling manually
849 bool const SmartConf
= (_config
->Find("PackageManager::Configure", "all") != "all");
850 bool const TriggersPending
= _config
->FindB("DPkg::TriggersPending", false);
851 if (_config
->FindB("DPkg::ConfigurePending", SmartConf
) == true)
852 List
.push_back(Item(Item::ConfigurePending
, PkgIterator()));
854 // map the dpkg states to the operations that are performed
855 // (this is sorted in the same way as Item::Ops)
856 static const struct DpkgState DpkgStatesOpMap
[][7] = {
859 {"half-installed", N_("Preparing %s")},
860 {"unpacked", N_("Unpacking %s") },
863 // Configure operation
865 {"unpacked",N_("Preparing to configure %s") },
866 {"half-configured", N_("Configuring %s") },
867 { "installed", N_("Installed %s")},
872 {"half-configured", N_("Preparing for removal of %s")},
873 {"half-installed", N_("Removing %s")},
874 {"config-files", N_("Removed %s")},
879 {"config-files", N_("Preparing to completely remove %s")},
880 {"not-installed", N_("Completely removed %s")},
885 // init the PackageOps map, go over the list of packages that
886 // that will be [installed|configured|removed|purged] and add
887 // them to the PackageOps map (the dpkg states it goes through)
888 // and the PackageOpsTranslations (human readable strings)
889 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end(); ++I
)
891 if((*I
).Pkg
.end() == true)
894 string
const name
= (*I
).Pkg
.Name();
895 PackageOpsDone
[name
] = 0;
896 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; ++i
)
898 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
903 d
->stdin_is_dev_null
= false;
908 // Generate the base argument list for dpkg
909 std::vector
<const char *> Args
;
910 unsigned long StartSize
= 0;
911 string
const Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
912 Args
.push_back(Tmp
.c_str());
913 StartSize
+= Tmp
.length();
915 // Stick in any custom dpkg options
916 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
920 for (; Opts
!= 0; Opts
= Opts
->Next
)
922 if (Opts
->Value
.empty() == true)
924 Args
.push_back(Opts
->Value
.c_str());
925 StartSize
+= Opts
->Value
.length();
928 size_t const BaseArgs
= Args
.size();
930 // this loop is runs once per operation
931 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();)
933 // Do all actions with the same Op in one run
934 vector
<Item
>::const_iterator J
= I
;
935 if (TriggersPending
== true)
936 for (; J
!= List
.end(); ++J
)
940 if (J
->Op
!= Item::TriggersPending
)
942 vector
<Item
>::const_iterator T
= J
+ 1;
943 if (T
!= List
.end() && T
->Op
== I
->Op
)
948 for (; J
!= List
.end() && J
->Op
== I
->Op
; ++J
)
951 // keep track of allocated strings for multiarch package names
952 std::vector
<char *> Packages
;
954 // start with the baseset of arguments
955 unsigned long Size
= StartSize
;
956 Args
.erase(Args
.begin() + BaseArgs
, Args
.end());
958 // Now check if we are within the MaxArgs limit
960 // this code below is problematic, because it may happen that
961 // the argument list is split in a way that A depends on B
962 // and they are in the same "--configure A B" run
963 // - with the split they may now be configured in different
964 // runs, using Immediate-Configure-All can help prevent this.
965 if (J
- I
> (signed)MaxArgs
)
968 Args
.reserve(MaxArgs
+ 10);
972 Args
.reserve((J
- I
) + 10);
979 #define ADDARG(X) Args.push_back(X); Size += strlen(X)
980 #define ADDARGC(X) Args.push_back(X); Size += sizeof(X) - 1
982 ADDARGC("--status-fd");
983 char status_fd_buf
[20];
984 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
985 ADDARG(status_fd_buf
);
986 unsigned long const Op
= I
->Op
;
991 ADDARGC("--force-depends");
992 ADDARGC("--force-remove-essential");
997 ADDARGC("--force-depends");
998 ADDARGC("--force-remove-essential");
1002 case Item::Configure
:
1003 ADDARGC("--configure");
1006 case Item::ConfigurePending
:
1007 ADDARGC("--configure");
1008 ADDARGC("--pending");
1011 case Item::TriggersPending
:
1012 ADDARGC("--triggers-only");
1013 ADDARGC("--pending");
1017 ADDARGC("--unpack");
1018 ADDARGC("--auto-deconfigure");
1022 if (NoTriggers
== true && I
->Op
!= Item::TriggersPending
&&
1023 I
->Op
!= Item::ConfigurePending
)
1025 ADDARGC("--no-triggers");
1029 // Write in the file or package names
1030 if (I
->Op
== Item::Install
)
1032 for (;I
!= J
&& Size
< MaxArgBytes
; ++I
)
1034 if (I
->File
[0] != '/')
1035 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
1036 Args
.push_back(I
->File
.c_str());
1037 Size
+= I
->File
.length();
1042 string
const nativeArch
= _config
->Find("APT::Architecture");
1043 unsigned long const oldSize
= I
->Op
== Item::Configure
? Size
: 0;
1044 for (;I
!= J
&& Size
< MaxArgBytes
; ++I
)
1046 if((*I
).Pkg
.end() == true)
1048 if (I
->Op
== Item::Configure
&& disappearedPkgs
.find(I
->Pkg
.Name()) != disappearedPkgs
.end())
1050 if (I
->Pkg
.Arch() == nativeArch
|| !strcmp(I
->Pkg
.Arch(), "all"))
1052 char const * const name
= I
->Pkg
.Name();
1057 char * const fullname
= strdup(I
->Pkg
.FullName(false).c_str());
1058 Packages
.push_back(fullname
);
1062 // skip configure action if all sheduled packages disappeared
1063 if (oldSize
== Size
)
1070 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
1072 for (std::vector
<const char *>::const_iterator a
= Args
.begin();
1073 a
!= Args
.end(); ++a
)
1078 Args
.push_back(NULL
);
1084 /* Mask off sig int/quit. We do this because dpkg also does when
1085 it forks scripts. What happens is that when you hit ctrl-c it sends
1086 it to all processes in the group. Since dpkg ignores the signal
1087 it doesn't die but we do! So we must also ignore it */
1088 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
1089 sighandler_t old_SIGINT
= signal(SIGINT
,SigINT
);
1091 // Check here for any SIGINT
1092 if (pkgPackageManager::SigINTStop
&& (Op
== Item::Remove
|| Op
== Item::Purge
|| Op
== Item::Install
))
1096 // ignore SIGHUP as well (debian #463030)
1097 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
1104 // if tcgetattr does not return zero there was a error
1105 // and we do not do any pty magic
1106 if (tcgetattr(0, &tt
) == 0)
1108 ioctl(0, TIOCGWINSZ
, (char *)&win
);
1109 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
1111 const char *s
= _("Can not write log, openpty() "
1112 "failed (/dev/pts not mounted?)\n");
1113 fprintf(stderr
, "%s",s
);
1115 fprintf(d
->term_out
, "%s",s
);
1116 master
= slave
= -1;
1121 rtt
.c_lflag
&= ~ECHO
;
1122 rtt
.c_lflag
|= ISIG
;
1123 // block SIGTTOU during tcsetattr to prevent a hang if
1124 // the process is a member of the background process group
1125 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
1126 sigemptyset(&sigmask
);
1127 sigaddset(&sigmask
, SIGTTOU
);
1128 sigprocmask(SIG_BLOCK
,&sigmask
, &original_sigmask
);
1129 tcsetattr(0, TCSAFLUSH
, &rtt
);
1130 sigprocmask(SIG_SETMASK
, &original_sigmask
, 0);
1135 _config
->Set("APT::Keep-Fds::",fd
[1]);
1136 // send status information that we are about to fork dpkg
1137 if(OutStatusFd
> 0) {
1138 ostringstream status
;
1139 status
<< "pmstatus:dpkg-exec:"
1140 << (PackagesDone
/float(PackagesTotal
)*100.0)
1141 << ":" << _("Running dpkg")
1143 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
1147 // This is the child
1150 if(slave
>= 0 && master
>= 0)
1153 ioctl(slave
, TIOCSCTTY
, 0);
1160 close(fd
[0]); // close the read end of the pipe
1162 if (_config
->FindDir("DPkg::Chroot-Directory","/") != "/")
1164 std::cerr
<< "Chrooting into "
1165 << _config
->FindDir("DPkg::Chroot-Directory")
1167 if (chroot(_config
->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
1171 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
1174 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
1177 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
1180 // Discard everything in stdin before forking dpkg
1181 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
1184 while (read(STDIN_FILENO
,&dummy
,1) == 1);
1186 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
1190 /* No Job Control Stop Env is a magic dpkg var that prevents it
1191 from using sigstop */
1192 putenv((char *)"DPKG_NO_TSTP=yes");
1193 execvp(Args
[0], (char**) &Args
[0]);
1194 cerr
<< "Could not exec dpkg!" << endl
;
1199 if (_config
->FindB("DPkg::UseIoNice", false) == true)
1202 // clear the Keep-Fd again
1203 _config
->Clear("APT::Keep-Fds",fd
[1]);
1208 // we read from dpkg here
1209 int const _dpkgin
= fd
[0];
1210 close(fd
[1]); // close the write end of the pipe
1216 sigemptyset(&sigmask
);
1217 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
1219 /* free vectors (and therefore memory) as we don't need the included data anymore */
1220 for (std::vector
<char *>::const_iterator p
= Packages
.begin();
1221 p
!= Packages
.end(); ++p
)
1225 // the result of the waitpid call
1228 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
1230 // FIXME: move this to a function or something, looks ugly here
1231 // error handling, waitpid returned -1
1234 RunScripts("DPkg::Post-Invoke");
1236 // Restore sig int/quit
1237 signal(SIGQUIT
,old_SIGQUIT
);
1238 signal(SIGINT
,old_SIGINT
);
1240 signal(SIGHUP
,old_SIGHUP
);
1241 return _error
->Errno("waitpid","Couldn't wait for subprocess");
1244 // wait for input or output here
1246 if (master
>= 0 && !d
->stdin_is_dev_null
)
1248 FD_SET(_dpkgin
, &rfds
);
1250 FD_SET(master
, &rfds
);
1253 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
1254 &tv
, &original_sigmask
);
1255 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
1256 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
1257 NULL
, &tv
, &original_sigmask
);
1258 if (select_ret
== 0)
1260 else if (select_ret
< 0 && errno
== EINTR
)
1262 else if (select_ret
< 0)
1264 perror("select() returned error");
1268 if(master
>= 0 && FD_ISSET(master
, &rfds
))
1269 DoTerminalPty(master
);
1270 if(master
>= 0 && FD_ISSET(0, &rfds
))
1272 if(FD_ISSET(_dpkgin
, &rfds
))
1273 DoDpkgStatusFd(_dpkgin
, OutStatusFd
);
1277 // Restore sig int/quit
1278 signal(SIGQUIT
,old_SIGQUIT
);
1279 signal(SIGINT
,old_SIGINT
);
1281 signal(SIGHUP
,old_SIGHUP
);
1285 tcsetattr(0, TCSAFLUSH
, &tt
);
1289 // Check for an error code.
1290 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
1292 // if it was set to "keep-dpkg-runing" then we won't return
1293 // here but keep the loop going and just report it as a error
1295 bool const stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
1298 RunScripts("DPkg::Post-Invoke");
1300 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
1301 strprintf(d
->dpkg_error
, "Sub-process %s received a segmentation fault.",Args
[0]);
1302 else if (WIFEXITED(Status
) != 0)
1303 strprintf(d
->dpkg_error
, "Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
1305 strprintf(d
->dpkg_error
, "Sub-process %s exited unexpectedly",Args
[0]);
1307 if(d
->dpkg_error
.size() > 0)
1308 _error
->Error("%s", d
->dpkg_error
.c_str());
1319 if (pkgPackageManager::SigINTStop
)
1320 _error
->Warning(_("Operation was interrupted before it could finish"));
1322 if (RunScripts("DPkg::Post-Invoke") == false)
1325 if (_config
->FindB("Debug::pkgDPkgPM",false) == false)
1327 std::string
const oldpkgcache
= _config
->FindFile("Dir::cache::pkgcache");
1328 if (oldpkgcache
.empty() == false && RealFileExists(oldpkgcache
) == true &&
1329 unlink(oldpkgcache
.c_str()) == 0)
1331 std::string
const srcpkgcache
= _config
->FindFile("Dir::cache::srcpkgcache");
1332 if (srcpkgcache
.empty() == false && RealFileExists(srcpkgcache
) == true)
1334 _error
->PushToStack();
1335 pkgCacheFile CacheFile
;
1336 CacheFile
.BuildCaches(NULL
, true);
1337 _error
->RevertToStack();
1342 Cache
.writeStateFile(NULL
);
1346 void SigINT(int sig
) {
1347 if (_config
->FindB("APT::Immediate-Configure-All",false))
1348 pkgPackageManager::SigINTStop
= true;
1351 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1352 // ---------------------------------------------------------------------
1354 void pkgDPkgPM::Reset()
1356 List
.erase(List
.begin(),List
.end());
1359 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1360 // ---------------------------------------------------------------------
1362 void pkgDPkgPM::WriteApportReport(const char *pkgpath
, const char *errormsg
)
1364 string pkgname
, reportfile
, srcpkgname
, pkgver
, arch
;
1365 string::size_type pos
;
1368 if (_config
->FindB("Dpkg::ApportFailureReport", false) == false)
1370 std::clog
<< "configured to not write apport reports" << std::endl
;
1374 // only report the first errors
1375 if(pkgFailures
> _config
->FindI("APT::Apport::MaxReports", 3))
1377 std::clog
<< _("No apport report written because MaxReports is reached already") << std::endl
;
1381 // check if its not a follow up error
1382 const char *needle
= dgettext("dpkg", "dependency problems - leaving unconfigured");
1383 if(strstr(errormsg
, needle
) != NULL
) {
1384 std::clog
<< _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl
;
1388 // do not report disk-full failures
1389 if(strstr(errormsg
, strerror(ENOSPC
)) != NULL
) {
1390 std::clog
<< _("No apport report written because the error message indicates a disk full error") << std::endl
;
1394 // do not report out-of-memory failures
1395 if(strstr(errormsg
, strerror(ENOMEM
)) != NULL
) {
1396 std::clog
<< _("No apport report written because the error message indicates a out of memory error") << std::endl
;
1400 // do not report dpkg I/O errors
1401 // XXX - this message is localized, but this only matches the English version. This is better than nothing.
1402 if(strstr(errormsg
, "short read in buffer_copy (")) {
1403 std::clog
<< _("No apport report written because the error message indicates a dpkg I/O error") << std::endl
;
1407 // get the pkgname and reportfile
1408 pkgname
= flNotDir(pkgpath
);
1409 pos
= pkgname
.find('_');
1410 if(pos
!= string::npos
)
1411 pkgname
= pkgname
.substr(0, pos
);
1413 // find the package versin and source package name
1414 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
1415 if (Pkg
.end() == true)
1417 pkgCache::VerIterator Ver
= Cache
.GetCandidateVer(Pkg
);
1418 if (Ver
.end() == true)
1420 pkgver
= Ver
.VerStr() == NULL
? "unknown" : Ver
.VerStr();
1421 pkgRecords
Recs(Cache
);
1422 pkgRecords::Parser
&Parse
= Recs
.Lookup(Ver
.FileList());
1423 srcpkgname
= Parse
.SourcePkg();
1424 if(srcpkgname
.empty())
1425 srcpkgname
= pkgname
;
1427 // if the file exists already, we check:
1428 // - if it was reported already (touched by apport).
1429 // If not, we do nothing, otherwise
1430 // we overwrite it. This is the same behaviour as apport
1431 // - if we have a report with the same pkgversion already
1433 reportfile
= flCombine("/var/crash",pkgname
+".0.crash");
1434 if(FileExists(reportfile
))
1439 // check atime/mtime
1440 stat(reportfile
.c_str(), &buf
);
1441 if(buf
.st_mtime
> buf
.st_atime
)
1444 // check if the existing report is the same version
1445 report
= fopen(reportfile
.c_str(),"r");
1446 while(fgets(strbuf
, sizeof(strbuf
), report
) != NULL
)
1448 if(strstr(strbuf
,"Package:") == strbuf
)
1450 char pkgname
[255], version
[255];
1451 if(sscanf(strbuf
, "Package: %s %s", pkgname
, version
) == 2)
1452 if(strcmp(pkgver
.c_str(), version
) == 0)
1462 // now write the report
1463 arch
= _config
->Find("APT::Architecture");
1464 report
= fopen(reportfile
.c_str(),"w");
1467 if(_config
->FindB("DPkgPM::InitialReportOnly",false) == true)
1468 chmod(reportfile
.c_str(), 0);
1470 chmod(reportfile
.c_str(), 0600);
1471 fprintf(report
, "ProblemType: Package\n");
1472 fprintf(report
, "Architecture: %s\n", arch
.c_str());
1473 time_t now
= time(NULL
);
1474 fprintf(report
, "Date: %s" , ctime(&now
));
1475 fprintf(report
, "Package: %s %s\n", pkgname
.c_str(), pkgver
.c_str());
1476 fprintf(report
, "SourcePackage: %s\n", srcpkgname
.c_str());
1477 fprintf(report
, "ErrorMessage:\n %s\n", errormsg
);
1479 // ensure that the log is flushed
1481 fflush(d
->term_out
);
1483 // attach terminal log it if we have it
1484 string logfile_name
= _config
->FindFile("Dir::Log::Terminal");
1485 if (!logfile_name
.empty())
1490 fprintf(report
, "DpkgTerminalLog:\n");
1491 log
= fopen(logfile_name
.c_str(),"r");
1494 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1495 fprintf(report
, " %s", buf
);
1501 const char *ops_str
[] = {"Install", "Configure","Remove","Purge"};
1502 fprintf(report
, "AptOrdering:\n");
1503 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
1504 fprintf(report
, " %s: %s\n", (*I
).Pkg
.Name(), ops_str
[(*I
).Op
]);
1506 // attach dmesg log (to learn about segfaults)
1507 if (FileExists("/bin/dmesg"))
1512 fprintf(report
, "Dmesg:\n");
1513 log
= popen("/bin/dmesg","r");
1516 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1517 fprintf(report
, " %s", buf
);
1522 // attach df -l log (to learn about filesystem status)
1523 if (FileExists("/bin/df"))
1528 fprintf(report
, "Df:\n");
1529 log
= popen("/bin/df -l","r");
1532 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1533 fprintf(report
, " %s", buf
);