dpkgpm.cc 32 KB

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