dpkgpm.cc 23 KB

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