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>
18 #include <apt-pkg/fileutl.h>
23 #include <sys/select.h>
25 #include <sys/types.h>
38 #include <sys/ioctl.h>
47 class pkgDPkgPMPrivate
50 pkgDPkgPMPrivate() : dpkgbuf_pos(0), term_out(NULL
), history_out(NULL
)
53 bool stdin_is_dev_null
;
54 // the buffer we use for the dpkg status-fd reading
64 // Maps the dpkg "processing" info to human readable names. Entry 0
65 // of each array is the key, entry 1 is the value.
66 const std::pair
<const char *, const char *> PackageProcessingOps
[] = {
67 std::make_pair("install", N_("Installing %s")),
68 std::make_pair("configure", N_("Configuring %s")),
69 std::make_pair("remove", N_("Removing %s")),
70 std::make_pair("purge", N_("Completely removing %s")),
71 std::make_pair("disappear", N_("Noting disappearance of %s")),
72 std::make_pair("trigproc", N_("Running post-installation trigger %s"))
75 const std::pair
<const char *, const char *> * const PackageProcessingOpsBegin
= PackageProcessingOps
;
76 const std::pair
<const char *, const char *> * const PackageProcessingOpsEnd
= PackageProcessingOps
+ sizeof(PackageProcessingOps
) / sizeof(PackageProcessingOps
[0]);
78 // Predicate to test whether an entry in the PackageProcessingOps
79 // array matches a string.
80 class MatchProcessingOp
85 MatchProcessingOp(const char *the_target
)
90 bool operator()(const std::pair
<const char *, const char *> &pair
) const
92 return strcmp(pair
.first
, target
) == 0;
97 /* helper function to ionice the given PID
99 there is no C header for ionice yet - just the syscall interface
100 so we use the binary from util-linux
105 if (!FileExists("/usr/bin/ionice"))
107 pid_t Process
= ExecFork();
111 snprintf(buf
, sizeof(buf
), "-p%d", PID
);
113 Args
[0] = "/usr/bin/ionice";
117 execv(Args
[0], (char **)Args
);
119 return ExecWait(Process
, "ionice");
122 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
123 // ---------------------------------------------------------------------
125 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
126 : pkgPackageManager(Cache
), PackagesDone(0), PackagesTotal(0)
128 d
= new pkgDPkgPMPrivate();
131 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
132 // ---------------------------------------------------------------------
134 pkgDPkgPM::~pkgDPkgPM()
139 // DPkgPM::Install - Install a package /*{{{*/
140 // ---------------------------------------------------------------------
141 /* Add an install operation to the sequence list */
142 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
144 if (File
.empty() == true || Pkg
.end() == true)
145 return _error
->Error("Internal Error, No file name for %s",Pkg
.Name());
147 // If the filename string begins with DPkg::Chroot-Directory, return the
148 // substr that is within the chroot so dpkg can access it.
149 string
const chrootdir
= _config
->FindDir("DPkg::Chroot-Directory","/");
150 if (chrootdir
!= "/" && File
.find(chrootdir
) == 0)
152 size_t len
= chrootdir
.length();
153 if (chrootdir
.at(len
- 1) == '/')
155 List
.push_back(Item(Item::Install
,Pkg
,File
.substr(len
)));
158 List
.push_back(Item(Item::Install
,Pkg
,File
));
163 // DPkgPM::Configure - Configure a package /*{{{*/
164 // ---------------------------------------------------------------------
165 /* Add a configure operation to the sequence list */
166 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
168 if (Pkg
.end() == true)
171 List
.push_back(Item(Item::Configure
, Pkg
));
173 // Use triggers for config calls if we configure "smart"
174 // as otherwise Pre-Depends will not be satisfied, see #526774
175 if (_config
->FindB("DPkg::TriggersPending", false) == true)
176 List
.push_back(Item(Item::TriggersPending
, PkgIterator()));
181 // DPkgPM::Remove - Remove a package /*{{{*/
182 // ---------------------------------------------------------------------
183 /* Add a remove operation to the sequence list */
184 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
186 if (Pkg
.end() == true)
190 List
.push_back(Item(Item::Purge
,Pkg
));
192 List
.push_back(Item(Item::Remove
,Pkg
));
196 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
197 // ---------------------------------------------------------------------
198 /* This is part of the helper script communication interface, it sends
199 very complete information down to the other end of the pipe.*/
200 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
202 fprintf(F
,"VERSION 2\n");
204 /* Write out all of the configuration directives by walking the
205 configuration tree */
206 const Configuration::Item
*Top
= _config
->Tree(0);
209 if (Top
->Value
.empty() == false)
212 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
213 QuoteString(Top
->Value
,"\n").c_str());
222 while (Top
!= 0 && Top
->Next
== 0)
229 // Write out the package actions in order.
230 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
232 if(I
->Pkg
.end() == true)
235 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
237 fprintf(F
,"%s ",I
->Pkg
.Name());
239 if (I
->Pkg
->CurrentVer
== 0)
242 fprintf(F
,"%s ",I
->Pkg
.CurrentVer().VerStr());
244 // Show the compare operator
246 if (S
.InstallVer
!= 0)
249 if (I
->Pkg
->CurrentVer
!= 0)
250 Comp
= S
.InstVerIter(Cache
).CompareVer(I
->Pkg
.CurrentVer());
257 fprintf(F
,"%s ",S
.InstVerIter(Cache
).VerStr());
262 // Show the filename/operation
263 if (I
->Op
== Item::Install
)
266 if (I
->File
[0] != '/')
267 fprintf(F
,"**ERROR**\n");
269 fprintf(F
,"%s\n",I
->File
.c_str());
271 if (I
->Op
== Item::Configure
)
272 fprintf(F
,"**CONFIGURE**\n");
273 if (I
->Op
== Item::Remove
||
274 I
->Op
== Item::Purge
)
275 fprintf(F
,"**REMOVE**\n");
283 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
284 // ---------------------------------------------------------------------
285 /* This looks for a list of scripts to run from the configuration file
286 each one is run and is fed on standard input a list of all .deb files
287 that are due to be installed. */
288 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
290 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
291 if (Opts
== 0 || Opts
->Child
== 0)
295 unsigned int Count
= 1;
296 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
298 if (Opts
->Value
.empty() == true)
301 // Determine the protocol version
302 string OptSec
= Opts
->Value
;
303 string::size_type Pos
;
304 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
305 Pos
= OptSec
.length();
306 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
308 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
312 if (pipe(Pipes
) != 0)
313 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
314 SetCloseExec(Pipes
[0],true);
315 SetCloseExec(Pipes
[1],true);
317 // Purified Fork for running the script
318 pid_t Process
= ExecFork();
322 dup2(Pipes
[0],STDIN_FILENO
);
323 SetCloseExec(STDOUT_FILENO
,false);
324 SetCloseExec(STDIN_FILENO
,false);
325 SetCloseExec(STDERR_FILENO
,false);
327 if (_config
->FindDir("DPkg::Chroot-Directory","/") != "/")
329 std::cerr
<< "Chrooting into "
330 << _config
->FindDir("DPkg::Chroot-Directory")
332 if (chroot(_config
->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
339 Args
[2] = Opts
->Value
.c_str();
341 execv(Args
[0],(char **)Args
);
345 FILE *F
= fdopen(Pipes
[1],"w");
347 return _error
->Errno("fdopen","Faild to open new FD");
349 // Feed it the filenames.
352 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
354 // Only deal with packages to be installed from .deb
355 if (I
->Op
!= Item::Install
)
359 if (I
->File
[0] != '/')
362 /* Feed the filename of each package that is pending install
364 fprintf(F
,"%s\n",I
->File
.c_str());
374 // Clean up the sub process
375 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
376 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
382 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
383 // ---------------------------------------------------------------------
386 void pkgDPkgPM::DoStdin(int master
)
388 unsigned char input_buf
[256] = {0,};
389 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
391 write(master
, input_buf
, len
);
393 d
->stdin_is_dev_null
= true;
396 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
397 // ---------------------------------------------------------------------
399 * read the terminal pty and write log
401 void pkgDPkgPM::DoTerminalPty(int master
)
403 unsigned char term_buf
[1024] = {0,0, };
405 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
406 if(len
== -1 && errno
== EIO
)
408 // this happens when the child is about to exit, we
409 // give it time to actually exit, otherwise we run
410 // into a race so we sleep for half a second.
411 struct timespec sleepfor
= { 0, 500000000 };
412 nanosleep(&sleepfor
, NULL
);
417 write(1, term_buf
, len
);
419 fwrite(term_buf
, len
, sizeof(char), d
->term_out
);
422 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
423 // ---------------------------------------------------------------------
426 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd
, char *line
)
428 bool const Debug
= _config
->FindB("Debug::pkgDPkgProgressReporting",false);
429 // the status we output
430 ostringstream status
;
433 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
436 /* dpkg sends strings like this:
437 'status: <pkg>: <pkg qstate>'
438 errors look like this:
439 '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
440 and conffile-prompt like this
441 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
443 Newer versions of dpkg sent also:
444 'processing: install: pkg'
445 'processing: configure: pkg'
446 'processing: remove: pkg'
447 'processing: purge: pkg'
448 'processing: disappear: pkg'
449 'processing: trigproc: trigger'
453 // dpkg sends multiline error messages sometimes (see
454 // #374195 for a example. we should support this by
455 // either patching dpkg to not send multiline over the
456 // statusfd or by rewriting the code here to deal with
457 // it. for now we just ignore it and not crash
458 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
459 if( list
[0] == NULL
|| list
[1] == NULL
|| list
[2] == NULL
)
462 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
465 const char* const pkg
= list
[1];
466 const char* action
= _strstrip(list
[2]);
468 // 'processing' from dpkg looks like
469 // 'processing: action: pkg'
470 if(strncmp(list
[0], "processing", strlen("processing")) == 0)
473 const char* const pkg_or_trigger
= _strstrip(list
[2]);
474 action
= _strstrip( list
[1]);
475 const std::pair
<const char *, const char *> * const iter
=
476 std::find_if(PackageProcessingOpsBegin
,
477 PackageProcessingOpsEnd
,
478 MatchProcessingOp(action
));
479 if(iter
== PackageProcessingOpsEnd
)
482 std::clog
<< "ignoring unknown action: " << action
<< std::endl
;
485 snprintf(s
, sizeof(s
), _(iter
->second
), pkg_or_trigger
);
487 status
<< "pmstatus:" << pkg_or_trigger
488 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
492 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
494 std::clog
<< "send: '" << status
.str() << "'" << endl
;
496 if (strncmp(action
, "disappear", strlen("disappear")) == 0)
497 handleDisappearAction(pkg_or_trigger
);
501 if(strncmp(action
,"error",strlen("error")) == 0)
503 // urgs, sometime has ":" in its error string so that we
504 // end up with the error message split between list[3]
505 // and list[4], e.g. the message:
506 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
508 if( list
[4] != NULL
)
509 list
[3][strlen(list
[3])] = ':';
511 status
<< "pmerror:" << 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
;
520 WriteApportReport(list
[1], list
[3]);
523 else if(strncmp(action
,"conffile",strlen("conffile")) == 0)
525 status
<< "pmconffile:" << list
[1]
526 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
530 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
532 std::clog
<< "send: '" << status
.str() << "'" << endl
;
536 vector
<struct DpkgState
> const &states
= PackageOps
[pkg
];
537 const char *next_action
= NULL
;
538 if(PackageOpsDone
[pkg
] < states
.size())
539 next_action
= states
[PackageOpsDone
[pkg
]].state
;
540 // check if the package moved to the next dpkg state
541 if(next_action
&& (strcmp(action
, next_action
) == 0))
543 // only read the translation if there is actually a next
545 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
547 snprintf(s
, sizeof(s
), translation
, pkg
);
549 // we moved from one dpkg state to a new one, report that
550 PackageOpsDone
[pkg
]++;
552 // build the status str
553 status
<< "pmstatus:" << pkg
554 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
558 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
560 std::clog
<< "send: '" << status
.str() << "'" << endl
;
563 std::clog
<< "(parsed from dpkg) pkg: " << pkg
564 << " action: " << action
<< endl
;
567 // DPkgPM::handleDisappearAction /*{{{*/
568 void pkgDPkgPM::handleDisappearAction(string
const &pkgname
)
570 // record the package name for display and stuff later
571 disappearedPkgs
.insert(pkgname
);
573 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
574 if (unlikely(Pkg
.end() == true))
576 // the disappeared package was auto-installed - nothing to do
577 if ((Cache
[Pkg
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
579 pkgCache::VerIterator PkgVer
= Cache
[Pkg
].InstVerIter(Cache
);
580 if (unlikely(PkgVer
.end() == true))
582 /* search in the list of dependencies for (Pre)Depends,
583 check if this dependency has a Replaces on our package
584 and if so transfer the manual installed flag to it */
585 for (pkgCache::DepIterator Dep
= PkgVer
.DependsList(); Dep
.end() != true; ++Dep
)
587 if (Dep
->Type
!= pkgCache::Dep::Depends
&&
588 Dep
->Type
!= pkgCache::Dep::PreDepends
)
590 pkgCache::PkgIterator Tar
= Dep
.TargetPkg();
591 if (unlikely(Tar
.end() == true))
593 // the package is already marked as manual
594 if ((Cache
[Tar
].Flags
& pkgCache::Flag::Auto
) != pkgCache::Flag::Auto
)
596 pkgCache::VerIterator TarVer
= Cache
[Tar
].InstVerIter(Cache
);
597 if (TarVer
.end() == true)
599 for (pkgCache::DepIterator Rep
= TarVer
.DependsList(); Rep
.end() != true; ++Rep
)
601 if (Rep
->Type
!= pkgCache::Dep::Replaces
)
603 if (Pkg
!= Rep
.TargetPkg())
605 // okay, they are strongly connected - transfer manual-bit
607 std::clog
<< "transfer manual-bit from disappeared »" << pkgname
<< "« to »" << Tar
.FullName() << "«" << std::endl
;
608 Cache
[Tar
].Flags
&= ~Flag::Auto
;
614 // DPkgPM::DoDpkgStatusFd /*{{{*/
615 // ---------------------------------------------------------------------
618 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
, int OutStatusFd
)
623 len
=read(statusfd
, &d
->dpkgbuf
[d
->dpkgbuf_pos
], sizeof(d
->dpkgbuf
)-d
->dpkgbuf_pos
);
624 d
->dpkgbuf_pos
+= len
;
628 // process line by line if we have a buffer
630 while((q
=(char*)memchr(p
, '\n', d
->dpkgbuf
+d
->dpkgbuf_pos
-p
)) != NULL
)
633 ProcessDpkgStatusLine(OutStatusFd
, p
);
634 p
=q
+1; // continue with next line
637 // now move the unprocessed bits (after the final \n that is now a 0x0)
638 // to the start and update d->dpkgbuf_pos
639 p
= (char*)memrchr(d
->dpkgbuf
, 0, d
->dpkgbuf_pos
);
643 // we are interessted in the first char *after* 0x0
646 // move the unprocessed tail to the start and update pos
647 memmove(d
->dpkgbuf
, p
, p
-d
->dpkgbuf
);
648 d
->dpkgbuf_pos
= d
->dpkgbuf
+d
->dpkgbuf_pos
-p
;
651 // DPkgPM::WriteHistoryTag /*{{{*/
652 void pkgDPkgPM::WriteHistoryTag(string
const &tag
, string value
)
654 size_t const length
= value
.length();
657 // poor mans rstrip(", ")
658 if (value
[length
-2] == ',' && value
[length
-1] == ' ')
659 value
.erase(length
- 2, 2);
660 fprintf(d
->history_out
, "%s: %s\n", tag
.c_str(), value
.c_str());
662 // DPkgPM::OpenLog /*{{{*/
663 bool pkgDPkgPM::OpenLog()
665 string
const logdir
= _config
->FindDir("Dir::Log");
666 if(CreateAPTDirectoryIfNeeded(logdir
, logdir
) == false)
667 // FIXME: use a better string after freeze
668 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
672 time_t const t
= time(NULL
);
673 struct tm
const * const tmp
= localtime(&t
);
674 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
677 string
const logfile_name
= flCombine(logdir
,
678 _config
->Find("Dir::Log::Terminal"));
679 if (!logfile_name
.empty())
681 d
->term_out
= fopen(logfile_name
.c_str(),"a");
682 if (d
->term_out
== NULL
)
683 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name
.c_str());
684 setvbuf(d
->term_out
, NULL
, _IONBF
, 0);
685 SetCloseExec(fileno(d
->term_out
), true);
686 chmod(logfile_name
.c_str(), 0600);
687 fprintf(d
->term_out
, "\nLog started: %s\n", timestr
);
690 // write your history
691 string
const history_name
= flCombine(logdir
,
692 _config
->Find("Dir::Log::History"));
693 if (!history_name
.empty())
695 d
->history_out
= fopen(history_name
.c_str(),"a");
696 if (d
->history_out
== NULL
)
697 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), history_name
.c_str());
698 chmod(history_name
.c_str(), 0644);
699 fprintf(d
->history_out
, "\nStart-Date: %s\n", timestr
);
700 string remove
, purge
, install
, upgrade
, downgrade
;
701 for (pkgCache::PkgIterator I
= Cache
.PkgBegin(); I
.end() == false; I
++)
703 if (Cache
[I
].NewInstall())
705 install
+= I
.FullName(false) + string(" (") + Cache
[I
].CandVersion
;
706 if (Cache
[I
].Flags
& pkgCache::Flag::Auto
)
707 install
+= ", automatic";
708 install
+= string("), ");
710 else if (Cache
[I
].Upgrade())
711 upgrade
+= I
.FullName(false) + string(" (") + Cache
[I
].CurVersion
+ string(", ") + Cache
[I
].CandVersion
+ string("), ");
712 else if (Cache
[I
].Downgrade())
713 downgrade
+= I
.FullName(false) + string(" (") + Cache
[I
].CurVersion
+ string(", ") + Cache
[I
].CandVersion
+ string("), ");
714 else if (Cache
[I
].Delete())
716 if ((Cache
[I
].iFlags
& pkgDepCache::Purge
) == pkgDepCache::Purge
)
717 purge
+= I
.FullName(false) + string(" (") + Cache
[I
].CurVersion
+ string("), ");
719 remove
+= I
.FullName(false) + string(" (") + Cache
[I
].CurVersion
+ string("), ");
722 if (_config
->Exists("Commandline::AsString") == true)
723 WriteHistoryTag("Commandline", _config
->Find("Commandline::AsString"));
724 WriteHistoryTag("Install", install
);
725 WriteHistoryTag("Upgrade", upgrade
);
726 WriteHistoryTag("Downgrade",downgrade
);
727 WriteHistoryTag("Remove",remove
);
728 WriteHistoryTag("Purge",purge
);
729 fflush(d
->history_out
);
735 // DPkg::CloseLog /*{{{*/
736 bool pkgDPkgPM::CloseLog()
739 time_t t
= time(NULL
);
740 struct tm
*tmp
= localtime(&t
);
741 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
745 fprintf(d
->term_out
, "Log ended: ");
746 fprintf(d
->term_out
, "%s", timestr
);
747 fprintf(d
->term_out
, "\n");
754 if (disappearedPkgs
.empty() == false)
757 for (std::set
<std::string
>::const_iterator d
= disappearedPkgs
.begin();
758 d
!= disappearedPkgs
.end(); ++d
)
760 pkgCache::PkgIterator P
= Cache
.FindPkg(*d
);
761 disappear
.append(*d
);
763 disappear
.append(", ");
765 disappear
.append(" (").append(Cache
[P
].CurVersion
).append("), ");
767 WriteHistoryTag("Disappeared", disappear
);
769 if (d
->dpkg_error
.empty() == false)
770 fprintf(d
->history_out
, "Error: %s\n", d
->dpkg_error
.c_str());
771 fprintf(d
->history_out
, "End-Date: %s\n", timestr
);
772 fclose(d
->history_out
);
774 d
->history_out
= NULL
;
780 // This implements a racy version of pselect for those architectures
781 // that don't have a working implementation.
782 // FIXME: Probably can be removed on Lenny+1
783 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
784 fd_set
*exceptfds
, const struct timespec
*timeout
,
785 const sigset_t
*sigmask
)
791 tv
.tv_sec
= timeout
->tv_sec
;
792 tv
.tv_usec
= timeout
->tv_nsec
/1000;
794 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
795 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
796 sigprocmask(SIG_SETMASK
, &origmask
, 0);
800 // DPkgPM::Go - Run the sequence /*{{{*/
801 // ---------------------------------------------------------------------
802 /* This globs the operations and calls dpkg
804 * If it is called with "OutStatusFd" set to a valid file descriptor
805 * apt will report the install progress over this fd. It maps the
806 * dpkg states a package goes through to human readable (and i10n-able)
807 * names and calculates a percentage for each step.
809 bool pkgDPkgPM::Go(int OutStatusFd
)
814 sigset_t original_sigmask
;
816 unsigned int const MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
817 unsigned int const MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
818 bool const NoTriggers
= _config
->FindB("DPkg::NoTriggers", false);
820 if (RunScripts("DPkg::Pre-Invoke") == false)
823 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
826 // support subpressing of triggers processing for special
827 // cases like d-i that runs the triggers handling manually
828 bool const SmartConf
= (_config
->Find("PackageManager::Configure", "all") != "all");
829 bool const TriggersPending
= _config
->FindB("DPkg::TriggersPending", false);
830 if (_config
->FindB("DPkg::ConfigurePending", SmartConf
) == true)
831 List
.push_back(Item(Item::ConfigurePending
, PkgIterator()));
833 // map the dpkg states to the operations that are performed
834 // (this is sorted in the same way as Item::Ops)
835 static const struct DpkgState DpkgStatesOpMap
[][7] = {
838 {"half-installed", N_("Preparing %s")},
839 {"unpacked", N_("Unpacking %s") },
842 // Configure operation
844 {"unpacked",N_("Preparing to configure %s") },
845 {"half-configured", N_("Configuring %s") },
846 { "installed", N_("Installed %s")},
851 {"half-configured", N_("Preparing for removal of %s")},
852 {"half-installed", N_("Removing %s")},
853 {"config-files", N_("Removed %s")},
858 {"config-files", N_("Preparing to completely remove %s")},
859 {"not-installed", N_("Completely removed %s")},
864 // init the PackageOps map, go over the list of packages that
865 // that will be [installed|configured|removed|purged] and add
866 // them to the PackageOps map (the dpkg states it goes through)
867 // and the PackageOpsTranslations (human readable strings)
868 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();I
++)
870 if((*I
).Pkg
.end() == true)
873 string
const name
= (*I
).Pkg
.Name();
874 PackageOpsDone
[name
] = 0;
875 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; i
++)
877 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
882 d
->stdin_is_dev_null
= false;
887 // this loop is runs once per operation
888 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();)
890 // Do all actions with the same Op in one run
891 vector
<Item
>::const_iterator J
= I
;
892 if (TriggersPending
== true)
893 for (; J
!= List
.end(); J
++)
897 if (J
->Op
!= Item::TriggersPending
)
899 vector
<Item
>::const_iterator T
= J
+ 1;
900 if (T
!= List
.end() && T
->Op
== I
->Op
)
905 for (; J
!= List
.end() && J
->Op
== I
->Op
; J
++)
908 // Generate the argument list
909 const char *Args
[MaxArgs
+ 50];
910 // keep track of allocated strings for multiarch package names
911 char *Packages
[MaxArgs
+ 50];
912 unsigned int pkgcount
= 0;
914 // Now check if we are within the MaxArgs limit
916 // this code below is problematic, because it may happen that
917 // the argument list is split in a way that A depends on B
918 // and they are in the same "--configure A B" run
919 // - with the split they may now be configured in different
921 if (J
- I
> (signed)MaxArgs
)
925 unsigned long Size
= 0;
926 string
const Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
927 Args
[n
++] = Tmp
.c_str();
928 Size
+= strlen(Args
[n
-1]);
930 // Stick in any custom dpkg options
931 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
935 for (; Opts
!= 0; Opts
= Opts
->Next
)
937 if (Opts
->Value
.empty() == true)
939 Args
[n
++] = Opts
->Value
.c_str();
940 Size
+= Opts
->Value
.length();
944 char status_fd_buf
[20];
948 Args
[n
++] = "--status-fd";
949 Size
+= strlen(Args
[n
-1]);
950 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
951 Args
[n
++] = status_fd_buf
;
952 Size
+= strlen(Args
[n
-1]);
957 Args
[n
++] = "--force-depends";
958 Size
+= strlen(Args
[n
-1]);
959 Args
[n
++] = "--force-remove-essential";
960 Size
+= strlen(Args
[n
-1]);
961 Args
[n
++] = "--remove";
962 Size
+= strlen(Args
[n
-1]);
966 Args
[n
++] = "--force-depends";
967 Size
+= strlen(Args
[n
-1]);
968 Args
[n
++] = "--force-remove-essential";
969 Size
+= strlen(Args
[n
-1]);
970 Args
[n
++] = "--purge";
971 Size
+= strlen(Args
[n
-1]);
974 case Item::Configure
:
975 Args
[n
++] = "--configure";
976 Size
+= strlen(Args
[n
-1]);
979 case Item::ConfigurePending
:
980 Args
[n
++] = "--configure";
981 Size
+= strlen(Args
[n
-1]);
982 Args
[n
++] = "--pending";
983 Size
+= strlen(Args
[n
-1]);
986 case Item::TriggersPending
:
987 Args
[n
++] = "--triggers-only";
988 Size
+= strlen(Args
[n
-1]);
989 Args
[n
++] = "--pending";
990 Size
+= strlen(Args
[n
-1]);
994 Args
[n
++] = "--unpack";
995 Size
+= strlen(Args
[n
-1]);
996 Args
[n
++] = "--auto-deconfigure";
997 Size
+= strlen(Args
[n
-1]);
1001 if (NoTriggers
== true && I
->Op
!= Item::TriggersPending
&&
1002 I
->Op
!= Item::ConfigurePending
)
1004 Args
[n
++] = "--no-triggers";
1005 Size
+= strlen(Args
[n
-1]);
1008 // Write in the file or package names
1009 if (I
->Op
== Item::Install
)
1011 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
1013 if (I
->File
[0] != '/')
1014 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
1015 Args
[n
++] = I
->File
.c_str();
1016 Size
+= strlen(Args
[n
-1]);
1021 string
const nativeArch
= _config
->Find("APT::Architecture");
1022 unsigned long const oldSize
= I
->Op
== Item::Configure
? Size
: 0;
1023 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
1025 if((*I
).Pkg
.end() == true)
1027 if (I
->Op
== Item::Configure
&& disappearedPkgs
.find(I
->Pkg
.Name()) != disappearedPkgs
.end())
1029 if (I
->Pkg
.Arch() == nativeArch
|| !strcmp(I
->Pkg
.Arch(), "all"))
1030 Args
[n
++] = I
->Pkg
.Name();
1033 Packages
[pkgcount
] = strdup(I
->Pkg
.FullName(false).c_str());
1034 Args
[n
++] = Packages
[pkgcount
++];
1036 Size
+= strlen(Args
[n
-1]);
1038 // skip configure action if all sheduled packages disappeared
1039 if (oldSize
== Size
)
1045 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
1047 for (unsigned int k
= 0; k
!= n
; k
++)
1048 clog
<< Args
[k
] << ' ';
1057 /* Mask off sig int/quit. We do this because dpkg also does when
1058 it forks scripts. What happens is that when you hit ctrl-c it sends
1059 it to all processes in the group. Since dpkg ignores the signal
1060 it doesn't die but we do! So we must also ignore it */
1061 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
1062 sighandler_t old_SIGINT
= signal(SIGINT
,SIG_IGN
);
1064 // ignore SIGHUP as well (debian #463030)
1065 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
1072 // if tcgetattr does not return zero there was a error
1073 // and we do not do any pty magic
1074 if (tcgetattr(0, &tt
) == 0)
1076 ioctl(0, TIOCGWINSZ
, (char *)&win
);
1077 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
1079 const char *s
= _("Can not write log, openpty() "
1080 "failed (/dev/pts not mounted?)\n");
1081 fprintf(stderr
, "%s",s
);
1083 fprintf(d
->term_out
, "%s",s
);
1084 master
= slave
= -1;
1089 rtt
.c_lflag
&= ~ECHO
;
1090 rtt
.c_lflag
|= ISIG
;
1091 // block SIGTTOU during tcsetattr to prevent a hang if
1092 // the process is a member of the background process group
1093 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
1094 sigemptyset(&sigmask
);
1095 sigaddset(&sigmask
, SIGTTOU
);
1096 sigprocmask(SIG_BLOCK
,&sigmask
, &original_sigmask
);
1097 tcsetattr(0, TCSAFLUSH
, &rtt
);
1098 sigprocmask(SIG_SETMASK
, &original_sigmask
, 0);
1104 _config
->Set("APT::Keep-Fds::",fd
[1]);
1105 // send status information that we are about to fork dpkg
1106 if(OutStatusFd
> 0) {
1107 ostringstream status
;
1108 status
<< "pmstatus:dpkg-exec:"
1109 << (PackagesDone
/float(PackagesTotal
)*100.0)
1110 << ":" << _("Running dpkg")
1112 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
1116 // This is the child
1119 if(slave
>= 0 && master
>= 0)
1122 ioctl(slave
, TIOCSCTTY
, 0);
1129 close(fd
[0]); // close the read end of the pipe
1131 if (_config
->FindDir("DPkg::Chroot-Directory","/") != "/")
1133 std::cerr
<< "Chrooting into "
1134 << _config
->FindDir("DPkg::Chroot-Directory")
1136 if (chroot(_config
->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
1140 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
1143 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
1146 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
1149 // Discard everything in stdin before forking dpkg
1150 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
1153 while (read(STDIN_FILENO
,&dummy
,1) == 1);
1155 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
1159 /* No Job Control Stop Env is a magic dpkg var that prevents it
1160 from using sigstop */
1161 putenv((char *)"DPKG_NO_TSTP=yes");
1162 execvp(Args
[0],(char **)Args
);
1163 cerr
<< "Could not exec dpkg!" << endl
;
1168 if (_config
->FindB("DPkg::UseIoNice", false) == true)
1171 // clear the Keep-Fd again
1172 _config
->Clear("APT::Keep-Fds",fd
[1]);
1177 // we read from dpkg here
1178 int const _dpkgin
= fd
[0];
1179 close(fd
[1]); // close the write end of the pipe
1185 sigemptyset(&sigmask
);
1186 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
1188 /* clean up the temporary allocation for multiarch package names in
1189 the parent, so we don't leak memory when we return. */
1190 for (unsigned int i
= 0; i
< pkgcount
; i
++)
1193 // the result of the waitpid call
1196 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
1198 // FIXME: move this to a function or something, looks ugly here
1199 // error handling, waitpid returned -1
1202 RunScripts("DPkg::Post-Invoke");
1204 // Restore sig int/quit
1205 signal(SIGQUIT
,old_SIGQUIT
);
1206 signal(SIGINT
,old_SIGINT
);
1207 signal(SIGHUP
,old_SIGHUP
);
1208 return _error
->Errno("waitpid","Couldn't wait for subprocess");
1211 // wait for input or output here
1213 if (master
>= 0 && !d
->stdin_is_dev_null
)
1215 FD_SET(_dpkgin
, &rfds
);
1217 FD_SET(master
, &rfds
);
1220 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
1221 &tv
, &original_sigmask
);
1222 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
1223 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
1224 NULL
, &tv
, &original_sigmask
);
1225 if (select_ret
== 0)
1227 else if (select_ret
< 0 && errno
== EINTR
)
1229 else if (select_ret
< 0)
1231 perror("select() returned error");
1235 if(master
>= 0 && FD_ISSET(master
, &rfds
))
1236 DoTerminalPty(master
);
1237 if(master
>= 0 && FD_ISSET(0, &rfds
))
1239 if(FD_ISSET(_dpkgin
, &rfds
))
1240 DoDpkgStatusFd(_dpkgin
, OutStatusFd
);
1244 // Restore sig int/quit
1245 signal(SIGQUIT
,old_SIGQUIT
);
1246 signal(SIGINT
,old_SIGINT
);
1247 signal(SIGHUP
,old_SIGHUP
);
1251 tcsetattr(0, TCSAFLUSH
, &tt
);
1255 // Check for an error code.
1256 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
1258 // if it was set to "keep-dpkg-runing" then we won't return
1259 // here but keep the loop going and just report it as a error
1261 bool const stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
1264 RunScripts("DPkg::Post-Invoke");
1266 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
1267 strprintf(d
->dpkg_error
, "Sub-process %s received a segmentation fault.",Args
[0]);
1268 else if (WIFEXITED(Status
) != 0)
1269 strprintf(d
->dpkg_error
, "Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
1271 strprintf(d
->dpkg_error
, "Sub-process %s exited unexpectedly",Args
[0]);
1273 if(d
->dpkg_error
.size() > 0)
1274 _error
->Error("%s", d
->dpkg_error
.c_str());
1285 if (RunScripts("DPkg::Post-Invoke") == false)
1288 Cache
.writeStateFile(NULL
);
1292 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1293 // ---------------------------------------------------------------------
1295 void pkgDPkgPM::Reset()
1297 List
.erase(List
.begin(),List
.end());
1300 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1301 // ---------------------------------------------------------------------
1303 void pkgDPkgPM::WriteApportReport(const char *pkgpath
, const char *errormsg
)
1305 string pkgname
, reportfile
, srcpkgname
, pkgver
, arch
;
1306 string::size_type pos
;
1309 if (_config
->FindB("Dpkg::ApportFailureReport", false) == false)
1311 std::clog
<< "configured to not write apport reports" << std::endl
;
1315 // only report the first errors
1316 if(pkgFailures
> _config
->FindI("APT::Apport::MaxReports", 3))
1318 std::clog
<< _("No apport report written because MaxReports is reached already") << std::endl
;
1322 // check if its not a follow up error
1323 const char *needle
= dgettext("dpkg", "dependency problems - leaving unconfigured");
1324 if(strstr(errormsg
, needle
) != NULL
) {
1325 std::clog
<< _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl
;
1329 // do not report disk-full failures
1330 if(strstr(errormsg
, strerror(ENOSPC
)) != NULL
) {
1331 std::clog
<< _("No apport report written because the error message indicates a disk full error") << std::endl
;
1335 // do not report out-of-memory failures
1336 if(strstr(errormsg
, strerror(ENOMEM
)) != NULL
) {
1337 std::clog
<< _("No apport report written because the error message indicates a out of memory error") << std::endl
;
1341 // do not report dpkg I/O errors
1342 // XXX - this message is localized, but this only matches the English version. This is better than nothing.
1343 if(strstr(errormsg
, "short read in buffer_copy (")) {
1344 std::clog
<< _("No apport report written because the error message indicates a dpkg I/O error") << std::endl
;
1348 // get the pkgname and reportfile
1349 pkgname
= flNotDir(pkgpath
);
1350 pos
= pkgname
.find('_');
1351 if(pos
!= string::npos
)
1352 pkgname
= pkgname
.substr(0, pos
);
1354 // find the package versin and source package name
1355 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
1356 if (Pkg
.end() == true)
1358 pkgCache::VerIterator Ver
= Cache
.GetCandidateVer(Pkg
);
1359 if (Ver
.end() == true)
1361 pkgver
= Ver
.VerStr() == NULL
? "unknown" : Ver
.VerStr();
1362 pkgRecords
Recs(Cache
);
1363 pkgRecords::Parser
&Parse
= Recs
.Lookup(Ver
.FileList());
1364 srcpkgname
= Parse
.SourcePkg();
1365 if(srcpkgname
.empty())
1366 srcpkgname
= pkgname
;
1368 // if the file exists already, we check:
1369 // - if it was reported already (touched by apport).
1370 // If not, we do nothing, otherwise
1371 // we overwrite it. This is the same behaviour as apport
1372 // - if we have a report with the same pkgversion already
1374 reportfile
= flCombine("/var/crash",pkgname
+".0.crash");
1375 if(FileExists(reportfile
))
1380 // check atime/mtime
1381 stat(reportfile
.c_str(), &buf
);
1382 if(buf
.st_mtime
> buf
.st_atime
)
1385 // check if the existing report is the same version
1386 report
= fopen(reportfile
.c_str(),"r");
1387 while(fgets(strbuf
, sizeof(strbuf
), report
) != NULL
)
1389 if(strstr(strbuf
,"Package:") == strbuf
)
1391 char pkgname
[255], version
[255];
1392 if(sscanf(strbuf
, "Package: %s %s", pkgname
, version
) == 2)
1393 if(strcmp(pkgver
.c_str(), version
) == 0)
1403 // now write the report
1404 arch
= _config
->Find("APT::Architecture");
1405 report
= fopen(reportfile
.c_str(),"w");
1408 if(_config
->FindB("DPkgPM::InitialReportOnly",false) == true)
1409 chmod(reportfile
.c_str(), 0);
1411 chmod(reportfile
.c_str(), 0600);
1412 fprintf(report
, "ProblemType: Package\n");
1413 fprintf(report
, "Architecture: %s\n", arch
.c_str());
1414 time_t now
= time(NULL
);
1415 fprintf(report
, "Date: %s" , ctime(&now
));
1416 fprintf(report
, "Package: %s %s\n", pkgname
.c_str(), pkgver
.c_str());
1417 fprintf(report
, "SourcePackage: %s\n", srcpkgname
.c_str());
1418 fprintf(report
, "ErrorMessage:\n %s\n", errormsg
);
1420 // ensure that the log is flushed
1422 fflush(d
->term_out
);
1424 // attach terminal log it if we have it
1425 string logfile_name
= _config
->FindFile("Dir::Log::Terminal");
1426 if (!logfile_name
.empty())
1431 fprintf(report
, "DpkgTerminalLog:\n");
1432 log
= fopen(logfile_name
.c_str(),"r");
1435 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1436 fprintf(report
, " %s", buf
);
1442 const char *ops_str
[] = {"Install", "Configure","Remove","Purge"};
1443 fprintf(report
, "AptOrdering:\n");
1444 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
1445 fprintf(report
, " %s: %s\n", (*I
).Pkg
.Name(), ops_str
[(*I
).Op
]);
1447 // attach dmesg log (to learn about segfaults)
1448 if (FileExists("/bin/dmesg"))
1453 fprintf(report
, "Dmesg:\n");
1454 log
= popen("/bin/dmesg","r");
1457 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1458 fprintf(report
, " %s", buf
);
1463 // attach df -l log (to learn about filesystem status)
1464 if (FileExists("/bin/df"))
1469 fprintf(report
, "Df:\n");
1470 log
= popen("/bin/df -l","r");
1473 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1474 fprintf(report
, " %s", buf
);