dpkgpm.cc 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844
  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(pkgname, PackagesDone, PackagesTotal,
  559. list[3]);
  560. pkgFailures++;
  561. WriteApportReport(pkgname.c_str(), list[3].c_str());
  562. return;
  563. }
  564. else if(action == "conffile-prompt")
  565. {
  566. d->progress->ConffilePrompt(pkgname, 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;
  1300. int dummy = 0;
  1301. if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
  1302. _exit(100);
  1303. // Discard everything in stdin before forking dpkg
  1304. if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
  1305. _exit(100);
  1306. while (read(STDIN_FILENO,&dummy,1) == 1);
  1307. if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
  1308. _exit(100);
  1309. }
  1310. /* No Job Control Stop Env is a magic dpkg var that prevents it
  1311. from using sigstop */
  1312. putenv((char *)"DPKG_NO_TSTP=yes");
  1313. execvp(Args[0], (char**) &Args[0]);
  1314. cerr << "Could not exec dpkg!" << endl;
  1315. _exit(100);
  1316. }
  1317. // apply ionice
  1318. if (_config->FindB("DPkg::UseIoNice", false) == true)
  1319. ionice(Child);
  1320. // Wait for dpkg
  1321. int Status = 0;
  1322. // we read from dpkg here
  1323. int const _dpkgin = fd[0];
  1324. close(fd[1]); // close the write end of the pipe
  1325. // setups fds
  1326. sigemptyset(&d->sigmask);
  1327. sigprocmask(SIG_BLOCK,&d->sigmask,&d->original_sigmask);
  1328. /* free vectors (and therefore memory) as we don't need the included data anymore */
  1329. for (std::vector<char *>::const_iterator p = Packages.begin();
  1330. p != Packages.end(); ++p)
  1331. free(*p);
  1332. Packages.clear();
  1333. // the result of the waitpid call
  1334. int res;
  1335. int select_ret;
  1336. while ((res=waitpid(Child,&Status, WNOHANG)) != Child) {
  1337. if(res < 0) {
  1338. // FIXME: move this to a function or something, looks ugly here
  1339. // error handling, waitpid returned -1
  1340. if (errno == EINTR)
  1341. continue;
  1342. RunScripts("DPkg::Post-Invoke");
  1343. // Restore sig int/quit
  1344. signal(SIGQUIT,old_SIGQUIT);
  1345. signal(SIGINT,old_SIGINT);
  1346. signal(SIGHUP,old_SIGHUP);
  1347. return _error->Errno("waitpid","Couldn't wait for subprocess");
  1348. }
  1349. // wait for input or output here
  1350. FD_ZERO(&rfds);
  1351. if (d->master >= 0 && !d->stdin_is_dev_null)
  1352. FD_SET(0, &rfds);
  1353. FD_SET(_dpkgin, &rfds);
  1354. if(d->master >= 0)
  1355. FD_SET(d->master, &rfds);
  1356. tv.tv_sec = 0;
  1357. tv.tv_nsec = d->progress->GetPulseInterval();
  1358. select_ret = pselect(max(d->master, _dpkgin)+1, &rfds, NULL, NULL,
  1359. &tv, &d->original_sigmask);
  1360. if (select_ret < 0 && (errno == EINVAL || errno == ENOSYS))
  1361. select_ret = racy_pselect(max(d->master, _dpkgin)+1, &rfds, NULL,
  1362. NULL, &tv, &d->original_sigmask);
  1363. d->progress->Pulse();
  1364. if (select_ret == 0)
  1365. continue;
  1366. else if (select_ret < 0 && errno == EINTR)
  1367. continue;
  1368. else if (select_ret < 0)
  1369. {
  1370. perror("select() returned error");
  1371. continue;
  1372. }
  1373. if(d->master >= 0 && FD_ISSET(d->master, &rfds))
  1374. DoTerminalPty(d->master);
  1375. if(d->master >= 0 && FD_ISSET(0, &rfds))
  1376. DoStdin(d->master);
  1377. if(FD_ISSET(_dpkgin, &rfds))
  1378. DoDpkgStatusFd(_dpkgin);
  1379. }
  1380. close(_dpkgin);
  1381. // Restore sig int/quit
  1382. signal(SIGQUIT,old_SIGQUIT);
  1383. signal(SIGINT,old_SIGINT);
  1384. signal(SIGHUP,old_SIGHUP);
  1385. // Check for an error code.
  1386. if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
  1387. {
  1388. // if it was set to "keep-dpkg-runing" then we won't return
  1389. // here but keep the loop going and just report it as a error
  1390. // for later
  1391. bool const stopOnError = _config->FindB("Dpkg::StopOnError",true);
  1392. if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
  1393. strprintf(d->dpkg_error, "Sub-process %s received a segmentation fault.",Args[0]);
  1394. else if (WIFEXITED(Status) != 0)
  1395. strprintf(d->dpkg_error, "Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
  1396. else
  1397. strprintf(d->dpkg_error, "Sub-process %s exited unexpectedly",Args[0]);
  1398. _error->Error("%s", d->dpkg_error.c_str());
  1399. if(stopOnError)
  1400. break;
  1401. }
  1402. }
  1403. // dpkg is done at this point
  1404. d->progress->Stop();
  1405. StopPtyMagic();
  1406. CloseLog();
  1407. if (pkgPackageManager::SigINTStop)
  1408. _error->Warning(_("Operation was interrupted before it could finish"));
  1409. if (RunScripts("DPkg::Post-Invoke") == false)
  1410. return false;
  1411. if (_config->FindB("Debug::pkgDPkgPM",false) == false)
  1412. {
  1413. std::string const oldpkgcache = _config->FindFile("Dir::cache::pkgcache");
  1414. if (oldpkgcache.empty() == false && RealFileExists(oldpkgcache) == true &&
  1415. unlink(oldpkgcache.c_str()) == 0)
  1416. {
  1417. std::string const srcpkgcache = _config->FindFile("Dir::cache::srcpkgcache");
  1418. if (srcpkgcache.empty() == false && RealFileExists(srcpkgcache) == true)
  1419. {
  1420. _error->PushToStack();
  1421. pkgCacheFile CacheFile;
  1422. CacheFile.BuildCaches(NULL, true);
  1423. _error->RevertToStack();
  1424. }
  1425. }
  1426. }
  1427. Cache.writeStateFile(NULL);
  1428. return d->dpkg_error.empty();
  1429. }
  1430. void SigINT(int /*sig*/) {
  1431. pkgPackageManager::SigINTStop = true;
  1432. }
  1433. /*}}}*/
  1434. // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
  1435. // ---------------------------------------------------------------------
  1436. /* */
  1437. void pkgDPkgPM::Reset()
  1438. {
  1439. List.erase(List.begin(),List.end());
  1440. }
  1441. /*}}}*/
  1442. // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
  1443. // ---------------------------------------------------------------------
  1444. /* */
  1445. void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
  1446. {
  1447. // If apport doesn't exist or isn't installed do nothing
  1448. // This e.g. prevents messages in 'universes' without apport
  1449. pkgCache::PkgIterator apportPkg = Cache.FindPkg("apport");
  1450. if (apportPkg.end() == true || apportPkg->CurrentVer == 0)
  1451. return;
  1452. string pkgname, reportfile, srcpkgname, pkgver, arch;
  1453. string::size_type pos;
  1454. FILE *report;
  1455. if (_config->FindB("Dpkg::ApportFailureReport", true) == false)
  1456. {
  1457. std::clog << "configured to not write apport reports" << std::endl;
  1458. return;
  1459. }
  1460. // only report the first errors
  1461. if(pkgFailures > _config->FindI("APT::Apport::MaxReports", 3))
  1462. {
  1463. std::clog << _("No apport report written because MaxReports is reached already") << std::endl;
  1464. return;
  1465. }
  1466. // check if its not a follow up error
  1467. const char *needle = dgettext("dpkg", "dependency problems - leaving unconfigured");
  1468. if(strstr(errormsg, needle) != NULL) {
  1469. std::clog << _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl;
  1470. return;
  1471. }
  1472. // do not report disk-full failures
  1473. if(strstr(errormsg, strerror(ENOSPC)) != NULL) {
  1474. std::clog << _("No apport report written because the error message indicates a disk full error") << std::endl;
  1475. return;
  1476. }
  1477. // do not report out-of-memory failures
  1478. if(strstr(errormsg, strerror(ENOMEM)) != NULL ||
  1479. strstr(errormsg, "failed to allocate memory") != NULL) {
  1480. std::clog << _("No apport report written because the error message indicates a out of memory error") << std::endl;
  1481. return;
  1482. }
  1483. // do not report bugs regarding inaccessible local files
  1484. if(strstr(errormsg, strerror(ENOENT)) != NULL ||
  1485. strstr(errormsg, "cannot access archive") != NULL) {
  1486. std::clog << _("No apport report written because the error message indicates an issue on the local system") << std::endl;
  1487. return;
  1488. }
  1489. // do not report errors encountered when decompressing packages
  1490. if(strstr(errormsg, "--fsys-tarfile returned error exit status 2") != NULL) {
  1491. std::clog << _("No apport report written because the error message indicates an issue on the local system") << std::endl;
  1492. return;
  1493. }
  1494. // do not report dpkg I/O errors, this is a format string, so we compare
  1495. // the prefix and the suffix of the error with the dpkg error message
  1496. vector<string> io_errors;
  1497. io_errors.push_back(string("failed to read"));
  1498. io_errors.push_back(string("failed to write"));
  1499. io_errors.push_back(string("failed to seek"));
  1500. io_errors.push_back(string("unexpected end of file or stream"));
  1501. for (vector<string>::iterator I = io_errors.begin(); I != io_errors.end(); ++I)
  1502. {
  1503. vector<string> list = VectorizeString(dgettext("dpkg", (*I).c_str()), '%');
  1504. if (list.size() > 1) {
  1505. // we need to split %s, VectorizeString only allows char so we need
  1506. // to kill the "s" manually
  1507. if (list[1].size() > 1) {
  1508. list[1].erase(0, 1);
  1509. if(strstr(errormsg, list[0].c_str()) &&
  1510. strstr(errormsg, list[1].c_str())) {
  1511. std::clog << _("No apport report written because the error message indicates a dpkg I/O error") << std::endl;
  1512. return;
  1513. }
  1514. }
  1515. }
  1516. }
  1517. // get the pkgname and reportfile
  1518. pkgname = flNotDir(pkgpath);
  1519. pos = pkgname.find('_');
  1520. if(pos != string::npos)
  1521. pkgname = pkgname.substr(0, pos);
  1522. // find the package versin and source package name
  1523. pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
  1524. if (Pkg.end() == true)
  1525. return;
  1526. pkgCache::VerIterator Ver = Cache.GetCandidateVer(Pkg);
  1527. if (Ver.end() == true)
  1528. return;
  1529. pkgver = Ver.VerStr() == NULL ? "unknown" : Ver.VerStr();
  1530. pkgRecords Recs(Cache);
  1531. pkgRecords::Parser &Parse = Recs.Lookup(Ver.FileList());
  1532. srcpkgname = Parse.SourcePkg();
  1533. if(srcpkgname.empty())
  1534. srcpkgname = pkgname;
  1535. // if the file exists already, we check:
  1536. // - if it was reported already (touched by apport).
  1537. // If not, we do nothing, otherwise
  1538. // we overwrite it. This is the same behaviour as apport
  1539. // - if we have a report with the same pkgversion already
  1540. // then we skip it
  1541. reportfile = flCombine("/var/crash",pkgname+".0.crash");
  1542. if(FileExists(reportfile))
  1543. {
  1544. struct stat buf;
  1545. char strbuf[255];
  1546. // check atime/mtime
  1547. stat(reportfile.c_str(), &buf);
  1548. if(buf.st_mtime > buf.st_atime)
  1549. return;
  1550. // check if the existing report is the same version
  1551. report = fopen(reportfile.c_str(),"r");
  1552. while(fgets(strbuf, sizeof(strbuf), report) != NULL)
  1553. {
  1554. if(strstr(strbuf,"Package:") == strbuf)
  1555. {
  1556. char pkgname[255], version[255];
  1557. if(sscanf(strbuf, "Package: %254s %254s", pkgname, version) == 2)
  1558. if(strcmp(pkgver.c_str(), version) == 0)
  1559. {
  1560. fclose(report);
  1561. return;
  1562. }
  1563. }
  1564. }
  1565. fclose(report);
  1566. }
  1567. // now write the report
  1568. arch = _config->Find("APT::Architecture");
  1569. report = fopen(reportfile.c_str(),"w");
  1570. if(report == NULL)
  1571. return;
  1572. if(_config->FindB("DPkgPM::InitialReportOnly",false) == true)
  1573. chmod(reportfile.c_str(), 0);
  1574. else
  1575. chmod(reportfile.c_str(), 0600);
  1576. fprintf(report, "ProblemType: Package\n");
  1577. fprintf(report, "Architecture: %s\n", arch.c_str());
  1578. time_t now = time(NULL);
  1579. fprintf(report, "Date: %s" , ctime(&now));
  1580. fprintf(report, "Package: %s %s\n", pkgname.c_str(), pkgver.c_str());
  1581. fprintf(report, "SourcePackage: %s\n", srcpkgname.c_str());
  1582. fprintf(report, "ErrorMessage:\n %s\n", errormsg);
  1583. // ensure that the log is flushed
  1584. if(d->term_out)
  1585. fflush(d->term_out);
  1586. // attach terminal log it if we have it
  1587. string logfile_name = _config->FindFile("Dir::Log::Terminal");
  1588. if (!logfile_name.empty())
  1589. {
  1590. FILE *log = NULL;
  1591. fprintf(report, "DpkgTerminalLog:\n");
  1592. log = fopen(logfile_name.c_str(),"r");
  1593. if(log != NULL)
  1594. {
  1595. char buf[1024];
  1596. while( fgets(buf, sizeof(buf), log) != NULL)
  1597. fprintf(report, " %s", buf);
  1598. fprintf(report, " \n");
  1599. fclose(log);
  1600. }
  1601. }
  1602. // attach history log it if we have it
  1603. string histfile_name = _config->FindFile("Dir::Log::History");
  1604. if (!histfile_name.empty())
  1605. {
  1606. fprintf(report, "DpkgHistoryLog:\n");
  1607. FILE* log = fopen(histfile_name.c_str(),"r");
  1608. if(log != NULL)
  1609. {
  1610. char buf[1024];
  1611. while( fgets(buf, sizeof(buf), log) != NULL)
  1612. fprintf(report, " %s", buf);
  1613. fclose(log);
  1614. }
  1615. }
  1616. // log the ordering
  1617. const char *ops_str[] = {"Install", "Configure","Remove","Purge"};
  1618. fprintf(report, "AptOrdering:\n");
  1619. for (vector<Item>::iterator I = List.begin(); I != List.end(); ++I)
  1620. if ((*I).Pkg != NULL)
  1621. fprintf(report, " %s: %s\n", (*I).Pkg.Name(), ops_str[(*I).Op]);
  1622. else
  1623. fprintf(report, " %s: %s\n", "NULL", ops_str[(*I).Op]);
  1624. // attach dmesg log (to learn about segfaults)
  1625. if (FileExists("/bin/dmesg"))
  1626. {
  1627. fprintf(report, "Dmesg:\n");
  1628. FILE *log = popen("/bin/dmesg","r");
  1629. if(log != NULL)
  1630. {
  1631. char buf[1024];
  1632. while( fgets(buf, sizeof(buf), log) != NULL)
  1633. fprintf(report, " %s", buf);
  1634. pclose(log);
  1635. }
  1636. }
  1637. // attach df -l log (to learn about filesystem status)
  1638. if (FileExists("/bin/df"))
  1639. {
  1640. fprintf(report, "Df:\n");
  1641. FILE *log = popen("/bin/df -l","r");
  1642. if(log != NULL)
  1643. {
  1644. char buf[1024];
  1645. while( fgets(buf, sizeof(buf), log) != NULL)
  1646. fprintf(report, " %s", buf);
  1647. pclose(log);
  1648. }
  1649. }
  1650. fclose(report);
  1651. }
  1652. /*}}}*/