dpkgpm.cc 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: dpkgpm.cc,v 1.28 2004/01/27 02:25:01 mdz Exp $
  4. /* ######################################################################
  5. DPKG Package Manager - Provide an interface to dpkg
  6. ##################################################################### */
  7. /*}}}*/
  8. // Includes /*{{{*/
  9. #include <apt-pkg/dpkgpm.h>
  10. #include <apt-pkg/error.h>
  11. #include <apt-pkg/configuration.h>
  12. #include <apt-pkg/depcache.h>
  13. #include <apt-pkg/strutl.h>
  14. #include <unistd.h>
  15. #include <stdlib.h>
  16. #include <fcntl.h>
  17. #include <sys/select.h>
  18. #include <sys/types.h>
  19. #include <sys/wait.h>
  20. #include <signal.h>
  21. #include <errno.h>
  22. #include <stdio.h>
  23. #include <sstream>
  24. #include <map>
  25. #include <termios.h>
  26. #include <unistd.h>
  27. #include <sys/ioctl.h>
  28. #include <pty.h>
  29. #include <config.h>
  30. #include <apti18n.h>
  31. /*}}}*/
  32. using namespace std;
  33. // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
  34. // ---------------------------------------------------------------------
  35. /* */
  36. pkgDPkgPM::pkgDPkgPM(pkgDepCache *Cache)
  37. : pkgPackageManager(Cache), dpkgbuf_pos(0), PackagesTotal(0), PackagesDone(0)
  38. {
  39. }
  40. /*}}}*/
  41. // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
  42. // ---------------------------------------------------------------------
  43. /* */
  44. pkgDPkgPM::~pkgDPkgPM()
  45. {
  46. }
  47. /*}}}*/
  48. // DPkgPM::Install - Install a package /*{{{*/
  49. // ---------------------------------------------------------------------
  50. /* Add an install operation to the sequence list */
  51. bool pkgDPkgPM::Install(PkgIterator Pkg,string File)
  52. {
  53. if (File.empty() == true || Pkg.end() == true)
  54. return _error->Error("Internal Error, No file name for %s",Pkg.Name());
  55. List.push_back(Item(Item::Install,Pkg,File));
  56. return true;
  57. }
  58. /*}}}*/
  59. // DPkgPM::Configure - Configure a package /*{{{*/
  60. // ---------------------------------------------------------------------
  61. /* Add a configure operation to the sequence list */
  62. bool pkgDPkgPM::Configure(PkgIterator Pkg)
  63. {
  64. if (Pkg.end() == true)
  65. return false;
  66. List.push_back(Item(Item::Configure,Pkg));
  67. return true;
  68. }
  69. /*}}}*/
  70. // DPkgPM::Remove - Remove a package /*{{{*/
  71. // ---------------------------------------------------------------------
  72. /* Add a remove operation to the sequence list */
  73. bool pkgDPkgPM::Remove(PkgIterator Pkg,bool Purge)
  74. {
  75. if (Pkg.end() == true)
  76. return false;
  77. if (Purge == true)
  78. List.push_back(Item(Item::Purge,Pkg));
  79. else
  80. List.push_back(Item(Item::Remove,Pkg));
  81. return true;
  82. }
  83. /*}}}*/
  84. // DPkgPM::RunScripts - Run a set of scripts /*{{{*/
  85. // ---------------------------------------------------------------------
  86. /* This looks for a list of script sto run from the configuration file,
  87. each one is run with system from a forked child. */
  88. bool pkgDPkgPM::RunScripts(const char *Cnf)
  89. {
  90. Configuration::Item const *Opts = _config->Tree(Cnf);
  91. if (Opts == 0 || Opts->Child == 0)
  92. return true;
  93. Opts = Opts->Child;
  94. // Fork for running the system calls
  95. pid_t Child = ExecFork();
  96. // This is the child
  97. if (Child == 0)
  98. {
  99. if (chdir("/tmp/") != 0)
  100. _exit(100);
  101. unsigned int Count = 1;
  102. for (; Opts != 0; Opts = Opts->Next, Count++)
  103. {
  104. if (Opts->Value.empty() == true)
  105. continue;
  106. if (system(Opts->Value.c_str()) != 0)
  107. _exit(100+Count);
  108. }
  109. _exit(0);
  110. }
  111. // Wait for the child
  112. int Status = 0;
  113. while (waitpid(Child,&Status,0) != Child)
  114. {
  115. if (errno == EINTR)
  116. continue;
  117. return _error->Errno("waitpid","Couldn't wait for subprocess");
  118. }
  119. // Restore sig int/quit
  120. signal(SIGQUIT,SIG_DFL);
  121. signal(SIGINT,SIG_DFL);
  122. // Check for an error code.
  123. if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
  124. {
  125. unsigned int Count = WEXITSTATUS(Status);
  126. if (Count > 100)
  127. {
  128. Count -= 100;
  129. for (; Opts != 0 && Count != 1; Opts = Opts->Next, Count--);
  130. _error->Error("Problem executing scripts %s '%s'",Cnf,Opts->Value.c_str());
  131. }
  132. return _error->Error("Sub-process returned an error code");
  133. }
  134. return true;
  135. }
  136. /*}}}*/
  137. // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
  138. // ---------------------------------------------------------------------
  139. /* This is part of the helper script communication interface, it sends
  140. very complete information down to the other end of the pipe.*/
  141. bool pkgDPkgPM::SendV2Pkgs(FILE *F)
  142. {
  143. fprintf(F,"VERSION 2\n");
  144. /* Write out all of the configuration directives by walking the
  145. configuration tree */
  146. const Configuration::Item *Top = _config->Tree(0);
  147. for (; Top != 0;)
  148. {
  149. if (Top->Value.empty() == false)
  150. {
  151. fprintf(F,"%s=%s\n",
  152. QuoteString(Top->FullTag(),"=\"\n").c_str(),
  153. QuoteString(Top->Value,"\n").c_str());
  154. }
  155. if (Top->Child != 0)
  156. {
  157. Top = Top->Child;
  158. continue;
  159. }
  160. while (Top != 0 && Top->Next == 0)
  161. Top = Top->Parent;
  162. if (Top != 0)
  163. Top = Top->Next;
  164. }
  165. fprintf(F,"\n");
  166. // Write out the package actions in order.
  167. for (vector<Item>::iterator I = List.begin(); I != List.end(); I++)
  168. {
  169. pkgDepCache::StateCache &S = Cache[I->Pkg];
  170. fprintf(F,"%s ",I->Pkg.Name());
  171. // Current version
  172. if (I->Pkg->CurrentVer == 0)
  173. fprintf(F,"- ");
  174. else
  175. fprintf(F,"%s ",I->Pkg.CurrentVer().VerStr());
  176. // Show the compare operator
  177. // Target version
  178. if (S.InstallVer != 0)
  179. {
  180. int Comp = 2;
  181. if (I->Pkg->CurrentVer != 0)
  182. Comp = S.InstVerIter(Cache).CompareVer(I->Pkg.CurrentVer());
  183. if (Comp < 0)
  184. fprintf(F,"> ");
  185. if (Comp == 0)
  186. fprintf(F,"= ");
  187. if (Comp > 0)
  188. fprintf(F,"< ");
  189. fprintf(F,"%s ",S.InstVerIter(Cache).VerStr());
  190. }
  191. else
  192. fprintf(F,"> - ");
  193. // Show the filename/operation
  194. if (I->Op == Item::Install)
  195. {
  196. // No errors here..
  197. if (I->File[0] != '/')
  198. fprintf(F,"**ERROR**\n");
  199. else
  200. fprintf(F,"%s\n",I->File.c_str());
  201. }
  202. if (I->Op == Item::Configure)
  203. fprintf(F,"**CONFIGURE**\n");
  204. if (I->Op == Item::Remove ||
  205. I->Op == Item::Purge)
  206. fprintf(F,"**REMOVE**\n");
  207. if (ferror(F) != 0)
  208. return false;
  209. }
  210. return true;
  211. }
  212. /*}}}*/
  213. // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
  214. // ---------------------------------------------------------------------
  215. /* This looks for a list of scripts to run from the configuration file
  216. each one is run and is fed on standard input a list of all .deb files
  217. that are due to be installed. */
  218. bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf)
  219. {
  220. Configuration::Item const *Opts = _config->Tree(Cnf);
  221. if (Opts == 0 || Opts->Child == 0)
  222. return true;
  223. Opts = Opts->Child;
  224. unsigned int Count = 1;
  225. for (; Opts != 0; Opts = Opts->Next, Count++)
  226. {
  227. if (Opts->Value.empty() == true)
  228. continue;
  229. // Determine the protocol version
  230. string OptSec = Opts->Value;
  231. string::size_type Pos;
  232. if ((Pos = OptSec.find(' ')) == string::npos || Pos == 0)
  233. Pos = OptSec.length();
  234. OptSec = "DPkg::Tools::Options::" + string(Opts->Value.c_str(),Pos);
  235. unsigned int Version = _config->FindI(OptSec+"::Version",1);
  236. // Create the pipes
  237. int Pipes[2];
  238. if (pipe(Pipes) != 0)
  239. return _error->Errno("pipe","Failed to create IPC pipe to subprocess");
  240. SetCloseExec(Pipes[0],true);
  241. SetCloseExec(Pipes[1],true);
  242. // Purified Fork for running the script
  243. pid_t Process = ExecFork();
  244. if (Process == 0)
  245. {
  246. // Setup the FDs
  247. dup2(Pipes[0],STDIN_FILENO);
  248. SetCloseExec(STDOUT_FILENO,false);
  249. SetCloseExec(STDIN_FILENO,false);
  250. SetCloseExec(STDERR_FILENO,false);
  251. const char *Args[4];
  252. Args[0] = "/bin/sh";
  253. Args[1] = "-c";
  254. Args[2] = Opts->Value.c_str();
  255. Args[3] = 0;
  256. execv(Args[0],(char **)Args);
  257. _exit(100);
  258. }
  259. close(Pipes[0]);
  260. FILE *F = fdopen(Pipes[1],"w");
  261. if (F == 0)
  262. return _error->Errno("fdopen","Faild to open new FD");
  263. // Feed it the filenames.
  264. bool Die = false;
  265. if (Version <= 1)
  266. {
  267. for (vector<Item>::iterator I = List.begin(); I != List.end(); I++)
  268. {
  269. // Only deal with packages to be installed from .deb
  270. if (I->Op != Item::Install)
  271. continue;
  272. // No errors here..
  273. if (I->File[0] != '/')
  274. continue;
  275. /* Feed the filename of each package that is pending install
  276. into the pipe. */
  277. fprintf(F,"%s\n",I->File.c_str());
  278. if (ferror(F) != 0)
  279. {
  280. Die = true;
  281. break;
  282. }
  283. }
  284. }
  285. else
  286. Die = !SendV2Pkgs(F);
  287. fclose(F);
  288. // Clean up the sub process
  289. if (ExecWait(Process,Opts->Value.c_str()) == false)
  290. return _error->Error("Failure running script %s",Opts->Value.c_str());
  291. }
  292. return true;
  293. }
  294. /*}}}*/
  295. // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
  296. // ---------------------------------------------------------------------
  297. /*
  298. */
  299. void pkgDPkgPM::DoStdin(int master)
  300. {
  301. char input_buf[256] = {0,};
  302. int len = read(0, input_buf, sizeof(input_buf));
  303. write(master, input_buf, len);
  304. }
  305. /*}}}*/
  306. // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
  307. // ---------------------------------------------------------------------
  308. /*
  309. * read the terminal pty and write log
  310. */
  311. void pkgDPkgPM::DoTerminalPty(int master, FILE *term_out)
  312. {
  313. char term_buf[1024] = {0,};
  314. int len=read(master, term_buf, sizeof(term_buf));
  315. if(len <= 0)
  316. return;
  317. fwrite(term_buf, len, sizeof(char), term_out);
  318. write(1, term_buf, len);
  319. }
  320. /*}}}*/
  321. // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
  322. // ---------------------------------------------------------------------
  323. /*
  324. */
  325. void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd, char *line)
  326. {
  327. // the status we output
  328. ostringstream status;
  329. if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
  330. std::clog << "got from dpkg '" << line << "'" << std::endl;
  331. /* dpkg sends strings like this:
  332. 'status: <pkg>: <pkg qstate>'
  333. errors look like this:
  334. '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
  335. and conffile-prompt like this
  336. 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
  337. */
  338. char* list[5];
  339. // dpkg sends multiline error messages sometimes (see
  340. // #374195 for a example. we should support this by
  341. // either patching dpkg to not send multiline over the
  342. // statusfd or by rewriting the code here to deal with
  343. // it. for now we just ignore it and not crash
  344. TokSplitString(':', line, list, sizeof(list)/sizeof(list[0]));
  345. char *pkg = list[1];
  346. char *action = _strstrip(list[2]);
  347. if( pkg == NULL || action == NULL)
  348. {
  349. if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
  350. std::clog << "ignoring line: not enough ':'" << std::endl;
  351. return;
  352. }
  353. if(strncmp(action,"error",strlen("error")) == 0)
  354. {
  355. status << "pmerror:" << list[1]
  356. << ":" << (PackagesDone/float(PackagesTotal)*100.0)
  357. << ":" << list[3]
  358. << endl;
  359. if(OutStatusFd > 0)
  360. write(OutStatusFd, status.str().c_str(), status.str().size());
  361. if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
  362. std::clog << "send: '" << status.str() << "'" << endl;
  363. return;
  364. }
  365. if(strncmp(action,"conffile",strlen("conffile")) == 0)
  366. {
  367. status << "pmconffile:" << list[1]
  368. << ":" << (PackagesDone/float(PackagesTotal)*100.0)
  369. << ":" << list[3]
  370. << endl;
  371. if(OutStatusFd > 0)
  372. write(OutStatusFd, status.str().c_str(), status.str().size());
  373. if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
  374. std::clog << "send: '" << status.str() << "'" << endl;
  375. return;
  376. }
  377. vector<struct DpkgState> &states = PackageOps[pkg];
  378. const char *next_action = NULL;
  379. if(PackageOpsDone[pkg] < states.size())
  380. next_action = states[PackageOpsDone[pkg]].state;
  381. // check if the package moved to the next dpkg state
  382. if(next_action && (strcmp(action, next_action) == 0))
  383. {
  384. // only read the translation if there is actually a next
  385. // action
  386. const char *translation = _(states[PackageOpsDone[pkg]].str);
  387. char s[200];
  388. snprintf(s, sizeof(s), translation, pkg);
  389. // we moved from one dpkg state to a new one, report that
  390. PackageOpsDone[pkg]++;
  391. PackagesDone++;
  392. // build the status str
  393. status << "pmstatus:" << pkg
  394. << ":" << (PackagesDone/float(PackagesTotal)*100.0)
  395. << ":" << s
  396. << endl;
  397. if(OutStatusFd > 0)
  398. write(OutStatusFd, status.str().c_str(), status.str().size());
  399. if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
  400. std::clog << "send: '" << status.str() << "'" << endl;
  401. }
  402. if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
  403. std::clog << "(parsed from dpkg) pkg: " << pkg
  404. << " action: " << action << endl;
  405. }
  406. // DPkgPM::DoDpkgStatusFd /*{{{*/
  407. // ---------------------------------------------------------------------
  408. /*
  409. */
  410. void pkgDPkgPM::DoDpkgStatusFd(int statusfd, int OutStatusFd)
  411. {
  412. char *p, *q;
  413. int len;
  414. len=read(statusfd, &dpkgbuf[dpkgbuf_pos], sizeof(dpkgbuf)-dpkgbuf_pos);
  415. dpkgbuf_pos += len;
  416. if(len <= 0)
  417. return;
  418. // process line by line if we have a buffer
  419. p = q = dpkgbuf;
  420. while((q=(char*)memchr(p, '\n', dpkgbuf+dpkgbuf_pos-p)) != NULL)
  421. {
  422. *q = 0;
  423. ProcessDpkgStatusLine(OutStatusFd, p);
  424. p=q+1; // continue with next line
  425. }
  426. // now move the unprocessed bits (after the final \n that is now a 0x0)
  427. // to the start and update dpkgbuf_pos
  428. p = (char*)memrchr(dpkgbuf, 0, dpkgbuf_pos);
  429. if(p == NULL)
  430. return;
  431. // we are interessted in the first char *after* 0x0
  432. p++;
  433. // move the unprocessed tail to the start and update pos
  434. memmove(dpkgbuf, p, p-dpkgbuf);
  435. dpkgbuf_pos = dpkgbuf+dpkgbuf_pos-p;
  436. }
  437. /*}}}*/
  438. // DPkgPM::Go - Run the sequence /*{{{*/
  439. // ---------------------------------------------------------------------
  440. /* This globs the operations and calls dpkg
  441. *
  442. * If it is called with "OutStatusFd" set to a valid file descriptor
  443. * apt will report the install progress over this fd. It maps the
  444. * dpkg states a package goes through to human readable (and i10n-able)
  445. * names and calculates a percentage for each step.
  446. */
  447. bool pkgDPkgPM::Go(int OutStatusFd)
  448. {
  449. unsigned int MaxArgs = _config->FindI("Dpkg::MaxArgs",8*1024);
  450. unsigned int MaxArgBytes = _config->FindI("Dpkg::MaxArgBytes",32*1024);
  451. if (RunScripts("DPkg::Pre-Invoke") == false)
  452. return false;
  453. if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
  454. return false;
  455. // map the dpkg states to the operations that are performed
  456. // (this is sorted in the same way as Item::Ops)
  457. static const struct DpkgState DpkgStatesOpMap[][5] = {
  458. // Install operation
  459. {
  460. {"half-installed", N_("Preparing %s")},
  461. {"unpacked", N_("Unpacking %s") },
  462. {NULL, NULL}
  463. },
  464. // Configure operation
  465. {
  466. {"unpacked",N_("Preparing to configure %s") },
  467. {"half-configured", N_("Configuring %s") },
  468. { "installed", N_("Installed %s")},
  469. {NULL, NULL}
  470. },
  471. // Remove operation
  472. {
  473. {"half-configured", N_("Preparing for removal of %s")},
  474. {"half-installed", N_("Removing %s")},
  475. {"config-files", N_("Removed %s")},
  476. {NULL, NULL}
  477. },
  478. // Purge operation
  479. {
  480. {"config-files", N_("Preparing to completely remove %s")},
  481. {"not-installed", N_("Completely removed %s")},
  482. {NULL, NULL}
  483. },
  484. };
  485. // init the PackageOps map, go over the list of packages that
  486. // that will be [installed|configured|removed|purged] and add
  487. // them to the PackageOps map (the dpkg states it goes through)
  488. // and the PackageOpsTranslations (human readable strings)
  489. for (vector<Item>::iterator I = List.begin(); I != List.end();I++)
  490. {
  491. string name = (*I).Pkg.Name();
  492. PackageOpsDone[name] = 0;
  493. for(int i=0; (DpkgStatesOpMap[(*I).Op][i]).state != NULL; i++)
  494. {
  495. PackageOps[name].push_back(DpkgStatesOpMap[(*I).Op][i]);
  496. PackagesTotal++;
  497. }
  498. }
  499. // create log
  500. string logdir = _config->FindDir("Dir::Log");
  501. if(not FileExists(logdir))
  502. return _error->Error(_("Directory '%s' missing"), logdir.c_str());
  503. string logfile_name = flCombine(logdir,
  504. _config->Find("Dir::Log::Name"));
  505. FILE *term_out = fopen(logfile_name.c_str(),"a");
  506. chmod(logfile_name.c_str(), 0600);
  507. // output current time
  508. char outstr[200];
  509. time_t t = time(NULL);
  510. struct tm *tmp = localtime(&t);
  511. strftime(outstr, sizeof(outstr), "%F %T", tmp);
  512. fprintf(term_out, "Log started: ");
  513. fprintf(term_out, outstr);
  514. fprintf(term_out, "\n");
  515. // this loop is runs once per operation
  516. for (vector<Item>::iterator I = List.begin(); I != List.end();)
  517. {
  518. vector<Item>::iterator J = I;
  519. for (; J != List.end() && J->Op == I->Op; J++);
  520. // Generate the argument list
  521. const char *Args[MaxArgs + 50];
  522. if (J - I > (signed)MaxArgs)
  523. J = I + MaxArgs;
  524. unsigned int n = 0;
  525. unsigned long Size = 0;
  526. string Tmp = _config->Find("Dir::Bin::dpkg","dpkg");
  527. Args[n++] = Tmp.c_str();
  528. Size += strlen(Args[n-1]);
  529. // Stick in any custom dpkg options
  530. Configuration::Item const *Opts = _config->Tree("DPkg::Options");
  531. if (Opts != 0)
  532. {
  533. Opts = Opts->Child;
  534. for (; Opts != 0; Opts = Opts->Next)
  535. {
  536. if (Opts->Value.empty() == true)
  537. continue;
  538. Args[n++] = Opts->Value.c_str();
  539. Size += Opts->Value.length();
  540. }
  541. }
  542. char status_fd_buf[20];
  543. int fd[2];
  544. pipe(fd);
  545. Args[n++] = "--status-fd";
  546. Size += strlen(Args[n-1]);
  547. snprintf(status_fd_buf,sizeof(status_fd_buf),"%i", fd[1]);
  548. Args[n++] = status_fd_buf;
  549. Size += strlen(Args[n-1]);
  550. switch (I->Op)
  551. {
  552. case Item::Remove:
  553. Args[n++] = "--force-depends";
  554. Size += strlen(Args[n-1]);
  555. Args[n++] = "--force-remove-essential";
  556. Size += strlen(Args[n-1]);
  557. Args[n++] = "--remove";
  558. Size += strlen(Args[n-1]);
  559. break;
  560. case Item::Purge:
  561. Args[n++] = "--force-depends";
  562. Size += strlen(Args[n-1]);
  563. Args[n++] = "--force-remove-essential";
  564. Size += strlen(Args[n-1]);
  565. Args[n++] = "--purge";
  566. Size += strlen(Args[n-1]);
  567. break;
  568. case Item::Configure:
  569. Args[n++] = "--configure";
  570. Size += strlen(Args[n-1]);
  571. break;
  572. case Item::Install:
  573. Args[n++] = "--unpack";
  574. Size += strlen(Args[n-1]);
  575. Args[n++] = "--auto-deconfigure";
  576. Size += strlen(Args[n-1]);
  577. break;
  578. }
  579. // Write in the file or package names
  580. if (I->Op == Item::Install)
  581. {
  582. for (;I != J && Size < MaxArgBytes; I++)
  583. {
  584. if (I->File[0] != '/')
  585. return _error->Error("Internal Error, Pathname to install is not absolute '%s'",I->File.c_str());
  586. Args[n++] = I->File.c_str();
  587. Size += strlen(Args[n-1]);
  588. }
  589. }
  590. else
  591. {
  592. for (;I != J && Size < MaxArgBytes; I++)
  593. {
  594. Args[n++] = I->Pkg.Name();
  595. Size += strlen(Args[n-1]);
  596. }
  597. }
  598. Args[n] = 0;
  599. J = I;
  600. if (_config->FindB("Debug::pkgDPkgPM",false) == true)
  601. {
  602. for (unsigned int k = 0; k != n; k++)
  603. clog << Args[k] << ' ';
  604. clog << endl;
  605. continue;
  606. }
  607. cout << flush;
  608. clog << flush;
  609. cerr << flush;
  610. /* Mask off sig int/quit. We do this because dpkg also does when
  611. it forks scripts. What happens is that when you hit ctrl-c it sends
  612. it to all processes in the group. Since dpkg ignores the signal
  613. it doesn't die but we do! So we must also ignore it */
  614. sighandler_t old_SIGQUIT = signal(SIGQUIT,SIG_IGN);
  615. sighandler_t old_SIGINT = signal(SIGINT,SIG_IGN);
  616. struct termios tt;
  617. struct winsize win;
  618. int master;
  619. int slave;
  620. // FIXME: setup sensible signal handling (*ick*)
  621. tcgetattr(0, &tt);
  622. ioctl(0, TIOCGWINSZ, (char *)&win);
  623. if (openpty(&master, &slave, NULL, &tt, &win) < 0)
  624. {
  625. fprintf(stderr, _("openpty failed\n"));
  626. }
  627. struct termios rtt;
  628. rtt = tt;
  629. cfmakeraw(&rtt);
  630. rtt.c_lflag &= ~ECHO;
  631. tcsetattr(0, TCSAFLUSH, &rtt);
  632. // Fork dpkg
  633. pid_t Child;
  634. _config->Set("APT::Keep-Fds::",fd[1]);
  635. Child = ExecFork();
  636. // This is the child
  637. if (Child == 0)
  638. {
  639. setsid();
  640. ioctl(slave, TIOCSCTTY, 0);
  641. close(master);
  642. dup2(slave, 0);
  643. dup2(slave, 1);
  644. dup2(slave, 2);
  645. close(slave);
  646. close(fd[0]); // close the read end of the pipe
  647. if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
  648. _exit(100);
  649. if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
  650. {
  651. int Flags,dummy;
  652. if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
  653. _exit(100);
  654. // Discard everything in stdin before forking dpkg
  655. if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
  656. _exit(100);
  657. while (read(STDIN_FILENO,&dummy,1) == 1);
  658. if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
  659. _exit(100);
  660. }
  661. /* No Job Control Stop Env is a magic dpkg var that prevents it
  662. from using sigstop */
  663. putenv("DPKG_NO_TSTP=yes");
  664. execvp(Args[0],(char **)Args);
  665. cerr << "Could not exec dpkg!" << endl;
  666. _exit(100);
  667. }
  668. // clear the Keep-Fd again
  669. _config->Clear("APT::Keep-Fds",fd[1]);
  670. // Wait for dpkg
  671. int Status = 0;
  672. // we read from dpkg here
  673. int _dpkgin = fd[0];
  674. close(fd[1]); // close the write end of the pipe
  675. // the read buffers for the communication with dpkg
  676. char buf[2] = {0,0};
  677. // the result of the waitpid call
  678. int res;
  679. close(slave);
  680. // setups fds
  681. fd_set rfds;
  682. struct timeval tv;
  683. int select_ret;
  684. while ((res=waitpid(Child,&Status, WNOHANG)) != Child) {
  685. if(res < 0) {
  686. // FIXME: move this to a function or something, looks ugly here
  687. // error handling, waitpid returned -1
  688. if (errno == EINTR)
  689. continue;
  690. RunScripts("DPkg::Post-Invoke");
  691. // Restore sig int/quit
  692. signal(SIGQUIT,old_SIGQUIT);
  693. signal(SIGINT,old_SIGINT);
  694. return _error->Errno("waitpid","Couldn't wait for subprocess");
  695. }
  696. // wait for input or output here
  697. FD_ZERO(&rfds);
  698. FD_SET(0, &rfds);
  699. FD_SET(_dpkgin, &rfds);
  700. FD_SET(master, &rfds);
  701. tv.tv_sec = 1;
  702. tv.tv_usec = 0;
  703. select_ret = select(max(master, _dpkgin)+1, &rfds, NULL, NULL, &tv);
  704. if (select_ret < 0)
  705. std::cerr << "Error in select()" << std::endl;
  706. else if (select_ret == 0)
  707. continue;
  708. if(FD_ISSET(master, &rfds))
  709. DoTerminalPty(master, term_out);
  710. if(FD_ISSET(0, &rfds))
  711. DoStdin(master);
  712. if(FD_ISSET(_dpkgin, &rfds))
  713. DoDpkgStatusFd(_dpkgin, OutStatusFd);
  714. }
  715. close(_dpkgin);
  716. // Restore sig int/quit
  717. signal(SIGQUIT,old_SIGQUIT);
  718. signal(SIGINT,old_SIGINT);
  719. tcsetattr(0, TCSAFLUSH, &tt);
  720. // Check for an error code.
  721. if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
  722. {
  723. // if it was set to "keep-dpkg-runing" then we won't return
  724. // here but keep the loop going and just report it as a error
  725. // for later
  726. bool stopOnError = _config->FindB("Dpkg::StopOnError",true);
  727. if(stopOnError)
  728. RunScripts("DPkg::Post-Invoke");
  729. if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
  730. _error->Error("Sub-process %s received a segmentation fault.",Args[0]);
  731. else if (WIFEXITED(Status) != 0)
  732. _error->Error("Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
  733. else
  734. _error->Error("Sub-process %s exited unexpectedly",Args[0]);
  735. if(stopOnError)
  736. {
  737. fclose(term_out);
  738. return false;
  739. }
  740. }
  741. }
  742. fclose(term_out);
  743. if (RunScripts("DPkg::Post-Invoke") == false)
  744. return false;
  745. return true;
  746. }
  747. /*}}}*/
  748. // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
  749. // ---------------------------------------------------------------------
  750. /* */
  751. void pkgDPkgPM::Reset()
  752. {
  753. List.erase(List.begin(),List.end());
  754. }
  755. /*}}}*/