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/select.h>
21 #include <sys/types.h>
31 #include <sys/ioctl.h>
40 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
41 // ---------------------------------------------------------------------
43 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
) : pkgPackageManager(Cache
)
47 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
48 // ---------------------------------------------------------------------
50 pkgDPkgPM::~pkgDPkgPM()
54 // DPkgPM::Install - Install a package /*{{{*/
55 // ---------------------------------------------------------------------
56 /* Add an install operation to the sequence list */
57 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
59 if (File
.empty() == true || Pkg
.end() == true)
60 return _error
->Error("Internal Error, No file name for %s",Pkg
.Name());
62 List
.push_back(Item(Item::Install
,Pkg
,File
));
66 // DPkgPM::Configure - Configure a package /*{{{*/
67 // ---------------------------------------------------------------------
68 /* Add a configure operation to the sequence list */
69 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
71 if (Pkg
.end() == true)
74 List
.push_back(Item(Item::Configure
,Pkg
));
78 // DPkgPM::Remove - Remove a package /*{{{*/
79 // ---------------------------------------------------------------------
80 /* Add a remove operation to the sequence list */
81 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
83 if (Pkg
.end() == true)
87 List
.push_back(Item(Item::Purge
,Pkg
));
89 List
.push_back(Item(Item::Remove
,Pkg
));
93 // DPkgPM::RunScripts - Run a set of scripts /*{{{*/
94 // ---------------------------------------------------------------------
95 /* This looks for a list of script sto run from the configuration file,
96 each one is run with system from a forked child. */
97 bool pkgDPkgPM::RunScripts(const char *Cnf
)
99 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
100 if (Opts
== 0 || Opts
->Child
== 0)
104 // Fork for running the system calls
105 pid_t Child
= ExecFork();
110 if (chdir("/tmp/") != 0)
113 unsigned int Count
= 1;
114 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
116 if (Opts
->Value
.empty() == true)
119 if (system(Opts
->Value
.c_str()) != 0)
125 // Wait for the child
127 while (waitpid(Child
,&Status
,0) != Child
)
131 return _error
->Errno("waitpid","Couldn't wait for subprocess");
134 // Restore sig int/quit
135 signal(SIGQUIT
,SIG_DFL
);
136 signal(SIGINT
,SIG_DFL
);
138 // Check for an error code.
139 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
141 unsigned int Count
= WEXITSTATUS(Status
);
145 for (; Opts
!= 0 && Count
!= 1; Opts
= Opts
->Next
, Count
--);
146 _error
->Error("Problem executing scripts %s '%s'",Cnf
,Opts
->Value
.c_str());
149 return _error
->Error("Sub-process returned an error code");
155 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
156 // ---------------------------------------------------------------------
157 /* This is part of the helper script communication interface, it sends
158 very complete information down to the other end of the pipe.*/
159 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
161 fprintf(F
,"VERSION 2\n");
163 /* Write out all of the configuration directives by walking the
164 configuration tree */
165 const Configuration::Item
*Top
= _config
->Tree(0);
168 if (Top
->Value
.empty() == false)
171 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
172 QuoteString(Top
->Value
,"\n").c_str());
181 while (Top
!= 0 && Top
->Next
== 0)
188 // Write out the package actions in order.
189 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
191 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
193 fprintf(F
,"%s ",I
->Pkg
.Name());
195 if (I
->Pkg
->CurrentVer
== 0)
198 fprintf(F
,"%s ",I
->Pkg
.CurrentVer().VerStr());
200 // Show the compare operator
202 if (S
.InstallVer
!= 0)
205 if (I
->Pkg
->CurrentVer
!= 0)
206 Comp
= S
.InstVerIter(Cache
).CompareVer(I
->Pkg
.CurrentVer());
213 fprintf(F
,"%s ",S
.InstVerIter(Cache
).VerStr());
218 // Show the filename/operation
219 if (I
->Op
== Item::Install
)
222 if (I
->File
[0] != '/')
223 fprintf(F
,"**ERROR**\n");
225 fprintf(F
,"%s\n",I
->File
.c_str());
227 if (I
->Op
== Item::Configure
)
228 fprintf(F
,"**CONFIGURE**\n");
229 if (I
->Op
== Item::Remove
||
230 I
->Op
== Item::Purge
)
231 fprintf(F
,"**REMOVE**\n");
239 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
240 // ---------------------------------------------------------------------
241 /* This looks for a list of scripts to run from the configuration file
242 each one is run and is fed on standard input a list of all .deb files
243 that are due to be installed. */
244 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
246 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
247 if (Opts
== 0 || Opts
->Child
== 0)
251 unsigned int Count
= 1;
252 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
254 if (Opts
->Value
.empty() == true)
257 // Determine the protocol version
258 string OptSec
= Opts
->Value
;
259 string::size_type Pos
;
260 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
261 Pos
= OptSec
.length();
262 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
264 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
268 if (pipe(Pipes
) != 0)
269 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
270 SetCloseExec(Pipes
[0],true);
271 SetCloseExec(Pipes
[1],true);
273 // Purified Fork for running the script
274 pid_t Process
= ExecFork();
278 dup2(Pipes
[0],STDIN_FILENO
);
279 SetCloseExec(STDOUT_FILENO
,false);
280 SetCloseExec(STDIN_FILENO
,false);
281 SetCloseExec(STDERR_FILENO
,false);
286 Args
[2] = Opts
->Value
.c_str();
288 execv(Args
[0],(char **)Args
);
292 FILE *F
= fdopen(Pipes
[1],"w");
294 return _error
->Errno("fdopen","Faild to open new FD");
296 // Feed it the filenames.
300 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
302 // Only deal with packages to be installed from .deb
303 if (I
->Op
!= Item::Install
)
307 if (I
->File
[0] != '/')
310 /* Feed the filename of each package that is pending install
312 fprintf(F
,"%s\n",I
->File
.c_str());
321 Die
= !SendV2Pkgs(F
);
325 // Clean up the sub process
326 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
327 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
334 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
335 // ---------------------------------------------------------------------
338 void pkgDPkgPM::DoStdin(int master
)
340 char input_buf
[2] = {0,0};
341 while(read(0, input_buf
, 1) > 0)
342 write(master
, input_buf
, 1);
345 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
346 // ---------------------------------------------------------------------
348 * read the terminal pty and write log
350 void pkgDPkgPM::DoTerminalPty(int master
, FILE *term_out
)
352 char term_buf
[2] = {0,0};
354 // read a single char, make sure that the read can't block
355 // (otherwise we may leave zombies)
356 while(read(master
, term_buf
, 1) > 0)
358 fwrite(term_buf
, 1, 1, term_out
);
359 write(1, term_buf
, 1);
366 // DPkgPM::Go - Run the sequence /*{{{*/
367 // ---------------------------------------------------------------------
368 /* This globs the operations and calls dpkg
370 * If it is called with "OutStatusFd" set to a valid file descriptor
371 * apt will report the install progress over this fd. It maps the
372 * dpkg states a package goes through to human readable (and i10n-able)
373 * names and calculates a percentage for each step.
375 bool pkgDPkgPM::Go(int OutStatusFd
)
377 unsigned int MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
378 unsigned int MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
380 if (RunScripts("DPkg::Pre-Invoke") == false)
383 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
386 // prepare the progress reporting
389 // map the dpkg states to the operations that are performed
390 // (this is sorted in the same way as Item::Ops)
391 static const struct DpkgState DpkgStatesOpMap
[][5] = {
394 {"half-installed", N_("Preparing %s")},
395 {"unpacked", N_("Unpacking %s") },
398 // Configure operation
400 {"unpacked",N_("Preparing to configure %s") },
401 {"half-configured", N_("Configuring %s") },
402 { "installed", N_("Installed %s")},
407 {"half-configured", N_("Preparing for removal of %s")},
408 {"half-installed", N_("Removing %s")},
409 {"config-files", N_("Removed %s")},
414 {"config-files", N_("Preparing to completely remove %s")},
415 {"not-installed", N_("Completely removed %s")},
420 // the dpkg states that the pkg will run through, the string is
421 // the package, the vector contains the dpkg states that the package
423 map
<string
,vector
<struct DpkgState
> > PackageOps
;
424 // the dpkg states that are already done; the string is the package
425 // the int is the state that is already done (e.g. a package that is
426 // going to be install is already in state "half-installed")
427 map
<string
,int> PackageOpsDone
;
429 // init the PackageOps map, go over the list of packages that
430 // that will be [installed|configured|removed|purged] and add
431 // them to the PackageOps map (the dpkg states it goes through)
432 // and the PackageOpsTranslations (human readable strings)
433 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end();I
++)
435 string name
= (*I
).Pkg
.Name();
436 PackageOpsDone
[name
] = 0;
437 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; i
++)
439 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
444 // this loop is runs once per operation
445 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end();)
447 vector
<Item
>::iterator J
= I
;
448 for (; J
!= List
.end() && J
->Op
== I
->Op
; J
++);
450 // Generate the argument list
451 const char *Args
[MaxArgs
+ 50];
452 if (J
- I
> (signed)MaxArgs
)
456 unsigned long Size
= 0;
457 string Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
458 Args
[n
++] = Tmp
.c_str();
459 Size
+= strlen(Args
[n
-1]);
461 // Stick in any custom dpkg options
462 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
466 for (; Opts
!= 0; Opts
= Opts
->Next
)
468 if (Opts
->Value
.empty() == true)
470 Args
[n
++] = Opts
->Value
.c_str();
471 Size
+= Opts
->Value
.length();
475 char status_fd_buf
[20];
479 Args
[n
++] = "--status-fd";
480 Size
+= strlen(Args
[n
-1]);
481 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
482 Args
[n
++] = status_fd_buf
;
483 Size
+= strlen(Args
[n
-1]);
488 Args
[n
++] = "--force-depends";
489 Size
+= strlen(Args
[n
-1]);
490 Args
[n
++] = "--force-remove-essential";
491 Size
+= strlen(Args
[n
-1]);
492 Args
[n
++] = "--remove";
493 Size
+= strlen(Args
[n
-1]);
497 Args
[n
++] = "--force-depends";
498 Size
+= strlen(Args
[n
-1]);
499 Args
[n
++] = "--force-remove-essential";
500 Size
+= strlen(Args
[n
-1]);
501 Args
[n
++] = "--purge";
502 Size
+= strlen(Args
[n
-1]);
505 case Item::Configure
:
506 Args
[n
++] = "--configure";
507 Size
+= strlen(Args
[n
-1]);
511 Args
[n
++] = "--unpack";
512 Size
+= strlen(Args
[n
-1]);
513 Args
[n
++] = "--auto-deconfigure";
514 Size
+= strlen(Args
[n
-1]);
518 // Write in the file or package names
519 if (I
->Op
== Item::Install
)
521 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
523 if (I
->File
[0] != '/')
524 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
525 Args
[n
++] = I
->File
.c_str();
526 Size
+= strlen(Args
[n
-1]);
531 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
533 Args
[n
++] = I
->Pkg
.Name();
534 Size
+= strlen(Args
[n
-1]);
540 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
542 for (unsigned int k
= 0; k
!= n
; k
++)
543 clog
<< Args
[k
] << ' ';
552 /* Mask off sig int/quit. We do this because dpkg also does when
553 it forks scripts. What happens is that when you hit ctrl-c it sends
554 it to all processes in the group. Since dpkg ignores the signal
555 it doesn't die but we do! So we must also ignore it */
556 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
557 sighandler_t old_SIGINT
= signal(SIGINT
,SIG_IGN
);
564 // FIXME: setup sensible signal handling (*ick*)
566 ioctl(0, TIOCGWINSZ
, (char *)&win
);
567 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
569 fprintf(stderr
, _("openpty failed\n"));
575 rtt
.c_lflag
&= ~ECHO
;
576 tcsetattr(0, TCSAFLUSH
, &rtt
);
580 _config
->Set("APT::Keep-Fds::",fd
[1]);
587 ioctl(slave
, TIOCSCTTY
, 0);
593 close(fd
[0]); // close the read end of the pipe
595 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
598 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
601 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
604 // Discard everything in stdin before forking dpkg
605 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
608 while (read(STDIN_FILENO
,&dummy
,1) == 1);
610 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
615 /* No Job Control Stop Env is a magic dpkg var that prevents it
616 from using sigstop */
617 putenv("DPKG_NO_TSTP=yes");
618 execvp(Args
[0],(char **)Args
);
619 cerr
<< "Could not exec dpkg!" << endl
;
623 // clear the Keep-Fd again
624 _config
->Clear("APT::Keep-Fds",fd
[1]);
629 // we read from dpkg here
631 fcntl(_dpkgin
, F_SETFL
, O_NONBLOCK
);
632 close(fd
[1]); // close the write end of the pipe
634 // the read buffers for the communication with dpkg
635 char line
[1024] = {0,};
638 // the result of the waitpid call
641 fcntl(0, F_SETFL
, O_NONBLOCK
);
642 fcntl(master
, F_SETFL
, O_NONBLOCK
);
644 // FIXME: make this a apt config option and add a logrotate file
645 FILE *term_out
= fopen("/var/log/dpkg-out.log","a");
646 chmod("/var/log/dpkg-out.log", 0600);
647 // output current time
649 time_t t
= time(NULL
);
650 struct tm
*tmp
= localtime(&t
);
651 strftime(outstr
, sizeof(outstr
), "%F %T", tmp
);
652 fprintf(term_out
, "Log started: ");
653 fprintf(term_out
, outstr
);
654 fprintf(term_out
, "\n");
662 FD_SET(_dpkgin
, &rfds
);
663 FD_SET(master
, &rfds
);
664 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
666 // FIXME: move this to a function or something, looks ugly here
667 // error handling, waitpid returned -1
670 RunScripts("DPkg::Post-Invoke");
672 // Restore sig int/quit
673 signal(SIGQUIT
,old_SIGQUIT
);
674 signal(SIGINT
,old_SIGINT
);
675 return _error
->Errno("waitpid","Couldn't wait for subprocess");
678 // wait for input or output here
681 select_ret
= select(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
, &tv
);
683 std::cerr
<< "Error in select()" << std::endl
;
684 else if (select_ret
== 0)
688 DoTerminalPty(master
, term_out
);
690 // FIXME: move this into its own function too
694 if(read(_dpkgin
, buf
, 1) <= 0)
697 // sanity check (should never happen)
698 if(strlen(line
) >= sizeof(line
)-10)
700 _error
->Error("got a overlong line from dpkg: '%s'",line
);
704 // append to line, check if we got a complete line
709 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
710 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
712 // the status we output
713 ostringstream status
;
715 /* dpkg sends strings like this:
716 'status: <pkg>: <pkg qstate>'
717 errors look like this:
718 '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
719 and conffile-prompt like this
720 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
724 // dpkg sends multiline error messages sometimes (see
725 // #374195 for a example. we should support this by
726 // either patching dpkg to not send multiline over the
727 // statusfd or by rewriting the code here to deal with
728 // it. for now we just ignore it and not crash
729 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
731 char *action
= _strstrip(list
[2]);
732 if( pkg
== NULL
|| action
== NULL
)
734 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
735 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
736 // reset the line buffer
741 if(strncmp(action
,"error",strlen("error")) == 0)
743 status
<< "pmerror:" << list
[1]
744 << ":" << (Done
/float(Total
)*100.0)
748 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
750 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
751 std::clog
<< "send: '" << status
.str() << "'" << endl
;
754 if(strncmp(action
,"conffile",strlen("conffile")) == 0)
756 status
<< "pmconffile:" << list
[1]
757 << ":" << (Done
/float(Total
)*100.0)
761 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
763 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
764 std::clog
<< "send: '" << status
.str() << "'" << endl
;
768 vector
<struct DpkgState
> &states
= PackageOps
[pkg
];
769 const char *next_action
= NULL
;
770 if(PackageOpsDone
[pkg
] < states
.size())
771 next_action
= states
[PackageOpsDone
[pkg
]].state
;
772 // check if the package moved to the next dpkg state
773 if(next_action
&& (strcmp(action
, next_action
) == 0))
775 // only read the translation if there is actually a next
777 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
779 snprintf(s
, sizeof(s
), translation
, pkg
);
781 // we moved from one dpkg state to a new one, report that
782 PackageOpsDone
[pkg
]++;
784 // build the status str
785 status
<< "pmstatus:" << pkg
786 << ":" << (Done
/float(Total
)*100.0)
790 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
791 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
792 std::clog
<< "send: '" << status
.str() << "'" << endl
;
795 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
796 std::clog
<< "(parsed from dpkg) pkg: " << pkg
797 << " action: " << action
<< endl
;
799 // reset the line buffer
806 // Restore sig int/quit
807 signal(SIGQUIT
,old_SIGQUIT
);
808 signal(SIGINT
,old_SIGINT
);
810 tcsetattr(0, TCSAFLUSH
, &tt
);
812 // Check for an error code.
813 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
815 // if it was set to "keep-dpkg-runing" then we won't return
816 // here but keep the loop going and just report it as a error
818 bool stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
821 RunScripts("DPkg::Post-Invoke");
823 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
824 _error
->Error("Sub-process %s received a segmentation fault.",Args
[0]);
825 else if (WIFEXITED(Status
) != 0)
826 _error
->Error("Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
828 _error
->Error("Sub-process %s exited unexpectedly",Args
[0]);
835 if (RunScripts("DPkg::Post-Invoke") == false)
840 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
841 // ---------------------------------------------------------------------
843 void pkgDPkgPM::Reset()
845 List
.erase(List
.begin(),List
.end());