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/dispatcher.h"
8 #include "base/callback.h"
9 #include "base/command_line.h"
10 #include "base/debug/alias.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/metrics/histogram_macros.h"
13 #include "base/metrics/user_metrics_action.h"
14 #include "base/strings/string_piece.h"
15 #include "base/strings/string_split.h"
16 #include "base/strings/string_util.h"
17 #include "base/time/time.h"
18 #include "base/values.h"
19 #include "content/grit/content_resources.h"
20 #include "content/public/child/v8_value_converter.h"
21 #include "content/public/common/content_switches.h"
22 #include "content/public/common/url_constants.h"
23 #include "content/public/renderer/render_thread.h"
24 #include "content/public/renderer/render_view.h"
25 #include "extensions/common/api/messaging/message.h"
26 #include "extensions/common/constants.h"
27 #include "extensions/common/extension.h"
28 #include "extensions/common/extension_api.h"
29 #include "extensions/common/extension_messages.h"
30 #include "extensions/common/extension_urls.h"
31 #include "extensions/common/feature_switch.h"
32 #include "extensions/common/features/feature.h"
33 #include "extensions/common/features/feature_provider.h"
34 #include "extensions/common/manifest.h"
35 #include "extensions/common/manifest_constants.h"
36 #include "extensions/common/manifest_handlers/background_info.h"
37 #include "extensions/common/manifest_handlers/content_capabilities_handler.h"
38 #include "extensions/common/manifest_handlers/externally_connectable.h"
39 #include "extensions/common/manifest_handlers/options_page_info.h"
40 #include "extensions/common/manifest_handlers/sandboxed_page_info.h"
41 #include "extensions/common/message_bundle.h"
42 #include "extensions/common/permissions/permission_set.h"
43 #include "extensions/common/permissions/permissions_data.h"
44 #include "extensions/common/switches.h"
45 #include "extensions/common/view_type.h"
46 #include "extensions/renderer/api_activity_logger.h"
47 #include "extensions/renderer/api_definitions_natives.h"
48 #include "extensions/renderer/app_runtime_custom_bindings.h"
49 #include "extensions/renderer/app_window_custom_bindings.h"
50 #include "extensions/renderer/binding_generating_native_handler.h"
51 #include "extensions/renderer/blob_native_handler.h"
52 #include "extensions/renderer/content_watcher.h"
53 #include "extensions/renderer/context_menus_custom_bindings.h"
54 #include "extensions/renderer/css_native_handler.h"
55 #include "extensions/renderer/dispatcher_delegate.h"
56 #include "extensions/renderer/document_custom_bindings.h"
57 #include "extensions/renderer/dom_activity_logger.h"
58 #include "extensions/renderer/event_bindings.h"
59 #include "extensions/renderer/extension_groups.h"
60 #include "extensions/renderer/extension_helper.h"
61 #include "extensions/renderer/extensions_renderer_client.h"
62 #include "extensions/renderer/file_system_natives.h"
63 #include "extensions/renderer/guest_view/guest_view_internal_custom_bindings.h"
64 #include "extensions/renderer/i18n_custom_bindings.h"
65 #include "extensions/renderer/id_generator_custom_bindings.h"
66 #include "extensions/renderer/lazy_background_page_native_handler.h"
67 #include "extensions/renderer/logging_native_handler.h"
68 #include "extensions/renderer/messaging_bindings.h"
69 #include "extensions/renderer/module_system.h"
70 #include "extensions/renderer/print_native_handler.h"
71 #include "extensions/renderer/process_info_native_handler.h"
72 #include "extensions/renderer/render_view_observer_natives.h"
73 #include "extensions/renderer/request_sender.h"
74 #include "extensions/renderer/runtime_custom_bindings.h"
75 #include "extensions/renderer/safe_builtins.h"
76 #include "extensions/renderer/script_context.h"
77 #include "extensions/renderer/script_context_set.h"
78 #include "extensions/renderer/script_injection.h"
79 #include "extensions/renderer/script_injection_manager.h"
80 #include "extensions/renderer/send_request_natives.h"
81 #include "extensions/renderer/set_icon_natives.h"
82 #include "extensions/renderer/tab_finder.h"
83 #include "extensions/renderer/test_features_native_handler.h"
84 #include "extensions/renderer/user_gestures_native_handler.h"
85 #include "extensions/renderer/utils_native_handler.h"
86 #include "extensions/renderer/v8_context_native_handler.h"
87 #include "grit/extensions_renderer_resources.h"
88 #include "third_party/WebKit/public/platform/WebString.h"
89 #include "third_party/WebKit/public/platform/WebURLRequest.h"
90 #include "third_party/WebKit/public/web/WebCustomElement.h"
91 #include "third_party/WebKit/public/web/WebDataSource.h"
92 #include "third_party/WebKit/public/web/WebDocument.h"
93 #include "third_party/WebKit/public/web/WebFrame.h"
94 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
95 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
96 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
97 #include "third_party/WebKit/public/web/WebView.h"
98 #include "third_party/mojo/src/mojo/public/js/constants.h"
99 #include "ui/base/layout.h"
100 #include "ui/base/resource/resource_bundle.h"
101 #include "v8/include/v8.h"
103 using base::UserMetricsAction
;
104 using blink::WebDataSource
;
105 using blink::WebDocument
;
106 using blink::WebFrame
;
107 using blink::WebScopedUserGesture
;
108 using blink::WebSecurityPolicy
;
109 using blink::WebString
;
110 using blink::WebVector
;
111 using blink::WebView
;
112 using content::RenderThread
;
113 using content::RenderView
;
115 namespace extensions
{
119 static const int64 kInitialExtensionIdleHandlerDelayMs
= 5 * 1000;
120 static const int64 kMaxExtensionIdleHandlerDelayMs
= 5 * 60 * 1000;
121 static const char kEventDispatchFunction
[] = "dispatchEvent";
122 static const char kOnSuspendEvent
[] = "runtime.onSuspend";
123 static const char kOnSuspendCanceledEvent
[] = "runtime.onSuspendCanceled";
125 // Returns the global value for "chrome" from |context|. If one doesn't exist
126 // creates a new object for it.
128 // Note that this isn't necessarily an object, since webpages can write, for
129 // example, "window.chrome = true".
130 v8::Handle
<v8::Value
> GetOrCreateChrome(ScriptContext
* context
) {
131 v8::Handle
<v8::String
> chrome_string(
132 v8::String::NewFromUtf8(context
->isolate(), "chrome"));
133 v8::Handle
<v8::Object
> global(context
->v8_context()->Global());
134 v8::Handle
<v8::Value
> chrome(global
->Get(chrome_string
));
135 if (chrome
->IsUndefined()) {
136 chrome
= v8::Object::New(context
->isolate());
137 global
->Set(chrome_string
, chrome
);
142 // Returns |value| cast to an object if possible, else an empty handle.
143 v8::Handle
<v8::Object
> AsObjectOrEmpty(v8::Handle
<v8::Value
> value
) {
144 return value
->IsObject() ? value
.As
<v8::Object
>() : v8::Handle
<v8::Object
>();
147 // Calls a method |method_name| in a module |module_name| belonging to the
148 // module system from |context|. Intended as a callback target from
149 // ScriptContextSet::ForEach.
150 void CallModuleMethod(const std::string
& module_name
,
151 const std::string
& method_name
,
152 const base::ListValue
* args
,
153 ScriptContext
* context
) {
154 v8::HandleScope
handle_scope(context
->isolate());
155 v8::Context::Scope
context_scope(context
->v8_context());
157 scoped_ptr
<content::V8ValueConverter
> converter(
158 content::V8ValueConverter::create());
160 std::vector
<v8::Handle
<v8::Value
> > arguments
;
161 for (base::ListValue::const_iterator it
= args
->begin(); it
!= args
->end();
163 arguments
.push_back(converter
->ToV8Value(*it
, context
->v8_context()));
166 context
->module_system()->CallModuleMethod(
167 module_name
, method_name
, &arguments
);
170 // This handles the "chrome." root API object in script contexts.
171 class ChromeNativeHandler
: public ObjectBackedNativeHandler
{
173 explicit ChromeNativeHandler(ScriptContext
* context
)
174 : ObjectBackedNativeHandler(context
) {
177 base::Bind(&ChromeNativeHandler::GetChrome
, base::Unretained(this)));
180 void GetChrome(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
181 args
.GetReturnValue().Set(GetOrCreateChrome(context()));
187 Dispatcher::Dispatcher(DispatcherDelegate
* delegate
)
188 : delegate_(delegate
),
189 content_watcher_(new ContentWatcher()),
190 source_map_(&ResourceBundle::GetSharedInstance()),
191 v8_schema_registry_(new V8SchemaRegistry
),
192 is_webkit_initialized_(false),
193 user_script_set_manager_observer_(this),
194 webrequest_used_(false) {
195 const base::CommandLine
& command_line
=
196 *(base::CommandLine::ForCurrentProcess());
197 is_extension_process_
=
198 command_line
.HasSwitch(switches::kExtensionProcess
) ||
199 command_line
.HasSwitch(::switches::kSingleProcess
);
201 if (is_extension_process_
) {
202 RenderThread::Get()->SetIdleNotificationDelayInMs(
203 kInitialExtensionIdleHandlerDelayMs
);
206 RenderThread::Get()->RegisterExtension(SafeBuiltins::CreateV8Extension());
208 user_script_set_manager_
.reset(new UserScriptSetManager(&extensions_
));
209 script_injection_manager_
.reset(
210 new ScriptInjectionManager(&extensions_
, user_script_set_manager_
.get()));
211 user_script_set_manager_observer_
.Add(user_script_set_manager_
.get());
212 request_sender_
.reset(new RequestSender(this));
216 Dispatcher::~Dispatcher() {
219 void Dispatcher::OnRenderViewCreated(content::RenderView
* render_view
) {
220 script_injection_manager_
->OnRenderViewCreated(render_view
);
223 bool Dispatcher::IsExtensionActive(const std::string
& extension_id
) const {
225 active_extension_ids_
.find(extension_id
) != active_extension_ids_
.end();
227 CHECK(extensions_
.Contains(extension_id
));
231 const Extension
* Dispatcher::GetExtensionFromFrameAndWorld(
232 const WebFrame
* frame
,
234 bool use_effective_url
) {
235 std::string extension_id
;
237 // Isolated worlds (content script).
238 extension_id
= ScriptInjection::GetHostIdForIsolatedWorld(world_id
);
239 } else if (!frame
->document().securityOrigin().isUnique()) {
240 // TODO(kalman): Delete the above check.
242 // Extension pages (chrome-extension:// URLs).
243 GURL frame_url
= ScriptContext::GetDataSourceURLForFrame(frame
);
244 frame_url
= ScriptContext::GetEffectiveDocumentURL(
245 frame
, frame_url
, use_effective_url
);
246 extension_id
= extensions_
.GetExtensionOrAppIDByURL(frame_url
);
249 const Extension
* extension
= extensions_
.GetByID(extension_id
);
250 if (!extension
&& !extension_id
.empty()) {
251 // There are conditions where despite a context being associated with an
252 // extension, no extension actually gets found. Ignore "invalid" because
253 // CSP blocks extension page loading by switching the extension ID to
254 // "invalid". This isn't interesting.
255 if (extension_id
!= "invalid") {
256 LOG(ERROR
) << "Extension \"" << extension_id
<< "\" not found";
257 RenderThread::Get()->RecordAction(
258 UserMetricsAction("ExtensionNotFound_ED"));
264 void Dispatcher::DidCreateScriptContext(
266 const v8::Handle
<v8::Context
>& v8_context
,
269 const base::TimeTicks start_time
= base::TimeTicks::Now();
271 const Extension
* extension
=
272 GetExtensionFromFrameAndWorld(frame
, world_id
, false);
273 const Extension
* effective_extension
=
274 GetExtensionFromFrameAndWorld(frame
, world_id
, true);
276 GURL frame_url
= ScriptContext::GetDataSourceURLForFrame(frame
);
277 Feature::Context context_type
=
278 ClassifyJavaScriptContext(extension
,
281 frame
->document().securityOrigin());
282 Feature::Context effective_context_type
= ClassifyJavaScriptContext(
285 ScriptContext::GetEffectiveDocumentURL(frame
, frame_url
, true),
286 frame
->document().securityOrigin());
288 ScriptContext
* context
=
289 delegate_
->CreateScriptContext(v8_context
,
294 effective_context_type
).release();
295 script_context_set_
.Add(context
);
297 // Initialize origin permissions for content scripts, which can't be
298 // initialized in |OnActivateExtension|.
299 if (context_type
== Feature::CONTENT_SCRIPT_CONTEXT
)
300 InitOriginPermissions(extension
);
303 scoped_ptr
<ModuleSystem
> module_system(
304 new ModuleSystem(context
, &source_map_
));
305 context
->set_module_system(module_system
.Pass());
307 ModuleSystem
* module_system
= context
->module_system();
309 // Enable natives in startup.
310 ModuleSystem::NativesEnabledScope
natives_enabled_scope(module_system
);
312 RegisterNativeHandlers(module_system
, context
);
314 // chrome.Event is part of the public API (although undocumented). Make it
315 // lazily evalulate to Event from event_bindings.js. For extensions only
316 // though, not all webpages!
317 if (context
->extension()) {
318 v8::Handle
<v8::Object
> chrome
= AsObjectOrEmpty(GetOrCreateChrome(context
));
319 if (!chrome
.IsEmpty())
320 module_system
->SetLazyField(chrome
, "Event", kEventBindings
, "Event");
323 UpdateBindingsForContext(context
);
325 bool is_within_platform_app
= IsWithinPlatformApp();
326 // Inject custom JS into the platform app context.
327 if (is_within_platform_app
) {
328 module_system
->Require("platformApp");
331 if (context
->GetAvailability("appViewEmbedderInternal").is_available()) {
332 module_system
->Require("appView");
333 } else if (context_type
== Feature::BLESSED_EXTENSION_CONTEXT
) {
334 module_system
->Require("denyAppView");
337 if (extensions::FeatureSwitch::surface_worker()->IsEnabled() &&
338 context
->GetAvailability("surfaceWorkerInternal").is_available()) {
339 module_system
->Require("surfaceWorker");
342 if (context
->GetAvailability("extensionViewInternal").is_available()) {
343 module_system
->Require("extensionView");
344 module_system
->Require("extensionViewApiMethods");
345 module_system
->Require("extensionViewAttributes");
348 // Note: setting up the WebView class here, not the chrome.webview API.
349 // The API will be automatically set up when first used.
350 if (context
->GetAvailability("webViewInternal").is_available()) {
351 module_system
->Require("webView");
352 module_system
->Require("webViewApiMethods");
353 module_system
->Require("webViewAttributes");
354 if (context
->GetAvailability("webViewExperimentalInternal")
356 module_system
->Require("webViewExperimental");
358 } else if (context_type
== Feature::BLESSED_EXTENSION_CONTEXT
) {
359 module_system
->Require("denyWebView");
362 delegate_
->RequireAdditionalModules(context
, is_within_platform_app
);
364 const base::TimeDelta elapsed
= base::TimeTicks::Now() - start_time
;
365 switch (context_type
) {
366 case Feature::UNSPECIFIED_CONTEXT
:
367 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Unspecified",
370 case Feature::BLESSED_EXTENSION_CONTEXT
:
371 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Blessed", elapsed
);
373 case Feature::UNBLESSED_EXTENSION_CONTEXT
:
374 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Unblessed",
377 case Feature::CONTENT_SCRIPT_CONTEXT
:
378 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_ContentScript",
381 case Feature::WEB_PAGE_CONTEXT
:
382 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_WebPage", elapsed
);
384 case Feature::BLESSED_WEB_PAGE_CONTEXT
:
385 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_BlessedWebPage",
388 case Feature::WEBUI_CONTEXT
:
389 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_WebUI", elapsed
);
393 VLOG(1) << "Num tracked contexts: " << script_context_set_
.size();
396 void Dispatcher::WillReleaseScriptContext(
398 const v8::Handle
<v8::Context
>& v8_context
,
400 ScriptContext
* context
= script_context_set_
.GetByV8Context(v8_context
);
404 context
->DispatchOnUnloadEvent();
405 // TODO(kalman): add an invalidation observer interface to ScriptContext.
406 request_sender_
->InvalidateSource(context
);
408 script_context_set_
.Remove(context
);
409 VLOG(1) << "Num tracked contexts: " << script_context_set_
.size();
412 void Dispatcher::DidCreateDocumentElement(blink::WebFrame
* frame
) {
413 // Note: use GetEffectiveDocumentURL not just frame->document()->url()
414 // so that this also injects the stylesheet on about:blank frames that
415 // are hosted in the extension process.
416 GURL effective_document_url
= ScriptContext::GetEffectiveDocumentURL(
417 frame
, frame
->document().url(), true /* match_about_blank */);
419 const Extension
* extension
=
420 extensions_
.GetExtensionOrAppByURL(effective_document_url
);
423 (extension
->is_extension() || extension
->is_platform_app())) {
424 int resource_id
= extension
->is_platform_app() ? IDR_PLATFORM_APP_CSS
425 : IDR_EXTENSION_FONTS_CSS
;
426 std::string stylesheet
= ResourceBundle::GetSharedInstance()
427 .GetRawDataResource(resource_id
)
429 ReplaceFirstSubstringAfterOffset(
430 &stylesheet
, 0, "$FONTFAMILY", system_font_family_
);
431 ReplaceFirstSubstringAfterOffset(
432 &stylesheet
, 0, "$FONTSIZE", system_font_size_
);
434 // Blink doesn't let us define an additional user agent stylesheet, so
435 // we insert the default platform app or extension stylesheet into all
436 // documents that are loaded in each app or extension.
437 frame
->document().insertStyleSheet(WebString::fromUTF8(stylesheet
));
440 // If this is an extension options page, and the extension has opted into
441 // using Chrome styles, then insert the Chrome extension stylesheet.
442 if (extension
&& extension
->is_extension() &&
443 OptionsPageInfo::ShouldUseChromeStyle(extension
) &&
444 effective_document_url
== OptionsPageInfo::GetOptionsPage(extension
)) {
445 frame
->document().insertStyleSheet(
446 WebString::fromUTF8(ResourceBundle::GetSharedInstance()
447 .GetRawDataResource(IDR_EXTENSION_CSS
)
451 content_watcher_
->DidCreateDocumentElement(frame
);
454 void Dispatcher::DidMatchCSS(
455 blink::WebFrame
* frame
,
456 const blink::WebVector
<blink::WebString
>& newly_matching_selectors
,
457 const blink::WebVector
<blink::WebString
>& stopped_matching_selectors
) {
458 content_watcher_
->DidMatchCSS(
459 frame
, newly_matching_selectors
, stopped_matching_selectors
);
462 void Dispatcher::OnExtensionResponse(int request_id
,
464 const base::ListValue
& response
,
465 const std::string
& error
) {
466 request_sender_
->HandleResponse(request_id
, success
, response
, error
);
469 bool Dispatcher::CheckContextAccessToExtensionAPI(
470 const std::string
& function_name
,
471 ScriptContext
* context
) const {
473 DLOG(ERROR
) << "Not in a v8::Context";
477 // Theoretically we could end up with bindings being injected into sandboxed
478 // frames, for example content scripts. Don't let them execute API functions.
479 blink::WebFrame
* frame
= context
->web_frame();
480 if (IsSandboxedPage(ScriptContext::GetDataSourceURLForFrame(frame
))) {
481 static const char kMessage
[] =
482 "%s cannot be used within a sandboxed frame.";
483 std::string error_msg
= base::StringPrintf(kMessage
, function_name
.c_str());
484 context
->isolate()->ThrowException(v8::Exception::Error(
485 v8::String::NewFromUtf8(context
->isolate(), error_msg
.c_str())));
489 Feature::Availability availability
= context
->GetAvailability(function_name
);
490 if (!availability
.is_available()) {
491 context
->isolate()->ThrowException(
492 v8::Exception::Error(v8::String::NewFromUtf8(
493 context
->isolate(), availability
.message().c_str())));
496 return availability
.is_available();
499 void Dispatcher::DispatchEvent(const std::string
& extension_id
,
500 const std::string
& event_name
) const {
501 base::ListValue args
;
502 args
.Set(0, new base::StringValue(event_name
));
503 args
.Set(1, new base::ListValue());
505 // Needed for Windows compilation, since kEventBindings is declared extern.
506 const char* local_event_bindings
= kEventBindings
;
507 script_context_set_
.ForEach(extension_id
,
508 base::Bind(&CallModuleMethod
,
509 local_event_bindings
,
510 kEventDispatchFunction
,
514 void Dispatcher::InvokeModuleSystemMethod(content::RenderView
* render_view
,
515 const std::string
& extension_id
,
516 const std::string
& module_name
,
517 const std::string
& function_name
,
518 const base::ListValue
& args
,
520 scoped_ptr
<WebScopedUserGesture
> web_user_gesture
;
522 web_user_gesture
.reset(new WebScopedUserGesture
);
524 script_context_set_
.ForEach(
527 base::Bind(&CallModuleMethod
, module_name
, function_name
, &args
));
529 // Reset the idle handler each time there's any activity like event or message
530 // dispatch, for which Invoke is the chokepoint.
531 if (is_extension_process_
) {
532 RenderThread::Get()->ScheduleIdleHandler(
533 kInitialExtensionIdleHandlerDelayMs
);
536 // Tell the browser process when an event has been dispatched with a lazy
537 // background page active.
538 const Extension
* extension
= extensions_
.GetByID(extension_id
);
539 if (extension
&& BackgroundInfo::HasLazyBackgroundPage(extension
) &&
540 module_name
== kEventBindings
&&
541 function_name
== kEventDispatchFunction
) {
542 RenderView
* background_view
=
543 ExtensionHelper::GetBackgroundPage(extension_id
);
544 if (background_view
) {
546 args
.GetInteger(3, &message_id
);
547 background_view
->Send(new ExtensionHostMsg_EventAck(
548 background_view
->GetRoutingID(), message_id
));
553 void Dispatcher::ClearPortData(int port_id
) {
554 // Only the target port side has entries in |port_to_tab_id_map_|. If
555 // |port_id| is a source port, std::map::erase() will just silently fail
557 port_to_tab_id_map_
.erase(port_id
);
561 std::vector
<std::pair
<std::string
, int> > Dispatcher::GetJsResources() {
562 std::vector
<std::pair
<std::string
, int> > resources
;
565 resources
.push_back(std::make_pair("appView", IDR_APP_VIEW_JS
));
566 resources
.push_back(std::make_pair("denyAppView", IDR_APP_VIEW_DENY_JS
));
567 resources
.push_back(std::make_pair("entryIdManager", IDR_ENTRY_ID_MANAGER
));
568 resources
.push_back(std::make_pair(kEventBindings
, IDR_EVENT_BINDINGS_JS
));
569 resources
.push_back(std::make_pair("imageUtil", IDR_IMAGE_UTIL_JS
));
570 resources
.push_back(std::make_pair("json_schema", IDR_JSON_SCHEMA_JS
));
571 resources
.push_back(std::make_pair("lastError", IDR_LAST_ERROR_JS
));
572 resources
.push_back(std::make_pair("messaging", IDR_MESSAGING_JS
));
574 std::make_pair("messaging_utils", IDR_MESSAGING_UTILS_JS
));
575 resources
.push_back(std::make_pair(kSchemaUtils
, IDR_SCHEMA_UTILS_JS
));
576 resources
.push_back(std::make_pair("sendRequest", IDR_SEND_REQUEST_JS
));
577 resources
.push_back(std::make_pair("setIcon", IDR_SET_ICON_JS
));
578 resources
.push_back(std::make_pair("test", IDR_TEST_CUSTOM_BINDINGS_JS
));
580 std::make_pair("test_environment_specific_bindings",
581 IDR_BROWSER_TEST_ENVIRONMENT_SPECIFIC_BINDINGS_JS
));
582 resources
.push_back(std::make_pair("uncaught_exception_handler",
583 IDR_UNCAUGHT_EXCEPTION_HANDLER_JS
));
584 resources
.push_back(std::make_pair("unload_event", IDR_UNLOAD_EVENT_JS
));
585 resources
.push_back(std::make_pair("utils", IDR_UTILS_JS
));
586 resources
.push_back(std::make_pair("webRequest",
587 IDR_WEB_REQUEST_CUSTOM_BINDINGS_JS
));
589 std::make_pair("webRequestInternal",
590 IDR_WEB_REQUEST_INTERNAL_CUSTOM_BINDINGS_JS
));
591 // Note: webView not webview so that this doesn't interfere with the
592 // chrome.webview API bindings.
593 resources
.push_back(std::make_pair("guestView", IDR_GUEST_VIEW_JS
));
594 resources
.push_back(std::make_pair("guestViewContainer",
595 IDR_GUEST_VIEW_CONTAINER_JS
));
596 resources
.push_back(std::make_pair("extensionView", IDR_EXTENSION_VIEW_JS
));
597 resources
.push_back(std::make_pair("extensionViewApiMethods",
598 IDR_EXTENSION_VIEW_API_METHODS_JS
));
599 resources
.push_back(std::make_pair("extensionViewAttributes",
600 IDR_EXTENSION_VIEW_ATTRIBUTES_JS
));
601 resources
.push_back(std::make_pair("extensionViewConstants",
602 IDR_EXTENSION_VIEW_CONSTANTS_JS
));
603 resources
.push_back(std::make_pair("extensionViewEvents",
604 IDR_EXTENSION_VIEW_EVENTS_JS
));
605 resources
.push_back(std::make_pair(
606 "extensionViewInternal", IDR_EXTENSION_VIEW_INTERNAL_CUSTOM_BINDINGS_JS
));
607 resources
.push_back(std::make_pair("webView", IDR_WEB_VIEW_JS
));
608 resources
.push_back(std::make_pair("surfaceWorker", IDR_SURFACE_VIEW_JS
));
609 resources
.push_back(std::make_pair("webViewActionRequests",
610 IDR_WEB_VIEW_ACTION_REQUESTS_JS
));
611 resources
.push_back(std::make_pair("webViewApiMethods",
612 IDR_WEB_VIEW_API_METHODS_JS
));
613 resources
.push_back(std::make_pair("webViewAttributes",
614 IDR_WEB_VIEW_ATTRIBUTES_JS
));
615 resources
.push_back(std::make_pair("webViewConstants",
616 IDR_WEB_VIEW_CONSTANTS_JS
));
617 resources
.push_back(std::make_pair("webViewEvents", IDR_WEB_VIEW_EVENTS_JS
));
619 std::make_pair("webViewExperimental", IDR_WEB_VIEW_EXPERIMENTAL_JS
));
620 resources
.push_back(std::make_pair("webViewInternal",
621 IDR_WEB_VIEW_INTERNAL_CUSTOM_BINDINGS_JS
));
622 resources
.push_back(std::make_pair("denyWebView", IDR_WEB_VIEW_DENY_JS
));
624 std::make_pair(mojo::kBindingsModuleName
, IDR_MOJO_BINDINGS_JS
));
626 std::make_pair(mojo::kBufferModuleName
, IDR_MOJO_BUFFER_JS
));
628 std::make_pair(mojo::kCodecModuleName
, IDR_MOJO_CODEC_JS
));
630 std::make_pair(mojo::kConnectionModuleName
, IDR_MOJO_CONNECTION_JS
));
632 std::make_pair(mojo::kConnectorModuleName
, IDR_MOJO_CONNECTOR_JS
));
634 std::make_pair(mojo::kRouterModuleName
, IDR_MOJO_ROUTER_JS
));
636 std::make_pair(mojo::kUnicodeModuleName
, IDR_MOJO_UNICODE_JS
));
638 std::make_pair(mojo::kValidatorModuleName
, IDR_MOJO_VALIDATOR_JS
));
639 resources
.push_back(std::make_pair("async_waiter", IDR_ASYNC_WAITER_JS
));
640 resources
.push_back(std::make_pair("data_receiver", IDR_DATA_RECEIVER_JS
));
641 resources
.push_back(std::make_pair("data_sender", IDR_DATA_SENDER_JS
));
642 resources
.push_back(std::make_pair("keep_alive", IDR_KEEP_ALIVE_JS
));
643 resources
.push_back(std::make_pair("extensions/common/mojo/keep_alive.mojom",
644 IDR_KEEP_ALIVE_MOJOM_JS
));
645 resources
.push_back(std::make_pair("device/serial/data_stream.mojom",
646 IDR_DATA_STREAM_MOJOM_JS
));
648 std::make_pair("device/serial/data_stream_serialization.mojom",
649 IDR_DATA_STREAM_SERIALIZATION_MOJOM_JS
));
650 resources
.push_back(std::make_pair("stash_client", IDR_STASH_CLIENT_JS
));
652 std::make_pair("extensions/common/mojo/stash.mojom", IDR_STASH_MOJOM_JS
));
656 std::make_pair("app.runtime", IDR_APP_RUNTIME_CUSTOM_BINDINGS_JS
));
658 std::make_pair("app.window", IDR_APP_WINDOW_CUSTOM_BINDINGS_JS
));
660 std::make_pair("declarativeWebRequest",
661 IDR_DECLARATIVE_WEBREQUEST_CUSTOM_BINDINGS_JS
));
663 std::make_pair("contextMenus", IDR_CONTEXT_MENUS_CUSTOM_BINDINGS_JS
));
665 std::make_pair("extension", IDR_EXTENSION_CUSTOM_BINDINGS_JS
));
666 resources
.push_back(std::make_pair("i18n", IDR_I18N_CUSTOM_BINDINGS_JS
));
667 resources
.push_back(std::make_pair(
668 "mimeHandlerPrivate", IDR_MIME_HANDLER_PRIVATE_CUSTOM_BINDINGS_JS
));
669 resources
.push_back(std::make_pair("extensions/common/api/mime_handler.mojom",
670 IDR_MIME_HANDLER_MOJOM_JS
));
672 std::make_pair("mojoPrivate", IDR_MOJO_PRIVATE_CUSTOM_BINDINGS_JS
));
674 std::make_pair("permissions", IDR_PERMISSIONS_CUSTOM_BINDINGS_JS
));
675 resources
.push_back(std::make_pair("printerProvider",
676 IDR_PRINTER_PROVIDER_CUSTOM_BINDINGS_JS
));
678 std::make_pair("runtime", IDR_RUNTIME_CUSTOM_BINDINGS_JS
));
679 resources
.push_back(std::make_pair("windowControls", IDR_WINDOW_CONTROLS_JS
));
681 std::make_pair("webViewRequest",
682 IDR_WEB_VIEW_REQUEST_CUSTOM_BINDINGS_JS
));
683 resources
.push_back(std::make_pair("binding", IDR_BINDING_JS
));
685 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
686 switches::kEnableMojoSerialService
)) {
688 std::make_pair("serial", IDR_SERIAL_CUSTOM_BINDINGS_JS
));
690 resources
.push_back(std::make_pair("serial_service", IDR_SERIAL_SERVICE_JS
));
692 std::make_pair("device/serial/serial.mojom", IDR_SERIAL_MOJOM_JS
));
693 resources
.push_back(std::make_pair("device/serial/serial_serialization.mojom",
694 IDR_SERIAL_SERIALIZATION_MOJOM_JS
));
696 // Custom types sources.
697 resources
.push_back(std::make_pair("StorageArea", IDR_STORAGE_AREA_JS
));
699 // Platform app sources that are not API-specific..
700 resources
.push_back(std::make_pair("platformApp", IDR_PLATFORM_APP_JS
));
705 // NOTE: please use the naming convention "foo_natives" for these.
707 void Dispatcher::RegisterNativeHandlers(ModuleSystem
* module_system
,
708 ScriptContext
* context
,
709 Dispatcher
* dispatcher
,
710 RequestSender
* request_sender
,
711 V8SchemaRegistry
* v8_schema_registry
) {
712 module_system
->RegisterNativeHandler(
713 "chrome", scoped_ptr
<NativeHandler
>(new ChromeNativeHandler(context
)));
714 module_system
->RegisterNativeHandler(
715 "lazy_background_page",
716 scoped_ptr
<NativeHandler
>(new LazyBackgroundPageNativeHandler(context
)));
717 module_system
->RegisterNativeHandler(
718 "logging", scoped_ptr
<NativeHandler
>(new LoggingNativeHandler(context
)));
719 module_system
->RegisterNativeHandler("schema_registry",
720 v8_schema_registry
->AsNativeHandler());
721 module_system
->RegisterNativeHandler(
722 "print", scoped_ptr
<NativeHandler
>(new PrintNativeHandler(context
)));
723 module_system
->RegisterNativeHandler(
725 scoped_ptr
<NativeHandler
>(new TestFeaturesNativeHandler(context
)));
726 module_system
->RegisterNativeHandler(
728 scoped_ptr
<NativeHandler
>(new UserGesturesNativeHandler(context
)));
729 module_system
->RegisterNativeHandler(
730 "utils", scoped_ptr
<NativeHandler
>(new UtilsNativeHandler(context
)));
731 module_system
->RegisterNativeHandler(
733 scoped_ptr
<NativeHandler
>(
734 new V8ContextNativeHandler(context
, dispatcher
)));
735 module_system
->RegisterNativeHandler(
737 scoped_ptr
<NativeHandler
>(new EventBindings(dispatcher
, context
)));
738 module_system
->RegisterNativeHandler(
740 scoped_ptr
<NativeHandler
>(MessagingBindings::Get(dispatcher
, context
)));
741 module_system
->RegisterNativeHandler(
743 scoped_ptr
<NativeHandler
>(
744 new ApiDefinitionsNatives(dispatcher
, context
)));
745 module_system
->RegisterNativeHandler(
747 scoped_ptr
<NativeHandler
>(
748 new SendRequestNatives(request_sender
, context
)));
749 module_system
->RegisterNativeHandler(
751 scoped_ptr
<NativeHandler
>(new SetIconNatives(context
)));
752 module_system
->RegisterNativeHandler(
754 scoped_ptr
<NativeHandler
>(new APIActivityLogger(context
)));
755 module_system
->RegisterNativeHandler(
756 "renderViewObserverNatives",
757 scoped_ptr
<NativeHandler
>(new RenderViewObserverNatives(context
)));
759 // Natives used by multiple APIs.
760 module_system
->RegisterNativeHandler(
761 "file_system_natives",
762 scoped_ptr
<NativeHandler
>(new FileSystemNatives(context
)));
765 module_system
->RegisterNativeHandler(
767 scoped_ptr
<NativeHandler
>(new AppRuntimeCustomBindings(context
)));
768 module_system
->RegisterNativeHandler(
769 "app_window_natives",
770 scoped_ptr
<NativeHandler
>(
771 new AppWindowCustomBindings(dispatcher
, context
)));
772 module_system
->RegisterNativeHandler(
774 scoped_ptr
<NativeHandler
>(new BlobNativeHandler(context
)));
775 module_system
->RegisterNativeHandler(
777 scoped_ptr
<NativeHandler
>(new ContextMenusCustomBindings(context
)));
778 module_system
->RegisterNativeHandler(
779 "css_natives", scoped_ptr
<NativeHandler
>(new CssNativeHandler(context
)));
780 module_system
->RegisterNativeHandler(
782 scoped_ptr
<NativeHandler
>(new DocumentCustomBindings(context
)));
783 module_system
->RegisterNativeHandler(
784 "guest_view_internal",
785 scoped_ptr
<NativeHandler
>(
786 new GuestViewInternalCustomBindings(context
)));
787 module_system
->RegisterNativeHandler(
788 "i18n", scoped_ptr
<NativeHandler
>(new I18NCustomBindings(context
)));
789 module_system
->RegisterNativeHandler(
791 scoped_ptr
<NativeHandler
>(new IdGeneratorCustomBindings(context
)));
792 module_system
->RegisterNativeHandler(
793 "runtime", scoped_ptr
<NativeHandler
>(new RuntimeCustomBindings(context
)));
796 bool Dispatcher::OnControlMessageReceived(const IPC::Message
& message
) {
798 IPC_BEGIN_MESSAGE_MAP(Dispatcher
, message
)
799 IPC_MESSAGE_HANDLER(ExtensionMsg_ActivateExtension
, OnActivateExtension
)
800 IPC_MESSAGE_HANDLER(ExtensionMsg_CancelSuspend
, OnCancelSuspend
)
801 IPC_MESSAGE_HANDLER(ExtensionMsg_DeliverMessage
, OnDeliverMessage
)
802 IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnConnect
, OnDispatchOnConnect
)
803 IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnDisconnect
, OnDispatchOnDisconnect
)
804 IPC_MESSAGE_HANDLER(ExtensionMsg_Loaded
, OnLoaded
)
805 IPC_MESSAGE_HANDLER(ExtensionMsg_MessageInvoke
, OnMessageInvoke
)
806 IPC_MESSAGE_HANDLER(ExtensionMsg_SetChannel
, OnSetChannel
)
807 IPC_MESSAGE_HANDLER(ExtensionMsg_SetFunctionNames
, OnSetFunctionNames
)
808 IPC_MESSAGE_HANDLER(ExtensionMsg_SetScriptingWhitelist
,
809 OnSetScriptingWhitelist
)
810 IPC_MESSAGE_HANDLER(ExtensionMsg_SetSystemFont
, OnSetSystemFont
)
811 IPC_MESSAGE_HANDLER(ExtensionMsg_ShouldSuspend
, OnShouldSuspend
)
812 IPC_MESSAGE_HANDLER(ExtensionMsg_Suspend
, OnSuspend
)
813 IPC_MESSAGE_HANDLER(ExtensionMsg_TransferBlobs
, OnTransferBlobs
)
814 IPC_MESSAGE_HANDLER(ExtensionMsg_Unloaded
, OnUnloaded
)
815 IPC_MESSAGE_HANDLER(ExtensionMsg_UpdatePermissions
, OnUpdatePermissions
)
816 IPC_MESSAGE_HANDLER(ExtensionMsg_UpdateTabSpecificPermissions
,
817 OnUpdateTabSpecificPermissions
)
818 IPC_MESSAGE_HANDLER(ExtensionMsg_ClearTabSpecificPermissions
,
819 OnClearTabSpecificPermissions
)
820 IPC_MESSAGE_HANDLER(ExtensionMsg_UsingWebRequestAPI
, OnUsingWebRequestAPI
)
821 IPC_MESSAGE_FORWARD(ExtensionMsg_WatchPages
,
822 content_watcher_
.get(),
823 ContentWatcher::OnWatchPages
)
824 IPC_MESSAGE_UNHANDLED(handled
= false)
825 IPC_END_MESSAGE_MAP()
830 void Dispatcher::WebKitInitialized() {
831 // For extensions, we want to ensure we call the IdleHandler every so often,
832 // even if the extension keeps up activity.
833 if (is_extension_process_
) {
834 forced_idle_timer_
.reset(new base::RepeatingTimer
<content::RenderThread
>);
835 forced_idle_timer_
->Start(
837 base::TimeDelta::FromMilliseconds(kMaxExtensionIdleHandlerDelayMs
),
839 &RenderThread::IdleHandler
);
842 // Initialize host permissions for any extensions that were activated before
843 // WebKit was initialized.
844 for (std::set
<std::string
>::iterator iter
= active_extension_ids_
.begin();
845 iter
!= active_extension_ids_
.end();
847 const Extension
* extension
= extensions_
.GetByID(*iter
);
850 InitOriginPermissions(extension
);
853 EnableCustomElementWhiteList();
855 is_webkit_initialized_
= true;
858 void Dispatcher::IdleNotification() {
859 if (is_extension_process_
&& forced_idle_timer_
) {
860 // Dampen the forced delay as well if the extension stays idle for long
861 // periods of time. (forced_idle_timer_ can be NULL after
862 // OnRenderProcessShutdown has been called.)
863 int64 forced_delay_ms
=
864 std::max(RenderThread::Get()->GetIdleNotificationDelayInMs(),
865 kMaxExtensionIdleHandlerDelayMs
);
866 forced_idle_timer_
->Stop();
867 forced_idle_timer_
->Start(
869 base::TimeDelta::FromMilliseconds(forced_delay_ms
),
871 &RenderThread::IdleHandler
);
875 void Dispatcher::OnRenderProcessShutdown() {
876 v8_schema_registry_
.reset();
877 forced_idle_timer_
.reset();
880 void Dispatcher::OnActivateExtension(const std::string
& extension_id
) {
881 const Extension
* extension
= extensions_
.GetByID(extension_id
);
883 // Extension was activated but was never loaded. This probably means that
884 // the renderer failed to load it (or the browser failed to tell us when it
885 // did). Failures shouldn't happen, but instead of crashing there (which
886 // executes on all renderers) be conservative and only crash in the renderer
887 // of the extension which failed to load; this one.
888 std::string
& error
= extension_load_errors_
[extension_id
];
890 base::debug::Alias(&minidump
);
891 base::snprintf(minidump
,
893 "e::dispatcher:%s:%s",
894 extension_id
.c_str(),
896 CHECK(extension
) << extension_id
<< " was never loaded: " << error
;
899 active_extension_ids_
.insert(extension_id
);
901 // This is called when starting a new extension page, so start the idle
903 RenderThread::Get()->ScheduleIdleHandler(kInitialExtensionIdleHandlerDelayMs
);
905 if (is_webkit_initialized_
) {
906 DOMActivityLogger::AttachToWorld(
907 DOMActivityLogger::kMainWorldId
, extension_id
);
909 InitOriginPermissions(extension
);
912 UpdateActiveExtensions();
915 void Dispatcher::OnCancelSuspend(const std::string
& extension_id
) {
916 DispatchEvent(extension_id
, kOnSuspendCanceledEvent
);
919 void Dispatcher::OnDeliverMessage(int target_port_id
, const Message
& message
) {
920 scoped_ptr
<RequestSender::ScopedTabID
> scoped_tab_id
;
921 std::map
<int, int>::const_iterator it
=
922 port_to_tab_id_map_
.find(target_port_id
);
923 if (it
!= port_to_tab_id_map_
.end()) {
925 new RequestSender::ScopedTabID(request_sender(), it
->second
));
928 MessagingBindings::DeliverMessage(script_context_set_
,
931 NULL
); // All render frames.
934 void Dispatcher::OnDispatchOnConnect(
936 const std::string
& channel_name
,
937 const ExtensionMsg_TabConnectionInfo
& source
,
938 const ExtensionMsg_ExternalConnectionInfo
& info
,
939 const std::string
& tls_channel_id
) {
940 DCHECK(!ContainsKey(port_to_tab_id_map_
, target_port_id
));
941 DCHECK_EQ(1, target_port_id
% 2); // target renderer ports have odd IDs.
942 int sender_tab_id
= -1;
943 source
.tab
.GetInteger("id", &sender_tab_id
);
944 port_to_tab_id_map_
[target_port_id
] = sender_tab_id
;
946 MessagingBindings::DispatchOnConnect(script_context_set_
,
952 NULL
); // All render frames.
955 void Dispatcher::OnDispatchOnDisconnect(int port_id
,
956 const std::string
& error_message
) {
957 MessagingBindings::DispatchOnDisconnect(script_context_set_
,
960 NULL
); // All render frames.
963 void Dispatcher::OnLoaded(
964 const std::vector
<ExtensionMsg_Loaded_Params
>& loaded_extensions
) {
965 std::vector
<ExtensionMsg_Loaded_Params
>::const_iterator i
;
966 for (i
= loaded_extensions
.begin(); i
!= loaded_extensions
.end(); ++i
) {
968 scoped_refptr
<const Extension
> extension
= i
->ConvertToExtension(&error
);
969 if (!extension
.get()) {
970 extension_load_errors_
[i
->id
] = error
;
973 OnLoadedInternal(extension
);
975 // Update the available bindings for all contexts. These may have changed if
976 // an externally_connectable extension was loaded that can connect to an
981 void Dispatcher::OnLoadedInternal(scoped_refptr
<const Extension
> extension
) {
982 extensions_
.Insert(extension
);
985 void Dispatcher::OnMessageInvoke(const std::string
& extension_id
,
986 const std::string
& module_name
,
987 const std::string
& function_name
,
988 const base::ListValue
& args
,
990 InvokeModuleSystemMethod(
991 NULL
, extension_id
, module_name
, function_name
, args
, user_gesture
);
994 void Dispatcher::OnSetChannel(int channel
) {
995 delegate_
->SetChannel(channel
);
998 void Dispatcher::OnSetFunctionNames(const std::vector
<std::string
>& names
) {
999 function_names_
.clear();
1000 for (size_t i
= 0; i
< names
.size(); ++i
)
1001 function_names_
.insert(names
[i
]);
1004 void Dispatcher::OnSetScriptingWhitelist(
1005 const ExtensionsClient::ScriptingWhitelist
& extension_ids
) {
1006 ExtensionsClient::Get()->SetScriptingWhitelist(extension_ids
);
1009 void Dispatcher::OnSetSystemFont(const std::string
& font_family
,
1010 const std::string
& font_size
) {
1011 system_font_family_
= font_family
;
1012 system_font_size_
= font_size
;
1015 void Dispatcher::OnShouldSuspend(const std::string
& extension_id
,
1016 uint64 sequence_id
) {
1017 RenderThread::Get()->Send(
1018 new ExtensionHostMsg_ShouldSuspendAck(extension_id
, sequence_id
));
1021 void Dispatcher::OnSuspend(const std::string
& extension_id
) {
1022 // Dispatch the suspend event. This doesn't go through the standard event
1023 // dispatch machinery because it requires special handling. We need to let
1024 // the browser know when we are starting and stopping the event dispatch, so
1025 // that it still considers the extension idle despite any activity the suspend
1027 DispatchEvent(extension_id
, kOnSuspendEvent
);
1028 RenderThread::Get()->Send(new ExtensionHostMsg_SuspendAck(extension_id
));
1031 void Dispatcher::OnTransferBlobs(const std::vector
<std::string
>& blob_uuids
) {
1032 RenderThread::Get()->Send(new ExtensionHostMsg_TransferBlobsAck(blob_uuids
));
1035 void Dispatcher::OnUnloaded(const std::string
& id
) {
1036 extensions_
.Remove(id
);
1037 active_extension_ids_
.erase(id
);
1039 // If the extension is later reloaded with a different set of permissions,
1040 // we'd like it to get a new isolated world ID, so that it can pick up the
1041 // changed origin whitelist.
1042 ScriptInjection::RemoveIsolatedWorld(id
);
1044 // Invalidate all of the contexts that were removed.
1045 // TODO(kalman): add an invalidation observer interface to ScriptContext.
1046 ScriptContextSet::ContextSet removed_contexts
=
1047 script_context_set_
.OnExtensionUnloaded(id
);
1048 for (ScriptContextSet::ContextSet::iterator it
= removed_contexts
.begin();
1049 it
!= removed_contexts
.end();
1051 request_sender_
->InvalidateSource(*it
);
1054 // Update the available bindings for the remaining contexts. These may have
1055 // changed if an externally_connectable extension is unloaded and a webpage
1056 // is no longer accessible.
1059 // Invalidates the messages map for the extension in case the extension is
1060 // reloaded with a new messages map.
1061 EraseL10nMessagesMap(id
);
1063 // We don't do anything with existing platform-app stylesheets. They will
1064 // stay resident, but the URL pattern corresponding to the unloaded
1065 // extension's URL just won't match anything anymore.
1068 void Dispatcher::OnUpdatePermissions(
1069 const ExtensionMsg_UpdatePermissions_Params
& params
) {
1070 const Extension
* extension
= extensions_
.GetByID(params
.extension_id
);
1074 scoped_refptr
<const PermissionSet
> active
=
1075 params
.active_permissions
.ToPermissionSet();
1076 scoped_refptr
<const PermissionSet
> withheld
=
1077 params
.withheld_permissions
.ToPermissionSet();
1079 if (is_webkit_initialized_
) {
1080 UpdateOriginPermissions(
1082 extension
->permissions_data()->GetEffectiveHostPermissions(),
1083 active
->effective_hosts());
1086 extension
->permissions_data()->SetPermissions(active
, withheld
);
1087 UpdateBindings(extension
->id());
1090 void Dispatcher::OnUpdateTabSpecificPermissions(const GURL
& visible_url
,
1091 const std::string
& extension_id
,
1092 const URLPatternSet
& new_hosts
,
1093 bool update_origin_whitelist
,
1095 // Check against the URL to avoid races. If we can't find the tab, it's
1096 // because this is an extension's background page (run in a different
1097 // process) - in this case, we can't perform the security check. However,
1098 // since activeTab is only granted via user action, this isn't a huge concern.
1099 content::RenderView
* render_view
= TabFinder::Find(tab_id
);
1101 render_view
->GetWebView()->mainFrame()->document().url() != visible_url
) {
1105 const Extension
* extension
= extensions_
.GetByID(extension_id
);
1109 URLPatternSet old_effective
=
1110 extension
->permissions_data()->GetEffectiveHostPermissions();
1111 extension
->permissions_data()->UpdateTabSpecificPermissions(
1113 new extensions::PermissionSet(extensions::APIPermissionSet(),
1114 extensions::ManifestPermissionSet(),
1116 extensions::URLPatternSet()));
1118 if (is_webkit_initialized_
&& update_origin_whitelist
) {
1119 UpdateOriginPermissions(
1122 extension
->permissions_data()->GetEffectiveHostPermissions());
1126 void Dispatcher::OnClearTabSpecificPermissions(
1127 const std::vector
<std::string
>& extension_ids
,
1128 bool update_origin_whitelist
,
1130 for (const std::string
& id
: extension_ids
) {
1131 const Extension
* extension
= extensions_
.GetByID(id
);
1133 URLPatternSet old_effective
=
1134 extension
->permissions_data()->GetEffectiveHostPermissions();
1135 extension
->permissions_data()->ClearTabSpecificPermissions(tab_id
);
1136 if (is_webkit_initialized_
&& update_origin_whitelist
) {
1137 UpdateOriginPermissions(
1140 extension
->permissions_data()->GetEffectiveHostPermissions());
1146 void Dispatcher::OnUsingWebRequestAPI(bool webrequest_used
) {
1147 webrequest_used_
= webrequest_used
;
1150 void Dispatcher::OnUserScriptsUpdated(
1151 const std::set
<std::string
>& changed_extensions
,
1152 const std::vector
<UserScript
*>& scripts
) {
1153 UpdateActiveExtensions();
1156 void Dispatcher::UpdateActiveExtensions() {
1157 std::set
<std::string
> active_extensions
= active_extension_ids_
;
1158 user_script_set_manager_
->GetAllActiveExtensionIds(&active_extensions
);
1159 delegate_
->OnActiveExtensionsUpdated(active_extensions
);
1162 void Dispatcher::InitOriginPermissions(const Extension
* extension
) {
1163 delegate_
->InitOriginPermissions(extension
,
1164 IsExtensionActive(extension
->id()));
1165 UpdateOriginPermissions(
1167 URLPatternSet(), // No old permissions.
1168 extension
->permissions_data()->GetEffectiveHostPermissions());
1171 void Dispatcher::UpdateOriginPermissions(const GURL
& extension_url
,
1172 const URLPatternSet
& old_patterns
,
1173 const URLPatternSet
& new_patterns
) {
1174 static const char* kSchemes
[] = {
1178 content::kChromeUIScheme
,
1180 #if defined(OS_CHROMEOS)
1181 content::kExternalFileScheme
,
1184 for (size_t i
= 0; i
< arraysize(kSchemes
); ++i
) {
1185 const char* scheme
= kSchemes
[i
];
1186 // Remove all old patterns...
1187 for (URLPatternSet::const_iterator pattern
= old_patterns
.begin();
1188 pattern
!= old_patterns
.end(); ++pattern
) {
1189 if (pattern
->MatchesScheme(scheme
)) {
1190 WebSecurityPolicy::removeOriginAccessWhitelistEntry(
1192 WebString::fromUTF8(scheme
),
1193 WebString::fromUTF8(pattern
->host()),
1194 pattern
->match_subdomains());
1197 // ...And add the new ones.
1198 for (URLPatternSet::const_iterator pattern
= new_patterns
.begin();
1199 pattern
!= new_patterns
.end(); ++pattern
) {
1200 if (pattern
->MatchesScheme(scheme
)) {
1201 WebSecurityPolicy::addOriginAccessWhitelistEntry(
1203 WebString::fromUTF8(scheme
),
1204 WebString::fromUTF8(pattern
->host()),
1205 pattern
->match_subdomains());
1211 void Dispatcher::EnableCustomElementWhiteList() {
1212 blink::WebCustomElement::addEmbedderCustomElementName("appview");
1213 blink::WebCustomElement::addEmbedderCustomElementName("appviewbrowserplugin");
1214 blink::WebCustomElement::addEmbedderCustomElementName("extensionoptions");
1215 blink::WebCustomElement::addEmbedderCustomElementName(
1216 "extensionoptionsbrowserplugin");
1217 blink::WebCustomElement::addEmbedderCustomElementName("extensionview");
1218 blink::WebCustomElement::addEmbedderCustomElementName(
1219 "extensionviewbrowserplugin");
1220 blink::WebCustomElement::addEmbedderCustomElementName("webview");
1221 blink::WebCustomElement::addEmbedderCustomElementName("webviewbrowserplugin");
1222 blink::WebCustomElement::addEmbedderCustomElementName("surfaceview");
1223 blink::WebCustomElement::addEmbedderCustomElementName(
1224 "surfaceviewbrowserplugin");
1227 void Dispatcher::UpdateBindings(const std::string
& extension_id
) {
1228 script_context_set().ForEach(extension_id
,
1229 base::Bind(&Dispatcher::UpdateBindingsForContext
,
1230 base::Unretained(this)));
1233 void Dispatcher::UpdateBindingsForContext(ScriptContext
* context
) {
1234 v8::HandleScope
handle_scope(context
->isolate());
1235 v8::Context::Scope
context_scope(context
->v8_context());
1237 // TODO(kalman): Make the bindings registration have zero overhead then run
1238 // the same code regardless of context type.
1239 switch (context
->context_type()) {
1240 case Feature::UNSPECIFIED_CONTEXT
:
1241 case Feature::WEB_PAGE_CONTEXT
:
1242 case Feature::BLESSED_WEB_PAGE_CONTEXT
:
1243 // Web page context; it's too expensive to run the full bindings code.
1244 // Hard-code that the app and webstore APIs are available...
1245 if (context
->GetAvailability("app").is_available())
1246 RegisterBinding("app", context
);
1247 if (context
->GetAvailability("webstore").is_available())
1248 RegisterBinding("webstore", context
);
1249 if (IsRuntimeAvailableToContext(context
))
1250 RegisterBinding("runtime", context
);
1251 UpdateContentCapabilities(context
);
1254 case Feature::BLESSED_EXTENSION_CONTEXT
:
1255 case Feature::UNBLESSED_EXTENSION_CONTEXT
:
1256 case Feature::CONTENT_SCRIPT_CONTEXT
:
1257 case Feature::WEBUI_CONTEXT
: {
1258 // Extension context; iterate through all the APIs and bind the available
1260 const FeatureProvider
* api_feature_provider
=
1261 FeatureProvider::GetAPIFeatures();
1262 const std::vector
<std::string
>& apis
=
1263 api_feature_provider
->GetAllFeatureNames();
1264 for (std::vector
<std::string
>::const_iterator it
= apis
.begin();
1267 const std::string
& api_name
= *it
;
1268 Feature
* feature
= api_feature_provider
->GetFeature(api_name
);
1271 // Internal APIs are included via require(api_name) from internal code
1272 // rather than chrome[api_name].
1273 if (feature
->IsInternal())
1276 // If this API has a parent feature (and isn't marked 'noparent'),
1277 // then this must be a function or event, so we should not register.
1278 if (api_feature_provider
->GetParent(feature
) != NULL
)
1281 // Skip chrome.test if this isn't a test.
1282 if (api_name
== "test" &&
1283 !base::CommandLine::ForCurrentProcess()->HasSwitch(
1284 ::switches::kTestType
)) {
1288 if (context
->IsAnyFeatureAvailableToContext(*feature
))
1289 RegisterBinding(api_name
, context
);
1296 void Dispatcher::RegisterBinding(const std::string
& api_name
,
1297 ScriptContext
* context
) {
1298 std::string bind_name
;
1299 v8::Handle
<v8::Object
> bind_object
=
1300 GetOrCreateBindObjectIfAvailable(api_name
, &bind_name
, context
);
1302 // Empty if the bind object failed to be created, probably because the
1303 // extension overrode chrome with a non-object, e.g. window.chrome = true.
1304 if (bind_object
.IsEmpty())
1307 v8::Local
<v8::String
> v8_bind_name
=
1308 v8::String::NewFromUtf8(context
->isolate(), bind_name
.c_str());
1309 if (bind_object
->HasRealNamedProperty(v8_bind_name
)) {
1310 // The bind object may already have the property if the API has been
1311 // registered before (or if the extension has put something there already,
1314 // In the former case, we need to re-register the bindings for the APIs
1315 // which the extension now has permissions for (if any), but not touch any
1316 // others so that we don't destroy state such as event listeners.
1318 // TODO(kalman): Only register available APIs to make this all moot.
1319 if (bind_object
->HasRealNamedCallbackProperty(v8_bind_name
))
1320 return; // lazy binding still there, nothing to do
1321 if (bind_object
->Get(v8_bind_name
)->IsObject())
1322 return; // binding has already been fully installed
1325 ModuleSystem
* module_system
= context
->module_system();
1326 if (!source_map_
.Contains(api_name
)) {
1327 module_system
->RegisterNativeHandler(
1329 scoped_ptr
<NativeHandler
>(new BindingGeneratingNativeHandler(
1330 module_system
, api_name
, "binding")));
1331 module_system
->SetNativeLazyField(
1332 bind_object
, bind_name
, api_name
, "binding");
1334 module_system
->SetLazyField(bind_object
, bind_name
, api_name
, "binding");
1338 // NOTE: please use the naming convention "foo_natives" for these.
1339 void Dispatcher::RegisterNativeHandlers(ModuleSystem
* module_system
,
1340 ScriptContext
* context
) {
1341 RegisterNativeHandlers(module_system
,
1344 request_sender_
.get(),
1345 v8_schema_registry_
.get());
1346 const Extension
* extension
= context
->extension();
1347 int manifest_version
= extension
? extension
->manifest_version() : 1;
1348 bool is_component_extension
=
1349 extension
&& Manifest::IsComponentLocation(extension
->location());
1350 bool send_request_disabled
=
1351 (extension
&& Manifest::IsUnpackedLocation(extension
->location()) &&
1352 BackgroundInfo::HasLazyBackgroundPage(extension
));
1353 module_system
->RegisterNativeHandler(
1355 scoped_ptr
<NativeHandler
>(new ProcessInfoNativeHandler(
1357 context
->GetExtensionID(),
1358 context
->GetContextTypeDescription(),
1359 ExtensionsRendererClient::Get()->IsIncognitoProcess(),
1360 is_component_extension
,
1362 send_request_disabled
)));
1364 delegate_
->RegisterNativeHandlers(this, module_system
, context
);
1367 bool Dispatcher::IsRuntimeAvailableToContext(ScriptContext
* context
) {
1368 if (extensions::FeatureSwitch::surface_worker()->IsEnabled() &&
1369 context
->GetAvailability("surfaceWorkerInternal").is_available()) {
1372 for (const auto& extension
: extensions_
) {
1373 ExternallyConnectableInfo
* info
= static_cast<ExternallyConnectableInfo
*>(
1374 extension
->GetManifestData(manifest_keys::kExternallyConnectable
));
1375 if (info
&& info
->matches
.MatchesURL(context
->GetURL()))
1381 void Dispatcher::UpdateContentCapabilities(ScriptContext
* context
) {
1382 APIPermissionSet permissions
;
1383 for (const auto& extension
: extensions_
) {
1384 const ContentCapabilitiesInfo
& info
=
1385 ContentCapabilitiesInfo::Get(extension
.get());
1386 if (info
.url_patterns
.MatchesURL(context
->GetURL())) {
1387 APIPermissionSet new_permissions
;
1388 APIPermissionSet::Union(permissions
, info
.permissions
, &new_permissions
);
1389 permissions
= new_permissions
;
1392 context
->SetContentCapabilities(permissions
);
1395 void Dispatcher::PopulateSourceMap() {
1396 const std::vector
<std::pair
<std::string
, int> > resources
= GetJsResources();
1397 for (std::vector
<std::pair
<std::string
, int> >::const_iterator resource
=
1399 resource
!= resources
.end();
1401 source_map_
.RegisterSource(resource
->first
, resource
->second
);
1403 delegate_
->PopulateSourceMap(&source_map_
);
1406 bool Dispatcher::IsWithinPlatformApp() {
1407 for (std::set
<std::string
>::iterator iter
= active_extension_ids_
.begin();
1408 iter
!= active_extension_ids_
.end();
1410 const Extension
* extension
= extensions_
.GetByID(*iter
);
1411 if (extension
&& extension
->is_platform_app())
1417 // TODO(kalman): This is checking for the wrong thing, it should be checking if
1418 // the frame's security origin is unique. The extension sandbox directive is
1419 // checked for in extensions/common/manifest_handlers/csp_info.cc.
1420 bool Dispatcher::IsSandboxedPage(const GURL
& url
) const {
1421 if (url
.SchemeIs(kExtensionScheme
)) {
1422 const Extension
* extension
= extensions_
.GetByID(url
.host());
1424 return SandboxedPageInfo::IsSandboxedPage(extension
, url
.path());
1430 Feature::Context
Dispatcher::ClassifyJavaScriptContext(
1431 const Extension
* extension
,
1432 int extension_group
,
1434 const blink::WebSecurityOrigin
& origin
) {
1435 // WARNING: This logic must match ProcessMap::GetContextType, as much as
1438 DCHECK_GE(extension_group
, 0);
1439 if (extension_group
== EXTENSION_GROUP_CONTENT_SCRIPTS
) {
1440 return extension
? // TODO(kalman): when does this happen?
1441 Feature::CONTENT_SCRIPT_CONTEXT
1442 : Feature::UNSPECIFIED_CONTEXT
;
1445 // We have an explicit check for sandboxed pages before checking whether the
1446 // extension is active in this process because:
1447 // 1. Sandboxed pages run in the same process as regular extension pages, so
1448 // the extension is considered active.
1449 // 2. ScriptContext creation (which triggers bindings injection) happens
1450 // before the SecurityContext is updated with the sandbox flags (after
1451 // reading the CSP header), so the caller can't check if the context's
1452 // security origin is unique yet.
1453 if (IsSandboxedPage(url
))
1454 return Feature::WEB_PAGE_CONTEXT
;
1456 if (extension
&& IsExtensionActive(extension
->id())) {
1457 // |extension| is active in this process, but it could be either a true
1458 // extension process or within the extent of a hosted app. In the latter
1459 // case this would usually be considered a (blessed) web page context,
1460 // unless the extension in question is a component extension, in which case
1461 // we cheat and call it blessed.
1462 return (extension
->is_hosted_app() &&
1463 extension
->location() != Manifest::COMPONENT
)
1464 ? Feature::BLESSED_WEB_PAGE_CONTEXT
1465 : Feature::BLESSED_EXTENSION_CONTEXT
;
1468 // TODO(kalman): This isUnique() check is wrong, it should be performed as
1469 // part of IsSandboxedPage().
1470 if (!origin
.isUnique() && extensions_
.ExtensionBindingsAllowed(url
)) {
1471 if (!extension
) // TODO(kalman): when does this happen?
1472 return Feature::UNSPECIFIED_CONTEXT
;
1473 return extension
->is_hosted_app() ? Feature::BLESSED_WEB_PAGE_CONTEXT
1474 : Feature::UNBLESSED_EXTENSION_CONTEXT
;
1477 if (!url
.is_valid())
1478 return Feature::UNSPECIFIED_CONTEXT
;
1480 if (url
.SchemeIs(content::kChromeUIScheme
))
1481 return Feature::WEBUI_CONTEXT
;
1483 return Feature::WEB_PAGE_CONTEXT
;
1486 v8::Handle
<v8::Object
> Dispatcher::GetOrCreateObject(
1487 const v8::Handle
<v8::Object
>& object
,
1488 const std::string
& field
,
1489 v8::Isolate
* isolate
) {
1490 v8::Handle
<v8::String
> key
= v8::String::NewFromUtf8(isolate
, field
.c_str());
1491 // If the object has a callback property, it is assumed it is an unavailable
1492 // API, so it is safe to delete. This is checked before GetOrCreateObject is
1494 if (object
->HasRealNamedCallbackProperty(key
)) {
1495 object
->Delete(key
);
1496 } else if (object
->HasRealNamedProperty(key
)) {
1497 v8::Handle
<v8::Value
> value
= object
->Get(key
);
1498 CHECK(value
->IsObject());
1499 return v8::Handle
<v8::Object
>::Cast(value
);
1502 v8::Handle
<v8::Object
> new_object
= v8::Object::New(isolate
);
1503 object
->Set(key
, new_object
);
1507 v8::Handle
<v8::Object
> Dispatcher::GetOrCreateBindObjectIfAvailable(
1508 const std::string
& api_name
,
1509 std::string
* bind_name
,
1510 ScriptContext
* context
) {
1511 std::vector
<std::string
> split
;
1512 base::SplitString(api_name
, '.', &split
);
1514 v8::Handle
<v8::Object
> bind_object
;
1516 // Check if this API has an ancestor. If the API's ancestor is available and
1517 // the API is not available, don't install the bindings for this API. If
1518 // the API is available and its ancestor is not, delete the ancestor and
1519 // install the bindings for the API. This is to prevent loading the ancestor
1520 // API schema if it will not be needed.
1523 // If app is available and app.window is not, just install app.
1524 // If app.window is available and app is not, delete app and install
1525 // app.window on a new object so app does not have to be loaded.
1526 const FeatureProvider
* api_feature_provider
=
1527 FeatureProvider::GetAPIFeatures();
1528 std::string ancestor_name
;
1529 bool only_ancestor_available
= false;
1531 for (size_t i
= 0; i
< split
.size() - 1; ++i
) {
1532 ancestor_name
+= (i
? "." : "") + split
[i
];
1533 if (api_feature_provider
->GetFeature(ancestor_name
) &&
1534 context
->GetAvailability(ancestor_name
).is_available() &&
1535 !context
->GetAvailability(api_name
).is_available()) {
1536 only_ancestor_available
= true;
1540 if (bind_object
.IsEmpty()) {
1541 bind_object
= AsObjectOrEmpty(GetOrCreateChrome(context
));
1542 if (bind_object
.IsEmpty())
1543 return v8::Handle
<v8::Object
>();
1545 bind_object
= GetOrCreateObject(bind_object
, split
[i
], context
->isolate());
1548 if (only_ancestor_available
)
1549 return v8::Handle
<v8::Object
>();
1552 *bind_name
= split
.back();
1554 return bind_object
.IsEmpty() ? AsObjectOrEmpty(GetOrCreateChrome(context
))
1558 } // namespace extensions