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 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
78 // ---------------------------------------------------------------------
80 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
81 : pkgPackageManager(Cache
), dpkgbuf_pos(0),
82 term_out(NULL
), PackagesDone(0), PackagesTotal(0)
86 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
87 // ---------------------------------------------------------------------
89 pkgDPkgPM::~pkgDPkgPM()
93 // DPkgPM::Install - Install a package /*{{{*/
94 // ---------------------------------------------------------------------
95 /* Add an install operation to the sequence list */
96 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
98 if (File
.empty() == true || Pkg
.end() == true)
99 return _error
->Error("Internal Error, No file name for %s",Pkg
.Name());
101 List
.push_back(Item(Item::Install
,Pkg
,File
));
105 // DPkgPM::Configure - Configure a package /*{{{*/
106 // ---------------------------------------------------------------------
107 /* Add a configure operation to the sequence list */
108 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
110 if (Pkg
.end() == true)
113 List
.push_back(Item(Item::Configure
,Pkg
));
117 // DPkgPM::Remove - Remove a package /*{{{*/
118 // ---------------------------------------------------------------------
119 /* Add a remove operation to the sequence list */
120 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
122 if (Pkg
.end() == true)
126 List
.push_back(Item(Item::Purge
,Pkg
));
128 List
.push_back(Item(Item::Remove
,Pkg
));
132 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
133 // ---------------------------------------------------------------------
134 /* This is part of the helper script communication interface, it sends
135 very complete information down to the other end of the pipe.*/
136 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
138 fprintf(F
,"VERSION 2\n");
140 /* Write out all of the configuration directives by walking the
141 configuration tree */
142 const Configuration::Item
*Top
= _config
->Tree(0);
145 if (Top
->Value
.empty() == false)
148 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
149 QuoteString(Top
->Value
,"\n").c_str());
158 while (Top
!= 0 && Top
->Next
== 0)
165 // Write out the package actions in order.
166 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
168 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
170 fprintf(F
,"%s ",I
->Pkg
.Name());
172 if (I
->Pkg
->CurrentVer
== 0)
175 fprintf(F
,"%s ",I
->Pkg
.CurrentVer().VerStr());
177 // Show the compare operator
179 if (S
.InstallVer
!= 0)
182 if (I
->Pkg
->CurrentVer
!= 0)
183 Comp
= S
.InstVerIter(Cache
).CompareVer(I
->Pkg
.CurrentVer());
190 fprintf(F
,"%s ",S
.InstVerIter(Cache
).VerStr());
195 // Show the filename/operation
196 if (I
->Op
== Item::Install
)
199 if (I
->File
[0] != '/')
200 fprintf(F
,"**ERROR**\n");
202 fprintf(F
,"%s\n",I
->File
.c_str());
204 if (I
->Op
== Item::Configure
)
205 fprintf(F
,"**CONFIGURE**\n");
206 if (I
->Op
== Item::Remove
||
207 I
->Op
== Item::Purge
)
208 fprintf(F
,"**REMOVE**\n");
216 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
217 // ---------------------------------------------------------------------
218 /* This looks for a list of scripts to run from the configuration file
219 each one is run and is fed on standard input a list of all .deb files
220 that are due to be installed. */
221 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
223 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
224 if (Opts
== 0 || Opts
->Child
== 0)
228 unsigned int Count
= 1;
229 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
231 if (Opts
->Value
.empty() == true)
234 // Determine the protocol version
235 string OptSec
= Opts
->Value
;
236 string::size_type Pos
;
237 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
238 Pos
= OptSec
.length();
239 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
241 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
245 if (pipe(Pipes
) != 0)
246 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
247 SetCloseExec(Pipes
[0],true);
248 SetCloseExec(Pipes
[1],true);
250 // Purified Fork for running the script
251 pid_t Process
= ExecFork();
255 dup2(Pipes
[0],STDIN_FILENO
);
256 SetCloseExec(STDOUT_FILENO
,false);
257 SetCloseExec(STDIN_FILENO
,false);
258 SetCloseExec(STDERR_FILENO
,false);
263 Args
[2] = Opts
->Value
.c_str();
265 execv(Args
[0],(char **)Args
);
269 FILE *F
= fdopen(Pipes
[1],"w");
271 return _error
->Errno("fdopen","Faild to open new FD");
273 // Feed it the filenames.
277 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
279 // Only deal with packages to be installed from .deb
280 if (I
->Op
!= Item::Install
)
284 if (I
->File
[0] != '/')
287 /* Feed the filename of each package that is pending install
289 fprintf(F
,"%s\n",I
->File
.c_str());
298 Die
= !SendV2Pkgs(F
);
302 // Clean up the sub process
303 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
304 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
311 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
312 // ---------------------------------------------------------------------
315 void pkgDPkgPM::DoStdin(int master
)
317 unsigned char input_buf
[256] = {0,};
318 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
320 write(master
, input_buf
, len
);
322 stdin_is_dev_null
= true;
325 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
326 // ---------------------------------------------------------------------
328 * read the terminal pty and write log
330 void pkgDPkgPM::DoTerminalPty(int master
)
332 unsigned char term_buf
[1024] = {0,0, };
334 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
335 if(len
== -1 && errno
== EIO
)
337 // this happens when the child is about to exit, we
338 // give it time to actually exit, otherwise we run
345 write(1, term_buf
, len
);
347 fwrite(term_buf
, len
, sizeof(char), term_out
);
350 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
351 // ---------------------------------------------------------------------
354 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd
, char *line
)
356 // the status we output
357 ostringstream status
;
359 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
360 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
363 /* dpkg sends strings like this:
364 'status: <pkg>: <pkg qstate>'
365 errors look like this:
366 '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
367 and conffile-prompt like this
368 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
370 Newer versions of dpkg sent also:
371 'processing: install: pkg'
372 'processing: configure: pkg'
373 'processing: remove: pkg'
374 'processing: trigproc: trigger'
378 // dpkg sends multiline error messages sometimes (see
379 // #374195 for a example. we should support this by
380 // either patching dpkg to not send multiline over the
381 // statusfd or by rewriting the code here to deal with
382 // it. for now we just ignore it and not crash
383 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
384 if( list
[0] == NULL
|| list
[1] == NULL
|| list
[2] == NULL
)
386 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
387 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
391 char *action
= _strstrip(list
[2]);
393 // 'processing' from dpkg looks like
394 // 'processing: action: pkg'
395 if(strncmp(list
[0], "processing", strlen("processing")) == 0)
398 char *pkg_or_trigger
= _strstrip(list
[2]);
399 action
=_strstrip( list
[1]);
400 const std::pair
<const char *, const char *> * const iter
=
401 std::find_if(PackageProcessingOpsBegin
,
402 PackageProcessingOpsEnd
,
403 MatchProcessingOp(action
));
404 if(iter
== PackageProcessingOpsEnd
)
406 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
407 std::clog
<< "ignoring unknwon action: " << action
<< std::endl
;
410 snprintf(s
, sizeof(s
), _(iter
->second
), pkg_or_trigger
);
412 status
<< "pmstatus:" << pkg_or_trigger
413 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
417 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
418 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
419 std::clog
<< "send: '" << status
.str() << "'" << endl
;
423 if(strncmp(action
,"error",strlen("error")) == 0)
425 status
<< "pmerror:" << list
[1]
426 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
430 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
431 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
432 std::clog
<< "send: '" << status
.str() << "'" << endl
;
435 if(strncmp(action
,"conffile",strlen("conffile")) == 0)
437 status
<< "pmconffile:" << list
[1]
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 vector
<struct DpkgState
> &states
= PackageOps
[pkg
];
449 const char *next_action
= NULL
;
450 if(PackageOpsDone
[pkg
] < states
.size())
451 next_action
= states
[PackageOpsDone
[pkg
]].state
;
452 // check if the package moved to the next dpkg state
453 if(next_action
&& (strcmp(action
, next_action
) == 0))
455 // only read the translation if there is actually a next
457 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
459 snprintf(s
, sizeof(s
), translation
, pkg
);
461 // we moved from one dpkg state to a new one, report that
462 PackageOpsDone
[pkg
]++;
464 // build the status str
465 status
<< "pmstatus:" << pkg
466 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
470 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
471 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
472 std::clog
<< "send: '" << status
.str() << "'" << endl
;
474 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
475 std::clog
<< "(parsed from dpkg) pkg: " << pkg
476 << " action: " << action
<< endl
;
479 // DPkgPM::DoDpkgStatusFd /*{{{*/
480 // ---------------------------------------------------------------------
483 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
, int OutStatusFd
)
488 len
=read(statusfd
, &dpkgbuf
[dpkgbuf_pos
], sizeof(dpkgbuf
)-dpkgbuf_pos
);
493 // process line by line if we have a buffer
495 while((q
=(char*)memchr(p
, '\n', dpkgbuf
+dpkgbuf_pos
-p
)) != NULL
)
498 ProcessDpkgStatusLine(OutStatusFd
, p
);
499 p
=q
+1; // continue with next line
502 // now move the unprocessed bits (after the final \n that is now a 0x0)
503 // to the start and update dpkgbuf_pos
504 p
= (char*)memrchr(dpkgbuf
, 0, dpkgbuf_pos
);
508 // we are interessted in the first char *after* 0x0
511 // move the unprocessed tail to the start and update pos
512 memmove(dpkgbuf
, p
, p
-dpkgbuf
);
513 dpkgbuf_pos
= dpkgbuf
+dpkgbuf_pos
-p
;
517 bool pkgDPkgPM::OpenLog()
519 string logdir
= _config
->FindDir("Dir::Log");
520 if(not FileExists(logdir
))
521 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
522 string logfile_name
= flCombine(logdir
,
523 _config
->Find("Dir::Log::Terminal"));
524 if (!logfile_name
.empty())
526 term_out
= fopen(logfile_name
.c_str(),"a");
527 chmod(logfile_name
.c_str(), 0600);
528 // output current time
530 time_t t
= time(NULL
);
531 struct tm
*tmp
= localtime(&t
);
532 strftime(outstr
, sizeof(outstr
), "%F %T", tmp
);
533 fprintf(term_out
, "\nLog started: ");
534 fprintf(term_out
, "%s", outstr
);
535 fprintf(term_out
, "\n");
540 bool pkgDPkgPM::CloseLog()
545 time_t t
= time(NULL
);
546 struct tm
*tmp
= localtime(&t
);
547 strftime(outstr
, sizeof(outstr
), "%F %T", tmp
);
548 fprintf(term_out
, "Log ended: ");
549 fprintf(term_out
, "%s", outstr
);
550 fprintf(term_out
, "\n");
558 // This implements a racy version of pselect for those architectures
559 // that don't have a working implementation.
560 // FIXME: Probably can be removed on Lenny+1
561 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
562 fd_set
*exceptfds
, const struct timespec
*timeout
,
563 const sigset_t
*sigmask
)
569 tv
.tv_sec
= timeout
->tv_sec
;
570 tv
.tv_usec
= timeout
->tv_nsec
/1000;
572 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
573 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
574 sigprocmask(SIG_SETMASK
, &origmask
, 0);
579 // DPkgPM::Go - Run the sequence /*{{{*/
580 // ---------------------------------------------------------------------
581 /* This globs the operations and calls dpkg
583 * If it is called with "OutStatusFd" set to a valid file descriptor
584 * apt will report the install progress over this fd. It maps the
585 * dpkg states a package goes through to human readable (and i10n-able)
586 * names and calculates a percentage for each step.
588 bool pkgDPkgPM::Go(int OutStatusFd
)
593 sigset_t original_sigmask
;
595 unsigned int MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
596 unsigned int MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
597 bool NoTriggers
= _config
->FindB("DPkg::NoTriggers",false);
599 if (RunScripts("DPkg::Pre-Invoke") == false)
602 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
605 // map the dpkg states to the operations that are performed
606 // (this is sorted in the same way as Item::Ops)
607 static const struct DpkgState DpkgStatesOpMap
[][7] = {
610 {"half-installed", N_("Preparing %s")},
611 {"unpacked", N_("Unpacking %s") },
614 // Configure operation
616 {"unpacked",N_("Preparing to configure %s") },
617 {"half-configured", N_("Configuring %s") },
619 {"triggers-awaited", N_("Processing triggers for %s") },
620 {"triggers-pending", N_("Processing triggers for %s") },
622 { "installed", N_("Installed %s")},
627 {"half-configured", N_("Preparing for removal of %s")},
629 {"triggers-awaited", N_("Preparing for removal of %s")},
630 {"triggers-pending", N_("Preparing for removal of %s")},
632 {"half-installed", N_("Removing %s")},
633 {"config-files", N_("Removed %s")},
638 {"config-files", N_("Preparing to completely remove %s")},
639 {"not-installed", N_("Completely removed %s")},
644 // init the PackageOps map, go over the list of packages that
645 // that will be [installed|configured|removed|purged] and add
646 // them to the PackageOps map (the dpkg states it goes through)
647 // and the PackageOpsTranslations (human readable strings)
648 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end();I
++)
650 string name
= (*I
).Pkg
.Name();
651 PackageOpsDone
[name
] = 0;
652 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; i
++)
654 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
659 stdin_is_dev_null
= false;
664 // this loop is runs once per operation
665 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end();)
667 vector
<Item
>::iterator J
= I
;
668 for (; J
!= List
.end() && J
->Op
== I
->Op
; J
++);
670 // Generate the argument list
671 const char *Args
[MaxArgs
+ 50];
672 if (J
- I
> (signed)MaxArgs
)
676 unsigned long Size
= 0;
677 string Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
678 Args
[n
++] = Tmp
.c_str();
679 Size
+= strlen(Args
[n
-1]);
681 // Stick in any custom dpkg options
682 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
686 for (; Opts
!= 0; Opts
= Opts
->Next
)
688 if (Opts
->Value
.empty() == true)
690 Args
[n
++] = Opts
->Value
.c_str();
691 Size
+= Opts
->Value
.length();
695 char status_fd_buf
[20];
699 Args
[n
++] = "--status-fd";
700 Size
+= strlen(Args
[n
-1]);
701 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
702 Args
[n
++] = status_fd_buf
;
703 Size
+= strlen(Args
[n
-1]);
708 Args
[n
++] = "--force-depends";
709 Size
+= strlen(Args
[n
-1]);
710 Args
[n
++] = "--force-remove-essential";
711 Size
+= strlen(Args
[n
-1]);
712 Args
[n
++] = "--remove";
713 Size
+= strlen(Args
[n
-1]);
717 Args
[n
++] = "--force-depends";
718 Size
+= strlen(Args
[n
-1]);
719 Args
[n
++] = "--force-remove-essential";
720 Size
+= strlen(Args
[n
-1]);
721 Args
[n
++] = "--purge";
722 Size
+= strlen(Args
[n
-1]);
725 case Item::Configure
:
726 Args
[n
++] = "--configure";
728 Args
[n
++] = "--no-triggers";
729 Size
+= strlen(Args
[n
-1]);
733 Args
[n
++] = "--unpack";
734 Size
+= strlen(Args
[n
-1]);
735 Args
[n
++] = "--auto-deconfigure";
736 Size
+= strlen(Args
[n
-1]);
740 // Write in the file or package names
741 if (I
->Op
== Item::Install
)
743 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
745 if (I
->File
[0] != '/')
746 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
747 Args
[n
++] = I
->File
.c_str();
748 Size
+= strlen(Args
[n
-1]);
753 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
755 Args
[n
++] = I
->Pkg
.Name();
756 Size
+= strlen(Args
[n
-1]);
762 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
764 for (unsigned int k
= 0; k
!= n
; k
++)
765 clog
<< Args
[k
] << ' ';
774 /* Mask off sig int/quit. We do this because dpkg also does when
775 it forks scripts. What happens is that when you hit ctrl-c it sends
776 it to all processes in the group. Since dpkg ignores the signal
777 it doesn't die but we do! So we must also ignore it */
778 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
779 sighandler_t old_SIGINT
= signal(SIGINT
,SIG_IGN
);
781 // ignore SIGHUP as well (debian #463030)
782 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
789 // FIXME: setup sensible signal handling (*ick*)
791 ioctl(0, TIOCGWINSZ
, (char *)&win
);
792 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
794 const char *s
= _("Can not write log, openpty() "
795 "failed (/dev/pts not mounted?)\n");
796 fprintf(stderr
, "%s",s
);
797 fprintf(term_out
, "%s",s
);
803 rtt
.c_lflag
&= ~ECHO
;
804 // block SIGTTOU during tcsetattr to prevent a hang if
805 // the process is a member of the background process group
806 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
807 sigemptyset(&sigmask
);
808 sigaddset(&sigmask
, SIGTTOU
);
809 sigprocmask(SIG_BLOCK
,&sigmask
, &original_sigmask
);
810 tcsetattr(0, TCSAFLUSH
, &rtt
);
811 sigprocmask(SIG_SETMASK
, &original_sigmask
, 0);
816 _config
->Set("APT::Keep-Fds::",fd
[1]);
822 if(slave
>= 0 && master
>= 0)
825 ioctl(slave
, TIOCSCTTY
, 0);
832 close(fd
[0]); // close the read end of the pipe
834 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
837 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
840 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
843 // Discard everything in stdin before forking dpkg
844 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
847 while (read(STDIN_FILENO
,&dummy
,1) == 1);
849 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
854 /* No Job Control Stop Env is a magic dpkg var that prevents it
855 from using sigstop */
856 putenv((char *)"DPKG_NO_TSTP=yes");
857 execvp(Args
[0],(char **)Args
);
858 cerr
<< "Could not exec dpkg!" << endl
;
862 // clear the Keep-Fd again
863 _config
->Clear("APT::Keep-Fds",fd
[1]);
868 // we read from dpkg here
870 close(fd
[1]); // close the write end of the pipe
872 // the result of the waitpid call
878 sigemptyset(&sigmask
);
879 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
882 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
884 // FIXME: move this to a function or something, looks ugly here
885 // error handling, waitpid returned -1
888 RunScripts("DPkg::Post-Invoke");
890 // Restore sig int/quit
891 signal(SIGQUIT
,old_SIGQUIT
);
892 signal(SIGINT
,old_SIGINT
);
893 signal(SIGHUP
,old_SIGHUP
);
894 return _error
->Errno("waitpid","Couldn't wait for subprocess");
897 // wait for input or output here
899 if (!stdin_is_dev_null
)
901 FD_SET(_dpkgin
, &rfds
);
903 FD_SET(master
, &rfds
);
906 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
907 &tv
, &original_sigmask
);
908 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
909 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
910 NULL
, &tv
, &original_sigmask
);
913 else if (select_ret
< 0 && errno
== EINTR
)
915 else if (select_ret
< 0)
917 perror("select() returned error");
921 if(master
>= 0 && FD_ISSET(master
, &rfds
))
922 DoTerminalPty(master
);
923 if(master
>= 0 && FD_ISSET(0, &rfds
))
925 if(FD_ISSET(_dpkgin
, &rfds
))
926 DoDpkgStatusFd(_dpkgin
, OutStatusFd
);
930 // Restore sig int/quit
931 signal(SIGQUIT
,old_SIGQUIT
);
932 signal(SIGINT
,old_SIGINT
);
933 signal(SIGHUP
,old_SIGHUP
);
937 tcsetattr(0, TCSAFLUSH
, &tt
);
941 // Check for an error code.
942 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
944 // if it was set to "keep-dpkg-runing" then we won't return
945 // here but keep the loop going and just report it as a error
947 bool stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
950 RunScripts("DPkg::Post-Invoke");
952 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
953 _error
->Error("Sub-process %s received a segmentation fault.",Args
[0]);
954 else if (WIFEXITED(Status
) != 0)
955 _error
->Error("Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
957 _error
->Error("Sub-process %s exited unexpectedly",Args
[0]);
968 if (RunScripts("DPkg::Post-Invoke") == false)
971 Cache
.writeStateFile(NULL
);
975 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
976 // ---------------------------------------------------------------------
978 void pkgDPkgPM::Reset()
980 List
.erase(List
.begin(),List
.end());