dpkgpm.cc 45 KB

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