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/strutl.h>
23 #include <sys/types.h>
37 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
38 // ---------------------------------------------------------------------
40 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
) : pkgPackageManager(Cache
)
44 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
45 // ---------------------------------------------------------------------
47 pkgDPkgPM::~pkgDPkgPM()
51 // DPkgPM::Install - Install a package /*{{{*/
52 // ---------------------------------------------------------------------
53 /* Add an install operation to the sequence list */
54 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
56 if (File
.empty() == true || Pkg
.end() == true)
57 return _error
->Error("Internal Error, No file name for %s",Pkg
.Name());
59 List
.push_back(Item(Item::Install
,Pkg
,File
));
63 // DPkgPM::Configure - Configure a package /*{{{*/
64 // ---------------------------------------------------------------------
65 /* Add a configure operation to the sequence list */
66 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
68 if (Pkg
.end() == true)
71 List
.push_back(Item(Item::Configure
,Pkg
));
75 // DPkgPM::Remove - Remove a package /*{{{*/
76 // ---------------------------------------------------------------------
77 /* Add a remove operation to the sequence list */
78 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
80 if (Pkg
.end() == true)
84 List
.push_back(Item(Item::Purge
,Pkg
));
86 List
.push_back(Item(Item::Remove
,Pkg
));
90 // DPkgPM::RunScripts - Run a set of scripts /*{{{*/
91 // ---------------------------------------------------------------------
92 /* This looks for a list of script sto run from the configuration file,
93 each one is run with system from a forked child. */
94 bool pkgDPkgPM::RunScripts(const char *Cnf
)
96 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
97 if (Opts
== 0 || Opts
->Child
== 0)
101 // Fork for running the system calls
102 pid_t Child
= ExecFork();
107 if (chdir("/tmp/") != 0)
110 unsigned int Count
= 1;
111 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
113 if (Opts
->Value
.empty() == true)
116 if (system(Opts
->Value
.c_str()) != 0)
122 // Wait for the child
124 while (waitpid(Child
,&Status
,0) != Child
)
128 return _error
->Errno("waitpid","Couldn't wait for subprocess");
131 // Restore sig int/quit
132 signal(SIGQUIT
,SIG_DFL
);
133 signal(SIGINT
,SIG_DFL
);
135 // Check for an error code.
136 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
138 unsigned int Count
= WEXITSTATUS(Status
);
142 for (; Opts
!= 0 && Count
!= 1; Opts
= Opts
->Next
, Count
--);
143 _error
->Error("Problem executing scripts %s '%s'",Cnf
,Opts
->Value
.c_str());
146 return _error
->Error("Sub-process returned an error code");
152 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
153 // ---------------------------------------------------------------------
154 /* This is part of the helper script communication interface, it sends
155 very complete information down to the other end of the pipe.*/
156 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
158 fprintf(F
,"VERSION 2\n");
160 /* Write out all of the configuration directives by walking the
161 configuration tree */
162 const Configuration::Item
*Top
= _config
->Tree(0);
165 if (Top
->Value
.empty() == false)
168 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
169 QuoteString(Top
->Value
,"\n").c_str());
178 while (Top
!= 0 && Top
->Next
== 0)
185 // Write out the package actions in order.
186 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
188 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
190 fprintf(F
,"%s ",I
->Pkg
.Name());
192 if (I
->Pkg
->CurrentVer
== 0)
195 fprintf(F
,"%s ",I
->Pkg
.CurrentVer().VerStr());
197 // Show the compare operator
199 if (S
.InstallVer
!= 0)
202 if (I
->Pkg
->CurrentVer
!= 0)
203 Comp
= S
.InstVerIter(Cache
).CompareVer(I
->Pkg
.CurrentVer());
210 fprintf(F
,"%s ",S
.InstVerIter(Cache
).VerStr());
215 // Show the filename/operation
216 if (I
->Op
== Item::Install
)
219 if (I
->File
[0] != '/')
220 fprintf(F
,"**ERROR**\n");
222 fprintf(F
,"%s\n",I
->File
.c_str());
224 if (I
->Op
== Item::Configure
)
225 fprintf(F
,"**CONFIGURE**\n");
226 if (I
->Op
== Item::Remove
||
227 I
->Op
== Item::Purge
)
228 fprintf(F
,"**REMOVE**\n");
236 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
237 // ---------------------------------------------------------------------
238 /* This looks for a list of scripts to run from the configuration file
239 each one is run and is fed on standard input a list of all .deb files
240 that are due to be installed. */
241 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
243 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
244 if (Opts
== 0 || Opts
->Child
== 0)
248 unsigned int Count
= 1;
249 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
251 if (Opts
->Value
.empty() == true)
254 // Determine the protocol version
255 string OptSec
= Opts
->Value
;
256 string::size_type Pos
;
257 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
258 Pos
= OptSec
.length();
259 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
261 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
265 if (pipe(Pipes
) != 0)
266 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
267 SetCloseExec(Pipes
[0],true);
268 SetCloseExec(Pipes
[1],true);
270 // Purified Fork for running the script
271 pid_t Process
= ExecFork();
275 dup2(Pipes
[0],STDIN_FILENO
);
276 SetCloseExec(STDOUT_FILENO
,false);
277 SetCloseExec(STDIN_FILENO
,false);
278 SetCloseExec(STDERR_FILENO
,false);
283 Args
[2] = Opts
->Value
.c_str();
285 execv(Args
[0],(char **)Args
);
289 FILE *F
= fdopen(Pipes
[1],"w");
291 return _error
->Errno("fdopen","Faild to open new FD");
293 // Feed it the filenames.
297 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
299 // Only deal with packages to be installed from .deb
300 if (I
->Op
!= Item::Install
)
304 if (I
->File
[0] != '/')
307 /* Feed the filename of each package that is pending install
309 fprintf(F
,"%s\n",I
->File
.c_str());
318 Die
= !SendV2Pkgs(F
);
322 // Clean up the sub process
323 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
324 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
330 // DPkgPM::Go - Run the sequence /*{{{*/
331 // ---------------------------------------------------------------------
332 /* This globs the operations and calls dpkg
334 * If it is called with "OutStatusFd" set to a valid file descriptor
335 * apt will report the install progress over this fd. It maps the
336 * dpkg states a package goes through to human readable (and i10n-able)
337 * names and calculates a percentage for each step.
339 bool pkgDPkgPM::Go(int OutStatusFd
)
341 unsigned int MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
342 unsigned int MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
344 if (RunScripts("DPkg::Pre-Invoke") == false)
347 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
350 // prepare the progress reporting
353 // map the dpkg states to the operations that are performed
354 // (this is sorted in the same way as Item::Ops)
355 static const struct DpkgState DpkgStatesOpMap
[][5] = {
358 {"half-installed", _("Preparing %s")},
359 {"unpacked", _("Unpacking %s") },
362 // Configure operation
364 {"unpacked",_("Preparing to configure %s") },
365 {"half-configured", _("Configuring %s") },
366 { "installed", _("Installed %s")},
371 {"half-configured", _("Preparing for removal of %s")},
372 {"half-installed", _("Removing %s")},
373 {"config-files", _("Removed %s")},
378 {"config-files", _("Preparing to completely remove %s")},
379 {"not-installed", _("Completely removed %s")},
384 // the dpkg states that the pkg will run through, the string is
385 // the package, the vector contains the dpkg states that the package
387 map
<string
,vector
<struct DpkgState
> > PackageOps
;
388 // the dpkg states that are already done; the string is the package
389 // the int is the state that is already done (e.g. a package that is
390 // going to be install is already in state "half-installed")
391 map
<string
,int> PackageOpsDone
;
393 // init the PackageOps map, go over the list of packages that
394 // that will be [installed|configured|removed|purged] and add
395 // them to the PackageOps map (the dpkg states it goes through)
396 // and the PackageOpsTranslations (human readable strings)
397 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end();I
++)
399 string name
= (*I
).Pkg
.Name();
400 PackageOpsDone
[name
] = 0;
401 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; i
++)
403 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
408 // this loop is runs once per operation
409 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end();)
411 vector
<Item
>::iterator J
= I
;
412 for (; J
!= List
.end() && J
->Op
== I
->Op
; J
++);
414 // Generate the argument list
415 const char *Args
[MaxArgs
+ 50];
416 if (J
- I
> (signed)MaxArgs
)
420 unsigned long Size
= 0;
421 string Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
422 Args
[n
++] = Tmp
.c_str();
423 Size
+= strlen(Args
[n
-1]);
425 // Stick in any custom dpkg options
426 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
430 for (; Opts
!= 0; Opts
= Opts
->Next
)
432 if (Opts
->Value
.empty() == true)
434 Args
[n
++] = Opts
->Value
.c_str();
435 Size
+= Opts
->Value
.length();
439 char status_fd_buf
[20];
443 Args
[n
++] = "--status-fd";
444 Size
+= strlen(Args
[n
-1]);
445 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
446 Args
[n
++] = status_fd_buf
;
447 Size
+= strlen(Args
[n
-1]);
452 Args
[n
++] = "--force-depends";
453 Size
+= strlen(Args
[n
-1]);
454 Args
[n
++] = "--force-remove-essential";
455 Size
+= strlen(Args
[n
-1]);
456 Args
[n
++] = "--remove";
457 Size
+= strlen(Args
[n
-1]);
461 Args
[n
++] = "--force-depends";
462 Size
+= strlen(Args
[n
-1]);
463 Args
[n
++] = "--force-remove-essential";
464 Size
+= strlen(Args
[n
-1]);
465 Args
[n
++] = "--purge";
466 Size
+= strlen(Args
[n
-1]);
469 case Item::Configure
:
470 Args
[n
++] = "--configure";
471 Size
+= strlen(Args
[n
-1]);
475 Args
[n
++] = "--unpack";
476 Size
+= strlen(Args
[n
-1]);
477 Args
[n
++] = "--auto-deconfigure";
478 Size
+= strlen(Args
[n
-1]);
482 // Write in the file or package names
483 if (I
->Op
== Item::Install
)
485 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
487 if (I
->File
[0] != '/')
488 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
489 Args
[n
++] = I
->File
.c_str();
490 Size
+= strlen(Args
[n
-1]);
495 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
497 Args
[n
++] = I
->Pkg
.Name();
498 Size
+= strlen(Args
[n
-1]);
504 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
506 for (unsigned int k
= 0; k
!= n
; k
++)
507 clog
<< Args
[k
] << ' ';
516 /* Mask off sig int/quit. We do this because dpkg also does when
517 it forks scripts. What happens is that when you hit ctrl-c it sends
518 it to all processes in the group. Since dpkg ignores the signal
519 it doesn't die but we do! So we must also ignore it */
520 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
521 sighandler_t old_SIGINT
= signal(SIGINT
,SIG_IGN
);
525 _config
->Set("APT::Keep-Fds::",fd
[1]);
531 close(fd
[0]); // close the read end of the pipe
533 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
536 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
539 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
542 // Discard everything in stdin before forking dpkg
543 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
546 while (read(STDIN_FILENO
,&dummy
,1) == 1);
548 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
552 /* No Job Control Stop Env is a magic dpkg var that prevents it
553 from using sigstop */
554 putenv("DPKG_NO_TSTP=yes");
555 execvp(Args
[0],(char **)Args
);
556 cerr
<< "Could not exec dpkg!" << endl
;
560 // clear the Keep-Fd again
561 _config
->Clear("APT::Keep-Fds",fd
[1]);
566 // we read from dpkg here
568 fcntl(_dpkgin
, F_SETFL
, O_NONBLOCK
);
569 close(fd
[1]); // close the write end of the pipe
571 // the read buffers for the communication with dpkg
572 char line
[1024] = {0,};
575 // the result of the waitpid call
578 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
580 // FIXME: move this to a function or something, looks ugly here
581 // error handling, waitpid returned -1
584 RunScripts("DPkg::Post-Invoke");
586 // Restore sig int/quit
587 signal(SIGQUIT
,old_SIGQUIT
);
588 signal(SIGINT
,old_SIGINT
);
589 return _error
->Errno("waitpid","Couldn't wait for subprocess");
592 // read a single char, make sure that the read can't block
593 // (otherwise we may leave zombies)
594 int len
= read(_dpkgin
, buf
, 1);
596 // nothing to read, wait a bit for more
603 // sanity check (should never happen)
604 if(strlen(line
) >= sizeof(line
)-10)
606 _error
->Error("got a overlong line from dpkg: '%s'",line
);
609 // append to line, check if we got a complete line
614 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
615 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
617 // the status we output
618 ostringstream status
;
620 /* dpkg sends strings like this:
621 'status: <pkg>: <pkg qstate>'
622 errors look like this:
623 '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
624 and conffile-prompt like this
625 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
629 if(!TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0])))
630 // FIXME: dpkg sends multiline error messages sometimes (see
631 // #374195 for a example. we should support this by
632 // either patching dpkg to not send multiline over the
633 // statusfd or by rewriting the code here to deal with
634 // it. for now we just ignore it and not crash
637 char *action
= _strstrip(list
[2]);
639 if(strncmp(action
,"error",strlen("error")) == 0)
641 status
<< "pmerror:" << list
[1]
642 << ":" << (Done
/float(Total
)*100.0)
646 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
648 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
649 std::clog
<< "send: '" << status
.str() << "'" << endl
;
652 if(strncmp(action
,"conffile",strlen("conffile")) == 0)
654 status
<< "pmconffile:" << list
[1]
655 << ":" << (Done
/float(Total
)*100.0)
659 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
661 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
662 std::clog
<< "send: '" << status
.str() << "'" << endl
;
666 vector
<struct DpkgState
> &states
= PackageOps
[pkg
];
667 const char *next_action
= NULL
;
668 if(PackageOpsDone
[pkg
] < states
.size())
669 next_action
= states
[PackageOpsDone
[pkg
]].state
;
670 // check if the package moved to the next dpkg state
671 if(next_action
&& (strcmp(action
, next_action
) == 0))
673 // only read the translation if there is actually a next
675 const char *translation
= states
[PackageOpsDone
[pkg
]].str
;
677 snprintf(s
, sizeof(s
), translation
, pkg
);
679 // we moved from one dpkg state to a new one, report that
680 PackageOpsDone
[pkg
]++;
682 // build the status str
683 status
<< "pmstatus:" << pkg
684 << ":" << (Done
/float(Total
)*100.0)
688 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
689 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
690 std::clog
<< "send: '" << status
.str() << "'" << endl
;
693 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
694 std::clog
<< "(parsed from dpkg) pkg: " << pkg
695 << " action: " << action
<< endl
;
697 // reset the line buffer
702 // Restore sig int/quit
703 signal(SIGQUIT
,old_SIGQUIT
);
704 signal(SIGINT
,old_SIGINT
);
706 // Check for an error code.
707 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
709 RunScripts("DPkg::Post-Invoke");
710 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
711 return _error
->Error("Sub-process %s received a segmentation fault.",Args
[0]);
713 if (WIFEXITED(Status
) != 0)
714 return _error
->Error("Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
716 return _error
->Error("Sub-process %s exited unexpectedly",Args
[0]);
720 if (RunScripts("DPkg::Post-Invoke") == false)
725 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
726 // ---------------------------------------------------------------------
728 void pkgDPkgPM::Reset()
730 List
.erase(List
.begin(),List
.end());