dpkgpm.cc 25 KB

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