dpkgpm.cc 55 KB

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