]> git.saurik.com Git - apt.git/blob - apt-pkg/deb/dpkgpm.cc
* apt-pkg/deb/dpkgpm.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 fd_set rfds;
567 struct timespec tv;
568 sigset_t sigmask;
569 sigset_t original_sigmask;
570
571 unsigned int MaxArgs = _config->FindI("Dpkg::MaxArgs",8*1024);
572 unsigned int MaxArgBytes = _config->FindI("Dpkg::MaxArgBytes",32*1024);
573 bool NoTriggers = _config->FindB("DPkg::NoTriggers",false);
574
575 if (RunScripts("DPkg::Pre-Invoke") == false)
576 return false;
577
578 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
579 return false;
580
581 // map the dpkg states to the operations that are performed
582 // (this is sorted in the same way as Item::Ops)
583 static const struct DpkgState DpkgStatesOpMap[][7] = {
584 // Install operation
585 {
586 {"half-installed", N_("Preparing %s")},
587 {"unpacked", N_("Unpacking %s") },
588 {NULL, NULL}
589 },
590 // Configure operation
591 {
592 {"unpacked",N_("Preparing to configure %s") },
593 {"half-configured", N_("Configuring %s") },
594 #if 0
595 {"triggers-awaited", N_("Processing triggers for %s") },
596 {"triggers-pending", N_("Processing triggers for %s") },
597 #endif
598 { "installed", N_("Installed %s")},
599 {NULL, NULL}
600 },
601 // Remove operation
602 {
603 {"half-configured", N_("Preparing for removal of %s")},
604 #if 0
605 {"triggers-awaited", N_("Preparing for removal of %s")},
606 {"triggers-pending", N_("Preparing for removal of %s")},
607 #endif
608 {"half-installed", N_("Removing %s")},
609 {"config-files", N_("Removed %s")},
610 {NULL, NULL}
611 },
612 // Purge operation
613 {
614 {"config-files", N_("Preparing to completely remove %s")},
615 {"not-installed", N_("Completely removed %s")},
616 {NULL, NULL}
617 },
618 };
619
620 // populate the "processing" map
621 PackageProcessingOps.insert( make_pair("install",N_("Installing %s")) );
622 PackageProcessingOps.insert( make_pair("configure",N_("Configuring %s")) );
623 PackageProcessingOps.insert( make_pair("remove",N_("Removing %s")) );
624 PackageProcessingOps.insert( make_pair("trigproc",N_("Running post-installation trigger %s")) );
625
626 // init the PackageOps map, go over the list of packages that
627 // that will be [installed|configured|removed|purged] and add
628 // them to the PackageOps map (the dpkg states it goes through)
629 // and the PackageOpsTranslations (human readable strings)
630 for (vector<Item>::iterator I = List.begin(); I != List.end();I++)
631 {
632 string name = (*I).Pkg.Name();
633 PackageOpsDone[name] = 0;
634 for(int i=0; (DpkgStatesOpMap[(*I).Op][i]).state != NULL; i++)
635 {
636 PackageOps[name].push_back(DpkgStatesOpMap[(*I).Op][i]);
637 PackagesTotal++;
638 }
639 }
640
641 stdin_is_dev_null = false;
642
643 // create log
644 OpenLog();
645
646 // this loop is runs once per operation
647 for (vector<Item>::iterator I = List.begin(); I != List.end();)
648 {
649 vector<Item>::iterator J = I;
650 for (; J != List.end() && J->Op == I->Op; J++);
651
652 // Generate the argument list
653 const char *Args[MaxArgs + 50];
654 if (J - I > (signed)MaxArgs)
655 J = I + MaxArgs;
656
657 unsigned int n = 0;
658 unsigned long Size = 0;
659 string Tmp = _config->Find("Dir::Bin::dpkg","dpkg");
660 Args[n++] = Tmp.c_str();
661 Size += strlen(Args[n-1]);
662
663 // Stick in any custom dpkg options
664 Configuration::Item const *Opts = _config->Tree("DPkg::Options");
665 if (Opts != 0)
666 {
667 Opts = Opts->Child;
668 for (; Opts != 0; Opts = Opts->Next)
669 {
670 if (Opts->Value.empty() == true)
671 continue;
672 Args[n++] = Opts->Value.c_str();
673 Size += Opts->Value.length();
674 }
675 }
676
677 char status_fd_buf[20];
678 int fd[2];
679 pipe(fd);
680
681 Args[n++] = "--status-fd";
682 Size += strlen(Args[n-1]);
683 snprintf(status_fd_buf,sizeof(status_fd_buf),"%i", fd[1]);
684 Args[n++] = status_fd_buf;
685 Size += strlen(Args[n-1]);
686
687 switch (I->Op)
688 {
689 case Item::Remove:
690 Args[n++] = "--force-depends";
691 Size += strlen(Args[n-1]);
692 Args[n++] = "--force-remove-essential";
693 Size += strlen(Args[n-1]);
694 Args[n++] = "--remove";
695 Size += strlen(Args[n-1]);
696 break;
697
698 case Item::Purge:
699 Args[n++] = "--force-depends";
700 Size += strlen(Args[n-1]);
701 Args[n++] = "--force-remove-essential";
702 Size += strlen(Args[n-1]);
703 Args[n++] = "--purge";
704 Size += strlen(Args[n-1]);
705 break;
706
707 case Item::Configure:
708 Args[n++] = "--configure";
709 if (NoTriggers)
710 Args[n++] = "--no-triggers";
711 Size += strlen(Args[n-1]);
712 break;
713
714 case Item::Install:
715 Args[n++] = "--unpack";
716 Size += strlen(Args[n-1]);
717 Args[n++] = "--auto-deconfigure";
718 Size += strlen(Args[n-1]);
719 break;
720 }
721
722 // Write in the file or package names
723 if (I->Op == Item::Install)
724 {
725 for (;I != J && Size < MaxArgBytes; I++)
726 {
727 if (I->File[0] != '/')
728 return _error->Error("Internal Error, Pathname to install is not absolute '%s'",I->File.c_str());
729 Args[n++] = I->File.c_str();
730 Size += strlen(Args[n-1]);
731 }
732 }
733 else
734 {
735 for (;I != J && Size < MaxArgBytes; I++)
736 {
737 Args[n++] = I->Pkg.Name();
738 Size += strlen(Args[n-1]);
739 }
740 }
741 Args[n] = 0;
742 J = I;
743
744 if (_config->FindB("Debug::pkgDPkgPM",false) == true)
745 {
746 for (unsigned int k = 0; k != n; k++)
747 clog << Args[k] << ' ';
748 clog << endl;
749 continue;
750 }
751
752 cout << flush;
753 clog << flush;
754 cerr << flush;
755
756 /* Mask off sig int/quit. We do this because dpkg also does when
757 it forks scripts. What happens is that when you hit ctrl-c it sends
758 it to all processes in the group. Since dpkg ignores the signal
759 it doesn't die but we do! So we must also ignore it */
760 sighandler_t old_SIGQUIT = signal(SIGQUIT,SIG_IGN);
761 sighandler_t old_SIGINT = signal(SIGINT,SIG_IGN);
762
763 struct termios tt;
764 struct termios tt_out;
765 struct winsize win;
766 int master;
767 int slave;
768
769 // FIXME: setup sensible signal handling (*ick*)
770 tcgetattr(0, &tt);
771 tcgetattr(1, &tt_out);
772 ioctl(0, TIOCGWINSZ, (char *)&win);
773 if (openpty(&master, &slave, NULL, &tt_out, &win) < 0)
774 {
775 const char *s = _("Can not write log, openpty() "
776 "failed (/dev/pts not mounted?)\n");
777 fprintf(stderr, "%s",s);
778 fprintf(term_out, "%s",s);
779 master = slave = -1;
780 } else {
781 struct termios rtt;
782 rtt = tt;
783 cfmakeraw(&rtt);
784 rtt.c_lflag &= ~ECHO;
785 // block SIGTTOU during tcsetattr to prevent a hang if
786 // the process is a member of the background process group
787 // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
788 sigemptyset(&sigmask);
789 sigaddset(&sigmask, SIGTTOU);
790 sigprocmask(SIG_BLOCK,&sigmask, &original_sigmask);
791 tcsetattr(0, TCSAFLUSH, &rtt);
792 sigprocmask(SIG_SETMASK, &original_sigmask, 0);
793 }
794
795 // Fork dpkg
796 pid_t Child;
797 _config->Set("APT::Keep-Fds::",fd[1]);
798 Child = ExecFork();
799
800 // This is the child
801 if (Child == 0)
802 {
803 if(slave >= 0 && master >= 0)
804 {
805 setsid();
806 ioctl(slave, TIOCSCTTY, 0);
807 close(master);
808 dup2(slave, 0);
809 dup2(slave, 1);
810 dup2(slave, 2);
811 close(slave);
812 }
813 close(fd[0]); // close the read end of the pipe
814
815 if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
816 _exit(100);
817
818 if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
819 {
820 int Flags,dummy;
821 if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
822 _exit(100);
823
824 // Discard everything in stdin before forking dpkg
825 if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
826 _exit(100);
827
828 while (read(STDIN_FILENO,&dummy,1) == 1);
829
830 if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
831 _exit(100);
832 }
833
834
835 /* No Job Control Stop Env is a magic dpkg var that prevents it
836 from using sigstop */
837 putenv((char *)"DPKG_NO_TSTP=yes");
838 execvp(Args[0],(char **)Args);
839 cerr << "Could not exec dpkg!" << endl;
840 _exit(100);
841 }
842
843 // clear the Keep-Fd again
844 _config->Clear("APT::Keep-Fds",fd[1]);
845
846 // Wait for dpkg
847 int Status = 0;
848
849 // we read from dpkg here
850 int _dpkgin = fd[0];
851 close(fd[1]); // close the write end of the pipe
852
853 // the result of the waitpid call
854 int res;
855 if(slave > 0)
856 close(slave);
857
858 // setups fds
859 sigemptyset(&sigmask);
860 sigprocmask(SIG_BLOCK,&sigmask,&original_sigmask);
861
862 int select_ret;
863 while ((res=waitpid(Child,&Status, WNOHANG)) != Child) {
864 if(res < 0) {
865 // FIXME: move this to a function or something, looks ugly here
866 // error handling, waitpid returned -1
867 if (errno == EINTR)
868 continue;
869 RunScripts("DPkg::Post-Invoke");
870
871 // Restore sig int/quit
872 signal(SIGQUIT,old_SIGQUIT);
873 signal(SIGINT,old_SIGINT);
874 return _error->Errno("waitpid","Couldn't wait for subprocess");
875 }
876 // wait for input or output here
877 FD_ZERO(&rfds);
878 if (!stdin_is_dev_null)
879 FD_SET(0, &rfds);
880 FD_SET(_dpkgin, &rfds);
881 if(master >= 0)
882 FD_SET(master, &rfds);
883 tv.tv_sec = 1;
884 tv.tv_nsec = 0;
885 select_ret = pselect(max(master, _dpkgin)+1, &rfds, NULL, NULL,
886 &tv, &original_sigmask);
887 if (select_ret < 0 && (errno == EINVAL || errno == ENOSYS))
888 select_ret = racy_pselect(max(master, _dpkgin)+1, &rfds, NULL,
889 NULL, &tv, &original_sigmask);
890 if (select_ret == 0)
891 continue;
892 else if (select_ret < 0 && errno == EINTR)
893 continue;
894 else if (select_ret < 0)
895 {
896 perror("select() returned error");
897 continue;
898 }
899
900 if(master >= 0 && FD_ISSET(master, &rfds))
901 DoTerminalPty(master);
902 if(master >= 0 && FD_ISSET(0, &rfds))
903 DoStdin(master);
904 if(FD_ISSET(_dpkgin, &rfds))
905 DoDpkgStatusFd(_dpkgin, OutStatusFd);
906 }
907 close(_dpkgin);
908
909 // Restore sig int/quit
910 signal(SIGQUIT,old_SIGQUIT);
911 signal(SIGINT,old_SIGINT);
912
913 if(master >= 0)
914 {
915 tcsetattr(0, TCSAFLUSH, &tt);
916 close(master);
917 }
918
919 // Check for an error code.
920 if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
921 {
922 // if it was set to "keep-dpkg-runing" then we won't return
923 // here but keep the loop going and just report it as a error
924 // for later
925 bool stopOnError = _config->FindB("Dpkg::StopOnError",true);
926
927 if(stopOnError)
928 RunScripts("DPkg::Post-Invoke");
929
930 if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
931 _error->Error("Sub-process %s received a segmentation fault.",Args[0]);
932 else if (WIFEXITED(Status) != 0)
933 _error->Error("Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
934 else
935 _error->Error("Sub-process %s exited unexpectedly",Args[0]);
936
937 if(stopOnError)
938 {
939 CloseLog();
940 return false;
941 }
942 }
943 }
944 CloseLog();
945
946 if (RunScripts("DPkg::Post-Invoke") == false)
947 return false;
948 return true;
949 }
950 /*}}}*/
951 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
952 // ---------------------------------------------------------------------
953 /* */
954 void pkgDPkgPM::Reset()
955 {
956 List.erase(List.begin(),List.end());
957 }
958 /*}}}*/
959 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
960 // ---------------------------------------------------------------------
961 /* */
962 void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
963 {
964 string pkgname, reportfile, srcpkgname, pkgver, arch;
965 string::size_type pos;
966 FILE *report;
967
968 if (_config->FindB("Dpkg::ApportFailureReport",true) == false)
969 {
970 std::clog << "configured to not write apport reports" << std::endl;
971 return;
972 }
973
974 // only report the first errors
975 if(pkgFailures > _config->FindI("APT::Apport::MaxReports", 3))
976 {
977 std::clog << _("No apport report written because MaxReports is reached already") << std::endl;
978 return;
979 }
980
981 // check if its not a follow up error
982 const char *needle = dgettext("dpkg", "dependency problems - leaving unconfigured");
983 if(strstr(errormsg, needle) != NULL) {
984 std::clog << _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl;
985 return;
986 }
987
988 // do not report disk-full failures
989 if(strstr(errormsg, strerror(ENOSPC)) != NULL) {
990 std::clog << _("No apport report written because the error message indicates a disk full error") << std::endl;
991 return;
992 }
993
994 // get the pkgname and reportfile
995 pkgname = flNotDir(pkgpath);
996 pos = pkgname.find('_');
997 if(pos != string::npos)
998 pkgname = pkgname.substr(0, pos);
999
1000 // find the package versin and source package name
1001 pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
1002 if (Pkg.end() == true)
1003 return;
1004 pkgCache::VerIterator Ver = Cache.GetCandidateVer(Pkg);
1005 if (Ver.end() == true)
1006 return;
1007 pkgver = Ver.VerStr() == NULL ? "unknown" : Ver.VerStr();
1008 pkgRecords Recs(Cache);
1009 pkgRecords::Parser &Parse = Recs.Lookup(Ver.FileList());
1010 srcpkgname = Parse.SourcePkg();
1011 if(srcpkgname.empty())
1012 srcpkgname = pkgname;
1013
1014 // if the file exists already, we check:
1015 // - if it was reported already (touched by apport).
1016 // If not, we do nothing, otherwise
1017 // we overwrite it. This is the same behaviour as apport
1018 // - if we have a report with the same pkgversion already
1019 // then we skip it
1020 reportfile = flCombine("/var/crash",pkgname+".0.crash");
1021 if(FileExists(reportfile))
1022 {
1023 struct stat buf;
1024 char strbuf[255];
1025
1026 // check atime/mtime
1027 stat(reportfile.c_str(), &buf);
1028 if(buf.st_mtime > buf.st_atime)
1029 return;
1030
1031 // check if the existing report is the same version
1032 report = fopen(reportfile.c_str(),"r");
1033 while(fgets(strbuf, sizeof(strbuf), report) != NULL)
1034 {
1035 if(strstr(strbuf,"Package:") == strbuf)
1036 {
1037 char pkgname[255], version[255];
1038 if(sscanf(strbuf, "Package: %s %s", pkgname, version) == 2)
1039 if(strcmp(pkgver.c_str(), version) == 0)
1040 {
1041 fclose(report);
1042 return;
1043 }
1044 }
1045 }
1046 fclose(report);
1047 }
1048
1049 // now write the report
1050 arch = _config->Find("APT::Architecture");
1051 report = fopen(reportfile.c_str(),"w");
1052 if(report == NULL)
1053 return;
1054 if(_config->FindB("DPkgPM::InitialReportOnly",false) == true)
1055 chmod(reportfile.c_str(), 0);
1056 else
1057 chmod(reportfile.c_str(), 0600);
1058 fprintf(report, "ProblemType: Package\n");
1059 fprintf(report, "Architecture: %s\n", arch.c_str());
1060 time_t now = time(NULL);
1061 fprintf(report, "Date: %s" , ctime(&now));
1062 fprintf(report, "Package: %s %s\n", pkgname.c_str(), pkgver.c_str());
1063 fprintf(report, "SourcePackage: %s\n", srcpkgname.c_str());
1064 fprintf(report, "ErrorMessage:\n %s\n", errormsg);
1065
1066 // ensure that the log is flushed
1067 if(term_out)
1068 fflush(term_out);
1069
1070 // attach terminal log it if we have it
1071 string logfile_name = _config->FindFile("Dir::Log::Terminal");
1072 if (!logfile_name.empty())
1073 {
1074 FILE *log = NULL;
1075 char buf[1024];
1076
1077 fprintf(report, "DpkgTerminalLog:\n");
1078 log = fopen(logfile_name.c_str(),"r");
1079 if(log != NULL)
1080 {
1081 while( fgets(buf, sizeof(buf), log) != NULL)
1082 fprintf(report, " %s", buf);
1083 fclose(log);
1084 }
1085 }
1086 fclose(report);
1087 }
1088 /*}}}*/