dpkgpm.cc 24 KB

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