process_singleton.patch 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
  2. From: Raymond Zhao <[email protected]>
  3. Date: Wed, 18 Aug 2021 08:24:10 -0700
  4. Subject: extend ProcessSingleton
  5. This patch applies Electron ProcessSingleton changes onto the Chromium
  6. files.
  7. This patch adds a few changes to the Chromium code:
  8. 1. It adds a parameter `program_name` to the Windows constructor, making
  9. the generated mutex name on the Windows-side program-dependent,
  10. rather than shared between all Electron applications.
  11. 2. It adds an `IsAppSandboxed` check for macOS so that
  12. sandboxed applications generate shorter temp paths.
  13. 3. It adds a `ChangeWindowMessageFilterEx` call to the Windows
  14. implementation, along with a parameter `is_app_sandboxed` in the
  15. constructor, to handle the case when the primary app is run with
  16. admin permissions.
  17. 4. It adds an `OnBrowserReady` function to allow
  18. `requestSingleInstanceLock` to start listening to the socket later
  19. in the posix implementation. This function is necessary, because
  20. otherwise, users calling `requestSingleInstanceLock` create a
  21. `ProcessSingleton` instance that tries to connect to the socket
  22. before the browser thread is ready.
  23. diff --git a/chrome/browser/process_singleton.h b/chrome/browser/process_singleton.h
  24. index 16bb3aa15a5378e8319f75f4b6b72b39177828f4..5a64220aaf1309832dc0ad543e353de67fe0a779 100644
  25. --- a/chrome/browser/process_singleton.h
  26. +++ b/chrome/browser/process_singleton.h
  27. @@ -102,12 +102,19 @@ class ProcessSingleton {
  28. base::RepeatingCallback<bool(const base::CommandLine& command_line,
  29. const base::FilePath& current_directory)>;
  30. +#if BUILDFLAG(IS_WIN)
  31. + ProcessSingleton(const std::string& program_name,
  32. + const base::FilePath& user_data_dir,
  33. + bool is_sandboxed,
  34. + const NotificationCallback& notification_callback);
  35. +#else
  36. ProcessSingleton(const base::FilePath& user_data_dir,
  37. const NotificationCallback& notification_callback);
  38. ProcessSingleton(const ProcessSingleton&) = delete;
  39. ProcessSingleton& operator=(const ProcessSingleton&) = delete;
  40. +#endif
  41. ~ProcessSingleton();
  42. // Notify another process, if available. Otherwise sets ourselves as the
  43. @@ -118,6 +125,8 @@ class ProcessSingleton {
  44. // TODO(brettw): Make the implementation of this method non-platform-specific
  45. // by making Linux re-use the Windows implementation.
  46. NotifyResult NotifyOtherProcessOrCreate();
  47. + void StartListeningOnSocket();
  48. + void OnBrowserReady();
  49. // Sets ourself up as the singleton instance. Returns true on success. If
  50. // false is returned, we are not the singleton instance and the caller must
  51. @@ -173,6 +182,8 @@ class ProcessSingleton {
  52. #if BUILDFLAG(IS_WIN)
  53. bool EscapeVirtualization(const base::FilePath& user_data_dir);
  54. + std::string program_name_; // Used for mutexName.
  55. + bool is_app_sandboxed_; // Whether the Electron app is sandboxed.
  56. HWND remote_window_; // The HWND_MESSAGE of another browser.
  57. base::win::MessageWindow window_; // The message-only window.
  58. bool is_virtualized_; // Stuck inside Microsoft Softricity VM environment.
  59. @@ -222,6 +233,8 @@ class ProcessSingleton {
  60. // because it posts messages between threads.
  61. class LinuxWatcher;
  62. scoped_refptr<LinuxWatcher> watcher_;
  63. + int sock_ = -1;
  64. + bool listen_on_ready_ = false;
  65. #endif
  66. #if BUILDFLAG(IS_MAC)
  67. diff --git a/chrome/browser/process_singleton_posix.cc b/chrome/browser/process_singleton_posix.cc
  68. index 22331cd6985b2aa2347fe9d4211f51634e94d0a6..be2c417c07a4206fac4a9a6c03e516fd0493c942 100644
  69. --- a/chrome/browser/process_singleton_posix.cc
  70. +++ b/chrome/browser/process_singleton_posix.cc
  71. @@ -54,6 +54,7 @@
  72. #include <memory>
  73. #include <set>
  74. #include <string>
  75. +#include <tuple>
  76. #include <type_traits>
  77. #include "base/base_paths.h"
  78. @@ -80,6 +81,7 @@
  79. #include "base/strings/utf_string_conversions.h"
  80. #include "base/task/sequenced_task_runner_helpers.h"
  81. #include "base/task/single_thread_task_runner.h"
  82. +#include "base/task/post_task.h"
  83. #include "base/threading/platform_thread.h"
  84. #include "base/threading/thread_task_runner_handle.h"
  85. #include "base/time/time.h"
  86. @@ -96,9 +98,11 @@
  87. #include "net/base/network_interfaces.h"
  88. #include "ui/base/l10n/l10n_util.h"
  89. +#if 0
  90. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
  91. #include "chrome/browser/ui/process_singleton_dialog_linux.h"
  92. #endif
  93. +#endif
  94. #if defined(TOOLKIT_VIEWS) && \
  95. (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS))
  96. @@ -347,6 +351,9 @@ bool SymlinkPath(const base::FilePath& target, const base::FilePath& path) {
  97. bool DisplayProfileInUseError(const base::FilePath& lock_path,
  98. const std::string& hostname,
  99. int pid) {
  100. + return true;
  101. +
  102. +#if 0
  103. std::u16string error = l10n_util::GetStringFUTF16(
  104. IDS_PROFILE_IN_USE_POSIX, base::NumberToString16(pid),
  105. base::ASCIIToUTF16(hostname));
  106. @@ -366,6 +373,7 @@ bool DisplayProfileInUseError(const base::FilePath& lock_path,
  107. NOTREACHED();
  108. return false;
  109. +#endif
  110. }
  111. bool IsChromeProcess(pid_t pid) {
  112. @@ -406,6 +414,21 @@ bool CheckCookie(const base::FilePath& path, const base::FilePath& cookie) {
  113. return (cookie == ReadLink(path));
  114. }
  115. +bool IsAppSandboxed() {
  116. +#if BUILDFLAG(IS_MAC)
  117. + // NB: There is no sane API for this, we have to just guess by
  118. + // reading tea leaves
  119. + base::FilePath home_dir;
  120. + if (!base::PathService::Get(base::DIR_HOME, &home_dir)) {
  121. + return false;
  122. + }
  123. +
  124. + return home_dir.value().find("Library/Containers") != std::string::npos;
  125. +#else
  126. + return false;
  127. +#endif // BUILDFLAG(IS_MAC)
  128. +}
  129. +
  130. bool ConnectSocket(ScopedSocket* socket,
  131. const base::FilePath& socket_path,
  132. const base::FilePath& cookie_path) {
  133. @@ -773,6 +796,10 @@ ProcessSingleton::ProcessSingleton(
  134. ProcessSingleton::~ProcessSingleton() {
  135. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  136. + // Manually free resources with IO explicitly allowed.
  137. + base::ThreadRestrictions::ScopedAllowIO allow_io;
  138. + watcher_ = nullptr;
  139. + std::ignore = socket_dir_.Delete();
  140. }
  141. ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcess() {
  142. @@ -945,6 +972,20 @@ ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcessOrCreate() {
  143. base::Seconds(kTimeoutInSeconds));
  144. }
  145. +void ProcessSingleton::StartListeningOnSocket() {
  146. + watcher_ = base::MakeRefCounted<LinuxWatcher>(this);
  147. + base::PostTask(FROM_HERE, {BrowserThread::IO},
  148. + base::BindOnce(&ProcessSingleton::LinuxWatcher::StartListening,
  149. + watcher_, sock_));
  150. +}
  151. +
  152. +void ProcessSingleton::OnBrowserReady() {
  153. + if (listen_on_ready_) {
  154. + StartListeningOnSocket();
  155. + listen_on_ready_ = false;
  156. + }
  157. +}
  158. +
  159. ProcessSingleton::NotifyResult
  160. ProcessSingleton::NotifyOtherProcessWithTimeoutOrCreate(
  161. const base::CommandLine& command_line,
  162. @@ -1044,14 +1085,32 @@ bool ProcessSingleton::Create() {
  163. #endif
  164. }
  165. - // Create the socket file somewhere in /tmp which is usually mounted as a
  166. - // normal filesystem. Some network filesystems (notably AFS) are screwy and
  167. - // do not support Unix domain sockets.
  168. - if (!socket_dir_.CreateUniqueTempDir()) {
  169. - LOG(ERROR) << "Failed to create socket directory.";
  170. + base::FilePath tmp_dir;
  171. + if (!base::GetTempDir(&tmp_dir)) {
  172. + LOG(ERROR) << "Failed to get temporary directory.";
  173. return false;
  174. }
  175. + if (IsAppSandboxed()) {
  176. + // For sandboxed applications, the tmp dir could be too long to fit
  177. + // addr->sun_path, so we need to make it as short as possible.
  178. + if (!socket_dir_.Set(tmp_dir.Append("S"))) {
  179. + LOG(ERROR) << "Failed to set socket directory.";
  180. + return false;
  181. + }
  182. + } else {
  183. + // Create the socket file somewhere in /tmp which is usually mounted as a
  184. + // normal filesystem. Some network filesystems (notably AFS) are screwy and
  185. + // do not support Unix domain sockets.
  186. + // Prefer CreateUniqueTempDirUnderPath rather than CreateUniqueTempDir as
  187. + // the latter will calculate unique paths based on bundle ids which can
  188. + // increase the socket path length than what is allowed.
  189. + if (!socket_dir_.CreateUniqueTempDirUnderPath(tmp_dir)) {
  190. + LOG(ERROR) << "Failed to create socket directory.";
  191. + return false;
  192. + }
  193. + }
  194. +
  195. // Check that the directory was created with the correct permissions.
  196. int dir_mode = 0;
  197. CHECK(base::GetPosixFilePermissions(socket_dir_.GetPath(), &dir_mode) &&
  198. @@ -1094,10 +1153,13 @@ bool ProcessSingleton::Create() {
  199. if (listen(sock, 5) < 0)
  200. NOTREACHED() << "listen failed: " << base::safe_strerror(errno);
  201. - DCHECK(BrowserThread::IsThreadInitialized(BrowserThread::IO));
  202. - content::GetIOThreadTaskRunner({})->PostTask(
  203. - FROM_HERE, base::BindOnce(&ProcessSingleton::LinuxWatcher::StartListening,
  204. - watcher_, sock));
  205. + sock_ = sock;
  206. +
  207. + if (BrowserThread::IsThreadInitialized(BrowserThread::IO)) {
  208. + StartListeningOnSocket();
  209. + } else {
  210. + listen_on_ready_ = true;
  211. + }
  212. return true;
  213. }
  214. diff --git a/chrome/browser/process_singleton_win.cc b/chrome/browser/process_singleton_win.cc
  215. index e2312c65623a3f54ecbc18058720ccae53822e76..ec725b44296266bea1a51aea889463a0bba8449c 100644
  216. --- a/chrome/browser/process_singleton_win.cc
  217. +++ b/chrome/browser/process_singleton_win.cc
  218. @@ -28,7 +28,9 @@
  219. #include "base/win/wmi.h"
  220. #include "chrome/browser/process_singleton_internal.h"
  221. #include "chrome/browser/shell_integration.h"
  222. +#if 0
  223. #include "chrome/browser/ui/simple_message_box.h"
  224. +#endif
  225. #include "chrome/browser/win/chrome_process_finder.h"
  226. #include "chrome/common/chrome_constants.h"
  227. #include "chrome/common/chrome_paths.h"
  228. @@ -163,11 +165,16 @@ bool ProcessLaunchNotification(
  229. }
  230. bool DisplayShouldKillMessageBox() {
  231. +#if 0
  232. TRACE_EVENT0("startup", "ProcessSingleton:DisplayShouldKillMessageBox");
  233. return chrome::ShowQuestionMessageBoxSync(
  234. NULL, l10n_util::GetStringUTF16(IDS_PRODUCT_NAME),
  235. l10n_util::GetStringUTF16(IDS_BROWSER_HUNGBROWSER_MESSAGE)) !=
  236. chrome::MESSAGE_BOX_RESULT_NO;
  237. +#endif
  238. + // This is called when the secondary process can't ping the primary
  239. + // process.
  240. + return false;
  241. }
  242. // Function was copied from Process::Terminate.
  243. @@ -252,9 +259,13 @@ bool ProcessSingleton::EscapeVirtualization(
  244. }
  245. ProcessSingleton::ProcessSingleton(
  246. + const std::string& program_name,
  247. const base::FilePath& user_data_dir,
  248. + bool is_app_sandboxed,
  249. const NotificationCallback& notification_callback)
  250. : notification_callback_(notification_callback),
  251. + program_name_(program_name),
  252. + is_app_sandboxed_(is_app_sandboxed),
  253. is_virtualized_(false),
  254. lock_file_(INVALID_HANDLE_VALUE),
  255. user_data_dir_(user_data_dir),
  256. @@ -368,13 +379,16 @@ ProcessSingleton::NotifyOtherProcessOrCreate() {
  257. return PROFILE_IN_USE;
  258. }
  259. +void ProcessSingleton::StartListeningOnSocket() {}
  260. +void ProcessSingleton::OnBrowserReady() {}
  261. +
  262. // Look for a Chrome instance that uses the same profile directory. If there
  263. // isn't one, create a message window with its title set to the profile
  264. // directory path.
  265. bool ProcessSingleton::Create() {
  266. TRACE_EVENT0("startup", "ProcessSingleton::Create");
  267. - static const wchar_t kMutexName[] = L"Local\\ChromeProcessSingletonStartup!";
  268. + std::wstring mutexName = base::UTF8ToWide("Local\\" + program_name_ + "ProcessSingletonStartup");
  269. remote_window_ = chrome::FindRunningChromeWindow(user_data_dir_);
  270. if (!remote_window_ && !EscapeVirtualization(user_data_dir_)) {
  271. @@ -383,7 +397,7 @@ bool ProcessSingleton::Create() {
  272. // access. As documented, it's clearer to NOT request ownership on creation
  273. // since it isn't guaranteed we will get it. It is better to create it
  274. // without ownership and explicitly get the ownership afterward.
  275. - base::win::ScopedHandle only_me(::CreateMutex(NULL, FALSE, kMutexName));
  276. + base::win::ScopedHandle only_me(::CreateMutex(NULL, FALSE, mutexName.c_str()));
  277. if (!only_me.IsValid()) {
  278. DPLOG(FATAL) << "CreateMutex failed";
  279. return false;
  280. @@ -422,6 +436,17 @@ bool ProcessSingleton::Create() {
  281. window_.CreateNamed(base::BindRepeating(&ProcessLaunchNotification,
  282. notification_callback_),
  283. user_data_dir_.value());
  284. +
  285. + // When the app is sandboxed, firstly, the app should not be in
  286. + // admin mode, and even if it somehow is, messages from an unelevated
  287. + // instance should not be able to be sent to it.
  288. + if (!is_app_sandboxed_) {
  289. + // NB: Ensure that if the primary app gets started as elevated
  290. + // admin inadvertently, secondary windows running not as elevated
  291. + // will still be able to send messages.
  292. + ::ChangeWindowMessageFilterEx(window_.hwnd(), WM_COPYDATA, MSGFLT_ALLOW,
  293. + NULL);
  294. + }
  295. CHECK(result && window_.hwnd());
  296. }
  297. }