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>
51 // Maps the dpkg "processing" info to human readable names. Entry 0
52 // of each array is the key, entry 1 is the value.
53 const std::pair
<const char *, const char *> PackageProcessingOps
[] = {
54 std::make_pair("install", N_("Installing %s")),
55 std::make_pair("configure", N_("Configuring %s")),
56 std::make_pair("remove", N_("Removing %s")),
57 std::make_pair("purge", N_("Completely removing %s")),
58 std::make_pair("disappear", N_("Noting disappearance of %s")),
59 std::make_pair("trigproc", N_("Running post-installation trigger %s"))
62 const std::pair
<const char *, const char *> * const PackageProcessingOpsBegin
= PackageProcessingOps
;
63 const std::pair
<const char *, const char *> * const PackageProcessingOpsEnd
= PackageProcessingOps
+ sizeof(PackageProcessingOps
) / sizeof(PackageProcessingOps
[0]);
65 // Predicate to test whether an entry in the PackageProcessingOps
66 // array matches a string.
67 class MatchProcessingOp
72 MatchProcessingOp(const char *the_target
)
77 bool operator()(const std::pair
<const char *, const char *> &pair
) const
79 return strcmp(pair
.first
, target
) == 0;
84 /* helper function to ionice the given PID
86 there is no C header for ionice yet - just the syscall interface
87 so we use the binary from util-linux
92 if (!FileExists("/usr/bin/ionice"))
94 pid_t Process
= ExecFork();
98 snprintf(buf
, sizeof(buf
), "-p%d", PID
);
100 Args
[0] = "/usr/bin/ionice";
104 execv(Args
[0], (char **)Args
);
106 return ExecWait(Process
, "ionice");
109 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
110 // ---------------------------------------------------------------------
112 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
113 : pkgPackageManager(Cache
), dpkgbuf_pos(0),
114 term_out(NULL
), history_out(NULL
), PackagesDone(0), PackagesTotal(0)
118 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
119 // ---------------------------------------------------------------------
121 pkgDPkgPM::~pkgDPkgPM()
125 // DPkgPM::Install - Install a package /*{{{*/
126 // ---------------------------------------------------------------------
127 /* Add an install operation to the sequence list */
128 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
130 if (File
.empty() == true || Pkg
.end() == true)
131 return _error
->Error("Internal Error, No file name for %s",Pkg
.Name());
133 // If the filename string begins with DPkg::Chroot-Directory, return the
134 // substr that is within the chroot so dpkg can access it.
135 string
const chrootdir
= _config
->FindDir("DPkg::Chroot-Directory","/");
136 if (chrootdir
!= "/" && File
.find(chrootdir
) == 0)
138 size_t len
= chrootdir
.length();
139 if (chrootdir
.at(len
- 1) == '/')
141 List
.push_back(Item(Item::Install
,Pkg
,File
.substr(len
)));
144 List
.push_back(Item(Item::Install
,Pkg
,File
));
149 // DPkgPM::Configure - Configure a package /*{{{*/
150 // ---------------------------------------------------------------------
151 /* Add a configure operation to the sequence list */
152 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
154 if (Pkg
.end() == true)
157 List
.push_back(Item(Item::Configure
, Pkg
));
159 // Use triggers for config calls if we configure "smart"
160 // as otherwise Pre-Depends will not be satisfied, see #526774
161 if (_config
->FindB("DPkg::TriggersPending", false) == true)
162 List
.push_back(Item(Item::TriggersPending
, PkgIterator()));
167 // DPkgPM::Remove - Remove a package /*{{{*/
168 // ---------------------------------------------------------------------
169 /* Add a remove operation to the sequence list */
170 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
172 if (Pkg
.end() == true)
176 List
.push_back(Item(Item::Purge
,Pkg
));
178 List
.push_back(Item(Item::Remove
,Pkg
));
182 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
183 // ---------------------------------------------------------------------
184 /* This is part of the helper script communication interface, it sends
185 very complete information down to the other end of the pipe.*/
186 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
188 fprintf(F
,"VERSION 2\n");
190 /* Write out all of the configuration directives by walking the
191 configuration tree */
192 const Configuration::Item
*Top
= _config
->Tree(0);
195 if (Top
->Value
.empty() == false)
198 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
199 QuoteString(Top
->Value
,"\n").c_str());
208 while (Top
!= 0 && Top
->Next
== 0)
215 // Write out the package actions in order.
216 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
218 if(I
->Pkg
.end() == true)
221 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
223 fprintf(F
,"%s ",I
->Pkg
.Name());
225 if (I
->Pkg
->CurrentVer
== 0)
228 fprintf(F
,"%s ",I
->Pkg
.CurrentVer().VerStr());
230 // Show the compare operator
232 if (S
.InstallVer
!= 0)
235 if (I
->Pkg
->CurrentVer
!= 0)
236 Comp
= S
.InstVerIter(Cache
).CompareVer(I
->Pkg
.CurrentVer());
243 fprintf(F
,"%s ",S
.InstVerIter(Cache
).VerStr());
248 // Show the filename/operation
249 if (I
->Op
== Item::Install
)
252 if (I
->File
[0] != '/')
253 fprintf(F
,"**ERROR**\n");
255 fprintf(F
,"%s\n",I
->File
.c_str());
257 if (I
->Op
== Item::Configure
)
258 fprintf(F
,"**CONFIGURE**\n");
259 if (I
->Op
== Item::Remove
||
260 I
->Op
== Item::Purge
)
261 fprintf(F
,"**REMOVE**\n");
269 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
270 // ---------------------------------------------------------------------
271 /* This looks for a list of scripts to run from the configuration file
272 each one is run and is fed on standard input a list of all .deb files
273 that are due to be installed. */
274 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
276 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
277 if (Opts
== 0 || Opts
->Child
== 0)
281 unsigned int Count
= 1;
282 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
284 if (Opts
->Value
.empty() == true)
287 // Determine the protocol version
288 string OptSec
= Opts
->Value
;
289 string::size_type Pos
;
290 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
291 Pos
= OptSec
.length();
292 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
294 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
298 if (pipe(Pipes
) != 0)
299 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
300 SetCloseExec(Pipes
[0],true);
301 SetCloseExec(Pipes
[1],true);
303 // Purified Fork for running the script
304 pid_t Process
= ExecFork();
308 dup2(Pipes
[0],STDIN_FILENO
);
309 SetCloseExec(STDOUT_FILENO
,false);
310 SetCloseExec(STDIN_FILENO
,false);
311 SetCloseExec(STDERR_FILENO
,false);
313 if (_config
->FindDir("DPkg::Chroot-Directory","/") != "/")
315 std::cerr
<< "Chrooting into "
316 << _config
->FindDir("DPkg::Chroot-Directory")
318 if (chroot(_config
->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
325 Args
[2] = Opts
->Value
.c_str();
327 execv(Args
[0],(char **)Args
);
331 FILE *F
= fdopen(Pipes
[1],"w");
333 return _error
->Errno("fdopen","Faild to open new FD");
335 // Feed it the filenames.
338 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
340 // Only deal with packages to be installed from .deb
341 if (I
->Op
!= Item::Install
)
345 if (I
->File
[0] != '/')
348 /* Feed the filename of each package that is pending install
350 fprintf(F
,"%s\n",I
->File
.c_str());
360 // Clean up the sub process
361 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
362 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
368 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
369 // ---------------------------------------------------------------------
372 void pkgDPkgPM::DoStdin(int master
)
374 unsigned char input_buf
[256] = {0,};
375 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
377 write(master
, input_buf
, len
);
379 stdin_is_dev_null
= true;
382 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
383 // ---------------------------------------------------------------------
385 * read the terminal pty and write log
387 void pkgDPkgPM::DoTerminalPty(int master
)
389 unsigned char term_buf
[1024] = {0,0, };
391 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
392 if(len
== -1 && errno
== EIO
)
394 // this happens when the child is about to exit, we
395 // give it time to actually exit, otherwise we run
396 // into a race so we sleep for half a second.
397 struct timespec sleepfor
= { 0, 500000000 };
398 nanosleep(&sleepfor
, NULL
);
403 write(1, term_buf
, len
);
405 fwrite(term_buf
, len
, sizeof(char), term_out
);
408 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
409 // ---------------------------------------------------------------------
412 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd
, char *line
)
414 bool const Debug
= _config
->FindB("Debug::pkgDPkgProgressReporting",false);
415 // the status we output
416 ostringstream status
;
419 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
422 /* dpkg sends strings like this:
423 'status: <pkg>: <pkg qstate>'
424 errors look like this:
425 '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
426 and conffile-prompt like this
427 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
429 Newer versions of dpkg sent also:
430 'processing: install: pkg'
431 'processing: configure: pkg'
432 'processing: remove: pkg'
433 'processing: purge: pkg'
434 'processing: disappear: pkg'
435 'processing: trigproc: trigger'
439 // dpkg sends multiline error messages sometimes (see
440 // #374195 for a example. we should support this by
441 // either patching dpkg to not send multiline over the
442 // statusfd or by rewriting the code here to deal with
443 // it. for now we just ignore it and not crash
444 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
445 if( list
[0] == NULL
|| list
[1] == NULL
|| list
[2] == NULL
)
448 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
451 const char* const pkg
= list
[1];
452 const char* action
= _strstrip(list
[2]);
454 // 'processing' from dpkg looks like
455 // 'processing: action: pkg'
456 if(strncmp(list
[0], "processing", strlen("processing")) == 0)
459 const char* const pkg_or_trigger
= _strstrip(list
[2]);
460 action
= _strstrip( list
[1]);
461 const std::pair
<const char *, const char *> * const iter
=
462 std::find_if(PackageProcessingOpsBegin
,
463 PackageProcessingOpsEnd
,
464 MatchProcessingOp(action
));
465 if(iter
== PackageProcessingOpsEnd
)
468 std::clog
<< "ignoring unknown action: " << action
<< std::endl
;
471 snprintf(s
, sizeof(s
), _(iter
->second
), pkg_or_trigger
);
473 status
<< "pmstatus:" << pkg_or_trigger
474 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
478 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
480 std::clog
<< "send: '" << status
.str() << "'" << endl
;
482 if (strncmp(action
, "disappear", strlen("disappear")) == 0)
483 handleDisappearAction(pkg_or_trigger
);
487 if(strncmp(action
,"error",strlen("error")) == 0)
489 // urgs, sometime has ":" in its error string so that we
490 // end up with the error message split between list[3]
491 // and list[4], e.g. the message:
492 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
494 if( list
[4] != NULL
)
495 list
[3][strlen(list
[3])] = ':';
497 status
<< "pmerror:" << list
[1]
498 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
502 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
504 std::clog
<< "send: '" << status
.str() << "'" << endl
;
506 WriteApportReport(list
[1], list
[3]);
509 else if(strncmp(action
,"conffile",strlen("conffile")) == 0)
511 status
<< "pmconffile:" << list
[1]
512 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
516 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
518 std::clog
<< "send: '" << status
.str() << "'" << endl
;
522 vector
<struct DpkgState
> const &states
= PackageOps
[pkg
];
523 const char *next_action
= NULL
;
524 if(PackageOpsDone
[pkg
] < states
.size())
525 next_action
= states
[PackageOpsDone
[pkg
]].state
;
526 // check if the package moved to the next dpkg state
527 if(next_action
&& (strcmp(action
, next_action
) == 0))
529 // only read the translation if there is actually a next
531 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
533 snprintf(s
, sizeof(s
), translation
, pkg
);
535 // we moved from one dpkg state to a new one, report that
536 PackageOpsDone
[pkg
]++;
538 // build the status str
539 status
<< "pmstatus:" << pkg
540 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
544 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
546 std::clog
<< "send: '" << status
.str() << "'" << endl
;
549 std::clog
<< "(parsed from dpkg) pkg: " << pkg
550 << " action: " << action
<< endl
;
553 // DPkgPM::handleDisappearAction /*{{{*/
554 void pkgDPkgPM::handleDisappearAction(string
const &pkgname
)
556 // record the package name for display and stuff later
557 disappearedPkgs
.insert(pkgname
);
559 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
560 if (unlikely(Pkg
.end() == true))
562 // the disappeared package was auto-installed - nothing to do
563 if ((Cache
[Pkg
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
565 pkgCache::VerIterator PkgVer
= Cache
[Pkg
].InstVerIter(Cache
);
566 if (unlikely(PkgVer
.end() == true))
568 /* search in the list of dependencies for (Pre)Depends,
569 check if this dependency has a Replaces on our package
570 and if so transfer the manual installed flag to it */
571 for (pkgCache::DepIterator Dep
= PkgVer
.DependsList(); Dep
.end() != true; ++Dep
)
573 if (Dep
->Type
!= pkgCache::Dep::Depends
&&
574 Dep
->Type
!= pkgCache::Dep::PreDepends
)
576 pkgCache::PkgIterator Tar
= Dep
.TargetPkg();
577 if (unlikely(Tar
.end() == true))
579 // the package is already marked as manual
580 if ((Cache
[Tar
].Flags
& pkgCache::Flag::Auto
) != pkgCache::Flag::Auto
)
582 pkgCache::VerIterator TarVer
= Cache
[Tar
].InstVerIter(Cache
);
583 if (TarVer
.end() == true)
585 for (pkgCache::DepIterator Rep
= TarVer
.DependsList(); Rep
.end() != true; ++Rep
)
587 if (Rep
->Type
!= pkgCache::Dep::Replaces
)
589 if (Pkg
!= Rep
.TargetPkg())
591 // okay, they are strongly connected - transfer manual-bit
593 std::clog
<< "transfer manual-bit from disappeared »" << pkgname
<< "« to »" << Tar
.FullName() << "«" << std::endl
;
594 Cache
[Tar
].Flags
&= ~Flag::Auto
;
600 // DPkgPM::DoDpkgStatusFd /*{{{*/
601 // ---------------------------------------------------------------------
604 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
, int OutStatusFd
)
609 len
=read(statusfd
, &dpkgbuf
[dpkgbuf_pos
], sizeof(dpkgbuf
)-dpkgbuf_pos
);
614 // process line by line if we have a buffer
616 while((q
=(char*)memchr(p
, '\n', dpkgbuf
+dpkgbuf_pos
-p
)) != NULL
)
619 ProcessDpkgStatusLine(OutStatusFd
, p
);
620 p
=q
+1; // continue with next line
623 // now move the unprocessed bits (after the final \n that is now a 0x0)
624 // to the start and update dpkgbuf_pos
625 p
= (char*)memrchr(dpkgbuf
, 0, dpkgbuf_pos
);
629 // we are interessted in the first char *after* 0x0
632 // move the unprocessed tail to the start and update pos
633 memmove(dpkgbuf
, p
, p
-dpkgbuf
);
634 dpkgbuf_pos
= dpkgbuf
+dpkgbuf_pos
-p
;
637 // DPkgPM::WriteHistoryTag /*{{{*/
638 void pkgDPkgPM::WriteHistoryTag(string
const &tag
, string value
)
640 size_t const length
= value
.length();
643 // poor mans rstrip(", ")
644 if (value
[length
-2] == ',' && value
[length
-1] == ' ')
645 value
.erase(length
- 2, 2);
646 fprintf(history_out
, "%s: %s\n", tag
.c_str(), value
.c_str());
648 // DPkgPM::OpenLog /*{{{*/
649 bool pkgDPkgPM::OpenLog()
651 string
const logdir
= _config
->FindDir("Dir::Log");
652 if(CreateAPTDirectoryIfNeeded(logdir
, logdir
) == false)
653 // FIXME: use a better string after freeze
654 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
658 time_t const t
= time(NULL
);
659 struct tm
const * const tmp
= localtime(&t
);
660 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
663 string
const logfile_name
= flCombine(logdir
,
664 _config
->Find("Dir::Log::Terminal"));
665 if (!logfile_name
.empty())
667 term_out
= fopen(logfile_name
.c_str(),"a");
668 if (term_out
== NULL
)
669 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name
.c_str());
670 setvbuf(term_out
, NULL
, _IONBF
, 0);
671 SetCloseExec(fileno(term_out
), true);
674 pw
= getpwnam("root");
675 gr
= getgrnam("adm");
676 if (pw
!= NULL
&& gr
!= NULL
)
677 chown(logfile_name
.c_str(), pw
->pw_uid
, gr
->gr_gid
);
678 chmod(logfile_name
.c_str(), 0644);
679 fprintf(term_out
, "\nLog started: %s\n", timestr
);
682 // write your history
683 string
const history_name
= flCombine(logdir
,
684 _config
->Find("Dir::Log::History"));
685 if (!history_name
.empty())
687 history_out
= fopen(history_name
.c_str(),"a");
688 if (history_out
== NULL
)
689 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), history_name
.c_str());
690 chmod(history_name
.c_str(), 0644);
691 fprintf(history_out
, "\nStart-Date: %s\n", timestr
);
692 string remove
, purge
, install
, reinstall
, upgrade
, downgrade
;
693 for (pkgCache::PkgIterator I
= Cache
.PkgBegin(); I
.end() == false; ++I
)
695 enum { CANDIDATE
, CANDIDATE_AUTO
, CURRENT_CANDIDATE
, CURRENT
} infostring
;
697 #define HISTORYINFO(X, Y) { line = &X; infostring = Y; }
698 if (Cache
[I
].NewInstall() == true)
699 HISTORYINFO(install
, CANDIDATE_AUTO
)
700 else if (Cache
[I
].ReInstall() == true)
701 HISTORYINFO(reinstall
, CANDIDATE
)
702 else if (Cache
[I
].Upgrade() == true)
703 HISTORYINFO(upgrade
, CURRENT_CANDIDATE
)
704 else if (Cache
[I
].Downgrade() == true)
705 HISTORYINFO(downgrade
, CURRENT_CANDIDATE
)
706 else if (Cache
[I
].Delete() == true)
707 HISTORYINFO((Cache
[I
].Purge() ? purge
: remove
), CURRENT
)
711 line
->append(I
.FullName(false)).append(" (");
712 switch (infostring
) {
713 case CANDIDATE
: line
->append(Cache
[I
].CandVersion
); break;
715 line
->append(Cache
[I
].CandVersion
);
716 if ((Cache
[I
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
717 line
->append(", automatic");
719 case CURRENT_CANDIDATE
: line
->append(Cache
[I
].CurVersion
).append(", ").append(Cache
[I
].CandVersion
); break;
720 case CURRENT
: line
->append(Cache
[I
].CurVersion
); break;
724 if (_config
->Exists("Commandline::AsString") == true)
725 WriteHistoryTag("Commandline", _config
->Find("Commandline::AsString"));
726 WriteHistoryTag("Install", install
);
727 WriteHistoryTag("Reinstall", reinstall
);
728 WriteHistoryTag("Upgrade", upgrade
);
729 WriteHistoryTag("Downgrade",downgrade
);
730 WriteHistoryTag("Remove",remove
);
731 WriteHistoryTag("Purge",purge
);
738 // DPkg::CloseLog /*{{{*/
739 bool pkgDPkgPM::CloseLog()
742 time_t t
= time(NULL
);
743 struct tm
*tmp
= localtime(&t
);
744 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
748 fprintf(term_out
, "Log ended: ");
749 fprintf(term_out
, "%s", timestr
);
750 fprintf(term_out
, "\n");
757 if (disappearedPkgs
.empty() == false)
760 for (std::set
<std::string
>::const_iterator d
= disappearedPkgs
.begin();
761 d
!= disappearedPkgs
.end(); ++d
)
763 pkgCache::PkgIterator P
= Cache
.FindPkg(*d
);
764 disappear
.append(*d
);
766 disappear
.append(", ");
768 disappear
.append(" (").append(Cache
[P
].CurVersion
).append("), ");
770 WriteHistoryTag("Disappeared", disappear
);
772 if (dpkg_error
.empty() == false)
773 fprintf(history_out
, "Error: %s\n", dpkg_error
.c_str());
774 fprintf(history_out
, "End-Date: %s\n", timestr
);
783 // This implements a racy version of pselect for those architectures
784 // that don't have a working implementation.
785 // FIXME: Probably can be removed on Lenny+1
786 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
787 fd_set
*exceptfds
, const struct timespec
*timeout
,
788 const sigset_t
*sigmask
)
794 tv
.tv_sec
= timeout
->tv_sec
;
795 tv
.tv_usec
= timeout
->tv_nsec
/1000;
797 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
798 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
799 sigprocmask(SIG_SETMASK
, &origmask
, 0);
803 // DPkgPM::Go - Run the sequence /*{{{*/
804 // ---------------------------------------------------------------------
805 /* This globs the operations and calls dpkg
807 * If it is called with "OutStatusFd" set to a valid file descriptor
808 * apt will report the install progress over this fd. It maps the
809 * dpkg states a package goes through to human readable (and i10n-able)
810 * names and calculates a percentage for each step.
812 bool pkgDPkgPM::Go(int OutStatusFd
)
817 sigset_t original_sigmask
;
819 unsigned int const MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
820 unsigned int const MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
821 bool const NoTriggers
= _config
->FindB("DPkg::NoTriggers", false);
823 if (RunScripts("DPkg::Pre-Invoke") == false)
826 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
829 // support subpressing of triggers processing for special
830 // cases like d-i that runs the triggers handling manually
831 bool const SmartConf
= (_config
->Find("PackageManager::Configure", "all") != "all");
832 bool const TriggersPending
= _config
->FindB("DPkg::TriggersPending", false);
833 if (_config
->FindB("DPkg::ConfigurePending", SmartConf
) == true)
834 List
.push_back(Item(Item::ConfigurePending
, PkgIterator()));
836 // map the dpkg states to the operations that are performed
837 // (this is sorted in the same way as Item::Ops)
838 static const struct DpkgState DpkgStatesOpMap
[][7] = {
841 {"half-installed", N_("Preparing %s")},
842 {"unpacked", N_("Unpacking %s") },
845 // Configure operation
847 {"unpacked",N_("Preparing to configure %s") },
848 {"half-configured", N_("Configuring %s") },
849 { "installed", N_("Installed %s")},
854 {"half-configured", N_("Preparing for removal of %s")},
855 {"half-installed", N_("Removing %s")},
856 {"config-files", N_("Removed %s")},
861 {"config-files", N_("Preparing to completely remove %s")},
862 {"not-installed", N_("Completely removed %s")},
867 // init the PackageOps map, go over the list of packages that
868 // that will be [installed|configured|removed|purged] and add
869 // them to the PackageOps map (the dpkg states it goes through)
870 // and the PackageOpsTranslations (human readable strings)
871 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end(); ++I
)
873 if((*I
).Pkg
.end() == true)
876 string
const name
= (*I
).Pkg
.Name();
877 PackageOpsDone
[name
] = 0;
878 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; ++i
)
880 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
885 stdin_is_dev_null
= false;
890 // this loop is runs once per operation
891 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();)
893 // Do all actions with the same Op in one run
894 vector
<Item
>::const_iterator J
= I
;
895 if (TriggersPending
== true)
896 for (; J
!= List
.end(); ++J
)
900 if (J
->Op
!= Item::TriggersPending
)
902 vector
<Item
>::const_iterator T
= J
+ 1;
903 if (T
!= List
.end() && T
->Op
== I
->Op
)
908 for (; J
!= List
.end() && J
->Op
== I
->Op
; ++J
)
911 // Generate the argument list
912 const char *Args
[MaxArgs
+ 50];
913 // keep track of allocated strings for multiarch package names
914 char *Packages
[MaxArgs
+ 50];
915 unsigned int pkgcount
= 0;
917 // Now check if we are within the MaxArgs limit
919 // this code below is problematic, because it may happen that
920 // the argument list is split in a way that A depends on B
921 // and they are in the same "--configure A B" run
922 // - with the split they may now be configured in different
924 if (J
- I
> (signed)MaxArgs
)
928 unsigned long Size
= 0;
929 string
const Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
930 Args
[n
++] = Tmp
.c_str();
931 Size
+= strlen(Args
[n
-1]);
933 // Stick in any custom dpkg options
934 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
938 for (; Opts
!= 0; Opts
= Opts
->Next
)
940 if (Opts
->Value
.empty() == true)
942 Args
[n
++] = Opts
->Value
.c_str();
943 Size
+= Opts
->Value
.length();
947 char status_fd_buf
[20];
951 Args
[n
++] = "--status-fd";
952 Size
+= strlen(Args
[n
-1]);
953 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
954 Args
[n
++] = status_fd_buf
;
955 Size
+= strlen(Args
[n
-1]);
960 Args
[n
++] = "--force-depends";
961 Size
+= strlen(Args
[n
-1]);
962 Args
[n
++] = "--force-remove-essential";
963 Size
+= strlen(Args
[n
-1]);
964 Args
[n
++] = "--remove";
965 Size
+= strlen(Args
[n
-1]);
969 Args
[n
++] = "--force-depends";
970 Size
+= strlen(Args
[n
-1]);
971 Args
[n
++] = "--force-remove-essential";
972 Size
+= strlen(Args
[n
-1]);
973 Args
[n
++] = "--purge";
974 Size
+= strlen(Args
[n
-1]);
977 case Item::Configure
:
978 Args
[n
++] = "--configure";
979 Size
+= strlen(Args
[n
-1]);
982 case Item::ConfigurePending
:
983 Args
[n
++] = "--configure";
984 Size
+= strlen(Args
[n
-1]);
985 Args
[n
++] = "--pending";
986 Size
+= strlen(Args
[n
-1]);
989 case Item::TriggersPending
:
990 Args
[n
++] = "--triggers-only";
991 Size
+= strlen(Args
[n
-1]);
992 Args
[n
++] = "--pending";
993 Size
+= strlen(Args
[n
-1]);
997 Args
[n
++] = "--unpack";
998 Size
+= strlen(Args
[n
-1]);
999 Args
[n
++] = "--auto-deconfigure";
1000 Size
+= strlen(Args
[n
-1]);
1004 if (NoTriggers
== true && I
->Op
!= Item::TriggersPending
&&
1005 I
->Op
!= Item::ConfigurePending
)
1007 Args
[n
++] = "--no-triggers";
1008 Size
+= strlen(Args
[n
-1]);
1011 // Write in the file or package names
1012 if (I
->Op
== Item::Install
)
1014 for (;I
!= J
&& Size
< MaxArgBytes
; ++I
)
1016 if (I
->File
[0] != '/')
1017 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
1018 Args
[n
++] = I
->File
.c_str();
1019 Size
+= strlen(Args
[n
-1]);
1024 string
const nativeArch
= _config
->Find("APT::Architecture");
1025 unsigned long const oldSize
= I
->Op
== Item::Configure
? Size
: 0;
1026 for (;I
!= J
&& Size
< MaxArgBytes
; ++I
)
1028 if((*I
).Pkg
.end() == true)
1030 if (I
->Op
== Item::Configure
&& disappearedPkgs
.find(I
->Pkg
.Name()) != disappearedPkgs
.end())
1032 if (I
->Pkg
.Arch() == nativeArch
|| !strcmp(I
->Pkg
.Arch(), "all"))
1033 Args
[n
++] = I
->Pkg
.Name();
1036 Packages
[pkgcount
] = strdup(I
->Pkg
.FullName(false).c_str());
1037 Args
[n
++] = Packages
[pkgcount
++];
1039 Size
+= strlen(Args
[n
-1]);
1041 // skip configure action if all sheduled packages disappeared
1042 if (oldSize
== Size
)
1048 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
1050 for (unsigned int k
= 0; k
!= n
; k
++)
1051 clog
<< Args
[k
] << ' ';
1060 /* Mask off sig int/quit. We do this because dpkg also does when
1061 it forks scripts. What happens is that when you hit ctrl-c it sends
1062 it to all processes in the group. Since dpkg ignores the signal
1063 it doesn't die but we do! So we must also ignore it */
1064 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
1065 sighandler_t old_SIGINT
= signal(SIGINT
,SIG_IGN
);
1067 // ignore SIGHUP as well (debian #463030)
1068 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
1075 // if tcgetattr does not return zero there was a error
1076 // and we do not do any pty magic
1077 if (tcgetattr(0, &tt
) == 0)
1079 ioctl(0, TIOCGWINSZ
, (char *)&win
);
1080 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
1082 const char *s
= _("Can not write log, openpty() "
1083 "failed (/dev/pts not mounted?)\n");
1084 fprintf(stderr
, "%s",s
);
1086 fprintf(term_out
, "%s",s
);
1087 master
= slave
= -1;
1092 rtt
.c_lflag
&= ~ECHO
;
1093 rtt
.c_lflag
|= ISIG
;
1094 // block SIGTTOU during tcsetattr to prevent a hang if
1095 // the process is a member of the background process group
1096 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
1097 sigemptyset(&sigmask
);
1098 sigaddset(&sigmask
, SIGTTOU
);
1099 sigprocmask(SIG_BLOCK
,&sigmask
, &original_sigmask
);
1100 tcsetattr(0, TCSAFLUSH
, &rtt
);
1101 sigprocmask(SIG_SETMASK
, &original_sigmask
, 0);
1107 _config
->Set("APT::Keep-Fds::",fd
[1]);
1108 // send status information that we are about to fork dpkg
1109 if(OutStatusFd
> 0) {
1110 ostringstream status
;
1111 status
<< "pmstatus:dpkg-exec:"
1112 << (PackagesDone
/float(PackagesTotal
)*100.0)
1113 << ":" << _("Running dpkg")
1115 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
1119 // This is the child
1122 if(slave
>= 0 && master
>= 0)
1125 ioctl(slave
, TIOCSCTTY
, 0);
1132 close(fd
[0]); // close the read end of the pipe
1134 if (_config
->FindDir("DPkg::Chroot-Directory","/") != "/")
1136 std::cerr
<< "Chrooting into "
1137 << _config
->FindDir("DPkg::Chroot-Directory")
1139 if (chroot(_config
->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
1143 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
1146 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
1149 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
1152 // Discard everything in stdin before forking dpkg
1153 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
1156 while (read(STDIN_FILENO
,&dummy
,1) == 1);
1158 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
1162 /* No Job Control Stop Env is a magic dpkg var that prevents it
1163 from using sigstop */
1164 putenv((char *)"DPKG_NO_TSTP=yes");
1165 execvp(Args
[0],(char **)Args
);
1166 cerr
<< "Could not exec dpkg!" << endl
;
1171 if (_config
->FindB("DPkg::UseIoNice", false) == true)
1174 // clear the Keep-Fd again
1175 _config
->Clear("APT::Keep-Fds",fd
[1]);
1180 // we read from dpkg here
1181 int const _dpkgin
= fd
[0];
1182 close(fd
[1]); // close the write end of the pipe
1188 sigemptyset(&sigmask
);
1189 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
1191 /* clean up the temporary allocation for multiarch package names in
1192 the parent, so we don't leak memory when we return. */
1193 for (unsigned int i
= 0; i
< pkgcount
; i
++)
1196 // the result of the waitpid call
1199 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
1201 // FIXME: move this to a function or something, looks ugly here
1202 // error handling, waitpid returned -1
1205 RunScripts("DPkg::Post-Invoke");
1207 // Restore sig int/quit
1208 signal(SIGQUIT
,old_SIGQUIT
);
1209 signal(SIGINT
,old_SIGINT
);
1210 signal(SIGHUP
,old_SIGHUP
);
1211 return _error
->Errno("waitpid","Couldn't wait for subprocess");
1214 // wait for input or output here
1216 if (master
>= 0 && !stdin_is_dev_null
)
1218 FD_SET(_dpkgin
, &rfds
);
1220 FD_SET(master
, &rfds
);
1223 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
1224 &tv
, &original_sigmask
);
1225 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
1226 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
1227 NULL
, &tv
, &original_sigmask
);
1228 if (select_ret
== 0)
1230 else if (select_ret
< 0 && errno
== EINTR
)
1232 else if (select_ret
< 0)
1234 perror("select() returned error");
1238 if(master
>= 0 && FD_ISSET(master
, &rfds
))
1239 DoTerminalPty(master
);
1240 if(master
>= 0 && FD_ISSET(0, &rfds
))
1242 if(FD_ISSET(_dpkgin
, &rfds
))
1243 DoDpkgStatusFd(_dpkgin
, OutStatusFd
);
1247 // Restore sig int/quit
1248 signal(SIGQUIT
,old_SIGQUIT
);
1249 signal(SIGINT
,old_SIGINT
);
1250 signal(SIGHUP
,old_SIGHUP
);
1254 tcsetattr(0, TCSAFLUSH
, &tt
);
1258 // Check for an error code.
1259 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
1261 // if it was set to "keep-dpkg-runing" then we won't return
1262 // here but keep the loop going and just report it as a error
1264 bool const stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
1267 RunScripts("DPkg::Post-Invoke");
1269 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
1270 strprintf(dpkg_error
, "Sub-process %s received a segmentation fault.",Args
[0]);
1271 else if (WIFEXITED(Status
) != 0)
1272 strprintf(dpkg_error
, "Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
1274 strprintf(dpkg_error
, "Sub-process %s exited unexpectedly",Args
[0]);
1276 if(dpkg_error
.size() > 0)
1277 _error
->Error("%s", dpkg_error
.c_str());
1288 if (RunScripts("DPkg::Post-Invoke") == false)
1291 if (_config
->FindB("Debug::pkgDPkgPM",false) == false)
1293 std::string
const oldpkgcache
= _config
->FindFile("Dir::cache::pkgcache");
1294 if (oldpkgcache
.empty() == false && RealFileExists(oldpkgcache
) == true &&
1295 unlink(oldpkgcache
.c_str()) == 0)
1297 std::string
const srcpkgcache
= _config
->FindFile("Dir::cache::srcpkgcache");
1298 if (srcpkgcache
.empty() == false && RealFileExists(srcpkgcache
) == true)
1300 _error
->PushToStack();
1301 pkgCacheFile CacheFile
;
1302 CacheFile
.BuildCaches(NULL
, true);
1303 _error
->RevertToStack();
1308 Cache
.writeStateFile(NULL
);
1312 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1313 // ---------------------------------------------------------------------
1315 void pkgDPkgPM::Reset()
1317 List
.erase(List
.begin(),List
.end());
1320 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1321 // ---------------------------------------------------------------------
1323 void pkgDPkgPM::WriteApportReport(const char *pkgpath
, const char *errormsg
)
1325 string pkgname
, reportfile
, srcpkgname
, pkgver
, arch
;
1326 string::size_type pos
;
1329 if (_config
->FindB("Dpkg::ApportFailureReport", false) == false)
1331 std::clog
<< "configured to not write apport reports" << std::endl
;
1335 // only report the first errors
1336 if(pkgFailures
> _config
->FindI("APT::Apport::MaxReports", 3))
1338 std::clog
<< _("No apport report written because MaxReports is reached already") << std::endl
;
1342 // check if its not a follow up error
1343 const char *needle
= dgettext("dpkg", "dependency problems - leaving unconfigured");
1344 if(strstr(errormsg
, needle
) != NULL
) {
1345 std::clog
<< _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl
;
1349 // do not report disk-full failures
1350 if(strstr(errormsg
, strerror(ENOSPC
)) != NULL
) {
1351 std::clog
<< _("No apport report written because the error message indicates a disk full error") << std::endl
;
1355 // do not report out-of-memory failures
1356 if(strstr(errormsg
, strerror(ENOMEM
)) != NULL
) {
1357 std::clog
<< _("No apport report written because the error message indicates a out of memory error") << std::endl
;
1361 // do not report dpkg I/O errors
1362 // XXX - this message is localized, but this only matches the English version. This is better than nothing.
1363 if(strstr(errormsg
, "short read in buffer_copy (")) {
1364 std::clog
<< _("No apport report written because the error message indicates a dpkg I/O error") << std::endl
;
1368 // get the pkgname and reportfile
1369 pkgname
= flNotDir(pkgpath
);
1370 pos
= pkgname
.find('_');
1371 if(pos
!= string::npos
)
1372 pkgname
= pkgname
.substr(0, pos
);
1374 // find the package versin and source package name
1375 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
1376 if (Pkg
.end() == true)
1378 pkgCache::VerIterator Ver
= Cache
.GetCandidateVer(Pkg
);
1379 if (Ver
.end() == true)
1381 pkgver
= Ver
.VerStr() == NULL
? "unknown" : Ver
.VerStr();
1382 pkgRecords
Recs(Cache
);
1383 pkgRecords::Parser
&Parse
= Recs
.Lookup(Ver
.FileList());
1384 srcpkgname
= Parse
.SourcePkg();
1385 if(srcpkgname
.empty())
1386 srcpkgname
= pkgname
;
1388 // if the file exists already, we check:
1389 // - if it was reported already (touched by apport).
1390 // If not, we do nothing, otherwise
1391 // we overwrite it. This is the same behaviour as apport
1392 // - if we have a report with the same pkgversion already
1394 reportfile
= flCombine("/var/crash",pkgname
+".0.crash");
1395 if(FileExists(reportfile
))
1400 // check atime/mtime
1401 stat(reportfile
.c_str(), &buf
);
1402 if(buf
.st_mtime
> buf
.st_atime
)
1405 // check if the existing report is the same version
1406 report
= fopen(reportfile
.c_str(),"r");
1407 while(fgets(strbuf
, sizeof(strbuf
), report
) != NULL
)
1409 if(strstr(strbuf
,"Package:") == strbuf
)
1411 char pkgname
[255], version
[255];
1412 if(sscanf(strbuf
, "Package: %s %s", pkgname
, version
) == 2)
1413 if(strcmp(pkgver
.c_str(), version
) == 0)
1423 // now write the report
1424 arch
= _config
->Find("APT::Architecture");
1425 report
= fopen(reportfile
.c_str(),"w");
1428 if(_config
->FindB("DPkgPM::InitialReportOnly",false) == true)
1429 chmod(reportfile
.c_str(), 0);
1431 chmod(reportfile
.c_str(), 0600);
1432 fprintf(report
, "ProblemType: Package\n");
1433 fprintf(report
, "Architecture: %s\n", arch
.c_str());
1434 time_t now
= time(NULL
);
1435 fprintf(report
, "Date: %s" , ctime(&now
));
1436 fprintf(report
, "Package: %s %s\n", pkgname
.c_str(), pkgver
.c_str());
1437 fprintf(report
, "SourcePackage: %s\n", srcpkgname
.c_str());
1438 fprintf(report
, "ErrorMessage:\n %s\n", errormsg
);
1440 // ensure that the log is flushed
1444 // attach terminal log it if we have it
1445 string logfile_name
= _config
->FindFile("Dir::Log::Terminal");
1446 if (!logfile_name
.empty())
1451 fprintf(report
, "DpkgTerminalLog:\n");
1452 log
= fopen(logfile_name
.c_str(),"r");
1455 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1456 fprintf(report
, " %s", buf
);
1462 const char *ops_str
[] = {"Install", "Configure","Remove","Purge"};
1463 fprintf(report
, "AptOrdering:\n");
1464 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); ++I
)
1465 fprintf(report
, " %s: %s\n", (*I
).Pkg
.Name(), ops_str
[(*I
).Op
]);
1467 // attach dmesg log (to learn about segfaults)
1468 if (FileExists("/bin/dmesg"))
1473 fprintf(report
, "Dmesg:\n");
1474 log
= popen("/bin/dmesg","r");
1477 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1478 fprintf(report
, " %s", buf
);
1483 // attach df -l log (to learn about filesystem status)
1484 if (FileExists("/bin/df"))
1489 fprintf(report
, "Df:\n");
1490 log
= popen("/bin/df -l","r");
1493 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1494 fprintf(report
, " %s", buf
);