dpkgpm.cc 55 KB

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