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