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