Merge branch 'support-chromium-sandbox' of https://github.com/tarruda/electron into tarruda-support-chromium-sandbox

This commit is contained in:
Cheng Zhao 2016-09-27 20:02:23 +08:00
commit 458c4dd129
35 changed files with 1055 additions and 100 deletions

View file

@ -11,7 +11,9 @@
#include "atom/browser/atom_browser_client.h"
#include "atom/browser/relauncher.h"
#include "atom/common/google_api_key.h"
#include "atom/common/options_switches.h"
#include "atom/renderer/atom_renderer_client.h"
#include "atom/renderer/atom_sandboxed_renderer_client.h"
#include "atom/utility/atom_content_utility_client.h"
#include "base/command_line.h"
#include "base/debug/stack_trace.h"
@ -29,7 +31,7 @@ namespace {
const char* kRelauncherProcess = "relauncher";
bool IsBrowserProcess(base::CommandLine* cmd) {
std::string process_type = cmd->GetSwitchValueASCII(switches::kProcessType);
std::string process_type = cmd->GetSwitchValueASCII(::switches::kProcessType);
return process_type.empty();
}
@ -72,7 +74,7 @@ bool AtomMainDelegate::BasicStartupComplete(int* exit_code) {
// Only enable logging when --enable-logging is specified.
std::unique_ptr<base::Environment> env(base::Environment::Create());
if (!command_line->HasSwitch(switches::kEnableLogging) &&
if (!command_line->HasSwitch(::switches::kEnableLogging) &&
!env->HasVar("ELECTRON_ENABLE_LOGGING")) {
settings.logging_dest = logging::LOG_NONE;
logging::SetMinLogLevel(logging::LOG_NUM_SEVERITIES);
@ -115,17 +117,23 @@ void AtomMainDelegate::PreSandboxStartup() {
auto command_line = base::CommandLine::ForCurrentProcess();
std::string process_type = command_line->GetSwitchValueASCII(
switches::kProcessType);
::switches::kProcessType);
// Only append arguments for browser process.
if (!IsBrowserProcess(command_line))
return;
// Disable renderer sandbox for most of node's functions.
command_line->AppendSwitch(switches::kNoSandbox);
if (command_line->HasSwitch(switches::kEnableSandbox)) {
// Disable setuid sandbox since it is not longer required on linux(namespace
// sandbox is available on most distros).
command_line->AppendSwitch(::switches::kDisableSetuidSandbox);
} else {
// Disable renderer sandbox for most of node's functions.
command_line->AppendSwitch(::switches::kNoSandbox);
}
// Allow file:// URIs to read other file:// URIs by default.
command_line->AppendSwitch(switches::kAllowFileAccessFromFiles);
command_line->AppendSwitch(::switches::kAllowFileAccessFromFiles);
#if defined(OS_MACOSX)
// Enable AVFoundation.
@ -140,7 +148,13 @@ content::ContentBrowserClient* AtomMainDelegate::CreateContentBrowserClient() {
content::ContentRendererClient*
AtomMainDelegate::CreateContentRendererClient() {
renderer_client_.reset(new AtomRendererClient);
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableSandbox)) {
renderer_client_.reset(new AtomSandboxedRendererClient);
} else {
renderer_client_.reset(new AtomRendererClient);
}
return renderer_client_.get();
}

View file

@ -258,17 +258,25 @@ void OnCapturePageDone(base::Callback<void(const gfx::Image&)> callback,
} // namespace
WebContents::WebContents(v8::Isolate* isolate,
content::WebContents* web_contents)
content::WebContents* web_contents,
Type type)
: content::WebContentsObserver(web_contents),
embedder_(nullptr),
type_(REMOTE),
type_(type),
request_id_(0),
background_throttling_(true),
enable_devtools_(true) {
web_contents->SetUserAgentOverride(GetBrowserContext()->GetUserAgent());
Init(isolate);
AttachAsUserData(web_contents);
if (type == REMOTE) {
web_contents->SetUserAgentOverride(GetBrowserContext()->GetUserAgent());
Init(isolate);
AttachAsUserData(web_contents);
} else {
const mate::Dictionary options = mate::Dictionary::CreateEmpty(isolate);
auto session = Session::CreateFrom(isolate, GetBrowserContext());
session_.Reset(isolate, session.ToV8());
InitWithSessionAndOptions(isolate, web_contents, session, options);
}
}
WebContents::WebContents(v8::Isolate* isolate,
@ -336,6 +344,13 @@ WebContents::WebContents(v8::Isolate* isolate,
web_contents = content::WebContents::Create(params);
}
InitWithSessionAndOptions(isolate, web_contents, session, options);
}
void WebContents::InitWithSessionAndOptions(v8::Isolate* isolate,
content::WebContents *web_contents,
mate::Handle<api::Session> session,
const mate::Dictionary& options) {
Observe(web_contents);
InitWithWebContents(web_contents, session->browser_context());
@ -408,6 +423,31 @@ void WebContents::OnCreateWindow(const GURL& target_url,
Emit("new-window", target_url, frame_name, disposition);
}
void WebContents::WebContentsCreated(content::WebContents* source_contents,
int opener_render_frame_id,
const std::string& frame_name,
const GURL& target_url,
content::WebContents* new_contents) {
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
auto api_web_contents = CreateFrom(isolate(), new_contents, BROWSER_WINDOW);
Emit("-web-contents-created", api_web_contents, target_url, frame_name);
}
void WebContents::AddNewContents(content::WebContents* source,
content::WebContents* new_contents,
WindowOpenDisposition disposition,
const gfx::Rect& initial_rect,
bool user_gesture,
bool* was_blocked) {
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
auto api_web_contents = CreateFrom(isolate(), new_contents);
Emit("-add-new-contents", api_web_contents, disposition, user_gesture,
initial_rect.x(), initial_rect.y(), initial_rect.width(),
initial_rect.height());
}
content::WebContents* WebContents::OpenURLFromTab(
content::WebContents* source,
const content::OpenURLParams& params) {
@ -801,7 +841,14 @@ void WebContents::NavigationEntryCommitted(
details.is_in_page, details.did_replace_entry);
}
int WebContents::GetID() const {
int64_t WebContents::GetID() const {
int64_t process_id = web_contents()->GetRenderProcessHost()->GetID();
int64_t routing_id = web_contents()->GetRoutingID();
int64_t rv = (process_id << 32) + routing_id;
return rv;
}
int WebContents::GetProcessID() const {
return web_contents()->GetRenderProcessHost()->GetID();
}
@ -1496,6 +1543,7 @@ void WebContents::BuildPrototype(v8::Isolate* isolate,
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.MakeDestroyable()
.SetMethod("getId", &WebContents::GetID)
.SetMethod("getProcessId", &WebContents::GetProcessID)
.SetMethod("equal", &WebContents::Equal)
.SetMethod("_loadURL", &WebContents::LoadURL)
.SetMethod("downloadURL", &WebContents::DownloadURL)
@ -1605,7 +1653,15 @@ mate::Handle<WebContents> WebContents::CreateFrom(
return mate::CreateHandle(isolate, static_cast<WebContents*>(existing));
// Otherwise create a new WebContents wrapper object.
return mate::CreateHandle(isolate, new WebContents(isolate, web_contents));
return mate::CreateHandle(isolate, new WebContents(isolate, web_contents,
REMOTE));
}
mate::Handle<WebContents> WebContents::CreateFrom(
v8::Isolate* isolate, content::WebContents* web_contents, Type type) {
// Otherwise create a new WebContents wrapper object.
return mate::CreateHandle(isolate, new WebContents(isolate, web_contents,
type));
}
// static

View file

@ -58,6 +58,8 @@ class WebContents : public mate::TrackableObject<WebContents>,
// Create from an existing WebContents.
static mate::Handle<WebContents> CreateFrom(
v8::Isolate* isolate, content::WebContents* web_contents);
static mate::Handle<WebContents> CreateFrom(
v8::Isolate* isolate, content::WebContents* web_contents, Type type);
// Create a new WebContents.
static mate::Handle<WebContents> Create(
@ -66,7 +68,8 @@ class WebContents : public mate::TrackableObject<WebContents>,
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
int GetID() const;
int64_t GetID() const;
int GetProcessID() const;
Type GetType() const;
bool Equal(const WebContents* web_contents) const;
void LoadURL(const GURL& url, const mate::Dictionary& options);
@ -191,16 +194,34 @@ class WebContents : public mate::TrackableObject<WebContents>,
v8::Local<v8::Value> Debugger(v8::Isolate* isolate);
protected:
WebContents(v8::Isolate* isolate, content::WebContents* web_contents);
WebContents(v8::Isolate* isolate,
content::WebContents* web_contents,
Type type);
WebContents(v8::Isolate* isolate, const mate::Dictionary& options);
~WebContents();
void InitWithSessionAndOptions(v8::Isolate* isolate,
content::WebContents *web_contents,
mate::Handle<class Session> session,
const mate::Dictionary& options);
// content::WebContentsDelegate:
bool AddMessageToConsole(content::WebContents* source,
int32_t level,
const base::string16& message,
int32_t line_no,
const base::string16& source_id) override;
void WebContentsCreated(content::WebContents* source_contents,
int opener_render_frame_id,
const std::string& frame_name,
const GURL& target_url,
content::WebContents* new_contents) override;
void AddNewContents(content::WebContents* source,
content::WebContents* new_contents,
WindowOpenDisposition disposition,
const gfx::Rect& initial_rect,
bool user_gesture,
bool* was_blocked) override;
content::WebContents* OpenURLFromTab(
content::WebContents* source,
const content::OpenURLParams& params) override;

View file

@ -72,20 +72,33 @@ v8::Local<v8::Value> ToBuffer(v8::Isolate* isolate, void* val, int size) {
Window::Window(v8::Isolate* isolate, v8::Local<v8::Object> wrapper,
const mate::Dictionary& options) {
// Use options.webPreferences to create WebContents.
mate::Dictionary web_preferences = mate::Dictionary::CreateEmpty(isolate);
options.Get(options::kWebPreferences, &web_preferences);
mate::Handle<class WebContents> web_contents;
// If no WebContents was passed to the constructor, create it from options.
if (!options.Get("webContents", &web_contents)) {
// Use options.webPreferences to create WebContents.
mate::Dictionary web_preferences = mate::Dictionary::CreateEmpty(isolate);
options.Get(options::kWebPreferences, &web_preferences);
// Copy the backgroundColor to webContents.
v8::Local<v8::Value> value;
if (options.Get(options::kBackgroundColor, &value))
web_preferences.Set(options::kBackgroundColor, value);
// Copy the backgroundColor to webContents.
v8::Local<v8::Value> value;
if (options.Get(options::kBackgroundColor, &value))
web_preferences.Set(options::kBackgroundColor, value);
v8::Local<v8::Value> transparent;
if (options.Get("transparent", &transparent))
web_preferences.Set("transparent", transparent);
// Creates the WebContents used by BrowserWindow.
auto web_contents = WebContents::Create(isolate, web_preferences);
v8::Local<v8::Value> transparent;
if (options.Get("transparent", &transparent))
web_preferences.Set("transparent", transparent);
// Creates the WebContents used by BrowserWindow.
web_contents = WebContents::Create(isolate, web_preferences);
}
Init(isolate, wrapper, options, web_contents);
}
void Window::Init(v8::Isolate* isolate,
v8::Local<v8::Object> wrapper,
const mate::Dictionary& options,
mate::Handle<class WebContents> web_contents) {
web_contents_.Reset(isolate, web_contents.ToV8());
api_web_contents_ = web_contents.get();

View file

@ -89,6 +89,10 @@ class Window : public mate::TrackableObject<Window>,
#endif
private:
void Init(v8::Isolate* isolate,
v8::Local<v8::Object> wrapper,
const mate::Dictionary& options,
mate::Handle<class WebContents> web_contents);
// APIs for NativeWindow.
void Close();
void Focus();

View file

@ -99,6 +99,44 @@ content::WebContents* AtomBrowserClient::GetWebContentsFromProcessID(
return WebContentsPreferences::GetWebContentsFromProcessID(process_id);
}
bool AtomBrowserClient::ShouldCreateNewSiteInstance(
content::BrowserContext* browser_context,
content::SiteInstance* current_instance,
const GURL& url) {
if (url.SchemeIs(url::kJavaScriptScheme))
// "javacript:" scheme should always use same SiteInstance
return false;
if (!IsRendererSandboxed(current_instance->GetProcess()->GetID()))
// non-sandboxed renderers should always create a new SiteInstance
return true;
// Create new a SiteInstance if navigating to a different site.
auto src_url = current_instance->GetSiteURL();
return
!content::SiteInstance::IsSameWebSite(browser_context, src_url, url) &&
// `IsSameWebSite` doesn't seem to work for some URIs such as `file:`,
// handle these scenarios by comparing only the site as defined by
// `GetSiteForURL`.
content::SiteInstance::GetSiteForURL(browser_context, url) != src_url;
}
void AtomBrowserClient::AddSandboxedRendererId(int process_id) {
base::AutoLock auto_lock(sandboxed_renderers_lock_);
sandboxed_renderers_.insert(process_id);
}
void AtomBrowserClient::RemoveSandboxedRendererId(int process_id) {
base::AutoLock auto_lock(sandboxed_renderers_lock_);
sandboxed_renderers_.erase(process_id);
}
bool AtomBrowserClient::IsRendererSandboxed(int process_id) {
base::AutoLock auto_lock(sandboxed_renderers_lock_);
return sandboxed_renderers_.count(process_id);
}
void AtomBrowserClient::RenderProcessWillLaunch(
content::RenderProcessHost* host) {
int process_id = host->GetID();
@ -106,6 +144,13 @@ void AtomBrowserClient::RenderProcessWillLaunch(
host->AddFilter(new TtsMessageFilter(process_id, host->GetBrowserContext()));
host->AddFilter(
new WidevineCdmMessageFilter(process_id, host->GetBrowserContext()));
content::WebContents* web_contents = GetWebContentsFromProcessID(process_id);
if (WebContentsPreferences::IsSandboxed(web_contents)) {
AddSandboxedRendererId(host->GetID());
// ensure the sandboxed renderer id is removed later
host->AddObserver(this);
}
}
content::SpeechRecognitionManagerDelegate*
@ -155,8 +200,7 @@ void AtomBrowserClient::OverrideSiteInstanceForNavigation(
return;
}
// Restart renderer process for all navigations except "javacript:" scheme.
if (url.SchemeIs(url::kJavaScriptScheme))
if (!ShouldCreateNewSiteInstance(browser_context, current_instance, url))
return;
scoped_refptr<content::SiteInstance> site_instance =
@ -188,6 +232,7 @@ void AtomBrowserClient::AppendExtraCommandLineSwitches(
// Copy following switches to child process.
static const char* const kCommonSwitchNames[] = {
switches::kStandardSchemes,
switches::kEnableSandbox
};
command_line->CopySwitchesFrom(
*base::CommandLine::ForCurrentProcess(),
@ -281,6 +326,11 @@ bool AtomBrowserClient::CanCreateWindow(
bool* no_javascript_access) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (IsRendererSandboxed(render_process_id)) {
*no_javascript_access = false;
return true;
}
if (delegate_) {
content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE,
base::Bind(&api::App::OnCreateWindow,
@ -338,6 +388,7 @@ void AtomBrowserClient::RenderProcessHostDestroyed(
break;
}
}
RemoveSandboxedRendererId(process_id);
}
} // namespace atom

View file

@ -6,6 +6,7 @@
#define ATOM_BROWSER_ATOM_BROWSER_CLIENT_H_
#include <map>
#include <set>
#include <string>
#include <vector>
@ -108,8 +109,19 @@ class AtomBrowserClient : public brightray::BrowserClient,
void RenderProcessHostDestroyed(content::RenderProcessHost* host) override;
private:
bool ShouldCreateNewSiteInstance(content::BrowserContext* browser_context,
content::SiteInstance* current_instance,
const GURL& dest_url);
// Add/remove a process id to `sandboxed_renderers_`.
void AddSandboxedRendererId(int process_id);
void RemoveSandboxedRendererId(int process_id);
bool IsRendererSandboxed(int process_id);
// pending_render_process => current_render_process.
std::map<int, int> pending_processes_;
// Set that contains the process ids of all sandboxed renderers
std::set<int> sandboxed_renderers_;
base::Lock sandboxed_renderers_lock_;
std::unique_ptr<AtomResourceDispatcherHostDelegate>
resource_dispatcher_host_delegate_;

View file

@ -391,6 +391,10 @@ void NativeWindow::RequestToClosePage() {
if (window_unresposive_closure_.IsCancelled())
ScheduleUnresponsiveEvent(5000);
if (!web_contents())
// Already closed by renderer
return;
if (web_contents()->NeedToFireBeforeUnload())
web_contents()->DispatchBeforeUnload();
else

View file

@ -97,6 +97,12 @@ void WebContentsPreferences::AppendExtraCommandLineSwitches(
command_line->AppendSwitchASCII(switches::kNodeIntegration,
node_integration ? "true" : "false");
// If the `sandbox` option was passed to the BrowserWindow's webPreferences,
// pass `--enable-sandbox` to the renderer so it won't have any node.js
// integration.
if (IsSandboxed(web_contents))
command_line->AppendSwitch(switches::kEnableSandbox);
// The preload script.
base::FilePath::StringType preload;
if (web_preferences.GetString(options::kPreloadScript, &preload)) {
@ -194,6 +200,21 @@ void WebContentsPreferences::AppendExtraCommandLineSwitches(
command_line->AppendSwitch(cc::switches::kEnableBeginFrameScheduling);
}
bool WebContentsPreferences::IsSandboxed(content::WebContents* web_contents) {
WebContentsPreferences* self;
if (!web_contents)
return false;
self = FromWebContents(web_contents);
if (!self)
return false;
base::DictionaryValue& web_preferences = self->web_preferences_;
bool sandboxed = false;
web_preferences.GetBoolean("sandbox", &sandboxed);
return sandboxed;
}
// static
void WebContentsPreferences::OverrideWebkitPrefs(
content::WebContents* web_contents, content::WebPreferences* prefs) {

View file

@ -36,6 +36,8 @@ class WebContentsPreferences
static void AppendExtraCommandLineSwitches(
content::WebContents* web_contents, base::CommandLine* command_line);
static bool IsSandboxed(content::WebContents* web_contents);
// Modify the WebPreferences according to |web_contents|'s preferences.
static void OverrideWebkitPrefs(
content::WebContents* web_contents, content::WebPreferences* prefs);

View file

@ -104,7 +104,7 @@ void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
dict.SetMethod("setRemoteObjectFreer", &atom::RemoteObjectFreer::BindTo);
dict.SetMethod("createIDWeakMap", &atom::api::KeyWeakMap<int32_t>::Create);
dict.SetMethod("createDoubleIDWeakMap",
&atom::api::KeyWeakMap<std::pair<int32_t, int32_t>>::Create);
&atom::api::KeyWeakMap<std::pair<int64_t, int32_t>>::Create);
}
} // namespace

View file

@ -117,6 +117,9 @@ const char kDisableBlinkFeatures[] = "disableBlinkFeatures";
namespace switches {
// Enable chromium sandbox.
const char kEnableSandbox[] = "enable-sandbox";
// Enable plugins.
const char kEnablePlugins[] = "enable-plugins";

View file

@ -67,6 +67,7 @@ extern const char kDisableBlinkFeatures[];
namespace switches {
extern const char kEnableSandbox[];
extern const char kEnablePlugins[];
extern const char kPpapiFlashPath[];
extern const char kPpapiFlashVersion[];

View file

@ -2,6 +2,7 @@
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/renderer/api/atom_api_renderer_ipc.h"
#include "atom/common/api/api_messages.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
@ -15,7 +16,9 @@ using content::RenderView;
using blink::WebLocalFrame;
using blink::WebView;
namespace {
namespace atom {
namespace api {
RenderView* GetCurrentRenderView() {
WebLocalFrame* frame = WebLocalFrame::frameForCurrentContext();
@ -69,6 +72,8 @@ void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
dict.SetMethod("sendSync", &SendSync);
}
} // namespace
} // namespace api
NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_renderer_ipc, Initialize)
} // namespace atom
NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_renderer_ipc, atom::api::Initialize)

View file

@ -0,0 +1,30 @@
// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_RENDERER_API_ATOM_API_RENDERER_IPC_H_
#define ATOM_RENDERER_API_ATOM_API_RENDERER_IPC_H_
#include "base/values.h"
#include "native_mate/arguments.h"
namespace atom {
namespace api {
void Send(mate::Arguments* args,
const base::string16& channel,
const base::ListValue& arguments);
base::string16 SendSync(mate::Arguments* args,
const base::string16& channel,
const base::ListValue& arguments);
void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
v8::Local<v8::Context> context, void* priv);
} // namespace api
} // namespace atom
#endif // ATOM_RENDERER_API_ATOM_API_RENDERER_IPC_H_

View file

@ -59,9 +59,33 @@ std::vector<v8::Local<v8::Value>> ListValueToVector(
return result;
}
void EmitIPCEvent(blink::WebFrame* frame,
const base::string16& channel,
const base::ListValue& args) {
base::StringPiece NetResourceProvider(int key) {
if (key == IDR_DIR_HEADER_HTML) {
base::StringPiece html_data =
ui::ResourceBundle::GetSharedInstance().GetRawDataResource(
IDR_DIR_HEADER_HTML);
return html_data;
}
return base::StringPiece();
}
} // namespace
AtomRenderViewObserver::AtomRenderViewObserver(
content::RenderView* render_view,
AtomRendererClient* renderer_client)
: content::RenderViewObserver(render_view),
document_created_(false) {
// Initialise resource for directory listing.
net::NetModule::SetResourceProvider(NetResourceProvider);
}
AtomRenderViewObserver::~AtomRenderViewObserver() {
}
void AtomRenderViewObserver::EmitIPCEvent(blink::WebFrame* frame,
const base::string16& channel,
const base::ListValue& args) {
if (!frame || frame->isWebRemoteFrame())
return;
@ -87,30 +111,6 @@ void EmitIPCEvent(blink::WebFrame* frame,
}
}
base::StringPiece NetResourceProvider(int key) {
if (key == IDR_DIR_HEADER_HTML) {
base::StringPiece html_data =
ui::ResourceBundle::GetSharedInstance().GetRawDataResource(
IDR_DIR_HEADER_HTML);
return html_data;
}
return base::StringPiece();
}
} // namespace
AtomRenderViewObserver::AtomRenderViewObserver(
content::RenderView* render_view,
AtomRendererClient* renderer_client)
: content::RenderViewObserver(render_view),
document_created_(false) {
// Initialise resource for directory listing.
net::NetModule::SetResourceProvider(NetResourceProvider);
}
AtomRenderViewObserver::~AtomRenderViewObserver() {
}
void AtomRenderViewObserver::DidCreateDocumentElement(
blink::WebLocalFrame* frame) {
document_created_ = true;

View file

@ -7,6 +7,7 @@
#include "base/strings/string16.h"
#include "content/public/renderer/render_view_observer.h"
#include "third_party/WebKit/public/web/WebFrame.h"
namespace base {
class ListValue;
@ -24,6 +25,10 @@ class AtomRenderViewObserver : public content::RenderViewObserver {
protected:
virtual ~AtomRenderViewObserver();
virtual void EmitIPCEvent(blink::WebFrame* frame,
const base::string16& channel,
const base::ListValue& args);
private:
// content::RenderViewObserver implementation.
void DidCreateDocumentElement(blink::WebLocalFrame* frame) override;

View file

@ -0,0 +1,201 @@
// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/renderer/atom_sandboxed_renderer_client.h"
#include <string>
#include "atom_natives.h" // NOLINT: This file is generated with js2c
#include "atom/common/api/api_messages.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/options_switches.h"
#include "atom/renderer/api/atom_api_renderer_ipc.h"
#include "atom/renderer/atom_render_view_observer.h"
#include "base/command_line.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_frame_observer.h"
#include "content/public/renderer/render_view.h"
#include "content/public/renderer/render_view_observer.h"
#include "ipc/ipc_message_macros.h"
#include "third_party/WebKit/public/web/WebFrame.h"
#include "third_party/WebKit/public/web/WebKit.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#include "third_party/WebKit/public/web/WebScriptSource.h"
#include "third_party/WebKit/public/web/WebView.h"
namespace atom {
namespace {
const std::string kBindingKey = "binding";
class AtomSandboxedRenderFrameObserver : public content::RenderFrameObserver {
public:
AtomSandboxedRenderFrameObserver(content::RenderFrame* frame,
AtomSandboxedRendererClient* renderer_client)
: content::RenderFrameObserver(frame),
render_frame_(frame),
world_id_(-1),
renderer_client_(renderer_client) {}
// content::RenderFrameObserver:
void DidClearWindowObject() override {
// Make sure every page will get a script context created.
render_frame_->GetWebFrame()->executeScript(
blink::WebScriptSource("void 0"));
}
void DidCreateScriptContext(v8::Handle<v8::Context> context,
int extension_group,
int world_id) override {
if (world_id_ != -1 && world_id_ != world_id)
return;
world_id_ = world_id;
renderer_client_->DidCreateScriptContext(context, render_frame_);
}
void WillReleaseScriptContext(v8::Local<v8::Context> context,
int world_id) override {
if (world_id_ != world_id)
return;
renderer_client_->WillReleaseScriptContext(context, render_frame_);
}
void OnDestruct() override {
delete this;
}
private:
content::RenderFrame* render_frame_;
int world_id_;
AtomSandboxedRendererClient* renderer_client_;
DISALLOW_COPY_AND_ASSIGN(AtomSandboxedRenderFrameObserver);
};
class AtomSandboxedRenderViewObserver : public AtomRenderViewObserver {
public:
AtomSandboxedRenderViewObserver(content::RenderView* render_view,
AtomSandboxedRendererClient* renderer_client)
: AtomRenderViewObserver(render_view, nullptr),
renderer_client_(renderer_client) {
}
protected:
void EmitIPCEvent(blink::WebFrame* frame,
const base::string16& channel,
const base::ListValue& args) override {
if (!frame || frame->isWebRemoteFrame())
return;
auto isolate = blink::mainThreadIsolate();
v8::HandleScope handle_scope(isolate);
auto context = frame->mainWorldScriptContext();
v8::Context::Scope context_scope(context);
v8::Local<v8::Value> argv[] = {
mate::ConvertToV8(isolate, channel),
mate::ConvertToV8(isolate, args)
};
renderer_client_->InvokeBindingCallback(
context,
"onMessage",
std::vector<v8::Local<v8::Value>>(argv, argv + 2));
}
private:
AtomSandboxedRendererClient* renderer_client_;
DISALLOW_COPY_AND_ASSIGN(AtomSandboxedRenderViewObserver);
};
} // namespace
AtomSandboxedRendererClient::AtomSandboxedRendererClient() {
}
AtomSandboxedRendererClient::~AtomSandboxedRendererClient() {
}
void AtomSandboxedRendererClient::RenderFrameCreated(
content::RenderFrame* render_frame) {
new AtomSandboxedRenderFrameObserver(render_frame, this);
}
void AtomSandboxedRendererClient::RenderViewCreated(
content::RenderView* render_view) {
new AtomSandboxedRenderViewObserver(render_view, this);
}
void AtomSandboxedRendererClient::DidCreateScriptContext(
v8::Handle<v8::Context> context, content::RenderFrame* render_frame) {
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
std::string preload_script = command_line->GetSwitchValueASCII(
switches::kPreloadScript);
if (preload_script.empty())
return;
auto isolate = context->GetIsolate();
v8::HandleScope handle_scope(isolate);
v8::Context::Scope context_scope(context);
// Wrap the bundle into a function that receives the binding object and the
// preload script path as arguments.
std::string preload_bundle_native(node::preload_bundle_native,
node::preload_bundle_native + sizeof(node::preload_bundle_native));
std::stringstream ss;
ss << "(function(binding, preloadPath) {\n";
ss << preload_bundle_native << "\n";
ss << "})";
std::string preload_wrapper = ss.str();
// Compile the wrapper and run it to get the function object
auto script = v8::Script::Compile(
mate::ConvertToV8(isolate, preload_wrapper)->ToString());
auto func = v8::Handle<v8::Function>::Cast(
script->Run(context).ToLocalChecked());
// Create and initialize the binding object
auto binding = v8::Object::New(isolate);
api::Initialize(binding, v8::Null(isolate), context, nullptr);
v8::Local<v8::Value> args[] = {
binding,
mate::ConvertToV8(isolate, preload_script)
};
// Execute the function with proper arguments
ignore_result(func->Call(context, v8::Null(isolate), 2, args));
// Store the bindingt privately for handling messages from the main process.
auto binding_key = mate::ConvertToV8(isolate, kBindingKey)->ToString();
auto private_binding_key = v8::Private::ForApi(isolate, binding_key);
context->Global()->SetPrivate(context, private_binding_key, binding);
}
void AtomSandboxedRendererClient::WillReleaseScriptContext(
v8::Handle<v8::Context> context, content::RenderFrame* render_frame) {
auto isolate = context->GetIsolate();
v8::HandleScope handle_scope(isolate);
v8::Context::Scope context_scope(context);
InvokeBindingCallback(context, "onExit", std::vector<v8::Local<v8::Value>>());
}
void AtomSandboxedRendererClient::InvokeBindingCallback(
v8::Handle<v8::Context> context,
std::string callback_name,
std::vector<v8::Handle<v8::Value>> args) {
auto isolate = context->GetIsolate();
auto binding_key = mate::ConvertToV8(isolate, kBindingKey)->ToString();
auto private_binding_key = v8::Private::ForApi(isolate, binding_key);
auto global_object = context->Global();
v8::Local<v8::Value> value;
if (!global_object->GetPrivate(context, private_binding_key).ToLocal(&value))
return;
if (value.IsEmpty() || !value->IsObject())
return;
auto binding = value->ToObject();
auto callback_key = mate::ConvertToV8(isolate, callback_name)->ToString();
auto callback_value = binding->Get(callback_key);
DCHECK(callback_value->IsFunction()); // set by sandboxed_renderer/init.js
auto callback = v8::Handle<v8::Function>::Cast(callback_value);
ignore_result(callback->Call(context, binding, args.size(), &args[0]));
}
} // namespace atom

View file

@ -0,0 +1,37 @@
// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_RENDERER_ATOM_SANDBOXED_RENDERER_CLIENT_H_
#define ATOM_RENDERER_ATOM_SANDBOXED_RENDERER_CLIENT_H_
#include <string>
#include <vector>
#include "content/public/renderer/content_renderer_client.h"
#include "content/public/renderer/render_frame.h"
namespace atom {
class AtomSandboxedRendererClient : public content::ContentRendererClient {
public:
AtomSandboxedRendererClient();
virtual ~AtomSandboxedRendererClient();
void DidCreateScriptContext(
v8::Handle<v8::Context> context, content::RenderFrame* render_frame);
void WillReleaseScriptContext(
v8::Handle<v8::Context> context, content::RenderFrame* render_frame);
void InvokeBindingCallback(v8::Handle<v8::Context> context,
std::string callback_name,
std::vector<v8::Handle<v8::Value>> args);
// content::ContentRendererClient:
void RenderFrameCreated(content::RenderFrame*) override;
void RenderViewCreated(content::RenderView*) override;
private:
DISALLOW_COPY_AND_ASSIGN(AtomSandboxedRendererClient);
};
} // namespace atom
#endif // ATOM_RENDERER_ATOM_SANDBOXED_RENDERER_CLIENT_H_