]> git.saurik.com Git - apt.git/blame - apt-pkg/deb/dpkgpm.cc
* reupload to fix FTBFS
[apt.git] / apt-pkg / deb / dpkgpm.cc
CommitLineData
c0c0b100 1// -*- mode: cpp; mode: fold -*-
03e39e59 2// Description /*{{{*/
7f9a6360 3// $Id: dpkgpm.cc,v 1.28 2004/01/27 02:25:01 mdz Exp $
03e39e59
AL
4/* ######################################################################
5
6 DPKG Package Manager - Provide an interface to dpkg
7
8 ##################################################################### */
9 /*}}}*/
10// Includes /*{{{*/
03e39e59
AL
11#include <apt-pkg/dpkgpm.h>
12#include <apt-pkg/error.h>
13#include <apt-pkg/configuration.h>
b2e465d6 14#include <apt-pkg/depcache.h>
5e457a93 15#include <apt-pkg/pkgrecords.h>
b2e465d6 16#include <apt-pkg/strutl.h>
a4cf3665 17#include <apti18n.h>
233b185f 18
03e39e59
AL
19#include <unistd.h>
20#include <stdlib.h>
21#include <fcntl.h>
090c6566 22#include <sys/select.h>
03e39e59
AL
23#include <sys/types.h>
24#include <sys/wait.h>
25#include <signal.h>
26#include <errno.h>
db0c350f 27#include <stdio.h>
75ef8f14
MV
28#include <sstream>
29#include <map>
30
d8cb4aa4
MV
31#include <termios.h>
32#include <unistd.h>
33#include <sys/ioctl.h>
34#include <pty.h>
35
75ef8f14
MV
36#include <config.h>
37#include <apti18n.h>
b0ebdef5 38 /*}}}*/
233b185f
AL
39
40using namespace std;
03e39e59 41
09fa2df2
MV
42
43
03e39e59
AL
44// DPkgPM::pkgDPkgPM - Constructor /*{{{*/
45// ---------------------------------------------------------------------
46/* */
5e457a93 47pkgDPkgPM::pkgDPkgPM(pkgDepCache *Cache)
1ba38171
MV
48 : pkgPackageManager(Cache), dpkgbuf_pos(0), PackagesDone(0),
49 PackagesTotal(0), term_out(NULL)
03e39e59
AL
50{
51}
52 /*}}}*/
53// DPkgPM::pkgDPkgPM - Destructor /*{{{*/
54// ---------------------------------------------------------------------
55/* */
56pkgDPkgPM::~pkgDPkgPM()
57{
58}
59 /*}}}*/
60// DPkgPM::Install - Install a package /*{{{*/
61// ---------------------------------------------------------------------
62/* Add an install operation to the sequence list */
63bool 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 */
75bool 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 */
fc4b5c9f 87bool pkgDPkgPM::Remove(PkgIterator Pkg,bool Purge)
03e39e59
AL
88{
89 if (Pkg.end() == true)
90 return false;
91
fc4b5c9f
AL
92 if (Purge == true)
93 List.push_back(Item(Item::Purge,Pkg));
94 else
95 List.push_back(Item(Item::Remove,Pkg));
6dd55be7
AL
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. */
103bool 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
54676e1a 111 pid_t Child = ExecFork();
6dd55be7
AL
112
113 // This is the child
114 if (Child == 0)
115 {
6dd55be7
AL
116 if (chdir("/tmp/") != 0)
117 _exit(100);
118
6dd55be7
AL
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);
ddc1d8d0 143
6dd55be7
AL
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--);
cf544e14 152 _error->Error("Problem executing scripts %s '%s'",Cnf,Opts->Value.c_str());
6dd55be7
AL
153 }
154
155 return _error->Error("Sub-process returned an error code");
156 }
157
03e39e59
AL
158 return true;
159}
db0c350f 160 /*}}}*/
b2e465d6
AL
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.*/
165bool 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 /*}}}*/
db0c350f
AL
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. */
250bool 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;
b2e465d6
AL
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();
b2e465d6
AL
268 OptSec = "DPkg::Tools::Options::" + string(Opts->Value.c_str(),Pos);
269
270 unsigned int Version = _config->FindI(OptSec+"::Version",1);
271
db0c350f
AL
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);
90ecbd7d
AL
288
289 const char *Args[4];
db0c350f 290 Args[0] = "/bin/sh";
90ecbd7d
AL
291 Args[1] = "-c";
292 Args[2] = Opts->Value.c_str();
293 Args[3] = 0;
db0c350f
AL
294 execv(Args[0],(char **)Args);
295 _exit(100);
296 }
297 close(Pipes[0]);
b2e465d6
AL
298 FILE *F = fdopen(Pipes[1],"w");
299 if (F == 0)
300 return _error->Errno("fdopen","Faild to open new FD");
301
db0c350f 302 // Feed it the filenames.
b2e465d6
AL
303 bool Die = false;
304 if (Version <= 1)
db0c350f 305 {
b2e465d6 306 for (vector<Item>::iterator I = List.begin(); I != List.end(); I++)
db0c350f 307 {
b2e465d6
AL
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 }
90ecbd7d 324 }
db0c350f 325 }
b2e465d6
AL
326 else
327 Die = !SendV2Pkgs(F);
328
329 fclose(F);
db0c350f
AL
330
331 // Clean up the sub process
332 if (ExecWait(Process,Opts->Value.c_str()) == false)
90ecbd7d 333 return _error->Error("Failure running script %s",Opts->Value.c_str());
db0c350f
AL
334 }
335
336 return true;
337}
ceabc520
MV
338
339 /*}}}*/
340// DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
341// ---------------------------------------------------------------------
342/*
343*/
344void pkgDPkgPM::DoStdin(int master)
345{
955a6ddb
MV
346 char input_buf[256] = {0,};
347 int len = read(0, input_buf, sizeof(input_buf));
348 write(master, input_buf, len);
ceabc520 349}
03e39e59 350 /*}}}*/
ceabc520
MV
351// DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
352// ---------------------------------------------------------------------
353/*
354 * read the terminal pty and write log
355 */
8ecd1fed 356void pkgDPkgPM::DoTerminalPty(int master)
ceabc520 357{
955a6ddb 358 char term_buf[1024] = {0,};
ceabc520 359
955a6ddb
MV
360 int len=read(master, term_buf, sizeof(term_buf));
361 if(len <= 0)
362 return;
955a6ddb 363 write(1, term_buf, len);
8da1f029
MV
364 if(term_out)
365 fwrite(term_buf, len, sizeof(char), term_out);
ceabc520 366}
03e39e59 367 /*}}}*/
6191b008
MV
368// DPkgPM::ProcessDpkgStatusBuf /*{{{*/
369// ---------------------------------------------------------------------
370/*
371 */
09fa2df2 372void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd, char *line)
6191b008 373{
09fa2df2
MV
374 // the status we output
375 ostringstream status;
376
377 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
378 std::clog << "got from dpkg '" << line << "'" << std::endl;
379
380
381 /* dpkg sends strings like this:
382 'status: <pkg>: <pkg qstate>'
383 errors look like this:
384 '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
385 and conffile-prompt like this
386 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
387
388 */
389 char* list[5];
390 // dpkg sends multiline error messages sometimes (see
391 // #374195 for a example. we should support this by
392 // either patching dpkg to not send multiline over the
393 // statusfd or by rewriting the code here to deal with
394 // it. for now we just ignore it and not crash
395 TokSplitString(':', line, list, sizeof(list)/sizeof(list[0]));
396 char *pkg = list[1];
397 char *action = _strstrip(list[2]);
398 if( pkg == NULL || action == NULL)
399 {
400 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
401 std::clog << "ignoring line: not enough ':'" << std::endl;
402 return;
403 }
404
405 if(strncmp(action,"error",strlen("error")) == 0)
406 {
407 status << "pmerror:" << list[1]
ff56e980 408 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
09fa2df2
MV
409 << ":" << list[3]
410 << endl;
411 if(OutStatusFd > 0)
412 write(OutStatusFd, status.str().c_str(), status.str().size());
413 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
414 std::clog << "send: '" << status.str() << "'" << endl;
f060e833
MV
415 pkgFailures++;
416 WriteApportReport(list[1], list[3]);
09fa2df2
MV
417 return;
418 }
419 if(strncmp(action,"conffile",strlen("conffile")) == 0)
420 {
421 status << "pmconffile:" << list[1]
ff56e980 422 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
09fa2df2
MV
423 << ":" << list[3]
424 << endl;
425 if(OutStatusFd > 0)
426 write(OutStatusFd, status.str().c_str(), status.str().size());
427 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
428 std::clog << "send: '" << status.str() << "'" << endl;
429 return;
430 }
431
432 vector<struct DpkgState> &states = PackageOps[pkg];
433 const char *next_action = NULL;
434 if(PackageOpsDone[pkg] < states.size())
435 next_action = states[PackageOpsDone[pkg]].state;
436 // check if the package moved to the next dpkg state
437 if(next_action && (strcmp(action, next_action) == 0))
438 {
439 // only read the translation if there is actually a next
440 // action
441 const char *translation = _(states[PackageOpsDone[pkg]].str);
442 char s[200];
443 snprintf(s, sizeof(s), translation, pkg);
444
445 // we moved from one dpkg state to a new one, report that
446 PackageOpsDone[pkg]++;
ff56e980 447 PackagesDone++;
09fa2df2
MV
448 // build the status str
449 status << "pmstatus:" << pkg
ff56e980 450 << ":" << (PackagesDone/float(PackagesTotal)*100.0)
09fa2df2
MV
451 << ":" << s
452 << endl;
453 if(OutStatusFd > 0)
454 write(OutStatusFd, status.str().c_str(), status.str().size());
455 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
456 std::clog << "send: '" << status.str() << "'" << endl;
457 }
458 if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
459 std::clog << "(parsed from dpkg) pkg: " << pkg
460 << " action: " << action << endl;
6191b008
MV
461}
462
463// DPkgPM::DoDpkgStatusFd /*{{{*/
464// ---------------------------------------------------------------------
465/*
466 */
09fa2df2 467void pkgDPkgPM::DoDpkgStatusFd(int statusfd, int OutStatusFd)
6191b008
MV
468{
469 char *p, *q;
470 int len;
471
472 len=read(statusfd, &dpkgbuf[dpkgbuf_pos], sizeof(dpkgbuf)-dpkgbuf_pos);
473 dpkgbuf_pos += len;
474 if(len <= 0)
475 return;
ceabc520 476
6191b008
MV
477 // process line by line if we have a buffer
478 p = q = dpkgbuf;
479 while((q=(char*)memchr(p, '\n', dpkgbuf+dpkgbuf_pos-p)) != NULL)
480 {
481 *q = 0;
09fa2df2 482 ProcessDpkgStatusLine(OutStatusFd, p);
6191b008
MV
483 p=q+1; // continue with next line
484 }
485
486 // now move the unprocessed bits (after the final \n that is now a 0x0)
487 // to the start and update dpkgbuf_pos
488 p = (char*)memrchr(dpkgbuf, 0, dpkgbuf_pos);
489 if(p == NULL)
490 return;
491
492 // we are interessted in the first char *after* 0x0
493 p++;
494
495 // move the unprocessed tail to the start and update pos
496 memmove(dpkgbuf, p, p-dpkgbuf);
497 dpkgbuf_pos = dpkgbuf+dpkgbuf_pos-p;
498}
499 /*}}}*/
ceabc520
MV
500
501
03e39e59
AL
502// DPkgPM::Go - Run the sequence /*{{{*/
503// ---------------------------------------------------------------------
75ef8f14
MV
504/* This globs the operations and calls dpkg
505 *
506 * If it is called with "OutStatusFd" set to a valid file descriptor
507 * apt will report the install progress over this fd. It maps the
508 * dpkg states a package goes through to human readable (and i10n-able)
509 * names and calculates a percentage for each step.
510*/
511bool pkgDPkgPM::Go(int OutStatusFd)
03e39e59 512{
6b8147b8
MZ
513 unsigned int MaxArgs = _config->FindI("Dpkg::MaxArgs",8*1024);
514 unsigned int MaxArgBytes = _config->FindI("Dpkg::MaxArgBytes",32*1024);
aff4e2f1 515
6dd55be7
AL
516 if (RunScripts("DPkg::Pre-Invoke") == false)
517 return false;
db0c350f
AL
518
519 if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
520 return false;
75ef8f14 521
75ef8f14
MV
522 // map the dpkg states to the operations that are performed
523 // (this is sorted in the same way as Item::Ops)
fb7bf91c 524 static const struct DpkgState DpkgStatesOpMap[][7] = {
75ef8f14
MV
525 // Install operation
526 {
1d52ce01
MV
527 {"half-installed", N_("Preparing %s")},
528 {"unpacked", N_("Unpacking %s") },
75ef8f14
MV
529 {NULL, NULL}
530 },
531 // Configure operation
532 {
1d52ce01
MV
533 {"unpacked",N_("Preparing to configure %s") },
534 {"half-configured", N_("Configuring %s") },
fb7bf91c
IJ
535 {"triggers-awaited", N_("Processing triggers for %s") },
536 {"triggers-pending", N_("Processing triggers for %s") },
537 {"half-configured", N_("Configuring %s") },
1d52ce01 538 { "installed", N_("Installed %s")},
75ef8f14
MV
539 {NULL, NULL}
540 },
541 // Remove operation
542 {
1d52ce01 543 {"half-configured", N_("Preparing for removal of %s")},
fb7bf91c
IJ
544 {"triggers-awaited", N_("Preparing for removal of %s")},
545 {"triggers-pending", N_("Preparing for removal of %s")},
1d52ce01
MV
546 {"half-installed", N_("Removing %s")},
547 {"config-files", N_("Removed %s")},
75ef8f14
MV
548 {NULL, NULL}
549 },
550 // Purge operation
551 {
1d52ce01
MV
552 {"config-files", N_("Preparing to completely remove %s")},
553 {"not-installed", N_("Completely removed %s")},
75ef8f14
MV
554 {NULL, NULL}
555 },
556 };
db0c350f 557
75ef8f14
MV
558 // init the PackageOps map, go over the list of packages that
559 // that will be [installed|configured|removed|purged] and add
560 // them to the PackageOps map (the dpkg states it goes through)
561 // and the PackageOpsTranslations (human readable strings)
562 for (vector<Item>::iterator I = List.begin(); I != List.end();I++)
563 {
564 string name = (*I).Pkg.Name();
565 PackageOpsDone[name] = 0;
566 for(int i=0; (DpkgStatesOpMap[(*I).Op][i]).state != NULL; i++)
567 {
568 PackageOps[name].push_back(DpkgStatesOpMap[(*I).Op][i]);
ff56e980 569 PackagesTotal++;
75ef8f14
MV
570 }
571 }
572
ff56e980
MV
573 // create log
574 string logdir = _config->FindDir("Dir::Log");
575 if(not FileExists(logdir))
576 return _error->Error(_("Directory '%s' missing"), logdir.c_str());
577 string logfile_name = flCombine(logdir,
8da1f029 578 _config->Find("Dir::Log::Terminal"));
8da1f029
MV
579 if (!logfile_name.empty())
580 {
581 term_out = fopen(logfile_name.c_str(),"a");
582 chmod(logfile_name.c_str(), 0600);
583 // output current time
584 char outstr[200];
585 time_t t = time(NULL);
586 struct tm *tmp = localtime(&t);
587 strftime(outstr, sizeof(outstr), "%F %T", tmp);
588 fprintf(term_out, "\nLog started: ");
589 fprintf(term_out, outstr);
590 fprintf(term_out, "\n");
591 }
ff56e980 592
75ef8f14 593 // this loop is runs once per operation
03e39e59
AL
594 for (vector<Item>::iterator I = List.begin(); I != List.end();)
595 {
596 vector<Item>::iterator J = I;
597 for (; J != List.end() && J->Op == I->Op; J++);
30e1eab5 598
03e39e59 599 // Generate the argument list
aff4e2f1
AL
600 const char *Args[MaxArgs + 50];
601 if (J - I > (signed)MaxArgs)
602 J = I + MaxArgs;
03e39e59 603
30e1eab5
AL
604 unsigned int n = 0;
605 unsigned long Size = 0;
43b3b626 606 string Tmp = _config->Find("Dir::Bin::dpkg","dpkg");
50914ffa 607 Args[n++] = Tmp.c_str();
30e1eab5 608 Size += strlen(Args[n-1]);
03e39e59 609
6dd55be7
AL
610 // Stick in any custom dpkg options
611 Configuration::Item const *Opts = _config->Tree("DPkg::Options");
612 if (Opts != 0)
613 {
614 Opts = Opts->Child;
615 for (; Opts != 0; Opts = Opts->Next)
616 {
617 if (Opts->Value.empty() == true)
618 continue;
619 Args[n++] = Opts->Value.c_str();
620 Size += Opts->Value.length();
621 }
622 }
623
007dc9e0 624 char status_fd_buf[20];
75ef8f14
MV
625 int fd[2];
626 pipe(fd);
627
628 Args[n++] = "--status-fd";
629 Size += strlen(Args[n-1]);
630 snprintf(status_fd_buf,sizeof(status_fd_buf),"%i", fd[1]);
631 Args[n++] = status_fd_buf;
632 Size += strlen(Args[n-1]);
007dc9e0 633
03e39e59
AL
634 switch (I->Op)
635 {
636 case Item::Remove:
637 Args[n++] = "--force-depends";
30e1eab5 638 Size += strlen(Args[n-1]);
03e39e59 639 Args[n++] = "--force-remove-essential";
30e1eab5 640 Size += strlen(Args[n-1]);
03e39e59 641 Args[n++] = "--remove";
30e1eab5 642 Size += strlen(Args[n-1]);
03e39e59
AL
643 break;
644
fc4b5c9f
AL
645 case Item::Purge:
646 Args[n++] = "--force-depends";
647 Size += strlen(Args[n-1]);
648 Args[n++] = "--force-remove-essential";
649 Size += strlen(Args[n-1]);
650 Args[n++] = "--purge";
651 Size += strlen(Args[n-1]);
652 break;
653
03e39e59
AL
654 case Item::Configure:
655 Args[n++] = "--configure";
30e1eab5 656 Size += strlen(Args[n-1]);
03e39e59
AL
657 break;
658
659 case Item::Install:
660 Args[n++] = "--unpack";
30e1eab5 661 Size += strlen(Args[n-1]);
857a1d4a
MV
662 Args[n++] = "--auto-deconfigure";
663 Size += strlen(Args[n-1]);
03e39e59
AL
664 break;
665 }
666
667 // Write in the file or package names
668 if (I->Op == Item::Install)
30e1eab5 669 {
aff4e2f1 670 for (;I != J && Size < MaxArgBytes; I++)
30e1eab5 671 {
cf544e14
AL
672 if (I->File[0] != '/')
673 return _error->Error("Internal Error, Pathname to install is not absolute '%s'",I->File.c_str());
03e39e59 674 Args[n++] = I->File.c_str();
30e1eab5
AL
675 Size += strlen(Args[n-1]);
676 }
677 }
03e39e59 678 else
30e1eab5 679 {
aff4e2f1 680 for (;I != J && Size < MaxArgBytes; I++)
30e1eab5 681 {
03e39e59 682 Args[n++] = I->Pkg.Name();
30e1eab5
AL
683 Size += strlen(Args[n-1]);
684 }
685 }
03e39e59 686 Args[n] = 0;
30e1eab5
AL
687 J = I;
688
689 if (_config->FindB("Debug::pkgDPkgPM",false) == true)
690 {
691 for (unsigned int k = 0; k != n; k++)
692 clog << Args[k] << ' ';
693 clog << endl;
694 continue;
695 }
03e39e59 696
03e39e59
AL
697 cout << flush;
698 clog << flush;
699 cerr << flush;
700
701 /* Mask off sig int/quit. We do this because dpkg also does when
702 it forks scripts. What happens is that when you hit ctrl-c it sends
703 it to all processes in the group. Since dpkg ignores the signal
704 it doesn't die but we do! So we must also ignore it */
7f9a6360
AL
705 sighandler_t old_SIGQUIT = signal(SIGQUIT,SIG_IGN);
706 sighandler_t old_SIGINT = signal(SIGINT,SIG_IGN);
d8cb4aa4
MV
707
708 struct termios tt;
709 struct winsize win;
710 int master;
711 int slave;
712
ceabc520 713 // FIXME: setup sensible signal handling (*ick*)
d8cb4aa4
MV
714 tcgetattr(0, &tt);
715 ioctl(0, TIOCGWINSZ, (char *)&win);
090c6566
MV
716 if (openpty(&master, &slave, NULL, &tt, &win) < 0)
717 {
a4cf3665
MV
718 const char *s = _("Can not write log, openpty() "
719 "failed (/dev/pts not mounted?)\n");
720 fprintf(stderr, "%s",s);
721 fprintf(term_out, "%s",s);
722 master = slave = -1;
723 } else {
724 struct termios rtt;
725 rtt = tt;
726 cfmakeraw(&rtt);
727 rtt.c_lflag &= ~ECHO;
728 tcsetattr(0, TCSAFLUSH, &rtt);
d8cb4aa4
MV
729 }
730
75ef8f14 731 // Fork dpkg
007dc9e0 732 pid_t Child;
75ef8f14
MV
733 _config->Set("APT::Keep-Fds::",fd[1]);
734 Child = ExecFork();
6dd55be7 735
03e39e59
AL
736 // This is the child
737 if (Child == 0)
738 {
a4cf3665
MV
739 if(slave >= 0 && master >= 0)
740 {
741 setsid();
742 ioctl(slave, TIOCSCTTY, 0);
743 close(master);
744 dup2(slave, 0);
745 dup2(slave, 1);
746 dup2(slave, 2);
747 close(slave);
748 }
75ef8f14 749 close(fd[0]); // close the read end of the pipe
d8cb4aa4 750
cf544e14 751 if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
0dbb95d8 752 _exit(100);
03e39e59 753
421ff807 754 if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
8b5fe26c
AL
755 {
756 int Flags,dummy;
757 if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
758 _exit(100);
759
760 // Discard everything in stdin before forking dpkg
761 if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
762 _exit(100);
763
764 while (read(STDIN_FILENO,&dummy,1) == 1);
765
766 if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
767 _exit(100);
768 }
d8cb4aa4
MV
769
770
03e39e59
AL
771 /* No Job Control Stop Env is a magic dpkg var that prevents it
772 from using sigstop */
101030ab 773 putenv("DPKG_NO_TSTP=yes");
d568ed2d 774 execvp(Args[0],(char **)Args);
03e39e59 775 cerr << "Could not exec dpkg!" << endl;
0dbb95d8 776 _exit(100);
03e39e59
AL
777 }
778
75ef8f14
MV
779 // clear the Keep-Fd again
780 _config->Clear("APT::Keep-Fds",fd[1]);
781
03e39e59
AL
782 // Wait for dpkg
783 int Status = 0;
75ef8f14
MV
784
785 // we read from dpkg here
786 int _dpkgin = fd[0];
75ef8f14
MV
787 close(fd[1]); // close the write end of the pipe
788
75ef8f14
MV
789 // the result of the waitpid call
790 int res;
a4cf3665
MV
791 if(slave > 0)
792 close(slave);
75ef8f14 793
97efd303 794 // setups fds
090c6566
MV
795 fd_set rfds;
796 struct timeval tv;
797 int select_ret;
75ef8f14
MV
798 while ((res=waitpid(Child,&Status, WNOHANG)) != Child) {
799 if(res < 0) {
800 // FIXME: move this to a function or something, looks ugly here
801 // error handling, waitpid returned -1
802 if (errno == EINTR)
803 continue;
804 RunScripts("DPkg::Post-Invoke");
805
806 // Restore sig int/quit
807 signal(SIGQUIT,old_SIGQUIT);
808 signal(SIGINT,old_SIGINT);
809 return _error->Errno("waitpid","Couldn't wait for subprocess");
810 }
75ef8f14 811
d8cb4aa4 812 // wait for input or output here
955a6ddb
MV
813 FD_ZERO(&rfds);
814 FD_SET(0, &rfds);
815 FD_SET(_dpkgin, &rfds);
a4cf3665
MV
816 if(master >= 0)
817 FD_SET(master, &rfds);
090c6566
MV
818 tv.tv_sec = 1;
819 tv.tv_usec = 0;
7fdafa0f 820 select_ret = select(max(master, _dpkgin)+1, &rfds, NULL, NULL, &tv);
090c6566
MV
821 if (select_ret < 0)
822 std::cerr << "Error in select()" << std::endl;
823 else if (select_ret == 0)
75ef8f14 824 continue;
75ef8f14 825
a4cf3665 826 if(master >= 0 && FD_ISSET(master, &rfds))
1ba38171 827 DoTerminalPty(master);
a4cf3665 828 if(master >= 0 && FD_ISSET(0, &rfds))
955a6ddb 829 DoStdin(master);
955a6ddb 830 if(FD_ISSET(_dpkgin, &rfds))
09fa2df2 831 DoDpkgStatusFd(_dpkgin, OutStatusFd);
03e39e59 832 }
75ef8f14 833 close(_dpkgin);
03e39e59
AL
834
835 // Restore sig int/quit
7f9a6360
AL
836 signal(SIGQUIT,old_SIGQUIT);
837 signal(SIGINT,old_SIGINT);
d8cb4aa4 838
a4cf3665
MV
839 if(master >= 0 && slave >= 0)
840 tcsetattr(0, TCSAFLUSH, &tt);
6dd55be7
AL
841
842 // Check for an error code.
843 if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
844 {
c70496f9
MV
845 // if it was set to "keep-dpkg-runing" then we won't return
846 // here but keep the loop going and just report it as a error
847 // for later
848 bool stopOnError = _config->FindB("Dpkg::StopOnError",true);
f956efb4 849
c70496f9
MV
850 if(stopOnError)
851 RunScripts("DPkg::Post-Invoke");
852
853 if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
854 _error->Error("Sub-process %s received a segmentation fault.",Args[0]);
855 else if (WIFEXITED(Status) != 0)
856 _error->Error("Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
857 else
858 _error->Error("Sub-process %s exited unexpectedly",Args[0]);
859
ff56e980
MV
860 if(stopOnError)
861 {
b3aac1bb
MV
862 if(term_out)
863 fclose(term_out);
c70496f9 864 return false;
ff56e980 865 }
6dd55be7 866 }
03e39e59 867 }
b3aac1bb
MV
868 if(term_out)
869 fclose(term_out);
6dd55be7
AL
870
871 if (RunScripts("DPkg::Post-Invoke") == false)
872 return false;
03e39e59
AL
873 return true;
874}
875 /*}}}*/
281daf46
AL
876// pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
877// ---------------------------------------------------------------------
878/* */
879void pkgDPkgPM::Reset()
880{
881 List.erase(List.begin(),List.end());
882}
883 /*}}}*/
5e457a93
MV
884// pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
885// ---------------------------------------------------------------------
886/* */
887void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
888{
889 string pkgname, reportfile, srcpkgname, pkgver, arch;
890 string::size_type pos;
891 FILE *report;
892
893 if (_config->FindB("Dpkg::ApportFailureReport",true) == false)
894 return;
895
896 // only report the first error if we are in StopOnError=false mode
897 // to prevent bogus reports
898 if((_config->FindB("Dpkg::StopOnError",true) == false) && pkgFailures > 1)
899 return;
900
901 // get the pkgname and reportfile
902 pkgname = flNotDir(pkgpath);
25ffa4e8 903 pos = pkgname.find('_');
5e457a93 904 if(pos != string::npos)
25ffa4e8 905 pkgname = pkgname.substr(0, pos);
5e457a93
MV
906
907 // find the package versin and source package name
908 pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
909 if (Pkg.end() == true)
910 return;
911 pkgCache::VerIterator Ver = Cache.GetCandidateVer(Pkg);
912 pkgver = Ver.VerStr();
913 if (Ver.end() == true)
914 return;
915 pkgRecords Recs(Cache);
916 pkgRecords::Parser &Parse = Recs.Lookup(Ver.FileList());
917 srcpkgname = Parse.SourcePkg();
918 if(srcpkgname.empty())
919 srcpkgname = pkgname;
920
921 // if the file exists already, we check:
922 // - if it was reported already (touched by apport).
923 // If not, we do nothing, otherwise
924 // we overwrite it. This is the same behaviour as apport
925 // - if we have a report with the same pkgversion already
926 // then we skip it
927 reportfile = flCombine("/var/crash",pkgname+".0.crash");
928 if(FileExists(reportfile))
929 {
930 struct stat buf;
931 char strbuf[255];
932
933 // check atime/mtime
934 stat(reportfile.c_str(), &buf);
935 if(buf.st_mtime > buf.st_atime)
936 return;
937
938 // check if the existing report is the same version
939 report = fopen(reportfile.c_str(),"r");
940 while(fgets(strbuf, sizeof(strbuf), report) != NULL)
941 {
942 if(strstr(strbuf,"Package:") == strbuf)
943 {
944 char pkgname[255], version[255];
945 if(sscanf(strbuf, "Package: %s %s", pkgname, version) == 2)
946 if(strcmp(pkgver.c_str(), version) == 0)
947 {
948 fclose(report);
949 return;
950 }
951 }
952 }
953 fclose(report);
954 }
955
956 // now write the report
957 arch = _config->Find("APT::Architecture");
958 report = fopen(reportfile.c_str(),"w");
959 if(report == NULL)
960 return;
961 if(_config->FindB("DPkgPM::InitialReportOnly",false) == true)
962 chmod(reportfile.c_str(), 0);
963 else
964 chmod(reportfile.c_str(), 0600);
965 fprintf(report, "ProblemType: Package\n");
966 fprintf(report, "Architecture: %s\n", arch.c_str());
967 time_t now = time(NULL);
968 fprintf(report, "Date: %s" , ctime(&now));
969 fprintf(report, "Package: %s %s\n", pkgname.c_str(), pkgver.c_str());
970 fprintf(report, "SourcePackage: %s\n", srcpkgname.c_str());
971 fprintf(report, "ErrorMessage:\n %s\n", errormsg);
8ecd1fed
MV
972
973 // ensure that the log is flushed
974 if(term_out)
975 fflush(term_out);
976
977 // attach terminal log it if we have it
978 string logfile_name = _config->FindFile("Dir::Log::Terminal");
979 if (!logfile_name.empty())
980 {
981 FILE *log = NULL;
982 char buf[1024];
983
984 fprintf(report, "DpkgTerminalLog:\n");
985 log = fopen(logfile_name.c_str(),"r");
986 if(log != NULL)
987 {
988 while( fgets(buf, sizeof(buf), log) != NULL)
989 fprintf(report, " %s", buf);
990 fclose(log);
991 }
992 }
5e457a93
MV
993 fclose(report);
994}
995 /*}}}*/