dpkgpm.cc 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010
  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 termios tt_out;
  635. struct winsize win;
  636. int master;
  637. int slave;
  638. // FIXME: setup sensible signal handling (*ick*)
  639. tcgetattr(0, &tt);
  640. tcgetattr(1, &tt_out);
  641. ioctl(0, TIOCGWINSZ, (char *)&win);
  642. if (openpty(&master, &slave, NULL, &tt_out, &win) < 0)
  643. {
  644. const char *s = _("Can not write log, openpty() "
  645. "failed (/dev/pts not mounted?)\n");
  646. fprintf(stderr, "%s",s);
  647. fprintf(term_out, "%s",s);
  648. master = slave = -1;
  649. } else {
  650. struct termios rtt;
  651. rtt = tt;
  652. cfmakeraw(&rtt);
  653. rtt.c_lflag &= ~ECHO;
  654. tcsetattr(0, TCSAFLUSH, &rtt);
  655. }
  656. // Fork dpkg
  657. pid_t Child;
  658. _config->Set("APT::Keep-Fds::",fd[1]);
  659. Child = ExecFork();
  660. // This is the child
  661. if (Child == 0)
  662. {
  663. if(slave >= 0 && master >= 0)
  664. {
  665. setsid();
  666. ioctl(slave, TIOCSCTTY, 0);
  667. close(master);
  668. dup2(slave, 0);
  669. dup2(slave, 1);
  670. dup2(slave, 2);
  671. close(slave);
  672. }
  673. close(fd[0]); // close the read end of the pipe
  674. if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
  675. _exit(100);
  676. if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
  677. {
  678. int Flags,dummy;
  679. if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
  680. _exit(100);
  681. // Discard everything in stdin before forking dpkg
  682. if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
  683. _exit(100);
  684. while (read(STDIN_FILENO,&dummy,1) == 1);
  685. if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
  686. _exit(100);
  687. }
  688. /* No Job Control Stop Env is a magic dpkg var that prevents it
  689. from using sigstop */
  690. putenv((char *)"DPKG_NO_TSTP=yes");
  691. execvp(Args[0],(char **)Args);
  692. cerr << "Could not exec dpkg!" << endl;
  693. _exit(100);
  694. }
  695. // clear the Keep-Fd again
  696. _config->Clear("APT::Keep-Fds",fd[1]);
  697. // Wait for dpkg
  698. int Status = 0;
  699. // we read from dpkg here
  700. int _dpkgin = fd[0];
  701. close(fd[1]); // close the write end of the pipe
  702. // the result of the waitpid call
  703. int res;
  704. if(slave > 0)
  705. close(slave);
  706. // setups fds
  707. fd_set rfds;
  708. struct timespec tv;
  709. sigset_t sigmask;
  710. sigset_t original_sigmask;
  711. sigemptyset(&sigmask);
  712. sigprocmask(SIG_BLOCK,&sigmask,&original_sigmask);
  713. int select_ret;
  714. while ((res=waitpid(Child,&Status, WNOHANG)) != Child) {
  715. if(res < 0) {
  716. // FIXME: move this to a function or something, looks ugly here
  717. // error handling, waitpid returned -1
  718. if (errno == EINTR)
  719. continue;
  720. RunScripts("DPkg::Post-Invoke");
  721. // Restore sig int/quit
  722. signal(SIGQUIT,old_SIGQUIT);
  723. signal(SIGINT,old_SIGINT);
  724. return _error->Errno("waitpid","Couldn't wait for subprocess");
  725. }
  726. // wait for input or output here
  727. FD_ZERO(&rfds);
  728. if (!stdin_is_dev_null)
  729. FD_SET(0, &rfds);
  730. FD_SET(_dpkgin, &rfds);
  731. if(master >= 0)
  732. FD_SET(master, &rfds);
  733. tv.tv_sec = 1;
  734. tv.tv_nsec = 0;
  735. select_ret = pselect(max(master, _dpkgin)+1, &rfds, NULL, NULL,
  736. &tv, &original_sigmask);
  737. if (select_ret < 0 && (errno == EINVAL || errno == ENOSYS))
  738. select_ret = racy_pselect(max(master, _dpkgin)+1, &rfds, NULL,
  739. NULL, &tv, &original_sigmask);
  740. if (select_ret == 0)
  741. continue;
  742. else if (select_ret < 0 && errno == EINTR)
  743. continue;
  744. else if (select_ret < 0)
  745. {
  746. perror("select() returned error");
  747. continue;
  748. }
  749. if(master >= 0 && FD_ISSET(master, &rfds))
  750. DoTerminalPty(master);
  751. if(master >= 0 && FD_ISSET(0, &rfds))
  752. DoStdin(master);
  753. if(FD_ISSET(_dpkgin, &rfds))
  754. DoDpkgStatusFd(_dpkgin, OutStatusFd);
  755. }
  756. close(_dpkgin);
  757. // Restore sig int/quit
  758. signal(SIGQUIT,old_SIGQUIT);
  759. signal(SIGINT,old_SIGINT);
  760. if(master >= 0)
  761. {
  762. tcsetattr(0, TCSAFLUSH, &tt);
  763. close(master);
  764. }
  765. // Check for an error code.
  766. if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
  767. {
  768. // if it was set to "keep-dpkg-runing" then we won't return
  769. // here but keep the loop going and just report it as a error
  770. // for later
  771. bool stopOnError = _config->FindB("Dpkg::StopOnError",true);
  772. if(stopOnError)
  773. RunScripts("DPkg::Post-Invoke");
  774. if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
  775. _error->Error("Sub-process %s received a segmentation fault.",Args[0]);
  776. else if (WIFEXITED(Status) != 0)
  777. _error->Error("Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
  778. else
  779. _error->Error("Sub-process %s exited unexpectedly",Args[0]);
  780. if(stopOnError)
  781. {
  782. CloseLog();
  783. return false;
  784. }
  785. }
  786. }
  787. CloseLog();
  788. if (RunScripts("DPkg::Post-Invoke") == false)
  789. return false;
  790. return true;
  791. }
  792. /*}}}*/
  793. // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
  794. // ---------------------------------------------------------------------
  795. /* */
  796. void pkgDPkgPM::Reset()
  797. {
  798. List.erase(List.begin(),List.end());
  799. }
  800. /*}}}*/
  801. // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
  802. // ---------------------------------------------------------------------
  803. /* */
  804. void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
  805. {
  806. string pkgname, reportfile, srcpkgname, pkgver, arch;
  807. string::size_type pos;
  808. FILE *report;
  809. if (_config->FindB("Dpkg::ApportFailureReport",true) == false)
  810. return;
  811. // only report the first error
  812. if(pkgFailures > _config->FindI("APT::Apport::MaxReports", 3))
  813. return;
  814. // get the pkgname and reportfile
  815. pkgname = flNotDir(pkgpath);
  816. pos = pkgname.find('_');
  817. if(pos != string::npos)
  818. pkgname = pkgname.substr(0, pos);
  819. // find the package versin and source package name
  820. pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
  821. if (Pkg.end() == true)
  822. return;
  823. pkgCache::VerIterator Ver = Cache.GetCandidateVer(Pkg);
  824. if (Ver.end() == true)
  825. return;
  826. pkgver = Ver.VerStr() == NULL ? "unknown" : Ver.VerStr();
  827. pkgRecords Recs(Cache);
  828. pkgRecords::Parser &Parse = Recs.Lookup(Ver.FileList());
  829. srcpkgname = Parse.SourcePkg();
  830. if(srcpkgname.empty())
  831. srcpkgname = pkgname;
  832. // if the file exists already, we check:
  833. // - if it was reported already (touched by apport).
  834. // If not, we do nothing, otherwise
  835. // we overwrite it. This is the same behaviour as apport
  836. // - if we have a report with the same pkgversion already
  837. // then we skip it
  838. reportfile = flCombine("/var/crash",pkgname+".0.crash");
  839. if(FileExists(reportfile))
  840. {
  841. struct stat buf;
  842. char strbuf[255];
  843. // check atime/mtime
  844. stat(reportfile.c_str(), &buf);
  845. if(buf.st_mtime > buf.st_atime)
  846. return;
  847. // check if the existing report is the same version
  848. report = fopen(reportfile.c_str(),"r");
  849. while(fgets(strbuf, sizeof(strbuf), report) != NULL)
  850. {
  851. if(strstr(strbuf,"Package:") == strbuf)
  852. {
  853. char pkgname[255], version[255];
  854. if(sscanf(strbuf, "Package: %s %s", pkgname, version) == 2)
  855. if(strcmp(pkgver.c_str(), version) == 0)
  856. {
  857. fclose(report);
  858. return;
  859. }
  860. }
  861. }
  862. fclose(report);
  863. }
  864. // now write the report
  865. arch = _config->Find("APT::Architecture");
  866. report = fopen(reportfile.c_str(),"w");
  867. if(report == NULL)
  868. return;
  869. if(_config->FindB("DPkgPM::InitialReportOnly",false) == true)
  870. chmod(reportfile.c_str(), 0);
  871. else
  872. chmod(reportfile.c_str(), 0600);
  873. fprintf(report, "ProblemType: Package\n");
  874. fprintf(report, "Architecture: %s\n", arch.c_str());
  875. time_t now = time(NULL);
  876. fprintf(report, "Date: %s" , ctime(&now));
  877. fprintf(report, "Package: %s %s\n", pkgname.c_str(), pkgver.c_str());
  878. fprintf(report, "SourcePackage: %s\n", srcpkgname.c_str());
  879. fprintf(report, "ErrorMessage:\n %s\n", errormsg);
  880. // ensure that the log is flushed
  881. if(term_out)
  882. fflush(term_out);
  883. // attach terminal log it if we have it
  884. string logfile_name = _config->FindFile("Dir::Log::Terminal");
  885. if (!logfile_name.empty())
  886. {
  887. FILE *log = NULL;
  888. char buf[1024];
  889. fprintf(report, "DpkgTerminalLog:\n");
  890. log = fopen(logfile_name.c_str(),"r");
  891. if(log != NULL)
  892. {
  893. while( fgets(buf, sizeof(buf), log) != NULL)
  894. fprintf(report, " %s", buf);
  895. fclose(log);
  896. }
  897. }
  898. fclose(report);
  899. }
  900. /*}}}*/