dpkgpm.cc 33 KB

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