dpkgpm.cc 30 KB

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