dpkgpm.cc 25 KB

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