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/strutl.h>
20 #include <sys/types.h>
30 #include <sys/ioctl.h>
39 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
40 // ---------------------------------------------------------------------
42 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
) : pkgPackageManager(Cache
)
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
);
531 ioctl(0, TIOCGWINSZ
, (char *)&win
);
532 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0) {
533 fprintf(stderr
, _("openpty failed\n"));
539 rtt
.c_lflag
&= ~ECHO
;
540 tcsetattr(0, TCSAFLUSH
, &rtt
);
544 _config
->Set("APT::Keep-Fds::",fd
[1]);
551 ioctl(slave
, TIOCSCTTY
, 0);
558 close(fd
[0]); // close the read end of the pipe
560 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
563 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
566 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
569 // Discard everything in stdin before forking dpkg
570 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
573 while (read(STDIN_FILENO
,&dummy
,1) == 1);
575 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
580 /* No Job Control Stop Env is a magic dpkg var that prevents it
581 from using sigstop */
582 putenv("DPKG_NO_TSTP=yes");
583 execvp(Args
[0],(char **)Args
);
584 cerr
<< "Could not exec dpkg!" << endl
;
588 // clear the Keep-Fd again
589 _config
->Clear("APT::Keep-Fds",fd
[1]);
594 // we read from dpkg here
596 fcntl(_dpkgin
, F_SETFL
, O_NONBLOCK
);
597 close(fd
[1]); // close the write end of the pipe
599 // the read buffers for the communication with dpkg
600 char line
[1024] = {0,};
603 char term_buf
[2] = {0,0};
604 char input_buf
[2] = {0,0};
606 // the result of the waitpid call
609 fcntl(0, F_SETFL
, O_NONBLOCK
);
610 fcntl(master
, F_SETFL
, O_NONBLOCK
);
611 FILE *term_out
= fopen("/var/log/dpkg-out.log","a");
612 chmod("/var/log/dpkg-out.log", 0600);
614 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
616 // FIXME: move this to a function or something, looks ugly here
617 // error handling, waitpid returned -1
620 RunScripts("DPkg::Post-Invoke");
622 // Restore sig int/quit
623 signal(SIGQUIT
,old_SIGQUIT
);
624 signal(SIGINT
,old_SIGINT
);
625 return _error
->Errno("waitpid","Couldn't wait for subprocess");
628 // wait for input or output here
630 // FIXME: use select() instead of the rubish below
632 // read a single char, make sure that the read can't block
633 // (otherwise we may leave zombies)
634 int term_len
= read(master
, term_buf
, 1);
635 int input_len
= read(0, input_buf
, 1);
636 int len
= read(_dpkgin
, buf
, 1);
638 // see if we have any input that needs to go to the
641 write(master
, input_buf
, 1);
643 // see if we have any output that needs to be echoed
644 // and written to the log
649 fwrite(term_buf
, 1, 1, term_out
);
650 write(1, term_buf
, 1);
651 } while(read(master
, term_buf
, 1) > 0);
655 // nothing to read from dpkg , wait a bit for more
662 // sanity check (should never happen)
663 if(strlen(line
) >= sizeof(line
)-10)
665 _error
->Error("got a overlong line from dpkg: '%s'",line
);
668 // append to line, check if we got a complete line
673 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
674 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
676 // the status we output
677 ostringstream status
;
679 /* dpkg sends strings like this:
680 'status: <pkg>: <pkg qstate>'
681 errors look like this:
682 '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
683 and conffile-prompt like this
684 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
688 // dpkg sends multiline error messages sometimes (see
689 // #374195 for a example. we should support this by
690 // either patching dpkg to not send multiline over the
691 // statusfd or by rewriting the code here to deal with
692 // it. for now we just ignore it and not crash
693 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
695 char *action
= _strstrip(list
[2]);
696 if( pkg
== NULL
|| action
== NULL
)
698 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
699 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
700 // reset the line buffer
705 if(strncmp(action
,"error",strlen("error")) == 0)
707 status
<< "pmerror:" << list
[1]
708 << ":" << (Done
/float(Total
)*100.0)
712 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
714 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
715 std::clog
<< "send: '" << status
.str() << "'" << endl
;
718 if(strncmp(action
,"conffile",strlen("conffile")) == 0)
720 status
<< "pmconffile:" << list
[1]
721 << ":" << (Done
/float(Total
)*100.0)
725 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
727 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
728 std::clog
<< "send: '" << status
.str() << "'" << endl
;
732 vector
<struct DpkgState
> &states
= PackageOps
[pkg
];
733 const char *next_action
= NULL
;
734 if(PackageOpsDone
[pkg
] < states
.size())
735 next_action
= states
[PackageOpsDone
[pkg
]].state
;
736 // check if the package moved to the next dpkg state
737 if(next_action
&& (strcmp(action
, next_action
) == 0))
739 // only read the translation if there is actually a next
741 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
743 snprintf(s
, sizeof(s
), translation
, pkg
);
745 // we moved from one dpkg state to a new one, report that
746 PackageOpsDone
[pkg
]++;
748 // build the status str
749 status
<< "pmstatus:" << pkg
750 << ":" << (Done
/float(Total
)*100.0)
754 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
755 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
756 std::clog
<< "send: '" << status
.str() << "'" << endl
;
759 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
760 std::clog
<< "(parsed from dpkg) pkg: " << pkg
761 << " action: " << action
<< endl
;
763 // reset the line buffer
769 // Restore sig int/quit
770 signal(SIGQUIT
,old_SIGQUIT
);
771 signal(SIGINT
,old_SIGINT
);
773 tcsetattr(0, TCSAFLUSH
, &tt
);
775 // Check for an error code.
776 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
778 // if it was set to "keep-dpkg-runing" then we won't return
779 // here but keep the loop going and just report it as a error
781 bool stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
784 RunScripts("DPkg::Post-Invoke");
786 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
787 _error
->Error("Sub-process %s received a segmentation fault.",Args
[0]);
788 else if (WIFEXITED(Status
) != 0)
789 _error
->Error("Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
791 _error
->Error("Sub-process %s exited unexpectedly",Args
[0]);
798 if (RunScripts("DPkg::Post-Invoke") == false)
803 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
804 // ---------------------------------------------------------------------
806 void pkgDPkgPM::Reset()
808 List
.erase(List
.begin(),List
.end());