dpkgpm.cc 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  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. Newer versions of dpkg sent also:
  300. 'processing: install: pkg'
  301. 'processing: configure: pkg'
  302. 'processing: remove: pkg'
  303. 'processing: trigproc: trigger'
  304. */
  305. char* list[5];
  306. // dpkg sends multiline error messages sometimes (see
  307. // #374195 for a example. we should support this by
  308. // either patching dpkg to not send multiline over the
  309. // statusfd or by rewriting the code here to deal with
  310. // it. for now we just ignore it and not crash
  311. TokSplitString(':', line, list, sizeof(list)/sizeof(list[0]));
  312. if( list[0] == NULL || list[1] == NULL || list[2] == NULL)
  313. {
  314. if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
  315. std::clog << "ignoring line: not enough ':'" << std::endl;
  316. return;
  317. }
  318. char *pkg = list[1];
  319. char *action = _strstrip(list[2]);
  320. // 'processing' from dpkg looks like
  321. // 'processing: action: pkg'
  322. if(strncmp(list[0], "processing", strlen("processing")) == 0)
  323. {
  324. char s[200];
  325. map<string,string>::iterator iter;
  326. char *pkg_or_trigger = _strstrip(list[2]);
  327. action =_strstrip( list[1]);
  328. iter = PackageProcessingOps.find(action);
  329. if(iter == PackageProcessingOps.end())
  330. {
  331. if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
  332. std::clog << "ignoring unknwon action: " << action << std::endl;
  333. return;
  334. }
  335. snprintf(s, sizeof(s), _(iter->second.c_str()), pkg_or_trigger);
  336. status << "pmstatus:" << pkg_or_trigger
  337. << ":" << (PackagesDone/float(PackagesTotal)*100.0)
  338. << ":" << s
  339. << endl;
  340. if(OutStatusFd > 0)
  341. write(OutStatusFd, status.str().c_str(), status.str().size());
  342. if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
  343. std::clog << "send: '" << status.str() << "'" << endl;
  344. return;
  345. }
  346. if(strncmp(action,"error",strlen("error")) == 0)
  347. {
  348. status << "pmerror:" << list[1]
  349. << ":" << (PackagesDone/float(PackagesTotal)*100.0)
  350. << ":" << list[3]
  351. << endl;
  352. if(OutStatusFd > 0)
  353. write(OutStatusFd, status.str().c_str(), status.str().size());
  354. if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
  355. std::clog << "send: '" << status.str() << "'" << endl;
  356. return;
  357. }
  358. if(strncmp(action,"conffile",strlen("conffile")) == 0)
  359. {
  360. status << "pmconffile:" << list[1]
  361. << ":" << (PackagesDone/float(PackagesTotal)*100.0)
  362. << ":" << list[3]
  363. << endl;
  364. if(OutStatusFd > 0)
  365. write(OutStatusFd, status.str().c_str(), status.str().size());
  366. if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
  367. std::clog << "send: '" << status.str() << "'" << endl;
  368. return;
  369. }
  370. vector<struct DpkgState> &states = PackageOps[pkg];
  371. const char *next_action = NULL;
  372. if(PackageOpsDone[pkg] < states.size())
  373. next_action = states[PackageOpsDone[pkg]].state;
  374. // check if the package moved to the next dpkg state
  375. if(next_action && (strcmp(action, next_action) == 0))
  376. {
  377. // only read the translation if there is actually a next
  378. // action
  379. const char *translation = _(states[PackageOpsDone[pkg]].str);
  380. char s[200];
  381. snprintf(s, sizeof(s), translation, pkg);
  382. // we moved from one dpkg state to a new one, report that
  383. PackageOpsDone[pkg]++;
  384. PackagesDone++;
  385. // build the status str
  386. status << "pmstatus:" << pkg
  387. << ":" << (PackagesDone/float(PackagesTotal)*100.0)
  388. << ":" << s
  389. << endl;
  390. if(OutStatusFd > 0)
  391. write(OutStatusFd, status.str().c_str(), status.str().size());
  392. if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
  393. std::clog << "send: '" << status.str() << "'" << endl;
  394. }
  395. if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
  396. std::clog << "(parsed from dpkg) pkg: " << pkg
  397. << " action: " << action << endl;
  398. }
  399. // DPkgPM::DoDpkgStatusFd /*{{{*/
  400. // ---------------------------------------------------------------------
  401. /*
  402. */
  403. void pkgDPkgPM::DoDpkgStatusFd(int statusfd, int OutStatusFd)
  404. {
  405. char *p, *q;
  406. int len;
  407. len=read(statusfd, &dpkgbuf[dpkgbuf_pos], sizeof(dpkgbuf)-dpkgbuf_pos);
  408. dpkgbuf_pos += len;
  409. if(len <= 0)
  410. return;
  411. // process line by line if we have a buffer
  412. p = q = dpkgbuf;
  413. while((q=(char*)memchr(p, '\n', dpkgbuf+dpkgbuf_pos-p)) != NULL)
  414. {
  415. *q = 0;
  416. ProcessDpkgStatusLine(OutStatusFd, p);
  417. p=q+1; // continue with next line
  418. }
  419. // now move the unprocessed bits (after the final \n that is now a 0x0)
  420. // to the start and update dpkgbuf_pos
  421. p = (char*)memrchr(dpkgbuf, 0, dpkgbuf_pos);
  422. if(p == NULL)
  423. return;
  424. // we are interessted in the first char *after* 0x0
  425. p++;
  426. // move the unprocessed tail to the start and update pos
  427. memmove(dpkgbuf, p, p-dpkgbuf);
  428. dpkgbuf_pos = dpkgbuf+dpkgbuf_pos-p;
  429. }
  430. /*}}}*/
  431. bool pkgDPkgPM::OpenLog()
  432. {
  433. string logdir = _config->FindDir("Dir::Log");
  434. if(not FileExists(logdir))
  435. return _error->Error(_("Directory '%s' missing"), logdir.c_str());
  436. string logfile_name = flCombine(logdir,
  437. _config->Find("Dir::Log::Terminal"));
  438. if (!logfile_name.empty())
  439. {
  440. term_out = fopen(logfile_name.c_str(),"a");
  441. chmod(logfile_name.c_str(), 0600);
  442. // output current time
  443. char outstr[200];
  444. time_t t = time(NULL);
  445. struct tm *tmp = localtime(&t);
  446. strftime(outstr, sizeof(outstr), "%F %T", tmp);
  447. fprintf(term_out, "\nLog started: ");
  448. fprintf(term_out, outstr);
  449. fprintf(term_out, "\n");
  450. }
  451. return true;
  452. }
  453. bool pkgDPkgPM::CloseLog()
  454. {
  455. if(term_out)
  456. {
  457. char outstr[200];
  458. time_t t = time(NULL);
  459. struct tm *tmp = localtime(&t);
  460. strftime(outstr, sizeof(outstr), "%F %T", tmp);
  461. fprintf(term_out, "Log ended: ");
  462. fprintf(term_out, outstr);
  463. fprintf(term_out, "\n");
  464. fclose(term_out);
  465. }
  466. term_out = NULL;
  467. return true;
  468. }
  469. /*{{{*/
  470. // This implements a racy version of pselect for those architectures
  471. // that don't have a working implementation.
  472. // FIXME: Probably can be removed on Lenny+1
  473. static int racy_pselect(int nfds, fd_set *readfds, fd_set *writefds,
  474. fd_set *exceptfds, const struct timespec *timeout,
  475. const sigset_t *sigmask)
  476. {
  477. sigset_t origmask;
  478. struct timeval tv;
  479. int retval;
  480. tv.tv_sec = timeout->tv_sec;
  481. tv.tv_usec = timeout->tv_nsec/1000;
  482. sigprocmask(SIG_SETMASK, sigmask, &origmask);
  483. retval = select(nfds, readfds, writefds, exceptfds, &tv);
  484. sigprocmask(SIG_SETMASK, &origmask, 0);
  485. return retval;
  486. }
  487. /*}}}*/
  488. // DPkgPM::Go - Run the sequence /*{{{*/
  489. // ---------------------------------------------------------------------
  490. /* This globs the operations and calls dpkg
  491. *
  492. * If it is called with "OutStatusFd" set to a valid file descriptor
  493. * apt will report the install progress over this fd. It maps the
  494. * dpkg states a package goes through to human readable (and i10n-able)
  495. * names and calculates a percentage for each step.
  496. */
  497. bool pkgDPkgPM::Go(int OutStatusFd)
  498. {
  499. unsigned int MaxArgs = _config->FindI("Dpkg::MaxArgs",8*1024);
  500. unsigned int MaxArgBytes = _config->FindI("Dpkg::MaxArgBytes",32*1024);
  501. bool NoTriggers = _config->FindB("DPkg::NoTriggers",false);
  502. if (RunScripts("DPkg::Pre-Invoke") == false)
  503. return false;
  504. if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
  505. return false;
  506. // map the dpkg states to the operations that are performed
  507. // (this is sorted in the same way as Item::Ops)
  508. static const struct DpkgState DpkgStatesOpMap[][7] = {
  509. // Install operation
  510. {
  511. {"half-installed", N_("Preparing %s")},
  512. {"unpacked", N_("Unpacking %s") },
  513. {NULL, NULL}
  514. },
  515. // Configure operation
  516. {
  517. {"unpacked",N_("Preparing to configure %s") },
  518. {"half-configured", N_("Configuring %s") },
  519. #if 0
  520. {"triggers-awaited", N_("Processing triggers for %s") },
  521. {"triggers-pending", N_("Processing triggers for %s") },
  522. #endif
  523. { "installed", N_("Installed %s")},
  524. {NULL, NULL}
  525. },
  526. // Remove operation
  527. {
  528. {"half-configured", N_("Preparing for removal of %s")},
  529. #if 0
  530. {"triggers-awaited", N_("Preparing for removal of %s")},
  531. {"triggers-pending", N_("Preparing for removal of %s")},
  532. #endif
  533. {"half-installed", N_("Removing %s")},
  534. {"config-files", N_("Removed %s")},
  535. {NULL, NULL}
  536. },
  537. // Purge operation
  538. {
  539. {"config-files", N_("Preparing to completely remove %s")},
  540. {"not-installed", N_("Completely removed %s")},
  541. {NULL, NULL}
  542. },
  543. };
  544. // populate the "processing" map
  545. PackageProcessingOps.insert( make_pair("install",N_("Installing %s")) );
  546. PackageProcessingOps.insert( make_pair("configure",N_("Configuring %s")) );
  547. PackageProcessingOps.insert( make_pair("remove",N_("Removing %s")) );
  548. PackageProcessingOps.insert( make_pair("trigproc",N_("Running post-installation trigger %s")) );
  549. // init the PackageOps map, go over the list of packages that
  550. // that will be [installed|configured|removed|purged] and add
  551. // them to the PackageOps map (the dpkg states it goes through)
  552. // and the PackageOpsTranslations (human readable strings)
  553. for (vector<Item>::iterator I = List.begin(); I != List.end();I++)
  554. {
  555. string name = (*I).Pkg.Name();
  556. PackageOpsDone[name] = 0;
  557. for(int i=0; (DpkgStatesOpMap[(*I).Op][i]).state != NULL; i++)
  558. {
  559. PackageOps[name].push_back(DpkgStatesOpMap[(*I).Op][i]);
  560. PackagesTotal++;
  561. }
  562. }
  563. stdin_is_dev_null = false;
  564. // create log
  565. OpenLog();
  566. // this loop is runs once per operation
  567. for (vector<Item>::iterator I = List.begin(); I != List.end();)
  568. {
  569. vector<Item>::iterator J = I;
  570. for (; J != List.end() && J->Op == I->Op; J++);
  571. // Generate the argument list
  572. const char *Args[MaxArgs + 50];
  573. if (J - I > (signed)MaxArgs)
  574. J = I + MaxArgs;
  575. unsigned int n = 0;
  576. unsigned long Size = 0;
  577. string Tmp = _config->Find("Dir::Bin::dpkg","dpkg");
  578. Args[n++] = Tmp.c_str();
  579. Size += strlen(Args[n-1]);
  580. // Stick in any custom dpkg options
  581. Configuration::Item const *Opts = _config->Tree("DPkg::Options");
  582. if (Opts != 0)
  583. {
  584. Opts = Opts->Child;
  585. for (; Opts != 0; Opts = Opts->Next)
  586. {
  587. if (Opts->Value.empty() == true)
  588. continue;
  589. Args[n++] = Opts->Value.c_str();
  590. Size += Opts->Value.length();
  591. }
  592. }
  593. char status_fd_buf[20];
  594. int fd[2];
  595. pipe(fd);
  596. Args[n++] = "--status-fd";
  597. Size += strlen(Args[n-1]);
  598. snprintf(status_fd_buf,sizeof(status_fd_buf),"%i", fd[1]);
  599. Args[n++] = status_fd_buf;
  600. Size += strlen(Args[n-1]);
  601. switch (I->Op)
  602. {
  603. case Item::Remove:
  604. Args[n++] = "--force-depends";
  605. Size += strlen(Args[n-1]);
  606. Args[n++] = "--force-remove-essential";
  607. Size += strlen(Args[n-1]);
  608. Args[n++] = "--remove";
  609. Size += strlen(Args[n-1]);
  610. break;
  611. case Item::Purge:
  612. Args[n++] = "--force-depends";
  613. Size += strlen(Args[n-1]);
  614. Args[n++] = "--force-remove-essential";
  615. Size += strlen(Args[n-1]);
  616. Args[n++] = "--purge";
  617. Size += strlen(Args[n-1]);
  618. break;
  619. case Item::Configure:
  620. Args[n++] = "--configure";
  621. if (NoTriggers)
  622. Args[n++] = "--no-triggers";
  623. Size += strlen(Args[n-1]);
  624. break;
  625. case Item::Install:
  626. Args[n++] = "--unpack";
  627. Size += strlen(Args[n-1]);
  628. Args[n++] = "--auto-deconfigure";
  629. Size += strlen(Args[n-1]);
  630. break;
  631. }
  632. // Write in the file or package names
  633. if (I->Op == Item::Install)
  634. {
  635. for (;I != J && Size < MaxArgBytes; I++)
  636. {
  637. if (I->File[0] != '/')
  638. return _error->Error("Internal Error, Pathname to install is not absolute '%s'",I->File.c_str());
  639. Args[n++] = I->File.c_str();
  640. Size += strlen(Args[n-1]);
  641. }
  642. }
  643. else
  644. {
  645. for (;I != J && Size < MaxArgBytes; I++)
  646. {
  647. Args[n++] = I->Pkg.Name();
  648. Size += strlen(Args[n-1]);
  649. }
  650. }
  651. Args[n] = 0;
  652. J = I;
  653. if (_config->FindB("Debug::pkgDPkgPM",false) == true)
  654. {
  655. for (unsigned int k = 0; k != n; k++)
  656. clog << Args[k] << ' ';
  657. clog << endl;
  658. continue;
  659. }
  660. cout << flush;
  661. clog << flush;
  662. cerr << flush;
  663. /* Mask off sig int/quit. We do this because dpkg also does when
  664. it forks scripts. What happens is that when you hit ctrl-c it sends
  665. it to all processes in the group. Since dpkg ignores the signal
  666. it doesn't die but we do! So we must also ignore it */
  667. sighandler_t old_SIGQUIT = signal(SIGQUIT,SIG_IGN);
  668. sighandler_t old_SIGINT = signal(SIGINT,SIG_IGN);
  669. struct termios tt;
  670. struct termios tt_out;
  671. struct winsize win;
  672. int master;
  673. int slave;
  674. // FIXME: setup sensible signal handling (*ick*)
  675. tcgetattr(0, &tt);
  676. tcgetattr(1, &tt_out);
  677. ioctl(0, TIOCGWINSZ, (char *)&win);
  678. if (openpty(&master, &slave, NULL, &tt_out, &win) < 0)
  679. {
  680. const char *s = _("Can not write log, openpty() "
  681. "failed (/dev/pts not mounted?)\n");
  682. fprintf(stderr, "%s",s);
  683. fprintf(term_out, "%s",s);
  684. master = slave = -1;
  685. } else {
  686. struct termios rtt;
  687. rtt = tt;
  688. cfmakeraw(&rtt);
  689. rtt.c_lflag &= ~ECHO;
  690. tcsetattr(0, TCSAFLUSH, &rtt);
  691. }
  692. // Fork dpkg
  693. pid_t Child;
  694. _config->Set("APT::Keep-Fds::",fd[1]);
  695. Child = ExecFork();
  696. // This is the child
  697. if (Child == 0)
  698. {
  699. if(slave >= 0 && master >= 0)
  700. {
  701. setsid();
  702. ioctl(slave, TIOCSCTTY, 0);
  703. close(master);
  704. dup2(slave, 0);
  705. dup2(slave, 1);
  706. dup2(slave, 2);
  707. close(slave);
  708. }
  709. close(fd[0]); // close the read end of the pipe
  710. if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
  711. _exit(100);
  712. if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
  713. {
  714. int Flags,dummy;
  715. if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
  716. _exit(100);
  717. // Discard everything in stdin before forking dpkg
  718. if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
  719. _exit(100);
  720. while (read(STDIN_FILENO,&dummy,1) == 1);
  721. if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
  722. _exit(100);
  723. }
  724. /* No Job Control Stop Env is a magic dpkg var that prevents it
  725. from using sigstop */
  726. putenv((char *)"DPKG_NO_TSTP=yes");
  727. execvp(Args[0],(char **)Args);
  728. cerr << "Could not exec dpkg!" << endl;
  729. _exit(100);
  730. }
  731. // clear the Keep-Fd again
  732. _config->Clear("APT::Keep-Fds",fd[1]);
  733. // Wait for dpkg
  734. int Status = 0;
  735. // we read from dpkg here
  736. int _dpkgin = fd[0];
  737. close(fd[1]); // close the write end of the pipe
  738. // the result of the waitpid call
  739. int res;
  740. if(slave > 0)
  741. close(slave);
  742. // setups fds
  743. fd_set rfds;
  744. struct timespec tv;
  745. sigset_t sigmask;
  746. sigset_t original_sigmask;
  747. sigemptyset(&sigmask);
  748. sigprocmask(SIG_BLOCK,&sigmask,&original_sigmask);
  749. int select_ret;
  750. while ((res=waitpid(Child,&Status, WNOHANG)) != Child) {
  751. if(res < 0) {
  752. // FIXME: move this to a function or something, looks ugly here
  753. // error handling, waitpid returned -1
  754. if (errno == EINTR)
  755. continue;
  756. RunScripts("DPkg::Post-Invoke");
  757. // Restore sig int/quit
  758. signal(SIGQUIT,old_SIGQUIT);
  759. signal(SIGINT,old_SIGINT);
  760. return _error->Errno("waitpid","Couldn't wait for subprocess");
  761. }
  762. // wait for input or output here
  763. FD_ZERO(&rfds);
  764. if (!stdin_is_dev_null)
  765. FD_SET(0, &rfds);
  766. FD_SET(_dpkgin, &rfds);
  767. if(master >= 0)
  768. FD_SET(master, &rfds);
  769. tv.tv_sec = 1;
  770. tv.tv_nsec = 0;
  771. select_ret = pselect(max(master, _dpkgin)+1, &rfds, NULL, NULL,
  772. &tv, &original_sigmask);
  773. if (select_ret < 0 && (errno == EINVAL || errno == ENOSYS))
  774. select_ret = racy_pselect(max(master, _dpkgin)+1, &rfds, NULL,
  775. NULL, &tv, &original_sigmask);
  776. if (select_ret == 0)
  777. continue;
  778. else if (select_ret < 0 && errno == EINTR)
  779. continue;
  780. else if (select_ret < 0)
  781. {
  782. perror("select() returned error");
  783. continue;
  784. }
  785. if(master >= 0 && FD_ISSET(master, &rfds))
  786. DoTerminalPty(master);
  787. if(master >= 0 && FD_ISSET(0, &rfds))
  788. DoStdin(master);
  789. if(FD_ISSET(_dpkgin, &rfds))
  790. DoDpkgStatusFd(_dpkgin, OutStatusFd);
  791. }
  792. close(_dpkgin);
  793. // Restore sig int/quit
  794. signal(SIGQUIT,old_SIGQUIT);
  795. signal(SIGINT,old_SIGINT);
  796. if(master >= 0)
  797. {
  798. tcsetattr(0, TCSAFLUSH, &tt);
  799. close(master);
  800. }
  801. // Check for an error code.
  802. if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
  803. {
  804. // if it was set to "keep-dpkg-runing" then we won't return
  805. // here but keep the loop going and just report it as a error
  806. // for later
  807. bool stopOnError = _config->FindB("Dpkg::StopOnError",true);
  808. if(stopOnError)
  809. RunScripts("DPkg::Post-Invoke");
  810. if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
  811. _error->Error("Sub-process %s received a segmentation fault.",Args[0]);
  812. else if (WIFEXITED(Status) != 0)
  813. _error->Error("Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
  814. else
  815. _error->Error("Sub-process %s exited unexpectedly",Args[0]);
  816. if(stopOnError)
  817. {
  818. CloseLog();
  819. return false;
  820. }
  821. }
  822. }
  823. CloseLog();
  824. if (RunScripts("DPkg::Post-Invoke") == false)
  825. return false;
  826. return true;
  827. }
  828. /*}}}*/
  829. // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
  830. // ---------------------------------------------------------------------
  831. /* */
  832. void pkgDPkgPM::Reset()
  833. {
  834. List.erase(List.begin(),List.end());
  835. }
  836. /*}}}*/