dpkgpm.cc 74 KB

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