dpkgpm.cc 27 KB

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