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/user_metrics_action.h"
13 #include "base/strings/string_piece.h"
14 #include "base/strings/string_split.h"
15 #include "base/strings/string_util.h"
16 #include "base/values.h"
17 #include "content/grit/content_resources.h"
18 #include "content/public/common/content_switches.h"
19 #include "content/public/common/url_constants.h"
20 #include "content/public/renderer/render_thread.h"
21 #include "content/public/renderer/render_view.h"
22 #include "content/public/renderer/v8_value_converter.h"
23 #include "extensions/common/api/messaging/message.h"
24 #include "extensions/common/constants.h"
25 #include "extensions/common/extension.h"
26 #include "extensions/common/extension_api.h"
27 #include "extensions/common/extension_messages.h"
28 #include "extensions/common/extension_urls.h"
29 #include "extensions/common/features/feature.h"
30 #include "extensions/common/features/feature_provider.h"
31 #include "extensions/common/manifest.h"
32 #include "extensions/common/manifest_constants.h"
33 #include "extensions/common/manifest_handlers/background_info.h"
34 #include "extensions/common/manifest_handlers/externally_connectable.h"
35 #include "extensions/common/manifest_handlers/options_page_info.h"
36 #include "extensions/common/manifest_handlers/sandboxed_page_info.h"
37 #include "extensions/common/message_bundle.h"
38 #include "extensions/common/permissions/permission_set.h"
39 #include "extensions/common/permissions/permissions_data.h"
40 #include "extensions/common/switches.h"
41 #include "extensions/common/view_type.h"
42 #include "extensions/renderer/api_activity_logger.h"
43 #include "extensions/renderer/api_definitions_natives.h"
44 #include "extensions/renderer/app_runtime_custom_bindings.h"
45 #include "extensions/renderer/app_window_custom_bindings.h"
46 #include "extensions/renderer/binding_generating_native_handler.h"
47 #include "extensions/renderer/blob_native_handler.h"
48 #include "extensions/renderer/content_watcher.h"
49 #include "extensions/renderer/context_menus_custom_bindings.h"
50 #include "extensions/renderer/css_native_handler.h"
51 #include "extensions/renderer/dispatcher_delegate.h"
52 #include "extensions/renderer/document_custom_bindings.h"
53 #include "extensions/renderer/dom_activity_logger.h"
54 #include "extensions/renderer/event_bindings.h"
55 #include "extensions/renderer/extension_groups.h"
56 #include "extensions/renderer/extension_helper.h"
57 #include "extensions/renderer/extensions_renderer_client.h"
58 #include "extensions/renderer/file_system_natives.h"
59 #include "extensions/renderer/guest_view/guest_view_internal_custom_bindings.h"
60 #include "extensions/renderer/i18n_custom_bindings.h"
61 #include "extensions/renderer/id_generator_custom_bindings.h"
62 #include "extensions/renderer/lazy_background_page_native_handler.h"
63 #include "extensions/renderer/logging_native_handler.h"
64 #include "extensions/renderer/messaging_bindings.h"
65 #include "extensions/renderer/module_system.h"
66 #include "extensions/renderer/print_native_handler.h"
67 #include "extensions/renderer/process_info_native_handler.h"
68 #include "extensions/renderer/render_view_observer_natives.h"
69 #include "extensions/renderer/request_sender.h"
70 #include "extensions/renderer/runtime_custom_bindings.h"
71 #include "extensions/renderer/safe_builtins.h"
72 #include "extensions/renderer/script_context.h"
73 #include "extensions/renderer/script_context_set.h"
74 #include "extensions/renderer/script_injection.h"
75 #include "extensions/renderer/script_injection_manager.h"
76 #include "extensions/renderer/send_request_natives.h"
77 #include "extensions/renderer/set_icon_natives.h"
78 #include "extensions/renderer/test_features_native_handler.h"
79 #include "extensions/renderer/user_gestures_native_handler.h"
80 #include "extensions/renderer/utils_native_handler.h"
81 #include "extensions/renderer/v8_context_native_handler.h"
82 #include "grit/extensions_renderer_resources.h"
83 #include "mojo/public/js/bindings/constants.h"
84 #include "third_party/WebKit/public/platform/WebString.h"
85 #include "third_party/WebKit/public/platform/WebURLRequest.h"
86 #include "third_party/WebKit/public/web/WebCustomElement.h"
87 #include "third_party/WebKit/public/web/WebDataSource.h"
88 #include "third_party/WebKit/public/web/WebDocument.h"
89 #include "third_party/WebKit/public/web/WebFrame.h"
90 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
91 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
92 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
93 #include "third_party/WebKit/public/web/WebView.h"
94 #include "ui/base/layout.h"
95 #include "ui/base/resource/resource_bundle.h"
96 #include "v8/include/v8.h"
98 using base::UserMetricsAction
;
99 using blink::WebDataSource
;
100 using blink::WebDocument
;
101 using blink::WebFrame
;
102 using blink::WebScopedUserGesture
;
103 using blink::WebSecurityPolicy
;
104 using blink::WebString
;
105 using blink::WebVector
;
106 using blink::WebView
;
107 using content::RenderThread
;
108 using content::RenderView
;
110 namespace extensions
{
114 static const int64 kInitialExtensionIdleHandlerDelayMs
= 5 * 1000;
115 static const int64 kMaxExtensionIdleHandlerDelayMs
= 5 * 60 * 1000;
116 static const char kEventDispatchFunction
[] = "dispatchEvent";
117 static const char kOnSuspendEvent
[] = "runtime.onSuspend";
118 static const char kOnSuspendCanceledEvent
[] = "runtime.onSuspendCanceled";
120 // Returns the global value for "chrome" from |context|. If one doesn't exist
121 // creates a new object for it.
123 // Note that this isn't necessarily an object, since webpages can write, for
124 // example, "window.chrome = true".
125 v8::Handle
<v8::Value
> GetOrCreateChrome(ScriptContext
* context
) {
126 v8::Handle
<v8::String
> chrome_string(
127 v8::String::NewFromUtf8(context
->isolate(), "chrome"));
128 v8::Handle
<v8::Object
> global(context
->v8_context()->Global());
129 v8::Handle
<v8::Value
> chrome(global
->Get(chrome_string
));
130 if (chrome
->IsUndefined()) {
131 chrome
= v8::Object::New(context
->isolate());
132 global
->Set(chrome_string
, chrome
);
137 // Returns |value| cast to an object if possible, else an empty handle.
138 v8::Handle
<v8::Object
> AsObjectOrEmpty(v8::Handle
<v8::Value
> value
) {
139 return value
->IsObject() ? value
.As
<v8::Object
>() : v8::Handle
<v8::Object
>();
142 // Calls a method |method_name| in a module |module_name| belonging to the
143 // module system from |context|. Intended as a callback target from
144 // ScriptContextSet::ForEach.
145 void CallModuleMethod(const std::string
& module_name
,
146 const std::string
& method_name
,
147 const base::ListValue
* args
,
148 ScriptContext
* context
) {
149 v8::HandleScope
handle_scope(context
->isolate());
150 v8::Context::Scope
context_scope(context
->v8_context());
152 scoped_ptr
<content::V8ValueConverter
> converter(
153 content::V8ValueConverter::create());
155 std::vector
<v8::Handle
<v8::Value
> > arguments
;
156 for (base::ListValue::const_iterator it
= args
->begin(); it
!= args
->end();
158 arguments
.push_back(converter
->ToV8Value(*it
, context
->v8_context()));
161 context
->module_system()->CallModuleMethod(
162 module_name
, method_name
, &arguments
);
165 // This handles the "chrome." root API object in script contexts.
166 class ChromeNativeHandler
: public ObjectBackedNativeHandler
{
168 explicit ChromeNativeHandler(ScriptContext
* context
)
169 : ObjectBackedNativeHandler(context
) {
172 base::Bind(&ChromeNativeHandler::GetChrome
, base::Unretained(this)));
175 void GetChrome(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
176 args
.GetReturnValue().Set(GetOrCreateChrome(context()));
182 Dispatcher::Dispatcher(DispatcherDelegate
* delegate
)
183 : delegate_(delegate
),
184 content_watcher_(new ContentWatcher()),
185 source_map_(&ResourceBundle::GetSharedInstance()),
186 v8_schema_registry_(new V8SchemaRegistry
),
187 is_webkit_initialized_(false),
188 user_script_set_manager_observer_(this),
189 webrequest_used_(false) {
190 const CommandLine
& command_line
= *(CommandLine::ForCurrentProcess());
191 is_extension_process_
=
192 command_line
.HasSwitch(extensions::switches::kExtensionProcess
) ||
193 command_line
.HasSwitch(::switches::kSingleProcess
);
195 if (is_extension_process_
) {
196 RenderThread::Get()->SetIdleNotificationDelayInMs(
197 kInitialExtensionIdleHandlerDelayMs
);
200 RenderThread::Get()->RegisterExtension(SafeBuiltins::CreateV8Extension());
202 user_script_set_manager_
.reset(new UserScriptSetManager(&extensions_
));
203 script_injection_manager_
.reset(
204 new ScriptInjectionManager(&extensions_
, user_script_set_manager_
.get()));
205 user_script_set_manager_observer_
.Add(user_script_set_manager_
.get());
206 request_sender_
.reset(new RequestSender(this));
210 Dispatcher::~Dispatcher() {
213 void Dispatcher::OnRenderViewCreated(content::RenderView
* render_view
) {
214 script_injection_manager_
->OnRenderViewCreated(render_view
);
217 bool Dispatcher::IsExtensionActive(const std::string
& extension_id
) const {
219 active_extension_ids_
.find(extension_id
) != active_extension_ids_
.end();
221 CHECK(extensions_
.Contains(extension_id
));
225 const Extension
* Dispatcher::GetExtensionFromFrameAndWorld(
226 const WebFrame
* frame
,
228 bool use_effective_url
) {
229 std::string extension_id
;
231 // Isolated worlds (content script).
232 extension_id
= ScriptInjection::GetExtensionIdForIsolatedWorld(world_id
);
233 } else if (!frame
->document().securityOrigin().isUnique()) {
234 // TODO(kalman): Delete the above check.
236 // Extension pages (chrome-extension:// URLs).
237 GURL frame_url
= ScriptContext::GetDataSourceURLForFrame(frame
);
238 frame_url
= ScriptContext::GetEffectiveDocumentURL(
239 frame
, frame_url
, use_effective_url
);
240 extension_id
= extensions_
.GetExtensionOrAppIDByURL(frame_url
);
243 const Extension
* extension
= extensions_
.GetByID(extension_id
);
244 if (!extension
&& !extension_id
.empty()) {
245 // There are conditions where despite a context being associated with an
246 // extension, no extension actually gets found. Ignore "invalid" because
247 // CSP blocks extension page loading by switching the extension ID to
248 // "invalid". This isn't interesting.
249 if (extension_id
!= "invalid") {
250 LOG(ERROR
) << "Extension \"" << extension_id
<< "\" not found";
251 RenderThread::Get()->RecordAction(
252 UserMetricsAction("ExtensionNotFound_ED"));
258 void Dispatcher::DidCreateScriptContext(
260 const v8::Handle
<v8::Context
>& v8_context
,
263 #if !defined(ENABLE_EXTENSIONS)
267 const Extension
* extension
=
268 GetExtensionFromFrameAndWorld(frame
, world_id
, false);
269 const Extension
* effective_extension
=
270 GetExtensionFromFrameAndWorld(frame
, world_id
, true);
272 GURL frame_url
= ScriptContext::GetDataSourceURLForFrame(frame
);
273 Feature::Context context_type
=
274 ClassifyJavaScriptContext(extension
,
277 frame
->document().securityOrigin());
278 Feature::Context effective_context_type
= ClassifyJavaScriptContext(
281 ScriptContext::GetEffectiveDocumentURL(frame
, frame_url
, true),
282 frame
->document().securityOrigin());
284 ScriptContext
* context
=
285 delegate_
->CreateScriptContext(v8_context
,
290 effective_context_type
).release();
291 script_context_set_
.Add(context
);
293 // Initialize origin permissions for content scripts, which can't be
294 // initialized in |OnActivateExtension|.
295 if (context_type
== Feature::CONTENT_SCRIPT_CONTEXT
)
296 InitOriginPermissions(extension
);
299 scoped_ptr
<ModuleSystem
> module_system(
300 new ModuleSystem(context
, &source_map_
));
301 context
->set_module_system(module_system
.Pass());
303 ModuleSystem
* module_system
= context
->module_system();
305 // Enable natives in startup.
306 ModuleSystem::NativesEnabledScope
natives_enabled_scope(module_system
);
308 RegisterNativeHandlers(module_system
, context
);
310 // chrome.Event is part of the public API (although undocumented). Make it
311 // lazily evalulate to Event from event_bindings.js. For extensions only
312 // though, not all webpages!
313 if (context
->extension()) {
314 v8::Handle
<v8::Object
> chrome
= AsObjectOrEmpty(GetOrCreateChrome(context
));
315 if (!chrome
.IsEmpty())
316 module_system
->SetLazyField(chrome
, "Event", kEventBindings
, "Event");
319 UpdateBindingsForContext(context
);
321 bool is_within_platform_app
= IsWithinPlatformApp();
322 // Inject custom JS into the platform app context.
323 if (is_within_platform_app
) {
324 module_system
->Require("platformApp");
327 if (context
->GetAvailability("appViewEmbedderInternal").is_available()) {
328 module_system
->Require("appView");
329 } else if (context_type
== extensions::Feature::BLESSED_EXTENSION_CONTEXT
) {
330 module_system
->Require("denyAppView");
333 // Note: setting up the WebView class here, not the chrome.webview API.
334 // The API will be automatically set up when first used.
335 if (context
->GetAvailability("webViewInternal").is_available()) {
336 module_system
->Require("webView");
337 module_system
->Require("webViewConstants");
338 module_system
->Require("webViewAttributes");
339 if (context
->GetAvailability("webViewExperimentalInternal")
341 module_system
->Require("webViewExperimental");
343 } else if (context_type
== extensions::Feature::BLESSED_EXTENSION_CONTEXT
) {
344 module_system
->Require("denyWebView");
347 delegate_
->RequireAdditionalModules(context
, is_within_platform_app
);
349 VLOG(1) << "Num tracked contexts: " << script_context_set_
.size();
352 void Dispatcher::WillReleaseScriptContext(
354 const v8::Handle
<v8::Context
>& v8_context
,
356 ScriptContext
* context
= script_context_set_
.GetByV8Context(v8_context
);
360 context
->DispatchOnUnloadEvent();
361 // TODO(kalman): add an invalidation observer interface to ScriptContext.
362 request_sender_
->InvalidateSource(context
);
364 script_context_set_
.Remove(context
);
365 VLOG(1) << "Num tracked contexts: " << script_context_set_
.size();
368 void Dispatcher::DidCreateDocumentElement(blink::WebFrame
* frame
) {
369 // Note: use GetEffectiveDocumentURL not just frame->document()->url()
370 // so that this also injects the stylesheet on about:blank frames that
371 // are hosted in the extension process.
372 GURL effective_document_url
= ScriptContext::GetEffectiveDocumentURL(
373 frame
, frame
->document().url(), true /* match_about_blank */);
375 const Extension
* extension
=
376 extensions_
.GetExtensionOrAppByURL(effective_document_url
);
379 (extension
->is_extension() || extension
->is_platform_app())) {
380 int resource_id
= extension
->is_platform_app() ? IDR_PLATFORM_APP_CSS
381 : IDR_EXTENSION_FONTS_CSS
;
382 std::string stylesheet
= ResourceBundle::GetSharedInstance()
383 .GetRawDataResource(resource_id
)
385 ReplaceFirstSubstringAfterOffset(
386 &stylesheet
, 0, "$FONTFAMILY", system_font_family_
);
387 ReplaceFirstSubstringAfterOffset(
388 &stylesheet
, 0, "$FONTSIZE", system_font_size_
);
390 // Blink doesn't let us define an additional user agent stylesheet, so
391 // we insert the default platform app or extension stylesheet into all
392 // documents that are loaded in each app or extension.
393 frame
->document().insertStyleSheet(WebString::fromUTF8(stylesheet
));
396 // This preprocessor directive is because this file is still built in Android
397 // builds, but OptionsPageInfo is not. For Android builds, exclude this block
398 // of code to prevent link errors.
399 #if defined(ENABLE_EXTENSIONS)
400 // If this is an extension options page, and the extension has opted into
401 // using Chrome styles, then insert the Chrome extension stylesheet.
402 if (extension
&& extension
->is_extension() &&
403 OptionsPageInfo::ShouldUseChromeStyle(extension
) &&
404 effective_document_url
== OptionsPageInfo::GetOptionsPage(extension
)) {
405 frame
->document().insertStyleSheet(
406 WebString::fromUTF8(ResourceBundle::GetSharedInstance()
407 .GetRawDataResource(IDR_EXTENSION_CSS
)
412 content_watcher_
->DidCreateDocumentElement(frame
);
415 void Dispatcher::DidMatchCSS(
416 blink::WebFrame
* frame
,
417 const blink::WebVector
<blink::WebString
>& newly_matching_selectors
,
418 const blink::WebVector
<blink::WebString
>& stopped_matching_selectors
) {
419 content_watcher_
->DidMatchCSS(
420 frame
, newly_matching_selectors
, stopped_matching_selectors
);
423 void Dispatcher::OnExtensionResponse(int request_id
,
425 const base::ListValue
& response
,
426 const std::string
& error
) {
427 request_sender_
->HandleResponse(request_id
, success
, response
, error
);
430 bool Dispatcher::CheckContextAccessToExtensionAPI(
431 const std::string
& function_name
,
432 ScriptContext
* context
) const {
434 DLOG(ERROR
) << "Not in a v8::Context";
438 // Theoretically we could end up with bindings being injected into sandboxed
439 // frames, for example content scripts. Don't let them execute API functions.
440 blink::WebFrame
* frame
= context
->web_frame();
441 if (IsSandboxedPage(ScriptContext::GetDataSourceURLForFrame(frame
))) {
442 static const char kMessage
[] =
443 "%s cannot be used within a sandboxed frame.";
444 std::string error_msg
= base::StringPrintf(kMessage
, function_name
.c_str());
445 context
->isolate()->ThrowException(v8::Exception::Error(
446 v8::String::NewFromUtf8(context
->isolate(), error_msg
.c_str())));
450 Feature::Availability availability
= context
->GetAvailability(function_name
);
451 if (!availability
.is_available()) {
452 context
->isolate()->ThrowException(
453 v8::Exception::Error(v8::String::NewFromUtf8(
454 context
->isolate(), availability
.message().c_str())));
457 return availability
.is_available();
460 void Dispatcher::DispatchEvent(const std::string
& extension_id
,
461 const std::string
& event_name
) const {
462 base::ListValue args
;
463 args
.Set(0, new base::StringValue(event_name
));
464 args
.Set(1, new base::ListValue());
466 // Needed for Windows compilation, since kEventBindings is declared extern.
467 const char* local_event_bindings
= kEventBindings
;
468 script_context_set_
.ForEach(extension_id
,
469 base::Bind(&CallModuleMethod
,
470 local_event_bindings
,
471 kEventDispatchFunction
,
475 void Dispatcher::InvokeModuleSystemMethod(content::RenderView
* render_view
,
476 const std::string
& extension_id
,
477 const std::string
& module_name
,
478 const std::string
& function_name
,
479 const base::ListValue
& args
,
481 scoped_ptr
<WebScopedUserGesture
> web_user_gesture
;
483 web_user_gesture
.reset(new WebScopedUserGesture
);
485 script_context_set_
.ForEach(
488 base::Bind(&CallModuleMethod
, module_name
, function_name
, &args
));
490 // Reset the idle handler each time there's any activity like event or message
491 // dispatch, for which Invoke is the chokepoint.
492 if (is_extension_process_
) {
493 RenderThread::Get()->ScheduleIdleHandler(
494 kInitialExtensionIdleHandlerDelayMs
);
497 // Tell the browser process when an event has been dispatched with a lazy
498 // background page active.
499 const Extension
* extension
= extensions_
.GetByID(extension_id
);
500 if (extension
&& BackgroundInfo::HasLazyBackgroundPage(extension
) &&
501 module_name
== kEventBindings
&&
502 function_name
== kEventDispatchFunction
) {
503 RenderView
* background_view
=
504 ExtensionHelper::GetBackgroundPage(extension_id
);
505 if (background_view
) {
506 background_view
->Send(
507 new ExtensionHostMsg_EventAck(background_view
->GetRoutingID()));
512 void Dispatcher::ClearPortData(int port_id
) {
513 // Only the target port side has entries in |port_to_tab_id_map_|. If
514 // |port_id| is a source port, std::map::erase() will just silently fail
516 port_to_tab_id_map_
.erase(port_id
);
520 std::vector
<std::pair
<std::string
, int> > Dispatcher::GetJsResources() {
521 std::vector
<std::pair
<std::string
, int> > resources
;
524 resources
.push_back(std::make_pair("appView", IDR_APP_VIEW_JS
));
525 resources
.push_back(std::make_pair("denyAppView", IDR_APP_VIEW_DENY_JS
));
526 resources
.push_back(std::make_pair("entryIdManager", IDR_ENTRY_ID_MANAGER
));
527 resources
.push_back(std::make_pair(kEventBindings
, IDR_EVENT_BINDINGS_JS
));
528 resources
.push_back(std::make_pair("imageUtil", IDR_IMAGE_UTIL_JS
));
529 resources
.push_back(std::make_pair("json_schema", IDR_JSON_SCHEMA_JS
));
530 resources
.push_back(std::make_pair("lastError", IDR_LAST_ERROR_JS
));
531 resources
.push_back(std::make_pair("messaging", IDR_MESSAGING_JS
));
533 std::make_pair("messaging_utils", IDR_MESSAGING_UTILS_JS
));
534 resources
.push_back(std::make_pair(kSchemaUtils
, IDR_SCHEMA_UTILS_JS
));
535 resources
.push_back(std::make_pair("sendRequest", IDR_SEND_REQUEST_JS
));
536 resources
.push_back(std::make_pair("setIcon", IDR_SET_ICON_JS
));
537 resources
.push_back(std::make_pair("test", IDR_TEST_CUSTOM_BINDINGS_JS
));
539 std::make_pair("test_environment_specific_bindings",
540 IDR_BROWSER_TEST_ENVIRONMENT_SPECIFIC_BINDINGS_JS
));
541 resources
.push_back(std::make_pair("uncaught_exception_handler",
542 IDR_UNCAUGHT_EXCEPTION_HANDLER_JS
));
543 resources
.push_back(std::make_pair("unload_event", IDR_UNLOAD_EVENT_JS
));
544 resources
.push_back(std::make_pair("utils", IDR_UTILS_JS
));
545 resources
.push_back(std::make_pair("webRequest",
546 IDR_WEB_REQUEST_CUSTOM_BINDINGS_JS
));
548 std::make_pair("webRequestInternal",
549 IDR_WEB_REQUEST_INTERNAL_CUSTOM_BINDINGS_JS
));
550 // Note: webView not webview so that this doesn't interfere with the
551 // chrome.webview API bindings.
552 resources
.push_back(std::make_pair("webView", IDR_WEB_VIEW_JS
));
553 resources
.push_back(std::make_pair("webViewAttributes",
554 IDR_WEB_VIEW_ATTRIBUTES_JS
));
555 resources
.push_back(std::make_pair("webViewConstants",
556 IDR_WEB_VIEW_CONSTANTS_JS
));
557 resources
.push_back(std::make_pair("webViewEvents", IDR_WEB_VIEW_EVENTS_JS
));
559 std::make_pair("webViewExperimental", IDR_WEB_VIEW_EXPERIMENTAL_JS
));
560 resources
.push_back(std::make_pair("webViewInternal",
561 IDR_WEB_VIEW_INTERNAL_CUSTOM_BINDINGS_JS
));
562 resources
.push_back(std::make_pair("denyWebView", IDR_WEB_VIEW_DENY_JS
));
564 std::make_pair(mojo::kBufferModuleName
, IDR_MOJO_BUFFER_JS
));
566 std::make_pair(mojo::kCodecModuleName
, IDR_MOJO_CODEC_JS
));
568 std::make_pair(mojo::kConnectionModuleName
, IDR_MOJO_CONNECTION_JS
));
570 std::make_pair(mojo::kConnectorModuleName
, IDR_MOJO_CONNECTOR_JS
));
572 std::make_pair(mojo::kRouterModuleName
, IDR_MOJO_ROUTER_JS
));
574 std::make_pair(mojo::kUnicodeModuleName
, IDR_MOJO_UNICODE_JS
));
576 std::make_pair(mojo::kValidatorModuleName
, IDR_MOJO_VALIDATOR_JS
));
577 resources
.push_back(std::make_pair("async_waiter", IDR_ASYNC_WAITER_JS
));
578 resources
.push_back(std::make_pair("data_receiver", IDR_DATA_RECEIVER_JS
));
579 resources
.push_back(std::make_pair("data_sender", IDR_DATA_SENDER_JS
));
580 resources
.push_back(std::make_pair("keep_alive", IDR_KEEP_ALIVE_JS
));
581 resources
.push_back(std::make_pair("extensions/common/mojo/keep_alive.mojom",
582 IDR_KEEP_ALIVE_MOJOM_JS
));
583 resources
.push_back(std::make_pair("device/serial/data_stream.mojom",
584 IDR_DATA_STREAM_MOJOM_JS
));
586 std::make_pair("device/serial/data_stream_serialization.mojom",
587 IDR_DATA_STREAM_SERIALIZATION_MOJOM_JS
));
591 std::make_pair("app.runtime", IDR_APP_RUNTIME_CUSTOM_BINDINGS_JS
));
593 std::make_pair("app.window", IDR_APP_WINDOW_CUSTOM_BINDINGS_JS
));
595 std::make_pair("declarativeWebRequest",
596 IDR_DECLARATIVE_WEBREQUEST_CUSTOM_BINDINGS_JS
));
598 std::make_pair("contextMenus", IDR_CONTEXT_MENUS_CUSTOM_BINDINGS_JS
));
600 std::make_pair("extension", IDR_EXTENSION_CUSTOM_BINDINGS_JS
));
601 resources
.push_back(std::make_pair("i18n", IDR_I18N_CUSTOM_BINDINGS_JS
));
603 std::make_pair("permissions", IDR_PERMISSIONS_CUSTOM_BINDINGS_JS
));
605 std::make_pair("runtime", IDR_RUNTIME_CUSTOM_BINDINGS_JS
));
606 resources
.push_back(std::make_pair("windowControls", IDR_WINDOW_CONTROLS_JS
));
608 std::make_pair("webViewRequest",
609 IDR_WEB_VIEW_REQUEST_CUSTOM_BINDINGS_JS
));
610 resources
.push_back(std::make_pair("binding", IDR_BINDING_JS
));
612 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
613 switches::kEnableMojoSerialService
)) {
615 std::make_pair("serial", IDR_SERIAL_CUSTOM_BINDINGS_JS
));
617 resources
.push_back(std::make_pair("serial_service", IDR_SERIAL_SERVICE_JS
));
619 std::make_pair("device/serial/serial.mojom", IDR_SERIAL_MOJOM_JS
));
620 resources
.push_back(std::make_pair("device/serial/serial_serialization.mojom",
621 IDR_SERIAL_SERIALIZATION_MOJOM_JS
));
623 // Custom types sources.
624 resources
.push_back(std::make_pair("StorageArea", IDR_STORAGE_AREA_JS
));
626 // Platform app sources that are not API-specific..
627 resources
.push_back(std::make_pair("platformApp", IDR_PLATFORM_APP_JS
));
632 // NOTE: please use the naming convention "foo_natives" for these.
634 void Dispatcher::RegisterNativeHandlers(ModuleSystem
* module_system
,
635 ScriptContext
* context
,
636 Dispatcher
* dispatcher
,
637 RequestSender
* request_sender
,
638 V8SchemaRegistry
* v8_schema_registry
) {
639 module_system
->RegisterNativeHandler(
640 "chrome", scoped_ptr
<NativeHandler
>(new ChromeNativeHandler(context
)));
641 module_system
->RegisterNativeHandler(
642 "lazy_background_page",
643 scoped_ptr
<NativeHandler
>(new LazyBackgroundPageNativeHandler(context
)));
644 module_system
->RegisterNativeHandler(
645 "logging", scoped_ptr
<NativeHandler
>(new LoggingNativeHandler(context
)));
646 module_system
->RegisterNativeHandler("schema_registry",
647 v8_schema_registry
->AsNativeHandler());
648 module_system
->RegisterNativeHandler(
649 "print", scoped_ptr
<NativeHandler
>(new PrintNativeHandler(context
)));
650 module_system
->RegisterNativeHandler(
652 scoped_ptr
<NativeHandler
>(new TestFeaturesNativeHandler(context
)));
653 module_system
->RegisterNativeHandler(
655 scoped_ptr
<NativeHandler
>(new UserGesturesNativeHandler(context
)));
656 module_system
->RegisterNativeHandler(
657 "utils", scoped_ptr
<NativeHandler
>(new UtilsNativeHandler(context
)));
658 module_system
->RegisterNativeHandler(
660 scoped_ptr
<NativeHandler
>(
661 new V8ContextNativeHandler(context
, dispatcher
)));
662 module_system
->RegisterNativeHandler(
664 scoped_ptr
<NativeHandler
>(new EventBindings(dispatcher
, context
)));
665 module_system
->RegisterNativeHandler(
667 scoped_ptr
<NativeHandler
>(MessagingBindings::Get(dispatcher
, context
)));
668 module_system
->RegisterNativeHandler(
670 scoped_ptr
<NativeHandler
>(
671 new ApiDefinitionsNatives(dispatcher
, context
)));
672 module_system
->RegisterNativeHandler(
674 scoped_ptr
<NativeHandler
>(
675 new SendRequestNatives(request_sender
, context
)));
676 module_system
->RegisterNativeHandler(
678 scoped_ptr
<NativeHandler
>(new SetIconNatives(request_sender
, context
)));
679 module_system
->RegisterNativeHandler(
681 scoped_ptr
<NativeHandler
>(new APIActivityLogger(context
)));
682 module_system
->RegisterNativeHandler(
683 "renderViewObserverNatives",
684 scoped_ptr
<NativeHandler
>(new RenderViewObserverNatives(context
)));
686 // Natives used by multiple APIs.
687 module_system
->RegisterNativeHandler(
688 "file_system_natives",
689 scoped_ptr
<NativeHandler
>(new FileSystemNatives(context
)));
692 module_system
->RegisterNativeHandler(
694 scoped_ptr
<NativeHandler
>(new AppRuntimeCustomBindings(context
)));
695 module_system
->RegisterNativeHandler(
696 "app_window_natives",
697 scoped_ptr
<NativeHandler
>(
698 new AppWindowCustomBindings(dispatcher
, context
)));
699 module_system
->RegisterNativeHandler(
701 scoped_ptr
<NativeHandler
>(new BlobNativeHandler(context
)));
702 module_system
->RegisterNativeHandler(
704 scoped_ptr
<NativeHandler
>(new ContextMenusCustomBindings(context
)));
705 module_system
->RegisterNativeHandler(
706 "css_natives", scoped_ptr
<NativeHandler
>(new CssNativeHandler(context
)));
707 module_system
->RegisterNativeHandler(
709 scoped_ptr
<NativeHandler
>(new DocumentCustomBindings(context
)));
710 module_system
->RegisterNativeHandler(
711 "guest_view_internal",
712 scoped_ptr
<NativeHandler
>(
713 new GuestViewInternalCustomBindings(context
)));
714 module_system
->RegisterNativeHandler(
715 "i18n", scoped_ptr
<NativeHandler
>(new I18NCustomBindings(context
)));
716 module_system
->RegisterNativeHandler(
718 scoped_ptr
<NativeHandler
>(new IdGeneratorCustomBindings(context
)));
719 module_system
->RegisterNativeHandler(
720 "runtime", scoped_ptr
<NativeHandler
>(new RuntimeCustomBindings(context
)));
723 bool Dispatcher::OnControlMessageReceived(const IPC::Message
& message
) {
725 IPC_BEGIN_MESSAGE_MAP(Dispatcher
, message
)
726 IPC_MESSAGE_HANDLER(ExtensionMsg_ActivateExtension
, OnActivateExtension
)
727 IPC_MESSAGE_HANDLER(ExtensionMsg_CancelSuspend
, OnCancelSuspend
)
728 IPC_MESSAGE_HANDLER(ExtensionMsg_ClearTabSpecificPermissions
,
729 OnClearTabSpecificPermissions
)
730 IPC_MESSAGE_HANDLER(ExtensionMsg_DeliverMessage
, OnDeliverMessage
)
731 IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnConnect
, OnDispatchOnConnect
)
732 IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnDisconnect
, OnDispatchOnDisconnect
)
733 IPC_MESSAGE_HANDLER(ExtensionMsg_Loaded
, OnLoaded
)
734 IPC_MESSAGE_HANDLER(ExtensionMsg_MessageInvoke
, OnMessageInvoke
)
735 IPC_MESSAGE_HANDLER(ExtensionMsg_SetChannel
, OnSetChannel
)
736 IPC_MESSAGE_HANDLER(ExtensionMsg_SetFunctionNames
, OnSetFunctionNames
)
737 IPC_MESSAGE_HANDLER(ExtensionMsg_SetScriptingWhitelist
,
738 OnSetScriptingWhitelist
)
739 IPC_MESSAGE_HANDLER(ExtensionMsg_SetSystemFont
, OnSetSystemFont
)
740 IPC_MESSAGE_HANDLER(ExtensionMsg_ShouldSuspend
, OnShouldSuspend
)
741 IPC_MESSAGE_HANDLER(ExtensionMsg_Suspend
, OnSuspend
)
742 IPC_MESSAGE_HANDLER(ExtensionMsg_TransferBlobs
, OnTransferBlobs
)
743 IPC_MESSAGE_HANDLER(ExtensionMsg_Unloaded
, OnUnloaded
)
744 IPC_MESSAGE_HANDLER(ExtensionMsg_UpdatePermissions
, OnUpdatePermissions
)
745 IPC_MESSAGE_HANDLER(ExtensionMsg_UpdateTabSpecificPermissions
,
746 OnUpdateTabSpecificPermissions
)
747 IPC_MESSAGE_HANDLER(ExtensionMsg_UsingWebRequestAPI
, OnUsingWebRequestAPI
)
748 IPC_MESSAGE_FORWARD(ExtensionMsg_WatchPages
,
749 content_watcher_
.get(),
750 ContentWatcher::OnWatchPages
)
751 IPC_MESSAGE_UNHANDLED(handled
= false)
752 IPC_END_MESSAGE_MAP()
757 void Dispatcher::WebKitInitialized() {
758 // For extensions, we want to ensure we call the IdleHandler every so often,
759 // even if the extension keeps up activity.
760 if (is_extension_process_
) {
761 forced_idle_timer_
.reset(new base::RepeatingTimer
<content::RenderThread
>);
762 forced_idle_timer_
->Start(
764 base::TimeDelta::FromMilliseconds(kMaxExtensionIdleHandlerDelayMs
),
766 &RenderThread::IdleHandler
);
769 // Initialize host permissions for any extensions that were activated before
770 // WebKit was initialized.
771 for (std::set
<std::string
>::iterator iter
= active_extension_ids_
.begin();
772 iter
!= active_extension_ids_
.end();
774 const Extension
* extension
= extensions_
.GetByID(*iter
);
777 InitOriginPermissions(extension
);
780 EnableCustomElementWhiteList();
782 is_webkit_initialized_
= true;
785 void Dispatcher::IdleNotification() {
786 if (is_extension_process_
&& forced_idle_timer_
) {
787 // Dampen the forced delay as well if the extension stays idle for long
788 // periods of time. (forced_idle_timer_ can be NULL after
789 // OnRenderProcessShutdown has been called.)
790 int64 forced_delay_ms
=
791 std::max(RenderThread::Get()->GetIdleNotificationDelayInMs(),
792 kMaxExtensionIdleHandlerDelayMs
);
793 forced_idle_timer_
->Stop();
794 forced_idle_timer_
->Start(
796 base::TimeDelta::FromMilliseconds(forced_delay_ms
),
798 &RenderThread::IdleHandler
);
802 void Dispatcher::OnRenderProcessShutdown() {
803 v8_schema_registry_
.reset();
804 forced_idle_timer_
.reset();
807 void Dispatcher::OnActivateExtension(const std::string
& extension_id
) {
808 const Extension
* extension
= extensions_
.GetByID(extension_id
);
810 // Extension was activated but was never loaded. This probably means that
811 // the renderer failed to load it (or the browser failed to tell us when it
812 // did). Failures shouldn't happen, but instead of crashing there (which
813 // executes on all renderers) be conservative and only crash in the renderer
814 // of the extension which failed to load; this one.
815 std::string
& error
= extension_load_errors_
[extension_id
];
817 base::debug::Alias(&minidump
);
818 base::snprintf(minidump
,
820 "e::dispatcher:%s:%s",
821 extension_id
.c_str(),
823 CHECK(extension
) << extension_id
<< " was never loaded: " << error
;
826 active_extension_ids_
.insert(extension_id
);
828 // This is called when starting a new extension page, so start the idle
830 RenderThread::Get()->ScheduleIdleHandler(kInitialExtensionIdleHandlerDelayMs
);
832 if (is_webkit_initialized_
) {
833 extensions::DOMActivityLogger::AttachToWorld(
834 extensions::DOMActivityLogger::kMainWorldId
, extension_id
);
836 InitOriginPermissions(extension
);
839 UpdateActiveExtensions();
842 void Dispatcher::OnCancelSuspend(const std::string
& extension_id
) {
843 DispatchEvent(extension_id
, kOnSuspendCanceledEvent
);
846 void Dispatcher::OnClearTabSpecificPermissions(
848 const std::vector
<std::string
>& extension_ids
) {
849 delegate_
->ClearTabSpecificPermissions(this, tab_id
, extension_ids
);
852 void Dispatcher::OnDeliverMessage(int target_port_id
, const Message
& message
) {
853 scoped_ptr
<RequestSender::ScopedTabID
> scoped_tab_id
;
854 std::map
<int, int>::const_iterator it
=
855 port_to_tab_id_map_
.find(target_port_id
);
856 if (it
!= port_to_tab_id_map_
.end()) {
858 new RequestSender::ScopedTabID(request_sender(), it
->second
));
861 MessagingBindings::DeliverMessage(script_context_set_
,
864 NULL
); // All render views.
867 void Dispatcher::OnDispatchOnConnect(
869 const std::string
& channel_name
,
870 const base::DictionaryValue
& source_tab
,
871 const ExtensionMsg_ExternalConnectionInfo
& info
,
872 const std::string
& tls_channel_id
) {
873 DCHECK(!ContainsKey(port_to_tab_id_map_
, target_port_id
));
874 DCHECK_EQ(1, target_port_id
% 2); // target renderer ports have odd IDs.
875 int sender_tab_id
= -1;
876 source_tab
.GetInteger("id", &sender_tab_id
);
877 port_to_tab_id_map_
[target_port_id
] = sender_tab_id
;
879 MessagingBindings::DispatchOnConnect(script_context_set_
,
885 NULL
); // All render views.
888 void Dispatcher::OnDispatchOnDisconnect(int port_id
,
889 const std::string
& error_message
) {
890 MessagingBindings::DispatchOnDisconnect(script_context_set_
,
893 NULL
); // All render views.
896 void Dispatcher::OnLoaded(
897 const std::vector
<ExtensionMsg_Loaded_Params
>& loaded_extensions
) {
898 std::vector
<ExtensionMsg_Loaded_Params
>::const_iterator i
;
899 for (i
= loaded_extensions
.begin(); i
!= loaded_extensions
.end(); ++i
) {
901 scoped_refptr
<const Extension
> extension
= i
->ConvertToExtension(&error
);
902 if (!extension
.get()) {
903 extension_load_errors_
[i
->id
] = error
;
906 OnLoadedInternal(extension
);
908 // Update the available bindings for all contexts. These may have changed if
909 // an externally_connectable extension was loaded that can connect to an
914 void Dispatcher::OnLoadedInternal(scoped_refptr
<const Extension
> extension
) {
915 extensions_
.Insert(extension
);
918 void Dispatcher::OnMessageInvoke(const std::string
& extension_id
,
919 const std::string
& module_name
,
920 const std::string
& function_name
,
921 const base::ListValue
& args
,
923 InvokeModuleSystemMethod(
924 NULL
, extension_id
, module_name
, function_name
, args
, user_gesture
);
927 void Dispatcher::OnSetChannel(int channel
) {
928 delegate_
->SetChannel(channel
);
931 void Dispatcher::OnSetFunctionNames(const std::vector
<std::string
>& names
) {
932 function_names_
.clear();
933 for (size_t i
= 0; i
< names
.size(); ++i
)
934 function_names_
.insert(names
[i
]);
937 void Dispatcher::OnSetScriptingWhitelist(
938 const ExtensionsClient::ScriptingWhitelist
& extension_ids
) {
939 ExtensionsClient::Get()->SetScriptingWhitelist(extension_ids
);
942 void Dispatcher::OnSetSystemFont(const std::string
& font_family
,
943 const std::string
& font_size
) {
944 system_font_family_
= font_family
;
945 system_font_size_
= font_size
;
948 void Dispatcher::OnShouldSuspend(const std::string
& extension_id
,
949 uint64 sequence_id
) {
950 RenderThread::Get()->Send(
951 new ExtensionHostMsg_ShouldSuspendAck(extension_id
, sequence_id
));
954 void Dispatcher::OnSuspend(const std::string
& extension_id
) {
955 // Dispatch the suspend event. This doesn't go through the standard event
956 // dispatch machinery because it requires special handling. We need to let
957 // the browser know when we are starting and stopping the event dispatch, so
958 // that it still considers the extension idle despite any activity the suspend
960 DispatchEvent(extension_id
, kOnSuspendEvent
);
961 RenderThread::Get()->Send(new ExtensionHostMsg_SuspendAck(extension_id
));
964 void Dispatcher::OnTransferBlobs(const std::vector
<std::string
>& blob_uuids
) {
965 RenderThread::Get()->Send(new ExtensionHostMsg_TransferBlobsAck(blob_uuids
));
968 void Dispatcher::OnUnloaded(const std::string
& id
) {
969 extensions_
.Remove(id
);
970 active_extension_ids_
.erase(id
);
972 // If the extension is later reloaded with a different set of permissions,
973 // we'd like it to get a new isolated world ID, so that it can pick up the
974 // changed origin whitelist.
975 ScriptInjection::RemoveIsolatedWorld(id
);
977 // Invalidate all of the contexts that were removed.
978 // TODO(kalman): add an invalidation observer interface to ScriptContext.
979 ScriptContextSet::ContextSet removed_contexts
=
980 script_context_set_
.OnExtensionUnloaded(id
);
981 for (ScriptContextSet::ContextSet::iterator it
= removed_contexts
.begin();
982 it
!= removed_contexts
.end();
984 request_sender_
->InvalidateSource(*it
);
987 // Update the available bindings for the remaining contexts. These may have
988 // changed if an externally_connectable extension is unloaded and a webpage
989 // is no longer accessible.
992 // Invalidates the messages map for the extension in case the extension is
993 // reloaded with a new messages map.
994 EraseL10nMessagesMap(id
);
996 // We don't do anything with existing platform-app stylesheets. They will
997 // stay resident, but the URL pattern corresponding to the unloaded
998 // extension's URL just won't match anything anymore.
1001 void Dispatcher::OnUpdatePermissions(
1002 const ExtensionMsg_UpdatePermissions_Params
& params
) {
1003 const Extension
* extension
= extensions_
.GetByID(params
.extension_id
);
1007 scoped_refptr
<const PermissionSet
> active
=
1008 params
.active_permissions
.ToPermissionSet();
1009 scoped_refptr
<const PermissionSet
> withheld
=
1010 params
.withheld_permissions
.ToPermissionSet();
1012 if (is_webkit_initialized_
) {
1013 UpdateOriginPermissions(
1015 extension
->permissions_data()->GetEffectiveHostPermissions(),
1016 active
->effective_hosts());
1019 extension
->permissions_data()->SetPermissions(active
, withheld
);
1020 UpdateBindings(extension
->id());
1023 void Dispatcher::OnUpdateTabSpecificPermissions(
1026 const std::string
& extension_id
,
1027 const URLPatternSet
& origin_set
) {
1028 delegate_
->UpdateTabSpecificPermissions(
1029 this, url
, tab_id
, extension_id
, origin_set
);
1032 void Dispatcher::OnUsingWebRequestAPI(bool webrequest_used
) {
1033 webrequest_used_
= webrequest_used
;
1036 void Dispatcher::OnUserScriptsUpdated(
1037 const std::set
<std::string
>& changed_extensions
,
1038 const std::vector
<UserScript
*>& scripts
) {
1039 UpdateActiveExtensions();
1042 void Dispatcher::UpdateActiveExtensions() {
1043 std::set
<std::string
> active_extensions
= active_extension_ids_
;
1044 user_script_set_manager_
->GetAllActiveExtensionIds(&active_extensions
);
1045 delegate_
->OnActiveExtensionsUpdated(active_extensions
);
1048 void Dispatcher::InitOriginPermissions(const Extension
* extension
) {
1049 delegate_
->InitOriginPermissions(extension
,
1050 IsExtensionActive(extension
->id()));
1051 UpdateOriginPermissions(
1053 URLPatternSet(), // No old permissions.
1054 extension
->permissions_data()->GetEffectiveHostPermissions());
1057 void Dispatcher::UpdateOriginPermissions(
1058 const Extension
* extension
,
1059 const URLPatternSet
& old_patterns
,
1060 const URLPatternSet
& new_patterns
) {
1061 static const char* kSchemes
[] = {
1065 content::kChromeUIScheme
,
1068 for (size_t i
= 0; i
< arraysize(kSchemes
); ++i
) {
1069 const char* scheme
= kSchemes
[i
];
1070 // Remove all old patterns...
1071 for (URLPatternSet::const_iterator pattern
= old_patterns
.begin();
1072 pattern
!= old_patterns
.end(); ++pattern
) {
1073 if (pattern
->MatchesScheme(scheme
)) {
1074 WebSecurityPolicy::removeOriginAccessWhitelistEntry(
1076 WebString::fromUTF8(scheme
),
1077 WebString::fromUTF8(pattern
->host()),
1078 pattern
->match_subdomains());
1081 // ...And add the new ones.
1082 for (URLPatternSet::const_iterator pattern
= new_patterns
.begin();
1083 pattern
!= new_patterns
.end(); ++pattern
) {
1084 if (pattern
->MatchesScheme(scheme
)) {
1085 WebSecurityPolicy::addOriginAccessWhitelistEntry(
1087 WebString::fromUTF8(scheme
),
1088 WebString::fromUTF8(pattern
->host()),
1089 pattern
->match_subdomains());
1095 void Dispatcher::EnableCustomElementWhiteList() {
1096 blink::WebCustomElement::addEmbedderCustomElementName("appplugin");
1097 blink::WebCustomElement::addEmbedderCustomElementName("appview");
1098 blink::WebCustomElement::addEmbedderCustomElementName("browserplugin");
1099 blink::WebCustomElement::addEmbedderCustomElementName("extensionoptions");
1100 blink::WebCustomElement::addEmbedderCustomElementName(
1101 "extensionoptionsplugin");
1102 blink::WebCustomElement::addEmbedderCustomElementName("webview");
1105 void Dispatcher::UpdateBindings(const std::string
& extension_id
) {
1106 script_context_set().ForEach(extension_id
,
1107 base::Bind(&Dispatcher::UpdateBindingsForContext
,
1108 base::Unretained(this)));
1111 void Dispatcher::UpdateBindingsForContext(ScriptContext
* context
) {
1112 v8::HandleScope
handle_scope(context
->isolate());
1113 v8::Context::Scope
context_scope(context
->v8_context());
1115 // TODO(kalman): Make the bindings registration have zero overhead then run
1116 // the same code regardless of context type.
1117 switch (context
->context_type()) {
1118 case Feature::UNSPECIFIED_CONTEXT
:
1119 case Feature::WEB_PAGE_CONTEXT
:
1120 case Feature::BLESSED_WEB_PAGE_CONTEXT
: {
1121 // Web page context; it's too expensive to run the full bindings code.
1122 // Hard-code that the app and webstore APIs are available...
1123 if (context
->GetAvailability("app").is_available())
1124 RegisterBinding("app", context
);
1126 if (context
->GetAvailability("webstore").is_available())
1127 RegisterBinding("webstore", context
);
1129 // ... and that the runtime API might be available if any extension can
1131 bool runtime_is_available
= false;
1132 for (ExtensionSet::const_iterator it
= extensions_
.begin();
1133 it
!= extensions_
.end();
1135 ExternallyConnectableInfo
* info
=
1136 static_cast<ExternallyConnectableInfo
*>(
1137 (*it
)->GetManifestData(manifest_keys::kExternallyConnectable
));
1138 if (info
&& info
->matches
.MatchesURL(context
->GetURL())) {
1139 runtime_is_available
= true;
1143 if (runtime_is_available
)
1144 RegisterBinding("runtime", context
);
1148 case Feature::BLESSED_EXTENSION_CONTEXT
:
1149 case Feature::UNBLESSED_EXTENSION_CONTEXT
:
1150 case Feature::CONTENT_SCRIPT_CONTEXT
:
1151 case Feature::WEBUI_CONTEXT
: {
1152 // Extension context; iterate through all the APIs and bind the available
1154 const FeatureProvider
* api_feature_provider
=
1155 FeatureProvider::GetAPIFeatures();
1156 const std::vector
<std::string
>& apis
=
1157 api_feature_provider
->GetAllFeatureNames();
1158 for (std::vector
<std::string
>::const_iterator it
= apis
.begin();
1161 const std::string
& api_name
= *it
;
1162 Feature
* feature
= api_feature_provider
->GetFeature(api_name
);
1165 // Internal APIs are included via require(api_name) from internal code
1166 // rather than chrome[api_name].
1167 if (feature
->IsInternal())
1170 // If this API has a parent feature (and isn't marked 'noparent'),
1171 // then this must be a function or event, so we should not register.
1172 if (api_feature_provider
->GetParent(feature
) != NULL
)
1175 // Skip chrome.test if this isn't a test.
1176 if (api_name
== "test" &&
1177 !CommandLine::ForCurrentProcess()->HasSwitch(
1178 ::switches::kTestType
)) {
1182 if (context
->IsAnyFeatureAvailableToContext(*feature
))
1183 RegisterBinding(api_name
, context
);
1190 void Dispatcher::RegisterBinding(const std::string
& api_name
,
1191 ScriptContext
* context
) {
1192 std::string bind_name
;
1193 v8::Handle
<v8::Object
> bind_object
=
1194 GetOrCreateBindObjectIfAvailable(api_name
, &bind_name
, context
);
1196 // Empty if the bind object failed to be created, probably because the
1197 // extension overrode chrome with a non-object, e.g. window.chrome = true.
1198 if (bind_object
.IsEmpty())
1201 v8::Local
<v8::String
> v8_api_name
=
1202 v8::String::NewFromUtf8(context
->isolate(), api_name
.c_str());
1203 if (bind_object
->HasRealNamedProperty(v8_api_name
)) {
1204 // The bind object may already have the property if the API has been
1205 // registered before (or if the extension has put something there already,
1208 // In the former case, we need to re-register the bindings for the APIs
1209 // which the extension now has permissions for (if any), but not touch any
1210 // others so that we don't destroy state such as event listeners.
1212 // TODO(kalman): Only register available APIs to make this all moot.
1213 if (bind_object
->HasRealNamedCallbackProperty(v8_api_name
))
1214 return; // lazy binding still there, nothing to do
1215 if (bind_object
->Get(v8_api_name
)->IsObject())
1216 return; // binding has already been fully installed
1219 ModuleSystem
* module_system
= context
->module_system();
1220 if (!source_map_
.Contains(api_name
)) {
1221 module_system
->RegisterNativeHandler(
1223 scoped_ptr
<NativeHandler
>(new BindingGeneratingNativeHandler(
1224 module_system
, api_name
, "binding")));
1225 module_system
->SetNativeLazyField(
1226 bind_object
, bind_name
, api_name
, "binding");
1228 module_system
->SetLazyField(bind_object
, bind_name
, api_name
, "binding");
1232 // NOTE: please use the naming convention "foo_natives" for these.
1233 void Dispatcher::RegisterNativeHandlers(ModuleSystem
* module_system
,
1234 ScriptContext
* context
) {
1235 RegisterNativeHandlers(module_system
,
1238 request_sender_
.get(),
1239 v8_schema_registry_
.get());
1240 const Extension
* extension
= context
->extension();
1241 int manifest_version
= extension
? extension
->manifest_version() : 1;
1242 bool send_request_disabled
=
1243 (extension
&& Manifest::IsUnpackedLocation(extension
->location()) &&
1244 BackgroundInfo::HasLazyBackgroundPage(extension
));
1245 module_system
->RegisterNativeHandler(
1247 scoped_ptr
<NativeHandler
>(new ProcessInfoNativeHandler(
1249 context
->GetExtensionID(),
1250 context
->GetContextTypeDescription(),
1251 ExtensionsRendererClient::Get()->IsIncognitoProcess(),
1253 send_request_disabled
)));
1255 delegate_
->RegisterNativeHandlers(this, module_system
, context
);
1258 void Dispatcher::PopulateSourceMap() {
1259 const std::vector
<std::pair
<std::string
, int> > resources
= GetJsResources();
1260 for (std::vector
<std::pair
<std::string
, int> >::const_iterator resource
=
1262 resource
!= resources
.end();
1264 source_map_
.RegisterSource(resource
->first
, resource
->second
);
1266 delegate_
->PopulateSourceMap(&source_map_
);
1269 bool Dispatcher::IsWithinPlatformApp() {
1270 for (std::set
<std::string
>::iterator iter
= active_extension_ids_
.begin();
1271 iter
!= active_extension_ids_
.end();
1273 const Extension
* extension
= extensions_
.GetByID(*iter
);
1274 if (extension
&& extension
->is_platform_app())
1280 // TODO(kalman): This is checking for the wrong thing, it should be checking if
1281 // the frame's security origin is unique. The extension sandbox directive is
1282 // checked for in extensions/common/manifest_handlers/csp_info.cc.
1283 bool Dispatcher::IsSandboxedPage(const GURL
& url
) const {
1284 if (url
.SchemeIs(kExtensionScheme
)) {
1285 const Extension
* extension
= extensions_
.GetByID(url
.host());
1287 return SandboxedPageInfo::IsSandboxedPage(extension
, url
.path());
1293 Feature::Context
Dispatcher::ClassifyJavaScriptContext(
1294 const Extension
* extension
,
1295 int extension_group
,
1297 const blink::WebSecurityOrigin
& origin
) {
1298 // WARNING: This logic must match ProcessMap::GetContextType, as much as
1301 DCHECK_GE(extension_group
, 0);
1302 if (extension_group
== EXTENSION_GROUP_CONTENT_SCRIPTS
) {
1303 return extension
? // TODO(kalman): when does this happen?
1304 Feature::CONTENT_SCRIPT_CONTEXT
1305 : Feature::UNSPECIFIED_CONTEXT
;
1308 // We have an explicit check for sandboxed pages before checking whether the
1309 // extension is active in this process because:
1310 // 1. Sandboxed pages run in the same process as regular extension pages, so
1311 // the extension is considered active.
1312 // 2. ScriptContext creation (which triggers bindings injection) happens
1313 // before the SecurityContext is updated with the sandbox flags (after
1314 // reading the CSP header), so the caller can't check if the context's
1315 // security origin is unique yet.
1316 if (IsSandboxedPage(url
))
1317 return Feature::WEB_PAGE_CONTEXT
;
1319 if (extension
&& IsExtensionActive(extension
->id())) {
1320 // |extension| is active in this process, but it could be either a true
1321 // extension process or within the extent of a hosted app. In the latter
1322 // case this would usually be considered a (blessed) web page context,
1323 // unless the extension in question is a component extension, in which case
1324 // we cheat and call it blessed.
1325 return (extension
->is_hosted_app() &&
1326 extension
->location() != Manifest::COMPONENT
)
1327 ? Feature::BLESSED_WEB_PAGE_CONTEXT
1328 : Feature::BLESSED_EXTENSION_CONTEXT
;
1331 // TODO(kalman): This isUnique() check is wrong, it should be performed as
1332 // part of IsSandboxedPage().
1333 if (!origin
.isUnique() && extensions_
.ExtensionBindingsAllowed(url
)) {
1334 if (!extension
) // TODO(kalman): when does this happen?
1335 return Feature::UNSPECIFIED_CONTEXT
;
1336 return extension
->is_hosted_app() ? Feature::BLESSED_WEB_PAGE_CONTEXT
1337 : Feature::UNBLESSED_EXTENSION_CONTEXT
;
1340 if (!url
.is_valid())
1341 return Feature::UNSPECIFIED_CONTEXT
;
1343 if (url
.SchemeIs(content::kChromeUIScheme
))
1344 return Feature::WEBUI_CONTEXT
;
1346 return Feature::WEB_PAGE_CONTEXT
;
1349 v8::Handle
<v8::Object
> Dispatcher::GetOrCreateObject(
1350 const v8::Handle
<v8::Object
>& object
,
1351 const std::string
& field
,
1352 v8::Isolate
* isolate
) {
1353 v8::Handle
<v8::String
> key
= v8::String::NewFromUtf8(isolate
, field
.c_str());
1354 // If the object has a callback property, it is assumed it is an unavailable
1355 // API, so it is safe to delete. This is checked before GetOrCreateObject is
1357 if (object
->HasRealNamedCallbackProperty(key
)) {
1358 object
->Delete(key
);
1359 } else if (object
->HasRealNamedProperty(key
)) {
1360 v8::Handle
<v8::Value
> value
= object
->Get(key
);
1361 CHECK(value
->IsObject());
1362 return v8::Handle
<v8::Object
>::Cast(value
);
1365 v8::Handle
<v8::Object
> new_object
= v8::Object::New(isolate
);
1366 object
->Set(key
, new_object
);
1370 v8::Handle
<v8::Object
> Dispatcher::GetOrCreateBindObjectIfAvailable(
1371 const std::string
& api_name
,
1372 std::string
* bind_name
,
1373 ScriptContext
* context
) {
1374 std::vector
<std::string
> split
;
1375 base::SplitString(api_name
, '.', &split
);
1377 v8::Handle
<v8::Object
> bind_object
;
1379 // Check if this API has an ancestor. If the API's ancestor is available and
1380 // the API is not available, don't install the bindings for this API. If
1381 // the API is available and its ancestor is not, delete the ancestor and
1382 // install the bindings for the API. This is to prevent loading the ancestor
1383 // API schema if it will not be needed.
1386 // If app is available and app.window is not, just install app.
1387 // If app.window is available and app is not, delete app and install
1388 // app.window on a new object so app does not have to be loaded.
1389 const FeatureProvider
* api_feature_provider
=
1390 FeatureProvider::GetAPIFeatures();
1391 std::string ancestor_name
;
1392 bool only_ancestor_available
= false;
1394 for (size_t i
= 0; i
< split
.size() - 1; ++i
) {
1395 ancestor_name
+= (i
? "." : "") + split
[i
];
1396 if (api_feature_provider
->GetFeature(ancestor_name
) &&
1397 context
->GetAvailability(ancestor_name
).is_available() &&
1398 !context
->GetAvailability(api_name
).is_available()) {
1399 only_ancestor_available
= true;
1403 if (bind_object
.IsEmpty()) {
1404 bind_object
= AsObjectOrEmpty(GetOrCreateChrome(context
));
1405 if (bind_object
.IsEmpty())
1406 return v8::Handle
<v8::Object
>();
1408 bind_object
= GetOrCreateObject(bind_object
, split
[i
], context
->isolate());
1411 if (only_ancestor_available
)
1412 return v8::Handle
<v8::Object
>();
1415 *bind_name
= split
.back();
1417 return bind_object
.IsEmpty() ? AsObjectOrEmpty(GetOrCreateChrome(context
))
1421 } // namespace extensions