You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

2112 lines
67 KiB

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