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 for remove with config %s")},
379 {"not-installed", _("Removed with config %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]);
480 // Write in the file or package names
481 if (I
->Op
== Item::Install
)
483 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
485 if (I
->File
[0] != '/')
486 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
487 Args
[n
++] = I
->File
.c_str();
488 Size
+= strlen(Args
[n
-1]);
493 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
495 Args
[n
++] = I
->Pkg
.Name();
496 Size
+= strlen(Args
[n
-1]);
502 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
504 for (unsigned int k
= 0; k
!= n
; k
++)
505 clog
<< Args
[k
] << ' ';
514 /* Mask off sig int/quit. We do this because dpkg also does when
515 it forks scripts. What happens is that when you hit ctrl-c it sends
516 it to all processes in the group. Since dpkg ignores the signal
517 it doesn't die but we do! So we must also ignore it */
518 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
519 sighandler_t old_SIGINT
= signal(SIGINT
,SIG_IGN
);
523 _config
->Set("APT::Keep-Fds::",fd
[1]);
529 close(fd
[0]); // close the read end of the pipe
531 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
534 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
537 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
540 // Discard everything in stdin before forking dpkg
541 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
544 while (read(STDIN_FILENO
,&dummy
,1) == 1);
546 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
550 /* No Job Control Stop Env is a magic dpkg var that prevents it
551 from using sigstop */
552 putenv("DPKG_NO_TSTP=yes");
553 execvp(Args
[0],(char **)Args
);
554 cerr
<< "Could not exec dpkg!" << endl
;
558 // clear the Keep-Fd again
559 _config
->Clear("APT::Keep-Fds",fd
[1]);
564 // we read from dpkg here
566 fcntl(_dpkgin
, F_SETFL
, O_NONBLOCK
);
567 close(fd
[1]); // close the write end of the pipe
569 // the read buffers for the communication with dpkg
570 char line
[1024] = {0,};
573 // the result of the waitpid call
576 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
578 // FIXME: move this to a function or something, looks ugly here
579 // error handling, waitpid returned -1
582 RunScripts("DPkg::Post-Invoke");
584 // Restore sig int/quit
585 signal(SIGQUIT
,old_SIGQUIT
);
586 signal(SIGINT
,old_SIGINT
);
587 return _error
->Errno("waitpid","Couldn't wait for subprocess");
590 // read a single char, make sure that the read can't block
591 // (otherwise we may leave zombies)
592 int len
= read(_dpkgin
, buf
, 1);
594 // nothing to read, wait a bit for more
601 // sanity check (should never happen)
602 if(strlen(line
) >= sizeof(line
)-10)
604 _error
->Error("got a overlong line from dpkg: '%s'",line
);
607 // append to line, check if we got a complete line
612 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
613 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
615 // the status we output
616 ostringstream status
;
618 /* dpkg sends strings like this:
619 'status: <pkg>: <pkg qstate>'
620 errors look like this:
621 '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
622 and conffile-prompt like this
623 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
627 TokSplitString(':', line
, list
, 5);
629 char *action
= _strstrip(list
[2]);
631 if(strncmp(action
,"error",strlen("error")) == 0)
633 status
<< "pmerror:" << list
[1]
634 << ":" << (Done
/float(Total
)*100.0)
638 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
640 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
641 std::clog
<< "send: '" << status
.str() << "'" << endl
;
644 if(strncmp(action
,"conffile",strlen("conffile")) == 0)
646 status
<< "pmconffile:" << list
[1]
647 << ":" << (Done
/float(Total
)*100.0)
651 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
653 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
654 std::clog
<< "send: '" << status
.str() << "'" << endl
;
658 vector
<struct DpkgState
> &states
= PackageOps
[pkg
];
659 const char *next_action
= NULL
;
660 if(PackageOpsDone
[pkg
] < states
.size())
661 next_action
= states
[PackageOpsDone
[pkg
]].state
;
662 // check if the package moved to the next dpkg state
663 if(next_action
&& (strcmp(action
, next_action
) == 0))
665 // only read the translation if there is actually a next
667 const char *translation
= states
[PackageOpsDone
[pkg
]].str
;
669 snprintf(s
, sizeof(s
), translation
, pkg
);
671 // we moved from one dpkg state to a new one, report that
672 PackageOpsDone
[pkg
]++;
674 // build the status str
675 status
<< "pmstatus:" << pkg
676 << ":" << (Done
/float(Total
)*100.0)
680 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
681 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
682 std::clog
<< "send: '" << status
.str() << "'" << endl
;
685 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
686 std::clog
<< "(parsed from dpkg) pkg: " << pkg
687 << " action: " << action
<< endl
;
689 // reset the line buffer
694 // Restore sig int/quit
695 signal(SIGQUIT
,old_SIGQUIT
);
696 signal(SIGINT
,old_SIGINT
);
698 // Check for an error code.
699 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
701 RunScripts("DPkg::Post-Invoke");
702 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
703 return _error
->Error("Sub-process %s received a segmentation fault.",Args
[0]);
705 if (WIFEXITED(Status
) != 0)
706 return _error
->Error("Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
708 return _error
->Error("Sub-process %s exited unexpectedly",Args
[0]);
712 if (RunScripts("DPkg::Post-Invoke") == false)
717 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
718 // ---------------------------------------------------------------------
720 void pkgDPkgPM::Reset()
722 List
.erase(List
.begin(),List
.end());