dpkgpm.cc 25 KB

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