dpkgpm.cc 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927
  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 == -1 && errno == EIO)
  318. {
  319. // this happens when the child is about to exit, we
  320. // give it time to actually exit, otherwise we run
  321. // into a race
  322. usleep(500000);
  323. return;
  324. }
  325. if(len <= 0)
  326. return;
  327. write(1, term_buf, len);
  328. if(term_out)
  329. fwrite(term_buf, len, sizeof(char), term_out);
  330. }
  331. /*}}}*/
  332. // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
  333. // ---------------------------------------------------------------------
  334. /*
  335. */
  336. void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd, char *line)
  337. {
  338. // the status we output
  339. ostringstream status;
  340. if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
  341. std::clog << "got from dpkg '" << line << "'" << std::endl;
  342. /* dpkg sends strings like this:
  343. 'status: <pkg>: <pkg qstate>'
  344. errors look like this:
  345. '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
  346. and conffile-prompt like this
  347. 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
  348. */
  349. char* list[5];
  350. // dpkg sends multiline error messages sometimes (see
  351. // #374195 for a example. we should support this by
  352. // either patching dpkg to not send multiline over the
  353. // statusfd or by rewriting the code here to deal with
  354. // it. for now we just ignore it and not crash
  355. TokSplitString(':', line, list, sizeof(list)/sizeof(list[0]));
  356. if( list[0] == NULL || list[1] == NULL || list[2] == NULL)
  357. {
  358. if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
  359. std::clog << "ignoring line: not enough ':'" << std::endl;
  360. return;
  361. }
  362. char *pkg = list[1];
  363. char *action = _strstrip(list[2]);
  364. if(strncmp(action,"error",strlen("error")) == 0)
  365. {
  366. status << "pmerror:" << list[1]
  367. << ":" << (PackagesDone/float(PackagesTotal)*100.0)
  368. << ":" << list[3]
  369. << endl;
  370. if(OutStatusFd > 0)
  371. write(OutStatusFd, status.str().c_str(), status.str().size());
  372. if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
  373. std::clog << "send: '" << status.str() << "'" << endl;
  374. return;
  375. }
  376. if(strncmp(action,"conffile",strlen("conffile")) == 0)
  377. {
  378. status << "pmconffile:" << list[1]
  379. << ":" << (PackagesDone/float(PackagesTotal)*100.0)
  380. << ":" << list[3]
  381. << endl;
  382. if(OutStatusFd > 0)
  383. write(OutStatusFd, status.str().c_str(), status.str().size());
  384. if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
  385. std::clog << "send: '" << status.str() << "'" << endl;
  386. return;
  387. }
  388. vector<struct DpkgState> &states = PackageOps[pkg];
  389. const char *next_action = NULL;
  390. if(PackageOpsDone[pkg] < states.size())
  391. next_action = states[PackageOpsDone[pkg]].state;
  392. // check if the package moved to the next dpkg state
  393. if(next_action && (strcmp(action, next_action) == 0))
  394. {
  395. // only read the translation if there is actually a next
  396. // action
  397. const char *translation = _(states[PackageOpsDone[pkg]].str);
  398. char s[200];
  399. snprintf(s, sizeof(s), translation, pkg);
  400. // we moved from one dpkg state to a new one, report that
  401. PackageOpsDone[pkg]++;
  402. PackagesDone++;
  403. // build the status str
  404. status << "pmstatus:" << pkg
  405. << ":" << (PackagesDone/float(PackagesTotal)*100.0)
  406. << ":" << s
  407. << endl;
  408. if(OutStatusFd > 0)
  409. write(OutStatusFd, status.str().c_str(), status.str().size());
  410. if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
  411. std::clog << "send: '" << status.str() << "'" << endl;
  412. }
  413. if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
  414. std::clog << "(parsed from dpkg) pkg: " << pkg
  415. << " action: " << action << endl;
  416. }
  417. // DPkgPM::DoDpkgStatusFd /*{{{*/
  418. // ---------------------------------------------------------------------
  419. /*
  420. */
  421. void pkgDPkgPM::DoDpkgStatusFd(int statusfd, int OutStatusFd)
  422. {
  423. char *p, *q;
  424. int len;
  425. len=read(statusfd, &dpkgbuf[dpkgbuf_pos], sizeof(dpkgbuf)-dpkgbuf_pos);
  426. dpkgbuf_pos += len;
  427. if(len <= 0)
  428. return;
  429. // process line by line if we have a buffer
  430. p = q = dpkgbuf;
  431. while((q=(char*)memchr(p, '\n', dpkgbuf+dpkgbuf_pos-p)) != NULL)
  432. {
  433. *q = 0;
  434. ProcessDpkgStatusLine(OutStatusFd, p);
  435. p=q+1; // continue with next line
  436. }
  437. // now move the unprocessed bits (after the final \n that is now a 0x0)
  438. // to the start and update dpkgbuf_pos
  439. p = (char*)memrchr(dpkgbuf, 0, dpkgbuf_pos);
  440. if(p == NULL)
  441. return;
  442. // we are interessted in the first char *after* 0x0
  443. p++;
  444. // move the unprocessed tail to the start and update pos
  445. memmove(dpkgbuf, p, p-dpkgbuf);
  446. dpkgbuf_pos = dpkgbuf+dpkgbuf_pos-p;
  447. }
  448. /*}}}*/
  449. bool pkgDPkgPM::OpenLog()
  450. {
  451. string logdir = _config->FindDir("Dir::Log");
  452. if(not FileExists(logdir))
  453. return _error->Error(_("Directory '%s' missing"), logdir.c_str());
  454. string logfile_name = flCombine(logdir,
  455. _config->Find("Dir::Log::Terminal"));
  456. if (!logfile_name.empty())
  457. {
  458. term_out = fopen(logfile_name.c_str(),"a");
  459. chmod(logfile_name.c_str(), 0600);
  460. // output current time
  461. char outstr[200];
  462. time_t t = time(NULL);
  463. struct tm *tmp = localtime(&t);
  464. strftime(outstr, sizeof(outstr), "%F %T", tmp);
  465. fprintf(term_out, "\nLog started: ");
  466. fprintf(term_out, outstr);
  467. fprintf(term_out, "\n");
  468. }
  469. return true;
  470. }
  471. bool pkgDPkgPM::CloseLog()
  472. {
  473. if(term_out)
  474. {
  475. char outstr[200];
  476. time_t t = time(NULL);
  477. struct tm *tmp = localtime(&t);
  478. strftime(outstr, sizeof(outstr), "%F %T", tmp);
  479. fprintf(term_out, "Log ended: ");
  480. fprintf(term_out, outstr);
  481. fprintf(term_out, "\n");
  482. fclose(term_out);
  483. }
  484. term_out = NULL;
  485. return true;
  486. }
  487. // DPkgPM::Go - Run the sequence /*{{{*/
  488. // ---------------------------------------------------------------------
  489. /* This globs the operations and calls dpkg
  490. *
  491. * If it is called with "OutStatusFd" set to a valid file descriptor
  492. * apt will report the install progress over this fd. It maps the
  493. * dpkg states a package goes through to human readable (and i10n-able)
  494. * names and calculates a percentage for each step.
  495. */
  496. bool pkgDPkgPM::Go(int OutStatusFd)
  497. {
  498. unsigned int MaxArgs = _config->FindI("Dpkg::MaxArgs",8*1024);
  499. unsigned int MaxArgBytes = _config->FindI("Dpkg::MaxArgBytes",32*1024);
  500. if (RunScripts("DPkg::Pre-Invoke") == false)
  501. return false;
  502. if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
  503. return false;
  504. // map the dpkg states to the operations that are performed
  505. // (this is sorted in the same way as Item::Ops)
  506. static const struct DpkgState DpkgStatesOpMap[][7] = {
  507. // Install operation
  508. {
  509. {"half-installed", N_("Preparing %s")},
  510. {"unpacked", N_("Unpacking %s") },
  511. {NULL, NULL}
  512. },
  513. // Configure operation
  514. {
  515. {"unpacked",N_("Preparing to configure %s") },
  516. {"half-configured", N_("Configuring %s") },
  517. #if 0
  518. {"triggers-awaited", N_("Processing triggers for %s") },
  519. {"triggers-pending", N_("Processing triggers for %s") },
  520. #endif
  521. { "installed", N_("Installed %s")},
  522. {NULL, NULL}
  523. },
  524. // Remove operation
  525. {
  526. {"half-configured", N_("Preparing for removal of %s")},
  527. #if 0
  528. {"triggers-awaited", N_("Preparing for removal of %s")},
  529. {"triggers-pending", N_("Preparing for removal of %s")},
  530. #endif
  531. {"half-installed", N_("Removing %s")},
  532. {"config-files", N_("Removed %s")},
  533. {NULL, NULL}
  534. },
  535. // Purge operation
  536. {
  537. {"config-files", N_("Preparing to completely remove %s")},
  538. {"not-installed", N_("Completely removed %s")},
  539. {NULL, NULL}
  540. },
  541. };
  542. // init the PackageOps map, go over the list of packages that
  543. // that will be [installed|configured|removed|purged] and add
  544. // them to the PackageOps map (the dpkg states it goes through)
  545. // and the PackageOpsTranslations (human readable strings)
  546. for (vector<Item>::iterator I = List.begin(); I != List.end();I++)
  547. {
  548. string name = (*I).Pkg.Name();
  549. PackageOpsDone[name] = 0;
  550. for(int i=0; (DpkgStatesOpMap[(*I).Op][i]).state != NULL; i++)
  551. {
  552. PackageOps[name].push_back(DpkgStatesOpMap[(*I).Op][i]);
  553. PackagesTotal++;
  554. }
  555. }
  556. // create log
  557. OpenLog();
  558. // this loop is runs once per operation
  559. for (vector<Item>::iterator I = List.begin(); I != List.end();)
  560. {
  561. vector<Item>::iterator J = I;
  562. for (; J != List.end() && J->Op == I->Op; J++);
  563. // Generate the argument list
  564. const char *Args[MaxArgs + 50];
  565. if (J - I > (signed)MaxArgs)
  566. J = I + MaxArgs;
  567. unsigned int n = 0;
  568. unsigned long Size = 0;
  569. string Tmp = _config->Find("Dir::Bin::dpkg","dpkg");
  570. Args[n++] = Tmp.c_str();
  571. Size += strlen(Args[n-1]);
  572. // Stick in any custom dpkg options
  573. Configuration::Item const *Opts = _config->Tree("DPkg::Options");
  574. if (Opts != 0)
  575. {
  576. Opts = Opts->Child;
  577. for (; Opts != 0; Opts = Opts->Next)
  578. {
  579. if (Opts->Value.empty() == true)
  580. continue;
  581. Args[n++] = Opts->Value.c_str();
  582. Size += Opts->Value.length();
  583. }
  584. }
  585. char status_fd_buf[20];
  586. int fd[2];
  587. pipe(fd);
  588. Args[n++] = "--status-fd";
  589. Size += strlen(Args[n-1]);
  590. snprintf(status_fd_buf,sizeof(status_fd_buf),"%i", fd[1]);
  591. Args[n++] = status_fd_buf;
  592. Size += strlen(Args[n-1]);
  593. switch (I->Op)
  594. {
  595. case Item::Remove:
  596. Args[n++] = "--force-depends";
  597. Size += strlen(Args[n-1]);
  598. Args[n++] = "--force-remove-essential";
  599. Size += strlen(Args[n-1]);
  600. Args[n++] = "--remove";
  601. Size += strlen(Args[n-1]);
  602. break;
  603. case Item::Purge:
  604. Args[n++] = "--force-depends";
  605. Size += strlen(Args[n-1]);
  606. Args[n++] = "--force-remove-essential";
  607. Size += strlen(Args[n-1]);
  608. Args[n++] = "--purge";
  609. Size += strlen(Args[n-1]);
  610. break;
  611. case Item::Configure:
  612. Args[n++] = "--configure";
  613. Size += strlen(Args[n-1]);
  614. break;
  615. case Item::Install:
  616. Args[n++] = "--unpack";
  617. Size += strlen(Args[n-1]);
  618. Args[n++] = "--auto-deconfigure";
  619. Size += strlen(Args[n-1]);
  620. break;
  621. }
  622. // Write in the file or package names
  623. if (I->Op == Item::Install)
  624. {
  625. for (;I != J && Size < MaxArgBytes; I++)
  626. {
  627. if (I->File[0] != '/')
  628. return _error->Error("Internal Error, Pathname to install is not absolute '%s'",I->File.c_str());
  629. Args[n++] = I->File.c_str();
  630. Size += strlen(Args[n-1]);
  631. }
  632. }
  633. else
  634. {
  635. for (;I != J && Size < MaxArgBytes; I++)
  636. {
  637. Args[n++] = I->Pkg.Name();
  638. Size += strlen(Args[n-1]);
  639. }
  640. }
  641. Args[n] = 0;
  642. J = I;
  643. if (_config->FindB("Debug::pkgDPkgPM",false) == true)
  644. {
  645. for (unsigned int k = 0; k != n; k++)
  646. clog << Args[k] << ' ';
  647. clog << endl;
  648. continue;
  649. }
  650. cout << flush;
  651. clog << flush;
  652. cerr << flush;
  653. /* Mask off sig int/quit. We do this because dpkg also does when
  654. it forks scripts. What happens is that when you hit ctrl-c it sends
  655. it to all processes in the group. Since dpkg ignores the signal
  656. it doesn't die but we do! So we must also ignore it */
  657. sighandler_t old_SIGQUIT = signal(SIGQUIT,SIG_IGN);
  658. sighandler_t old_SIGINT = signal(SIGINT,SIG_IGN);
  659. struct termios tt;
  660. struct winsize win;
  661. int master;
  662. int slave;
  663. // FIXME: setup sensible signal handling (*ick*)
  664. tcgetattr(0, &tt);
  665. ioctl(0, TIOCGWINSZ, (char *)&win);
  666. if (openpty(&master, &slave, NULL, &tt, &win) < 0)
  667. {
  668. const char *s = _("Can not write log, openpty() "
  669. "failed (/dev/pts not mounted?)\n");
  670. fprintf(stderr, "%s",s);
  671. fprintf(term_out, "%s",s);
  672. master = slave = -1;
  673. } else {
  674. struct termios rtt;
  675. rtt = tt;
  676. cfmakeraw(&rtt);
  677. rtt.c_lflag &= ~ECHO;
  678. tcsetattr(0, TCSAFLUSH, &rtt);
  679. }
  680. // Fork dpkg
  681. pid_t Child;
  682. _config->Set("APT::Keep-Fds::",fd[1]);
  683. Child = ExecFork();
  684. // This is the child
  685. if (Child == 0)
  686. {
  687. if(slave >= 0 && master >= 0)
  688. {
  689. setsid();
  690. ioctl(slave, TIOCSCTTY, 0);
  691. close(master);
  692. dup2(slave, 0);
  693. dup2(slave, 1);
  694. dup2(slave, 2);
  695. close(slave);
  696. }
  697. close(fd[0]); // close the read end of the pipe
  698. if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
  699. _exit(100);
  700. if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
  701. {
  702. int Flags,dummy;
  703. if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
  704. _exit(100);
  705. // Discard everything in stdin before forking dpkg
  706. if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
  707. _exit(100);
  708. while (read(STDIN_FILENO,&dummy,1) == 1);
  709. if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
  710. _exit(100);
  711. }
  712. /* No Job Control Stop Env is a magic dpkg var that prevents it
  713. from using sigstop */
  714. putenv((char *)"DPKG_NO_TSTP=yes");
  715. execvp(Args[0],(char **)Args);
  716. cerr << "Could not exec dpkg!" << endl;
  717. _exit(100);
  718. }
  719. // clear the Keep-Fd again
  720. _config->Clear("APT::Keep-Fds",fd[1]);
  721. // Wait for dpkg
  722. int Status = 0;
  723. // we read from dpkg here
  724. int _dpkgin = fd[0];
  725. close(fd[1]); // close the write end of the pipe
  726. // the result of the waitpid call
  727. int res;
  728. if(slave > 0)
  729. close(slave);
  730. // setups fds
  731. fd_set rfds;
  732. struct timespec tv;
  733. sigset_t sigmask;
  734. sigset_t original_sigmask;
  735. sigemptyset(&sigmask);
  736. sigprocmask(SIG_BLOCK,&sigmask,&original_sigmask);
  737. int select_ret;
  738. while ((res=waitpid(Child,&Status, WNOHANG)) != Child) {
  739. if(res < 0) {
  740. // FIXME: move this to a function or something, looks ugly here
  741. // error handling, waitpid returned -1
  742. if (errno == EINTR)
  743. continue;
  744. RunScripts("DPkg::Post-Invoke");
  745. // Restore sig int/quit
  746. signal(SIGQUIT,old_SIGQUIT);
  747. signal(SIGINT,old_SIGINT);
  748. return _error->Errno("waitpid","Couldn't wait for subprocess");
  749. }
  750. // wait for input or output here
  751. FD_ZERO(&rfds);
  752. FD_SET(0, &rfds);
  753. FD_SET(_dpkgin, &rfds);
  754. if(master >= 0)
  755. FD_SET(master, &rfds);
  756. tv.tv_sec = 1;
  757. tv.tv_nsec = 0;
  758. select_ret = pselect(max(master, _dpkgin)+1, &rfds, NULL, NULL,
  759. &tv, &original_sigmask);
  760. if (select_ret == 0)
  761. continue;
  762. else if (select_ret < 0 && errno == EINTR)
  763. continue;
  764. else if (select_ret < 0)
  765. {
  766. perror("select() returned error");
  767. continue;
  768. }
  769. if(master >= 0 && FD_ISSET(master, &rfds))
  770. DoTerminalPty(master);
  771. if(master >= 0 && FD_ISSET(0, &rfds))
  772. DoStdin(master);
  773. if(FD_ISSET(_dpkgin, &rfds))
  774. DoDpkgStatusFd(_dpkgin, OutStatusFd);
  775. }
  776. close(_dpkgin);
  777. // Restore sig int/quit
  778. signal(SIGQUIT,old_SIGQUIT);
  779. signal(SIGINT,old_SIGINT);
  780. if(master >= 0)
  781. {
  782. tcsetattr(0, TCSAFLUSH, &tt);
  783. close(master);
  784. }
  785. // Check for an error code.
  786. if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
  787. {
  788. // if it was set to "keep-dpkg-runing" then we won't return
  789. // here but keep the loop going and just report it as a error
  790. // for later
  791. bool stopOnError = _config->FindB("Dpkg::StopOnError",true);
  792. if(stopOnError)
  793. RunScripts("DPkg::Post-Invoke");
  794. if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
  795. _error->Error("Sub-process %s received a segmentation fault.",Args[0]);
  796. else if (WIFEXITED(Status) != 0)
  797. _error->Error("Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
  798. else
  799. _error->Error("Sub-process %s exited unexpectedly",Args[0]);
  800. if(stopOnError)
  801. {
  802. CloseLog();
  803. return false;
  804. }
  805. }
  806. }
  807. CloseLog();
  808. if (RunScripts("DPkg::Post-Invoke") == false)
  809. return false;
  810. return true;
  811. }
  812. /*}}}*/
  813. // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
  814. // ---------------------------------------------------------------------
  815. /* */
  816. void pkgDPkgPM::Reset()
  817. {
  818. List.erase(List.begin(),List.end());
  819. }
  820. /*}}}*/