dpkgpm.cc 56 KB

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