]> git.saurik.com Git - apt.git/blob - apt-pkg/deb/dpkgpm.cc
08291854fe57b22ea1a6ba599c04a91d02faf4bd
[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 // urgs, sometime has ":" in its error string so that we
391 // end up with the error message split between list[3]
392 // and list[4], e.g. the message:
393 // failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ...
394 // concat them again
395 if( list[4] != NULL)
396 list[4][-1] = ':';
397
398 status << "pmerror:" << list[1]
399 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
400 << ":" << list[3]
401 << endl;
402 if(OutStatusFd > 0)
403 write(OutStatusFd, status.str().c_str(), status.str().size());
404 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
405 std::clog << "send: '" << status.str() << "'" << endl;
406 pkgFailures++;
407 WriteApportReport(list[1], list[3]);
408 return;
409 }
410 if(strncmp(action,"conffile",strlen("conffile")) == 0)
411 {
412 status << "pmconffile:" << list[1]
413 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
414 << ":" << list[3]
415 << endl;
416 if(OutStatusFd > 0)
417 write(OutStatusFd, status.str().c_str(), status.str().size());
418 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
419 std::clog << "send: '" << status.str() << "'" << endl;
420 return;
421 }
422
423 vector<struct DpkgState> &states = PackageOps[pkg];
424 const char *next_action = NULL;
425 if(PackageOpsDone[pkg] < states.size())
426 next_action = states[PackageOpsDone[pkg]].state;
427 // check if the package moved to the next dpkg state
428 if(next_action && (strcmp(action, next_action) == 0))
429 {
430 // only read the translation if there is actually a next
431 // action
432 const char *translation = _(states[PackageOpsDone[pkg]].str);
433 char s[200];
434 snprintf(s, sizeof(s), translation, pkg);
435
436 // we moved from one dpkg state to a new one, report that
437 PackageOpsDone[pkg]++;
438 PackagesDone++;
439 // build the status str
440 status << "pmstatus:" << pkg
441 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
442 << ":" << s
443 << endl;
444 if(OutStatusFd > 0)
445 write(OutStatusFd, status.str().c_str(), status.str().size());
446 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
447 std::clog << "send: '" << status.str() << "'" << endl;
448 }
449 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
450 std::clog << "(parsed from dpkg) pkg: " << pkg
451 << " action: " << action << endl;
452 }
453
454 // DPkgPM::DoDpkgStatusFd /*{{{*/
455 // ---------------------------------------------------------------------
456 /*
457 */
458 void pkgDPkgPM::DoDpkgStatusFd(int statusfd, int OutStatusFd)
459 {
460 char *p, *q;
461 int len;
462
463 len=read(statusfd, &dpkgbuf[dpkgbuf_pos], sizeof(dpkgbuf)-dpkgbuf_pos);
464 dpkgbuf_pos += len;
465 if(len <= 0)
466 return;
467
468 // process line by line if we have a buffer
469 p = q = dpkgbuf;
470 while((q=(char*)memchr(p, '\n', dpkgbuf+dpkgbuf_pos-p)) != NULL)
471 {
472 *q = 0;
473 ProcessDpkgStatusLine(OutStatusFd, p);
474 p=q+1; // continue with next line
475 }
476
477 // now move the unprocessed bits (after the final \n that is now a 0x0)
478 // to the start and update dpkgbuf_pos
479 p = (char*)memrchr(dpkgbuf, 0, dpkgbuf_pos);
480 if(p == NULL)
481 return;
482
483 // we are interessted in the first char *after* 0x0
484 p++;
485
486 // move the unprocessed tail to the start and update pos
487 memmove(dpkgbuf, p, p-dpkgbuf);
488 dpkgbuf_pos = dpkgbuf+dpkgbuf_pos-p;
489 }
490 /*}}}*/
491
492 bool pkgDPkgPM::OpenLog()
493 {
494 string logdir = _config->FindDir("Dir::Log");
495 if(not FileExists(logdir))
496 return _error->Error(_("Directory '%s' missing"), logdir.c_str());
497 string logfile_name = flCombine(logdir,
498 _config->Find("Dir::Log::Terminal"));
499 if (!logfile_name.empty())
500 {
501 term_out = fopen(logfile_name.c_str(),"a");
502 chmod(logfile_name.c_str(), 0600);
503 // output current time
504 char outstr[200];
505 time_t t = time(NULL);
506 struct tm *tmp = localtime(&t);
507 strftime(outstr, sizeof(outstr), "%F %T", tmp);
508 fprintf(term_out, "\nLog started: ");
509 fprintf(term_out, "%s", outstr);
510 fprintf(term_out, "\n");
511 }
512 return true;
513 }
514
515 bool pkgDPkgPM::CloseLog()
516 {
517 if(term_out)
518 {
519 char outstr[200];
520 time_t t = time(NULL);
521 struct tm *tmp = localtime(&t);
522 strftime(outstr, sizeof(outstr), "%F %T", tmp);
523 fprintf(term_out, "Log ended: ");
524 fprintf(term_out, "%s", outstr);
525 fprintf(term_out, "\n");
526 fclose(term_out);
527 }
528 term_out = NULL;
529 return true;
530 }
531
532 /*{{{*/
533 // This implements a racy version of pselect for those architectures
534 // that don't have a working implementation.
535 // FIXME: Probably can be removed on Lenny+1
536 static int racy_pselect(int nfds, fd_set *readfds, fd_set *writefds,
537 fd_set *exceptfds, const struct timespec *timeout,
538 const sigset_t *sigmask)
539 {
540 sigset_t origmask;
541 struct timeval tv;
542 int retval;
543
544 tv.tv_sec = timeout->tv_sec;
545 tv.tv_usec = timeout->tv_nsec/1000;
546
547 sigprocmask(SIG_SETMASK, sigmask, &origmask);
548 retval = select(nfds, readfds, writefds, exceptfds, &tv);
549 sigprocmask(SIG_SETMASK, &origmask, 0);
550 return retval;
551 }
552 /*}}}*/
553
554 // DPkgPM::Go - Run the sequence /*{{{*/
555 // ---------------------------------------------------------------------
556 /* This globs the operations and calls dpkg
557 *
558 * If it is called with "OutStatusFd" set to a valid file descriptor
559 * apt will report the install progress over this fd. It maps the
560 * dpkg states a package goes through to human readable (and i10n-able)
561 * names and calculates a percentage for each step.
562 */
563 bool pkgDPkgPM::Go(int OutStatusFd)
564 {
565 unsigned int MaxArgs = _config->FindI("Dpkg::MaxArgs",8*1024);
566 unsigned int MaxArgBytes = _config->FindI("Dpkg::MaxArgBytes",32*1024);
567 bool NoTriggers = _config->FindB("DPkg::NoTriggers",false);
568
569 if (RunScripts("DPkg::Pre-Invoke") == false)
570 return false;
571
572 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
573 return false;
574
575 // map the dpkg states to the operations that are performed
576 // (this is sorted in the same way as Item::Ops)
577 static const struct DpkgState DpkgStatesOpMap[][7] = {
578 // Install operation
579 {
580 {"half-installed", N_("Preparing %s")},
581 {"unpacked", N_("Unpacking %s") },
582 {NULL, NULL}
583 },
584 // Configure operation
585 {
586 {"unpacked",N_("Preparing to configure %s") },
587 {"half-configured", N_("Configuring %s") },
588 #if 0
589 {"triggers-awaited", N_("Processing triggers for %s") },
590 {"triggers-pending", N_("Processing triggers for %s") },
591 #endif
592 { "installed", N_("Installed %s")},
593 {NULL, NULL}
594 },
595 // Remove operation
596 {
597 {"half-configured", N_("Preparing for removal of %s")},
598 #if 0
599 {"triggers-awaited", N_("Preparing for removal of %s")},
600 {"triggers-pending", N_("Preparing for removal of %s")},
601 #endif
602 {"half-installed", N_("Removing %s")},
603 {"config-files", N_("Removed %s")},
604 {NULL, NULL}
605 },
606 // Purge operation
607 {
608 {"config-files", N_("Preparing to completely remove %s")},
609 {"not-installed", N_("Completely removed %s")},
610 {NULL, NULL}
611 },
612 };
613
614 // populate the "processing" map
615 PackageProcessingOps.insert( make_pair("install",N_("Installing %s")) );
616 PackageProcessingOps.insert( make_pair("configure",N_("Configuring %s")) );
617 PackageProcessingOps.insert( make_pair("remove",N_("Removing %s")) );
618 PackageProcessingOps.insert( make_pair("trigproc",N_("Running post-installation trigger %s")) );
619
620 // init the PackageOps map, go over the list of packages that
621 // that will be [installed|configured|removed|purged] and add
622 // them to the PackageOps map (the dpkg states it goes through)
623 // and the PackageOpsTranslations (human readable strings)
624 for (vector<Item>::iterator I = List.begin(); I != List.end();I++)
625 {
626 string name = (*I).Pkg.Name();
627 PackageOpsDone[name] = 0;
628 for(int i=0; (DpkgStatesOpMap[(*I).Op][i]).state != NULL; i++)
629 {
630 PackageOps[name].push_back(DpkgStatesOpMap[(*I).Op][i]);
631 PackagesTotal++;
632 }
633 }
634
635 stdin_is_dev_null = false;
636
637 // create log
638 OpenLog();
639
640 // this loop is runs once per operation
641 for (vector<Item>::iterator I = List.begin(); I != List.end();)
642 {
643 vector<Item>::iterator J = I;
644 for (; J != List.end() && J->Op == I->Op; J++);
645
646 // Generate the argument list
647 const char *Args[MaxArgs + 50];
648 if (J - I > (signed)MaxArgs)
649 J = I + MaxArgs;
650
651 unsigned int n = 0;
652 unsigned long Size = 0;
653 string Tmp = _config->Find("Dir::Bin::dpkg","dpkg");
654 Args[n++] = Tmp.c_str();
655 Size += strlen(Args[n-1]);
656
657 // Stick in any custom dpkg options
658 Configuration::Item const *Opts = _config->Tree("DPkg::Options");
659 if (Opts != 0)
660 {
661 Opts = Opts->Child;
662 for (; Opts != 0; Opts = Opts->Next)
663 {
664 if (Opts->Value.empty() == true)
665 continue;
666 Args[n++] = Opts->Value.c_str();
667 Size += Opts->Value.length();
668 }
669 }
670
671 char status_fd_buf[20];
672 int fd[2];
673 pipe(fd);
674
675 Args[n++] = "--status-fd";
676 Size += strlen(Args[n-1]);
677 snprintf(status_fd_buf,sizeof(status_fd_buf),"%i", fd[1]);
678 Args[n++] = status_fd_buf;
679 Size += strlen(Args[n-1]);
680
681 switch (I->Op)
682 {
683 case Item::Remove:
684 Args[n++] = "--force-depends";
685 Size += strlen(Args[n-1]);
686 Args[n++] = "--force-remove-essential";
687 Size += strlen(Args[n-1]);
688 Args[n++] = "--remove";
689 Size += strlen(Args[n-1]);
690 break;
691
692 case Item::Purge:
693 Args[n++] = "--force-depends";
694 Size += strlen(Args[n-1]);
695 Args[n++] = "--force-remove-essential";
696 Size += strlen(Args[n-1]);
697 Args[n++] = "--purge";
698 Size += strlen(Args[n-1]);
699 break;
700
701 case Item::Configure:
702 Args[n++] = "--configure";
703 if (NoTriggers)
704 Args[n++] = "--no-triggers";
705 Size += strlen(Args[n-1]);
706 break;
707
708 case Item::Install:
709 Args[n++] = "--unpack";
710 Size += strlen(Args[n-1]);
711 Args[n++] = "--auto-deconfigure";
712 Size += strlen(Args[n-1]);
713 break;
714 }
715
716 // Write in the file or package names
717 if (I->Op == Item::Install)
718 {
719 for (;I != J && Size < MaxArgBytes; I++)
720 {
721 if (I->File[0] != '/')
722 return _error->Error("Internal Error, Pathname to install is not absolute '%s'",I->File.c_str());
723 Args[n++] = I->File.c_str();
724 Size += strlen(Args[n-1]);
725 }
726 }
727 else
728 {
729 for (;I != J && Size < MaxArgBytes; I++)
730 {
731 Args[n++] = I->Pkg.Name();
732 Size += strlen(Args[n-1]);
733 }
734 }
735 Args[n] = 0;
736 J = I;
737
738 if (_config->FindB("Debug::pkgDPkgPM",false) == true)
739 {
740 for (unsigned int k = 0; k != n; k++)
741 clog << Args[k] << ' ';
742 clog << endl;
743 continue;
744 }
745
746 cout << flush;
747 clog << flush;
748 cerr << flush;
749
750 /* Mask off sig int/quit. We do this because dpkg also does when
751 it forks scripts. What happens is that when you hit ctrl-c it sends
752 it to all processes in the group. Since dpkg ignores the signal
753 it doesn't die but we do! So we must also ignore it */
754 sighandler_t old_SIGQUIT = signal(SIGQUIT,SIG_IGN);
755 sighandler_t old_SIGINT = signal(SIGINT,SIG_IGN);
756
757 struct termios tt;
758 struct termios tt_out;
759 struct winsize win;
760 int master;
761 int slave;
762
763 // FIXME: setup sensible signal handling (*ick*)
764 tcgetattr(0, &tt);
765 tcgetattr(1, &tt_out);
766 ioctl(0, TIOCGWINSZ, (char *)&win);
767 if (openpty(&master, &slave, NULL, &tt_out, &win) < 0)
768 {
769 const char *s = _("Can not write log, openpty() "
770 "failed (/dev/pts not mounted?)\n");
771 fprintf(stderr, "%s",s);
772 fprintf(term_out, "%s",s);
773 master = slave = -1;
774 } else {
775 struct termios rtt;
776 rtt = tt;
777 cfmakeraw(&rtt);
778 rtt.c_lflag &= ~ECHO;
779 tcsetattr(0, TCSAFLUSH, &rtt);
780 }
781
782 // Fork dpkg
783 pid_t Child;
784 _config->Set("APT::Keep-Fds::",fd[1]);
785 Child = ExecFork();
786
787 // This is the child
788 if (Child == 0)
789 {
790 if(slave >= 0 && master >= 0)
791 {
792 setsid();
793 ioctl(slave, TIOCSCTTY, 0);
794 close(master);
795 dup2(slave, 0);
796 dup2(slave, 1);
797 dup2(slave, 2);
798 close(slave);
799 }
800 close(fd[0]); // close the read end of the pipe
801
802 if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
803 _exit(100);
804
805 if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
806 {
807 int Flags,dummy;
808 if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
809 _exit(100);
810
811 // Discard everything in stdin before forking dpkg
812 if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
813 _exit(100);
814
815 while (read(STDIN_FILENO,&dummy,1) == 1);
816
817 if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
818 _exit(100);
819 }
820
821
822 /* No Job Control Stop Env is a magic dpkg var that prevents it
823 from using sigstop */
824 putenv((char *)"DPKG_NO_TSTP=yes");
825 execvp(Args[0],(char **)Args);
826 cerr << "Could not exec dpkg!" << endl;
827 _exit(100);
828 }
829
830 // clear the Keep-Fd again
831 _config->Clear("APT::Keep-Fds",fd[1]);
832
833 // Wait for dpkg
834 int Status = 0;
835
836 // we read from dpkg here
837 int _dpkgin = fd[0];
838 close(fd[1]); // close the write end of the pipe
839
840 // the result of the waitpid call
841 int res;
842 if(slave > 0)
843 close(slave);
844
845 // setups fds
846 fd_set rfds;
847 struct timespec tv;
848 sigset_t sigmask;
849 sigset_t original_sigmask;
850 sigemptyset(&sigmask);
851 sigprocmask(SIG_BLOCK,&sigmask,&original_sigmask);
852
853 int select_ret;
854 while ((res=waitpid(Child,&Status, WNOHANG)) != Child) {
855 if(res < 0) {
856 // FIXME: move this to a function or something, looks ugly here
857 // error handling, waitpid returned -1
858 if (errno == EINTR)
859 continue;
860 RunScripts("DPkg::Post-Invoke");
861
862 // Restore sig int/quit
863 signal(SIGQUIT,old_SIGQUIT);
864 signal(SIGINT,old_SIGINT);
865 return _error->Errno("waitpid","Couldn't wait for subprocess");
866 }
867 // wait for input or output here
868 FD_ZERO(&rfds);
869 if (!stdin_is_dev_null)
870 FD_SET(0, &rfds);
871 FD_SET(_dpkgin, &rfds);
872 if(master >= 0)
873 FD_SET(master, &rfds);
874 tv.tv_sec = 1;
875 tv.tv_nsec = 0;
876 select_ret = pselect(max(master, _dpkgin)+1, &rfds, NULL, NULL,
877 &tv, &original_sigmask);
878 if (select_ret < 0 && (errno == EINVAL || errno == ENOSYS))
879 select_ret = racy_pselect(max(master, _dpkgin)+1, &rfds, NULL,
880 NULL, &tv, &original_sigmask);
881 if (select_ret == 0)
882 continue;
883 else if (select_ret < 0 && errno == EINTR)
884 continue;
885 else if (select_ret < 0)
886 {
887 perror("select() returned error");
888 continue;
889 }
890
891 if(master >= 0 && FD_ISSET(master, &rfds))
892 DoTerminalPty(master);
893 if(master >= 0 && FD_ISSET(0, &rfds))
894 DoStdin(master);
895 if(FD_ISSET(_dpkgin, &rfds))
896 DoDpkgStatusFd(_dpkgin, OutStatusFd);
897 }
898 close(_dpkgin);
899
900 // Restore sig int/quit
901 signal(SIGQUIT,old_SIGQUIT);
902 signal(SIGINT,old_SIGINT);
903
904 if(master >= 0)
905 {
906 tcsetattr(0, TCSAFLUSH, &tt);
907 close(master);
908 }
909
910 // Check for an error code.
911 if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
912 {
913 // if it was set to "keep-dpkg-runing" then we won't return
914 // here but keep the loop going and just report it as a error
915 // for later
916 bool stopOnError = _config->FindB("Dpkg::StopOnError",true);
917
918 if(stopOnError)
919 RunScripts("DPkg::Post-Invoke");
920
921 if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
922 _error->Error("Sub-process %s received a segmentation fault.",Args[0]);
923 else if (WIFEXITED(Status) != 0)
924 _error->Error("Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
925 else
926 _error->Error("Sub-process %s exited unexpectedly",Args[0]);
927
928 if(stopOnError)
929 {
930 CloseLog();
931 return false;
932 }
933 }
934 }
935 CloseLog();
936
937 if (RunScripts("DPkg::Post-Invoke") == false)
938 return false;
939 return true;
940 }
941 /*}}}*/
942 // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
943 // ---------------------------------------------------------------------
944 /* */
945 void pkgDPkgPM::Reset()
946 {
947 List.erase(List.begin(),List.end());
948 }
949 /*}}}*/
950 // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
951 // ---------------------------------------------------------------------
952 /* */
953 void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
954 {
955 string pkgname, reportfile, srcpkgname, pkgver, arch;
956 string::size_type pos;
957 FILE *report;
958
959 if (_config->FindB("Dpkg::ApportFailureReport",true) == false)
960 {
961 std::clog << "configured to not write apport reports" << std::endl;
962 return;
963 }
964
965 // only report the first errors
966 if(pkgFailures > _config->FindI("APT::Apport::MaxReports", 3))
967 {
968 std::clog << _("No apport report written because MaxReports is reached already") << std::endl;
969 return;
970 }
971
972 // check if its not a follow up error
973 const char *needle = dgettext("dpkg", "dependency problems - leaving unconfigured");
974 if(strstr(errormsg, needle) != NULL) {
975 std::clog << _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl;
976 return;
977 }
978
979 // get the pkgname and reportfile
980 pkgname = flNotDir(pkgpath);
981 pos = pkgname.find('_');
982 if(pos != string::npos)
983 pkgname = pkgname.substr(0, pos);
984
985 // find the package versin and source package name
986 pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
987 if (Pkg.end() == true)
988 return;
989 pkgCache::VerIterator Ver = Cache.GetCandidateVer(Pkg);
990 if (Ver.end() == true)
991 return;
992 pkgver = Ver.VerStr() == NULL ? "unknown" : Ver.VerStr();
993 pkgRecords Recs(Cache);
994 pkgRecords::Parser &Parse = Recs.Lookup(Ver.FileList());
995 srcpkgname = Parse.SourcePkg();
996 if(srcpkgname.empty())
997 srcpkgname = pkgname;
998
999 // if the file exists already, we check:
1000 // - if it was reported already (touched by apport).
1001 // If not, we do nothing, otherwise
1002 // we overwrite it. This is the same behaviour as apport
1003 // - if we have a report with the same pkgversion already
1004 // then we skip it
1005 reportfile = flCombine("/var/crash",pkgname+".0.crash");
1006 if(FileExists(reportfile))
1007 {
1008 struct stat buf;
1009 char strbuf[255];
1010
1011 // check atime/mtime
1012 stat(reportfile.c_str(), &buf);
1013 if(buf.st_mtime > buf.st_atime)
1014 return;
1015
1016 // check if the existing report is the same version
1017 report = fopen(reportfile.c_str(),"r");
1018 while(fgets(strbuf, sizeof(strbuf), report) != NULL)
1019 {
1020 if(strstr(strbuf,"Package:") == strbuf)
1021 {
1022 char pkgname[255], version[255];
1023 if(sscanf(strbuf, "Package: %s %s", pkgname, version) == 2)
1024 if(strcmp(pkgver.c_str(), version) == 0)
1025 {
1026 fclose(report);
1027 return;
1028 }
1029 }
1030 }
1031 fclose(report);
1032 }
1033
1034 // now write the report
1035 arch = _config->Find("APT::Architecture");
1036 report = fopen(reportfile.c_str(),"w");
1037 if(report == NULL)
1038 return;
1039 if(_config->FindB("DPkgPM::InitialReportOnly",false) == true)
1040 chmod(reportfile.c_str(), 0);
1041 else
1042 chmod(reportfile.c_str(), 0600);
1043 fprintf(report, "ProblemType: Package\n");
1044 fprintf(report, "Architecture: %s\n", arch.c_str());
1045 time_t now = time(NULL);
1046 fprintf(report, "Date: %s" , ctime(&now));
1047 fprintf(report, "Package: %s %s\n", pkgname.c_str(), pkgver.c_str());
1048 fprintf(report, "SourcePackage: %s\n", srcpkgname.c_str());
1049 fprintf(report, "ErrorMessage:\n %s\n", errormsg);
1050
1051 // ensure that the log is flushed
1052 if(term_out)
1053 fflush(term_out);
1054
1055 // attach terminal log it if we have it
1056 string logfile_name = _config->FindFile("Dir::Log::Terminal");
1057 if (!logfile_name.empty())
1058 {
1059 FILE *log = NULL;
1060 char buf[1024];
1061
1062 fprintf(report, "DpkgTerminalLog:\n");
1063 log = fopen(logfile_name.c_str(),"r");
1064 if(log != NULL)
1065 {
1066 while( fgets(buf, sizeof(buf), log) != NULL)
1067 fprintf(report, " %s", buf);
1068 fclose(log);
1069 }
1070 }
1071 fclose(report);
1072 }
1073 /*}}}*/