dpkgpm.cc 34 KB

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