dpkgpm.cc 56 KB

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