dpkgpm.cc 56 KB

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