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>
22 #include <sys/select.h>
23 #include <sys/types.h>
33 #include <sys/ioctl.h>
44 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
45 // ---------------------------------------------------------------------
47 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
48 : pkgPackageManager(Cache
), dpkgbuf_pos(0),
49 term_out(NULL
), PackagesDone(0), PackagesTotal(0)
53 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
54 // ---------------------------------------------------------------------
56 pkgDPkgPM::~pkgDPkgPM()
60 // DPkgPM::Install - Install a package /*{{{*/
61 // ---------------------------------------------------------------------
62 /* Add an install operation to the sequence list */
63 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
65 if (File
.empty() == true || Pkg
.end() == true)
66 return _error
->Error("Internal Error, No file name for %s",Pkg
.Name());
68 List
.push_back(Item(Item::Install
,Pkg
,File
));
72 // DPkgPM::Configure - Configure a package /*{{{*/
73 // ---------------------------------------------------------------------
74 /* Add a configure operation to the sequence list */
75 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
77 if (Pkg
.end() == true)
80 List
.push_back(Item(Item::Configure
,Pkg
));
84 // DPkgPM::Remove - Remove a package /*{{{*/
85 // ---------------------------------------------------------------------
86 /* Add a remove operation to the sequence list */
87 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
89 if (Pkg
.end() == true)
93 List
.push_back(Item(Item::Purge
,Pkg
));
95 List
.push_back(Item(Item::Remove
,Pkg
));
99 // DPkgPM::RunScripts - Run a set of scripts /*{{{*/
100 // ---------------------------------------------------------------------
101 /* This looks for a list of script sto run from the configuration file,
102 each one is run with system from a forked child. */
103 bool pkgDPkgPM::RunScripts(const char *Cnf
)
105 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
106 if (Opts
== 0 || Opts
->Child
== 0)
110 // Fork for running the system calls
111 pid_t Child
= ExecFork();
116 if (chdir("/tmp/") != 0)
119 unsigned int Count
= 1;
120 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
122 if (Opts
->Value
.empty() == true)
125 if (system(Opts
->Value
.c_str()) != 0)
131 // Wait for the child
133 while (waitpid(Child
,&Status
,0) != Child
)
137 return _error
->Errno("waitpid","Couldn't wait for subprocess");
140 // Restore sig int/quit
141 signal(SIGQUIT
,SIG_DFL
);
142 signal(SIGINT
,SIG_DFL
);
144 // Check for an error code.
145 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
147 unsigned int Count
= WEXITSTATUS(Status
);
151 for (; Opts
!= 0 && Count
!= 1; Opts
= Opts
->Next
, Count
--);
152 _error
->Error("Problem executing scripts %s '%s'",Cnf
,Opts
->Value
.c_str());
155 return _error
->Error("Sub-process returned an error code");
161 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
162 // ---------------------------------------------------------------------
163 /* This is part of the helper script communication interface, it sends
164 very complete information down to the other end of the pipe.*/
165 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
167 fprintf(F
,"VERSION 2\n");
169 /* Write out all of the configuration directives by walking the
170 configuration tree */
171 const Configuration::Item
*Top
= _config
->Tree(0);
174 if (Top
->Value
.empty() == false)
177 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
178 QuoteString(Top
->Value
,"\n").c_str());
187 while (Top
!= 0 && Top
->Next
== 0)
194 // Write out the package actions in order.
195 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
197 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
199 fprintf(F
,"%s ",I
->Pkg
.Name());
201 if (I
->Pkg
->CurrentVer
== 0)
204 fprintf(F
,"%s ",I
->Pkg
.CurrentVer().VerStr());
206 // Show the compare operator
208 if (S
.InstallVer
!= 0)
211 if (I
->Pkg
->CurrentVer
!= 0)
212 Comp
= S
.InstVerIter(Cache
).CompareVer(I
->Pkg
.CurrentVer());
219 fprintf(F
,"%s ",S
.InstVerIter(Cache
).VerStr());
224 // Show the filename/operation
225 if (I
->Op
== Item::Install
)
228 if (I
->File
[0] != '/')
229 fprintf(F
,"**ERROR**\n");
231 fprintf(F
,"%s\n",I
->File
.c_str());
233 if (I
->Op
== Item::Configure
)
234 fprintf(F
,"**CONFIGURE**\n");
235 if (I
->Op
== Item::Remove
||
236 I
->Op
== Item::Purge
)
237 fprintf(F
,"**REMOVE**\n");
245 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
246 // ---------------------------------------------------------------------
247 /* This looks for a list of scripts to run from the configuration file
248 each one is run and is fed on standard input a list of all .deb files
249 that are due to be installed. */
250 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
252 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
253 if (Opts
== 0 || Opts
->Child
== 0)
257 unsigned int Count
= 1;
258 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
260 if (Opts
->Value
.empty() == true)
263 // Determine the protocol version
264 string OptSec
= Opts
->Value
;
265 string::size_type Pos
;
266 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
267 Pos
= OptSec
.length();
268 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
270 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
274 if (pipe(Pipes
) != 0)
275 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
276 SetCloseExec(Pipes
[0],true);
277 SetCloseExec(Pipes
[1],true);
279 // Purified Fork for running the script
280 pid_t Process
= ExecFork();
284 dup2(Pipes
[0],STDIN_FILENO
);
285 SetCloseExec(STDOUT_FILENO
,false);
286 SetCloseExec(STDIN_FILENO
,false);
287 SetCloseExec(STDERR_FILENO
,false);
292 Args
[2] = Opts
->Value
.c_str();
294 execv(Args
[0],(char **)Args
);
298 FILE *F
= fdopen(Pipes
[1],"w");
300 return _error
->Errno("fdopen","Faild to open new FD");
302 // Feed it the filenames.
306 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
308 // Only deal with packages to be installed from .deb
309 if (I
->Op
!= Item::Install
)
313 if (I
->File
[0] != '/')
316 /* Feed the filename of each package that is pending install
318 fprintf(F
,"%s\n",I
->File
.c_str());
327 Die
= !SendV2Pkgs(F
);
331 // Clean up the sub process
332 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
333 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
339 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
340 // ---------------------------------------------------------------------
343 void pkgDPkgPM::DoStdin(int master
)
345 unsigned char input_buf
[256] = {0,};
346 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
348 write(master
, input_buf
, len
);
350 stdin_is_dev_null
= true;
353 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
354 // ---------------------------------------------------------------------
356 * read the terminal pty and write log
358 void pkgDPkgPM::DoTerminalPty(int master
)
360 unsigned char term_buf
[1024] = {0,0, };
362 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
363 if(len
== -1 && errno
== EIO
)
365 // this happens when the child is about to exit, we
366 // give it time to actually exit, otherwise we run
373 write(1, term_buf
, len
);
375 fwrite(term_buf
, len
, sizeof(char), term_out
);
378 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
379 // ---------------------------------------------------------------------
382 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd
, char *line
)
384 // the status we output
385 ostringstream status
;
387 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
388 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
391 /* dpkg sends strings like this:
392 'status: <pkg>: <pkg qstate>'
393 errors look like this:
394 '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
395 and conffile-prompt like this
396 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
400 // dpkg sends multiline error messages sometimes (see
401 // #374195 for a example. we should support this by
402 // either patching dpkg to not send multiline over the
403 // statusfd or by rewriting the code here to deal with
404 // it. for now we just ignore it and not crash
405 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
406 if( list
[0] == NULL
|| list
[1] == NULL
|| list
[2] == NULL
)
408 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
409 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
413 char *action
= _strstrip(list
[2]);
415 if(strncmp(action
,"error",strlen("error")) == 0)
417 status
<< "pmerror:" << list
[1]
418 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
422 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
423 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
424 std::clog
<< "send: '" << status
.str() << "'" << endl
;
426 WriteApportReport(list
[1], list
[3]);
429 if(strncmp(action
,"conffile",strlen("conffile")) == 0)
431 status
<< "pmconffile:" << list
[1]
432 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
436 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
437 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
438 std::clog
<< "send: '" << status
.str() << "'" << endl
;
442 vector
<struct DpkgState
> &states
= PackageOps
[pkg
];
443 const char *next_action
= NULL
;
444 if(PackageOpsDone
[pkg
] < states
.size())
445 next_action
= states
[PackageOpsDone
[pkg
]].state
;
446 // check if the package moved to the next dpkg state
447 if(next_action
&& (strcmp(action
, next_action
) == 0))
449 // only read the translation if there is actually a next
451 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
453 snprintf(s
, sizeof(s
), translation
, pkg
);
455 // we moved from one dpkg state to a new one, report that
456 PackageOpsDone
[pkg
]++;
458 // build the status str
459 status
<< "pmstatus:" << pkg
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 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
469 std::clog
<< "(parsed from dpkg) pkg: " << pkg
470 << " action: " << action
<< endl
;
473 // DPkgPM::DoDpkgStatusFd /*{{{*/
474 // ---------------------------------------------------------------------
477 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
, int OutStatusFd
)
482 len
=read(statusfd
, &dpkgbuf
[dpkgbuf_pos
], sizeof(dpkgbuf
)-dpkgbuf_pos
);
487 // process line by line if we have a buffer
489 while((q
=(char*)memchr(p
, '\n', dpkgbuf
+dpkgbuf_pos
-p
)) != NULL
)
492 ProcessDpkgStatusLine(OutStatusFd
, p
);
493 p
=q
+1; // continue with next line
496 // now move the unprocessed bits (after the final \n that is now a 0x0)
497 // to the start and update dpkgbuf_pos
498 p
= (char*)memrchr(dpkgbuf
, 0, dpkgbuf_pos
);
502 // we are interessted in the first char *after* 0x0
505 // move the unprocessed tail to the start and update pos
506 memmove(dpkgbuf
, p
, p
-dpkgbuf
);
507 dpkgbuf_pos
= dpkgbuf
+dpkgbuf_pos
-p
;
511 bool pkgDPkgPM::OpenLog()
513 string logdir
= _config
->FindDir("Dir::Log");
514 if(not FileExists(logdir
))
515 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
516 string logfile_name
= flCombine(logdir
,
517 _config
->Find("Dir::Log::Terminal"));
518 if (!logfile_name
.empty())
520 term_out
= fopen(logfile_name
.c_str(),"a");
521 chmod(logfile_name
.c_str(), 0600);
522 // output current time
524 time_t t
= time(NULL
);
525 struct tm
*tmp
= localtime(&t
);
526 strftime(outstr
, sizeof(outstr
), "%F %T", tmp
);
527 fprintf(term_out
, "\nLog started: ");
528 fprintf(term_out
, outstr
);
529 fprintf(term_out
, "\n");
534 bool pkgDPkgPM::CloseLog()
539 time_t t
= time(NULL
);
540 struct tm
*tmp
= localtime(&t
);
541 strftime(outstr
, sizeof(outstr
), "%F %T", tmp
);
542 fprintf(term_out
, "Log ended: ");
543 fprintf(term_out
, outstr
);
544 fprintf(term_out
, "\n");
552 // This implements a racy version of pselect for those architectures
553 // that don't have a working implementation.
554 // FIXME: Probably can be removed on Lenny+1
555 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
556 fd_set
*exceptfds
, const struct timespec
*timeout
,
557 const sigset_t
*sigmask
)
563 tv
.tv_sec
= timeout
->tv_sec
;
564 tv
.tv_usec
= timeout
->tv_nsec
/1000;
566 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
567 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
568 sigprocmask(SIG_SETMASK
, &origmask
, 0);
573 // DPkgPM::Go - Run the sequence /*{{{*/
574 // ---------------------------------------------------------------------
575 /* This globs the operations and calls dpkg
577 * If it is called with "OutStatusFd" set to a valid file descriptor
578 * apt will report the install progress over this fd. It maps the
579 * dpkg states a package goes through to human readable (and i10n-able)
580 * names and calculates a percentage for each step.
582 bool pkgDPkgPM::Go(int OutStatusFd
)
584 unsigned int MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
585 unsigned int MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
587 if (RunScripts("DPkg::Pre-Invoke") == false)
590 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
593 // map the dpkg states to the operations that are performed
594 // (this is sorted in the same way as Item::Ops)
595 static const struct DpkgState DpkgStatesOpMap
[][7] = {
598 {"half-installed", N_("Preparing %s")},
599 {"unpacked", N_("Unpacking %s") },
602 // Configure operation
604 {"unpacked",N_("Preparing to configure %s") },
605 {"half-configured", N_("Configuring %s") },
607 {"triggers-awaited", N_("Processing triggers for %s") },
608 {"triggers-pending", N_("Processing triggers for %s") },
610 { "installed", N_("Installed %s")},
615 {"half-configured", N_("Preparing for removal of %s")},
617 {"triggers-awaited", N_("Preparing for removal of %s")},
618 {"triggers-pending", N_("Preparing for removal of %s")},
620 {"half-installed", N_("Removing %s")},
621 {"config-files", N_("Removed %s")},
626 {"config-files", N_("Preparing to completely remove %s")},
627 {"not-installed", N_("Completely removed %s")},
632 // init the PackageOps map, go over the list of packages that
633 // that will be [installed|configured|removed|purged] and add
634 // them to the PackageOps map (the dpkg states it goes through)
635 // and the PackageOpsTranslations (human readable strings)
636 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end();I
++)
638 string name
= (*I
).Pkg
.Name();
639 PackageOpsDone
[name
] = 0;
640 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; i
++)
642 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
647 stdin_is_dev_null
= false;
652 // this loop is runs once per operation
653 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end();)
655 vector
<Item
>::iterator J
= I
;
656 for (; J
!= List
.end() && J
->Op
== I
->Op
; J
++);
658 // Generate the argument list
659 const char *Args
[MaxArgs
+ 50];
660 if (J
- I
> (signed)MaxArgs
)
664 unsigned long Size
= 0;
665 string Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
666 Args
[n
++] = Tmp
.c_str();
667 Size
+= strlen(Args
[n
-1]);
669 // Stick in any custom dpkg options
670 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
674 for (; Opts
!= 0; Opts
= Opts
->Next
)
676 if (Opts
->Value
.empty() == true)
678 Args
[n
++] = Opts
->Value
.c_str();
679 Size
+= Opts
->Value
.length();
683 char status_fd_buf
[20];
687 Args
[n
++] = "--status-fd";
688 Size
+= strlen(Args
[n
-1]);
689 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
690 Args
[n
++] = status_fd_buf
;
691 Size
+= strlen(Args
[n
-1]);
696 Args
[n
++] = "--force-depends";
697 Size
+= strlen(Args
[n
-1]);
698 Args
[n
++] = "--force-remove-essential";
699 Size
+= strlen(Args
[n
-1]);
700 Args
[n
++] = "--remove";
701 Size
+= strlen(Args
[n
-1]);
705 Args
[n
++] = "--force-depends";
706 Size
+= strlen(Args
[n
-1]);
707 Args
[n
++] = "--force-remove-essential";
708 Size
+= strlen(Args
[n
-1]);
709 Args
[n
++] = "--purge";
710 Size
+= strlen(Args
[n
-1]);
713 case Item::Configure
:
714 Args
[n
++] = "--configure";
715 Size
+= strlen(Args
[n
-1]);
719 Args
[n
++] = "--unpack";
720 Size
+= strlen(Args
[n
-1]);
721 Args
[n
++] = "--auto-deconfigure";
722 Size
+= strlen(Args
[n
-1]);
726 // Write in the file or package names
727 if (I
->Op
== Item::Install
)
729 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
731 if (I
->File
[0] != '/')
732 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
733 Args
[n
++] = I
->File
.c_str();
734 Size
+= strlen(Args
[n
-1]);
739 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
741 Args
[n
++] = I
->Pkg
.Name();
742 Size
+= strlen(Args
[n
-1]);
748 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
750 for (unsigned int k
= 0; k
!= n
; k
++)
751 clog
<< Args
[k
] << ' ';
760 /* Mask off sig int/quit. We do this because dpkg also does when
761 it forks scripts. What happens is that when you hit ctrl-c it sends
762 it to all processes in the group. Since dpkg ignores the signal
763 it doesn't die but we do! So we must also ignore it */
764 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
765 sighandler_t old_SIGINT
= signal(SIGINT
,SIG_IGN
);
772 // FIXME: setup sensible signal handling (*ick*)
774 ioctl(0, TIOCGWINSZ
, (char *)&win
);
775 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
777 const char *s
= _("Can not write log, openpty() "
778 "failed (/dev/pts not mounted?)\n");
779 fprintf(stderr
, "%s",s
);
780 fprintf(term_out
, "%s",s
);
786 rtt
.c_lflag
&= ~ECHO
;
787 tcsetattr(0, TCSAFLUSH
, &rtt
);
792 _config
->Set("APT::Keep-Fds::",fd
[1]);
798 if(slave
>= 0 && master
>= 0)
801 ioctl(slave
, TIOCSCTTY
, 0);
808 close(fd
[0]); // close the read end of the pipe
810 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
813 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
816 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
819 // Discard everything in stdin before forking dpkg
820 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
823 while (read(STDIN_FILENO
,&dummy
,1) == 1);
825 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
830 /* No Job Control Stop Env is a magic dpkg var that prevents it
831 from using sigstop */
832 putenv((char *)"DPKG_NO_TSTP=yes");
833 execvp(Args
[0],(char **)Args
);
834 cerr
<< "Could not exec dpkg!" << endl
;
838 // clear the Keep-Fd again
839 _config
->Clear("APT::Keep-Fds",fd
[1]);
844 // we read from dpkg here
846 close(fd
[1]); // close the write end of the pipe
848 // the result of the waitpid call
857 sigset_t original_sigmask
;
858 sigemptyset(&sigmask
);
859 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
862 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
864 // FIXME: move this to a function or something, looks ugly here
865 // error handling, waitpid returned -1
868 RunScripts("DPkg::Post-Invoke");
870 // Restore sig int/quit
871 signal(SIGQUIT
,old_SIGQUIT
);
872 signal(SIGINT
,old_SIGINT
);
873 return _error
->Errno("waitpid","Couldn't wait for subprocess");
875 // wait for input or output here
877 if (!stdin_is_dev_null
)
879 FD_SET(_dpkgin
, &rfds
);
881 FD_SET(master
, &rfds
);
884 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
885 &tv
, &original_sigmask
);
886 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
887 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
888 NULL
, &tv
, &original_sigmask
);
891 else if (select_ret
< 0 && errno
== EINTR
)
893 else if (select_ret
< 0)
895 perror("select() returned error");
899 if(master
>= 0 && FD_ISSET(master
, &rfds
))
900 DoTerminalPty(master
);
901 if(master
>= 0 && FD_ISSET(0, &rfds
))
903 if(FD_ISSET(_dpkgin
, &rfds
))
904 DoDpkgStatusFd(_dpkgin
, OutStatusFd
);
908 // Restore sig int/quit
909 signal(SIGQUIT
,old_SIGQUIT
);
910 signal(SIGINT
,old_SIGINT
);
914 tcsetattr(0, TCSAFLUSH
, &tt
);
918 // Check for an error code.
919 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
921 // if it was set to "keep-dpkg-runing" then we won't return
922 // here but keep the loop going and just report it as a error
924 bool stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
927 RunScripts("DPkg::Post-Invoke");
929 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
930 _error
->Error("Sub-process %s received a segmentation fault.",Args
[0]);
931 else if (WIFEXITED(Status
) != 0)
932 _error
->Error("Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
934 _error
->Error("Sub-process %s exited unexpectedly",Args
[0]);
945 if (RunScripts("DPkg::Post-Invoke") == false)
950 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
951 // ---------------------------------------------------------------------
953 void pkgDPkgPM::Reset()
955 List
.erase(List
.begin(),List
.end());
958 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
959 // ---------------------------------------------------------------------
961 void pkgDPkgPM::WriteApportReport(const char *pkgpath
, const char *errormsg
)
963 string pkgname
, reportfile
, srcpkgname
, pkgver
, arch
;
964 string::size_type pos
;
967 if (_config
->FindB("Dpkg::ApportFailureReport",true) == false)
970 // only report the first error if we are in StopOnError=false mode
971 // to prevent bogus reports
972 if((_config
->FindB("Dpkg::StopOnError",true) == false) && pkgFailures
> 1)
975 // get the pkgname and reportfile
976 pkgname
= flNotDir(pkgpath
);
977 pos
= pkgname
.find('_');
978 if(pos
!= string::npos
)
979 pkgname
= pkgname
.substr(0, pos
);
981 // find the package versin and source package name
982 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
983 if (Pkg
.end() == true)
985 pkgCache::VerIterator Ver
= Cache
.GetCandidateVer(Pkg
);
986 if (Ver
.end() == true)
988 pkgver
= Ver
.VerStr() == NULL
? "unknown" : Ver
.VerStr();
989 pkgRecords
Recs(Cache
);
990 pkgRecords::Parser
&Parse
= Recs
.Lookup(Ver
.FileList());
991 srcpkgname
= Parse
.SourcePkg();
992 if(srcpkgname
.empty())
993 srcpkgname
= pkgname
;
995 // if the file exists already, we check:
996 // - if it was reported already (touched by apport).
997 // If not, we do nothing, otherwise
998 // we overwrite it. This is the same behaviour as apport
999 // - if we have a report with the same pkgversion already
1001 reportfile
= flCombine("/var/crash",pkgname
+".0.crash");
1002 if(FileExists(reportfile
))
1007 // check atime/mtime
1008 stat(reportfile
.c_str(), &buf
);
1009 if(buf
.st_mtime
> buf
.st_atime
)
1012 // check if the existing report is the same version
1013 report
= fopen(reportfile
.c_str(),"r");
1014 while(fgets(strbuf
, sizeof(strbuf
), report
) != NULL
)
1016 if(strstr(strbuf
,"Package:") == strbuf
)
1018 char pkgname
[255], version
[255];
1019 if(sscanf(strbuf
, "Package: %s %s", pkgname
, version
) == 2)
1020 if(strcmp(pkgver
.c_str(), version
) == 0)
1030 // now write the report
1031 arch
= _config
->Find("APT::Architecture");
1032 report
= fopen(reportfile
.c_str(),"w");
1035 if(_config
->FindB("DPkgPM::InitialReportOnly",false) == true)
1036 chmod(reportfile
.c_str(), 0);
1038 chmod(reportfile
.c_str(), 0600);
1039 fprintf(report
, "ProblemType: Package\n");
1040 fprintf(report
, "Architecture: %s\n", arch
.c_str());
1041 time_t now
= time(NULL
);
1042 fprintf(report
, "Date: %s" , ctime(&now
));
1043 fprintf(report
, "Package: %s %s\n", pkgname
.c_str(), pkgver
.c_str());
1044 fprintf(report
, "SourcePackage: %s\n", srcpkgname
.c_str());
1045 fprintf(report
, "ErrorMessage:\n %s\n", errormsg
);
1047 // ensure that the log is flushed
1051 // attach terminal log it if we have it
1052 string logfile_name
= _config
->FindFile("Dir::Log::Terminal");
1053 if (!logfile_name
.empty())
1058 fprintf(report
, "DpkgTerminalLog:\n");
1059 log
= fopen(logfile_name
.c_str(),"r");
1062 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1063 fprintf(report
, " %s", buf
);