node_main.cc 11 KB

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