dpkgpm.cc 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089
  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. bool const TriggersPending = _config->FindB("DPkg::TriggersPending", false);
  582. if (_config->FindB("DPkg::ConfigurePending", SmartConf) == true)
  583. List.push_back(Item(Item::ConfigurePending, PkgIterator()));
  584. // map the dpkg states to the operations that are performed
  585. // (this is sorted in the same way as Item::Ops)
  586. static const struct DpkgState DpkgStatesOpMap[][7] = {
  587. // Install operation
  588. {
  589. {"half-installed", N_("Preparing %s")},
  590. {"unpacked", N_("Unpacking %s") },
  591. {NULL, NULL}
  592. },
  593. // Configure operation
  594. {
  595. {"unpacked",N_("Preparing to configure %s") },
  596. {"half-configured", N_("Configuring %s") },
  597. { "installed", N_("Installed %s")},
  598. {NULL, NULL}
  599. },
  600. // Remove operation
  601. {
  602. {"half-configured", N_("Preparing for removal of %s")},
  603. {"half-installed", N_("Removing %s")},
  604. {"config-files", N_("Removed %s")},
  605. {NULL, NULL}
  606. },
  607. // Purge operation
  608. {
  609. {"config-files", N_("Preparing to completely remove %s")},
  610. {"not-installed", N_("Completely removed %s")},
  611. {NULL, NULL}
  612. },
  613. };
  614. // init the PackageOps map, go over the list of packages that
  615. // that will be [installed|configured|removed|purged] and add
  616. // them to the PackageOps map (the dpkg states it goes through)
  617. // and the PackageOpsTranslations (human readable strings)
  618. for (vector<Item>::const_iterator I = List.begin(); I != List.end();I++)
  619. {
  620. if((*I).Pkg.end() == true)
  621. continue;
  622. string const name = (*I).Pkg.Name();
  623. PackageOpsDone[name] = 0;
  624. for(int i=0; (DpkgStatesOpMap[(*I).Op][i]).state != NULL; i++)
  625. {
  626. PackageOps[name].push_back(DpkgStatesOpMap[(*I).Op][i]);
  627. PackagesTotal++;
  628. }
  629. }
  630. stdin_is_dev_null = false;
  631. // create log
  632. OpenLog();
  633. // this loop is runs once per operation
  634. for (vector<Item>::const_iterator I = List.begin(); I != List.end();)
  635. {
  636. // Do all actions with the same Op in one run
  637. vector<Item>::const_iterator J = I;
  638. if (TriggersPending == true)
  639. for (; J != List.end(); J++)
  640. {
  641. if (J->Op == I->Op)
  642. continue;
  643. if (J->Op != Item::TriggersPending)
  644. break;
  645. vector<Item>::const_iterator T = J + 1;
  646. if (T != List.end() && T->Op == I->Op)
  647. continue;
  648. break;
  649. }
  650. else
  651. for (; J != List.end() && J->Op == I->Op; J++)
  652. /* nothing */;
  653. // Generate the argument list
  654. const char *Args[MaxArgs + 50];
  655. // Now check if we are within the MaxArgs limit
  656. //
  657. // this code below is problematic, because it may happen that
  658. // the argument list is split in a way that A depends on B
  659. // and they are in the same "--configure A B" run
  660. // - with the split they may now be configured in different
  661. // runs
  662. if (J - I > (signed)MaxArgs)
  663. J = I + MaxArgs;
  664. unsigned int n = 0;
  665. unsigned long Size = 0;
  666. string const Tmp = _config->Find("Dir::Bin::dpkg","dpkg");
  667. Args[n++] = Tmp.c_str();
  668. Size += strlen(Args[n-1]);
  669. // Stick in any custom dpkg options
  670. Configuration::Item const *Opts = _config->Tree("DPkg::Options");
  671. if (Opts != 0)
  672. {
  673. Opts = Opts->Child;
  674. for (; Opts != 0; Opts = Opts->Next)
  675. {
  676. if (Opts->Value.empty() == true)
  677. continue;
  678. Args[n++] = Opts->Value.c_str();
  679. Size += Opts->Value.length();
  680. }
  681. }
  682. char status_fd_buf[20];
  683. int fd[2];
  684. pipe(fd);
  685. Args[n++] = "--status-fd";
  686. Size += strlen(Args[n-1]);
  687. snprintf(status_fd_buf,sizeof(status_fd_buf),"%i", fd[1]);
  688. Args[n++] = status_fd_buf;
  689. Size += strlen(Args[n-1]);
  690. switch (I->Op)
  691. {
  692. case Item::Remove:
  693. Args[n++] = "--force-depends";
  694. Size += strlen(Args[n-1]);
  695. Args[n++] = "--force-remove-essential";
  696. Size += strlen(Args[n-1]);
  697. Args[n++] = "--remove";
  698. Size += strlen(Args[n-1]);
  699. break;
  700. case Item::Purge:
  701. Args[n++] = "--force-depends";
  702. Size += strlen(Args[n-1]);
  703. Args[n++] = "--force-remove-essential";
  704. Size += strlen(Args[n-1]);
  705. Args[n++] = "--purge";
  706. Size += strlen(Args[n-1]);
  707. break;
  708. case Item::Configure:
  709. Args[n++] = "--configure";
  710. Size += strlen(Args[n-1]);
  711. break;
  712. case Item::ConfigurePending:
  713. Args[n++] = "--configure";
  714. Size += strlen(Args[n-1]);
  715. Args[n++] = "--pending";
  716. Size += strlen(Args[n-1]);
  717. break;
  718. case Item::TriggersPending:
  719. Args[n++] = "--triggers-only";
  720. Size += strlen(Args[n-1]);
  721. Args[n++] = "--pending";
  722. Size += strlen(Args[n-1]);
  723. break;
  724. case Item::Install:
  725. Args[n++] = "--unpack";
  726. Size += strlen(Args[n-1]);
  727. Args[n++] = "--auto-deconfigure";
  728. Size += strlen(Args[n-1]);
  729. break;
  730. }
  731. if (NoTriggers == true && I->Op != Item::TriggersPending &&
  732. I->Op != Item::ConfigurePending)
  733. {
  734. Args[n++] = "--no-triggers";
  735. Size += strlen(Args[n-1]);
  736. }
  737. // Write in the file or package names
  738. if (I->Op == Item::Install)
  739. {
  740. for (;I != J && Size < MaxArgBytes; I++)
  741. {
  742. if (I->File[0] != '/')
  743. return _error->Error("Internal Error, Pathname to install is not absolute '%s'",I->File.c_str());
  744. Args[n++] = I->File.c_str();
  745. Size += strlen(Args[n-1]);
  746. }
  747. }
  748. else
  749. {
  750. for (;I != J && Size < MaxArgBytes; I++)
  751. {
  752. if((*I).Pkg.end() == true)
  753. continue;
  754. Args[n++] = I->Pkg.Name();
  755. Size += strlen(Args[n-1]);
  756. }
  757. }
  758. Args[n] = 0;
  759. J = I;
  760. if (_config->FindB("Debug::pkgDPkgPM",false) == true)
  761. {
  762. for (unsigned int k = 0; k != n; k++)
  763. clog << Args[k] << ' ';
  764. clog << endl;
  765. continue;
  766. }
  767. cout << flush;
  768. clog << flush;
  769. cerr << flush;
  770. /* Mask off sig int/quit. We do this because dpkg also does when
  771. it forks scripts. What happens is that when you hit ctrl-c it sends
  772. it to all processes in the group. Since dpkg ignores the signal
  773. it doesn't die but we do! So we must also ignore it */
  774. sighandler_t old_SIGQUIT = signal(SIGQUIT,SIG_IGN);
  775. sighandler_t old_SIGINT = signal(SIGINT,SIG_IGN);
  776. // ignore SIGHUP as well (debian #463030)
  777. sighandler_t old_SIGHUP = signal(SIGHUP,SIG_IGN);
  778. struct termios tt;
  779. struct winsize win;
  780. int master = -1;
  781. int slave = -1;
  782. // if tcgetattr does not return zero there was a error
  783. // and we do not do any pty magic
  784. if (tcgetattr(0, &tt) == 0)
  785. {
  786. ioctl(0, TIOCGWINSZ, (char *)&win);
  787. if (openpty(&master, &slave, NULL, &tt, &win) < 0)
  788. {
  789. const char *s = _("Can not write log, openpty() "
  790. "failed (/dev/pts not mounted?)\n");
  791. fprintf(stderr, "%s",s);
  792. fprintf(term_out, "%s",s);
  793. master = slave = -1;
  794. } else {
  795. struct termios rtt;
  796. rtt = tt;
  797. cfmakeraw(&rtt);
  798. rtt.c_lflag &= ~ECHO;
  799. // block SIGTTOU during tcsetattr to prevent a hang if
  800. // the process is a member of the background process group
  801. // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
  802. sigemptyset(&sigmask);
  803. sigaddset(&sigmask, SIGTTOU);
  804. sigprocmask(SIG_BLOCK,&sigmask, &original_sigmask);
  805. tcsetattr(0, TCSAFLUSH, &rtt);
  806. sigprocmask(SIG_SETMASK, &original_sigmask, 0);
  807. }
  808. }
  809. // Fork dpkg
  810. pid_t Child;
  811. _config->Set("APT::Keep-Fds::",fd[1]);
  812. // send status information that we are about to fork dpkg
  813. if(OutStatusFd > 0) {
  814. ostringstream status;
  815. status << "pmstatus:dpkg-exec:"
  816. << (PackagesDone/float(PackagesTotal)*100.0)
  817. << ":" << _("Running dpkg")
  818. << endl;
  819. write(OutStatusFd, status.str().c_str(), status.str().size());
  820. }
  821. Child = ExecFork();
  822. // This is the child
  823. if (Child == 0)
  824. {
  825. if(slave >= 0 && master >= 0)
  826. {
  827. setsid();
  828. ioctl(slave, TIOCSCTTY, 0);
  829. close(master);
  830. dup2(slave, 0);
  831. dup2(slave, 1);
  832. dup2(slave, 2);
  833. close(slave);
  834. }
  835. close(fd[0]); // close the read end of the pipe
  836. if (_config->FindDir("DPkg::Chroot-Directory","/") != "/")
  837. {
  838. std::cerr << "Chrooting into "
  839. << _config->FindDir("DPkg::Chroot-Directory")
  840. << std::endl;
  841. if (chroot(_config->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
  842. _exit(100);
  843. }
  844. if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
  845. _exit(100);
  846. if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
  847. {
  848. int Flags,dummy;
  849. if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
  850. _exit(100);
  851. // Discard everything in stdin before forking dpkg
  852. if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
  853. _exit(100);
  854. while (read(STDIN_FILENO,&dummy,1) == 1);
  855. if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
  856. _exit(100);
  857. }
  858. /* No Job Control Stop Env is a magic dpkg var that prevents it
  859. from using sigstop */
  860. putenv((char *)"DPKG_NO_TSTP=yes");
  861. execvp(Args[0],(char **)Args);
  862. cerr << "Could not exec dpkg!" << endl;
  863. _exit(100);
  864. }
  865. // apply ionice
  866. if (_config->FindB("DPkg::UseIoNice", false) == true)
  867. ionice(Child);
  868. // clear the Keep-Fd again
  869. _config->Clear("APT::Keep-Fds",fd[1]);
  870. // Wait for dpkg
  871. int Status = 0;
  872. // we read from dpkg here
  873. int const _dpkgin = fd[0];
  874. close(fd[1]); // close the write end of the pipe
  875. if(slave > 0)
  876. close(slave);
  877. // setups fds
  878. sigemptyset(&sigmask);
  879. sigprocmask(SIG_BLOCK,&sigmask,&original_sigmask);
  880. // the result of the waitpid call
  881. int res;
  882. int select_ret;
  883. while ((res=waitpid(Child,&Status, WNOHANG)) != Child) {
  884. if(res < 0) {
  885. // FIXME: move this to a function or something, looks ugly here
  886. // error handling, waitpid returned -1
  887. if (errno == EINTR)
  888. continue;
  889. RunScripts("DPkg::Post-Invoke");
  890. // Restore sig int/quit
  891. signal(SIGQUIT,old_SIGQUIT);
  892. signal(SIGINT,old_SIGINT);
  893. signal(SIGHUP,old_SIGHUP);
  894. return _error->Errno("waitpid","Couldn't wait for subprocess");
  895. }
  896. // wait for input or output here
  897. FD_ZERO(&rfds);
  898. if (!stdin_is_dev_null)
  899. FD_SET(0, &rfds);
  900. FD_SET(_dpkgin, &rfds);
  901. if(master >= 0)
  902. FD_SET(master, &rfds);
  903. tv.tv_sec = 1;
  904. tv.tv_nsec = 0;
  905. select_ret = pselect(max(master, _dpkgin)+1, &rfds, NULL, NULL,
  906. &tv, &original_sigmask);
  907. if (select_ret < 0 && (errno == EINVAL || errno == ENOSYS))
  908. select_ret = racy_pselect(max(master, _dpkgin)+1, &rfds, NULL,
  909. NULL, &tv, &original_sigmask);
  910. if (select_ret == 0)
  911. continue;
  912. else if (select_ret < 0 && errno == EINTR)
  913. continue;
  914. else if (select_ret < 0)
  915. {
  916. perror("select() returned error");
  917. continue;
  918. }
  919. if(master >= 0 && FD_ISSET(master, &rfds))
  920. DoTerminalPty(master);
  921. if(master >= 0 && FD_ISSET(0, &rfds))
  922. DoStdin(master);
  923. if(FD_ISSET(_dpkgin, &rfds))
  924. DoDpkgStatusFd(_dpkgin, OutStatusFd);
  925. }
  926. close(_dpkgin);
  927. // Restore sig int/quit
  928. signal(SIGQUIT,old_SIGQUIT);
  929. signal(SIGINT,old_SIGINT);
  930. signal(SIGHUP,old_SIGHUP);
  931. if(master >= 0)
  932. {
  933. tcsetattr(0, TCSAFLUSH, &tt);
  934. close(master);
  935. }
  936. // Check for an error code.
  937. if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
  938. {
  939. // if it was set to "keep-dpkg-runing" then we won't return
  940. // here but keep the loop going and just report it as a error
  941. // for later
  942. bool const stopOnError = _config->FindB("Dpkg::StopOnError",true);
  943. if(stopOnError)
  944. RunScripts("DPkg::Post-Invoke");
  945. if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
  946. _error->Error("Sub-process %s received a segmentation fault.",Args[0]);
  947. else if (WIFEXITED(Status) != 0)
  948. _error->Error("Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
  949. else
  950. _error->Error("Sub-process %s exited unexpectedly",Args[0]);
  951. if(stopOnError)
  952. {
  953. CloseLog();
  954. return false;
  955. }
  956. }
  957. }
  958. CloseLog();
  959. if (RunScripts("DPkg::Post-Invoke") == false)
  960. return false;
  961. Cache.writeStateFile(NULL);
  962. return true;
  963. }
  964. /*}}}*/
  965. // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
  966. // ---------------------------------------------------------------------
  967. /* */
  968. void pkgDPkgPM::Reset()
  969. {
  970. List.erase(List.begin(),List.end());
  971. }
  972. /*}}}*/