dpkgpm.cc 44 KB

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