dpkgpm.cc 25 KB

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