dpkgpm.cc 28 KB

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