dpkgpm.cc 34 KB

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