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
));
140 // Use triggers for config calls if we configure "smart"
141 // as otherwise Pre-Depends will not be satisfied, see #526774
142 if (_config
->FindB("DPkg::TriggersPending", false) == true)
143 List
.push_back(Item(Item::TriggersPending
, PkgIterator()));
148 // DPkgPM::Remove - Remove a package /*{{{*/
149 // ---------------------------------------------------------------------
150 /* Add a remove operation to the sequence list */
151 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
153 if (Pkg
.end() == true)
157 List
.push_back(Item(Item::Purge
,Pkg
));
159 List
.push_back(Item(Item::Remove
,Pkg
));
163 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
164 // ---------------------------------------------------------------------
165 /* This is part of the helper script communication interface, it sends
166 very complete information down to the other end of the pipe.*/
167 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
169 fprintf(F
,"VERSION 2\n");
171 /* Write out all of the configuration directives by walking the
172 configuration tree */
173 const Configuration::Item
*Top
= _config
->Tree(0);
176 if (Top
->Value
.empty() == false)
179 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
180 QuoteString(Top
->Value
,"\n").c_str());
189 while (Top
!= 0 && Top
->Next
== 0)
196 // Write out the package actions in order.
197 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
199 if(I
->Pkg
.end() == true)
202 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
204 fprintf(F
,"%s ",I
->Pkg
.Name());
206 if (I
->Pkg
->CurrentVer
== 0)
209 fprintf(F
,"%s ",I
->Pkg
.CurrentVer().VerStr());
211 // Show the compare operator
213 if (S
.InstallVer
!= 0)
216 if (I
->Pkg
->CurrentVer
!= 0)
217 Comp
= S
.InstVerIter(Cache
).CompareVer(I
->Pkg
.CurrentVer());
224 fprintf(F
,"%s ",S
.InstVerIter(Cache
).VerStr());
229 // Show the filename/operation
230 if (I
->Op
== Item::Install
)
233 if (I
->File
[0] != '/')
234 fprintf(F
,"**ERROR**\n");
236 fprintf(F
,"%s\n",I
->File
.c_str());
238 if (I
->Op
== Item::Configure
)
239 fprintf(F
,"**CONFIGURE**\n");
240 if (I
->Op
== Item::Remove
||
241 I
->Op
== Item::Purge
)
242 fprintf(F
,"**REMOVE**\n");
250 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
251 // ---------------------------------------------------------------------
252 /* This looks for a list of scripts to run from the configuration file
253 each one is run and is fed on standard input a list of all .deb files
254 that are due to be installed. */
255 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
257 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
258 if (Opts
== 0 || Opts
->Child
== 0)
262 unsigned int Count
= 1;
263 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
265 if (Opts
->Value
.empty() == true)
268 // Determine the protocol version
269 string OptSec
= Opts
->Value
;
270 string::size_type Pos
;
271 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
272 Pos
= OptSec
.length();
273 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
275 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
279 if (pipe(Pipes
) != 0)
280 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
281 SetCloseExec(Pipes
[0],true);
282 SetCloseExec(Pipes
[1],true);
284 // Purified Fork for running the script
285 pid_t Process
= ExecFork();
289 dup2(Pipes
[0],STDIN_FILENO
);
290 SetCloseExec(STDOUT_FILENO
,false);
291 SetCloseExec(STDIN_FILENO
,false);
292 SetCloseExec(STDERR_FILENO
,false);
297 Args
[2] = Opts
->Value
.c_str();
299 execv(Args
[0],(char **)Args
);
303 FILE *F
= fdopen(Pipes
[1],"w");
305 return _error
->Errno("fdopen","Faild to open new FD");
307 // Feed it the filenames.
311 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
313 // Only deal with packages to be installed from .deb
314 if (I
->Op
!= Item::Install
)
318 if (I
->File
[0] != '/')
321 /* Feed the filename of each package that is pending install
323 fprintf(F
,"%s\n",I
->File
.c_str());
332 Die
= !SendV2Pkgs(F
);
336 // Clean up the sub process
337 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
338 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
345 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
346 // ---------------------------------------------------------------------
349 void pkgDPkgPM::DoStdin(int master
)
351 unsigned char input_buf
[256] = {0,};
352 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
354 write(master
, input_buf
, len
);
356 stdin_is_dev_null
= true;
359 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
360 // ---------------------------------------------------------------------
362 * read the terminal pty and write log
364 void pkgDPkgPM::DoTerminalPty(int master
)
366 unsigned char term_buf
[1024] = {0,0, };
368 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
369 if(len
== -1 && errno
== EIO
)
371 // this happens when the child is about to exit, we
372 // give it time to actually exit, otherwise we run
379 write(1, term_buf
, len
);
381 fwrite(term_buf
, len
, sizeof(char), term_out
);
384 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
385 // ---------------------------------------------------------------------
388 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd
, char *line
)
390 bool const Debug
= _config
->FindB("Debug::pkgDPkgProgressReporting",false);
391 // the status we output
392 ostringstream status
;
395 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
398 /* dpkg sends strings like this:
399 'status: <pkg>: <pkg qstate>'
400 errors look like this:
401 '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
402 and conffile-prompt like this
403 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
405 Newer versions of dpkg sent also:
406 'processing: install: pkg'
407 'processing: configure: pkg'
408 'processing: remove: pkg'
409 'processing: purge: pkg' - but for apt is it a ignored "unknown" action
410 'processing: trigproc: trigger'
414 // dpkg sends multiline error messages sometimes (see
415 // #374195 for a example. we should support this by
416 // either patching dpkg to not send multiline over the
417 // statusfd or by rewriting the code here to deal with
418 // it. for now we just ignore it and not crash
419 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
420 if( list
[0] == NULL
|| list
[1] == NULL
|| list
[2] == NULL
)
423 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
426 const char* const pkg
= list
[1];
427 const char* action
= _strstrip(list
[2]);
429 // 'processing' from dpkg looks like
430 // 'processing: action: pkg'
431 if(strncmp(list
[0], "processing", strlen("processing")) == 0)
434 const char* const pkg_or_trigger
= _strstrip(list
[2]);
435 action
= _strstrip( list
[1]);
436 const std::pair
<const char *, const char *> * const iter
=
437 std::find_if(PackageProcessingOpsBegin
,
438 PackageProcessingOpsEnd
,
439 MatchProcessingOp(action
));
440 if(iter
== PackageProcessingOpsEnd
)
443 std::clog
<< "ignoring unknown action: " << action
<< std::endl
;
446 snprintf(s
, sizeof(s
), _(iter
->second
), pkg_or_trigger
);
448 status
<< "pmstatus:" << pkg_or_trigger
449 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
453 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
455 std::clog
<< "send: '" << status
.str() << "'" << endl
;
459 if(strncmp(action
,"error",strlen("error")) == 0)
461 status
<< "pmerror:" << list
[1]
462 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
466 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
468 std::clog
<< "send: '" << status
.str() << "'" << endl
;
471 else if(strncmp(action
,"conffile",strlen("conffile")) == 0)
473 status
<< "pmconffile:" << list
[1]
474 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
478 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
480 std::clog
<< "send: '" << status
.str() << "'" << endl
;
484 vector
<struct DpkgState
> const &states
= PackageOps
[pkg
];
485 const char *next_action
= NULL
;
486 if(PackageOpsDone
[pkg
] < states
.size())
487 next_action
= states
[PackageOpsDone
[pkg
]].state
;
488 // check if the package moved to the next dpkg state
489 if(next_action
&& (strcmp(action
, next_action
) == 0))
491 // only read the translation if there is actually a next
493 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
495 snprintf(s
, sizeof(s
), translation
, pkg
);
497 // we moved from one dpkg state to a new one, report that
498 PackageOpsDone
[pkg
]++;
500 // build the status str
501 status
<< "pmstatus:" << pkg
502 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
506 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
508 std::clog
<< "send: '" << status
.str() << "'" << endl
;
511 std::clog
<< "(parsed from dpkg) pkg: " << pkg
512 << " action: " << action
<< endl
;
515 // DPkgPM::DoDpkgStatusFd /*{{{*/
516 // ---------------------------------------------------------------------
519 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
, int OutStatusFd
)
524 len
=read(statusfd
, &dpkgbuf
[dpkgbuf_pos
], sizeof(dpkgbuf
)-dpkgbuf_pos
);
529 // process line by line if we have a buffer
531 while((q
=(char*)memchr(p
, '\n', dpkgbuf
+dpkgbuf_pos
-p
)) != NULL
)
534 ProcessDpkgStatusLine(OutStatusFd
, p
);
535 p
=q
+1; // continue with next line
538 // now move the unprocessed bits (after the final \n that is now a 0x0)
539 // to the start and update dpkgbuf_pos
540 p
= (char*)memrchr(dpkgbuf
, 0, dpkgbuf_pos
);
544 // we are interessted in the first char *after* 0x0
547 // move the unprocessed tail to the start and update pos
548 memmove(dpkgbuf
, p
, p
-dpkgbuf
);
549 dpkgbuf_pos
= dpkgbuf
+dpkgbuf_pos
-p
;
552 // DPkgPM::OpenLog /*{{{*/
553 bool pkgDPkgPM::OpenLog()
555 string logdir
= _config
->FindDir("Dir::Log");
556 if(not FileExists(logdir
))
557 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
558 string logfile_name
= flCombine(logdir
,
559 _config
->Find("Dir::Log::Terminal"));
560 if (!logfile_name
.empty())
562 term_out
= fopen(logfile_name
.c_str(),"a");
563 chmod(logfile_name
.c_str(), 0600);
564 // output current time
566 time_t t
= time(NULL
);
567 struct tm
*tmp
= localtime(&t
);
568 strftime(outstr
, sizeof(outstr
), "%F %T", tmp
);
569 fprintf(term_out
, "\nLog started: ");
570 fprintf(term_out
, "%s", outstr
);
571 fprintf(term_out
, "\n");
576 // DPkg::CloseLog /*{{{*/
577 bool pkgDPkgPM::CloseLog()
582 time_t t
= time(NULL
);
583 struct tm
*tmp
= localtime(&t
);
584 strftime(outstr
, sizeof(outstr
), "%F %T", tmp
);
585 fprintf(term_out
, "Log ended: ");
586 fprintf(term_out
, "%s", outstr
);
587 fprintf(term_out
, "\n");
595 // This implements a racy version of pselect for those architectures
596 // that don't have a working implementation.
597 // FIXME: Probably can be removed on Lenny+1
598 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
599 fd_set
*exceptfds
, const struct timespec
*timeout
,
600 const sigset_t
*sigmask
)
606 tv
.tv_sec
= timeout
->tv_sec
;
607 tv
.tv_usec
= timeout
->tv_nsec
/1000;
609 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
610 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
611 sigprocmask(SIG_SETMASK
, &origmask
, 0);
615 // DPkgPM::Go - Run the sequence /*{{{*/
616 // ---------------------------------------------------------------------
617 /* This globs the operations and calls dpkg
619 * If it is called with "OutStatusFd" set to a valid file descriptor
620 * apt will report the install progress over this fd. It maps the
621 * dpkg states a package goes through to human readable (and i10n-able)
622 * names and calculates a percentage for each step.
624 bool pkgDPkgPM::Go(int OutStatusFd
)
629 sigset_t original_sigmask
;
631 unsigned int const MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
632 unsigned int const MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
633 bool const NoTriggers
= _config
->FindB("DPkg::NoTriggers", false);
635 if (RunScripts("DPkg::Pre-Invoke") == false)
638 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
641 // support subpressing of triggers processing for special
642 // cases like d-i that runs the triggers handling manually
643 bool const SmartConf
= (_config
->Find("PackageManager::Configure", "all") != "all");
644 bool const TriggersPending
= _config
->FindB("DPkg::TriggersPending", false);
645 if (_config
->FindB("DPkg::ConfigurePending", SmartConf
) == true)
646 List
.push_back(Item(Item::ConfigurePending
, PkgIterator()));
648 // map the dpkg states to the operations that are performed
649 // (this is sorted in the same way as Item::Ops)
650 static const struct DpkgState DpkgStatesOpMap
[][7] = {
653 {"half-installed", N_("Preparing %s")},
654 {"unpacked", N_("Unpacking %s") },
657 // Configure operation
659 {"unpacked",N_("Preparing to configure %s") },
660 {"half-configured", N_("Configuring %s") },
661 { "installed", N_("Installed %s")},
666 {"half-configured", N_("Preparing for removal of %s")},
667 {"half-installed", N_("Removing %s")},
668 {"config-files", N_("Removed %s")},
673 {"config-files", N_("Preparing to completely remove %s")},
674 {"not-installed", N_("Completely removed %s")},
679 // init the PackageOps map, go over the list of packages that
680 // that will be [installed|configured|removed|purged] and add
681 // them to the PackageOps map (the dpkg states it goes through)
682 // and the PackageOpsTranslations (human readable strings)
683 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();I
++)
685 if((*I
).Pkg
.end() == true)
688 string
const name
= (*I
).Pkg
.Name();
689 PackageOpsDone
[name
] = 0;
690 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; i
++)
692 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
697 stdin_is_dev_null
= false;
702 // this loop is runs once per operation
703 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();)
705 // Do all actions with the same Op in one run
706 vector
<Item
>::const_iterator J
= I
;
707 if (TriggersPending
== true)
708 for (; J
!= List
.end(); J
++)
712 if (J
->Op
!= Item::TriggersPending
)
714 vector
<Item
>::const_iterator T
= J
+ 1;
715 if (T
!= List
.end() && T
->Op
== I
->Op
)
720 for (; J
!= List
.end() && J
->Op
== I
->Op
; J
++)
723 // Generate the argument list
724 const char *Args
[MaxArgs
+ 50];
726 // Now check if we are within the MaxArgs limit
728 // this code below is problematic, because it may happen that
729 // the argument list is split in a way that A depends on B
730 // and they are in the same "--configure A B" run
731 // - with the split they may now be configured in different
733 if (J
- I
> (signed)MaxArgs
)
737 unsigned long Size
= 0;
738 string
const Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
739 Args
[n
++] = Tmp
.c_str();
740 Size
+= strlen(Args
[n
-1]);
742 // Stick in any custom dpkg options
743 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
747 for (; Opts
!= 0; Opts
= Opts
->Next
)
749 if (Opts
->Value
.empty() == true)
751 Args
[n
++] = Opts
->Value
.c_str();
752 Size
+= Opts
->Value
.length();
756 char status_fd_buf
[20];
760 Args
[n
++] = "--status-fd";
761 Size
+= strlen(Args
[n
-1]);
762 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
763 Args
[n
++] = status_fd_buf
;
764 Size
+= strlen(Args
[n
-1]);
769 Args
[n
++] = "--force-depends";
770 Size
+= strlen(Args
[n
-1]);
771 Args
[n
++] = "--force-remove-essential";
772 Size
+= strlen(Args
[n
-1]);
773 Args
[n
++] = "--remove";
774 Size
+= strlen(Args
[n
-1]);
778 Args
[n
++] = "--force-depends";
779 Size
+= strlen(Args
[n
-1]);
780 Args
[n
++] = "--force-remove-essential";
781 Size
+= strlen(Args
[n
-1]);
782 Args
[n
++] = "--purge";
783 Size
+= strlen(Args
[n
-1]);
786 case Item::Configure
:
787 Args
[n
++] = "--configure";
788 Size
+= strlen(Args
[n
-1]);
791 case Item::ConfigurePending
:
792 Args
[n
++] = "--configure";
793 Size
+= strlen(Args
[n
-1]);
794 Args
[n
++] = "--pending";
795 Size
+= strlen(Args
[n
-1]);
798 case Item::TriggersPending
:
799 Args
[n
++] = "--triggers-only";
800 Size
+= strlen(Args
[n
-1]);
801 Args
[n
++] = "--pending";
802 Size
+= strlen(Args
[n
-1]);
806 Args
[n
++] = "--unpack";
807 Size
+= strlen(Args
[n
-1]);
808 Args
[n
++] = "--auto-deconfigure";
809 Size
+= strlen(Args
[n
-1]);
813 if (NoTriggers
== true && I
->Op
!= Item::TriggersPending
&&
814 I
->Op
!= Item::ConfigurePending
)
816 Args
[n
++] = "--no-triggers";
817 Size
+= strlen(Args
[n
-1]);
820 // Write in the file or package names
821 if (I
->Op
== Item::Install
)
823 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
825 if (I
->File
[0] != '/')
826 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
827 Args
[n
++] = I
->File
.c_str();
828 Size
+= strlen(Args
[n
-1]);
833 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
835 if((*I
).Pkg
.end() == true)
837 Args
[n
++] = I
->Pkg
.Name();
838 Size
+= strlen(Args
[n
-1]);
844 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
846 for (unsigned int k
= 0; k
!= n
; k
++)
847 clog
<< Args
[k
] << ' ';
856 /* Mask off sig int/quit. We do this because dpkg also does when
857 it forks scripts. What happens is that when you hit ctrl-c it sends
858 it to all processes in the group. Since dpkg ignores the signal
859 it doesn't die but we do! So we must also ignore it */
860 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
861 sighandler_t old_SIGINT
= signal(SIGINT
,SIG_IGN
);
863 // ignore SIGHUP as well (debian #463030)
864 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
871 // FIXME: setup sensible signal handling (*ick*)
873 ioctl(0, TIOCGWINSZ
, (char *)&win
);
874 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
876 const char *s
= _("Can not write log, openpty() "
877 "failed (/dev/pts not mounted?)\n");
878 fprintf(stderr
, "%s",s
);
879 fprintf(term_out
, "%s",s
);
885 rtt
.c_lflag
&= ~ECHO
;
886 // block SIGTTOU during tcsetattr to prevent a hang if
887 // the process is a member of the background process group
888 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
889 sigemptyset(&sigmask
);
890 sigaddset(&sigmask
, SIGTTOU
);
891 sigprocmask(SIG_BLOCK
,&sigmask
, &original_sigmask
);
892 tcsetattr(0, TCSAFLUSH
, &rtt
);
893 sigprocmask(SIG_SETMASK
, &original_sigmask
, 0);
898 _config
->Set("APT::Keep-Fds::",fd
[1]);
899 // send status information that we are about to fork dpkg
900 if(OutStatusFd
> 0) {
901 ostringstream status
;
902 status
<< "pmstatus:dpkg-exec:"
903 << (PackagesDone
/float(PackagesTotal
)*100.0)
904 << ":" << _("Running dpkg")
906 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
913 if(slave
>= 0 && master
>= 0)
916 ioctl(slave
, TIOCSCTTY
, 0);
923 close(fd
[0]); // close the read end of the pipe
925 if (_config
->FindDir("DPkg::Chroot-Directory","/") != "/")
927 std::cerr
<< "Chrooting into "
928 << _config
->FindDir("DPkg::Chroot-Directory")
930 if (chroot(_config
->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
934 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
937 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
940 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
943 // Discard everything in stdin before forking dpkg
944 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
947 while (read(STDIN_FILENO
,&dummy
,1) == 1);
949 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
953 /* No Job Control Stop Env is a magic dpkg var that prevents it
954 from using sigstop */
955 putenv((char *)"DPKG_NO_TSTP=yes");
956 execvp(Args
[0],(char **)Args
);
957 cerr
<< "Could not exec dpkg!" << endl
;
962 if (_config
->FindB("DPkg::UseIoNice", false) == true)
965 // clear the Keep-Fd again
966 _config
->Clear("APT::Keep-Fds",fd
[1]);
971 // we read from dpkg here
972 int const _dpkgin
= fd
[0];
973 close(fd
[1]); // close the write end of the pipe
979 sigemptyset(&sigmask
);
980 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
982 // the result of the waitpid call
985 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
987 // FIXME: move this to a function or something, looks ugly here
988 // error handling, waitpid returned -1
991 RunScripts("DPkg::Post-Invoke");
993 // Restore sig int/quit
994 signal(SIGQUIT
,old_SIGQUIT
);
995 signal(SIGINT
,old_SIGINT
);
996 signal(SIGHUP
,old_SIGHUP
);
997 return _error
->Errno("waitpid","Couldn't wait for subprocess");
1000 // wait for input or output here
1002 if (!stdin_is_dev_null
)
1004 FD_SET(_dpkgin
, &rfds
);
1006 FD_SET(master
, &rfds
);
1009 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
1010 &tv
, &original_sigmask
);
1011 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
1012 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
1013 NULL
, &tv
, &original_sigmask
);
1014 if (select_ret
== 0)
1016 else if (select_ret
< 0 && errno
== EINTR
)
1018 else if (select_ret
< 0)
1020 perror("select() returned error");
1024 if(master
>= 0 && FD_ISSET(master
, &rfds
))
1025 DoTerminalPty(master
);
1026 if(master
>= 0 && FD_ISSET(0, &rfds
))
1028 if(FD_ISSET(_dpkgin
, &rfds
))
1029 DoDpkgStatusFd(_dpkgin
, OutStatusFd
);
1033 // Restore sig int/quit
1034 signal(SIGQUIT
,old_SIGQUIT
);
1035 signal(SIGINT
,old_SIGINT
);
1036 signal(SIGHUP
,old_SIGHUP
);
1040 tcsetattr(0, TCSAFLUSH
, &tt
);
1044 // Check for an error code.
1045 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
1047 // if it was set to "keep-dpkg-runing" then we won't return
1048 // here but keep the loop going and just report it as a error
1050 bool const stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
1053 RunScripts("DPkg::Post-Invoke");
1055 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
1056 _error
->Error("Sub-process %s received a segmentation fault.",Args
[0]);
1057 else if (WIFEXITED(Status
) != 0)
1058 _error
->Error("Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
1060 _error
->Error("Sub-process %s exited unexpectedly",Args
[0]);
1071 if (RunScripts("DPkg::Post-Invoke") == false)
1074 Cache
.writeStateFile(NULL
);
1078 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1079 // ---------------------------------------------------------------------
1081 void pkgDPkgPM::Reset()
1083 List
.erase(List
.begin(),List
.end());