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