]> git.saurik.com Git - apt.git/blob - apt-pkg/deb/dpkgpm.cc
LP: #263089
[apt.git] / apt-pkg / deb / dpkgpm.cc
1 // -*- mode: cpp; mode: fold -*-
2 // Description /*{{{*/
3 // $Id: dpkgpm.cc,v 1.28 2004/01/27 02:25:01 mdz Exp $
4 /* ######################################################################
5
6 DPKG Package Manager - Provide an interface to dpkg
7
8 ##################################################################### */
9 /*}}}*/
10 // Includes /*{{{*/
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>
17 #include <apti18n.h>
18 #include <apt-pkg/fileutl.h>
19
20 #include <unistd.h>
21 #include <stdlib.h>
22 #include <fcntl.h>
23 #include <sys/select.h>
24 #include <sys/types.h>
25 #include <sys/wait.h>
26 #include <signal.h>
27 #include <errno.h>
28 #include <string.h>
29 #include <stdio.h>
30 #include <string.h>
31 #include <algorithm>
32 #include <sstream>
33 #include <map>
34
35 #include <termios.h>
36 #include <unistd.h>
37 #include <sys/ioctl.h>
38 #include <pty.h>
39
40 #include <config.h>
41 #include <apti18n.h>
42 /*}}}*/
43
44 using namespace std;
45
46 namespace
47 {
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("trigproc", N_("Running post-installation trigger %s"))
55 };
56
57 const std::pair<const char *, const char *> * const PackageProcessingOpsBegin = PackageProcessingOps;
58 const std::pair<const char *, const char *> * const PackageProcessingOpsEnd = PackageProcessingOps + sizeof(PackageProcessingOps) / sizeof(PackageProcessingOps[0]);
59
60 // Predicate to test whether an entry in the PackageProcessingOps
61 // array matches a string.
62 class MatchProcessingOp
63 {
64 const char *target;
65
66 public:
67 MatchProcessingOp(const char *the_target)
68 : target(the_target)
69 {
70 }
71
72 bool operator()(const std::pair<const char *, const char *> &pair) const
73 {
74 return strcmp(pair.first, target) == 0;
75 }
76 };
77 }
78
79 // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
80 // ---------------------------------------------------------------------
81 /* */
82 pkgDPkgPM::pkgDPkgPM(pkgDepCache *Cache)
83 : pkgPackageManager(Cache), dpkgbuf_pos(0),
84 term_out(NULL), PackagesDone(0), PackagesTotal(0), pkgFailures(0)
85 {
86 }
87 /*}}}*/
88 // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
89 // ---------------------------------------------------------------------
90 /* */
91 pkgDPkgPM::~pkgDPkgPM()
92 {
93 }
94 /*}}}*/
95 // DPkgPM::Install - Install a package /*{{{*/
96 // ---------------------------------------------------------------------
97 /* Add an install operation to the sequence list */
98 bool pkgDPkgPM::Install(PkgIterator Pkg,string File)
99 {
100 if (File.empty() == true || Pkg.end() == true)
101 return _error->Error("Internal Error, No file name for %s",Pkg.Name());
102
103 List.push_back(Item(Item::Install,Pkg,File));
104 return true;
105 }
106 /*}}}*/
107 // DPkgPM::Configure - Configure a package /*{{{*/
108 // ---------------------------------------------------------------------
109 /* Add a configure operation to the sequence list */
110 bool pkgDPkgPM::Configure(PkgIterator Pkg)
111 {
112 if (Pkg.end() == true)
113 return false;
114
115 List.push_back(Item(Item::Configure,Pkg));
116 return true;
117 }
118 /*}}}*/
119 // DPkgPM::Remove - Remove a package /*{{{*/
120 // ---------------------------------------------------------------------
121 /* Add a remove operation to the sequence list */
122 bool pkgDPkgPM::Remove(PkgIterator Pkg,bool Purge)
123 {
124 if (Pkg.end() == true)
125 return false;
126
127 if (Purge == true)
128 List.push_back(Item(Item::Purge,Pkg));
129 else
130 List.push_back(Item(Item::Remove,Pkg));
131 return true;
132 }
133 /*}}}*/
134 // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
135 // ---------------------------------------------------------------------
136 /* This is part of the helper script communication interface, it sends
137 very complete information down to the other end of the pipe.*/
138 bool pkgDPkgPM::SendV2Pkgs(FILE *F)
139 {
140 fprintf(F,"VERSION 2\n");
141
142 /* Write out all of the configuration directives by walking the
143 configuration tree */
144 const Configuration::Item *Top = _config->Tree(0);
145 for (; Top != 0;)
146 {
147 if (Top->Value.empty() == false)
148 {
149 fprintf(F,"%s=%s\n",
150 QuoteString(Top->FullTag(),"=\"\n").c_str(),
151 QuoteString(Top->Value,"\n").c_str());
152 }
153
154 if (Top->Child != 0)
155 {
156 Top = Top->Child;
157 continue;
158 }
159
160 while (Top != 0 && Top->Next == 0)
161 Top = Top->Parent;
162 if (Top != 0)
163 Top = Top->Next;
164 }
165 fprintf(F,"\n");
166
167 // Write out the package actions in order.
168 for (vector<Item>::iterator I = List.begin(); I != List.end(); I++)
169 {
170 pkgDepCache::StateCache &S = Cache[I->Pkg];
171
172 fprintf(F,"%s ",I->Pkg.Name());
173 // Current version
174 if (I->Pkg->CurrentVer == 0)
175 fprintf(F,"- ");
176 else
177 fprintf(F,"%s ",I->Pkg.CurrentVer().VerStr());
178
179 // Show the compare operator
180 // Target version
181 if (S.InstallVer != 0)
182 {
183 int Comp = 2;
184 if (I->Pkg->CurrentVer != 0)
185 Comp = S.InstVerIter(Cache).CompareVer(I->Pkg.CurrentVer());
186 if (Comp < 0)
187 fprintf(F,"> ");
188 if (Comp == 0)
189 fprintf(F,"= ");
190 if (Comp > 0)
191 fprintf(F,"< ");
192 fprintf(F,"%s ",S.InstVerIter(Cache).VerStr());
193 }
194 else
195 fprintf(F,"> - ");
196
197 // Show the filename/operation
198 if (I->Op == Item::Install)
199 {
200 // No errors here..
201 if (I->File[0] != '/')
202 fprintf(F,"**ERROR**\n");
203 else
204 fprintf(F,"%s\n",I->File.c_str());
205 }
206 if (I->Op == Item::Configure)
207 fprintf(F,"**CONFIGURE**\n");
208 if (I->Op == Item::Remove ||
209 I->Op == Item::Purge)
210 fprintf(F,"**REMOVE**\n");
211
212 if (ferror(F) != 0)
213 return false;
214 }
215 return true;
216 }
217 /*}}}*/
218 // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
219 // ---------------------------------------------------------------------
220 /* This looks for a list of scripts to run from the configuration file
221 each one is run and is fed on standard input a list of all .deb files
222 that are due to be installed. */
223 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf)
224 {
225 Configuration::Item const *Opts = _config->Tree(Cnf);
226 if (Opts == 0 || Opts->Child == 0)
227 return true;
228 Opts = Opts->Child;
229
230 unsigned int Count = 1;
231 for (; Opts != 0; Opts = Opts->Next, Count++)
232 {
233 if (Opts->Value.empty() == true)
234 continue;
235
236 // Determine the protocol version
237 string OptSec = Opts->Value;
238 string::size_type Pos;
239 if ((Pos = OptSec.find(' ')) == string::npos || Pos == 0)
240 Pos = OptSec.length();
241 OptSec = "DPkg::Tools::Options::" + string(Opts->Value.c_str(),Pos);
242
243 unsigned int Version = _config->FindI(OptSec+"::Version",1);
244
245 // Create the pipes
246 int Pipes[2];
247 if (pipe(Pipes) != 0)
248 return _error->Errno("pipe","Failed to create IPC pipe to subprocess");
249 SetCloseExec(Pipes[0],true);
250 SetCloseExec(Pipes[1],true);
251
252 // Purified Fork for running the script
253 pid_t Process = ExecFork();
254 if (Process == 0)
255 {
256 // Setup the FDs
257 dup2(Pipes[0],STDIN_FILENO);
258 SetCloseExec(STDOUT_FILENO,false);
259 SetCloseExec(STDIN_FILENO,false);
260 SetCloseExec(STDERR_FILENO,false);
261
262 const char *Args[4];
263 Args[0] = "/bin/sh";
264 Args[1] = "-c";
265 Args[2] = Opts->Value.c_str();
266 Args[3] = 0;
267 execv(Args[0],(char **)Args);
268 _exit(100);
269 }
270 close(Pipes[0]);
271 FILE *F = fdopen(Pipes[1],"w");
272 if (F == 0)
273 return _error->Errno("fdopen","Faild to open new FD");
274
275 // Feed it the filenames.
276 bool Die = false;
277 if (Version <= 1)
278 {
279 for (vector<Item>::iterator I = List.begin(); I != List.end(); I++)
280 {
281 // Only deal with packages to be installed from .deb
282 if (I->Op != Item::Install)
283 continue;
284
285 // No errors here..
286 if (I->File[0] != '/')
287 continue;
288
289 /* Feed the filename of each package that is pending install
290 into the pipe. */
291 fprintf(F,"%s\n",I->File.c_str());
292 if (ferror(F) != 0)
293 {
294 Die = true;
295 break;
296 }
297 }
298 }
299 else
300 Die = !SendV2Pkgs(F);
301
302 fclose(F);
303
304 // Clean up the sub process
305 if (ExecWait(Process,Opts->Value.c_str()) == false)
306 return _error->Error("Failure running script %s",Opts->Value.c_str());
307 }
308
309 return true;
310 }
311 /*}}}*/
312 // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
313 // ---------------------------------------------------------------------
314 /*
315 */
316 void pkgDPkgPM::DoStdin(int master)
317 {
318 unsigned char input_buf[256] = {0,};
319 ssize_t len = read(0, input_buf, sizeof(input_buf));
320 if (len)
321 write(master, input_buf, len);
322 else
323 stdin_is_dev_null = true;
324 }
325 /*}}}*/
326 // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
327 // ---------------------------------------------------------------------
328 /*
329 * read the terminal pty and write log
330 */
331 void pkgDPkgPM::DoTerminalPty(int master)
332 {
333 unsigned char term_buf[1024] = {0,0, };
334
335 ssize_t len=read(master, term_buf, sizeof(term_buf));
336 if(len == -1 && errno == EIO)
337 {
338 // this happens when the child is about to exit, we
339 // give it time to actually exit, otherwise we run
340 // into a race
341 usleep(500000);
342 return;
343 }
344 if(len <= 0)
345 return;
346 write(1, term_buf, len);
347 if(term_out)
348 fwrite(term_buf, len, sizeof(char), term_out);
349 }
350 /*}}}*/
351 // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
352 // ---------------------------------------------------------------------
353 /*
354 */
355 void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd, char *line)
356 {
357 // the status we output
358 ostringstream status;
359
360 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
361 std::clog << "got from dpkg '" << line << "'" << std::endl;
362
363
364 /* dpkg sends strings like this:
365 'status: <pkg>: <pkg qstate>'
366 errors look like this:
367 '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
368 and conffile-prompt like this
369 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
370
371 Newer versions of dpkg sent also:
372 'processing: install: pkg'
373 'processing: configure: pkg'
374 'processing: remove: pkg'
375 'processing: trigproc: trigger'
376
377 */
378 char* list[6];
379 // dpkg sends multiline error messages sometimes (see
380 // #374195 for a example. we should support this by
381 // either patching dpkg to not send multiline over the
382 // statusfd or by rewriting the code here to deal with
383 // it. for now we just ignore it and not crash
384 TokSplitString(':', line, list, sizeof(list)/sizeof(list[0]));
385 if( list[0] == NULL || list[1] == NULL || list[2] == NULL)
386 {
387 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
388 std::clog << "ignoring line: not enough ':'" << std::endl;
389 return;
390 }
391 char *pkg = list[1];
392 char *action = _strstrip(list[2]);
393
394 // 'processing' from dpkg looks like
395 // 'processing: action: pkg'
396 if(strncmp(list[0], "processing", strlen("processing")) == 0)
397 {
398 char s[200];
399 char *pkg_or_trigger = _strstrip(list[2]);
400 action =_strstrip( list[1]);
401 const std::pair<const char *, const char *> * const iter =
402 std::find_if(PackageProcessingOpsBegin,
403 PackageProcessingOpsEnd,
404 MatchProcessingOp(action));
405 if(iter == PackageProcessingOpsEnd)
406 {
407 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
408 std::clog << "ignoring unknwon action: " << action << std::endl;
409 return;
410 }
411 snprintf(s, sizeof(s), _(iter->second), pkg_or_trigger);
412
413 status << "pmstatus:" << pkg_or_trigger
414 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
415 << ":" << s
416 << endl;
417 if(OutStatusFd > 0)
418 write(OutStatusFd, status.str().c_str(), status.str().size());
419 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
420 std::clog << "send: '" << status.str() << "'" << endl;
421 return;
422 }
423
424 if(strncmp(action,"error",strlen("error")) == 0)
425 {
426 // urgs, sometime has ":" in its error string so that we
427 // end up with the error message split between list[3]
428 // and list[4], e.g. the message:
429 // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
430 // concat them again
431 if( list[4] != NULL )
432 list[3][strlen(list[3])] = ':';
433
434 status << "pmerror:" << list[1]
435 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
436 << ":" << list[3]
437 << endl;
438 if(OutStatusFd > 0)
439 write(OutStatusFd, status.str().c_str(), status.str().size());
440 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
441 std::clog << "send: '" << status.str() << "'" << endl;
442 pkgFailures++;
443 WriteApportReport(list[1], list[3]);
444 return;
445 }
446 if(strncmp(action,"conffile",strlen("conffile")) == 0)
447 {
448 status << "pmconffile:" << list[1]
449 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
450 << ":" << list[3]
451 << endl;
452 if(OutStatusFd > 0)
453 write(OutStatusFd, status.str().c_str(), status.str().size());
454 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
455 std::clog << "send: '" << status.str() << "'" << endl;
456 return;
457 }
458
459 vector<struct DpkgState> &states = PackageOps[pkg];
460 const char *next_action = NULL;
461 if(PackageOpsDone[pkg] < states.size())
462 next_action = states[PackageOpsDone[pkg]].state;
463 // check if the package moved to the next dpkg state
464 if(next_action && (strcmp(action, next_action) == 0))
465 {
466 // only read the translation if there is actually a next
467 // action
468 const char *translation = _(states[PackageOpsDone[pkg]].str);
469 char s[200];
470 snprintf(s, sizeof(s), translation, pkg);
471
472 // we moved from one dpkg state to a new one, report that
473 PackageOpsDone[pkg]++;
474 PackagesDone++;
475 // build the status str
476 status << "pmstatus:" << pkg
477 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
478 << ":" << s
479 << endl;
480 if(OutStatusFd > 0)
481 write(OutStatusFd, status.str().c_str(), status.str().size());
482 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
483 std::clog << "send: '" << status.str() << "'" << endl;
484 }
485 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
486 std::clog << "(parsed from dpkg) pkg: " << pkg
487 << " action: " << action << endl;
488 }
489
490 // DPkgPM::DoDpkgStatusFd /*{{{*/
491 // ---------------------------------------------------------------------
492 /*
493 */
494 void pkgDPkgPM::DoDpkgStatusFd(int statusfd, int OutStatusFd)
495 {
496 char *p, *q;
497 int len;
498
499 len=read(statusfd, &dpkgbuf[dpkgbuf_pos], sizeof(dpkgbuf)-dpkgbuf_pos);
500 dpkgbuf_pos += len;
501 if(len <= 0)
502 return;
503
504 // process line by line if we have a buffer
505 p = q = dpkgbuf;
506 while((q=(char*)memchr(p, '\n', dpkgbuf+dpkgbuf_pos-p)) != NULL)
507 {
508 *q = 0;
509 ProcessDpkgStatusLine(OutStatusFd, p);
510 p=q+1; // continue with next line
511 }
512
513 // now move the unprocessed bits (after the final \n that is now a 0x0)
514 // to the start and update dpkgbuf_pos
515 p = (char*)memrchr(dpkgbuf, 0, dpkgbuf_pos);
516 if(p == NULL)
517 return;
518
519 // we are interessted in the first char *after* 0x0
520 p++;
521
522 // move the unprocessed tail to the start and update pos
523 memmove(dpkgbuf, p, p-dpkgbuf);
524 dpkgbuf_pos = dpkgbuf+dpkgbuf_pos-p;
525 }
526 /*}}}*/
527
528 bool pkgDPkgPM::OpenLog()
529 {
530 string logdir = _config->FindDir("Dir::Log");
531 if(not FileExists(logdir))
532 return _error->Error(_("Directory '%s' missing"), logdir.c_str());
533 string logfile_name = flCombine(logdir,
534 _config->Find("Dir::Log::Terminal"));
535 if (!logfile_name.empty())
536 {
537 term_out = fopen(logfile_name.c_str(),"a");
538 chmod(logfile_name.c_str(), 0600);
539 // output current time
540 char outstr[200];
541 time_t t = time(NULL);
542 struct tm *tmp = localtime(&t);
543 strftime(outstr, sizeof(outstr), "%F %T", tmp);
544 fprintf(term_out, "\nLog started: ");
545 fprintf(term_out, "%s", outstr);
546 fprintf(term_out, "\n");
547 }
548 return true;
549 }
550
551 bool pkgDPkgPM::CloseLog()
552 {
553 if(term_out)
554 {
555 char outstr[200];
556 time_t t = time(NULL);
557 struct tm *tmp = localtime(&t);
558 strftime(outstr, sizeof(outstr), "%F %T", tmp);
559 fprintf(term_out, "Log ended: ");
560 fprintf(term_out, "%s", outstr);
561 fprintf(term_out, "\n");
562 fclose(term_out);
563 }
564 term_out = NULL;
565 return true;
566 }
567
568 /*{{{*/
569 // This implements a racy version of pselect for those architectures
570 // that don't have a working implementation.
571 // FIXME: Probably can be removed on Lenny+1
572 static int racy_pselect(int nfds, fd_set *readfds, fd_set *writefds,
573 fd_set *exceptfds, const struct timespec *timeout,
574 const sigset_t *sigmask)
575 {
576 sigset_t origmask;
577 struct timeval tv;
578 int retval;
579
580 tv.tv_sec = timeout->tv_sec;
581 tv.tv_usec = timeout->tv_nsec/1000;
582
583 sigprocmask(SIG_SETMASK, sigmask, &origmask);
584 retval = select(nfds, readfds, writefds, exceptfds, &tv);
585 sigprocmask(SIG_SETMASK, &origmask, 0);
586 return retval;
587 }
588 /*}}}*/
589
590 // DPkgPM::Go - Run the sequence /*{{{*/
591 // ---------------------------------------------------------------------
592 /* This globs the operations and calls dpkg
593 *
594 * If it is called with "OutStatusFd" set to a valid file descriptor
595 * apt will report the install progress over this fd. It maps the
596 * dpkg states a package goes through to human readable (and i10n-able)
597 * names and calculates a percentage for each step.
598 */
599 bool pkgDPkgPM::Go(int OutStatusFd)
600 {
601 fd_set rfds;
602 struct timespec tv;
603 sigset_t sigmask;
604 sigset_t original_sigmask;
605
606 unsigned int MaxArgs = _config->FindI("Dpkg::MaxArgs",8*1024);
607 unsigned int MaxArgBytes = _config->FindI("Dpkg::MaxArgBytes",32*1024);
608 bool NoTriggers = _config->FindB("DPkg::NoTriggers",false);
609
610 if (RunScripts("DPkg::Pre-Invoke") == false)
611 return false;
612
613 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
614 return false;
615
616 // map the dpkg states to the operations that are performed
617 // (this is sorted in the same way as Item::Ops)
618 static const struct DpkgState DpkgStatesOpMap[][7] = {
619 // Install operation
620 {
621 {"half-installed", N_("Preparing %s")},
622 {"unpacked", N_("Unpacking %s") },
623 {NULL, NULL}
624 },
625 // Configure operation
626 {
627 {"unpacked",N_("Preparing to configure %s") },
628 {"half-configured", N_("Configuring %s") },
629 #if 0
630 {"triggers-awaited", N_("Processing triggers for %s") },
631 {"triggers-pending", N_("Processing triggers for %s") },
632 #endif
633 { "installed", N_("Installed %s")},
634 {NULL, NULL}
635 },
636 // Remove operation
637 {
638 {"half-configured", N_("Preparing for removal of %s")},
639 #if 0
640 {"triggers-awaited", N_("Preparing for removal of %s")},
641 {"triggers-pending", N_("Preparing for removal of %s")},
642 #endif
643 {"half-installed", N_("Removing %s")},
644 {"config-files", N_("Removed %s")},
645 {NULL, NULL}
646 },
647 // Purge operation
648 {
649 {"config-files", N_("Preparing to completely remove %s")},
650 {"not-installed", N_("Completely removed %s")},
651 {NULL, NULL}
652 },
653 };
654
655 // init the PackageOps map, go over the list of packages that
656 // that will be [installed|configured|removed|purged] and add
657 // them to the PackageOps map (the dpkg states it goes through)
658 // and the PackageOpsTranslations (human readable strings)
659 for (vector<Item>::iterator I = List.begin(); I != List.end();I++)
660 {
661 string name = (*I).Pkg.Name();
662 PackageOpsDone[name] = 0;
663 for(int i=0; (DpkgStatesOpMap[(*I).Op][i]).state != NULL; i++)
664 {
665 PackageOps[name].push_back(DpkgStatesOpMap[(*I).Op][i]);
666 PackagesTotal++;
667 }
668 }
669
670 stdin_is_dev_null = false;
671
672 // create log
673 OpenLog();
674
675 // this loop is runs once per operation
676 for (vector<Item>::iterator I = List.begin(); I != List.end();)
677 {
678 vector<Item>::iterator J = I;
679 for (; J != List.end() && J->Op == I->Op; J++);
680
681 // Generate the argument list
682 const char *Args[MaxArgs + 50];
683 if (J - I > (signed)MaxArgs)
684 J = I + MaxArgs;
685
686 unsigned int n = 0;
687 unsigned long Size = 0;
688 string Tmp = _config->Find("Dir::Bin::dpkg","dpkg");
689 Args[n++] = Tmp.c_str();
690 Size += strlen(Args[n-1]);
691
692 // Stick in any custom dpkg options
693 Configuration::Item const *Opts = _config->Tree("DPkg::Options");
694 if (Opts != 0)
695 {
696 Opts = Opts->Child;
697 for (; Opts != 0; Opts = Opts->Next)
698 {
699 if (Opts->Value.empty() == true)
700 continue;
701 Args[n++] = Opts->Value.c_str();
702 Size += Opts->Value.length();
703 }
704 }
705
706 char status_fd_buf[20];
707 int fd[2];
708 pipe(fd);
709
710 Args[n++] = "--status-fd";
711 Size += strlen(Args[n-1]);
712 snprintf(status_fd_buf,sizeof(status_fd_buf),"%i", fd[1]);
713 Args[n++] = status_fd_buf;
714 Size += strlen(Args[n-1]);
715
716 switch (I->Op)
717 {
718 case Item::Remove:
719 Args[n++] = "--force-depends";
720 Size += strlen(Args[n-1]);
721 Args[n++] = "--force-remove-essential";
722 Size += strlen(Args[n-1]);
723 Args[n++] = "--remove";
724 Size += strlen(Args[n-1]);
725 break;
726
727 case Item::Purge:
728 Args[n++] = "--force-depends";
729 Size += strlen(Args[n-1]);
730 Args[n++] = "--force-remove-essential";
731 Size += strlen(Args[n-1]);
732 Args[n++] = "--purge";
733 Size += strlen(Args[n-1]);
734 break;
735
736 case Item::Configure:
737 Args[n++] = "--configure";
738 if (NoTriggers)
739 Args[n++] = "--no-triggers";
740 Size += strlen(Args[n-1]);
741 break;
742
743 case Item::Install:
744 Args[n++] = "--unpack";
745 Size += strlen(Args[n-1]);
746 Args[n++] = "--auto-deconfigure";
747 Size += strlen(Args[n-1]);
748 break;
749 }
750
751 // Write in the file or package names
752 if (I->Op == Item::Install)
753 {
754 for (;I != J && Size < MaxArgBytes; I++)
755 {
756 if (I->File[0] != '/')
757 return _error->Error("Internal Error, Pathname to install is not absolute '%s'",I->File.c_str());
758 Args[n++] = I->File.c_str();
759 Size += strlen(Args[n-1]);
760 }
761 }
762 else
763 {
764 for (;I != J && Size < MaxArgBytes; I++)
765 {
766 Args[n++] = I->Pkg.Name();
767 Size += strlen(Args[n-1]);
768 }
769 }
770 Args[n] = 0;
771 J = I;
772
773 if (_config->FindB("Debug::pkgDPkgPM",false) == true)
774 {
775 for (unsigned int k = 0; k != n; k++)
776 clog << Args[k] << ' ';
777 clog << endl;
778 continue;
779 }
780
781 cout << flush;
782 clog << flush;
783 cerr << flush;
784
785 /* Mask off sig int/quit. We do this because dpkg also does when
786 it forks scripts. What happens is that when you hit ctrl-c it sends
787 it to all processes in the group. Since dpkg ignores the signal
788 it doesn't die but we do! So we must also ignore it */
789 sighandler_t old_SIGQUIT = signal(SIGQUIT,SIG_IGN);
790 sighandler_t old_SIGINT = signal(SIGINT,SIG_IGN);
791
792 // ignore SIGHUP as well (debian #463030)
793 sighandler_t old_SIGHUP = signal(SIGHUP,SIG_IGN);
794
795 struct termios tt;
796 struct termios tt_out;
797 struct winsize win;
798 int master;
799 int slave;
800
801 // FIXME: setup sensible signal handling (*ick*)
802 tcgetattr(0, &tt);
803 tcgetattr(1, &tt_out);
804 ioctl(0, TIOCGWINSZ, (char *)&win);
805 if (openpty(&master, &slave, NULL, &tt_out, &win) < 0)
806 {
807 const char *s = _("Can not write log, openpty() "
808 "failed (/dev/pts not mounted?)\n");
809 fprintf(stderr, "%s",s);
810 fprintf(term_out, "%s",s);
811 master = slave = -1;
812 } else {
813 struct termios rtt;
814 rtt = tt;
815 cfmakeraw(&rtt);
816 rtt.c_lflag &= ~ECHO;
817 // block SIGTTOU during tcsetattr to prevent a hang if
818 // the process is a member of the background process group
819 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
820 sigemptyset(&sigmask);
821 sigaddset(&sigmask, SIGTTOU);
822 sigprocmask(SIG_BLOCK,&sigmask, &original_sigmask);
823 tcsetattr(0, TCSAFLUSH, &rtt);
824 sigprocmask(SIG_SETMASK, &original_sigmask, 0);
825 }
826
827 // Fork dpkg
828 pid_t Child;
829 _config->Set("APT::Keep-Fds::",fd[1]);
830 Child = ExecFork();
831
832 // This is the child
833 if (Child == 0)
834 {
835 if(slave >= 0 && master >= 0)
836 {
837 setsid();
838 ioctl(slave, TIOCSCTTY, 0);
839 close(master);
840 dup2(slave, 0);
841 dup2(slave, 1);
842 dup2(slave, 2);
843 close(slave);
844 }
845 close(fd[0]); // close the read end of the pipe
846
847 if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
848 _exit(100);
849
850 if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
851 {
852 int Flags,dummy;
853 if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
854 _exit(100);
855
856 // Discard everything in stdin before forking dpkg
857 if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
858 _exit(100);
859
860 while (read(STDIN_FILENO,&dummy,1) == 1);
861
862 if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
863 _exit(100);
864 }
865
866
867 /* No Job Control Stop Env is a magic dpkg var that prevents it
868 from using sigstop */
869 putenv((char *)"DPKG_NO_TSTP=yes");
870 execvp(Args[0],(char **)Args);
871 cerr << "Could not exec dpkg!" << endl;
872 _exit(100);
873 }
874
875 // clear the Keep-Fd again
876 _config->Clear("APT::Keep-Fds",fd[1]);
877
878 // Wait for dpkg
879 int Status = 0;
880
881 // we read from dpkg here
882 int _dpkgin = fd[0];
883 close(fd[1]); // close the write end of the pipe
884
885 // the result of the waitpid call
886 int res;
887 if(slave > 0)
888 close(slave);
889
890 // setups fds
891 sigemptyset(&sigmask);
892 sigprocmask(SIG_BLOCK,&sigmask,&original_sigmask);
893
894 int select_ret;
895 while ((res=waitpid(Child,&Status, WNOHANG)) != Child) {
896 if(res < 0) {
897 // FIXME: move this to a function or something, looks ugly here
898 // error handling, waitpid returned -1
899 if (errno == EINTR)
900 continue;
901 RunScripts("DPkg::Post-Invoke");
902
903 // Restore sig int/quit
904 signal(SIGQUIT,old_SIGQUIT);
905 signal(SIGINT,old_SIGINT);
906 signal(SIGHUP,old_SIGHUP);
907 return _error->Errno("waitpid","Couldn't wait for subprocess");
908 }
909 // wait for input or output here
910 FD_ZERO(&rfds);
911 if (!stdin_is_dev_null)
912 FD_SET(0, &rfds);
913 FD_SET(_dpkgin, &rfds);
914 if(master >= 0)
915 FD_SET(master, &rfds);
916 tv.tv_sec = 1;
917 tv.tv_nsec = 0;
918 select_ret = pselect(max(master, _dpkgin)+1, &rfds, NULL, NULL,
919 &tv, &original_sigmask);
920 if (select_ret < 0 && (errno == EINVAL || errno == ENOSYS))
921 select_ret = racy_pselect(max(master, _dpkgin)+1, &rfds, NULL,
922 NULL, &tv, &original_sigmask);
923 if (select_ret == 0)
924 continue;
925 else if (select_ret < 0 && errno == EINTR)
926 continue;
927 else if (select_ret < 0)
928 {
929 perror("select() returned error");
930 continue;
931 }
932
933 if(master >= 0 && FD_ISSET(master, &rfds))
934 DoTerminalPty(master);
935 if(master >= 0 && FD_ISSET(0, &rfds))
936 DoStdin(master);
937 if(FD_ISSET(_dpkgin, &rfds))
938 DoDpkgStatusFd(_dpkgin, OutStatusFd);
939 }
940 close(_dpkgin);
941
942 // Restore sig int/quit
943 signal(SIGQUIT,old_SIGQUIT);
944 signal(SIGINT,old_SIGINT);
945 signal(SIGHUP,old_SIGHUP);
946
947 if(master >= 0)
948 {
949 tcsetattr(0, TCSAFLUSH, &tt);
950 close(master);
951 }
952
953 // Check for an error code.
954 if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
955 {
956 // if it was set to "keep-dpkg-runing" then we won't return
957 // here but keep the loop going and just report it as a error
958 // for later
959 bool stopOnError = _config->FindB("Dpkg::StopOnError",true);
960
961 if(stopOnError)
962 RunScripts("DPkg::Post-Invoke");
963
964 if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
965 _error->Error("Sub-process %s received a segmentation fault.",Args[0]);
966 else if (WIFEXITED(Status) != 0)
967 _error->Error("Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
968 else
969 _error->Error("Sub-process %s exited unexpectedly",Args[0]);
970
971 if(stopOnError)
972 {
973 CloseLog();
974 return false;
975 }
976 }
977 }
978 CloseLog();
979
980 if (RunScripts("DPkg::Post-Invoke") == false)
981 return false;
982
983 Cache.writeStateFile(NULL);
984 return true;
985 }
986 /*}}}*/
987 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
988 // ---------------------------------------------------------------------
989 /* */
990 void pkgDPkgPM::Reset()
991 {
992 List.erase(List.begin(),List.end());
993 }
994 /*}}}*/
995 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
996 // ---------------------------------------------------------------------
997 /* */
998 void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
999 {
1000 string pkgname, reportfile, srcpkgname, pkgver, arch;
1001 string::size_type pos;
1002 FILE *report;
1003
1004 if (_config->FindB("Dpkg::ApportFailureReport",true) == false)
1005 {
1006 std::clog << "configured to not write apport reports" << std::endl;
1007 return;
1008 }
1009
1010 // only report the first errors
1011 if(pkgFailures > _config->FindI("APT::Apport::MaxReports", 3))
1012 {
1013 std::clog << _("No apport report written because MaxReports is reached already") << std::endl;
1014 return;
1015 }
1016
1017 // check if its not a follow up error
1018 const char *needle = dgettext("dpkg", "dependency problems - leaving unconfigured");
1019 if(strstr(errormsg, needle) != NULL) {
1020 std::clog << _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl;
1021 return;
1022 }
1023
1024 // do not report disk-full failures
1025 if(strstr(errormsg, strerror(ENOSPC)) != NULL) {
1026 std::clog << _("No apport report written because the error message indicates a disk full error") << std::endl;
1027 return;
1028 }
1029
1030 // do not report out-of-memory failures
1031 if(strstr(errormsg, strerror(ENOMEM)) != NULL) {
1032 std::clog << _("No apport report written because the error message indicates a out of memory error") << std::endl;
1033 return;
1034 }
1035
1036 // get the pkgname and reportfile
1037 pkgname = flNotDir(pkgpath);
1038 pos = pkgname.find('_');
1039 if(pos != string::npos)
1040 pkgname = pkgname.substr(0, pos);
1041
1042 // find the package versin and source package name
1043 pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
1044 if (Pkg.end() == true)
1045 return;
1046 pkgCache::VerIterator Ver = Cache.GetCandidateVer(Pkg);
1047 if (Ver.end() == true)
1048 return;
1049 pkgver = Ver.VerStr() == NULL ? "unknown" : Ver.VerStr();
1050 pkgRecords Recs(Cache);
1051 pkgRecords::Parser &Parse = Recs.Lookup(Ver.FileList());
1052 srcpkgname = Parse.SourcePkg();
1053 if(srcpkgname.empty())
1054 srcpkgname = pkgname;
1055
1056 // if the file exists already, we check:
1057 // - if it was reported already (touched by apport).
1058 // If not, we do nothing, otherwise
1059 // we overwrite it. This is the same behaviour as apport
1060 // - if we have a report with the same pkgversion already
1061 // then we skip it
1062 reportfile = flCombine("/var/crash",pkgname+".0.crash");
1063 if(FileExists(reportfile))
1064 {
1065 struct stat buf;
1066 char strbuf[255];
1067
1068 // check atime/mtime
1069 stat(reportfile.c_str(), &buf);
1070 if(buf.st_mtime > buf.st_atime)
1071 return;
1072
1073 // check if the existing report is the same version
1074 report = fopen(reportfile.c_str(),"r");
1075 while(fgets(strbuf, sizeof(strbuf), report) != NULL)
1076 {
1077 if(strstr(strbuf,"Package:") == strbuf)
1078 {
1079 char pkgname[255], version[255];
1080 if(sscanf(strbuf, "Package: %s %s", pkgname, version) == 2)
1081 if(strcmp(pkgver.c_str(), version) == 0)
1082 {
1083 fclose(report);
1084 return;
1085 }
1086 }
1087 }
1088 fclose(report);
1089 }
1090
1091 // now write the report
1092 arch = _config->Find("APT::Architecture");
1093 report = fopen(reportfile.c_str(),"w");
1094 if(report == NULL)
1095 return;
1096 if(_config->FindB("DPkgPM::InitialReportOnly",false) == true)
1097 chmod(reportfile.c_str(), 0);
1098 else
1099 chmod(reportfile.c_str(), 0600);
1100 fprintf(report, "ProblemType: Package\n");
1101 fprintf(report, "Architecture: %s\n", arch.c_str());
1102 time_t now = time(NULL);
1103 fprintf(report, "Date: %s" , ctime(&now));
1104 fprintf(report, "Package: %s %s\n", pkgname.c_str(), pkgver.c_str());
1105 fprintf(report, "SourcePackage: %s\n", srcpkgname.c_str());
1106 fprintf(report, "ErrorMessage:\n %s\n", errormsg);
1107
1108 // ensure that the log is flushed
1109 if(term_out)
1110 fflush(term_out);
1111
1112 // attach terminal log it if we have it
1113 string logfile_name = _config->FindFile("Dir::Log::Terminal");
1114 if (!logfile_name.empty())
1115 {
1116 FILE *log = NULL;
1117 char buf[1024];
1118
1119 fprintf(report, "DpkgTerminalLog:\n");
1120 log = fopen(logfile_name.c_str(),"r");
1121 if(log != NULL)
1122 {
1123 while( fgets(buf, sizeof(buf), log) != NULL)
1124 fprintf(report, " %s", buf);
1125 fclose(log);
1126 }
1127 }
1128 fclose(report);
1129 }
1130 /*}}}*/