dpkgpm.cc 57 KB

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