dpkgpm.cc 29 KB

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