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 bool static const NoConfigure
= _config
->FindB("DPkg::NoConfigure",false);
139 if (NoConfigure
== false)
140 List
.push_back(Item(Item::Configure
,Pkg
));
145 // DPkgPM::Remove - Remove a package /*{{{*/
146 // ---------------------------------------------------------------------
147 /* Add a remove operation to the sequence list */
148 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
150 if (Pkg
.end() == true)
154 List
.push_back(Item(Item::Purge
,Pkg
));
156 List
.push_back(Item(Item::Remove
,Pkg
));
160 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
161 // ---------------------------------------------------------------------
162 /* This is part of the helper script communication interface, it sends
163 very complete information down to the other end of the pipe.*/
164 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
166 fprintf(F
,"VERSION 2\n");
168 /* Write out all of the configuration directives by walking the
169 configuration tree */
170 const Configuration::Item
*Top
= _config
->Tree(0);
173 if (Top
->Value
.empty() == false)
176 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
177 QuoteString(Top
->Value
,"\n").c_str());
186 while (Top
!= 0 && Top
->Next
== 0)
193 // Write out the package actions in order.
194 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
196 if(I
->Pkg
.end() == true)
199 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
201 fprintf(F
,"%s ",I
->Pkg
.Name());
203 if (I
->Pkg
->CurrentVer
== 0)
206 fprintf(F
,"%s ",I
->Pkg
.CurrentVer().VerStr());
208 // Show the compare operator
210 if (S
.InstallVer
!= 0)
213 if (I
->Pkg
->CurrentVer
!= 0)
214 Comp
= S
.InstVerIter(Cache
).CompareVer(I
->Pkg
.CurrentVer());
221 fprintf(F
,"%s ",S
.InstVerIter(Cache
).VerStr());
226 // Show the filename/operation
227 if (I
->Op
== Item::Install
)
230 if (I
->File
[0] != '/')
231 fprintf(F
,"**ERROR**\n");
233 fprintf(F
,"%s\n",I
->File
.c_str());
235 if (I
->Op
== Item::Configure
)
236 fprintf(F
,"**CONFIGURE**\n");
237 if (I
->Op
== Item::Remove
||
238 I
->Op
== Item::Purge
)
239 fprintf(F
,"**REMOVE**\n");
247 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
248 // ---------------------------------------------------------------------
249 /* This looks for a list of scripts to run from the configuration file
250 each one is run and is fed on standard input a list of all .deb files
251 that are due to be installed. */
252 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
254 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
255 if (Opts
== 0 || Opts
->Child
== 0)
259 unsigned int Count
= 1;
260 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
262 if (Opts
->Value
.empty() == true)
265 // Determine the protocol version
266 string OptSec
= Opts
->Value
;
267 string::size_type Pos
;
268 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
269 Pos
= OptSec
.length();
270 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
272 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
276 if (pipe(Pipes
) != 0)
277 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
278 SetCloseExec(Pipes
[0],true);
279 SetCloseExec(Pipes
[1],true);
281 // Purified Fork for running the script
282 pid_t Process
= ExecFork();
286 dup2(Pipes
[0],STDIN_FILENO
);
287 SetCloseExec(STDOUT_FILENO
,false);
288 SetCloseExec(STDIN_FILENO
,false);
289 SetCloseExec(STDERR_FILENO
,false);
294 Args
[2] = Opts
->Value
.c_str();
296 execv(Args
[0],(char **)Args
);
300 FILE *F
= fdopen(Pipes
[1],"w");
302 return _error
->Errno("fdopen","Faild to open new FD");
304 // Feed it the filenames.
308 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
310 // Only deal with packages to be installed from .deb
311 if (I
->Op
!= Item::Install
)
315 if (I
->File
[0] != '/')
318 /* Feed the filename of each package that is pending install
320 fprintf(F
,"%s\n",I
->File
.c_str());
329 Die
= !SendV2Pkgs(F
);
333 // Clean up the sub process
334 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
335 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
342 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
343 // ---------------------------------------------------------------------
346 void pkgDPkgPM::DoStdin(int master
)
348 unsigned char input_buf
[256] = {0,};
349 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
351 write(master
, input_buf
, len
);
353 stdin_is_dev_null
= true;
356 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
357 // ---------------------------------------------------------------------
359 * read the terminal pty and write log
361 void pkgDPkgPM::DoTerminalPty(int master
)
363 unsigned char term_buf
[1024] = {0,0, };
365 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
366 if(len
== -1 && errno
== EIO
)
368 // this happens when the child is about to exit, we
369 // give it time to actually exit, otherwise we run
376 write(1, term_buf
, len
);
378 fwrite(term_buf
, len
, sizeof(char), term_out
);
381 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
382 // ---------------------------------------------------------------------
385 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd
, char *line
)
387 bool const Debug
= _config
->FindB("Debug::pkgDPkgProgressReporting",false);
388 // the status we output
389 ostringstream status
;
392 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
395 /* dpkg sends strings like this:
396 'status: <pkg>: <pkg qstate>'
397 errors look like this:
398 '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
399 and conffile-prompt like this
400 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
402 Newer versions of dpkg sent also:
403 'processing: install: pkg'
404 'processing: configure: pkg'
405 'processing: remove: pkg'
406 'processing: purge: pkg' - but for apt is it a ignored "unknown" action
407 'processing: trigproc: trigger'
411 // dpkg sends multiline error messages sometimes (see
412 // #374195 for a example. we should support this by
413 // either patching dpkg to not send multiline over the
414 // statusfd or by rewriting the code here to deal with
415 // it. for now we just ignore it and not crash
416 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
417 if( list
[0] == NULL
|| list
[1] == NULL
|| list
[2] == NULL
)
420 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
423 const char* const pkg
= list
[1];
424 const char* action
= _strstrip(list
[2]);
426 // 'processing' from dpkg looks like
427 // 'processing: action: pkg'
428 if(strncmp(list
[0], "processing", strlen("processing")) == 0)
431 const char* const pkg_or_trigger
= _strstrip(list
[2]);
432 action
= _strstrip( list
[1]);
433 const std::pair
<const char *, const char *> * const iter
=
434 std::find_if(PackageProcessingOpsBegin
,
435 PackageProcessingOpsEnd
,
436 MatchProcessingOp(action
));
437 if(iter
== PackageProcessingOpsEnd
)
440 std::clog
<< "ignoring unknown action: " << action
<< std::endl
;
443 snprintf(s
, sizeof(s
), _(iter
->second
), pkg_or_trigger
);
445 status
<< "pmstatus:" << pkg_or_trigger
446 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
450 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
452 std::clog
<< "send: '" << status
.str() << "'" << endl
;
456 if(strncmp(action
,"error",strlen("error")) == 0)
458 status
<< "pmerror:" << list
[1]
459 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
463 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
465 std::clog
<< "send: '" << status
.str() << "'" << endl
;
468 else if(strncmp(action
,"conffile",strlen("conffile")) == 0)
470 status
<< "pmconffile:" << list
[1]
471 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
475 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
477 std::clog
<< "send: '" << status
.str() << "'" << endl
;
481 vector
<struct DpkgState
> const &states
= PackageOps
[pkg
];
482 const char *next_action
= NULL
;
483 if(PackageOpsDone
[pkg
] < states
.size())
484 next_action
= states
[PackageOpsDone
[pkg
]].state
;
485 // check if the package moved to the next dpkg state
486 if(next_action
&& (strcmp(action
, next_action
) == 0))
488 // only read the translation if there is actually a next
490 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
492 snprintf(s
, sizeof(s
), translation
, pkg
);
494 // we moved from one dpkg state to a new one, report that
495 PackageOpsDone
[pkg
]++;
497 // build the status str
498 status
<< "pmstatus:" << pkg
499 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
503 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
505 std::clog
<< "send: '" << status
.str() << "'" << endl
;
508 std::clog
<< "(parsed from dpkg) pkg: " << pkg
509 << " action: " << action
<< endl
;
512 // DPkgPM::DoDpkgStatusFd /*{{{*/
513 // ---------------------------------------------------------------------
516 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
, int OutStatusFd
)
521 len
=read(statusfd
, &dpkgbuf
[dpkgbuf_pos
], sizeof(dpkgbuf
)-dpkgbuf_pos
);
526 // process line by line if we have a buffer
528 while((q
=(char*)memchr(p
, '\n', dpkgbuf
+dpkgbuf_pos
-p
)) != NULL
)
531 ProcessDpkgStatusLine(OutStatusFd
, p
);
532 p
=q
+1; // continue with next line
535 // now move the unprocessed bits (after the final \n that is now a 0x0)
536 // to the start and update dpkgbuf_pos
537 p
= (char*)memrchr(dpkgbuf
, 0, dpkgbuf_pos
);
541 // we are interessted in the first char *after* 0x0
544 // move the unprocessed tail to the start and update pos
545 memmove(dpkgbuf
, p
, p
-dpkgbuf
);
546 dpkgbuf_pos
= dpkgbuf
+dpkgbuf_pos
-p
;
549 // DPkgPM::OpenLog /*{{{*/
550 bool pkgDPkgPM::OpenLog()
552 string logdir
= _config
->FindDir("Dir::Log");
553 if(not FileExists(logdir
))
554 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
555 string logfile_name
= flCombine(logdir
,
556 _config
->Find("Dir::Log::Terminal"));
557 if (!logfile_name
.empty())
559 term_out
= fopen(logfile_name
.c_str(),"a");
560 chmod(logfile_name
.c_str(), 0600);
561 // output current time
563 time_t t
= time(NULL
);
564 struct tm
*tmp
= localtime(&t
);
565 strftime(outstr
, sizeof(outstr
), "%F %T", tmp
);
566 fprintf(term_out
, "\nLog started: ");
567 fprintf(term_out
, "%s", outstr
);
568 fprintf(term_out
, "\n");
573 // DPkg::CloseLog /*{{{*/
574 bool pkgDPkgPM::CloseLog()
579 time_t t
= time(NULL
);
580 struct tm
*tmp
= localtime(&t
);
581 strftime(outstr
, sizeof(outstr
), "%F %T", tmp
);
582 fprintf(term_out
, "Log ended: ");
583 fprintf(term_out
, "%s", outstr
);
584 fprintf(term_out
, "\n");
592 // This implements a racy version of pselect for those architectures
593 // that don't have a working implementation.
594 // FIXME: Probably can be removed on Lenny+1
595 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
596 fd_set
*exceptfds
, const struct timespec
*timeout
,
597 const sigset_t
*sigmask
)
603 tv
.tv_sec
= timeout
->tv_sec
;
604 tv
.tv_usec
= timeout
->tv_nsec
/1000;
606 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
607 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
608 sigprocmask(SIG_SETMASK
, &origmask
, 0);
612 // DPkgPM::Go - Run the sequence /*{{{*/
613 // ---------------------------------------------------------------------
614 /* This globs the operations and calls dpkg
616 * If it is called with "OutStatusFd" set to a valid file descriptor
617 * apt will report the install progress over this fd. It maps the
618 * dpkg states a package goes through to human readable (and i10n-able)
619 * names and calculates a percentage for each step.
621 bool pkgDPkgPM::Go(int OutStatusFd
)
626 sigset_t original_sigmask
;
628 unsigned int const MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
629 unsigned int const MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
630 bool const NoTriggers
= _config
->FindB("DPkg::NoTriggers",false);
632 if (RunScripts("DPkg::Pre-Invoke") == false)
635 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
638 // support subpressing of triggers processing for special
639 // cases like d-i that runs the triggers handling manually
640 if(_config
->FindB("DPkg::ConfigurePending",_config
->FindB("DPkg::NoConfigure",false)) == true)
641 List
.push_back(Item(Item::ConfigurePending
,PkgIterator()));
643 // map the dpkg states to the operations that are performed
644 // (this is sorted in the same way as Item::Ops)
645 static const struct DpkgState DpkgStatesOpMap
[][7] = {
648 {"half-installed", N_("Preparing %s")},
649 {"unpacked", N_("Unpacking %s") },
652 // Configure operation
654 {"unpacked",N_("Preparing to configure %s") },
655 {"half-configured", N_("Configuring %s") },
656 { "installed", N_("Installed %s")},
661 {"half-configured", N_("Preparing for removal of %s")},
662 {"half-installed", N_("Removing %s")},
663 {"config-files", N_("Removed %s")},
668 {"config-files", N_("Preparing to completely remove %s")},
669 {"not-installed", N_("Completely removed %s")},
674 // init the PackageOps map, go over the list of packages that
675 // that will be [installed|configured|removed|purged] and add
676 // them to the PackageOps map (the dpkg states it goes through)
677 // and the PackageOpsTranslations (human readable strings)
678 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();I
++)
680 if((*I
).Pkg
.end() == true)
683 string
const name
= (*I
).Pkg
.Name();
684 PackageOpsDone
[name
] = 0;
685 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; i
++)
687 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
692 stdin_is_dev_null
= false;
697 // this loop is runs once per operation
698 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();)
700 vector
<Item
>::const_iterator J
= I
;
701 for (; J
!= List
.end() && J
->Op
== I
->Op
; J
++)
704 // Generate the argument list
705 const char *Args
[MaxArgs
+ 50];
707 // Now check if we are within the MaxArgs limit
709 // this code below is problematic, because it may happen that
710 // the argument list is split in a way that A depends on B
711 // and they are in the same "--configure A B" run
712 // - with the split they may now be configured in different
714 if (J
- I
> (signed)MaxArgs
)
718 unsigned long Size
= 0;
719 string
const Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
720 Args
[n
++] = Tmp
.c_str();
721 Size
+= strlen(Args
[n
-1]);
723 // Stick in any custom dpkg options
724 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
728 for (; Opts
!= 0; Opts
= Opts
->Next
)
730 if (Opts
->Value
.empty() == true)
732 Args
[n
++] = Opts
->Value
.c_str();
733 Size
+= Opts
->Value
.length();
737 char status_fd_buf
[20];
741 Args
[n
++] = "--status-fd";
742 Size
+= strlen(Args
[n
-1]);
743 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
744 Args
[n
++] = status_fd_buf
;
745 Size
+= strlen(Args
[n
-1]);
750 Args
[n
++] = "--force-depends";
751 Size
+= strlen(Args
[n
-1]);
752 Args
[n
++] = "--force-remove-essential";
753 Size
+= strlen(Args
[n
-1]);
754 Args
[n
++] = "--remove";
755 Size
+= strlen(Args
[n
-1]);
759 Args
[n
++] = "--force-depends";
760 Size
+= strlen(Args
[n
-1]);
761 Args
[n
++] = "--force-remove-essential";
762 Size
+= strlen(Args
[n
-1]);
763 Args
[n
++] = "--purge";
764 Size
+= strlen(Args
[n
-1]);
767 case Item::Configure
:
768 Args
[n
++] = "--configure";
769 Size
+= strlen(Args
[n
-1]);
772 case Item::ConfigurePending
:
773 Args
[n
++] = "--configure";
774 Size
+= strlen(Args
[n
-1]);
775 Args
[n
++] = "--pending";
776 Size
+= strlen(Args
[n
-1]);
780 Args
[n
++] = "--unpack";
781 Size
+= strlen(Args
[n
-1]);
782 Args
[n
++] = "--auto-deconfigure";
783 Size
+= strlen(Args
[n
-1]);
787 if (NoTriggers
== true && I
->Op
!= Item::ConfigurePending
)
789 Args
[n
++] = "--no-triggers";
790 Size
+= strlen(Args
[n
-1]);
793 // Write in the file or package names
794 if (I
->Op
== Item::Install
)
796 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
798 if (I
->File
[0] != '/')
799 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
800 Args
[n
++] = I
->File
.c_str();
801 Size
+= strlen(Args
[n
-1]);
806 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
808 if((*I
).Pkg
.end() == true)
810 Args
[n
++] = I
->Pkg
.Name();
811 Size
+= strlen(Args
[n
-1]);
817 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
819 for (unsigned int k
= 0; k
!= n
; k
++)
820 clog
<< Args
[k
] << ' ';
829 /* Mask off sig int/quit. We do this because dpkg also does when
830 it forks scripts. What happens is that when you hit ctrl-c it sends
831 it to all processes in the group. Since dpkg ignores the signal
832 it doesn't die but we do! So we must also ignore it */
833 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
834 sighandler_t old_SIGINT
= signal(SIGINT
,SIG_IGN
);
836 // ignore SIGHUP as well (debian #463030)
837 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
844 // FIXME: setup sensible signal handling (*ick*)
846 ioctl(0, TIOCGWINSZ
, (char *)&win
);
847 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
849 const char *s
= _("Can not write log, openpty() "
850 "failed (/dev/pts not mounted?)\n");
851 fprintf(stderr
, "%s",s
);
852 fprintf(term_out
, "%s",s
);
858 rtt
.c_lflag
&= ~ECHO
;
859 // block SIGTTOU during tcsetattr to prevent a hang if
860 // the process is a member of the background process group
861 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
862 sigemptyset(&sigmask
);
863 sigaddset(&sigmask
, SIGTTOU
);
864 sigprocmask(SIG_BLOCK
,&sigmask
, &original_sigmask
);
865 tcsetattr(0, TCSAFLUSH
, &rtt
);
866 sigprocmask(SIG_SETMASK
, &original_sigmask
, 0);
871 _config
->Set("APT::Keep-Fds::",fd
[1]);
872 // send status information that we are about to fork dpkg
873 if(OutStatusFd
> 0) {
874 ostringstream status
;
875 status
<< "pmstatus:dpkg-exec:"
876 << (PackagesDone
/float(PackagesTotal
)*100.0)
877 << ":" << _("Running dpkg")
879 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
886 if(slave
>= 0 && master
>= 0)
889 ioctl(slave
, TIOCSCTTY
, 0);
896 close(fd
[0]); // close the read end of the pipe
898 if (_config
->FindDir("DPkg::Chroot-Directory","/") != "/")
900 std::cerr
<< "Chrooting into "
901 << _config
->FindDir("DPkg::Chroot-Directory")
903 if (chroot(_config
->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
907 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
910 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
913 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
916 // Discard everything in stdin before forking dpkg
917 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
920 while (read(STDIN_FILENO
,&dummy
,1) == 1);
922 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
926 /* No Job Control Stop Env is a magic dpkg var that prevents it
927 from using sigstop */
928 putenv((char *)"DPKG_NO_TSTP=yes");
929 execvp(Args
[0],(char **)Args
);
930 cerr
<< "Could not exec dpkg!" << endl
;
935 if (_config
->FindB("DPkg::UseIoNice", false) == true)
938 // clear the Keep-Fd again
939 _config
->Clear("APT::Keep-Fds",fd
[1]);
944 // we read from dpkg here
945 int const _dpkgin
= fd
[0];
946 close(fd
[1]); // close the write end of the pipe
952 sigemptyset(&sigmask
);
953 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
955 // the result of the waitpid call
958 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
960 // FIXME: move this to a function or something, looks ugly here
961 // error handling, waitpid returned -1
964 RunScripts("DPkg::Post-Invoke");
966 // Restore sig int/quit
967 signal(SIGQUIT
,old_SIGQUIT
);
968 signal(SIGINT
,old_SIGINT
);
969 signal(SIGHUP
,old_SIGHUP
);
970 return _error
->Errno("waitpid","Couldn't wait for subprocess");
973 // wait for input or output here
975 if (!stdin_is_dev_null
)
977 FD_SET(_dpkgin
, &rfds
);
979 FD_SET(master
, &rfds
);
982 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
983 &tv
, &original_sigmask
);
984 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
985 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
986 NULL
, &tv
, &original_sigmask
);
989 else if (select_ret
< 0 && errno
== EINTR
)
991 else if (select_ret
< 0)
993 perror("select() returned error");
997 if(master
>= 0 && FD_ISSET(master
, &rfds
))
998 DoTerminalPty(master
);
999 if(master
>= 0 && FD_ISSET(0, &rfds
))
1001 if(FD_ISSET(_dpkgin
, &rfds
))
1002 DoDpkgStatusFd(_dpkgin
, OutStatusFd
);
1006 // Restore sig int/quit
1007 signal(SIGQUIT
,old_SIGQUIT
);
1008 signal(SIGINT
,old_SIGINT
);
1009 signal(SIGHUP
,old_SIGHUP
);
1013 tcsetattr(0, TCSAFLUSH
, &tt
);
1017 // Check for an error code.
1018 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
1020 // if it was set to "keep-dpkg-runing" then we won't return
1021 // here but keep the loop going and just report it as a error
1023 bool const stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
1026 RunScripts("DPkg::Post-Invoke");
1028 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
1029 _error
->Error("Sub-process %s received a segmentation fault.",Args
[0]);
1030 else if (WIFEXITED(Status
) != 0)
1031 _error
->Error("Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
1033 _error
->Error("Sub-process %s exited unexpectedly",Args
[0]);
1044 if (RunScripts("DPkg::Post-Invoke") == false)
1047 Cache
.writeStateFile(NULL
);
1051 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1052 // ---------------------------------------------------------------------
1054 void pkgDPkgPM::Reset()
1056 List
.erase(List
.begin(),List
.end());