node_main.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. // Copyright (c) 2015 GitHub, Inc.
  2. // Use of this source code is governed by the MIT license that can be
  3. // found in the LICENSE file.
  4. #include "shell/app/node_main.h"
  5. #include <map>
  6. #include <memory>
  7. #include <string>
  8. #include <string_view>
  9. #include <utility>
  10. #include <vector>
  11. #include "base/base_switches.h"
  12. #include "base/command_line.h"
  13. #include "base/containers/fixed_flat_set.h"
  14. #include "base/environment.h"
  15. #include "base/feature_list.h"
  16. #include "base/task/single_thread_task_runner.h"
  17. #include "base/task/thread_pool/thread_pool_instance.h"
  18. #include "content/public/common/content_switches.h"
  19. #include "electron/fuses.h"
  20. #include "electron/mas.h"
  21. #include "gin/array_buffer.h"
  22. #include "gin/public/isolate_holder.h"
  23. #include "gin/v8_initializer.h"
  24. #include "shell/app/uv_task_runner.h"
  25. #include "shell/browser/javascript_environment.h"
  26. #include "shell/common/api/electron_bindings.h"
  27. #include "shell/common/electron_command_line.h"
  28. #include "shell/common/gin_helper/dictionary.h"
  29. #include "shell/common/node_bindings.h"
  30. #include "shell/common/node_includes.h"
  31. #include "shell/common/node_util.h"
  32. #if BUILDFLAG(IS_WIN)
  33. #include "chrome/child/v8_crashpad_support_win.h"
  34. #endif
  35. #if BUILDFLAG(IS_LINUX)
  36. #include "base/posix/global_descriptors.h"
  37. #include "base/strings/string_number_conversions.h"
  38. #include "components/crash/core/app/crash_switches.h" // nogncheck
  39. #include "content/public/common/content_descriptors.h"
  40. #endif
  41. #if BUILDFLAG(IS_MAC)
  42. #include "shell/common/mac/codesign_util.h"
  43. #endif
  44. #if !IS_MAS_BUILD()
  45. #include "components/crash/core/app/crashpad.h" // nogncheck
  46. #include "shell/app/electron_crash_reporter_client.h"
  47. #include "shell/common/crash_keys.h"
  48. #endif
  49. namespace {
  50. // Preparse Node.js cli options to pass to Node.js
  51. // See https://nodejs.org/api/cli.html#cli_options
  52. void ExitIfContainsDisallowedFlags(const std::vector<std::string>& argv) {
  53. // Options that are unilaterally disallowed.
  54. static constexpr auto disallowed = base::MakeFixedFlatSet<std::string_view>({
  55. "--enable-fips",
  56. "--force-fips",
  57. "--openssl-config",
  58. "--use-bundled-ca",
  59. "--use-openssl-ca",
  60. });
  61. for (const auto& arg : argv) {
  62. const auto key = std::string_view{arg}.substr(0, arg.find('='));
  63. if (disallowed.contains(key)) {
  64. LOG(ERROR) << "The Node.js cli flag " << key
  65. << " is not supported in Electron";
  66. // Node.js returns 9 from ProcessGlobalArgs for any errors encountered
  67. // when setting up cli flags and env vars. Since we're outlawing these
  68. // flags (making them errors) exit with the same error code for
  69. // consistency.
  70. exit(9);
  71. }
  72. }
  73. }
  74. #if BUILDFLAG(IS_MAC)
  75. // A list of node envs that may be used to inject scripts.
  76. const char* kHijackableEnvs[] = {"NODE_OPTIONS", "NODE_REPL_EXTERNAL_MODULE"};
  77. // Return true if there is any env in kHijackableEnvs.
  78. bool UnsetHijackableEnvs(base::Environment* env) {
  79. bool has = false;
  80. for (const char* name : kHijackableEnvs) {
  81. if (env->HasVar(name)) {
  82. env->UnSetVar(name);
  83. has = true;
  84. }
  85. }
  86. return has;
  87. }
  88. #endif
  89. #if IS_MAS_BUILD()
  90. void SetCrashKeyStub(const std::string& key, const std::string& value) {}
  91. void ClearCrashKeyStub(const std::string& key) {}
  92. #endif
  93. v8::Local<v8::Value> GetParameters(v8::Isolate* isolate) {
  94. std::map<std::string, std::string> keys;
  95. #if !IS_MAS_BUILD()
  96. electron::crash_keys::GetCrashKeys(&keys);
  97. #endif
  98. return gin::ConvertToV8(isolate, keys);
  99. }
  100. } // namespace
  101. namespace electron {
  102. int NodeMain() {
  103. DCHECK(base::CommandLine::InitializedForCurrentProcess());
  104. auto os_env = base::Environment::Create();
  105. bool node_options_enabled = electron::fuses::IsNodeOptionsEnabled();
  106. if (!node_options_enabled) {
  107. os_env->UnSetVar("NODE_OPTIONS");
  108. os_env->UnSetVar("NODE_EXTRA_CA_CERTS");
  109. }
  110. #if BUILDFLAG(IS_MAC)
  111. if (!ProcessSignatureIsSameWithCurrentApp(getppid())) {
  112. // On macOS, it is forbidden to run sandboxed app with custom arguments
  113. // from another app, i.e. args are discarded in following call:
  114. // exec("Sandboxed.app", ["--custom-args-will-be-discarded"])
  115. // However it is possible to bypass the restriction by abusing the node mode
  116. // of Electron apps:
  117. // exec("Electron.app", {env: {ELECTRON_RUN_AS_NODE: "1",
  118. // NODE_OPTIONS: "--require 'bad.js'"}})
  119. // To prevent Electron apps from being used to work around macOS security
  120. // restrictions, when the parent process is not part of the app bundle, all
  121. // environment variables that may be used to inject scripts are removed.
  122. if (UnsetHijackableEnvs(os_env.get())) {
  123. LOG(ERROR) << "Node.js environment variables are disabled because this "
  124. "process is invoked by other apps.";
  125. }
  126. }
  127. #endif // BUILDFLAG(IS_MAC)
  128. #if BUILDFLAG(IS_WIN)
  129. v8_crashpad_support::SetUp();
  130. #endif
  131. #if BUILDFLAG(IS_LINUX)
  132. std::string fd_string, pid_string;
  133. if (os_env->GetVar("CRASHDUMP_SIGNAL_FD", &fd_string) &&
  134. os_env->GetVar("CRASHPAD_HANDLER_PID", &pid_string)) {
  135. int fd = -1, pid = -1;
  136. DCHECK(base::StringToInt(fd_string, &fd));
  137. DCHECK(base::StringToInt(pid_string, &pid));
  138. base::GlobalDescriptors::GetInstance()->Set(kCrashDumpSignal, fd);
  139. // Following API is unsafe in multi-threaded scenario, but at this point
  140. // we are still single threaded.
  141. os_env->UnSetVar("CRASHDUMP_SIGNAL_FD");
  142. os_env->UnSetVar("CRASHPAD_HANDLER_PID");
  143. }
  144. #endif
  145. int exit_code = 1;
  146. {
  147. // Feed gin::PerIsolateData with a task runner.
  148. uv_loop_t* loop = uv_default_loop();
  149. auto uv_task_runner = base::MakeRefCounted<UvTaskRunner>(loop);
  150. base::SingleThreadTaskRunner::CurrentDefaultHandle handle(uv_task_runner);
  151. // Initialize feature list.
  152. auto feature_list = std::make_unique<base::FeatureList>();
  153. feature_list->InitFromCommandLine("", "");
  154. base::FeatureList::SetInstance(std::move(feature_list));
  155. // Explicitly register electron's builtin bindings.
  156. NodeBindings::RegisterBuiltinBindings();
  157. // Parse Node.js cli flags and strip out disallowed options.
  158. const std::vector<std::string> args = ElectronCommandLine::AsUtf8();
  159. ExitIfContainsDisallowedFlags(args);
  160. std::shared_ptr<node::InitializationResult> result =
  161. node::InitializeOncePerProcess(
  162. args,
  163. {node::ProcessInitializationFlags::kNoInitializeV8,
  164. node::ProcessInitializationFlags::kNoInitializeNodeV8Platform});
  165. for (const std::string& error : result->errors())
  166. fprintf(stderr, "%s: %s\n", args[0].c_str(), error.c_str());
  167. if (result->early_return() != 0) {
  168. return result->exit_code();
  169. }
  170. #if BUILDFLAG(IS_LINUX)
  171. // On Linux, initialize crashpad after Nodejs init phase so that
  172. // crash and termination signal handlers can be set by the crashpad client.
  173. if (!pid_string.empty()) {
  174. auto* command_line = base::CommandLine::ForCurrentProcess();
  175. command_line->AppendSwitchASCII(
  176. crash_reporter::switches::kCrashpadHandlerPid, pid_string);
  177. ElectronCrashReporterClient::Create();
  178. crash_reporter::InitializeCrashpad(false, "node");
  179. crash_keys::SetCrashKeysFromCommandLine(
  180. *base::CommandLine::ForCurrentProcess());
  181. crash_keys::SetPlatformCrashKey();
  182. // Ensure the flags and env variable does not propagate to userland.
  183. command_line->RemoveSwitch(crash_reporter::switches::kCrashpadHandlerPid);
  184. }
  185. #elif BUILDFLAG(IS_WIN) || (BUILDFLAG(IS_MAC) && !IS_MAS_BUILD())
  186. ElectronCrashReporterClient::Create();
  187. crash_reporter::InitializeCrashpad(false, "node");
  188. crash_keys::SetCrashKeysFromCommandLine(
  189. *base::CommandLine::ForCurrentProcess());
  190. crash_keys::SetPlatformCrashKey();
  191. #endif
  192. gin::V8Initializer::LoadV8Snapshot(
  193. gin::V8SnapshotFileType::kWithAdditionalContext);
  194. // V8 requires a task scheduler.
  195. base::ThreadPoolInstance::CreateAndStartWithDefaultParams("Electron");
  196. // Allow Node.js to track the amount of time the event loop has spent
  197. // idle in the kernel’s event provider .
  198. uv_loop_configure(loop, UV_METRICS_IDLE_TIME);
  199. // Initialize gin::IsolateHolder.
  200. bool setup_wasm_streaming =
  201. node::per_process::cli_options->get_per_isolate_options()
  202. ->get_per_env_options()
  203. ->experimental_fetch;
  204. JavascriptEnvironment gin_env(loop, setup_wasm_streaming);
  205. v8::Isolate* isolate = gin_env.isolate();
  206. v8::Isolate::Scope isolate_scope(isolate);
  207. v8::Locker locker(isolate);
  208. node::Environment* env = nullptr;
  209. node::IsolateData* isolate_data = nullptr;
  210. {
  211. v8::HandleScope scope(isolate);
  212. isolate_data = node::CreateIsolateData(isolate, loop, gin_env.platform());
  213. CHECK_NE(nullptr, isolate_data);
  214. uint64_t env_flags = node::EnvironmentFlags::kDefaultFlags |
  215. node::EnvironmentFlags::kHideConsoleWindows;
  216. env = node::CreateEnvironment(
  217. isolate_data, isolate->GetCurrentContext(), result->args(),
  218. result->exec_args(),
  219. static_cast<node::EnvironmentFlags::Flags>(env_flags));
  220. CHECK_NE(nullptr, env);
  221. node::SetIsolateUpForNode(isolate);
  222. gin_helper::Dictionary process(isolate, env->process_object());
  223. process.SetMethod("crash", &ElectronBindings::Crash);
  224. // Setup process.crashReporter in child node processes
  225. auto reporter = gin_helper::Dictionary::CreateEmpty(isolate);
  226. reporter.SetMethod("getParameters", &GetParameters);
  227. #if IS_MAS_BUILD()
  228. reporter.SetMethod("addExtraParameter", &SetCrashKeyStub);
  229. reporter.SetMethod("removeExtraParameter", &ClearCrashKeyStub);
  230. #else
  231. reporter.SetMethod("addExtraParameter",
  232. &electron::crash_keys::SetCrashKey);
  233. reporter.SetMethod("removeExtraParameter",
  234. &electron::crash_keys::ClearCrashKey);
  235. #endif
  236. process.Set("crashReporter", reporter);
  237. }
  238. v8::HandleScope scope(isolate);
  239. node::LoadEnvironment(env, node::StartExecutionCallback{}, &OnNodePreload);
  240. // Potential reasons we get Nothing here may include: the env
  241. // is stopping, or the user hooks process.emit('exit').
  242. exit_code = node::SpinEventLoop(env).FromMaybe(1);
  243. node::ResetStdio();
  244. node::Stop(env, node::StopFlags::kDoNotTerminateIsolate);
  245. node::FreeEnvironment(env);
  246. node::FreeIsolateData(isolate_data);
  247. }
  248. // According to "src/gin/shell/gin_main.cc":
  249. //
  250. // gin::IsolateHolder waits for tasks running in ThreadPool in its
  251. // destructor and thus must be destroyed before ThreadPool starts skipping
  252. // CONTINUE_ON_SHUTDOWN tasks.
  253. base::ThreadPoolInstance::Get()->Shutdown();
  254. v8::V8::Dispose();
  255. return exit_code;
  256. }
  257. } // namespace electron