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
), 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 List
.push_back(Item(Item::Install
,Pkg
,File
));
131 // DPkgPM::Configure - Configure a package /*{{{*/
132 // ---------------------------------------------------------------------
133 /* Add a configure operation to the sequence list */
134 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
136 if (Pkg
.end() == true)
139 List
.push_back(Item(Item::Configure
,Pkg
));
143 // DPkgPM::Remove - Remove a package /*{{{*/
144 // ---------------------------------------------------------------------
145 /* Add a remove operation to the sequence list */
146 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
148 if (Pkg
.end() == true)
152 List
.push_back(Item(Item::Purge
,Pkg
));
154 List
.push_back(Item(Item::Remove
,Pkg
));
158 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
159 // ---------------------------------------------------------------------
160 /* This is part of the helper script communication interface, it sends
161 very complete information down to the other end of the pipe.*/
162 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
164 fprintf(F
,"VERSION 2\n");
166 /* Write out all of the configuration directives by walking the
167 configuration tree */
168 const Configuration::Item
*Top
= _config
->Tree(0);
171 if (Top
->Value
.empty() == false)
174 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
175 QuoteString(Top
->Value
,"\n").c_str());
184 while (Top
!= 0 && Top
->Next
== 0)
191 // Write out the package actions in order.
192 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
194 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
196 fprintf(F
,"%s ",I
->Pkg
.Name());
198 if (I
->Pkg
->CurrentVer
== 0)
201 fprintf(F
,"%s ",I
->Pkg
.CurrentVer().VerStr());
203 // Show the compare operator
205 if (S
.InstallVer
!= 0)
208 if (I
->Pkg
->CurrentVer
!= 0)
209 Comp
= S
.InstVerIter(Cache
).CompareVer(I
->Pkg
.CurrentVer());
216 fprintf(F
,"%s ",S
.InstVerIter(Cache
).VerStr());
221 // Show the filename/operation
222 if (I
->Op
== Item::Install
)
225 if (I
->File
[0] != '/')
226 fprintf(F
,"**ERROR**\n");
228 fprintf(F
,"%s\n",I
->File
.c_str());
230 if (I
->Op
== Item::Configure
)
231 fprintf(F
,"**CONFIGURE**\n");
232 if (I
->Op
== Item::Remove
||
233 I
->Op
== Item::Purge
)
234 fprintf(F
,"**REMOVE**\n");
242 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
243 // ---------------------------------------------------------------------
244 /* This looks for a list of scripts to run from the configuration file
245 each one is run and is fed on standard input a list of all .deb files
246 that are due to be installed. */
247 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
249 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
250 if (Opts
== 0 || Opts
->Child
== 0)
254 unsigned int Count
= 1;
255 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
257 if (Opts
->Value
.empty() == true)
260 // Determine the protocol version
261 string OptSec
= Opts
->Value
;
262 string::size_type Pos
;
263 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
264 Pos
= OptSec
.length();
265 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
267 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
271 if (pipe(Pipes
) != 0)
272 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
273 SetCloseExec(Pipes
[0],true);
274 SetCloseExec(Pipes
[1],true);
276 // Purified Fork for running the script
277 pid_t Process
= ExecFork();
281 dup2(Pipes
[0],STDIN_FILENO
);
282 SetCloseExec(STDOUT_FILENO
,false);
283 SetCloseExec(STDIN_FILENO
,false);
284 SetCloseExec(STDERR_FILENO
,false);
289 Args
[2] = Opts
->Value
.c_str();
291 execv(Args
[0],(char **)Args
);
295 FILE *F
= fdopen(Pipes
[1],"w");
297 return _error
->Errno("fdopen","Faild to open new FD");
299 // Feed it the filenames.
303 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
305 // Only deal with packages to be installed from .deb
306 if (I
->Op
!= Item::Install
)
310 if (I
->File
[0] != '/')
313 /* Feed the filename of each package that is pending install
315 fprintf(F
,"%s\n",I
->File
.c_str());
324 Die
= !SendV2Pkgs(F
);
328 // Clean up the sub process
329 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
330 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
337 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
338 // ---------------------------------------------------------------------
341 void pkgDPkgPM::DoStdin(int master
)
343 unsigned char input_buf
[256] = {0,};
344 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
346 write(master
, input_buf
, len
);
348 stdin_is_dev_null
= true;
351 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
352 // ---------------------------------------------------------------------
354 * read the terminal pty and write log
356 void pkgDPkgPM::DoTerminalPty(int master
)
358 unsigned char term_buf
[1024] = {0,0, };
360 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
361 if(len
== -1 && errno
== EIO
)
363 // this happens when the child is about to exit, we
364 // give it time to actually exit, otherwise we run
371 write(1, term_buf
, len
);
373 fwrite(term_buf
, len
, sizeof(char), term_out
);
376 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
377 // ---------------------------------------------------------------------
380 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd
, char *line
)
382 // the status we output
383 ostringstream status
;
385 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
386 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
389 /* dpkg sends strings like this:
390 'status: <pkg>: <pkg qstate>'
391 errors look like this:
392 '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
393 and conffile-prompt like this
394 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
396 Newer versions of dpkg sent also:
397 'processing: install: pkg'
398 'processing: configure: pkg'
399 'processing: remove: pkg'
400 'processing: trigproc: trigger'
404 // dpkg sends multiline error messages sometimes (see
405 // #374195 for a example. we should support this by
406 // either patching dpkg to not send multiline over the
407 // statusfd or by rewriting the code here to deal with
408 // it. for now we just ignore it and not crash
409 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
410 if( list
[0] == NULL
|| list
[1] == NULL
|| list
[2] == NULL
)
412 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
413 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
417 char *action
= _strstrip(list
[2]);
419 // 'processing' from dpkg looks like
420 // 'processing: action: pkg'
421 if(strncmp(list
[0], "processing", strlen("processing")) == 0)
424 char *pkg_or_trigger
= _strstrip(list
[2]);
425 action
=_strstrip( list
[1]);
426 const std::pair
<const char *, const char *> * const iter
=
427 std::find_if(PackageProcessingOpsBegin
,
428 PackageProcessingOpsEnd
,
429 MatchProcessingOp(action
));
430 if(iter
== PackageProcessingOpsEnd
)
432 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
433 std::clog
<< "ignoring unknwon action: " << action
<< std::endl
;
436 snprintf(s
, sizeof(s
), _(iter
->second
), pkg_or_trigger
);
438 status
<< "pmstatus:" << pkg_or_trigger
439 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
443 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
444 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
445 std::clog
<< "send: '" << status
.str() << "'" << endl
;
449 if(strncmp(action
,"error",strlen("error")) == 0)
451 status
<< "pmerror:" << list
[1]
452 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
456 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
457 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
458 std::clog
<< "send: '" << status
.str() << "'" << endl
;
461 if(strncmp(action
,"conffile",strlen("conffile")) == 0)
463 status
<< "pmconffile:" << list
[1]
464 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
468 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
469 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
470 std::clog
<< "send: '" << status
.str() << "'" << endl
;
474 vector
<struct DpkgState
> &states
= PackageOps
[pkg
];
475 const char *next_action
= NULL
;
476 if(PackageOpsDone
[pkg
] < states
.size())
477 next_action
= states
[PackageOpsDone
[pkg
]].state
;
478 // check if the package moved to the next dpkg state
479 if(next_action
&& (strcmp(action
, next_action
) == 0))
481 // only read the translation if there is actually a next
483 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
485 snprintf(s
, sizeof(s
), translation
, pkg
);
487 // we moved from one dpkg state to a new one, report that
488 PackageOpsDone
[pkg
]++;
490 // build the status str
491 status
<< "pmstatus:" << pkg
492 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
496 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
497 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
498 std::clog
<< "send: '" << status
.str() << "'" << endl
;
500 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
501 std::clog
<< "(parsed from dpkg) pkg: " << pkg
502 << " action: " << action
<< endl
;
505 // DPkgPM::DoDpkgStatusFd /*{{{*/
506 // ---------------------------------------------------------------------
509 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
, int OutStatusFd
)
514 len
=read(statusfd
, &dpkgbuf
[dpkgbuf_pos
], sizeof(dpkgbuf
)-dpkgbuf_pos
);
519 // process line by line if we have a buffer
521 while((q
=(char*)memchr(p
, '\n', dpkgbuf
+dpkgbuf_pos
-p
)) != NULL
)
524 ProcessDpkgStatusLine(OutStatusFd
, p
);
525 p
=q
+1; // continue with next line
528 // now move the unprocessed bits (after the final \n that is now a 0x0)
529 // to the start and update dpkgbuf_pos
530 p
= (char*)memrchr(dpkgbuf
, 0, dpkgbuf_pos
);
534 // we are interessted in the first char *after* 0x0
537 // move the unprocessed tail to the start and update pos
538 memmove(dpkgbuf
, p
, p
-dpkgbuf
);
539 dpkgbuf_pos
= dpkgbuf
+dpkgbuf_pos
-p
;
543 bool pkgDPkgPM::OpenLog()
545 string logdir
= _config
->FindDir("Dir::Log");
546 if(not FileExists(logdir
))
547 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
548 string logfile_name
= flCombine(logdir
,
549 _config
->Find("Dir::Log::Terminal"));
550 if (!logfile_name
.empty())
552 term_out
= fopen(logfile_name
.c_str(),"a");
553 chmod(logfile_name
.c_str(), 0600);
554 // output current time
556 time_t t
= time(NULL
);
557 struct tm
*tmp
= localtime(&t
);
558 strftime(outstr
, sizeof(outstr
), "%F %T", tmp
);
559 fprintf(term_out
, "\nLog started: ");
560 fprintf(term_out
, "%s", outstr
);
561 fprintf(term_out
, "\n");
566 bool pkgDPkgPM::CloseLog()
571 time_t t
= time(NULL
);
572 struct tm
*tmp
= localtime(&t
);
573 strftime(outstr
, sizeof(outstr
), "%F %T", tmp
);
574 fprintf(term_out
, "Log ended: ");
575 fprintf(term_out
, "%s", outstr
);
576 fprintf(term_out
, "\n");
584 // This implements a racy version of pselect for those architectures
585 // that don't have a working implementation.
586 // FIXME: Probably can be removed on Lenny+1
587 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
588 fd_set
*exceptfds
, const struct timespec
*timeout
,
589 const sigset_t
*sigmask
)
595 tv
.tv_sec
= timeout
->tv_sec
;
596 tv
.tv_usec
= timeout
->tv_nsec
/1000;
598 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
599 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
600 sigprocmask(SIG_SETMASK
, &origmask
, 0);
605 // DPkgPM::Go - Run the sequence /*{{{*/
606 // ---------------------------------------------------------------------
607 /* This globs the operations and calls dpkg
609 * If it is called with "OutStatusFd" set to a valid file descriptor
610 * apt will report the install progress over this fd. It maps the
611 * dpkg states a package goes through to human readable (and i10n-able)
612 * names and calculates a percentage for each step.
614 bool pkgDPkgPM::Go(int OutStatusFd
)
619 sigset_t original_sigmask
;
621 unsigned int MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
622 unsigned int MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
623 bool NoTriggers
= _config
->FindB("DPkg::NoTriggers",false);
625 if (RunScripts("DPkg::Pre-Invoke") == false)
628 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
631 // map the dpkg states to the operations that are performed
632 // (this is sorted in the same way as Item::Ops)
633 static const struct DpkgState DpkgStatesOpMap
[][7] = {
636 {"half-installed", N_("Preparing %s")},
637 {"unpacked", N_("Unpacking %s") },
640 // Configure operation
642 {"unpacked",N_("Preparing to configure %s") },
643 {"half-configured", N_("Configuring %s") },
644 { "installed", N_("Installed %s")},
649 {"half-configured", N_("Preparing for removal of %s")},
650 {"half-installed", N_("Removing %s")},
651 {"config-files", N_("Removed %s")},
656 {"config-files", N_("Preparing to completely remove %s")},
657 {"not-installed", N_("Completely removed %s")},
662 // init the PackageOps map, go over the list of packages that
663 // that will be [installed|configured|removed|purged] and add
664 // them to the PackageOps map (the dpkg states it goes through)
665 // and the PackageOpsTranslations (human readable strings)
666 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end();I
++)
668 string name
= (*I
).Pkg
.Name();
669 PackageOpsDone
[name
] = 0;
670 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; i
++)
672 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
677 stdin_is_dev_null
= false;
682 // this loop is runs once per operation
683 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end();)
685 vector
<Item
>::iterator J
= I
;
686 for (; J
!= List
.end() && J
->Op
== I
->Op
; J
++)
689 // Generate the argument list
690 const char *Args
[MaxArgs
+ 50];
692 // Now check if we are within the MaxArgs limit
694 // this code below is problematic, because it may happen that
695 // the argument list is split in a way that A depends on B
696 // and they are in the same "--configure A B" run
697 // - with the split they may now be configured in different
699 if (J
- I
> (signed)MaxArgs
)
703 unsigned long Size
= 0;
704 string Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
705 Args
[n
++] = Tmp
.c_str();
706 Size
+= strlen(Args
[n
-1]);
708 // Stick in any custom dpkg options
709 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
713 for (; Opts
!= 0; Opts
= Opts
->Next
)
715 if (Opts
->Value
.empty() == true)
717 Args
[n
++] = Opts
->Value
.c_str();
718 Size
+= Opts
->Value
.length();
722 char status_fd_buf
[20];
726 Args
[n
++] = "--status-fd";
727 Size
+= strlen(Args
[n
-1]);
728 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
729 Args
[n
++] = status_fd_buf
;
730 Size
+= strlen(Args
[n
-1]);
735 Args
[n
++] = "--force-depends";
736 Size
+= strlen(Args
[n
-1]);
737 Args
[n
++] = "--force-remove-essential";
738 Size
+= strlen(Args
[n
-1]);
739 Args
[n
++] = "--remove";
740 Size
+= strlen(Args
[n
-1]);
744 Args
[n
++] = "--force-depends";
745 Size
+= strlen(Args
[n
-1]);
746 Args
[n
++] = "--force-remove-essential";
747 Size
+= strlen(Args
[n
-1]);
748 Args
[n
++] = "--purge";
749 Size
+= strlen(Args
[n
-1]);
752 case Item::Configure
:
753 Args
[n
++] = "--configure";
755 Args
[n
++] = "--no-triggers";
756 Size
+= strlen(Args
[n
-1]);
760 Args
[n
++] = "--unpack";
761 Size
+= strlen(Args
[n
-1]);
762 Args
[n
++] = "--auto-deconfigure";
763 Size
+= strlen(Args
[n
-1]);
767 // Write in the file or package names
768 if (I
->Op
== Item::Install
)
770 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
772 if (I
->File
[0] != '/')
773 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
774 Args
[n
++] = I
->File
.c_str();
775 Size
+= strlen(Args
[n
-1]);
780 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
782 Args
[n
++] = I
->Pkg
.Name();
783 Size
+= strlen(Args
[n
-1]);
789 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
791 for (unsigned int k
= 0; k
!= n
; k
++)
792 clog
<< Args
[k
] << ' ';
801 /* Mask off sig int/quit. We do this because dpkg also does when
802 it forks scripts. What happens is that when you hit ctrl-c it sends
803 it to all processes in the group. Since dpkg ignores the signal
804 it doesn't die but we do! So we must also ignore it */
805 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
806 sighandler_t old_SIGINT
= signal(SIGINT
,SIG_IGN
);
808 // ignore SIGHUP as well (debian #463030)
809 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
816 // if tcgetattr does not return zero there was a error
817 // and we do not do any pty magic
818 if (tcgetattr(0, &tt
) == 0)
820 ioctl(0, TIOCGWINSZ
, (char *)&win
);
821 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
823 const char *s
= _("Can not write log, openpty() "
824 "failed (/dev/pts not mounted?)\n");
825 fprintf(stderr
, "%s",s
);
826 fprintf(term_out
, "%s",s
);
832 rtt
.c_lflag
&= ~ECHO
;
833 // block SIGTTOU during tcsetattr to prevent a hang if
834 // the process is a member of the background process group
835 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
836 sigemptyset(&sigmask
);
837 sigaddset(&sigmask
, SIGTTOU
);
838 sigprocmask(SIG_BLOCK
,&sigmask
, &original_sigmask
);
839 tcsetattr(0, TCSAFLUSH
, &rtt
);
840 sigprocmask(SIG_SETMASK
, &original_sigmask
, 0);
846 _config
->Set("APT::Keep-Fds::",fd
[1]);
847 // send status information that we are about to fork dpkg
848 if(OutStatusFd
> 0) {
849 ostringstream status
;
850 status
<< "pmstatus:dpkg-exec:"
851 << (PackagesDone
/float(PackagesTotal
)*100.0)
852 << ":" << _("Running dpkg")
854 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
861 if(slave
>= 0 && master
>= 0)
864 ioctl(slave
, TIOCSCTTY
, 0);
871 close(fd
[0]); // close the read end of the pipe
873 if (_config
->FindDir("DPkg::Chroot-Directory","/") != "/")
875 std::cerr
<< "Chrooting into "
876 << _config
->FindDir("DPkg::Chroot-Directory")
878 if (chroot(_config
->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
882 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
885 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
888 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
891 // Discard everything in stdin before forking dpkg
892 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
895 while (read(STDIN_FILENO
,&dummy
,1) == 1);
897 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
901 /* No Job Control Stop Env is a magic dpkg var that prevents it
902 from using sigstop */
903 putenv((char *)"DPKG_NO_TSTP=yes");
904 execvp(Args
[0],(char **)Args
);
905 cerr
<< "Could not exec dpkg!" << endl
;
910 if (_config
->FindB("DPkg::UseIoNice", false) == true)
913 // clear the Keep-Fd again
914 _config
->Clear("APT::Keep-Fds",fd
[1]);
919 // we read from dpkg here
921 close(fd
[1]); // close the write end of the pipe
923 // the result of the waitpid call
929 sigemptyset(&sigmask
);
930 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
933 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
935 // FIXME: move this to a function or something, looks ugly here
936 // error handling, waitpid returned -1
939 RunScripts("DPkg::Post-Invoke");
941 // Restore sig int/quit
942 signal(SIGQUIT
,old_SIGQUIT
);
943 signal(SIGINT
,old_SIGINT
);
944 signal(SIGHUP
,old_SIGHUP
);
945 return _error
->Errno("waitpid","Couldn't wait for subprocess");
948 // wait for input or output here
950 if (!stdin_is_dev_null
)
952 FD_SET(_dpkgin
, &rfds
);
954 FD_SET(master
, &rfds
);
957 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
958 &tv
, &original_sigmask
);
959 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
960 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
961 NULL
, &tv
, &original_sigmask
);
964 else if (select_ret
< 0 && errno
== EINTR
)
966 else if (select_ret
< 0)
968 perror("select() returned error");
972 if(master
>= 0 && FD_ISSET(master
, &rfds
))
973 DoTerminalPty(master
);
974 if(master
>= 0 && FD_ISSET(0, &rfds
))
976 if(FD_ISSET(_dpkgin
, &rfds
))
977 DoDpkgStatusFd(_dpkgin
, OutStatusFd
);
981 // Restore sig int/quit
982 signal(SIGQUIT
,old_SIGQUIT
);
983 signal(SIGINT
,old_SIGINT
);
984 signal(SIGHUP
,old_SIGHUP
);
988 tcsetattr(0, TCSAFLUSH
, &tt
);
992 // Check for an error code.
993 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
995 // if it was set to "keep-dpkg-runing" then we won't return
996 // here but keep the loop going and just report it as a error
998 bool stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
1001 RunScripts("DPkg::Post-Invoke");
1003 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
1004 _error
->Error("Sub-process %s received a segmentation fault.",Args
[0]);
1005 else if (WIFEXITED(Status
) != 0)
1006 _error
->Error("Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
1008 _error
->Error("Sub-process %s exited unexpectedly",Args
[0]);
1019 if (RunScripts("DPkg::Post-Invoke") == false)
1022 Cache
.writeStateFile(NULL
);
1026 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1027 // ---------------------------------------------------------------------
1029 void pkgDPkgPM::Reset()
1031 List
.erase(List
.begin(),List
.end());