WebBrowserContext.cpp 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. #include "WebBrowserContext.h"
  2. #include "CEF/BrowserApp.h"
  3. #include "WallpaperEngine/Application/WallpaperApplication.h"
  4. #include "WallpaperEngine/Desktop/SessionBus.h"
  5. #include "WallpaperEngine/Logging/Log.h"
  6. #include "WallpaperEngine/WebBrowser/CEF/SubprocessApp.h"
  7. #include "WallpaperEngine/WebBrowser/IPC/WebHostSharedMemory.h"
  8. #include "include/cef_app.h"
  9. #include "include/cef_render_handler.h"
  10. #include <cerrno>
  11. #include <cstdio>
  12. #include <cstdlib>
  13. #include <fcntl.h>
  14. #include <filesystem>
  15. #include <random>
  16. #include <sched.h>
  17. #include <string_view>
  18. #include <sys/file.h>
  19. #include <sys/stat.h>
  20. #include <sys/wait.h>
  21. #include <unistd.h>
  22. using namespace WallpaperEngine::WebBrowser;
  23. // TODO: THIS IS USED TO GENERATE A RANDOM FOLDER FOR THE CHROME PROFILE, MAYBE A DIFFERENT APPROACH WOULD BE BETTER?
  24. namespace uuid {
  25. static std::random_device rd;
  26. static std::mt19937 gen (rd ());
  27. static std::uniform_int_distribution<> dis (0, 15);
  28. static std::uniform_int_distribution<> dis2 (8, 11);
  29. std::string generate_uuid_v4 () {
  30. std::stringstream ss;
  31. int i;
  32. ss << std::hex;
  33. for (i = 0; i < 8; i++) {
  34. ss << dis (gen);
  35. }
  36. ss << "-";
  37. for (i = 0; i < 4; i++) {
  38. ss << dis (gen);
  39. }
  40. ss << "-4";
  41. for (i = 0; i < 3; i++) {
  42. ss << dis (gen);
  43. }
  44. ss << "-";
  45. ss << dis2 (gen);
  46. for (i = 0; i < 3; i++) {
  47. ss << dis (gen);
  48. }
  49. ss << "-";
  50. for (i = 0; i < 12; i++) {
  51. ss << dis (gen);
  52. };
  53. return ss.str ();
  54. }
  55. }
  56. namespace {
  57. // empty when missing, Chromium then re-execs this binary (main() hands it to runSubprocess)
  58. std::filesystem::path subprocessHelper () {
  59. constexpr std::string_view deletedSuffix = " (deleted)";
  60. std::error_code error;
  61. std::string self = std::filesystem::read_symlink ("/proc/self/exe", error).string ();
  62. if (error) {
  63. return {};
  64. }
  65. if (self.ends_with (deletedSuffix)) {
  66. self.resize (self.size () - deletedSuffix.size ());
  67. }
  68. auto helper = std::filesystem::path (self).parent_path () / "linux-wallpaperengine-web-helper";
  69. if (access (helper.c_str (), X_OK) != 0) {
  70. return {};
  71. }
  72. return helper;
  73. }
  74. bool writeFile (const char* path, const char* text, size_t length) {
  75. const int fd = open (path, O_WRONLY);
  76. if (fd < 0) {
  77. return false;
  78. }
  79. const bool written = write (fd, text, length) == static_cast<ssize_t> (length);
  80. close (fd);
  81. return written;
  82. }
  83. // Ubuntu 24.04+ allows the unshare but AppArmor drops its capabilities, so the uid map write is what fails
  84. bool userNamespacesWork () {
  85. char uidMap[64];
  86. const int uidMapLength = snprintf (uidMap, sizeof (uidMap), "0 %u 1\n", getuid ());
  87. const pid_t child = fork ();
  88. if (child < 0) {
  89. return false;
  90. }
  91. if (child == 0) {
  92. const bool mapped = unshare (CLONE_NEWUSER) == 0 && writeFile ("/proc/self/setgroups", "deny", 4)
  93. && writeFile ("/proc/self/uid_map", uidMap, uidMapLength);
  94. _exit (mapped ? 0 : 1);
  95. }
  96. int status = 0;
  97. while (waitpid (child, &status, 0) < 0 && errno == EINTR) { }
  98. return WIFEXITED (status) && WEXITSTATUS (status) == 0;
  99. }
  100. // Chromium aborts without a user namespace or a setuid root chrome-sandbox next to libcef
  101. bool chromiumSandboxUsable () {
  102. std::error_code error;
  103. const auto self = std::filesystem::read_symlink ("/proc/self/exe", error);
  104. struct stat sandbox {};
  105. if (!error && stat ((self.parent_path () / "chrome-sandbox").c_str (), &sandbox) == 0 && sandbox.st_uid == 0
  106. && (sandbox.st_mode & S_ISUID) != 0) {
  107. return true;
  108. }
  109. return userNamespacesWork ();
  110. }
  111. } // namespace
  112. int WebBrowserContext::runSubprocess (int argc, char* argv[]) {
  113. const CefMainArgs mainArgs (argc, argv);
  114. return CefExecuteProcess (mainArgs, new CEF::SubprocessApp (), nullptr);
  115. }
  116. WebBrowserContext::WebBrowserContext (WallpaperEngine::Application::WallpaperApplication& wallpaperApplication) :
  117. m_browserApplication (nullptr), m_wallpaperApplication (wallpaperApplication) {
  118. CefMainArgs main_args (
  119. this->m_wallpaperApplication.getContext ().getArgc (), this->m_wallpaperApplication.getContext ().getArgv ()
  120. );
  121. this->m_browserApplication = new CEF::BrowserApp (wallpaperApplication);
  122. CefSettings settings;
  123. // a later engine run removes it if we get killed before cleaning up, unless something still holds its lock
  124. this->m_cachePath = (std::filesystem::temp_directory_path ()
  125. / ("lwe-cef-" + Desktop::processTag () + "-" + uuid::generate_uuid_v4 ()))
  126. .string ();
  127. this->lockProfile ();
  128. cef_string_utf8_to_utf16 (this->m_cachePath.c_str (), this->m_cachePath.length (), &settings.root_cache_path);
  129. settings.windowless_rendering_enabled = true;
  130. if (const std::string helper = subprocessHelper ().string (); !helper.empty ()) {
  131. cef_string_utf8_to_utf16 (helper.c_str (), helper.length (), &settings.browser_subprocess_path);
  132. } else {
  133. sLog.out ("linux-wallpaperengine-web-helper not found next to the engine, Chromium's processes start slower");
  134. }
  135. // Chromium's own ERROR-level chatter (cancelled requests and the like) is noise here, the page's console is
  136. // still forwarded by BrowserClient
  137. settings.log_severity = LOGSEVERITY_FATAL;
  138. #if defined(CEF_NO_SANDBOX)
  139. settings.no_sandbox = true;
  140. #endif
  141. // tests only: containers without a setuid chrome-sandbox or user namespaces
  142. if (const char* noSandbox = std::getenv ("LWE_CEF_NO_SANDBOX"); noSandbox != nullptr && noSandbox[0] == '1') {
  143. sLog.error ("LWE_CEF_NO_SANDBOX is set, web content runs without Chromium's sandbox");
  144. settings.no_sandbox = true;
  145. } else if (!settings.no_sandbox && !chromiumSandboxUsable ()) {
  146. sLog.error (
  147. "No user namespaces and no setuid root chrome-sandbox, web content runs without Chromium's sandbox. "
  148. "Distribution packages set it up, or as root: chown root:root chrome-sandbox; chmod 4755 chrome-sandbox"
  149. );
  150. settings.no_sandbox = true;
  151. }
  152. if (!CefInitialize (main_args, settings, this->m_browserApplication, nullptr)) {
  153. sLog.exception ("CefInitialize: failed");
  154. }
  155. }
  156. WebBrowserContext::~WebBrowserContext () {
  157. sLog.out ("Shutting down CEF");
  158. CefShutdown ();
  159. if (!this->m_cachePath.empty ()) {
  160. std::error_code error;
  161. std::filesystem::remove_all (this->m_cachePath, error);
  162. }
  163. if (this->m_profileLock >= 0) {
  164. close (this->m_profileLock);
  165. }
  166. }
  167. void WebBrowserContext::lockProfile () {
  168. std::error_code error;
  169. std::filesystem::create_directories (this->m_cachePath, error);
  170. const auto lockFile = std::filesystem::path (this->m_cachePath) / IPC::CEF_PROFILE_LOCK;
  171. this->m_profileLock = open (lockFile.c_str (), O_CREAT | O_RDWR | O_CLOEXEC, 0600);
  172. if (this->m_profileLock >= 0 && flock (this->m_profileLock, LOCK_SH) != 0) {
  173. close (this->m_profileLock);
  174. this->m_profileLock = -1;
  175. }
  176. }