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>
24 #include <sys/types.h>
37 #include <sys/ioctl.h>
48 // Maps the dpkg "processing" info to human readable names. Entry 0
49 // of each array is the key, entry 1 is the value.
50 const std::pair
<const char *, const char *> PackageProcessingOps
[] = {
51 std::make_pair("install", N_("Installing %s")),
52 std::make_pair("configure", N_("Configuring %s")),
53 std::make_pair("remove", N_("Removing %s")),
54 std::make_pair("purge", N_("Completely removing %s")),
55 std::make_pair("disappear", N_("Noting disappearance of %s")),
56 std::make_pair("trigproc", N_("Running post-installation trigger %s"))
59 const std::pair
<const char *, const char *> * const PackageProcessingOpsBegin
= PackageProcessingOps
;
60 const std::pair
<const char *, const char *> * const PackageProcessingOpsEnd
= PackageProcessingOps
+ sizeof(PackageProcessingOps
) / sizeof(PackageProcessingOps
[0]);
62 // Predicate to test whether an entry in the PackageProcessingOps
63 // array matches a string.
64 class MatchProcessingOp
69 MatchProcessingOp(const char *the_target
)
74 bool operator()(const std::pair
<const char *, const char *> &pair
) const
76 return strcmp(pair
.first
, target
) == 0;
81 /* helper function to ionice the given PID
83 there is no C header for ionice yet - just the syscall interface
84 so we use the binary from util-linux
89 if (!FileExists("/usr/bin/ionice"))
91 pid_t Process
= ExecFork();
95 snprintf(buf
, sizeof(buf
), "-p%d", PID
);
97 Args
[0] = "/usr/bin/ionice";
101 execv(Args
[0], (char **)Args
);
103 return ExecWait(Process
, "ionice");
106 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
107 // ---------------------------------------------------------------------
109 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
110 : pkgPackageManager(Cache
), dpkgbuf_pos(0),
111 term_out(NULL
), history_out(NULL
), PackagesDone(0), PackagesTotal(0)
115 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
116 // ---------------------------------------------------------------------
118 pkgDPkgPM::~pkgDPkgPM()
122 // DPkgPM::Install - Install a package /*{{{*/
123 // ---------------------------------------------------------------------
124 /* Add an install operation to the sequence list */
125 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
127 if (File
.empty() == true || Pkg
.end() == true)
128 return _error
->Error("Internal Error, No file name for %s",Pkg
.Name());
130 // If the filename string begins with DPkg::Chroot-Directory, return the
131 // substr that is within the chroot so dpkg can access it.
132 string
const chrootdir
= _config
->FindDir("DPkg::Chroot-Directory","/");
133 if (chrootdir
!= "/" && File
.find(chrootdir
) == 0)
135 size_t len
= chrootdir
.length();
136 if (chrootdir
.at(len
- 1) == '/')
138 List
.push_back(Item(Item::Install
,Pkg
,File
.substr(len
)));
141 List
.push_back(Item(Item::Install
,Pkg
,File
));
146 // DPkgPM::Configure - Configure a package /*{{{*/
147 // ---------------------------------------------------------------------
148 /* Add a configure operation to the sequence list */
149 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
151 if (Pkg
.end() == true)
154 List
.push_back(Item(Item::Configure
, Pkg
));
156 // Use triggers for config calls if we configure "smart"
157 // as otherwise Pre-Depends will not be satisfied, see #526774
158 if (_config
->FindB("DPkg::TriggersPending", false) == true)
159 List
.push_back(Item(Item::TriggersPending
, PkgIterator()));
164 // DPkgPM::Remove - Remove a package /*{{{*/
165 // ---------------------------------------------------------------------
166 /* Add a remove operation to the sequence list */
167 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
169 if (Pkg
.end() == true)
173 List
.push_back(Item(Item::Purge
,Pkg
));
175 List
.push_back(Item(Item::Remove
,Pkg
));
179 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
180 // ---------------------------------------------------------------------
181 /* This is part of the helper script communication interface, it sends
182 very complete information down to the other end of the pipe.*/
183 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
185 fprintf(F
,"VERSION 2\n");
187 /* Write out all of the configuration directives by walking the
188 configuration tree */
189 const Configuration::Item
*Top
= _config
->Tree(0);
192 if (Top
->Value
.empty() == false)
195 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
196 QuoteString(Top
->Value
,"\n").c_str());
205 while (Top
!= 0 && Top
->Next
== 0)
212 // Write out the package actions in order.
213 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
215 if(I
->Pkg
.end() == true)
218 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
220 fprintf(F
,"%s ",I
->Pkg
.Name());
222 if (I
->Pkg
->CurrentVer
== 0)
225 fprintf(F
,"%s ",I
->Pkg
.CurrentVer().VerStr());
227 // Show the compare operator
229 if (S
.InstallVer
!= 0)
232 if (I
->Pkg
->CurrentVer
!= 0)
233 Comp
= S
.InstVerIter(Cache
).CompareVer(I
->Pkg
.CurrentVer());
240 fprintf(F
,"%s ",S
.InstVerIter(Cache
).VerStr());
245 // Show the filename/operation
246 if (I
->Op
== Item::Install
)
249 if (I
->File
[0] != '/')
250 fprintf(F
,"**ERROR**\n");
252 fprintf(F
,"%s\n",I
->File
.c_str());
254 if (I
->Op
== Item::Configure
)
255 fprintf(F
,"**CONFIGURE**\n");
256 if (I
->Op
== Item::Remove
||
257 I
->Op
== Item::Purge
)
258 fprintf(F
,"**REMOVE**\n");
266 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
267 // ---------------------------------------------------------------------
268 /* This looks for a list of scripts to run from the configuration file
269 each one is run and is fed on standard input a list of all .deb files
270 that are due to be installed. */
271 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
273 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
274 if (Opts
== 0 || Opts
->Child
== 0)
278 unsigned int Count
= 1;
279 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
281 if (Opts
->Value
.empty() == true)
284 // Determine the protocol version
285 string OptSec
= Opts
->Value
;
286 string::size_type Pos
;
287 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
288 Pos
= OptSec
.length();
289 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
291 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
295 if (pipe(Pipes
) != 0)
296 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
297 SetCloseExec(Pipes
[0],true);
298 SetCloseExec(Pipes
[1],true);
300 // Purified Fork for running the script
301 pid_t Process
= ExecFork();
305 dup2(Pipes
[0],STDIN_FILENO
);
306 SetCloseExec(STDOUT_FILENO
,false);
307 SetCloseExec(STDIN_FILENO
,false);
308 SetCloseExec(STDERR_FILENO
,false);
313 Args
[2] = Opts
->Value
.c_str();
315 execv(Args
[0],(char **)Args
);
319 FILE *F
= fdopen(Pipes
[1],"w");
321 return _error
->Errno("fdopen","Faild to open new FD");
323 // Feed it the filenames.
327 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
329 // Only deal with packages to be installed from .deb
330 if (I
->Op
!= Item::Install
)
334 if (I
->File
[0] != '/')
337 /* Feed the filename of each package that is pending install
339 fprintf(F
,"%s\n",I
->File
.c_str());
348 Die
= !SendV2Pkgs(F
);
352 // Clean up the sub process
353 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
354 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
360 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
361 // ---------------------------------------------------------------------
364 void pkgDPkgPM::DoStdin(int master
)
366 unsigned char input_buf
[256] = {0,};
367 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
369 write(master
, input_buf
, len
);
371 stdin_is_dev_null
= true;
374 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
375 // ---------------------------------------------------------------------
377 * read the terminal pty and write log
379 void pkgDPkgPM::DoTerminalPty(int master
)
381 unsigned char term_buf
[1024] = {0,0, };
383 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
384 if(len
== -1 && errno
== EIO
)
386 // this happens when the child is about to exit, we
387 // give it time to actually exit, otherwise we run
394 write(1, term_buf
, len
);
396 fwrite(term_buf
, len
, sizeof(char), term_out
);
399 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
400 // ---------------------------------------------------------------------
403 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd
, char *line
)
405 bool const Debug
= _config
->FindB("Debug::pkgDPkgProgressReporting",false);
406 // the status we output
407 ostringstream status
;
410 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
413 /* dpkg sends strings like this:
414 'status: <pkg>: <pkg qstate>'
415 errors look like this:
416 '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
417 and conffile-prompt like this
418 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
420 Newer versions of dpkg sent also:
421 'processing: install: pkg'
422 'processing: configure: pkg'
423 'processing: remove: pkg'
424 'processing: purge: pkg'
425 'processing: disappear: pkg'
426 'processing: trigproc: trigger'
430 // dpkg sends multiline error messages sometimes (see
431 // #374195 for a example. we should support this by
432 // either patching dpkg to not send multiline over the
433 // statusfd or by rewriting the code here to deal with
434 // it. for now we just ignore it and not crash
435 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
436 if( list
[0] == NULL
|| list
[1] == NULL
|| list
[2] == NULL
)
439 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
442 const char* const pkg
= list
[1];
443 const char* action
= _strstrip(list
[2]);
445 // 'processing' from dpkg looks like
446 // 'processing: action: pkg'
447 if(strncmp(list
[0], "processing", strlen("processing")) == 0)
450 const char* const pkg_or_trigger
= _strstrip(list
[2]);
451 action
= _strstrip( list
[1]);
452 const std::pair
<const char *, const char *> * const iter
=
453 std::find_if(PackageProcessingOpsBegin
,
454 PackageProcessingOpsEnd
,
455 MatchProcessingOp(action
));
456 if(iter
== PackageProcessingOpsEnd
)
459 std::clog
<< "ignoring unknown action: " << action
<< std::endl
;
462 snprintf(s
, sizeof(s
), _(iter
->second
), pkg_or_trigger
);
464 status
<< "pmstatus:" << pkg_or_trigger
465 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
469 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
471 std::clog
<< "send: '" << status
.str() << "'" << endl
;
473 if (strncmp(action
, "disappear", strlen("disappear")) == 0)
474 disappearedPkgs
.insert(string(pkg_or_trigger
));
478 if(strncmp(action
,"error",strlen("error")) == 0)
480 // urgs, sometime has ":" in its error string so that we
481 // end up with the error message split between list[3]
482 // and list[4], e.g. the message:
483 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
485 if( list
[4] != NULL
)
486 list
[3][strlen(list
[3])] = ':';
488 status
<< "pmerror:" << list
[1]
489 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
493 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
495 std::clog
<< "send: '" << status
.str() << "'" << endl
;
497 WriteApportReport(list
[1], list
[3]);
500 else if(strncmp(action
,"conffile",strlen("conffile")) == 0)
502 status
<< "pmconffile:" << list
[1]
503 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
507 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
509 std::clog
<< "send: '" << status
.str() << "'" << endl
;
513 vector
<struct DpkgState
> const &states
= PackageOps
[pkg
];
514 const char *next_action
= NULL
;
515 if(PackageOpsDone
[pkg
] < states
.size())
516 next_action
= states
[PackageOpsDone
[pkg
]].state
;
517 // check if the package moved to the next dpkg state
518 if(next_action
&& (strcmp(action
, next_action
) == 0))
520 // only read the translation if there is actually a next
522 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
524 snprintf(s
, sizeof(s
), translation
, pkg
);
526 // we moved from one dpkg state to a new one, report that
527 PackageOpsDone
[pkg
]++;
529 // build the status str
530 status
<< "pmstatus:" << pkg
531 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
535 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
537 std::clog
<< "send: '" << status
.str() << "'" << endl
;
540 std::clog
<< "(parsed from dpkg) pkg: " << pkg
541 << " action: " << action
<< endl
;
544 // DPkgPM::DoDpkgStatusFd /*{{{*/
545 // ---------------------------------------------------------------------
548 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
, int OutStatusFd
)
553 len
=read(statusfd
, &dpkgbuf
[dpkgbuf_pos
], sizeof(dpkgbuf
)-dpkgbuf_pos
);
558 // process line by line if we have a buffer
560 while((q
=(char*)memchr(p
, '\n', dpkgbuf
+dpkgbuf_pos
-p
)) != NULL
)
563 ProcessDpkgStatusLine(OutStatusFd
, p
);
564 p
=q
+1; // continue with next line
567 // now move the unprocessed bits (after the final \n that is now a 0x0)
568 // to the start and update dpkgbuf_pos
569 p
= (char*)memrchr(dpkgbuf
, 0, dpkgbuf_pos
);
573 // we are interessted in the first char *after* 0x0
576 // move the unprocessed tail to the start and update pos
577 memmove(dpkgbuf
, p
, p
-dpkgbuf
);
578 dpkgbuf_pos
= dpkgbuf
+dpkgbuf_pos
-p
;
581 // DPkgPM::WriteHistoryTag /*{{{*/
582 void pkgDPkgPM::WriteHistoryTag(string tag
, string value
)
584 if (value
.size() > 0)
586 // poor mans rstrip(", ")
587 if (value
[value
.size()-2] == ',' && value
[value
.size()-1] == ' ')
588 value
.erase(value
.size() - 2, 2);
589 fprintf(history_out
, "%s: %s\n", tag
.c_str(), value
.c_str());
592 // DPkgPM::OpenLog /*{{{*/
593 bool pkgDPkgPM::OpenLog()
595 string
const logdir
= _config
->FindDir("Dir::Log");
596 if(not FileExists(logdir
))
597 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
601 time_t const t
= time(NULL
);
602 struct tm
const * const tmp
= localtime(&t
);
603 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
606 string
const logfile_name
= flCombine(logdir
,
607 _config
->Find("Dir::Log::Terminal"));
608 if (!logfile_name
.empty())
610 term_out
= fopen(logfile_name
.c_str(),"a");
611 if (term_out
== NULL
)
612 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name
.c_str());
614 chmod(logfile_name
.c_str(), 0600);
615 fprintf(term_out
, "\nLog started: %s\n", timestr
);
618 // write your history
619 string
const history_name
= flCombine(logdir
,
620 _config
->Find("Dir::Log::History"));
621 if (!history_name
.empty())
623 history_out
= fopen(history_name
.c_str(),"a");
624 if (history_out
== NULL
)
625 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), history_name
.c_str());
626 chmod(history_name
.c_str(), 0644);
627 fprintf(history_out
, "\nStart-Date: %s\n", timestr
);
628 string remove
, purge
, install
, upgrade
, downgrade
;
629 for (pkgCache::PkgIterator I
= Cache
.PkgBegin(); I
.end() == false; I
++)
631 if (Cache
[I
].NewInstall())
632 install
+= I
.Name() + string(" (") + Cache
[I
].CandVersion
+ string("), ");
633 else if (Cache
[I
].Upgrade())
634 upgrade
+= I
.Name() + string(" (") + Cache
[I
].CurVersion
+ string(", ") + Cache
[I
].CandVersion
+ string("), ");
635 else if (Cache
[I
].Downgrade())
636 downgrade
+= I
.Name() + string(" (") + Cache
[I
].CurVersion
+ string(", ") + Cache
[I
].CandVersion
+ string("), ");
637 else if (Cache
[I
].Delete())
639 if ((Cache
[I
].iFlags
& pkgDepCache::Purge
) == pkgDepCache::Purge
)
640 purge
+= I
.Name() + string(" (") + Cache
[I
].CurVersion
+ string("), ");
642 remove
+= I
.Name() + string(" (") + Cache
[I
].CurVersion
+ string("), ");
645 if (_config
->Exists("Commandline::AsString") == true)
646 WriteHistoryTag("Commandline", _config
->Find("Commandline::AsString"));
647 WriteHistoryTag("Install", install
);
648 WriteHistoryTag("Upgrade", upgrade
);
649 WriteHistoryTag("Downgrade",downgrade
);
650 WriteHistoryTag("Remove",remove
);
651 WriteHistoryTag("Purge",purge
);
658 // DPkg::CloseLog /*{{{*/
659 bool pkgDPkgPM::CloseLog()
662 time_t t
= time(NULL
);
663 struct tm
*tmp
= localtime(&t
);
664 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
668 fprintf(term_out
, "Log ended: ");
669 fprintf(term_out
, "%s", timestr
);
670 fprintf(term_out
, "\n");
677 if (dpkg_error
.size() > 0)
678 fprintf(history_out
, "Error: %s\n", dpkg_error
.c_str());
679 fprintf(history_out
, "End-Date: %s\n", timestr
);
688 // This implements a racy version of pselect for those architectures
689 // that don't have a working implementation.
690 // FIXME: Probably can be removed on Lenny+1
691 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
692 fd_set
*exceptfds
, const struct timespec
*timeout
,
693 const sigset_t
*sigmask
)
699 tv
.tv_sec
= timeout
->tv_sec
;
700 tv
.tv_usec
= timeout
->tv_nsec
/1000;
702 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
703 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
704 sigprocmask(SIG_SETMASK
, &origmask
, 0);
708 // DPkgPM::Go - Run the sequence /*{{{*/
709 // ---------------------------------------------------------------------
710 /* This globs the operations and calls dpkg
712 * If it is called with "OutStatusFd" set to a valid file descriptor
713 * apt will report the install progress over this fd. It maps the
714 * dpkg states a package goes through to human readable (and i10n-able)
715 * names and calculates a percentage for each step.
717 bool pkgDPkgPM::Go(int OutStatusFd
)
722 sigset_t original_sigmask
;
724 unsigned int const MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
725 unsigned int const MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
726 bool const NoTriggers
= _config
->FindB("DPkg::NoTriggers", false);
728 if (RunScripts("DPkg::Pre-Invoke") == false)
731 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
734 // support subpressing of triggers processing for special
735 // cases like d-i that runs the triggers handling manually
736 bool const SmartConf
= (_config
->Find("PackageManager::Configure", "all") != "all");
737 bool const TriggersPending
= _config
->FindB("DPkg::TriggersPending", false);
738 if (_config
->FindB("DPkg::ConfigurePending", SmartConf
) == true)
739 List
.push_back(Item(Item::ConfigurePending
, PkgIterator()));
741 // map the dpkg states to the operations that are performed
742 // (this is sorted in the same way as Item::Ops)
743 static const struct DpkgState DpkgStatesOpMap
[][7] = {
746 {"half-installed", N_("Preparing %s")},
747 {"unpacked", N_("Unpacking %s") },
750 // Configure operation
752 {"unpacked",N_("Preparing to configure %s") },
753 {"half-configured", N_("Configuring %s") },
754 { "installed", N_("Installed %s")},
759 {"half-configured", N_("Preparing for removal of %s")},
760 {"half-installed", N_("Removing %s")},
761 {"config-files", N_("Removed %s")},
766 {"config-files", N_("Preparing to completely remove %s")},
767 {"not-installed", N_("Completely removed %s")},
772 // init the PackageOps map, go over the list of packages that
773 // that will be [installed|configured|removed|purged] and add
774 // them to the PackageOps map (the dpkg states it goes through)
775 // and the PackageOpsTranslations (human readable strings)
776 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();I
++)
778 if((*I
).Pkg
.end() == true)
781 string
const name
= (*I
).Pkg
.Name();
782 PackageOpsDone
[name
] = 0;
783 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; i
++)
785 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
790 stdin_is_dev_null
= false;
795 // this loop is runs once per operation
796 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();)
798 // Do all actions with the same Op in one run
799 vector
<Item
>::const_iterator J
= I
;
800 if (TriggersPending
== true)
801 for (; J
!= List
.end(); J
++)
805 if (J
->Op
!= Item::TriggersPending
)
807 vector
<Item
>::const_iterator T
= J
+ 1;
808 if (T
!= List
.end() && T
->Op
== I
->Op
)
813 for (; J
!= List
.end() && J
->Op
== I
->Op
; J
++)
816 // Generate the argument list
817 const char *Args
[MaxArgs
+ 50];
819 // Now check if we are within the MaxArgs limit
821 // this code below is problematic, because it may happen that
822 // the argument list is split in a way that A depends on B
823 // and they are in the same "--configure A B" run
824 // - with the split they may now be configured in different
826 if (J
- I
> (signed)MaxArgs
)
830 unsigned long Size
= 0;
831 string
const Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
832 Args
[n
++] = Tmp
.c_str();
833 Size
+= strlen(Args
[n
-1]);
835 // Stick in any custom dpkg options
836 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
840 for (; Opts
!= 0; Opts
= Opts
->Next
)
842 if (Opts
->Value
.empty() == true)
844 Args
[n
++] = Opts
->Value
.c_str();
845 Size
+= Opts
->Value
.length();
849 char status_fd_buf
[20];
853 Args
[n
++] = "--status-fd";
854 Size
+= strlen(Args
[n
-1]);
855 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
856 Args
[n
++] = status_fd_buf
;
857 Size
+= strlen(Args
[n
-1]);
862 Args
[n
++] = "--force-depends";
863 Size
+= strlen(Args
[n
-1]);
864 Args
[n
++] = "--force-remove-essential";
865 Size
+= strlen(Args
[n
-1]);
866 Args
[n
++] = "--remove";
867 Size
+= strlen(Args
[n
-1]);
871 Args
[n
++] = "--force-depends";
872 Size
+= strlen(Args
[n
-1]);
873 Args
[n
++] = "--force-remove-essential";
874 Size
+= strlen(Args
[n
-1]);
875 Args
[n
++] = "--purge";
876 Size
+= strlen(Args
[n
-1]);
879 case Item::Configure
:
880 Args
[n
++] = "--configure";
881 Size
+= strlen(Args
[n
-1]);
884 case Item::ConfigurePending
:
885 Args
[n
++] = "--configure";
886 Size
+= strlen(Args
[n
-1]);
887 Args
[n
++] = "--pending";
888 Size
+= strlen(Args
[n
-1]);
891 case Item::TriggersPending
:
892 Args
[n
++] = "--triggers-only";
893 Size
+= strlen(Args
[n
-1]);
894 Args
[n
++] = "--pending";
895 Size
+= strlen(Args
[n
-1]);
899 Args
[n
++] = "--unpack";
900 Size
+= strlen(Args
[n
-1]);
901 Args
[n
++] = "--auto-deconfigure";
902 Size
+= strlen(Args
[n
-1]);
906 if (NoTriggers
== true && I
->Op
!= Item::TriggersPending
&&
907 I
->Op
!= Item::ConfigurePending
)
909 Args
[n
++] = "--no-triggers";
910 Size
+= strlen(Args
[n
-1]);
913 // Write in the file or package names
914 if (I
->Op
== Item::Install
)
916 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
918 if (I
->File
[0] != '/')
919 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
920 Args
[n
++] = I
->File
.c_str();
921 Size
+= strlen(Args
[n
-1]);
926 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
928 if((*I
).Pkg
.end() == true)
930 if (I
->Op
== Item::Configure
&& disappearedPkgs
.find(I
->Pkg
.Name()) != disappearedPkgs
.end())
932 Args
[n
++] = I
->Pkg
.Name();
933 Size
+= strlen(Args
[n
-1]);
939 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
941 for (unsigned int k
= 0; k
!= n
; k
++)
942 clog
<< Args
[k
] << ' ';
951 /* Mask off sig int/quit. We do this because dpkg also does when
952 it forks scripts. What happens is that when you hit ctrl-c it sends
953 it to all processes in the group. Since dpkg ignores the signal
954 it doesn't die but we do! So we must also ignore it */
955 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
956 sighandler_t old_SIGINT
= signal(SIGINT
,SIG_IGN
);
958 // ignore SIGHUP as well (debian #463030)
959 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
966 // if tcgetattr does not return zero there was a error
967 // and we do not do any pty magic
968 if (tcgetattr(0, &tt
) == 0)
970 ioctl(0, TIOCGWINSZ
, (char *)&win
);
971 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
973 const char *s
= _("Can not write log, openpty() "
974 "failed (/dev/pts not mounted?)\n");
975 fprintf(stderr
, "%s",s
);
977 fprintf(term_out
, "%s",s
);
983 rtt
.c_lflag
&= ~ECHO
;
985 // block SIGTTOU during tcsetattr to prevent a hang if
986 // the process is a member of the background process group
987 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
988 sigemptyset(&sigmask
);
989 sigaddset(&sigmask
, SIGTTOU
);
990 sigprocmask(SIG_BLOCK
,&sigmask
, &original_sigmask
);
991 tcsetattr(0, TCSAFLUSH
, &rtt
);
992 sigprocmask(SIG_SETMASK
, &original_sigmask
, 0);
998 _config
->Set("APT::Keep-Fds::",fd
[1]);
999 // send status information that we are about to fork dpkg
1000 if(OutStatusFd
> 0) {
1001 ostringstream status
;
1002 status
<< "pmstatus:dpkg-exec:"
1003 << (PackagesDone
/float(PackagesTotal
)*100.0)
1004 << ":" << _("Running dpkg")
1006 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
1010 // This is the child
1013 if(slave
>= 0 && master
>= 0)
1016 ioctl(slave
, TIOCSCTTY
, 0);
1023 close(fd
[0]); // close the read end of the pipe
1025 if (_config
->FindDir("DPkg::Chroot-Directory","/") != "/")
1027 std::cerr
<< "Chrooting into "
1028 << _config
->FindDir("DPkg::Chroot-Directory")
1030 if (chroot(_config
->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
1034 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
1037 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
1040 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
1043 // Discard everything in stdin before forking dpkg
1044 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
1047 while (read(STDIN_FILENO
,&dummy
,1) == 1);
1049 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
1053 /* No Job Control Stop Env is a magic dpkg var that prevents it
1054 from using sigstop */
1055 putenv((char *)"DPKG_NO_TSTP=yes");
1056 execvp(Args
[0],(char **)Args
);
1057 cerr
<< "Could not exec dpkg!" << endl
;
1062 if (_config
->FindB("DPkg::UseIoNice", false) == true)
1065 // clear the Keep-Fd again
1066 _config
->Clear("APT::Keep-Fds",fd
[1]);
1071 // we read from dpkg here
1072 int const _dpkgin
= fd
[0];
1073 close(fd
[1]); // close the write end of the pipe
1079 sigemptyset(&sigmask
);
1080 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
1082 // the result of the waitpid call
1085 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
1087 // FIXME: move this to a function or something, looks ugly here
1088 // error handling, waitpid returned -1
1091 RunScripts("DPkg::Post-Invoke");
1093 // Restore sig int/quit
1094 signal(SIGQUIT
,old_SIGQUIT
);
1095 signal(SIGINT
,old_SIGINT
);
1096 signal(SIGHUP
,old_SIGHUP
);
1097 return _error
->Errno("waitpid","Couldn't wait for subprocess");
1100 // wait for input or output here
1102 if (master
>= 0 && !stdin_is_dev_null
)
1104 FD_SET(_dpkgin
, &rfds
);
1106 FD_SET(master
, &rfds
);
1109 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
1110 &tv
, &original_sigmask
);
1111 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
1112 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
1113 NULL
, &tv
, &original_sigmask
);
1114 if (select_ret
== 0)
1116 else if (select_ret
< 0 && errno
== EINTR
)
1118 else if (select_ret
< 0)
1120 perror("select() returned error");
1124 if(master
>= 0 && FD_ISSET(master
, &rfds
))
1125 DoTerminalPty(master
);
1126 if(master
>= 0 && FD_ISSET(0, &rfds
))
1128 if(FD_ISSET(_dpkgin
, &rfds
))
1129 DoDpkgStatusFd(_dpkgin
, OutStatusFd
);
1133 // Restore sig int/quit
1134 signal(SIGQUIT
,old_SIGQUIT
);
1135 signal(SIGINT
,old_SIGINT
);
1136 signal(SIGHUP
,old_SIGHUP
);
1140 tcsetattr(0, TCSAFLUSH
, &tt
);
1144 // Check for an error code.
1145 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
1147 // if it was set to "keep-dpkg-runing" then we won't return
1148 // here but keep the loop going and just report it as a error
1150 bool const stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
1153 RunScripts("DPkg::Post-Invoke");
1155 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
1156 strprintf(dpkg_error
, "Sub-process %s received a segmentation fault.",Args
[0]);
1157 else if (WIFEXITED(Status
) != 0)
1158 strprintf(dpkg_error
, "Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
1160 strprintf(dpkg_error
, "Sub-process %s exited unexpectedly",Args
[0]);
1162 if(dpkg_error
.size() > 0)
1163 _error
->Error(dpkg_error
.c_str());
1174 if (RunScripts("DPkg::Post-Invoke") == false)
1177 Cache
.writeStateFile(NULL
);
1181 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1182 // ---------------------------------------------------------------------
1184 void pkgDPkgPM::Reset()
1186 List
.erase(List
.begin(),List
.end());
1189 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1190 // ---------------------------------------------------------------------
1192 void pkgDPkgPM::WriteApportReport(const char *pkgpath
, const char *errormsg
)
1194 string pkgname
, reportfile
, srcpkgname
, pkgver
, arch
;
1195 string::size_type pos
;
1198 if (_config
->FindB("Dpkg::ApportFailureReport", false) == false)
1200 std::clog
<< "configured to not write apport reports" << std::endl
;
1204 // only report the first errors
1205 if(pkgFailures
> _config
->FindI("APT::Apport::MaxReports", 3))
1207 std::clog
<< _("No apport report written because MaxReports is reached already") << std::endl
;
1211 // check if its not a follow up error
1212 const char *needle
= dgettext("dpkg", "dependency problems - leaving unconfigured");
1213 if(strstr(errormsg
, needle
) != NULL
) {
1214 std::clog
<< _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl
;
1218 // do not report disk-full failures
1219 if(strstr(errormsg
, strerror(ENOSPC
)) != NULL
) {
1220 std::clog
<< _("No apport report written because the error message indicates a disk full error") << std::endl
;
1224 // do not report out-of-memory failures
1225 if(strstr(errormsg
, strerror(ENOMEM
)) != NULL
) {
1226 std::clog
<< _("No apport report written because the error message indicates a out of memory error") << std::endl
;
1230 // do not report dpkg I/O errors
1231 // XXX - this message is localized, but this only matches the English version. This is better than nothing.
1232 if(strstr(errormsg
, "short read in buffer_copy (")) {
1233 std::clog
<< _("No apport report written because the error message indicates a dpkg I/O error") << std::endl
;
1237 // get the pkgname and reportfile
1238 pkgname
= flNotDir(pkgpath
);
1239 pos
= pkgname
.find('_');
1240 if(pos
!= string::npos
)
1241 pkgname
= pkgname
.substr(0, pos
);
1243 // find the package versin and source package name
1244 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
1245 if (Pkg
.end() == true)
1247 pkgCache::VerIterator Ver
= Cache
.GetCandidateVer(Pkg
);
1248 if (Ver
.end() == true)
1250 pkgver
= Ver
.VerStr() == NULL
? "unknown" : Ver
.VerStr();
1251 pkgRecords
Recs(Cache
);
1252 pkgRecords::Parser
&Parse
= Recs
.Lookup(Ver
.FileList());
1253 srcpkgname
= Parse
.SourcePkg();
1254 if(srcpkgname
.empty())
1255 srcpkgname
= pkgname
;
1257 // if the file exists already, we check:
1258 // - if it was reported already (touched by apport).
1259 // If not, we do nothing, otherwise
1260 // we overwrite it. This is the same behaviour as apport
1261 // - if we have a report with the same pkgversion already
1263 reportfile
= flCombine("/var/crash",pkgname
+".0.crash");
1264 if(FileExists(reportfile
))
1269 // check atime/mtime
1270 stat(reportfile
.c_str(), &buf
);
1271 if(buf
.st_mtime
> buf
.st_atime
)
1274 // check if the existing report is the same version
1275 report
= fopen(reportfile
.c_str(),"r");
1276 while(fgets(strbuf
, sizeof(strbuf
), report
) != NULL
)
1278 if(strstr(strbuf
,"Package:") == strbuf
)
1280 char pkgname
[255], version
[255];
1281 if(sscanf(strbuf
, "Package: %s %s", pkgname
, version
) == 2)
1282 if(strcmp(pkgver
.c_str(), version
) == 0)
1292 // now write the report
1293 arch
= _config
->Find("APT::Architecture");
1294 report
= fopen(reportfile
.c_str(),"w");
1297 if(_config
->FindB("DPkgPM::InitialReportOnly",false) == true)
1298 chmod(reportfile
.c_str(), 0);
1300 chmod(reportfile
.c_str(), 0600);
1301 fprintf(report
, "ProblemType: Package\n");
1302 fprintf(report
, "Architecture: %s\n", arch
.c_str());
1303 time_t now
= time(NULL
);
1304 fprintf(report
, "Date: %s" , ctime(&now
));
1305 fprintf(report
, "Package: %s %s\n", pkgname
.c_str(), pkgver
.c_str());
1306 fprintf(report
, "SourcePackage: %s\n", srcpkgname
.c_str());
1307 fprintf(report
, "ErrorMessage:\n %s\n", errormsg
);
1309 // ensure that the log is flushed
1313 // attach terminal log it if we have it
1314 string logfile_name
= _config
->FindFile("Dir::Log::Terminal");
1315 if (!logfile_name
.empty())
1320 fprintf(report
, "DpkgTerminalLog:\n");
1321 log
= fopen(logfile_name
.c_str(),"r");
1324 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1325 fprintf(report
, " %s", buf
);
1331 const char *ops_str
[] = {"Install", "Configure","Remove","Purge"};
1332 fprintf(report
, "AptOrdering:\n");
1333 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
1334 fprintf(report
, " %s: %s\n", (*I
).Pkg
.Name(), ops_str
[(*I
).Op
]);
1336 // attach dmesg log (to learn about segfaults)
1337 if (FileExists("/bin/dmesg"))
1342 fprintf(report
, "Dmesg:\n");
1343 log
= popen("/bin/dmesg","r");
1346 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1347 fprintf(report
, " %s", buf
);
1352 // attach df -l log (to learn about filesystem status)
1353 if (FileExists("/bin/df"))
1358 fprintf(report
, "Df:\n");
1359 log
= popen("/bin/df -l","r");
1362 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1363 fprintf(report
, " %s", buf
);