dpkgpm.cc 24 KB

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