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 ##################################################################### */
11 #include <apt-pkg/dpkgpm.h>
12 #include <apt-pkg/error.h>
13 #include <apt-pkg/configuration.h>
14 #include <apt-pkg/depcache.h>
15 #include <apt-pkg/pkgrecords.h>
16 #include <apt-pkg/strutl.h>
17 #include <apt-pkg/fileutl.h>
18 #include <apt-pkg/cachefile.h>
23 #include <sys/select.h>
25 #include <sys/types.h>
40 #include <sys/ioctl.h>
49 class pkgDPkgPMPrivate
52 pkgDPkgPMPrivate() : dpkgbuf_pos(0), term_out(NULL
), history_out(NULL
)
55 bool stdin_is_dev_null
;
56 // the buffer we use for the dpkg status-fd reading
66 // Maps the dpkg "processing" info to human readable names. Entry 0
67 // of each array is the key, entry 1 is the value.
68 const std::pair
<const char *, const char *> PackageProcessingOps
[] = {
69 std::make_pair("install", N_("Installing %s")),
70 std::make_pair("configure", N_("Configuring %s")),
71 std::make_pair("remove", N_("Removing %s")),
72 std::make_pair("purge", N_("Completely removing %s")),
73 std::make_pair("disappear", N_("Noting disappearance of %s")),
74 std::make_pair("trigproc", N_("Running post-installation trigger %s"))
77 const std::pair
<const char *, const char *> * const PackageProcessingOpsBegin
= PackageProcessingOps
;
78 const std::pair
<const char *, const char *> * const PackageProcessingOpsEnd
= PackageProcessingOps
+ sizeof(PackageProcessingOps
) / sizeof(PackageProcessingOps
[0]);
80 // Predicate to test whether an entry in the PackageProcessingOps
81 // array matches a string.
82 class MatchProcessingOp
87 MatchProcessingOp(const char *the_target
)
92 bool operator()(const std::pair
<const char *, const char *> &pair
) const
94 return strcmp(pair
.first
, target
) == 0;
99 /* helper function to ionice the given PID
101 there is no C header for ionice yet - just the syscall interface
102 so we use the binary from util-linux
107 if (!FileExists("/usr/bin/ionice"))
109 pid_t Process
= ExecFork();
113 snprintf(buf
, sizeof(buf
), "-p%d", PID
);
115 Args
[0] = "/usr/bin/ionice";
119 execv(Args
[0], (char **)Args
);
121 return ExecWait(Process
, "ionice");
124 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
125 // ---------------------------------------------------------------------
127 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
128 : pkgPackageManager(Cache
), PackagesDone(0), PackagesTotal(0)
130 d
= new pkgDPkgPMPrivate();
133 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
134 // ---------------------------------------------------------------------
136 pkgDPkgPM::~pkgDPkgPM()
141 // DPkgPM::Install - Install a package /*{{{*/
142 // ---------------------------------------------------------------------
143 /* Add an install operation to the sequence list */
144 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
146 if (File
.empty() == true || Pkg
.end() == true)
147 return _error
->Error("Internal Error, No file name for %s",Pkg
.Name());
149 // If the filename string begins with DPkg::Chroot-Directory, return the
150 // substr that is within the chroot so dpkg can access it.
151 string
const chrootdir
= _config
->FindDir("DPkg::Chroot-Directory","/");
152 if (chrootdir
!= "/" && File
.find(chrootdir
) == 0)
154 size_t len
= chrootdir
.length();
155 if (chrootdir
.at(len
- 1) == '/')
157 List
.push_back(Item(Item::Install
,Pkg
,File
.substr(len
)));
160 List
.push_back(Item(Item::Install
,Pkg
,File
));
165 // DPkgPM::Configure - Configure a package /*{{{*/
166 // ---------------------------------------------------------------------
167 /* Add a configure operation to the sequence list */
168 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
170 if (Pkg
.end() == true)
173 List
.push_back(Item(Item::Configure
, Pkg
));
175 // Use triggers for config calls if we configure "smart"
176 // as otherwise Pre-Depends will not be satisfied, see #526774
177 if (_config
->FindB("DPkg::TriggersPending", false) == true)
178 List
.push_back(Item(Item::TriggersPending
, PkgIterator()));
183 // DPkgPM::Remove - Remove a package /*{{{*/
184 // ---------------------------------------------------------------------
185 /* Add a remove operation to the sequence list */
186 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
188 if (Pkg
.end() == true)
192 List
.push_back(Item(Item::Purge
,Pkg
));
194 List
.push_back(Item(Item::Remove
,Pkg
));
198 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
199 // ---------------------------------------------------------------------
200 /* This is part of the helper script communication interface, it sends
201 very complete information down to the other end of the pipe.*/
202 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
204 fprintf(F
,"VERSION 2\n");
206 /* Write out all of the configuration directives by walking the
207 configuration tree */
208 const Configuration::Item
*Top
= _config
->Tree(0);
211 if (Top
->Value
.empty() == false)
214 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
215 QuoteString(Top
->Value
,"\n").c_str());
224 while (Top
!= 0 && Top
->Next
== 0)
231 // Write out the package actions in order.
232 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
234 if(I
->Pkg
.end() == true)
237 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
239 fprintf(F
,"%s ",I
->Pkg
.Name());
241 if (I
->Pkg
->CurrentVer
== 0)
244 fprintf(F
,"%s ",I
->Pkg
.CurrentVer().VerStr());
246 // Show the compare operator
248 if (S
.InstallVer
!= 0)
251 if (I
->Pkg
->CurrentVer
!= 0)
252 Comp
= S
.InstVerIter(Cache
).CompareVer(I
->Pkg
.CurrentVer());
259 fprintf(F
,"%s ",S
.InstVerIter(Cache
).VerStr());
264 // Show the filename/operation
265 if (I
->Op
== Item::Install
)
268 if (I
->File
[0] != '/')
269 fprintf(F
,"**ERROR**\n");
271 fprintf(F
,"%s\n",I
->File
.c_str());
273 if (I
->Op
== Item::Configure
)
274 fprintf(F
,"**CONFIGURE**\n");
275 if (I
->Op
== Item::Remove
||
276 I
->Op
== Item::Purge
)
277 fprintf(F
,"**REMOVE**\n");
285 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
286 // ---------------------------------------------------------------------
287 /* This looks for a list of scripts to run from the configuration file
288 each one is run and is fed on standard input a list of all .deb files
289 that are due to be installed. */
290 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
292 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
293 if (Opts
== 0 || Opts
->Child
== 0)
297 unsigned int Count
= 1;
298 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
300 if (Opts
->Value
.empty() == true)
303 // Determine the protocol version
304 string OptSec
= Opts
->Value
;
305 string::size_type Pos
;
306 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
307 Pos
= OptSec
.length();
308 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
310 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
314 if (pipe(Pipes
) != 0)
315 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
316 SetCloseExec(Pipes
[0],true);
317 SetCloseExec(Pipes
[1],true);
319 // Purified Fork for running the script
320 pid_t Process
= ExecFork();
324 dup2(Pipes
[0],STDIN_FILENO
);
325 SetCloseExec(STDOUT_FILENO
,false);
326 SetCloseExec(STDIN_FILENO
,false);
327 SetCloseExec(STDERR_FILENO
,false);
329 if (_config
->FindDir("DPkg::Chroot-Directory","/") != "/")
331 std::cerr
<< "Chrooting into "
332 << _config
->FindDir("DPkg::Chroot-Directory")
334 if (chroot(_config
->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
341 Args
[2] = Opts
->Value
.c_str();
343 execv(Args
[0],(char **)Args
);
347 FILE *F
= fdopen(Pipes
[1],"w");
349 return _error
->Errno("fdopen","Faild to open new FD");
351 // Feed it the filenames.
354 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
356 // Only deal with packages to be installed from .deb
357 if (I
->Op
!= Item::Install
)
361 if (I
->File
[0] != '/')
364 /* Feed the filename of each package that is pending install
366 fprintf(F
,"%s\n",I
->File
.c_str());
376 // Clean up the sub process
377 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
378 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
384 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
385 // ---------------------------------------------------------------------
388 void pkgDPkgPM::DoStdin(int master
)
390 unsigned char input_buf
[256] = {0,};
391 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
393 write(master
, input_buf
, len
);
395 d
->stdin_is_dev_null
= true;
398 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
399 // ---------------------------------------------------------------------
401 * read the terminal pty and write log
403 void pkgDPkgPM::DoTerminalPty(int master
)
405 unsigned char term_buf
[1024] = {0,0, };
407 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
408 if(len
== -1 && errno
== EIO
)
410 // this happens when the child is about to exit, we
411 // give it time to actually exit, otherwise we run
412 // into a race so we sleep for half a second.
413 struct timespec sleepfor
= { 0, 500000000 };
414 nanosleep(&sleepfor
, NULL
);
419 write(1, term_buf
, len
);
421 fwrite(term_buf
, len
, sizeof(char), d
->term_out
);
424 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
425 // ---------------------------------------------------------------------
428 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd
, char *line
)
430 bool const Debug
= _config
->FindB("Debug::pkgDPkgProgressReporting",false);
431 // the status we output
432 ostringstream status
;
435 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
438 /* dpkg sends strings like this:
439 'status: <pkg>: <pkg qstate>'
440 errors look like this:
441 '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
442 and conffile-prompt like this
443 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
445 Newer versions of dpkg sent also:
446 'processing: install: pkg'
447 'processing: configure: pkg'
448 'processing: remove: pkg'
449 'processing: purge: pkg'
450 'processing: disappear: pkg'
451 'processing: trigproc: trigger'
455 // dpkg sends multiline error messages sometimes (see
456 // #374195 for a example. we should support this by
457 // either patching dpkg to not send multiline over the
458 // statusfd or by rewriting the code here to deal with
459 // it. for now we just ignore it and not crash
460 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
461 if( list
[0] == NULL
|| list
[1] == NULL
|| list
[2] == NULL
)
464 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
467 const char* const pkg
= list
[1];
468 const char* action
= _strstrip(list
[2]);
470 // 'processing' from dpkg looks like
471 // 'processing: action: pkg'
472 if(strncmp(list
[0], "processing", strlen("processing")) == 0)
475 const char* const pkg_or_trigger
= _strstrip(list
[2]);
476 action
= _strstrip( list
[1]);
477 const std::pair
<const char *, const char *> * const iter
=
478 std::find_if(PackageProcessingOpsBegin
,
479 PackageProcessingOpsEnd
,
480 MatchProcessingOp(action
));
481 if(iter
== PackageProcessingOpsEnd
)
484 std::clog
<< "ignoring unknown action: " << action
<< std::endl
;
487 snprintf(s
, sizeof(s
), _(iter
->second
), pkg_or_trigger
);
489 status
<< "pmstatus:" << pkg_or_trigger
490 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
494 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
496 std::clog
<< "send: '" << status
.str() << "'" << endl
;
498 if (strncmp(action
, "disappear", strlen("disappear")) == 0)
499 handleDisappearAction(pkg_or_trigger
);
503 if(strncmp(action
,"error",strlen("error")) == 0)
505 // urgs, sometime has ":" in its error string so that we
506 // end up with the error message split between list[3]
507 // and list[4], e.g. the message:
508 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
510 if( list
[4] != NULL
)
511 list
[3][strlen(list
[3])] = ':';
513 status
<< "pmerror:" << list
[1]
514 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
518 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
520 std::clog
<< "send: '" << status
.str() << "'" << endl
;
522 WriteApportReport(list
[1], list
[3]);
525 else if(strncmp(action
,"conffile",strlen("conffile")) == 0)
527 status
<< "pmconffile:" << list
[1]
528 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
532 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
534 std::clog
<< "send: '" << status
.str() << "'" << endl
;
538 vector
<struct DpkgState
> const &states
= PackageOps
[pkg
];
539 const char *next_action
= NULL
;
540 if(PackageOpsDone
[pkg
] < states
.size())
541 next_action
= states
[PackageOpsDone
[pkg
]].state
;
542 // check if the package moved to the next dpkg state
543 if(next_action
&& (strcmp(action
, next_action
) == 0))
545 // only read the translation if there is actually a next
547 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
549 snprintf(s
, sizeof(s
), translation
, pkg
);
551 // we moved from one dpkg state to a new one, report that
552 PackageOpsDone
[pkg
]++;
554 // build the status str
555 status
<< "pmstatus:" << pkg
556 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
560 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
562 std::clog
<< "send: '" << status
.str() << "'" << endl
;
565 std::clog
<< "(parsed from dpkg) pkg: " << pkg
566 << " action: " << action
<< endl
;
569 // DPkgPM::handleDisappearAction /*{{{*/
570 void pkgDPkgPM::handleDisappearAction(string
const &pkgname
)
572 // record the package name for display and stuff later
573 disappearedPkgs
.insert(pkgname
);
575 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
576 if (unlikely(Pkg
.end() == true))
578 // the disappeared package was auto-installed - nothing to do
579 if ((Cache
[Pkg
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
581 pkgCache::VerIterator PkgVer
= Cache
[Pkg
].InstVerIter(Cache
);
582 if (unlikely(PkgVer
.end() == true))
584 /* search in the list of dependencies for (Pre)Depends,
585 check if this dependency has a Replaces on our package
586 and if so transfer the manual installed flag to it */
587 for (pkgCache::DepIterator Dep
= PkgVer
.DependsList(); Dep
.end() != true; ++Dep
)
589 if (Dep
->Type
!= pkgCache::Dep::Depends
&&
590 Dep
->Type
!= pkgCache::Dep::PreDepends
)
592 pkgCache::PkgIterator Tar
= Dep
.TargetPkg();
593 if (unlikely(Tar
.end() == true))
595 // the package is already marked as manual
596 if ((Cache
[Tar
].Flags
& pkgCache::Flag::Auto
) != pkgCache::Flag::Auto
)
598 pkgCache::VerIterator TarVer
= Cache
[Tar
].InstVerIter(Cache
);
599 if (TarVer
.end() == true)
601 for (pkgCache::DepIterator Rep
= TarVer
.DependsList(); Rep
.end() != true; ++Rep
)
603 if (Rep
->Type
!= pkgCache::Dep::Replaces
)
605 if (Pkg
!= Rep
.TargetPkg())
607 // okay, they are strongly connected - transfer manual-bit
609 std::clog
<< "transfer manual-bit from disappeared »" << pkgname
<< "« to »" << Tar
.FullName() << "«" << std::endl
;
610 Cache
[Tar
].Flags
&= ~Flag::Auto
;
616 // DPkgPM::DoDpkgStatusFd /*{{{*/
617 // ---------------------------------------------------------------------
620 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
, int OutStatusFd
)
625 len
=read(statusfd
, &d
->dpkgbuf
[d
->dpkgbuf_pos
], sizeof(d
->dpkgbuf
)-d
->dpkgbuf_pos
);
626 d
->dpkgbuf_pos
+= len
;
630 // process line by line if we have a buffer
632 while((q
=(char*)memchr(p
, '\n', d
->dpkgbuf
+d
->dpkgbuf_pos
-p
)) != NULL
)
635 ProcessDpkgStatusLine(OutStatusFd
, p
);
636 p
=q
+1; // continue with next line
639 // now move the unprocessed bits (after the final \n that is now a 0x0)
640 // to the start and update d->dpkgbuf_pos
641 p
= (char*)memrchr(d
->dpkgbuf
, 0, d
->dpkgbuf_pos
);
645 // we are interessted in the first char *after* 0x0
648 // move the unprocessed tail to the start and update pos
649 memmove(d
->dpkgbuf
, p
, p
-d
->dpkgbuf
);
650 d
->dpkgbuf_pos
= d
->dpkgbuf
+d
->dpkgbuf_pos
-p
;
653 // DPkgPM::WriteHistoryTag /*{{{*/
654 void pkgDPkgPM::WriteHistoryTag(string
const &tag
, string value
)
656 size_t const length
= value
.length();
659 // poor mans rstrip(", ")
660 if (value
[length
-2] == ',' && value
[length
-1] == ' ')
661 value
.erase(length
- 2, 2);
662 fprintf(d
->history_out
, "%s: %s\n", tag
.c_str(), value
.c_str());
664 // DPkgPM::OpenLog /*{{{*/
665 bool pkgDPkgPM::OpenLog()
667 string
const logdir
= _config
->FindDir("Dir::Log");
668 if(CreateAPTDirectoryIfNeeded(logdir
, logdir
) == false)
669 // FIXME: use a better string after freeze
670 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
674 time_t const t
= time(NULL
);
675 struct tm
const * const tmp
= localtime(&t
);
676 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
679 string
const logfile_name
= flCombine(logdir
,
680 _config
->Find("Dir::Log::Terminal"));
681 if (!logfile_name
.empty())
683 d
->term_out
= fopen(logfile_name
.c_str(),"a");
684 if (d
->term_out
== NULL
)
685 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name
.c_str());
686 setvbuf(d
->term_out
, NULL
, _IONBF
, 0);
687 SetCloseExec(fileno(d
->term_out
), true);
690 pw
= getpwnam("root");
691 gr
= getgrnam("adm");
692 if (pw
!= NULL
&& gr
!= NULL
)
693 chown(logfile_name
.c_str(), pw
->pw_uid
, gr
->gr_gid
);
694 chmod(logfile_name
.c_str(), 0644);
695 fprintf(d
->term_out
, "\nLog started: %s\n", timestr
);
698 // write your history
699 string
const history_name
= flCombine(logdir
,
700 _config
->Find("Dir::Log::History"));
701 if (!history_name
.empty())
703 d
->history_out
= fopen(history_name
.c_str(),"a");
704 if (d
->history_out
== NULL
)
705 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), history_name
.c_str());
706 chmod(history_name
.c_str(), 0644);
707 fprintf(d
->history_out
, "\nStart-Date: %s\n", timestr
);
708 string remove
, purge
, install
, reinstall
, upgrade
, downgrade
;
709 for (pkgCache::PkgIterator I
= Cache
.PkgBegin(); I
.end() == false; I
++)
711 enum { CANDIDATE
, CANDIDATE_AUTO
, CURRENT_CANDIDATE
, CURRENT
} infostring
;
713 #define HISTORYINFO(X, Y) { line = &X; infostring = Y; }
714 if (Cache
[I
].NewInstall() == true)
715 HISTORYINFO(install
, CANDIDATE_AUTO
)
716 else if (Cache
[I
].ReInstall() == true)
717 HISTORYINFO(reinstall
, CANDIDATE
)
718 else if (Cache
[I
].Upgrade() == true)
719 HISTORYINFO(upgrade
, CURRENT_CANDIDATE
)
720 else if (Cache
[I
].Downgrade() == true)
721 HISTORYINFO(downgrade
, CURRENT_CANDIDATE
)
722 else if (Cache
[I
].Delete() == true)
723 HISTORYINFO((Cache
[I
].Purge() ? purge
: remove
), CURRENT
)
727 line
->append(I
.FullName(false)).append(" (");
728 switch (infostring
) {
729 case CANDIDATE
: line
->append(Cache
[I
].CandVersion
); break;
731 line
->append(Cache
[I
].CandVersion
);
732 if ((Cache
[I
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
733 line
->append(", automatic");
735 case CURRENT_CANDIDATE
: line
->append(Cache
[I
].CurVersion
).append(", ").append(Cache
[I
].CandVersion
); break;
736 case CURRENT
: line
->append(Cache
[I
].CurVersion
); break;
740 if (_config
->Exists("Commandline::AsString") == true)
741 WriteHistoryTag("Commandline", _config
->Find("Commandline::AsString"));
742 WriteHistoryTag("Install", install
);
743 WriteHistoryTag("Reinstall", reinstall
);
744 WriteHistoryTag("Upgrade", upgrade
);
745 WriteHistoryTag("Downgrade",downgrade
);
746 WriteHistoryTag("Remove",remove
);
747 WriteHistoryTag("Purge",purge
);
748 fflush(d
->history_out
);
754 // DPkg::CloseLog /*{{{*/
755 bool pkgDPkgPM::CloseLog()
758 time_t t
= time(NULL
);
759 struct tm
*tmp
= localtime(&t
);
760 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
764 fprintf(d
->term_out
, "Log ended: ");
765 fprintf(d
->term_out
, "%s", timestr
);
766 fprintf(d
->term_out
, "\n");
773 if (disappearedPkgs
.empty() == false)
776 for (std::set
<std::string
>::const_iterator d
= disappearedPkgs
.begin();
777 d
!= disappearedPkgs
.end(); ++d
)
779 pkgCache::PkgIterator P
= Cache
.FindPkg(*d
);
780 disappear
.append(*d
);
782 disappear
.append(", ");
784 disappear
.append(" (").append(Cache
[P
].CurVersion
).append("), ");
786 WriteHistoryTag("Disappeared", disappear
);
788 if (d
->dpkg_error
.empty() == false)
789 fprintf(d
->history_out
, "Error: %s\n", d
->dpkg_error
.c_str());
790 fprintf(d
->history_out
, "End-Date: %s\n", timestr
);
791 fclose(d
->history_out
);
793 d
->history_out
= NULL
;
799 // This implements a racy version of pselect for those architectures
800 // that don't have a working implementation.
801 // FIXME: Probably can be removed on Lenny+1
802 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
803 fd_set
*exceptfds
, const struct timespec
*timeout
,
804 const sigset_t
*sigmask
)
810 tv
.tv_sec
= timeout
->tv_sec
;
811 tv
.tv_usec
= timeout
->tv_nsec
/1000;
813 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
814 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
815 sigprocmask(SIG_SETMASK
, &origmask
, 0);
819 // DPkgPM::Go - Run the sequence /*{{{*/
820 // ---------------------------------------------------------------------
821 /* This globs the operations and calls dpkg
823 * If it is called with "OutStatusFd" set to a valid file descriptor
824 * apt will report the install progress over this fd. It maps the
825 * dpkg states a package goes through to human readable (and i10n-able)
826 * names and calculates a percentage for each step.
828 bool pkgDPkgPM::Go(int OutStatusFd
)
833 sigset_t original_sigmask
;
835 unsigned int const MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
836 unsigned int const MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
837 bool const NoTriggers
= _config
->FindB("DPkg::NoTriggers", false);
839 if (RunScripts("DPkg::Pre-Invoke") == false)
842 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
845 // support subpressing of triggers processing for special
846 // cases like d-i that runs the triggers handling manually
847 bool const SmartConf
= (_config
->Find("PackageManager::Configure", "all") != "all");
848 bool const TriggersPending
= _config
->FindB("DPkg::TriggersPending", false);
849 if (_config
->FindB("DPkg::ConfigurePending", SmartConf
) == true)
850 List
.push_back(Item(Item::ConfigurePending
, PkgIterator()));
852 // map the dpkg states to the operations that are performed
853 // (this is sorted in the same way as Item::Ops)
854 static const struct DpkgState DpkgStatesOpMap
[][7] = {
857 {"half-installed", N_("Preparing %s")},
858 {"unpacked", N_("Unpacking %s") },
861 // Configure operation
863 {"unpacked",N_("Preparing to configure %s") },
864 {"half-configured", N_("Configuring %s") },
865 { "installed", N_("Installed %s")},
870 {"half-configured", N_("Preparing for removal of %s")},
871 {"half-installed", N_("Removing %s")},
872 {"config-files", N_("Removed %s")},
877 {"config-files", N_("Preparing to completely remove %s")},
878 {"not-installed", N_("Completely removed %s")},
883 // init the PackageOps map, go over the list of packages that
884 // that will be [installed|configured|removed|purged] and add
885 // them to the PackageOps map (the dpkg states it goes through)
886 // and the PackageOpsTranslations (human readable strings)
887 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();I
++)
889 if((*I
).Pkg
.end() == true)
892 string
const name
= (*I
).Pkg
.Name();
893 PackageOpsDone
[name
] = 0;
894 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; i
++)
896 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
901 d
->stdin_is_dev_null
= false;
906 // this loop is runs once per operation
907 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();)
909 // Do all actions with the same Op in one run
910 vector
<Item
>::const_iterator J
= I
;
911 if (TriggersPending
== true)
912 for (; J
!= List
.end(); J
++)
916 if (J
->Op
!= Item::TriggersPending
)
918 vector
<Item
>::const_iterator T
= J
+ 1;
919 if (T
!= List
.end() && T
->Op
== I
->Op
)
924 for (; J
!= List
.end() && J
->Op
== I
->Op
; J
++)
927 // Generate the argument list
928 const char *Args
[MaxArgs
+ 50];
929 // keep track of allocated strings for multiarch package names
930 char *Packages
[MaxArgs
+ 50];
931 unsigned int pkgcount
= 0;
933 // Now check if we are within the MaxArgs limit
935 // this code below is problematic, because it may happen that
936 // the argument list is split in a way that A depends on B
937 // and they are in the same "--configure A B" run
938 // - with the split they may now be configured in different
940 if (J
- I
> (signed)MaxArgs
)
944 unsigned long Size
= 0;
945 string
const Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
946 Args
[n
++] = Tmp
.c_str();
947 Size
+= strlen(Args
[n
-1]);
949 // Stick in any custom dpkg options
950 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
954 for (; Opts
!= 0; Opts
= Opts
->Next
)
956 if (Opts
->Value
.empty() == true)
958 Args
[n
++] = Opts
->Value
.c_str();
959 Size
+= Opts
->Value
.length();
963 char status_fd_buf
[20];
967 Args
[n
++] = "--status-fd";
968 Size
+= strlen(Args
[n
-1]);
969 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
970 Args
[n
++] = status_fd_buf
;
971 Size
+= strlen(Args
[n
-1]);
976 Args
[n
++] = "--force-depends";
977 Size
+= strlen(Args
[n
-1]);
978 Args
[n
++] = "--force-remove-essential";
979 Size
+= strlen(Args
[n
-1]);
980 Args
[n
++] = "--remove";
981 Size
+= strlen(Args
[n
-1]);
985 Args
[n
++] = "--force-depends";
986 Size
+= strlen(Args
[n
-1]);
987 Args
[n
++] = "--force-remove-essential";
988 Size
+= strlen(Args
[n
-1]);
989 Args
[n
++] = "--purge";
990 Size
+= strlen(Args
[n
-1]);
993 case Item::Configure
:
994 Args
[n
++] = "--configure";
995 Size
+= strlen(Args
[n
-1]);
998 case Item::ConfigurePending
:
999 Args
[n
++] = "--configure";
1000 Size
+= strlen(Args
[n
-1]);
1001 Args
[n
++] = "--pending";
1002 Size
+= strlen(Args
[n
-1]);
1005 case Item::TriggersPending
:
1006 Args
[n
++] = "--triggers-only";
1007 Size
+= strlen(Args
[n
-1]);
1008 Args
[n
++] = "--pending";
1009 Size
+= strlen(Args
[n
-1]);
1013 Args
[n
++] = "--unpack";
1014 Size
+= strlen(Args
[n
-1]);
1015 Args
[n
++] = "--auto-deconfigure";
1016 Size
+= strlen(Args
[n
-1]);
1020 if (NoTriggers
== true && I
->Op
!= Item::TriggersPending
&&
1021 I
->Op
!= Item::ConfigurePending
)
1023 Args
[n
++] = "--no-triggers";
1024 Size
+= strlen(Args
[n
-1]);
1027 // Write in the file or package names
1028 if (I
->Op
== Item::Install
)
1030 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
1032 if (I
->File
[0] != '/')
1033 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
1034 Args
[n
++] = I
->File
.c_str();
1035 Size
+= strlen(Args
[n
-1]);
1040 string
const nativeArch
= _config
->Find("APT::Architecture");
1041 unsigned long const oldSize
= I
->Op
== Item::Configure
? Size
: 0;
1042 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
1044 if((*I
).Pkg
.end() == true)
1046 if (I
->Op
== Item::Configure
&& disappearedPkgs
.find(I
->Pkg
.Name()) != disappearedPkgs
.end())
1048 if (I
->Pkg
.Arch() == nativeArch
|| !strcmp(I
->Pkg
.Arch(), "all"))
1049 Args
[n
++] = I
->Pkg
.Name();
1052 Packages
[pkgcount
] = strdup(I
->Pkg
.FullName(false).c_str());
1053 Args
[n
++] = Packages
[pkgcount
++];
1055 Size
+= strlen(Args
[n
-1]);
1057 // skip configure action if all sheduled packages disappeared
1058 if (oldSize
== Size
)
1064 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
1066 for (unsigned int k
= 0; k
!= n
; k
++)
1067 clog
<< Args
[k
] << ' ';
1076 /* Mask off sig int/quit. We do this because dpkg also does when
1077 it forks scripts. What happens is that when you hit ctrl-c it sends
1078 it to all processes in the group. Since dpkg ignores the signal
1079 it doesn't die but we do! So we must also ignore it */
1080 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
1081 sighandler_t old_SIGINT
= signal(SIGINT
,SIG_IGN
);
1083 // ignore SIGHUP as well (debian #463030)
1084 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
1091 // if tcgetattr does not return zero there was a error
1092 // and we do not do any pty magic
1093 if (tcgetattr(0, &tt
) == 0)
1095 ioctl(0, TIOCGWINSZ
, (char *)&win
);
1096 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
1098 const char *s
= _("Can not write log, openpty() "
1099 "failed (/dev/pts not mounted?)\n");
1100 fprintf(stderr
, "%s",s
);
1102 fprintf(d
->term_out
, "%s",s
);
1103 master
= slave
= -1;
1108 rtt
.c_lflag
&= ~ECHO
;
1109 rtt
.c_lflag
|= ISIG
;
1110 // block SIGTTOU during tcsetattr to prevent a hang if
1111 // the process is a member of the background process group
1112 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
1113 sigemptyset(&sigmask
);
1114 sigaddset(&sigmask
, SIGTTOU
);
1115 sigprocmask(SIG_BLOCK
,&sigmask
, &original_sigmask
);
1116 tcsetattr(0, TCSAFLUSH
, &rtt
);
1117 sigprocmask(SIG_SETMASK
, &original_sigmask
, 0);
1123 _config
->Set("APT::Keep-Fds::",fd
[1]);
1124 // send status information that we are about to fork dpkg
1125 if(OutStatusFd
> 0) {
1126 ostringstream status
;
1127 status
<< "pmstatus:dpkg-exec:"
1128 << (PackagesDone
/float(PackagesTotal
)*100.0)
1129 << ":" << _("Running dpkg")
1131 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
1135 // This is the child
1138 if(slave
>= 0 && master
>= 0)
1141 ioctl(slave
, TIOCSCTTY
, 0);
1148 close(fd
[0]); // close the read end of the pipe
1150 if (_config
->FindDir("DPkg::Chroot-Directory","/") != "/")
1152 std::cerr
<< "Chrooting into "
1153 << _config
->FindDir("DPkg::Chroot-Directory")
1155 if (chroot(_config
->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
1159 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
1162 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
1165 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
1168 // Discard everything in stdin before forking dpkg
1169 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
1172 while (read(STDIN_FILENO
,&dummy
,1) == 1);
1174 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
1178 /* No Job Control Stop Env is a magic dpkg var that prevents it
1179 from using sigstop */
1180 putenv((char *)"DPKG_NO_TSTP=yes");
1181 execvp(Args
[0],(char **)Args
);
1182 cerr
<< "Could not exec dpkg!" << endl
;
1187 if (_config
->FindB("DPkg::UseIoNice", false) == true)
1190 // clear the Keep-Fd again
1191 _config
->Clear("APT::Keep-Fds",fd
[1]);
1196 // we read from dpkg here
1197 int const _dpkgin
= fd
[0];
1198 close(fd
[1]); // close the write end of the pipe
1204 sigemptyset(&sigmask
);
1205 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
1207 /* clean up the temporary allocation for multiarch package names in
1208 the parent, so we don't leak memory when we return. */
1209 for (unsigned int i
= 0; i
< pkgcount
; i
++)
1212 // the result of the waitpid call
1215 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
1217 // FIXME: move this to a function or something, looks ugly here
1218 // error handling, waitpid returned -1
1221 RunScripts("DPkg::Post-Invoke");
1223 // Restore sig int/quit
1224 signal(SIGQUIT
,old_SIGQUIT
);
1225 signal(SIGINT
,old_SIGINT
);
1226 signal(SIGHUP
,old_SIGHUP
);
1227 return _error
->Errno("waitpid","Couldn't wait for subprocess");
1230 // wait for input or output here
1232 if (master
>= 0 && !d
->stdin_is_dev_null
)
1234 FD_SET(_dpkgin
, &rfds
);
1236 FD_SET(master
, &rfds
);
1239 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
1240 &tv
, &original_sigmask
);
1241 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
1242 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
1243 NULL
, &tv
, &original_sigmask
);
1244 if (select_ret
== 0)
1246 else if (select_ret
< 0 && errno
== EINTR
)
1248 else if (select_ret
< 0)
1250 perror("select() returned error");
1254 if(master
>= 0 && FD_ISSET(master
, &rfds
))
1255 DoTerminalPty(master
);
1256 if(master
>= 0 && FD_ISSET(0, &rfds
))
1258 if(FD_ISSET(_dpkgin
, &rfds
))
1259 DoDpkgStatusFd(_dpkgin
, OutStatusFd
);
1263 // Restore sig int/quit
1264 signal(SIGQUIT
,old_SIGQUIT
);
1265 signal(SIGINT
,old_SIGINT
);
1266 signal(SIGHUP
,old_SIGHUP
);
1270 tcsetattr(0, TCSAFLUSH
, &tt
);
1274 // Check for an error code.
1275 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
1277 // if it was set to "keep-dpkg-runing" then we won't return
1278 // here but keep the loop going and just report it as a error
1280 bool const stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
1283 RunScripts("DPkg::Post-Invoke");
1285 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
1286 strprintf(d
->dpkg_error
, "Sub-process %s received a segmentation fault.",Args
[0]);
1287 else if (WIFEXITED(Status
) != 0)
1288 strprintf(d
->dpkg_error
, "Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
1290 strprintf(d
->dpkg_error
, "Sub-process %s exited unexpectedly",Args
[0]);
1292 if(d
->dpkg_error
.size() > 0)
1293 _error
->Error("%s", d
->dpkg_error
.c_str());
1304 if (RunScripts("DPkg::Post-Invoke") == false)
1307 if (_config
->FindB("Debug::pkgDPkgPM",false) == false)
1309 std::string
const oldpkgcache
= _config
->FindFile("Dir::cache::pkgcache");
1310 if (oldpkgcache
.empty() == false && RealFileExists(oldpkgcache
) == true &&
1311 unlink(oldpkgcache
.c_str()) == 0)
1313 std::string
const srcpkgcache
= _config
->FindFile("Dir::cache::srcpkgcache");
1314 if (srcpkgcache
.empty() == false && RealFileExists(srcpkgcache
) == true)
1316 _error
->PushToStack();
1317 pkgCacheFile CacheFile
;
1318 CacheFile
.BuildCaches(NULL
, true);
1319 _error
->RevertToStack();
1324 Cache
.writeStateFile(NULL
);
1328 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1329 // ---------------------------------------------------------------------
1331 void pkgDPkgPM::Reset()
1333 List
.erase(List
.begin(),List
.end());
1336 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1337 // ---------------------------------------------------------------------
1339 void pkgDPkgPM::WriteApportReport(const char *pkgpath
, const char *errormsg
)
1341 string pkgname
, reportfile
, srcpkgname
, pkgver
, arch
;
1342 string::size_type pos
;
1345 if (_config
->FindB("Dpkg::ApportFailureReport", false) == false)
1347 std::clog
<< "configured to not write apport reports" << std::endl
;
1351 // only report the first errors
1352 if(pkgFailures
> _config
->FindI("APT::Apport::MaxReports", 3))
1354 std::clog
<< _("No apport report written because MaxReports is reached already") << std::endl
;
1358 // check if its not a follow up error
1359 const char *needle
= dgettext("dpkg", "dependency problems - leaving unconfigured");
1360 if(strstr(errormsg
, needle
) != NULL
) {
1361 std::clog
<< _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl
;
1365 // do not report disk-full failures
1366 if(strstr(errormsg
, strerror(ENOSPC
)) != NULL
) {
1367 std::clog
<< _("No apport report written because the error message indicates a disk full error") << std::endl
;
1371 // do not report out-of-memory failures
1372 if(strstr(errormsg
, strerror(ENOMEM
)) != NULL
) {
1373 std::clog
<< _("No apport report written because the error message indicates a out of memory error") << std::endl
;
1377 // do not report dpkg I/O errors
1378 // XXX - this message is localized, but this only matches the English version. This is better than nothing.
1379 if(strstr(errormsg
, "short read in buffer_copy (")) {
1380 std::clog
<< _("No apport report written because the error message indicates a dpkg I/O error") << std::endl
;
1384 // get the pkgname and reportfile
1385 pkgname
= flNotDir(pkgpath
);
1386 pos
= pkgname
.find('_');
1387 if(pos
!= string::npos
)
1388 pkgname
= pkgname
.substr(0, pos
);
1390 // find the package versin and source package name
1391 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
1392 if (Pkg
.end() == true)
1394 pkgCache::VerIterator Ver
= Cache
.GetCandidateVer(Pkg
);
1395 if (Ver
.end() == true)
1397 pkgver
= Ver
.VerStr() == NULL
? "unknown" : Ver
.VerStr();
1398 pkgRecords
Recs(Cache
);
1399 pkgRecords::Parser
&Parse
= Recs
.Lookup(Ver
.FileList());
1400 srcpkgname
= Parse
.SourcePkg();
1401 if(srcpkgname
.empty())
1402 srcpkgname
= pkgname
;
1404 // if the file exists already, we check:
1405 // - if it was reported already (touched by apport).
1406 // If not, we do nothing, otherwise
1407 // we overwrite it. This is the same behaviour as apport
1408 // - if we have a report with the same pkgversion already
1410 reportfile
= flCombine("/var/crash",pkgname
+".0.crash");
1411 if(FileExists(reportfile
))
1416 // check atime/mtime
1417 stat(reportfile
.c_str(), &buf
);
1418 if(buf
.st_mtime
> buf
.st_atime
)
1421 // check if the existing report is the same version
1422 report
= fopen(reportfile
.c_str(),"r");
1423 while(fgets(strbuf
, sizeof(strbuf
), report
) != NULL
)
1425 if(strstr(strbuf
,"Package:") == strbuf
)
1427 char pkgname
[255], version
[255];
1428 if(sscanf(strbuf
, "Package: %s %s", pkgname
, version
) == 2)
1429 if(strcmp(pkgver
.c_str(), version
) == 0)
1439 // now write the report
1440 arch
= _config
->Find("APT::Architecture");
1441 report
= fopen(reportfile
.c_str(),"w");
1444 if(_config
->FindB("DPkgPM::InitialReportOnly",false) == true)
1445 chmod(reportfile
.c_str(), 0);
1447 chmod(reportfile
.c_str(), 0600);
1448 fprintf(report
, "ProblemType: Package\n");
1449 fprintf(report
, "Architecture: %s\n", arch
.c_str());
1450 time_t now
= time(NULL
);
1451 fprintf(report
, "Date: %s" , ctime(&now
));
1452 fprintf(report
, "Package: %s %s\n", pkgname
.c_str(), pkgver
.c_str());
1453 fprintf(report
, "SourcePackage: %s\n", srcpkgname
.c_str());
1454 fprintf(report
, "ErrorMessage:\n %s\n", errormsg
);
1456 // ensure that the log is flushed
1458 fflush(d
->term_out
);
1460 // attach terminal log it if we have it
1461 string logfile_name
= _config
->FindFile("Dir::Log::Terminal");
1462 if (!logfile_name
.empty())
1467 fprintf(report
, "DpkgTerminalLog:\n");
1468 log
= fopen(logfile_name
.c_str(),"r");
1471 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1472 fprintf(report
, " %s", buf
);
1478 const char *ops_str
[] = {"Install", "Configure","Remove","Purge"};
1479 fprintf(report
, "AptOrdering:\n");
1480 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
1481 fprintf(report
, " %s: %s\n", (*I
).Pkg
.Name(), ops_str
[(*I
).Op
]);
1483 // attach dmesg log (to learn about segfaults)
1484 if (FileExists("/bin/dmesg"))
1489 fprintf(report
, "Dmesg:\n");
1490 log
= popen("/bin/dmesg","r");
1493 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1494 fprintf(report
, " %s", buf
);
1499 // attach df -l log (to learn about filesystem status)
1500 if (FileExists("/bin/df"))
1505 fprintf(report
, "Df:\n");
1506 log
= popen("/bin/df -l","r");
1509 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1510 fprintf(report
, " %s", buf
);