dpkgpm.cc 59 KB

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