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>
21 #include <sys/types.h>
35 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
36 // ---------------------------------------------------------------------
38 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
39 : pkgPackageManager(Cache
), pkgFailures(0)
43 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
44 // ---------------------------------------------------------------------
46 pkgDPkgPM::~pkgDPkgPM()
50 // DPkgPM::Install - Install a package /*{{{*/
51 // ---------------------------------------------------------------------
52 /* Add an install operation to the sequence list */
53 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
55 if (File
.empty() == true || Pkg
.end() == true)
56 return _error
->Error("Internal Error, No file name for %s",Pkg
.Name());
58 List
.push_back(Item(Item::Install
,Pkg
,File
));
62 // DPkgPM::Configure - Configure a package /*{{{*/
63 // ---------------------------------------------------------------------
64 /* Add a configure operation to the sequence list */
65 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
67 if (Pkg
.end() == true)
70 List
.push_back(Item(Item::Configure
,Pkg
));
74 // DPkgPM::Remove - Remove a package /*{{{*/
75 // ---------------------------------------------------------------------
76 /* Add a remove operation to the sequence list */
77 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
79 if (Pkg
.end() == true)
83 List
.push_back(Item(Item::Purge
,Pkg
));
85 List
.push_back(Item(Item::Remove
,Pkg
));
89 // DPkgPM::RunScripts - Run a set of scripts /*{{{*/
90 // ---------------------------------------------------------------------
91 /* This looks for a list of script sto run from the configuration file,
92 each one is run with system from a forked child. */
93 bool pkgDPkgPM::RunScripts(const char *Cnf
)
95 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
96 if (Opts
== 0 || Opts
->Child
== 0)
100 // Fork for running the system calls
101 pid_t Child
= ExecFork();
106 if (chdir("/tmp/") != 0)
109 unsigned int Count
= 1;
110 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
112 if (Opts
->Value
.empty() == true)
115 if (system(Opts
->Value
.c_str()) != 0)
121 // Wait for the child
123 while (waitpid(Child
,&Status
,0) != Child
)
127 return _error
->Errno("waitpid","Couldn't wait for subprocess");
130 // Restore sig int/quit
131 signal(SIGQUIT
,SIG_DFL
);
132 signal(SIGINT
,SIG_DFL
);
134 // Check for an error code.
135 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
137 unsigned int Count
= WEXITSTATUS(Status
);
141 for (; Opts
!= 0 && Count
!= 1; Opts
= Opts
->Next
, Count
--);
142 _error
->Error("Problem executing scripts %s '%s'",Cnf
,Opts
->Value
.c_str());
145 return _error
->Error("Sub-process returned an error code");
151 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
152 // ---------------------------------------------------------------------
153 /* This is part of the helper script communication interface, it sends
154 very complete information down to the other end of the pipe.*/
155 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
157 fprintf(F
,"VERSION 2\n");
159 /* Write out all of the configuration directives by walking the
160 configuration tree */
161 const Configuration::Item
*Top
= _config
->Tree(0);
164 if (Top
->Value
.empty() == false)
167 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
168 QuoteString(Top
->Value
,"\n").c_str());
177 while (Top
!= 0 && Top
->Next
== 0)
184 // Write out the package actions in order.
185 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
187 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
189 fprintf(F
,"%s ",I
->Pkg
.Name());
191 if (I
->Pkg
->CurrentVer
== 0)
194 fprintf(F
,"%s ",I
->Pkg
.CurrentVer().VerStr());
196 // Show the compare operator
198 if (S
.InstallVer
!= 0)
201 if (I
->Pkg
->CurrentVer
!= 0)
202 Comp
= S
.InstVerIter(Cache
).CompareVer(I
->Pkg
.CurrentVer());
209 fprintf(F
,"%s ",S
.InstVerIter(Cache
).VerStr());
214 // Show the filename/operation
215 if (I
->Op
== Item::Install
)
218 if (I
->File
[0] != '/')
219 fprintf(F
,"**ERROR**\n");
221 fprintf(F
,"%s\n",I
->File
.c_str());
223 if (I
->Op
== Item::Configure
)
224 fprintf(F
,"**CONFIGURE**\n");
225 if (I
->Op
== Item::Remove
||
226 I
->Op
== Item::Purge
)
227 fprintf(F
,"**REMOVE**\n");
235 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
236 // ---------------------------------------------------------------------
237 /* This looks for a list of scripts to run from the configuration file
238 each one is run and is fed on standard input a list of all .deb files
239 that are due to be installed. */
240 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
242 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
243 if (Opts
== 0 || Opts
->Child
== 0)
247 unsigned int Count
= 1;
248 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
250 if (Opts
->Value
.empty() == true)
253 // Determine the protocol version
254 string OptSec
= Opts
->Value
;
255 string::size_type Pos
;
256 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
257 Pos
= OptSec
.length();
258 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
260 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
264 if (pipe(Pipes
) != 0)
265 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
266 SetCloseExec(Pipes
[0],true);
267 SetCloseExec(Pipes
[1],true);
269 // Purified Fork for running the script
270 pid_t Process
= ExecFork();
274 dup2(Pipes
[0],STDIN_FILENO
);
275 SetCloseExec(STDOUT_FILENO
,false);
276 SetCloseExec(STDIN_FILENO
,false);
277 SetCloseExec(STDERR_FILENO
,false);
282 Args
[2] = Opts
->Value
.c_str();
284 execv(Args
[0],(char **)Args
);
288 FILE *F
= fdopen(Pipes
[1],"w");
290 return _error
->Errno("fdopen","Faild to open new FD");
292 // Feed it the filenames.
296 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
298 // Only deal with packages to be installed from .deb
299 if (I
->Op
!= Item::Install
)
303 if (I
->File
[0] != '/')
306 /* Feed the filename of each package that is pending install
308 fprintf(F
,"%s\n",I
->File
.c_str());
317 Die
= !SendV2Pkgs(F
);
321 // Clean up the sub process
322 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
323 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
329 // DPkgPM::Go - Run the sequence /*{{{*/
330 // ---------------------------------------------------------------------
331 /* This globs the operations and calls dpkg
333 * If it is called with "OutStatusFd" set to a valid file descriptor
334 * apt will report the install progress over this fd. It maps the
335 * dpkg states a package goes through to human readable (and i10n-able)
336 * names and calculates a percentage for each step.
338 bool pkgDPkgPM::Go(int OutStatusFd
)
340 unsigned int MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
341 unsigned int MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
343 if (RunScripts("DPkg::Pre-Invoke") == false)
346 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
349 // prepare the progress reporting
352 // map the dpkg states to the operations that are performed
353 // (this is sorted in the same way as Item::Ops)
354 static const struct DpkgState DpkgStatesOpMap
[][5] = {
357 {"half-installed", N_("Preparing %s")},
358 {"unpacked", N_("Unpacking %s") },
361 // Configure operation
363 {"unpacked",N_("Preparing to configure %s") },
364 {"half-configured", N_("Configuring %s") },
365 { "installed", N_("Installed %s")},
370 {"half-configured", N_("Preparing for removal of %s")},
371 {"half-installed", N_("Removing %s")},
372 {"config-files", N_("Removed %s")},
377 {"config-files", N_("Preparing to completely remove %s")},
378 {"not-installed", N_("Completely removed %s")},
383 // the dpkg states that the pkg will run through, the string is
384 // the package, the vector contains the dpkg states that the package
386 map
<string
,vector
<struct DpkgState
> > PackageOps
;
387 // the dpkg states that are already done; the string is the package
388 // the int is the state that is already done (e.g. a package that is
389 // going to be install is already in state "half-installed")
390 map
<string
,int> PackageOpsDone
;
392 // init the PackageOps map, go over the list of packages that
393 // that will be [installed|configured|removed|purged] and add
394 // them to the PackageOps map (the dpkg states it goes through)
395 // and the PackageOpsTranslations (human readable strings)
396 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end();I
++)
398 string name
= (*I
).Pkg
.Name();
399 PackageOpsDone
[name
] = 0;
400 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; i
++)
402 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
407 // this loop is runs once per operation
408 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end();)
410 vector
<Item
>::iterator J
= I
;
411 for (; J
!= List
.end() && J
->Op
== I
->Op
; J
++);
413 // Generate the argument list
414 const char *Args
[MaxArgs
+ 50];
415 if (J
- I
> (signed)MaxArgs
)
419 unsigned long Size
= 0;
420 string Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
421 Args
[n
++] = Tmp
.c_str();
422 Size
+= strlen(Args
[n
-1]);
424 // Stick in any custom dpkg options
425 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
429 for (; Opts
!= 0; Opts
= Opts
->Next
)
431 if (Opts
->Value
.empty() == true)
433 Args
[n
++] = Opts
->Value
.c_str();
434 Size
+= Opts
->Value
.length();
438 char status_fd_buf
[20];
442 Args
[n
++] = "--status-fd";
443 Size
+= strlen(Args
[n
-1]);
444 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
445 Args
[n
++] = status_fd_buf
;
446 Size
+= strlen(Args
[n
-1]);
451 Args
[n
++] = "--force-depends";
452 Size
+= strlen(Args
[n
-1]);
453 Args
[n
++] = "--force-remove-essential";
454 Size
+= strlen(Args
[n
-1]);
455 Args
[n
++] = "--remove";
456 Size
+= strlen(Args
[n
-1]);
460 Args
[n
++] = "--force-depends";
461 Size
+= strlen(Args
[n
-1]);
462 Args
[n
++] = "--force-remove-essential";
463 Size
+= strlen(Args
[n
-1]);
464 Args
[n
++] = "--purge";
465 Size
+= strlen(Args
[n
-1]);
468 case Item::Configure
:
469 Args
[n
++] = "--configure";
470 Size
+= strlen(Args
[n
-1]);
474 Args
[n
++] = "--unpack";
475 Size
+= strlen(Args
[n
-1]);
476 Args
[n
++] = "--auto-deconfigure";
477 Size
+= strlen(Args
[n
-1]);
481 // Write in the file or package names
482 if (I
->Op
== Item::Install
)
484 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
486 if (I
->File
[0] != '/')
487 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
488 Args
[n
++] = I
->File
.c_str();
489 Size
+= strlen(Args
[n
-1]);
494 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
496 Args
[n
++] = I
->Pkg
.Name();
497 Size
+= strlen(Args
[n
-1]);
503 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
505 for (unsigned int k
= 0; k
!= n
; k
++)
506 clog
<< Args
[k
] << ' ';
515 /* Mask off sig int/quit. We do this because dpkg also does when
516 it forks scripts. What happens is that when you hit ctrl-c it sends
517 it to all processes in the group. Since dpkg ignores the signal
518 it doesn't die but we do! So we must also ignore it */
519 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
520 sighandler_t old_SIGINT
= signal(SIGINT
,SIG_IGN
);
524 _config
->Set("APT::Keep-Fds::",fd
[1]);
530 close(fd
[0]); // close the read end of the pipe
532 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
535 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
538 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
541 // Discard everything in stdin before forking dpkg
542 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
545 while (read(STDIN_FILENO
,&dummy
,1) == 1);
547 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
551 /* No Job Control Stop Env is a magic dpkg var that prevents it
552 from using sigstop */
553 putenv("DPKG_NO_TSTP=yes");
554 execvp(Args
[0],(char **)Args
);
555 cerr
<< "Could not exec dpkg!" << endl
;
559 // clear the Keep-Fd again
560 _config
->Clear("APT::Keep-Fds",fd
[1]);
565 // we read from dpkg here
567 fcntl(_dpkgin
, F_SETFL
, O_NONBLOCK
);
568 close(fd
[1]); // close the write end of the pipe
570 // the read buffers for the communication with dpkg
571 char line
[1024] = {0,};
574 // the result of the waitpid call
577 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
579 // FIXME: move this to a function or something, looks ugly here
580 // error handling, waitpid returned -1
583 RunScripts("DPkg::Post-Invoke");
585 // Restore sig int/quit
586 signal(SIGQUIT
,old_SIGQUIT
);
587 signal(SIGINT
,old_SIGINT
);
588 return _error
->Errno("waitpid","Couldn't wait for subprocess");
591 // read a single char, make sure that the read can't block
592 // (otherwise we may leave zombies)
593 int len
= read(_dpkgin
, buf
, 1);
595 // nothing to read, wait a bit for more
602 // sanity check (should never happen)
603 if(strlen(line
) >= sizeof(line
)-10)
605 _error
->Error("got a overlong line from dpkg: '%s'",line
);
608 // append to line, check if we got a complete line
613 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
614 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
616 // the status we output
617 ostringstream status
;
619 /* dpkg sends strings like this:
620 'status: <pkg>: <pkg qstate>'
621 errors look like this:
622 '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
623 and conffile-prompt like this
624 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
628 // dpkg sends multiline error messages sometimes (see
629 // #374195 for a example. we should support this by
630 // either patching dpkg to not send multiline over the
631 // statusfd or by rewriting the code here to deal with
632 // it. for now we just ignore it and not crash
633 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
635 char *action
= _strstrip(list
[2]);
636 if( pkg
== NULL
|| action
== NULL
)
638 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
639 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
640 // reset the line buffer
645 if(strncmp(action
,"error",strlen("error")) == 0)
647 status
<< "pmerror:" << list
[1]
648 << ":" << (Done
/float(Total
)*100.0)
652 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
654 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
655 std::clog
<< "send: '" << status
.str() << "'" << endl
;
657 WriteApportReport(list
[1], list
[3]);
660 if(strncmp(action
,"conffile",strlen("conffile")) == 0)
662 status
<< "pmconffile:" << list
[1]
663 << ":" << (Done
/float(Total
)*100.0)
667 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
669 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
670 std::clog
<< "send: '" << status
.str() << "'" << endl
;
674 vector
<struct DpkgState
> &states
= PackageOps
[pkg
];
675 const char *next_action
= NULL
;
676 if(PackageOpsDone
[pkg
] < states
.size())
677 next_action
= states
[PackageOpsDone
[pkg
]].state
;
678 // check if the package moved to the next dpkg state
679 if(next_action
&& (strcmp(action
, next_action
) == 0))
681 // only read the translation if there is actually a next
683 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
685 snprintf(s
, sizeof(s
), translation
, pkg
);
687 // we moved from one dpkg state to a new one, report that
688 PackageOpsDone
[pkg
]++;
690 // build the status str
691 status
<< "pmstatus:" << pkg
692 << ":" << (Done
/float(Total
)*100.0)
696 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
697 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
698 std::clog
<< "send: '" << status
.str() << "'" << endl
;
701 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
702 std::clog
<< "(parsed from dpkg) pkg: " << pkg
703 << " action: " << action
<< endl
;
705 // reset the line buffer
710 // Restore sig int/quit
711 signal(SIGQUIT
,old_SIGQUIT
);
712 signal(SIGINT
,old_SIGINT
);
714 // Check for an error code.
715 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
717 // if it was set to "keep-dpkg-runing" then we won't return
718 // here but keep the loop going and just report it as a error
720 bool stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
723 RunScripts("DPkg::Post-Invoke");
725 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
726 _error
->Error("Sub-process %s received a segmentation fault.",Args
[0]);
727 else if (WIFEXITED(Status
) != 0)
728 _error
->Error("Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
730 _error
->Error("Sub-process %s exited unexpectedly",Args
[0]);
737 if (RunScripts("DPkg::Post-Invoke") == false)
742 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
743 // ---------------------------------------------------------------------
745 void pkgDPkgPM::Reset()
747 List
.erase(List
.begin(),List
.end());
750 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
751 // ---------------------------------------------------------------------
753 void pkgDPkgPM::WriteApportReport(const char *pkgpath
, const char *errormsg
)
755 string pkgname
, reportfile
, srcpkgname
, pkgver
, arch
;
756 string::size_type pos
;
759 if (_config
->FindB("Dpkg::ApportFailureReport",true) == false)
762 // only report the first error if we are in StopOnError=false mode
763 // to prevent bogus reports
764 if((_config
->FindB("Dpkg::StopOnError",true) == false) && pkgFailures
> 1)
767 // get the pkgname and reportfile
768 pkgname
= flNotDir(pkgpath
);
769 pos
= pkgname
.rfind('_');
770 if(pos
!= string::npos
)
771 pkgname
= string(pkgname
, 0, pos
);
773 // find the package versin and source package name
774 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
775 if (Pkg
.end() == true)
777 pkgCache::VerIterator Ver
= Cache
.GetCandidateVer(Pkg
);
778 pkgver
= Ver
.VerStr();
779 if (Ver
.end() == true)
781 pkgRecords
Recs(Cache
);
782 pkgRecords::Parser
&Parse
= Recs
.Lookup(Ver
.FileList());
783 srcpkgname
= Parse
.SourcePkg();
784 if(srcpkgname
.empty())
785 srcpkgname
= pkgname
;
787 // if the file exists already, we check:
788 // - if it was reported already (touched by apport).
789 // If not, we do nothing, otherwise
790 // we overwrite it. This is the same behaviour as apport
791 // - if we have a report with the same pkgversion already
793 reportfile
= flCombine("/var/crash",pkgname
+".0.crash");
794 if(FileExists(reportfile
))
800 stat(reportfile
.c_str(), &buf
);
801 if(buf
.st_mtime
> buf
.st_atime
)
804 // check if the existing report is the same version
805 report
= fopen(reportfile
.c_str(),"r");
806 while(fgets(strbuf
, sizeof(strbuf
), report
) != NULL
)
808 if(strstr(strbuf
,"Package:") == strbuf
)
810 char pkgname
[255], version
[255];
811 if(sscanf(strbuf
, "Package: %s %s", pkgname
, version
) == 2)
812 if(strcmp(pkgver
.c_str(), version
) == 0)
822 // now write the report
823 arch
= _config
->Find("APT::Architecture");
824 report
= fopen(reportfile
.c_str(),"w");
827 if(_config
->FindB("DPkgPM::InitialReportOnly",false) == true)
828 chmod(reportfile
.c_str(), 0);
830 chmod(reportfile
.c_str(), 0600);
831 fprintf(report
, "ProblemType: Package\n");
832 fprintf(report
, "Architecture: %s\n", arch
.c_str());
833 time_t now
= time(NULL
);
834 fprintf(report
, "Date: %s" , ctime(&now
));
835 fprintf(report
, "Package: %s %s\n", pkgname
.c_str(), pkgver
.c_str());
836 fprintf(report
, "SourcePackage: %s\n", srcpkgname
.c_str());
837 fprintf(report
, "ErrorMessage:\n %s\n", errormsg
);