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>
42 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
43 // ---------------------------------------------------------------------
45 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
46 : pkgPackageManager(Cache
), dpkgbuf_pos(0), PackagesDone(0), PackagesTotal(0)
50 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
51 // ---------------------------------------------------------------------
53 pkgDPkgPM::~pkgDPkgPM()
57 // DPkgPM::Install - Install a package /*{{{*/
58 // ---------------------------------------------------------------------
59 /* Add an install operation to the sequence list */
60 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
62 if (File
.empty() == true || Pkg
.end() == true)
63 return _error
->Error("Internal Error, No file name for %s",Pkg
.Name());
65 List
.push_back(Item(Item::Install
,Pkg
,File
));
69 // DPkgPM::Configure - Configure a package /*{{{*/
70 // ---------------------------------------------------------------------
71 /* Add a configure operation to the sequence list */
72 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
74 if (Pkg
.end() == true)
77 List
.push_back(Item(Item::Configure
,Pkg
));
81 // DPkgPM::Remove - Remove a package /*{{{*/
82 // ---------------------------------------------------------------------
83 /* Add a remove operation to the sequence list */
84 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
86 if (Pkg
.end() == true)
90 List
.push_back(Item(Item::Purge
,Pkg
));
92 List
.push_back(Item(Item::Remove
,Pkg
));
96 // DPkgPM::RunScripts - Run a set of scripts /*{{{*/
97 // ---------------------------------------------------------------------
98 /* This looks for a list of script sto run from the configuration file,
99 each one is run with system from a forked child. */
100 bool pkgDPkgPM::RunScripts(const char *Cnf
)
102 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
103 if (Opts
== 0 || Opts
->Child
== 0)
107 // Fork for running the system calls
108 pid_t Child
= ExecFork();
113 if (chdir("/tmp/") != 0)
116 unsigned int Count
= 1;
117 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
119 if (Opts
->Value
.empty() == true)
122 if (system(Opts
->Value
.c_str()) != 0)
128 // Wait for the child
130 while (waitpid(Child
,&Status
,0) != Child
)
134 return _error
->Errno("waitpid","Couldn't wait for subprocess");
137 // Restore sig int/quit
138 signal(SIGQUIT
,SIG_DFL
);
139 signal(SIGINT
,SIG_DFL
);
141 // Check for an error code.
142 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
144 unsigned int Count
= WEXITSTATUS(Status
);
148 for (; Opts
!= 0 && Count
!= 1; Opts
= Opts
->Next
, Count
--);
149 _error
->Error("Problem executing scripts %s '%s'",Cnf
,Opts
->Value
.c_str());
152 return _error
->Error("Sub-process returned an error code");
158 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
159 // ---------------------------------------------------------------------
160 /* This is part of the helper script communication interface, it sends
161 very complete information down to the other end of the pipe.*/
162 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
164 fprintf(F
,"VERSION 2\n");
166 /* Write out all of the configuration directives by walking the
167 configuration tree */
168 const Configuration::Item
*Top
= _config
->Tree(0);
171 if (Top
->Value
.empty() == false)
174 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
175 QuoteString(Top
->Value
,"\n").c_str());
184 while (Top
!= 0 && Top
->Next
== 0)
191 // Write out the package actions in order.
192 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
194 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
196 fprintf(F
,"%s ",I
->Pkg
.Name());
198 if (I
->Pkg
->CurrentVer
== 0)
201 fprintf(F
,"%s ",I
->Pkg
.CurrentVer().VerStr());
203 // Show the compare operator
205 if (S
.InstallVer
!= 0)
208 if (I
->Pkg
->CurrentVer
!= 0)
209 Comp
= S
.InstVerIter(Cache
).CompareVer(I
->Pkg
.CurrentVer());
216 fprintf(F
,"%s ",S
.InstVerIter(Cache
).VerStr());
221 // Show the filename/operation
222 if (I
->Op
== Item::Install
)
225 if (I
->File
[0] != '/')
226 fprintf(F
,"**ERROR**\n");
228 fprintf(F
,"%s\n",I
->File
.c_str());
230 if (I
->Op
== Item::Configure
)
231 fprintf(F
,"**CONFIGURE**\n");
232 if (I
->Op
== Item::Remove
||
233 I
->Op
== Item::Purge
)
234 fprintf(F
,"**REMOVE**\n");
242 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
243 // ---------------------------------------------------------------------
244 /* This looks for a list of scripts to run from the configuration file
245 each one is run and is fed on standard input a list of all .deb files
246 that are due to be installed. */
247 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
249 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
250 if (Opts
== 0 || Opts
->Child
== 0)
254 unsigned int Count
= 1;
255 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
257 if (Opts
->Value
.empty() == true)
260 // Determine the protocol version
261 string OptSec
= Opts
->Value
;
262 string::size_type Pos
;
263 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
264 Pos
= OptSec
.length();
265 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
267 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
271 if (pipe(Pipes
) != 0)
272 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
273 SetCloseExec(Pipes
[0],true);
274 SetCloseExec(Pipes
[1],true);
276 // Purified Fork for running the script
277 pid_t Process
= ExecFork();
281 dup2(Pipes
[0],STDIN_FILENO
);
282 SetCloseExec(STDOUT_FILENO
,false);
283 SetCloseExec(STDIN_FILENO
,false);
284 SetCloseExec(STDERR_FILENO
,false);
289 Args
[2] = Opts
->Value
.c_str();
291 execv(Args
[0],(char **)Args
);
295 FILE *F
= fdopen(Pipes
[1],"w");
297 return _error
->Errno("fdopen","Faild to open new FD");
299 // Feed it the filenames.
303 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
305 // Only deal with packages to be installed from .deb
306 if (I
->Op
!= Item::Install
)
310 if (I
->File
[0] != '/')
313 /* Feed the filename of each package that is pending install
315 fprintf(F
,"%s\n",I
->File
.c_str());
324 Die
= !SendV2Pkgs(F
);
328 // Clean up the sub process
329 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
330 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
337 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
338 // ---------------------------------------------------------------------
341 void pkgDPkgPM::DoStdin(int master
)
343 char input_buf
[256] = {0,};
344 int len
= read(0, input_buf
, sizeof(input_buf
));
345 write(master
, input_buf
, len
);
348 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
349 // ---------------------------------------------------------------------
351 * read the terminal pty and write log
353 void pkgDPkgPM::DoTerminalPty(int master
, FILE *term_out
)
355 char term_buf
[1024] = {0,};
357 int len
=read(master
, term_buf
, sizeof(term_buf
));
360 write(1, term_buf
, len
);
362 fwrite(term_buf
, len
, sizeof(char), term_out
);
365 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
366 // ---------------------------------------------------------------------
369 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd
, char *line
)
371 // the status we output
372 ostringstream status
;
374 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
375 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
378 /* dpkg sends strings like this:
379 'status: <pkg>: <pkg qstate>'
380 errors look like this:
381 '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
382 and conffile-prompt like this
383 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
387 // dpkg sends multiline error messages sometimes (see
388 // #374195 for a example. we should support this by
389 // either patching dpkg to not send multiline over the
390 // statusfd or by rewriting the code here to deal with
391 // it. for now we just ignore it and not crash
392 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
394 char *action
= _strstrip(list
[2]);
395 if( pkg
== NULL
|| action
== NULL
)
397 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
398 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
402 if(strncmp(action
,"error",strlen("error")) == 0)
404 status
<< "pmerror:" << list
[1]
405 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
409 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
410 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
411 std::clog
<< "send: '" << status
.str() << "'" << endl
;
414 if(strncmp(action
,"conffile",strlen("conffile")) == 0)
416 status
<< "pmconffile:" << list
[1]
417 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
421 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
422 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
423 std::clog
<< "send: '" << status
.str() << "'" << endl
;
427 vector
<struct DpkgState
> &states
= PackageOps
[pkg
];
428 const char *next_action
= NULL
;
429 if(PackageOpsDone
[pkg
] < states
.size())
430 next_action
= states
[PackageOpsDone
[pkg
]].state
;
431 // check if the package moved to the next dpkg state
432 if(next_action
&& (strcmp(action
, next_action
) == 0))
434 // only read the translation if there is actually a next
436 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
438 snprintf(s
, sizeof(s
), translation
, pkg
);
440 // we moved from one dpkg state to a new one, report that
441 PackageOpsDone
[pkg
]++;
443 // build the status str
444 status
<< "pmstatus:" << pkg
445 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
449 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
450 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
451 std::clog
<< "send: '" << status
.str() << "'" << endl
;
453 if (_config
->FindB("Debug::pkgDPkgProgressReporting",false) == true)
454 std::clog
<< "(parsed from dpkg) pkg: " << pkg
455 << " action: " << action
<< endl
;
458 // DPkgPM::DoDpkgStatusFd /*{{{*/
459 // ---------------------------------------------------------------------
462 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
, int OutStatusFd
)
467 len
=read(statusfd
, &dpkgbuf
[dpkgbuf_pos
], sizeof(dpkgbuf
)-dpkgbuf_pos
);
472 // process line by line if we have a buffer
474 while((q
=(char*)memchr(p
, '\n', dpkgbuf
+dpkgbuf_pos
-p
)) != NULL
)
477 ProcessDpkgStatusLine(OutStatusFd
, p
);
478 p
=q
+1; // continue with next line
481 // now move the unprocessed bits (after the final \n that is now a 0x0)
482 // to the start and update dpkgbuf_pos
483 p
= (char*)memrchr(dpkgbuf
, 0, dpkgbuf_pos
);
487 // we are interessted in the first char *after* 0x0
490 // move the unprocessed tail to the start and update pos
491 memmove(dpkgbuf
, p
, p
-dpkgbuf
);
492 dpkgbuf_pos
= dpkgbuf
+dpkgbuf_pos
-p
;
497 // DPkgPM::Go - Run the sequence /*{{{*/
498 // ---------------------------------------------------------------------
499 /* This globs the operations and calls dpkg
501 * If it is called with "OutStatusFd" set to a valid file descriptor
502 * apt will report the install progress over this fd. It maps the
503 * dpkg states a package goes through to human readable (and i10n-able)
504 * names and calculates a percentage for each step.
506 bool pkgDPkgPM::Go(int OutStatusFd
)
508 unsigned int MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
509 unsigned int MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
511 if (RunScripts("DPkg::Pre-Invoke") == false)
514 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
517 // map the dpkg states to the operations that are performed
518 // (this is sorted in the same way as Item::Ops)
519 static const struct DpkgState DpkgStatesOpMap
[][5] = {
522 {"half-installed", N_("Preparing %s")},
523 {"unpacked", N_("Unpacking %s") },
526 // Configure operation
528 {"unpacked",N_("Preparing to configure %s") },
529 {"half-configured", N_("Configuring %s") },
530 { "installed", N_("Installed %s")},
535 {"half-configured", N_("Preparing for removal of %s")},
536 {"half-installed", N_("Removing %s")},
537 {"config-files", N_("Removed %s")},
542 {"config-files", N_("Preparing to completely remove %s")},
543 {"not-installed", N_("Completely removed %s")},
548 // init the PackageOps map, go over the list of packages that
549 // that will be [installed|configured|removed|purged] and add
550 // them to the PackageOps map (the dpkg states it goes through)
551 // and the PackageOpsTranslations (human readable strings)
552 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end();I
++)
554 string name
= (*I
).Pkg
.Name();
555 PackageOpsDone
[name
] = 0;
556 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; i
++)
558 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
564 string logdir
= _config
->FindDir("Dir::Log");
565 if(not FileExists(logdir
))
566 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
567 string logfile_name
= flCombine(logdir
,
568 _config
->Find("Dir::Log::Terminal"));
569 FILE *term_out
= NULL
;
570 if (!logfile_name
.empty())
572 term_out
= fopen(logfile_name
.c_str(),"a");
573 chmod(logfile_name
.c_str(), 0600);
574 // output current time
576 time_t t
= time(NULL
);
577 struct tm
*tmp
= localtime(&t
);
578 strftime(outstr
, sizeof(outstr
), "%F %T", tmp
);
579 fprintf(term_out
, "\nLog started: ");
580 fprintf(term_out
, outstr
);
581 fprintf(term_out
, "\n");
584 // this loop is runs once per operation
585 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end();)
587 vector
<Item
>::iterator J
= I
;
588 for (; J
!= List
.end() && J
->Op
== I
->Op
; J
++);
590 // Generate the argument list
591 const char *Args
[MaxArgs
+ 50];
592 if (J
- I
> (signed)MaxArgs
)
596 unsigned long Size
= 0;
597 string Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
598 Args
[n
++] = Tmp
.c_str();
599 Size
+= strlen(Args
[n
-1]);
601 // Stick in any custom dpkg options
602 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
606 for (; Opts
!= 0; Opts
= Opts
->Next
)
608 if (Opts
->Value
.empty() == true)
610 Args
[n
++] = Opts
->Value
.c_str();
611 Size
+= Opts
->Value
.length();
615 char status_fd_buf
[20];
619 Args
[n
++] = "--status-fd";
620 Size
+= strlen(Args
[n
-1]);
621 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
622 Args
[n
++] = status_fd_buf
;
623 Size
+= strlen(Args
[n
-1]);
628 Args
[n
++] = "--force-depends";
629 Size
+= strlen(Args
[n
-1]);
630 Args
[n
++] = "--force-remove-essential";
631 Size
+= strlen(Args
[n
-1]);
632 Args
[n
++] = "--remove";
633 Size
+= strlen(Args
[n
-1]);
637 Args
[n
++] = "--force-depends";
638 Size
+= strlen(Args
[n
-1]);
639 Args
[n
++] = "--force-remove-essential";
640 Size
+= strlen(Args
[n
-1]);
641 Args
[n
++] = "--purge";
642 Size
+= strlen(Args
[n
-1]);
645 case Item::Configure
:
646 Args
[n
++] = "--configure";
647 Size
+= strlen(Args
[n
-1]);
651 Args
[n
++] = "--unpack";
652 Size
+= strlen(Args
[n
-1]);
653 Args
[n
++] = "--auto-deconfigure";
654 Size
+= strlen(Args
[n
-1]);
658 // Write in the file or package names
659 if (I
->Op
== Item::Install
)
661 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
663 if (I
->File
[0] != '/')
664 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
665 Args
[n
++] = I
->File
.c_str();
666 Size
+= strlen(Args
[n
-1]);
671 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
673 Args
[n
++] = I
->Pkg
.Name();
674 Size
+= strlen(Args
[n
-1]);
680 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
682 for (unsigned int k
= 0; k
!= n
; k
++)
683 clog
<< Args
[k
] << ' ';
692 /* Mask off sig int/quit. We do this because dpkg also does when
693 it forks scripts. What happens is that when you hit ctrl-c it sends
694 it to all processes in the group. Since dpkg ignores the signal
695 it doesn't die but we do! So we must also ignore it */
696 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
697 sighandler_t old_SIGINT
= signal(SIGINT
,SIG_IGN
);
704 // FIXME: setup sensible signal handling (*ick*)
706 ioctl(0, TIOCGWINSZ
, (char *)&win
);
707 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
709 fprintf(stderr
, _("openpty failed\n"));
715 rtt
.c_lflag
&= ~ECHO
;
716 tcsetattr(0, TCSAFLUSH
, &rtt
);
720 _config
->Set("APT::Keep-Fds::",fd
[1]);
727 ioctl(slave
, TIOCSCTTY
, 0);
733 close(fd
[0]); // close the read end of the pipe
735 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
738 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
741 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
744 // Discard everything in stdin before forking dpkg
745 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
748 while (read(STDIN_FILENO
,&dummy
,1) == 1);
750 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
755 /* No Job Control Stop Env is a magic dpkg var that prevents it
756 from using sigstop */
757 putenv("DPKG_NO_TSTP=yes");
758 execvp(Args
[0],(char **)Args
);
759 cerr
<< "Could not exec dpkg!" << endl
;
763 // clear the Keep-Fd again
764 _config
->Clear("APT::Keep-Fds",fd
[1]);
769 // we read from dpkg here
771 close(fd
[1]); // close the write end of the pipe
773 // the result of the waitpid call
781 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
783 // FIXME: move this to a function or something, looks ugly here
784 // error handling, waitpid returned -1
787 RunScripts("DPkg::Post-Invoke");
789 // Restore sig int/quit
790 signal(SIGQUIT
,old_SIGQUIT
);
791 signal(SIGINT
,old_SIGINT
);
792 return _error
->Errno("waitpid","Couldn't wait for subprocess");
795 // wait for input or output here
798 FD_SET(_dpkgin
, &rfds
);
799 FD_SET(master
, &rfds
);
802 select_ret
= select(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
, &tv
);
804 std::cerr
<< "Error in select()" << std::endl
;
805 else if (select_ret
== 0)
808 if(FD_ISSET(master
, &rfds
))
809 DoTerminalPty(master
, term_out
);
810 if(FD_ISSET(0, &rfds
))
812 if(FD_ISSET(_dpkgin
, &rfds
))
813 DoDpkgStatusFd(_dpkgin
, OutStatusFd
);
817 // Restore sig int/quit
818 signal(SIGQUIT
,old_SIGQUIT
);
819 signal(SIGINT
,old_SIGINT
);
821 tcsetattr(0, TCSAFLUSH
, &tt
);
823 // Check for an error code.
824 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
826 // if it was set to "keep-dpkg-runing" then we won't return
827 // here but keep the loop going and just report it as a error
829 bool stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
832 RunScripts("DPkg::Post-Invoke");
834 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
835 _error
->Error("Sub-process %s received a segmentation fault.",Args
[0]);
836 else if (WIFEXITED(Status
) != 0)
837 _error
->Error("Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
839 _error
->Error("Sub-process %s exited unexpectedly",Args
[0]);
852 if (RunScripts("DPkg::Post-Invoke") == false)
857 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
858 // ---------------------------------------------------------------------
860 void pkgDPkgPM::Reset()
862 List
.erase(List
.begin(),List
.end());