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
));
142 // Use triggers for config calls if we configure "smart"
143 // as otherwise Pre-Depends will not be satisfied, see #526774
144 if (_config
->FindB("DPkg::TriggersPending", false) == true)
145 List
.push_back(Item(Item::TriggersPending
, PkgIterator()));
150 // DPkgPM::Remove - Remove a package /*{{{*/
151 // ---------------------------------------------------------------------
152 /* Add a remove operation to the sequence list */
153 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
155 if (Pkg
.end() == true)
159 List
.push_back(Item(Item::Purge
,Pkg
));
161 List
.push_back(Item(Item::Remove
,Pkg
));
165 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
166 // ---------------------------------------------------------------------
167 /* This is part of the helper script communication interface, it sends
168 very complete information down to the other end of the pipe.*/
169 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
171 fprintf(F
,"VERSION 2\n");
173 /* Write out all of the configuration directives by walking the
174 configuration tree */
175 const Configuration::Item
*Top
= _config
->Tree(0);
178 if (Top
->Value
.empty() == false)
181 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
182 QuoteString(Top
->Value
,"\n").c_str());
191 while (Top
!= 0 && Top
->Next
== 0)
198 // Write out the package actions in order.
199 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
201 if(I
->Pkg
.end() == true)
204 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
206 fprintf(F
,"%s ",I
->Pkg
.Name());
208 if (I
->Pkg
->CurrentVer
== 0)
211 fprintf(F
,"%s ",I
->Pkg
.CurrentVer().VerStr());
213 // Show the compare operator
215 if (S
.InstallVer
!= 0)
218 if (I
->Pkg
->CurrentVer
!= 0)
219 Comp
= S
.InstVerIter(Cache
).CompareVer(I
->Pkg
.CurrentVer());
226 fprintf(F
,"%s ",S
.InstVerIter(Cache
).VerStr());
231 // Show the filename/operation
232 if (I
->Op
== Item::Install
)
235 if (I
->File
[0] != '/')
236 fprintf(F
,"**ERROR**\n");
238 fprintf(F
,"%s\n",I
->File
.c_str());
240 if (I
->Op
== Item::Configure
)
241 fprintf(F
,"**CONFIGURE**\n");
242 if (I
->Op
== Item::Remove
||
243 I
->Op
== Item::Purge
)
244 fprintf(F
,"**REMOVE**\n");
252 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
253 // ---------------------------------------------------------------------
254 /* This looks for a list of scripts to run from the configuration file
255 each one is run and is fed on standard input a list of all .deb files
256 that are due to be installed. */
257 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
259 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
260 if (Opts
== 0 || Opts
->Child
== 0)
264 unsigned int Count
= 1;
265 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
267 if (Opts
->Value
.empty() == true)
270 // Determine the protocol version
271 string OptSec
= Opts
->Value
;
272 string::size_type Pos
;
273 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
274 Pos
= OptSec
.length();
275 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
277 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
281 if (pipe(Pipes
) != 0)
282 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
283 SetCloseExec(Pipes
[0],true);
284 SetCloseExec(Pipes
[1],true);
286 // Purified Fork for running the script
287 pid_t Process
= ExecFork();
291 dup2(Pipes
[0],STDIN_FILENO
);
292 SetCloseExec(STDOUT_FILENO
,false);
293 SetCloseExec(STDIN_FILENO
,false);
294 SetCloseExec(STDERR_FILENO
,false);
299 Args
[2] = Opts
->Value
.c_str();
301 execv(Args
[0],(char **)Args
);
305 FILE *F
= fdopen(Pipes
[1],"w");
307 return _error
->Errno("fdopen","Faild to open new FD");
309 // Feed it the filenames.
313 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
315 // Only deal with packages to be installed from .deb
316 if (I
->Op
!= Item::Install
)
320 if (I
->File
[0] != '/')
323 /* Feed the filename of each package that is pending install
325 fprintf(F
,"%s\n",I
->File
.c_str());
334 Die
= !SendV2Pkgs(F
);
338 // Clean up the sub process
339 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
340 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 // urgs, sometime has ":" in its error string so that we
463 // end up with the error message split between list[3]
464 // and list[4], e.g. the message:
465 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
467 if( list
[4] != NULL
)
468 list
[3][strlen(list
[3])] = ':';
470 status
<< "pmerror:" << 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
;
479 WriteApportReport(list
[1], list
[3]);
482 else if(strncmp(action
,"conffile",strlen("conffile")) == 0)
484 status
<< "pmconffile:" << list
[1]
485 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
489 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
491 std::clog
<< "send: '" << status
.str() << "'" << endl
;
495 vector
<struct DpkgState
> const &states
= PackageOps
[pkg
];
496 const char *next_action
= NULL
;
497 if(PackageOpsDone
[pkg
] < states
.size())
498 next_action
= states
[PackageOpsDone
[pkg
]].state
;
499 // check if the package moved to the next dpkg state
500 if(next_action
&& (strcmp(action
, next_action
) == 0))
502 // only read the translation if there is actually a next
504 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
506 snprintf(s
, sizeof(s
), translation
, pkg
);
508 // we moved from one dpkg state to a new one, report that
509 PackageOpsDone
[pkg
]++;
511 // build the status str
512 status
<< "pmstatus:" << pkg
513 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
517 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
519 std::clog
<< "send: '" << status
.str() << "'" << endl
;
522 std::clog
<< "(parsed from dpkg) pkg: " << pkg
523 << " action: " << action
<< endl
;
526 // DPkgPM::DoDpkgStatusFd /*{{{*/
527 // ---------------------------------------------------------------------
530 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
, int OutStatusFd
)
535 len
=read(statusfd
, &dpkgbuf
[dpkgbuf_pos
], sizeof(dpkgbuf
)-dpkgbuf_pos
);
540 // process line by line if we have a buffer
542 while((q
=(char*)memchr(p
, '\n', dpkgbuf
+dpkgbuf_pos
-p
)) != NULL
)
545 ProcessDpkgStatusLine(OutStatusFd
, p
);
546 p
=q
+1; // continue with next line
549 // now move the unprocessed bits (after the final \n that is now a 0x0)
550 // to the start and update dpkgbuf_pos
551 p
= (char*)memrchr(dpkgbuf
, 0, dpkgbuf_pos
);
555 // we are interessted in the first char *after* 0x0
558 // move the unprocessed tail to the start and update pos
559 memmove(dpkgbuf
, p
, p
-dpkgbuf
);
560 dpkgbuf_pos
= dpkgbuf
+dpkgbuf_pos
-p
;
563 // DPkgPM::OpenLog /*{{{*/
564 bool pkgDPkgPM::OpenLog()
566 string logdir
= _config
->FindDir("Dir::Log");
567 if(not FileExists(logdir
))
568 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
569 string logfile_name
= flCombine(logdir
,
570 _config
->Find("Dir::Log::Terminal"));
571 if (!logfile_name
.empty())
573 term_out
= fopen(logfile_name
.c_str(),"a");
574 chmod(logfile_name
.c_str(), 0600);
575 // output current time
577 time_t t
= time(NULL
);
578 struct tm
*tmp
= localtime(&t
);
579 strftime(outstr
, sizeof(outstr
), "%F %T", tmp
);
580 fprintf(term_out
, "\nLog started: ");
581 fprintf(term_out
, "%s", outstr
);
582 fprintf(term_out
, "\n");
587 // DPkg::CloseLog /*{{{*/
588 bool pkgDPkgPM::CloseLog()
593 time_t t
= time(NULL
);
594 struct tm
*tmp
= localtime(&t
);
595 strftime(outstr
, sizeof(outstr
), "%F %T", tmp
);
596 fprintf(term_out
, "Log ended: ");
597 fprintf(term_out
, "%s", outstr
);
598 fprintf(term_out
, "\n");
606 // This implements a racy version of pselect for those architectures
607 // that don't have a working implementation.
608 // FIXME: Probably can be removed on Lenny+1
609 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
610 fd_set
*exceptfds
, const struct timespec
*timeout
,
611 const sigset_t
*sigmask
)
617 tv
.tv_sec
= timeout
->tv_sec
;
618 tv
.tv_usec
= timeout
->tv_nsec
/1000;
620 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
621 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
622 sigprocmask(SIG_SETMASK
, &origmask
, 0);
626 // DPkgPM::Go - Run the sequence /*{{{*/
627 // ---------------------------------------------------------------------
628 /* This globs the operations and calls dpkg
630 * If it is called with "OutStatusFd" set to a valid file descriptor
631 * apt will report the install progress over this fd. It maps the
632 * dpkg states a package goes through to human readable (and i10n-able)
633 * names and calculates a percentage for each step.
635 bool pkgDPkgPM::Go(int OutStatusFd
)
640 sigset_t original_sigmask
;
642 unsigned int const MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
643 unsigned int const MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
644 bool const NoTriggers
= _config
->FindB("DPkg::NoTriggers", false);
646 if (RunScripts("DPkg::Pre-Invoke") == false)
649 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
652 // support subpressing of triggers processing for special
653 // cases like d-i that runs the triggers handling manually
654 bool const SmartConf
= (_config
->Find("PackageManager::Configure", "all") != "all");
655 bool const TriggersPending
= _config
->FindB("DPkg::TriggersPending", false);
656 if (_config
->FindB("DPkg::ConfigurePending", SmartConf
) == true)
657 List
.push_back(Item(Item::ConfigurePending
, PkgIterator()));
659 // map the dpkg states to the operations that are performed
660 // (this is sorted in the same way as Item::Ops)
661 static const struct DpkgState DpkgStatesOpMap
[][7] = {
664 {"half-installed", N_("Preparing %s")},
665 {"unpacked", N_("Unpacking %s") },
668 // Configure operation
670 {"unpacked",N_("Preparing to configure %s") },
671 {"half-configured", N_("Configuring %s") },
672 { "installed", N_("Installed %s")},
677 {"half-configured", N_("Preparing for removal of %s")},
678 {"half-installed", N_("Removing %s")},
679 {"config-files", N_("Removed %s")},
684 {"config-files", N_("Preparing to completely remove %s")},
685 {"not-installed", N_("Completely removed %s")},
690 // init the PackageOps map, go over the list of packages that
691 // that will be [installed|configured|removed|purged] and add
692 // them to the PackageOps map (the dpkg states it goes through)
693 // and the PackageOpsTranslations (human readable strings)
694 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();I
++)
696 if((*I
).Pkg
.end() == true)
699 string
const name
= (*I
).Pkg
.Name();
700 PackageOpsDone
[name
] = 0;
701 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; i
++)
703 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
708 stdin_is_dev_null
= false;
713 // this loop is runs once per operation
714 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();)
716 // Do all actions with the same Op in one run
717 vector
<Item
>::const_iterator J
= I
;
718 if (TriggersPending
== true)
719 for (; J
!= List
.end(); J
++)
723 if (J
->Op
!= Item::TriggersPending
)
725 vector
<Item
>::const_iterator T
= J
+ 1;
726 if (T
!= List
.end() && T
->Op
== I
->Op
)
731 for (; J
!= List
.end() && J
->Op
== I
->Op
; J
++)
734 // Generate the argument list
735 const char *Args
[MaxArgs
+ 50];
737 // Now check if we are within the MaxArgs limit
739 // this code below is problematic, because it may happen that
740 // the argument list is split in a way that A depends on B
741 // and they are in the same "--configure A B" run
742 // - with the split they may now be configured in different
744 if (J
- I
> (signed)MaxArgs
)
748 unsigned long Size
= 0;
749 string
const Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
750 Args
[n
++] = Tmp
.c_str();
751 Size
+= strlen(Args
[n
-1]);
753 // Stick in any custom dpkg options
754 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
758 for (; Opts
!= 0; Opts
= Opts
->Next
)
760 if (Opts
->Value
.empty() == true)
762 Args
[n
++] = Opts
->Value
.c_str();
763 Size
+= Opts
->Value
.length();
767 char status_fd_buf
[20];
771 Args
[n
++] = "--status-fd";
772 Size
+= strlen(Args
[n
-1]);
773 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
774 Args
[n
++] = status_fd_buf
;
775 Size
+= strlen(Args
[n
-1]);
780 Args
[n
++] = "--force-depends";
781 Size
+= strlen(Args
[n
-1]);
782 Args
[n
++] = "--force-remove-essential";
783 Size
+= strlen(Args
[n
-1]);
784 Args
[n
++] = "--remove";
785 Size
+= strlen(Args
[n
-1]);
789 Args
[n
++] = "--force-depends";
790 Size
+= strlen(Args
[n
-1]);
791 Args
[n
++] = "--force-remove-essential";
792 Size
+= strlen(Args
[n
-1]);
793 Args
[n
++] = "--purge";
794 Size
+= strlen(Args
[n
-1]);
797 case Item::Configure
:
798 Args
[n
++] = "--configure";
799 Size
+= strlen(Args
[n
-1]);
802 case Item::ConfigurePending
:
803 Args
[n
++] = "--configure";
804 Size
+= strlen(Args
[n
-1]);
805 Args
[n
++] = "--pending";
806 Size
+= strlen(Args
[n
-1]);
809 case Item::TriggersPending
:
810 Args
[n
++] = "--triggers-only";
811 Size
+= strlen(Args
[n
-1]);
812 Args
[n
++] = "--pending";
813 Size
+= strlen(Args
[n
-1]);
817 Args
[n
++] = "--unpack";
818 Size
+= strlen(Args
[n
-1]);
819 Args
[n
++] = "--auto-deconfigure";
820 Size
+= strlen(Args
[n
-1]);
824 if (NoTriggers
== true && I
->Op
!= Item::TriggersPending
&&
825 I
->Op
!= Item::ConfigurePending
)
827 Args
[n
++] = "--no-triggers";
828 Size
+= strlen(Args
[n
-1]);
831 // Write in the file or package names
832 if (I
->Op
== Item::Install
)
834 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
836 if (I
->File
[0] != '/')
837 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
838 Args
[n
++] = I
->File
.c_str();
839 Size
+= strlen(Args
[n
-1]);
844 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
846 if((*I
).Pkg
.end() == true)
848 Args
[n
++] = I
->Pkg
.Name();
849 Size
+= strlen(Args
[n
-1]);
855 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
857 for (unsigned int k
= 0; k
!= n
; k
++)
858 clog
<< Args
[k
] << ' ';
867 /* Mask off sig int/quit. We do this because dpkg also does when
868 it forks scripts. What happens is that when you hit ctrl-c it sends
869 it to all processes in the group. Since dpkg ignores the signal
870 it doesn't die but we do! So we must also ignore it */
871 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
872 sighandler_t old_SIGINT
= signal(SIGINT
,SIG_IGN
);
874 // ignore SIGHUP as well (debian #463030)
875 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
882 // if tcgetattr does not return zero there was a error
883 // and we do not do any pty magic
884 if (tcgetattr(0, &tt
) == 0)
886 ioctl(0, TIOCGWINSZ
, (char *)&win
);
887 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
889 const char *s
= _("Can not write log, openpty() "
890 "failed (/dev/pts not mounted?)\n");
891 fprintf(stderr
, "%s",s
);
892 fprintf(term_out
, "%s",s
);
898 rtt
.c_lflag
&= ~ECHO
;
899 // block SIGTTOU during tcsetattr to prevent a hang if
900 // the process is a member of the background process group
901 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
902 sigemptyset(&sigmask
);
903 sigaddset(&sigmask
, SIGTTOU
);
904 sigprocmask(SIG_BLOCK
,&sigmask
, &original_sigmask
);
905 tcsetattr(0, TCSAFLUSH
, &rtt
);
906 sigprocmask(SIG_SETMASK
, &original_sigmask
, 0);
912 _config
->Set("APT::Keep-Fds::",fd
[1]);
913 // send status information that we are about to fork dpkg
914 if(OutStatusFd
> 0) {
915 ostringstream status
;
916 status
<< "pmstatus:dpkg-exec:"
917 << (PackagesDone
/float(PackagesTotal
)*100.0)
918 << ":" << _("Running dpkg")
920 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
927 if(slave
>= 0 && master
>= 0)
930 ioctl(slave
, TIOCSCTTY
, 0);
937 close(fd
[0]); // close the read end of the pipe
939 if (_config
->FindDir("DPkg::Chroot-Directory","/") != "/")
941 std::cerr
<< "Chrooting into "
942 << _config
->FindDir("DPkg::Chroot-Directory")
944 if (chroot(_config
->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
948 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
951 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
954 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
957 // Discard everything in stdin before forking dpkg
958 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
961 while (read(STDIN_FILENO
,&dummy
,1) == 1);
963 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
967 /* No Job Control Stop Env is a magic dpkg var that prevents it
968 from using sigstop */
969 putenv((char *)"DPKG_NO_TSTP=yes");
970 execvp(Args
[0],(char **)Args
);
971 cerr
<< "Could not exec dpkg!" << endl
;
976 if (_config
->FindB("DPkg::UseIoNice", false) == true)
979 // clear the Keep-Fd again
980 _config
->Clear("APT::Keep-Fds",fd
[1]);
985 // we read from dpkg here
986 int const _dpkgin
= fd
[0];
987 close(fd
[1]); // close the write end of the pipe
993 sigemptyset(&sigmask
);
994 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
996 // the result of the waitpid call
999 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
1001 // FIXME: move this to a function or something, looks ugly here
1002 // error handling, waitpid returned -1
1005 RunScripts("DPkg::Post-Invoke");
1007 // Restore sig int/quit
1008 signal(SIGQUIT
,old_SIGQUIT
);
1009 signal(SIGINT
,old_SIGINT
);
1010 signal(SIGHUP
,old_SIGHUP
);
1011 return _error
->Errno("waitpid","Couldn't wait for subprocess");
1013 // wait for input or output here
1015 if (!stdin_is_dev_null
)
1017 FD_SET(_dpkgin
, &rfds
);
1019 FD_SET(master
, &rfds
);
1022 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
1023 &tv
, &original_sigmask
);
1024 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
1025 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
1026 NULL
, &tv
, &original_sigmask
);
1027 if (select_ret
== 0)
1029 else if (select_ret
< 0 && errno
== EINTR
)
1031 else if (select_ret
< 0)
1033 perror("select() returned error");
1037 if(master
>= 0 && FD_ISSET(master
, &rfds
))
1038 DoTerminalPty(master
);
1039 if(master
>= 0 && FD_ISSET(0, &rfds
))
1041 if(FD_ISSET(_dpkgin
, &rfds
))
1042 DoDpkgStatusFd(_dpkgin
, OutStatusFd
);
1046 // Restore sig int/quit
1047 signal(SIGQUIT
,old_SIGQUIT
);
1048 signal(SIGINT
,old_SIGINT
);
1049 signal(SIGHUP
,old_SIGHUP
);
1053 tcsetattr(0, TCSAFLUSH
, &tt
);
1057 // Check for an error code.
1058 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
1060 // if it was set to "keep-dpkg-runing" then we won't return
1061 // here but keep the loop going and just report it as a error
1063 bool const stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
1066 RunScripts("DPkg::Post-Invoke");
1068 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
1069 _error
->Error("Sub-process %s received a segmentation fault.",Args
[0]);
1070 else if (WIFEXITED(Status
) != 0)
1071 _error
->Error("Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
1073 _error
->Error("Sub-process %s exited unexpectedly",Args
[0]);
1084 if (RunScripts("DPkg::Post-Invoke") == false)
1087 Cache
.writeStateFile(NULL
);
1091 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1092 // ---------------------------------------------------------------------
1094 void pkgDPkgPM::Reset()
1096 List
.erase(List
.begin(),List
.end());
1099 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1100 // ---------------------------------------------------------------------
1102 void pkgDPkgPM::WriteApportReport(const char *pkgpath
, const char *errormsg
)
1104 string pkgname
, reportfile
, srcpkgname
, pkgver
, arch
;
1105 string::size_type pos
;
1108 if (_config
->FindB("Dpkg::ApportFailureReport",true) == false)
1110 std::clog
<< "configured to not write apport reports" << std::endl
;
1114 // only report the first errors
1115 if(pkgFailures
> _config
->FindI("APT::Apport::MaxReports", 3))
1117 std::clog
<< _("No apport report written because MaxReports is reached already") << std::endl
;
1121 // check if its not a follow up error
1122 const char *needle
= dgettext("dpkg", "dependency problems - leaving unconfigured");
1123 if(strstr(errormsg
, needle
) != NULL
) {
1124 std::clog
<< _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl
;
1128 // do not report disk-full failures
1129 if(strstr(errormsg
, strerror(ENOSPC
)) != NULL
) {
1130 std::clog
<< _("No apport report written because the error message indicates a disk full error") << std::endl
;
1134 // do not report out-of-memory failures
1135 if(strstr(errormsg
, strerror(ENOMEM
)) != NULL
) {
1136 std::clog
<< _("No apport report written because the error message indicates a out of memory error") << std::endl
;
1140 // do not report dpkg I/O errors
1141 // XXX - this message is localized, but this only matches the English version. This is better than nothing.
1142 if(strstr(errormsg
, "short read in buffer_copy (")) {
1143 std::clog
<< _("No apport report written because the error message indicates a dpkg I/O error") << std::endl
;
1147 // get the pkgname and reportfile
1148 pkgname
= flNotDir(pkgpath
);
1149 pos
= pkgname
.find('_');
1150 if(pos
!= string::npos
)
1151 pkgname
= pkgname
.substr(0, pos
);
1153 // find the package versin and source package name
1154 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
1155 if (Pkg
.end() == true)
1157 pkgCache::VerIterator Ver
= Cache
.GetCandidateVer(Pkg
);
1158 if (Ver
.end() == true)
1160 pkgver
= Ver
.VerStr() == NULL
? "unknown" : Ver
.VerStr();
1161 pkgRecords
Recs(Cache
);
1162 pkgRecords::Parser
&Parse
= Recs
.Lookup(Ver
.FileList());
1163 srcpkgname
= Parse
.SourcePkg();
1164 if(srcpkgname
.empty())
1165 srcpkgname
= pkgname
;
1167 // if the file exists already, we check:
1168 // - if it was reported already (touched by apport).
1169 // If not, we do nothing, otherwise
1170 // we overwrite it. This is the same behaviour as apport
1171 // - if we have a report with the same pkgversion already
1173 reportfile
= flCombine("/var/crash",pkgname
+".0.crash");
1174 if(FileExists(reportfile
))
1179 // check atime/mtime
1180 stat(reportfile
.c_str(), &buf
);
1181 if(buf
.st_mtime
> buf
.st_atime
)
1184 // check if the existing report is the same version
1185 report
= fopen(reportfile
.c_str(),"r");
1186 while(fgets(strbuf
, sizeof(strbuf
), report
) != NULL
)
1188 if(strstr(strbuf
,"Package:") == strbuf
)
1190 char pkgname
[255], version
[255];
1191 if(sscanf(strbuf
, "Package: %s %s", pkgname
, version
) == 2)
1192 if(strcmp(pkgver
.c_str(), version
) == 0)
1202 // now write the report
1203 arch
= _config
->Find("APT::Architecture");
1204 report
= fopen(reportfile
.c_str(),"w");
1207 if(_config
->FindB("DPkgPM::InitialReportOnly",false) == true)
1208 chmod(reportfile
.c_str(), 0);
1210 chmod(reportfile
.c_str(), 0600);
1211 fprintf(report
, "ProblemType: Package\n");
1212 fprintf(report
, "Architecture: %s\n", arch
.c_str());
1213 time_t now
= time(NULL
);
1214 fprintf(report
, "Date: %s" , ctime(&now
));
1215 fprintf(report
, "Package: %s %s\n", pkgname
.c_str(), pkgver
.c_str());
1216 fprintf(report
, "SourcePackage: %s\n", srcpkgname
.c_str());
1217 fprintf(report
, "ErrorMessage:\n %s\n", errormsg
);
1219 // ensure that the log is flushed
1223 // attach terminal log it if we have it
1224 string logfile_name
= _config
->FindFile("Dir::Log::Terminal");
1225 if (!logfile_name
.empty())
1230 fprintf(report
, "DpkgTerminalLog:\n");
1231 log
= fopen(logfile_name
.c_str(),"r");
1234 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1235 fprintf(report
, " %s", buf
);
1241 const char *ops_str
[] = {"Install", "Configure","Remove","Purge"};
1242 fprintf(report
, "AptOrdering:\n");
1243 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
1244 fprintf(report
, " %s: %s\n", (*I
).Pkg
.Name(), ops_str
[(*I
).Op
]);
1246 // attach dmesg log (to learn about segfaults)
1247 if (FileExists("/bin/dmesg"))
1252 fprintf(report
, "Dmesg:\n");
1253 log
= popen("/bin/dmesg","r");
1256 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1257 fprintf(report
, " %s", buf
);
1262 // attach df -l log (to learn about filesystem status)
1263 if (FileExists("/bin/df"))
1268 fprintf(report
, "Df:\n");
1269 log
= popen("/bin/df -l","r");
1272 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1273 fprintf(report
, " %s", buf
);