dpkgpm.cc 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  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. unsigned int MaxArgs = _config->FindI("Dpkg::MaxArgs",8*1024);
  511. unsigned int MaxArgBytes = _config->FindI("Dpkg::MaxArgBytes",32*1024);
  512. bool NoTriggers = _config->FindB("DPkg::NoTriggers",false);
  513. if (RunScripts("DPkg::Pre-Invoke") == false)
  514. return false;
  515. if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
  516. return false;
  517. // map the dpkg states to the operations that are performed
  518. // (this is sorted in the same way as Item::Ops)
  519. static const struct DpkgState DpkgStatesOpMap[][7] = {
  520. // Install operation
  521. {
  522. {"half-installed", N_("Preparing %s")},
  523. {"unpacked", N_("Unpacking %s") },
  524. {NULL, NULL}
  525. },
  526. // Configure operation
  527. {
  528. {"unpacked",N_("Preparing to configure %s") },
  529. {"half-configured", N_("Configuring %s") },
  530. #if 0
  531. {"triggers-awaited", N_("Processing triggers for %s") },
  532. {"triggers-pending", N_("Processing triggers for %s") },
  533. #endif
  534. { "installed", N_("Installed %s")},
  535. {NULL, NULL}
  536. },
  537. // Remove operation
  538. {
  539. {"half-configured", N_("Preparing for removal of %s")},
  540. #if 0
  541. {"triggers-awaited", N_("Preparing for removal of %s")},
  542. {"triggers-pending", N_("Preparing for removal of %s")},
  543. #endif
  544. {"half-installed", N_("Removing %s")},
  545. {"config-files", N_("Removed %s")},
  546. {NULL, NULL}
  547. },
  548. // Purge operation
  549. {
  550. {"config-files", N_("Preparing to completely remove %s")},
  551. {"not-installed", N_("Completely removed %s")},
  552. {NULL, NULL}
  553. },
  554. };
  555. // populate the "processing" map
  556. PackageProcessingOps.insert( make_pair("install",N_("Installing %s")) );
  557. PackageProcessingOps.insert( make_pair("configure",N_("Configuring %s")) );
  558. PackageProcessingOps.insert( make_pair("remove",N_("Removing %s")) );
  559. PackageProcessingOps.insert( make_pair("trigproc",N_("Running post-installation trigger %s")) );
  560. // init the PackageOps map, go over the list of packages that
  561. // that will be [installed|configured|removed|purged] and add
  562. // them to the PackageOps map (the dpkg states it goes through)
  563. // and the PackageOpsTranslations (human readable strings)
  564. for (vector<Item>::iterator I = List.begin(); I != List.end();I++)
  565. {
  566. string name = (*I).Pkg.Name();
  567. PackageOpsDone[name] = 0;
  568. for(int i=0; (DpkgStatesOpMap[(*I).Op][i]).state != NULL; i++)
  569. {
  570. PackageOps[name].push_back(DpkgStatesOpMap[(*I).Op][i]);
  571. PackagesTotal++;
  572. }
  573. }
  574. stdin_is_dev_null = false;
  575. // create log
  576. OpenLog();
  577. // this loop is runs once per operation
  578. for (vector<Item>::iterator I = List.begin(); I != List.end();)
  579. {
  580. vector<Item>::iterator J = I;
  581. for (; J != List.end() && J->Op == I->Op; J++);
  582. // Generate the argument list
  583. const char *Args[MaxArgs + 50];
  584. if (J - I > (signed)MaxArgs)
  585. J = I + MaxArgs;
  586. unsigned int n = 0;
  587. unsigned long Size = 0;
  588. string Tmp = _config->Find("Dir::Bin::dpkg","dpkg");
  589. Args[n++] = Tmp.c_str();
  590. Size += strlen(Args[n-1]);
  591. // Stick in any custom dpkg options
  592. Configuration::Item const *Opts = _config->Tree("DPkg::Options");
  593. if (Opts != 0)
  594. {
  595. Opts = Opts->Child;
  596. for (; Opts != 0; Opts = Opts->Next)
  597. {
  598. if (Opts->Value.empty() == true)
  599. continue;
  600. Args[n++] = Opts->Value.c_str();
  601. Size += Opts->Value.length();
  602. }
  603. }
  604. char status_fd_buf[20];
  605. int fd[2];
  606. pipe(fd);
  607. Args[n++] = "--status-fd";
  608. Size += strlen(Args[n-1]);
  609. snprintf(status_fd_buf,sizeof(status_fd_buf),"%i", fd[1]);
  610. Args[n++] = status_fd_buf;
  611. Size += strlen(Args[n-1]);
  612. switch (I->Op)
  613. {
  614. case Item::Remove:
  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++] = "--remove";
  620. Size += strlen(Args[n-1]);
  621. break;
  622. case Item::Purge:
  623. Args[n++] = "--force-depends";
  624. Size += strlen(Args[n-1]);
  625. Args[n++] = "--force-remove-essential";
  626. Size += strlen(Args[n-1]);
  627. Args[n++] = "--purge";
  628. Size += strlen(Args[n-1]);
  629. break;
  630. case Item::Configure:
  631. Args[n++] = "--configure";
  632. if (NoTriggers)
  633. Args[n++] = "--no-triggers";
  634. Size += strlen(Args[n-1]);
  635. break;
  636. case Item::Install:
  637. Args[n++] = "--unpack";
  638. Size += strlen(Args[n-1]);
  639. Args[n++] = "--auto-deconfigure";
  640. Size += strlen(Args[n-1]);
  641. break;
  642. }
  643. // Write in the file or package names
  644. if (I->Op == Item::Install)
  645. {
  646. for (;I != J && Size < MaxArgBytes; I++)
  647. {
  648. if (I->File[0] != '/')
  649. return _error->Error("Internal Error, Pathname to install is not absolute '%s'",I->File.c_str());
  650. Args[n++] = I->File.c_str();
  651. Size += strlen(Args[n-1]);
  652. }
  653. }
  654. else
  655. {
  656. for (;I != J && Size < MaxArgBytes; I++)
  657. {
  658. Args[n++] = I->Pkg.Name();
  659. Size += strlen(Args[n-1]);
  660. }
  661. }
  662. Args[n] = 0;
  663. J = I;
  664. if (_config->FindB("Debug::pkgDPkgPM",false) == true)
  665. {
  666. for (unsigned int k = 0; k != n; k++)
  667. clog << Args[k] << ' ';
  668. clog << endl;
  669. continue;
  670. }
  671. cout << flush;
  672. clog << flush;
  673. cerr << flush;
  674. /* Mask off sig int/quit. We do this because dpkg also does when
  675. it forks scripts. What happens is that when you hit ctrl-c it sends
  676. it to all processes in the group. Since dpkg ignores the signal
  677. it doesn't die but we do! So we must also ignore it */
  678. sighandler_t old_SIGQUIT = signal(SIGQUIT,SIG_IGN);
  679. sighandler_t old_SIGINT = signal(SIGINT,SIG_IGN);
  680. struct termios tt;
  681. struct termios tt_out;
  682. struct winsize win;
  683. int master;
  684. int slave;
  685. // FIXME: setup sensible signal handling (*ick*)
  686. tcgetattr(0, &tt);
  687. tcgetattr(1, &tt_out);
  688. ioctl(0, TIOCGWINSZ, (char *)&win);
  689. if (openpty(&master, &slave, NULL, &tt_out, &win) < 0)
  690. {
  691. const char *s = _("Can not write log, openpty() "
  692. "failed (/dev/pts not mounted?)\n");
  693. fprintf(stderr, "%s",s);
  694. fprintf(term_out, "%s",s);
  695. master = slave = -1;
  696. } else {
  697. struct termios rtt;
  698. rtt = tt;
  699. cfmakeraw(&rtt);
  700. rtt.c_lflag &= ~ECHO;
  701. tcsetattr(0, TCSAFLUSH, &rtt);
  702. }
  703. // Fork dpkg
  704. pid_t Child;
  705. _config->Set("APT::Keep-Fds::",fd[1]);
  706. Child = ExecFork();
  707. // This is the child
  708. if (Child == 0)
  709. {
  710. if(slave >= 0 && master >= 0)
  711. {
  712. setsid();
  713. ioctl(slave, TIOCSCTTY, 0);
  714. close(master);
  715. dup2(slave, 0);
  716. dup2(slave, 1);
  717. dup2(slave, 2);
  718. close(slave);
  719. }
  720. close(fd[0]); // close the read end of the pipe
  721. if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
  722. _exit(100);
  723. if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
  724. {
  725. int Flags,dummy;
  726. if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
  727. _exit(100);
  728. // Discard everything in stdin before forking dpkg
  729. if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
  730. _exit(100);
  731. while (read(STDIN_FILENO,&dummy,1) == 1);
  732. if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
  733. _exit(100);
  734. }
  735. /* No Job Control Stop Env is a magic dpkg var that prevents it
  736. from using sigstop */
  737. putenv((char *)"DPKG_NO_TSTP=yes");
  738. execvp(Args[0],(char **)Args);
  739. cerr << "Could not exec dpkg!" << endl;
  740. _exit(100);
  741. }
  742. // clear the Keep-Fd again
  743. _config->Clear("APT::Keep-Fds",fd[1]);
  744. // Wait for dpkg
  745. int Status = 0;
  746. // we read from dpkg here
  747. int _dpkgin = fd[0];
  748. close(fd[1]); // close the write end of the pipe
  749. // the result of the waitpid call
  750. int res;
  751. if(slave > 0)
  752. close(slave);
  753. // setups fds
  754. fd_set rfds;
  755. struct timespec tv;
  756. sigset_t sigmask;
  757. sigset_t original_sigmask;
  758. sigemptyset(&sigmask);
  759. sigprocmask(SIG_BLOCK,&sigmask,&original_sigmask);
  760. int select_ret;
  761. while ((res=waitpid(Child,&Status, WNOHANG)) != Child) {
  762. if(res < 0) {
  763. // FIXME: move this to a function or something, looks ugly here
  764. // error handling, waitpid returned -1
  765. if (errno == EINTR)
  766. continue;
  767. RunScripts("DPkg::Post-Invoke");
  768. // Restore sig int/quit
  769. signal(SIGQUIT,old_SIGQUIT);
  770. signal(SIGINT,old_SIGINT);
  771. return _error->Errno("waitpid","Couldn't wait for subprocess");
  772. }
  773. // wait for input or output here
  774. FD_ZERO(&rfds);
  775. if (!stdin_is_dev_null)
  776. FD_SET(0, &rfds);
  777. FD_SET(_dpkgin, &rfds);
  778. if(master >= 0)
  779. FD_SET(master, &rfds);
  780. tv.tv_sec = 1;
  781. tv.tv_nsec = 0;
  782. select_ret = pselect(max(master, _dpkgin)+1, &rfds, NULL, NULL,
  783. &tv, &original_sigmask);
  784. if (select_ret < 0 && (errno == EINVAL || errno == ENOSYS))
  785. select_ret = racy_pselect(max(master, _dpkgin)+1, &rfds, NULL,
  786. NULL, &tv, &original_sigmask);
  787. if (select_ret == 0)
  788. continue;
  789. else if (select_ret < 0 && errno == EINTR)
  790. continue;
  791. else if (select_ret < 0)
  792. {
  793. perror("select() returned error");
  794. continue;
  795. }
  796. if(master >= 0 && FD_ISSET(master, &rfds))
  797. DoTerminalPty(master);
  798. if(master >= 0 && FD_ISSET(0, &rfds))
  799. DoStdin(master);
  800. if(FD_ISSET(_dpkgin, &rfds))
  801. DoDpkgStatusFd(_dpkgin, OutStatusFd);
  802. }
  803. close(_dpkgin);
  804. // Restore sig int/quit
  805. signal(SIGQUIT,old_SIGQUIT);
  806. signal(SIGINT,old_SIGINT);
  807. if(master >= 0)
  808. {
  809. tcsetattr(0, TCSAFLUSH, &tt);
  810. close(master);
  811. }
  812. // Check for an error code.
  813. if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
  814. {
  815. // if it was set to "keep-dpkg-runing" then we won't return
  816. // here but keep the loop going and just report it as a error
  817. // for later
  818. bool stopOnError = _config->FindB("Dpkg::StopOnError",true);
  819. if(stopOnError)
  820. RunScripts("DPkg::Post-Invoke");
  821. if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
  822. _error->Error("Sub-process %s received a segmentation fault.",Args[0]);
  823. else if (WIFEXITED(Status) != 0)
  824. _error->Error("Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
  825. else
  826. _error->Error("Sub-process %s exited unexpectedly",Args[0]);
  827. if(stopOnError)
  828. {
  829. CloseLog();
  830. return false;
  831. }
  832. }
  833. }
  834. CloseLog();
  835. if (RunScripts("DPkg::Post-Invoke") == false)
  836. return false;
  837. return true;
  838. }
  839. /*}}}*/
  840. // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
  841. // ---------------------------------------------------------------------
  842. /* */
  843. void pkgDPkgPM::Reset()
  844. {
  845. List.erase(List.begin(),List.end());
  846. }
  847. /*}}}*/
  848. // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
  849. // ---------------------------------------------------------------------
  850. /* */
  851. void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
  852. {
  853. string pkgname, reportfile, srcpkgname, pkgver, arch;
  854. string::size_type pos;
  855. FILE *report;
  856. if (_config->FindB("Dpkg::ApportFailureReport",true) == false)
  857. {
  858. std::clog << "configured to not write apport reports" << std::endl;
  859. return;
  860. }
  861. // only report the first errors
  862. if(pkgFailures > _config->FindI("APT::Apport::MaxReports", 3))
  863. {
  864. std::clog << _("No apport report written because MaxReports is reached already") << std::endl;
  865. return;
  866. }
  867. // check if its not a follow up error
  868. const char *needle = dgettext("dpkg", "dependency problems - leaving unconfigured");
  869. if(strstr(errormsg, needle) != NULL) {
  870. std::clog << _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl;
  871. return;
  872. }
  873. // do not report disk-full failures
  874. if(strstr(errormsg, strerror(ENOSPC)) != NULL) {
  875. std::clog << _("No apport report written because the error message indicates a disk full error") << std::endl;
  876. return;
  877. }
  878. // get the pkgname and reportfile
  879. pkgname = flNotDir(pkgpath);
  880. pos = pkgname.find('_');
  881. if(pos != string::npos)
  882. pkgname = pkgname.substr(0, pos);
  883. // find the package versin and source package name
  884. pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
  885. if (Pkg.end() == true)
  886. return;
  887. pkgCache::VerIterator Ver = Cache.GetCandidateVer(Pkg);
  888. if (Ver.end() == true)
  889. return;
  890. pkgver = Ver.VerStr() == NULL ? "unknown" : Ver.VerStr();
  891. pkgRecords Recs(Cache);
  892. pkgRecords::Parser &Parse = Recs.Lookup(Ver.FileList());
  893. srcpkgname = Parse.SourcePkg();
  894. if(srcpkgname.empty())
  895. srcpkgname = pkgname;
  896. // if the file exists already, we check:
  897. // - if it was reported already (touched by apport).
  898. // If not, we do nothing, otherwise
  899. // we overwrite it. This is the same behaviour as apport
  900. // - if we have a report with the same pkgversion already
  901. // then we skip it
  902. reportfile = flCombine("/var/crash",pkgname+".0.crash");
  903. if(FileExists(reportfile))
  904. {
  905. struct stat buf;
  906. char strbuf[255];
  907. // check atime/mtime
  908. stat(reportfile.c_str(), &buf);
  909. if(buf.st_mtime > buf.st_atime)
  910. return;
  911. // check if the existing report is the same version
  912. report = fopen(reportfile.c_str(),"r");
  913. while(fgets(strbuf, sizeof(strbuf), report) != NULL)
  914. {
  915. if(strstr(strbuf,"Package:") == strbuf)
  916. {
  917. char pkgname[255], version[255];
  918. if(sscanf(strbuf, "Package: %s %s", pkgname, version) == 2)
  919. if(strcmp(pkgver.c_str(), version) == 0)
  920. {
  921. fclose(report);
  922. return;
  923. }
  924. }
  925. }
  926. fclose(report);
  927. }
  928. // now write the report
  929. arch = _config->Find("APT::Architecture");
  930. report = fopen(reportfile.c_str(),"w");
  931. if(report == NULL)
  932. return;
  933. if(_config->FindB("DPkgPM::InitialReportOnly",false) == true)
  934. chmod(reportfile.c_str(), 0);
  935. else
  936. chmod(reportfile.c_str(), 0600);
  937. fprintf(report, "ProblemType: Package\n");
  938. fprintf(report, "Architecture: %s\n", arch.c_str());
  939. time_t now = time(NULL);
  940. fprintf(report, "Date: %s" , ctime(&now));
  941. fprintf(report, "Package: %s %s\n", pkgname.c_str(), pkgver.c_str());
  942. fprintf(report, "SourcePackage: %s\n", srcpkgname.c_str());
  943. fprintf(report, "ErrorMessage:\n %s\n", errormsg);
  944. // ensure that the log is flushed
  945. if(term_out)
  946. fflush(term_out);
  947. // attach terminal log it if we have it
  948. string logfile_name = _config->FindFile("Dir::Log::Terminal");
  949. if (!logfile_name.empty())
  950. {
  951. FILE *log = NULL;
  952. char buf[1024];
  953. fprintf(report, "DpkgTerminalLog:\n");
  954. log = fopen(logfile_name.c_str(),"r");
  955. if(log != NULL)
  956. {
  957. while( fgets(buf, sizeof(buf), log) != NULL)
  958. fprintf(report, " %s", buf);
  959. fclose(log);
  960. }
  961. }
  962. fclose(report);
  963. }
  964. /*}}}*/