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 ##################################################################### */
12 #pragma implementation "apt-pkg/dpkgpm.h"
14 #include <apt-pkg/dpkgpm.h>
15 #include <apt-pkg/error.h>
16 #include <apt-pkg/configuration.h>
17 #include <apt-pkg/depcache.h>
18 #include <apt-pkg/pkgrecords.h>
19 #include <apt-pkg/strutl.h>
24 #include <sys/types.h>
38 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
39 // ---------------------------------------------------------------------
41 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
42 : pkgPackageManager(Cache
), pkgFailures(0)
46 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
47 // ---------------------------------------------------------------------
49 pkgDPkgPM::~pkgDPkgPM()
53 // DPkgPM::Install - Install a package /*{{{*/
54 // ---------------------------------------------------------------------
55 /* Add an install operation to the sequence list */
56 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
58 if (File
.empty() == true || Pkg
.end() == true)
59 return _error
->Error("Internal Error, No file name for %s",Pkg
.Name());
61 List
.push_back(Item(Item::Install
,Pkg
,File
));
65 // DPkgPM::Configure - Configure a package /*{{{*/
66 // ---------------------------------------------------------------------
67 /* Add a configure operation to the sequence list */
68 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
70 if (Pkg
.end() == true)
73 List
.push_back(Item(Item::Configure
,Pkg
));
77 // DPkgPM::Remove - Remove a package /*{{{*/
78 // ---------------------------------------------------------------------
79 /* Add a remove operation to the sequence list */
80 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
82 if (Pkg
.end() == true)
86 List
.push_back(Item(Item::Purge
,Pkg
));
88 List
.push_back(Item(Item::Remove
,Pkg
));
92 // DPkgPM::RunScripts - Run a set of scripts /*{{{*/
93 // ---------------------------------------------------------------------
94 /* This looks for a list of script sto run from the configuration file,
95 each one is run with system from a forked child. */
96 bool pkgDPkgPM::RunScripts(const char *Cnf
)
98 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
99 if (Opts
== 0 || Opts
->Child
== 0)
103 // Fork for running the system calls
104 pid_t Child
= ExecFork();
109 if (chdir("/tmp/") != 0)
112 unsigned int Count
= 1;
113 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
115 if (Opts
->Value
.empty() == true)
118 if (system(Opts
->Value
.c_str()) != 0)
124 // Wait for the child
126 while (waitpid(Child
,&Status
,0) != Child
)
130 return _error
->Errno("waitpid","Couldn't wait for subprocess");
133 // Restore sig int/quit
134 signal(SIGQUIT
,SIG_DFL
);
135 signal(SIGINT
,SIG_DFL
);
137 // Check for an error code.
138 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
140 unsigned int Count
= WEXITSTATUS(Status
);
144 for (; Opts
!= 0 && Count
!= 1; Opts
= Opts
->Next
, Count
--);
145 _error
->Error("Problem executing scripts %s '%s'",Cnf
,Opts
->Value
.c_str());
148 return _error
->Error("Sub-process returned an error code");
154 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
155 // ---------------------------------------------------------------------
156 /* This is part of the helper script communication interface, it sends
157 very complete information down to the other end of the pipe.*/
158 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
160 fprintf(F
,"VERSION 2\n");
162 /* Write out all of the configuration directives by walking the
163 configuration tree */
164 const Configuration::Item
*Top
= _config
->Tree(0);
167 if (Top
->Value
.empty() == false)
170 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
171 QuoteString(Top
->Value
,"\n").c_str());
180 while (Top
!= 0 && Top
->Next
== 0)
187 // Write out the package actions in order.
188 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
190 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
192 fprintf(F
,"%s ",I
->Pkg
.Name());
194 if (I
->Pkg
->CurrentVer
== 0)
197 fprintf(F
,"%s ",I
->Pkg
.CurrentVer().VerStr());
199 // Show the compare operator
201 if (S
.InstallVer
!= 0)
204 if (I
->Pkg
->CurrentVer
!= 0)
205 Comp
= S
.InstVerIter(Cache
).CompareVer(I
->Pkg
.CurrentVer());
212 fprintf(F
,"%s ",S
.InstVerIter(Cache
).VerStr());
217 // Show the filename/operation
218 if (I
->Op
== Item::Install
)
221 if (I
->File
[0] != '/')
222 fprintf(F
,"**ERROR**\n");
224 fprintf(F
,"%s\n",I
->File
.c_str());
226 if (I
->Op
== Item::Configure
)
227 fprintf(F
,"**CONFIGURE**\n");
228 if (I
->Op
== Item::Remove
||
229 I
->Op
== Item::Purge
)
230 fprintf(F
,"**REMOVE**\n");
238 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
239 // ---------------------------------------------------------------------
240 /* This looks for a list of scripts to run from the configuration file
241 each one is run and is fed on standard input a list of all .deb files
242 that are due to be installed. */
243 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
245 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
246 if (Opts
== 0 || Opts
->Child
== 0)
250 unsigned int Count
= 1;
251 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
253 if (Opts
->Value
.empty() == true)
256 // Determine the protocol version
257 string OptSec
= Opts
->Value
;
258 string::size_type Pos
;
259 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
260 Pos
= OptSec
.length();
261 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
263 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
267 if (pipe(Pipes
) != 0)
268 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
269 SetCloseExec(Pipes
[0],true);
270 SetCloseExec(Pipes
[1],true);
272 // Purified Fork for running the script
273 pid_t Process
= ExecFork();
277 dup2(Pipes
[0],STDIN_FILENO
);
278 SetCloseExec(STDOUT_FILENO
,false);
279 SetCloseExec(STDIN_FILENO
,false);
280 SetCloseExec(STDERR_FILENO
,false);
285 Args
[2] = Opts
->Value
.c_str();
287 execv(Args
[0],(char **)Args
);
291 FILE *F
= fdopen(Pipes
[1],"w");
293 return _error
->Errno("fdopen","Faild to open new FD");
295 // Feed it the filenames.
299 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
301 // Only deal with packages to be installed from .deb
302 if (I
->Op
!= Item::Install
)
306 if (I
->File
[0] != '/')
309 /* Feed the filename of each package that is pending install
311 fprintf(F
,"%s\n",I
->File
.c_str());
320 Die
= !SendV2Pkgs(F
);
324 // Clean up the sub process
325 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
326 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
332 // DPkgPM::Go - Run the sequence /*{{{*/
333 // ---------------------------------------------------------------------
334 /* This globs the operations and calls dpkg
336 * If it is called with "OutStatusFd" set to a valid file descriptor
337 * apt will report the install progress over this fd. It maps the
338 * dpkg states a package goes through to human readable (and i10n-able)
339 * names and calculates a percentage for each step.
341 bool pkgDPkgPM::Go(int OutStatusFd
)
343 unsigned int MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
344 unsigned int MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
346 if (RunScripts("DPkg::Pre-Invoke") == false)
349 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
352 // prepare the progress reporting
355 // map the dpkg states to the operations that are performed
356 // (this is sorted in the same way as Item::Ops)
357 static const struct DpkgState DpkgStatesOpMap
[][5] = {
360 {"half-installed", N_("Preparing %s")},
361 {"unpacked", N_("Unpacking %s") },
364 // Configure operation
366 {"unpacked",N_("Preparing to configure %s") },
367 {"half-configured", N_("Configuring %s") },
368 { "installed", N_("Installed %s")},
373 {"half-configured", N_("Preparing for removal of %s")},
374 {"half-installed", N_("Removing %s")},
375 {"config-files", N_("Removed %s")},
380 {"config-files", N_("Preparing to completely remove %s")},
381 {"not-installed", N_("Completely removed %s")},
386 // the dpkg states that the pkg will run through, the string is
387 // the package, the vector contains the dpkg states that the package
389 map
<string
,vector
<struct DpkgState
> > PackageOps
;
390 // the dpkg states that are already done; the string is the package
391 // the int is the state that is already done (e.g. a package that is
392 // going to be install is already in state "half-installed")
393 map
<string
,int> PackageOpsDone
;
395 // init the PackageOps map, go over the list of packages that
396 // that will be [installed|configured|removed|purged] and add
397 // them to the PackageOps map (the dpkg states it goes through)
398 // and the PackageOpsTranslations (human readable strings)
399 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end();I
++)
401 string name
= (*I
).Pkg
.Name();
402 PackageOpsDone
[name
] = 0;
403 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; i
++)
405 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
410 // this loop is runs once per operation
411 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end();)
413 vector
<Item
>::iterator J
= I
;
414 for (; J
!= List
.end() && J
->Op
== I
->Op
; J
++);
416 // Generate the argument list
417 const char *Args
[MaxArgs
+ 50];
418 if (J
- I
> (signed)MaxArgs
)
422 unsigned long Size
= 0;
423 string Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
424 Args
[n
++] = Tmp
.c_str();
425 Size
+= strlen(Args
[n
-1]);
427 // Stick in any custom dpkg options
428 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
432 for (; Opts
!= 0; Opts
= Opts
->Next
)
434 if (Opts
->Value
.empty() == true)
436 Args
[n
++] = Opts
->Value
.c_str();
437 Size
+= Opts
->Value
.length();
441 char status_fd_buf
[20];
445 Args
[n
++] = "--status-fd";
446 Size
+= strlen(Args
[n
-1]);
447 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
448 Args
[n
++] = status_fd_buf
;
449 Size
+= strlen(Args
[n
-1]);
454 Args
[n
++] = "--force-depends";
455 Size
+= strlen(Args
[n
-1]);
456 Args
[n
++] = "--force-remove-essential";
457 Size
+= strlen(Args
[n
-1]);
458 Args
[n
++] = "--remove";
459 Size
+= strlen(Args
[n
-1]);
463 Args
[n
++] = "--force-depends";
464 Size
+= strlen(Args
[n
-1]);
465 Args
[n
++] = "--force-remove-essential";
466 Size
+= strlen(Args
[n
-1]);
467 Args
[n
++] = "--purge";
468 Size
+= strlen(Args
[n
-1]);
471 case Item::Configure
:
472 Args
[n
++] = "--configure";
473 Size
+= strlen(Args
[n
-1]);
477 Args
[n
++] = "--unpack";
478 Size
+= strlen(Args
[n
-1]);
479 Args
[n
++] = "--auto-deconfigure";
480 Size
+= strlen(Args
[n
-1]);
484 // Write in the file or package names
485 if (I
->Op
== Item::Install
)
487 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
489 if (I
->File
[0] != '/')
490 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
491 Args
[n
++] = I
->File
.c_str();
492 Size
+= strlen(Args
[n
-1]);
497 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
499 Args
[n
++] = I
->Pkg
.Name();
500 Size
+= strlen(Args
[n
-1]);
506 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
508 for (unsigned int k
= 0; k
!= n
; k
++)
509 clog
<< Args
[k
] << ' ';
518 /* Mask off sig int/quit. We do this because dpkg also does when
519 it forks scripts. What happens is that when you hit ctrl-c it sends
520 it to all processes in the group. Since dpkg ignores the signal
521 it doesn't die but we do! So we must also ignore it */
522 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
523 sighandler_t old_SIGINT
= signal(SIGINT
,SIG_IGN
);
527 _config
->Set("APT::Keep-Fds::",fd
[1]);
533 close(fd
[0]); // close the read end of the pipe
535 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
538 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
541 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
544 // Discard everything in stdin before forking dpkg
545 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
548 while (read(STDIN_FILENO
,&dummy
,1) == 1);
550 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
554 /* No Job Control Stop Env is a magic dpkg var that prevents it
555 from using sigstop */
556 putenv("DPKG_NO_TSTP=yes");
557 execvp(Args
[0],(char **)Args
);
558 cerr
<< "Could not exec dpkg!" << endl
;
562 // clear the Keep-Fd again
563 _config
->Clear("APT::Keep-Fds",fd
[1]);
568 // we read from dpkg here
570 fcntl(_dpkgin
, F_SETFL
, O_NONBLOCK
);
571 close(fd
[1]); // close the write end of the pipe
573 // the read buffers for the communication with dpkg
574 char line
[1024] = {0,};
577 // the result of the waitpid call
580 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
582 // FIXME: move this to a function or something, looks ugly here
583 // error handling, waitpid returned -1
586 RunScripts("DPkg::Post-Invoke");
588 // Restore sig int/quit
589 signal(SIGQUIT
,old_SIGQUIT
);
590 signal(SIGINT
,old_SIGINT
);
591 return _error
->Errno("waitpid","Couldn't wait for subprocess");
594 // read a single char, make sure that the read can't block
595 // (otherwise we may leave zombies)
596 int len
= read(_dpkgin
, buf
, 1);
598 // nothing to read, wait a bit for more
605 // sanity check (should never happen)
606 if(strlen(line
) >= sizeof(line
)-10)
608 _error
->Error("got a overlong line from dpkg: '%s'",line
);
611 // append to line, check if we got a complete line
616 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
617 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
619 // the status we output
620 ostringstream status
;
622 /* dpkg sends strings like this:
623 'status: <pkg>: <pkg qstate>'
624 errors look like this:
625 '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
626 and conffile-prompt like this
627 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
631 // dpkg sends multiline error messages sometimes (see
632 // #374195 for a example. we should support this by
633 // either patching dpkg to not send multiline over the
634 // statusfd or by rewriting the code here to deal with
635 // it. for now we just ignore it and not crash
636 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
638 char *action
= _strstrip(list
[2]);
639 if( pkg
== NULL
|| action
== NULL
)
641 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
642 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
643 // reset the line buffer
648 if(strncmp(action
,"error",strlen("error")) == 0)
650 status
<< "pmerror:" << list
[1]
651 << ":" << (Done
/float(Total
)*100.0)
655 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
657 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
658 std::clog
<< "send: '" << status
.str() << "'" << endl
;
660 WriteApportReport(list
[1], list
[3]);
663 if(strncmp(action
,"conffile",strlen("conffile")) == 0)
665 status
<< "pmconffile:" << list
[1]
666 << ":" << (Done
/float(Total
)*100.0)
670 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
672 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
673 std::clog
<< "send: '" << status
.str() << "'" << endl
;
677 vector
<struct DpkgState
> &states
= PackageOps
[pkg
];
678 const char *next_action
= NULL
;
679 if(PackageOpsDone
[pkg
] < states
.size())
680 next_action
= states
[PackageOpsDone
[pkg
]].state
;
681 // check if the package moved to the next dpkg state
682 if(next_action
&& (strcmp(action
, next_action
) == 0))
684 // only read the translation if there is actually a next
686 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
688 snprintf(s
, sizeof(s
), translation
, pkg
);
690 // we moved from one dpkg state to a new one, report that
691 PackageOpsDone
[pkg
]++;
693 // build the status str
694 status
<< "pmstatus:" << pkg
695 << ":" << (Done
/float(Total
)*100.0)
699 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
700 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
701 std::clog
<< "send: '" << status
.str() << "'" << endl
;
704 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
705 std::clog
<< "(parsed from dpkg) pkg: " << pkg
706 << " action: " << action
<< endl
;
708 // reset the line buffer
713 // Restore sig int/quit
714 signal(SIGQUIT
,old_SIGQUIT
);
715 signal(SIGINT
,old_SIGINT
);
717 // Check for an error code.
718 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
720 // if it was set to "keep-dpkg-runing" then we won't return
721 // here but keep the loop going and just report it as a error
723 bool stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
726 RunScripts("DPkg::Post-Invoke");
728 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
729 _error
->Error("Sub-process %s received a segmentation fault.",Args
[0]);
730 else if (WIFEXITED(Status
) != 0)
731 _error
->Error("Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
733 _error
->Error("Sub-process %s exited unexpectedly",Args
[0]);
740 if (RunScripts("DPkg::Post-Invoke") == false)
745 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
746 // ---------------------------------------------------------------------
748 void pkgDPkgPM::Reset()
750 List
.erase(List
.begin(),List
.end());
753 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
754 // ---------------------------------------------------------------------
756 void pkgDPkgPM::WriteApportReport(const char *pkgpath
, const char *errormsg
)
758 string pkgname
, reportfile
, srcpkgname
, pkgver
, arch
;
759 string::size_type pos
;
762 if (_config
->FindB("Dpkg::ApportFailureReport",true) == false)
765 // only report the first error if we are in StopOnError=false mode
766 // to prevent bogus reports
767 if((_config
->FindB("Dpkg::StopOnError",true) == false) && pkgFailures
> 1)
770 // get the pkgname and reportfile
771 pkgname
= flNotDir(pkgpath
);
772 pos
= pkgname
.rfind('_');
773 if(pos
!= string::npos
)
774 pkgname
= string(pkgname
, 0, pos
);
776 // find the package versin and source package name
777 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
778 if (Pkg
.end() == true)
780 pkgCache::VerIterator Ver
= Cache
.GetCandidateVer(Pkg
);
781 pkgver
= Ver
.VerStr();
782 if (Ver
.end() == true)
784 pkgRecords
Recs(Cache
);
785 pkgRecords::Parser
&Parse
= Recs
.Lookup(Ver
.FileList());
786 srcpkgname
= Parse
.SourcePkg();
787 if(srcpkgname
.empty())
788 srcpkgname
= pkgname
;
790 // if the file exists already, we check:
791 // - if it was reported already (touched by apport).
792 // If not, we do nothing, otherwise
793 // we overwrite it. This is the same behaviour as apport
794 // - if we have a report with the same pkgversion already
796 reportfile
= flCombine("/var/crash",pkgname
+".0.crash");
797 if(FileExists(reportfile
))
803 stat(reportfile
.c_str(), &buf
);
804 if(buf
.st_mtime
> buf
.st_atime
)
807 // check if the existing report is the same version
808 report
= fopen(reportfile
.c_str(),"r");
809 while(fgets(strbuf
, sizeof(strbuf
), report
) != NULL
)
811 if(strstr(strbuf
,"Package:") == strbuf
)
813 char pkgname
[255], version
[255];
814 if(sscanf(strbuf
, "Package: %s %s", pkgname
, version
) == 2)
815 if(strcmp(pkgver
.c_str(), version
) == 0)
825 // now write the report
826 arch
= _config
->Find("APT::Architecture");
827 report
= fopen(reportfile
.c_str(),"w");
830 if(_config
->FindB("DPkgPM::InitialReportOnly",false) == true)
831 chmod(reportfile
.c_str(), 0);
833 chmod(reportfile
.c_str(), 0600);
834 fprintf(report
, "ProblemType: Package\n");
835 fprintf(report
, "Architecture: %s\n", arch
.c_str());
836 time_t now
= time(NULL
);
837 fprintf(report
, "Date: %s" , ctime(&now
));
838 fprintf(report
, "Package: %s %s\n", pkgname
.c_str(), pkgver
.c_str());
839 fprintf(report
, "SourcePackage: %s\n", srcpkgname
.c_str());
840 fprintf(report
, "ErrorMessage:\n %s\n", errormsg
);