dpkgpm.cc 33 KB

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