electron_sandboxed_renderer_client.cc 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. // Copyright (c) 2016 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/renderer/electron_sandboxed_renderer_client.h"
  5. #include <iterator>
  6. #include <tuple>
  7. #include <vector>
  8. #include "base/base_paths.h"
  9. #include "base/command_line.h"
  10. #include "base/containers/contains.h"
  11. #include "base/files/file_path.h"
  12. #include "base/path_service.h"
  13. #include "base/process/process_handle.h"
  14. #include "base/process/process_metrics.h"
  15. #include "content/public/renderer/render_frame.h"
  16. #include "electron/buildflags/buildflags.h"
  17. #include "shell/common/api/electron_bindings.h"
  18. #include "shell/common/application_info.h"
  19. #include "shell/common/gin_helper/dictionary.h"
  20. #include "shell/common/gin_helper/microtasks_scope.h"
  21. #include "shell/common/node_bindings.h"
  22. #include "shell/common/node_includes.h"
  23. #include "shell/common/node_util.h"
  24. #include "shell/common/options_switches.h"
  25. #include "shell/renderer/electron_render_frame_observer.h"
  26. #include "third_party/blink/public/common/web_preferences/web_preferences.h"
  27. #include "third_party/blink/public/web/blink.h"
  28. #include "third_party/blink/public/web/web_document.h"
  29. #include "third_party/electron_node/src/node_binding.h"
  30. namespace electron {
  31. namespace {
  32. const char kEmitProcessEventKey[] = "emit-process-event";
  33. const char kBindingCacheKey[] = "native-binding-cache";
  34. v8::Local<v8::Object> GetBindingCache(v8::Isolate* isolate) {
  35. auto context = isolate->GetCurrentContext();
  36. gin_helper::Dictionary global(isolate, context->Global());
  37. v8::Local<v8::Value> cache;
  38. if (!global.GetHidden(kBindingCacheKey, &cache)) {
  39. cache = v8::Object::New(isolate);
  40. global.SetHidden(kBindingCacheKey, cache);
  41. }
  42. return cache->ToObject(context).ToLocalChecked();
  43. }
  44. // adapted from node.cc
  45. v8::Local<v8::Value> GetBinding(v8::Isolate* isolate,
  46. v8::Local<v8::String> key,
  47. gin_helper::Arguments* margs) {
  48. v8::Local<v8::Object> exports;
  49. std::string binding_key = gin::V8ToString(isolate, key);
  50. gin_helper::Dictionary cache(isolate, GetBindingCache(isolate));
  51. if (cache.Get(binding_key.c_str(), &exports)) {
  52. return exports;
  53. }
  54. auto* mod = node::binding::get_linked_module(binding_key.c_str());
  55. if (!mod) {
  56. char errmsg[1024];
  57. snprintf(errmsg, sizeof(errmsg), "No such binding: %s",
  58. binding_key.c_str());
  59. margs->ThrowError(errmsg);
  60. return exports;
  61. }
  62. exports = v8::Object::New(isolate);
  63. DCHECK_EQ(mod->nm_register_func, nullptr);
  64. DCHECK_NE(mod->nm_context_register_func, nullptr);
  65. mod->nm_context_register_func(exports, v8::Null(isolate),
  66. isolate->GetCurrentContext(), mod->nm_priv);
  67. cache.Set(binding_key.c_str(), exports);
  68. return exports;
  69. }
  70. v8::Local<v8::Value> CreatePreloadScript(v8::Isolate* isolate,
  71. v8::Local<v8::String> source) {
  72. auto context = isolate->GetCurrentContext();
  73. auto maybe_script = v8::Script::Compile(context, source);
  74. v8::Local<v8::Script> script;
  75. if (!maybe_script.ToLocal(&script))
  76. return v8::Local<v8::Value>();
  77. return script->Run(context).ToLocalChecked();
  78. }
  79. double Uptime() {
  80. return (base::Time::Now() - base::Process::Current().CreationTime())
  81. .InSecondsF();
  82. }
  83. void InvokeEmitProcessEvent(v8::Handle<v8::Context> context,
  84. const std::string& event_name) {
  85. auto* isolate = context->GetIsolate();
  86. // set by sandboxed_renderer/init.js
  87. auto binding_key = gin::ConvertToV8(isolate, kEmitProcessEventKey)
  88. ->ToString(context)
  89. .ToLocalChecked();
  90. auto private_binding_key = v8::Private::ForApi(isolate, binding_key);
  91. auto global_object = context->Global();
  92. v8::Local<v8::Value> callback_value;
  93. if (!global_object->GetPrivate(context, private_binding_key)
  94. .ToLocal(&callback_value))
  95. return;
  96. if (callback_value.IsEmpty() || !callback_value->IsFunction())
  97. return;
  98. auto callback = callback_value.As<v8::Function>();
  99. v8::Local<v8::Value> args[] = {gin::ConvertToV8(isolate, event_name)};
  100. std::ignore =
  101. callback->Call(context, callback, std::size(args), std::data(args));
  102. }
  103. } // namespace
  104. ElectronSandboxedRendererClient::ElectronSandboxedRendererClient() {
  105. // Explicitly register electron's builtin bindings.
  106. NodeBindings::RegisterBuiltinBindings();
  107. metrics_ = base::ProcessMetrics::CreateCurrentProcessMetrics();
  108. }
  109. ElectronSandboxedRendererClient::~ElectronSandboxedRendererClient() = default;
  110. void ElectronSandboxedRendererClient::InitializeBindings(
  111. v8::Local<v8::Object> binding,
  112. v8::Local<v8::Context> context,
  113. content::RenderFrame* render_frame) {
  114. auto* isolate = context->GetIsolate();
  115. gin_helper::Dictionary b(isolate, binding);
  116. b.SetMethod("get", GetBinding);
  117. b.SetMethod("createPreloadScript", CreatePreloadScript);
  118. auto process = gin_helper::Dictionary::CreateEmpty(isolate);
  119. b.Set("process", process);
  120. ElectronBindings::BindProcess(isolate, &process, metrics_.get());
  121. BindProcess(isolate, &process, render_frame);
  122. process.SetMethod("uptime", Uptime);
  123. process.Set("argv", base::CommandLine::ForCurrentProcess()->argv());
  124. process.SetReadOnly("pid", base::GetCurrentProcId());
  125. process.SetReadOnly("sandboxed", true);
  126. process.SetReadOnly("type", "renderer");
  127. }
  128. void ElectronSandboxedRendererClient::RenderFrameCreated(
  129. content::RenderFrame* render_frame) {
  130. new ElectronRenderFrameObserver(render_frame, this);
  131. RendererClientBase::RenderFrameCreated(render_frame);
  132. }
  133. void ElectronSandboxedRendererClient::RunScriptsAtDocumentStart(
  134. content::RenderFrame* render_frame) {
  135. RendererClientBase::RunScriptsAtDocumentStart(render_frame);
  136. EmitProcessEvent(render_frame, "document-start");
  137. }
  138. void ElectronSandboxedRendererClient::RunScriptsAtDocumentEnd(
  139. content::RenderFrame* render_frame) {
  140. RendererClientBase::RunScriptsAtDocumentEnd(render_frame);
  141. EmitProcessEvent(render_frame, "document-end");
  142. }
  143. void ElectronSandboxedRendererClient::DidCreateScriptContext(
  144. v8::Handle<v8::Context> context,
  145. content::RenderFrame* render_frame) {
  146. // Only allow preload for the main frame or
  147. // For devtools we still want to run the preload_bundle script
  148. // Or when nodeSupport is explicitly enabled in sub frames
  149. if (!ShouldLoadPreload(context, render_frame))
  150. return;
  151. injected_frames_.insert(render_frame);
  152. // Wrap the bundle into a function that receives the binding object as
  153. // argument.
  154. auto* isolate = context->GetIsolate();
  155. auto binding = v8::Object::New(isolate);
  156. InitializeBindings(binding, context, render_frame);
  157. std::vector<v8::Local<v8::String>> sandbox_preload_bundle_params = {
  158. node::FIXED_ONE_BYTE_STRING(isolate, "binding")};
  159. std::vector<v8::Local<v8::Value>> sandbox_preload_bundle_args = {binding};
  160. util::CompileAndCall(
  161. isolate->GetCurrentContext(), "electron/js2c/sandbox_bundle",
  162. &sandbox_preload_bundle_params, &sandbox_preload_bundle_args);
  163. v8::HandleScope handle_scope(isolate);
  164. v8::Context::Scope context_scope(context);
  165. InvokeEmitProcessEvent(context, "loaded");
  166. }
  167. void ElectronSandboxedRendererClient::WillReleaseScriptContext(
  168. v8::Handle<v8::Context> context,
  169. content::RenderFrame* render_frame) {
  170. if (injected_frames_.erase(render_frame) == 0)
  171. return;
  172. auto* isolate = context->GetIsolate();
  173. gin_helper::MicrotasksScope microtasks_scope(
  174. isolate, context->GetMicrotaskQueue(),
  175. v8::MicrotasksScope::kDoNotRunMicrotasks);
  176. v8::HandleScope handle_scope(isolate);
  177. v8::Context::Scope context_scope(context);
  178. InvokeEmitProcessEvent(context, "exit");
  179. }
  180. void ElectronSandboxedRendererClient::EmitProcessEvent(
  181. content::RenderFrame* render_frame,
  182. const char* event_name) {
  183. if (!base::Contains(injected_frames_, render_frame))
  184. return;
  185. auto* isolate = blink::MainThreadIsolate();
  186. v8::HandleScope handle_scope(isolate);
  187. v8::Local<v8::Context> context =
  188. GetContext(render_frame->GetWebFrame(), isolate);
  189. gin_helper::MicrotasksScope microtasks_scope(
  190. isolate, context->GetMicrotaskQueue(),
  191. v8::MicrotasksScope::kDoNotRunMicrotasks);
  192. v8::Context::Scope context_scope(context);
  193. InvokeEmitProcessEvent(context, event_name);
  194. }
  195. } // namespace electron