dpkgpm.cc 29 KB

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