dpkgpm.cc 24 KB

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