Roll WebRTC 9745:9761, Libjingle 9742:9761
[chromium-blink-merge.git] / extensions / renderer / dispatcher.cc
blob34324e2be1bf10a27c375337e720fd03c5a85029
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"
7 #include "base/bind.h"
8 #include "base/callback.h"
9 #include "base/command_line.h"
10 #include "base/containers/scoped_ptr_map.h"
11 #include "base/debug/alias.h"
12 #include "base/lazy_instance.h"
13 #include "base/memory/scoped_ptr.h"
14 #include "base/metrics/histogram_macros.h"
15 #include "base/metrics/user_metrics_action.h"
16 #include "base/strings/string_piece.h"
17 #include "base/strings/string_split.h"
18 #include "base/strings/string_util.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "base/synchronization/lock.h"
21 #include "base/time/time.h"
22 #include "base/values.h"
23 #include "content/grit/content_resources.h"
24 #include "content/public/child/v8_value_converter.h"
25 #include "content/public/common/browser_plugin_guest_mode.h"
26 #include "content/public/common/content_switches.h"
27 #include "content/public/common/url_constants.h"
28 #include "content/public/renderer/render_frame.h"
29 #include "content/public/renderer/render_thread.h"
30 #include "extensions/common/api/messaging/message.h"
31 #include "extensions/common/constants.h"
32 #include "extensions/common/extension_api.h"
33 #include "extensions/common/extension_messages.h"
34 #include "extensions/common/extension_urls.h"
35 #include "extensions/common/feature_switch.h"
36 #include "extensions/common/features/behavior_feature.h"
37 #include "extensions/common/features/feature.h"
38 #include "extensions/common/features/feature_provider.h"
39 #include "extensions/common/manifest.h"
40 #include "extensions/common/manifest_constants.h"
41 #include "extensions/common/manifest_handlers/background_info.h"
42 #include "extensions/common/manifest_handlers/content_capabilities_handler.h"
43 #include "extensions/common/manifest_handlers/externally_connectable.h"
44 #include "extensions/common/manifest_handlers/options_page_info.h"
45 #include "extensions/common/message_bundle.h"
46 #include "extensions/common/permissions/permission_set.h"
47 #include "extensions/common/permissions/permissions_data.h"
48 #include "extensions/common/switches.h"
49 #include "extensions/common/view_type.h"
50 #include "extensions/renderer/api_activity_logger.h"
51 #include "extensions/renderer/api_definitions_natives.h"
52 #include "extensions/renderer/app_window_custom_bindings.h"
53 #include "extensions/renderer/binding_generating_native_handler.h"
54 #include "extensions/renderer/blob_native_handler.h"
55 #include "extensions/renderer/content_watcher.h"
56 #include "extensions/renderer/context_menus_custom_bindings.h"
57 #include "extensions/renderer/css_native_handler.h"
58 #include "extensions/renderer/dispatcher_delegate.h"
59 #include "extensions/renderer/document_custom_bindings.h"
60 #include "extensions/renderer/dom_activity_logger.h"
61 #include "extensions/renderer/event_bindings.h"
62 #include "extensions/renderer/extension_frame_helper.h"
63 #include "extensions/renderer/extension_helper.h"
64 #include "extensions/renderer/extensions_renderer_client.h"
65 #include "extensions/renderer/file_system_natives.h"
66 #include "extensions/renderer/guest_view/guest_view_internal_custom_bindings.h"
67 #include "extensions/renderer/i18n_custom_bindings.h"
68 #include "extensions/renderer/id_generator_custom_bindings.h"
69 #include "extensions/renderer/lazy_background_page_native_handler.h"
70 #include "extensions/renderer/logging_native_handler.h"
71 #include "extensions/renderer/messaging_bindings.h"
72 #include "extensions/renderer/module_system.h"
73 #include "extensions/renderer/print_native_handler.h"
74 #include "extensions/renderer/process_info_native_handler.h"
75 #include "extensions/renderer/render_frame_observer_natives.h"
76 #include "extensions/renderer/renderer_extension_registry.h"
77 #include "extensions/renderer/request_sender.h"
78 #include "extensions/renderer/runtime_custom_bindings.h"
79 #include "extensions/renderer/safe_builtins.h"
80 #include "extensions/renderer/script_context.h"
81 #include "extensions/renderer/script_context_set.h"
82 #include "extensions/renderer/script_injection.h"
83 #include "extensions/renderer/script_injection_manager.h"
84 #include "extensions/renderer/send_request_natives.h"
85 #include "extensions/renderer/set_icon_natives.h"
86 #include "extensions/renderer/static_v8_external_one_byte_string_resource.h"
87 #include "extensions/renderer/test_features_native_handler.h"
88 #include "extensions/renderer/test_native_handler.h"
89 #include "extensions/renderer/user_gestures_native_handler.h"
90 #include "extensions/renderer/utils_native_handler.h"
91 #include "extensions/renderer/v8_context_native_handler.h"
92 #include "extensions/renderer/v8_helpers.h"
93 #include "extensions/renderer/wake_event_page.h"
94 #include "grit/extensions_renderer_resources.h"
95 #include "third_party/WebKit/public/platform/WebString.h"
96 #include "third_party/WebKit/public/platform/WebURLRequest.h"
97 #include "third_party/WebKit/public/web/WebCustomElement.h"
98 #include "third_party/WebKit/public/web/WebDataSource.h"
99 #include "third_party/WebKit/public/web/WebDocument.h"
100 #include "third_party/WebKit/public/web/WebFrame.h"
101 #include "third_party/WebKit/public/web/WebLocalFrame.h"
102 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
103 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
104 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
105 #include "third_party/WebKit/public/web/WebView.h"
106 #include "third_party/mojo/src/mojo/public/js/constants.h"
107 #include "ui/base/layout.h"
108 #include "ui/base/resource/resource_bundle.h"
109 #include "v8/include/v8.h"
111 using base::UserMetricsAction;
112 using blink::WebDataSource;
113 using blink::WebDocument;
114 using blink::WebScopedUserGesture;
115 using blink::WebSecurityPolicy;
116 using blink::WebString;
117 using blink::WebVector;
118 using blink::WebView;
119 using content::RenderThread;
121 namespace extensions {
123 namespace {
125 static const int64 kInitialExtensionIdleHandlerDelayMs = 5 * 1000;
126 static const int64 kMaxExtensionIdleHandlerDelayMs = 5 * 60 * 1000;
127 static const char kEventDispatchFunction[] = "dispatchEvent";
128 static const char kOnSuspendEvent[] = "runtime.onSuspend";
129 static const char kOnSuspendCanceledEvent[] = "runtime.onSuspendCanceled";
131 void CrashOnException(const v8::TryCatch& trycatch) {
132 NOTREACHED();
135 // Returns the global value for "chrome" from |context|. If one doesn't exist
136 // creates a new object for it.
138 // Note that this isn't necessarily an object, since webpages can write, for
139 // example, "window.chrome = true".
140 v8::Local<v8::Value> GetOrCreateChrome(ScriptContext* context) {
141 v8::Local<v8::String> chrome_string(
142 v8::String::NewFromUtf8(context->isolate(), "chrome"));
143 v8::Local<v8::Object> global(context->v8_context()->Global());
144 v8::Local<v8::Value> chrome(global->Get(chrome_string));
145 if (chrome->IsUndefined()) {
146 chrome = v8::Object::New(context->isolate());
147 global->Set(chrome_string, chrome);
149 return chrome;
152 // Returns |value| cast to an object if possible, else an empty handle.
153 v8::Local<v8::Object> AsObjectOrEmpty(v8::Local<v8::Value> value) {
154 return value->IsObject() ? value.As<v8::Object>() : v8::Local<v8::Object>();
157 // Calls a method |method_name| in a module |module_name| belonging to the
158 // module system from |context|. Intended as a callback target from
159 // ScriptContextSet::ForEach.
160 void CallModuleMethod(const std::string& module_name,
161 const std::string& method_name,
162 const base::ListValue* args,
163 ScriptContext* context) {
164 v8::HandleScope handle_scope(context->isolate());
165 v8::Context::Scope context_scope(context->v8_context());
167 scoped_ptr<content::V8ValueConverter> converter(
168 content::V8ValueConverter::create());
170 std::vector<v8::Local<v8::Value>> arguments;
171 for (base::ListValue::const_iterator it = args->begin(); it != args->end();
172 ++it) {
173 arguments.push_back(converter->ToV8Value(*it, context->v8_context()));
176 context->module_system()->CallModuleMethod(
177 module_name, method_name, &arguments);
180 // This handles the "chrome." root API object in script contexts.
181 class ChromeNativeHandler : public ObjectBackedNativeHandler {
182 public:
183 explicit ChromeNativeHandler(ScriptContext* context)
184 : ObjectBackedNativeHandler(context) {
185 RouteFunction(
186 "GetChrome",
187 base::Bind(&ChromeNativeHandler::GetChrome, base::Unretained(this)));
190 void GetChrome(const v8::FunctionCallbackInfo<v8::Value>& args) {
191 args.GetReturnValue().Set(GetOrCreateChrome(context()));
195 class ServiceWorkerScriptContextSet {
196 public:
197 ServiceWorkerScriptContextSet() {}
198 ~ServiceWorkerScriptContextSet() {}
200 void Insert(const GURL& url, scoped_ptr<ScriptContext> context) {
201 base::AutoLock lock(lock_);
202 CHECK(script_contexts_.find(url) == script_contexts_.end());
203 script_contexts_.set(url, context.Pass());
206 void Remove(const GURL& url) {
207 base::AutoLock lock(lock_);
208 scoped_ptr<ScriptContext> context = script_contexts_.take_and_erase(url);
209 CHECK(context);
210 context->Invalidate();
213 private:
214 base::ScopedPtrMap<GURL, scoped_ptr<ScriptContext>> script_contexts_;
216 mutable base::Lock lock_;
218 DISALLOW_COPY_AND_ASSIGN(ServiceWorkerScriptContextSet);
221 base::LazyInstance<ServiceWorkerScriptContextSet>
222 g_service_worker_script_context_set = LAZY_INSTANCE_INITIALIZER;
224 } // namespace
226 Dispatcher::Dispatcher(DispatcherDelegate* delegate)
227 : delegate_(delegate),
228 content_watcher_(new ContentWatcher()),
229 source_map_(&ResourceBundle::GetSharedInstance()),
230 v8_schema_registry_(new V8SchemaRegistry),
231 is_webkit_initialized_(false),
232 user_script_set_manager_observer_(this),
233 webrequest_used_(false) {
234 const base::CommandLine& command_line =
235 *(base::CommandLine::ForCurrentProcess());
236 set_idle_notifications_ =
237 command_line.HasSwitch(switches::kExtensionProcess) ||
238 command_line.HasSwitch(::switches::kSingleProcess);
240 if (set_idle_notifications_) {
241 RenderThread::Get()->SetIdleNotificationDelayInMs(
242 kInitialExtensionIdleHandlerDelayMs);
245 script_context_set_.reset(new ScriptContextSet(&active_extension_ids_));
246 user_script_set_manager_.reset(new UserScriptSetManager());
247 script_injection_manager_.reset(
248 new ScriptInjectionManager(user_script_set_manager_.get()));
249 user_script_set_manager_observer_.Add(user_script_set_manager_.get());
250 request_sender_.reset(new RequestSender(this));
251 PopulateSourceMap();
252 WakeEventPage::Get()->Init(content::RenderThread::Get());
254 // chrome-extensions: and chrome-extensions-resource: schemes should be
255 // treated as secure because communication with them is entirely in the
256 // browser, so there is no danger of manipulation or eavesdropping on
257 // communication with them by third parties.
258 WebString extension_scheme(base::ASCIIToUTF16(kExtensionScheme));
259 blink::WebSecurityPolicy::registerURLSchemeAsSecure(extension_scheme);
261 WebString extension_resource_scheme(base::ASCIIToUTF16(
262 kExtensionResourceScheme));
263 blink::WebSecurityPolicy::registerURLSchemeAsSecure(
264 extension_resource_scheme);
266 // chrome-extension: and chrome-extension-resource: resources should be
267 // allowed to receive CORS requests.
268 WebSecurityPolicy::registerURLSchemeAsCORSEnabled(extension_scheme);
269 WebSecurityPolicy::registerURLSchemeAsCORSEnabled(extension_resource_scheme);
271 // chrome-extension: resources should bypass Content Security Policy checks
272 // when included in protected resources.
273 WebSecurityPolicy::registerURLSchemeAsBypassingContentSecurityPolicy(
274 extension_scheme);
275 WebSecurityPolicy::registerURLSchemeAsBypassingContentSecurityPolicy(
276 extension_resource_scheme);
279 Dispatcher::~Dispatcher() {
282 void Dispatcher::OnRenderFrameCreated(content::RenderFrame* render_frame) {
283 script_injection_manager_->OnRenderFrameCreated(render_frame);
286 bool Dispatcher::IsExtensionActive(const std::string& extension_id) const {
287 bool is_active =
288 active_extension_ids_.find(extension_id) != active_extension_ids_.end();
289 if (is_active)
290 CHECK(RendererExtensionRegistry::Get()->Contains(extension_id));
291 return is_active;
294 void Dispatcher::DidCreateScriptContext(
295 blink::WebLocalFrame* frame,
296 const v8::Local<v8::Context>& v8_context,
297 int extension_group,
298 int world_id) {
299 const base::TimeTicks start_time = base::TimeTicks::Now();
301 ScriptContext* context = script_context_set_->Register(
302 frame, v8_context, extension_group, world_id);
304 // Initialize origin permissions for content scripts, which can't be
305 // initialized in |OnActivateExtension|.
306 if (context->context_type() == Feature::CONTENT_SCRIPT_CONTEXT)
307 InitOriginPermissions(context->extension());
310 scoped_ptr<ModuleSystem> module_system(
311 new ModuleSystem(context, &source_map_));
312 context->set_module_system(module_system.Pass());
314 ModuleSystem* module_system = context->module_system();
316 // Enable natives in startup.
317 ModuleSystem::NativesEnabledScope natives_enabled_scope(module_system);
319 RegisterNativeHandlers(module_system, context);
321 // chrome.Event is part of the public API (although undocumented). Make it
322 // lazily evalulate to Event from event_bindings.js. For extensions only
323 // though, not all webpages!
324 if (context->extension()) {
325 v8::Local<v8::Object> chrome = AsObjectOrEmpty(GetOrCreateChrome(context));
326 if (!chrome.IsEmpty())
327 module_system->SetLazyField(chrome, "Event", kEventBindings, "Event");
330 UpdateBindingsForContext(context);
332 bool is_within_platform_app = IsWithinPlatformApp();
333 // Inject custom JS into the platform app context.
334 if (is_within_platform_app) {
335 module_system->Require("platformApp");
338 RequireGuestViewModules(context);
339 delegate_->RequireAdditionalModules(context, is_within_platform_app);
341 const base::TimeDelta elapsed = base::TimeTicks::Now() - start_time;
342 switch (context->context_type()) {
343 case Feature::UNSPECIFIED_CONTEXT:
344 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Unspecified",
345 elapsed);
346 break;
347 case Feature::BLESSED_EXTENSION_CONTEXT:
348 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Blessed", elapsed);
349 break;
350 case Feature::UNBLESSED_EXTENSION_CONTEXT:
351 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Unblessed",
352 elapsed);
353 break;
354 case Feature::CONTENT_SCRIPT_CONTEXT:
355 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_ContentScript",
356 elapsed);
357 break;
358 case Feature::WEB_PAGE_CONTEXT:
359 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_WebPage", elapsed);
360 break;
361 case Feature::BLESSED_WEB_PAGE_CONTEXT:
362 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_BlessedWebPage",
363 elapsed);
364 break;
365 case Feature::WEBUI_CONTEXT:
366 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_WebUI", elapsed);
367 break;
368 case Feature::SERVICE_WORKER_CONTEXT:
369 // Handled in DidInitializeServiceWorkerContextOnWorkerThread().
370 NOTREACHED();
371 break;
374 VLOG(1) << "Num tracked contexts: " << script_context_set_->size();
377 // static
378 void Dispatcher::DidInitializeServiceWorkerContextOnWorkerThread(
379 v8::Local<v8::Context> v8_context,
380 const GURL& url) {
381 const base::TimeTicks start_time = base::TimeTicks::Now();
383 const Extension* extension =
384 RendererExtensionRegistry::Get()->GetExtensionOrAppByURL(url);
386 if (!extension)
387 return;
389 ScriptContext* context = new ScriptContext(
390 v8_context, nullptr, extension, Feature::SERVICE_WORKER_CONTEXT,
391 extension, Feature::SERVICE_WORKER_CONTEXT);
393 g_service_worker_script_context_set.Get().Insert(url,
394 make_scoped_ptr(context));
396 v8::Isolate* isolate = context->isolate();
398 // Fetch the source code for service_worker_bindings.js.
399 base::StringPiece script_resource =
400 ResourceBundle::GetSharedInstance().GetRawDataResource(
401 IDR_SERVICE_WORKER_BINDINGS_JS);
402 v8::Local<v8::String> script = v8::String::NewExternal(
403 isolate, new StaticV8ExternalOneByteStringResource(script_resource));
405 // Run the script to get the main function, then run the main function to
406 // inject service worker bindings.
407 v8::Local<v8::Value> result = context->RunScript(
408 v8_helpers::ToV8StringUnsafe(isolate, "service_worker"), script,
409 base::Bind(&CrashOnException));
410 CHECK(result->IsFunction());
411 v8::Local<v8::Value> args[] = {
412 v8_helpers::ToV8StringUnsafe(
413 isolate, BackgroundInfo::GetBackgroundURL(extension).spec()),
415 context->CallFunction(result.As<v8::Function>(), arraysize(args), args);
417 const base::TimeDelta elapsed = base::TimeTicks::Now() - start_time;
418 UMA_HISTOGRAM_TIMES(
419 "Extensions.DidInitializeServiceWorkerContextOnWorkerThread", elapsed);
422 void Dispatcher::WillReleaseScriptContext(
423 blink::WebLocalFrame* frame,
424 const v8::Local<v8::Context>& v8_context,
425 int world_id) {
426 ScriptContext* context = script_context_set_->GetByV8Context(v8_context);
427 if (!context)
428 return;
430 context->DispatchOnUnloadEvent();
431 // TODO(kalman): Make |request_sender| use |context->AddInvalidationObserver|.
432 // In fact |request_sender_| should really be owned by ScriptContext.
433 request_sender_->InvalidateSource(context);
435 script_context_set_->Remove(context);
436 VLOG(1) << "Num tracked contexts: " << script_context_set_->size();
439 // static
440 void Dispatcher::WillDestroyServiceWorkerContextOnWorkerThread(
441 const GURL& url) {
442 if (RendererExtensionRegistry::Get()->GetExtensionOrAppByURL(url))
443 g_service_worker_script_context_set.Get().Remove(url);
446 void Dispatcher::DidCreateDocumentElement(blink::WebLocalFrame* frame) {
447 // Note: use GetEffectiveDocumentURL not just frame->document()->url()
448 // so that this also injects the stylesheet on about:blank frames that
449 // are hosted in the extension process.
450 GURL effective_document_url = ScriptContext::GetEffectiveDocumentURL(
451 frame, frame->document().url(), true /* match_about_blank */);
453 const Extension* extension =
454 RendererExtensionRegistry::Get()->GetExtensionOrAppByURL(
455 effective_document_url);
457 if (extension &&
458 (extension->is_extension() || extension->is_platform_app())) {
459 int resource_id = extension->is_platform_app() ? IDR_PLATFORM_APP_CSS
460 : IDR_EXTENSION_FONTS_CSS;
461 std::string stylesheet = ResourceBundle::GetSharedInstance()
462 .GetRawDataResource(resource_id)
463 .as_string();
464 base::ReplaceFirstSubstringAfterOffset(
465 &stylesheet, 0, "$FONTFAMILY", system_font_family_);
466 base::ReplaceFirstSubstringAfterOffset(
467 &stylesheet, 0, "$FONTSIZE", system_font_size_);
469 // Blink doesn't let us define an additional user agent stylesheet, so
470 // we insert the default platform app or extension stylesheet into all
471 // documents that are loaded in each app or extension.
472 frame->document().insertStyleSheet(WebString::fromUTF8(stylesheet));
475 // If this is an extension options page, and the extension has opted into
476 // using Chrome styles, then insert the Chrome extension stylesheet.
477 if (extension && extension->is_extension() &&
478 OptionsPageInfo::ShouldUseChromeStyle(extension) &&
479 effective_document_url == OptionsPageInfo::GetOptionsPage(extension)) {
480 frame->document().insertStyleSheet(
481 WebString::fromUTF8(ResourceBundle::GetSharedInstance()
482 .GetRawDataResource(IDR_EXTENSION_CSS)
483 .as_string()));
486 // In testing, the document lifetime events can happen after the render
487 // process shutdown event.
488 // See: http://crbug.com/21508 and http://crbug.com/500851
489 if (content_watcher_) {
490 content_watcher_->DidCreateDocumentElement(frame);
494 void Dispatcher::OnExtensionResponse(int request_id,
495 bool success,
496 const base::ListValue& response,
497 const std::string& error) {
498 request_sender_->HandleResponse(request_id, success, response, error);
501 void Dispatcher::DispatchEvent(const std::string& extension_id,
502 const std::string& event_name) const {
503 base::ListValue args;
504 args.Set(0, new base::StringValue(event_name));
505 args.Set(1, new base::ListValue());
507 // Needed for Windows compilation, since kEventBindings is declared extern.
508 const char* local_event_bindings = kEventBindings;
509 script_context_set_->ForEach(
510 extension_id, base::Bind(&CallModuleMethod, local_event_bindings,
511 kEventDispatchFunction, &args));
514 void Dispatcher::InvokeModuleSystemMethod(content::RenderFrame* render_frame,
515 const std::string& extension_id,
516 const std::string& module_name,
517 const std::string& function_name,
518 const base::ListValue& args,
519 bool user_gesture) {
520 scoped_ptr<WebScopedUserGesture> web_user_gesture;
521 if (user_gesture)
522 web_user_gesture.reset(new WebScopedUserGesture);
524 script_context_set_->ForEach(
525 extension_id, render_frame,
526 base::Bind(&CallModuleMethod, module_name, function_name, &args));
528 // Reset the idle handler each time there's any activity like event or message
529 // dispatch, for which Invoke is the chokepoint.
530 if (set_idle_notifications_) {
531 RenderThread::Get()->ScheduleIdleHandler(
532 kInitialExtensionIdleHandlerDelayMs);
535 // Tell the browser process when an event has been dispatched with a lazy
536 // background page active.
537 const Extension* extension =
538 RendererExtensionRegistry::Get()->GetByID(extension_id);
539 if (extension && BackgroundInfo::HasLazyBackgroundPage(extension) &&
540 module_name == kEventBindings &&
541 function_name == kEventDispatchFunction) {
542 content::RenderFrame* background_frame =
543 ExtensionFrameHelper::GetBackgroundPageFrame(extension_id);
544 if (background_frame) {
545 int message_id;
546 args.GetInteger(3, &message_id);
547 background_frame->Send(new ExtensionHostMsg_EventAck(
548 background_frame->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
556 // here as a no-op.
557 port_to_tab_id_map_.erase(port_id);
560 // static
561 std::vector<std::pair<std::string, int> > Dispatcher::GetJsResources() {
562 std::vector<std::pair<std::string, int> > resources;
564 // Libraries.
565 resources.push_back(std::make_pair("appView", IDR_APP_VIEW_JS));
566 resources.push_back(std::make_pair("entryIdManager", IDR_ENTRY_ID_MANAGER));
567 resources.push_back(std::make_pair(kEventBindings, IDR_EVENT_BINDINGS_JS));
568 resources.push_back(std::make_pair("extensionOptions",
569 IDR_EXTENSION_OPTIONS_JS));
570 resources.push_back(std::make_pair("extensionOptionsAttributes",
571 IDR_EXTENSION_OPTIONS_ATTRIBUTES_JS));
572 resources.push_back(std::make_pair("extensionOptionsConstants",
573 IDR_EXTENSION_OPTIONS_CONSTANTS_JS));
574 resources.push_back(std::make_pair("extensionOptionsEvents",
575 IDR_EXTENSION_OPTIONS_EVENTS_JS));
576 resources.push_back(std::make_pair("extensionView", IDR_EXTENSION_VIEW_JS));
577 resources.push_back(std::make_pair("extensionViewApiMethods",
578 IDR_EXTENSION_VIEW_API_METHODS_JS));
579 resources.push_back(std::make_pair("extensionViewAttributes",
580 IDR_EXTENSION_VIEW_ATTRIBUTES_JS));
581 resources.push_back(std::make_pair("extensionViewConstants",
582 IDR_EXTENSION_VIEW_CONSTANTS_JS));
583 resources.push_back(std::make_pair("extensionViewEvents",
584 IDR_EXTENSION_VIEW_EVENTS_JS));
585 resources.push_back(std::make_pair(
586 "extensionViewInternal", IDR_EXTENSION_VIEW_INTERNAL_CUSTOM_BINDINGS_JS));
587 resources.push_back(std::make_pair("guestView", IDR_GUEST_VIEW_JS));
588 resources.push_back(std::make_pair("guestViewAttributes",
589 IDR_GUEST_VIEW_ATTRIBUTES_JS));
590 resources.push_back(std::make_pair("guestViewContainer",
591 IDR_GUEST_VIEW_CONTAINER_JS));
592 resources.push_back(std::make_pair("guestViewDeny", IDR_GUEST_VIEW_DENY_JS));
593 resources.push_back(std::make_pair("guestViewEvents",
594 IDR_GUEST_VIEW_EVENTS_JS));
596 if (content::BrowserPluginGuestMode::UseCrossProcessFramesForGuests()) {
597 resources.push_back(std::make_pair("guestViewIframe",
598 IDR_GUEST_VIEW_IFRAME_JS));
599 resources.push_back(std::make_pair("guestViewIframeContainer",
600 IDR_GUEST_VIEW_IFRAME_CONTAINER_JS));
603 resources.push_back(std::make_pair("imageUtil", IDR_IMAGE_UTIL_JS));
604 resources.push_back(std::make_pair("json_schema", IDR_JSON_SCHEMA_JS));
605 resources.push_back(std::make_pair("lastError", IDR_LAST_ERROR_JS));
606 resources.push_back(std::make_pair("messaging", IDR_MESSAGING_JS));
607 resources.push_back(std::make_pair("messaging_utils",
608 IDR_MESSAGING_UTILS_JS));
609 resources.push_back(std::make_pair(kSchemaUtils, IDR_SCHEMA_UTILS_JS));
610 resources.push_back(std::make_pair("sendRequest", IDR_SEND_REQUEST_JS));
611 resources.push_back(std::make_pair("setIcon", IDR_SET_ICON_JS));
612 resources.push_back(std::make_pair("test", IDR_TEST_CUSTOM_BINDINGS_JS));
613 resources.push_back(
614 std::make_pair("test_environment_specific_bindings",
615 IDR_BROWSER_TEST_ENVIRONMENT_SPECIFIC_BINDINGS_JS));
616 resources.push_back(std::make_pair("uncaught_exception_handler",
617 IDR_UNCAUGHT_EXCEPTION_HANDLER_JS));
618 resources.push_back(std::make_pair("unload_event", IDR_UNLOAD_EVENT_JS));
619 resources.push_back(std::make_pair("utils", IDR_UTILS_JS));
620 resources.push_back(std::make_pair("webRequest",
621 IDR_WEB_REQUEST_CUSTOM_BINDINGS_JS));
622 resources.push_back(
623 std::make_pair("webRequestInternal",
624 IDR_WEB_REQUEST_INTERNAL_CUSTOM_BINDINGS_JS));
625 // Note: webView not webview so that this doesn't interfere with the
626 // chrome.webview API bindings.
627 resources.push_back(std::make_pair("webView", IDR_WEB_VIEW_JS));
628 resources.push_back(std::make_pair("webViewActionRequests",
629 IDR_WEB_VIEW_ACTION_REQUESTS_JS));
630 resources.push_back(std::make_pair("webViewApiMethods",
631 IDR_WEB_VIEW_API_METHODS_JS));
632 resources.push_back(std::make_pair("webViewAttributes",
633 IDR_WEB_VIEW_ATTRIBUTES_JS));
634 resources.push_back(std::make_pair("webViewConstants",
635 IDR_WEB_VIEW_CONSTANTS_JS));
636 resources.push_back(std::make_pair("webViewEvents", IDR_WEB_VIEW_EVENTS_JS));
637 resources.push_back(std::make_pair("webViewInternal",
638 IDR_WEB_VIEW_INTERNAL_CUSTOM_BINDINGS_JS));
639 if (content::BrowserPluginGuestMode::UseCrossProcessFramesForGuests()) {
640 resources.push_back(std::make_pair("webViewIframe",
641 IDR_WEB_VIEW_IFRAME_JS));
643 resources.push_back(
644 std::make_pair(mojo::kBindingsModuleName, IDR_MOJO_BINDINGS_JS));
645 resources.push_back(
646 std::make_pair(mojo::kBufferModuleName, IDR_MOJO_BUFFER_JS));
647 resources.push_back(
648 std::make_pair(mojo::kCodecModuleName, IDR_MOJO_CODEC_JS));
649 resources.push_back(
650 std::make_pair(mojo::kConnectionModuleName, IDR_MOJO_CONNECTION_JS));
651 resources.push_back(
652 std::make_pair(mojo::kConnectorModuleName, IDR_MOJO_CONNECTOR_JS));
653 resources.push_back(
654 std::make_pair(mojo::kRouterModuleName, IDR_MOJO_ROUTER_JS));
655 resources.push_back(
656 std::make_pair(mojo::kUnicodeModuleName, IDR_MOJO_UNICODE_JS));
657 resources.push_back(
658 std::make_pair(mojo::kValidatorModuleName, IDR_MOJO_VALIDATOR_JS));
659 resources.push_back(std::make_pair("async_waiter", IDR_ASYNC_WAITER_JS));
660 resources.push_back(std::make_pair("data_receiver", IDR_DATA_RECEIVER_JS));
661 resources.push_back(std::make_pair("data_sender", IDR_DATA_SENDER_JS));
662 resources.push_back(std::make_pair("keep_alive", IDR_KEEP_ALIVE_JS));
663 resources.push_back(std::make_pair("extensions/common/mojo/keep_alive.mojom",
664 IDR_KEEP_ALIVE_MOJOM_JS));
665 resources.push_back(std::make_pair("device/serial/data_stream.mojom",
666 IDR_DATA_STREAM_MOJOM_JS));
667 resources.push_back(
668 std::make_pair("device/serial/data_stream_serialization.mojom",
669 IDR_DATA_STREAM_SERIALIZATION_MOJOM_JS));
670 resources.push_back(std::make_pair("stash_client", IDR_STASH_CLIENT_JS));
671 resources.push_back(
672 std::make_pair("extensions/common/mojo/stash.mojom", IDR_STASH_MOJOM_JS));
674 // Custom bindings.
675 resources.push_back(
676 std::make_pair("app.runtime", IDR_APP_RUNTIME_CUSTOM_BINDINGS_JS));
677 resources.push_back(
678 std::make_pair("app.window", IDR_APP_WINDOW_CUSTOM_BINDINGS_JS));
679 resources.push_back(
680 std::make_pair("declarativeWebRequest",
681 IDR_DECLARATIVE_WEBREQUEST_CUSTOM_BINDINGS_JS));
682 resources.push_back(
683 std::make_pair("contextMenus", IDR_CONTEXT_MENUS_CUSTOM_BINDINGS_JS));
684 resources.push_back(
685 std::make_pair("contextMenusHandlers", IDR_CONTEXT_MENUS_HANDLERS_JS));
686 resources.push_back(
687 std::make_pair("extension", IDR_EXTENSION_CUSTOM_BINDINGS_JS));
688 resources.push_back(std::make_pair("i18n", IDR_I18N_CUSTOM_BINDINGS_JS));
689 resources.push_back(std::make_pair(
690 "mimeHandlerPrivate", IDR_MIME_HANDLER_PRIVATE_CUSTOM_BINDINGS_JS));
691 resources.push_back(std::make_pair("extensions/common/api/mime_handler.mojom",
692 IDR_MIME_HANDLER_MOJOM_JS));
693 resources.push_back(
694 std::make_pair("mojoPrivate", IDR_MOJO_PRIVATE_CUSTOM_BINDINGS_JS));
695 resources.push_back(
696 std::make_pair("permissions", IDR_PERMISSIONS_CUSTOM_BINDINGS_JS));
697 resources.push_back(std::make_pair("printerProvider",
698 IDR_PRINTER_PROVIDER_CUSTOM_BINDINGS_JS));
699 resources.push_back(
700 std::make_pair("runtime", IDR_RUNTIME_CUSTOM_BINDINGS_JS));
701 resources.push_back(std::make_pair("windowControls", IDR_WINDOW_CONTROLS_JS));
702 resources.push_back(
703 std::make_pair("webViewRequest",
704 IDR_WEB_VIEW_REQUEST_CUSTOM_BINDINGS_JS));
705 resources.push_back(std::make_pair("binding", IDR_BINDING_JS));
707 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
708 switches::kEnableMojoSerialService)) {
709 resources.push_back(
710 std::make_pair("serial", IDR_SERIAL_CUSTOM_BINDINGS_JS));
712 resources.push_back(std::make_pair("serial_service", IDR_SERIAL_SERVICE_JS));
713 resources.push_back(
714 std::make_pair("device/serial/serial.mojom", IDR_SERIAL_MOJOM_JS));
715 resources.push_back(std::make_pair("device/serial/serial_serialization.mojom",
716 IDR_SERIAL_SERIALIZATION_MOJOM_JS));
718 // Custom types sources.
719 resources.push_back(std::make_pair("StorageArea", IDR_STORAGE_AREA_JS));
721 // Platform app sources that are not API-specific..
722 resources.push_back(std::make_pair("platformApp", IDR_PLATFORM_APP_JS));
724 #if defined(ENABLE_MEDIA_ROUTER)
725 resources.push_back(
726 std::make_pair("chrome/browser/media/router/media_router.mojom",
727 IDR_MEDIA_ROUTER_MOJOM_JS));
728 resources.push_back(
729 std::make_pair("media_router_bindings", IDR_MEDIA_ROUTER_BINDINGS_JS));
730 #endif // defined(ENABLE_MEDIA_ROUTER)
732 return resources;
735 // NOTE: please use the naming convention "foo_natives" for these.
736 // static
737 void Dispatcher::RegisterNativeHandlers(ModuleSystem* module_system,
738 ScriptContext* context,
739 Dispatcher* dispatcher,
740 RequestSender* request_sender,
741 V8SchemaRegistry* v8_schema_registry) {
742 module_system->RegisterNativeHandler(
743 "chrome", scoped_ptr<NativeHandler>(new ChromeNativeHandler(context)));
744 module_system->RegisterNativeHandler(
745 "lazy_background_page",
746 scoped_ptr<NativeHandler>(new LazyBackgroundPageNativeHandler(context)));
747 module_system->RegisterNativeHandler(
748 "logging", scoped_ptr<NativeHandler>(new LoggingNativeHandler(context)));
749 module_system->RegisterNativeHandler("schema_registry",
750 v8_schema_registry->AsNativeHandler());
751 module_system->RegisterNativeHandler(
752 "print", scoped_ptr<NativeHandler>(new PrintNativeHandler(context)));
753 module_system->RegisterNativeHandler(
754 "test_features",
755 scoped_ptr<NativeHandler>(new TestFeaturesNativeHandler(context)));
756 module_system->RegisterNativeHandler(
757 "test_native_handler",
758 scoped_ptr<NativeHandler>(new TestNativeHandler(context)));
759 module_system->RegisterNativeHandler(
760 "user_gestures",
761 scoped_ptr<NativeHandler>(new UserGesturesNativeHandler(context)));
762 module_system->RegisterNativeHandler(
763 "utils", scoped_ptr<NativeHandler>(new UtilsNativeHandler(context)));
764 module_system->RegisterNativeHandler(
765 "v8_context",
766 scoped_ptr<NativeHandler>(
767 new V8ContextNativeHandler(context, dispatcher)));
768 module_system->RegisterNativeHandler(
769 "event_natives", scoped_ptr<NativeHandler>(new EventBindings(context)));
770 module_system->RegisterNativeHandler(
771 "messaging_natives",
772 scoped_ptr<NativeHandler>(MessagingBindings::Get(dispatcher, context)));
773 module_system->RegisterNativeHandler(
774 "apiDefinitions",
775 scoped_ptr<NativeHandler>(
776 new ApiDefinitionsNatives(dispatcher, context)));
777 module_system->RegisterNativeHandler(
778 "sendRequest",
779 scoped_ptr<NativeHandler>(
780 new SendRequestNatives(request_sender, context)));
781 module_system->RegisterNativeHandler(
782 "setIcon",
783 scoped_ptr<NativeHandler>(new SetIconNatives(context)));
784 module_system->RegisterNativeHandler(
785 "activityLogger",
786 scoped_ptr<NativeHandler>(new APIActivityLogger(context)));
787 module_system->RegisterNativeHandler(
788 "renderFrameObserverNatives",
789 scoped_ptr<NativeHandler>(new RenderFrameObserverNatives(context)));
791 // Natives used by multiple APIs.
792 module_system->RegisterNativeHandler(
793 "file_system_natives",
794 scoped_ptr<NativeHandler>(new FileSystemNatives(context)));
796 // Custom bindings.
797 // |dispatcher| is null in unit tests.
798 const ScriptContextSet* script_context_set = dispatcher ?
799 &dispatcher->script_context_set() : nullptr;
800 module_system->RegisterNativeHandler(
801 "app_window_natives",
802 scoped_ptr<NativeHandler>(new AppWindowCustomBindings(
803 script_context_set, context)));
804 module_system->RegisterNativeHandler(
805 "blob_natives",
806 scoped_ptr<NativeHandler>(new BlobNativeHandler(context)));
807 module_system->RegisterNativeHandler(
808 "context_menus",
809 scoped_ptr<NativeHandler>(new ContextMenusCustomBindings(context)));
810 module_system->RegisterNativeHandler(
811 "css_natives", scoped_ptr<NativeHandler>(new CssNativeHandler(context)));
812 module_system->RegisterNativeHandler(
813 "document_natives",
814 scoped_ptr<NativeHandler>(new DocumentCustomBindings(context)));
815 module_system->RegisterNativeHandler(
816 "guest_view_internal",
817 scoped_ptr<NativeHandler>(
818 new GuestViewInternalCustomBindings(context)));
819 module_system->RegisterNativeHandler(
820 "i18n", scoped_ptr<NativeHandler>(new I18NCustomBindings(context)));
821 module_system->RegisterNativeHandler(
822 "id_generator",
823 scoped_ptr<NativeHandler>(new IdGeneratorCustomBindings(context)));
824 module_system->RegisterNativeHandler(
825 "runtime", scoped_ptr<NativeHandler>(new RuntimeCustomBindings(context)));
828 bool Dispatcher::OnControlMessageReceived(const IPC::Message& message) {
829 bool handled = true;
830 IPC_BEGIN_MESSAGE_MAP(Dispatcher, message)
831 IPC_MESSAGE_HANDLER(ExtensionMsg_ActivateExtension, OnActivateExtension)
832 IPC_MESSAGE_HANDLER(ExtensionMsg_CancelSuspend, OnCancelSuspend)
833 IPC_MESSAGE_HANDLER(ExtensionMsg_DeliverMessage, OnDeliverMessage)
834 IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnConnect, OnDispatchOnConnect)
835 IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnDisconnect, OnDispatchOnDisconnect)
836 IPC_MESSAGE_HANDLER(ExtensionMsg_Loaded, OnLoaded)
837 IPC_MESSAGE_HANDLER(ExtensionMsg_MessageInvoke, OnMessageInvoke)
838 IPC_MESSAGE_HANDLER(ExtensionMsg_SetChannel, OnSetChannel)
839 IPC_MESSAGE_HANDLER(ExtensionMsg_SetFunctionNames, OnSetFunctionNames)
840 IPC_MESSAGE_HANDLER(ExtensionMsg_SetScriptingWhitelist,
841 OnSetScriptingWhitelist)
842 IPC_MESSAGE_HANDLER(ExtensionMsg_SetSystemFont, OnSetSystemFont)
843 IPC_MESSAGE_HANDLER(ExtensionMsg_ShouldSuspend, OnShouldSuspend)
844 IPC_MESSAGE_HANDLER(ExtensionMsg_Suspend, OnSuspend)
845 IPC_MESSAGE_HANDLER(ExtensionMsg_TransferBlobs, OnTransferBlobs)
846 IPC_MESSAGE_HANDLER(ExtensionMsg_Unloaded, OnUnloaded)
847 IPC_MESSAGE_HANDLER(ExtensionMsg_UpdatePermissions, OnUpdatePermissions)
848 IPC_MESSAGE_HANDLER(ExtensionMsg_UpdateTabSpecificPermissions,
849 OnUpdateTabSpecificPermissions)
850 IPC_MESSAGE_HANDLER(ExtensionMsg_ClearTabSpecificPermissions,
851 OnClearTabSpecificPermissions)
852 IPC_MESSAGE_HANDLER(ExtensionMsg_UsingWebRequestAPI, OnUsingWebRequestAPI)
853 IPC_MESSAGE_FORWARD(ExtensionMsg_WatchPages,
854 content_watcher_.get(),
855 ContentWatcher::OnWatchPages)
856 IPC_MESSAGE_UNHANDLED(handled = false)
857 IPC_END_MESSAGE_MAP()
859 return handled;
862 void Dispatcher::WebKitInitialized() {
863 RenderThread::Get()->RegisterExtension(SafeBuiltins::CreateV8Extension());
865 // For extensions, we want to ensure we call the IdleHandler every so often,
866 // even if the extension keeps up activity.
867 if (set_idle_notifications_) {
868 forced_idle_timer_.reset(new base::RepeatingTimer<content::RenderThread>);
869 forced_idle_timer_->Start(
870 FROM_HERE,
871 base::TimeDelta::FromMilliseconds(kMaxExtensionIdleHandlerDelayMs),
872 RenderThread::Get(),
873 &RenderThread::IdleHandler);
876 // Initialize host permissions for any extensions that were activated before
877 // WebKit was initialized.
878 for (const std::string& extension_id : active_extension_ids_) {
879 const Extension* extension =
880 RendererExtensionRegistry::Get()->GetByID(extension_id);
881 CHECK(extension);
882 InitOriginPermissions(extension);
885 EnableCustomElementWhiteList();
887 is_webkit_initialized_ = true;
890 void Dispatcher::IdleNotification() {
891 if (set_idle_notifications_ && forced_idle_timer_) {
892 // Dampen the forced delay as well if the extension stays idle for long
893 // periods of time. (forced_idle_timer_ can be NULL after
894 // OnRenderProcessShutdown has been called.)
895 int64 forced_delay_ms =
896 std::max(RenderThread::Get()->GetIdleNotificationDelayInMs(),
897 kMaxExtensionIdleHandlerDelayMs);
898 forced_idle_timer_->Stop();
899 forced_idle_timer_->Start(
900 FROM_HERE,
901 base::TimeDelta::FromMilliseconds(forced_delay_ms),
902 RenderThread::Get(),
903 &RenderThread::IdleHandler);
907 void Dispatcher::OnRenderProcessShutdown() {
908 v8_schema_registry_.reset();
909 forced_idle_timer_.reset();
910 content_watcher_.reset();
913 void Dispatcher::OnActivateExtension(const std::string& extension_id) {
914 const Extension* extension =
915 RendererExtensionRegistry::Get()->GetByID(extension_id);
916 if (!extension) {
917 // Extension was activated but was never loaded. This probably means that
918 // the renderer failed to load it (or the browser failed to tell us when it
919 // did). Failures shouldn't happen, but instead of crashing there (which
920 // executes on all renderers) be conservative and only crash in the renderer
921 // of the extension which failed to load; this one.
922 std::string& error = extension_load_errors_[extension_id];
923 char minidump[256];
924 base::debug::Alias(&minidump);
925 base::snprintf(minidump,
926 arraysize(minidump),
927 "e::dispatcher:%s:%s",
928 extension_id.c_str(),
929 error.c_str());
930 LOG(FATAL) << extension_id << " was never loaded: " << error;
933 active_extension_ids_.insert(extension_id);
935 // This is called when starting a new extension page, so start the idle
936 // handler ticking.
937 RenderThread::Get()->ScheduleIdleHandler(kInitialExtensionIdleHandlerDelayMs);
939 if (is_webkit_initialized_) {
940 DOMActivityLogger::AttachToWorld(
941 DOMActivityLogger::kMainWorldId, extension_id);
943 InitOriginPermissions(extension);
946 UpdateActiveExtensions();
949 void Dispatcher::OnCancelSuspend(const std::string& extension_id) {
950 DispatchEvent(extension_id, kOnSuspendCanceledEvent);
953 void Dispatcher::OnDeliverMessage(int target_port_id, const Message& message) {
954 scoped_ptr<RequestSender::ScopedTabID> scoped_tab_id;
955 std::map<int, int>::const_iterator it =
956 port_to_tab_id_map_.find(target_port_id);
957 if (it != port_to_tab_id_map_.end()) {
958 scoped_tab_id.reset(
959 new RequestSender::ScopedTabID(request_sender(), it->second));
962 MessagingBindings::DeliverMessage(*script_context_set_, target_port_id,
963 message,
964 NULL); // All render frames.
967 void Dispatcher::OnDispatchOnConnect(
968 int target_port_id,
969 const std::string& channel_name,
970 const ExtensionMsg_TabConnectionInfo& source,
971 const ExtensionMsg_ExternalConnectionInfo& info,
972 const std::string& tls_channel_id) {
973 DCHECK(!ContainsKey(port_to_tab_id_map_, target_port_id));
974 DCHECK_EQ(1, target_port_id % 2); // target renderer ports have odd IDs.
975 int sender_tab_id = -1;
976 source.tab.GetInteger("id", &sender_tab_id);
977 port_to_tab_id_map_[target_port_id] = sender_tab_id;
979 MessagingBindings::DispatchOnConnect(*script_context_set_, target_port_id,
980 channel_name, source, info,
981 tls_channel_id,
982 NULL); // All render frames.
985 void Dispatcher::OnDispatchOnDisconnect(int port_id,
986 const std::string& error_message) {
987 MessagingBindings::DispatchOnDisconnect(*script_context_set_, port_id,
988 error_message,
989 NULL); // All render frames.
992 void Dispatcher::OnLoaded(
993 const std::vector<ExtensionMsg_Loaded_Params>& loaded_extensions) {
994 for (const auto& param : loaded_extensions) {
995 std::string error;
996 scoped_refptr<const Extension> extension = param.ConvertToExtension(&error);
997 if (!extension.get()) {
998 NOTREACHED() << error;
999 // Note: in tests |param.id| has been observed to be empty (see comment
1000 // just below) so this isn't all that reliable.
1001 extension_load_errors_[param.id] = error;
1002 continue;
1005 RendererExtensionRegistry* extension_registry =
1006 RendererExtensionRegistry::Get();
1007 // TODO(kalman): This test is deliberately not a CHECK (though I wish it
1008 // could be) and uses extension->id() not params.id:
1009 // 1. For some reason params.id can be empty. I've only seen it with
1010 // the webstore extension, in tests, and I've spent some time trying to
1011 // figure out why - but cost/benefit won.
1012 // 2. The browser only sends this IPC to RenderProcessHosts once, but the
1013 // Dispatcher is attached to a RenderThread. Presumably there is a
1014 // mismatch there. In theory one would think it's possible for the
1015 // browser to figure this out itself - but again, cost/benefit.
1016 if (!extension_registry->Contains(extension->id()))
1017 extension_registry->Insert(extension);
1020 // Update the available bindings for all contexts. These may have changed if
1021 // an externally_connectable extension was loaded that can connect to an
1022 // open webpage.
1023 UpdateBindings("");
1026 void Dispatcher::OnMessageInvoke(const std::string& extension_id,
1027 const std::string& module_name,
1028 const std::string& function_name,
1029 const base::ListValue& args,
1030 bool user_gesture) {
1031 InvokeModuleSystemMethod(
1032 NULL, extension_id, module_name, function_name, args, user_gesture);
1035 void Dispatcher::OnSetChannel(int channel) {
1036 delegate_->SetChannel(channel);
1037 AddChannelSpecificFeatures();
1040 void Dispatcher::OnSetFunctionNames(const std::vector<std::string>& names) {
1041 function_names_.clear();
1042 for (size_t i = 0; i < names.size(); ++i)
1043 function_names_.insert(names[i]);
1046 void Dispatcher::OnSetScriptingWhitelist(
1047 const ExtensionsClient::ScriptingWhitelist& extension_ids) {
1048 ExtensionsClient::Get()->SetScriptingWhitelist(extension_ids);
1051 void Dispatcher::OnSetSystemFont(const std::string& font_family,
1052 const std::string& font_size) {
1053 system_font_family_ = font_family;
1054 system_font_size_ = font_size;
1057 void Dispatcher::OnShouldSuspend(const std::string& extension_id,
1058 uint64 sequence_id) {
1059 RenderThread::Get()->Send(
1060 new ExtensionHostMsg_ShouldSuspendAck(extension_id, sequence_id));
1063 void Dispatcher::OnSuspend(const std::string& extension_id) {
1064 // Dispatch the suspend event. This doesn't go through the standard event
1065 // dispatch machinery because it requires special handling. We need to let
1066 // the browser know when we are starting and stopping the event dispatch, so
1067 // that it still considers the extension idle despite any activity the suspend
1068 // event creates.
1069 DispatchEvent(extension_id, kOnSuspendEvent);
1070 RenderThread::Get()->Send(new ExtensionHostMsg_SuspendAck(extension_id));
1073 void Dispatcher::OnTransferBlobs(const std::vector<std::string>& blob_uuids) {
1074 RenderThread::Get()->Send(new ExtensionHostMsg_TransferBlobsAck(blob_uuids));
1077 void Dispatcher::OnUnloaded(const std::string& id) {
1078 // See comment in OnLoaded for why it would be nice, but perhaps incorrect,
1079 // to CHECK here rather than guarding.
1080 if (!RendererExtensionRegistry::Get()->Remove(id))
1081 return;
1083 active_extension_ids_.erase(id);
1085 script_injection_manager_->OnExtensionUnloaded(id);
1087 // If the extension is later reloaded with a different set of permissions,
1088 // we'd like it to get a new isolated world ID, so that it can pick up the
1089 // changed origin whitelist.
1090 ScriptInjection::RemoveIsolatedWorld(id);
1092 // Invalidate all of the contexts that were removed.
1093 // TODO(kalman): add an invalidation observer interface to ScriptContext.
1094 std::set<ScriptContext*> removed_contexts =
1095 script_context_set_->OnExtensionUnloaded(id);
1096 for (ScriptContext* context : removed_contexts) {
1097 request_sender_->InvalidateSource(context);
1100 // Update the available bindings for the remaining contexts. These may have
1101 // changed if an externally_connectable extension is unloaded and a webpage
1102 // is no longer accessible.
1103 UpdateBindings("");
1105 // Invalidates the messages map for the extension in case the extension is
1106 // reloaded with a new messages map.
1107 EraseL10nMessagesMap(id);
1109 // We don't do anything with existing platform-app stylesheets. They will
1110 // stay resident, but the URL pattern corresponding to the unloaded
1111 // extension's URL just won't match anything anymore.
1114 void Dispatcher::OnUpdatePermissions(
1115 const ExtensionMsg_UpdatePermissions_Params& params) {
1116 const Extension* extension =
1117 RendererExtensionRegistry::Get()->GetByID(params.extension_id);
1118 if (!extension)
1119 return;
1121 scoped_refptr<const PermissionSet> active =
1122 params.active_permissions.ToPermissionSet();
1123 scoped_refptr<const PermissionSet> withheld =
1124 params.withheld_permissions.ToPermissionSet();
1126 if (is_webkit_initialized_) {
1127 UpdateOriginPermissions(
1128 extension->url(),
1129 extension->permissions_data()->GetEffectiveHostPermissions(),
1130 active->effective_hosts());
1133 extension->permissions_data()->SetPermissions(active, withheld);
1134 UpdateBindings(extension->id());
1137 void Dispatcher::OnUpdateTabSpecificPermissions(const GURL& visible_url,
1138 const std::string& extension_id,
1139 const URLPatternSet& new_hosts,
1140 bool update_origin_whitelist,
1141 int tab_id) {
1142 const Extension* extension =
1143 RendererExtensionRegistry::Get()->GetByID(extension_id);
1144 if (!extension)
1145 return;
1147 URLPatternSet old_effective =
1148 extension->permissions_data()->GetEffectiveHostPermissions();
1149 extension->permissions_data()->UpdateTabSpecificPermissions(
1150 tab_id,
1151 new extensions::PermissionSet(extensions::APIPermissionSet(),
1152 extensions::ManifestPermissionSet(),
1153 new_hosts,
1154 extensions::URLPatternSet()));
1156 if (is_webkit_initialized_ && update_origin_whitelist) {
1157 UpdateOriginPermissions(
1158 extension->url(),
1159 old_effective,
1160 extension->permissions_data()->GetEffectiveHostPermissions());
1164 void Dispatcher::OnClearTabSpecificPermissions(
1165 const std::vector<std::string>& extension_ids,
1166 bool update_origin_whitelist,
1167 int tab_id) {
1168 for (const std::string& id : extension_ids) {
1169 const Extension* extension = RendererExtensionRegistry::Get()->GetByID(id);
1170 if (extension) {
1171 URLPatternSet old_effective =
1172 extension->permissions_data()->GetEffectiveHostPermissions();
1173 extension->permissions_data()->ClearTabSpecificPermissions(tab_id);
1174 if (is_webkit_initialized_ && update_origin_whitelist) {
1175 UpdateOriginPermissions(
1176 extension->url(),
1177 old_effective,
1178 extension->permissions_data()->GetEffectiveHostPermissions());
1184 void Dispatcher::OnUsingWebRequestAPI(bool webrequest_used) {
1185 webrequest_used_ = webrequest_used;
1188 void Dispatcher::OnUserScriptsUpdated(const std::set<HostID>& changed_hosts,
1189 const std::vector<UserScript*>& scripts) {
1190 UpdateActiveExtensions();
1193 void Dispatcher::UpdateActiveExtensions() {
1194 std::set<std::string> active_extensions = active_extension_ids_;
1195 user_script_set_manager_->GetAllActiveExtensionIds(&active_extensions);
1196 delegate_->OnActiveExtensionsUpdated(active_extensions);
1199 void Dispatcher::InitOriginPermissions(const Extension* extension) {
1200 delegate_->InitOriginPermissions(extension,
1201 IsExtensionActive(extension->id()));
1202 UpdateOriginPermissions(
1203 extension->url(),
1204 URLPatternSet(), // No old permissions.
1205 extension->permissions_data()->GetEffectiveHostPermissions());
1208 void Dispatcher::UpdateOriginPermissions(const GURL& extension_url,
1209 const URLPatternSet& old_patterns,
1210 const URLPatternSet& new_patterns) {
1211 static const char* kSchemes[] = {
1212 url::kHttpScheme,
1213 url::kHttpsScheme,
1214 url::kFileScheme,
1215 content::kChromeUIScheme,
1216 url::kFtpScheme,
1217 #if defined(OS_CHROMEOS)
1218 content::kExternalFileScheme,
1219 #endif
1220 extensions::kExtensionScheme,
1222 for (size_t i = 0; i < arraysize(kSchemes); ++i) {
1223 const char* scheme = kSchemes[i];
1224 // Remove all old patterns...
1225 for (URLPatternSet::const_iterator pattern = old_patterns.begin();
1226 pattern != old_patterns.end(); ++pattern) {
1227 if (pattern->MatchesScheme(scheme)) {
1228 WebSecurityPolicy::removeOriginAccessWhitelistEntry(
1229 extension_url,
1230 WebString::fromUTF8(scheme),
1231 WebString::fromUTF8(pattern->host()),
1232 pattern->match_subdomains());
1235 // ...And add the new ones.
1236 for (URLPatternSet::const_iterator pattern = new_patterns.begin();
1237 pattern != new_patterns.end(); ++pattern) {
1238 if (pattern->MatchesScheme(scheme)) {
1239 WebSecurityPolicy::addOriginAccessWhitelistEntry(
1240 extension_url,
1241 WebString::fromUTF8(scheme),
1242 WebString::fromUTF8(pattern->host()),
1243 pattern->match_subdomains());
1249 void Dispatcher::EnableCustomElementWhiteList() {
1250 blink::WebCustomElement::addEmbedderCustomElementName("appview");
1251 blink::WebCustomElement::addEmbedderCustomElementName("appviewbrowserplugin");
1252 blink::WebCustomElement::addEmbedderCustomElementName("extensionoptions");
1253 blink::WebCustomElement::addEmbedderCustomElementName(
1254 "extensionoptionsbrowserplugin");
1255 blink::WebCustomElement::addEmbedderCustomElementName("extensionview");
1256 blink::WebCustomElement::addEmbedderCustomElementName(
1257 "extensionviewbrowserplugin");
1258 blink::WebCustomElement::addEmbedderCustomElementName("webview");
1259 blink::WebCustomElement::addEmbedderCustomElementName("webviewbrowserplugin");
1262 void Dispatcher::UpdateBindings(const std::string& extension_id) {
1263 script_context_set().ForEach(extension_id,
1264 base::Bind(&Dispatcher::UpdateBindingsForContext,
1265 base::Unretained(this)));
1268 void Dispatcher::UpdateBindingsForContext(ScriptContext* context) {
1269 v8::HandleScope handle_scope(context->isolate());
1270 v8::Context::Scope context_scope(context->v8_context());
1272 // TODO(kalman): Make the bindings registration have zero overhead then run
1273 // the same code regardless of context type.
1274 switch (context->context_type()) {
1275 case Feature::UNSPECIFIED_CONTEXT:
1276 case Feature::WEB_PAGE_CONTEXT:
1277 case Feature::BLESSED_WEB_PAGE_CONTEXT:
1278 // Hard-code registration of any APIs that are exposed to webpage-like
1279 // contexts, because it's too expensive to run the full bindings code.
1280 // All of the same permission checks will still apply.
1281 if (context->GetAvailability("app").is_available())
1282 RegisterBinding("app", context);
1283 if (context->GetAvailability("webstore").is_available())
1284 RegisterBinding("webstore", context);
1285 if (context->GetAvailability("dashboardPrivate").is_available())
1286 RegisterBinding("dashboardPrivate", context);
1287 if (IsRuntimeAvailableToContext(context))
1288 RegisterBinding("runtime", context);
1289 UpdateContentCapabilities(context);
1290 break;
1292 case Feature::BLESSED_EXTENSION_CONTEXT:
1293 case Feature::UNBLESSED_EXTENSION_CONTEXT:
1294 case Feature::CONTENT_SCRIPT_CONTEXT:
1295 case Feature::WEBUI_CONTEXT: {
1296 // Extension context; iterate through all the APIs and bind the available
1297 // ones.
1298 const FeatureProvider* api_feature_provider =
1299 FeatureProvider::GetAPIFeatures();
1300 const std::vector<std::string>& apis =
1301 api_feature_provider->GetAllFeatureNames();
1302 for (const std::string& api_name : apis) {
1303 Feature* feature = api_feature_provider->GetFeature(api_name);
1304 DCHECK(feature);
1306 // Internal APIs are included via require(api_name) from internal code
1307 // rather than chrome[api_name].
1308 if (feature->IsInternal())
1309 continue;
1311 // If this API has a parent feature (and isn't marked 'noparent'),
1312 // then this must be a function or event, so we should not register.
1313 if (api_feature_provider->GetParent(feature) != NULL)
1314 continue;
1316 // Skip chrome.test if this isn't a test.
1317 if (api_name == "test" &&
1318 !base::CommandLine::ForCurrentProcess()->HasSwitch(
1319 ::switches::kTestType)) {
1320 continue;
1323 if (context->IsAnyFeatureAvailableToContext(*feature))
1324 RegisterBinding(api_name, context);
1326 break;
1328 case Feature::SERVICE_WORKER_CONTEXT:
1329 // Handled in DidInitializeServiceWorkerContextOnWorkerThread().
1330 NOTREACHED();
1331 break;
1335 void Dispatcher::RegisterBinding(const std::string& api_name,
1336 ScriptContext* context) {
1337 std::string bind_name;
1338 v8::Local<v8::Object> bind_object =
1339 GetOrCreateBindObjectIfAvailable(api_name, &bind_name, context);
1341 // Empty if the bind object failed to be created, probably because the
1342 // extension overrode chrome with a non-object, e.g. window.chrome = true.
1343 if (bind_object.IsEmpty())
1344 return;
1346 v8::Local<v8::String> v8_bind_name =
1347 v8::String::NewFromUtf8(context->isolate(), bind_name.c_str());
1348 if (bind_object->HasRealNamedProperty(v8_bind_name)) {
1349 // The bind object may already have the property if the API has been
1350 // registered before (or if the extension has put something there already,
1351 // but, whatevs).
1353 // In the former case, we need to re-register the bindings for the APIs
1354 // which the extension now has permissions for (if any), but not touch any
1355 // others so that we don't destroy state such as event listeners.
1357 // TODO(kalman): Only register available APIs to make this all moot.
1358 if (bind_object->HasRealNamedCallbackProperty(v8_bind_name))
1359 return; // lazy binding still there, nothing to do
1360 if (bind_object->Get(v8_bind_name)->IsObject())
1361 return; // binding has already been fully installed
1364 ModuleSystem* module_system = context->module_system();
1365 if (!source_map_.Contains(api_name)) {
1366 module_system->RegisterNativeHandler(
1367 api_name,
1368 scoped_ptr<NativeHandler>(new BindingGeneratingNativeHandler(
1369 context, api_name, "binding")));
1370 module_system->SetNativeLazyField(
1371 bind_object, bind_name, api_name, "binding");
1372 } else {
1373 module_system->SetLazyField(bind_object, bind_name, api_name, "binding");
1377 // NOTE: please use the naming convention "foo_natives" for these.
1378 void Dispatcher::RegisterNativeHandlers(ModuleSystem* module_system,
1379 ScriptContext* context) {
1380 RegisterNativeHandlers(module_system,
1381 context,
1382 this,
1383 request_sender_.get(),
1384 v8_schema_registry_.get());
1385 const Extension* extension = context->extension();
1386 int manifest_version = extension ? extension->manifest_version() : 1;
1387 bool is_component_extension =
1388 extension && Manifest::IsComponentLocation(extension->location());
1389 bool send_request_disabled =
1390 (extension && Manifest::IsUnpackedLocation(extension->location()) &&
1391 BackgroundInfo::HasLazyBackgroundPage(extension));
1392 module_system->RegisterNativeHandler(
1393 "process",
1394 scoped_ptr<NativeHandler>(new ProcessInfoNativeHandler(
1395 context,
1396 context->GetExtensionID(),
1397 context->GetContextTypeDescription(),
1398 ExtensionsRendererClient::Get()->IsIncognitoProcess(),
1399 is_component_extension,
1400 manifest_version,
1401 send_request_disabled)));
1403 delegate_->RegisterNativeHandlers(this, module_system, context);
1406 bool Dispatcher::IsRuntimeAvailableToContext(ScriptContext* context) {
1407 for (const auto& extension :
1408 *RendererExtensionRegistry::Get()->GetMainThreadExtensionSet()) {
1409 ExternallyConnectableInfo* info = static_cast<ExternallyConnectableInfo*>(
1410 extension->GetManifestData(manifest_keys::kExternallyConnectable));
1411 if (info && info->matches.MatchesURL(context->GetURL()))
1412 return true;
1414 return false;
1417 void Dispatcher::UpdateContentCapabilities(ScriptContext* context) {
1418 APIPermissionSet permissions;
1419 for (const auto& extension :
1420 *RendererExtensionRegistry::Get()->GetMainThreadExtensionSet()) {
1421 const ContentCapabilitiesInfo& info =
1422 ContentCapabilitiesInfo::Get(extension.get());
1423 if (info.url_patterns.MatchesURL(context->GetURL())) {
1424 APIPermissionSet new_permissions;
1425 APIPermissionSet::Union(permissions, info.permissions, &new_permissions);
1426 permissions = new_permissions;
1429 context->SetContentCapabilities(permissions);
1432 void Dispatcher::PopulateSourceMap() {
1433 const std::vector<std::pair<std::string, int> > resources = GetJsResources();
1434 for (std::vector<std::pair<std::string, int> >::const_iterator resource =
1435 resources.begin();
1436 resource != resources.end();
1437 ++resource) {
1438 source_map_.RegisterSource(resource->first, resource->second);
1440 delegate_->PopulateSourceMap(&source_map_);
1443 bool Dispatcher::IsWithinPlatformApp() {
1444 for (std::set<std::string>::iterator iter = active_extension_ids_.begin();
1445 iter != active_extension_ids_.end();
1446 ++iter) {
1447 const Extension* extension =
1448 RendererExtensionRegistry::Get()->GetByID(*iter);
1449 if (extension && extension->is_platform_app())
1450 return true;
1452 return false;
1455 v8::Local<v8::Object> Dispatcher::GetOrCreateObject(
1456 const v8::Local<v8::Object>& object,
1457 const std::string& field,
1458 v8::Isolate* isolate) {
1459 v8::Local<v8::String> key = v8::String::NewFromUtf8(isolate, field.c_str());
1460 // If the object has a callback property, it is assumed it is an unavailable
1461 // API, so it is safe to delete. This is checked before GetOrCreateObject is
1462 // called.
1463 if (object->HasRealNamedCallbackProperty(key)) {
1464 object->Delete(key);
1465 } else if (object->HasRealNamedProperty(key)) {
1466 v8::Local<v8::Value> value = object->Get(key);
1467 CHECK(value->IsObject());
1468 return v8::Local<v8::Object>::Cast(value);
1471 v8::Local<v8::Object> new_object = v8::Object::New(isolate);
1472 object->Set(key, new_object);
1473 return new_object;
1476 v8::Local<v8::Object> Dispatcher::GetOrCreateBindObjectIfAvailable(
1477 const std::string& api_name,
1478 std::string* bind_name,
1479 ScriptContext* context) {
1480 std::vector<std::string> split = base::SplitString(
1481 api_name, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
1483 v8::Local<v8::Object> bind_object;
1485 // Check if this API has an ancestor. If the API's ancestor is available and
1486 // the API is not available, don't install the bindings for this API. If
1487 // the API is available and its ancestor is not, delete the ancestor and
1488 // install the bindings for the API. This is to prevent loading the ancestor
1489 // API schema if it will not be needed.
1491 // For example:
1492 // If app is available and app.window is not, just install app.
1493 // If app.window is available and app is not, delete app and install
1494 // app.window on a new object so app does not have to be loaded.
1495 const FeatureProvider* api_feature_provider =
1496 FeatureProvider::GetAPIFeatures();
1497 std::string ancestor_name;
1498 bool only_ancestor_available = false;
1500 for (size_t i = 0; i < split.size() - 1; ++i) {
1501 ancestor_name += (i ? "." : "") + split[i];
1502 if (api_feature_provider->GetFeature(ancestor_name) &&
1503 context->GetAvailability(ancestor_name).is_available() &&
1504 !context->GetAvailability(api_name).is_available()) {
1505 only_ancestor_available = true;
1506 break;
1509 if (bind_object.IsEmpty()) {
1510 bind_object = AsObjectOrEmpty(GetOrCreateChrome(context));
1511 if (bind_object.IsEmpty())
1512 return v8::Local<v8::Object>();
1514 bind_object = GetOrCreateObject(bind_object, split[i], context->isolate());
1517 if (only_ancestor_available)
1518 return v8::Local<v8::Object>();
1520 if (bind_name)
1521 *bind_name = split.back();
1523 return bind_object.IsEmpty() ? AsObjectOrEmpty(GetOrCreateChrome(context))
1524 : bind_object;
1527 void Dispatcher::RequireGuestViewModules(ScriptContext* context) {
1528 Feature::Context context_type = context->context_type();
1529 ModuleSystem* module_system = context->module_system();
1531 // Require AppView.
1532 if (context->GetAvailability("appViewEmbedderInternal").is_available()) {
1533 module_system->Require("appView");
1536 // Require ExtensionOptions.
1537 if (context->GetAvailability("extensionOptionsInternal").is_available()) {
1538 module_system->Require("extensionOptions");
1539 module_system->Require("extensionOptionsAttributes");
1542 // Require ExtensionView.
1543 if (context->GetAvailability("extensionViewInternal").is_available()) {
1544 module_system->Require("extensionView");
1545 module_system->Require("extensionViewApiMethods");
1546 module_system->Require("extensionViewAttributes");
1549 // Require WebView.
1550 if (context->GetAvailability("webViewInternal").is_available()) {
1551 module_system->Require("webView");
1552 module_system->Require("webViewApiMethods");
1553 module_system->Require("webViewAttributes");
1555 if (content::BrowserPluginGuestMode::UseCrossProcessFramesForGuests()) {
1556 module_system->Require("webViewIframe");
1560 // The "guestViewDeny" module must always be loaded last. It registers
1561 // error-providing custom elements for the GuestView types that are not
1562 // available, and thus all of those types must have been checked and loaded
1563 // (or not loaded) beforehand.
1564 if (context_type == Feature::BLESSED_EXTENSION_CONTEXT) {
1565 module_system->Require("guestViewDeny");
1569 void Dispatcher::AddChannelSpecificFeatures() {
1570 // chrome-extension: resources should be allowed to register a Service Worker.
1571 if (FeatureProvider::GetBehaviorFeature(BehaviorFeature::kServiceWorker)
1572 ->IsAvailableToEnvironment()
1573 .is_available())
1574 WebSecurityPolicy::registerURLSchemeAsAllowingServiceWorkers(
1575 WebString::fromUTF8(kExtensionScheme));
1578 } // namespace extensions