dpkgpm.cc 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  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), PackagesDone(0),
  40. PackagesTotal(0), term_out(NULL)
  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. char input_buf[256] = {0,};
  305. int len = read(0, input_buf, sizeof(input_buf));
  306. write(master, input_buf, len);
  307. }
  308. /*}}}*/
  309. // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
  310. // ---------------------------------------------------------------------
  311. /*
  312. * read the terminal pty and write log
  313. */
  314. void pkgDPkgPM::DoTerminalPty(int master)
  315. {
  316. char term_buf[1024] = {0,};
  317. int len=read(master, term_buf, sizeof(term_buf));
  318. if(len <= 0)
  319. return;
  320. write(1, term_buf, len);
  321. if(term_out)
  322. fwrite(term_buf, len, sizeof(char), term_out);
  323. }
  324. /*}}}*/
  325. // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
  326. // ---------------------------------------------------------------------
  327. /*
  328. */
  329. void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd, char *line)
  330. {
  331. // the status we output
  332. ostringstream status;
  333. if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
  334. std::clog << "got from dpkg '" << line << "'" << std::endl;
  335. /* dpkg sends strings like this:
  336. 'status: <pkg>: <pkg qstate>'
  337. errors look like this:
  338. '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
  339. and conffile-prompt like this
  340. 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
  341. */
  342. char* list[5];
  343. // dpkg sends multiline error messages sometimes (see
  344. // #374195 for a example. we should support this by
  345. // either patching dpkg to not send multiline over the
  346. // statusfd or by rewriting the code here to deal with
  347. // it. for now we just ignore it and not crash
  348. TokSplitString(':', line, list, sizeof(list)/sizeof(list[0]));
  349. if( list[0] == NULL || list[1] == NULL || list[2] == NULL)
  350. {
  351. if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
  352. std::clog << "ignoring line: not enough ':'" << std::endl;
  353. return;
  354. }
  355. char *pkg = list[1];
  356. char *action = _strstrip(list[2]);
  357. if(strncmp(action,"error",strlen("error")) == 0)
  358. {
  359. status << "pmerror:" << list[1]
  360. << ":" << (PackagesDone/float(PackagesTotal)*100.0)
  361. << ":" << list[3]
  362. << endl;
  363. if(OutStatusFd > 0)
  364. write(OutStatusFd, status.str().c_str(), status.str().size());
  365. if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
  366. std::clog << "send: '" << status.str() << "'" << endl;
  367. pkgFailures++;
  368. WriteApportReport(list[1], list[3]);
  369. return;
  370. }
  371. if(strncmp(action,"conffile",strlen("conffile")) == 0)
  372. {
  373. status << "pmconffile:" << list[1]
  374. << ":" << (PackagesDone/float(PackagesTotal)*100.0)
  375. << ":" << list[3]
  376. << endl;
  377. if(OutStatusFd > 0)
  378. write(OutStatusFd, status.str().c_str(), status.str().size());
  379. if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
  380. std::clog << "send: '" << status.str() << "'" << endl;
  381. return;
  382. }
  383. vector<struct DpkgState> &states = PackageOps[pkg];
  384. const char *next_action = NULL;
  385. if(PackageOpsDone[pkg] < states.size())
  386. next_action = states[PackageOpsDone[pkg]].state;
  387. // check if the package moved to the next dpkg state
  388. if(next_action && (strcmp(action, next_action) == 0))
  389. {
  390. // only read the translation if there is actually a next
  391. // action
  392. const char *translation = _(states[PackageOpsDone[pkg]].str);
  393. char s[200];
  394. snprintf(s, sizeof(s), translation, pkg);
  395. // we moved from one dpkg state to a new one, report that
  396. PackageOpsDone[pkg]++;
  397. PackagesDone++;
  398. // build the status str
  399. status << "pmstatus:" << pkg
  400. << ":" << (PackagesDone/float(PackagesTotal)*100.0)
  401. << ":" << s
  402. << endl;
  403. if(OutStatusFd > 0)
  404. write(OutStatusFd, status.str().c_str(), status.str().size());
  405. if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
  406. std::clog << "send: '" << status.str() << "'" << endl;
  407. }
  408. if (_config->FindB("Debug::pkgDPkgProgressReporting",false) == true)
  409. std::clog << "(parsed from dpkg) pkg: " << pkg
  410. << " action: " << action << endl;
  411. }
  412. // DPkgPM::DoDpkgStatusFd /*{{{*/
  413. // ---------------------------------------------------------------------
  414. /*
  415. */
  416. void pkgDPkgPM::DoDpkgStatusFd(int statusfd, int OutStatusFd)
  417. {
  418. char *p, *q;
  419. int len;
  420. len=read(statusfd, &dpkgbuf[dpkgbuf_pos], sizeof(dpkgbuf)-dpkgbuf_pos);
  421. dpkgbuf_pos += len;
  422. if(len <= 0)
  423. return;
  424. // process line by line if we have a buffer
  425. p = q = dpkgbuf;
  426. while((q=(char*)memchr(p, '\n', dpkgbuf+dpkgbuf_pos-p)) != NULL)
  427. {
  428. *q = 0;
  429. ProcessDpkgStatusLine(OutStatusFd, p);
  430. p=q+1; // continue with next line
  431. }
  432. // now move the unprocessed bits (after the final \n that is now a 0x0)
  433. // to the start and update dpkgbuf_pos
  434. p = (char*)memrchr(dpkgbuf, 0, dpkgbuf_pos);
  435. if(p == NULL)
  436. return;
  437. // we are interessted in the first char *after* 0x0
  438. p++;
  439. // move the unprocessed tail to the start and update pos
  440. memmove(dpkgbuf, p, p-dpkgbuf);
  441. dpkgbuf_pos = dpkgbuf+dpkgbuf_pos-p;
  442. }
  443. /*}}}*/
  444. bool pkgDPkgPM::OpenLog()
  445. {
  446. string logdir = _config->FindDir("Dir::Log");
  447. if(not FileExists(logdir))
  448. return _error->Error(_("Directory '%s' missing"), logdir.c_str());
  449. string logfile_name = flCombine(logdir,
  450. _config->Find("Dir::Log::Terminal"));
  451. if (!logfile_name.empty())
  452. {
  453. term_out = fopen(logfile_name.c_str(),"a");
  454. chmod(logfile_name.c_str(), 0600);
  455. // output current time
  456. char outstr[200];
  457. time_t t = time(NULL);
  458. struct tm *tmp = localtime(&t);
  459. strftime(outstr, sizeof(outstr), "%F %T", tmp);
  460. fprintf(term_out, "\nLog started: ");
  461. fprintf(term_out, outstr);
  462. fprintf(term_out, "\n");
  463. }
  464. return true;
  465. }
  466. bool pkgDPkgPM::CloseLog()
  467. {
  468. if(term_out)
  469. {
  470. char outstr[200];
  471. time_t t = time(NULL);
  472. struct tm *tmp = localtime(&t);
  473. strftime(outstr, sizeof(outstr), "%F %T", tmp);
  474. fprintf(term_out, "Log ended: ");
  475. fprintf(term_out, outstr);
  476. fprintf(term_out, "\n");
  477. fclose(term_out);
  478. }
  479. term_out = NULL;
  480. return true;
  481. }
  482. // DPkgPM::Go - Run the sequence /*{{{*/
  483. // ---------------------------------------------------------------------
  484. /* This globs the operations and calls dpkg
  485. *
  486. * If it is called with "OutStatusFd" set to a valid file descriptor
  487. * apt will report the install progress over this fd. It maps the
  488. * dpkg states a package goes through to human readable (and i10n-able)
  489. * names and calculates a percentage for each step.
  490. */
  491. bool pkgDPkgPM::Go(int OutStatusFd)
  492. {
  493. unsigned int MaxArgs = _config->FindI("Dpkg::MaxArgs",8*1024);
  494. unsigned int MaxArgBytes = _config->FindI("Dpkg::MaxArgBytes",32*1024);
  495. if (RunScripts("DPkg::Pre-Invoke") == false)
  496. return false;
  497. if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
  498. return false;
  499. // map the dpkg states to the operations that are performed
  500. // (this is sorted in the same way as Item::Ops)
  501. static const struct DpkgState DpkgStatesOpMap[][7] = {
  502. // Install operation
  503. {
  504. {"half-installed", N_("Preparing %s")},
  505. {"unpacked", N_("Unpacking %s") },
  506. {NULL, NULL}
  507. },
  508. // Configure operation
  509. {
  510. {"unpacked",N_("Preparing to configure %s") },
  511. {"half-configured", N_("Configuring %s") },
  512. #if 0
  513. {"triggers-awaited", N_("Processing triggers for %s") },
  514. {"triggers-pending", N_("Processing triggers for %s") },
  515. #endif
  516. { "installed", N_("Installed %s")},
  517. {NULL, NULL}
  518. },
  519. // Remove operation
  520. {
  521. {"half-configured", N_("Preparing for removal of %s")},
  522. #if 0
  523. {"triggers-awaited", N_("Preparing for removal of %s")},
  524. {"triggers-pending", N_("Preparing for removal of %s")},
  525. #endif
  526. {"half-installed", N_("Removing %s")},
  527. {"config-files", N_("Removed %s")},
  528. {NULL, NULL}
  529. },
  530. // Purge operation
  531. {
  532. {"config-files", N_("Preparing to completely remove %s")},
  533. {"not-installed", N_("Completely removed %s")},
  534. {NULL, NULL}
  535. },
  536. };
  537. // init the PackageOps map, go over the list of packages that
  538. // that will be [installed|configured|removed|purged] and add
  539. // them to the PackageOps map (the dpkg states it goes through)
  540. // and the PackageOpsTranslations (human readable strings)
  541. for (vector<Item>::iterator I = List.begin(); I != List.end();I++)
  542. {
  543. string name = (*I).Pkg.Name();
  544. PackageOpsDone[name] = 0;
  545. for(int i=0; (DpkgStatesOpMap[(*I).Op][i]).state != NULL; i++)
  546. {
  547. PackageOps[name].push_back(DpkgStatesOpMap[(*I).Op][i]);
  548. PackagesTotal++;
  549. }
  550. }
  551. // create log
  552. OpenLog();
  553. // this loop is runs once per operation
  554. for (vector<Item>::iterator I = List.begin(); I != List.end();)
  555. {
  556. vector<Item>::iterator J = I;
  557. for (; J != List.end() && J->Op == I->Op; J++);
  558. // Generate the argument list
  559. const char *Args[MaxArgs + 50];
  560. if (J - I > (signed)MaxArgs)
  561. J = I + MaxArgs;
  562. unsigned int n = 0;
  563. unsigned long Size = 0;
  564. string Tmp = _config->Find("Dir::Bin::dpkg","dpkg");
  565. Args[n++] = Tmp.c_str();
  566. Size += strlen(Args[n-1]);
  567. // Stick in any custom dpkg options
  568. Configuration::Item const *Opts = _config->Tree("DPkg::Options");
  569. if (Opts != 0)
  570. {
  571. Opts = Opts->Child;
  572. for (; Opts != 0; Opts = Opts->Next)
  573. {
  574. if (Opts->Value.empty() == true)
  575. continue;
  576. Args[n++] = Opts->Value.c_str();
  577. Size += Opts->Value.length();
  578. }
  579. }
  580. char status_fd_buf[20];
  581. int fd[2];
  582. pipe(fd);
  583. Args[n++] = "--status-fd";
  584. Size += strlen(Args[n-1]);
  585. snprintf(status_fd_buf,sizeof(status_fd_buf),"%i", fd[1]);
  586. Args[n++] = status_fd_buf;
  587. Size += strlen(Args[n-1]);
  588. switch (I->Op)
  589. {
  590. case Item::Remove:
  591. Args[n++] = "--force-depends";
  592. Size += strlen(Args[n-1]);
  593. Args[n++] = "--force-remove-essential";
  594. Size += strlen(Args[n-1]);
  595. Args[n++] = "--remove";
  596. Size += strlen(Args[n-1]);
  597. break;
  598. case Item::Purge:
  599. Args[n++] = "--force-depends";
  600. Size += strlen(Args[n-1]);
  601. Args[n++] = "--force-remove-essential";
  602. Size += strlen(Args[n-1]);
  603. Args[n++] = "--purge";
  604. Size += strlen(Args[n-1]);
  605. break;
  606. case Item::Configure:
  607. Args[n++] = "--configure";
  608. Size += strlen(Args[n-1]);
  609. break;
  610. case Item::Install:
  611. Args[n++] = "--unpack";
  612. Size += strlen(Args[n-1]);
  613. Args[n++] = "--auto-deconfigure";
  614. Size += strlen(Args[n-1]);
  615. break;
  616. }
  617. // Write in the file or package names
  618. if (I->Op == Item::Install)
  619. {
  620. for (;I != J && Size < MaxArgBytes; I++)
  621. {
  622. if (I->File[0] != '/')
  623. return _error->Error("Internal Error, Pathname to install is not absolute '%s'",I->File.c_str());
  624. Args[n++] = I->File.c_str();
  625. Size += strlen(Args[n-1]);
  626. }
  627. }
  628. else
  629. {
  630. for (;I != J && Size < MaxArgBytes; I++)
  631. {
  632. Args[n++] = I->Pkg.Name();
  633. Size += strlen(Args[n-1]);
  634. }
  635. }
  636. Args[n] = 0;
  637. J = I;
  638. if (_config->FindB("Debug::pkgDPkgPM",false) == true)
  639. {
  640. for (unsigned int k = 0; k != n; k++)
  641. clog << Args[k] << ' ';
  642. clog << endl;
  643. continue;
  644. }
  645. cout << flush;
  646. clog << flush;
  647. cerr << flush;
  648. /* Mask off sig int/quit. We do this because dpkg also does when
  649. it forks scripts. What happens is that when you hit ctrl-c it sends
  650. it to all processes in the group. Since dpkg ignores the signal
  651. it doesn't die but we do! So we must also ignore it */
  652. sighandler_t old_SIGQUIT = signal(SIGQUIT,SIG_IGN);
  653. sighandler_t old_SIGINT = signal(SIGINT,SIG_IGN);
  654. struct termios tt;
  655. struct winsize win;
  656. int master;
  657. int slave;
  658. // FIXME: setup sensible signal handling (*ick*)
  659. tcgetattr(0, &tt);
  660. ioctl(0, TIOCGWINSZ, (char *)&win);
  661. if (openpty(&master, &slave, NULL, &tt, &win) < 0)
  662. {
  663. const char *s = _("Can not write log, openpty() "
  664. "failed (/dev/pts not mounted?)\n");
  665. fprintf(stderr, "%s",s);
  666. fprintf(term_out, "%s",s);
  667. master = slave = -1;
  668. } else {
  669. struct termios rtt;
  670. rtt = tt;
  671. cfmakeraw(&rtt);
  672. rtt.c_lflag &= ~ECHO;
  673. tcsetattr(0, TCSAFLUSH, &rtt);
  674. }
  675. // Fork dpkg
  676. pid_t Child;
  677. _config->Set("APT::Keep-Fds::",fd[1]);
  678. Child = ExecFork();
  679. // This is the child
  680. if (Child == 0)
  681. {
  682. if(slave >= 0 && master >= 0)
  683. {
  684. setsid();
  685. ioctl(slave, TIOCSCTTY, 0);
  686. close(master);
  687. dup2(slave, 0);
  688. dup2(slave, 1);
  689. dup2(slave, 2);
  690. close(slave);
  691. }
  692. close(fd[0]); // close the read end of the pipe
  693. if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
  694. _exit(100);
  695. if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
  696. {
  697. int Flags,dummy;
  698. if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
  699. _exit(100);
  700. // Discard everything in stdin before forking dpkg
  701. if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
  702. _exit(100);
  703. while (read(STDIN_FILENO,&dummy,1) == 1);
  704. if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
  705. _exit(100);
  706. }
  707. /* No Job Control Stop Env is a magic dpkg var that prevents it
  708. from using sigstop */
  709. putenv("DPKG_NO_TSTP=yes");
  710. execvp(Args[0],(char **)Args);
  711. cerr << "Could not exec dpkg!" << endl;
  712. _exit(100);
  713. }
  714. // clear the Keep-Fd again
  715. _config->Clear("APT::Keep-Fds",fd[1]);
  716. // Wait for dpkg
  717. int Status = 0;
  718. // we read from dpkg here
  719. int _dpkgin = fd[0];
  720. close(fd[1]); // close the write end of the pipe
  721. // the result of the waitpid call
  722. int res;
  723. if(slave > 0)
  724. close(slave);
  725. // setups fds
  726. fd_set rfds;
  727. struct timeval tv;
  728. int select_ret;
  729. while ((res=waitpid(Child,&Status, WNOHANG)) != Child) {
  730. if(res < 0) {
  731. // FIXME: move this to a function or something, looks ugly here
  732. // error handling, waitpid returned -1
  733. if (errno == EINTR)
  734. continue;
  735. RunScripts("DPkg::Post-Invoke");
  736. // Restore sig int/quit
  737. signal(SIGQUIT,old_SIGQUIT);
  738. signal(SIGINT,old_SIGINT);
  739. return _error->Errno("waitpid","Couldn't wait for subprocess");
  740. }
  741. // wait for input or output here
  742. FD_ZERO(&rfds);
  743. FD_SET(0, &rfds);
  744. FD_SET(_dpkgin, &rfds);
  745. if(master >= 0)
  746. FD_SET(master, &rfds);
  747. tv.tv_sec = 1;
  748. tv.tv_usec = 0;
  749. select_ret = select(max(master, _dpkgin)+1, &rfds, NULL, NULL, &tv);
  750. if (select_ret == 0)
  751. continue;
  752. else if (select_ret < 0 && errno == EINTR)
  753. continue;
  754. else if (select_ret < 0)
  755. {
  756. perror("select() returned error");
  757. continue;
  758. }
  759. if(master >= 0 && FD_ISSET(master, &rfds))
  760. DoTerminalPty(master);
  761. if(master >= 0 && FD_ISSET(0, &rfds))
  762. DoStdin(master);
  763. if(FD_ISSET(_dpkgin, &rfds))
  764. DoDpkgStatusFd(_dpkgin, OutStatusFd);
  765. }
  766. close(_dpkgin);
  767. // Restore sig int/quit
  768. signal(SIGQUIT,old_SIGQUIT);
  769. signal(SIGINT,old_SIGINT);
  770. if(master >= 0 && slave >= 0)
  771. tcsetattr(0, TCSAFLUSH, &tt);
  772. // Check for an error code.
  773. if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
  774. {
  775. // if it was set to "keep-dpkg-runing" then we won't return
  776. // here but keep the loop going and just report it as a error
  777. // for later
  778. bool stopOnError = _config->FindB("Dpkg::StopOnError",true);
  779. if(stopOnError)
  780. RunScripts("DPkg::Post-Invoke");
  781. if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
  782. _error->Error("Sub-process %s received a segmentation fault.",Args[0]);
  783. else if (WIFEXITED(Status) != 0)
  784. _error->Error("Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
  785. else
  786. _error->Error("Sub-process %s exited unexpectedly",Args[0]);
  787. if(stopOnError)
  788. {
  789. CloseLog();
  790. return false;
  791. }
  792. }
  793. }
  794. CloseLog();
  795. if (RunScripts("DPkg::Post-Invoke") == false)
  796. return false;
  797. return true;
  798. }
  799. /*}}}*/
  800. // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
  801. // ---------------------------------------------------------------------
  802. /* */
  803. void pkgDPkgPM::Reset()
  804. {
  805. List.erase(List.begin(),List.end());
  806. }
  807. /*}}}*/
  808. // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
  809. // ---------------------------------------------------------------------
  810. /* */
  811. void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
  812. {
  813. string pkgname, reportfile, srcpkgname, pkgver, arch;
  814. string::size_type pos;
  815. FILE *report;
  816. if (_config->FindB("Dpkg::ApportFailureReport",true) == false)
  817. return;
  818. // only report the first error if we are in StopOnError=false mode
  819. // to prevent bogus reports
  820. if((_config->FindB("Dpkg::StopOnError",true) == false) && pkgFailures > 1)
  821. return;
  822. // get the pkgname and reportfile
  823. pkgname = flNotDir(pkgpath);
  824. pos = pkgname.find('_');
  825. if(pos != string::npos)
  826. pkgname = pkgname.substr(0, pos);
  827. // find the package versin and source package name
  828. pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
  829. if (Pkg.end() == true)
  830. return;
  831. pkgCache::VerIterator Ver = Cache.GetCandidateVer(Pkg);
  832. pkgver = Ver.VerStr();
  833. if (Ver.end() == true)
  834. return;
  835. pkgRecords Recs(Cache);
  836. pkgRecords::Parser &Parse = Recs.Lookup(Ver.FileList());
  837. srcpkgname = Parse.SourcePkg();
  838. if(srcpkgname.empty())
  839. srcpkgname = pkgname;
  840. // if the file exists already, we check:
  841. // - if it was reported already (touched by apport).
  842. // If not, we do nothing, otherwise
  843. // we overwrite it. This is the same behaviour as apport
  844. // - if we have a report with the same pkgversion already
  845. // then we skip it
  846. reportfile = flCombine("/var/crash",pkgname+".0.crash");
  847. if(FileExists(reportfile))
  848. {
  849. struct stat buf;
  850. char strbuf[255];
  851. // check atime/mtime
  852. stat(reportfile.c_str(), &buf);
  853. if(buf.st_mtime > buf.st_atime)
  854. return;
  855. // check if the existing report is the same version
  856. report = fopen(reportfile.c_str(),"r");
  857. while(fgets(strbuf, sizeof(strbuf), report) != NULL)
  858. {
  859. if(strstr(strbuf,"Package:") == strbuf)
  860. {
  861. char pkgname[255], version[255];
  862. if(sscanf(strbuf, "Package: %s %s", pkgname, version) == 2)
  863. if(strcmp(pkgver.c_str(), version) == 0)
  864. {
  865. fclose(report);
  866. return;
  867. }
  868. }
  869. }
  870. fclose(report);
  871. }
  872. // now write the report
  873. arch = _config->Find("APT::Architecture");
  874. report = fopen(reportfile.c_str(),"w");
  875. if(report == NULL)
  876. return;
  877. if(_config->FindB("DPkgPM::InitialReportOnly",false) == true)
  878. chmod(reportfile.c_str(), 0);
  879. else
  880. chmod(reportfile.c_str(), 0600);
  881. fprintf(report, "ProblemType: Package\n");
  882. fprintf(report, "Architecture: %s\n", arch.c_str());
  883. time_t now = time(NULL);
  884. fprintf(report, "Date: %s" , ctime(&now));
  885. fprintf(report, "Package: %s %s\n", pkgname.c_str(), pkgver.c_str());
  886. fprintf(report, "SourcePackage: %s\n", srcpkgname.c_str());
  887. fprintf(report, "ErrorMessage:\n %s\n", errormsg);
  888. // ensure that the log is flushed
  889. if(term_out)
  890. fflush(term_out);
  891. // attach terminal log it if we have it
  892. string logfile_name = _config->FindFile("Dir::Log::Terminal");
  893. if (!logfile_name.empty())
  894. {
  895. FILE *log = NULL;
  896. char buf[1024];
  897. fprintf(report, "DpkgTerminalLog:\n");
  898. log = fopen(logfile_name.c_str(),"r");
  899. if(log != NULL)
  900. {
  901. while( fgets(buf, sizeof(buf), log) != NULL)
  902. fprintf(report, " %s", buf);
  903. fclose(log);
  904. }
  905. }
  906. fclose(report);
  907. }
  908. /*}}}*/