Compute can_use_lcd_text using property trees.
[chromium-blink-merge.git] / extensions / renderer / script_context.cc
blob32222b0ca065128032dc5142f1401c19ba208368
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "extensions/renderer/script_context.h"
7 #include "base/logging.h"
8 #include "base/memory/scoped_ptr.h"
9 #include "base/strings/string_split.h"
10 #include "base/strings/string_util.h"
11 #include "base/strings/stringprintf.h"
12 #include "base/values.h"
13 #include "content/public/child/v8_value_converter.h"
14 #include "content/public/common/url_constants.h"
15 #include "content/public/renderer/render_frame.h"
16 #include "content/public/renderer/render_view.h"
17 #include "extensions/common/constants.h"
18 #include "extensions/common/extension.h"
19 #include "extensions/common/extension_api.h"
20 #include "extensions/common/extension_set.h"
21 #include "extensions/common/extension_urls.h"
22 #include "extensions/common/features/base_feature_provider.h"
23 #include "extensions/common/manifest_handlers/sandboxed_page_info.h"
24 #include "extensions/common/permissions/permissions_data.h"
25 #include "gin/per_context_data.h"
26 #include "third_party/WebKit/public/web/WebDataSource.h"
27 #include "third_party/WebKit/public/web/WebDocument.h"
28 #include "third_party/WebKit/public/web/WebFrame.h"
29 #include "third_party/WebKit/public/web/WebLocalFrame.h"
30 #include "third_party/WebKit/public/web/WebScopedMicrotaskSuppression.h"
31 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
32 #include "third_party/WebKit/public/web/WebView.h"
33 #include "v8/include/v8.h"
35 using content::V8ValueConverter;
37 namespace extensions {
39 namespace {
41 std::string GetContextTypeDescriptionString(Feature::Context context_type) {
42 switch (context_type) {
43 case Feature::UNSPECIFIED_CONTEXT:
44 return "UNSPECIFIED";
45 case Feature::BLESSED_EXTENSION_CONTEXT:
46 return "BLESSED_EXTENSION";
47 case Feature::UNBLESSED_EXTENSION_CONTEXT:
48 return "UNBLESSED_EXTENSION";
49 case Feature::CONTENT_SCRIPT_CONTEXT:
50 return "CONTENT_SCRIPT";
51 case Feature::WEB_PAGE_CONTEXT:
52 return "WEB_PAGE";
53 case Feature::BLESSED_WEB_PAGE_CONTEXT:
54 return "BLESSED_WEB_PAGE";
55 case Feature::WEBUI_CONTEXT:
56 return "WEBUI";
58 NOTREACHED();
59 return std::string();
62 } // namespace
64 // A gin::Runner that delegates to its ScriptContext.
65 class ScriptContext::Runner : public gin::Runner {
66 public:
67 explicit Runner(ScriptContext* context);
69 // gin::Runner overrides.
70 void Run(const std::string& source,
71 const std::string& resource_name) override;
72 v8::Local<v8::Value> Call(v8::Local<v8::Function> function,
73 v8::Local<v8::Value> receiver,
74 int argc,
75 v8::Local<v8::Value> argv[]) override;
76 gin::ContextHolder* GetContextHolder() override;
78 private:
79 ScriptContext* context_;
82 ScriptContext::ScriptContext(const v8::Local<v8::Context>& v8_context,
83 blink::WebLocalFrame* web_frame,
84 const Extension* extension,
85 Feature::Context context_type,
86 const Extension* effective_extension,
87 Feature::Context effective_context_type)
88 : is_valid_(true),
89 v8_context_(v8_context->GetIsolate(), v8_context),
90 web_frame_(web_frame),
91 extension_(extension),
92 context_type_(context_type),
93 effective_extension_(effective_extension),
94 effective_context_type_(effective_context_type),
95 safe_builtins_(this),
96 isolate_(v8_context->GetIsolate()),
97 url_(web_frame_ ? GetDataSourceURLForFrame(web_frame_) : GURL()),
98 runner_(new Runner(this)) {
99 VLOG(1) << "Created context:\n" << GetDebugString();
100 gin::PerContextData* gin_data = gin::PerContextData::From(v8_context);
101 CHECK(gin_data); // may fail if the v8::Context hasn't been registered yet
102 gin_data->set_runner(runner_.get());
105 ScriptContext::~ScriptContext() {
106 VLOG(1) << "Destroyed context for extension\n"
107 << " extension id: " << GetExtensionID() << "\n"
108 << " effective extension id: "
109 << (effective_extension_.get() ? effective_extension_->id() : "");
110 CHECK(!is_valid_) << "ScriptContexts must be invalidated before destruction";
113 // static
114 bool ScriptContext::IsSandboxedPage(const ExtensionSet& extensions,
115 const GURL& url) {
116 // TODO(kalman): This is checking the wrong thing. See comment in
117 // HasAccessOrThrowError.
118 if (url.SchemeIs(kExtensionScheme)) {
119 const Extension* extension = extensions.GetByID(url.host());
120 if (extension) {
121 return SandboxedPageInfo::IsSandboxedPage(extension, url.path());
124 return false;
127 void ScriptContext::Invalidate() {
128 CHECK(is_valid_);
129 is_valid_ = false;
131 // TODO(kalman): Make ModuleSystem use AddInvalidationObserver.
132 // Ownership graph is a bit weird here.
133 if (module_system_)
134 module_system_->Invalidate();
136 // Swap |invalidate_observers_| to a local variable to clear it, and to make
137 // sure it's not mutated as we iterate.
138 std::vector<base::Closure> observers;
139 observers.swap(invalidate_observers_);
140 for (const base::Closure& observer : observers) {
141 observer.Run();
143 DCHECK(invalidate_observers_.empty())
144 << "Invalidation observers cannot be added during invalidation";
146 runner_.reset();
147 v8_context_.Reset();
150 void ScriptContext::AddInvalidationObserver(const base::Closure& observer) {
151 invalidate_observers_.push_back(observer);
154 const std::string& ScriptContext::GetExtensionID() const {
155 return extension_.get() ? extension_->id() : base::EmptyString();
158 content::RenderView* ScriptContext::GetRenderView() const {
159 if (web_frame_ && web_frame_->view())
160 return content::RenderView::FromWebView(web_frame_->view());
161 return NULL;
164 content::RenderFrame* ScriptContext::GetRenderFrame() const {
165 if (web_frame_)
166 return content::RenderFrame::FromWebFrame(web_frame_);
167 return NULL;
170 v8::Local<v8::Value> ScriptContext::CallFunction(
171 const v8::Local<v8::Function>& function,
172 int argc,
173 v8::Local<v8::Value> argv[]) const {
174 v8::EscapableHandleScope handle_scope(isolate());
175 v8::Context::Scope scope(v8_context());
177 blink::WebScopedMicrotaskSuppression suppression;
178 if (!is_valid_) {
179 return handle_scope.Escape(
180 v8::Local<v8::Primitive>(v8::Undefined(isolate())));
183 v8::Local<v8::Object> global = v8_context()->Global();
184 if (!web_frame_)
185 return handle_scope.Escape(function->Call(global, argc, argv));
186 return handle_scope.Escape(
187 v8::Local<v8::Value>(web_frame_->callFunctionEvenIfScriptDisabled(
188 function, global, argc, argv)));
191 v8::Local<v8::Value> ScriptContext::CallFunction(
192 const v8::Local<v8::Function>& function) const {
193 return CallFunction(function, 0, nullptr);
196 Feature::Availability ScriptContext::GetAvailability(
197 const std::string& api_name) {
198 // Hack: Hosted apps should have the availability of messaging APIs based on
199 // the URL of the page (which might have access depending on some extension
200 // with externally_connectable), not whether the app has access to messaging
201 // (which it won't).
202 const Extension* extension = extension_.get();
203 if (extension && extension->is_hosted_app() &&
204 (api_name == "runtime.connect" || api_name == "runtime.sendMessage")) {
205 extension = NULL;
207 return ExtensionAPI::GetSharedInstance()->IsAvailable(
208 api_name, extension, context_type_, GetURL());
211 void ScriptContext::DispatchEvent(const char* event_name,
212 v8::Local<v8::Array> args) const {
213 v8::HandleScope handle_scope(isolate());
214 v8::Context::Scope context_scope(v8_context());
216 v8::Local<v8::Value> argv[] = {v8::String::NewFromUtf8(isolate(), event_name),
217 args};
218 module_system_->CallModuleMethod(
219 kEventBindings, "dispatchEvent", arraysize(argv), argv);
222 void ScriptContext::DispatchOnUnloadEvent() {
223 v8::HandleScope handle_scope(isolate());
224 v8::Context::Scope context_scope(v8_context());
225 module_system_->CallModuleMethod("unload_event", "dispatch");
228 std::string ScriptContext::GetContextTypeDescription() const {
229 return GetContextTypeDescriptionString(context_type_);
232 std::string ScriptContext::GetEffectiveContextTypeDescription() const {
233 return GetContextTypeDescriptionString(effective_context_type_);
236 GURL ScriptContext::GetURL() const {
237 return url_;
240 bool ScriptContext::IsAnyFeatureAvailableToContext(const Feature& api) {
241 return ExtensionAPI::GetSharedInstance()->IsAnyFeatureAvailableToContext(
242 api, extension(), context_type(), GetDataSourceURLForFrame(web_frame()));
245 // static
246 GURL ScriptContext::GetDataSourceURLForFrame(const blink::WebFrame* frame) {
247 // Normally we would use frame->document().url() to determine the document's
248 // URL, but to decide whether to inject a content script, we use the URL from
249 // the data source. This "quirk" helps prevents content scripts from
250 // inadvertently adding DOM elements to the compose iframe in Gmail because
251 // the compose iframe's dataSource URL is about:blank, but the document URL
252 // changes to match the parent document after Gmail document.writes into
253 // it to create the editor.
254 // http://code.google.com/p/chromium/issues/detail?id=86742
255 blink::WebDataSource* data_source = frame->provisionalDataSource()
256 ? frame->provisionalDataSource()
257 : frame->dataSource();
258 return data_source ? GURL(data_source->request().url()) : GURL();
261 // static
262 GURL ScriptContext::GetEffectiveDocumentURL(const blink::WebFrame* frame,
263 const GURL& document_url,
264 bool match_about_blank) {
265 // Common scenario. If |match_about_blank| is false (as is the case in most
266 // extensions), or if the frame is not an about:-page, just return
267 // |document_url| (supposedly the URL of the frame).
268 if (!match_about_blank || !document_url.SchemeIs(url::kAboutScheme))
269 return document_url;
271 // Non-sandboxed about:blank and about:srcdoc pages inherit their security
272 // origin from their parent frame/window. So, traverse the frame/window
273 // hierarchy to find the closest non-about:-page and return its URL.
274 const blink::WebFrame* parent = frame;
275 do {
276 parent = parent->parent() ? parent->parent() : parent->opener();
277 } while (parent != NULL && !parent->document().isNull() &&
278 GURL(parent->document().url()).SchemeIs(url::kAboutScheme));
280 if (parent && !parent->document().isNull()) {
281 // Only return the parent URL if the frame can access it.
282 const blink::WebDocument& parent_document = parent->document();
283 if (frame->document().securityOrigin().canAccess(
284 parent_document.securityOrigin()))
285 return parent_document.url();
287 return document_url;
290 ScriptContext* ScriptContext::GetContext() { return this; }
292 void ScriptContext::OnResponseReceived(const std::string& name,
293 int request_id,
294 bool success,
295 const base::ListValue& response,
296 const std::string& error) {
297 v8::HandleScope handle_scope(isolate());
299 scoped_ptr<V8ValueConverter> converter(V8ValueConverter::create());
300 v8::Local<v8::Value> argv[] = {
301 v8::Integer::New(isolate(), request_id),
302 v8::String::NewFromUtf8(isolate(), name.c_str()),
303 v8::Boolean::New(isolate(), success),
304 converter->ToV8Value(&response,
305 v8::Local<v8::Context>::New(isolate(), v8_context_)),
306 v8::String::NewFromUtf8(isolate(), error.c_str())};
308 v8::Local<v8::Value> retval = module_system()->CallModuleMethod(
309 "sendRequest", "handleResponse", arraysize(argv), argv);
311 // In debug, the js will validate the callback parameters and return a
312 // string if a validation error has occured.
313 DCHECK(retval.IsEmpty() || retval->IsUndefined())
314 << *v8::String::Utf8Value(retval);
317 void ScriptContext::SetContentCapabilities(
318 const APIPermissionSet& permissions) {
319 content_capabilities_ = permissions;
322 bool ScriptContext::HasAPIPermission(APIPermission::ID permission) const {
323 if (effective_extension_.get()) {
324 return effective_extension_->permissions_data()->HasAPIPermission(
325 permission);
326 } else if (context_type() == Feature::WEB_PAGE_CONTEXT) {
327 // Only web page contexts may be granted content capabilities. Other
328 // contexts are either privileged WebUI or extensions with their own set of
329 // permissions.
330 if (content_capabilities_.find(permission) != content_capabilities_.end())
331 return true;
333 return false;
336 bool ScriptContext::HasAccessOrThrowError(const std::string& name) {
337 // Theoretically[1] we could end up with bindings being injected into
338 // sandboxed frames, for example content scripts. Don't let them execute API
339 // functions.
341 // In any case, this check is silly. The frame's document's security origin
342 // already tells us if it's sandboxed. The only problem is that until
343 // crbug.com/466373 is fixed, we don't know the security origin up-front and
344 // may not know it here, either.
346 // [1] citation needed. This ScriptContext should already be in a state that
347 // doesn't allow this, from ScriptContextSet::ClassifyJavaScriptContext.
348 if (extension() &&
349 SandboxedPageInfo::IsSandboxedPage(extension(), url_.path())) {
350 static const char kMessage[] =
351 "%s cannot be used within a sandboxed frame.";
352 std::string error_msg = base::StringPrintf(kMessage, name.c_str());
353 isolate()->ThrowException(v8::Exception::Error(
354 v8::String::NewFromUtf8(isolate(), error_msg.c_str())));
355 return false;
358 Feature::Availability availability = GetAvailability(name);
359 if (!availability.is_available()) {
360 isolate()->ThrowException(v8::Exception::Error(
361 v8::String::NewFromUtf8(isolate(), availability.message().c_str())));
362 return false;
365 return true;
368 std::string ScriptContext::GetDebugString() const {
369 return base::StringPrintf(
370 " extension id: %s\n"
371 " frame: %p\n"
372 " URL: %s\n"
373 " context_type: %s\n"
374 " effective extension id: %s\n"
375 " effective context type: %s",
376 extension_.get() ? extension_->id().c_str() : "(none)", web_frame_,
377 GetURL().spec().c_str(), GetContextTypeDescription().c_str(),
378 effective_extension_.get() ? effective_extension_->id().c_str()
379 : "(none)",
380 GetEffectiveContextTypeDescription().c_str());
383 ScriptContext::Runner::Runner(ScriptContext* context) : context_(context) {
386 void ScriptContext::Runner::Run(const std::string& source,
387 const std::string& resource_name) {
388 context_->module_system()->RunString(source, resource_name);
391 v8::Local<v8::Value> ScriptContext::Runner::Call(
392 v8::Local<v8::Function> function,
393 v8::Local<v8::Value> receiver,
394 int argc,
395 v8::Local<v8::Value> argv[]) {
396 return context_->CallFunction(function, argc, argv);
399 gin::ContextHolder* ScriptContext::Runner::GetContextHolder() {
400 v8::HandleScope handle_scope(context_->isolate());
401 return gin::PerContextData::From(context_->v8_context())->context_holder();
404 } // namespace extensions