dpkgpm.cc 35 KB

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