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/pkgrecords.h>
16 #include <apt-pkg/strutl.h>
18 #include <apt-pkg/fileutl.h>
23 #include <sys/select.h>
24 #include <sys/types.h>
37 #include <sys/ioctl.h>
48 // Maps the dpkg "processing" info to human readable names. Entry 0
49 // of each array is the key, entry 1 is the value.
50 const std::pair
<const char *, const char *> PackageProcessingOps
[] = {
51 std::make_pair("install", N_("Installing %s")),
52 std::make_pair("configure", N_("Configuring %s")),
53 std::make_pair("remove", N_("Removing %s")),
54 std::make_pair("trigproc", N_("Running post-installation trigger %s"))
57 const std::pair
<const char *, const char *> * const PackageProcessingOpsBegin
= PackageProcessingOps
;
58 const std::pair
<const char *, const char *> * const PackageProcessingOpsEnd
= PackageProcessingOps
+ sizeof(PackageProcessingOps
) / sizeof(PackageProcessingOps
[0]);
60 // Predicate to test whether an entry in the PackageProcessingOps
61 // array matches a string.
62 class MatchProcessingOp
67 MatchProcessingOp(const char *the_target
)
72 bool operator()(const std::pair
<const char *, const char *> &pair
) const
74 return strcmp(pair
.first
, target
) == 0;
79 /* helper function to ionice the given PID
81 there is no C header for ionice yet - just the syscall interface
82 so we use the binary from util-linux
87 if (!FileExists("/usr/bin/ionice"))
89 pid_t Process
= ExecFork();
93 snprintf(buf
, sizeof(buf
), "-p%d", PID
);
95 Args
[0] = "/usr/bin/ionice";
99 execv(Args
[0], (char **)Args
);
101 return ExecWait(Process
, "ionice");
104 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
105 // ---------------------------------------------------------------------
107 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
108 : pkgPackageManager(Cache
), dpkgbuf_pos(0),
109 term_out(NULL
), PackagesDone(0), PackagesTotal(0), pkgFailures(0)
113 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
114 // ---------------------------------------------------------------------
116 pkgDPkgPM::~pkgDPkgPM()
120 // DPkgPM::Install - Install a package /*{{{*/
121 // ---------------------------------------------------------------------
122 /* Add an install operation to the sequence list */
123 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
125 if (File
.empty() == true || Pkg
.end() == true)
126 return _error
->Error("Internal Error, No file name for %s",Pkg
.Name());
128 List
.push_back(Item(Item::Install
,Pkg
,File
));
132 // DPkgPM::Configure - Configure a package /*{{{*/
133 // ---------------------------------------------------------------------
134 /* Add a configure operation to the sequence list */
135 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
137 if (Pkg
.end() == true)
140 List
.push_back(Item(Item::Configure
,Pkg
));
144 // DPkgPM::Remove - Remove a package /*{{{*/
145 // ---------------------------------------------------------------------
146 /* Add a remove operation to the sequence list */
147 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
149 if (Pkg
.end() == true)
153 List
.push_back(Item(Item::Purge
,Pkg
));
155 List
.push_back(Item(Item::Remove
,Pkg
));
159 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
160 // ---------------------------------------------------------------------
161 /* This is part of the helper script communication interface, it sends
162 very complete information down to the other end of the pipe.*/
163 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
165 fprintf(F
,"VERSION 2\n");
167 /* Write out all of the configuration directives by walking the
168 configuration tree */
169 const Configuration::Item
*Top
= _config
->Tree(0);
172 if (Top
->Value
.empty() == false)
175 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
176 QuoteString(Top
->Value
,"\n").c_str());
185 while (Top
!= 0 && Top
->Next
== 0)
192 // Write out the package actions in order.
193 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
195 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
197 fprintf(F
,"%s ",I
->Pkg
.Name());
199 if (I
->Pkg
->CurrentVer
== 0)
202 fprintf(F
,"%s ",I
->Pkg
.CurrentVer().VerStr());
204 // Show the compare operator
206 if (S
.InstallVer
!= 0)
209 if (I
->Pkg
->CurrentVer
!= 0)
210 Comp
= S
.InstVerIter(Cache
).CompareVer(I
->Pkg
.CurrentVer());
217 fprintf(F
,"%s ",S
.InstVerIter(Cache
).VerStr());
222 // Show the filename/operation
223 if (I
->Op
== Item::Install
)
226 if (I
->File
[0] != '/')
227 fprintf(F
,"**ERROR**\n");
229 fprintf(F
,"%s\n",I
->File
.c_str());
231 if (I
->Op
== Item::Configure
)
232 fprintf(F
,"**CONFIGURE**\n");
233 if (I
->Op
== Item::Remove
||
234 I
->Op
== Item::Purge
)
235 fprintf(F
,"**REMOVE**\n");
243 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
244 // ---------------------------------------------------------------------
245 /* This looks for a list of scripts to run from the configuration file
246 each one is run and is fed on standard input a list of all .deb files
247 that are due to be installed. */
248 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
250 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
251 if (Opts
== 0 || Opts
->Child
== 0)
255 unsigned int Count
= 1;
256 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
258 if (Opts
->Value
.empty() == true)
261 // Determine the protocol version
262 string OptSec
= Opts
->Value
;
263 string::size_type Pos
;
264 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
265 Pos
= OptSec
.length();
266 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
268 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
272 if (pipe(Pipes
) != 0)
273 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
274 SetCloseExec(Pipes
[0],true);
275 SetCloseExec(Pipes
[1],true);
277 // Purified Fork for running the script
278 pid_t Process
= ExecFork();
282 dup2(Pipes
[0],STDIN_FILENO
);
283 SetCloseExec(STDOUT_FILENO
,false);
284 SetCloseExec(STDIN_FILENO
,false);
285 SetCloseExec(STDERR_FILENO
,false);
290 Args
[2] = Opts
->Value
.c_str();
292 execv(Args
[0],(char **)Args
);
296 FILE *F
= fdopen(Pipes
[1],"w");
298 return _error
->Errno("fdopen","Faild to open new FD");
300 // Feed it the filenames.
304 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
306 // Only deal with packages to be installed from .deb
307 if (I
->Op
!= Item::Install
)
311 if (I
->File
[0] != '/')
314 /* Feed the filename of each package that is pending install
316 fprintf(F
,"%s\n",I
->File
.c_str());
325 Die
= !SendV2Pkgs(F
);
329 // Clean up the sub process
330 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
331 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
337 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
338 // ---------------------------------------------------------------------
341 void pkgDPkgPM::DoStdin(int master
)
343 unsigned char input_buf
[256] = {0,};
344 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
346 write(master
, input_buf
, len
);
348 stdin_is_dev_null
= true;
351 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
352 // ---------------------------------------------------------------------
354 * read the terminal pty and write log
356 void pkgDPkgPM::DoTerminalPty(int master
)
358 unsigned char term_buf
[1024] = {0,0, };
360 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
361 if(len
== -1 && errno
== EIO
)
363 // this happens when the child is about to exit, we
364 // give it time to actually exit, otherwise we run
371 write(1, term_buf
, len
);
373 fwrite(term_buf
, len
, sizeof(char), term_out
);
376 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
377 // ---------------------------------------------------------------------
380 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd
, char *line
)
382 // the status we output
383 ostringstream status
;
385 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
386 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
389 /* dpkg sends strings like this:
390 'status: <pkg>: <pkg qstate>'
391 errors look like this:
392 'status: /var/cache/apt/archives/krecipes_0.8.1-0ubuntu1_i386.deb : error : trying to overwrite `/usr/share/doc/kde/HTML/en/krecipes/krectip.png', which is also in package krecipes-data
393 and conffile-prompt like this
394 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
396 Newer versions of dpkg sent also:
397 'processing: install: pkg'
398 'processing: configure: pkg'
399 'processing: remove: pkg'
400 'processing: trigproc: trigger'
404 // dpkg sends multiline error messages sometimes (see
405 // #374195 for a example. we should support this by
406 // either patching dpkg to not send multiline over the
407 // statusfd or by rewriting the code here to deal with
408 // it. for now we just ignore it and not crash
409 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
410 if( list
[0] == NULL
|| list
[1] == NULL
|| list
[2] == NULL
)
412 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
413 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
417 char *action
= _strstrip(list
[2]);
419 // 'processing' from dpkg looks like
420 // 'processing: action: pkg'
421 if(strncmp(list
[0], "processing", strlen("processing")) == 0)
424 char *pkg_or_trigger
= _strstrip(list
[2]);
425 action
=_strstrip( list
[1]);
426 const std::pair
<const char *, const char *> * const iter
=
427 std::find_if(PackageProcessingOpsBegin
,
428 PackageProcessingOpsEnd
,
429 MatchProcessingOp(action
));
430 if(iter
== PackageProcessingOpsEnd
)
432 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
433 std::clog
<< "ignoring unknwon action: " << action
<< std::endl
;
436 snprintf(s
, sizeof(s
), _(iter
->second
), pkg_or_trigger
);
438 status
<< "pmstatus:" << pkg_or_trigger
439 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
443 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
444 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
445 std::clog
<< "send: '" << status
.str() << "'" << endl
;
449 if(strncmp(action
,"error",strlen("error")) == 0)
451 // urgs, sometime has ":" in its error string so that we
452 // end up with the error message split between list[3]
453 // and list[4], e.g. the message:
454 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
456 if( list
[4] != NULL
)
457 list
[3][strlen(list
[3])] = ':';
459 status
<< "pmerror:" << list
[1]
460 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
464 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
465 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
466 std::clog
<< "send: '" << status
.str() << "'" << endl
;
468 WriteApportReport(list
[1], list
[3]);
471 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());
479 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
480 std::clog
<< "send: '" << status
.str() << "'" << endl
;
484 vector
<struct DpkgState
> &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());
507 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
508 std::clog
<< "send: '" << status
.str() << "'" << endl
;
510 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
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
;
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 bool pkgDPkgPM::CloseLog()
581 time_t t
= time(NULL
);
582 struct tm
*tmp
= localtime(&t
);
583 strftime(outstr
, sizeof(outstr
), "%F %T", tmp
);
584 fprintf(term_out
, "Log ended: ");
585 fprintf(term_out
, "%s", outstr
);
586 fprintf(term_out
, "\n");
594 // This implements a racy version of pselect for those architectures
595 // that don't have a working implementation.
596 // FIXME: Probably can be removed on Lenny+1
597 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
598 fd_set
*exceptfds
, const struct timespec
*timeout
,
599 const sigset_t
*sigmask
)
605 tv
.tv_sec
= timeout
->tv_sec
;
606 tv
.tv_usec
= timeout
->tv_nsec
/1000;
608 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
609 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
610 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 MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
632 unsigned int MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
633 bool NoTriggers
= _config
->FindB("DPkg::NoTriggers",false);
635 if (RunScripts("DPkg::Pre-Invoke") == false)
638 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
641 // map the dpkg states to the operations that are performed
642 // (this is sorted in the same way as Item::Ops)
643 static const struct DpkgState DpkgStatesOpMap
[][7] = {
646 {"half-installed", N_("Preparing %s")},
647 {"unpacked", N_("Unpacking %s") },
650 // Configure operation
652 {"unpacked",N_("Preparing to configure %s") },
653 {"half-configured", N_("Configuring %s") },
654 { "installed", N_("Installed %s")},
659 {"half-configured", N_("Preparing for removal of %s")},
660 {"half-installed", N_("Removing %s")},
661 {"config-files", N_("Removed %s")},
666 {"config-files", N_("Preparing to completely remove %s")},
667 {"not-installed", N_("Completely removed %s")},
672 // init the PackageOps map, go over the list of packages that
673 // that will be [installed|configured|removed|purged] and add
674 // them to the PackageOps map (the dpkg states it goes through)
675 // and the PackageOpsTranslations (human readable strings)
676 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end();I
++)
678 string name
= (*I
).Pkg
.Name();
679 PackageOpsDone
[name
] = 0;
680 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; i
++)
682 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
687 stdin_is_dev_null
= false;
692 // this loop is runs once per operation
693 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end();)
695 vector
<Item
>::iterator J
= I
;
696 for (; J
!= List
.end() && J
->Op
== I
->Op
; J
++)
699 // Generate the argument list
700 const char *Args
[MaxArgs
+ 50];
702 // Now check if we are within the MaxArgs limit
704 // this code below is problematic, because it may happen that
705 // the argument list is split in a way that A depends on B
706 // and they are in the same "--configure A B" run
707 // - with the split they may now be configured in different
709 if (J
- I
> (signed)MaxArgs
)
713 unsigned long Size
= 0;
714 string Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
715 Args
[n
++] = Tmp
.c_str();
716 Size
+= strlen(Args
[n
-1]);
718 // Stick in any custom dpkg options
719 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
723 for (; Opts
!= 0; Opts
= Opts
->Next
)
725 if (Opts
->Value
.empty() == true)
727 Args
[n
++] = Opts
->Value
.c_str();
728 Size
+= Opts
->Value
.length();
732 char status_fd_buf
[20];
736 Args
[n
++] = "--status-fd";
737 Size
+= strlen(Args
[n
-1]);
738 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
739 Args
[n
++] = status_fd_buf
;
740 Size
+= strlen(Args
[n
-1]);
745 Args
[n
++] = "--force-depends";
746 Size
+= strlen(Args
[n
-1]);
747 Args
[n
++] = "--force-remove-essential";
748 Size
+= strlen(Args
[n
-1]);
749 Args
[n
++] = "--remove";
750 Size
+= strlen(Args
[n
-1]);
754 Args
[n
++] = "--force-depends";
755 Size
+= strlen(Args
[n
-1]);
756 Args
[n
++] = "--force-remove-essential";
757 Size
+= strlen(Args
[n
-1]);
758 Args
[n
++] = "--purge";
759 Size
+= strlen(Args
[n
-1]);
762 case Item::Configure
:
763 Args
[n
++] = "--configure";
765 Args
[n
++] = "--no-triggers";
766 Size
+= strlen(Args
[n
-1]);
770 Args
[n
++] = "--unpack";
771 Size
+= strlen(Args
[n
-1]);
772 Args
[n
++] = "--auto-deconfigure";
773 Size
+= strlen(Args
[n
-1]);
777 // Write in the file or package names
778 if (I
->Op
== Item::Install
)
780 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
782 if (I
->File
[0] != '/')
783 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
784 Args
[n
++] = I
->File
.c_str();
785 Size
+= strlen(Args
[n
-1]);
790 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
792 Args
[n
++] = I
->Pkg
.Name();
793 Size
+= strlen(Args
[n
-1]);
799 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
801 for (unsigned int k
= 0; k
!= n
; k
++)
802 clog
<< Args
[k
] << ' ';
811 /* Mask off sig int/quit. We do this because dpkg also does when
812 it forks scripts. What happens is that when you hit ctrl-c it sends
813 it to all processes in the group. Since dpkg ignores the signal
814 it doesn't die but we do! So we must also ignore it */
815 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
816 sighandler_t old_SIGINT
= signal(SIGINT
,SIG_IGN
);
818 // ignore SIGHUP as well (debian #463030)
819 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
826 // FIXME: setup sensible signal handling (*ick*)
828 ioctl(0, TIOCGWINSZ
, (char *)&win
);
829 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
831 const char *s
= _("Can not write log, openpty() "
832 "failed (/dev/pts not mounted?)\n");
833 fprintf(stderr
, "%s",s
);
834 fprintf(term_out
, "%s",s
);
840 rtt
.c_lflag
&= ~ECHO
;
841 // block SIGTTOU during tcsetattr to prevent a hang if
842 // the process is a member of the background process group
843 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
844 sigemptyset(&sigmask
);
845 sigaddset(&sigmask
, SIGTTOU
);
846 sigprocmask(SIG_BLOCK
,&sigmask
, &original_sigmask
);
847 tcsetattr(0, TCSAFLUSH
, &rtt
);
848 sigprocmask(SIG_SETMASK
, &original_sigmask
, 0);
853 _config
->Set("APT::Keep-Fds::",fd
[1]);
854 // send status information that we are about to fork dpkg
855 if(OutStatusFd
> 0) {
856 ostringstream status
;
857 status
<< "pmstatus:dpkg-exec:"
858 << (PackagesDone
/float(PackagesTotal
)*100.0)
859 << ":" << _("Running dpkg")
861 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
868 if(slave
>= 0 && master
>= 0)
871 ioctl(slave
, TIOCSCTTY
, 0);
878 close(fd
[0]); // close the read end of the pipe
880 if (_config
->FindDir("DPkg::Chroot-Directory","/") != "/")
882 std::cerr
<< "Chrooting into "
883 << _config
->FindDir("DPkg::Chroot-Directory")
885 if (chroot(_config
->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
889 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
892 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
895 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
898 // Discard everything in stdin before forking dpkg
899 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
902 while (read(STDIN_FILENO
,&dummy
,1) == 1);
904 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
908 /* No Job Control Stop Env is a magic dpkg var that prevents it
909 from using sigstop */
910 putenv((char *)"DPKG_NO_TSTP=yes");
911 execvp(Args
[0],(char **)Args
);
912 cerr
<< "Could not exec dpkg!" << endl
;
917 if (_config
->FindB("DPkg::UseIoNice", false) == true)
920 // clear the Keep-Fd again
921 _config
->Clear("APT::Keep-Fds",fd
[1]);
926 // we read from dpkg here
928 close(fd
[1]); // close the write end of the pipe
930 // the result of the waitpid call
936 sigemptyset(&sigmask
);
937 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
940 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
942 // FIXME: move this to a function or something, looks ugly here
943 // error handling, waitpid returned -1
946 RunScripts("DPkg::Post-Invoke");
948 // Restore sig int/quit
949 signal(SIGQUIT
,old_SIGQUIT
);
950 signal(SIGINT
,old_SIGINT
);
951 signal(SIGHUP
,old_SIGHUP
);
952 return _error
->Errno("waitpid","Couldn't wait for subprocess");
954 // wait for input or output here
956 if (!stdin_is_dev_null
)
958 FD_SET(_dpkgin
, &rfds
);
960 FD_SET(master
, &rfds
);
963 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
964 &tv
, &original_sigmask
);
965 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
966 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
967 NULL
, &tv
, &original_sigmask
);
970 else if (select_ret
< 0 && errno
== EINTR
)
972 else if (select_ret
< 0)
974 perror("select() returned error");
978 if(master
>= 0 && FD_ISSET(master
, &rfds
))
979 DoTerminalPty(master
);
980 if(master
>= 0 && FD_ISSET(0, &rfds
))
982 if(FD_ISSET(_dpkgin
, &rfds
))
983 DoDpkgStatusFd(_dpkgin
, OutStatusFd
);
987 // Restore sig int/quit
988 signal(SIGQUIT
,old_SIGQUIT
);
989 signal(SIGINT
,old_SIGINT
);
990 signal(SIGHUP
,old_SIGHUP
);
994 tcsetattr(0, TCSAFLUSH
, &tt
);
998 // Check for an error code.
999 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
1001 // if it was set to "keep-dpkg-runing" then we won't return
1002 // here but keep the loop going and just report it as a error
1004 bool stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
1007 RunScripts("DPkg::Post-Invoke");
1009 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
1010 _error
->Error("Sub-process %s received a segmentation fault.",Args
[0]);
1011 else if (WIFEXITED(Status
) != 0)
1012 _error
->Error("Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
1014 _error
->Error("Sub-process %s exited unexpectedly",Args
[0]);
1025 if (RunScripts("DPkg::Post-Invoke") == false)
1028 Cache
.writeStateFile(NULL
);
1032 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1033 // ---------------------------------------------------------------------
1035 void pkgDPkgPM::Reset()
1037 List
.erase(List
.begin(),List
.end());
1040 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1041 // ---------------------------------------------------------------------
1043 void pkgDPkgPM::WriteApportReport(const char *pkgpath
, const char *errormsg
)
1045 string pkgname
, reportfile
, srcpkgname
, pkgver
, arch
;
1046 string::size_type pos
;
1049 if (_config
->FindB("Dpkg::ApportFailureReport",true) == false)
1051 std::clog
<< "configured to not write apport reports" << std::endl
;
1055 // only report the first errors
1056 if(pkgFailures
> _config
->FindI("APT::Apport::MaxReports", 3))
1058 std::clog
<< _("No apport report written because MaxReports is reached already") << std::endl
;
1062 // check if its not a follow up error
1063 const char *needle
= dgettext("dpkg", "dependency problems - leaving unconfigured");
1064 if(strstr(errormsg
, needle
) != NULL
) {
1065 std::clog
<< _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl
;
1069 // do not report disk-full failures
1070 if(strstr(errormsg
, strerror(ENOSPC
)) != NULL
) {
1071 std::clog
<< _("No apport report written because the error message indicates a disk full error") << std::endl
;
1075 // do not report out-of-memory failures
1076 if(strstr(errormsg
, strerror(ENOMEM
)) != NULL
) {
1077 std::clog
<< _("No apport report written because the error message indicates a out of memory error") << std::endl
;
1081 // get the pkgname and reportfile
1082 pkgname
= flNotDir(pkgpath
);
1083 pos
= pkgname
.find('_');
1084 if(pos
!= string::npos
)
1085 pkgname
= pkgname
.substr(0, pos
);
1087 // find the package versin and source package name
1088 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
1089 if (Pkg
.end() == true)
1091 pkgCache::VerIterator Ver
= Cache
.GetCandidateVer(Pkg
);
1092 if (Ver
.end() == true)
1094 pkgver
= Ver
.VerStr() == NULL
? "unknown" : Ver
.VerStr();
1095 pkgRecords
Recs(Cache
);
1096 pkgRecords::Parser
&Parse
= Recs
.Lookup(Ver
.FileList());
1097 srcpkgname
= Parse
.SourcePkg();
1098 if(srcpkgname
.empty())
1099 srcpkgname
= pkgname
;
1101 // if the file exists already, we check:
1102 // - if it was reported already (touched by apport).
1103 // If not, we do nothing, otherwise
1104 // we overwrite it. This is the same behaviour as apport
1105 // - if we have a report with the same pkgversion already
1107 reportfile
= flCombine("/var/crash",pkgname
+".0.crash");
1108 if(FileExists(reportfile
))
1113 // check atime/mtime
1114 stat(reportfile
.c_str(), &buf
);
1115 if(buf
.st_mtime
> buf
.st_atime
)
1118 // check if the existing report is the same version
1119 report
= fopen(reportfile
.c_str(),"r");
1120 while(fgets(strbuf
, sizeof(strbuf
), report
) != NULL
)
1122 if(strstr(strbuf
,"Package:") == strbuf
)
1124 char pkgname
[255], version
[255];
1125 if(sscanf(strbuf
, "Package: %s %s", pkgname
, version
) == 2)
1126 if(strcmp(pkgver
.c_str(), version
) == 0)
1136 // now write the report
1137 arch
= _config
->Find("APT::Architecture");
1138 report
= fopen(reportfile
.c_str(),"w");
1141 if(_config
->FindB("DPkgPM::InitialReportOnly",false) == true)
1142 chmod(reportfile
.c_str(), 0);
1144 chmod(reportfile
.c_str(), 0600);
1145 fprintf(report
, "ProblemType: Package\n");
1146 fprintf(report
, "Architecture: %s\n", arch
.c_str());
1147 time_t now
= time(NULL
);
1148 fprintf(report
, "Date: %s" , ctime(&now
));
1149 fprintf(report
, "Package: %s %s\n", pkgname
.c_str(), pkgver
.c_str());
1150 fprintf(report
, "SourcePackage: %s\n", srcpkgname
.c_str());
1151 fprintf(report
, "ErrorMessage:\n %s\n", errormsg
);
1153 // ensure that the log is flushed
1157 // attach terminal log it if we have it
1158 string logfile_name
= _config
->FindFile("Dir::Log::Terminal");
1159 if (!logfile_name
.empty())
1164 fprintf(report
, "DpkgTerminalLog:\n");
1165 log
= fopen(logfile_name
.c_str(),"r");
1168 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1169 fprintf(report
, " %s", buf
);
1175 const char *ops_str
[] = {"Install", "Configure","Remove","Purge"};
1176 fprintf(report
, "AptOrdering:\n");
1177 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
1178 fprintf(report
, " %s: %s\n", (*I
).Pkg
.Name(), ops_str
[(*I
).Op
]);
1180 // attach dmesg log (to learn about segfaults)
1181 if (FileExists("/bin/dmesg"))
1186 fprintf(report
, "Dmesg:\n");
1187 log
= popen("/bin/dmesg","r");
1190 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1191 fprintf(report
, " %s", buf
);