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("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
), PackagesDone(0), PackagesTotal(0), pkgFailures(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 List
.push_back(Item(Item::Install
,Pkg
,File
));
134 // DPkgPM::Configure - Configure a package /*{{{*/
135 // ---------------------------------------------------------------------
136 /* Add a configure operation to the sequence list */
137 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
139 if (Pkg
.end() == true)
142 List
.push_back(Item(Item::Configure
, Pkg
));
144 // Use triggers for config calls if we configure "smart"
145 // as otherwise Pre-Depends will not be satisfied, see #526774
146 if (_config
->FindB("DPkg::TriggersPending", false) == true)
147 List
.push_back(Item(Item::TriggersPending
, PkgIterator()));
152 // DPkgPM::Remove - Remove a package /*{{{*/
153 // ---------------------------------------------------------------------
154 /* Add a remove operation to the sequence list */
155 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
157 if (Pkg
.end() == true)
161 List
.push_back(Item(Item::Purge
,Pkg
));
163 List
.push_back(Item(Item::Remove
,Pkg
));
167 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
168 // ---------------------------------------------------------------------
169 /* This is part of the helper script communication interface, it sends
170 very complete information down to the other end of the pipe.*/
171 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
173 fprintf(F
,"VERSION 2\n");
175 /* Write out all of the configuration directives by walking the
176 configuration tree */
177 const Configuration::Item
*Top
= _config
->Tree(0);
180 if (Top
->Value
.empty() == false)
183 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
184 QuoteString(Top
->Value
,"\n").c_str());
193 while (Top
!= 0 && Top
->Next
== 0)
200 // Write out the package actions in order.
201 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
203 if(I
->Pkg
.end() == true)
206 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
208 fprintf(F
,"%s ",I
->Pkg
.Name());
210 if (I
->Pkg
->CurrentVer
== 0)
213 fprintf(F
,"%s ",I
->Pkg
.CurrentVer().VerStr());
215 // Show the compare operator
217 if (S
.InstallVer
!= 0)
220 if (I
->Pkg
->CurrentVer
!= 0)
221 Comp
= S
.InstVerIter(Cache
).CompareVer(I
->Pkg
.CurrentVer());
228 fprintf(F
,"%s ",S
.InstVerIter(Cache
).VerStr());
233 // Show the filename/operation
234 if (I
->Op
== Item::Install
)
237 if (I
->File
[0] != '/')
238 fprintf(F
,"**ERROR**\n");
240 fprintf(F
,"%s\n",I
->File
.c_str());
242 if (I
->Op
== Item::Configure
)
243 fprintf(F
,"**CONFIGURE**\n");
244 if (I
->Op
== Item::Remove
||
245 I
->Op
== Item::Purge
)
246 fprintf(F
,"**REMOVE**\n");
254 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
255 // ---------------------------------------------------------------------
256 /* This looks for a list of scripts to run from the configuration file
257 each one is run and is fed on standard input a list of all .deb files
258 that are due to be installed. */
259 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
261 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
262 if (Opts
== 0 || Opts
->Child
== 0)
266 unsigned int Count
= 1;
267 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
269 if (Opts
->Value
.empty() == true)
272 // Determine the protocol version
273 string OptSec
= Opts
->Value
;
274 string::size_type Pos
;
275 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
276 Pos
= OptSec
.length();
277 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
279 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
283 if (pipe(Pipes
) != 0)
284 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
285 SetCloseExec(Pipes
[0],true);
286 SetCloseExec(Pipes
[1],true);
288 // Purified Fork for running the script
289 pid_t Process
= ExecFork();
293 dup2(Pipes
[0],STDIN_FILENO
);
294 SetCloseExec(STDOUT_FILENO
,false);
295 SetCloseExec(STDIN_FILENO
,false);
296 SetCloseExec(STDERR_FILENO
,false);
301 Args
[2] = Opts
->Value
.c_str();
303 execv(Args
[0],(char **)Args
);
307 FILE *F
= fdopen(Pipes
[1],"w");
309 return _error
->Errno("fdopen","Faild to open new FD");
311 // Feed it the filenames.
315 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
317 // Only deal with packages to be installed from .deb
318 if (I
->Op
!= Item::Install
)
322 if (I
->File
[0] != '/')
325 /* Feed the filename of each package that is pending install
327 fprintf(F
,"%s\n",I
->File
.c_str());
336 Die
= !SendV2Pkgs(F
);
340 // Clean up the sub process
341 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
342 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
348 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
349 // ---------------------------------------------------------------------
352 void pkgDPkgPM::DoStdin(int master
)
354 unsigned char input_buf
[256] = {0,};
355 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
357 write(master
, input_buf
, len
);
359 stdin_is_dev_null
= true;
362 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
363 // ---------------------------------------------------------------------
365 * read the terminal pty and write log
367 void pkgDPkgPM::DoTerminalPty(int master
)
369 unsigned char term_buf
[1024] = {0,0, };
371 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
372 if(len
== -1 && errno
== EIO
)
374 // this happens when the child is about to exit, we
375 // give it time to actually exit, otherwise we run
382 write(1, term_buf
, len
);
384 fwrite(term_buf
, len
, sizeof(char), term_out
);
387 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
388 // ---------------------------------------------------------------------
391 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd
, char *line
)
393 bool const Debug
= _config
->FindB("Debug::pkgDPkgProgressReporting",false);
394 // the status we output
395 ostringstream status
;
398 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
401 /* dpkg sends strings like this:
402 'status: <pkg>: <pkg qstate>'
403 errors look like this:
404 '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
405 and conffile-prompt like this
406 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
408 Newer versions of dpkg sent also:
409 'processing: install: pkg'
410 'processing: configure: pkg'
411 'processing: remove: pkg'
412 'processing: purge: pkg' - but for apt is it a ignored "unknown" action
413 'processing: trigproc: trigger'
417 // dpkg sends multiline error messages sometimes (see
418 // #374195 for a example. we should support this by
419 // either patching dpkg to not send multiline over the
420 // statusfd or by rewriting the code here to deal with
421 // it. for now we just ignore it and not crash
422 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
423 if( list
[0] == NULL
|| list
[1] == NULL
|| list
[2] == NULL
)
426 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
429 const char* const pkg
= list
[1];
430 const char* action
= _strstrip(list
[2]);
432 // 'processing' from dpkg looks like
433 // 'processing: action: pkg'
434 if(strncmp(list
[0], "processing", strlen("processing")) == 0)
437 const char* const pkg_or_trigger
= _strstrip(list
[2]);
438 action
= _strstrip( list
[1]);
439 const std::pair
<const char *, const char *> * const iter
=
440 std::find_if(PackageProcessingOpsBegin
,
441 PackageProcessingOpsEnd
,
442 MatchProcessingOp(action
));
443 if(iter
== PackageProcessingOpsEnd
)
446 std::clog
<< "ignoring unknown action: " << action
<< std::endl
;
449 snprintf(s
, sizeof(s
), _(iter
->second
), pkg_or_trigger
);
451 status
<< "pmstatus:" << pkg_or_trigger
452 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
456 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
458 std::clog
<< "send: '" << status
.str() << "'" << endl
;
462 if(strncmp(action
,"error",strlen("error")) == 0)
464 // urgs, sometime has ":" in its error string so that we
465 // end up with the error message split between list[3]
466 // and list[4], e.g. the message:
467 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
469 if( list
[4] != NULL
)
470 list
[3][strlen(list
[3])] = ':';
472 status
<< "pmerror:" << list
[1]
473 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
477 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
479 std::clog
<< "send: '" << status
.str() << "'" << endl
;
481 WriteApportReport(list
[1], list
[3]);
484 else if(strncmp(action
,"conffile",strlen("conffile")) == 0)
486 status
<< "pmconffile:" << list
[1]
487 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
491 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
493 std::clog
<< "send: '" << status
.str() << "'" << endl
;
497 vector
<struct DpkgState
> const &states
= PackageOps
[pkg
];
498 const char *next_action
= NULL
;
499 if(PackageOpsDone
[pkg
] < states
.size())
500 next_action
= states
[PackageOpsDone
[pkg
]].state
;
501 // check if the package moved to the next dpkg state
502 if(next_action
&& (strcmp(action
, next_action
) == 0))
504 // only read the translation if there is actually a next
506 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
508 snprintf(s
, sizeof(s
), translation
, pkg
);
510 // we moved from one dpkg state to a new one, report that
511 PackageOpsDone
[pkg
]++;
513 // build the status str
514 status
<< "pmstatus:" << pkg
515 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
519 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
521 std::clog
<< "send: '" << status
.str() << "'" << endl
;
524 std::clog
<< "(parsed from dpkg) pkg: " << pkg
525 << " action: " << action
<< endl
;
528 // DPkgPM::DoDpkgStatusFd /*{{{*/
529 // ---------------------------------------------------------------------
532 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
, int OutStatusFd
)
537 len
=read(statusfd
, &dpkgbuf
[dpkgbuf_pos
], sizeof(dpkgbuf
)-dpkgbuf_pos
);
542 // process line by line if we have a buffer
544 while((q
=(char*)memchr(p
, '\n', dpkgbuf
+dpkgbuf_pos
-p
)) != NULL
)
547 ProcessDpkgStatusLine(OutStatusFd
, p
);
548 p
=q
+1; // continue with next line
551 // now move the unprocessed bits (after the final \n that is now a 0x0)
552 // to the start and update dpkgbuf_pos
553 p
= (char*)memrchr(dpkgbuf
, 0, dpkgbuf_pos
);
557 // we are interessted in the first char *after* 0x0
560 // move the unprocessed tail to the start and update pos
561 memmove(dpkgbuf
, p
, p
-dpkgbuf
);
562 dpkgbuf_pos
= dpkgbuf
+dpkgbuf_pos
-p
;
565 // DPkgPM::WriteHistoryTag /*{{{*/
566 void pkgDPkgPM::WriteHistoryTag(FILE *history_out
, string tag
, string value
)
568 if (value
.size() > 0)
570 // poor mans rstrip(", ")
571 if (value
[value
.size()-2] == ',' && value
[value
.size()-1] == ' ')
572 value
.erase(value
.size() - 2, 2);
573 fprintf(history_out
, "%s: %s\n", tag
.c_str(), value
.c_str());
576 // DPkgPM::OpenLog /*{{{*/
577 bool pkgDPkgPM::OpenLog()
579 string
const logdir
= _config
->FindDir("Dir::Log");
580 if(not FileExists(logdir
))
581 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
585 time_t const t
= time(NULL
);
586 struct tm
const * const tmp
= localtime(&t
);
587 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
590 string
const logfile_name
= flCombine(logdir
,
591 _config
->Find("Dir::Log::Terminal"));
592 if (!logfile_name
.empty())
594 term_out
= fopen(logfile_name
.c_str(),"a");
595 if (term_out
== NULL
)
596 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name
.c_str());
598 chmod(logfile_name
.c_str(), 0600);
599 fprintf(term_out
, "\nLog started: %s\n", timestr
);
602 // write your history
603 string
const history_name
= flCombine(logdir
,
604 _config
->Find("Dir::Log::History"));
605 if (!history_name
.empty())
607 FILE *history_out
= fopen(history_name
.c_str(),"a");
608 if (history_out
== NULL
)
609 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), history_name
.c_str());
610 chmod(history_name
.c_str(), 0644);
611 fprintf(history_out
, "\nStart-Date: %s\n", timestr
);
612 string remove
, purge
, install
, upgrade
, downgrade
;
613 for (pkgCache::PkgIterator I
= Cache
.PkgBegin(); I
.end() == false; I
++)
615 if (Cache
[I
].NewInstall())
616 install
+= I
.Name() + string(" (") + Cache
[I
].CandVersion
+ string("), ");
617 else if (Cache
[I
].Upgrade())
618 upgrade
+= I
.Name() + string(" (") + Cache
[I
].CurVersion
+ string(", ") + Cache
[I
].CandVersion
+ string("), ");
619 else if (Cache
[I
].Downgrade())
620 downgrade
+= I
.Name() + string(" (") + Cache
[I
].CurVersion
+ string(", ") + Cache
[I
].CandVersion
+ string("), ");
621 else if (Cache
[I
].Delete())
623 if ((Cache
[I
].iFlags
& pkgDepCache::Purge
) == pkgDepCache::Purge
)
624 purge
+= I
.Name() + string(" (") + Cache
[I
].CurVersion
+ string("), ");
626 remove
+= I
.Name() + string(" (") + Cache
[I
].CurVersion
+ string("), ");
629 WriteHistoryTag(history_out
, "Install", install
);
630 WriteHistoryTag(history_out
, "Upgrade", upgrade
);
631 WriteHistoryTag(history_out
, "Downgrade",downgrade
);
632 WriteHistoryTag(history_out
, "Remove",remove
);
633 WriteHistoryTag(history_out
, "Purge",purge
);
640 // DPkg::CloseLog /*{{{*/
641 bool pkgDPkgPM::CloseLog()
644 time_t t
= time(NULL
);
645 struct tm
*tmp
= localtime(&t
);
646 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
650 fprintf(term_out
, "Log ended: ");
651 fprintf(term_out
, "%s", timestr
);
652 fprintf(term_out
, "\n");
657 string history_name
= flCombine(_config
->FindDir("Dir::Log"),
658 _config
->Find("Dir::Log::History"));
659 if (!history_name
.empty())
661 FILE *history_out
= fopen(history_name
.c_str(),"a");
662 fprintf(history_out
, "End-Date: %s\n", timestr
);
670 // This implements a racy version of pselect for those architectures
671 // that don't have a working implementation.
672 // FIXME: Probably can be removed on Lenny+1
673 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
674 fd_set
*exceptfds
, const struct timespec
*timeout
,
675 const sigset_t
*sigmask
)
681 tv
.tv_sec
= timeout
->tv_sec
;
682 tv
.tv_usec
= timeout
->tv_nsec
/1000;
684 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
685 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
686 sigprocmask(SIG_SETMASK
, &origmask
, 0);
690 // DPkgPM::Go - Run the sequence /*{{{*/
691 // ---------------------------------------------------------------------
692 /* This globs the operations and calls dpkg
694 * If it is called with "OutStatusFd" set to a valid file descriptor
695 * apt will report the install progress over this fd. It maps the
696 * dpkg states a package goes through to human readable (and i10n-able)
697 * names and calculates a percentage for each step.
699 bool pkgDPkgPM::Go(int OutStatusFd
)
704 sigset_t original_sigmask
;
706 unsigned int const MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
707 unsigned int const MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
708 bool const NoTriggers
= _config
->FindB("DPkg::NoTriggers", false);
710 if (RunScripts("DPkg::Pre-Invoke") == false)
713 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
716 // support subpressing of triggers processing for special
717 // cases like d-i that runs the triggers handling manually
718 bool const SmartConf
= (_config
->Find("PackageManager::Configure", "all") != "all");
719 bool const TriggersPending
= _config
->FindB("DPkg::TriggersPending", false);
720 if (_config
->FindB("DPkg::ConfigurePending", SmartConf
) == true)
721 List
.push_back(Item(Item::ConfigurePending
, PkgIterator()));
723 // map the dpkg states to the operations that are performed
724 // (this is sorted in the same way as Item::Ops)
725 static const struct DpkgState DpkgStatesOpMap
[][7] = {
728 {"half-installed", N_("Preparing %s")},
729 {"unpacked", N_("Unpacking %s") },
732 // Configure operation
734 {"unpacked",N_("Preparing to configure %s") },
735 {"half-configured", N_("Configuring %s") },
736 { "installed", N_("Installed %s")},
741 {"half-configured", N_("Preparing for removal of %s")},
742 {"half-installed", N_("Removing %s")},
743 {"config-files", N_("Removed %s")},
748 {"config-files", N_("Preparing to completely remove %s")},
749 {"not-installed", N_("Completely removed %s")},
754 // init the PackageOps map, go over the list of packages that
755 // that will be [installed|configured|removed|purged] and add
756 // them to the PackageOps map (the dpkg states it goes through)
757 // and the PackageOpsTranslations (human readable strings)
758 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();I
++)
760 if((*I
).Pkg
.end() == true)
763 string
const name
= (*I
).Pkg
.Name();
764 PackageOpsDone
[name
] = 0;
765 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; i
++)
767 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
772 stdin_is_dev_null
= false;
777 // this loop is runs once per operation
778 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();)
780 // Do all actions with the same Op in one run
781 vector
<Item
>::const_iterator J
= I
;
782 if (TriggersPending
== true)
783 for (; J
!= List
.end(); J
++)
787 if (J
->Op
!= Item::TriggersPending
)
789 vector
<Item
>::const_iterator T
= J
+ 1;
790 if (T
!= List
.end() && T
->Op
== I
->Op
)
795 for (; J
!= List
.end() && J
->Op
== I
->Op
; J
++)
798 // Generate the argument list
799 const char *Args
[MaxArgs
+ 50];
801 // Now check if we are within the MaxArgs limit
803 // this code below is problematic, because it may happen that
804 // the argument list is split in a way that A depends on B
805 // and they are in the same "--configure A B" run
806 // - with the split they may now be configured in different
808 if (J
- I
> (signed)MaxArgs
)
812 unsigned long Size
= 0;
813 string
const Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
814 Args
[n
++] = Tmp
.c_str();
815 Size
+= strlen(Args
[n
-1]);
817 // Stick in any custom dpkg options
818 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
822 for (; Opts
!= 0; Opts
= Opts
->Next
)
824 if (Opts
->Value
.empty() == true)
826 Args
[n
++] = Opts
->Value
.c_str();
827 Size
+= Opts
->Value
.length();
831 char status_fd_buf
[20];
835 Args
[n
++] = "--status-fd";
836 Size
+= strlen(Args
[n
-1]);
837 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
838 Args
[n
++] = status_fd_buf
;
839 Size
+= strlen(Args
[n
-1]);
844 Args
[n
++] = "--force-depends";
845 Size
+= strlen(Args
[n
-1]);
846 Args
[n
++] = "--force-remove-essential";
847 Size
+= strlen(Args
[n
-1]);
848 Args
[n
++] = "--remove";
849 Size
+= strlen(Args
[n
-1]);
853 Args
[n
++] = "--force-depends";
854 Size
+= strlen(Args
[n
-1]);
855 Args
[n
++] = "--force-remove-essential";
856 Size
+= strlen(Args
[n
-1]);
857 Args
[n
++] = "--purge";
858 Size
+= strlen(Args
[n
-1]);
861 case Item::Configure
:
862 Args
[n
++] = "--configure";
863 Size
+= strlen(Args
[n
-1]);
866 case Item::ConfigurePending
:
867 Args
[n
++] = "--configure";
868 Size
+= strlen(Args
[n
-1]);
869 Args
[n
++] = "--pending";
870 Size
+= strlen(Args
[n
-1]);
873 case Item::TriggersPending
:
874 Args
[n
++] = "--triggers-only";
875 Size
+= strlen(Args
[n
-1]);
876 Args
[n
++] = "--pending";
877 Size
+= strlen(Args
[n
-1]);
881 Args
[n
++] = "--unpack";
882 Size
+= strlen(Args
[n
-1]);
883 Args
[n
++] = "--auto-deconfigure";
884 Size
+= strlen(Args
[n
-1]);
888 if (NoTriggers
== true && I
->Op
!= Item::TriggersPending
&&
889 I
->Op
!= Item::ConfigurePending
)
891 Args
[n
++] = "--no-triggers";
892 Size
+= strlen(Args
[n
-1]);
895 // Write in the file or package names
896 if (I
->Op
== Item::Install
)
898 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
900 if (I
->File
[0] != '/')
901 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
902 Args
[n
++] = I
->File
.c_str();
903 Size
+= strlen(Args
[n
-1]);
908 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
910 if((*I
).Pkg
.end() == true)
912 Args
[n
++] = I
->Pkg
.Name();
913 Size
+= strlen(Args
[n
-1]);
919 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
921 for (unsigned int k
= 0; k
!= n
; k
++)
922 clog
<< Args
[k
] << ' ';
931 /* Mask off sig int/quit. We do this because dpkg also does when
932 it forks scripts. What happens is that when you hit ctrl-c it sends
933 it to all processes in the group. Since dpkg ignores the signal
934 it doesn't die but we do! So we must also ignore it */
935 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
936 sighandler_t old_SIGINT
= signal(SIGINT
,SIG_IGN
);
938 // ignore SIGHUP as well (debian #463030)
939 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
946 // if tcgetattr does not return zero there was a error
947 // and we do not do any pty magic
948 if (tcgetattr(0, &tt
) == 0)
950 ioctl(0, TIOCGWINSZ
, (char *)&win
);
951 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
953 const char *s
= _("Can not write log, openpty() "
954 "failed (/dev/pts not mounted?)\n");
955 fprintf(stderr
, "%s",s
);
957 fprintf(term_out
, "%s",s
);
963 rtt
.c_lflag
&= ~ECHO
;
965 // block SIGTTOU during tcsetattr to prevent a hang if
966 // the process is a member of the background process group
967 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
968 sigemptyset(&sigmask
);
969 sigaddset(&sigmask
, SIGTTOU
);
970 sigprocmask(SIG_BLOCK
,&sigmask
, &original_sigmask
);
971 tcsetattr(0, TCSAFLUSH
, &rtt
);
972 sigprocmask(SIG_SETMASK
, &original_sigmask
, 0);
978 _config
->Set("APT::Keep-Fds::",fd
[1]);
979 // send status information that we are about to fork dpkg
980 if(OutStatusFd
> 0) {
981 ostringstream status
;
982 status
<< "pmstatus:dpkg-exec:"
983 << (PackagesDone
/float(PackagesTotal
)*100.0)
984 << ":" << _("Running dpkg")
986 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
993 if(slave
>= 0 && master
>= 0)
996 ioctl(slave
, TIOCSCTTY
, 0);
1003 close(fd
[0]); // close the read end of the pipe
1005 if (_config
->FindDir("DPkg::Chroot-Directory","/") != "/")
1007 std::cerr
<< "Chrooting into "
1008 << _config
->FindDir("DPkg::Chroot-Directory")
1010 if (chroot(_config
->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
1014 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
1017 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
1020 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
1023 // Discard everything in stdin before forking dpkg
1024 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
1027 while (read(STDIN_FILENO
,&dummy
,1) == 1);
1029 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
1033 /* No Job Control Stop Env is a magic dpkg var that prevents it
1034 from using sigstop */
1035 putenv((char *)"DPKG_NO_TSTP=yes");
1036 execvp(Args
[0],(char **)Args
);
1037 cerr
<< "Could not exec dpkg!" << endl
;
1042 if (_config
->FindB("DPkg::UseIoNice", false) == true)
1045 // clear the Keep-Fd again
1046 _config
->Clear("APT::Keep-Fds",fd
[1]);
1051 // we read from dpkg here
1052 int const _dpkgin
= fd
[0];
1053 close(fd
[1]); // close the write end of the pipe
1059 sigemptyset(&sigmask
);
1060 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
1062 // the result of the waitpid call
1065 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
1067 // FIXME: move this to a function or something, looks ugly here
1068 // error handling, waitpid returned -1
1071 RunScripts("DPkg::Post-Invoke");
1073 // Restore sig int/quit
1074 signal(SIGQUIT
,old_SIGQUIT
);
1075 signal(SIGINT
,old_SIGINT
);
1076 signal(SIGHUP
,old_SIGHUP
);
1077 return _error
->Errno("waitpid","Couldn't wait for subprocess");
1079 // wait for input or output here
1081 if (!stdin_is_dev_null
)
1083 FD_SET(_dpkgin
, &rfds
);
1085 FD_SET(master
, &rfds
);
1088 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
1089 &tv
, &original_sigmask
);
1090 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
1091 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
1092 NULL
, &tv
, &original_sigmask
);
1093 if (select_ret
== 0)
1095 else if (select_ret
< 0 && errno
== EINTR
)
1097 else if (select_ret
< 0)
1099 perror("select() returned error");
1103 if(master
>= 0 && FD_ISSET(master
, &rfds
))
1104 DoTerminalPty(master
);
1105 if(master
>= 0 && FD_ISSET(0, &rfds
))
1107 if(FD_ISSET(_dpkgin
, &rfds
))
1108 DoDpkgStatusFd(_dpkgin
, OutStatusFd
);
1112 // Restore sig int/quit
1113 signal(SIGQUIT
,old_SIGQUIT
);
1114 signal(SIGINT
,old_SIGINT
);
1115 signal(SIGHUP
,old_SIGHUP
);
1119 tcsetattr(0, TCSAFLUSH
, &tt
);
1123 // Check for an error code.
1124 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
1126 // if it was set to "keep-dpkg-runing" then we won't return
1127 // here but keep the loop going and just report it as a error
1129 bool const stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
1132 RunScripts("DPkg::Post-Invoke");
1135 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
1136 strprintf(dpkg_error
, "Sub-process %s received a segmentation fault.",Args
[0]);
1137 else if (WIFEXITED(Status
) != 0)
1138 strprintf(dpkg_error
, "Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
1140 strprintf(dpkg_error
, "Sub-process %s exited unexpectedly",Args
[0]);
1142 if(dpkg_error
.size() > 0)
1144 _error
->Error(dpkg_error
.c_str());
1145 string history_name
= flCombine(_config
->FindDir("Dir::Log"),
1146 _config
->Find("Dir::Log::History"));
1147 if (!history_name
.empty())
1149 FILE *history_out
= fopen(history_name
.c_str(),"a");
1150 fprintf(history_out
, "Error: %s\n", dpkg_error
.c_str());
1151 fclose(history_out
);
1164 if (RunScripts("DPkg::Post-Invoke") == false)
1167 Cache
.writeStateFile(NULL
);
1171 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1172 // ---------------------------------------------------------------------
1174 void pkgDPkgPM::Reset()
1176 List
.erase(List
.begin(),List
.end());
1179 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1180 // ---------------------------------------------------------------------
1182 void pkgDPkgPM::WriteApportReport(const char *pkgpath
, const char *errormsg
)
1184 string pkgname
, reportfile
, srcpkgname
, pkgver
, arch
;
1185 string::size_type pos
;
1188 if (_config
->FindB("Dpkg::ApportFailureReport",true) == false)
1190 std::clog
<< "configured to not write apport reports" << std::endl
;
1194 // only report the first errors
1195 if(pkgFailures
> _config
->FindI("APT::Apport::MaxReports", 3))
1197 std::clog
<< _("No apport report written because MaxReports is reached already") << std::endl
;
1201 // check if its not a follow up error
1202 const char *needle
= dgettext("dpkg", "dependency problems - leaving unconfigured");
1203 if(strstr(errormsg
, needle
) != NULL
) {
1204 std::clog
<< _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl
;
1208 // do not report disk-full failures
1209 if(strstr(errormsg
, strerror(ENOSPC
)) != NULL
) {
1210 std::clog
<< _("No apport report written because the error message indicates a disk full error") << std::endl
;
1214 // do not report out-of-memory failures
1215 if(strstr(errormsg
, strerror(ENOMEM
)) != NULL
) {
1216 std::clog
<< _("No apport report written because the error message indicates a out of memory error") << std::endl
;
1220 // do not report dpkg I/O errors
1221 // XXX - this message is localized, but this only matches the English version. This is better than nothing.
1222 if(strstr(errormsg
, "short read in buffer_copy (")) {
1223 std::clog
<< _("No apport report written because the error message indicates a dpkg I/O error") << std::endl
;
1227 // get the pkgname and reportfile
1228 pkgname
= flNotDir(pkgpath
);
1229 pos
= pkgname
.find('_');
1230 if(pos
!= string::npos
)
1231 pkgname
= pkgname
.substr(0, pos
);
1233 // find the package versin and source package name
1234 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
1235 if (Pkg
.end() == true)
1237 pkgCache::VerIterator Ver
= Cache
.GetCandidateVer(Pkg
);
1238 if (Ver
.end() == true)
1240 pkgver
= Ver
.VerStr() == NULL
? "unknown" : Ver
.VerStr();
1241 pkgRecords
Recs(Cache
);
1242 pkgRecords::Parser
&Parse
= Recs
.Lookup(Ver
.FileList());
1243 srcpkgname
= Parse
.SourcePkg();
1244 if(srcpkgname
.empty())
1245 srcpkgname
= pkgname
;
1247 // if the file exists already, we check:
1248 // - if it was reported already (touched by apport).
1249 // If not, we do nothing, otherwise
1250 // we overwrite it. This is the same behaviour as apport
1251 // - if we have a report with the same pkgversion already
1253 reportfile
= flCombine("/var/crash",pkgname
+".0.crash");
1254 if(FileExists(reportfile
))
1259 // check atime/mtime
1260 stat(reportfile
.c_str(), &buf
);
1261 if(buf
.st_mtime
> buf
.st_atime
)
1264 // check if the existing report is the same version
1265 report
= fopen(reportfile
.c_str(),"r");
1266 while(fgets(strbuf
, sizeof(strbuf
), report
) != NULL
)
1268 if(strstr(strbuf
,"Package:") == strbuf
)
1270 char pkgname
[255], version
[255];
1271 if(sscanf(strbuf
, "Package: %s %s", pkgname
, version
) == 2)
1272 if(strcmp(pkgver
.c_str(), version
) == 0)
1282 // now write the report
1283 arch
= _config
->Find("APT::Architecture");
1284 report
= fopen(reportfile
.c_str(),"w");
1287 if(_config
->FindB("DPkgPM::InitialReportOnly",false) == true)
1288 chmod(reportfile
.c_str(), 0);
1290 chmod(reportfile
.c_str(), 0600);
1291 fprintf(report
, "ProblemType: Package\n");
1292 fprintf(report
, "Architecture: %s\n", arch
.c_str());
1293 time_t now
= time(NULL
);
1294 fprintf(report
, "Date: %s" , ctime(&now
));
1295 fprintf(report
, "Package: %s %s\n", pkgname
.c_str(), pkgver
.c_str());
1296 fprintf(report
, "SourcePackage: %s\n", srcpkgname
.c_str());
1297 fprintf(report
, "ErrorMessage:\n %s\n", errormsg
);
1299 // ensure that the log is flushed
1303 // attach terminal log it if we have it
1304 string logfile_name
= _config
->FindFile("Dir::Log::Terminal");
1305 if (!logfile_name
.empty())
1310 fprintf(report
, "DpkgTerminalLog:\n");
1311 log
= fopen(logfile_name
.c_str(),"r");
1314 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1315 fprintf(report
, " %s", buf
);
1321 const char *ops_str
[] = {"Install", "Configure","Remove","Purge"};
1322 fprintf(report
, "AptOrdering:\n");
1323 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
1324 fprintf(report
, " %s: %s\n", (*I
).Pkg
.Name(), ops_str
[(*I
).Op
]);
1326 // attach dmesg log (to learn about segfaults)
1327 if (FileExists("/bin/dmesg"))
1332 fprintf(report
, "Dmesg:\n");
1333 log
= popen("/bin/dmesg","r");
1336 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1337 fprintf(report
, " %s", buf
);
1342 // attach df -l log (to learn about filesystem status)
1343 if (FileExists("/bin/df"))
1348 fprintf(report
, "Df:\n");
1349 log
= popen("/bin/df -l","r");
1352 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1353 fprintf(report
, " %s", buf
);