dpkgpm.cc 28 KB

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