dpkgpm.cc 30 KB

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