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("trigproc", N_("Running post-installation trigger %s"))
56 const std::pair
<const char *, const char *> * const PackageProcessingOpsBegin
= PackageProcessingOps
;
57 const std::pair
<const char *, const char *> * const PackageProcessingOpsEnd
= PackageProcessingOps
+ sizeof(PackageProcessingOps
) / sizeof(PackageProcessingOps
[0]);
59 // Predicate to test whether an entry in the PackageProcessingOps
60 // array matches a string.
61 class MatchProcessingOp
66 MatchProcessingOp(const char *the_target
)
71 bool operator()(const std::pair
<const char *, const char *> &pair
) const
73 return strcmp(pair
.first
, target
) == 0;
78 /* helper function to ionice the given PID
80 there is no C header for ionice yet - just the syscall interface
81 so we use the binary from util-linux
86 if (!FileExists("/usr/bin/ionice"))
88 pid_t Process
= ExecFork();
92 snprintf(buf
, sizeof(buf
), "-p%d", PID
);
94 Args
[0] = "/usr/bin/ionice";
98 execv(Args
[0], (char **)Args
);
100 return ExecWait(Process
, "ionice");
103 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
104 // ---------------------------------------------------------------------
106 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
107 : pkgPackageManager(Cache
), dpkgbuf_pos(0),
108 term_out(NULL
), history_out(NULL
), PackagesDone(0), PackagesTotal(0)
112 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
113 // ---------------------------------------------------------------------
115 pkgDPkgPM::~pkgDPkgPM()
119 // DPkgPM::Install - Install a package /*{{{*/
120 // ---------------------------------------------------------------------
121 /* Add an install operation to the sequence list */
122 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
124 if (File
.empty() == true || Pkg
.end() == true)
125 return _error
->Error("Internal Error, No file name for %s",Pkg
.Name());
127 // If the filename string begins with DPkg::Chroot-Directory, return the
128 // substr that is within the chroot so dpkg can access it.
129 string
const chrootdir
= _config
->FindDir("DPkg::Chroot-Directory","/");
130 if (chrootdir
!= "/" && File
.find(chrootdir
) == 0)
132 size_t len
= chrootdir
.length();
133 if (chrootdir
.at(len
- 1) == '/')
135 List
.push_back(Item(Item::Install
,Pkg
,File
.substr(len
)));
138 List
.push_back(Item(Item::Install
,Pkg
,File
));
143 // DPkgPM::Configure - Configure a package /*{{{*/
144 // ---------------------------------------------------------------------
145 /* Add a configure operation to the sequence list */
146 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
148 if (Pkg
.end() == true)
151 List
.push_back(Item(Item::Configure
, Pkg
));
153 // Use triggers for config calls if we configure "smart"
154 // as otherwise Pre-Depends will not be satisfied, see #526774
155 if (_config
->FindB("DPkg::TriggersPending", false) == true)
156 List
.push_back(Item(Item::TriggersPending
, PkgIterator()));
161 // DPkgPM::Remove - Remove a package /*{{{*/
162 // ---------------------------------------------------------------------
163 /* Add a remove operation to the sequence list */
164 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
166 if (Pkg
.end() == true)
170 List
.push_back(Item(Item::Purge
,Pkg
));
172 List
.push_back(Item(Item::Remove
,Pkg
));
176 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
177 // ---------------------------------------------------------------------
178 /* This is part of the helper script communication interface, it sends
179 very complete information down to the other end of the pipe.*/
180 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
182 fprintf(F
,"VERSION 2\n");
184 /* Write out all of the configuration directives by walking the
185 configuration tree */
186 const Configuration::Item
*Top
= _config
->Tree(0);
189 if (Top
->Value
.empty() == false)
192 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
193 QuoteString(Top
->Value
,"\n").c_str());
202 while (Top
!= 0 && Top
->Next
== 0)
209 // Write out the package actions in order.
210 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
212 if(I
->Pkg
.end() == true)
215 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
217 fprintf(F
,"%s ",I
->Pkg
.Name());
219 if (I
->Pkg
->CurrentVer
== 0)
222 fprintf(F
,"%s ",I
->Pkg
.CurrentVer().VerStr());
224 // Show the compare operator
226 if (S
.InstallVer
!= 0)
229 if (I
->Pkg
->CurrentVer
!= 0)
230 Comp
= S
.InstVerIter(Cache
).CompareVer(I
->Pkg
.CurrentVer());
237 fprintf(F
,"%s ",S
.InstVerIter(Cache
).VerStr());
242 // Show the filename/operation
243 if (I
->Op
== Item::Install
)
246 if (I
->File
[0] != '/')
247 fprintf(F
,"**ERROR**\n");
249 fprintf(F
,"%s\n",I
->File
.c_str());
251 if (I
->Op
== Item::Configure
)
252 fprintf(F
,"**CONFIGURE**\n");
253 if (I
->Op
== Item::Remove
||
254 I
->Op
== Item::Purge
)
255 fprintf(F
,"**REMOVE**\n");
263 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
264 // ---------------------------------------------------------------------
265 /* This looks for a list of scripts to run from the configuration file
266 each one is run and is fed on standard input a list of all .deb files
267 that are due to be installed. */
268 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
270 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
271 if (Opts
== 0 || Opts
->Child
== 0)
275 unsigned int Count
= 1;
276 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
278 if (Opts
->Value
.empty() == true)
281 // Determine the protocol version
282 string OptSec
= Opts
->Value
;
283 string::size_type Pos
;
284 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
285 Pos
= OptSec
.length();
286 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
288 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
292 if (pipe(Pipes
) != 0)
293 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
294 SetCloseExec(Pipes
[0],true);
295 SetCloseExec(Pipes
[1],true);
297 // Purified Fork for running the script
298 pid_t Process
= ExecFork();
302 dup2(Pipes
[0],STDIN_FILENO
);
303 SetCloseExec(STDOUT_FILENO
,false);
304 SetCloseExec(STDIN_FILENO
,false);
305 SetCloseExec(STDERR_FILENO
,false);
310 Args
[2] = Opts
->Value
.c_str();
312 execv(Args
[0],(char **)Args
);
316 FILE *F
= fdopen(Pipes
[1],"w");
318 return _error
->Errno("fdopen","Faild to open new FD");
320 // Feed it the filenames.
324 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
326 // Only deal with packages to be installed from .deb
327 if (I
->Op
!= Item::Install
)
331 if (I
->File
[0] != '/')
334 /* Feed the filename of each package that is pending install
336 fprintf(F
,"%s\n",I
->File
.c_str());
345 Die
= !SendV2Pkgs(F
);
349 // Clean up the sub process
350 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
351 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
358 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
359 // ---------------------------------------------------------------------
362 void pkgDPkgPM::DoStdin(int master
)
364 unsigned char input_buf
[256] = {0,};
365 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
367 write(master
, input_buf
, len
);
369 stdin_is_dev_null
= true;
372 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
373 // ---------------------------------------------------------------------
375 * read the terminal pty and write log
377 void pkgDPkgPM::DoTerminalPty(int master
)
379 unsigned char term_buf
[1024] = {0,0, };
381 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
382 if(len
== -1 && errno
== EIO
)
384 // this happens when the child is about to exit, we
385 // give it time to actually exit, otherwise we run
392 write(1, term_buf
, len
);
394 fwrite(term_buf
, len
, sizeof(char), term_out
);
397 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
398 // ---------------------------------------------------------------------
401 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd
, char *line
)
403 bool const Debug
= _config
->FindB("Debug::pkgDPkgProgressReporting",false);
404 // the status we output
405 ostringstream status
;
408 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
411 /* dpkg sends strings like this:
412 'status: <pkg>: <pkg qstate>'
413 errors look like this:
414 '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
415 and conffile-prompt like this
416 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
418 Newer versions of dpkg sent also:
419 'processing: install: pkg'
420 'processing: configure: pkg'
421 'processing: remove: pkg'
422 'processing: purge: pkg' - but for apt is it a ignored "unknown" action
423 'processing: trigproc: trigger'
427 // dpkg sends multiline error messages sometimes (see
428 // #374195 for a example. we should support this by
429 // either patching dpkg to not send multiline over the
430 // statusfd or by rewriting the code here to deal with
431 // it. for now we just ignore it and not crash
432 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
433 if( list
[0] == NULL
|| list
[1] == NULL
|| list
[2] == NULL
)
436 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
439 const char* const pkg
= list
[1];
440 const char* action
= _strstrip(list
[2]);
442 // 'processing' from dpkg looks like
443 // 'processing: action: pkg'
444 if(strncmp(list
[0], "processing", strlen("processing")) == 0)
447 const char* const pkg_or_trigger
= _strstrip(list
[2]);
448 action
= _strstrip( list
[1]);
449 const std::pair
<const char *, const char *> * const iter
=
450 std::find_if(PackageProcessingOpsBegin
,
451 PackageProcessingOpsEnd
,
452 MatchProcessingOp(action
));
453 if(iter
== PackageProcessingOpsEnd
)
456 std::clog
<< "ignoring unknown action: " << action
<< std::endl
;
459 snprintf(s
, sizeof(s
), _(iter
->second
), pkg_or_trigger
);
461 status
<< "pmstatus:" << pkg_or_trigger
462 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
466 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
468 std::clog
<< "send: '" << status
.str() << "'" << endl
;
472 if(strncmp(action
,"error",strlen("error")) == 0)
474 status
<< "pmerror:" << list
[1]
475 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
479 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
481 std::clog
<< "send: '" << status
.str() << "'" << endl
;
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(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 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 if (_config
->Exists("Commandline::AsString") == true)
630 WriteHistoryTag("Commandline", _config
->Find("Commandline::AsString"));
631 WriteHistoryTag("Install", install
);
632 WriteHistoryTag("Upgrade", upgrade
);
633 WriteHistoryTag("Downgrade",downgrade
);
634 WriteHistoryTag("Remove",remove
);
635 WriteHistoryTag("Purge",purge
);
642 // DPkg::CloseLog /*{{{*/
643 bool pkgDPkgPM::CloseLog()
646 time_t t
= time(NULL
);
647 struct tm
*tmp
= localtime(&t
);
648 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
652 fprintf(term_out
, "Log ended: ");
653 fprintf(term_out
, "%s", timestr
);
654 fprintf(term_out
, "\n");
661 if (dpkg_error
.size() > 0)
662 fprintf(history_out
, "Error: %s\n", dpkg_error
.c_str());
663 fprintf(history_out
, "End-Date: %s\n", timestr
);
672 // This implements a racy version of pselect for those architectures
673 // that don't have a working implementation.
674 // FIXME: Probably can be removed on Lenny+1
675 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
676 fd_set
*exceptfds
, const struct timespec
*timeout
,
677 const sigset_t
*sigmask
)
683 tv
.tv_sec
= timeout
->tv_sec
;
684 tv
.tv_usec
= timeout
->tv_nsec
/1000;
686 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
687 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
688 sigprocmask(SIG_SETMASK
, &origmask
, 0);
692 // DPkgPM::Go - Run the sequence /*{{{*/
693 // ---------------------------------------------------------------------
694 /* This globs the operations and calls dpkg
696 * If it is called with "OutStatusFd" set to a valid file descriptor
697 * apt will report the install progress over this fd. It maps the
698 * dpkg states a package goes through to human readable (and i10n-able)
699 * names and calculates a percentage for each step.
701 bool pkgDPkgPM::Go(int OutStatusFd
)
706 sigset_t original_sigmask
;
708 unsigned int const MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
709 unsigned int const MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
710 bool const NoTriggers
= _config
->FindB("DPkg::NoTriggers", false);
712 if (RunScripts("DPkg::Pre-Invoke") == false)
715 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
718 // support subpressing of triggers processing for special
719 // cases like d-i that runs the triggers handling manually
720 bool const SmartConf
= (_config
->Find("PackageManager::Configure", "all") != "all");
721 bool const TriggersPending
= _config
->FindB("DPkg::TriggersPending", false);
722 if (_config
->FindB("DPkg::ConfigurePending", SmartConf
) == true)
723 List
.push_back(Item(Item::ConfigurePending
, PkgIterator()));
725 // map the dpkg states to the operations that are performed
726 // (this is sorted in the same way as Item::Ops)
727 static const struct DpkgState DpkgStatesOpMap
[][7] = {
730 {"half-installed", N_("Preparing %s")},
731 {"unpacked", N_("Unpacking %s") },
734 // Configure operation
736 {"unpacked",N_("Preparing to configure %s") },
737 {"half-configured", N_("Configuring %s") },
738 { "installed", N_("Installed %s")},
743 {"half-configured", N_("Preparing for removal of %s")},
744 {"half-installed", N_("Removing %s")},
745 {"config-files", N_("Removed %s")},
750 {"config-files", N_("Preparing to completely remove %s")},
751 {"not-installed", N_("Completely removed %s")},
756 // init the PackageOps map, go over the list of packages that
757 // that will be [installed|configured|removed|purged] and add
758 // them to the PackageOps map (the dpkg states it goes through)
759 // and the PackageOpsTranslations (human readable strings)
760 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();I
++)
762 if((*I
).Pkg
.end() == true)
765 string
const name
= (*I
).Pkg
.Name();
766 PackageOpsDone
[name
] = 0;
767 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; i
++)
769 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
774 stdin_is_dev_null
= false;
779 // this loop is runs once per operation
780 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();)
782 // Do all actions with the same Op in one run
783 vector
<Item
>::const_iterator J
= I
;
784 if (TriggersPending
== true)
785 for (; J
!= List
.end(); J
++)
789 if (J
->Op
!= Item::TriggersPending
)
791 vector
<Item
>::const_iterator T
= J
+ 1;
792 if (T
!= List
.end() && T
->Op
== I
->Op
)
797 for (; J
!= List
.end() && J
->Op
== I
->Op
; J
++)
800 // Generate the argument list
801 const char *Args
[MaxArgs
+ 50];
803 // Now check if we are within the MaxArgs limit
805 // this code below is problematic, because it may happen that
806 // the argument list is split in a way that A depends on B
807 // and they are in the same "--configure A B" run
808 // - with the split they may now be configured in different
810 if (J
- I
> (signed)MaxArgs
)
814 unsigned long Size
= 0;
815 string
const Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
816 Args
[n
++] = Tmp
.c_str();
817 Size
+= strlen(Args
[n
-1]);
819 // Stick in any custom dpkg options
820 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
824 for (; Opts
!= 0; Opts
= Opts
->Next
)
826 if (Opts
->Value
.empty() == true)
828 Args
[n
++] = Opts
->Value
.c_str();
829 Size
+= Opts
->Value
.length();
833 char status_fd_buf
[20];
837 Args
[n
++] = "--status-fd";
838 Size
+= strlen(Args
[n
-1]);
839 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
840 Args
[n
++] = status_fd_buf
;
841 Size
+= strlen(Args
[n
-1]);
846 Args
[n
++] = "--force-depends";
847 Size
+= strlen(Args
[n
-1]);
848 Args
[n
++] = "--force-remove-essential";
849 Size
+= strlen(Args
[n
-1]);
850 Args
[n
++] = "--remove";
851 Size
+= strlen(Args
[n
-1]);
855 Args
[n
++] = "--force-depends";
856 Size
+= strlen(Args
[n
-1]);
857 Args
[n
++] = "--force-remove-essential";
858 Size
+= strlen(Args
[n
-1]);
859 Args
[n
++] = "--purge";
860 Size
+= strlen(Args
[n
-1]);
863 case Item::Configure
:
864 Args
[n
++] = "--configure";
865 Size
+= strlen(Args
[n
-1]);
868 case Item::ConfigurePending
:
869 Args
[n
++] = "--configure";
870 Size
+= strlen(Args
[n
-1]);
871 Args
[n
++] = "--pending";
872 Size
+= strlen(Args
[n
-1]);
875 case Item::TriggersPending
:
876 Args
[n
++] = "--triggers-only";
877 Size
+= strlen(Args
[n
-1]);
878 Args
[n
++] = "--pending";
879 Size
+= strlen(Args
[n
-1]);
883 Args
[n
++] = "--unpack";
884 Size
+= strlen(Args
[n
-1]);
885 Args
[n
++] = "--auto-deconfigure";
886 Size
+= strlen(Args
[n
-1]);
890 if (NoTriggers
== true && I
->Op
!= Item::TriggersPending
&&
891 I
->Op
!= Item::ConfigurePending
)
893 Args
[n
++] = "--no-triggers";
894 Size
+= strlen(Args
[n
-1]);
897 // Write in the file or package names
898 if (I
->Op
== Item::Install
)
900 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
902 if (I
->File
[0] != '/')
903 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
904 Args
[n
++] = I
->File
.c_str();
905 Size
+= strlen(Args
[n
-1]);
910 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
912 if((*I
).Pkg
.end() == true)
914 Args
[n
++] = I
->Pkg
.Name();
915 Size
+= strlen(Args
[n
-1]);
921 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
923 for (unsigned int k
= 0; k
!= n
; k
++)
924 clog
<< Args
[k
] << ' ';
933 /* Mask off sig int/quit. We do this because dpkg also does when
934 it forks scripts. What happens is that when you hit ctrl-c it sends
935 it to all processes in the group. Since dpkg ignores the signal
936 it doesn't die but we do! So we must also ignore it */
937 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
938 sighandler_t old_SIGINT
= signal(SIGINT
,SIG_IGN
);
940 // ignore SIGHUP as well (debian #463030)
941 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
948 // if tcgetattr does not return zero there was a error
949 // and we do not do any pty magic
950 if (tcgetattr(0, &tt
) == 0)
952 ioctl(0, TIOCGWINSZ
, (char *)&win
);
953 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
955 const char *s
= _("Can not write log, openpty() "
956 "failed (/dev/pts not mounted?)\n");
957 fprintf(stderr
, "%s",s
);
959 fprintf(term_out
, "%s",s
);
965 rtt
.c_lflag
&= ~ECHO
;
967 // block SIGTTOU during tcsetattr to prevent a hang if
968 // the process is a member of the background process group
969 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
970 sigemptyset(&sigmask
);
971 sigaddset(&sigmask
, SIGTTOU
);
972 sigprocmask(SIG_BLOCK
,&sigmask
, &original_sigmask
);
973 tcsetattr(0, TCSAFLUSH
, &rtt
);
974 sigprocmask(SIG_SETMASK
, &original_sigmask
, 0);
980 _config
->Set("APT::Keep-Fds::",fd
[1]);
981 // send status information that we are about to fork dpkg
982 if(OutStatusFd
> 0) {
983 ostringstream status
;
984 status
<< "pmstatus:dpkg-exec:"
985 << (PackagesDone
/float(PackagesTotal
)*100.0)
986 << ":" << _("Running dpkg")
988 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
995 if(slave
>= 0 && master
>= 0)
998 ioctl(slave
, TIOCSCTTY
, 0);
1005 close(fd
[0]); // close the read end of the pipe
1007 if (_config
->FindDir("DPkg::Chroot-Directory","/") != "/")
1009 std::cerr
<< "Chrooting into "
1010 << _config
->FindDir("DPkg::Chroot-Directory")
1012 if (chroot(_config
->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
1016 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
1019 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
1022 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
1025 // Discard everything in stdin before forking dpkg
1026 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
1029 while (read(STDIN_FILENO
,&dummy
,1) == 1);
1031 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
1035 /* No Job Control Stop Env is a magic dpkg var that prevents it
1036 from using sigstop */
1037 putenv((char *)"DPKG_NO_TSTP=yes");
1038 execvp(Args
[0],(char **)Args
);
1039 cerr
<< "Could not exec dpkg!" << endl
;
1044 if (_config
->FindB("DPkg::UseIoNice", false) == true)
1047 // clear the Keep-Fd again
1048 _config
->Clear("APT::Keep-Fds",fd
[1]);
1053 // we read from dpkg here
1054 int const _dpkgin
= fd
[0];
1055 close(fd
[1]); // close the write end of the pipe
1061 sigemptyset(&sigmask
);
1062 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
1064 // the result of the waitpid call
1067 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
1069 // FIXME: move this to a function or something, looks ugly here
1070 // error handling, waitpid returned -1
1073 RunScripts("DPkg::Post-Invoke");
1075 // Restore sig int/quit
1076 signal(SIGQUIT
,old_SIGQUIT
);
1077 signal(SIGINT
,old_SIGINT
);
1078 signal(SIGHUP
,old_SIGHUP
);
1079 return _error
->Errno("waitpid","Couldn't wait for subprocess");
1082 // wait for input or output here
1084 if (master
>= 0 && !stdin_is_dev_null
)
1086 FD_SET(_dpkgin
, &rfds
);
1088 FD_SET(master
, &rfds
);
1091 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
1092 &tv
, &original_sigmask
);
1093 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
1094 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
1095 NULL
, &tv
, &original_sigmask
);
1096 if (select_ret
== 0)
1098 else if (select_ret
< 0 && errno
== EINTR
)
1100 else if (select_ret
< 0)
1102 perror("select() returned error");
1106 if(master
>= 0 && FD_ISSET(master
, &rfds
))
1107 DoTerminalPty(master
);
1108 if(master
>= 0 && FD_ISSET(0, &rfds
))
1110 if(FD_ISSET(_dpkgin
, &rfds
))
1111 DoDpkgStatusFd(_dpkgin
, OutStatusFd
);
1115 // Restore sig int/quit
1116 signal(SIGQUIT
,old_SIGQUIT
);
1117 signal(SIGINT
,old_SIGINT
);
1118 signal(SIGHUP
,old_SIGHUP
);
1122 tcsetattr(0, TCSAFLUSH
, &tt
);
1126 // Check for an error code.
1127 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
1129 // if it was set to "keep-dpkg-runing" then we won't return
1130 // here but keep the loop going and just report it as a error
1132 bool const stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
1135 RunScripts("DPkg::Post-Invoke");
1137 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
1138 strprintf(dpkg_error
, "Sub-process %s received a segmentation fault.",Args
[0]);
1139 else if (WIFEXITED(Status
) != 0)
1140 strprintf(dpkg_error
, "Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
1142 strprintf(dpkg_error
, "Sub-process %s exited unexpectedly",Args
[0]);
1144 if(dpkg_error
.size() > 0)
1145 _error
->Error(dpkg_error
.c_str());
1156 if (RunScripts("DPkg::Post-Invoke") == false)
1159 Cache
.writeStateFile(NULL
);
1163 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1164 // ---------------------------------------------------------------------
1166 void pkgDPkgPM::Reset()
1168 List
.erase(List
.begin(),List
.end());