dpkgpm.cc 25 KB

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