dpkgpm.cc 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  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. { "installed", N_("Installed %s")},
  579. {NULL, NULL}
  580. },
  581. // Remove operation
  582. {
  583. {"half-configured", N_("Preparing for removal of %s")},
  584. {"half-installed", N_("Removing %s")},
  585. {"config-files", N_("Removed %s")},
  586. {NULL, NULL}
  587. },
  588. // Purge operation
  589. {
  590. {"config-files", N_("Preparing to completely remove %s")},
  591. {"not-installed", N_("Completely removed %s")},
  592. {NULL, NULL}
  593. },
  594. };
  595. // init the PackageOps map, go over the list of packages that
  596. // that will be [installed|configured|removed|purged] and add
  597. // them to the PackageOps map (the dpkg states it goes through)
  598. // and the PackageOpsTranslations (human readable strings)
  599. for (vector<Item>::iterator I = List.begin(); I != List.end();I++)
  600. {
  601. string name = (*I).Pkg.Name();
  602. PackageOpsDone[name] = 0;
  603. for(int i=0; (DpkgStatesOpMap[(*I).Op][i]).state != NULL; i++)
  604. {
  605. PackageOps[name].push_back(DpkgStatesOpMap[(*I).Op][i]);
  606. PackagesTotal++;
  607. }
  608. }
  609. stdin_is_dev_null = false;
  610. // create log
  611. OpenLog();
  612. // this loop is runs once per operation
  613. for (vector<Item>::iterator I = List.begin(); I != List.end();)
  614. {
  615. vector<Item>::iterator J = I;
  616. for (; J != List.end() && J->Op == I->Op; J++)
  617. /* nothing */;
  618. // Generate the argument list
  619. const char *Args[MaxArgs + 50];
  620. // Now check if we are within the MaxArgs limit
  621. //
  622. // this code below is problematic, because it may happen that
  623. // the argument list is split in a way that A depends on B
  624. // and they are in the same "--configure A B" run
  625. // - with the split they may now be configured in different
  626. // runs
  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. // send status information that we are about to fork dpkg
  757. if(OutStatusFd > 0) {
  758. ostringstream status;
  759. status << "pmstatus:dpkg-exec:"
  760. << (PackagesDone/float(PackagesTotal)*100.0)
  761. << ":" << _("Running dpkg")
  762. << endl;
  763. write(OutStatusFd, status.str().c_str(), status.str().size());
  764. }
  765. Child = ExecFork();
  766. // This is the child
  767. if (Child == 0)
  768. {
  769. if(slave >= 0 && master >= 0)
  770. {
  771. setsid();
  772. ioctl(slave, TIOCSCTTY, 0);
  773. close(master);
  774. dup2(slave, 0);
  775. dup2(slave, 1);
  776. dup2(slave, 2);
  777. close(slave);
  778. }
  779. close(fd[0]); // close the read end of the pipe
  780. if (_config->FindDir("DPkg::Chroot-Directory","/") != "/")
  781. {
  782. std::cerr << "Chrooting into "
  783. << _config->FindDir("DPkg::Chroot-Directory")
  784. << std::endl;
  785. if (chroot(_config->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
  786. _exit(100);
  787. }
  788. if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
  789. _exit(100);
  790. if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
  791. {
  792. int Flags,dummy;
  793. if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
  794. _exit(100);
  795. // Discard everything in stdin before forking dpkg
  796. if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
  797. _exit(100);
  798. while (read(STDIN_FILENO,&dummy,1) == 1);
  799. if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
  800. _exit(100);
  801. }
  802. /* No Job Control Stop Env is a magic dpkg var that prevents it
  803. from using sigstop */
  804. putenv((char *)"DPKG_NO_TSTP=yes");
  805. execvp(Args[0],(char **)Args);
  806. cerr << "Could not exec dpkg!" << endl;
  807. _exit(100);
  808. }
  809. // apply ionice
  810. if (_config->FindB("DPkg::UseIoNice", false) == true)
  811. ionice(Child);
  812. // clear the Keep-Fd again
  813. _config->Clear("APT::Keep-Fds",fd[1]);
  814. // Wait for dpkg
  815. int Status = 0;
  816. // we read from dpkg here
  817. int _dpkgin = fd[0];
  818. close(fd[1]); // close the write end of the pipe
  819. // the result of the waitpid call
  820. int res;
  821. if(slave > 0)
  822. close(slave);
  823. // setups fds
  824. sigemptyset(&sigmask);
  825. sigprocmask(SIG_BLOCK,&sigmask,&original_sigmask);
  826. int select_ret;
  827. while ((res=waitpid(Child,&Status, WNOHANG)) != Child) {
  828. if(res < 0) {
  829. // FIXME: move this to a function or something, looks ugly here
  830. // error handling, waitpid returned -1
  831. if (errno == EINTR)
  832. continue;
  833. RunScripts("DPkg::Post-Invoke");
  834. // Restore sig int/quit
  835. signal(SIGQUIT,old_SIGQUIT);
  836. signal(SIGINT,old_SIGINT);
  837. signal(SIGHUP,old_SIGHUP);
  838. return _error->Errno("waitpid","Couldn't wait for subprocess");
  839. }
  840. // wait for input or output here
  841. FD_ZERO(&rfds);
  842. if (!stdin_is_dev_null)
  843. FD_SET(0, &rfds);
  844. FD_SET(_dpkgin, &rfds);
  845. if(master >= 0)
  846. FD_SET(master, &rfds);
  847. tv.tv_sec = 1;
  848. tv.tv_nsec = 0;
  849. select_ret = pselect(max(master, _dpkgin)+1, &rfds, NULL, NULL,
  850. &tv, &original_sigmask);
  851. if (select_ret < 0 && (errno == EINVAL || errno == ENOSYS))
  852. select_ret = racy_pselect(max(master, _dpkgin)+1, &rfds, NULL,
  853. NULL, &tv, &original_sigmask);
  854. if (select_ret == 0)
  855. continue;
  856. else if (select_ret < 0 && errno == EINTR)
  857. continue;
  858. else if (select_ret < 0)
  859. {
  860. perror("select() returned error");
  861. continue;
  862. }
  863. if(master >= 0 && FD_ISSET(master, &rfds))
  864. DoTerminalPty(master);
  865. if(master >= 0 && FD_ISSET(0, &rfds))
  866. DoStdin(master);
  867. if(FD_ISSET(_dpkgin, &rfds))
  868. DoDpkgStatusFd(_dpkgin, OutStatusFd);
  869. }
  870. close(_dpkgin);
  871. // Restore sig int/quit
  872. signal(SIGQUIT,old_SIGQUIT);
  873. signal(SIGINT,old_SIGINT);
  874. signal(SIGHUP,old_SIGHUP);
  875. if(master >= 0)
  876. {
  877. tcsetattr(0, TCSAFLUSH, &tt);
  878. close(master);
  879. }
  880. // Check for an error code.
  881. if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
  882. {
  883. // if it was set to "keep-dpkg-runing" then we won't return
  884. // here but keep the loop going and just report it as a error
  885. // for later
  886. bool stopOnError = _config->FindB("Dpkg::StopOnError",true);
  887. if(stopOnError)
  888. RunScripts("DPkg::Post-Invoke");
  889. if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
  890. _error->Error("Sub-process %s received a segmentation fault.",Args[0]);
  891. else if (WIFEXITED(Status) != 0)
  892. _error->Error("Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
  893. else
  894. _error->Error("Sub-process %s exited unexpectedly",Args[0]);
  895. if(stopOnError)
  896. {
  897. CloseLog();
  898. return false;
  899. }
  900. }
  901. }
  902. CloseLog();
  903. if (RunScripts("DPkg::Post-Invoke") == false)
  904. return false;
  905. Cache.writeStateFile(NULL);
  906. return true;
  907. }
  908. /*}}}*/
  909. // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
  910. // ---------------------------------------------------------------------
  911. /* */
  912. void pkgDPkgPM::Reset()
  913. {
  914. List.erase(List.begin(),List.end());
  915. }
  916. /*}}}*/