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 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
80 // ---------------------------------------------------------------------
82 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
83 : pkgPackageManager(Cache
), dpkgbuf_pos(0),
84 term_out(NULL
), PackagesDone(0), PackagesTotal(0), pkgFailures(0)
88 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
89 // ---------------------------------------------------------------------
91 pkgDPkgPM::~pkgDPkgPM()
95 // DPkgPM::Install - Install a package /*{{{*/
96 // ---------------------------------------------------------------------
97 /* Add an install operation to the sequence list */
98 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
100 if (File
.empty() == true || Pkg
.end() == true)
101 return _error
->Error("Internal Error, No file name for %s",Pkg
.Name());
103 List
.push_back(Item(Item::Install
,Pkg
,File
));
107 // DPkgPM::Configure - Configure a package /*{{{*/
108 // ---------------------------------------------------------------------
109 /* Add a configure operation to the sequence list */
110 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
112 if (Pkg
.end() == true)
115 List
.push_back(Item(Item::Configure
,Pkg
));
119 // DPkgPM::Remove - Remove a package /*{{{*/
120 // ---------------------------------------------------------------------
121 /* Add a remove operation to the sequence list */
122 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
124 if (Pkg
.end() == true)
128 List
.push_back(Item(Item::Purge
,Pkg
));
130 List
.push_back(Item(Item::Remove
,Pkg
));
134 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
135 // ---------------------------------------------------------------------
136 /* This is part of the helper script communication interface, it sends
137 very complete information down to the other end of the pipe.*/
138 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
140 fprintf(F
,"VERSION 2\n");
142 /* Write out all of the configuration directives by walking the
143 configuration tree */
144 const Configuration::Item
*Top
= _config
->Tree(0);
147 if (Top
->Value
.empty() == false)
150 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
151 QuoteString(Top
->Value
,"\n").c_str());
160 while (Top
!= 0 && Top
->Next
== 0)
167 // Write out the package actions in order.
168 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
170 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
172 fprintf(F
,"%s ",I
->Pkg
.Name());
174 if (I
->Pkg
->CurrentVer
== 0)
177 fprintf(F
,"%s ",I
->Pkg
.CurrentVer().VerStr());
179 // Show the compare operator
181 if (S
.InstallVer
!= 0)
184 if (I
->Pkg
->CurrentVer
!= 0)
185 Comp
= S
.InstVerIter(Cache
).CompareVer(I
->Pkg
.CurrentVer());
192 fprintf(F
,"%s ",S
.InstVerIter(Cache
).VerStr());
197 // Show the filename/operation
198 if (I
->Op
== Item::Install
)
201 if (I
->File
[0] != '/')
202 fprintf(F
,"**ERROR**\n");
204 fprintf(F
,"%s\n",I
->File
.c_str());
206 if (I
->Op
== Item::Configure
)
207 fprintf(F
,"**CONFIGURE**\n");
208 if (I
->Op
== Item::Remove
||
209 I
->Op
== Item::Purge
)
210 fprintf(F
,"**REMOVE**\n");
218 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
219 // ---------------------------------------------------------------------
220 /* This looks for a list of scripts to run from the configuration file
221 each one is run and is fed on standard input a list of all .deb files
222 that are due to be installed. */
223 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
225 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
226 if (Opts
== 0 || Opts
->Child
== 0)
230 unsigned int Count
= 1;
231 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
233 if (Opts
->Value
.empty() == true)
236 // Determine the protocol version
237 string OptSec
= Opts
->Value
;
238 string::size_type Pos
;
239 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
240 Pos
= OptSec
.length();
241 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
243 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
247 if (pipe(Pipes
) != 0)
248 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
249 SetCloseExec(Pipes
[0],true);
250 SetCloseExec(Pipes
[1],true);
252 // Purified Fork for running the script
253 pid_t Process
= ExecFork();
257 dup2(Pipes
[0],STDIN_FILENO
);
258 SetCloseExec(STDOUT_FILENO
,false);
259 SetCloseExec(STDIN_FILENO
,false);
260 SetCloseExec(STDERR_FILENO
,false);
265 Args
[2] = Opts
->Value
.c_str();
267 execv(Args
[0],(char **)Args
);
271 FILE *F
= fdopen(Pipes
[1],"w");
273 return _error
->Errno("fdopen","Faild to open new FD");
275 // Feed it the filenames.
279 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
281 // Only deal with packages to be installed from .deb
282 if (I
->Op
!= Item::Install
)
286 if (I
->File
[0] != '/')
289 /* Feed the filename of each package that is pending install
291 fprintf(F
,"%s\n",I
->File
.c_str());
300 Die
= !SendV2Pkgs(F
);
304 // Clean up the sub process
305 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
306 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
312 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
313 // ---------------------------------------------------------------------
316 void pkgDPkgPM::DoStdin(int master
)
318 unsigned char input_buf
[256] = {0,};
319 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
321 write(master
, input_buf
, len
);
323 stdin_is_dev_null
= true;
326 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
327 // ---------------------------------------------------------------------
329 * read the terminal pty and write log
331 void pkgDPkgPM::DoTerminalPty(int master
)
333 unsigned char term_buf
[1024] = {0,0, };
335 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
336 if(len
== -1 && errno
== EIO
)
338 // this happens when the child is about to exit, we
339 // give it time to actually exit, otherwise we run
346 write(1, term_buf
, len
);
348 fwrite(term_buf
, len
, sizeof(char), term_out
);
351 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
352 // ---------------------------------------------------------------------
355 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd
, char *line
)
357 // the status we output
358 ostringstream status
;
360 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
361 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
364 /* dpkg sends strings like this:
365 'status: <pkg>: <pkg qstate>'
366 errors look like this:
367 '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
368 and conffile-prompt like this
369 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
371 Newer versions of dpkg sent also:
372 'processing: install: pkg'
373 'processing: configure: pkg'
374 'processing: remove: pkg'
375 'processing: trigproc: trigger'
379 // dpkg sends multiline error messages sometimes (see
380 // #374195 for a example. we should support this by
381 // either patching dpkg to not send multiline over the
382 // statusfd or by rewriting the code here to deal with
383 // it. for now we just ignore it and not crash
384 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
385 if( list
[0] == NULL
|| list
[1] == NULL
|| list
[2] == NULL
)
387 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
388 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
392 char *action
= _strstrip(list
[2]);
394 // 'processing' from dpkg looks like
395 // 'processing: action: pkg'
396 if(strncmp(list
[0], "processing", strlen("processing")) == 0)
399 char *pkg_or_trigger
= _strstrip(list
[2]);
400 action
=_strstrip( list
[1]);
401 const std::pair
<const char *, const char *> * const iter
=
402 std::find_if(PackageProcessingOpsBegin
,
403 PackageProcessingOpsEnd
,
404 MatchProcessingOp(action
));
405 if(iter
== PackageProcessingOpsEnd
)
407 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
408 std::clog
<< "ignoring unknwon action: " << action
<< std::endl
;
411 snprintf(s
, sizeof(s
), _(iter
->second
), pkg_or_trigger
);
413 status
<< "pmstatus:" << pkg_or_trigger
414 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
418 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
419 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
420 std::clog
<< "send: '" << status
.str() << "'" << endl
;
424 if(strncmp(action
,"error",strlen("error")) == 0)
426 // urgs, sometime has ":" in its error string so that we
427 // end up with the error message split between list[3]
428 // and list[4], e.g. the message:
429 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
431 if( list
[4] != NULL
)
432 list
[3][strlen(list
[3])] = ':';
434 status
<< "pmerror:" << list
[1]
435 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
439 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
440 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
441 std::clog
<< "send: '" << status
.str() << "'" << endl
;
443 WriteApportReport(list
[1], list
[3]);
446 if(strncmp(action
,"conffile",strlen("conffile")) == 0)
448 status
<< "pmconffile:" << list
[1]
449 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
453 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
454 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
455 std::clog
<< "send: '" << status
.str() << "'" << endl
;
459 vector
<struct DpkgState
> &states
= PackageOps
[pkg
];
460 const char *next_action
= NULL
;
461 if(PackageOpsDone
[pkg
] < states
.size())
462 next_action
= states
[PackageOpsDone
[pkg
]].state
;
463 // check if the package moved to the next dpkg state
464 if(next_action
&& (strcmp(action
, next_action
) == 0))
466 // only read the translation if there is actually a next
468 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
470 snprintf(s
, sizeof(s
), translation
, pkg
);
472 // we moved from one dpkg state to a new one, report that
473 PackageOpsDone
[pkg
]++;
475 // build the status str
476 status
<< "pmstatus:" << pkg
477 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
481 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
482 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
483 std::clog
<< "send: '" << status
.str() << "'" << endl
;
485 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
486 std::clog
<< "(parsed from dpkg) pkg: " << pkg
487 << " action: " << action
<< endl
;
490 // DPkgPM::DoDpkgStatusFd /*{{{*/
491 // ---------------------------------------------------------------------
494 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
, int OutStatusFd
)
499 len
=read(statusfd
, &dpkgbuf
[dpkgbuf_pos
], sizeof(dpkgbuf
)-dpkgbuf_pos
);
504 // process line by line if we have a buffer
506 while((q
=(char*)memchr(p
, '\n', dpkgbuf
+dpkgbuf_pos
-p
)) != NULL
)
509 ProcessDpkgStatusLine(OutStatusFd
, p
);
510 p
=q
+1; // continue with next line
513 // now move the unprocessed bits (after the final \n that is now a 0x0)
514 // to the start and update dpkgbuf_pos
515 p
= (char*)memrchr(dpkgbuf
, 0, dpkgbuf_pos
);
519 // we are interessted in the first char *after* 0x0
522 // move the unprocessed tail to the start and update pos
523 memmove(dpkgbuf
, p
, p
-dpkgbuf
);
524 dpkgbuf_pos
= dpkgbuf
+dpkgbuf_pos
-p
;
528 bool pkgDPkgPM::OpenLog()
530 string logdir
= _config
->FindDir("Dir::Log");
531 if(not FileExists(logdir
))
532 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
533 string logfile_name
= flCombine(logdir
,
534 _config
->Find("Dir::Log::Terminal"));
535 if (!logfile_name
.empty())
537 term_out
= fopen(logfile_name
.c_str(),"a");
538 chmod(logfile_name
.c_str(), 0600);
539 // output current time
541 time_t t
= time(NULL
);
542 struct tm
*tmp
= localtime(&t
);
543 strftime(outstr
, sizeof(outstr
), "%F %T", tmp
);
544 fprintf(term_out
, "\nLog started: ");
545 fprintf(term_out
, "%s", outstr
);
546 fprintf(term_out
, "\n");
551 bool pkgDPkgPM::CloseLog()
556 time_t t
= time(NULL
);
557 struct tm
*tmp
= localtime(&t
);
558 strftime(outstr
, sizeof(outstr
), "%F %T", tmp
);
559 fprintf(term_out
, "Log ended: ");
560 fprintf(term_out
, "%s", outstr
);
561 fprintf(term_out
, "\n");
569 // This implements a racy version of pselect for those architectures
570 // that don't have a working implementation.
571 // FIXME: Probably can be removed on Lenny+1
572 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
573 fd_set
*exceptfds
, const struct timespec
*timeout
,
574 const sigset_t
*sigmask
)
580 tv
.tv_sec
= timeout
->tv_sec
;
581 tv
.tv_usec
= timeout
->tv_nsec
/1000;
583 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
584 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
585 sigprocmask(SIG_SETMASK
, &origmask
, 0);
590 // DPkgPM::Go - Run the sequence /*{{{*/
591 // ---------------------------------------------------------------------
592 /* This globs the operations and calls dpkg
594 * If it is called with "OutStatusFd" set to a valid file descriptor
595 * apt will report the install progress over this fd. It maps the
596 * dpkg states a package goes through to human readable (and i10n-able)
597 * names and calculates a percentage for each step.
599 bool pkgDPkgPM::Go(int OutStatusFd
)
604 sigset_t original_sigmask
;
606 unsigned int MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
607 unsigned int MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
608 bool NoTriggers
= _config
->FindB("DPkg::NoTriggers",false);
610 if (RunScripts("DPkg::Pre-Invoke") == false)
613 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
616 // map the dpkg states to the operations that are performed
617 // (this is sorted in the same way as Item::Ops)
618 static const struct DpkgState DpkgStatesOpMap
[][7] = {
621 {"half-installed", N_("Preparing %s")},
622 {"unpacked", N_("Unpacking %s") },
625 // Configure operation
627 {"unpacked",N_("Preparing to configure %s") },
628 {"half-configured", N_("Configuring %s") },
630 {"triggers-awaited", N_("Processing triggers for %s") },
631 {"triggers-pending", N_("Processing triggers for %s") },
633 { "installed", N_("Installed %s")},
638 {"half-configured", N_("Preparing for removal of %s")},
640 {"triggers-awaited", N_("Preparing for removal of %s")},
641 {"triggers-pending", N_("Preparing for removal of %s")},
643 {"half-installed", N_("Removing %s")},
644 {"config-files", N_("Removed %s")},
649 {"config-files", N_("Preparing to completely remove %s")},
650 {"not-installed", N_("Completely removed %s")},
655 // init the PackageOps map, go over the list of packages that
656 // that will be [installed|configured|removed|purged] and add
657 // them to the PackageOps map (the dpkg states it goes through)
658 // and the PackageOpsTranslations (human readable strings)
659 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end();I
++)
661 string name
= (*I
).Pkg
.Name();
662 PackageOpsDone
[name
] = 0;
663 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; i
++)
665 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
670 stdin_is_dev_null
= false;
675 // this loop is runs once per operation
676 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end();)
678 vector
<Item
>::iterator J
= I
;
679 for (; J
!= List
.end() && J
->Op
== I
->Op
; J
++);
681 // Generate the argument list
682 const char *Args
[MaxArgs
+ 50];
683 if (J
- I
> (signed)MaxArgs
)
687 unsigned long Size
= 0;
688 string Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
689 Args
[n
++] = Tmp
.c_str();
690 Size
+= strlen(Args
[n
-1]);
692 // Stick in any custom dpkg options
693 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
697 for (; Opts
!= 0; Opts
= Opts
->Next
)
699 if (Opts
->Value
.empty() == true)
701 Args
[n
++] = Opts
->Value
.c_str();
702 Size
+= Opts
->Value
.length();
706 char status_fd_buf
[20];
710 Args
[n
++] = "--status-fd";
711 Size
+= strlen(Args
[n
-1]);
712 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
713 Args
[n
++] = status_fd_buf
;
714 Size
+= strlen(Args
[n
-1]);
719 Args
[n
++] = "--force-depends";
720 Size
+= strlen(Args
[n
-1]);
721 Args
[n
++] = "--force-remove-essential";
722 Size
+= strlen(Args
[n
-1]);
723 Args
[n
++] = "--remove";
724 Size
+= strlen(Args
[n
-1]);
728 Args
[n
++] = "--force-depends";
729 Size
+= strlen(Args
[n
-1]);
730 Args
[n
++] = "--force-remove-essential";
731 Size
+= strlen(Args
[n
-1]);
732 Args
[n
++] = "--purge";
733 Size
+= strlen(Args
[n
-1]);
736 case Item::Configure
:
737 Args
[n
++] = "--configure";
739 Args
[n
++] = "--no-triggers";
740 Size
+= strlen(Args
[n
-1]);
744 Args
[n
++] = "--unpack";
745 Size
+= strlen(Args
[n
-1]);
746 Args
[n
++] = "--auto-deconfigure";
747 Size
+= strlen(Args
[n
-1]);
751 // Write in the file or package names
752 if (I
->Op
== Item::Install
)
754 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
756 if (I
->File
[0] != '/')
757 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
758 Args
[n
++] = I
->File
.c_str();
759 Size
+= strlen(Args
[n
-1]);
764 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
766 Args
[n
++] = I
->Pkg
.Name();
767 Size
+= strlen(Args
[n
-1]);
773 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
775 for (unsigned int k
= 0; k
!= n
; k
++)
776 clog
<< Args
[k
] << ' ';
785 /* Mask off sig int/quit. We do this because dpkg also does when
786 it forks scripts. What happens is that when you hit ctrl-c it sends
787 it to all processes in the group. Since dpkg ignores the signal
788 it doesn't die but we do! So we must also ignore it */
789 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
790 sighandler_t old_SIGINT
= signal(SIGINT
,SIG_IGN
);
792 // ignore SIGHUP as well (debian #463030)
793 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
796 struct termios tt_out
;
801 // FIXME: setup sensible signal handling (*ick*)
803 tcgetattr(1, &tt_out
);
804 ioctl(0, TIOCGWINSZ
, (char *)&win
);
805 if (openpty(&master
, &slave
, NULL
, &tt_out
, &win
) < 0)
807 const char *s
= _("Can not write log, openpty() "
808 "failed (/dev/pts not mounted?)\n");
809 fprintf(stderr
, "%s",s
);
810 fprintf(term_out
, "%s",s
);
816 rtt
.c_lflag
&= ~ECHO
;
817 // block SIGTTOU during tcsetattr to prevent a hang if
818 // the process is a member of the background process group
819 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
820 sigemptyset(&sigmask
);
821 sigaddset(&sigmask
, SIGTTOU
);
822 sigprocmask(SIG_BLOCK
,&sigmask
, &original_sigmask
);
823 tcsetattr(0, TCSAFLUSH
, &rtt
);
824 sigprocmask(SIG_SETMASK
, &original_sigmask
, 0);
829 _config
->Set("APT::Keep-Fds::",fd
[1]);
835 if(slave
>= 0 && master
>= 0)
838 ioctl(slave
, TIOCSCTTY
, 0);
845 close(fd
[0]); // close the read end of the pipe
847 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
850 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
853 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
856 // Discard everything in stdin before forking dpkg
857 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
860 while (read(STDIN_FILENO
,&dummy
,1) == 1);
862 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
867 /* No Job Control Stop Env is a magic dpkg var that prevents it
868 from using sigstop */
869 putenv((char *)"DPKG_NO_TSTP=yes");
870 execvp(Args
[0],(char **)Args
);
871 cerr
<< "Could not exec dpkg!" << endl
;
875 // clear the Keep-Fd again
876 _config
->Clear("APT::Keep-Fds",fd
[1]);
881 // we read from dpkg here
883 close(fd
[1]); // close the write end of the pipe
885 // the result of the waitpid call
891 sigemptyset(&sigmask
);
892 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
895 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
897 // FIXME: move this to a function or something, looks ugly here
898 // error handling, waitpid returned -1
901 RunScripts("DPkg::Post-Invoke");
903 // Restore sig int/quit
904 signal(SIGQUIT
,old_SIGQUIT
);
905 signal(SIGINT
,old_SIGINT
);
906 signal(SIGHUP
,old_SIGHUP
);
907 return _error
->Errno("waitpid","Couldn't wait for subprocess");
909 // wait for input or output here
911 if (!stdin_is_dev_null
)
913 FD_SET(_dpkgin
, &rfds
);
915 FD_SET(master
, &rfds
);
918 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
919 &tv
, &original_sigmask
);
920 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
921 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
922 NULL
, &tv
, &original_sigmask
);
925 else if (select_ret
< 0 && errno
== EINTR
)
927 else if (select_ret
< 0)
929 perror("select() returned error");
933 if(master
>= 0 && FD_ISSET(master
, &rfds
))
934 DoTerminalPty(master
);
935 if(master
>= 0 && FD_ISSET(0, &rfds
))
937 if(FD_ISSET(_dpkgin
, &rfds
))
938 DoDpkgStatusFd(_dpkgin
, OutStatusFd
);
942 // Restore sig int/quit
943 signal(SIGQUIT
,old_SIGQUIT
);
944 signal(SIGINT
,old_SIGINT
);
945 signal(SIGHUP
,old_SIGHUP
);
949 tcsetattr(0, TCSAFLUSH
, &tt
);
953 // Check for an error code.
954 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
956 // if it was set to "keep-dpkg-runing" then we won't return
957 // here but keep the loop going and just report it as a error
959 bool stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
962 RunScripts("DPkg::Post-Invoke");
964 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
965 _error
->Error("Sub-process %s received a segmentation fault.",Args
[0]);
966 else if (WIFEXITED(Status
) != 0)
967 _error
->Error("Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
969 _error
->Error("Sub-process %s exited unexpectedly",Args
[0]);
980 if (RunScripts("DPkg::Post-Invoke") == false)
983 Cache
.writeStateFile(NULL
);
987 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
988 // ---------------------------------------------------------------------
990 void pkgDPkgPM::Reset()
992 List
.erase(List
.begin(),List
.end());
995 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
996 // ---------------------------------------------------------------------
998 void pkgDPkgPM::WriteApportReport(const char *pkgpath
, const char *errormsg
)
1000 string pkgname
, reportfile
, srcpkgname
, pkgver
, arch
;
1001 string::size_type pos
;
1004 if (_config
->FindB("Dpkg::ApportFailureReport",true) == false)
1006 std::clog
<< "configured to not write apport reports" << std::endl
;
1010 // only report the first errors
1011 if(pkgFailures
> _config
->FindI("APT::Apport::MaxReports", 3))
1013 std::clog
<< _("No apport report written because MaxReports is reached already") << std::endl
;
1017 // check if its not a follow up error
1018 const char *needle
= dgettext("dpkg", "dependency problems - leaving unconfigured");
1019 if(strstr(errormsg
, needle
) != NULL
) {
1020 std::clog
<< _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl
;
1024 // do not report disk-full failures
1025 if(strstr(errormsg
, strerror(ENOSPC
)) != NULL
) {
1026 std::clog
<< _("No apport report written because the error message indicates a disk full error") << std::endl
;
1030 // get the pkgname and reportfile
1031 pkgname
= flNotDir(pkgpath
);
1032 pos
= pkgname
.find('_');
1033 if(pos
!= string::npos
)
1034 pkgname
= pkgname
.substr(0, pos
);
1036 // find the package versin and source package name
1037 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
1038 if (Pkg
.end() == true)
1040 pkgCache::VerIterator Ver
= Cache
.GetCandidateVer(Pkg
);
1041 if (Ver
.end() == true)
1043 pkgver
= Ver
.VerStr() == NULL
? "unknown" : Ver
.VerStr();
1044 pkgRecords
Recs(Cache
);
1045 pkgRecords::Parser
&Parse
= Recs
.Lookup(Ver
.FileList());
1046 srcpkgname
= Parse
.SourcePkg();
1047 if(srcpkgname
.empty())
1048 srcpkgname
= pkgname
;
1050 // if the file exists already, we check:
1051 // - if it was reported already (touched by apport).
1052 // If not, we do nothing, otherwise
1053 // we overwrite it. This is the same behaviour as apport
1054 // - if we have a report with the same pkgversion already
1056 reportfile
= flCombine("/var/crash",pkgname
+".0.crash");
1057 if(FileExists(reportfile
))
1062 // check atime/mtime
1063 stat(reportfile
.c_str(), &buf
);
1064 if(buf
.st_mtime
> buf
.st_atime
)
1067 // check if the existing report is the same version
1068 report
= fopen(reportfile
.c_str(),"r");
1069 while(fgets(strbuf
, sizeof(strbuf
), report
) != NULL
)
1071 if(strstr(strbuf
,"Package:") == strbuf
)
1073 char pkgname
[255], version
[255];
1074 if(sscanf(strbuf
, "Package: %s %s", pkgname
, version
) == 2)
1075 if(strcmp(pkgver
.c_str(), version
) == 0)
1085 // now write the report
1086 arch
= _config
->Find("APT::Architecture");
1087 report
= fopen(reportfile
.c_str(),"w");
1090 if(_config
->FindB("DPkgPM::InitialReportOnly",false) == true)
1091 chmod(reportfile
.c_str(), 0);
1093 chmod(reportfile
.c_str(), 0600);
1094 fprintf(report
, "ProblemType: Package\n");
1095 fprintf(report
, "Architecture: %s\n", arch
.c_str());
1096 time_t now
= time(NULL
);
1097 fprintf(report
, "Date: %s" , ctime(&now
));
1098 fprintf(report
, "Package: %s %s\n", pkgname
.c_str(), pkgver
.c_str());
1099 fprintf(report
, "SourcePackage: %s\n", srcpkgname
.c_str());
1100 fprintf(report
, "ErrorMessage:\n %s\n", errormsg
);
1102 // ensure that the log is flushed
1106 // attach terminal log it if we have it
1107 string logfile_name
= _config
->FindFile("Dir::Log::Terminal");
1108 if (!logfile_name
.empty())
1113 fprintf(report
, "DpkgTerminalLog:\n");
1114 log
= fopen(logfile_name
.c_str(),"r");
1117 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1118 fprintf(report
, " %s", buf
);