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/pkgrecords.h>
16 #include <apt-pkg/strutl.h>
18 #include <apt-pkg/fileutl.h>
23 #include <sys/select.h>
25 #include <sys/types.h>
38 #include <sys/ioctl.h>
49 // Maps the dpkg "processing" info to human readable names. Entry 0
50 // of each array is the key, entry 1 is the value.
51 const std::pair
<const char *, const char *> PackageProcessingOps
[] = {
52 std::make_pair("install", N_("Installing %s")),
53 std::make_pair("configure", N_("Configuring %s")),
54 std::make_pair("remove", N_("Removing %s")),
55 std::make_pair("purge", N_("Completely removing %s")),
56 std::make_pair("disappear", N_("Noting disappearance of %s")),
57 std::make_pair("trigproc", N_("Running post-installation trigger %s"))
60 const std::pair
<const char *, const char *> * const PackageProcessingOpsBegin
= PackageProcessingOps
;
61 const std::pair
<const char *, const char *> * const PackageProcessingOpsEnd
= PackageProcessingOps
+ sizeof(PackageProcessingOps
) / sizeof(PackageProcessingOps
[0]);
63 // Predicate to test whether an entry in the PackageProcessingOps
64 // array matches a string.
65 class MatchProcessingOp
70 MatchProcessingOp(const char *the_target
)
75 bool operator()(const std::pair
<const char *, const char *> &pair
) const
77 return strcmp(pair
.first
, target
) == 0;
82 /* helper function to ionice the given PID
84 there is no C header for ionice yet - just the syscall interface
85 so we use the binary from util-linux
90 if (!FileExists("/usr/bin/ionice"))
92 pid_t Process
= ExecFork();
96 snprintf(buf
, sizeof(buf
), "-p%d", PID
);
98 Args
[0] = "/usr/bin/ionice";
102 execv(Args
[0], (char **)Args
);
104 return ExecWait(Process
, "ionice");
107 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
108 // ---------------------------------------------------------------------
110 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
111 : pkgPackageManager(Cache
), dpkgbuf_pos(0),
112 term_out(NULL
), history_out(NULL
), PackagesDone(0), PackagesTotal(0)
116 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
117 // ---------------------------------------------------------------------
119 pkgDPkgPM::~pkgDPkgPM()
123 // DPkgPM::Install - Install a package /*{{{*/
124 // ---------------------------------------------------------------------
125 /* Add an install operation to the sequence list */
126 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
128 if (File
.empty() == true || Pkg
.end() == true)
129 return _error
->Error("Internal Error, No file name for %s",Pkg
.Name());
131 // If the filename string begins with DPkg::Chroot-Directory, return the
132 // substr that is within the chroot so dpkg can access it.
133 string
const chrootdir
= _config
->FindDir("DPkg::Chroot-Directory","/");
134 if (chrootdir
!= "/" && File
.find(chrootdir
) == 0)
136 size_t len
= chrootdir
.length();
137 if (chrootdir
.at(len
- 1) == '/')
139 List
.push_back(Item(Item::Install
,Pkg
,File
.substr(len
)));
142 List
.push_back(Item(Item::Install
,Pkg
,File
));
147 // DPkgPM::Configure - Configure a package /*{{{*/
148 // ---------------------------------------------------------------------
149 /* Add a configure operation to the sequence list */
150 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
152 if (Pkg
.end() == true)
155 List
.push_back(Item(Item::Configure
, Pkg
));
157 // Use triggers for config calls if we configure "smart"
158 // as otherwise Pre-Depends will not be satisfied, see #526774
159 if (_config
->FindB("DPkg::TriggersPending", false) == true)
160 List
.push_back(Item(Item::TriggersPending
, PkgIterator()));
165 // DPkgPM::Remove - Remove a package /*{{{*/
166 // ---------------------------------------------------------------------
167 /* Add a remove operation to the sequence list */
168 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
170 if (Pkg
.end() == true)
174 List
.push_back(Item(Item::Purge
,Pkg
));
176 List
.push_back(Item(Item::Remove
,Pkg
));
180 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
181 // ---------------------------------------------------------------------
182 /* This is part of the helper script communication interface, it sends
183 very complete information down to the other end of the pipe.*/
184 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
186 fprintf(F
,"VERSION 2\n");
188 /* Write out all of the configuration directives by walking the
189 configuration tree */
190 const Configuration::Item
*Top
= _config
->Tree(0);
193 if (Top
->Value
.empty() == false)
196 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
197 QuoteString(Top
->Value
,"\n").c_str());
206 while (Top
!= 0 && Top
->Next
== 0)
213 // Write out the package actions in order.
214 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
216 if(I
->Pkg
.end() == true)
219 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
221 fprintf(F
,"%s ",I
->Pkg
.Name());
223 if (I
->Pkg
->CurrentVer
== 0)
226 fprintf(F
,"%s ",I
->Pkg
.CurrentVer().VerStr());
228 // Show the compare operator
230 if (S
.InstallVer
!= 0)
233 if (I
->Pkg
->CurrentVer
!= 0)
234 Comp
= S
.InstVerIter(Cache
).CompareVer(I
->Pkg
.CurrentVer());
241 fprintf(F
,"%s ",S
.InstVerIter(Cache
).VerStr());
246 // Show the filename/operation
247 if (I
->Op
== Item::Install
)
250 if (I
->File
[0] != '/')
251 fprintf(F
,"**ERROR**\n");
253 fprintf(F
,"%s\n",I
->File
.c_str());
255 if (I
->Op
== Item::Configure
)
256 fprintf(F
,"**CONFIGURE**\n");
257 if (I
->Op
== Item::Remove
||
258 I
->Op
== Item::Purge
)
259 fprintf(F
,"**REMOVE**\n");
267 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
268 // ---------------------------------------------------------------------
269 /* This looks for a list of scripts to run from the configuration file
270 each one is run and is fed on standard input a list of all .deb files
271 that are due to be installed. */
272 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
274 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
275 if (Opts
== 0 || Opts
->Child
== 0)
279 unsigned int Count
= 1;
280 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
282 if (Opts
->Value
.empty() == true)
285 // Determine the protocol version
286 string OptSec
= Opts
->Value
;
287 string::size_type Pos
;
288 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
289 Pos
= OptSec
.length();
290 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
292 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
296 if (pipe(Pipes
) != 0)
297 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
298 SetCloseExec(Pipes
[0],true);
299 SetCloseExec(Pipes
[1],true);
301 // Purified Fork for running the script
302 pid_t Process
= ExecFork();
306 dup2(Pipes
[0],STDIN_FILENO
);
307 SetCloseExec(STDOUT_FILENO
,false);
308 SetCloseExec(STDIN_FILENO
,false);
309 SetCloseExec(STDERR_FILENO
,false);
311 if (_config
->FindDir("DPkg::Chroot-Directory","/") != "/")
313 std::cerr
<< "Chrooting into "
314 << _config
->FindDir("DPkg::Chroot-Directory")
316 if (chroot(_config
->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
323 Args
[2] = Opts
->Value
.c_str();
325 execv(Args
[0],(char **)Args
);
329 FILE *F
= fdopen(Pipes
[1],"w");
331 return _error
->Errno("fdopen","Faild to open new FD");
333 // Feed it the filenames.
336 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
338 // Only deal with packages to be installed from .deb
339 if (I
->Op
!= Item::Install
)
343 if (I
->File
[0] != '/')
346 /* Feed the filename of each package that is pending install
348 fprintf(F
,"%s\n",I
->File
.c_str());
358 // Clean up the sub process
359 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
360 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
366 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
367 // ---------------------------------------------------------------------
370 void pkgDPkgPM::DoStdin(int master
)
372 unsigned char input_buf
[256] = {0,};
373 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
375 write(master
, input_buf
, len
);
377 stdin_is_dev_null
= true;
380 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
381 // ---------------------------------------------------------------------
383 * read the terminal pty and write log
385 void pkgDPkgPM::DoTerminalPty(int master
)
387 unsigned char term_buf
[1024] = {0,0, };
389 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
390 if(len
== -1 && errno
== EIO
)
392 // this happens when the child is about to exit, we
393 // give it time to actually exit, otherwise we run
400 write(1, term_buf
, len
);
402 fwrite(term_buf
, len
, sizeof(char), term_out
);
405 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
406 // ---------------------------------------------------------------------
409 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd
, char *line
)
411 bool const Debug
= _config
->FindB("Debug::pkgDPkgProgressReporting",false);
412 // the status we output
413 ostringstream status
;
416 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
419 /* dpkg sends strings like this:
420 'status: <pkg>: <pkg qstate>'
421 errors look like this:
422 '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
423 and conffile-prompt like this
424 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
426 Newer versions of dpkg sent also:
427 'processing: install: pkg'
428 'processing: configure: pkg'
429 'processing: remove: pkg'
430 'processing: purge: pkg'
431 'processing: disappear: pkg'
432 'processing: trigproc: trigger'
436 // dpkg sends multiline error messages sometimes (see
437 // #374195 for a example. we should support this by
438 // either patching dpkg to not send multiline over the
439 // statusfd or by rewriting the code here to deal with
440 // it. for now we just ignore it and not crash
441 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
442 if( list
[0] == NULL
|| list
[1] == NULL
|| list
[2] == NULL
)
445 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
448 const char* const pkg
= list
[1];
449 const char* action
= _strstrip(list
[2]);
451 // 'processing' from dpkg looks like
452 // 'processing: action: pkg'
453 if(strncmp(list
[0], "processing", strlen("processing")) == 0)
456 const char* const pkg_or_trigger
= _strstrip(list
[2]);
457 action
= _strstrip( list
[1]);
458 const std::pair
<const char *, const char *> * const iter
=
459 std::find_if(PackageProcessingOpsBegin
,
460 PackageProcessingOpsEnd
,
461 MatchProcessingOp(action
));
462 if(iter
== PackageProcessingOpsEnd
)
465 std::clog
<< "ignoring unknown action: " << action
<< std::endl
;
468 snprintf(s
, sizeof(s
), _(iter
->second
), pkg_or_trigger
);
470 status
<< "pmstatus:" << pkg_or_trigger
471 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
475 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
477 std::clog
<< "send: '" << status
.str() << "'" << endl
;
479 if (strncmp(action
, "disappear", strlen("disappear")) == 0)
480 handleDisappearAction(pkg_or_trigger
);
484 if(strncmp(action
,"error",strlen("error")) == 0)
486 // urgs, sometime has ":" in its error string so that we
487 // end up with the error message split between list[3]
488 // and list[4], e.g. the message:
489 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
491 if( list
[4] != NULL
)
492 list
[3][strlen(list
[3])] = ':';
494 status
<< "pmerror:" << list
[1]
495 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
499 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
501 std::clog
<< "send: '" << status
.str() << "'" << endl
;
503 WriteApportReport(list
[1], list
[3]);
506 else if(strncmp(action
,"conffile",strlen("conffile")) == 0)
508 status
<< "pmconffile:" << list
[1]
509 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
513 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
515 std::clog
<< "send: '" << status
.str() << "'" << endl
;
519 vector
<struct DpkgState
> const &states
= PackageOps
[pkg
];
520 const char *next_action
= NULL
;
521 if(PackageOpsDone
[pkg
] < states
.size())
522 next_action
= states
[PackageOpsDone
[pkg
]].state
;
523 // check if the package moved to the next dpkg state
524 if(next_action
&& (strcmp(action
, next_action
) == 0))
526 // only read the translation if there is actually a next
528 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
530 snprintf(s
, sizeof(s
), translation
, pkg
);
532 // we moved from one dpkg state to a new one, report that
533 PackageOpsDone
[pkg
]++;
535 // build the status str
536 status
<< "pmstatus:" << pkg
537 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
541 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
543 std::clog
<< "send: '" << status
.str() << "'" << endl
;
546 std::clog
<< "(parsed from dpkg) pkg: " << pkg
547 << " action: " << action
<< endl
;
550 // DPkgPM::handleDisappearAction /*{{{*/
551 void pkgDPkgPM::handleDisappearAction(string
const &pkgname
)
553 // record the package name for display and stuff later
554 disappearedPkgs
.insert(pkgname
);
556 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
557 if (unlikely(Pkg
.end() == true))
559 // the disappeared package was auto-installed - nothing to do
560 if ((Cache
[Pkg
].Flags
& pkgCache::Flag::Auto
) == pkgCache::Flag::Auto
)
562 pkgCache::VerIterator PkgVer
= Cache
[Pkg
].InstVerIter(Cache
);
563 if (unlikely(PkgVer
.end() == true))
565 /* search in the list of dependencies for (Pre)Depends,
566 check if this dependency has a Replaces on our package
567 and if so transfer the manual installed flag to it */
568 for (pkgCache::DepIterator Dep
= PkgVer
.DependsList(); Dep
.end() != true; ++Dep
)
570 if (Dep
->Type
!= pkgCache::Dep::Depends
&&
571 Dep
->Type
!= pkgCache::Dep::PreDepends
)
573 pkgCache::PkgIterator Tar
= Dep
.TargetPkg();
574 if (unlikely(Tar
.end() == true))
576 // the package is already marked as manual
577 if ((Cache
[Tar
].Flags
& pkgCache::Flag::Auto
) != pkgCache::Flag::Auto
)
579 pkgCache::VerIterator TarVer
= Cache
[Tar
].InstVerIter(Cache
);
580 if (TarVer
.end() == true)
582 for (pkgCache::DepIterator Rep
= TarVer
.DependsList(); Rep
.end() != true; ++Rep
)
584 if (Rep
->Type
!= pkgCache::Dep::Replaces
)
586 if (Pkg
!= Rep
.TargetPkg())
588 // okay, they are strongly connected - transfer manual-bit
590 std::clog
<< "transfer manual-bit from disappeared »" << pkgname
<< "« to »" << Tar
.FullName() << "«" << std::endl
;
591 Cache
[Tar
].Flags
&= ~Flag::Auto
;
597 // DPkgPM::DoDpkgStatusFd /*{{{*/
598 // ---------------------------------------------------------------------
601 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
, int OutStatusFd
)
606 len
=read(statusfd
, &dpkgbuf
[dpkgbuf_pos
], sizeof(dpkgbuf
)-dpkgbuf_pos
);
611 // process line by line if we have a buffer
613 while((q
=(char*)memchr(p
, '\n', dpkgbuf
+dpkgbuf_pos
-p
)) != NULL
)
616 ProcessDpkgStatusLine(OutStatusFd
, p
);
617 p
=q
+1; // continue with next line
620 // now move the unprocessed bits (after the final \n that is now a 0x0)
621 // to the start and update dpkgbuf_pos
622 p
= (char*)memrchr(dpkgbuf
, 0, dpkgbuf_pos
);
626 // we are interessted in the first char *after* 0x0
629 // move the unprocessed tail to the start and update pos
630 memmove(dpkgbuf
, p
, p
-dpkgbuf
);
631 dpkgbuf_pos
= dpkgbuf
+dpkgbuf_pos
-p
;
634 // DPkgPM::WriteHistoryTag /*{{{*/
635 void pkgDPkgPM::WriteHistoryTag(string
const &tag
, string value
)
637 size_t const length
= value
.length();
640 // poor mans rstrip(", ")
641 if (value
[length
-2] == ',' && value
[length
-1] == ' ')
642 value
.erase(length
- 2, 2);
643 fprintf(history_out
, "%s: %s\n", tag
.c_str(), value
.c_str());
645 // DPkgPM::OpenLog /*{{{*/
646 bool pkgDPkgPM::OpenLog()
648 string
const logdir
= _config
->FindDir("Dir::Log");
649 if(CreateAPTDirectoryIfNeeded(logdir
, logdir
) == false)
650 // FIXME: use a better string after freeze
651 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
655 time_t const t
= time(NULL
);
656 struct tm
const * const tmp
= localtime(&t
);
657 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
660 string
const logfile_name
= flCombine(logdir
,
661 _config
->Find("Dir::Log::Terminal"));
662 if (!logfile_name
.empty())
664 term_out
= fopen(logfile_name
.c_str(),"a");
665 if (term_out
== NULL
)
666 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name
.c_str());
667 setvbuf(term_out
, NULL
, _IONBF
, 0);
668 SetCloseExec(fileno(term_out
), true);
669 chmod(logfile_name
.c_str(), 0600);
670 fprintf(term_out
, "\nLog started: %s\n", timestr
);
673 // write your history
674 string
const history_name
= flCombine(logdir
,
675 _config
->Find("Dir::Log::History"));
676 if (!history_name
.empty())
678 history_out
= fopen(history_name
.c_str(),"a");
679 if (history_out
== NULL
)
680 return _error
->WarningE("OpenLog", _("Could not open file '%s'"), history_name
.c_str());
681 chmod(history_name
.c_str(), 0644);
682 fprintf(history_out
, "\nStart-Date: %s\n", timestr
);
683 string remove
, purge
, install
, upgrade
, downgrade
;
684 for (pkgCache::PkgIterator I
= Cache
.PkgBegin(); I
.end() == false; I
++)
686 if (Cache
[I
].NewInstall())
688 install
+= I
.FullName(false) + string(" (") + Cache
[I
].CandVersion
;
689 if (Cache
[I
].Flags
& pkgCache::Flag::Auto
)
690 install
+= ", automatic";
691 install
+= string("), ");
693 else if (Cache
[I
].Upgrade())
694 upgrade
+= I
.FullName(false) + string(" (") + Cache
[I
].CurVersion
+ string(", ") + Cache
[I
].CandVersion
+ string("), ");
695 else if (Cache
[I
].Downgrade())
696 downgrade
+= I
.FullName(false) + string(" (") + Cache
[I
].CurVersion
+ string(", ") + Cache
[I
].CandVersion
+ string("), ");
697 else if (Cache
[I
].Delete())
699 if ((Cache
[I
].iFlags
& pkgDepCache::Purge
) == pkgDepCache::Purge
)
700 purge
+= I
.FullName(false) + string(" (") + Cache
[I
].CurVersion
+ string("), ");
702 remove
+= I
.FullName(false) + string(" (") + Cache
[I
].CurVersion
+ string("), ");
705 if (_config
->Exists("Commandline::AsString") == true)
706 WriteHistoryTag("Commandline", _config
->Find("Commandline::AsString"));
707 WriteHistoryTag("Install", install
);
708 WriteHistoryTag("Upgrade", upgrade
);
709 WriteHistoryTag("Downgrade",downgrade
);
710 WriteHistoryTag("Remove",remove
);
711 WriteHistoryTag("Purge",purge
);
718 // DPkg::CloseLog /*{{{*/
719 bool pkgDPkgPM::CloseLog()
722 time_t t
= time(NULL
);
723 struct tm
*tmp
= localtime(&t
);
724 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
728 fprintf(term_out
, "Log ended: ");
729 fprintf(term_out
, "%s", timestr
);
730 fprintf(term_out
, "\n");
737 if (disappearedPkgs
.empty() == false)
740 for (std::set
<std::string
>::const_iterator d
= disappearedPkgs
.begin();
741 d
!= disappearedPkgs
.end(); ++d
)
743 pkgCache::PkgIterator P
= Cache
.FindPkg(*d
);
744 disappear
.append(*d
);
746 disappear
.append(", ");
748 disappear
.append(" (").append(Cache
[P
].CurVersion
).append("), ");
750 WriteHistoryTag("Disappeared", disappear
);
752 if (dpkg_error
.empty() == false)
753 fprintf(history_out
, "Error: %s\n", dpkg_error
.c_str());
754 fprintf(history_out
, "End-Date: %s\n", timestr
);
763 // This implements a racy version of pselect for those architectures
764 // that don't have a working implementation.
765 // FIXME: Probably can be removed on Lenny+1
766 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
767 fd_set
*exceptfds
, const struct timespec
*timeout
,
768 const sigset_t
*sigmask
)
774 tv
.tv_sec
= timeout
->tv_sec
;
775 tv
.tv_usec
= timeout
->tv_nsec
/1000;
777 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
778 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
779 sigprocmask(SIG_SETMASK
, &origmask
, 0);
783 // DPkgPM::Go - Run the sequence /*{{{*/
784 // ---------------------------------------------------------------------
785 /* This globs the operations and calls dpkg
787 * If it is called with "OutStatusFd" set to a valid file descriptor
788 * apt will report the install progress over this fd. It maps the
789 * dpkg states a package goes through to human readable (and i10n-able)
790 * names and calculates a percentage for each step.
792 bool pkgDPkgPM::Go(int OutStatusFd
)
797 sigset_t original_sigmask
;
799 unsigned int const MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
800 unsigned int const MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
801 bool const NoTriggers
= _config
->FindB("DPkg::NoTriggers", false);
803 if (RunScripts("DPkg::Pre-Invoke") == false)
806 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
809 // support subpressing of triggers processing for special
810 // cases like d-i that runs the triggers handling manually
811 bool const SmartConf
= (_config
->Find("PackageManager::Configure", "all") != "all");
812 bool const TriggersPending
= _config
->FindB("DPkg::TriggersPending", false);
813 if (_config
->FindB("DPkg::ConfigurePending", SmartConf
) == true)
814 List
.push_back(Item(Item::ConfigurePending
, PkgIterator()));
816 // map the dpkg states to the operations that are performed
817 // (this is sorted in the same way as Item::Ops)
818 static const struct DpkgState DpkgStatesOpMap
[][7] = {
821 {"half-installed", N_("Preparing %s")},
822 {"unpacked", N_("Unpacking %s") },
825 // Configure operation
827 {"unpacked",N_("Preparing to configure %s") },
828 {"half-configured", N_("Configuring %s") },
829 { "installed", N_("Installed %s")},
834 {"half-configured", N_("Preparing for removal of %s")},
835 {"half-installed", N_("Removing %s")},
836 {"config-files", N_("Removed %s")},
841 {"config-files", N_("Preparing to completely remove %s")},
842 {"not-installed", N_("Completely removed %s")},
847 // init the PackageOps map, go over the list of packages that
848 // that will be [installed|configured|removed|purged] and add
849 // them to the PackageOps map (the dpkg states it goes through)
850 // and the PackageOpsTranslations (human readable strings)
851 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();I
++)
853 if((*I
).Pkg
.end() == true)
856 string
const name
= (*I
).Pkg
.Name();
857 PackageOpsDone
[name
] = 0;
858 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; i
++)
860 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
865 stdin_is_dev_null
= false;
870 // this loop is runs once per operation
871 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();)
873 // Do all actions with the same Op in one run
874 vector
<Item
>::const_iterator J
= I
;
875 if (TriggersPending
== true)
876 for (; J
!= List
.end(); J
++)
880 if (J
->Op
!= Item::TriggersPending
)
882 vector
<Item
>::const_iterator T
= J
+ 1;
883 if (T
!= List
.end() && T
->Op
== I
->Op
)
888 for (; J
!= List
.end() && J
->Op
== I
->Op
; J
++)
891 // Generate the argument list
892 const char *Args
[MaxArgs
+ 50];
893 // keep track of allocated strings for multiarch package names
894 char *Packages
[MaxArgs
+ 50];
895 unsigned int pkgcount
= 0;
897 // Now check if we are within the MaxArgs limit
899 // this code below is problematic, because it may happen that
900 // the argument list is split in a way that A depends on B
901 // and they are in the same "--configure A B" run
902 // - with the split they may now be configured in different
904 if (J
- I
> (signed)MaxArgs
)
908 unsigned long Size
= 0;
909 string
const Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
910 Args
[n
++] = Tmp
.c_str();
911 Size
+= strlen(Args
[n
-1]);
913 // Stick in any custom dpkg options
914 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
918 for (; Opts
!= 0; Opts
= Opts
->Next
)
920 if (Opts
->Value
.empty() == true)
922 Args
[n
++] = Opts
->Value
.c_str();
923 Size
+= Opts
->Value
.length();
927 char status_fd_buf
[20];
931 Args
[n
++] = "--status-fd";
932 Size
+= strlen(Args
[n
-1]);
933 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
934 Args
[n
++] = status_fd_buf
;
935 Size
+= strlen(Args
[n
-1]);
940 Args
[n
++] = "--force-depends";
941 Size
+= strlen(Args
[n
-1]);
942 Args
[n
++] = "--force-remove-essential";
943 Size
+= strlen(Args
[n
-1]);
944 Args
[n
++] = "--remove";
945 Size
+= strlen(Args
[n
-1]);
949 Args
[n
++] = "--force-depends";
950 Size
+= strlen(Args
[n
-1]);
951 Args
[n
++] = "--force-remove-essential";
952 Size
+= strlen(Args
[n
-1]);
953 Args
[n
++] = "--purge";
954 Size
+= strlen(Args
[n
-1]);
957 case Item::Configure
:
958 Args
[n
++] = "--configure";
959 Size
+= strlen(Args
[n
-1]);
962 case Item::ConfigurePending
:
963 Args
[n
++] = "--configure";
964 Size
+= strlen(Args
[n
-1]);
965 Args
[n
++] = "--pending";
966 Size
+= strlen(Args
[n
-1]);
969 case Item::TriggersPending
:
970 Args
[n
++] = "--triggers-only";
971 Size
+= strlen(Args
[n
-1]);
972 Args
[n
++] = "--pending";
973 Size
+= strlen(Args
[n
-1]);
977 Args
[n
++] = "--unpack";
978 Size
+= strlen(Args
[n
-1]);
979 Args
[n
++] = "--auto-deconfigure";
980 Size
+= strlen(Args
[n
-1]);
984 if (NoTriggers
== true && I
->Op
!= Item::TriggersPending
&&
985 I
->Op
!= Item::ConfigurePending
)
987 Args
[n
++] = "--no-triggers";
988 Size
+= strlen(Args
[n
-1]);
991 // Write in the file or package names
992 if (I
->Op
== Item::Install
)
994 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
996 if (I
->File
[0] != '/')
997 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
998 Args
[n
++] = I
->File
.c_str();
999 Size
+= strlen(Args
[n
-1]);
1004 string
const nativeArch
= _config
->Find("APT::Architecture");
1005 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
1007 if((*I
).Pkg
.end() == true)
1009 if (I
->Op
== Item::Configure
&& disappearedPkgs
.find(I
->Pkg
.Name()) != disappearedPkgs
.end())
1011 if (I
->Pkg
.Arch() == nativeArch
|| !strcmp(I
->Pkg
.Arch(), "all"))
1012 Args
[n
++] = I
->Pkg
.Name();
1015 Packages
[pkgcount
] = strdup(I
->Pkg
.FullName(false).c_str());
1016 Args
[n
++] = Packages
[pkgcount
++];
1018 Size
+= strlen(Args
[n
-1]);
1024 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
1026 for (unsigned int k
= 0; k
!= n
; k
++)
1027 clog
<< Args
[k
] << ' ';
1036 /* Mask off sig int/quit. We do this because dpkg also does when
1037 it forks scripts. What happens is that when you hit ctrl-c it sends
1038 it to all processes in the group. Since dpkg ignores the signal
1039 it doesn't die but we do! So we must also ignore it */
1040 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
1041 sighandler_t old_SIGINT
= signal(SIGINT
,SIG_IGN
);
1043 // ignore SIGHUP as well (debian #463030)
1044 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
1051 // if tcgetattr does not return zero there was a error
1052 // and we do not do any pty magic
1053 if (tcgetattr(0, &tt
) == 0)
1055 ioctl(0, TIOCGWINSZ
, (char *)&win
);
1056 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
1058 const char *s
= _("Can not write log, openpty() "
1059 "failed (/dev/pts not mounted?)\n");
1060 fprintf(stderr
, "%s",s
);
1062 fprintf(term_out
, "%s",s
);
1063 master
= slave
= -1;
1068 rtt
.c_lflag
&= ~ECHO
;
1069 rtt
.c_lflag
|= ISIG
;
1070 // block SIGTTOU during tcsetattr to prevent a hang if
1071 // the process is a member of the background process group
1072 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
1073 sigemptyset(&sigmask
);
1074 sigaddset(&sigmask
, SIGTTOU
);
1075 sigprocmask(SIG_BLOCK
,&sigmask
, &original_sigmask
);
1076 tcsetattr(0, TCSAFLUSH
, &rtt
);
1077 sigprocmask(SIG_SETMASK
, &original_sigmask
, 0);
1083 _config
->Set("APT::Keep-Fds::",fd
[1]);
1084 // send status information that we are about to fork dpkg
1085 if(OutStatusFd
> 0) {
1086 ostringstream status
;
1087 status
<< "pmstatus:dpkg-exec:"
1088 << (PackagesDone
/float(PackagesTotal
)*100.0)
1089 << ":" << _("Running dpkg")
1091 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
1095 // This is the child
1098 if(slave
>= 0 && master
>= 0)
1101 ioctl(slave
, TIOCSCTTY
, 0);
1108 close(fd
[0]); // close the read end of the pipe
1110 if (_config
->FindDir("DPkg::Chroot-Directory","/") != "/")
1112 std::cerr
<< "Chrooting into "
1113 << _config
->FindDir("DPkg::Chroot-Directory")
1115 if (chroot(_config
->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
1119 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
1122 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
1125 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
1128 // Discard everything in stdin before forking dpkg
1129 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
1132 while (read(STDIN_FILENO
,&dummy
,1) == 1);
1134 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
1138 /* No Job Control Stop Env is a magic dpkg var that prevents it
1139 from using sigstop */
1140 putenv((char *)"DPKG_NO_TSTP=yes");
1141 execvp(Args
[0],(char **)Args
);
1142 cerr
<< "Could not exec dpkg!" << endl
;
1147 if (_config
->FindB("DPkg::UseIoNice", false) == true)
1150 // clear the Keep-Fd again
1151 _config
->Clear("APT::Keep-Fds",fd
[1]);
1156 // we read from dpkg here
1157 int const _dpkgin
= fd
[0];
1158 close(fd
[1]); // close the write end of the pipe
1164 sigemptyset(&sigmask
);
1165 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
1167 /* clean up the temporary allocation for multiarch package names in
1168 the parent, so we don't leak memory when we return. */
1169 for (unsigned int i
= 0; i
< pkgcount
; i
++)
1172 // the result of the waitpid call
1175 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
1177 // FIXME: move this to a function or something, looks ugly here
1178 // error handling, waitpid returned -1
1181 RunScripts("DPkg::Post-Invoke");
1183 // Restore sig int/quit
1184 signal(SIGQUIT
,old_SIGQUIT
);
1185 signal(SIGINT
,old_SIGINT
);
1186 signal(SIGHUP
,old_SIGHUP
);
1187 return _error
->Errno("waitpid","Couldn't wait for subprocess");
1190 // wait for input or output here
1192 if (master
>= 0 && !stdin_is_dev_null
)
1194 FD_SET(_dpkgin
, &rfds
);
1196 FD_SET(master
, &rfds
);
1199 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
1200 &tv
, &original_sigmask
);
1201 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
1202 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
1203 NULL
, &tv
, &original_sigmask
);
1204 if (select_ret
== 0)
1206 else if (select_ret
< 0 && errno
== EINTR
)
1208 else if (select_ret
< 0)
1210 perror("select() returned error");
1214 if(master
>= 0 && FD_ISSET(master
, &rfds
))
1215 DoTerminalPty(master
);
1216 if(master
>= 0 && FD_ISSET(0, &rfds
))
1218 if(FD_ISSET(_dpkgin
, &rfds
))
1219 DoDpkgStatusFd(_dpkgin
, OutStatusFd
);
1223 // Restore sig int/quit
1224 signal(SIGQUIT
,old_SIGQUIT
);
1225 signal(SIGINT
,old_SIGINT
);
1226 signal(SIGHUP
,old_SIGHUP
);
1230 tcsetattr(0, TCSAFLUSH
, &tt
);
1234 // Check for an error code.
1235 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
1237 // if it was set to "keep-dpkg-runing" then we won't return
1238 // here but keep the loop going and just report it as a error
1240 bool const stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
1243 RunScripts("DPkg::Post-Invoke");
1245 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
1246 strprintf(dpkg_error
, "Sub-process %s received a segmentation fault.",Args
[0]);
1247 else if (WIFEXITED(Status
) != 0)
1248 strprintf(dpkg_error
, "Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
1250 strprintf(dpkg_error
, "Sub-process %s exited unexpectedly",Args
[0]);
1252 if(dpkg_error
.size() > 0)
1253 _error
->Error("%s", dpkg_error
.c_str());
1264 if (RunScripts("DPkg::Post-Invoke") == false)
1267 Cache
.writeStateFile(NULL
);
1271 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1272 // ---------------------------------------------------------------------
1274 void pkgDPkgPM::Reset()
1276 List
.erase(List
.begin(),List
.end());
1279 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1280 // ---------------------------------------------------------------------
1282 void pkgDPkgPM::WriteApportReport(const char *pkgpath
, const char *errormsg
)
1284 string pkgname
, reportfile
, srcpkgname
, pkgver
, arch
;
1285 string::size_type pos
;
1288 if (_config
->FindB("Dpkg::ApportFailureReport", false) == false)
1290 std::clog
<< "configured to not write apport reports" << std::endl
;
1294 // only report the first errors
1295 if(pkgFailures
> _config
->FindI("APT::Apport::MaxReports", 3))
1297 std::clog
<< _("No apport report written because MaxReports is reached already") << std::endl
;
1301 // check if its not a follow up error
1302 const char *needle
= dgettext("dpkg", "dependency problems - leaving unconfigured");
1303 if(strstr(errormsg
, needle
) != NULL
) {
1304 std::clog
<< _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl
;
1308 // do not report disk-full failures
1309 if(strstr(errormsg
, strerror(ENOSPC
)) != NULL
) {
1310 std::clog
<< _("No apport report written because the error message indicates a disk full error") << std::endl
;
1314 // do not report out-of-memory failures
1315 if(strstr(errormsg
, strerror(ENOMEM
)) != NULL
) {
1316 std::clog
<< _("No apport report written because the error message indicates a out of memory error") << std::endl
;
1320 // do not report dpkg I/O errors
1321 // XXX - this message is localized, but this only matches the English version. This is better than nothing.
1322 if(strstr(errormsg
, "short read in buffer_copy (")) {
1323 std::clog
<< _("No apport report written because the error message indicates a dpkg I/O error") << std::endl
;
1327 // get the pkgname and reportfile
1328 pkgname
= flNotDir(pkgpath
);
1329 pos
= pkgname
.find('_');
1330 if(pos
!= string::npos
)
1331 pkgname
= pkgname
.substr(0, pos
);
1333 // find the package versin and source package name
1334 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
1335 if (Pkg
.end() == true)
1337 pkgCache::VerIterator Ver
= Cache
.GetCandidateVer(Pkg
);
1338 if (Ver
.end() == true)
1340 pkgver
= Ver
.VerStr() == NULL
? "unknown" : Ver
.VerStr();
1341 pkgRecords
Recs(Cache
);
1342 pkgRecords::Parser
&Parse
= Recs
.Lookup(Ver
.FileList());
1343 srcpkgname
= Parse
.SourcePkg();
1344 if(srcpkgname
.empty())
1345 srcpkgname
= pkgname
;
1347 // if the file exists already, we check:
1348 // - if it was reported already (touched by apport).
1349 // If not, we do nothing, otherwise
1350 // we overwrite it. This is the same behaviour as apport
1351 // - if we have a report with the same pkgversion already
1353 reportfile
= flCombine("/var/crash",pkgname
+".0.crash");
1354 if(FileExists(reportfile
))
1359 // check atime/mtime
1360 stat(reportfile
.c_str(), &buf
);
1361 if(buf
.st_mtime
> buf
.st_atime
)
1364 // check if the existing report is the same version
1365 report
= fopen(reportfile
.c_str(),"r");
1366 while(fgets(strbuf
, sizeof(strbuf
), report
) != NULL
)
1368 if(strstr(strbuf
,"Package:") == strbuf
)
1370 char pkgname
[255], version
[255];
1371 if(sscanf(strbuf
, "Package: %s %s", pkgname
, version
) == 2)
1372 if(strcmp(pkgver
.c_str(), version
) == 0)
1382 // now write the report
1383 arch
= _config
->Find("APT::Architecture");
1384 report
= fopen(reportfile
.c_str(),"w");
1387 if(_config
->FindB("DPkgPM::InitialReportOnly",false) == true)
1388 chmod(reportfile
.c_str(), 0);
1390 chmod(reportfile
.c_str(), 0600);
1391 fprintf(report
, "ProblemType: Package\n");
1392 fprintf(report
, "Architecture: %s\n", arch
.c_str());
1393 time_t now
= time(NULL
);
1394 fprintf(report
, "Date: %s" , ctime(&now
));
1395 fprintf(report
, "Package: %s %s\n", pkgname
.c_str(), pkgver
.c_str());
1396 fprintf(report
, "SourcePackage: %s\n", srcpkgname
.c_str());
1397 fprintf(report
, "ErrorMessage:\n %s\n", errormsg
);
1399 // ensure that the log is flushed
1403 // attach terminal log it if we have it
1404 string logfile_name
= _config
->FindFile("Dir::Log::Terminal");
1405 if (!logfile_name
.empty())
1410 fprintf(report
, "DpkgTerminalLog:\n");
1411 log
= fopen(logfile_name
.c_str(),"r");
1414 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1415 fprintf(report
, " %s", buf
);
1421 const char *ops_str
[] = {"Install", "Configure","Remove","Purge"};
1422 fprintf(report
, "AptOrdering:\n");
1423 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
1424 fprintf(report
, " %s: %s\n", (*I
).Pkg
.Name(), ops_str
[(*I
).Op
]);
1426 // attach dmesg log (to learn about segfaults)
1427 if (FileExists("/bin/dmesg"))
1432 fprintf(report
, "Dmesg:\n");
1433 log
= popen("/bin/dmesg","r");
1436 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1437 fprintf(report
, " %s", buf
);
1442 // attach df -l log (to learn about filesystem status)
1443 if (FileExists("/bin/df"))
1448 fprintf(report
, "Df:\n");
1449 log
= popen("/bin/df -l","r");
1452 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1453 fprintf(report
, " %s", buf
);