node_main.cc 11 KB

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