dpkgpm.cc 43 KB

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