dpkgpm.cc 56 KB

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