Add new certificateProvider extension API.
[chromium-blink-merge.git] / extensions / renderer / dispatcher.cc
blobad631e7dd18e1ce1bcc25e25ffcf685fe96e01a5
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 scoped_ptr<ScriptContext> existing = script_contexts_.take_and_erase(url);
203 // This should be CHECK(!existing), but can't until these ScriptContexts
204 // are keyed on v8::Contexts rather than URLs. See crbug.com/525965.
205 if (existing)
206 existing->Invalidate();
207 script_contexts_.set(url, context.Pass());
210 void Remove(const GURL& url) {
211 base::AutoLock lock(lock_);
212 scoped_ptr<ScriptContext> context = script_contexts_.take_and_erase(url);
213 CHECK(context);
214 context->Invalidate();
217 private:
218 base::ScopedPtrMap<GURL, scoped_ptr<ScriptContext>> script_contexts_;
220 mutable base::Lock lock_;
222 DISALLOW_COPY_AND_ASSIGN(ServiceWorkerScriptContextSet);
225 base::LazyInstance<ServiceWorkerScriptContextSet>
226 g_service_worker_script_context_set = LAZY_INSTANCE_INITIALIZER;
228 } // namespace
230 // Note that we can't use Blink public APIs in the constructor becase Blink
231 // is not initialized at the point we create Dispatcher.
232 Dispatcher::Dispatcher(DispatcherDelegate* delegate)
233 : delegate_(delegate),
234 content_watcher_(new ContentWatcher()),
235 source_map_(&ResourceBundle::GetSharedInstance()),
236 v8_schema_registry_(new V8SchemaRegistry),
237 is_webkit_initialized_(false),
238 user_script_set_manager_observer_(this),
239 webrequest_used_(false) {
240 const base::CommandLine& command_line =
241 *(base::CommandLine::ForCurrentProcess());
242 set_idle_notifications_ =
243 command_line.HasSwitch(switches::kExtensionProcess) ||
244 command_line.HasSwitch(::switches::kSingleProcess);
246 if (set_idle_notifications_) {
247 RenderThread::Get()->SetIdleNotificationDelayInMs(
248 kInitialExtensionIdleHandlerDelayMs);
251 script_context_set_.reset(new ScriptContextSet(&active_extension_ids_));
252 user_script_set_manager_.reset(new UserScriptSetManager());
253 script_injection_manager_.reset(
254 new ScriptInjectionManager(user_script_set_manager_.get()));
255 user_script_set_manager_observer_.Add(user_script_set_manager_.get());
256 request_sender_.reset(new RequestSender(this));
257 PopulateSourceMap();
258 WakeEventPage::Get()->Init(content::RenderThread::Get());
261 Dispatcher::~Dispatcher() {
264 void Dispatcher::OnRenderFrameCreated(content::RenderFrame* render_frame) {
265 script_injection_manager_->OnRenderFrameCreated(render_frame);
268 bool Dispatcher::IsExtensionActive(const std::string& extension_id) const {
269 bool is_active =
270 active_extension_ids_.find(extension_id) != active_extension_ids_.end();
271 if (is_active)
272 CHECK(RendererExtensionRegistry::Get()->Contains(extension_id));
273 return is_active;
276 void Dispatcher::DidCreateScriptContext(
277 blink::WebLocalFrame* frame,
278 const v8::Local<v8::Context>& v8_context,
279 int extension_group,
280 int world_id) {
281 const base::TimeTicks start_time = base::TimeTicks::Now();
283 ScriptContext* context = script_context_set_->Register(
284 frame, v8_context, extension_group, world_id);
286 // Initialize origin permissions for content scripts, which can't be
287 // initialized in |OnActivateExtension|.
288 if (context->context_type() == Feature::CONTENT_SCRIPT_CONTEXT)
289 InitOriginPermissions(context->extension());
292 scoped_ptr<ModuleSystem> module_system(
293 new ModuleSystem(context, &source_map_));
294 context->set_module_system(module_system.Pass());
296 ModuleSystem* module_system = context->module_system();
298 // Enable natives in startup.
299 ModuleSystem::NativesEnabledScope natives_enabled_scope(module_system);
301 RegisterNativeHandlers(module_system, context);
303 // chrome.Event is part of the public API (although undocumented). Make it
304 // lazily evalulate to Event from event_bindings.js. For extensions only
305 // though, not all webpages!
306 if (context->extension()) {
307 v8::Local<v8::Object> chrome = AsObjectOrEmpty(GetOrCreateChrome(context));
308 if (!chrome.IsEmpty())
309 module_system->SetLazyField(chrome, "Event", kEventBindings, "Event");
312 UpdateBindingsForContext(context);
314 bool is_within_platform_app = IsWithinPlatformApp();
315 // Inject custom JS into the platform app context.
316 if (is_within_platform_app) {
317 module_system->Require("platformApp");
320 RequireGuestViewModules(context);
321 delegate_->RequireAdditionalModules(context, is_within_platform_app);
323 const base::TimeDelta elapsed = base::TimeTicks::Now() - start_time;
324 switch (context->context_type()) {
325 case Feature::UNSPECIFIED_CONTEXT:
326 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Unspecified",
327 elapsed);
328 break;
329 case Feature::BLESSED_EXTENSION_CONTEXT:
330 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Blessed", elapsed);
331 break;
332 case Feature::UNBLESSED_EXTENSION_CONTEXT:
333 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Unblessed",
334 elapsed);
335 break;
336 case Feature::CONTENT_SCRIPT_CONTEXT:
337 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_ContentScript",
338 elapsed);
339 break;
340 case Feature::WEB_PAGE_CONTEXT:
341 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_WebPage", elapsed);
342 break;
343 case Feature::BLESSED_WEB_PAGE_CONTEXT:
344 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_BlessedWebPage",
345 elapsed);
346 break;
347 case Feature::WEBUI_CONTEXT:
348 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_WebUI", elapsed);
349 break;
350 case Feature::SERVICE_WORKER_CONTEXT:
351 // Handled in DidInitializeServiceWorkerContextOnWorkerThread().
352 NOTREACHED();
353 break;
356 VLOG(1) << "Num tracked contexts: " << script_context_set_->size();
359 // static
360 void Dispatcher::DidInitializeServiceWorkerContextOnWorkerThread(
361 v8::Local<v8::Context> v8_context,
362 const GURL& url) {
363 const base::TimeTicks start_time = base::TimeTicks::Now();
365 if (!url.SchemeIs(kExtensionScheme) &&
366 !url.SchemeIs(kExtensionResourceScheme)) {
367 // Early-out if this isn't a chrome-extension:// or resource scheme,
368 // because looking up the extension registry is unnecessary if it's not.
369 // Checking this will also skip over hosted apps, which is the desired
370 // behavior - hosted app service workers are not our concern.
371 return;
374 const Extension* extension =
375 RendererExtensionRegistry::Get()->GetExtensionOrAppByURL(url);
377 if (!extension)
378 return;
380 ScriptContext* context = new ScriptContext(
381 v8_context, nullptr, extension, Feature::SERVICE_WORKER_CONTEXT,
382 extension, Feature::SERVICE_WORKER_CONTEXT);
384 g_service_worker_script_context_set.Get().Insert(url,
385 make_scoped_ptr(context));
387 v8::Isolate* isolate = context->isolate();
389 // Fetch the source code for service_worker_bindings.js.
390 base::StringPiece script_resource =
391 ResourceBundle::GetSharedInstance().GetRawDataResource(
392 IDR_SERVICE_WORKER_BINDINGS_JS);
393 v8::Local<v8::String> script = v8::String::NewExternal(
394 isolate, new StaticV8ExternalOneByteStringResource(script_resource));
396 // Run the script to get the main function, then run the main function to
397 // inject service worker bindings.
398 v8::Local<v8::Value> result = context->RunScript(
399 v8_helpers::ToV8StringUnsafe(isolate, "service_worker"), script,
400 base::Bind(&CrashOnException));
401 CHECK(result->IsFunction());
402 v8::Local<v8::Value> args[] = {
403 v8_helpers::ToV8StringUnsafe(
404 isolate, BackgroundInfo::GetBackgroundURL(extension).spec()),
406 context->CallFunction(result.As<v8::Function>(), arraysize(args), args);
408 const base::TimeDelta elapsed = base::TimeTicks::Now() - start_time;
409 UMA_HISTOGRAM_TIMES(
410 "Extensions.DidInitializeServiceWorkerContextOnWorkerThread", elapsed);
413 void Dispatcher::WillReleaseScriptContext(
414 blink::WebLocalFrame* frame,
415 const v8::Local<v8::Context>& v8_context,
416 int world_id) {
417 ScriptContext* context = script_context_set_->GetByV8Context(v8_context);
418 if (!context)
419 return;
421 context->DispatchOnUnloadEvent();
422 // TODO(kalman): Make |request_sender| use |context->AddInvalidationObserver|.
423 // In fact |request_sender_| should really be owned by ScriptContext.
424 request_sender_->InvalidateSource(context);
426 script_context_set_->Remove(context);
427 VLOG(1) << "Num tracked contexts: " << script_context_set_->size();
430 // static
431 void Dispatcher::WillDestroyServiceWorkerContextOnWorkerThread(
432 const GURL& url) {
433 if (url.SchemeIs(kExtensionScheme) ||
434 url.SchemeIs(kExtensionResourceScheme)) {
435 // See comment in DidInitializeServiceWorkerContextOnWorkerThread.
436 g_service_worker_script_context_set.Get().Remove(url);
440 void Dispatcher::DidCreateDocumentElement(blink::WebLocalFrame* frame) {
441 // Note: use GetEffectiveDocumentURL not just frame->document()->url()
442 // so that this also injects the stylesheet on about:blank frames that
443 // are hosted in the extension process.
444 GURL effective_document_url = ScriptContext::GetEffectiveDocumentURL(
445 frame, frame->document().url(), true /* match_about_blank */);
447 const Extension* extension =
448 RendererExtensionRegistry::Get()->GetExtensionOrAppByURL(
449 effective_document_url);
451 if (extension &&
452 (extension->is_extension() || extension->is_platform_app())) {
453 int resource_id = extension->is_platform_app() ? IDR_PLATFORM_APP_CSS
454 : IDR_EXTENSION_FONTS_CSS;
455 std::string stylesheet = ResourceBundle::GetSharedInstance()
456 .GetRawDataResource(resource_id)
457 .as_string();
458 base::ReplaceFirstSubstringAfterOffset(
459 &stylesheet, 0, "$FONTFAMILY", system_font_family_);
460 base::ReplaceFirstSubstringAfterOffset(
461 &stylesheet, 0, "$FONTSIZE", system_font_size_);
463 // Blink doesn't let us define an additional user agent stylesheet, so
464 // we insert the default platform app or extension stylesheet into all
465 // documents that are loaded in each app or extension.
466 frame->document().insertStyleSheet(WebString::fromUTF8(stylesheet));
469 // If this is an extension options page, and the extension has opted into
470 // using Chrome styles, then insert the Chrome extension stylesheet.
471 if (extension && extension->is_extension() &&
472 OptionsPageInfo::ShouldUseChromeStyle(extension) &&
473 effective_document_url == OptionsPageInfo::GetOptionsPage(extension)) {
474 frame->document().insertStyleSheet(
475 WebString::fromUTF8(ResourceBundle::GetSharedInstance()
476 .GetRawDataResource(IDR_EXTENSION_CSS)
477 .as_string()));
480 // In testing, the document lifetime events can happen after the render
481 // process shutdown event.
482 // See: http://crbug.com/21508 and http://crbug.com/500851
483 if (content_watcher_) {
484 content_watcher_->DidCreateDocumentElement(frame);
488 void Dispatcher::OnExtensionResponse(int request_id,
489 bool success,
490 const base::ListValue& response,
491 const std::string& error) {
492 request_sender_->HandleResponse(request_id, success, response, error);
495 void Dispatcher::DispatchEvent(const std::string& extension_id,
496 const std::string& event_name) const {
497 base::ListValue args;
498 args.Set(0, new base::StringValue(event_name));
499 args.Set(1, new base::ListValue());
501 // Needed for Windows compilation, since kEventBindings is declared extern.
502 const char* local_event_bindings = kEventBindings;
503 script_context_set_->ForEach(
504 extension_id, base::Bind(&CallModuleMethod, local_event_bindings,
505 kEventDispatchFunction, &args));
508 void Dispatcher::InvokeModuleSystemMethod(content::RenderFrame* render_frame,
509 const std::string& extension_id,
510 const std::string& module_name,
511 const std::string& function_name,
512 const base::ListValue& args,
513 bool user_gesture) {
514 scoped_ptr<WebScopedUserGesture> web_user_gesture;
515 if (user_gesture)
516 web_user_gesture.reset(new WebScopedUserGesture);
518 script_context_set_->ForEach(
519 extension_id, render_frame,
520 base::Bind(&CallModuleMethod, module_name, function_name, &args));
522 // Reset the idle handler each time there's any activity like event or message
523 // dispatch, for which Invoke is the chokepoint.
524 if (set_idle_notifications_) {
525 RenderThread::Get()->ScheduleIdleHandler(
526 kInitialExtensionIdleHandlerDelayMs);
529 // Tell the browser process when an event has been dispatched with a lazy
530 // background page active.
531 const Extension* extension =
532 RendererExtensionRegistry::Get()->GetByID(extension_id);
533 if (extension && BackgroundInfo::HasLazyBackgroundPage(extension) &&
534 module_name == kEventBindings &&
535 function_name == kEventDispatchFunction) {
536 content::RenderFrame* background_frame =
537 ExtensionFrameHelper::GetBackgroundPageFrame(extension_id);
538 if (background_frame) {
539 int message_id;
540 args.GetInteger(3, &message_id);
541 background_frame->Send(new ExtensionHostMsg_EventAck(
542 background_frame->GetRoutingID(), message_id));
547 void Dispatcher::ClearPortData(int port_id) {
548 // Only the target port side has entries in |port_to_tab_id_map_|. If
549 // |port_id| is a source port, std::map::erase() will just silently fail
550 // here as a no-op.
551 port_to_tab_id_map_.erase(port_id);
554 // static
555 std::vector<std::pair<std::string, int> > Dispatcher::GetJsResources() {
556 std::vector<std::pair<std::string, int> > resources;
558 // Libraries.
559 resources.push_back(std::make_pair("appView", IDR_APP_VIEW_JS));
560 resources.push_back(std::make_pair("entryIdManager", IDR_ENTRY_ID_MANAGER));
561 resources.push_back(std::make_pair(kEventBindings, IDR_EVENT_BINDINGS_JS));
562 resources.push_back(std::make_pair("extensionOptions",
563 IDR_EXTENSION_OPTIONS_JS));
564 resources.push_back(std::make_pair("extensionOptionsAttributes",
565 IDR_EXTENSION_OPTIONS_ATTRIBUTES_JS));
566 resources.push_back(std::make_pair("extensionOptionsConstants",
567 IDR_EXTENSION_OPTIONS_CONSTANTS_JS));
568 resources.push_back(std::make_pair("extensionOptionsEvents",
569 IDR_EXTENSION_OPTIONS_EVENTS_JS));
570 resources.push_back(std::make_pair("extensionView", IDR_EXTENSION_VIEW_JS));
571 resources.push_back(std::make_pair("extensionViewApiMethods",
572 IDR_EXTENSION_VIEW_API_METHODS_JS));
573 resources.push_back(std::make_pair("extensionViewAttributes",
574 IDR_EXTENSION_VIEW_ATTRIBUTES_JS));
575 resources.push_back(std::make_pair("extensionViewConstants",
576 IDR_EXTENSION_VIEW_CONSTANTS_JS));
577 resources.push_back(std::make_pair("extensionViewEvents",
578 IDR_EXTENSION_VIEW_EVENTS_JS));
579 resources.push_back(std::make_pair(
580 "extensionViewInternal", IDR_EXTENSION_VIEW_INTERNAL_CUSTOM_BINDINGS_JS));
581 resources.push_back(std::make_pair("guestView", IDR_GUEST_VIEW_JS));
582 resources.push_back(std::make_pair("guestViewAttributes",
583 IDR_GUEST_VIEW_ATTRIBUTES_JS));
584 resources.push_back(std::make_pair("guestViewContainer",
585 IDR_GUEST_VIEW_CONTAINER_JS));
586 resources.push_back(std::make_pair("guestViewDeny", IDR_GUEST_VIEW_DENY_JS));
587 resources.push_back(std::make_pair("guestViewEvents",
588 IDR_GUEST_VIEW_EVENTS_JS));
590 if (content::BrowserPluginGuestMode::UseCrossProcessFramesForGuests()) {
591 resources.push_back(std::make_pair("guestViewIframe",
592 IDR_GUEST_VIEW_IFRAME_JS));
593 resources.push_back(std::make_pair("guestViewIframeContainer",
594 IDR_GUEST_VIEW_IFRAME_CONTAINER_JS));
597 resources.push_back(std::make_pair("imageUtil", IDR_IMAGE_UTIL_JS));
598 resources.push_back(std::make_pair("json_schema", IDR_JSON_SCHEMA_JS));
599 resources.push_back(std::make_pair("lastError", IDR_LAST_ERROR_JS));
600 resources.push_back(std::make_pair("messaging", IDR_MESSAGING_JS));
601 resources.push_back(std::make_pair("messaging_utils",
602 IDR_MESSAGING_UTILS_JS));
603 resources.push_back(std::make_pair(kSchemaUtils, IDR_SCHEMA_UTILS_JS));
604 resources.push_back(std::make_pair("sendRequest", IDR_SEND_REQUEST_JS));
605 resources.push_back(std::make_pair("setIcon", IDR_SET_ICON_JS));
606 resources.push_back(std::make_pair("test", IDR_TEST_CUSTOM_BINDINGS_JS));
607 resources.push_back(
608 std::make_pair("test_environment_specific_bindings",
609 IDR_BROWSER_TEST_ENVIRONMENT_SPECIFIC_BINDINGS_JS));
610 resources.push_back(std::make_pair("uncaught_exception_handler",
611 IDR_UNCAUGHT_EXCEPTION_HANDLER_JS));
612 resources.push_back(std::make_pair("unload_event", IDR_UNLOAD_EVENT_JS));
613 resources.push_back(std::make_pair("utils", IDR_UTILS_JS));
614 resources.push_back(std::make_pair("webRequest",
615 IDR_WEB_REQUEST_CUSTOM_BINDINGS_JS));
616 resources.push_back(
617 std::make_pair("webRequestInternal",
618 IDR_WEB_REQUEST_INTERNAL_CUSTOM_BINDINGS_JS));
619 // Note: webView not webview so that this doesn't interfere with the
620 // chrome.webview API bindings.
621 resources.push_back(std::make_pair("webView", IDR_WEB_VIEW_JS));
622 resources.push_back(std::make_pair("webViewActionRequests",
623 IDR_WEB_VIEW_ACTION_REQUESTS_JS));
624 resources.push_back(std::make_pair("webViewApiMethods",
625 IDR_WEB_VIEW_API_METHODS_JS));
626 resources.push_back(std::make_pair("webViewAttributes",
627 IDR_WEB_VIEW_ATTRIBUTES_JS));
628 resources.push_back(std::make_pair("webViewConstants",
629 IDR_WEB_VIEW_CONSTANTS_JS));
630 resources.push_back(std::make_pair("webViewEvents", IDR_WEB_VIEW_EVENTS_JS));
631 resources.push_back(std::make_pair("webViewInternal",
632 IDR_WEB_VIEW_INTERNAL_CUSTOM_BINDINGS_JS));
633 if (content::BrowserPluginGuestMode::UseCrossProcessFramesForGuests()) {
634 resources.push_back(std::make_pair("webViewIframe",
635 IDR_WEB_VIEW_IFRAME_JS));
637 resources.push_back(
638 std::make_pair(mojo::kBindingsModuleName, IDR_MOJO_BINDINGS_JS));
639 resources.push_back(
640 std::make_pair(mojo::kBufferModuleName, IDR_MOJO_BUFFER_JS));
641 resources.push_back(
642 std::make_pair(mojo::kCodecModuleName, IDR_MOJO_CODEC_JS));
643 resources.push_back(
644 std::make_pair(mojo::kConnectionModuleName, IDR_MOJO_CONNECTION_JS));
645 resources.push_back(
646 std::make_pair(mojo::kConnectorModuleName, IDR_MOJO_CONNECTOR_JS));
647 resources.push_back(
648 std::make_pair(mojo::kRouterModuleName, IDR_MOJO_ROUTER_JS));
649 resources.push_back(
650 std::make_pair(mojo::kUnicodeModuleName, IDR_MOJO_UNICODE_JS));
651 resources.push_back(
652 std::make_pair(mojo::kValidatorModuleName, IDR_MOJO_VALIDATOR_JS));
653 resources.push_back(std::make_pair("async_waiter", IDR_ASYNC_WAITER_JS));
654 resources.push_back(std::make_pair("data_receiver", IDR_DATA_RECEIVER_JS));
655 resources.push_back(std::make_pair("data_sender", IDR_DATA_SENDER_JS));
656 resources.push_back(std::make_pair("keep_alive", IDR_KEEP_ALIVE_JS));
657 resources.push_back(std::make_pair("extensions/common/mojo/keep_alive.mojom",
658 IDR_KEEP_ALIVE_MOJOM_JS));
659 resources.push_back(std::make_pair("device/serial/data_stream.mojom",
660 IDR_DATA_STREAM_MOJOM_JS));
661 resources.push_back(
662 std::make_pair("device/serial/data_stream_serialization.mojom",
663 IDR_DATA_STREAM_SERIALIZATION_MOJOM_JS));
664 resources.push_back(std::make_pair("stash_client", IDR_STASH_CLIENT_JS));
665 resources.push_back(
666 std::make_pair("extensions/common/mojo/stash.mojom", IDR_STASH_MOJOM_JS));
668 // Custom bindings.
669 resources.push_back(
670 std::make_pair("app.runtime", IDR_APP_RUNTIME_CUSTOM_BINDINGS_JS));
671 resources.push_back(
672 std::make_pair("app.window", IDR_APP_WINDOW_CUSTOM_BINDINGS_JS));
673 resources.push_back(
674 std::make_pair("declarativeWebRequest",
675 IDR_DECLARATIVE_WEBREQUEST_CUSTOM_BINDINGS_JS));
676 resources.push_back(
677 std::make_pair("contextMenus", IDR_CONTEXT_MENUS_CUSTOM_BINDINGS_JS));
678 resources.push_back(
679 std::make_pair("contextMenusHandlers", IDR_CONTEXT_MENUS_HANDLERS_JS));
680 resources.push_back(
681 std::make_pair("extension", IDR_EXTENSION_CUSTOM_BINDINGS_JS));
682 resources.push_back(std::make_pair("i18n", IDR_I18N_CUSTOM_BINDINGS_JS));
683 resources.push_back(std::make_pair(
684 "mimeHandlerPrivate", IDR_MIME_HANDLER_PRIVATE_CUSTOM_BINDINGS_JS));
685 resources.push_back(std::make_pair("extensions/common/api/mime_handler.mojom",
686 IDR_MIME_HANDLER_MOJOM_JS));
687 resources.push_back(
688 std::make_pair("mojoPrivate", IDR_MOJO_PRIVATE_CUSTOM_BINDINGS_JS));
689 resources.push_back(
690 std::make_pair("permissions", IDR_PERMISSIONS_CUSTOM_BINDINGS_JS));
691 resources.push_back(std::make_pair("printerProvider",
692 IDR_PRINTER_PROVIDER_CUSTOM_BINDINGS_JS));
693 resources.push_back(
694 std::make_pair("runtime", IDR_RUNTIME_CUSTOM_BINDINGS_JS));
695 resources.push_back(std::make_pair("windowControls", IDR_WINDOW_CONTROLS_JS));
696 resources.push_back(
697 std::make_pair("webViewRequest",
698 IDR_WEB_VIEW_REQUEST_CUSTOM_BINDINGS_JS));
699 resources.push_back(std::make_pair("binding", IDR_BINDING_JS));
701 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
702 switches::kEnableMojoSerialService)) {
703 resources.push_back(
704 std::make_pair("serial", IDR_SERIAL_CUSTOM_BINDINGS_JS));
706 resources.push_back(std::make_pair("serial_service", IDR_SERIAL_SERVICE_JS));
707 resources.push_back(
708 std::make_pair("device/serial/serial.mojom", IDR_SERIAL_MOJOM_JS));
709 resources.push_back(std::make_pair("device/serial/serial_serialization.mojom",
710 IDR_SERIAL_SERIALIZATION_MOJOM_JS));
712 // Custom types sources.
713 resources.push_back(std::make_pair("StorageArea", IDR_STORAGE_AREA_JS));
715 // Platform app sources that are not API-specific..
716 resources.push_back(std::make_pair("platformApp", IDR_PLATFORM_APP_JS));
718 #if defined(ENABLE_MEDIA_ROUTER)
719 resources.push_back(
720 std::make_pair("chrome/browser/media/router/media_router.mojom",
721 IDR_MEDIA_ROUTER_MOJOM_JS));
722 resources.push_back(
723 std::make_pair("media_router_bindings", IDR_MEDIA_ROUTER_BINDINGS_JS));
724 #endif // defined(ENABLE_MEDIA_ROUTER)
726 return resources;
729 // NOTE: please use the naming convention "foo_natives" for these.
730 // static
731 void Dispatcher::RegisterNativeHandlers(ModuleSystem* module_system,
732 ScriptContext* context,
733 Dispatcher* dispatcher,
734 RequestSender* request_sender,
735 V8SchemaRegistry* v8_schema_registry) {
736 module_system->RegisterNativeHandler(
737 "chrome", scoped_ptr<NativeHandler>(new ChromeNativeHandler(context)));
738 module_system->RegisterNativeHandler(
739 "lazy_background_page",
740 scoped_ptr<NativeHandler>(new LazyBackgroundPageNativeHandler(context)));
741 module_system->RegisterNativeHandler(
742 "logging", scoped_ptr<NativeHandler>(new LoggingNativeHandler(context)));
743 module_system->RegisterNativeHandler("schema_registry",
744 v8_schema_registry->AsNativeHandler());
745 module_system->RegisterNativeHandler(
746 "print", scoped_ptr<NativeHandler>(new PrintNativeHandler(context)));
747 module_system->RegisterNativeHandler(
748 "test_features",
749 scoped_ptr<NativeHandler>(new TestFeaturesNativeHandler(context)));
750 module_system->RegisterNativeHandler(
751 "test_native_handler",
752 scoped_ptr<NativeHandler>(new TestNativeHandler(context)));
753 module_system->RegisterNativeHandler(
754 "user_gestures",
755 scoped_ptr<NativeHandler>(new UserGesturesNativeHandler(context)));
756 module_system->RegisterNativeHandler(
757 "utils", scoped_ptr<NativeHandler>(new UtilsNativeHandler(context)));
758 module_system->RegisterNativeHandler(
759 "v8_context",
760 scoped_ptr<NativeHandler>(
761 new V8ContextNativeHandler(context, dispatcher)));
762 module_system->RegisterNativeHandler(
763 "event_natives", scoped_ptr<NativeHandler>(new EventBindings(context)));
764 module_system->RegisterNativeHandler(
765 "messaging_natives",
766 scoped_ptr<NativeHandler>(MessagingBindings::Get(dispatcher, context)));
767 module_system->RegisterNativeHandler(
768 "apiDefinitions",
769 scoped_ptr<NativeHandler>(
770 new ApiDefinitionsNatives(dispatcher, context)));
771 module_system->RegisterNativeHandler(
772 "sendRequest",
773 scoped_ptr<NativeHandler>(
774 new SendRequestNatives(request_sender, context)));
775 module_system->RegisterNativeHandler(
776 "setIcon",
777 scoped_ptr<NativeHandler>(new SetIconNatives(context)));
778 module_system->RegisterNativeHandler(
779 "activityLogger",
780 scoped_ptr<NativeHandler>(new APIActivityLogger(context)));
781 module_system->RegisterNativeHandler(
782 "renderFrameObserverNatives",
783 scoped_ptr<NativeHandler>(new RenderFrameObserverNatives(context)));
785 // Natives used by multiple APIs.
786 module_system->RegisterNativeHandler(
787 "file_system_natives",
788 scoped_ptr<NativeHandler>(new FileSystemNatives(context)));
790 // Custom bindings.
791 // |dispatcher| is null in unit tests.
792 const ScriptContextSet* script_context_set = dispatcher ?
793 &dispatcher->script_context_set() : nullptr;
794 module_system->RegisterNativeHandler(
795 "app_window_natives",
796 scoped_ptr<NativeHandler>(new AppWindowCustomBindings(
797 script_context_set, context)));
798 module_system->RegisterNativeHandler(
799 "blob_natives",
800 scoped_ptr<NativeHandler>(new BlobNativeHandler(context)));
801 module_system->RegisterNativeHandler(
802 "context_menus",
803 scoped_ptr<NativeHandler>(new ContextMenusCustomBindings(context)));
804 module_system->RegisterNativeHandler(
805 "css_natives", scoped_ptr<NativeHandler>(new CssNativeHandler(context)));
806 module_system->RegisterNativeHandler(
807 "document_natives",
808 scoped_ptr<NativeHandler>(new DocumentCustomBindings(context)));
809 module_system->RegisterNativeHandler(
810 "guest_view_internal",
811 scoped_ptr<NativeHandler>(
812 new GuestViewInternalCustomBindings(context)));
813 module_system->RegisterNativeHandler(
814 "i18n", scoped_ptr<NativeHandler>(new I18NCustomBindings(context)));
815 module_system->RegisterNativeHandler(
816 "id_generator",
817 scoped_ptr<NativeHandler>(new IdGeneratorCustomBindings(context)));
818 module_system->RegisterNativeHandler(
819 "runtime", scoped_ptr<NativeHandler>(new RuntimeCustomBindings(context)));
822 bool Dispatcher::OnControlMessageReceived(const IPC::Message& message) {
823 bool handled = true;
824 IPC_BEGIN_MESSAGE_MAP(Dispatcher, message)
825 IPC_MESSAGE_HANDLER(ExtensionMsg_ActivateExtension, OnActivateExtension)
826 IPC_MESSAGE_HANDLER(ExtensionMsg_CancelSuspend, OnCancelSuspend)
827 IPC_MESSAGE_HANDLER(ExtensionMsg_DeliverMessage, OnDeliverMessage)
828 IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnConnect, OnDispatchOnConnect)
829 IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnDisconnect, OnDispatchOnDisconnect)
830 IPC_MESSAGE_HANDLER(ExtensionMsg_Loaded, OnLoaded)
831 IPC_MESSAGE_HANDLER(ExtensionMsg_MessageInvoke, OnMessageInvoke)
832 IPC_MESSAGE_HANDLER(ExtensionMsg_SetChannel, OnSetChannel)
833 IPC_MESSAGE_HANDLER(ExtensionMsg_SetScriptingWhitelist,
834 OnSetScriptingWhitelist)
835 IPC_MESSAGE_HANDLER(ExtensionMsg_SetSystemFont, OnSetSystemFont)
836 IPC_MESSAGE_HANDLER(ExtensionMsg_ShouldSuspend, OnShouldSuspend)
837 IPC_MESSAGE_HANDLER(ExtensionMsg_Suspend, OnSuspend)
838 IPC_MESSAGE_HANDLER(ExtensionMsg_TransferBlobs, OnTransferBlobs)
839 IPC_MESSAGE_HANDLER(ExtensionMsg_Unloaded, OnUnloaded)
840 IPC_MESSAGE_HANDLER(ExtensionMsg_UpdatePermissions, OnUpdatePermissions)
841 IPC_MESSAGE_HANDLER(ExtensionMsg_UpdateTabSpecificPermissions,
842 OnUpdateTabSpecificPermissions)
843 IPC_MESSAGE_HANDLER(ExtensionMsg_ClearTabSpecificPermissions,
844 OnClearTabSpecificPermissions)
845 IPC_MESSAGE_HANDLER(ExtensionMsg_UsingWebRequestAPI, OnUsingWebRequestAPI)
846 IPC_MESSAGE_FORWARD(ExtensionMsg_WatchPages,
847 content_watcher_.get(),
848 ContentWatcher::OnWatchPages)
849 IPC_MESSAGE_UNHANDLED(handled = false)
850 IPC_END_MESSAGE_MAP()
852 return handled;
855 void Dispatcher::WebKitInitialized() {
856 RenderThread::Get()->RegisterExtension(SafeBuiltins::CreateV8Extension());
858 // WebSecurityPolicy whitelists. They should be registered for both
859 // chrome-extension: and chrome-extension-resource.
860 using RegisterFunction = void (*)(const WebString&);
861 RegisterFunction register_functions[] = {
862 // Treat as secure because communication with them is entirely in the
863 // browser, so there is no danger of manipulation or eavesdropping on
864 // communication with them by third parties.
865 WebSecurityPolicy::registerURLSchemeAsSecure,
866 // As far as Blink is concerned, they should be allowed to receive CORS
867 // requests. At the Extensions layer, requests will actually be blocked
868 // unless overridden by the web_accessible_resources manifest key.
869 // TODO(kalman): See what happens with a service worker.
870 WebSecurityPolicy::registerURLSchemeAsCORSEnabled,
871 // Resources should bypass Content Security Policy checks when included in
872 // protected resources. TODO(kalman): What are "protected resources"?
873 WebSecurityPolicy::registerURLSchemeAsBypassingContentSecurityPolicy,
874 // Extension resources are HTTP-like and safe to expose to the fetch API.
875 // The rules for the fetch API are consistent with XHR.
876 WebSecurityPolicy::registerURLSchemeAsSupportingFetchAPI,
879 WebString extension_scheme(base::ASCIIToUTF16(kExtensionScheme));
880 WebString extension_resource_scheme(base::ASCIIToUTF16(
881 kExtensionResourceScheme));
882 for (RegisterFunction func : register_functions) {
883 func(extension_scheme);
884 func(extension_resource_scheme);
887 // For extensions, we want to ensure we call the IdleHandler every so often,
888 // even if the extension keeps up activity.
889 if (set_idle_notifications_) {
890 forced_idle_timer_.reset(new base::RepeatingTimer<content::RenderThread>);
891 forced_idle_timer_->Start(
892 FROM_HERE,
893 base::TimeDelta::FromMilliseconds(kMaxExtensionIdleHandlerDelayMs),
894 RenderThread::Get(),
895 &RenderThread::IdleHandler);
898 // Initialize host permissions for any extensions that were activated before
899 // WebKit was initialized.
900 for (const std::string& extension_id : active_extension_ids_) {
901 const Extension* extension =
902 RendererExtensionRegistry::Get()->GetByID(extension_id);
903 CHECK(extension);
904 InitOriginPermissions(extension);
907 EnableCustomElementWhiteList();
909 is_webkit_initialized_ = true;
912 void Dispatcher::IdleNotification() {
913 if (set_idle_notifications_ && forced_idle_timer_) {
914 // Dampen the forced delay as well if the extension stays idle for long
915 // periods of time. (forced_idle_timer_ can be NULL after
916 // OnRenderProcessShutdown has been called.)
917 int64 forced_delay_ms =
918 std::max(RenderThread::Get()->GetIdleNotificationDelayInMs(),
919 kMaxExtensionIdleHandlerDelayMs);
920 forced_idle_timer_->Stop();
921 forced_idle_timer_->Start(
922 FROM_HERE,
923 base::TimeDelta::FromMilliseconds(forced_delay_ms),
924 RenderThread::Get(),
925 &RenderThread::IdleHandler);
929 void Dispatcher::OnRenderProcessShutdown() {
930 v8_schema_registry_.reset();
931 forced_idle_timer_.reset();
932 content_watcher_.reset();
935 void Dispatcher::OnActivateExtension(const std::string& extension_id) {
936 const Extension* extension =
937 RendererExtensionRegistry::Get()->GetByID(extension_id);
938 if (!extension) {
939 // Extension was activated but was never loaded. This probably means that
940 // the renderer failed to load it (or the browser failed to tell us when it
941 // did). Failures shouldn't happen, but instead of crashing there (which
942 // executes on all renderers) be conservative and only crash in the renderer
943 // of the extension which failed to load; this one.
944 std::string& error = extension_load_errors_[extension_id];
945 char minidump[256];
946 base::debug::Alias(&minidump);
947 base::snprintf(minidump,
948 arraysize(minidump),
949 "e::dispatcher:%s:%s",
950 extension_id.c_str(),
951 error.c_str());
952 LOG(FATAL) << extension_id << " was never loaded: " << error;
955 active_extension_ids_.insert(extension_id);
957 // This is called when starting a new extension page, so start the idle
958 // handler ticking.
959 RenderThread::Get()->ScheduleIdleHandler(kInitialExtensionIdleHandlerDelayMs);
961 if (is_webkit_initialized_) {
962 DOMActivityLogger::AttachToWorld(
963 DOMActivityLogger::kMainWorldId, extension_id);
965 InitOriginPermissions(extension);
968 UpdateActiveExtensions();
971 void Dispatcher::OnCancelSuspend(const std::string& extension_id) {
972 DispatchEvent(extension_id, kOnSuspendCanceledEvent);
975 void Dispatcher::OnDeliverMessage(int target_port_id, const Message& message) {
976 scoped_ptr<RequestSender::ScopedTabID> scoped_tab_id;
977 std::map<int, int>::const_iterator it =
978 port_to_tab_id_map_.find(target_port_id);
979 if (it != port_to_tab_id_map_.end()) {
980 scoped_tab_id.reset(
981 new RequestSender::ScopedTabID(request_sender(), it->second));
984 MessagingBindings::DeliverMessage(*script_context_set_, target_port_id,
985 message,
986 NULL); // All render frames.
989 void Dispatcher::OnDispatchOnConnect(
990 int target_port_id,
991 const std::string& channel_name,
992 const ExtensionMsg_TabConnectionInfo& source,
993 const ExtensionMsg_ExternalConnectionInfo& info,
994 const std::string& tls_channel_id) {
995 DCHECK(!ContainsKey(port_to_tab_id_map_, target_port_id));
996 DCHECK_EQ(1, target_port_id % 2); // target renderer ports have odd IDs.
997 int sender_tab_id = -1;
998 source.tab.GetInteger("id", &sender_tab_id);
999 port_to_tab_id_map_[target_port_id] = sender_tab_id;
1001 MessagingBindings::DispatchOnConnect(*script_context_set_, target_port_id,
1002 channel_name, source, info,
1003 tls_channel_id,
1004 NULL); // All render frames.
1007 void Dispatcher::OnDispatchOnDisconnect(int port_id,
1008 const std::string& error_message) {
1009 MessagingBindings::DispatchOnDisconnect(*script_context_set_, port_id,
1010 error_message,
1011 NULL); // All render frames.
1014 void Dispatcher::OnLoaded(
1015 const std::vector<ExtensionMsg_Loaded_Params>& loaded_extensions) {
1016 for (const auto& param : loaded_extensions) {
1017 std::string error;
1018 scoped_refptr<const Extension> extension = param.ConvertToExtension(&error);
1019 if (!extension.get()) {
1020 NOTREACHED() << error;
1021 // Note: in tests |param.id| has been observed to be empty (see comment
1022 // just below) so this isn't all that reliable.
1023 extension_load_errors_[param.id] = error;
1024 continue;
1027 RendererExtensionRegistry* extension_registry =
1028 RendererExtensionRegistry::Get();
1029 // TODO(kalman): This test is deliberately not a CHECK (though I wish it
1030 // could be) and uses extension->id() not params.id:
1031 // 1. For some reason params.id can be empty. I've only seen it with
1032 // the webstore extension, in tests, and I've spent some time trying to
1033 // figure out why - but cost/benefit won.
1034 // 2. The browser only sends this IPC to RenderProcessHosts once, but the
1035 // Dispatcher is attached to a RenderThread. Presumably there is a
1036 // mismatch there. In theory one would think it's possible for the
1037 // browser to figure this out itself - but again, cost/benefit.
1038 if (!extension_registry->Contains(extension->id()))
1039 extension_registry->Insert(extension);
1042 // Update the available bindings for all contexts. These may have changed if
1043 // an externally_connectable extension was loaded that can connect to an
1044 // open webpage.
1045 UpdateBindings("");
1048 void Dispatcher::OnMessageInvoke(const std::string& extension_id,
1049 const std::string& module_name,
1050 const std::string& function_name,
1051 const base::ListValue& args,
1052 bool user_gesture) {
1053 InvokeModuleSystemMethod(
1054 NULL, extension_id, module_name, function_name, args, user_gesture);
1057 void Dispatcher::OnSetChannel(int channel) {
1058 delegate_->SetChannel(channel);
1059 AddChannelSpecificFeatures();
1062 void Dispatcher::OnSetScriptingWhitelist(
1063 const ExtensionsClient::ScriptingWhitelist& extension_ids) {
1064 ExtensionsClient::Get()->SetScriptingWhitelist(extension_ids);
1067 void Dispatcher::OnSetSystemFont(const std::string& font_family,
1068 const std::string& font_size) {
1069 system_font_family_ = font_family;
1070 system_font_size_ = font_size;
1073 void Dispatcher::OnShouldSuspend(const std::string& extension_id,
1074 uint64 sequence_id) {
1075 RenderThread::Get()->Send(
1076 new ExtensionHostMsg_ShouldSuspendAck(extension_id, sequence_id));
1079 void Dispatcher::OnSuspend(const std::string& extension_id) {
1080 // Dispatch the suspend event. This doesn't go through the standard event
1081 // dispatch machinery because it requires special handling. We need to let
1082 // the browser know when we are starting and stopping the event dispatch, so
1083 // that it still considers the extension idle despite any activity the suspend
1084 // event creates.
1085 DispatchEvent(extension_id, kOnSuspendEvent);
1086 RenderThread::Get()->Send(new ExtensionHostMsg_SuspendAck(extension_id));
1089 void Dispatcher::OnTransferBlobs(const std::vector<std::string>& blob_uuids) {
1090 RenderThread::Get()->Send(new ExtensionHostMsg_TransferBlobsAck(blob_uuids));
1093 void Dispatcher::OnUnloaded(const std::string& id) {
1094 // See comment in OnLoaded for why it would be nice, but perhaps incorrect,
1095 // to CHECK here rather than guarding.
1096 if (!RendererExtensionRegistry::Get()->Remove(id))
1097 return;
1099 active_extension_ids_.erase(id);
1101 script_injection_manager_->OnExtensionUnloaded(id);
1103 // If the extension is later reloaded with a different set of permissions,
1104 // we'd like it to get a new isolated world ID, so that it can pick up the
1105 // changed origin whitelist.
1106 ScriptInjection::RemoveIsolatedWorld(id);
1108 // Invalidate all of the contexts that were removed.
1109 // TODO(kalman): add an invalidation observer interface to ScriptContext.
1110 std::set<ScriptContext*> removed_contexts =
1111 script_context_set_->OnExtensionUnloaded(id);
1112 for (ScriptContext* context : removed_contexts) {
1113 request_sender_->InvalidateSource(context);
1116 // Update the available bindings for the remaining contexts. These may have
1117 // changed if an externally_connectable extension is unloaded and a webpage
1118 // is no longer accessible.
1119 UpdateBindings("");
1121 // Invalidates the messages map for the extension in case the extension is
1122 // reloaded with a new messages map.
1123 EraseL10nMessagesMap(id);
1125 // We don't do anything with existing platform-app stylesheets. They will
1126 // stay resident, but the URL pattern corresponding to the unloaded
1127 // extension's URL just won't match anything anymore.
1130 void Dispatcher::OnUpdatePermissions(
1131 const ExtensionMsg_UpdatePermissions_Params& params) {
1132 const Extension* extension =
1133 RendererExtensionRegistry::Get()->GetByID(params.extension_id);
1134 if (!extension)
1135 return;
1137 scoped_refptr<const PermissionSet> active =
1138 params.active_permissions.ToPermissionSet();
1139 scoped_refptr<const PermissionSet> withheld =
1140 params.withheld_permissions.ToPermissionSet();
1142 if (is_webkit_initialized_) {
1143 UpdateOriginPermissions(
1144 extension->url(),
1145 extension->permissions_data()->GetEffectiveHostPermissions(),
1146 active->effective_hosts());
1149 extension->permissions_data()->SetPermissions(active, withheld);
1150 UpdateBindings(extension->id());
1153 void Dispatcher::OnUpdateTabSpecificPermissions(const GURL& visible_url,
1154 const std::string& extension_id,
1155 const URLPatternSet& new_hosts,
1156 bool update_origin_whitelist,
1157 int tab_id) {
1158 const Extension* extension =
1159 RendererExtensionRegistry::Get()->GetByID(extension_id);
1160 if (!extension)
1161 return;
1163 URLPatternSet old_effective =
1164 extension->permissions_data()->GetEffectiveHostPermissions();
1165 extension->permissions_data()->UpdateTabSpecificPermissions(
1166 tab_id,
1167 new extensions::PermissionSet(extensions::APIPermissionSet(),
1168 extensions::ManifestPermissionSet(),
1169 new_hosts,
1170 extensions::URLPatternSet()));
1172 if (is_webkit_initialized_ && update_origin_whitelist) {
1173 UpdateOriginPermissions(
1174 extension->url(),
1175 old_effective,
1176 extension->permissions_data()->GetEffectiveHostPermissions());
1180 void Dispatcher::OnClearTabSpecificPermissions(
1181 const std::vector<std::string>& extension_ids,
1182 bool update_origin_whitelist,
1183 int tab_id) {
1184 for (const std::string& id : extension_ids) {
1185 const Extension* extension = RendererExtensionRegistry::Get()->GetByID(id);
1186 if (extension) {
1187 URLPatternSet old_effective =
1188 extension->permissions_data()->GetEffectiveHostPermissions();
1189 extension->permissions_data()->ClearTabSpecificPermissions(tab_id);
1190 if (is_webkit_initialized_ && update_origin_whitelist) {
1191 UpdateOriginPermissions(
1192 extension->url(),
1193 old_effective,
1194 extension->permissions_data()->GetEffectiveHostPermissions());
1200 void Dispatcher::OnUsingWebRequestAPI(bool webrequest_used) {
1201 webrequest_used_ = webrequest_used;
1204 void Dispatcher::OnUserScriptsUpdated(const std::set<HostID>& changed_hosts,
1205 const std::vector<UserScript*>& scripts) {
1206 UpdateActiveExtensions();
1209 void Dispatcher::UpdateActiveExtensions() {
1210 std::set<std::string> active_extensions = active_extension_ids_;
1211 user_script_set_manager_->GetAllActiveExtensionIds(&active_extensions);
1212 delegate_->OnActiveExtensionsUpdated(active_extensions);
1215 void Dispatcher::InitOriginPermissions(const Extension* extension) {
1216 delegate_->InitOriginPermissions(extension,
1217 IsExtensionActive(extension->id()));
1218 UpdateOriginPermissions(
1219 extension->url(),
1220 URLPatternSet(), // No old permissions.
1221 extension->permissions_data()->GetEffectiveHostPermissions());
1224 void Dispatcher::UpdateOriginPermissions(const GURL& extension_url,
1225 const URLPatternSet& old_patterns,
1226 const URLPatternSet& new_patterns) {
1227 static const char* kSchemes[] = {
1228 url::kHttpScheme,
1229 url::kHttpsScheme,
1230 url::kFileScheme,
1231 content::kChromeUIScheme,
1232 url::kFtpScheme,
1233 #if defined(OS_CHROMEOS)
1234 content::kExternalFileScheme,
1235 #endif
1236 extensions::kExtensionScheme,
1238 for (size_t i = 0; i < arraysize(kSchemes); ++i) {
1239 const char* scheme = kSchemes[i];
1240 // Remove all old patterns...
1241 for (URLPatternSet::const_iterator pattern = old_patterns.begin();
1242 pattern != old_patterns.end(); ++pattern) {
1243 if (pattern->MatchesScheme(scheme)) {
1244 WebSecurityPolicy::removeOriginAccessWhitelistEntry(
1245 extension_url,
1246 WebString::fromUTF8(scheme),
1247 WebString::fromUTF8(pattern->host()),
1248 pattern->match_subdomains());
1251 // ...And add the new ones.
1252 for (URLPatternSet::const_iterator pattern = new_patterns.begin();
1253 pattern != new_patterns.end(); ++pattern) {
1254 if (pattern->MatchesScheme(scheme)) {
1255 WebSecurityPolicy::addOriginAccessWhitelistEntry(
1256 extension_url,
1257 WebString::fromUTF8(scheme),
1258 WebString::fromUTF8(pattern->host()),
1259 pattern->match_subdomains());
1265 void Dispatcher::EnableCustomElementWhiteList() {
1266 blink::WebCustomElement::addEmbedderCustomElementName("appview");
1267 blink::WebCustomElement::addEmbedderCustomElementName("appviewbrowserplugin");
1268 blink::WebCustomElement::addEmbedderCustomElementName("extensionoptions");
1269 blink::WebCustomElement::addEmbedderCustomElementName(
1270 "extensionoptionsbrowserplugin");
1271 blink::WebCustomElement::addEmbedderCustomElementName("extensionview");
1272 blink::WebCustomElement::addEmbedderCustomElementName(
1273 "extensionviewbrowserplugin");
1274 blink::WebCustomElement::addEmbedderCustomElementName("webview");
1275 blink::WebCustomElement::addEmbedderCustomElementName("webviewbrowserplugin");
1278 void Dispatcher::UpdateBindings(const std::string& extension_id) {
1279 script_context_set().ForEach(extension_id,
1280 base::Bind(&Dispatcher::UpdateBindingsForContext,
1281 base::Unretained(this)));
1284 void Dispatcher::UpdateBindingsForContext(ScriptContext* context) {
1285 v8::HandleScope handle_scope(context->isolate());
1286 v8::Context::Scope context_scope(context->v8_context());
1288 // TODO(kalman): Make the bindings registration have zero overhead then run
1289 // the same code regardless of context type.
1290 switch (context->context_type()) {
1291 case Feature::UNSPECIFIED_CONTEXT:
1292 case Feature::WEB_PAGE_CONTEXT:
1293 case Feature::BLESSED_WEB_PAGE_CONTEXT:
1294 // Hard-code registration of any APIs that are exposed to webpage-like
1295 // contexts, because it's too expensive to run the full bindings code.
1296 // All of the same permission checks will still apply.
1297 if (context->GetAvailability("app").is_available())
1298 RegisterBinding("app", context);
1299 if (context->GetAvailability("webstore").is_available())
1300 RegisterBinding("webstore", context);
1301 if (context->GetAvailability("dashboardPrivate").is_available())
1302 RegisterBinding("dashboardPrivate", context);
1303 if (IsRuntimeAvailableToContext(context))
1304 RegisterBinding("runtime", context);
1305 UpdateContentCapabilities(context);
1306 break;
1308 case Feature::BLESSED_EXTENSION_CONTEXT:
1309 case Feature::UNBLESSED_EXTENSION_CONTEXT:
1310 case Feature::CONTENT_SCRIPT_CONTEXT:
1311 case Feature::WEBUI_CONTEXT: {
1312 // Extension context; iterate through all the APIs and bind the available
1313 // ones.
1314 const FeatureProvider* api_feature_provider =
1315 FeatureProvider::GetAPIFeatures();
1316 const std::vector<std::string>& apis =
1317 api_feature_provider->GetAllFeatureNames();
1318 for (const std::string& api_name : apis) {
1319 Feature* feature = api_feature_provider->GetFeature(api_name);
1320 DCHECK(feature);
1322 // Internal APIs are included via require(api_name) from internal code
1323 // rather than chrome[api_name].
1324 if (feature->IsInternal())
1325 continue;
1327 // If this API has a parent feature (and isn't marked 'noparent'),
1328 // then this must be a function or event, so we should not register.
1329 if (api_feature_provider->GetParent(feature) != NULL)
1330 continue;
1332 // Skip chrome.test if this isn't a test.
1333 if (api_name == "test" &&
1334 !base::CommandLine::ForCurrentProcess()->HasSwitch(
1335 ::switches::kTestType)) {
1336 continue;
1339 if (context->IsAnyFeatureAvailableToContext(*feature))
1340 RegisterBinding(api_name, context);
1342 break;
1344 case Feature::SERVICE_WORKER_CONTEXT:
1345 // Handled in DidInitializeServiceWorkerContextOnWorkerThread().
1346 NOTREACHED();
1347 break;
1351 void Dispatcher::RegisterBinding(const std::string& api_name,
1352 ScriptContext* context) {
1353 std::string bind_name;
1354 v8::Local<v8::Object> bind_object =
1355 GetOrCreateBindObjectIfAvailable(api_name, &bind_name, context);
1357 // Empty if the bind object failed to be created, probably because the
1358 // extension overrode chrome with a non-object, e.g. window.chrome = true.
1359 if (bind_object.IsEmpty())
1360 return;
1362 v8::Local<v8::String> v8_bind_name =
1363 v8::String::NewFromUtf8(context->isolate(), bind_name.c_str());
1364 if (bind_object->HasRealNamedProperty(v8_bind_name)) {
1365 // The bind object may already have the property if the API has been
1366 // registered before (or if the extension has put something there already,
1367 // but, whatevs).
1369 // In the former case, we need to re-register the bindings for the APIs
1370 // which the extension now has permissions for (if any), but not touch any
1371 // others so that we don't destroy state such as event listeners.
1373 // TODO(kalman): Only register available APIs to make this all moot.
1374 if (bind_object->HasRealNamedCallbackProperty(v8_bind_name))
1375 return; // lazy binding still there, nothing to do
1376 if (bind_object->Get(v8_bind_name)->IsObject())
1377 return; // binding has already been fully installed
1380 ModuleSystem* module_system = context->module_system();
1381 if (!source_map_.Contains(api_name)) {
1382 module_system->RegisterNativeHandler(
1383 api_name,
1384 scoped_ptr<NativeHandler>(new BindingGeneratingNativeHandler(
1385 context, api_name, "binding")));
1386 module_system->SetNativeLazyField(
1387 bind_object, bind_name, api_name, "binding");
1388 } else {
1389 module_system->SetLazyField(bind_object, bind_name, api_name, "binding");
1393 // NOTE: please use the naming convention "foo_natives" for these.
1394 void Dispatcher::RegisterNativeHandlers(ModuleSystem* module_system,
1395 ScriptContext* context) {
1396 RegisterNativeHandlers(module_system,
1397 context,
1398 this,
1399 request_sender_.get(),
1400 v8_schema_registry_.get());
1401 const Extension* extension = context->extension();
1402 int manifest_version = extension ? extension->manifest_version() : 1;
1403 bool is_component_extension =
1404 extension && Manifest::IsComponentLocation(extension->location());
1405 bool send_request_disabled =
1406 (extension && Manifest::IsUnpackedLocation(extension->location()) &&
1407 BackgroundInfo::HasLazyBackgroundPage(extension));
1408 module_system->RegisterNativeHandler(
1409 "process",
1410 scoped_ptr<NativeHandler>(new ProcessInfoNativeHandler(
1411 context,
1412 context->GetExtensionID(),
1413 context->GetContextTypeDescription(),
1414 ExtensionsRendererClient::Get()->IsIncognitoProcess(),
1415 is_component_extension,
1416 manifest_version,
1417 send_request_disabled)));
1419 delegate_->RegisterNativeHandlers(this, module_system, context);
1422 bool Dispatcher::IsRuntimeAvailableToContext(ScriptContext* context) {
1423 for (const auto& extension :
1424 *RendererExtensionRegistry::Get()->GetMainThreadExtensionSet()) {
1425 ExternallyConnectableInfo* info = static_cast<ExternallyConnectableInfo*>(
1426 extension->GetManifestData(manifest_keys::kExternallyConnectable));
1427 if (info && info->matches.MatchesURL(context->GetURL()))
1428 return true;
1430 return false;
1433 void Dispatcher::UpdateContentCapabilities(ScriptContext* context) {
1434 APIPermissionSet permissions;
1435 for (const auto& extension :
1436 *RendererExtensionRegistry::Get()->GetMainThreadExtensionSet()) {
1437 const ContentCapabilitiesInfo& info =
1438 ContentCapabilitiesInfo::Get(extension.get());
1439 if (info.url_patterns.MatchesURL(context->GetURL())) {
1440 APIPermissionSet new_permissions;
1441 APIPermissionSet::Union(permissions, info.permissions, &new_permissions);
1442 permissions = new_permissions;
1445 context->SetContentCapabilities(permissions);
1448 void Dispatcher::PopulateSourceMap() {
1449 const std::vector<std::pair<std::string, int> > resources = GetJsResources();
1450 for (std::vector<std::pair<std::string, int> >::const_iterator resource =
1451 resources.begin();
1452 resource != resources.end();
1453 ++resource) {
1454 source_map_.RegisterSource(resource->first, resource->second);
1456 delegate_->PopulateSourceMap(&source_map_);
1459 bool Dispatcher::IsWithinPlatformApp() {
1460 for (std::set<std::string>::iterator iter = active_extension_ids_.begin();
1461 iter != active_extension_ids_.end();
1462 ++iter) {
1463 const Extension* extension =
1464 RendererExtensionRegistry::Get()->GetByID(*iter);
1465 if (extension && extension->is_platform_app())
1466 return true;
1468 return false;
1471 v8::Local<v8::Object> Dispatcher::GetOrCreateObject(
1472 const v8::Local<v8::Object>& object,
1473 const std::string& field,
1474 v8::Isolate* isolate) {
1475 v8::Local<v8::String> key = v8::String::NewFromUtf8(isolate, field.c_str());
1476 // If the object has a callback property, it is assumed it is an unavailable
1477 // API, so it is safe to delete. This is checked before GetOrCreateObject is
1478 // called.
1479 if (object->HasRealNamedCallbackProperty(key)) {
1480 object->Delete(key);
1481 } else if (object->HasRealNamedProperty(key)) {
1482 v8::Local<v8::Value> value = object->Get(key);
1483 CHECK(value->IsObject());
1484 return v8::Local<v8::Object>::Cast(value);
1487 v8::Local<v8::Object> new_object = v8::Object::New(isolate);
1488 object->Set(key, new_object);
1489 return new_object;
1492 v8::Local<v8::Object> Dispatcher::GetOrCreateBindObjectIfAvailable(
1493 const std::string& api_name,
1494 std::string* bind_name,
1495 ScriptContext* context) {
1496 std::vector<std::string> split = base::SplitString(
1497 api_name, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
1499 v8::Local<v8::Object> bind_object;
1501 // Check if this API has an ancestor. If the API's ancestor is available and
1502 // the API is not available, don't install the bindings for this API. If
1503 // the API is available and its ancestor is not, delete the ancestor and
1504 // install the bindings for the API. This is to prevent loading the ancestor
1505 // API schema if it will not be needed.
1507 // For example:
1508 // If app is available and app.window is not, just install app.
1509 // If app.window is available and app is not, delete app and install
1510 // app.window on a new object so app does not have to be loaded.
1511 const FeatureProvider* api_feature_provider =
1512 FeatureProvider::GetAPIFeatures();
1513 std::string ancestor_name;
1514 bool only_ancestor_available = false;
1516 for (size_t i = 0; i < split.size() - 1; ++i) {
1517 ancestor_name += (i ? "." : "") + split[i];
1518 if (api_feature_provider->GetFeature(ancestor_name) &&
1519 context->GetAvailability(ancestor_name).is_available() &&
1520 !context->GetAvailability(api_name).is_available()) {
1521 only_ancestor_available = true;
1522 break;
1525 if (bind_object.IsEmpty()) {
1526 bind_object = AsObjectOrEmpty(GetOrCreateChrome(context));
1527 if (bind_object.IsEmpty())
1528 return v8::Local<v8::Object>();
1530 bind_object = GetOrCreateObject(bind_object, split[i], context->isolate());
1533 if (only_ancestor_available)
1534 return v8::Local<v8::Object>();
1536 if (bind_name)
1537 *bind_name = split.back();
1539 return bind_object.IsEmpty() ? AsObjectOrEmpty(GetOrCreateChrome(context))
1540 : bind_object;
1543 void Dispatcher::RequireGuestViewModules(ScriptContext* context) {
1544 Feature::Context context_type = context->context_type();
1545 ModuleSystem* module_system = context->module_system();
1547 // Require AppView.
1548 if (context->GetAvailability("appViewEmbedderInternal").is_available()) {
1549 module_system->Require("appView");
1552 // Require ExtensionOptions.
1553 if (context->GetAvailability("extensionOptionsInternal").is_available()) {
1554 module_system->Require("extensionOptions");
1555 module_system->Require("extensionOptionsAttributes");
1558 // Require ExtensionView.
1559 if (context->GetAvailability("extensionViewInternal").is_available()) {
1560 module_system->Require("extensionView");
1561 module_system->Require("extensionViewApiMethods");
1562 module_system->Require("extensionViewAttributes");
1565 // Require WebView.
1566 if (context->GetAvailability("webViewInternal").is_available()) {
1567 module_system->Require("webView");
1568 module_system->Require("webViewApiMethods");
1569 module_system->Require("webViewAttributes");
1571 if (content::BrowserPluginGuestMode::UseCrossProcessFramesForGuests()) {
1572 module_system->Require("webViewIframe");
1576 // The "guestViewDeny" module must always be loaded last. It registers
1577 // error-providing custom elements for the GuestView types that are not
1578 // available, and thus all of those types must have been checked and loaded
1579 // (or not loaded) beforehand.
1580 if (context_type == Feature::BLESSED_EXTENSION_CONTEXT) {
1581 module_system->Require("guestViewDeny");
1585 void Dispatcher::AddChannelSpecificFeatures() {
1586 // chrome-extension: resources should be allowed to register a Service Worker.
1587 if (FeatureProvider::GetBehaviorFeature(BehaviorFeature::kServiceWorker)
1588 ->IsAvailableToEnvironment()
1589 .is_available())
1590 WebSecurityPolicy::registerURLSchemeAsAllowingServiceWorkers(
1591 WebString::fromUTF8(kExtensionScheme));
1594 } // namespace extensions