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/strutl.h>
17 #include <apt-pkg/fileutl.h>
22 #include <sys/select.h>
23 #include <sys/types.h>
35 #include <sys/ioctl.h>
46 // Maps the dpkg "processing" info to human readable names. Entry 0
47 // of each array is the key, entry 1 is the value.
48 const std::pair
<const char *, const char *> PackageProcessingOps
[] = {
49 std::make_pair("install", N_("Installing %s")),
50 std::make_pair("configure", N_("Configuring %s")),
51 std::make_pair("remove", N_("Removing %s")),
52 std::make_pair("purge", N_("Completely removing %s")),
53 std::make_pair("disappear", N_("Noting disappearance of %s")),
54 std::make_pair("trigproc", N_("Running post-installation trigger %s"))
57 const std::pair
<const char *, const char *> * const PackageProcessingOpsBegin
= PackageProcessingOps
;
58 const std::pair
<const char *, const char *> * const PackageProcessingOpsEnd
= PackageProcessingOps
+ sizeof(PackageProcessingOps
) / sizeof(PackageProcessingOps
[0]);
60 // Predicate to test whether an entry in the PackageProcessingOps
61 // array matches a string.
62 class MatchProcessingOp
67 MatchProcessingOp(const char *the_target
)
72 bool operator()(const std::pair
<const char *, const char *> &pair
) const
74 return strcmp(pair
.first
, target
) == 0;
79 /* helper function to ionice the given PID
81 there is no C header for ionice yet - just the syscall interface
82 so we use the binary from util-linux
87 if (!FileExists("/usr/bin/ionice"))
89 pid_t Process
= ExecFork();
93 snprintf(buf
, sizeof(buf
), "-p%d", PID
);
95 Args
[0] = "/usr/bin/ionice";
99 execv(Args
[0], (char **)Args
);
101 return ExecWait(Process
, "ionice");
104 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
105 // ---------------------------------------------------------------------
107 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
108 : pkgPackageManager(Cache
), dpkgbuf_pos(0),
109 term_out(NULL
), history_out(NULL
), PackagesDone(0), PackagesTotal(0)
113 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
114 // ---------------------------------------------------------------------
116 pkgDPkgPM::~pkgDPkgPM()
120 // DPkgPM::Install - Install a package /*{{{*/
121 // ---------------------------------------------------------------------
122 /* Add an install operation to the sequence list */
123 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
125 if (File
.empty() == true || Pkg
.end() == true)
126 return _error
->Error("Internal Error, No file name for %s",Pkg
.Name());
128 // If the filename string begins with DPkg::Chroot-Directory, return the
129 // substr that is within the chroot so dpkg can access it.
130 string
const chrootdir
= _config
->FindDir("DPkg::Chroot-Directory","/");
131 if (chrootdir
!= "/" && File
.find(chrootdir
) == 0)
133 size_t len
= chrootdir
.length();
134 if (chrootdir
.at(len
- 1) == '/')
136 List
.push_back(Item(Item::Install
,Pkg
,File
.substr(len
)));
139 List
.push_back(Item(Item::Install
,Pkg
,File
));
144 // DPkgPM::Configure - Configure a package /*{{{*/
145 // ---------------------------------------------------------------------
146 /* Add a configure operation to the sequence list */
147 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
149 if (Pkg
.end() == true)
152 List
.push_back(Item(Item::Configure
, Pkg
));
154 // Use triggers for config calls if we configure "smart"
155 // as otherwise Pre-Depends will not be satisfied, see #526774
156 if (_config
->FindB("DPkg::TriggersPending", false) == true)
157 List
.push_back(Item(Item::TriggersPending
, PkgIterator()));
162 // DPkgPM::Remove - Remove a package /*{{{*/
163 // ---------------------------------------------------------------------
164 /* Add a remove operation to the sequence list */
165 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
167 if (Pkg
.end() == true)
171 List
.push_back(Item(Item::Purge
,Pkg
));
173 List
.push_back(Item(Item::Remove
,Pkg
));
177 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
178 // ---------------------------------------------------------------------
179 /* This is part of the helper script communication interface, it sends
180 very complete information down to the other end of the pipe.*/
181 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
183 fprintf(F
,"VERSION 2\n");
185 /* Write out all of the configuration directives by walking the
186 configuration tree */
187 const Configuration::Item
*Top
= _config
->Tree(0);
190 if (Top
->Value
.empty() == false)
193 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
194 QuoteString(Top
->Value
,"\n").c_str());
203 while (Top
!= 0 && Top
->Next
== 0)
210 // Write out the package actions in order.
211 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
213 if(I
->Pkg
.end() == true)
216 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
218 fprintf(F
,"%s ",I
->Pkg
.Name());
220 if (I
->Pkg
->CurrentVer
== 0)
223 fprintf(F
,"%s ",I
->Pkg
.CurrentVer().VerStr());
225 // Show the compare operator
227 if (S
.InstallVer
!= 0)
230 if (I
->Pkg
->CurrentVer
!= 0)
231 Comp
= S
.InstVerIter(Cache
).CompareVer(I
->Pkg
.CurrentVer());
238 fprintf(F
,"%s ",S
.InstVerIter(Cache
).VerStr());
243 // Show the filename/operation
244 if (I
->Op
== Item::Install
)
247 if (I
->File
[0] != '/')
248 fprintf(F
,"**ERROR**\n");
250 fprintf(F
,"%s\n",I
->File
.c_str());
252 if (I
->Op
== Item::Configure
)
253 fprintf(F
,"**CONFIGURE**\n");
254 if (I
->Op
== Item::Remove
||
255 I
->Op
== Item::Purge
)
256 fprintf(F
,"**REMOVE**\n");
264 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
265 // ---------------------------------------------------------------------
266 /* This looks for a list of scripts to run from the configuration file
267 each one is run and is fed on standard input a list of all .deb files
268 that are due to be installed. */
269 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
271 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
272 if (Opts
== 0 || Opts
->Child
== 0)
276 unsigned int Count
= 1;
277 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
279 if (Opts
->Value
.empty() == true)
282 // Determine the protocol version
283 string OptSec
= Opts
->Value
;
284 string::size_type Pos
;
285 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
286 Pos
= OptSec
.length();
287 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
289 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
293 if (pipe(Pipes
) != 0)
294 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
295 SetCloseExec(Pipes
[0],true);
296 SetCloseExec(Pipes
[1],true);
298 // Purified Fork for running the script
299 pid_t Process
= ExecFork();
303 dup2(Pipes
[0],STDIN_FILENO
);
304 SetCloseExec(STDOUT_FILENO
,false);
305 SetCloseExec(STDIN_FILENO
,false);
306 SetCloseExec(STDERR_FILENO
,false);
311 Args
[2] = Opts
->Value
.c_str();
313 execv(Args
[0],(char **)Args
);
317 FILE *F
= fdopen(Pipes
[1],"w");
319 return _error
->Errno("fdopen","Faild to open new FD");
321 // Feed it the filenames.
325 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
327 // Only deal with packages to be installed from .deb
328 if (I
->Op
!= Item::Install
)
332 if (I
->File
[0] != '/')
335 /* Feed the filename of each package that is pending install
337 fprintf(F
,"%s\n",I
->File
.c_str());
346 Die
= !SendV2Pkgs(F
);
350 // Clean up the sub process
351 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
352 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
359 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
360 // ---------------------------------------------------------------------
363 void pkgDPkgPM::DoStdin(int master
)
365 unsigned char input_buf
[256] = {0,};
366 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
368 write(master
, input_buf
, len
);
370 stdin_is_dev_null
= true;
373 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
374 // ---------------------------------------------------------------------
376 * read the terminal pty and write log
378 void pkgDPkgPM::DoTerminalPty(int master
)
380 unsigned char term_buf
[1024] = {0,0, };
382 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
383 if(len
== -1 && errno
== EIO
)
385 // this happens when the child is about to exit, we
386 // give it time to actually exit, otherwise we run
393 write(1, term_buf
, len
);
395 fwrite(term_buf
, len
, sizeof(char), term_out
);
398 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
399 // ---------------------------------------------------------------------
402 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd
, char *line
)
404 bool const Debug
= _config
->FindB("Debug::pkgDPkgProgressReporting",false);
405 // the status we output
406 ostringstream status
;
409 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
412 /* dpkg sends strings like this:
413 'status: <pkg>: <pkg qstate>'
414 errors look like this:
415 '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
416 and conffile-prompt like this
417 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
419 Newer versions of dpkg sent also:
420 'processing: install: pkg'
421 'processing: configure: pkg'
422 'processing: remove: pkg'
423 'processing: purge: pkg'
424 'processing: disappear: pkg'
425 'processing: trigproc: trigger'
429 // dpkg sends multiline error messages sometimes (see
430 // #374195 for a example. we should support this by
431 // either patching dpkg to not send multiline over the
432 // statusfd or by rewriting the code here to deal with
433 // it. for now we just ignore it and not crash
434 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
435 if( list
[0] == NULL
|| list
[1] == NULL
|| list
[2] == NULL
)
438 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
441 const char* const pkg
= list
[1];
442 const char* action
= _strstrip(list
[2]);
444 // 'processing' from dpkg looks like
445 // 'processing: action: pkg'
446 if(strncmp(list
[0], "processing", strlen("processing")) == 0)
449 const char* const pkg_or_trigger
= _strstrip(list
[2]);
450 action
= _strstrip( list
[1]);
451 const std::pair
<const char *, const char *> * const iter
=
452 std::find_if(PackageProcessingOpsBegin
,
453 PackageProcessingOpsEnd
,
454 MatchProcessingOp(action
));
455 if(iter
== PackageProcessingOpsEnd
)
458 std::clog
<< "ignoring unknown action: " << action
<< std::endl
;
461 snprintf(s
, sizeof(s
), _(iter
->second
), pkg_or_trigger
);
463 status
<< "pmstatus:" << pkg_or_trigger
464 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
468 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
470 std::clog
<< "send: '" << status
.str() << "'" << endl
;
472 if (strncmp(action
, "disappear", strlen("disappear")) == 0)
473 disappearedPkgs
.insert(string(pkg_or_trigger
));
477 if(strncmp(action
,"error",strlen("error")) == 0)
479 status
<< "pmerror:" << list
[1]
480 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
484 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
486 std::clog
<< "send: '" << status
.str() << "'" << endl
;
489 else if(strncmp(action
,"conffile",strlen("conffile")) == 0)
491 status
<< "pmconffile:" << list
[1]
492 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
496 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
498 std::clog
<< "send: '" << status
.str() << "'" << endl
;
502 vector
<struct DpkgState
> const &states
= PackageOps
[pkg
];
503 const char *next_action
= NULL
;
504 if(PackageOpsDone
[pkg
] < states
.size())
505 next_action
= states
[PackageOpsDone
[pkg
]].state
;
506 // check if the package moved to the next dpkg state
507 if(next_action
&& (strcmp(action
, next_action
) == 0))
509 // only read the translation if there is actually a next
511 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
513 snprintf(s
, sizeof(s
), translation
, pkg
);
515 // we moved from one dpkg state to a new one, report that
516 PackageOpsDone
[pkg
]++;
518 // build the status str
519 status
<< "pmstatus:" << pkg
520 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
524 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
526 std::clog
<< "send: '" << status
.str() << "'" << endl
;
529 std::clog
<< "(parsed from dpkg) pkg: " << pkg
530 << " action: " << action
<< endl
;
533 // DPkgPM::DoDpkgStatusFd /*{{{*/
534 // ---------------------------------------------------------------------
537 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
, int OutStatusFd
)
542 len
=read(statusfd
, &dpkgbuf
[dpkgbuf_pos
], sizeof(dpkgbuf
)-dpkgbuf_pos
);
547 // process line by line if we have a buffer
549 while((q
=(char*)memchr(p
, '\n', dpkgbuf
+dpkgbuf_pos
-p
)) != NULL
)
552 ProcessDpkgStatusLine(OutStatusFd
, p
);
553 p
=q
+1; // continue with next line
556 // now move the unprocessed bits (after the final \n that is now a 0x0)
557 // to the start and update dpkgbuf_pos
558 p
= (char*)memrchr(dpkgbuf
, 0, dpkgbuf_pos
);
562 // we are interessted in the first char *after* 0x0
565 // move the unprocessed tail to the start and update pos
566 memmove(dpkgbuf
, p
, p
-dpkgbuf
);
567 dpkgbuf_pos
= dpkgbuf
+dpkgbuf_pos
-p
;
570 // DPkgPM::WriteHistoryTag /*{{{*/
571 void pkgDPkgPM::WriteHistoryTag(string tag
, string value
)
573 if (value
.size() > 0)
575 // poor mans rstrip(", ")
576 if (value
[value
.size()-2] == ',' && value
[value
.size()-1] == ' ')
577 value
.erase(value
.size() - 2, 2);
578 fprintf(history_out
, "%s: %s\n", tag
.c_str(), value
.c_str());
581 // DPkgPM::OpenLog /*{{{*/
582 bool pkgDPkgPM::OpenLog()
584 string
const logdir
= _config
->FindDir("Dir::Log");
585 if(not FileExists(logdir
))
586 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
590 time_t const t
= time(NULL
);
591 struct tm
const * const tmp
= localtime(&t
);
592 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
595 string
const logfile_name
= flCombine(logdir
,
596 _config
->Find("Dir::Log::Terminal"));
597 if (!logfile_name
.empty())
599 term_out
= fopen(logfile_name
.c_str(),"a");
600 if (term_out
== NULL
)
601 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name
.c_str());
603 chmod(logfile_name
.c_str(), 0600);
604 fprintf(term_out
, "\nLog started: %s\n", timestr
);
607 // write your history
608 string
const history_name
= flCombine(logdir
,
609 _config
->Find("Dir::Log::History"));
610 if (!history_name
.empty())
612 history_out
= fopen(history_name
.c_str(),"a");
613 if (history_out
== NULL
)
614 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), history_name
.c_str());
615 chmod(history_name
.c_str(), 0644);
616 fprintf(history_out
, "\nStart-Date: %s\n", timestr
);
617 string remove
, purge
, install
, upgrade
, downgrade
;
618 for (pkgCache::PkgIterator I
= Cache
.PkgBegin(); I
.end() == false; I
++)
620 if (Cache
[I
].NewInstall())
621 install
+= I
.Name() + string(" (") + Cache
[I
].CandVersion
+ string("), ");
622 else if (Cache
[I
].Upgrade())
623 upgrade
+= I
.Name() + string(" (") + Cache
[I
].CurVersion
+ string(", ") + Cache
[I
].CandVersion
+ string("), ");
624 else if (Cache
[I
].Downgrade())
625 downgrade
+= I
.Name() + string(" (") + Cache
[I
].CurVersion
+ string(", ") + Cache
[I
].CandVersion
+ string("), ");
626 else if (Cache
[I
].Delete())
628 if ((Cache
[I
].iFlags
& pkgDepCache::Purge
) == pkgDepCache::Purge
)
629 purge
+= I
.Name() + string(" (") + Cache
[I
].CurVersion
+ string("), ");
631 remove
+= I
.Name() + string(" (") + Cache
[I
].CurVersion
+ string("), ");
634 if (_config
->Exists("Commandline::AsString") == true)
635 WriteHistoryTag("Commandline", _config
->Find("Commandline::AsString"));
636 WriteHistoryTag("Install", install
);
637 WriteHistoryTag("Upgrade", upgrade
);
638 WriteHistoryTag("Downgrade",downgrade
);
639 WriteHistoryTag("Remove",remove
);
640 WriteHistoryTag("Purge",purge
);
647 // DPkg::CloseLog /*{{{*/
648 bool pkgDPkgPM::CloseLog()
651 time_t t
= time(NULL
);
652 struct tm
*tmp
= localtime(&t
);
653 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
657 fprintf(term_out
, "Log ended: ");
658 fprintf(term_out
, "%s", timestr
);
659 fprintf(term_out
, "\n");
666 if (dpkg_error
.size() > 0)
667 fprintf(history_out
, "Error: %s\n", dpkg_error
.c_str());
668 fprintf(history_out
, "End-Date: %s\n", timestr
);
677 // This implements a racy version of pselect for those architectures
678 // that don't have a working implementation.
679 // FIXME: Probably can be removed on Lenny+1
680 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
681 fd_set
*exceptfds
, const struct timespec
*timeout
,
682 const sigset_t
*sigmask
)
688 tv
.tv_sec
= timeout
->tv_sec
;
689 tv
.tv_usec
= timeout
->tv_nsec
/1000;
691 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
692 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
693 sigprocmask(SIG_SETMASK
, &origmask
, 0);
697 // DPkgPM::Go - Run the sequence /*{{{*/
698 // ---------------------------------------------------------------------
699 /* This globs the operations and calls dpkg
701 * If it is called with "OutStatusFd" set to a valid file descriptor
702 * apt will report the install progress over this fd. It maps the
703 * dpkg states a package goes through to human readable (and i10n-able)
704 * names and calculates a percentage for each step.
706 bool pkgDPkgPM::Go(int OutStatusFd
)
711 sigset_t original_sigmask
;
713 unsigned int const MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
714 unsigned int const MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
715 bool const NoTriggers
= _config
->FindB("DPkg::NoTriggers", false);
717 if (RunScripts("DPkg::Pre-Invoke") == false)
720 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
723 // support subpressing of triggers processing for special
724 // cases like d-i that runs the triggers handling manually
725 bool const SmartConf
= (_config
->Find("PackageManager::Configure", "all") != "all");
726 bool const TriggersPending
= _config
->FindB("DPkg::TriggersPending", false);
727 if (_config
->FindB("DPkg::ConfigurePending", SmartConf
) == true)
728 List
.push_back(Item(Item::ConfigurePending
, PkgIterator()));
730 // map the dpkg states to the operations that are performed
731 // (this is sorted in the same way as Item::Ops)
732 static const struct DpkgState DpkgStatesOpMap
[][7] = {
735 {"half-installed", N_("Preparing %s")},
736 {"unpacked", N_("Unpacking %s") },
739 // Configure operation
741 {"unpacked",N_("Preparing to configure %s") },
742 {"half-configured", N_("Configuring %s") },
743 { "installed", N_("Installed %s")},
748 {"half-configured", N_("Preparing for removal of %s")},
749 {"half-installed", N_("Removing %s")},
750 {"config-files", N_("Removed %s")},
755 {"config-files", N_("Preparing to completely remove %s")},
756 {"not-installed", N_("Completely removed %s")},
761 // init the PackageOps map, go over the list of packages that
762 // that will be [installed|configured|removed|purged] and add
763 // them to the PackageOps map (the dpkg states it goes through)
764 // and the PackageOpsTranslations (human readable strings)
765 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();I
++)
767 if((*I
).Pkg
.end() == true)
770 string
const name
= (*I
).Pkg
.Name();
771 PackageOpsDone
[name
] = 0;
772 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; i
++)
774 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
779 stdin_is_dev_null
= false;
784 // this loop is runs once per operation
785 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();)
787 // Do all actions with the same Op in one run
788 vector
<Item
>::const_iterator J
= I
;
789 if (TriggersPending
== true)
790 for (; J
!= List
.end(); J
++)
794 if (J
->Op
!= Item::TriggersPending
)
796 vector
<Item
>::const_iterator T
= J
+ 1;
797 if (T
!= List
.end() && T
->Op
== I
->Op
)
802 for (; J
!= List
.end() && J
->Op
== I
->Op
; J
++)
805 // Generate the argument list
806 const char *Args
[MaxArgs
+ 50];
808 // Now check if we are within the MaxArgs limit
810 // this code below is problematic, because it may happen that
811 // the argument list is split in a way that A depends on B
812 // and they are in the same "--configure A B" run
813 // - with the split they may now be configured in different
815 if (J
- I
> (signed)MaxArgs
)
819 unsigned long Size
= 0;
820 string
const Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
821 Args
[n
++] = Tmp
.c_str();
822 Size
+= strlen(Args
[n
-1]);
824 // Stick in any custom dpkg options
825 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
829 for (; Opts
!= 0; Opts
= Opts
->Next
)
831 if (Opts
->Value
.empty() == true)
833 Args
[n
++] = Opts
->Value
.c_str();
834 Size
+= Opts
->Value
.length();
838 char status_fd_buf
[20];
842 Args
[n
++] = "--status-fd";
843 Size
+= strlen(Args
[n
-1]);
844 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
845 Args
[n
++] = status_fd_buf
;
846 Size
+= strlen(Args
[n
-1]);
851 Args
[n
++] = "--force-depends";
852 Size
+= strlen(Args
[n
-1]);
853 Args
[n
++] = "--force-remove-essential";
854 Size
+= strlen(Args
[n
-1]);
855 Args
[n
++] = "--remove";
856 Size
+= strlen(Args
[n
-1]);
860 Args
[n
++] = "--force-depends";
861 Size
+= strlen(Args
[n
-1]);
862 Args
[n
++] = "--force-remove-essential";
863 Size
+= strlen(Args
[n
-1]);
864 Args
[n
++] = "--purge";
865 Size
+= strlen(Args
[n
-1]);
868 case Item::Configure
:
869 Args
[n
++] = "--configure";
870 Size
+= strlen(Args
[n
-1]);
873 case Item::ConfigurePending
:
874 Args
[n
++] = "--configure";
875 Size
+= strlen(Args
[n
-1]);
876 Args
[n
++] = "--pending";
877 Size
+= strlen(Args
[n
-1]);
880 case Item::TriggersPending
:
881 Args
[n
++] = "--triggers-only";
882 Size
+= strlen(Args
[n
-1]);
883 Args
[n
++] = "--pending";
884 Size
+= strlen(Args
[n
-1]);
888 Args
[n
++] = "--unpack";
889 Size
+= strlen(Args
[n
-1]);
890 Args
[n
++] = "--auto-deconfigure";
891 Size
+= strlen(Args
[n
-1]);
895 if (NoTriggers
== true && I
->Op
!= Item::TriggersPending
&&
896 I
->Op
!= Item::ConfigurePending
)
898 Args
[n
++] = "--no-triggers";
899 Size
+= strlen(Args
[n
-1]);
902 // Write in the file or package names
903 if (I
->Op
== Item::Install
)
905 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
907 if (I
->File
[0] != '/')
908 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
909 Args
[n
++] = I
->File
.c_str();
910 Size
+= strlen(Args
[n
-1]);
915 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
917 if((*I
).Pkg
.end() == true)
919 if (I
->Op
== Item::Configure
&& disappearedPkgs
.find(I
->Pkg
.Name()) != disappearedPkgs
.end())
921 Args
[n
++] = I
->Pkg
.Name();
922 Size
+= strlen(Args
[n
-1]);
928 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
930 for (unsigned int k
= 0; k
!= n
; k
++)
931 clog
<< Args
[k
] << ' ';
940 /* Mask off sig int/quit. We do this because dpkg also does when
941 it forks scripts. What happens is that when you hit ctrl-c it sends
942 it to all processes in the group. Since dpkg ignores the signal
943 it doesn't die but we do! So we must also ignore it */
944 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
945 sighandler_t old_SIGINT
= signal(SIGINT
,SIG_IGN
);
947 // ignore SIGHUP as well (debian #463030)
948 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
955 // if tcgetattr does not return zero there was a error
956 // and we do not do any pty magic
957 if (tcgetattr(0, &tt
) == 0)
959 ioctl(0, TIOCGWINSZ
, (char *)&win
);
960 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
962 const char *s
= _("Can not write log, openpty() "
963 "failed (/dev/pts not mounted?)\n");
964 fprintf(stderr
, "%s",s
);
966 fprintf(term_out
, "%s",s
);
972 rtt
.c_lflag
&= ~ECHO
;
974 // block SIGTTOU during tcsetattr to prevent a hang if
975 // the process is a member of the background process group
976 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
977 sigemptyset(&sigmask
);
978 sigaddset(&sigmask
, SIGTTOU
);
979 sigprocmask(SIG_BLOCK
,&sigmask
, &original_sigmask
);
980 tcsetattr(0, TCSAFLUSH
, &rtt
);
981 sigprocmask(SIG_SETMASK
, &original_sigmask
, 0);
987 _config
->Set("APT::Keep-Fds::",fd
[1]);
988 // send status information that we are about to fork dpkg
989 if(OutStatusFd
> 0) {
990 ostringstream status
;
991 status
<< "pmstatus:dpkg-exec:"
992 << (PackagesDone
/float(PackagesTotal
)*100.0)
993 << ":" << _("Running dpkg")
995 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
1002 if(slave
>= 0 && master
>= 0)
1005 ioctl(slave
, TIOCSCTTY
, 0);
1012 close(fd
[0]); // close the read end of the pipe
1014 if (_config
->FindDir("DPkg::Chroot-Directory","/") != "/")
1016 std::cerr
<< "Chrooting into "
1017 << _config
->FindDir("DPkg::Chroot-Directory")
1019 if (chroot(_config
->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
1023 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
1026 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
1029 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
1032 // Discard everything in stdin before forking dpkg
1033 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
1036 while (read(STDIN_FILENO
,&dummy
,1) == 1);
1038 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
1042 /* No Job Control Stop Env is a magic dpkg var that prevents it
1043 from using sigstop */
1044 putenv((char *)"DPKG_NO_TSTP=yes");
1045 execvp(Args
[0],(char **)Args
);
1046 cerr
<< "Could not exec dpkg!" << endl
;
1051 if (_config
->FindB("DPkg::UseIoNice", false) == true)
1054 // clear the Keep-Fd again
1055 _config
->Clear("APT::Keep-Fds",fd
[1]);
1060 // we read from dpkg here
1061 int const _dpkgin
= fd
[0];
1062 close(fd
[1]); // close the write end of the pipe
1068 sigemptyset(&sigmask
);
1069 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
1071 // the result of the waitpid call
1074 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
1076 // FIXME: move this to a function or something, looks ugly here
1077 // error handling, waitpid returned -1
1080 RunScripts("DPkg::Post-Invoke");
1082 // Restore sig int/quit
1083 signal(SIGQUIT
,old_SIGQUIT
);
1084 signal(SIGINT
,old_SIGINT
);
1085 signal(SIGHUP
,old_SIGHUP
);
1086 return _error
->Errno("waitpid","Couldn't wait for subprocess");
1089 // wait for input or output here
1091 if (master
>= 0 && !stdin_is_dev_null
)
1093 FD_SET(_dpkgin
, &rfds
);
1095 FD_SET(master
, &rfds
);
1098 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
1099 &tv
, &original_sigmask
);
1100 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
1101 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
1102 NULL
, &tv
, &original_sigmask
);
1103 if (select_ret
== 0)
1105 else if (select_ret
< 0 && errno
== EINTR
)
1107 else if (select_ret
< 0)
1109 perror("select() returned error");
1113 if(master
>= 0 && FD_ISSET(master
, &rfds
))
1114 DoTerminalPty(master
);
1115 if(master
>= 0 && FD_ISSET(0, &rfds
))
1117 if(FD_ISSET(_dpkgin
, &rfds
))
1118 DoDpkgStatusFd(_dpkgin
, OutStatusFd
);
1122 // Restore sig int/quit
1123 signal(SIGQUIT
,old_SIGQUIT
);
1124 signal(SIGINT
,old_SIGINT
);
1125 signal(SIGHUP
,old_SIGHUP
);
1129 tcsetattr(0, TCSAFLUSH
, &tt
);
1133 // Check for an error code.
1134 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
1136 // if it was set to "keep-dpkg-runing" then we won't return
1137 // here but keep the loop going and just report it as a error
1139 bool const stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
1142 RunScripts("DPkg::Post-Invoke");
1144 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
1145 strprintf(dpkg_error
, "Sub-process %s received a segmentation fault.",Args
[0]);
1146 else if (WIFEXITED(Status
) != 0)
1147 strprintf(dpkg_error
, "Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
1149 strprintf(dpkg_error
, "Sub-process %s exited unexpectedly",Args
[0]);
1151 if(dpkg_error
.size() > 0)
1152 _error
->Error(dpkg_error
.c_str());
1163 if (RunScripts("DPkg::Post-Invoke") == false)
1166 Cache
.writeStateFile(NULL
);
1170 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1171 // ---------------------------------------------------------------------
1173 void pkgDPkgPM::Reset()
1175 List
.erase(List
.begin(),List
.end());