]> git.saurik.com Git - apt.git/blame - apt-pkg/deb/dpkgpm.cc
* methods/copy.cc:
[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)
524 static const struct DpkgState DpkgStatesOpMap[][5] = {
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") },
535 { "installed", N_("Installed %s")},
75ef8f14
MV
536 {NULL, NULL}
537 },
538 // Remove operation
539 {
1d52ce01
MV
540 {"half-configured", N_("Preparing for removal of %s")},
541 {"half-installed", N_("Removing %s")},
542 {"config-files", N_("Removed %s")},
75ef8f14
MV
543 {NULL, NULL}
544 },
545 // Purge operation
546 {
1d52ce01
MV
547 {"config-files", N_("Preparing to completely remove %s")},
548 {"not-installed", N_("Completely removed %s")},
75ef8f14
MV
549 {NULL, NULL}
550 },
551 };
db0c350f 552
75ef8f14
MV
553 // init the PackageOps map, go over the list of packages that
554 // that will be [installed|configured|removed|purged] and add
555 // them to the PackageOps map (the dpkg states it goes through)
556 // and the PackageOpsTranslations (human readable strings)
557 for (vector<Item>::iterator I = List.begin(); I != List.end();I++)
558 {
559 string name = (*I).Pkg.Name();
560 PackageOpsDone[name] = 0;
561 for(int i=0; (DpkgStatesOpMap[(*I).Op][i]).state != NULL; i++)
562 {
563 PackageOps[name].push_back(DpkgStatesOpMap[(*I).Op][i]);
ff56e980 564 PackagesTotal++;
75ef8f14
MV
565 }
566 }
567
ff56e980
MV
568 // create log
569 string logdir = _config->FindDir("Dir::Log");
570 if(not FileExists(logdir))
571 return _error->Error(_("Directory '%s' missing"), logdir.c_str());
572 string logfile_name = flCombine(logdir,
8da1f029 573 _config->Find("Dir::Log::Terminal"));
8da1f029
MV
574 if (!logfile_name.empty())
575 {
576 term_out = fopen(logfile_name.c_str(),"a");
577 chmod(logfile_name.c_str(), 0600);
578 // output current time
579 char outstr[200];
580 time_t t = time(NULL);
581 struct tm *tmp = localtime(&t);
582 strftime(outstr, sizeof(outstr), "%F %T", tmp);
583 fprintf(term_out, "\nLog started: ");
584 fprintf(term_out, outstr);
585 fprintf(term_out, "\n");
586 }
ff56e980 587
75ef8f14 588 // this loop is runs once per operation
03e39e59
AL
589 for (vector<Item>::iterator I = List.begin(); I != List.end();)
590 {
591 vector<Item>::iterator J = I;
592 for (; J != List.end() && J->Op == I->Op; J++);
30e1eab5 593
03e39e59 594 // Generate the argument list
aff4e2f1
AL
595 const char *Args[MaxArgs + 50];
596 if (J - I > (signed)MaxArgs)
597 J = I + MaxArgs;
03e39e59 598
30e1eab5
AL
599 unsigned int n = 0;
600 unsigned long Size = 0;
43b3b626 601 string Tmp = _config->Find("Dir::Bin::dpkg","dpkg");
50914ffa 602 Args[n++] = Tmp.c_str();
30e1eab5 603 Size += strlen(Args[n-1]);
03e39e59 604
6dd55be7
AL
605 // Stick in any custom dpkg options
606 Configuration::Item const *Opts = _config->Tree("DPkg::Options");
607 if (Opts != 0)
608 {
609 Opts = Opts->Child;
610 for (; Opts != 0; Opts = Opts->Next)
611 {
612 if (Opts->Value.empty() == true)
613 continue;
614 Args[n++] = Opts->Value.c_str();
615 Size += Opts->Value.length();
616 }
617 }
618
007dc9e0 619 char status_fd_buf[20];
75ef8f14
MV
620 int fd[2];
621 pipe(fd);
622
623 Args[n++] = "--status-fd";
624 Size += strlen(Args[n-1]);
625 snprintf(status_fd_buf,sizeof(status_fd_buf),"%i", fd[1]);
626 Args[n++] = status_fd_buf;
627 Size += strlen(Args[n-1]);
007dc9e0 628
03e39e59
AL
629 switch (I->Op)
630 {
631 case Item::Remove:
632 Args[n++] = "--force-depends";
30e1eab5 633 Size += strlen(Args[n-1]);
03e39e59 634 Args[n++] = "--force-remove-essential";
30e1eab5 635 Size += strlen(Args[n-1]);
03e39e59 636 Args[n++] = "--remove";
30e1eab5 637 Size += strlen(Args[n-1]);
03e39e59
AL
638 break;
639
fc4b5c9f
AL
640 case Item::Purge:
641 Args[n++] = "--force-depends";
642 Size += strlen(Args[n-1]);
643 Args[n++] = "--force-remove-essential";
644 Size += strlen(Args[n-1]);
645 Args[n++] = "--purge";
646 Size += strlen(Args[n-1]);
647 break;
648
03e39e59
AL
649 case Item::Configure:
650 Args[n++] = "--configure";
30e1eab5 651 Size += strlen(Args[n-1]);
03e39e59
AL
652 break;
653
654 case Item::Install:
655 Args[n++] = "--unpack";
30e1eab5 656 Size += strlen(Args[n-1]);
857a1d4a
MV
657 Args[n++] = "--auto-deconfigure";
658 Size += strlen(Args[n-1]);
03e39e59
AL
659 break;
660 }
661
662 // Write in the file or package names
663 if (I->Op == Item::Install)
30e1eab5 664 {
aff4e2f1 665 for (;I != J && Size < MaxArgBytes; I++)
30e1eab5 666 {
cf544e14
AL
667 if (I->File[0] != '/')
668 return _error->Error("Internal Error, Pathname to install is not absolute '%s'",I->File.c_str());
03e39e59 669 Args[n++] = I->File.c_str();
30e1eab5
AL
670 Size += strlen(Args[n-1]);
671 }
672 }
03e39e59 673 else
30e1eab5 674 {
aff4e2f1 675 for (;I != J && Size < MaxArgBytes; I++)
30e1eab5 676 {
03e39e59 677 Args[n++] = I->Pkg.Name();
30e1eab5
AL
678 Size += strlen(Args[n-1]);
679 }
680 }
03e39e59 681 Args[n] = 0;
30e1eab5
AL
682 J = I;
683
684 if (_config->FindB("Debug::pkgDPkgPM",false) == true)
685 {
686 for (unsigned int k = 0; k != n; k++)
687 clog << Args[k] << ' ';
688 clog << endl;
689 continue;
690 }
03e39e59 691
03e39e59
AL
692 cout << flush;
693 clog << flush;
694 cerr << flush;
695
696 /* Mask off sig int/quit. We do this because dpkg also does when
697 it forks scripts. What happens is that when you hit ctrl-c it sends
698 it to all processes in the group. Since dpkg ignores the signal
699 it doesn't die but we do! So we must also ignore it */
7f9a6360
AL
700 sighandler_t old_SIGQUIT = signal(SIGQUIT,SIG_IGN);
701 sighandler_t old_SIGINT = signal(SIGINT,SIG_IGN);
d8cb4aa4
MV
702
703 struct termios tt;
704 struct winsize win;
705 int master;
706 int slave;
707
ceabc520 708 // FIXME: setup sensible signal handling (*ick*)
d8cb4aa4
MV
709 tcgetattr(0, &tt);
710 ioctl(0, TIOCGWINSZ, (char *)&win);
090c6566
MV
711 if (openpty(&master, &slave, NULL, &tt, &win) < 0)
712 {
a4cf3665
MV
713 const char *s = _("Can not write log, openpty() "
714 "failed (/dev/pts not mounted?)\n");
715 fprintf(stderr, "%s",s);
716 fprintf(term_out, "%s",s);
717 master = slave = -1;
718 } else {
719 struct termios rtt;
720 rtt = tt;
721 cfmakeraw(&rtt);
722 rtt.c_lflag &= ~ECHO;
723 tcsetattr(0, TCSAFLUSH, &rtt);
d8cb4aa4
MV
724 }
725
75ef8f14 726 // Fork dpkg
007dc9e0 727 pid_t Child;
75ef8f14
MV
728 _config->Set("APT::Keep-Fds::",fd[1]);
729 Child = ExecFork();
6dd55be7 730
03e39e59
AL
731 // This is the child
732 if (Child == 0)
733 {
a4cf3665
MV
734 if(slave >= 0 && master >= 0)
735 {
736 setsid();
737 ioctl(slave, TIOCSCTTY, 0);
738 close(master);
739 dup2(slave, 0);
740 dup2(slave, 1);
741 dup2(slave, 2);
742 close(slave);
743 }
75ef8f14 744 close(fd[0]); // close the read end of the pipe
d8cb4aa4 745
cf544e14 746 if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
0dbb95d8 747 _exit(100);
03e39e59 748
421ff807 749 if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
8b5fe26c
AL
750 {
751 int Flags,dummy;
752 if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
753 _exit(100);
754
755 // Discard everything in stdin before forking dpkg
756 if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
757 _exit(100);
758
759 while (read(STDIN_FILENO,&dummy,1) == 1);
760
761 if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
762 _exit(100);
763 }
d8cb4aa4
MV
764
765
03e39e59
AL
766 /* No Job Control Stop Env is a magic dpkg var that prevents it
767 from using sigstop */
101030ab 768 putenv("DPKG_NO_TSTP=yes");
d568ed2d 769 execvp(Args[0],(char **)Args);
03e39e59 770 cerr << "Could not exec dpkg!" << endl;
0dbb95d8 771 _exit(100);
03e39e59
AL
772 }
773
75ef8f14
MV
774 // clear the Keep-Fd again
775 _config->Clear("APT::Keep-Fds",fd[1]);
776
03e39e59
AL
777 // Wait for dpkg
778 int Status = 0;
75ef8f14
MV
779
780 // we read from dpkg here
781 int _dpkgin = fd[0];
75ef8f14
MV
782 close(fd[1]); // close the write end of the pipe
783
75ef8f14
MV
784 // the result of the waitpid call
785 int res;
a4cf3665
MV
786 if(slave > 0)
787 close(slave);
75ef8f14 788
97efd303 789 // setups fds
090c6566
MV
790 fd_set rfds;
791 struct timeval tv;
792 int select_ret;
75ef8f14
MV
793 while ((res=waitpid(Child,&Status, WNOHANG)) != Child) {
794 if(res < 0) {
795 // FIXME: move this to a function or something, looks ugly here
796 // error handling, waitpid returned -1
797 if (errno == EINTR)
798 continue;
799 RunScripts("DPkg::Post-Invoke");
800
801 // Restore sig int/quit
802 signal(SIGQUIT,old_SIGQUIT);
803 signal(SIGINT,old_SIGINT);
804 return _error->Errno("waitpid","Couldn't wait for subprocess");
805 }
75ef8f14 806
d8cb4aa4 807 // wait for input or output here
955a6ddb
MV
808 FD_ZERO(&rfds);
809 FD_SET(0, &rfds);
810 FD_SET(_dpkgin, &rfds);
a4cf3665
MV
811 if(master >= 0)
812 FD_SET(master, &rfds);
090c6566
MV
813 tv.tv_sec = 1;
814 tv.tv_usec = 0;
7fdafa0f 815 select_ret = select(max(master, _dpkgin)+1, &rfds, NULL, NULL, &tv);
090c6566
MV
816 if (select_ret < 0)
817 std::cerr << "Error in select()" << std::endl;
818 else if (select_ret == 0)
75ef8f14 819 continue;
75ef8f14 820
a4cf3665 821 if(master >= 0 && FD_ISSET(master, &rfds))
1ba38171 822 DoTerminalPty(master);
a4cf3665 823 if(master >= 0 && FD_ISSET(0, &rfds))
955a6ddb 824 DoStdin(master);
955a6ddb 825 if(FD_ISSET(_dpkgin, &rfds))
09fa2df2 826 DoDpkgStatusFd(_dpkgin, OutStatusFd);
03e39e59 827 }
75ef8f14 828 close(_dpkgin);
03e39e59
AL
829
830 // Restore sig int/quit
7f9a6360
AL
831 signal(SIGQUIT,old_SIGQUIT);
832 signal(SIGINT,old_SIGINT);
d8cb4aa4 833
a4cf3665
MV
834 if(master >= 0 && slave >= 0)
835 tcsetattr(0, TCSAFLUSH, &tt);
6dd55be7
AL
836
837 // Check for an error code.
838 if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
839 {
c70496f9
MV
840 // if it was set to "keep-dpkg-runing" then we won't return
841 // here but keep the loop going and just report it as a error
842 // for later
843 bool stopOnError = _config->FindB("Dpkg::StopOnError",true);
f956efb4 844
c70496f9
MV
845 if(stopOnError)
846 RunScripts("DPkg::Post-Invoke");
847
848 if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
849 _error->Error("Sub-process %s received a segmentation fault.",Args[0]);
850 else if (WIFEXITED(Status) != 0)
851 _error->Error("Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
852 else
853 _error->Error("Sub-process %s exited unexpectedly",Args[0]);
854
ff56e980
MV
855 if(stopOnError)
856 {
b3aac1bb
MV
857 if(term_out)
858 fclose(term_out);
c70496f9 859 return false;
ff56e980 860 }
6dd55be7 861 }
03e39e59 862 }
b3aac1bb
MV
863 if(term_out)
864 fclose(term_out);
6dd55be7
AL
865
866 if (RunScripts("DPkg::Post-Invoke") == false)
867 return false;
03e39e59
AL
868 return true;
869}
870 /*}}}*/
281daf46
AL
871// pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
872// ---------------------------------------------------------------------
873/* */
874void pkgDPkgPM::Reset()
875{
876 List.erase(List.begin(),List.end());
877}
878 /*}}}*/
5e457a93
MV
879// pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
880// ---------------------------------------------------------------------
881/* */
882void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
883{
884 string pkgname, reportfile, srcpkgname, pkgver, arch;
885 string::size_type pos;
886 FILE *report;
887
888 if (_config->FindB("Dpkg::ApportFailureReport",true) == false)
889 return;
890
891 // only report the first error if we are in StopOnError=false mode
892 // to prevent bogus reports
893 if((_config->FindB("Dpkg::StopOnError",true) == false) && pkgFailures > 1)
894 return;
895
896 // get the pkgname and reportfile
897 pkgname = flNotDir(pkgpath);
25ffa4e8 898 pos = pkgname.find('_');
5e457a93 899 if(pos != string::npos)
25ffa4e8 900 pkgname = pkgname.substr(0, pos);
5e457a93
MV
901
902 // find the package versin and source package name
903 pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
904 if (Pkg.end() == true)
905 return;
906 pkgCache::VerIterator Ver = Cache.GetCandidateVer(Pkg);
907 pkgver = Ver.VerStr();
908 if (Ver.end() == true)
909 return;
910 pkgRecords Recs(Cache);
911 pkgRecords::Parser &Parse = Recs.Lookup(Ver.FileList());
912 srcpkgname = Parse.SourcePkg();
913 if(srcpkgname.empty())
914 srcpkgname = pkgname;
915
916 // if the file exists already, we check:
917 // - if it was reported already (touched by apport).
918 // If not, we do nothing, otherwise
919 // we overwrite it. This is the same behaviour as apport
920 // - if we have a report with the same pkgversion already
921 // then we skip it
922 reportfile = flCombine("/var/crash",pkgname+".0.crash");
923 if(FileExists(reportfile))
924 {
925 struct stat buf;
926 char strbuf[255];
927
928 // check atime/mtime
929 stat(reportfile.c_str(), &buf);
930 if(buf.st_mtime > buf.st_atime)
931 return;
932
933 // check if the existing report is the same version
934 report = fopen(reportfile.c_str(),"r");
935 while(fgets(strbuf, sizeof(strbuf), report) != NULL)
936 {
937 if(strstr(strbuf,"Package:") == strbuf)
938 {
939 char pkgname[255], version[255];
940 if(sscanf(strbuf, "Package: %s %s", pkgname, version) == 2)
941 if(strcmp(pkgver.c_str(), version) == 0)
942 {
943 fclose(report);
944 return;
945 }
946 }
947 }
948 fclose(report);
949 }
950
951 // now write the report
952 arch = _config->Find("APT::Architecture");
953 report = fopen(reportfile.c_str(),"w");
954 if(report == NULL)
955 return;
956 if(_config->FindB("DPkgPM::InitialReportOnly",false) == true)
957 chmod(reportfile.c_str(), 0);
958 else
959 chmod(reportfile.c_str(), 0600);
960 fprintf(report, "ProblemType: Package\n");
961 fprintf(report, "Architecture: %s\n", arch.c_str());
962 time_t now = time(NULL);
963 fprintf(report, "Date: %s" , ctime(&now));
964 fprintf(report, "Package: %s %s\n", pkgname.c_str(), pkgver.c_str());
965 fprintf(report, "SourcePackage: %s\n", srcpkgname.c_str());
966 fprintf(report, "ErrorMessage:\n %s\n", errormsg);
8ecd1fed
MV
967
968 // ensure that the log is flushed
969 if(term_out)
970 fflush(term_out);
971
972 // attach terminal log it if we have it
973 string logfile_name = _config->FindFile("Dir::Log::Terminal");
974 if (!logfile_name.empty())
975 {
976 FILE *log = NULL;
977 char buf[1024];
978
979 fprintf(report, "DpkgTerminalLog:\n");
980 log = fopen(logfile_name.c_str(),"r");
981 if(log != NULL)
982 {
983 while( fgets(buf, sizeof(buf), log) != NULL)
984 fprintf(report, " %s", buf);
985 fclose(log);
986 }
987 }
5e457a93
MV
988 fclose(report);
989}
990 /*}}}*/