dpkgpm.cc 30 KB

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