dpkgpm.cc 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. /* ######################################################################
  4. DPKG Package Manager - Provide an interface to dpkg
  5. ##################################################################### */
  6. /*}}}*/
  7. // Includes /*{{{*/
  8. #include <config.h>
  9. #include <apt-pkg/cachefile.h>
  10. #include <apt-pkg/configuration.h>
  11. #include <apt-pkg/depcache.h>
  12. #include <apt-pkg/dpkgpm.h>
  13. #include <apt-pkg/debsystem.h>
  14. #include <apt-pkg/error.h>
  15. #include <apt-pkg/fileutl.h>
  16. #include <apt-pkg/install-progress.h>
  17. #include <apt-pkg/packagemanager.h>
  18. #include <apt-pkg/strutl.h>
  19. #include <apt-pkg/statechanges.h>
  20. #include <apt-pkg/cacheiterators.h>
  21. #include <apt-pkg/macros.h>
  22. #include <apt-pkg/pkgcache.h>
  23. #include <apt-pkg/version.h>
  24. #include <errno.h>
  25. #include <fcntl.h>
  26. #include <grp.h>
  27. #include <pwd.h>
  28. #include <signal.h>
  29. #include <stddef.h>
  30. #include <stdio.h>
  31. #include <stdlib.h>
  32. #include <sys/ioctl.h>
  33. #include <sys/select.h>
  34. #include <sys/stat.h>
  35. #include <sys/time.h>
  36. #include <sys/wait.h>
  37. #include <sys/types.h>
  38. #include <dirent.h>
  39. #include <termios.h>
  40. #include <time.h>
  41. #include <unistd.h>
  42. #include <algorithm>
  43. #include <array>
  44. #include <cstring>
  45. #include <iostream>
  46. #include <map>
  47. #include <set>
  48. #include <string>
  49. #include <type_traits>
  50. #include <utility>
  51. #include <unordered_set>
  52. #include <vector>
  53. #include <sstream>
  54. #include <numeric>
  55. #include <apti18n.h>
  56. /*}}}*/
  57. extern char **environ;
  58. using namespace std;
  59. APT_PURE static string AptHistoryRequestingUser() /*{{{*/
  60. {
  61. const char* EnvKeys[]{"SUDO_UID", "PKEXEC_UID", "PACKAGEKIT_CALLER_UID"};
  62. for (const auto &Key: EnvKeys)
  63. {
  64. if (getenv(Key) != nullptr)
  65. {
  66. int uid = atoi(getenv(Key));
  67. if (uid > 0) {
  68. struct passwd pwd;
  69. struct passwd *result;
  70. char buf[255];
  71. if (getpwuid_r(uid, &pwd, buf, sizeof(buf), &result) == 0 && result != NULL) {
  72. std::string res;
  73. strprintf(res, "%s (%d)", pwd.pw_name, uid);
  74. return res;
  75. }
  76. }
  77. }
  78. }
  79. return "";
  80. }
  81. /*}}}*/
  82. APT_PURE static unsigned int EnvironmentSize() /*{{{*/
  83. {
  84. unsigned int size = 0;
  85. char **envp = environ;
  86. while (*envp != NULL)
  87. size += strlen (*envp++) + 1;
  88. return size;
  89. }
  90. /*}}}*/
  91. class pkgDPkgPMPrivate /*{{{*/
  92. {
  93. public:
  94. pkgDPkgPMPrivate() : stdin_is_dev_null(false), dpkgbuf_pos(0),
  95. term_out(NULL), history_out(NULL),
  96. progress(NULL), tt_is_valid(false), master(-1),
  97. slave(NULL), protect_slave_from_dying(-1),
  98. direct_stdin(false)
  99. {
  100. dpkgbuf[0] = '\0';
  101. }
  102. ~pkgDPkgPMPrivate()
  103. {
  104. }
  105. bool stdin_is_dev_null;
  106. // the buffer we use for the dpkg status-fd reading
  107. char dpkgbuf[1024];
  108. size_t dpkgbuf_pos;
  109. FILE *term_out;
  110. FILE *history_out;
  111. string dpkg_error;
  112. APT::Progress::PackageManager *progress;
  113. // pty stuff
  114. struct termios tt;
  115. bool tt_is_valid;
  116. int master;
  117. char * slave;
  118. int protect_slave_from_dying;
  119. // signals
  120. sigset_t sigmask;
  121. sigset_t original_sigmask;
  122. bool direct_stdin;
  123. };
  124. /*}}}*/
  125. namespace
  126. {
  127. // Maps the dpkg "processing" info to human readable names. Entry 0
  128. // of each array is the key, entry 1 is the value.
  129. const std::pair<const char *, const char *> PackageProcessingOps[] = {
  130. std::make_pair("install", N_("Installing %s")),
  131. // we don't care for the difference
  132. std::make_pair("upgrade", N_("Installing %s")),
  133. std::make_pair("configure", N_("Configuring %s")),
  134. std::make_pair("remove", N_("Removing %s")),
  135. std::make_pair("purge", N_("Completely removing %s")),
  136. std::make_pair("disappear", N_("Noting disappearance of %s")),
  137. std::make_pair("trigproc", N_("Running post-installation trigger %s"))
  138. };
  139. const std::pair<const char *, const char *> * const PackageProcessingOpsBegin = PackageProcessingOps;
  140. const std::pair<const char *, const char *> * const PackageProcessingOpsEnd = PackageProcessingOps + sizeof(PackageProcessingOps) / sizeof(PackageProcessingOps[0]);
  141. // Predicate to test whether an entry in the PackageProcessingOps
  142. // array matches a string.
  143. class MatchProcessingOp
  144. {
  145. const char *target;
  146. public:
  147. explicit MatchProcessingOp(const char *the_target)
  148. : target(the_target)
  149. {
  150. }
  151. bool operator()(const std::pair<const char *, const char *> &pair) const
  152. {
  153. return strcmp(pair.first, target) == 0;
  154. }
  155. };
  156. }
  157. // ionice - helper function to ionice the given PID /*{{{*/
  158. /* there is no C header for ionice yet - just the syscall interface
  159. so we use the binary from util-linux */
  160. static bool ionice(int PID)
  161. {
  162. if (!FileExists("/usr/bin/ionice"))
  163. return false;
  164. pid_t Process = ExecFork();
  165. if (Process == 0)
  166. {
  167. char buf[32];
  168. snprintf(buf, sizeof(buf), "-p%d", PID);
  169. const char *Args[4];
  170. Args[0] = "/usr/bin/ionice";
  171. Args[1] = "-c3";
  172. Args[2] = buf;
  173. Args[3] = 0;
  174. execv(Args[0], (char **)Args);
  175. }
  176. return ExecWait(Process, "ionice");
  177. }
  178. /*}}}*/
  179. // FindNowVersion - Helper to find a Version in "now" state /*{{{*/
  180. // ---------------------------------------------------------------------
  181. /* This is helpful when a package is no longer installed but has residual
  182. * config files
  183. */
  184. static
  185. pkgCache::VerIterator FindNowVersion(const pkgCache::PkgIterator &Pkg)
  186. {
  187. pkgCache::VerIterator Ver;
  188. for (Ver = Pkg.VersionList(); Ver.end() == false; ++Ver)
  189. for (pkgCache::VerFileIterator Vf = Ver.FileList(); Vf.end() == false; ++Vf)
  190. for (pkgCache::PkgFileIterator F = Vf.File(); F.end() == false; ++F)
  191. {
  192. if (F.Archive() != 0 && strcmp(F.Archive(), "now") == 0)
  193. return Ver;
  194. }
  195. return Ver;
  196. }
  197. /*}}}*/
  198. static pkgCache::VerIterator FindToBeRemovedVersion(pkgCache::PkgIterator const &Pkg)/*{{{*/
  199. {
  200. auto const PV = Pkg.CurrentVer();
  201. if (PV.end() == false)
  202. return PV;
  203. return FindNowVersion(Pkg);
  204. }
  205. /*}}}*/
  206. // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
  207. // ---------------------------------------------------------------------
  208. /* */
  209. pkgDPkgPM::pkgDPkgPM(pkgDepCache *Cache)
  210. : pkgPackageManager(Cache),d(new pkgDPkgPMPrivate()), pkgFailures(0), PackagesDone(0), PackagesTotal(0)
  211. {
  212. }
  213. /*}}}*/
  214. // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
  215. // ---------------------------------------------------------------------
  216. /* */
  217. pkgDPkgPM::~pkgDPkgPM()
  218. {
  219. delete d;
  220. }
  221. /*}}}*/
  222. // DPkgPM::Install - Install a package /*{{{*/
  223. // ---------------------------------------------------------------------
  224. /* Add an install operation to the sequence list */
  225. bool pkgDPkgPM::Install(PkgIterator Pkg,string File)
  226. {
  227. if (File.empty() == true || Pkg.end() == true)
  228. return _error->Error("Internal Error, No file name for %s",Pkg.FullName().c_str());
  229. // If the filename string begins with DPkg::Chroot-Directory, return the
  230. // substr that is within the chroot so dpkg can access it.
  231. string const chrootdir = _config->FindDir("DPkg::Chroot-Directory","/");
  232. if (chrootdir != "/" && File.find(chrootdir) == 0)
  233. {
  234. size_t len = chrootdir.length();
  235. if (chrootdir.at(len - 1) == '/')
  236. len--;
  237. List.push_back(Item(Item::Install,Pkg,File.substr(len)));
  238. }
  239. else
  240. List.push_back(Item(Item::Install,Pkg,File));
  241. return true;
  242. }
  243. /*}}}*/
  244. // DPkgPM::Configure - Configure a package /*{{{*/
  245. // ---------------------------------------------------------------------
  246. /* Add a configure operation to the sequence list */
  247. bool pkgDPkgPM::Configure(PkgIterator Pkg)
  248. {
  249. if (Pkg.end() == true)
  250. return false;
  251. List.push_back(Item(Item::Configure, Pkg));
  252. // Use triggers for config calls if we configure "smart"
  253. // as otherwise Pre-Depends will not be satisfied, see #526774
  254. if (_config->FindB("DPkg::TriggersPending", false) == true)
  255. List.push_back(Item(Item::TriggersPending, PkgIterator()));
  256. return true;
  257. }
  258. /*}}}*/
  259. // DPkgPM::Remove - Remove a package /*{{{*/
  260. // ---------------------------------------------------------------------
  261. /* Add a remove operation to the sequence list */
  262. bool pkgDPkgPM::Remove(PkgIterator Pkg,bool Purge)
  263. {
  264. if (Pkg.end() == true)
  265. return false;
  266. if (Purge == true)
  267. List.push_back(Item(Item::Purge,Pkg));
  268. else
  269. List.push_back(Item(Item::Remove,Pkg));
  270. return true;
  271. }
  272. /*}}}*/
  273. // DPkgPM::SendPkgInfo - Send info for install-pkgs hook /*{{{*/
  274. // ---------------------------------------------------------------------
  275. /* This is part of the helper script communication interface, it sends
  276. very complete information down to the other end of the pipe.*/
  277. bool pkgDPkgPM::SendV2Pkgs(FILE *F)
  278. {
  279. return SendPkgsInfo(F, 2);
  280. }
  281. bool pkgDPkgPM::SendPkgsInfo(FILE * const F, unsigned int const &Version)
  282. {
  283. // This version of APT supports only v3, so don't sent higher versions
  284. if (Version <= 3)
  285. fprintf(F,"VERSION %u\n", Version);
  286. else
  287. fprintf(F,"VERSION 3\n");
  288. /* Write out all of the configuration directives by walking the
  289. configuration tree */
  290. const Configuration::Item *Top = _config->Tree(0);
  291. for (; Top != 0;)
  292. {
  293. if (Top->Value.empty() == false)
  294. {
  295. fprintf(F,"%s=%s\n",
  296. QuoteString(Top->FullTag(),"=\"\n").c_str(),
  297. QuoteString(Top->Value,"\n").c_str());
  298. }
  299. if (Top->Child != 0)
  300. {
  301. Top = Top->Child;
  302. continue;
  303. }
  304. while (Top != 0 && Top->Next == 0)
  305. Top = Top->Parent;
  306. if (Top != 0)
  307. Top = Top->Next;
  308. }
  309. fprintf(F,"\n");
  310. // Write out the package actions in order.
  311. for (vector<Item>::iterator I = List.begin(); I != List.end(); ++I)
  312. {
  313. if(I->Pkg.end() == true)
  314. continue;
  315. pkgDepCache::StateCache &S = Cache[I->Pkg];
  316. fprintf(F,"%s ",I->Pkg.Name());
  317. // Current version which we are going to replace
  318. pkgCache::VerIterator CurVer = I->Pkg.CurrentVer();
  319. if (CurVer.end() == true && (I->Op == Item::Remove || I->Op == Item::Purge))
  320. CurVer = FindNowVersion(I->Pkg);
  321. if (CurVer.end() == true)
  322. {
  323. if (Version <= 2)
  324. fprintf(F, "- ");
  325. else
  326. fprintf(F, "- - none ");
  327. }
  328. else
  329. {
  330. fprintf(F, "%s ", CurVer.VerStr());
  331. if (Version >= 3)
  332. fprintf(F, "%s %s ", CurVer.Arch(), CurVer.MultiArchType());
  333. }
  334. // Show the compare operator between current and install version
  335. if (S.InstallVer != 0)
  336. {
  337. pkgCache::VerIterator const InstVer = S.InstVerIter(Cache);
  338. int Comp = 2;
  339. if (CurVer.end() == false)
  340. Comp = InstVer.CompareVer(CurVer);
  341. if (Comp < 0)
  342. fprintf(F,"> ");
  343. else if (Comp == 0)
  344. fprintf(F,"= ");
  345. else if (Comp > 0)
  346. fprintf(F,"< ");
  347. fprintf(F, "%s ", InstVer.VerStr());
  348. if (Version >= 3)
  349. fprintf(F, "%s %s ", InstVer.Arch(), InstVer.MultiArchType());
  350. }
  351. else
  352. {
  353. if (Version <= 2)
  354. fprintf(F, "> - ");
  355. else
  356. fprintf(F, "> - - none ");
  357. }
  358. // Show the filename/operation
  359. if (I->Op == Item::Install)
  360. {
  361. // No errors here..
  362. if (I->File[0] != '/')
  363. fprintf(F,"**ERROR**\n");
  364. else
  365. fprintf(F,"%s\n",I->File.c_str());
  366. }
  367. else if (I->Op == Item::Configure)
  368. fprintf(F,"**CONFIGURE**\n");
  369. else if (I->Op == Item::Remove ||
  370. I->Op == Item::Purge)
  371. fprintf(F,"**REMOVE**\n");
  372. if (ferror(F) != 0)
  373. return false;
  374. }
  375. return true;
  376. }
  377. /*}}}*/
  378. // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
  379. // ---------------------------------------------------------------------
  380. /* This looks for a list of scripts to run from the configuration file
  381. each one is run and is fed on standard input a list of all .deb files
  382. that are due to be installed. */
  383. bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf)
  384. {
  385. bool result = true;
  386. Configuration::Item const *Opts = _config->Tree(Cnf);
  387. if (Opts == 0 || Opts->Child == 0)
  388. return true;
  389. Opts = Opts->Child;
  390. sighandler_t old_sigpipe = signal(SIGPIPE, SIG_IGN);
  391. sighandler_t old_sigint = signal(SIGINT, SIG_IGN);
  392. sighandler_t old_sigquit = signal(SIGQUIT, SIG_IGN);
  393. unsigned int Count = 1;
  394. for (; Opts != 0; Opts = Opts->Next, Count++)
  395. {
  396. if (Opts->Value.empty() == true)
  397. continue;
  398. if(_config->FindB("Debug::RunScripts", false) == true)
  399. std::clog << "Running external script with list of all .deb file: '"
  400. << Opts->Value << "'" << std::endl;
  401. // Determine the protocol version
  402. string OptSec = Opts->Value;
  403. string::size_type Pos;
  404. if ((Pos = OptSec.find(' ')) == string::npos || Pos == 0)
  405. Pos = OptSec.length();
  406. OptSec = "DPkg::Tools::Options::" + string(Opts->Value.c_str(),Pos);
  407. unsigned int Version = _config->FindI(OptSec+"::Version",1);
  408. unsigned int InfoFD = _config->FindI(OptSec + "::InfoFD", STDIN_FILENO);
  409. // Create the pipes
  410. std::set<int> KeepFDs;
  411. MergeKeepFdsFromConfiguration(KeepFDs);
  412. int Pipes[2];
  413. if (pipe(Pipes) != 0) {
  414. result = _error->Errno("pipe","Failed to create IPC pipe to subprocess");
  415. break;
  416. }
  417. if (InfoFD != (unsigned)Pipes[0])
  418. SetCloseExec(Pipes[0],true);
  419. else
  420. KeepFDs.insert(Pipes[0]);
  421. SetCloseExec(Pipes[1],true);
  422. // Purified Fork for running the script
  423. pid_t Process = ExecFork(KeepFDs);
  424. if (Process == 0)
  425. {
  426. // Setup the FDs
  427. dup2(Pipes[0], InfoFD);
  428. SetCloseExec(STDOUT_FILENO,false);
  429. SetCloseExec(STDIN_FILENO,false);
  430. SetCloseExec(STDERR_FILENO,false);
  431. string hookfd;
  432. strprintf(hookfd, "%d", InfoFD);
  433. setenv("APT_HOOK_INFO_FD", hookfd.c_str(), 1);
  434. debSystem::DpkgChrootDirectory();
  435. const char *Args[4];
  436. Args[0] = "/bin/sh";
  437. Args[1] = "-c";
  438. Args[2] = Opts->Value.c_str();
  439. Args[3] = 0;
  440. execv(Args[0],(char **)Args);
  441. _exit(100);
  442. }
  443. close(Pipes[0]);
  444. FILE *F = fdopen(Pipes[1],"w");
  445. if (F == 0) {
  446. result = _error->Errno("fdopen","Failed to open new FD");
  447. break;
  448. }
  449. // Feed it the filenames.
  450. if (Version <= 1)
  451. {
  452. for (vector<Item>::iterator I = List.begin(); I != List.end(); ++I)
  453. {
  454. // Only deal with packages to be installed from .deb
  455. if (I->Op != Item::Install)
  456. continue;
  457. // No errors here..
  458. if (I->File[0] != '/')
  459. continue;
  460. /* Feed the filename of each package that is pending install
  461. into the pipe. */
  462. fprintf(F,"%s\n",I->File.c_str());
  463. if (ferror(F) != 0)
  464. break;
  465. }
  466. }
  467. else
  468. SendPkgsInfo(F, Version);
  469. fclose(F);
  470. // Clean up the sub process
  471. if (ExecWait(Process,Opts->Value.c_str()) == false) {
  472. result = _error->Error("Failure running script %s",Opts->Value.c_str());
  473. break;
  474. }
  475. }
  476. signal(SIGINT, old_sigint);
  477. signal(SIGPIPE, old_sigpipe);
  478. signal(SIGQUIT, old_sigquit);
  479. return result;
  480. }
  481. /*}}}*/
  482. // DPkgPM::DoStdin - Read stdin and pass to master pty /*{{{*/
  483. // ---------------------------------------------------------------------
  484. /*
  485. */
  486. void pkgDPkgPM::DoStdin(int master)
  487. {
  488. unsigned char input_buf[256] = {0,};
  489. ssize_t len = read(STDIN_FILENO, input_buf, sizeof(input_buf));
  490. if (len)
  491. FileFd::Write(master, input_buf, len);
  492. else
  493. d->stdin_is_dev_null = true;
  494. }
  495. /*}}}*/
  496. // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
  497. // ---------------------------------------------------------------------
  498. /*
  499. * read the terminal pty and write log
  500. */
  501. void pkgDPkgPM::DoTerminalPty(int master)
  502. {
  503. unsigned char term_buf[1024] = {0,0, };
  504. ssize_t len=read(master, term_buf, sizeof(term_buf));
  505. if(len == -1 && errno == EIO)
  506. {
  507. // this happens when the child is about to exit, we
  508. // give it time to actually exit, otherwise we run
  509. // into a race so we sleep for half a second.
  510. struct timespec sleepfor = { 0, 500000000 };
  511. nanosleep(&sleepfor, NULL);
  512. return;
  513. }
  514. if(len <= 0)
  515. return;
  516. FileFd::Write(1, term_buf, len);
  517. if(d->term_out)
  518. fwrite(term_buf, len, sizeof(char), d->term_out);
  519. }
  520. /*}}}*/
  521. // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
  522. void pkgDPkgPM::ProcessDpkgStatusLine(char *line)
  523. {
  524. bool const Debug = _config->FindB("Debug::pkgDPkgProgressReporting",false);
  525. if (Debug == true)
  526. std::clog << "got from dpkg '" << line << "'" << std::endl;
  527. /* dpkg sends strings like this:
  528. 'status: <pkg>: <pkg qstate>'
  529. 'status: <pkg>:<arch>: <pkg qstate>'
  530. 'processing: {install,upgrade,configure,remove,purge,disappear,trigproc}: pkg'
  531. 'processing: {install,upgrade,configure,remove,purge,disappear,trigproc}: trigger'
  532. */
  533. // we need to split on ": " (note the appended space) as the ':' is
  534. // part of the pkgname:arch information that dpkg sends
  535. //
  536. // A dpkg error message may contain additional ":" (like
  537. // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
  538. // so we need to ensure to not split too much
  539. std::vector<std::string> list = StringSplit(line, ": ", 4);
  540. if(list.size() < 3)
  541. {
  542. if (Debug == true)
  543. std::clog << "ignoring line: not enough ':'" << std::endl;
  544. return;
  545. }
  546. // build the (prefix, pkgname, action) tuple, position of this
  547. // is different for "processing" or "status" messages
  548. std::string prefix = APT::String::Strip(list[0]);
  549. std::string pkgname;
  550. std::string action;
  551. // "processing" has the form "processing: action: pkg or trigger"
  552. // with action = ["install", "upgrade", "configure", "remove", "purge",
  553. // "disappear", "trigproc"]
  554. if (prefix == "processing")
  555. {
  556. pkgname = APT::String::Strip(list[2]);
  557. action = APT::String::Strip(list[1]);
  558. }
  559. // "status" has the form: "status: pkg: state"
  560. // with state in ["half-installed", "unpacked", "half-configured",
  561. // "installed", "config-files", "not-installed"]
  562. else if (prefix == "status")
  563. {
  564. pkgname = APT::String::Strip(list[1]);
  565. action = APT::String::Strip(list[2]);
  566. /* handle the special cases first:
  567. errors look like this:
  568. '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
  569. and conffile-prompt like this
  570. 'status:/etc/compiz.conf/compiz.conf : conffile-prompt: 'current-conffile' 'new-conffile' useredited distedited
  571. */
  572. if(action == "error")
  573. {
  574. d->progress->Error(pkgname, PackagesDone, PackagesTotal, list[3]);
  575. ++pkgFailures;
  576. WriteApportReport(pkgname.c_str(), list[3].c_str());
  577. return;
  578. }
  579. else if(action == "conffile-prompt")
  580. {
  581. d->progress->ConffilePrompt(pkgname, PackagesDone, PackagesTotal, list[3]);
  582. return;
  583. }
  584. } else {
  585. if (Debug == true)
  586. std::clog << "unknown prefix '" << prefix << "'" << std::endl;
  587. return;
  588. }
  589. // At this point we have a pkgname, but it might not be arch-qualified !
  590. if (pkgname.find(":") == std::string::npos)
  591. {
  592. pkgCache::GrpIterator Grp = Cache.FindGrp(pkgname);
  593. /* No arch means that dpkg believes there can only be one package
  594. this can refer to so lets see what could be candidates here: */
  595. std::vector<pkgCache::PkgIterator> candset;
  596. for (auto P = Grp.PackageList(); P.end() != true; P = Grp.NextPkg(P))
  597. {
  598. if (PackageOps.find(P.FullName()) != PackageOps.end())
  599. candset.push_back(P);
  600. // packages can disappear without them having any interaction itself
  601. // so we have to consider these as candidates, too
  602. else if (P->CurrentVer != 0 && action == "disappear")
  603. candset.push_back(P);
  604. }
  605. if (unlikely(candset.empty()))
  606. {
  607. if (Debug == true)
  608. std::clog << "unable to figure out which package is dpkg refering to with '" << pkgname << "'! (1)" << std::endl;
  609. return;
  610. }
  611. else if (candset.size() == 1) // we are lucky
  612. pkgname = candset.cbegin()->FullName();
  613. else
  614. {
  615. /* here be dragons^Wassumptions about dpkg:
  616. - an M-A:same version is always arch-qualified
  617. - a package from a foreign arch is (in newer versions) */
  618. size_t installedInstances = 0, wannabeInstances = 0;
  619. for (auto const &P: candset)
  620. {
  621. if (P->CurrentVer != 0)
  622. {
  623. ++installedInstances;
  624. if (Cache[P].Delete() == false)
  625. ++wannabeInstances;
  626. }
  627. else if (Cache[P].Install())
  628. ++wannabeInstances;
  629. }
  630. // the package becomes M-A:same, so we are still talking about current
  631. if (installedInstances == 1 && wannabeInstances >= 2)
  632. {
  633. for (auto const &P: candset)
  634. {
  635. if (P->CurrentVer == 0)
  636. continue;
  637. pkgname = P.FullName();
  638. break;
  639. }
  640. }
  641. // the package was M-A:same, it isn't now, so we can only talk about that
  642. else if (installedInstances >= 2 && wannabeInstances == 1)
  643. {
  644. for (auto const &P: candset)
  645. {
  646. auto const IV = Cache[P].InstVerIter(Cache);
  647. if (IV.end())
  648. continue;
  649. pkgname = P.FullName();
  650. break;
  651. }
  652. }
  653. // that is a crossgrade
  654. else if (installedInstances == 1 && wannabeInstances == 1 && candset.size() == 2)
  655. {
  656. auto const PkgHasCurrentVersion = [](pkgCache::PkgIterator const &P) { return P->CurrentVer != 0; };
  657. auto const P = std::find_if(candset.begin(), candset.end(), PkgHasCurrentVersion);
  658. if (unlikely(P == candset.end()))
  659. {
  660. if (Debug == true)
  661. std::clog << "situation for '" << pkgname << "' looked like a crossgrade, but no current version?!" << std::endl;
  662. return;
  663. }
  664. auto fullname = P->FullName();
  665. if (PackageOps[fullname].size() != PackageOpsDone[fullname])
  666. pkgname = std::move(fullname);
  667. else
  668. pkgname = std::find_if_not(candset.begin(), candset.end(), PkgHasCurrentVersion)->FullName();
  669. }
  670. // we are desperate: so "just" take the native one, but that might change mid-air,
  671. // so we have to ask dpkg what it believes native is at the moment… all the time
  672. else
  673. {
  674. std::vector<std::string> sArgs = debSystem::GetDpkgBaseCommand();
  675. sArgs.push_back("--print-architecture");
  676. int outputFd = -1;
  677. pid_t const dpkgNativeArch = debSystem::ExecDpkg(sArgs, nullptr, &outputFd, true);
  678. if (unlikely(dpkgNativeArch == -1))
  679. {
  680. if (Debug == true)
  681. std::clog << "calling dpkg failed to ask it for its current native architecture to expand '" << pkgname << "'!" << std::endl;
  682. return;
  683. }
  684. FILE *dpkg = fdopen(outputFd, "r");
  685. if(dpkg != NULL)
  686. {
  687. char* buf = NULL;
  688. size_t bufsize = 0;
  689. if (getline(&buf, &bufsize, dpkg) != -1)
  690. pkgname += ':' + bufsize;
  691. free(buf);
  692. fclose(dpkg);
  693. }
  694. ExecWait(dpkgNativeArch, "dpkg --print-architecture", true);
  695. if (pkgname.find(':') != std::string::npos)
  696. {
  697. if (Debug == true)
  698. std::clog << "unable to figure out which package is dpkg refering to with '" << pkgname << "'! (2)" << std::endl;
  699. return;
  700. }
  701. }
  702. }
  703. }
  704. std::string arch = "";
  705. if (pkgname.find(":") != string::npos)
  706. arch = StringSplit(pkgname, ":")[1];
  707. std::string i18n_pkgname = pkgname;
  708. if (arch.size() != 0)
  709. strprintf(i18n_pkgname, "%s (%s)", StringSplit(pkgname, ":")[0].c_str(), arch.c_str());
  710. // 'processing' from dpkg looks like
  711. // 'processing: action: pkg'
  712. if(prefix == "processing")
  713. {
  714. auto const iter = std::find_if(PackageProcessingOpsBegin, PackageProcessingOpsEnd, MatchProcessingOp(action.c_str()));
  715. if(iter == PackageProcessingOpsEnd)
  716. {
  717. if (Debug == true)
  718. std::clog << "ignoring unknown action: " << action << std::endl;
  719. return;
  720. }
  721. std::string msg;
  722. strprintf(msg, _(iter->second), i18n_pkgname.c_str());
  723. d->progress->StatusChanged(pkgname, PackagesDone, PackagesTotal, msg);
  724. // FIXME: this needs a muliarch testcase
  725. // FIXME2: is "pkgname" here reliable with dpkg only sending us
  726. // short pkgnames?
  727. if (action == "disappear")
  728. handleDisappearAction(pkgname);
  729. else if (action == "upgrade")
  730. handleCrossUpgradeAction(pkgname);
  731. return;
  732. }
  733. if (prefix == "status")
  734. {
  735. std::vector<struct DpkgState> &states = PackageOps[pkgname];
  736. if(PackageOpsDone[pkgname] < states.size())
  737. {
  738. char const * next_action = states[PackageOpsDone[pkgname]].state;
  739. if (next_action)
  740. {
  741. /*
  742. if (action == "half-installed" && strcmp("half-configured", next_action) == 0 &&
  743. PackageOpsDone[pkg] + 2 < states.size() && action == states[PackageOpsDone[pkg] + 2].state)
  744. {
  745. if (Debug == true)
  746. std::clog << "(parsed from dpkg) pkg: " << short_pkgname << " action: " << action
  747. << " pending trigger defused by unpack" << std::endl;
  748. // unpacking a package defuses the pending trigger
  749. PackageOpsDone[pkg] += 2;
  750. PackagesDone += 2;
  751. next_action = states[PackageOpsDone[pkg]].state;
  752. }
  753. */
  754. if (Debug == true)
  755. std::clog << "(parsed from dpkg) pkg: " << pkgname
  756. << " action: " << action << " (expected: '" << next_action << "' "
  757. << PackageOpsDone[pkgname] << " of " << states.size() << ")" << endl;
  758. // check if the package moved to the next dpkg state
  759. if(action == next_action)
  760. {
  761. // only read the translation if there is actually a next action
  762. char const * const translation = _(states[PackageOpsDone[pkgname]].str);
  763. // we moved from one dpkg state to a new one, report that
  764. ++PackageOpsDone[pkgname];
  765. ++PackagesDone;
  766. std::string msg;
  767. strprintf(msg, translation, i18n_pkgname.c_str());
  768. d->progress->StatusChanged(pkgname, PackagesDone, PackagesTotal, msg);
  769. }
  770. }
  771. }
  772. else if (action == "triggers-pending")
  773. {
  774. if (Debug == true)
  775. std::clog << "(parsed from dpkg) pkg: " << pkgname
  776. << " action: " << action << " (prefix 2 to "
  777. << PackageOpsDone[pkgname] << " of " << states.size() << ")" << endl;
  778. states.insert(states.begin(), {"installed", N_("Installed %s")});
  779. states.insert(states.begin(), {"half-configured", N_("Configuring %s")});
  780. PackagesTotal += 2;
  781. }
  782. }
  783. }
  784. /*}}}*/
  785. // DPkgPM::handleDisappearAction /*{{{*/
  786. void pkgDPkgPM::handleDisappearAction(string const &pkgname)
  787. {
  788. pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
  789. if (unlikely(Pkg.end() == true))
  790. return;
  791. // a disappeared package has no further actions
  792. auto const ROps = PackageOps[Pkg.FullName()].size();
  793. auto && ROpsDone = PackageOpsDone[Pkg.FullName()];
  794. PackagesDone += ROps - ROpsDone;
  795. ROpsDone = ROps;
  796. // record the package name for display and stuff later
  797. disappearedPkgs.insert(Pkg.FullName(true));
  798. // the disappeared package was auto-installed - nothing to do
  799. if ((Cache[Pkg].Flags & pkgCache::Flag::Auto) == pkgCache::Flag::Auto)
  800. return;
  801. pkgCache::VerIterator PkgVer = Cache[Pkg].InstVerIter(Cache);
  802. if (unlikely(PkgVer.end() == true))
  803. return;
  804. /* search in the list of dependencies for (Pre)Depends,
  805. check if this dependency has a Replaces on our package
  806. and if so transfer the manual installed flag to it */
  807. for (pkgCache::DepIterator Dep = PkgVer.DependsList(); Dep.end() != true; ++Dep)
  808. {
  809. if (Dep->Type != pkgCache::Dep::Depends &&
  810. Dep->Type != pkgCache::Dep::PreDepends)
  811. continue;
  812. pkgCache::PkgIterator Tar = Dep.TargetPkg();
  813. if (unlikely(Tar.end() == true))
  814. continue;
  815. // the package is already marked as manual
  816. if ((Cache[Tar].Flags & pkgCache::Flag::Auto) != pkgCache::Flag::Auto)
  817. continue;
  818. pkgCache::VerIterator TarVer = Cache[Tar].InstVerIter(Cache);
  819. if (TarVer.end() == true)
  820. continue;
  821. for (pkgCache::DepIterator Rep = TarVer.DependsList(); Rep.end() != true; ++Rep)
  822. {
  823. if (Rep->Type != pkgCache::Dep::Replaces)
  824. continue;
  825. if (Pkg != Rep.TargetPkg())
  826. continue;
  827. // okay, they are strongly connected - transfer manual-bit
  828. if (Debug == true)
  829. std::clog << "transfer manual-bit from disappeared »" << pkgname << "« to »" << Tar.FullName() << "«" << std::endl;
  830. Cache[Tar].Flags &= ~Flag::Auto;
  831. break;
  832. }
  833. }
  834. }
  835. /*}}}*/
  836. void pkgDPkgPM::handleCrossUpgradeAction(string const &pkgname) /*{{{*/
  837. {
  838. // in a crossgrade what looked like a remove first is really an unpack over it
  839. auto const Pkg = Cache.FindPkg(pkgname);
  840. if (likely(Pkg.end() == false) && Cache[Pkg].Delete())
  841. {
  842. auto const Grp = Pkg.Group();
  843. if (likely(Grp.end() == false))
  844. {
  845. for (auto P = Grp.PackageList(); P.end() != true; P = Grp.NextPkg(P))
  846. if(Cache[P].Install())
  847. {
  848. auto && Ops = PackageOps[P.FullName()];
  849. auto const unpackOp = std::find_if(Ops.cbegin(), Ops.cend(), [](DpkgState const &s) { return strcmp(s.state, "unpacked") == 0; });
  850. if (unpackOp != Ops.cend())
  851. {
  852. // skip ahead in the crossgraded packages
  853. auto const skipped = std::distance(Ops.cbegin(), unpackOp);
  854. PackagesDone += skipped;
  855. PackageOpsDone[P.FullName()] += skipped;
  856. // finish the crossremoved package
  857. auto const ROps = PackageOps[Pkg.FullName()].size();
  858. auto && ROpsDone = PackageOpsDone[Pkg.FullName()];
  859. PackagesDone += ROps - ROpsDone;
  860. ROpsDone = ROps;
  861. break;
  862. }
  863. }
  864. }
  865. }
  866. }
  867. /*}}}*/
  868. // DPkgPM::DoDpkgStatusFd /*{{{*/
  869. void pkgDPkgPM::DoDpkgStatusFd(int statusfd)
  870. {
  871. ssize_t const len = read(statusfd, &d->dpkgbuf[d->dpkgbuf_pos],
  872. (sizeof(d->dpkgbuf)/sizeof(d->dpkgbuf[0])) - d->dpkgbuf_pos);
  873. if(len <= 0)
  874. return;
  875. d->dpkgbuf_pos += (len / sizeof(d->dpkgbuf[0]));
  876. // process line by line from the buffer
  877. char *p = d->dpkgbuf, *q = nullptr;
  878. while((q=(char*)memchr(p, '\n', (d->dpkgbuf + d->dpkgbuf_pos) - p)) != nullptr)
  879. {
  880. *q = '\0';
  881. ProcessDpkgStatusLine(p);
  882. p = q + 1; // continue with next line
  883. }
  884. // check if we stripped the buffer clean
  885. if (p > (d->dpkgbuf + d->dpkgbuf_pos))
  886. {
  887. d->dpkgbuf_pos = 0;
  888. return;
  889. }
  890. // otherwise move the unprocessed tail to the start and update pos
  891. memmove(d->dpkgbuf, p, (p - d->dpkgbuf));
  892. d->dpkgbuf_pos = (d->dpkgbuf + d->dpkgbuf_pos) - p;
  893. }
  894. /*}}}*/
  895. // DPkgPM::WriteHistoryTag /*{{{*/
  896. void pkgDPkgPM::WriteHistoryTag(string const &tag, string value)
  897. {
  898. size_t const length = value.length();
  899. if (length == 0)
  900. return;
  901. // poor mans rstrip(", ")
  902. if (value[length-2] == ',' && value[length-1] == ' ')
  903. value.erase(length - 2, 2);
  904. fprintf(d->history_out, "%s: %s\n", tag.c_str(), value.c_str());
  905. } /*}}}*/
  906. // DPkgPM::OpenLog /*{{{*/
  907. bool pkgDPkgPM::OpenLog()
  908. {
  909. string const logdir = _config->FindDir("Dir::Log");
  910. if(CreateAPTDirectoryIfNeeded(logdir, logdir) == false)
  911. // FIXME: use a better string after freeze
  912. return _error->Error(_("Directory '%s' missing"), logdir.c_str());
  913. // get current time
  914. char timestr[200];
  915. time_t const t = time(NULL);
  916. struct tm tm_buf;
  917. struct tm const * const tmp = localtime_r(&t, &tm_buf);
  918. strftime(timestr, sizeof(timestr), "%F %T", tmp);
  919. // open terminal log
  920. string const logfile_name = flCombine(logdir,
  921. _config->Find("Dir::Log::Terminal"));
  922. if (!logfile_name.empty())
  923. {
  924. d->term_out = fopen(logfile_name.c_str(),"a");
  925. if (d->term_out == NULL)
  926. return _error->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name.c_str());
  927. setvbuf(d->term_out, NULL, _IONBF, 0);
  928. SetCloseExec(fileno(d->term_out), true);
  929. if (getuid() == 0) // if we aren't root, we can't chown a file, so don't try it
  930. {
  931. struct passwd *pw = getpwnam("root");
  932. struct group *gr = getgrnam("adm");
  933. if (pw != NULL && gr != NULL && chown(logfile_name.c_str(), pw->pw_uid, gr->gr_gid) != 0)
  934. _error->WarningE("OpenLog", "chown to root:adm of file %s failed", logfile_name.c_str());
  935. }
  936. if (chmod(logfile_name.c_str(), 0640) != 0)
  937. _error->WarningE("OpenLog", "chmod 0640 of file %s failed", logfile_name.c_str());
  938. fprintf(d->term_out, "\nLog started: %s\n", timestr);
  939. }
  940. // write your history
  941. string const history_name = flCombine(logdir,
  942. _config->Find("Dir::Log::History"));
  943. if (!history_name.empty())
  944. {
  945. d->history_out = fopen(history_name.c_str(),"a");
  946. if (d->history_out == NULL)
  947. return _error->WarningE("OpenLog", _("Could not open file '%s'"), history_name.c_str());
  948. SetCloseExec(fileno(d->history_out), true);
  949. chmod(history_name.c_str(), 0644);
  950. fprintf(d->history_out, "\nStart-Date: %s\n", timestr);
  951. string remove, purge, install, reinstall, upgrade, downgrade;
  952. for (pkgCache::PkgIterator I = Cache.PkgBegin(); I.end() == false; ++I)
  953. {
  954. enum { CANDIDATE, CANDIDATE_AUTO, CURRENT_CANDIDATE, CURRENT } infostring;
  955. string *line = NULL;
  956. #define HISTORYINFO(X, Y) { line = &X; infostring = Y; }
  957. if (Cache[I].NewInstall() == true)
  958. HISTORYINFO(install, CANDIDATE_AUTO)
  959. else if (Cache[I].ReInstall() == true)
  960. HISTORYINFO(reinstall, CANDIDATE)
  961. else if (Cache[I].Upgrade() == true)
  962. HISTORYINFO(upgrade, CURRENT_CANDIDATE)
  963. else if (Cache[I].Downgrade() == true)
  964. HISTORYINFO(downgrade, CURRENT_CANDIDATE)
  965. else if (Cache[I].Delete() == true)
  966. HISTORYINFO((Cache[I].Purge() ? purge : remove), CURRENT)
  967. else
  968. continue;
  969. #undef HISTORYINFO
  970. line->append(I.FullName(false)).append(" (");
  971. switch (infostring) {
  972. case CANDIDATE: line->append(Cache[I].CandVersion); break;
  973. case CANDIDATE_AUTO:
  974. line->append(Cache[I].CandVersion);
  975. if ((Cache[I].Flags & pkgCache::Flag::Auto) == pkgCache::Flag::Auto)
  976. line->append(", automatic");
  977. break;
  978. case CURRENT_CANDIDATE: line->append(Cache[I].CurVersion).append(", ").append(Cache[I].CandVersion); break;
  979. case CURRENT: line->append(Cache[I].CurVersion); break;
  980. }
  981. line->append("), ");
  982. }
  983. if (_config->Exists("Commandline::AsString") == true)
  984. WriteHistoryTag("Commandline", _config->Find("Commandline::AsString"));
  985. std::string RequestingUser = AptHistoryRequestingUser();
  986. if (RequestingUser != "")
  987. WriteHistoryTag("Requested-By", RequestingUser);
  988. WriteHistoryTag("Install", install);
  989. WriteHistoryTag("Reinstall", reinstall);
  990. WriteHistoryTag("Upgrade", upgrade);
  991. WriteHistoryTag("Downgrade",downgrade);
  992. WriteHistoryTag("Remove",remove);
  993. WriteHistoryTag("Purge",purge);
  994. fflush(d->history_out);
  995. }
  996. return true;
  997. }
  998. /*}}}*/
  999. // DPkg::CloseLog /*{{{*/
  1000. bool pkgDPkgPM::CloseLog()
  1001. {
  1002. char timestr[200];
  1003. time_t t = time(NULL);
  1004. struct tm tm_buf;
  1005. struct tm *tmp = localtime_r(&t, &tm_buf);
  1006. strftime(timestr, sizeof(timestr), "%F %T", tmp);
  1007. if(d->term_out)
  1008. {
  1009. fprintf(d->term_out, "Log ended: ");
  1010. fprintf(d->term_out, "%s", timestr);
  1011. fprintf(d->term_out, "\n");
  1012. fclose(d->term_out);
  1013. }
  1014. d->term_out = NULL;
  1015. if(d->history_out)
  1016. {
  1017. if (disappearedPkgs.empty() == false)
  1018. {
  1019. string disappear;
  1020. for (std::set<std::string>::const_iterator d = disappearedPkgs.begin();
  1021. d != disappearedPkgs.end(); ++d)
  1022. {
  1023. pkgCache::PkgIterator P = Cache.FindPkg(*d);
  1024. disappear.append(*d);
  1025. if (P.end() == true)
  1026. disappear.append(", ");
  1027. else
  1028. disappear.append(" (").append(Cache[P].CurVersion).append("), ");
  1029. }
  1030. WriteHistoryTag("Disappeared", disappear);
  1031. }
  1032. if (d->dpkg_error.empty() == false)
  1033. fprintf(d->history_out, "Error: %s\n", d->dpkg_error.c_str());
  1034. fprintf(d->history_out, "End-Date: %s\n", timestr);
  1035. fclose(d->history_out);
  1036. }
  1037. d->history_out = NULL;
  1038. return true;
  1039. }
  1040. /*}}}*/
  1041. // DPkgPM::BuildPackagesProgressMap /*{{{*/
  1042. void pkgDPkgPM::BuildPackagesProgressMap()
  1043. {
  1044. // map the dpkg states to the operations that are performed
  1045. // (this is sorted in the same way as Item::Ops)
  1046. static const std::array<std::array<DpkgState, 3>, 4> DpkgStatesOpMap = {{
  1047. // Install operation
  1048. {{
  1049. {"half-installed", N_("Preparing %s")},
  1050. {"unpacked", N_("Unpacking %s") },
  1051. {nullptr, nullptr}
  1052. }},
  1053. // Configure operation
  1054. {{
  1055. {"unpacked",N_("Preparing to configure %s") },
  1056. {"half-configured", N_("Configuring %s") },
  1057. { "installed", N_("Installed %s")},
  1058. }},
  1059. // Remove operation
  1060. {{
  1061. {"half-configured", N_("Preparing for removal of %s")},
  1062. {"half-installed", N_("Removing %s")},
  1063. {"config-files", N_("Removed %s")},
  1064. }},
  1065. // Purge operation
  1066. {{
  1067. {"config-files", N_("Preparing to completely remove %s")},
  1068. {"not-installed", N_("Completely removed %s")},
  1069. {nullptr, nullptr}
  1070. }},
  1071. }};
  1072. static_assert(Item::Purge == 3, "Enum item has unexpected index for mapping array");
  1073. // init the PackageOps map, go over the list of packages that
  1074. // that will be [installed|configured|removed|purged] and add
  1075. // them to the PackageOps map (the dpkg states it goes through)
  1076. // and the PackageOpsTranslations (human readable strings)
  1077. for (auto &&I : List)
  1078. {
  1079. if(I.Pkg.end() == true)
  1080. continue;
  1081. string const name = I.Pkg.FullName();
  1082. PackageOpsDone[name] = 0;
  1083. auto AddToPackageOps = std::back_inserter(PackageOps[name]);
  1084. if (I.Op == Item::Purge && I.Pkg->CurrentVer != 0)
  1085. {
  1086. // purging a package which is installed first passes through remove states
  1087. auto const DpkgOps = DpkgStatesOpMap[Item::Remove];
  1088. std::copy(DpkgOps.begin(), DpkgOps.end(), AddToPackageOps);
  1089. PackagesTotal += DpkgOps.size();
  1090. }
  1091. auto const DpkgOps = DpkgStatesOpMap[I.Op];
  1092. std::copy_if(DpkgOps.begin(), DpkgOps.end(), AddToPackageOps, [&](DpkgState const &state) {
  1093. if (state.state == nullptr)
  1094. return false;
  1095. ++PackagesTotal;
  1096. return true;
  1097. });
  1098. if ((I.Op == Item::Remove || I.Op == Item::Purge) && I.Pkg->CurrentVer != 0)
  1099. {
  1100. if (I.Pkg->CurrentState == pkgCache::State::UnPacked ||
  1101. I.Pkg->CurrentState == pkgCache::State::HalfInstalled)
  1102. {
  1103. if (likely(strcmp(PackageOps[name][0].state, "half-configured") == 0))
  1104. {
  1105. ++PackageOpsDone[name];
  1106. --PackagesTotal;
  1107. }
  1108. }
  1109. }
  1110. }
  1111. /* one extra: We don't want the progress bar to reach 100%, especially not
  1112. if we call dpkg --configure --pending and process a bunch of triggers
  1113. while showing 100%. Also, spindown takes a while, so never reaching 100%
  1114. is way more correct than reaching 100% while still doing stuff even if
  1115. doing it this way is slightly bending the rules */
  1116. ++PackagesTotal;
  1117. }
  1118. /*}}}*/
  1119. bool pkgDPkgPM::Go(int StatusFd) /*{{{*/
  1120. {
  1121. APT::Progress::PackageManager *progress = NULL;
  1122. if (StatusFd == -1)
  1123. progress = APT::Progress::PackageManagerProgressFactory();
  1124. else
  1125. progress = new APT::Progress::PackageManagerProgressFd(StatusFd);
  1126. return Go(progress);
  1127. }
  1128. /*}}}*/
  1129. void pkgDPkgPM::StartPtyMagic() /*{{{*/
  1130. {
  1131. if (_config->FindB("Dpkg::Use-Pty", true) == false)
  1132. {
  1133. d->master = -1;
  1134. if (d->slave != NULL)
  1135. free(d->slave);
  1136. d->slave = NULL;
  1137. return;
  1138. }
  1139. if (isatty(STDIN_FILENO) == 0)
  1140. d->direct_stdin = true;
  1141. _error->PushToStack();
  1142. d->master = posix_openpt(O_RDWR | O_NOCTTY);
  1143. if (d->master == -1)
  1144. _error->Errno("posix_openpt", _("Can not write log (%s)"), _("Is /dev/pts mounted?"));
  1145. else if (unlockpt(d->master) == -1)
  1146. _error->Errno("unlockpt", "Unlocking the slave of master fd %d failed!", d->master);
  1147. else
  1148. {
  1149. #ifdef HAVE_PTSNAME_R
  1150. char slave_name[64]; // 64 is used by bionic
  1151. if (ptsname_r(d->master, slave_name, sizeof(slave_name)) != 0)
  1152. #else
  1153. char const * const slave_name = ptsname(d->master);
  1154. if (slave_name == NULL)
  1155. #endif
  1156. _error->Errno("ptsname", "Getting name for slave of master fd %d failed!", d->master);
  1157. else
  1158. {
  1159. d->slave = strdup(slave_name);
  1160. if (d->slave == NULL)
  1161. _error->Errno("strdup", "Copying name %s for slave of master fd %d failed!", slave_name, d->master);
  1162. else if (grantpt(d->master) == -1)
  1163. _error->Errno("grantpt", "Granting access to slave %s based on master fd %d failed!", slave_name, d->master);
  1164. else if (tcgetattr(STDIN_FILENO, &d->tt) == 0)
  1165. {
  1166. d->tt_is_valid = true;
  1167. struct termios raw_tt;
  1168. // copy window size of stdout if its a 'good' terminal
  1169. if (tcgetattr(STDOUT_FILENO, &raw_tt) == 0)
  1170. {
  1171. struct winsize win;
  1172. if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) < 0)
  1173. _error->Errno("ioctl", "Getting TIOCGWINSZ from stdout failed!");
  1174. if (ioctl(d->master, TIOCSWINSZ, &win) < 0)
  1175. _error->Errno("ioctl", "Setting TIOCSWINSZ for master fd %d failed!", d->master);
  1176. }
  1177. if (tcsetattr(d->master, TCSANOW, &d->tt) == -1)
  1178. _error->Errno("tcsetattr", "Setting in Start via TCSANOW for master fd %d failed!", d->master);
  1179. raw_tt = d->tt;
  1180. cfmakeraw(&raw_tt);
  1181. raw_tt.c_lflag &= ~ECHO;
  1182. raw_tt.c_lflag |= ISIG;
  1183. // block SIGTTOU during tcsetattr to prevent a hang if
  1184. // the process is a member of the background process group
  1185. // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
  1186. sigemptyset(&d->sigmask);
  1187. sigaddset(&d->sigmask, SIGTTOU);
  1188. sigprocmask(SIG_BLOCK,&d->sigmask, &d->original_sigmask);
  1189. if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw_tt) == -1)
  1190. _error->Errno("tcsetattr", "Setting in Start via TCSAFLUSH for stdin failed!");
  1191. sigprocmask(SIG_SETMASK, &d->original_sigmask, NULL);
  1192. }
  1193. if (d->slave != NULL)
  1194. {
  1195. /* on linux, closing (and later reopening) all references to the slave
  1196. makes the slave a death end, so we open it here to have one open all
  1197. the time. We could use this fd in SetupSlavePtyMagic() for linux, but
  1198. on kfreebsd we get an incorrect ("step like") output then while it has
  1199. no problem with closing all references… so to avoid platform specific
  1200. code here we combine both and be happy once more */
  1201. d->protect_slave_from_dying = open(d->slave, O_RDWR | O_CLOEXEC | O_NOCTTY);
  1202. }
  1203. }
  1204. }
  1205. if (_error->PendingError() == true)
  1206. {
  1207. if (d->master != -1)
  1208. {
  1209. close(d->master);
  1210. d->master = -1;
  1211. }
  1212. if (d->slave != NULL)
  1213. {
  1214. free(d->slave);
  1215. d->slave = NULL;
  1216. }
  1217. _error->DumpErrors(std::cerr, GlobalError::DEBUG, false);
  1218. }
  1219. _error->RevertToStack();
  1220. }
  1221. /*}}}*/
  1222. void pkgDPkgPM::SetupSlavePtyMagic() /*{{{*/
  1223. {
  1224. if(d->master == -1 || d->slave == NULL)
  1225. return;
  1226. if (close(d->master) == -1)
  1227. _error->FatalE("close", "Closing master %d in child failed!", d->master);
  1228. d->master = -1;
  1229. if (setsid() == -1)
  1230. _error->FatalE("setsid", "Starting a new session for child failed!");
  1231. int const slaveFd = open(d->slave, O_RDWR | O_NOCTTY);
  1232. if (slaveFd == -1)
  1233. _error->FatalE("open", _("Can not write log (%s)"), _("Is /dev/pts mounted?"));
  1234. else if (ioctl(slaveFd, TIOCSCTTY, 0) < 0)
  1235. _error->FatalE("ioctl", "Setting TIOCSCTTY for slave fd %d failed!", slaveFd);
  1236. else
  1237. {
  1238. unsigned short i = 0;
  1239. if (d->direct_stdin == true)
  1240. ++i;
  1241. for (; i < 3; ++i)
  1242. if (dup2(slaveFd, i) == -1)
  1243. _error->FatalE("dup2", "Dupping %d to %d in child failed!", slaveFd, i);
  1244. if (d->tt_is_valid == true && tcsetattr(STDIN_FILENO, TCSANOW, &d->tt) < 0)
  1245. _error->FatalE("tcsetattr", "Setting in Setup via TCSANOW for slave fd %d failed!", slaveFd);
  1246. }
  1247. if (slaveFd != -1)
  1248. close(slaveFd);
  1249. }
  1250. /*}}}*/
  1251. void pkgDPkgPM::StopPtyMagic() /*{{{*/
  1252. {
  1253. if (d->slave != NULL)
  1254. free(d->slave);
  1255. d->slave = NULL;
  1256. if (d->protect_slave_from_dying != -1)
  1257. {
  1258. close(d->protect_slave_from_dying);
  1259. d->protect_slave_from_dying = -1;
  1260. }
  1261. if(d->master >= 0)
  1262. {
  1263. if (d->tt_is_valid == true && tcsetattr(STDIN_FILENO, TCSAFLUSH, &d->tt) == -1)
  1264. _error->FatalE("tcsetattr", "Setting in Stop via TCSAFLUSH for stdin failed!");
  1265. close(d->master);
  1266. d->master = -1;
  1267. }
  1268. }
  1269. /*}}}*/
  1270. static void cleanUpTmpDir(char * const tmpdir) /*{{{*/
  1271. {
  1272. if (tmpdir == nullptr)
  1273. return;
  1274. DIR * const D = opendir(tmpdir);
  1275. if (D == nullptr)
  1276. _error->Errno("opendir", _("Unable to read %s"), tmpdir);
  1277. else
  1278. {
  1279. auto const dfd = dirfd(D);
  1280. for (struct dirent *Ent = readdir(D); Ent != nullptr; Ent = readdir(D))
  1281. {
  1282. if (Ent->d_name[0] == '.')
  1283. continue;
  1284. #ifdef _DIRENT_HAVE_D_TYPE
  1285. if (unlikely(Ent->d_type != DT_LNK && Ent->d_type != DT_UNKNOWN))
  1286. continue;
  1287. #endif
  1288. char path[strlen(tmpdir) + 1 + strlen(Ent->d_name) + 1];
  1289. sprintf(path, "%s/%s", tmpdir, Ent->d_name);
  1290. if (unlikely(unlink(path) != 0))
  1291. break;
  1292. }
  1293. closedir(D);
  1294. rmdir(tmpdir);
  1295. }
  1296. free(tmpdir);
  1297. }
  1298. /*}}}*/
  1299. // DPkgPM::Go - Run the sequence /*{{{*/
  1300. // ---------------------------------------------------------------------
  1301. /* This globs the operations and calls dpkg
  1302. *
  1303. * If it is called with a progress object apt will report the install
  1304. * progress to this object. It maps the dpkg states a package goes
  1305. * through to human readable (and i10n-able)
  1306. * names and calculates a percentage for each step.
  1307. */
  1308. static bool ItemIsEssential(pkgDPkgPM::Item const &I)
  1309. {
  1310. static auto const cachegen = _config->Find("pkgCacheGen::Essential");
  1311. if (cachegen == "none" || cachegen == "native")
  1312. return true;
  1313. if (unlikely(I.Pkg.end()))
  1314. return true;
  1315. return (I.Pkg->Flags & pkgCache::Flag::Essential) != 0;
  1316. }
  1317. bool pkgDPkgPM::ExpandPendingCalls(std::vector<Item> &List, pkgDepCache &Cache)
  1318. {
  1319. {
  1320. std::unordered_set<decltype(pkgCache::Package::ID)> alreadyRemoved;
  1321. for (auto && I : List)
  1322. if (I.Op == Item::Remove || I.Op == Item::Purge)
  1323. alreadyRemoved.insert(I.Pkg->ID);
  1324. std::remove_reference<decltype(List)>::type AppendList;
  1325. for (auto Pkg = Cache.PkgBegin(); Pkg.end() == false; ++Pkg)
  1326. if (Cache[Pkg].Delete() && alreadyRemoved.insert(Pkg->ID).second == true)
  1327. AppendList.emplace_back(Cache[Pkg].Purge() ? Item::Purge : Item::Remove, Pkg);
  1328. std::move(AppendList.begin(), AppendList.end(), std::back_inserter(List));
  1329. }
  1330. {
  1331. std::unordered_set<decltype(pkgCache::Package::ID)> alreadyConfigured;
  1332. for (auto && I : List)
  1333. if (I.Op == Item::Configure)
  1334. alreadyConfigured.insert(I.Pkg->ID);
  1335. std::remove_reference<decltype(List)>::type AppendList;
  1336. for (auto && I : List)
  1337. if (I.Op == Item::Install && alreadyConfigured.insert(I.Pkg->ID).second == true)
  1338. AppendList.emplace_back(Item::Configure, I.Pkg);
  1339. for (auto Pkg = Cache.PkgBegin(); Pkg.end() == false; ++Pkg)
  1340. if (Pkg.State() == pkgCache::PkgIterator::NeedsConfigure &&
  1341. Cache[Pkg].Delete() == false && alreadyConfigured.insert(Pkg->ID).second == true)
  1342. AppendList.emplace_back(Item::Configure, Pkg);
  1343. std::move(AppendList.begin(), AppendList.end(), std::back_inserter(List));
  1344. }
  1345. return true;
  1346. }
  1347. bool pkgDPkgPM::Go(APT::Progress::PackageManager *progress)
  1348. {
  1349. // explicitely remove&configure everything for hookscripts and progress building
  1350. // we need them only temporarily through, so keep the length and erase afterwards
  1351. decltype(List)::const_iterator::difference_type explicitIdx =
  1352. std::distance(List.cbegin(), List.cend());
  1353. ExpandPendingCalls(List, Cache);
  1354. /* if dpkg told us that it has already done everything to the package we wanted it to do,
  1355. we shouldn't ask it for "more" later. That can e.g. happen if packages without conffiles
  1356. are purged as they will have pass through the purge states on remove already */
  1357. auto const StripAlreadyDoneFrom = [&](APT::VersionVector & Pending) {
  1358. Pending.erase(std::remove_if(Pending.begin(), Pending.end(), [&](pkgCache::VerIterator const &Ver) {
  1359. auto const PN = Ver.ParentPkg().FullName();
  1360. auto const POD = PackageOpsDone.find(PN);
  1361. if (POD == PackageOpsDone.end())
  1362. return false;
  1363. return PackageOps[PN].size() <= POD->second;
  1364. }), Pending.end());
  1365. };
  1366. pkgPackageManager::SigINTStop = false;
  1367. d->progress = progress;
  1368. // Generate the base argument list for dpkg
  1369. std::vector<std::string> const sArgs = debSystem::GetDpkgBaseCommand();
  1370. std::vector<const char *> Args(sArgs.size(), NULL);
  1371. std::transform(sArgs.begin(), sArgs.end(), Args.begin(),
  1372. [](std::string const &s) { return s.c_str(); });
  1373. unsigned long long const StartSize = std::accumulate(sArgs.begin(), sArgs.end(), 0llu,
  1374. [](unsigned long long const i, std::string const &s) { return i + s.length(); });
  1375. size_t const BaseArgs = Args.size();
  1376. fd_set rfds;
  1377. struct timespec tv;
  1378. // try to figure out the max environment size
  1379. int OSArgMax = sysconf(_SC_ARG_MAX);
  1380. if(OSArgMax < 0)
  1381. OSArgMax = 32*1024;
  1382. OSArgMax -= EnvironmentSize() - 2*1024;
  1383. unsigned int const MaxArgBytes = _config->FindI("Dpkg::MaxArgBytes", OSArgMax);
  1384. bool const NoTriggers = _config->FindB("DPkg::NoTriggers", true);
  1385. if (RunScripts("DPkg::Pre-Invoke") == false)
  1386. return false;
  1387. if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
  1388. return false;
  1389. auto const noopDPkgInvocation = _config->FindB("Debug::pkgDPkgPM",false);
  1390. // store auto-bits as they are supposed to be after dpkg is run
  1391. if (noopDPkgInvocation == false)
  1392. Cache.writeStateFile(NULL);
  1393. bool dpkg_recursive_install = _config->FindB("dpkg::install::recursive", false);
  1394. if (_config->FindB("dpkg::install::recursive::force", false) == false)
  1395. {
  1396. // dpkg uses a sorted treewalk since that version which enables the workaround to work
  1397. auto const dpkgpkg = Cache.FindPkg("dpkg");
  1398. if (likely(dpkgpkg.end() == false && dpkgpkg->CurrentVer != 0))
  1399. dpkg_recursive_install = Cache.VS().CmpVersion("1.18.5", dpkgpkg.CurrentVer().VerStr()) <= 0;
  1400. }
  1401. // no point in doing this dance for a handful of packages only
  1402. unsigned int const dpkg_recursive_install_min = _config->FindB("dpkg::install::recursive::minimum", 5);
  1403. // FIXME: workaround for dpkg bug, see our ./test-bug-740843-versioned-up-down-breaks test
  1404. bool const dpkg_recursive_install_numbered = _config->FindB("dpkg::install::recursive::numbered", true);
  1405. // for the progress
  1406. BuildPackagesProgressMap();
  1407. APT::StateChanges approvedStates;
  1408. if (_config->FindB("dpkg::selection::remove::approved", true))
  1409. {
  1410. for (auto && I : List)
  1411. if (I.Op == Item::Purge)
  1412. approvedStates.Purge(FindToBeRemovedVersion(I.Pkg));
  1413. else if (I.Op == Item::Remove)
  1414. approvedStates.Remove(FindToBeRemovedVersion(I.Pkg));
  1415. }
  1416. // Skip removes if we install another architecture of this package soon (crossgrade)
  1417. // We can't just skip them all the time as it could be an ordering requirement [of another package]
  1418. if ((approvedStates.Remove().empty() == false || approvedStates.Purge().empty() == false) &&
  1419. _config->FindB("dpkg::remove::crossgrade::implicit", true) == true)
  1420. {
  1421. std::unordered_set<decltype(pkgCache::Package::ID)> crossgraded;
  1422. std::vector<std::pair<Item*, std::string>> toCrossgrade;
  1423. auto const PlanedEnd = std::next(List.begin(), explicitIdx);
  1424. for (auto I = List.begin(); I != PlanedEnd; ++I)
  1425. {
  1426. if (I->Op != Item::Remove && I->Op != Item::Purge)
  1427. continue;
  1428. auto const Grp = I->Pkg.Group();
  1429. size_t installedInstances = 0, wannabeInstances = 0;
  1430. bool multiArchInstances = false;
  1431. for (auto Pkg = Grp.PackageList(); Pkg.end() == false; Pkg = Grp.NextPkg(Pkg))
  1432. {
  1433. if (Pkg->CurrentVer != 0)
  1434. {
  1435. ++installedInstances;
  1436. if (Cache[Pkg].Delete() == false)
  1437. ++wannabeInstances;
  1438. }
  1439. else if (PackageOps.find(Pkg.FullName()) != PackageOps.end())
  1440. ++wannabeInstances;
  1441. if (multiArchInstances == false)
  1442. {
  1443. auto const V = Cache[Pkg].InstVerIter(Cache);
  1444. if (V.end() == false && (Pkg->CurrentVer == 0 || V != Pkg.CurrentVer()))
  1445. multiArchInstances = ((V->MultiArch & pkgCache::Version::Same) == pkgCache::Version::Same);
  1446. }
  1447. }
  1448. /* theoretically the installed check would be enough as some wannabe will
  1449. be first and hence be the crossgrade we were looking for, but #844300
  1450. prevents this so we keep these situations explicit removes.
  1451. It is also the reason why neither of them can be a M-A:same package */
  1452. if (installedInstances == 1 && wannabeInstances == 1 && multiArchInstances == false)
  1453. {
  1454. auto const FirstInstall = std::find_if_not(I, List.end(),
  1455. [](Item const &i) { return i.Op == Item::Remove || i.Op == Item::Purge; });
  1456. auto const LastInstall = std::find_if_not(FirstInstall, List.end(),
  1457. [](Item const &i) { return i.Op == Item::Install; });
  1458. auto const crosser = std::find_if(FirstInstall, LastInstall,
  1459. [&I](Item const &i) { return i.Pkg->Group == I->Pkg->Group; });
  1460. if (crosser != LastInstall)
  1461. {
  1462. crossgraded.insert(I->Pkg->ID);
  1463. toCrossgrade.emplace_back(&(*I), crosser->Pkg.FullName());
  1464. }
  1465. }
  1466. }
  1467. for (auto I = PlanedEnd; I != List.end(); ++I)
  1468. {
  1469. if (I->Op != Item::Remove && I->Op != Item::Purge)
  1470. continue;
  1471. auto const Grp = I->Pkg.Group();
  1472. for (auto Pkg = Grp.PackageList(); Pkg.end() == false; Pkg = Grp.NextPkg(Pkg))
  1473. {
  1474. if (Pkg == I->Pkg || Cache[Pkg].Install() == false)
  1475. continue;
  1476. toCrossgrade.emplace_back(&(*I), Pkg.FullName());
  1477. break;
  1478. }
  1479. }
  1480. for (auto C : toCrossgrade)
  1481. {
  1482. // we never do purges on packages which are crossgraded, even if "requested"
  1483. if (C.first->Op == Item::Purge)
  1484. {
  1485. C.first->Op = Item::Remove; // crossgrades should never be purged
  1486. auto && Purges = approvedStates.Purge();
  1487. auto const Ver = std::find_if(
  1488. #if __GNUC__ >= 5 || (__GNUC_MINOR__ >= 9 && __GNUC__ >= 4)
  1489. Purges.cbegin(), Purges.cend(),
  1490. #else
  1491. Purges.begin(), Purges.end(),
  1492. #endif
  1493. [&C](pkgCache::VerIterator const &V) { return V.ParentPkg() == C.first->Pkg; });
  1494. approvedStates.Remove(*Ver);
  1495. Purges.erase(Ver);
  1496. auto && RemOp = PackageOps[C.first->Pkg.FullName()];
  1497. if (RemOp.size() == 5)
  1498. {
  1499. RemOp.erase(std::next(RemOp.begin(), 3), RemOp.end());
  1500. PackagesTotal -= 2;
  1501. }
  1502. else
  1503. _error->Warning("Unexpected amount of planned ops for package %s: %lu", C.first->Pkg.FullName().c_str(), RemOp.size());
  1504. }
  1505. }
  1506. if (crossgraded.empty() == false)
  1507. {
  1508. auto const oldsize = List.size();
  1509. List.erase(std::remove_if(List.begin(), PlanedEnd,
  1510. [&crossgraded](Item const &i){
  1511. return (i.Op == Item::Remove || i.Op == Item::Purge) &&
  1512. crossgraded.find(i.Pkg->ID) != crossgraded.end();
  1513. }), PlanedEnd);
  1514. explicitIdx -= (oldsize - List.size());
  1515. }
  1516. }
  1517. APT::StateChanges currentStates;
  1518. if (_config->FindB("dpkg::selection::current::saveandrestore", true))
  1519. {
  1520. for (auto Pkg = Cache.PkgBegin(); Pkg.end() == false; ++Pkg)
  1521. if (Pkg->CurrentVer == 0)
  1522. continue;
  1523. else if (Pkg->SelectedState == pkgCache::State::Purge)
  1524. currentStates.Purge(FindToBeRemovedVersion(Pkg));
  1525. else if (Pkg->SelectedState == pkgCache::State::DeInstall)
  1526. currentStates.Remove(FindToBeRemovedVersion(Pkg));
  1527. if (currentStates.empty() == false)
  1528. {
  1529. APT::StateChanges cleanStates;
  1530. for (auto && P: currentStates.Remove())
  1531. cleanStates.Install(P);
  1532. for (auto && P: currentStates.Purge())
  1533. cleanStates.Install(P);
  1534. if (cleanStates.Save(false) == false)
  1535. return _error->Error("Couldn't clean the currently selected dpkg states");
  1536. }
  1537. }
  1538. if (_config->FindB("dpkg::selection::remove::approved", true))
  1539. {
  1540. if (approvedStates.Save(false) == false)
  1541. {
  1542. _error->Error("Couldn't record the approved state changes as dpkg selection states");
  1543. if (currentStates.Save(false) == false)
  1544. _error->Error("Couldn't restore dpkg selection states which were present before this interaction!");
  1545. return false;
  1546. }
  1547. List.erase(std::next(List.begin(), explicitIdx), List.end());
  1548. std::vector<bool> toBeRemoved(Cache.Head().PackageCount, false);
  1549. for (auto && I: approvedStates.Remove())
  1550. toBeRemoved[I.ParentPkg()->ID] = true;
  1551. for (auto && I: approvedStates.Purge())
  1552. toBeRemoved[I.ParentPkg()->ID] = true;
  1553. for (auto && I: List)
  1554. if (I.Op == Item::Remove || I.Op == Item::Purge)
  1555. toBeRemoved[I.Pkg->ID] = false;
  1556. bool const RemovePending = std::find(toBeRemoved.begin(), toBeRemoved.end(), true) != toBeRemoved.end();
  1557. bool const PurgePending = approvedStates.Purge().empty() == false;
  1558. if (RemovePending != false || PurgePending != false)
  1559. List.emplace_back(Item::ConfigurePending, pkgCache::PkgIterator());
  1560. if (RemovePending)
  1561. List.emplace_back(Item::RemovePending, pkgCache::PkgIterator());
  1562. if (PurgePending)
  1563. List.emplace_back(Item::PurgePending, pkgCache::PkgIterator());
  1564. // support subpressing of triggers processing for special
  1565. // cases like d-i that runs the triggers handling manually
  1566. if (_config->FindB("DPkg::ConfigurePending", true))
  1567. List.emplace_back(Item::ConfigurePending, pkgCache::PkgIterator());
  1568. }
  1569. bool const TriggersPending = _config->FindB("DPkg::TriggersPending", false);
  1570. d->stdin_is_dev_null = false;
  1571. // create log
  1572. OpenLog();
  1573. bool dpkgMultiArch = debSystem::SupportsMultiArch();
  1574. // start pty magic before the loop
  1575. //StartPtyMagic(); or not...
  1576. // Tell the progress that its starting and fork dpkg
  1577. d->progress->Start(d->master);
  1578. // this loop is runs once per dpkg operation
  1579. vector<Item>::const_iterator I = List.cbegin();
  1580. while (I != List.end())
  1581. {
  1582. // Do all actions with the same Op in one run
  1583. vector<Item>::const_iterator J = I;
  1584. if (TriggersPending == true)
  1585. for (; J != List.end(); ++J)
  1586. {
  1587. if (J->Op == I->Op)
  1588. continue;
  1589. if (J->Op != Item::TriggersPending)
  1590. break;
  1591. vector<Item>::const_iterator T = J + 1;
  1592. if (T != List.end() && T->Op == I->Op)
  1593. continue;
  1594. break;
  1595. }
  1596. else if (J->Op == Item::Remove || J->Op == Item::Purge)
  1597. J = std::find_if(J, List.cend(), [](Item const &I) { return I.Op != Item::Remove && I.Op != Item::Purge; });
  1598. else
  1599. J = std::find_if(J, List.cend(), [&J](Item const &I) { return I.Op != J->Op; });
  1600. auto const size = (J - I) + 10;
  1601. // start with the baseset of arguments
  1602. auto Size = StartSize;
  1603. Args.erase(Args.begin() + BaseArgs, Args.end());
  1604. Args.reserve(size);
  1605. // keep track of allocated strings for multiarch package names
  1606. std::vector<char *> Packages(size, nullptr);
  1607. int fd[2];
  1608. if (pipe(fd) != 0)
  1609. return _error->Errno("pipe","Failed to create IPC pipe to dpkg");
  1610. #define ADDARG(X) Args.push_back(X); Size += strlen(X)
  1611. #define ADDARGC(X) Args.push_back(X); Size += sizeof(X) - 1
  1612. ADDARGC("--status-fd");
  1613. char status_fd_buf[20];
  1614. snprintf(status_fd_buf,sizeof(status_fd_buf),"%i", fd[1]);
  1615. ADDARG(status_fd_buf);
  1616. unsigned long const Op = I->Op;
  1617. if (NoTriggers == true && I->Op != Item::TriggersPending &&
  1618. (I->Op != Item::ConfigurePending || std::next(I) != List.end()))
  1619. {
  1620. ADDARGC("--no-triggers");
  1621. }
  1622. switch (I->Op)
  1623. {
  1624. case Item::Remove:
  1625. case Item::Purge:
  1626. ADDARGC("--force-depends");
  1627. ADDARGC("--force-remove-reinstreq");
  1628. if (std::any_of(I, J, ItemIsEssential))
  1629. ADDARGC("--force-remove-essential");
  1630. ADDARGC("--remove");
  1631. break;
  1632. case Item::Configure:
  1633. ADDARGC("--configure");
  1634. break;
  1635. case Item::ConfigurePending:
  1636. ADDARGC("--configure");
  1637. ADDARGC("--pending");
  1638. break;
  1639. case Item::TriggersPending:
  1640. ADDARGC("--triggers-only");
  1641. ADDARGC("--pending");
  1642. break;
  1643. case Item::RemovePending:
  1644. ADDARGC("--remove");
  1645. ADDARGC("--pending");
  1646. break;
  1647. case Item::PurgePending:
  1648. ADDARGC("--purge");
  1649. ADDARGC("--pending");
  1650. break;
  1651. case Item::Install:
  1652. ADDARGC("--unpack");
  1653. ADDARGC("--auto-deconfigure");
  1654. break;
  1655. }
  1656. char * tmpdir_to_free = nullptr;
  1657. // Write in the file or package names
  1658. if (I->Op == Item::Install)
  1659. {
  1660. auto const installsToDo = J - I;
  1661. if (dpkg_recursive_install == true && dpkg_recursive_install_min < installsToDo)
  1662. {
  1663. std::string tmpdir;
  1664. strprintf(tmpdir, "%s/apt-dpkg-install-XXXXXX", GetTempDir().c_str());
  1665. tmpdir_to_free = strndup(tmpdir.data(), tmpdir.length());
  1666. if (mkdtemp(tmpdir_to_free) == nullptr)
  1667. return _error->Errno("DPkg::Go", "mkdtemp of %s failed in preparation of calling dpkg unpack", tmpdir_to_free);
  1668. char p = 1;
  1669. for (auto c = installsToDo - 1; (c = c/10) != 0; ++p);
  1670. for (unsigned long n = 0; I != J; ++n, ++I)
  1671. {
  1672. if (I->File[0] != '/')
  1673. return _error->Error("Internal Error, Pathname to install is not absolute '%s'",I->File.c_str());
  1674. auto file = flNotDir(I->File);
  1675. if (flExtension(file) != "deb")
  1676. file.append(".deb");
  1677. std::string linkpath;
  1678. if (dpkg_recursive_install_numbered)
  1679. strprintf(linkpath, "%s/%.*lu-%s", tmpdir_to_free, p, n, file.c_str());
  1680. else
  1681. strprintf(linkpath, "%s/%s", tmpdir_to_free, file.c_str());
  1682. if (symlink(I->File.c_str(), linkpath.c_str()) != 0)
  1683. return _error->Errno("DPkg::Go", "Symlinking %s to %s failed!", I->File.c_str(), linkpath.c_str());
  1684. }
  1685. ADDARGC("--recursive");
  1686. ADDARG(tmpdir_to_free);
  1687. }
  1688. else
  1689. {
  1690. for (;I != J && Size < MaxArgBytes; ++I)
  1691. {
  1692. if (I->File[0] != '/')
  1693. return _error->Error("Internal Error, Pathname to install is not absolute '%s'",I->File.c_str());
  1694. Args.push_back(I->File.c_str());
  1695. Size += I->File.length();
  1696. }
  1697. }
  1698. }
  1699. else if (I->Op == Item::RemovePending)
  1700. {
  1701. ++I;
  1702. StripAlreadyDoneFrom(approvedStates.Remove());
  1703. if (approvedStates.Remove().empty())
  1704. continue;
  1705. }
  1706. else if (I->Op == Item::PurgePending)
  1707. {
  1708. ++I;
  1709. // explicit removes of packages without conffiles passthrough the purge states instantly, too.
  1710. // Setting these non-installed packages up for purging generates 'unknown pkg' warnings from dpkg
  1711. StripAlreadyDoneFrom(approvedStates.Purge());
  1712. if (approvedStates.Purge().empty())
  1713. continue;
  1714. std::remove_reference<decltype(approvedStates.Remove())>::type approvedRemoves;
  1715. std::swap(approvedRemoves, approvedStates.Remove());
  1716. // we apply it again here as an explicit remove in the ordering will have cleared the purge state
  1717. if (approvedStates.Save(false) == false)
  1718. {
  1719. _error->Error("Couldn't record the approved purges as dpkg selection states");
  1720. if (currentStates.Save(false) == false)
  1721. _error->Error("Couldn't restore dpkg selection states which were present before this interaction!");
  1722. return false;
  1723. }
  1724. std::swap(approvedRemoves, approvedStates.Remove());
  1725. }
  1726. else
  1727. {
  1728. string const nativeArch = _config->Find("APT::Architecture");
  1729. unsigned long const oldSize = I->Pkg.end() == false ? Size : 0;
  1730. for (;I != J && Size < MaxArgBytes; ++I)
  1731. {
  1732. if((*I).Pkg.end() == true)
  1733. continue;
  1734. if (I->Op == Item::Configure && disappearedPkgs.find(I->Pkg.FullName(true)) != disappearedPkgs.end())
  1735. continue;
  1736. // We keep this here to allow "smooth" transitions from e.g. multiarch dpkg/ubuntu to dpkg/debian
  1737. if (dpkgMultiArch == false && (I->Pkg.Arch() == nativeArch ||
  1738. strcmp(I->Pkg.Arch(), "all") == 0 ||
  1739. strcmp(I->Pkg.Arch(), "none") == 0))
  1740. {
  1741. char const * const name = I->Pkg.Name();
  1742. ADDARG(name);
  1743. }
  1744. else
  1745. {
  1746. pkgCache::VerIterator PkgVer;
  1747. std::string name = I->Pkg.Name();
  1748. if (Op == Item::Remove)
  1749. PkgVer = I->Pkg.CurrentVer();
  1750. else if (Op == Item::Purge)
  1751. {
  1752. // we purge later with --purge --pending, so if it isn't installed (aka rc-only), skip it here
  1753. PkgVer = I->Pkg.CurrentVer();
  1754. if (PkgVer.end() == true)
  1755. continue;
  1756. }
  1757. else
  1758. PkgVer = Cache[I->Pkg].InstVerIter(Cache);
  1759. if (strcmp(I->Pkg.Arch(), "none") == 0)
  1760. ; // never arch-qualify a package without an arch
  1761. else if (PkgVer.end() == false)
  1762. name.append(":").append(PkgVer.Arch());
  1763. else
  1764. _error->Warning("Can not find PkgVer for '%s'", name.c_str());
  1765. char * const fullname = strdup(name.c_str());
  1766. Packages.push_back(fullname);
  1767. ADDARG(fullname);
  1768. }
  1769. }
  1770. // skip configure action if all sheduled packages disappeared
  1771. if (oldSize == Size)
  1772. continue;
  1773. }
  1774. #undef ADDARGC
  1775. #undef ADDARG
  1776. J = I;
  1777. if (noopDPkgInvocation == true)
  1778. {
  1779. for (std::vector<const char *>::const_iterator a = Args.begin();
  1780. a != Args.end(); ++a)
  1781. clog << *a << ' ';
  1782. clog << endl;
  1783. for (std::vector<char *>::const_iterator p = Packages.begin();
  1784. p != Packages.end(); ++p)
  1785. free(*p);
  1786. Packages.clear();
  1787. close(fd[0]);
  1788. close(fd[1]);
  1789. cleanUpTmpDir(tmpdir_to_free);
  1790. continue;
  1791. }
  1792. Args.push_back(NULL);
  1793. cout << flush;
  1794. clog << flush;
  1795. cerr << flush;
  1796. /* Mask off sig int/quit. We do this because dpkg also does when
  1797. it forks scripts. What happens is that when you hit ctrl-c it sends
  1798. it to all processes in the group. Since dpkg ignores the signal
  1799. it doesn't die but we do! So we must also ignore it */
  1800. sighandler_t old_SIGQUIT = signal(SIGQUIT,SIG_IGN);
  1801. sighandler_t old_SIGINT = signal(SIGINT,SigINT);
  1802. // Check here for any SIGINT
  1803. if (pkgPackageManager::SigINTStop && (Op == Item::Remove || Op == Item::Purge || Op == Item::Install))
  1804. break;
  1805. // ignore SIGHUP as well (debian #463030)
  1806. sighandler_t old_SIGHUP = signal(SIGHUP,SIG_IGN);
  1807. // now run dpkg
  1808. d->progress->StartDpkg();
  1809. std::set<int> KeepFDs;
  1810. KeepFDs.insert(fd[1]);
  1811. MergeKeepFdsFromConfiguration(KeepFDs);
  1812. pid_t Child = ExecFork(KeepFDs);
  1813. if (Child == 0)
  1814. {
  1815. // This is the child
  1816. SetupSlavePtyMagic();
  1817. close(fd[0]); // close the read end of the pipe
  1818. debSystem::DpkgChrootDirectory();
  1819. if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
  1820. _exit(100);
  1821. if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
  1822. {
  1823. int Flags;
  1824. int dummy = 0;
  1825. if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
  1826. _exit(100);
  1827. // Discard everything in stdin before forking dpkg
  1828. if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
  1829. _exit(100);
  1830. while (read(STDIN_FILENO,&dummy,1) == 1);
  1831. if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
  1832. _exit(100);
  1833. }
  1834. // if color support isn't enabled/disabled explicitly tell
  1835. // dpkg to use the same state apt is using for its color support
  1836. if (_config->FindB("APT::Color", false) == true)
  1837. setenv("DPKG_COLORS", "always", 0);
  1838. else
  1839. setenv("DPKG_COLORS", "never", 0);
  1840. execvp(Args[0], (char**) &Args[0]);
  1841. cerr << "Could not exec dpkg!" << endl;
  1842. _exit(100);
  1843. }
  1844. // we read from dpkg here
  1845. int const _dpkgin = fd[0];
  1846. close(fd[1]); // close the write end of the pipe
  1847. // apply ionice
  1848. if (_config->FindB("DPkg::UseIoNice", false) == true)
  1849. ionice(Child);
  1850. // setups fds
  1851. sigemptyset(&d->sigmask);
  1852. sigprocmask(SIG_BLOCK,&d->sigmask,&d->original_sigmask);
  1853. /* free vectors (and therefore memory) as we don't need the included data anymore */
  1854. for (std::vector<char *>::const_iterator p = Packages.begin();
  1855. p != Packages.end(); ++p)
  1856. free(*p);
  1857. Packages.clear();
  1858. // the result of the waitpid call
  1859. int Status = 0;
  1860. int res;
  1861. bool waitpid_failure = false;
  1862. while ((res=waitpid(Child,&Status, WNOHANG)) != Child) {
  1863. if(res < 0) {
  1864. // error handling, waitpid returned -1
  1865. if (errno == EINTR)
  1866. continue;
  1867. waitpid_failure = true;
  1868. break;
  1869. }
  1870. // wait for input or output here
  1871. FD_ZERO(&rfds);
  1872. if (d->master >= 0 && d->direct_stdin == false && d->stdin_is_dev_null == false)
  1873. FD_SET(STDIN_FILENO, &rfds);
  1874. FD_SET(_dpkgin, &rfds);
  1875. if(d->master >= 0)
  1876. FD_SET(d->master, &rfds);
  1877. tv.tv_sec = 0;
  1878. tv.tv_nsec = d->progress->GetPulseInterval();
  1879. auto const select_ret = pselect(max(d->master, _dpkgin)+1, &rfds, NULL, NULL,
  1880. &tv, &d->original_sigmask);
  1881. d->progress->Pulse();
  1882. if (select_ret == 0)
  1883. continue;
  1884. else if (select_ret < 0 && errno == EINTR)
  1885. continue;
  1886. else if (select_ret < 0)
  1887. {
  1888. perror("select() returned error");
  1889. continue;
  1890. }
  1891. if(d->master >= 0 && FD_ISSET(d->master, &rfds))
  1892. DoTerminalPty(d->master);
  1893. if(d->master >= 0 && FD_ISSET(0, &rfds))
  1894. DoStdin(d->master);
  1895. if(FD_ISSET(_dpkgin, &rfds))
  1896. DoDpkgStatusFd(_dpkgin);
  1897. }
  1898. close(_dpkgin);
  1899. // Restore sig int/quit
  1900. signal(SIGQUIT,old_SIGQUIT);
  1901. signal(SIGINT,old_SIGINT);
  1902. signal(SIGHUP,old_SIGHUP);
  1903. cleanUpTmpDir(tmpdir_to_free);
  1904. if (waitpid_failure == true)
  1905. {
  1906. strprintf(d->dpkg_error, "Sub-process %s couldn't be waited for.",Args[0]);
  1907. _error->Error("%s", d->dpkg_error.c_str());
  1908. break;
  1909. }
  1910. // Check for an error code.
  1911. if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
  1912. {
  1913. // if it was set to "keep-dpkg-running" then we won't return
  1914. // here but keep the loop going and just report it as a error
  1915. // for later
  1916. bool const stopOnError = _config->FindB("Dpkg::StopOnError",true);
  1917. if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
  1918. strprintf(d->dpkg_error, "Sub-process %s received a segmentation fault.",Args[0]);
  1919. else if (WIFEXITED(Status) != 0)
  1920. strprintf(d->dpkg_error, "Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
  1921. else
  1922. strprintf(d->dpkg_error, "Sub-process %s exited unexpectedly",Args[0]);
  1923. _error->Error("%s", d->dpkg_error.c_str());
  1924. if(stopOnError)
  1925. break;
  1926. }
  1927. }
  1928. // dpkg is done at this point
  1929. //StopPtyMagic();
  1930. CloseLog();
  1931. if (d->dpkg_error.empty() == false)
  1932. {
  1933. // no point in reseting packages we already completed removal for
  1934. StripAlreadyDoneFrom(approvedStates.Remove());
  1935. StripAlreadyDoneFrom(approvedStates.Purge());
  1936. APT::StateChanges undo;
  1937. auto && undoRem = approvedStates.Remove();
  1938. std::move(undoRem.begin(), undoRem.end(), std::back_inserter(undo.Install()));
  1939. auto && undoPur = approvedStates.Purge();
  1940. std::move(undoPur.begin(), undoPur.end(), std::back_inserter(undo.Install()));
  1941. approvedStates.clear();
  1942. if (undo.Save(false) == false)
  1943. _error->Error("Couldn't revert dpkg selection for approved remove/purge after an error was encountered!");
  1944. }
  1945. StripAlreadyDoneFrom(currentStates.Remove());
  1946. StripAlreadyDoneFrom(currentStates.Purge());
  1947. if (currentStates.Save(false) == false)
  1948. _error->Error("Couldn't restore dpkg selection states which were present before this interaction!");
  1949. if (pkgPackageManager::SigINTStop)
  1950. _error->Warning(_("Operation was interrupted before it could finish"));
  1951. if (noopDPkgInvocation == false)
  1952. {
  1953. if (d->dpkg_error.empty() && (PackagesDone + 1) != PackagesTotal)
  1954. {
  1955. std::string pkglist;
  1956. for (auto const &PO: PackageOps)
  1957. if (PO.second.size() != PackageOpsDone[PO.first])
  1958. {
  1959. if (pkglist.empty() == false)
  1960. pkglist.append(" ");
  1961. pkglist.append(PO.first);
  1962. }
  1963. /* who cares about correct progress? As we depend on it for skipping actions
  1964. our parsing should be correct. People will no doubt be confused if they see
  1965. this message, but the dpkg warning about unknown packages isn't much better
  1966. from a user POV and combined we might have a chance to figure out what is wrong */
  1967. _error->Warning("APT had planned for dpkg to do more than it reported back (%u vs %u).\n"
  1968. "Affected packages: %s", PackagesDone, PackagesTotal, pkglist.c_str());
  1969. }
  1970. std::string const oldpkgcache = _config->FindFile("Dir::cache::pkgcache");
  1971. if (oldpkgcache.empty() == false && RealFileExists(oldpkgcache) == true &&
  1972. RemoveFile("pkgDPkgPM::Go", oldpkgcache))
  1973. {
  1974. std::string const srcpkgcache = _config->FindFile("Dir::cache::srcpkgcache");
  1975. if (srcpkgcache.empty() == false && RealFileExists(srcpkgcache) == true)
  1976. {
  1977. _error->PushToStack();
  1978. pkgCacheFile CacheFile;
  1979. CacheFile.BuildCaches(NULL, true);
  1980. _error->RevertToStack();
  1981. }
  1982. }
  1983. }
  1984. // disappearing packages can forward their auto-bit
  1985. if (disappearedPkgs.empty() == false)
  1986. Cache.writeStateFile(NULL);
  1987. d->progress->Stop();
  1988. if (RunScripts("DPkg::Post-Invoke") == false)
  1989. return false;
  1990. return d->dpkg_error.empty();
  1991. }
  1992. void SigINT(int /*sig*/) {
  1993. pkgPackageManager::SigINTStop = true;
  1994. }
  1995. /*}}}*/
  1996. // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
  1997. // ---------------------------------------------------------------------
  1998. /* */
  1999. void pkgDPkgPM::Reset()
  2000. {
  2001. List.erase(List.begin(),List.end());
  2002. }
  2003. /*}}}*/
  2004. // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
  2005. // ---------------------------------------------------------------------
  2006. /* */
  2007. void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
  2008. {
  2009. // If apport doesn't exist or isn't installed do nothing
  2010. // This e.g. prevents messages in 'universes' without apport
  2011. pkgCache::PkgIterator apportPkg = Cache.FindPkg("apport");
  2012. if (apportPkg.end() == true || apportPkg->CurrentVer == 0)
  2013. return;
  2014. string pkgname, reportfile, pkgver, arch;
  2015. string::size_type pos;
  2016. FILE *report;
  2017. if (_config->FindB("Dpkg::ApportFailureReport", true) == false)
  2018. {
  2019. std::clog << "configured to not write apport reports" << std::endl;
  2020. return;
  2021. }
  2022. // only report the first errors
  2023. if(pkgFailures > _config->FindI("APT::Apport::MaxReports", 3))
  2024. {
  2025. std::clog << _("No apport report written because MaxReports is reached already") << std::endl;
  2026. return;
  2027. }
  2028. // check if its not a follow up error
  2029. const char *needle = dgettext("dpkg", "dependency problems - leaving unconfigured");
  2030. if(strstr(errormsg, needle) != NULL) {
  2031. std::clog << _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl;
  2032. return;
  2033. }
  2034. // do not report disk-full failures
  2035. if(strstr(errormsg, strerror(ENOSPC)) != NULL) {
  2036. std::clog << _("No apport report written because the error message indicates a disk full error") << std::endl;
  2037. return;
  2038. }
  2039. // do not report out-of-memory failures
  2040. if(strstr(errormsg, strerror(ENOMEM)) != NULL ||
  2041. strstr(errormsg, "failed to allocate memory") != NULL) {
  2042. std::clog << _("No apport report written because the error message indicates a out of memory error") << std::endl;
  2043. return;
  2044. }
  2045. // do not report bugs regarding inaccessible local files
  2046. if(strstr(errormsg, strerror(ENOENT)) != NULL ||
  2047. strstr(errormsg, "cannot access archive") != NULL) {
  2048. std::clog << _("No apport report written because the error message indicates an issue on the local system") << std::endl;
  2049. return;
  2050. }
  2051. // do not report errors encountered when decompressing packages
  2052. if(strstr(errormsg, "--fsys-tarfile returned error exit status 2") != NULL) {
  2053. std::clog << _("No apport report written because the error message indicates an issue on the local system") << std::endl;
  2054. return;
  2055. }
  2056. // do not report dpkg I/O errors, this is a format string, so we compare
  2057. // the prefix and the suffix of the error with the dpkg error message
  2058. vector<string> io_errors;
  2059. io_errors.push_back(string("failed to read"));
  2060. io_errors.push_back(string("failed to write"));
  2061. io_errors.push_back(string("failed to seek"));
  2062. io_errors.push_back(string("unexpected end of file or stream"));
  2063. for (vector<string>::iterator I = io_errors.begin(); I != io_errors.end(); ++I)
  2064. {
  2065. vector<string> list = VectorizeString(dgettext("dpkg", (*I).c_str()), '%');
  2066. if (list.size() > 1) {
  2067. // we need to split %s, VectorizeString only allows char so we need
  2068. // to kill the "s" manually
  2069. if (list[1].size() > 1) {
  2070. list[1].erase(0, 1);
  2071. if(strstr(errormsg, list[0].c_str()) &&
  2072. strstr(errormsg, list[1].c_str())) {
  2073. std::clog << _("No apport report written because the error message indicates a dpkg I/O error") << std::endl;
  2074. return;
  2075. }
  2076. }
  2077. }
  2078. }
  2079. // get the pkgname and reportfile
  2080. pkgname = flNotDir(pkgpath);
  2081. pos = pkgname.find('_');
  2082. if(pos != string::npos)
  2083. pkgname = pkgname.substr(0, pos);
  2084. // find the package version and source package name
  2085. pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
  2086. if (Pkg.end() == true)
  2087. {
  2088. if (pos == std::string::npos || _config->FindB("dpkg::install::recursive::numbered", true) == false)
  2089. return;
  2090. auto const dash = pkgname.find_first_not_of("0123456789");
  2091. if (dash == std::string::npos || pkgname[dash] != '-')
  2092. return;
  2093. pkgname.erase(0, dash + 1);
  2094. Pkg = Cache.FindPkg(pkgname);
  2095. if (Pkg.end() == true)
  2096. return;
  2097. }
  2098. pkgCache::VerIterator Ver = Cache.GetCandidateVersion(Pkg);
  2099. if (Ver.end() == true)
  2100. return;
  2101. pkgver = Ver.VerStr() == NULL ? "unknown" : Ver.VerStr();
  2102. // if the file exists already, we check:
  2103. // - if it was reported already (touched by apport).
  2104. // If not, we do nothing, otherwise
  2105. // we overwrite it. This is the same behaviour as apport
  2106. // - if we have a report with the same pkgversion already
  2107. // then we skip it
  2108. _config->CndSet("Dir::Apport", "var/crash");
  2109. reportfile = flCombine(_config->FindDir("Dir::Apport", "var/crash"), pkgname+".0.crash");
  2110. if(FileExists(reportfile))
  2111. {
  2112. struct stat buf;
  2113. char strbuf[255];
  2114. // check atime/mtime
  2115. stat(reportfile.c_str(), &buf);
  2116. if(buf.st_mtime > buf.st_atime)
  2117. return;
  2118. // check if the existing report is the same version
  2119. report = fopen(reportfile.c_str(),"r");
  2120. while(fgets(strbuf, sizeof(strbuf), report) != NULL)
  2121. {
  2122. if(strstr(strbuf,"Package:") == strbuf)
  2123. {
  2124. char pkgname[255], version[255];
  2125. if(sscanf(strbuf, "Package: %254s %254s", pkgname, version) == 2)
  2126. if(strcmp(pkgver.c_str(), version) == 0)
  2127. {
  2128. fclose(report);
  2129. return;
  2130. }
  2131. }
  2132. }
  2133. fclose(report);
  2134. }
  2135. // now write the report
  2136. arch = _config->Find("APT::Architecture");
  2137. report = fopen(reportfile.c_str(),"w");
  2138. if(report == NULL)
  2139. return;
  2140. if(_config->FindB("DPkgPM::InitialReportOnly",false) == true)
  2141. chmod(reportfile.c_str(), 0);
  2142. else
  2143. chmod(reportfile.c_str(), 0600);
  2144. fprintf(report, "ProblemType: Package\n");
  2145. fprintf(report, "Architecture: %s\n", arch.c_str());
  2146. time_t now = time(NULL);
  2147. char ctime_buf[26]; // need at least 26 bytes according to ctime(3)
  2148. fprintf(report, "Date: %s" , ctime_r(&now, ctime_buf));
  2149. fprintf(report, "Package: %s %s\n", pkgname.c_str(), pkgver.c_str());
  2150. fprintf(report, "SourcePackage: %s\n", Ver.SourcePkgName());
  2151. fprintf(report, "ErrorMessage:\n %s\n", errormsg);
  2152. // ensure that the log is flushed
  2153. if(d->term_out)
  2154. fflush(d->term_out);
  2155. // attach terminal log it if we have it
  2156. string logfile_name = _config->FindFile("Dir::Log::Terminal");
  2157. if (!logfile_name.empty())
  2158. {
  2159. FILE *log = NULL;
  2160. fprintf(report, "DpkgTerminalLog:\n");
  2161. log = fopen(logfile_name.c_str(),"r");
  2162. if(log != NULL)
  2163. {
  2164. char buf[1024];
  2165. while( fgets(buf, sizeof(buf), log) != NULL)
  2166. fprintf(report, " %s", buf);
  2167. fprintf(report, " \n");
  2168. fclose(log);
  2169. }
  2170. }
  2171. // attach history log it if we have it
  2172. string histfile_name = _config->FindFile("Dir::Log::History");
  2173. if (!histfile_name.empty())
  2174. {
  2175. fprintf(report, "DpkgHistoryLog:\n");
  2176. FILE* log = fopen(histfile_name.c_str(),"r");
  2177. if(log != NULL)
  2178. {
  2179. char buf[1024];
  2180. while( fgets(buf, sizeof(buf), log) != NULL)
  2181. fprintf(report, " %s", buf);
  2182. fclose(log);
  2183. }
  2184. }
  2185. // log the ordering, see dpkgpm.h and the "Ops" enum there
  2186. fprintf(report, "AptOrdering:\n");
  2187. for (auto && I : List)
  2188. {
  2189. char const * opstr = nullptr;
  2190. switch (I.Op)
  2191. {
  2192. case Item::Install: opstr = "Install"; break;
  2193. case Item::Configure: opstr = "Configure"; break;
  2194. case Item::Remove: opstr = "Remove"; break;
  2195. case Item::Purge: opstr = "Purge"; break;
  2196. case Item::ConfigurePending: opstr = "ConfigurePending"; break;
  2197. case Item::TriggersPending: opstr = "TriggersPending"; break;
  2198. case Item::RemovePending: opstr = "RemovePending"; break;
  2199. case Item::PurgePending: opstr = "PurgePending"; break;
  2200. }
  2201. auto const pkgname = I.Pkg.end() ? "NULL" : I.Pkg.FullName();
  2202. fprintf(report, " %s: %s\n", pkgname.c_str(), opstr);
  2203. }
  2204. // attach dmesg log (to learn about segfaults)
  2205. if (FileExists("/bin/dmesg"))
  2206. {
  2207. fprintf(report, "Dmesg:\n");
  2208. FILE *log = popen("/bin/dmesg","r");
  2209. if(log != NULL)
  2210. {
  2211. char buf[1024];
  2212. while( fgets(buf, sizeof(buf), log) != NULL)
  2213. fprintf(report, " %s", buf);
  2214. pclose(log);
  2215. }
  2216. }
  2217. // attach df -l log (to learn about filesystem status)
  2218. if (FileExists("/bin/df"))
  2219. {
  2220. fprintf(report, "Df:\n");
  2221. FILE *log = popen("/bin/df -l","r");
  2222. if(log != NULL)
  2223. {
  2224. char buf[1024];
  2225. while( fgets(buf, sizeof(buf), log) != NULL)
  2226. fprintf(report, " %s", buf);
  2227. pclose(log);
  2228. }
  2229. }
  2230. fclose(report);
  2231. }
  2232. /*}}}*/