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>
34 #include <sys/ioctl.h>
45 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
46 // ---------------------------------------------------------------------
48 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
49 : pkgPackageManager(Cache
), dpkgbuf_pos(0),
50 term_out(NULL
), PackagesDone(0), PackagesTotal(0), pkgFailures(0)
54 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
55 // ---------------------------------------------------------------------
57 pkgDPkgPM::~pkgDPkgPM()
61 // DPkgPM::Install - Install a package /*{{{*/
62 // ---------------------------------------------------------------------
63 /* Add an install operation to the sequence list */
64 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
66 if (File
.empty() == true || Pkg
.end() == true)
67 return _error
->Error("Internal Error, No file name for %s",Pkg
.Name());
69 List
.push_back(Item(Item::Install
,Pkg
,File
));
73 // DPkgPM::Configure - Configure a package /*{{{*/
74 // ---------------------------------------------------------------------
75 /* Add a configure operation to the sequence list */
76 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
78 if (Pkg
.end() == true)
81 List
.push_back(Item(Item::Configure
,Pkg
));
85 // DPkgPM::Remove - Remove a package /*{{{*/
86 // ---------------------------------------------------------------------
87 /* Add a remove operation to the sequence list */
88 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
90 if (Pkg
.end() == true)
94 List
.push_back(Item(Item::Purge
,Pkg
));
96 List
.push_back(Item(Item::Remove
,Pkg
));
100 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
101 // ---------------------------------------------------------------------
102 /* This is part of the helper script communication interface, it sends
103 very complete information down to the other end of the pipe.*/
104 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
106 fprintf(F
,"VERSION 2\n");
108 /* Write out all of the configuration directives by walking the
109 configuration tree */
110 const Configuration::Item
*Top
= _config
->Tree(0);
113 if (Top
->Value
.empty() == false)
116 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
117 QuoteString(Top
->Value
,"\n").c_str());
126 while (Top
!= 0 && Top
->Next
== 0)
133 // Write out the package actions in order.
134 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
136 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
138 fprintf(F
,"%s ",I
->Pkg
.Name());
140 if (I
->Pkg
->CurrentVer
== 0)
143 fprintf(F
,"%s ",I
->Pkg
.CurrentVer().VerStr());
145 // Show the compare operator
147 if (S
.InstallVer
!= 0)
150 if (I
->Pkg
->CurrentVer
!= 0)
151 Comp
= S
.InstVerIter(Cache
).CompareVer(I
->Pkg
.CurrentVer());
158 fprintf(F
,"%s ",S
.InstVerIter(Cache
).VerStr());
163 // Show the filename/operation
164 if (I
->Op
== Item::Install
)
167 if (I
->File
[0] != '/')
168 fprintf(F
,"**ERROR**\n");
170 fprintf(F
,"%s\n",I
->File
.c_str());
172 if (I
->Op
== Item::Configure
)
173 fprintf(F
,"**CONFIGURE**\n");
174 if (I
->Op
== Item::Remove
||
175 I
->Op
== Item::Purge
)
176 fprintf(F
,"**REMOVE**\n");
184 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
185 // ---------------------------------------------------------------------
186 /* This looks for a list of scripts to run from the configuration file
187 each one is run and is fed on standard input a list of all .deb files
188 that are due to be installed. */
189 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
191 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
192 if (Opts
== 0 || Opts
->Child
== 0)
196 unsigned int Count
= 1;
197 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
199 if (Opts
->Value
.empty() == true)
202 // Determine the protocol version
203 string OptSec
= Opts
->Value
;
204 string::size_type Pos
;
205 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
206 Pos
= OptSec
.length();
207 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
209 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
213 if (pipe(Pipes
) != 0)
214 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
215 SetCloseExec(Pipes
[0],true);
216 SetCloseExec(Pipes
[1],true);
218 // Purified Fork for running the script
219 pid_t Process
= ExecFork();
223 dup2(Pipes
[0],STDIN_FILENO
);
224 SetCloseExec(STDOUT_FILENO
,false);
225 SetCloseExec(STDIN_FILENO
,false);
226 SetCloseExec(STDERR_FILENO
,false);
231 Args
[2] = Opts
->Value
.c_str();
233 execv(Args
[0],(char **)Args
);
237 FILE *F
= fdopen(Pipes
[1],"w");
239 return _error
->Errno("fdopen","Faild to open new FD");
241 // Feed it the filenames.
245 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
247 // Only deal with packages to be installed from .deb
248 if (I
->Op
!= Item::Install
)
252 if (I
->File
[0] != '/')
255 /* Feed the filename of each package that is pending install
257 fprintf(F
,"%s\n",I
->File
.c_str());
266 Die
= !SendV2Pkgs(F
);
270 // Clean up the sub process
271 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
272 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
278 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
279 // ---------------------------------------------------------------------
282 void pkgDPkgPM::DoStdin(int master
)
284 unsigned char input_buf
[256] = {0,};
285 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
287 write(master
, input_buf
, len
);
289 stdin_is_dev_null
= true;
292 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
293 // ---------------------------------------------------------------------
295 * read the terminal pty and write log
297 void pkgDPkgPM::DoTerminalPty(int master
)
299 unsigned char term_buf
[1024] = {0,0, };
301 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
302 if(len
== -1 && errno
== EIO
)
304 // this happens when the child is about to exit, we
305 // give it time to actually exit, otherwise we run
312 write(1, term_buf
, len
);
314 fwrite(term_buf
, len
, sizeof(char), term_out
);
317 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
318 // ---------------------------------------------------------------------
321 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd
, char *line
)
323 // the status we output
324 ostringstream status
;
326 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
327 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
330 /* dpkg sends strings like this:
331 'status: <pkg>: <pkg qstate>'
332 errors look like this:
333 '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
334 and conffile-prompt like this
335 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
337 Newer versions of dpkg sent also:
338 'processing: install: pkg'
339 'processing: configure: pkg'
340 'processing: remove: pkg'
341 'processing: trigproc: trigger'
345 // dpkg sends multiline error messages sometimes (see
346 // #374195 for a example. we should support this by
347 // either patching dpkg to not send multiline over the
348 // statusfd or by rewriting the code here to deal with
349 // it. for now we just ignore it and not crash
350 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
351 if( list
[0] == NULL
|| list
[1] == NULL
|| list
[2] == NULL
)
353 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
354 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
358 char *action
= _strstrip(list
[2]);
360 // 'processing' from dpkg looks like
361 // 'processing: action: pkg'
362 if(strncmp(list
[0], "processing", strlen("processing")) == 0)
365 map
<string
,string
>::iterator iter
;
366 char *pkg_or_trigger
= _strstrip(list
[2]);
367 action
=_strstrip( list
[1]);
368 iter
= PackageProcessingOps
.find(action
);
369 if(iter
== PackageProcessingOps
.end())
371 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
372 std::clog
<< "ignoring unknwon action: " << action
<< std::endl
;
375 snprintf(s
, sizeof(s
), _(iter
->second
.c_str()), pkg_or_trigger
);
377 status
<< "pmstatus:" << pkg_or_trigger
378 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
382 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
383 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
384 std::clog
<< "send: '" << status
.str() << "'" << endl
;
388 if(strncmp(action
,"error",strlen("error")) == 0)
390 status
<< "pmerror:" << list
[1]
391 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
395 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
396 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
397 std::clog
<< "send: '" << status
.str() << "'" << endl
;
399 WriteApportReport(list
[1], list
[3]);
402 if(strncmp(action
,"conffile",strlen("conffile")) == 0)
404 status
<< "pmconffile:" << list
[1]
405 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
409 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
410 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
411 std::clog
<< "send: '" << status
.str() << "'" << endl
;
415 vector
<struct DpkgState
> &states
= PackageOps
[pkg
];
416 const char *next_action
= NULL
;
417 if(PackageOpsDone
[pkg
] < states
.size())
418 next_action
= states
[PackageOpsDone
[pkg
]].state
;
419 // check if the package moved to the next dpkg state
420 if(next_action
&& (strcmp(action
, next_action
) == 0))
422 // only read the translation if there is actually a next
424 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
426 snprintf(s
, sizeof(s
), translation
, pkg
);
428 // we moved from one dpkg state to a new one, report that
429 PackageOpsDone
[pkg
]++;
431 // build the status str
432 status
<< "pmstatus:" << pkg
433 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
437 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
438 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
439 std::clog
<< "send: '" << status
.str() << "'" << endl
;
441 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
442 std::clog
<< "(parsed from dpkg) pkg: " << pkg
443 << " action: " << action
<< endl
;
446 // DPkgPM::DoDpkgStatusFd /*{{{*/
447 // ---------------------------------------------------------------------
450 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
, int OutStatusFd
)
455 len
=read(statusfd
, &dpkgbuf
[dpkgbuf_pos
], sizeof(dpkgbuf
)-dpkgbuf_pos
);
460 // process line by line if we have a buffer
462 while((q
=(char*)memchr(p
, '\n', dpkgbuf
+dpkgbuf_pos
-p
)) != NULL
)
465 ProcessDpkgStatusLine(OutStatusFd
, p
);
466 p
=q
+1; // continue with next line
469 // now move the unprocessed bits (after the final \n that is now a 0x0)
470 // to the start and update dpkgbuf_pos
471 p
= (char*)memrchr(dpkgbuf
, 0, dpkgbuf_pos
);
475 // we are interessted in the first char *after* 0x0
478 // move the unprocessed tail to the start and update pos
479 memmove(dpkgbuf
, p
, p
-dpkgbuf
);
480 dpkgbuf_pos
= dpkgbuf
+dpkgbuf_pos
-p
;
484 bool pkgDPkgPM::OpenLog()
486 string logdir
= _config
->FindDir("Dir::Log");
487 if(not FileExists(logdir
))
488 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
489 string logfile_name
= flCombine(logdir
,
490 _config
->Find("Dir::Log::Terminal"));
491 if (!logfile_name
.empty())
493 term_out
= fopen(logfile_name
.c_str(),"a");
494 chmod(logfile_name
.c_str(), 0600);
495 // output current time
497 time_t t
= time(NULL
);
498 struct tm
*tmp
= localtime(&t
);
499 strftime(outstr
, sizeof(outstr
), "%F %T", tmp
);
500 fprintf(term_out
, "\nLog started: ");
501 fprintf(term_out
, outstr
);
502 fprintf(term_out
, "\n");
507 bool pkgDPkgPM::CloseLog()
512 time_t t
= time(NULL
);
513 struct tm
*tmp
= localtime(&t
);
514 strftime(outstr
, sizeof(outstr
), "%F %T", tmp
);
515 fprintf(term_out
, "Log ended: ");
516 fprintf(term_out
, outstr
);
517 fprintf(term_out
, "\n");
525 // This implements a racy version of pselect for those architectures
526 // that don't have a working implementation.
527 // FIXME: Probably can be removed on Lenny+1
528 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
529 fd_set
*exceptfds
, const struct timespec
*timeout
,
530 const sigset_t
*sigmask
)
536 tv
.tv_sec
= timeout
->tv_sec
;
537 tv
.tv_usec
= timeout
->tv_nsec
/1000;
539 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
540 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
541 sigprocmask(SIG_SETMASK
, &origmask
, 0);
546 // DPkgPM::Go - Run the sequence /*{{{*/
547 // ---------------------------------------------------------------------
548 /* This globs the operations and calls dpkg
550 * If it is called with "OutStatusFd" set to a valid file descriptor
551 * apt will report the install progress over this fd. It maps the
552 * dpkg states a package goes through to human readable (and i10n-able)
553 * names and calculates a percentage for each step.
555 bool pkgDPkgPM::Go(int OutStatusFd
)
557 unsigned int MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
558 unsigned int MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
560 if (RunScripts("DPkg::Pre-Invoke") == false)
563 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
566 // map the dpkg states to the operations that are performed
567 // (this is sorted in the same way as Item::Ops)
568 static const struct DpkgState DpkgStatesOpMap
[][7] = {
571 {"half-installed", N_("Preparing %s")},
572 {"unpacked", N_("Unpacking %s") },
575 // Configure operation
577 {"unpacked",N_("Preparing to configure %s") },
578 {"half-configured", N_("Configuring %s") },
580 {"triggers-awaited", N_("Processing triggers for %s") },
581 {"triggers-pending", N_("Processing triggers for %s") },
583 { "installed", N_("Installed %s")},
588 {"half-configured", N_("Preparing for removal of %s")},
590 {"triggers-awaited", N_("Preparing for removal of %s")},
591 {"triggers-pending", N_("Preparing for removal of %s")},
593 {"half-installed", N_("Removing %s")},
594 {"config-files", N_("Removed %s")},
599 {"config-files", N_("Preparing to completely remove %s")},
600 {"not-installed", N_("Completely removed %s")},
605 // populate the "processing" map
606 PackageProcessingOps
.insert( make_pair("install",N_("Installing %s")) );
607 PackageProcessingOps
.insert( make_pair("configure",N_("Configuring %s")) );
608 PackageProcessingOps
.insert( make_pair("remove",N_("Removing %s")) );
609 PackageProcessingOps
.insert( make_pair("trigproc",N_("Triggering %s")) );
611 // init the PackageOps map, go over the list of packages that
612 // that will be [installed|configured|removed|purged] and add
613 // them to the PackageOps map (the dpkg states it goes through)
614 // and the PackageOpsTranslations (human readable strings)
615 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end();I
++)
617 string name
= (*I
).Pkg
.Name();
618 PackageOpsDone
[name
] = 0;
619 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; i
++)
621 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
626 stdin_is_dev_null
= false;
631 // this loop is runs once per operation
632 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end();)
634 vector
<Item
>::iterator J
= I
;
635 for (; J
!= List
.end() && J
->Op
== I
->Op
; J
++);
637 // Generate the argument list
638 const char *Args
[MaxArgs
+ 50];
639 if (J
- I
> (signed)MaxArgs
)
643 unsigned long Size
= 0;
644 string Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
645 Args
[n
++] = Tmp
.c_str();
646 Size
+= strlen(Args
[n
-1]);
648 // Stick in any custom dpkg options
649 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
653 for (; Opts
!= 0; Opts
= Opts
->Next
)
655 if (Opts
->Value
.empty() == true)
657 Args
[n
++] = Opts
->Value
.c_str();
658 Size
+= Opts
->Value
.length();
662 char status_fd_buf
[20];
666 Args
[n
++] = "--status-fd";
667 Size
+= strlen(Args
[n
-1]);
668 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
669 Args
[n
++] = status_fd_buf
;
670 Size
+= strlen(Args
[n
-1]);
675 Args
[n
++] = "--force-depends";
676 Size
+= strlen(Args
[n
-1]);
677 Args
[n
++] = "--force-remove-essential";
678 Size
+= strlen(Args
[n
-1]);
679 Args
[n
++] = "--remove";
680 Size
+= strlen(Args
[n
-1]);
684 Args
[n
++] = "--force-depends";
685 Size
+= strlen(Args
[n
-1]);
686 Args
[n
++] = "--force-remove-essential";
687 Size
+= strlen(Args
[n
-1]);
688 Args
[n
++] = "--purge";
689 Size
+= strlen(Args
[n
-1]);
692 case Item::Configure
:
693 Args
[n
++] = "--configure";
694 Size
+= strlen(Args
[n
-1]);
698 Args
[n
++] = "--unpack";
699 Size
+= strlen(Args
[n
-1]);
700 Args
[n
++] = "--auto-deconfigure";
701 Size
+= strlen(Args
[n
-1]);
705 // Write in the file or package names
706 if (I
->Op
== Item::Install
)
708 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
710 if (I
->File
[0] != '/')
711 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
712 Args
[n
++] = I
->File
.c_str();
713 Size
+= strlen(Args
[n
-1]);
718 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
720 Args
[n
++] = I
->Pkg
.Name();
721 Size
+= strlen(Args
[n
-1]);
727 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
729 for (unsigned int k
= 0; k
!= n
; k
++)
730 clog
<< Args
[k
] << ' ';
739 /* Mask off sig int/quit. We do this because dpkg also does when
740 it forks scripts. What happens is that when you hit ctrl-c it sends
741 it to all processes in the group. Since dpkg ignores the signal
742 it doesn't die but we do! So we must also ignore it */
743 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
744 sighandler_t old_SIGINT
= signal(SIGINT
,SIG_IGN
);
747 struct termios tt_out
;
752 // FIXME: setup sensible signal handling (*ick*)
754 tcgetattr(1, &tt_out
);
755 ioctl(0, TIOCGWINSZ
, (char *)&win
);
756 if (openpty(&master
, &slave
, NULL
, &tt_out
, &win
) < 0)
758 const char *s
= _("Can not write log, openpty() "
759 "failed (/dev/pts not mounted?)\n");
760 fprintf(stderr
, "%s",s
);
761 fprintf(term_out
, "%s",s
);
767 rtt
.c_lflag
&= ~ECHO
;
768 tcsetattr(0, TCSAFLUSH
, &rtt
);
773 _config
->Set("APT::Keep-Fds::",fd
[1]);
779 if(slave
>= 0 && master
>= 0)
782 ioctl(slave
, TIOCSCTTY
, 0);
789 close(fd
[0]); // close the read end of the pipe
791 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
794 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
797 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
800 // Discard everything in stdin before forking dpkg
801 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
804 while (read(STDIN_FILENO
,&dummy
,1) == 1);
806 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
811 /* No Job Control Stop Env is a magic dpkg var that prevents it
812 from using sigstop */
813 putenv((char *)"DPKG_NO_TSTP=yes");
814 execvp(Args
[0],(char **)Args
);
815 cerr
<< "Could not exec dpkg!" << endl
;
819 // clear the Keep-Fd again
820 _config
->Clear("APT::Keep-Fds",fd
[1]);
825 // we read from dpkg here
827 close(fd
[1]); // close the write end of the pipe
829 // the result of the waitpid call
838 sigset_t original_sigmask
;
839 sigemptyset(&sigmask
);
840 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
843 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
845 // FIXME: move this to a function or something, looks ugly here
846 // error handling, waitpid returned -1
849 RunScripts("DPkg::Post-Invoke");
851 // Restore sig int/quit
852 signal(SIGQUIT
,old_SIGQUIT
);
853 signal(SIGINT
,old_SIGINT
);
854 return _error
->Errno("waitpid","Couldn't wait for subprocess");
856 // wait for input or output here
858 if (!stdin_is_dev_null
)
860 FD_SET(_dpkgin
, &rfds
);
862 FD_SET(master
, &rfds
);
865 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
866 &tv
, &original_sigmask
);
867 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
868 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
869 NULL
, &tv
, &original_sigmask
);
872 else if (select_ret
< 0 && errno
== EINTR
)
874 else if (select_ret
< 0)
876 perror("select() returned error");
880 if(master
>= 0 && FD_ISSET(master
, &rfds
))
881 DoTerminalPty(master
);
882 if(master
>= 0 && FD_ISSET(0, &rfds
))
884 if(FD_ISSET(_dpkgin
, &rfds
))
885 DoDpkgStatusFd(_dpkgin
, OutStatusFd
);
889 // Restore sig int/quit
890 signal(SIGQUIT
,old_SIGQUIT
);
891 signal(SIGINT
,old_SIGINT
);
895 tcsetattr(0, TCSAFLUSH
, &tt
);
899 // Check for an error code.
900 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
902 // if it was set to "keep-dpkg-runing" then we won't return
903 // here but keep the loop going and just report it as a error
905 bool stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
908 RunScripts("DPkg::Post-Invoke");
910 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
911 _error
->Error("Sub-process %s received a segmentation fault.",Args
[0]);
912 else if (WIFEXITED(Status
) != 0)
913 _error
->Error("Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
915 _error
->Error("Sub-process %s exited unexpectedly",Args
[0]);
926 if (RunScripts("DPkg::Post-Invoke") == false)
931 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
932 // ---------------------------------------------------------------------
934 void pkgDPkgPM::Reset()
936 List
.erase(List
.begin(),List
.end());
939 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
940 // ---------------------------------------------------------------------
942 void pkgDPkgPM::WriteApportReport(const char *pkgpath
, const char *errormsg
)
944 string pkgname
, reportfile
, srcpkgname
, pkgver
, arch
;
945 string::size_type pos
;
948 if (_config
->FindB("Dpkg::ApportFailureReport",true) == false)
950 std::clog
<< "configured to not write apport reports" << std::endl
;
954 // only report the first error
955 if(pkgFailures
> _config
->FindI("APT::Apport::MaxReports", 3))
957 std::clog
<< _("No apport report written because MaxReports is reached already") << std::endl
;
961 // get the pkgname and reportfile
962 pkgname
= flNotDir(pkgpath
);
963 pos
= pkgname
.find('_');
964 if(pos
!= string::npos
)
965 pkgname
= pkgname
.substr(0, pos
);
967 // find the package versin and source package name
968 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
969 if (Pkg
.end() == true)
971 pkgCache::VerIterator Ver
= Cache
.GetCandidateVer(Pkg
);
972 if (Ver
.end() == true)
974 pkgver
= Ver
.VerStr() == NULL
? "unknown" : Ver
.VerStr();
975 pkgRecords
Recs(Cache
);
976 pkgRecords::Parser
&Parse
= Recs
.Lookup(Ver
.FileList());
977 srcpkgname
= Parse
.SourcePkg();
978 if(srcpkgname
.empty())
979 srcpkgname
= pkgname
;
981 // if the file exists already, we check:
982 // - if it was reported already (touched by apport).
983 // If not, we do nothing, otherwise
984 // we overwrite it. This is the same behaviour as apport
985 // - if we have a report with the same pkgversion already
987 reportfile
= flCombine("/var/crash",pkgname
+".0.crash");
988 if(FileExists(reportfile
))
994 stat(reportfile
.c_str(), &buf
);
995 if(buf
.st_mtime
> buf
.st_atime
)
998 // check if the existing report is the same version
999 report
= fopen(reportfile
.c_str(),"r");
1000 while(fgets(strbuf
, sizeof(strbuf
), report
) != NULL
)
1002 if(strstr(strbuf
,"Package:") == strbuf
)
1004 char pkgname
[255], version
[255];
1005 if(sscanf(strbuf
, "Package: %s %s", pkgname
, version
) == 2)
1006 if(strcmp(pkgver
.c_str(), version
) == 0)
1016 // now write the report
1017 arch
= _config
->Find("APT::Architecture");
1018 report
= fopen(reportfile
.c_str(),"w");
1021 if(_config
->FindB("DPkgPM::InitialReportOnly",false) == true)
1022 chmod(reportfile
.c_str(), 0);
1024 chmod(reportfile
.c_str(), 0600);
1025 fprintf(report
, "ProblemType: Package\n");
1026 fprintf(report
, "Architecture: %s\n", arch
.c_str());
1027 time_t now
= time(NULL
);
1028 fprintf(report
, "Date: %s" , ctime(&now
));
1029 fprintf(report
, "Package: %s %s\n", pkgname
.c_str(), pkgver
.c_str());
1030 fprintf(report
, "SourcePackage: %s\n", srcpkgname
.c_str());
1031 fprintf(report
, "ErrorMessage:\n %s\n", errormsg
);
1033 // ensure that the log is flushed
1037 // attach terminal log it if we have it
1038 string logfile_name
= _config
->FindFile("Dir::Log::Terminal");
1039 if (!logfile_name
.empty())
1044 fprintf(report
, "DpkgTerminalLog:\n");
1045 log
= fopen(logfile_name
.c_str(),"r");
1048 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1049 fprintf(report
, " %s", buf
);