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);
330 Args
[2] = Opts
->Value
.c_str();
332 execv(Args
[0],(char **)Args
);
336 FILE *F
= fdopen(Pipes
[1],"w");
338 return _error
->Errno("fdopen","Faild to open new FD");
340 // Feed it the filenames.
344 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
346 // Only deal with packages to be installed from .deb
347 if (I
->Op
!= Item::Install
)
351 if (I
->File
[0] != '/')
354 /* Feed the filename of each package that is pending install
356 fprintf(F
,"%s\n",I
->File
.c_str());
365 Die
= !SendV2Pkgs(F
);
369 // Clean up the sub process
370 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
371 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
377 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
378 // ---------------------------------------------------------------------
381 void pkgDPkgPM::DoStdin(int master
)
383 unsigned char input_buf
[256] = {0,};
384 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
386 write(master
, input_buf
, len
);
388 d
->stdin_is_dev_null
= true;
391 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
392 // ---------------------------------------------------------------------
394 * read the terminal pty and write log
396 void pkgDPkgPM::DoTerminalPty(int master
)
398 unsigned char term_buf
[1024] = {0,0, };
400 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
401 if(len
== -1 && errno
== EIO
)
403 // this happens when the child is about to exit, we
404 // give it time to actually exit, otherwise we run
411 write(1, term_buf
, len
);
413 fwrite(term_buf
, len
, sizeof(char), d
->term_out
);
416 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
417 // ---------------------------------------------------------------------
420 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd
, char *line
)
422 bool const Debug
= _config
->FindB("Debug::pkgDPkgProgressReporting",false);
423 // the status we output
424 ostringstream status
;
427 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
430 /* dpkg sends strings like this:
431 'status: <pkg>: <pkg qstate>'
432 errors look like this:
433 '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
434 and conffile-prompt like this
435 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
437 Newer versions of dpkg sent also:
438 'processing: install: pkg'
439 'processing: configure: pkg'
440 'processing: remove: pkg'
441 'processing: purge: pkg'
442 'processing: disappear: pkg'
443 'processing: trigproc: trigger'
447 // dpkg sends multiline error messages sometimes (see
448 // #374195 for a example. we should support this by
449 // either patching dpkg to not send multiline over the
450 // statusfd or by rewriting the code here to deal with
451 // it. for now we just ignore it and not crash
452 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
453 if( list
[0] == NULL
|| list
[1] == NULL
|| list
[2] == NULL
)
456 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
459 const char* const pkg
= list
[1];
460 const char* action
= _strstrip(list
[2]);
462 // 'processing' from dpkg looks like
463 // 'processing: action: pkg'
464 if(strncmp(list
[0], "processing", strlen("processing")) == 0)
467 const char* const pkg_or_trigger
= _strstrip(list
[2]);
468 action
= _strstrip( list
[1]);
469 const std::pair
<const char *, const char *> * const iter
=
470 std::find_if(PackageProcessingOpsBegin
,
471 PackageProcessingOpsEnd
,
472 MatchProcessingOp(action
));
473 if(iter
== PackageProcessingOpsEnd
)
476 std::clog
<< "ignoring unknown action: " << action
<< std::endl
;
479 snprintf(s
, sizeof(s
), _(iter
->second
), pkg_or_trigger
);
481 status
<< "pmstatus:" << pkg_or_trigger
482 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
486 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
488 std::clog
<< "send: '" << status
.str() << "'" << endl
;
490 if (strncmp(action
, "disappear", strlen("disappear")) == 0)
491 handleDisappearAction(pkg_or_trigger
);
495 if(strncmp(action
,"error",strlen("error")) == 0)
497 // urgs, sometime has ":" in its error string so that we
498 // end up with the error message split between list[3]
499 // and list[4], e.g. the message:
500 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
502 if( list
[4] != NULL
)
503 list
[3][strlen(list
[3])] = ':';
505 status
<< "pmerror:" << list
[1]
506 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
510 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
512 std::clog
<< "send: '" << status
.str() << "'" << endl
;
514 WriteApportReport(list
[1], list
[3]);
517 else if(strncmp(action
,"conffile",strlen("conffile")) == 0)
519 status
<< "pmconffile:" << list
[1]
520 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
524 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
526 std::clog
<< "send: '" << status
.str() << "'" << endl
;
530 vector
<struct DpkgState
> const &states
= PackageOps
[pkg
];
531 const char *next_action
= NULL
;
532 if(PackageOpsDone
[pkg
] < states
.size())
533 next_action
= states
[PackageOpsDone
[pkg
]].state
;
534 // check if the package moved to the next dpkg state
535 if(next_action
&& (strcmp(action
, next_action
) == 0))
537 // only read the translation if there is actually a next
539 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
541 snprintf(s
, sizeof(s
), translation
, pkg
);
543 // we moved from one dpkg state to a new one, report that
544 PackageOpsDone
[pkg
]++;
546 // build the status str
547 status
<< "pmstatus:" << pkg
548 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
552 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
554 std::clog
<< "send: '" << status
.str() << "'" << endl
;
557 std::clog
<< "(parsed from dpkg) pkg: " << pkg
558 << " action: " << action
<< endl
;
561 // DPkgPM::handleDisappearAction /*{{{*/
562 void pkgDPkgPM::handleDisappearAction(string
const &pkgname
)
564 // record the package name for display and stuff later
565 disappearedPkgs
.insert(pkgname
);
567 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
568 if (unlikely(Pkg
.end() == true))
570 // the disappeared package was auto-installed - nothing to do
571 if ((Cache
[Pkg
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
573 pkgCache::VerIterator PkgVer
= Cache
[Pkg
].InstVerIter(Cache
);
574 if (unlikely(PkgVer
.end() == true))
576 /* search in the list of dependencies for (Pre)Depends,
577 check if this dependency has a Replaces on our package
578 and if so transfer the manual installed flag to it */
579 for (pkgCache::DepIterator Dep
= PkgVer
.DependsList(); Dep
.end() != true; ++Dep
)
581 if (Dep
->Type
!= pkgCache::Dep::Depends
&&
582 Dep
->Type
!= pkgCache::Dep::PreDepends
)
584 pkgCache::PkgIterator Tar
= Dep
.TargetPkg();
585 if (unlikely(Tar
.end() == true))
587 // the package is already marked as manual
588 if ((Cache
[Tar
].Flags
& pkgCache::Flag::Auto
) != pkgCache::Flag::Auto
)
590 pkgCache::VerIterator TarVer
= Cache
[Tar
].InstVerIter(Cache
);
591 if (TarVer
.end() == true)
593 for (pkgCache::DepIterator Rep
= TarVer
.DependsList(); Rep
.end() != true; ++Rep
)
595 if (Rep
->Type
!= pkgCache::Dep::Replaces
)
597 if (Pkg
!= Rep
.TargetPkg())
599 // okay, they are strongly connected - transfer manual-bit
601 std::clog
<< "transfer manual-bit from disappeared »" << pkgname
<< "« to »" << Tar
.FullName() << "«" << std::endl
;
602 Cache
[Tar
].Flags
&= ~Flag::Auto
;
608 // DPkgPM::DoDpkgStatusFd /*{{{*/
609 // ---------------------------------------------------------------------
612 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
, int OutStatusFd
)
617 len
=read(statusfd
, &d
->dpkgbuf
[d
->dpkgbuf_pos
], sizeof(d
->dpkgbuf
)-d
->dpkgbuf_pos
);
618 d
->dpkgbuf_pos
+= len
;
622 // process line by line if we have a buffer
624 while((q
=(char*)memchr(p
, '\n', d
->dpkgbuf
+d
->dpkgbuf_pos
-p
)) != NULL
)
627 ProcessDpkgStatusLine(OutStatusFd
, p
);
628 p
=q
+1; // continue with next line
631 // now move the unprocessed bits (after the final \n that is now a 0x0)
632 // to the start and update d->dpkgbuf_pos
633 p
= (char*)memrchr(d
->dpkgbuf
, 0, d
->dpkgbuf_pos
);
637 // we are interessted in the first char *after* 0x0
640 // move the unprocessed tail to the start and update pos
641 memmove(d
->dpkgbuf
, p
, p
-d
->dpkgbuf
);
642 d
->dpkgbuf_pos
= d
->dpkgbuf
+d
->dpkgbuf_pos
-p
;
645 // DPkgPM::WriteHistoryTag /*{{{*/
646 void pkgDPkgPM::WriteHistoryTag(string
const &tag
, string value
)
648 size_t const length
= value
.length();
651 // poor mans rstrip(", ")
652 if (value
[length
-2] == ',' && value
[length
-1] == ' ')
653 value
.erase(length
- 2, 2);
654 fprintf(d
->history_out
, "%s: %s\n", tag
.c_str(), value
.c_str());
656 // DPkgPM::OpenLog /*{{{*/
657 bool pkgDPkgPM::OpenLog()
659 string
const logdir
= _config
->FindDir("Dir::Log");
660 if(CreateAPTDirectoryIfNeeded(logdir
, logdir
) == false)
661 // FIXME: use a better string after freeze
662 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
666 time_t const t
= time(NULL
);
667 struct tm
const * const tmp
= localtime(&t
);
668 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
671 string
const logfile_name
= flCombine(logdir
,
672 _config
->Find("Dir::Log::Terminal"));
673 if (!logfile_name
.empty())
675 d
->term_out
= fopen(logfile_name
.c_str(),"a");
676 if (d
->term_out
== NULL
)
677 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name
.c_str());
678 setvbuf(d
->term_out
, NULL
, _IONBF
, 0);
679 SetCloseExec(fileno(d
->term_out
), true);
680 chmod(logfile_name
.c_str(), 0600);
681 fprintf(d
->term_out
, "\nLog started: %s\n", timestr
);
684 // write your history
685 string
const history_name
= flCombine(logdir
,
686 _config
->Find("Dir::Log::History"));
687 if (!history_name
.empty())
689 d
->history_out
= fopen(history_name
.c_str(),"a");
690 if (d
->history_out
== NULL
)
691 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), history_name
.c_str());
692 chmod(history_name
.c_str(), 0644);
693 fprintf(d
->history_out
, "\nStart-Date: %s\n", timestr
);
694 string remove
, purge
, install
, upgrade
, downgrade
;
695 for (pkgCache::PkgIterator I
= Cache
.PkgBegin(); I
.end() == false; I
++)
697 if (Cache
[I
].NewInstall())
699 install
+= I
.FullName(false) + string(" (") + Cache
[I
].CandVersion
;
700 if (Cache
[I
].Flags
& pkgCache::Flag::Auto
)
701 install
+= ", automatic";
702 install
+= string("), ");
704 else if (Cache
[I
].Upgrade())
705 upgrade
+= I
.FullName(false) + string(" (") + Cache
[I
].CurVersion
+ string(", ") + Cache
[I
].CandVersion
+ string("), ");
706 else if (Cache
[I
].Downgrade())
707 downgrade
+= I
.FullName(false) + string(" (") + Cache
[I
].CurVersion
+ string(", ") + Cache
[I
].CandVersion
+ string("), ");
708 else if (Cache
[I
].Delete())
710 if ((Cache
[I
].iFlags
& pkgDepCache::Purge
) == pkgDepCache::Purge
)
711 purge
+= I
.FullName(false) + string(" (") + Cache
[I
].CurVersion
+ string("), ");
713 remove
+= I
.FullName(false) + string(" (") + Cache
[I
].CurVersion
+ string("), ");
716 if (_config
->Exists("Commandline::AsString") == true)
717 WriteHistoryTag("Commandline", _config
->Find("Commandline::AsString"));
718 WriteHistoryTag("Install", install
);
719 WriteHistoryTag("Upgrade", upgrade
);
720 WriteHistoryTag("Downgrade",downgrade
);
721 WriteHistoryTag("Remove",remove
);
722 WriteHistoryTag("Purge",purge
);
723 fflush(d
->history_out
);
729 // DPkg::CloseLog /*{{{*/
730 bool pkgDPkgPM::CloseLog()
733 time_t t
= time(NULL
);
734 struct tm
*tmp
= localtime(&t
);
735 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
739 fprintf(d
->term_out
, "Log ended: ");
740 fprintf(d
->term_out
, "%s", timestr
);
741 fprintf(d
->term_out
, "\n");
748 if (disappearedPkgs
.empty() == false)
751 for (std::set
<std::string
>::const_iterator d
= disappearedPkgs
.begin();
752 d
!= disappearedPkgs
.end(); ++d
)
754 pkgCache::PkgIterator P
= Cache
.FindPkg(*d
);
755 disappear
.append(*d
);
757 disappear
.append(", ");
759 disappear
.append(" (").append(Cache
[P
].CurVersion
).append("), ");
761 WriteHistoryTag("Disappeared", disappear
);
763 if (d
->dpkg_error
.empty() == false)
764 fprintf(d
->history_out
, "Error: %s\n", d
->dpkg_error
.c_str());
765 fprintf(d
->history_out
, "End-Date: %s\n", timestr
);
766 fclose(d
->history_out
);
768 d
->history_out
= NULL
;
774 // This implements a racy version of pselect for those architectures
775 // that don't have a working implementation.
776 // FIXME: Probably can be removed on Lenny+1
777 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
778 fd_set
*exceptfds
, const struct timespec
*timeout
,
779 const sigset_t
*sigmask
)
785 tv
.tv_sec
= timeout
->tv_sec
;
786 tv
.tv_usec
= timeout
->tv_nsec
/1000;
788 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
789 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
790 sigprocmask(SIG_SETMASK
, &origmask
, 0);
794 // DPkgPM::Go - Run the sequence /*{{{*/
795 // ---------------------------------------------------------------------
796 /* This globs the operations and calls dpkg
798 * If it is called with "OutStatusFd" set to a valid file descriptor
799 * apt will report the install progress over this fd. It maps the
800 * dpkg states a package goes through to human readable (and i10n-able)
801 * names and calculates a percentage for each step.
803 bool pkgDPkgPM::Go(int OutStatusFd
)
808 sigset_t original_sigmask
;
810 unsigned int const MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
811 unsigned int const MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
812 bool const NoTriggers
= _config
->FindB("DPkg::NoTriggers", false);
814 if (RunScripts("DPkg::Pre-Invoke") == false)
817 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
820 // support subpressing of triggers processing for special
821 // cases like d-i that runs the triggers handling manually
822 bool const SmartConf
= (_config
->Find("PackageManager::Configure", "all") != "all");
823 bool const TriggersPending
= _config
->FindB("DPkg::TriggersPending", false);
824 if (_config
->FindB("DPkg::ConfigurePending", SmartConf
) == true)
825 List
.push_back(Item(Item::ConfigurePending
, PkgIterator()));
827 // map the dpkg states to the operations that are performed
828 // (this is sorted in the same way as Item::Ops)
829 static const struct DpkgState DpkgStatesOpMap
[][7] = {
832 {"half-installed", N_("Preparing %s")},
833 {"unpacked", N_("Unpacking %s") },
836 // Configure operation
838 {"unpacked",N_("Preparing to configure %s") },
839 {"half-configured", N_("Configuring %s") },
840 { "installed", N_("Installed %s")},
845 {"half-configured", N_("Preparing for removal of %s")},
846 {"half-installed", N_("Removing %s")},
847 {"config-files", N_("Removed %s")},
852 {"config-files", N_("Preparing to completely remove %s")},
853 {"not-installed", N_("Completely removed %s")},
858 // init the PackageOps map, go over the list of packages that
859 // that will be [installed|configured|removed|purged] and add
860 // them to the PackageOps map (the dpkg states it goes through)
861 // and the PackageOpsTranslations (human readable strings)
862 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();I
++)
864 if((*I
).Pkg
.end() == true)
867 string
const name
= (*I
).Pkg
.Name();
868 PackageOpsDone
[name
] = 0;
869 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; i
++)
871 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
876 d
->stdin_is_dev_null
= false;
881 // this loop is runs once per operation
882 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();)
884 // Do all actions with the same Op in one run
885 vector
<Item
>::const_iterator J
= I
;
886 if (TriggersPending
== true)
887 for (; J
!= List
.end(); J
++)
891 if (J
->Op
!= Item::TriggersPending
)
893 vector
<Item
>::const_iterator T
= J
+ 1;
894 if (T
!= List
.end() && T
->Op
== I
->Op
)
899 for (; J
!= List
.end() && J
->Op
== I
->Op
; J
++)
902 // Generate the argument list
903 const char *Args
[MaxArgs
+ 50];
905 // Now check if we are within the MaxArgs limit
907 // this code below is problematic, because it may happen that
908 // the argument list is split in a way that A depends on B
909 // and they are in the same "--configure A B" run
910 // - with the split they may now be configured in different
912 if (J
- I
> (signed)MaxArgs
)
916 unsigned long Size
= 0;
917 string
const Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
918 Args
[n
++] = Tmp
.c_str();
919 Size
+= strlen(Args
[n
-1]);
921 // Stick in any custom dpkg options
922 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
926 for (; Opts
!= 0; Opts
= Opts
->Next
)
928 if (Opts
->Value
.empty() == true)
930 Args
[n
++] = Opts
->Value
.c_str();
931 Size
+= Opts
->Value
.length();
935 char status_fd_buf
[20];
939 Args
[n
++] = "--status-fd";
940 Size
+= strlen(Args
[n
-1]);
941 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
942 Args
[n
++] = status_fd_buf
;
943 Size
+= strlen(Args
[n
-1]);
948 Args
[n
++] = "--force-depends";
949 Size
+= strlen(Args
[n
-1]);
950 Args
[n
++] = "--force-remove-essential";
951 Size
+= strlen(Args
[n
-1]);
952 Args
[n
++] = "--remove";
953 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
++] = "--purge";
962 Size
+= strlen(Args
[n
-1]);
965 case Item::Configure
:
966 Args
[n
++] = "--configure";
967 Size
+= strlen(Args
[n
-1]);
970 case Item::ConfigurePending
:
971 Args
[n
++] = "--configure";
972 Size
+= strlen(Args
[n
-1]);
973 Args
[n
++] = "--pending";
974 Size
+= strlen(Args
[n
-1]);
977 case Item::TriggersPending
:
978 Args
[n
++] = "--triggers-only";
979 Size
+= strlen(Args
[n
-1]);
980 Args
[n
++] = "--pending";
981 Size
+= strlen(Args
[n
-1]);
985 Args
[n
++] = "--unpack";
986 Size
+= strlen(Args
[n
-1]);
987 Args
[n
++] = "--auto-deconfigure";
988 Size
+= strlen(Args
[n
-1]);
992 if (NoTriggers
== true && I
->Op
!= Item::TriggersPending
&&
993 I
->Op
!= Item::ConfigurePending
)
995 Args
[n
++] = "--no-triggers";
996 Size
+= strlen(Args
[n
-1]);
999 // Write in the file or package names
1000 if (I
->Op
== Item::Install
)
1002 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
1004 if (I
->File
[0] != '/')
1005 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
1006 Args
[n
++] = I
->File
.c_str();
1007 Size
+= strlen(Args
[n
-1]);
1012 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
1014 if((*I
).Pkg
.end() == true)
1016 if (I
->Op
== Item::Configure
&& disappearedPkgs
.find(I
->Pkg
.Name()) != disappearedPkgs
.end())
1018 Args
[n
++] = I
->Pkg
.Name();
1019 Size
+= strlen(Args
[n
-1]);
1025 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
1027 for (unsigned int k
= 0; k
!= n
; k
++)
1028 clog
<< Args
[k
] << ' ';
1037 /* Mask off sig int/quit. We do this because dpkg also does when
1038 it forks scripts. What happens is that when you hit ctrl-c it sends
1039 it to all processes in the group. Since dpkg ignores the signal
1040 it doesn't die but we do! So we must also ignore it */
1041 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
1042 sighandler_t old_SIGINT
= signal(SIGINT
,SIG_IGN
);
1044 // ignore SIGHUP as well (debian #463030)
1045 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
1052 // if tcgetattr does not return zero there was a error
1053 // and we do not do any pty magic
1054 if (tcgetattr(0, &tt
) == 0)
1056 ioctl(0, TIOCGWINSZ
, (char *)&win
);
1057 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
1059 const char *s
= _("Can not write log, openpty() "
1060 "failed (/dev/pts not mounted?)\n");
1061 fprintf(stderr
, "%s",s
);
1063 fprintf(d
->term_out
, "%s",s
);
1064 master
= slave
= -1;
1069 rtt
.c_lflag
&= ~ECHO
;
1070 rtt
.c_lflag
|= ISIG
;
1071 // block SIGTTOU during tcsetattr to prevent a hang if
1072 // the process is a member of the background process group
1073 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
1074 sigemptyset(&sigmask
);
1075 sigaddset(&sigmask
, SIGTTOU
);
1076 sigprocmask(SIG_BLOCK
,&sigmask
, &original_sigmask
);
1077 tcsetattr(0, TCSAFLUSH
, &rtt
);
1078 sigprocmask(SIG_SETMASK
, &original_sigmask
, 0);
1084 _config
->Set("APT::Keep-Fds::",fd
[1]);
1085 // send status information that we are about to fork dpkg
1086 if(OutStatusFd
> 0) {
1087 ostringstream status
;
1088 status
<< "pmstatus:dpkg-exec:"
1089 << (PackagesDone
/float(PackagesTotal
)*100.0)
1090 << ":" << _("Running dpkg")
1092 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
1096 // This is the child
1099 if(slave
>= 0 && master
>= 0)
1102 ioctl(slave
, TIOCSCTTY
, 0);
1109 close(fd
[0]); // close the read end of the pipe
1111 if (_config
->FindDir("DPkg::Chroot-Directory","/") != "/")
1113 std::cerr
<< "Chrooting into "
1114 << _config
->FindDir("DPkg::Chroot-Directory")
1116 if (chroot(_config
->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
1120 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
1123 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
1126 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
1129 // Discard everything in stdin before forking dpkg
1130 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
1133 while (read(STDIN_FILENO
,&dummy
,1) == 1);
1135 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
1139 /* No Job Control Stop Env is a magic dpkg var that prevents it
1140 from using sigstop */
1141 putenv((char *)"DPKG_NO_TSTP=yes");
1142 execvp(Args
[0],(char **)Args
);
1143 cerr
<< "Could not exec dpkg!" << endl
;
1148 if (_config
->FindB("DPkg::UseIoNice", false) == true)
1151 // clear the Keep-Fd again
1152 _config
->Clear("APT::Keep-Fds",fd
[1]);
1157 // we read from dpkg here
1158 int const _dpkgin
= fd
[0];
1159 close(fd
[1]); // close the write end of the pipe
1165 sigemptyset(&sigmask
);
1166 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
1168 // the result of the waitpid call
1171 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
1173 // FIXME: move this to a function or something, looks ugly here
1174 // error handling, waitpid returned -1
1177 RunScripts("DPkg::Post-Invoke");
1179 // Restore sig int/quit
1180 signal(SIGQUIT
,old_SIGQUIT
);
1181 signal(SIGINT
,old_SIGINT
);
1182 signal(SIGHUP
,old_SIGHUP
);
1183 return _error
->Errno("waitpid","Couldn't wait for subprocess");
1186 // wait for input or output here
1188 if (master
>= 0 && !d
->stdin_is_dev_null
)
1190 FD_SET(_dpkgin
, &rfds
);
1192 FD_SET(master
, &rfds
);
1195 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
1196 &tv
, &original_sigmask
);
1197 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
1198 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
1199 NULL
, &tv
, &original_sigmask
);
1200 if (select_ret
== 0)
1202 else if (select_ret
< 0 && errno
== EINTR
)
1204 else if (select_ret
< 0)
1206 perror("select() returned error");
1210 if(master
>= 0 && FD_ISSET(master
, &rfds
))
1211 DoTerminalPty(master
);
1212 if(master
>= 0 && FD_ISSET(0, &rfds
))
1214 if(FD_ISSET(_dpkgin
, &rfds
))
1215 DoDpkgStatusFd(_dpkgin
, OutStatusFd
);
1219 // Restore sig int/quit
1220 signal(SIGQUIT
,old_SIGQUIT
);
1221 signal(SIGINT
,old_SIGINT
);
1222 signal(SIGHUP
,old_SIGHUP
);
1226 tcsetattr(0, TCSAFLUSH
, &tt
);
1230 // Check for an error code.
1231 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
1233 // if it was set to "keep-dpkg-runing" then we won't return
1234 // here but keep the loop going and just report it as a error
1236 bool const stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
1239 RunScripts("DPkg::Post-Invoke");
1241 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
1242 strprintf(d
->dpkg_error
, "Sub-process %s received a segmentation fault.",Args
[0]);
1243 else if (WIFEXITED(Status
) != 0)
1244 strprintf(d
->dpkg_error
, "Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
1246 strprintf(d
->dpkg_error
, "Sub-process %s exited unexpectedly",Args
[0]);
1248 if(d
->dpkg_error
.size() > 0)
1249 _error
->Error(d
->dpkg_error
.c_str());
1260 if (RunScripts("DPkg::Post-Invoke") == false)
1263 Cache
.writeStateFile(NULL
);
1267 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1268 // ---------------------------------------------------------------------
1270 void pkgDPkgPM::Reset()
1272 List
.erase(List
.begin(),List
.end());
1275 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1276 // ---------------------------------------------------------------------
1278 void pkgDPkgPM::WriteApportReport(const char *pkgpath
, const char *errormsg
)
1280 string pkgname
, reportfile
, srcpkgname
, pkgver
, arch
;
1281 string::size_type pos
;
1284 if (_config
->FindB("Dpkg::ApportFailureReport", false) == false)
1286 std::clog
<< "configured to not write apport reports" << std::endl
;
1290 // only report the first errors
1291 if(pkgFailures
> _config
->FindI("APT::Apport::MaxReports", 3))
1293 std::clog
<< _("No apport report written because MaxReports is reached already") << std::endl
;
1297 // check if its not a follow up error
1298 const char *needle
= dgettext("dpkg", "dependency problems - leaving unconfigured");
1299 if(strstr(errormsg
, needle
) != NULL
) {
1300 std::clog
<< _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl
;
1304 // do not report disk-full failures
1305 if(strstr(errormsg
, strerror(ENOSPC
)) != NULL
) {
1306 std::clog
<< _("No apport report written because the error message indicates a disk full error") << std::endl
;
1310 // do not report out-of-memory failures
1311 if(strstr(errormsg
, strerror(ENOMEM
)) != NULL
) {
1312 std::clog
<< _("No apport report written because the error message indicates a out of memory error") << std::endl
;
1316 // do not report dpkg I/O errors
1317 // XXX - this message is localized, but this only matches the English version. This is better than nothing.
1318 if(strstr(errormsg
, "short read in buffer_copy (")) {
1319 std::clog
<< _("No apport report written because the error message indicates a dpkg I/O error") << std::endl
;
1323 // get the pkgname and reportfile
1324 pkgname
= flNotDir(pkgpath
);
1325 pos
= pkgname
.find('_');
1326 if(pos
!= string::npos
)
1327 pkgname
= pkgname
.substr(0, pos
);
1329 // find the package versin and source package name
1330 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
1331 if (Pkg
.end() == true)
1333 pkgCache::VerIterator Ver
= Cache
.GetCandidateVer(Pkg
);
1334 if (Ver
.end() == true)
1336 pkgver
= Ver
.VerStr() == NULL
? "unknown" : Ver
.VerStr();
1337 pkgRecords
Recs(Cache
);
1338 pkgRecords::Parser
&Parse
= Recs
.Lookup(Ver
.FileList());
1339 srcpkgname
= Parse
.SourcePkg();
1340 if(srcpkgname
.empty())
1341 srcpkgname
= pkgname
;
1343 // if the file exists already, we check:
1344 // - if it was reported already (touched by apport).
1345 // If not, we do nothing, otherwise
1346 // we overwrite it. This is the same behaviour as apport
1347 // - if we have a report with the same pkgversion already
1349 reportfile
= flCombine("/var/crash",pkgname
+".0.crash");
1350 if(FileExists(reportfile
))
1355 // check atime/mtime
1356 stat(reportfile
.c_str(), &buf
);
1357 if(buf
.st_mtime
> buf
.st_atime
)
1360 // check if the existing report is the same version
1361 report
= fopen(reportfile
.c_str(),"r");
1362 while(fgets(strbuf
, sizeof(strbuf
), report
) != NULL
)
1364 if(strstr(strbuf
,"Package:") == strbuf
)
1366 char pkgname
[255], version
[255];
1367 if(sscanf(strbuf
, "Package: %s %s", pkgname
, version
) == 2)
1368 if(strcmp(pkgver
.c_str(), version
) == 0)
1378 // now write the report
1379 arch
= _config
->Find("APT::Architecture");
1380 report
= fopen(reportfile
.c_str(),"w");
1383 if(_config
->FindB("DPkgPM::InitialReportOnly",false) == true)
1384 chmod(reportfile
.c_str(), 0);
1386 chmod(reportfile
.c_str(), 0600);
1387 fprintf(report
, "ProblemType: Package\n");
1388 fprintf(report
, "Architecture: %s\n", arch
.c_str());
1389 time_t now
= time(NULL
);
1390 fprintf(report
, "Date: %s" , ctime(&now
));
1391 fprintf(report
, "Package: %s %s\n", pkgname
.c_str(), pkgver
.c_str());
1392 fprintf(report
, "SourcePackage: %s\n", srcpkgname
.c_str());
1393 fprintf(report
, "ErrorMessage:\n %s\n", errormsg
);
1395 // ensure that the log is flushed
1397 fflush(d
->term_out
);
1399 // attach terminal log it if we have it
1400 string logfile_name
= _config
->FindFile("Dir::Log::Terminal");
1401 if (!logfile_name
.empty())
1406 fprintf(report
, "DpkgTerminalLog:\n");
1407 log
= fopen(logfile_name
.c_str(),"r");
1410 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1411 fprintf(report
, " %s", buf
);
1417 const char *ops_str
[] = {"Install", "Configure","Remove","Purge"};
1418 fprintf(report
, "AptOrdering:\n");
1419 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
1420 fprintf(report
, " %s: %s\n", (*I
).Pkg
.Name(), ops_str
[(*I
).Op
]);
1422 // attach dmesg log (to learn about segfaults)
1423 if (FileExists("/bin/dmesg"))
1428 fprintf(report
, "Dmesg:\n");
1429 log
= popen("/bin/dmesg","r");
1432 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1433 fprintf(report
, " %s", buf
);
1438 // attach df -l log (to learn about filesystem status)
1439 if (FileExists("/bin/df"))
1444 fprintf(report
, "Df:\n");
1445 log
= popen("/bin/df -l","r");
1448 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1449 fprintf(report
, " %s", buf
);