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>
24 #include <sys/types.h>
37 #include <sys/ioctl.h>
48 // Maps the dpkg "processing" info to human readable names. Entry 0
49 // of each array is the key, entry 1 is the value.
50 const std::pair
<const char *, const char *> PackageProcessingOps
[] = {
51 std::make_pair("install", N_("Installing %s")),
52 std::make_pair("configure", N_("Configuring %s")),
53 std::make_pair("remove", N_("Removing %s")),
54 std::make_pair("purge", N_("Completely removing %s")),
55 std::make_pair("trigproc", N_("Running post-installation trigger %s"))
58 const std::pair
<const char *, const char *> * const PackageProcessingOpsBegin
= PackageProcessingOps
;
59 const std::pair
<const char *, const char *> * const PackageProcessingOpsEnd
= PackageProcessingOps
+ sizeof(PackageProcessingOps
) / sizeof(PackageProcessingOps
[0]);
61 // Predicate to test whether an entry in the PackageProcessingOps
62 // array matches a string.
63 class MatchProcessingOp
68 MatchProcessingOp(const char *the_target
)
73 bool operator()(const std::pair
<const char *, const char *> &pair
) const
75 return strcmp(pair
.first
, target
) == 0;
80 /* helper function to ionice the given PID
82 there is no C header for ionice yet - just the syscall interface
83 so we use the binary from util-linux
88 if (!FileExists("/usr/bin/ionice"))
90 pid_t Process
= ExecFork();
94 snprintf(buf
, sizeof(buf
), "-p%d", PID
);
96 Args
[0] = "/usr/bin/ionice";
100 execv(Args
[0], (char **)Args
);
102 return ExecWait(Process
, "ionice");
105 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
106 // ---------------------------------------------------------------------
108 pkgDPkgPM::pkgDPkgPM(pkgDepCache
*Cache
)
109 : pkgPackageManager(Cache
), dpkgbuf_pos(0),
110 term_out(NULL
), PackagesDone(0), PackagesTotal(0), pkgFailures(0)
114 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
115 // ---------------------------------------------------------------------
117 pkgDPkgPM::~pkgDPkgPM()
121 // DPkgPM::Install - Install a package /*{{{*/
122 // ---------------------------------------------------------------------
123 /* Add an install operation to the sequence list */
124 bool pkgDPkgPM::Install(PkgIterator Pkg
,string File
)
126 if (File
.empty() == true || Pkg
.end() == true)
127 return _error
->Error("Internal Error, No file name for %s",Pkg
.Name());
129 List
.push_back(Item(Item::Install
,Pkg
,File
));
133 // DPkgPM::Configure - Configure a package /*{{{*/
134 // ---------------------------------------------------------------------
135 /* Add a configure operation to the sequence list */
136 bool pkgDPkgPM::Configure(PkgIterator Pkg
)
138 if (Pkg
.end() == true)
141 List
.push_back(Item(Item::Configure
, Pkg
));
143 // Use triggers for config calls if we configure "smart"
144 // as otherwise Pre-Depends will not be satisfied, see #526774
145 if (_config
->FindB("DPkg::TriggersPending", false) == true)
146 List
.push_back(Item(Item::TriggersPending
, PkgIterator()));
151 // DPkgPM::Remove - Remove a package /*{{{*/
152 // ---------------------------------------------------------------------
153 /* Add a remove operation to the sequence list */
154 bool pkgDPkgPM::Remove(PkgIterator Pkg
,bool Purge
)
156 if (Pkg
.end() == true)
160 List
.push_back(Item(Item::Purge
,Pkg
));
162 List
.push_back(Item(Item::Remove
,Pkg
));
166 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
167 // ---------------------------------------------------------------------
168 /* This is part of the helper script communication interface, it sends
169 very complete information down to the other end of the pipe.*/
170 bool pkgDPkgPM::SendV2Pkgs(FILE *F
)
172 fprintf(F
,"VERSION 2\n");
174 /* Write out all of the configuration directives by walking the
175 configuration tree */
176 const Configuration::Item
*Top
= _config
->Tree(0);
179 if (Top
->Value
.empty() == false)
182 QuoteString(Top
->FullTag(),"=\"\n").c_str(),
183 QuoteString(Top
->Value
,"\n").c_str());
192 while (Top
!= 0 && Top
->Next
== 0)
199 // Write out the package actions in order.
200 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
202 if(I
->Pkg
.end() == true)
205 pkgDepCache::StateCache
&S
= Cache
[I
->Pkg
];
207 fprintf(F
,"%s ",I
->Pkg
.Name());
209 if (I
->Pkg
->CurrentVer
== 0)
212 fprintf(F
,"%s ",I
->Pkg
.CurrentVer().VerStr());
214 // Show the compare operator
216 if (S
.InstallVer
!= 0)
219 if (I
->Pkg
->CurrentVer
!= 0)
220 Comp
= S
.InstVerIter(Cache
).CompareVer(I
->Pkg
.CurrentVer());
227 fprintf(F
,"%s ",S
.InstVerIter(Cache
).VerStr());
232 // Show the filename/operation
233 if (I
->Op
== Item::Install
)
236 if (I
->File
[0] != '/')
237 fprintf(F
,"**ERROR**\n");
239 fprintf(F
,"%s\n",I
->File
.c_str());
241 if (I
->Op
== Item::Configure
)
242 fprintf(F
,"**CONFIGURE**\n");
243 if (I
->Op
== Item::Remove
||
244 I
->Op
== Item::Purge
)
245 fprintf(F
,"**REMOVE**\n");
253 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
254 // ---------------------------------------------------------------------
255 /* This looks for a list of scripts to run from the configuration file
256 each one is run and is fed on standard input a list of all .deb files
257 that are due to be installed. */
258 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf
)
260 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
261 if (Opts
== 0 || Opts
->Child
== 0)
265 unsigned int Count
= 1;
266 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
268 if (Opts
->Value
.empty() == true)
271 // Determine the protocol version
272 string OptSec
= Opts
->Value
;
273 string::size_type Pos
;
274 if ((Pos
= OptSec
.find(' ')) == string::npos
|| Pos
== 0)
275 Pos
= OptSec
.length();
276 OptSec
= "DPkg::Tools::Options::" + string(Opts
->Value
.c_str(),Pos
);
278 unsigned int Version
= _config
->FindI(OptSec
+"::Version",1);
282 if (pipe(Pipes
) != 0)
283 return _error
->Errno("pipe","Failed to create IPC pipe to subprocess");
284 SetCloseExec(Pipes
[0],true);
285 SetCloseExec(Pipes
[1],true);
287 // Purified Fork for running the script
288 pid_t Process
= ExecFork();
292 dup2(Pipes
[0],STDIN_FILENO
);
293 SetCloseExec(STDOUT_FILENO
,false);
294 SetCloseExec(STDIN_FILENO
,false);
295 SetCloseExec(STDERR_FILENO
,false);
300 Args
[2] = Opts
->Value
.c_str();
302 execv(Args
[0],(char **)Args
);
306 FILE *F
= fdopen(Pipes
[1],"w");
308 return _error
->Errno("fdopen","Faild to open new FD");
310 // Feed it the filenames.
314 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
316 // Only deal with packages to be installed from .deb
317 if (I
->Op
!= Item::Install
)
321 if (I
->File
[0] != '/')
324 /* Feed the filename of each package that is pending install
326 fprintf(F
,"%s\n",I
->File
.c_str());
335 Die
= !SendV2Pkgs(F
);
339 // Clean up the sub process
340 if (ExecWait(Process
,Opts
->Value
.c_str()) == false)
341 return _error
->Error("Failure running script %s",Opts
->Value
.c_str());
347 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
348 // ---------------------------------------------------------------------
351 void pkgDPkgPM::DoStdin(int master
)
353 unsigned char input_buf
[256] = {0,};
354 ssize_t len
= read(0, input_buf
, sizeof(input_buf
));
356 write(master
, input_buf
, len
);
358 stdin_is_dev_null
= true;
361 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
362 // ---------------------------------------------------------------------
364 * read the terminal pty and write log
366 void pkgDPkgPM::DoTerminalPty(int master
)
368 unsigned char term_buf
[1024] = {0,0, };
370 ssize_t len
=read(master
, term_buf
, sizeof(term_buf
));
371 if(len
== -1 && errno
== EIO
)
373 // this happens when the child is about to exit, we
374 // give it time to actually exit, otherwise we run
381 write(1, term_buf
, len
);
383 fwrite(term_buf
, len
, sizeof(char), term_out
);
386 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
387 // ---------------------------------------------------------------------
390 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd
, char *line
)
392 bool const Debug
= _config
->FindB("Debug::pkgDPkgProgressReporting",false);
393 // the status we output
394 ostringstream status
;
397 std::clog
<< "got from dpkg '" << line
<< "'" << std::endl
;
400 /* dpkg sends strings like this:
401 'status: <pkg>: <pkg qstate>'
402 errors look like this:
403 '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
404 and conffile-prompt like this
405 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
407 Newer versions of dpkg sent also:
408 'processing: install: pkg'
409 'processing: configure: pkg'
410 'processing: remove: pkg'
411 'processing: purge: pkg' - but for apt is it a ignored "unknown" action
412 'processing: trigproc: trigger'
416 // dpkg sends multiline error messages sometimes (see
417 // #374195 for a example. we should support this by
418 // either patching dpkg to not send multiline over the
419 // statusfd or by rewriting the code here to deal with
420 // it. for now we just ignore it and not crash
421 TokSplitString(':', line
, list
, sizeof(list
)/sizeof(list
[0]));
422 if( list
[0] == NULL
|| list
[1] == NULL
|| list
[2] == NULL
)
425 std::clog
<< "ignoring line: not enough ':'" << std::endl
;
428 const char* const pkg
= list
[1];
429 const char* action
= _strstrip(list
[2]);
431 // 'processing' from dpkg looks like
432 // 'processing: action: pkg'
433 if(strncmp(list
[0], "processing", strlen("processing")) == 0)
436 const char* const pkg_or_trigger
= _strstrip(list
[2]);
437 action
= _strstrip( list
[1]);
438 const std::pair
<const char *, const char *> * const iter
=
439 std::find_if(PackageProcessingOpsBegin
,
440 PackageProcessingOpsEnd
,
441 MatchProcessingOp(action
));
442 if(iter
== PackageProcessingOpsEnd
)
445 std::clog
<< "ignoring unknown action: " << action
<< std::endl
;
448 snprintf(s
, sizeof(s
), _(iter
->second
), pkg_or_trigger
);
450 status
<< "pmstatus:" << pkg_or_trigger
451 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
455 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
457 std::clog
<< "send: '" << status
.str() << "'" << endl
;
461 if(strncmp(action
,"error",strlen("error")) == 0)
463 // urgs, sometime has ":" in its error string so that we
464 // end up with the error message split between list[3]
465 // and list[4], e.g. the message:
466 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
468 if( list
[4] != NULL
)
469 list
[3][strlen(list
[3])] = ':';
471 status
<< "pmerror:" << list
[1]
472 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
476 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
478 std::clog
<< "send: '" << status
.str() << "'" << endl
;
480 WriteApportReport(list
[1], list
[3]);
483 else if(strncmp(action
,"conffile",strlen("conffile")) == 0)
485 status
<< "pmconffile:" << list
[1]
486 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
490 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
492 std::clog
<< "send: '" << status
.str() << "'" << endl
;
496 vector
<struct DpkgState
> const &states
= PackageOps
[pkg
];
497 const char *next_action
= NULL
;
498 if(PackageOpsDone
[pkg
] < states
.size())
499 next_action
= states
[PackageOpsDone
[pkg
]].state
;
500 // check if the package moved to the next dpkg state
501 if(next_action
&& (strcmp(action
, next_action
) == 0))
503 // only read the translation if there is actually a next
505 const char *translation
= _(states
[PackageOpsDone
[pkg
]].str
);
507 snprintf(s
, sizeof(s
), translation
, pkg
);
509 // we moved from one dpkg state to a new one, report that
510 PackageOpsDone
[pkg
]++;
512 // build the status str
513 status
<< "pmstatus:" << pkg
514 << ":" << (PackagesDone
/float(PackagesTotal
)*100.0)
518 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
520 std::clog
<< "send: '" << status
.str() << "'" << endl
;
523 std::clog
<< "(parsed from dpkg) pkg: " << pkg
524 << " action: " << action
<< endl
;
527 // DPkgPM::DoDpkgStatusFd /*{{{*/
528 // ---------------------------------------------------------------------
531 void pkgDPkgPM::DoDpkgStatusFd(int statusfd
, int OutStatusFd
)
536 len
=read(statusfd
, &dpkgbuf
[dpkgbuf_pos
], sizeof(dpkgbuf
)-dpkgbuf_pos
);
541 // process line by line if we have a buffer
543 while((q
=(char*)memchr(p
, '\n', dpkgbuf
+dpkgbuf_pos
-p
)) != NULL
)
546 ProcessDpkgStatusLine(OutStatusFd
, p
);
547 p
=q
+1; // continue with next line
550 // now move the unprocessed bits (after the final \n that is now a 0x0)
551 // to the start and update dpkgbuf_pos
552 p
= (char*)memrchr(dpkgbuf
, 0, dpkgbuf_pos
);
556 // we are interessted in the first char *after* 0x0
559 // move the unprocessed tail to the start and update pos
560 memmove(dpkgbuf
, p
, p
-dpkgbuf
);
561 dpkgbuf_pos
= dpkgbuf
+dpkgbuf_pos
-p
;
564 // DPkgPM::WriteHistoryTag /*{{{*/
565 void pkgDPkgPM::WriteHistoryTag(string tag
, string value
)
567 if (value
.size() > 0)
569 // poor mans rstrip(", ")
570 if (value
[value
.size()-2] == ',' && value
[value
.size()-1] == ' ')
571 value
.erase(value
.size() - 2, 2);
572 fprintf(history_out
, "%s: %s\n", tag
.c_str(), value
.c_str());
575 // DPkgPM::OpenLog /*{{{*/
576 bool pkgDPkgPM::OpenLog()
578 string logdir
= _config
->FindDir("Dir::Log");
579 if(not FileExists(logdir
))
580 return _error
->Error(_("Directory '%s' missing"), logdir
.c_str());
584 time_t t
= time(NULL
);
585 struct tm
*tmp
= localtime(&t
);
586 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
589 string logfile_name
= flCombine(logdir
,
590 _config
->Find("Dir::Log::Terminal"));
591 if (!logfile_name
.empty())
593 term_out
= fopen(logfile_name
.c_str(),"a");
594 chmod(logfile_name
.c_str(), 0600);
595 fprintf(term_out
, "\n\nLog started: ");
596 fprintf(term_out
, "%s", timestr
);
597 fprintf(term_out
, "\n");
601 string history_name
= flCombine(logdir
,
602 _config
->Find("Dir::Log::History"));
603 if (!history_name
.empty())
605 history_out
= fopen(history_name
.c_str(),"a");
606 chmod(history_name
.c_str(), 0644);
607 fprintf(history_out
, "\nStart-Date: %s\n", timestr
);
608 string remove
, purge
, install
, upgrade
, downgrade
;
609 for (pkgCache::PkgIterator I
= Cache
.PkgBegin(); I
.end() == false; I
++)
611 if (Cache
[I
].NewInstall())
612 install
+= I
.Name() + string(" (") + Cache
[I
].CandVersion
+ string("), ");
613 else if (Cache
[I
].Upgrade())
614 upgrade
+= I
.Name() + string(" (") + Cache
[I
].CurVersion
+ string(", ") + Cache
[I
].CandVersion
+ string("), ");
615 else if (Cache
[I
].Downgrade())
616 downgrade
+= I
.Name() + string(" (") + Cache
[I
].CurVersion
+ string(", ") + Cache
[I
].CandVersion
+ string("), ");
617 else if (Cache
[I
].Delete())
619 if ((Cache
[I
].iFlags
& pkgDepCache::Purge
) == pkgDepCache::Purge
)
620 purge
+= I
.Name() + string(" (") + Cache
[I
].CurVersion
+ string("), ");
622 remove
+= I
.Name() + string(" (") + Cache
[I
].CurVersion
+ string("), ");
625 WriteHistoryTag("Install", install
);
626 WriteHistoryTag("Upgrade", upgrade
);
627 WriteHistoryTag("Downgrade",downgrade
);
628 WriteHistoryTag("Remove",remove
);
629 WriteHistoryTag("Purge",purge
);
636 // DPkg::CloseLog /*{{{*/
637 bool pkgDPkgPM::CloseLog()
640 time_t t
= time(NULL
);
641 struct tm
*tmp
= localtime(&t
);
642 strftime(timestr
, sizeof(timestr
), "%F %T", tmp
);
646 fprintf(term_out
, "Log ended: ");
647 fprintf(term_out
, "%s", timestr
);
648 fprintf(term_out
, "\n");
655 if (dpkg_error
.size() > 0)
656 fprintf(history_out
, "Error: %s\n", dpkg_error
.c_str());
657 fprintf(history_out
, "End-Date: %s\n", timestr
);
665 // This implements a racy version of pselect for those architectures
666 // that don't have a working implementation.
667 // FIXME: Probably can be removed on Lenny+1
668 static int racy_pselect(int nfds
, fd_set
*readfds
, fd_set
*writefds
,
669 fd_set
*exceptfds
, const struct timespec
*timeout
,
670 const sigset_t
*sigmask
)
676 tv
.tv_sec
= timeout
->tv_sec
;
677 tv
.tv_usec
= timeout
->tv_nsec
/1000;
679 sigprocmask(SIG_SETMASK
, sigmask
, &origmask
);
680 retval
= select(nfds
, readfds
, writefds
, exceptfds
, &tv
);
681 sigprocmask(SIG_SETMASK
, &origmask
, 0);
685 // DPkgPM::Go - Run the sequence /*{{{*/
686 // ---------------------------------------------------------------------
687 /* This globs the operations and calls dpkg
689 * If it is called with "OutStatusFd" set to a valid file descriptor
690 * apt will report the install progress over this fd. It maps the
691 * dpkg states a package goes through to human readable (and i10n-able)
692 * names and calculates a percentage for each step.
694 bool pkgDPkgPM::Go(int OutStatusFd
)
699 sigset_t original_sigmask
;
701 unsigned int const MaxArgs
= _config
->FindI("Dpkg::MaxArgs",8*1024);
702 unsigned int const MaxArgBytes
= _config
->FindI("Dpkg::MaxArgBytes",32*1024);
703 bool const NoTriggers
= _config
->FindB("DPkg::NoTriggers", false);
705 if (RunScripts("DPkg::Pre-Invoke") == false)
708 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
711 // support subpressing of triggers processing for special
712 // cases like d-i that runs the triggers handling manually
713 bool const SmartConf
= (_config
->Find("PackageManager::Configure", "all") != "all");
714 bool const TriggersPending
= _config
->FindB("DPkg::TriggersPending", false);
715 if (_config
->FindB("DPkg::ConfigurePending", SmartConf
) == true)
716 List
.push_back(Item(Item::ConfigurePending
, PkgIterator()));
718 // map the dpkg states to the operations that are performed
719 // (this is sorted in the same way as Item::Ops)
720 static const struct DpkgState DpkgStatesOpMap
[][7] = {
723 {"half-installed", N_("Preparing %s")},
724 {"unpacked", N_("Unpacking %s") },
727 // Configure operation
729 {"unpacked",N_("Preparing to configure %s") },
730 {"half-configured", N_("Configuring %s") },
731 { "installed", N_("Installed %s")},
736 {"half-configured", N_("Preparing for removal of %s")},
737 {"half-installed", N_("Removing %s")},
738 {"config-files", N_("Removed %s")},
743 {"config-files", N_("Preparing to completely remove %s")},
744 {"not-installed", N_("Completely removed %s")},
749 // init the PackageOps map, go over the list of packages that
750 // that will be [installed|configured|removed|purged] and add
751 // them to the PackageOps map (the dpkg states it goes through)
752 // and the PackageOpsTranslations (human readable strings)
753 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();I
++)
755 if((*I
).Pkg
.end() == true)
758 string
const name
= (*I
).Pkg
.Name();
759 PackageOpsDone
[name
] = 0;
760 for(int i
=0; (DpkgStatesOpMap
[(*I
).Op
][i
]).state
!= NULL
; i
++)
762 PackageOps
[name
].push_back(DpkgStatesOpMap
[(*I
).Op
][i
]);
767 stdin_is_dev_null
= false;
772 // this loop is runs once per operation
773 for (vector
<Item
>::const_iterator I
= List
.begin(); I
!= List
.end();)
775 // Do all actions with the same Op in one run
776 vector
<Item
>::const_iterator J
= I
;
777 if (TriggersPending
== true)
778 for (; J
!= List
.end(); J
++)
782 if (J
->Op
!= Item::TriggersPending
)
784 vector
<Item
>::const_iterator T
= J
+ 1;
785 if (T
!= List
.end() && T
->Op
== I
->Op
)
790 for (; J
!= List
.end() && J
->Op
== I
->Op
; J
++)
793 // Generate the argument list
794 const char *Args
[MaxArgs
+ 50];
796 // Now check if we are within the MaxArgs limit
798 // this code below is problematic, because it may happen that
799 // the argument list is split in a way that A depends on B
800 // and they are in the same "--configure A B" run
801 // - with the split they may now be configured in different
803 if (J
- I
> (signed)MaxArgs
)
807 unsigned long Size
= 0;
808 string
const Tmp
= _config
->Find("Dir::Bin::dpkg","dpkg");
809 Args
[n
++] = Tmp
.c_str();
810 Size
+= strlen(Args
[n
-1]);
812 // Stick in any custom dpkg options
813 Configuration::Item
const *Opts
= _config
->Tree("DPkg::Options");
817 for (; Opts
!= 0; Opts
= Opts
->Next
)
819 if (Opts
->Value
.empty() == true)
821 Args
[n
++] = Opts
->Value
.c_str();
822 Size
+= Opts
->Value
.length();
826 char status_fd_buf
[20];
830 Args
[n
++] = "--status-fd";
831 Size
+= strlen(Args
[n
-1]);
832 snprintf(status_fd_buf
,sizeof(status_fd_buf
),"%i", fd
[1]);
833 Args
[n
++] = status_fd_buf
;
834 Size
+= strlen(Args
[n
-1]);
839 Args
[n
++] = "--force-depends";
840 Size
+= strlen(Args
[n
-1]);
841 Args
[n
++] = "--force-remove-essential";
842 Size
+= strlen(Args
[n
-1]);
843 Args
[n
++] = "--remove";
844 Size
+= strlen(Args
[n
-1]);
848 Args
[n
++] = "--force-depends";
849 Size
+= strlen(Args
[n
-1]);
850 Args
[n
++] = "--force-remove-essential";
851 Size
+= strlen(Args
[n
-1]);
852 Args
[n
++] = "--purge";
853 Size
+= strlen(Args
[n
-1]);
856 case Item::Configure
:
857 Args
[n
++] = "--configure";
858 Size
+= strlen(Args
[n
-1]);
861 case Item::ConfigurePending
:
862 Args
[n
++] = "--configure";
863 Size
+= strlen(Args
[n
-1]);
864 Args
[n
++] = "--pending";
865 Size
+= strlen(Args
[n
-1]);
868 case Item::TriggersPending
:
869 Args
[n
++] = "--triggers-only";
870 Size
+= strlen(Args
[n
-1]);
871 Args
[n
++] = "--pending";
872 Size
+= strlen(Args
[n
-1]);
876 Args
[n
++] = "--unpack";
877 Size
+= strlen(Args
[n
-1]);
878 Args
[n
++] = "--auto-deconfigure";
879 Size
+= strlen(Args
[n
-1]);
883 if (NoTriggers
== true && I
->Op
!= Item::TriggersPending
&&
884 I
->Op
!= Item::ConfigurePending
)
886 Args
[n
++] = "--no-triggers";
887 Size
+= strlen(Args
[n
-1]);
890 // Write in the file or package names
891 if (I
->Op
== Item::Install
)
893 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
895 if (I
->File
[0] != '/')
896 return _error
->Error("Internal Error, Pathname to install is not absolute '%s'",I
->File
.c_str());
897 Args
[n
++] = I
->File
.c_str();
898 Size
+= strlen(Args
[n
-1]);
903 for (;I
!= J
&& Size
< MaxArgBytes
; I
++)
905 if((*I
).Pkg
.end() == true)
907 Args
[n
++] = I
->Pkg
.Name();
908 Size
+= strlen(Args
[n
-1]);
914 if (_config
->FindB("Debug::pkgDPkgPM",false) == true)
916 for (unsigned int k
= 0; k
!= n
; k
++)
917 clog
<< Args
[k
] << ' ';
926 /* Mask off sig int/quit. We do this because dpkg also does when
927 it forks scripts. What happens is that when you hit ctrl-c it sends
928 it to all processes in the group. Since dpkg ignores the signal
929 it doesn't die but we do! So we must also ignore it */
930 sighandler_t old_SIGQUIT
= signal(SIGQUIT
,SIG_IGN
);
931 sighandler_t old_SIGINT
= signal(SIGINT
,SIG_IGN
);
933 // ignore SIGHUP as well (debian #463030)
934 sighandler_t old_SIGHUP
= signal(SIGHUP
,SIG_IGN
);
941 // if tcgetattr does not return zero there was a error
942 // and we do not do any pty magic
943 if (tcgetattr(0, &tt
) == 0)
945 ioctl(0, TIOCGWINSZ
, (char *)&win
);
946 if (openpty(&master
, &slave
, NULL
, &tt
, &win
) < 0)
948 const char *s
= _("Can not write log, openpty() "
949 "failed (/dev/pts not mounted?)\n");
950 fprintf(stderr
, "%s",s
);
952 fprintf(term_out
, "%s",s
);
958 rtt
.c_lflag
&= ~ECHO
;
959 // block SIGTTOU during tcsetattr to prevent a hang if
960 // the process is a member of the background process group
961 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
962 sigemptyset(&sigmask
);
963 sigaddset(&sigmask
, SIGTTOU
);
964 sigprocmask(SIG_BLOCK
,&sigmask
, &original_sigmask
);
965 tcsetattr(0, TCSAFLUSH
, &rtt
);
966 sigprocmask(SIG_SETMASK
, &original_sigmask
, 0);
972 _config
->Set("APT::Keep-Fds::",fd
[1]);
973 // send status information that we are about to fork dpkg
974 if(OutStatusFd
> 0) {
975 ostringstream status
;
976 status
<< "pmstatus:dpkg-exec:"
977 << (PackagesDone
/float(PackagesTotal
)*100.0)
978 << ":" << _("Running dpkg")
980 write(OutStatusFd
, status
.str().c_str(), status
.str().size());
987 if(slave
>= 0 && master
>= 0)
990 ioctl(slave
, TIOCSCTTY
, 0);
997 close(fd
[0]); // close the read end of the pipe
999 if (_config
->FindDir("DPkg::Chroot-Directory","/") != "/")
1001 std::cerr
<< "Chrooting into "
1002 << _config
->FindDir("DPkg::Chroot-Directory")
1004 if (chroot(_config
->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
1008 if (chdir(_config
->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
1011 if (_config
->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO
))
1014 if ((Flags
= fcntl(STDIN_FILENO
,F_GETFL
,dummy
)) < 0)
1017 // Discard everything in stdin before forking dpkg
1018 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
| O_NONBLOCK
) < 0)
1021 while (read(STDIN_FILENO
,&dummy
,1) == 1);
1023 if (fcntl(STDIN_FILENO
,F_SETFL
,Flags
& (~(long)O_NONBLOCK
)) < 0)
1027 /* No Job Control Stop Env is a magic dpkg var that prevents it
1028 from using sigstop */
1029 putenv((char *)"DPKG_NO_TSTP=yes");
1030 execvp(Args
[0],(char **)Args
);
1031 cerr
<< "Could not exec dpkg!" << endl
;
1036 if (_config
->FindB("DPkg::UseIoNice", false) == true)
1039 // clear the Keep-Fd again
1040 _config
->Clear("APT::Keep-Fds",fd
[1]);
1045 // we read from dpkg here
1046 int const _dpkgin
= fd
[0];
1047 close(fd
[1]); // close the write end of the pipe
1053 sigemptyset(&sigmask
);
1054 sigprocmask(SIG_BLOCK
,&sigmask
,&original_sigmask
);
1056 // the result of the waitpid call
1059 while ((res
=waitpid(Child
,&Status
, WNOHANG
)) != Child
) {
1061 // FIXME: move this to a function or something, looks ugly here
1062 // error handling, waitpid returned -1
1065 RunScripts("DPkg::Post-Invoke");
1067 // Restore sig int/quit
1068 signal(SIGQUIT
,old_SIGQUIT
);
1069 signal(SIGINT
,old_SIGINT
);
1070 signal(SIGHUP
,old_SIGHUP
);
1071 return _error
->Errno("waitpid","Couldn't wait for subprocess");
1073 // wait for input or output here
1075 if (!stdin_is_dev_null
)
1077 FD_SET(_dpkgin
, &rfds
);
1079 FD_SET(master
, &rfds
);
1082 select_ret
= pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
, NULL
,
1083 &tv
, &original_sigmask
);
1084 if (select_ret
< 0 && (errno
== EINVAL
|| errno
== ENOSYS
))
1085 select_ret
= racy_pselect(max(master
, _dpkgin
)+1, &rfds
, NULL
,
1086 NULL
, &tv
, &original_sigmask
);
1087 if (select_ret
== 0)
1089 else if (select_ret
< 0 && errno
== EINTR
)
1091 else if (select_ret
< 0)
1093 perror("select() returned error");
1097 if(master
>= 0 && FD_ISSET(master
, &rfds
))
1098 DoTerminalPty(master
);
1099 if(master
>= 0 && FD_ISSET(0, &rfds
))
1101 if(FD_ISSET(_dpkgin
, &rfds
))
1102 DoDpkgStatusFd(_dpkgin
, OutStatusFd
);
1106 // Restore sig int/quit
1107 signal(SIGQUIT
,old_SIGQUIT
);
1108 signal(SIGINT
,old_SIGINT
);
1109 signal(SIGHUP
,old_SIGHUP
);
1113 tcsetattr(0, TCSAFLUSH
, &tt
);
1117 // Check for an error code.
1118 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
1120 // if it was set to "keep-dpkg-runing" then we won't return
1121 // here but keep the loop going and just report it as a error
1123 bool const stopOnError
= _config
->FindB("Dpkg::StopOnError",true);
1126 RunScripts("DPkg::Post-Invoke");
1128 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
1129 strprintf(dpkg_error
, "Sub-process %s received a segmentation fault.",Args
[0]);
1130 else if (WIFEXITED(Status
) != 0)
1131 strprintf(dpkg_error
, "Sub-process %s returned an error code (%u)",Args
[0],WEXITSTATUS(Status
));
1133 strprintf(dpkg_error
, "Sub-process %s exited unexpectedly",Args
[0]);
1135 if(dpkg_error
.size() > 0)
1136 _error
->Error(dpkg_error
.c_str());
1147 if (RunScripts("DPkg::Post-Invoke") == false)
1150 Cache
.writeStateFile(NULL
);
1154 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
1155 // ---------------------------------------------------------------------
1157 void pkgDPkgPM::Reset()
1159 List
.erase(List
.begin(),List
.end());
1162 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
1163 // ---------------------------------------------------------------------
1165 void pkgDPkgPM::WriteApportReport(const char *pkgpath
, const char *errormsg
)
1167 string pkgname
, reportfile
, srcpkgname
, pkgver
, arch
;
1168 string::size_type pos
;
1171 if (_config
->FindB("Dpkg::ApportFailureReport",true) == false)
1173 std::clog
<< "configured to not write apport reports" << std::endl
;
1177 // only report the first errors
1178 if(pkgFailures
> _config
->FindI("APT::Apport::MaxReports", 3))
1180 std::clog
<< _("No apport report written because MaxReports is reached already") << std::endl
;
1184 // check if its not a follow up error
1185 const char *needle
= dgettext("dpkg", "dependency problems - leaving unconfigured");
1186 if(strstr(errormsg
, needle
) != NULL
) {
1187 std::clog
<< _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl
;
1191 // do not report disk-full failures
1192 if(strstr(errormsg
, strerror(ENOSPC
)) != NULL
) {
1193 std::clog
<< _("No apport report written because the error message indicates a disk full error") << std::endl
;
1197 // do not report out-of-memory failures
1198 if(strstr(errormsg
, strerror(ENOMEM
)) != NULL
) {
1199 std::clog
<< _("No apport report written because the error message indicates a out of memory error") << std::endl
;
1203 // do not report dpkg I/O errors
1204 // XXX - this message is localized, but this only matches the English version. This is better than nothing.
1205 if(strstr(errormsg
, "short read in buffer_copy (")) {
1206 std::clog
<< _("No apport report written because the error message indicates a dpkg I/O error") << std::endl
;
1210 // get the pkgname and reportfile
1211 pkgname
= flNotDir(pkgpath
);
1212 pos
= pkgname
.find('_');
1213 if(pos
!= string::npos
)
1214 pkgname
= pkgname
.substr(0, pos
);
1216 // find the package versin and source package name
1217 pkgCache::PkgIterator Pkg
= Cache
.FindPkg(pkgname
);
1218 if (Pkg
.end() == true)
1220 pkgCache::VerIterator Ver
= Cache
.GetCandidateVer(Pkg
);
1221 if (Ver
.end() == true)
1223 pkgver
= Ver
.VerStr() == NULL
? "unknown" : Ver
.VerStr();
1224 pkgRecords
Recs(Cache
);
1225 pkgRecords::Parser
&Parse
= Recs
.Lookup(Ver
.FileList());
1226 srcpkgname
= Parse
.SourcePkg();
1227 if(srcpkgname
.empty())
1228 srcpkgname
= pkgname
;
1230 // if the file exists already, we check:
1231 // - if it was reported already (touched by apport).
1232 // If not, we do nothing, otherwise
1233 // we overwrite it. This is the same behaviour as apport
1234 // - if we have a report with the same pkgversion already
1236 reportfile
= flCombine("/var/crash",pkgname
+".0.crash");
1237 if(FileExists(reportfile
))
1242 // check atime/mtime
1243 stat(reportfile
.c_str(), &buf
);
1244 if(buf
.st_mtime
> buf
.st_atime
)
1247 // check if the existing report is the same version
1248 report
= fopen(reportfile
.c_str(),"r");
1249 while(fgets(strbuf
, sizeof(strbuf
), report
) != NULL
)
1251 if(strstr(strbuf
,"Package:") == strbuf
)
1253 char pkgname
[255], version
[255];
1254 if(sscanf(strbuf
, "Package: %s %s", pkgname
, version
) == 2)
1255 if(strcmp(pkgver
.c_str(), version
) == 0)
1265 // now write the report
1266 arch
= _config
->Find("APT::Architecture");
1267 report
= fopen(reportfile
.c_str(),"w");
1270 if(_config
->FindB("DPkgPM::InitialReportOnly",false) == true)
1271 chmod(reportfile
.c_str(), 0);
1273 chmod(reportfile
.c_str(), 0600);
1274 fprintf(report
, "ProblemType: Package\n");
1275 fprintf(report
, "Architecture: %s\n", arch
.c_str());
1276 time_t now
= time(NULL
);
1277 fprintf(report
, "Date: %s" , ctime(&now
));
1278 fprintf(report
, "Package: %s %s\n", pkgname
.c_str(), pkgver
.c_str());
1279 fprintf(report
, "SourcePackage: %s\n", srcpkgname
.c_str());
1280 fprintf(report
, "ErrorMessage:\n %s\n", errormsg
);
1282 // ensure that the log is flushed
1286 // attach terminal log it if we have it
1287 string logfile_name
= _config
->FindFile("Dir::Log::Terminal");
1288 if (!logfile_name
.empty())
1293 fprintf(report
, "DpkgTerminalLog:\n");
1294 log
= fopen(logfile_name
.c_str(),"r");
1297 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1298 fprintf(report
, " %s", buf
);
1304 const char *ops_str
[] = {"Install", "Configure","Remove","Purge"};
1305 fprintf(report
, "AptOrdering:\n");
1306 for (vector
<Item
>::iterator I
= List
.begin(); I
!= List
.end(); I
++)
1307 fprintf(report
, " %s: %s\n", (*I
).Pkg
.Name(), ops_str
[(*I
).Op
]);
1309 // attach dmesg log (to learn about segfaults)
1310 if (FileExists("/bin/dmesg"))
1315 fprintf(report
, "Dmesg:\n");
1316 log
= popen("/bin/dmesg","r");
1319 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1320 fprintf(report
, " %s", buf
);
1325 // attach df -l log (to learn about filesystem status)
1326 if (FileExists("/bin/df"))
1331 fprintf(report
, "Df:\n");
1332 log
= popen("/bin/df -l","r");
1335 while( fgets(buf
, sizeof(buf
), log
) != NULL
)
1336 fprintf(report
, " %s", buf
);