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>
49 // Maps the dpkg "processing" info to human readable names. Entry 0
50 // of each array is the key, entry 1 is the value.
51 const std::pair
<const char *, const char *> PackageProcessingOps
[] = {
52 std::make_pair("install", N_("Installing %s")),
53 std::make_pair("configure", N_("Configuring %s")),
54 std::make_pair("remove", N_("Removing %s")),
55 std::make_pair("purge", N_("Completely removing %s")),
56 std::make_pair("disappear", N_("Noting disappearance of %s")),
57 std::make_pair("trigproc", N_("Running post-installation trigger %s"))
60 const std::pair
<const char *, const char *> * const PackageProcessingOpsBegin
= PackageProcessingOps
;
61 const std::pair
<const char *, const char *> * const PackageProcessingOpsEnd
= PackageProcessingOps
+ sizeof(PackageProcessingOps
) / sizeof(PackageProcessingOps
[0]);
63 // Predicate to test whether an entry in the PackageProcessingOps
64 // array matches a string.
65 class MatchProcessingOp
70 MatchProcessingOp(const char *the_target
)
75 bool operator()(const std::pair
<const char *, const char *> &pair
) const
77 return strcmp(pair
.first
, target
) == 0;
82 /* helper function to ionice the given PID
84 there is no C header for ionice yet - just the syscall interface
85 so we use the binary from util-linux
90 if (!FileExists("/usr/bin/ionice"))
92 pid_t Process
= ExecFork();
96 snprintf(buf
, sizeof(buf
), "-p%d", PID
);
98 Args
[0] = "/usr/bin/ionice";
102 execv(Args
[0], (char **)Args
);
104 return ExecWait(Process
, "ionice");
107 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
108 // ---------------------------------------------------------------------
110 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
111 : pkgPackageManager(Cache
), dpkgbuf_pos(0),
112 term_out(NULL
), history_out(NULL
), PackagesDone(0), PackagesTotal(0)
116 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
117 // ---------------------------------------------------------------------
119 pkgDPkgPM::~pkgDPkgPM()
123 // DPkgPM::Install - Install a package /*{{{*/
124 // ---------------------------------------------------------------------
125 /* Add an install operation to the sequence list */
126 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
128 if (File
.empty() == true || Pkg
.end() == true)
129 return _error
->Error("Internal Error, No file name for %s",Pkg
.Name());
131 // If the filename string begins with DPkg::Chroot-Directory, return the
132 // substr that is within the chroot so dpkg can access it.
133 string
const chrootdir
= _config
->FindDir("DPkg::Chroot-Directory","/");
134 if (chrootdir
!= "/" && File
.find(chrootdir
) == 0)
136 size_t len
= chrootdir
.length();
137 if (chrootdir
.at(len
- 1) == '/')
139 List
.push_back(Item(Item::Install
,Pkg
,File
.substr(len
)));
142 List
.push_back(Item(Item::Install
,Pkg
,File
));
147 // DPkgPM::Configure - Configure a package /*{{{*/
148 // ---------------------------------------------------------------------
149 /* Add a configure operation to the sequence list */
150 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
152 if (Pkg
.end() == true)
155 List
.push_back(Item(Item::Configure
, Pkg
));
157 // Use triggers for config calls if we configure "smart"
158 // as otherwise Pre-Depends will not be satisfied, see #526774
159 if (_config
->FindB("DPkg::TriggersPending", false) == true)
160 List
.push_back(Item(Item::TriggersPending
, PkgIterator()));
165 // DPkgPM::Remove - Remove a package /*{{{*/
166 // ---------------------------------------------------------------------
167 /* Add a remove operation to the sequence list */
168 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
170 if (Pkg
.end() == true)
174 List
.push_back(Item(Item::Purge
,Pkg
));
176 List
.push_back(Item(Item::Remove
,Pkg
));
180 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
181 // ---------------------------------------------------------------------
182 /* This is part of the helper script communication interface, it sends
183 very complete information down to the other end of the pipe.*/
184 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
186 fprintf(F
,"VERSION 2\n");
188 /* Write out all of the configuration directives by walking the
189 configuration tree */
190 const Configuration::Item
*Top
= _config
->Tree(0);
193 if (Top
->Value
.empty() == false)
196 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
197 QuoteString(Top
->Value
,"\n").c_str());
206 while (Top
!= 0 && Top
->Next
== 0)
213 // Write out the package actions in order.
214 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
216 if(I
->Pkg
.end() == true)
219 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
221 fprintf(F
,"%s ",I
->Pkg
.Name());
223 if (I
->Pkg
->CurrentVer
== 0)
226 fprintf(F
,"%s ",I
->Pkg
.CurrentVer().VerStr());
228 // Show the compare operator
230 if (S
.InstallVer
!= 0)
233 if (I
->Pkg
->CurrentVer
!= 0)
234 Comp
= S
.InstVerIter(Cache
).CompareVer(I
->Pkg
.CurrentVer());
241 fprintf(F
,"%s ",S
.InstVerIter(Cache
).VerStr());
246 // Show the filename/operation
247 if (I
->Op
== Item::Install
)
250 if (I
->File
[0] != '/')
251 fprintf(F
,"**ERROR**\n");
253 fprintf(F
,"%s\n",I
->File
.c_str());
255 if (I
->Op
== Item::Configure
)
256 fprintf(F
,"**CONFIGURE**\n");
257 if (I
->Op
== Item::Remove
||
258 I
->Op
== Item::Purge
)
259 fprintf(F
,"**REMOVE**\n");
267 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
268 // ---------------------------------------------------------------------
269 /* This looks for a list of scripts to run from the configuration file
270 each one is run and is fed on standard input a list of all .deb files
271 that are due to be installed. */
272 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
274 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
275 if (Opts
== 0 || Opts
->Child
== 0)
279 unsigned int Count
= 1;
280 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
282 if (Opts
->Value
.empty() == true)
285 // Determine the protocol version
286 string OptSec
= Opts
->Value
;
287 string::size_type Pos
;
288 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
289 Pos
= OptSec
.length();
290 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
292 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
296 if (pipe(Pipes
) != 0)
297 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
298 SetCloseExec(Pipes
[0],true);
299 SetCloseExec(Pipes
[1],true);
301 // Purified Fork for running the script
302 pid_t Process
= ExecFork();
306 dup2(Pipes
[0],STDIN_FILENO
);
307 SetCloseExec(STDOUT_FILENO
,false);
308 SetCloseExec(STDIN_FILENO
,false);
309 SetCloseExec(STDERR_FILENO
,false);
314 Args
[2] = Opts
->Value
.c_str();
316 execv(Args
[0],(char **)Args
);
320 FILE *F
= fdopen(Pipes
[1],"w");
322 return _error
->Errno("fdopen","Faild to open new FD");
324 // Feed it the filenames.
328 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
330 // Only deal with packages to be installed from .deb
331 if (I
->Op
!= Item::Install
)
335 if (I
->File
[0] != '/')
338 /* Feed the filename of each package that is pending install
340 fprintf(F
,"%s\n",I
->File
.c_str());
349 Die
= !SendV2Pkgs(F
);
353 // Clean up the sub process
354 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
355 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
361 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
362 // ---------------------------------------------------------------------
365 void pkgDPkgPM::DoStdin(int master
)
367 unsigned char input_buf
[256] = {0,};
368 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
370 write(master
, input_buf
, len
);
372 stdin_is_dev_null
= true;
375 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
376 // ---------------------------------------------------------------------
378 * read the terminal pty and write log
380 void pkgDPkgPM::DoTerminalPty(int master
)
382 unsigned char term_buf
[1024] = {0,0, };
384 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
385 if(len
== -1 && errno
== EIO
)
387 // this happens when the child is about to exit, we
388 // give it time to actually exit, otherwise we run
395 write(1, term_buf
, len
);
397 fwrite(term_buf
, len
, sizeof(char), term_out
);
400 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
401 // ---------------------------------------------------------------------
404 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd
, char *line
)
406 bool const Debug
= _config
->FindB("Debug::pkgDPkgProgressReporting",false);
407 // the status we output
408 ostringstream status
;
411 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
414 /* dpkg sends strings like this:
415 'status: <pkg>: <pkg qstate>'
416 errors look like this:
417 '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
418 and conffile-prompt like this
419 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
421 Newer versions of dpkg sent also:
422 'processing: install: pkg'
423 'processing: configure: pkg'
424 'processing: remove: pkg'
425 'processing: purge: pkg'
426 'processing: disappear: pkg'
427 'processing: trigproc: trigger'
431 // dpkg sends multiline error messages sometimes (see
432 // #374195 for a example. we should support this by
433 // either patching dpkg to not send multiline over the
434 // statusfd or by rewriting the code here to deal with
435 // it. for now we just ignore it and not crash
436 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
437 if( list
[0] == NULL
|| list
[1] == NULL
|| list
[2] == NULL
)
440 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
443 const char* const pkg
= list
[1];
444 const char* action
= _strstrip(list
[2]);
446 // 'processing' from dpkg looks like
447 // 'processing: action: pkg'
448 if(strncmp(list
[0], "processing", strlen("processing")) == 0)
451 const char* const pkg_or_trigger
= _strstrip(list
[2]);
452 action
= _strstrip( list
[1]);
453 const std::pair
<const char *, const char *> * const iter
=
454 std::find_if(PackageProcessingOpsBegin
,
455 PackageProcessingOpsEnd
,
456 MatchProcessingOp(action
));
457 if(iter
== PackageProcessingOpsEnd
)
460 std::clog
<< "ignoring unknown action: " << action
<< std::endl
;
463 snprintf(s
, sizeof(s
), _(iter
->second
), pkg_or_trigger
);
465 status
<< "pmstatus:" << pkg_or_trigger
466 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
470 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
472 std::clog
<< "send: '" << status
.str() << "'" << endl
;
474 if (strncmp(action
, "disappear", strlen("disappear")) == 0)
475 handleDisappearAction(pkg_or_trigger
);
479 if(strncmp(action
,"error",strlen("error")) == 0)
481 // urgs, sometime has ":" in its error string so that we
482 // end up with the error message split between list[3]
483 // and list[4], e.g. the message:
484 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
486 if( list
[4] != NULL
)
487 list
[3][strlen(list
[3])] = ':';
489 status
<< "pmerror:" << list
[1]
490 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
494 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
496 std::clog
<< "send: '" << status
.str() << "'" << endl
;
498 WriteApportReport(list
[1], list
[3]);
501 else if(strncmp(action
,"conffile",strlen("conffile")) == 0)
503 status
<< "pmconffile:" << list
[1]
504 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
508 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
510 std::clog
<< "send: '" << status
.str() << "'" << endl
;
514 vector
<struct DpkgState
> const &states
= PackageOps
[pkg
];
515 const char *next_action
= NULL
;
516 if(PackageOpsDone
[pkg
] < states
.size())
517 next_action
= states
[PackageOpsDone
[pkg
]].state
;
518 // check if the package moved to the next dpkg state
519 if(next_action
&& (strcmp(action
, next_action
) == 0))
521 // only read the translation if there is actually a next
523 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
525 snprintf(s
, sizeof(s
), translation
, pkg
);
527 // we moved from one dpkg state to a new one, report that
528 PackageOpsDone
[pkg
]++;
530 // build the status str
531 status
<< "pmstatus:" << pkg
532 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
536 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
538 std::clog
<< "send: '" << status
.str() << "'" << endl
;
541 std::clog
<< "(parsed from dpkg) pkg: " << pkg
542 << " action: " << action
<< endl
;
545 // DPkgPM::handleDisappearAction /*{{{*/
546 void pkgDPkgPM::handleDisappearAction(string
const &pkgname
)
548 // record the package name for display and stuff later
549 disappearedPkgs
.insert(pkgname
);
551 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
552 if (unlikely(Pkg
.end() == true))
554 // the disappeared package was auto-installed - nothing to do
555 if ((Cache
[Pkg
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
557 pkgCache::VerIterator PkgVer
= Pkg
.CurrentVer();
558 if (unlikely(PkgVer
.end() == true))
560 /* search in the list of dependencies for (Pre)Depends,
561 check if this dependency has a Replaces on our package
562 and if so transfer the manual installed flag to it */
563 for (pkgCache::DepIterator Dep
= PkgVer
.DependsList(); Dep
.end() != true; ++Dep
)
565 if (Dep
->Type
!= pkgCache::Dep::Depends
&&
566 Dep
->Type
!= pkgCache::Dep::PreDepends
)
568 pkgCache::PkgIterator Tar
= Dep
.TargetPkg();
569 if (unlikely(Tar
.end() == true))
571 // the package is already marked as manual
572 if ((Cache
[Tar
].Flags
& pkgCache::Flag::Auto
) != pkgCache::Flag::Auto
)
574 pkgCache::VerIterator TarVer
= Tar
.CurrentVer();
575 for (pkgCache::DepIterator Rep
= TarVer
.DependsList(); Rep
.end() != true; ++Rep
)
577 if (Rep
->Type
!= pkgCache::Dep::Replaces
)
579 if (Pkg
!= Rep
.TargetPkg())
581 // okay, they are strongly connected - transfer manual-bit
583 std::clog
<< "transfer manual-bit from disappeared »" << pkgname
<< "« to »" << Tar
.FullName() << "«" << std::endl
;
584 Cache
[Tar
].Flags
&= ~Flag::Auto
;
590 // DPkgPM::DoDpkgStatusFd /*{{{*/
591 // ---------------------------------------------------------------------
594 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
, int OutStatusFd
)
599 len
=read(statusfd
, &dpkgbuf
[dpkgbuf_pos
], sizeof(dpkgbuf
)-dpkgbuf_pos
);
604 // process line by line if we have a buffer
606 while((q
=(char*)memchr(p
, '\n', dpkgbuf
+dpkgbuf_pos
-p
)) != NULL
)
609 ProcessDpkgStatusLine(OutStatusFd
, p
);
610 p
=q
+1; // continue with next line
613 // now move the unprocessed bits (after the final \n that is now a 0x0)
614 // to the start and update dpkgbuf_pos
615 p
= (char*)memrchr(dpkgbuf
, 0, dpkgbuf_pos
);
619 // we are interessted in the first char *after* 0x0
622 // move the unprocessed tail to the start and update pos
623 memmove(dpkgbuf
, p
, p
-dpkgbuf
);
624 dpkgbuf_pos
= dpkgbuf
+dpkgbuf_pos
-p
;
627 // DPkgPM::WriteHistoryTag /*{{{*/
628 void pkgDPkgPM::WriteHistoryTag(string
const &tag
, string value
)
630 size_t const length
= value
.length();
633 // poor mans rstrip(", ")
634 if (value
[length
-2] == ',' && value
[length
-1] == ' ')
635 value
.erase(length
- 2, 2);
636 fprintf(history_out
, "%s: %s\n", tag
.c_str(), value
.c_str());
638 // DPkgPM::OpenLog /*{{{*/
639 bool pkgDPkgPM::OpenLog()
641 string
const logdir
= _config
->FindDir("Dir::Log");
642 if(not FileExists(logdir
))
643 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
647 time_t const t
= time(NULL
);
648 struct tm
const * const tmp
= localtime(&t
);
649 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
652 string
const logfile_name
= flCombine(logdir
,
653 _config
->Find("Dir::Log::Terminal"));
654 if (!logfile_name
.empty())
656 term_out
= fopen(logfile_name
.c_str(),"a");
657 if (term_out
== NULL
)
658 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name
.c_str());
659 setvbuf(term_out
, NULL
, _IONBF
, 0);
660 chmod(logfile_name
.c_str(), 0600);
661 fprintf(term_out
, "\nLog started: %s\n", timestr
);
664 // write your history
665 string
const history_name
= flCombine(logdir
,
666 _config
->Find("Dir::Log::History"));
667 if (!history_name
.empty())
669 history_out
= fopen(history_name
.c_str(),"a");
670 if (history_out
== NULL
)
671 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), history_name
.c_str());
672 chmod(history_name
.c_str(), 0644);
673 fprintf(history_out
, "\nStart-Date: %s\n", timestr
);
674 string remove
, purge
, install
, upgrade
, downgrade
;
675 for (pkgCache::PkgIterator I
= Cache
.PkgBegin(); I
.end() == false; I
++)
677 if (Cache
[I
].NewInstall())
679 install
+= I
.FullName(false) + string(" (") + Cache
[I
].CandVersion
;
680 if (Cache
[I
].Flags
& pkgCache::Flag::Auto
)
681 install
+= ", automatic";
682 install
+= string("), ");
684 else if (Cache
[I
].Upgrade())
685 upgrade
+= I
.FullName(false) + string(" (") + Cache
[I
].CurVersion
+ string(", ") + Cache
[I
].CandVersion
+ string("), ");
686 else if (Cache
[I
].Downgrade())
687 downgrade
+= I
.FullName(false) + string(" (") + Cache
[I
].CurVersion
+ string(", ") + Cache
[I
].CandVersion
+ string("), ");
688 else if (Cache
[I
].Delete())
690 if ((Cache
[I
].iFlags
& pkgDepCache::Purge
) == pkgDepCache::Purge
)
691 purge
+= I
.FullName(false) + string(" (") + Cache
[I
].CurVersion
+ string("), ");
693 remove
+= I
.FullName(false) + string(" (") + Cache
[I
].CurVersion
+ string("), ");
696 if (_config
->Exists("Commandline::AsString") == true)
697 WriteHistoryTag("Commandline", _config
->Find("Commandline::AsString"));
698 WriteHistoryTag("Install", install
);
699 WriteHistoryTag("Upgrade", upgrade
);
700 WriteHistoryTag("Downgrade",downgrade
);
701 WriteHistoryTag("Remove",remove
);
702 WriteHistoryTag("Purge",purge
);
709 // DPkg::CloseLog /*{{{*/
710 bool pkgDPkgPM::CloseLog()
713 time_t t
= time(NULL
);
714 struct tm
*tmp
= localtime(&t
);
715 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
719 fprintf(term_out
, "Log ended: ");
720 fprintf(term_out
, "%s", timestr
);
721 fprintf(term_out
, "\n");
728 if (disappearedPkgs
.empty() == false)
731 for (std::set
<std::string
>::const_iterator d
= disappearedPkgs
.begin();
732 d
!= disappearedPkgs
.end(); ++d
)
734 pkgCache::PkgIterator P
= Cache
.FindPkg(*d
);
735 disappear
.append(*d
);
737 disappear
.append(", ");
739 disappear
.append(" (").append(Cache
[P
].CurVersion
).append("), ");
741 WriteHistoryTag("Disappeared", disappear
);
743 if (dpkg_error
.empty() == false)
744 fprintf(history_out
, "Error: %s\n", dpkg_error
.c_str());
745 fprintf(history_out
, "End-Date: %s\n", timestr
);
754 // This implements a racy version of pselect for those architectures
755 // that don't have a working implementation.
756 // FIXME: Probably can be removed on Lenny+1
757 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
758 fd_set
*exceptfds
, const struct timespec
*timeout
,
759 const sigset_t
*sigmask
)
765 tv
.tv_sec
= timeout
->tv_sec
;
766 tv
.tv_usec
= timeout
->tv_nsec
/1000;
768 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
769 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
770 sigprocmask(SIG_SETMASK
, &origmask
, 0);
774 // DPkgPM::Go - Run the sequence /*{{{*/
775 // ---------------------------------------------------------------------
776 /* This globs the operations and calls dpkg
778 * If it is called with "OutStatusFd" set to a valid file descriptor
779 * apt will report the install progress over this fd. It maps the
780 * dpkg states a package goes through to human readable (and i10n-able)
781 * names and calculates a percentage for each step.
783 bool pkgDPkgPM::Go(int OutStatusFd
)
788 sigset_t original_sigmask
;
790 unsigned int const MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
791 unsigned int const MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
792 bool const NoTriggers
= _config
->FindB("DPkg::NoTriggers", false);
794 if (RunScripts("DPkg::Pre-Invoke") == false)
797 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
800 // support subpressing of triggers processing for special
801 // cases like d-i that runs the triggers handling manually
802 bool const SmartConf
= (_config
->Find("PackageManager::Configure", "all") != "all");
803 bool const TriggersPending
= _config
->FindB("DPkg::TriggersPending", false);
804 if (_config
->FindB("DPkg::ConfigurePending", SmartConf
) == true)
805 List
.push_back(Item(Item::ConfigurePending
, PkgIterator()));
807 // map the dpkg states to the operations that are performed
808 // (this is sorted in the same way as Item::Ops)
809 static const struct DpkgState DpkgStatesOpMap
[][7] = {
812 {"half-installed", N_("Preparing %s")},
813 {"unpacked", N_("Unpacking %s") },
816 // Configure operation
818 {"unpacked",N_("Preparing to configure %s") },
819 {"half-configured", N_("Configuring %s") },
820 { "installed", N_("Installed %s")},
825 {"half-configured", N_("Preparing for removal of %s")},
826 {"half-installed", N_("Removing %s")},
827 {"config-files", N_("Removed %s")},
832 {"config-files", N_("Preparing to completely remove %s")},
833 {"not-installed", N_("Completely removed %s")},
838 // init the PackageOps map, go over the list of packages that
839 // that will be [installed|configured|removed|purged] and add
840 // them to the PackageOps map (the dpkg states it goes through)
841 // and the PackageOpsTranslations (human readable strings)
842 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();I
++)
844 if((*I
).Pkg
.end() == true)
847 string
const name
= (*I
).Pkg
.Name();
848 PackageOpsDone
[name
] = 0;
849 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; i
++)
851 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
856 stdin_is_dev_null
= false;
861 // this loop is runs once per operation
862 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();)
864 // Do all actions with the same Op in one run
865 vector
<Item
>::const_iterator J
= I
;
866 if (TriggersPending
== true)
867 for (; J
!= List
.end(); J
++)
871 if (J
->Op
!= Item::TriggersPending
)
873 vector
<Item
>::const_iterator T
= J
+ 1;
874 if (T
!= List
.end() && T
->Op
== I
->Op
)
879 for (; J
!= List
.end() && J
->Op
== I
->Op
; J
++)
882 // Generate the argument list
883 const char *Args
[MaxArgs
+ 50];
885 // Now check if we are within the MaxArgs limit
887 // this code below is problematic, because it may happen that
888 // the argument list is split in a way that A depends on B
889 // and they are in the same "--configure A B" run
890 // - with the split they may now be configured in different
892 if (J
- I
> (signed)MaxArgs
)
896 unsigned long Size
= 0;
897 string
const Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
898 Args
[n
++] = Tmp
.c_str();
899 Size
+= strlen(Args
[n
-1]);
901 // Stick in any custom dpkg options
902 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
906 for (; Opts
!= 0; Opts
= Opts
->Next
)
908 if (Opts
->Value
.empty() == true)
910 Args
[n
++] = Opts
->Value
.c_str();
911 Size
+= Opts
->Value
.length();
915 char status_fd_buf
[20];
919 Args
[n
++] = "--status-fd";
920 Size
+= strlen(Args
[n
-1]);
921 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
922 Args
[n
++] = status_fd_buf
;
923 Size
+= strlen(Args
[n
-1]);
928 Args
[n
++] = "--force-depends";
929 Size
+= strlen(Args
[n
-1]);
930 Args
[n
++] = "--force-remove-essential";
931 Size
+= strlen(Args
[n
-1]);
932 Args
[n
++] = "--remove";
933 Size
+= strlen(Args
[n
-1]);
937 Args
[n
++] = "--force-depends";
938 Size
+= strlen(Args
[n
-1]);
939 Args
[n
++] = "--force-remove-essential";
940 Size
+= strlen(Args
[n
-1]);
941 Args
[n
++] = "--purge";
942 Size
+= strlen(Args
[n
-1]);
945 case Item::Configure
:
946 Args
[n
++] = "--configure";
947 Size
+= strlen(Args
[n
-1]);
950 case Item::ConfigurePending
:
951 Args
[n
++] = "--configure";
952 Size
+= strlen(Args
[n
-1]);
953 Args
[n
++] = "--pending";
954 Size
+= strlen(Args
[n
-1]);
957 case Item::TriggersPending
:
958 Args
[n
++] = "--triggers-only";
959 Size
+= strlen(Args
[n
-1]);
960 Args
[n
++] = "--pending";
961 Size
+= strlen(Args
[n
-1]);
965 Args
[n
++] = "--unpack";
966 Size
+= strlen(Args
[n
-1]);
967 Args
[n
++] = "--auto-deconfigure";
968 Size
+= strlen(Args
[n
-1]);
972 if (NoTriggers
== true && I
->Op
!= Item::TriggersPending
&&
973 I
->Op
!= Item::ConfigurePending
)
975 Args
[n
++] = "--no-triggers";
976 Size
+= strlen(Args
[n
-1]);
979 // Write in the file or package names
980 if (I
->Op
== Item::Install
)
982 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
984 if (I
->File
[0] != '/')
985 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
986 Args
[n
++] = I
->File
.c_str();
987 Size
+= strlen(Args
[n
-1]);
992 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
994 if((*I
).Pkg
.end() == true)
996 if (I
->Op
== Item::Configure
&& disappearedPkgs
.find(I
->Pkg
.Name()) != disappearedPkgs
.end())
998 Args
[n
++] = I
->Pkg
.Name();
999 Size
+= strlen(Args
[n
-1]);
1005 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
1007 for (unsigned int k
= 0; k
!= n
; k
++)
1008 clog
<< Args
[k
] << ' ';
1017 /* Mask off sig int/quit. We do this because dpkg also does when
1018 it forks scripts. What happens is that when you hit ctrl-c it sends
1019 it to all processes in the group. Since dpkg ignores the signal
1020 it doesn't die but we do! So we must also ignore it */
1021 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
1022 sighandler_t old_SIGINT
= signal(SIGINT
,SIG_IGN
);
1024 // ignore SIGHUP as well (debian #463030)
1025 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
1032 // if tcgetattr does not return zero there was a error
1033 // and we do not do any pty magic
1034 if (tcgetattr(0, &tt
) == 0)
1036 ioctl(0, TIOCGWINSZ
, (char *)&win
);
1037 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
1039 const char *s
= _("Can not write log, openpty() "
1040 "failed (/dev/pts not mounted?)\n");
1041 fprintf(stderr
, "%s",s
);
1043 fprintf(term_out
, "%s",s
);
1044 master
= slave
= -1;
1049 rtt
.c_lflag
&= ~ECHO
;
1050 rtt
.c_lflag
|= ISIG
;
1051 // block SIGTTOU during tcsetattr to prevent a hang if
1052 // the process is a member of the background process group
1053 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
1054 sigemptyset(&sigmask
);
1055 sigaddset(&sigmask
, SIGTTOU
);
1056 sigprocmask(SIG_BLOCK
,&sigmask
, &original_sigmask
);
1057 tcsetattr(0, TCSAFLUSH
, &rtt
);
1058 sigprocmask(SIG_SETMASK
, &original_sigmask
, 0);
1064 _config
->Set("APT::Keep-Fds::",fd
[1]);
1065 // send status information that we are about to fork dpkg
1066 if(OutStatusFd
> 0) {
1067 ostringstream status
;
1068 status
<< "pmstatus:dpkg-exec:"
1069 << (PackagesDone
/float(PackagesTotal
)*100.0)
1070 << ":" << _("Running dpkg")
1072 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
1076 // This is the child
1079 if(slave
>= 0 && master
>= 0)
1082 ioctl(slave
, TIOCSCTTY
, 0);
1089 close(fd
[0]); // close the read end of the pipe
1091 if (_config
->FindDir("DPkg::Chroot-Directory","/") != "/")
1093 std::cerr
<< "Chrooting into "
1094 << _config
->FindDir("DPkg::Chroot-Directory")
1096 if (chroot(_config
->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
1100 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
1103 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
1106 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
1109 // Discard everything in stdin before forking dpkg
1110 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
1113 while (read(STDIN_FILENO
,&dummy
,1) == 1);
1115 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
1119 /* No Job Control Stop Env is a magic dpkg var that prevents it
1120 from using sigstop */
1121 putenv((char *)"DPKG_NO_TSTP=yes");
1122 execvp(Args
[0],(char **)Args
);
1123 cerr
<< "Could not exec dpkg!" << endl
;
1128 if (_config
->FindB("DPkg::UseIoNice", false) == true)
1131 // clear the Keep-Fd again
1132 _config
->Clear("APT::Keep-Fds",fd
[1]);
1137 // we read from dpkg here
1138 int const _dpkgin
= fd
[0];
1139 close(fd
[1]); // close the write end of the pipe
1145 sigemptyset(&sigmask
);
1146 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
1148 // the result of the waitpid call
1151 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
1153 // FIXME: move this to a function or something, looks ugly here
1154 // error handling, waitpid returned -1
1157 RunScripts("DPkg::Post-Invoke");
1159 // Restore sig int/quit
1160 signal(SIGQUIT
,old_SIGQUIT
);
1161 signal(SIGINT
,old_SIGINT
);
1162 signal(SIGHUP
,old_SIGHUP
);
1163 return _error
->Errno("waitpid","Couldn't wait for subprocess");
1166 // wait for input or output here
1168 if (master
>= 0 && !stdin_is_dev_null
)
1170 FD_SET(_dpkgin
, &rfds
);
1172 FD_SET(master
, &rfds
);
1175 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
1176 &tv
, &original_sigmask
);
1177 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
1178 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
1179 NULL
, &tv
, &original_sigmask
);
1180 if (select_ret
== 0)
1182 else if (select_ret
< 0 && errno
== EINTR
)
1184 else if (select_ret
< 0)
1186 perror("select() returned error");
1190 if(master
>= 0 && FD_ISSET(master
, &rfds
))
1191 DoTerminalPty(master
);
1192 if(master
>= 0 && FD_ISSET(0, &rfds
))
1194 if(FD_ISSET(_dpkgin
, &rfds
))
1195 DoDpkgStatusFd(_dpkgin
, OutStatusFd
);
1199 // Restore sig int/quit
1200 signal(SIGQUIT
,old_SIGQUIT
);
1201 signal(SIGINT
,old_SIGINT
);
1202 signal(SIGHUP
,old_SIGHUP
);
1206 tcsetattr(0, TCSAFLUSH
, &tt
);
1210 // Check for an error code.
1211 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
1213 // if it was set to "keep-dpkg-runing" then we won't return
1214 // here but keep the loop going and just report it as a error
1216 bool const stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
1219 RunScripts("DPkg::Post-Invoke");
1221 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
1222 strprintf(dpkg_error
, "Sub-process %s received a segmentation fault.",Args
[0]);
1223 else if (WIFEXITED(Status
) != 0)
1224 strprintf(dpkg_error
, "Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
1226 strprintf(dpkg_error
, "Sub-process %s exited unexpectedly",Args
[0]);
1228 if(dpkg_error
.size() > 0)
1229 _error
->Error(dpkg_error
.c_str());
1240 if (RunScripts("DPkg::Post-Invoke") == false)
1243 Cache
.writeStateFile(NULL
);
1247 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1248 // ---------------------------------------------------------------------
1250 void pkgDPkgPM::Reset()
1252 List
.erase(List
.begin(),List
.end());
1255 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1256 // ---------------------------------------------------------------------
1258 void pkgDPkgPM::WriteApportReport(const char *pkgpath
, const char *errormsg
)
1260 string pkgname
, reportfile
, srcpkgname
, pkgver
, arch
;
1261 string::size_type pos
;
1264 if (_config
->FindB("Dpkg::ApportFailureReport", false) == false)
1266 std::clog
<< "configured to not write apport reports" << std::endl
;
1270 // only report the first errors
1271 if(pkgFailures
> _config
->FindI("APT::Apport::MaxReports", 3))
1273 std::clog
<< _("No apport report written because MaxReports is reached already") << std::endl
;
1277 // check if its not a follow up error
1278 const char *needle
= dgettext("dpkg", "dependency problems - leaving unconfigured");
1279 if(strstr(errormsg
, needle
) != NULL
) {
1280 std::clog
<< _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl
;
1284 // do not report disk-full failures
1285 if(strstr(errormsg
, strerror(ENOSPC
)) != NULL
) {
1286 std::clog
<< _("No apport report written because the error message indicates a disk full error") << std::endl
;
1290 // do not report out-of-memory failures
1291 if(strstr(errormsg
, strerror(ENOMEM
)) != NULL
) {
1292 std::clog
<< _("No apport report written because the error message indicates a out of memory error") << std::endl
;
1296 // do not report dpkg I/O errors
1297 // XXX - this message is localized, but this only matches the English version. This is better than nothing.
1298 if(strstr(errormsg
, "short read in buffer_copy (")) {
1299 std::clog
<< _("No apport report written because the error message indicates a dpkg I/O error") << std::endl
;
1303 // get the pkgname and reportfile
1304 pkgname
= flNotDir(pkgpath
);
1305 pos
= pkgname
.find('_');
1306 if(pos
!= string::npos
)
1307 pkgname
= pkgname
.substr(0, pos
);
1309 // find the package versin and source package name
1310 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
1311 if (Pkg
.end() == true)
1313 pkgCache::VerIterator Ver
= Cache
.GetCandidateVer(Pkg
);
1314 if (Ver
.end() == true)
1316 pkgver
= Ver
.VerStr() == NULL
? "unknown" : Ver
.VerStr();
1317 pkgRecords
Recs(Cache
);
1318 pkgRecords::Parser
&Parse
= Recs
.Lookup(Ver
.FileList());
1319 srcpkgname
= Parse
.SourcePkg();
1320 if(srcpkgname
.empty())
1321 srcpkgname
= pkgname
;
1323 // if the file exists already, we check:
1324 // - if it was reported already (touched by apport).
1325 // If not, we do nothing, otherwise
1326 // we overwrite it. This is the same behaviour as apport
1327 // - if we have a report with the same pkgversion already
1329 reportfile
= flCombine("/var/crash",pkgname
+".0.crash");
1330 if(FileExists(reportfile
))
1335 // check atime/mtime
1336 stat(reportfile
.c_str(), &buf
);
1337 if(buf
.st_mtime
> buf
.st_atime
)
1340 // check if the existing report is the same version
1341 report
= fopen(reportfile
.c_str(),"r");
1342 while(fgets(strbuf
, sizeof(strbuf
), report
) != NULL
)
1344 if(strstr(strbuf
,"Package:") == strbuf
)
1346 char pkgname
[255], version
[255];
1347 if(sscanf(strbuf
, "Package: %s %s", pkgname
, version
) == 2)
1348 if(strcmp(pkgver
.c_str(), version
) == 0)
1358 // now write the report
1359 arch
= _config
->Find("APT::Architecture");
1360 report
= fopen(reportfile
.c_str(),"w");
1363 if(_config
->FindB("DPkgPM::InitialReportOnly",false) == true)
1364 chmod(reportfile
.c_str(), 0);
1366 chmod(reportfile
.c_str(), 0600);
1367 fprintf(report
, "ProblemType: Package\n");
1368 fprintf(report
, "Architecture: %s\n", arch
.c_str());
1369 time_t now
= time(NULL
);
1370 fprintf(report
, "Date: %s" , ctime(&now
));
1371 fprintf(report
, "Package: %s %s\n", pkgname
.c_str(), pkgver
.c_str());
1372 fprintf(report
, "SourcePackage: %s\n", srcpkgname
.c_str());
1373 fprintf(report
, "ErrorMessage:\n %s\n", errormsg
);
1375 // ensure that the log is flushed
1379 // attach terminal log it if we have it
1380 string logfile_name
= _config
->FindFile("Dir::Log::Terminal");
1381 if (!logfile_name
.empty())
1386 fprintf(report
, "DpkgTerminalLog:\n");
1387 log
= fopen(logfile_name
.c_str(),"r");
1390 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1391 fprintf(report
, " %s", buf
);
1397 const char *ops_str
[] = {"Install", "Configure","Remove","Purge"};
1398 fprintf(report
, "AptOrdering:\n");
1399 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
1400 fprintf(report
, " %s: %s\n", (*I
).Pkg
.Name(), ops_str
[(*I
).Op
]);
1402 // attach dmesg log (to learn about segfaults)
1403 if (FileExists("/bin/dmesg"))
1408 fprintf(report
, "Dmesg:\n");
1409 log
= popen("/bin/dmesg","r");
1412 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1413 fprintf(report
, " %s", buf
);
1418 // attach df -l log (to learn about filesystem status)
1419 if (FileExists("/bin/df"))
1424 fprintf(report
, "Df:\n");
1425 log
= popen("/bin/df -l","r");
1428 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1429 fprintf(report
, " %s", buf
);