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.
 
 
 
 
 
 

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