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("trigproc", N_("Running post-installation trigger %s"))
55 const std::pair
<const char *, const char *> * const PackageProcessingOpsBegin
= PackageProcessingOps
;
56 const std::pair
<const char *, const char *> * const PackageProcessingOpsEnd
= PackageProcessingOps
+ sizeof(PackageProcessingOps
) / sizeof(PackageProcessingOps
[0]);
58 // Predicate to test whether an entry in the PackageProcessingOps
59 // array matches a string.
60 class MatchProcessingOp
65 MatchProcessingOp(const char *the_target
)
70 bool operator()(const std::pair
<const char *, const char *> &pair
) const
72 return strcmp(pair
.first
, target
) == 0;
77 /* helper function to ionice the given PID
79 there is no C header for ionice yet - just the syscall interface
80 so we use the binary from util-linux
85 if (!FileExists("/usr/bin/ionice"))
87 pid_t Process
= ExecFork();
91 snprintf(buf
, sizeof(buf
), "-p%d", PID
);
93 Args
[0] = "/usr/bin/ionice";
97 execv(Args
[0], (char **)Args
);
99 return ExecWait(Process
, "ionice");
102 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
103 // ---------------------------------------------------------------------
105 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
106 : pkgPackageManager(Cache
), dpkgbuf_pos(0),
107 term_out(NULL
), PackagesDone(0), PackagesTotal(0)
111 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
112 // ---------------------------------------------------------------------
114 pkgDPkgPM::~pkgDPkgPM()
118 // DPkgPM::Install - Install a package /*{{{*/
119 // ---------------------------------------------------------------------
120 /* Add an install operation to the sequence list */
121 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
123 if (File
.empty() == true || Pkg
.end() == true)
124 return _error
->Error("Internal Error, No file name for %s",Pkg
.Name());
126 List
.push_back(Item(Item::Install
,Pkg
,File
));
130 // DPkgPM::Configure - Configure a package /*{{{*/
131 // ---------------------------------------------------------------------
132 /* Add a configure operation to the sequence list */
133 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
135 if (Pkg
.end() == true)
138 List
.push_back(Item(Item::Configure
,Pkg
));
142 // DPkgPM::Remove - Remove a package /*{{{*/
143 // ---------------------------------------------------------------------
144 /* Add a remove operation to the sequence list */
145 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
147 if (Pkg
.end() == true)
151 List
.push_back(Item(Item::Purge
,Pkg
));
153 List
.push_back(Item(Item::Remove
,Pkg
));
157 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
158 // ---------------------------------------------------------------------
159 /* This is part of the helper script communication interface, it sends
160 very complete information down to the other end of the pipe.*/
161 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
163 fprintf(F
,"VERSION 2\n");
165 /* Write out all of the configuration directives by walking the
166 configuration tree */
167 const Configuration::Item
*Top
= _config
->Tree(0);
170 if (Top
->Value
.empty() == false)
173 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
174 QuoteString(Top
->Value
,"\n").c_str());
183 while (Top
!= 0 && Top
->Next
== 0)
190 // Write out the package actions in order.
191 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
193 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
195 fprintf(F
,"%s ",I
->Pkg
.Name());
197 if (I
->Pkg
->CurrentVer
== 0)
200 fprintf(F
,"%s ",I
->Pkg
.CurrentVer().VerStr());
202 // Show the compare operator
204 if (S
.InstallVer
!= 0)
207 if (I
->Pkg
->CurrentVer
!= 0)
208 Comp
= S
.InstVerIter(Cache
).CompareVer(I
->Pkg
.CurrentVer());
215 fprintf(F
,"%s ",S
.InstVerIter(Cache
).VerStr());
220 // Show the filename/operation
221 if (I
->Op
== Item::Install
)
224 if (I
->File
[0] != '/')
225 fprintf(F
,"**ERROR**\n");
227 fprintf(F
,"%s\n",I
->File
.c_str());
229 if (I
->Op
== Item::Configure
)
230 fprintf(F
,"**CONFIGURE**\n");
231 if (I
->Op
== Item::Remove
||
232 I
->Op
== Item::Purge
)
233 fprintf(F
,"**REMOVE**\n");
241 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
242 // ---------------------------------------------------------------------
243 /* This looks for a list of scripts to run from the configuration file
244 each one is run and is fed on standard input a list of all .deb files
245 that are due to be installed. */
246 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
248 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
249 if (Opts
== 0 || Opts
->Child
== 0)
253 unsigned int Count
= 1;
254 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
256 if (Opts
->Value
.empty() == true)
259 // Determine the protocol version
260 string OptSec
= Opts
->Value
;
261 string::size_type Pos
;
262 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
263 Pos
= OptSec
.length();
264 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
266 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
270 if (pipe(Pipes
) != 0)
271 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
272 SetCloseExec(Pipes
[0],true);
273 SetCloseExec(Pipes
[1],true);
275 // Purified Fork for running the script
276 pid_t Process
= ExecFork();
280 dup2(Pipes
[0],STDIN_FILENO
);
281 SetCloseExec(STDOUT_FILENO
,false);
282 SetCloseExec(STDIN_FILENO
,false);
283 SetCloseExec(STDERR_FILENO
,false);
288 Args
[2] = Opts
->Value
.c_str();
290 execv(Args
[0],(char **)Args
);
294 FILE *F
= fdopen(Pipes
[1],"w");
296 return _error
->Errno("fdopen","Faild to open new FD");
298 // Feed it the filenames.
302 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
304 // Only deal with packages to be installed from .deb
305 if (I
->Op
!= Item::Install
)
309 if (I
->File
[0] != '/')
312 /* Feed the filename of each package that is pending install
314 fprintf(F
,"%s\n",I
->File
.c_str());
323 Die
= !SendV2Pkgs(F
);
327 // Clean up the sub process
328 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
329 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
336 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
337 // ---------------------------------------------------------------------
340 void pkgDPkgPM::DoStdin(int master
)
342 unsigned char input_buf
[256] = {0,};
343 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
345 write(master
, input_buf
, len
);
347 stdin_is_dev_null
= true;
350 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
351 // ---------------------------------------------------------------------
353 * read the terminal pty and write log
355 void pkgDPkgPM::DoTerminalPty(int master
)
357 unsigned char term_buf
[1024] = {0,0, };
359 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
360 if(len
== -1 && errno
== EIO
)
362 // this happens when the child is about to exit, we
363 // give it time to actually exit, otherwise we run
370 write(1, term_buf
, len
);
372 fwrite(term_buf
, len
, sizeof(char), term_out
);
375 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
376 // ---------------------------------------------------------------------
379 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd
, char *line
)
381 // the status we output
382 ostringstream status
;
384 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
385 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
388 /* dpkg sends strings like this:
389 'status: <pkg>: <pkg qstate>'
390 errors look like this:
391 '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
392 and conffile-prompt like this
393 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
395 Newer versions of dpkg sent also:
396 'processing: install: pkg'
397 'processing: configure: pkg'
398 'processing: remove: pkg'
399 'processing: trigproc: trigger'
403 // dpkg sends multiline error messages sometimes (see
404 // #374195 for a example. we should support this by
405 // either patching dpkg to not send multiline over the
406 // statusfd or by rewriting the code here to deal with
407 // it. for now we just ignore it and not crash
408 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
409 if( list
[0] == NULL
|| list
[1] == NULL
|| list
[2] == NULL
)
411 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
412 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
416 char *action
= _strstrip(list
[2]);
418 // 'processing' from dpkg looks like
419 // 'processing: action: pkg'
420 if(strncmp(list
[0], "processing", strlen("processing")) == 0)
423 char *pkg_or_trigger
= _strstrip(list
[2]);
424 action
=_strstrip( list
[1]);
425 const std::pair
<const char *, const char *> * const iter
=
426 std::find_if(PackageProcessingOpsBegin
,
427 PackageProcessingOpsEnd
,
428 MatchProcessingOp(action
));
429 if(iter
== PackageProcessingOpsEnd
)
431 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
432 std::clog
<< "ignoring unknwon action: " << action
<< std::endl
;
435 snprintf(s
, sizeof(s
), _(iter
->second
), pkg_or_trigger
);
437 status
<< "pmstatus:" << pkg_or_trigger
438 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
442 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
443 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
444 std::clog
<< "send: '" << status
.str() << "'" << endl
;
448 if(strncmp(action
,"error",strlen("error")) == 0)
450 status
<< "pmerror:" << list
[1]
451 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
455 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
456 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
457 std::clog
<< "send: '" << status
.str() << "'" << endl
;
460 if(strncmp(action
,"conffile",strlen("conffile")) == 0)
462 status
<< "pmconffile:" << list
[1]
463 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
467 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
468 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
469 std::clog
<< "send: '" << status
.str() << "'" << endl
;
473 vector
<struct DpkgState
> &states
= PackageOps
[pkg
];
474 const char *next_action
= NULL
;
475 if(PackageOpsDone
[pkg
] < states
.size())
476 next_action
= states
[PackageOpsDone
[pkg
]].state
;
477 // check if the package moved to the next dpkg state
478 if(next_action
&& (strcmp(action
, next_action
) == 0))
480 // only read the translation if there is actually a next
482 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
484 snprintf(s
, sizeof(s
), translation
, pkg
);
486 // we moved from one dpkg state to a new one, report that
487 PackageOpsDone
[pkg
]++;
489 // build the status str
490 status
<< "pmstatus:" << pkg
491 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
495 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
496 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
497 std::clog
<< "send: '" << status
.str() << "'" << endl
;
499 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
500 std::clog
<< "(parsed from dpkg) pkg: " << pkg
501 << " action: " << action
<< endl
;
504 // DPkgPM::DoDpkgStatusFd /*{{{*/
505 // ---------------------------------------------------------------------
508 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
, int OutStatusFd
)
513 len
=read(statusfd
, &dpkgbuf
[dpkgbuf_pos
], sizeof(dpkgbuf
)-dpkgbuf_pos
);
518 // process line by line if we have a buffer
520 while((q
=(char*)memchr(p
, '\n', dpkgbuf
+dpkgbuf_pos
-p
)) != NULL
)
523 ProcessDpkgStatusLine(OutStatusFd
, p
);
524 p
=q
+1; // continue with next line
527 // now move the unprocessed bits (after the final \n that is now a 0x0)
528 // to the start and update dpkgbuf_pos
529 p
= (char*)memrchr(dpkgbuf
, 0, dpkgbuf_pos
);
533 // we are interessted in the first char *after* 0x0
536 // move the unprocessed tail to the start and update pos
537 memmove(dpkgbuf
, p
, p
-dpkgbuf
);
538 dpkgbuf_pos
= dpkgbuf
+dpkgbuf_pos
-p
;
542 bool pkgDPkgPM::OpenLog()
544 string logdir
= _config
->FindDir("Dir::Log");
545 if(not FileExists(logdir
))
546 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
547 string logfile_name
= flCombine(logdir
,
548 _config
->Find("Dir::Log::Terminal"));
549 if (!logfile_name
.empty())
551 term_out
= fopen(logfile_name
.c_str(),"a");
552 chmod(logfile_name
.c_str(), 0600);
553 // output current time
555 time_t t
= time(NULL
);
556 struct tm
*tmp
= localtime(&t
);
557 strftime(outstr
, sizeof(outstr
), "%F %T", tmp
);
558 fprintf(term_out
, "\nLog started: ");
559 fprintf(term_out
, "%s", outstr
);
560 fprintf(term_out
, "\n");
565 bool pkgDPkgPM::CloseLog()
570 time_t t
= time(NULL
);
571 struct tm
*tmp
= localtime(&t
);
572 strftime(outstr
, sizeof(outstr
), "%F %T", tmp
);
573 fprintf(term_out
, "Log ended: ");
574 fprintf(term_out
, "%s", outstr
);
575 fprintf(term_out
, "\n");
583 // This implements a racy version of pselect for those architectures
584 // that don't have a working implementation.
585 // FIXME: Probably can be removed on Lenny+1
586 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
587 fd_set
*exceptfds
, const struct timespec
*timeout
,
588 const sigset_t
*sigmask
)
594 tv
.tv_sec
= timeout
->tv_sec
;
595 tv
.tv_usec
= timeout
->tv_nsec
/1000;
597 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
598 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
599 sigprocmask(SIG_SETMASK
, &origmask
, 0);
604 // DPkgPM::Go - Run the sequence /*{{{*/
605 // ---------------------------------------------------------------------
606 /* This globs the operations and calls dpkg
608 * If it is called with "OutStatusFd" set to a valid file descriptor
609 * apt will report the install progress over this fd. It maps the
610 * dpkg states a package goes through to human readable (and i10n-able)
611 * names and calculates a percentage for each step.
613 bool pkgDPkgPM::Go(int OutStatusFd
)
618 sigset_t original_sigmask
;
620 unsigned int MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
621 unsigned int MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
622 bool NoTriggers
= _config
->FindB("DPkg::NoTriggers",false);
624 if (RunScripts("DPkg::Pre-Invoke") == false)
627 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
630 // map the dpkg states to the operations that are performed
631 // (this is sorted in the same way as Item::Ops)
632 static const struct DpkgState DpkgStatesOpMap
[][7] = {
635 {"half-installed", N_("Preparing %s")},
636 {"unpacked", N_("Unpacking %s") },
639 // Configure operation
641 {"unpacked",N_("Preparing to configure %s") },
642 {"half-configured", N_("Configuring %s") },
644 {"triggers-awaited", N_("Processing triggers for %s") },
645 {"triggers-pending", N_("Processing triggers for %s") },
647 { "installed", N_("Installed %s")},
652 {"half-configured", N_("Preparing for removal of %s")},
654 {"triggers-awaited", N_("Preparing for removal of %s")},
655 {"triggers-pending", N_("Preparing for removal of %s")},
657 {"half-installed", N_("Removing %s")},
658 {"config-files", N_("Removed %s")},
663 {"config-files", N_("Preparing to completely remove %s")},
664 {"not-installed", N_("Completely removed %s")},
669 // init the PackageOps map, go over the list of packages that
670 // that will be [installed|configured|removed|purged] and add
671 // them to the PackageOps map (the dpkg states it goes through)
672 // and the PackageOpsTranslations (human readable strings)
673 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end();I
++)
675 string name
= (*I
).Pkg
.Name();
676 PackageOpsDone
[name
] = 0;
677 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; i
++)
679 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
684 stdin_is_dev_null
= false;
689 // this loop is runs once per operation
690 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end();)
692 vector
<Item
>::iterator J
= I
;
693 for (; J
!= List
.end() && J
->Op
== I
->Op
; J
++);
695 // Generate the argument list
696 const char *Args
[MaxArgs
+ 50];
697 if (J
- I
> (signed)MaxArgs
)
701 unsigned long Size
= 0;
702 string Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
703 Args
[n
++] = Tmp
.c_str();
704 Size
+= strlen(Args
[n
-1]);
706 // Stick in any custom dpkg options
707 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
711 for (; Opts
!= 0; Opts
= Opts
->Next
)
713 if (Opts
->Value
.empty() == true)
715 Args
[n
++] = Opts
->Value
.c_str();
716 Size
+= Opts
->Value
.length();
720 char status_fd_buf
[20];
724 Args
[n
++] = "--status-fd";
725 Size
+= strlen(Args
[n
-1]);
726 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
727 Args
[n
++] = status_fd_buf
;
728 Size
+= strlen(Args
[n
-1]);
733 Args
[n
++] = "--force-depends";
734 Size
+= strlen(Args
[n
-1]);
735 Args
[n
++] = "--force-remove-essential";
736 Size
+= strlen(Args
[n
-1]);
737 Args
[n
++] = "--remove";
738 Size
+= strlen(Args
[n
-1]);
742 Args
[n
++] = "--force-depends";
743 Size
+= strlen(Args
[n
-1]);
744 Args
[n
++] = "--force-remove-essential";
745 Size
+= strlen(Args
[n
-1]);
746 Args
[n
++] = "--purge";
747 Size
+= strlen(Args
[n
-1]);
750 case Item::Configure
:
751 Args
[n
++] = "--configure";
753 Args
[n
++] = "--no-triggers";
754 Size
+= strlen(Args
[n
-1]);
758 Args
[n
++] = "--unpack";
759 Size
+= strlen(Args
[n
-1]);
760 Args
[n
++] = "--auto-deconfigure";
761 Size
+= strlen(Args
[n
-1]);
765 // Write in the file or package names
766 if (I
->Op
== Item::Install
)
768 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
770 if (I
->File
[0] != '/')
771 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
772 Args
[n
++] = I
->File
.c_str();
773 Size
+= strlen(Args
[n
-1]);
778 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
780 Args
[n
++] = I
->Pkg
.Name();
781 Size
+= strlen(Args
[n
-1]);
787 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
789 for (unsigned int k
= 0; k
!= n
; k
++)
790 clog
<< Args
[k
] << ' ';
799 /* Mask off sig int/quit. We do this because dpkg also does when
800 it forks scripts. What happens is that when you hit ctrl-c it sends
801 it to all processes in the group. Since dpkg ignores the signal
802 it doesn't die but we do! So we must also ignore it */
803 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
804 sighandler_t old_SIGINT
= signal(SIGINT
,SIG_IGN
);
806 // ignore SIGHUP as well (debian #463030)
807 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
814 // FIXME: setup sensible signal handling (*ick*)
816 ioctl(0, TIOCGWINSZ
, (char *)&win
);
817 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
819 const char *s
= _("Can not write log, openpty() "
820 "failed (/dev/pts not mounted?)\n");
821 fprintf(stderr
, "%s",s
);
822 fprintf(term_out
, "%s",s
);
828 rtt
.c_lflag
&= ~ECHO
;
829 // block SIGTTOU during tcsetattr to prevent a hang if
830 // the process is a member of the background process group
831 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
832 sigemptyset(&sigmask
);
833 sigaddset(&sigmask
, SIGTTOU
);
834 sigprocmask(SIG_BLOCK
,&sigmask
, &original_sigmask
);
835 tcsetattr(0, TCSAFLUSH
, &rtt
);
836 sigprocmask(SIG_SETMASK
, &original_sigmask
, 0);
841 _config
->Set("APT::Keep-Fds::",fd
[1]);
842 // send status information that we are about to fork dpkg
843 if(OutStatusFd
> 0) {
844 ostringstream status
;
845 status
<< "pmstatus:dpkg-exec:"
846 << (PackagesDone
/float(PackagesTotal
)*100.0)
847 << ":" << _("Running dpkg")
849 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
856 if(slave
>= 0 && master
>= 0)
859 ioctl(slave
, TIOCSCTTY
, 0);
866 close(fd
[0]); // close the read end of the pipe
868 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
871 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
874 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
877 // Discard everything in stdin before forking dpkg
878 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
881 while (read(STDIN_FILENO
,&dummy
,1) == 1);
883 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
887 /* No Job Control Stop Env is a magic dpkg var that prevents it
888 from using sigstop */
889 putenv((char *)"DPKG_NO_TSTP=yes");
890 execvp(Args
[0],(char **)Args
);
891 cerr
<< "Could not exec dpkg!" << endl
;
896 if (_config
->FindB("DPkg::UseIoNice", false) == true)
899 // clear the Keep-Fd again
900 _config
->Clear("APT::Keep-Fds",fd
[1]);
905 // we read from dpkg here
907 close(fd
[1]); // close the write end of the pipe
909 // the result of the waitpid call
915 sigemptyset(&sigmask
);
916 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
919 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
921 // FIXME: move this to a function or something, looks ugly here
922 // error handling, waitpid returned -1
925 RunScripts("DPkg::Post-Invoke");
927 // Restore sig int/quit
928 signal(SIGQUIT
,old_SIGQUIT
);
929 signal(SIGINT
,old_SIGINT
);
930 signal(SIGHUP
,old_SIGHUP
);
931 return _error
->Errno("waitpid","Couldn't wait for subprocess");
934 // wait for input or output here
936 if (!stdin_is_dev_null
)
938 FD_SET(_dpkgin
, &rfds
);
940 FD_SET(master
, &rfds
);
943 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
944 &tv
, &original_sigmask
);
945 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
946 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
947 NULL
, &tv
, &original_sigmask
);
950 else if (select_ret
< 0 && errno
== EINTR
)
952 else if (select_ret
< 0)
954 perror("select() returned error");
958 if(master
>= 0 && FD_ISSET(master
, &rfds
))
959 DoTerminalPty(master
);
960 if(master
>= 0 && FD_ISSET(0, &rfds
))
962 if(FD_ISSET(_dpkgin
, &rfds
))
963 DoDpkgStatusFd(_dpkgin
, OutStatusFd
);
967 // Restore sig int/quit
968 signal(SIGQUIT
,old_SIGQUIT
);
969 signal(SIGINT
,old_SIGINT
);
970 signal(SIGHUP
,old_SIGHUP
);
974 tcsetattr(0, TCSAFLUSH
, &tt
);
978 // Check for an error code.
979 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
981 // if it was set to "keep-dpkg-runing" then we won't return
982 // here but keep the loop going and just report it as a error
984 bool stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
987 RunScripts("DPkg::Post-Invoke");
989 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
990 _error
->Error("Sub-process %s received a segmentation fault.",Args
[0]);
991 else if (WIFEXITED(Status
) != 0)
992 _error
->Error("Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
994 _error
->Error("Sub-process %s exited unexpectedly",Args
[0]);
1005 if (RunScripts("DPkg::Post-Invoke") == false)
1008 Cache
.writeStateFile(NULL
);
1012 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1013 // ---------------------------------------------------------------------
1015 void pkgDPkgPM::Reset()
1017 List
.erase(List
.begin(),List
.end());