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
));
141 // Use triggers for config calls if we configure "smart"
142 // as otherwise Pre-Depends will not be satisfied, see #526774
143 if (_config
->FindB("DPkg::TriggersPending", false) == true)
144 List
.push_back(Item(Item::TriggersPending
, PkgIterator()));
149 // DPkgPM::Remove - Remove a package /*{{{*/
150 // ---------------------------------------------------------------------
151 /* Add a remove operation to the sequence list */
152 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
154 if (Pkg
.end() == true)
158 List
.push_back(Item(Item::Purge
,Pkg
));
160 List
.push_back(Item(Item::Remove
,Pkg
));
164 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
165 // ---------------------------------------------------------------------
166 /* This is part of the helper script communication interface, it sends
167 very complete information down to the other end of the pipe.*/
168 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
170 fprintf(F
,"VERSION 2\n");
172 /* Write out all of the configuration directives by walking the
173 configuration tree */
174 const Configuration::Item
*Top
= _config
->Tree(0);
177 if (Top
->Value
.empty() == false)
180 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
181 QuoteString(Top
->Value
,"\n").c_str());
190 while (Top
!= 0 && Top
->Next
== 0)
197 // Write out the package actions in order.
198 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
200 if(I
->Pkg
.end() == true)
203 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
205 fprintf(F
,"%s ",I
->Pkg
.Name());
207 if (I
->Pkg
->CurrentVer
== 0)
210 fprintf(F
,"%s ",I
->Pkg
.CurrentVer().VerStr());
212 // Show the compare operator
214 if (S
.InstallVer
!= 0)
217 if (I
->Pkg
->CurrentVer
!= 0)
218 Comp
= S
.InstVerIter(Cache
).CompareVer(I
->Pkg
.CurrentVer());
225 fprintf(F
,"%s ",S
.InstVerIter(Cache
).VerStr());
230 // Show the filename/operation
231 if (I
->Op
== Item::Install
)
234 if (I
->File
[0] != '/')
235 fprintf(F
,"**ERROR**\n");
237 fprintf(F
,"%s\n",I
->File
.c_str());
239 if (I
->Op
== Item::Configure
)
240 fprintf(F
,"**CONFIGURE**\n");
241 if (I
->Op
== Item::Remove
||
242 I
->Op
== Item::Purge
)
243 fprintf(F
,"**REMOVE**\n");
251 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
252 // ---------------------------------------------------------------------
253 /* This looks for a list of scripts to run from the configuration file
254 each one is run and is fed on standard input a list of all .deb files
255 that are due to be installed. */
256 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
258 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
259 if (Opts
== 0 || Opts
->Child
== 0)
263 unsigned int Count
= 1;
264 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
266 if (Opts
->Value
.empty() == true)
269 // Determine the protocol version
270 string OptSec
= Opts
->Value
;
271 string::size_type Pos
;
272 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
273 Pos
= OptSec
.length();
274 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
276 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
280 if (pipe(Pipes
) != 0)
281 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
282 SetCloseExec(Pipes
[0],true);
283 SetCloseExec(Pipes
[1],true);
285 // Purified Fork for running the script
286 pid_t Process
= ExecFork();
290 dup2(Pipes
[0],STDIN_FILENO
);
291 SetCloseExec(STDOUT_FILENO
,false);
292 SetCloseExec(STDIN_FILENO
,false);
293 SetCloseExec(STDERR_FILENO
,false);
298 Args
[2] = Opts
->Value
.c_str();
300 execv(Args
[0],(char **)Args
);
304 FILE *F
= fdopen(Pipes
[1],"w");
306 return _error
->Errno("fdopen","Faild to open new FD");
308 // Feed it the filenames.
312 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
314 // Only deal with packages to be installed from .deb
315 if (I
->Op
!= Item::Install
)
319 if (I
->File
[0] != '/')
322 /* Feed the filename of each package that is pending install
324 fprintf(F
,"%s\n",I
->File
.c_str());
333 Die
= !SendV2Pkgs(F
);
337 // Clean up the sub process
338 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
339 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
346 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
347 // ---------------------------------------------------------------------
350 void pkgDPkgPM::DoStdin(int master
)
352 unsigned char input_buf
[256] = {0,};
353 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
355 write(master
, input_buf
, len
);
357 stdin_is_dev_null
= true;
360 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
361 // ---------------------------------------------------------------------
363 * read the terminal pty and write log
365 void pkgDPkgPM::DoTerminalPty(int master
)
367 unsigned char term_buf
[1024] = {0,0, };
369 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
370 if(len
== -1 && errno
== EIO
)
372 // this happens when the child is about to exit, we
373 // give it time to actually exit, otherwise we run
380 write(1, term_buf
, len
);
382 fwrite(term_buf
, len
, sizeof(char), term_out
);
385 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
386 // ---------------------------------------------------------------------
389 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd
, char *line
)
391 bool const Debug
= _config
->FindB("Debug::pkgDPkgProgressReporting",false);
392 // the status we output
393 ostringstream status
;
396 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
399 /* dpkg sends strings like this:
400 'status: <pkg>: <pkg qstate>'
401 errors look like this:
402 '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
403 and conffile-prompt like this
404 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
406 Newer versions of dpkg sent also:
407 'processing: install: pkg'
408 'processing: configure: pkg'
409 'processing: remove: pkg'
410 'processing: purge: pkg' - but for apt is it a ignored "unknown" action
411 'processing: trigproc: trigger'
415 // dpkg sends multiline error messages sometimes (see
416 // #374195 for a example. we should support this by
417 // either patching dpkg to not send multiline over the
418 // statusfd or by rewriting the code here to deal with
419 // it. for now we just ignore it and not crash
420 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
421 if( list
[0] == NULL
|| list
[1] == NULL
|| list
[2] == NULL
)
424 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
427 const char* const pkg
= list
[1];
428 const char* action
= _strstrip(list
[2]);
430 // 'processing' from dpkg looks like
431 // 'processing: action: pkg'
432 if(strncmp(list
[0], "processing", strlen("processing")) == 0)
435 const char* const pkg_or_trigger
= _strstrip(list
[2]);
436 action
= _strstrip( list
[1]);
437 const std::pair
<const char *, const char *> * const iter
=
438 std::find_if(PackageProcessingOpsBegin
,
439 PackageProcessingOpsEnd
,
440 MatchProcessingOp(action
));
441 if(iter
== PackageProcessingOpsEnd
)
444 std::clog
<< "ignoring unknown action: " << action
<< std::endl
;
447 snprintf(s
, sizeof(s
), _(iter
->second
), pkg_or_trigger
);
449 status
<< "pmstatus:" << pkg_or_trigger
450 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
454 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
456 std::clog
<< "send: '" << status
.str() << "'" << endl
;
460 if(strncmp(action
,"error",strlen("error")) == 0)
462 status
<< "pmerror:" << list
[1]
463 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
467 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
469 std::clog
<< "send: '" << status
.str() << "'" << endl
;
472 else if(strncmp(action
,"conffile",strlen("conffile")) == 0)
474 status
<< "pmconffile:" << list
[1]
475 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
479 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
481 std::clog
<< "send: '" << status
.str() << "'" << endl
;
485 vector
<struct DpkgState
> const &states
= PackageOps
[pkg
];
486 const char *next_action
= NULL
;
487 if(PackageOpsDone
[pkg
] < states
.size())
488 next_action
= states
[PackageOpsDone
[pkg
]].state
;
489 // check if the package moved to the next dpkg state
490 if(next_action
&& (strcmp(action
, next_action
) == 0))
492 // only read the translation if there is actually a next
494 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
496 snprintf(s
, sizeof(s
), translation
, pkg
);
498 // we moved from one dpkg state to a new one, report that
499 PackageOpsDone
[pkg
]++;
501 // build the status str
502 status
<< "pmstatus:" << pkg
503 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
507 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
509 std::clog
<< "send: '" << status
.str() << "'" << endl
;
512 std::clog
<< "(parsed from dpkg) pkg: " << pkg
513 << " action: " << action
<< endl
;
516 // DPkgPM::DoDpkgStatusFd /*{{{*/
517 // ---------------------------------------------------------------------
520 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
, int OutStatusFd
)
525 len
=read(statusfd
, &dpkgbuf
[dpkgbuf_pos
], sizeof(dpkgbuf
)-dpkgbuf_pos
);
530 // process line by line if we have a buffer
532 while((q
=(char*)memchr(p
, '\n', dpkgbuf
+dpkgbuf_pos
-p
)) != NULL
)
535 ProcessDpkgStatusLine(OutStatusFd
, p
);
536 p
=q
+1; // continue with next line
539 // now move the unprocessed bits (after the final \n that is now a 0x0)
540 // to the start and update dpkgbuf_pos
541 p
= (char*)memrchr(dpkgbuf
, 0, dpkgbuf_pos
);
545 // we are interessted in the first char *after* 0x0
548 // move the unprocessed tail to the start and update pos
549 memmove(dpkgbuf
, p
, p
-dpkgbuf
);
550 dpkgbuf_pos
= dpkgbuf
+dpkgbuf_pos
-p
;
553 // DPkgPM::OpenLog /*{{{*/
554 bool pkgDPkgPM::OpenLog()
556 string logdir
= _config
->FindDir("Dir::Log");
557 if(not FileExists(logdir
))
558 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
559 string logfile_name
= flCombine(logdir
,
560 _config
->Find("Dir::Log::Terminal"));
561 if (!logfile_name
.empty())
563 term_out
= fopen(logfile_name
.c_str(),"a");
564 chmod(logfile_name
.c_str(), 0600);
565 // output current time
567 time_t t
= time(NULL
);
568 struct tm
*tmp
= localtime(&t
);
569 strftime(outstr
, sizeof(outstr
), "%F %T", tmp
);
570 fprintf(term_out
, "\nLog started: ");
571 fprintf(term_out
, "%s", outstr
);
572 fprintf(term_out
, "\n");
577 // DPkg::CloseLog /*{{{*/
578 bool pkgDPkgPM::CloseLog()
583 time_t t
= time(NULL
);
584 struct tm
*tmp
= localtime(&t
);
585 strftime(outstr
, sizeof(outstr
), "%F %T", tmp
);
586 fprintf(term_out
, "Log ended: ");
587 fprintf(term_out
, "%s", outstr
);
588 fprintf(term_out
, "\n");
596 // This implements a racy version of pselect for those architectures
597 // that don't have a working implementation.
598 // FIXME: Probably can be removed on Lenny+1
599 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
600 fd_set
*exceptfds
, const struct timespec
*timeout
,
601 const sigset_t
*sigmask
)
607 tv
.tv_sec
= timeout
->tv_sec
;
608 tv
.tv_usec
= timeout
->tv_nsec
/1000;
610 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
611 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
612 sigprocmask(SIG_SETMASK
, &origmask
, 0);
616 // DPkgPM::Go - Run the sequence /*{{{*/
617 // ---------------------------------------------------------------------
618 /* This globs the operations and calls dpkg
620 * If it is called with "OutStatusFd" set to a valid file descriptor
621 * apt will report the install progress over this fd. It maps the
622 * dpkg states a package goes through to human readable (and i10n-able)
623 * names and calculates a percentage for each step.
625 bool pkgDPkgPM::Go(int OutStatusFd
)
630 sigset_t original_sigmask
;
632 unsigned int const MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
633 unsigned int const MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
634 bool const NoTriggers
= _config
->FindB("DPkg::NoTriggers", false);
636 if (RunScripts("DPkg::Pre-Invoke") == false)
639 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
642 // support subpressing of triggers processing for special
643 // cases like d-i that runs the triggers handling manually
644 bool const SmartConf
= (_config
->Find("PackageManager::Configure", "all") != "all");
645 bool const TriggersPending
= _config
->FindB("DPkg::TriggersPending", false);
646 if (_config
->FindB("DPkg::ConfigurePending", SmartConf
) == true)
647 List
.push_back(Item(Item::ConfigurePending
, PkgIterator()));
649 // map the dpkg states to the operations that are performed
650 // (this is sorted in the same way as Item::Ops)
651 static const struct DpkgState DpkgStatesOpMap
[][7] = {
654 {"half-installed", N_("Preparing %s")},
655 {"unpacked", N_("Unpacking %s") },
658 // Configure operation
660 {"unpacked",N_("Preparing to configure %s") },
661 {"half-configured", N_("Configuring %s") },
662 { "installed", N_("Installed %s")},
667 {"half-configured", N_("Preparing for removal of %s")},
668 {"half-installed", N_("Removing %s")},
669 {"config-files", N_("Removed %s")},
674 {"config-files", N_("Preparing to completely remove %s")},
675 {"not-installed", N_("Completely removed %s")},
680 // init the PackageOps map, go over the list of packages that
681 // that will be [installed|configured|removed|purged] and add
682 // them to the PackageOps map (the dpkg states it goes through)
683 // and the PackageOpsTranslations (human readable strings)
684 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();I
++)
686 if((*I
).Pkg
.end() == true)
689 string
const name
= (*I
).Pkg
.Name();
690 PackageOpsDone
[name
] = 0;
691 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; i
++)
693 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
698 stdin_is_dev_null
= false;
703 // this loop is runs once per operation
704 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();)
706 // Do all actions with the same Op in one run
707 vector
<Item
>::const_iterator J
= I
;
708 if (TriggersPending
== true)
709 for (; J
!= List
.end(); J
++)
713 if (J
->Op
!= Item::TriggersPending
)
715 vector
<Item
>::const_iterator T
= J
+ 1;
716 if (T
!= List
.end() && T
->Op
== I
->Op
)
721 for (; J
!= List
.end() && J
->Op
== I
->Op
; J
++)
724 // Generate the argument list
725 const char *Args
[MaxArgs
+ 50];
727 // Now check if we are within the MaxArgs limit
729 // this code below is problematic, because it may happen that
730 // the argument list is split in a way that A depends on B
731 // and they are in the same "--configure A B" run
732 // - with the split they may now be configured in different
734 if (J
- I
> (signed)MaxArgs
)
738 unsigned long Size
= 0;
739 string
const Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
740 Args
[n
++] = Tmp
.c_str();
741 Size
+= strlen(Args
[n
-1]);
743 // Stick in any custom dpkg options
744 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
748 for (; Opts
!= 0; Opts
= Opts
->Next
)
750 if (Opts
->Value
.empty() == true)
752 Args
[n
++] = Opts
->Value
.c_str();
753 Size
+= Opts
->Value
.length();
757 char status_fd_buf
[20];
761 Args
[n
++] = "--status-fd";
762 Size
+= strlen(Args
[n
-1]);
763 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
764 Args
[n
++] = status_fd_buf
;
765 Size
+= strlen(Args
[n
-1]);
770 Args
[n
++] = "--force-depends";
771 Size
+= strlen(Args
[n
-1]);
772 Args
[n
++] = "--force-remove-essential";
773 Size
+= strlen(Args
[n
-1]);
774 Args
[n
++] = "--remove";
775 Size
+= strlen(Args
[n
-1]);
779 Args
[n
++] = "--force-depends";
780 Size
+= strlen(Args
[n
-1]);
781 Args
[n
++] = "--force-remove-essential";
782 Size
+= strlen(Args
[n
-1]);
783 Args
[n
++] = "--purge";
784 Size
+= strlen(Args
[n
-1]);
787 case Item::Configure
:
788 Args
[n
++] = "--configure";
789 Size
+= strlen(Args
[n
-1]);
792 case Item::ConfigurePending
:
793 Args
[n
++] = "--configure";
794 Size
+= strlen(Args
[n
-1]);
795 Args
[n
++] = "--pending";
796 Size
+= strlen(Args
[n
-1]);
799 case Item::TriggersPending
:
800 Args
[n
++] = "--triggers-only";
801 Size
+= strlen(Args
[n
-1]);
802 Args
[n
++] = "--pending";
803 Size
+= strlen(Args
[n
-1]);
807 Args
[n
++] = "--unpack";
808 Size
+= strlen(Args
[n
-1]);
809 Args
[n
++] = "--auto-deconfigure";
810 Size
+= strlen(Args
[n
-1]);
814 if (NoTriggers
== true && I
->Op
!= Item::TriggersPending
&&
815 I
->Op
!= Item::ConfigurePending
)
817 Args
[n
++] = "--no-triggers";
818 Size
+= strlen(Args
[n
-1]);
821 // Write in the file or package names
822 if (I
->Op
== Item::Install
)
824 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
826 if (I
->File
[0] != '/')
827 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
828 Args
[n
++] = I
->File
.c_str();
829 Size
+= strlen(Args
[n
-1]);
834 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
836 if((*I
).Pkg
.end() == true)
838 Args
[n
++] = I
->Pkg
.Name();
839 Size
+= strlen(Args
[n
-1]);
845 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
847 for (unsigned int k
= 0; k
!= n
; k
++)
848 clog
<< Args
[k
] << ' ';
857 /* Mask off sig int/quit. We do this because dpkg also does when
858 it forks scripts. What happens is that when you hit ctrl-c it sends
859 it to all processes in the group. Since dpkg ignores the signal
860 it doesn't die but we do! So we must also ignore it */
861 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
862 sighandler_t old_SIGINT
= signal(SIGINT
,SIG_IGN
);
864 // ignore SIGHUP as well (debian #463030)
865 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
872 // if tcgetattr does not return zero there was a error
873 // and we do not do any pty magic
874 if (tcgetattr(0, &tt
) == 0)
876 ioctl(0, TIOCGWINSZ
, (char *)&win
);
877 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
879 const char *s
= _("Can not write log, openpty() "
880 "failed (/dev/pts not mounted?)\n");
881 fprintf(stderr
, "%s",s
);
883 fprintf(term_out
, "%s",s
);
889 rtt
.c_lflag
&= ~ECHO
;
890 // block SIGTTOU during tcsetattr to prevent a hang if
891 // the process is a member of the background process group
892 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
893 sigemptyset(&sigmask
);
894 sigaddset(&sigmask
, SIGTTOU
);
895 sigprocmask(SIG_BLOCK
,&sigmask
, &original_sigmask
);
896 tcsetattr(0, TCSAFLUSH
, &rtt
);
897 sigprocmask(SIG_SETMASK
, &original_sigmask
, 0);
903 _config
->Set("APT::Keep-Fds::",fd
[1]);
904 // send status information that we are about to fork dpkg
905 if(OutStatusFd
> 0) {
906 ostringstream status
;
907 status
<< "pmstatus:dpkg-exec:"
908 << (PackagesDone
/float(PackagesTotal
)*100.0)
909 << ":" << _("Running dpkg")
911 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
918 if(slave
>= 0 && master
>= 0)
921 ioctl(slave
, TIOCSCTTY
, 0);
928 close(fd
[0]); // close the read end of the pipe
930 if (_config
->FindDir("DPkg::Chroot-Directory","/") != "/")
932 std::cerr
<< "Chrooting into "
933 << _config
->FindDir("DPkg::Chroot-Directory")
935 if (chroot(_config
->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
939 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
942 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
945 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
948 // Discard everything in stdin before forking dpkg
949 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
952 while (read(STDIN_FILENO
,&dummy
,1) == 1);
954 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
958 /* No Job Control Stop Env is a magic dpkg var that prevents it
959 from using sigstop */
960 putenv((char *)"DPKG_NO_TSTP=yes");
961 execvp(Args
[0],(char **)Args
);
962 cerr
<< "Could not exec dpkg!" << endl
;
967 if (_config
->FindB("DPkg::UseIoNice", false) == true)
970 // clear the Keep-Fd again
971 _config
->Clear("APT::Keep-Fds",fd
[1]);
976 // we read from dpkg here
977 int const _dpkgin
= fd
[0];
978 close(fd
[1]); // close the write end of the pipe
984 sigemptyset(&sigmask
);
985 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
987 // the result of the waitpid call
990 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
992 // FIXME: move this to a function or something, looks ugly here
993 // error handling, waitpid returned -1
996 RunScripts("DPkg::Post-Invoke");
998 // Restore sig int/quit
999 signal(SIGQUIT
,old_SIGQUIT
);
1000 signal(SIGINT
,old_SIGINT
);
1001 signal(SIGHUP
,old_SIGHUP
);
1002 return _error
->Errno("waitpid","Couldn't wait for subprocess");
1005 // wait for input or output here
1007 if (!stdin_is_dev_null
)
1009 FD_SET(_dpkgin
, &rfds
);
1011 FD_SET(master
, &rfds
);
1014 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
1015 &tv
, &original_sigmask
);
1016 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
1017 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
1018 NULL
, &tv
, &original_sigmask
);
1019 if (select_ret
== 0)
1021 else if (select_ret
< 0 && errno
== EINTR
)
1023 else if (select_ret
< 0)
1025 perror("select() returned error");
1029 if(master
>= 0 && FD_ISSET(master
, &rfds
))
1030 DoTerminalPty(master
);
1031 if(master
>= 0 && FD_ISSET(0, &rfds
))
1033 if(FD_ISSET(_dpkgin
, &rfds
))
1034 DoDpkgStatusFd(_dpkgin
, OutStatusFd
);
1038 // Restore sig int/quit
1039 signal(SIGQUIT
,old_SIGQUIT
);
1040 signal(SIGINT
,old_SIGINT
);
1041 signal(SIGHUP
,old_SIGHUP
);
1045 tcsetattr(0, TCSAFLUSH
, &tt
);
1049 // Check for an error code.
1050 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
1052 // if it was set to "keep-dpkg-runing" then we won't return
1053 // here but keep the loop going and just report it as a error
1055 bool const stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
1058 RunScripts("DPkg::Post-Invoke");
1060 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
1061 _error
->Error("Sub-process %s received a segmentation fault.",Args
[0]);
1062 else if (WIFEXITED(Status
) != 0)
1063 _error
->Error("Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
1065 _error
->Error("Sub-process %s exited unexpectedly",Args
[0]);
1076 if (RunScripts("DPkg::Post-Invoke") == false)
1079 Cache
.writeStateFile(NULL
);
1083 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1084 // ---------------------------------------------------------------------
1086 void pkgDPkgPM::Reset()
1088 List
.erase(List
.begin(),List
.end());