Remove linux_chromium_gn_dbg from the chromium CQ.
[chromium-blink-merge.git] / extensions / renderer / dispatcher.cc
blobd69eb59e2c6310ad562f3f88c63f09cd412c50b3
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/bind_helpers.h"
9 #include "base/callback.h"
10 #include "base/command_line.h"
11 #include "base/containers/scoped_ptr_map.h"
12 #include "base/debug/alias.h"
13 #include "base/lazy_instance.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/metrics/histogram_macros.h"
16 #include "base/metrics/user_metrics_action.h"
17 #include "base/strings/string_piece.h"
18 #include "base/strings/string_split.h"
19 #include "base/strings/string_util.h"
20 #include "base/strings/utf_string_conversions.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 "extensions/renderer/worker_script_context_set.h"
95 #include "grit/extensions_renderer_resources.h"
96 #include "third_party/WebKit/public/platform/WebString.h"
97 #include "third_party/WebKit/public/platform/WebURLRequest.h"
98 #include "third_party/WebKit/public/web/WebCustomElement.h"
99 #include "third_party/WebKit/public/web/WebDataSource.h"
100 #include "third_party/WebKit/public/web/WebDocument.h"
101 #include "third_party/WebKit/public/web/WebFrame.h"
102 #include "third_party/WebKit/public/web/WebLocalFrame.h"
103 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
104 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
105 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
106 #include "third_party/WebKit/public/web/WebView.h"
107 #include "third_party/mojo/src/mojo/public/js/constants.h"
108 #include "ui/base/layout.h"
109 #include "ui/base/resource/resource_bundle.h"
110 #include "v8/include/v8.h"
112 using base::UserMetricsAction;
113 using blink::WebDataSource;
114 using blink::WebDocument;
115 using blink::WebScopedUserGesture;
116 using blink::WebSecurityPolicy;
117 using blink::WebString;
118 using blink::WebVector;
119 using blink::WebView;
120 using content::RenderThread;
122 namespace extensions {
124 namespace {
126 static const int64 kInitialExtensionIdleHandlerDelayMs = 5 * 1000;
127 static const int64 kMaxExtensionIdleHandlerDelayMs = 5 * 60 * 1000;
128 static const char kEventDispatchFunction[] = "dispatchEvent";
129 static const char kOnSuspendEvent[] = "runtime.onSuspend";
130 static const char kOnSuspendCanceledEvent[] = "runtime.onSuspendCanceled";
132 void CrashOnException(const v8::TryCatch& trycatch) {
133 NOTREACHED();
136 // Returns the global value for "chrome" from |context|. If one doesn't exist
137 // creates a new object for it.
139 // Note that this isn't necessarily an object, since webpages can write, for
140 // example, "window.chrome = true".
141 v8::Local<v8::Value> GetOrCreateChrome(ScriptContext* context) {
142 v8::Local<v8::String> chrome_string(
143 v8::String::NewFromUtf8(context->isolate(), "chrome"));
144 v8::Local<v8::Object> global(context->v8_context()->Global());
145 v8::Local<v8::Value> chrome(global->Get(chrome_string));
146 if (chrome->IsUndefined()) {
147 chrome = v8::Object::New(context->isolate());
148 global->Set(chrome_string, chrome);
150 return chrome;
153 // Returns |value| cast to an object if possible, else an empty handle.
154 v8::Local<v8::Object> AsObjectOrEmpty(v8::Local<v8::Value> value) {
155 return value->IsObject() ? value.As<v8::Object>() : v8::Local<v8::Object>();
158 // Calls a method |method_name| in a module |module_name| belonging to the
159 // module system from |context|. Intended as a callback target from
160 // ScriptContextSet::ForEach.
161 void CallModuleMethod(const std::string& module_name,
162 const std::string& method_name,
163 const base::ListValue* args,
164 ScriptContext* context) {
165 v8::HandleScope handle_scope(context->isolate());
166 v8::Context::Scope context_scope(context->v8_context());
168 scoped_ptr<content::V8ValueConverter> converter(
169 content::V8ValueConverter::create());
171 std::vector<v8::Local<v8::Value>> arguments;
172 for (base::ListValue::const_iterator it = args->begin(); it != args->end();
173 ++it) {
174 arguments.push_back(converter->ToV8Value(*it, context->v8_context()));
177 context->module_system()->CallModuleMethod(
178 module_name, method_name, &arguments);
181 // This handles the "chrome." root API object in script contexts.
182 class ChromeNativeHandler : public ObjectBackedNativeHandler {
183 public:
184 explicit ChromeNativeHandler(ScriptContext* context)
185 : ObjectBackedNativeHandler(context) {
186 RouteFunction(
187 "GetChrome",
188 base::Bind(&ChromeNativeHandler::GetChrome, base::Unretained(this)));
191 void GetChrome(const v8::FunctionCallbackInfo<v8::Value>& args) {
192 args.GetReturnValue().Set(GetOrCreateChrome(context()));
196 base::LazyInstance<WorkerScriptContextSet> g_worker_script_context_set =
197 LAZY_INSTANCE_INITIALIZER;
199 } // namespace
201 // Note that we can't use Blink public APIs in the constructor becase Blink
202 // is not initialized at the point we create Dispatcher.
203 Dispatcher::Dispatcher(DispatcherDelegate* delegate)
204 : delegate_(delegate),
205 content_watcher_(new ContentWatcher()),
206 source_map_(&ResourceBundle::GetSharedInstance()),
207 v8_schema_registry_(new V8SchemaRegistry),
208 is_webkit_initialized_(false),
209 user_script_set_manager_observer_(this),
210 webrequest_used_(false) {
211 const base::CommandLine& command_line =
212 *(base::CommandLine::ForCurrentProcess());
213 set_idle_notifications_ =
214 command_line.HasSwitch(switches::kExtensionProcess) ||
215 command_line.HasSwitch(::switches::kSingleProcess);
217 if (set_idle_notifications_) {
218 RenderThread::Get()->SetIdleNotificationDelayInMs(
219 kInitialExtensionIdleHandlerDelayMs);
222 script_context_set_.reset(new ScriptContextSet(&active_extension_ids_));
223 user_script_set_manager_.reset(new UserScriptSetManager());
224 script_injection_manager_.reset(
225 new ScriptInjectionManager(user_script_set_manager_.get()));
226 user_script_set_manager_observer_.Add(user_script_set_manager_.get());
227 request_sender_.reset(new RequestSender(this));
228 PopulateSourceMap();
229 WakeEventPage::Get()->Init(RenderThread::Get());
232 Dispatcher::~Dispatcher() {
235 void Dispatcher::OnRenderFrameCreated(content::RenderFrame* render_frame) {
236 script_injection_manager_->OnRenderFrameCreated(render_frame);
239 bool Dispatcher::IsExtensionActive(const std::string& extension_id) const {
240 bool is_active =
241 active_extension_ids_.find(extension_id) != active_extension_ids_.end();
242 if (is_active)
243 CHECK(RendererExtensionRegistry::Get()->Contains(extension_id));
244 return is_active;
247 void Dispatcher::DidCreateScriptContext(
248 blink::WebLocalFrame* frame,
249 const v8::Local<v8::Context>& v8_context,
250 int extension_group,
251 int world_id) {
252 const base::TimeTicks start_time = base::TimeTicks::Now();
254 ScriptContext* context = script_context_set_->Register(
255 frame, v8_context, extension_group, world_id);
257 // Initialize origin permissions for content scripts, which can't be
258 // initialized in |OnActivateExtension|.
259 if (context->context_type() == Feature::CONTENT_SCRIPT_CONTEXT)
260 InitOriginPermissions(context->extension());
263 scoped_ptr<ModuleSystem> module_system(
264 new ModuleSystem(context, &source_map_));
265 context->set_module_system(module_system.Pass());
267 ModuleSystem* module_system = context->module_system();
269 // Enable natives in startup.
270 ModuleSystem::NativesEnabledScope natives_enabled_scope(module_system);
272 RegisterNativeHandlers(module_system, context);
274 // chrome.Event is part of the public API (although undocumented). Make it
275 // lazily evalulate to Event from event_bindings.js. For extensions only
276 // though, not all webpages!
277 if (context->extension()) {
278 v8::Local<v8::Object> chrome = AsObjectOrEmpty(GetOrCreateChrome(context));
279 if (!chrome.IsEmpty())
280 module_system->SetLazyField(chrome, "Event", kEventBindings, "Event");
283 UpdateBindingsForContext(context);
285 bool is_within_platform_app = IsWithinPlatformApp();
286 // Inject custom JS into the platform app context.
287 if (is_within_platform_app) {
288 module_system->Require("platformApp");
291 RequireGuestViewModules(context);
292 delegate_->RequireAdditionalModules(context, is_within_platform_app);
294 const base::TimeDelta elapsed = base::TimeTicks::Now() - start_time;
295 switch (context->context_type()) {
296 case Feature::UNSPECIFIED_CONTEXT:
297 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Unspecified",
298 elapsed);
299 break;
300 case Feature::BLESSED_EXTENSION_CONTEXT:
301 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Blessed", elapsed);
302 break;
303 case Feature::UNBLESSED_EXTENSION_CONTEXT:
304 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Unblessed",
305 elapsed);
306 break;
307 case Feature::CONTENT_SCRIPT_CONTEXT:
308 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_ContentScript",
309 elapsed);
310 break;
311 case Feature::WEB_PAGE_CONTEXT:
312 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_WebPage", elapsed);
313 break;
314 case Feature::BLESSED_WEB_PAGE_CONTEXT:
315 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_BlessedWebPage",
316 elapsed);
317 break;
318 case Feature::WEBUI_CONTEXT:
319 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_WebUI", elapsed);
320 break;
321 case Feature::SERVICE_WORKER_CONTEXT:
322 // Handled in DidInitializeServiceWorkerContextOnWorkerThread().
323 NOTREACHED();
324 break;
327 VLOG(1) << "Num tracked contexts: " << script_context_set_->size();
330 // static
331 void Dispatcher::DidInitializeServiceWorkerContextOnWorkerThread(
332 v8::Local<v8::Context> v8_context,
333 const GURL& url) {
334 const base::TimeTicks start_time = base::TimeTicks::Now();
336 if (!url.SchemeIs(kExtensionScheme) &&
337 !url.SchemeIs(kExtensionResourceScheme)) {
338 // Early-out if this isn't a chrome-extension:// or resource scheme,
339 // because looking up the extension registry is unnecessary if it's not.
340 // Checking this will also skip over hosted apps, which is the desired
341 // behavior - hosted app service workers are not our concern.
342 return;
345 const Extension* extension =
346 RendererExtensionRegistry::Get()->GetExtensionOrAppByURL(url);
348 if (!extension) {
349 // TODO(kalman): This is no good. Instead we need to either:
351 // - Hold onto the v8::Context and create the ScriptContext and install
352 // our bindings when this extension is loaded.
353 // - Deal with there being an extension ID (url.host()) but no
354 // extension associated with it, then document that getBackgroundClient
355 // may fail if the extension hasn't loaded yet.
357 // The former is safer, but is unfriendly to caching (e.g. session restore).
358 // It seems to contradict the service worker idiom.
360 // The latter is friendly to caching, but running extension code without an
361 // installed extension makes me nervous, and means that we won't be able to
362 // expose arbitrary (i.e. capability-checked) extension APIs to service
363 // workers. We will probably need to relax some assertions - we just need
364 // to find them.
366 // Perhaps this could be solved with our own event on the service worker
367 // saying that an extension is ready, and documenting that extension APIs
368 // won't work before that event has fired?
369 return;
372 ScriptContext* context = new ScriptContext(
373 v8_context, nullptr, extension, Feature::SERVICE_WORKER_CONTEXT,
374 extension, Feature::SERVICE_WORKER_CONTEXT);
375 context->set_url(url);
377 g_worker_script_context_set.Get().Insert(make_scoped_ptr(context));
379 v8::Isolate* isolate = context->isolate();
381 // Fetch the source code for service_worker_bindings.js.
382 base::StringPiece script_resource =
383 ResourceBundle::GetSharedInstance().GetRawDataResource(
384 IDR_SERVICE_WORKER_BINDINGS_JS);
385 v8::Local<v8::String> script = v8::String::NewExternal(
386 isolate, new StaticV8ExternalOneByteStringResource(script_resource));
388 // Run service_worker.js to get the main function.
389 v8::Local<v8::Function> main_function;
391 v8::Local<v8::Value> result = context->RunScript(
392 v8_helpers::ToV8StringUnsafe(isolate, "service_worker"), script,
393 base::Bind(&CrashOnException));
394 CHECK(result->IsFunction());
395 main_function = result.As<v8::Function>();
398 // Expose CHECK/DCHECK/NOTREACHED to the main function with a
399 // LoggingNativeHandler. Admire the neat base::Bind trick to both Invalidate
400 // and delete the native handler.
401 LoggingNativeHandler* logging = new LoggingNativeHandler(context);
402 context->AddInvalidationObserver(
403 base::Bind(&NativeHandler::Invalidate, base::Owned(logging)));
405 // Execute the main function with its dependencies passed in as arguments.
406 v8::Local<v8::Value> args[] = {
407 // The extension's background URL.
408 v8_helpers::ToV8StringUnsafe(
409 isolate, BackgroundInfo::GetBackgroundURL(extension).spec()),
410 // The wake-event-page native function.
411 WakeEventPage::Get()->GetForContext(context),
412 // The logging module.
413 logging->NewInstance(),
415 context->CallFunction(main_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 v8::Local<v8::Context> v8_context,
442 const GURL& url) {
443 if (url.SchemeIs(kExtensionScheme) ||
444 url.SchemeIs(kExtensionResourceScheme)) {
445 // See comment in DidInitializeServiceWorkerContextOnWorkerThread.
446 g_worker_script_context_set.Get().Remove(v8_context, url);
450 void Dispatcher::DidCreateDocumentElement(blink::WebLocalFrame* frame) {
451 // Note: use GetEffectiveDocumentURL not just frame->document()->url()
452 // so that this also injects the stylesheet on about:blank frames that
453 // are hosted in the extension process.
454 GURL effective_document_url = ScriptContext::GetEffectiveDocumentURL(
455 frame, frame->document().url(), true /* match_about_blank */);
457 const Extension* extension =
458 RendererExtensionRegistry::Get()->GetExtensionOrAppByURL(
459 effective_document_url);
461 if (extension &&
462 (extension->is_extension() || extension->is_platform_app())) {
463 int resource_id = extension->is_platform_app() ? IDR_PLATFORM_APP_CSS
464 : IDR_EXTENSION_FONTS_CSS;
465 std::string stylesheet = ResourceBundle::GetSharedInstance()
466 .GetRawDataResource(resource_id)
467 .as_string();
468 base::ReplaceFirstSubstringAfterOffset(
469 &stylesheet, 0, "$FONTFAMILY", system_font_family_);
470 base::ReplaceFirstSubstringAfterOffset(
471 &stylesheet, 0, "$FONTSIZE", system_font_size_);
473 // Blink doesn't let us define an additional user agent stylesheet, so
474 // we insert the default platform app or extension stylesheet into all
475 // documents that are loaded in each app or extension.
476 frame->document().insertStyleSheet(WebString::fromUTF8(stylesheet));
479 // If this is an extension options page, and the extension has opted into
480 // using Chrome styles, then insert the Chrome extension stylesheet.
481 if (extension && extension->is_extension() &&
482 OptionsPageInfo::ShouldUseChromeStyle(extension) &&
483 effective_document_url == OptionsPageInfo::GetOptionsPage(extension)) {
484 frame->document().insertStyleSheet(
485 WebString::fromUTF8(ResourceBundle::GetSharedInstance()
486 .GetRawDataResource(IDR_EXTENSION_CSS)
487 .as_string()));
490 // In testing, the document lifetime events can happen after the render
491 // process shutdown event.
492 // See: http://crbug.com/21508 and http://crbug.com/500851
493 if (content_watcher_) {
494 content_watcher_->DidCreateDocumentElement(frame);
498 void Dispatcher::OnExtensionResponse(int request_id,
499 bool success,
500 const base::ListValue& response,
501 const std::string& error) {
502 request_sender_->HandleResponse(request_id, success, response, error);
505 void Dispatcher::DispatchEvent(const std::string& extension_id,
506 const std::string& event_name) const {
507 base::ListValue args;
508 args.Set(0, new base::StringValue(event_name));
509 args.Set(1, new base::ListValue());
511 // Needed for Windows compilation, since kEventBindings is declared extern.
512 const char* local_event_bindings = kEventBindings;
513 script_context_set_->ForEach(
514 extension_id, base::Bind(&CallModuleMethod, local_event_bindings,
515 kEventDispatchFunction, &args));
518 void Dispatcher::InvokeModuleSystemMethod(content::RenderFrame* render_frame,
519 const std::string& extension_id,
520 const std::string& module_name,
521 const std::string& function_name,
522 const base::ListValue& args,
523 bool user_gesture) {
524 scoped_ptr<WebScopedUserGesture> web_user_gesture;
525 if (user_gesture)
526 web_user_gesture.reset(new WebScopedUserGesture);
528 script_context_set_->ForEach(
529 extension_id, render_frame,
530 base::Bind(&CallModuleMethod, module_name, function_name, &args));
532 // Reset the idle handler each time there's any activity like event or message
533 // dispatch, for which Invoke is the chokepoint.
534 if (set_idle_notifications_) {
535 RenderThread::Get()->ScheduleIdleHandler(
536 kInitialExtensionIdleHandlerDelayMs);
539 // Tell the browser process when an event has been dispatched with a lazy
540 // background page active.
541 const Extension* extension =
542 RendererExtensionRegistry::Get()->GetByID(extension_id);
543 if (extension && BackgroundInfo::HasLazyBackgroundPage(extension) &&
544 module_name == kEventBindings &&
545 function_name == kEventDispatchFunction) {
546 content::RenderFrame* background_frame =
547 ExtensionFrameHelper::GetBackgroundPageFrame(extension_id);
548 if (background_frame) {
549 int message_id;
550 args.GetInteger(3, &message_id);
551 background_frame->Send(new ExtensionHostMsg_EventAck(
552 background_frame->GetRoutingID(), message_id));
557 void Dispatcher::ClearPortData(int port_id) {
558 // Only the target port side has entries in |port_to_tab_id_map_|. If
559 // |port_id| is a source port, std::map::erase() will just silently fail
560 // here as a no-op.
561 port_to_tab_id_map_.erase(port_id);
564 // static
565 std::vector<std::pair<std::string, int> > Dispatcher::GetJsResources() {
566 std::vector<std::pair<std::string, int> > resources;
568 // Libraries.
569 resources.push_back(std::make_pair("appView", IDR_APP_VIEW_JS));
570 resources.push_back(std::make_pair("entryIdManager", IDR_ENTRY_ID_MANAGER));
571 resources.push_back(std::make_pair(kEventBindings, IDR_EVENT_BINDINGS_JS));
572 resources.push_back(std::make_pair("extensionOptions",
573 IDR_EXTENSION_OPTIONS_JS));
574 resources.push_back(std::make_pair("extensionOptionsAttributes",
575 IDR_EXTENSION_OPTIONS_ATTRIBUTES_JS));
576 resources.push_back(std::make_pair("extensionOptionsConstants",
577 IDR_EXTENSION_OPTIONS_CONSTANTS_JS));
578 resources.push_back(std::make_pair("extensionOptionsEvents",
579 IDR_EXTENSION_OPTIONS_EVENTS_JS));
580 resources.push_back(std::make_pair("extensionView", IDR_EXTENSION_VIEW_JS));
581 resources.push_back(std::make_pair("extensionViewApiMethods",
582 IDR_EXTENSION_VIEW_API_METHODS_JS));
583 resources.push_back(std::make_pair("extensionViewAttributes",
584 IDR_EXTENSION_VIEW_ATTRIBUTES_JS));
585 resources.push_back(std::make_pair("extensionViewConstants",
586 IDR_EXTENSION_VIEW_CONSTANTS_JS));
587 resources.push_back(std::make_pair("extensionViewEvents",
588 IDR_EXTENSION_VIEW_EVENTS_JS));
589 resources.push_back(std::make_pair(
590 "extensionViewInternal", IDR_EXTENSION_VIEW_INTERNAL_CUSTOM_BINDINGS_JS));
591 resources.push_back(std::make_pair("guestView", IDR_GUEST_VIEW_JS));
592 resources.push_back(std::make_pair("guestViewAttributes",
593 IDR_GUEST_VIEW_ATTRIBUTES_JS));
594 resources.push_back(std::make_pair("guestViewContainer",
595 IDR_GUEST_VIEW_CONTAINER_JS));
596 resources.push_back(std::make_pair("guestViewDeny", IDR_GUEST_VIEW_DENY_JS));
597 resources.push_back(std::make_pair("guestViewEvents",
598 IDR_GUEST_VIEW_EVENTS_JS));
600 if (content::BrowserPluginGuestMode::UseCrossProcessFramesForGuests()) {
601 resources.push_back(std::make_pair("guestViewIframe",
602 IDR_GUEST_VIEW_IFRAME_JS));
603 resources.push_back(std::make_pair("guestViewIframeContainer",
604 IDR_GUEST_VIEW_IFRAME_CONTAINER_JS));
607 resources.push_back(std::make_pair("imageUtil", IDR_IMAGE_UTIL_JS));
608 resources.push_back(std::make_pair("json_schema", IDR_JSON_SCHEMA_JS));
609 resources.push_back(std::make_pair("lastError", IDR_LAST_ERROR_JS));
610 resources.push_back(std::make_pair("messaging", IDR_MESSAGING_JS));
611 resources.push_back(std::make_pair("messaging_utils",
612 IDR_MESSAGING_UTILS_JS));
613 resources.push_back(std::make_pair(kSchemaUtils, IDR_SCHEMA_UTILS_JS));
614 resources.push_back(std::make_pair("sendRequest", IDR_SEND_REQUEST_JS));
615 resources.push_back(std::make_pair("setIcon", IDR_SET_ICON_JS));
616 resources.push_back(std::make_pair("test", IDR_TEST_CUSTOM_BINDINGS_JS));
617 resources.push_back(
618 std::make_pair("test_environment_specific_bindings",
619 IDR_BROWSER_TEST_ENVIRONMENT_SPECIFIC_BINDINGS_JS));
620 resources.push_back(std::make_pair("uncaught_exception_handler",
621 IDR_UNCAUGHT_EXCEPTION_HANDLER_JS));
622 resources.push_back(std::make_pair("unload_event", IDR_UNLOAD_EVENT_JS));
623 resources.push_back(std::make_pair("utils", IDR_UTILS_JS));
624 resources.push_back(std::make_pair("webRequest",
625 IDR_WEB_REQUEST_CUSTOM_BINDINGS_JS));
626 resources.push_back(
627 std::make_pair("webRequestInternal",
628 IDR_WEB_REQUEST_INTERNAL_CUSTOM_BINDINGS_JS));
629 // Note: webView not webview so that this doesn't interfere with the
630 // chrome.webview API bindings.
631 resources.push_back(std::make_pair("webView", IDR_WEB_VIEW_JS));
632 resources.push_back(std::make_pair("webViewActionRequests",
633 IDR_WEB_VIEW_ACTION_REQUESTS_JS));
634 resources.push_back(std::make_pair("webViewApiMethods",
635 IDR_WEB_VIEW_API_METHODS_JS));
636 resources.push_back(std::make_pair("webViewAttributes",
637 IDR_WEB_VIEW_ATTRIBUTES_JS));
638 resources.push_back(std::make_pair("webViewConstants",
639 IDR_WEB_VIEW_CONSTANTS_JS));
640 resources.push_back(std::make_pair("webViewEvents", IDR_WEB_VIEW_EVENTS_JS));
641 resources.push_back(std::make_pair("webViewInternal",
642 IDR_WEB_VIEW_INTERNAL_CUSTOM_BINDINGS_JS));
643 if (content::BrowserPluginGuestMode::UseCrossProcessFramesForGuests()) {
644 resources.push_back(std::make_pair("webViewIframe",
645 IDR_WEB_VIEW_IFRAME_JS));
647 resources.push_back(
648 std::make_pair(mojo::kBindingsModuleName, IDR_MOJO_BINDINGS_JS));
649 resources.push_back(
650 std::make_pair(mojo::kBufferModuleName, IDR_MOJO_BUFFER_JS));
651 resources.push_back(
652 std::make_pair(mojo::kCodecModuleName, IDR_MOJO_CODEC_JS));
653 resources.push_back(
654 std::make_pair(mojo::kConnectionModuleName, IDR_MOJO_CONNECTION_JS));
655 resources.push_back(
656 std::make_pair(mojo::kConnectorModuleName, IDR_MOJO_CONNECTOR_JS));
657 resources.push_back(
658 std::make_pair(mojo::kRouterModuleName, IDR_MOJO_ROUTER_JS));
659 resources.push_back(
660 std::make_pair(mojo::kUnicodeModuleName, IDR_MOJO_UNICODE_JS));
661 resources.push_back(
662 std::make_pair(mojo::kValidatorModuleName, IDR_MOJO_VALIDATOR_JS));
663 resources.push_back(std::make_pair("async_waiter", IDR_ASYNC_WAITER_JS));
664 resources.push_back(std::make_pair("data_receiver", IDR_DATA_RECEIVER_JS));
665 resources.push_back(std::make_pair("data_sender", IDR_DATA_SENDER_JS));
666 resources.push_back(std::make_pair("keep_alive", IDR_KEEP_ALIVE_JS));
667 resources.push_back(std::make_pair("extensions/common/mojo/keep_alive.mojom",
668 IDR_KEEP_ALIVE_MOJOM_JS));
669 resources.push_back(std::make_pair("device/serial/data_stream.mojom",
670 IDR_DATA_STREAM_MOJOM_JS));
671 resources.push_back(
672 std::make_pair("device/serial/data_stream_serialization.mojom",
673 IDR_DATA_STREAM_SERIALIZATION_MOJOM_JS));
674 resources.push_back(std::make_pair("stash_client", IDR_STASH_CLIENT_JS));
675 resources.push_back(
676 std::make_pair("extensions/common/mojo/stash.mojom", IDR_STASH_MOJOM_JS));
678 // Custom bindings.
679 resources.push_back(
680 std::make_pair("app.runtime", IDR_APP_RUNTIME_CUSTOM_BINDINGS_JS));
681 resources.push_back(
682 std::make_pair("app.window", IDR_APP_WINDOW_CUSTOM_BINDINGS_JS));
683 resources.push_back(
684 std::make_pair("declarativeWebRequest",
685 IDR_DECLARATIVE_WEBREQUEST_CUSTOM_BINDINGS_JS));
686 resources.push_back(
687 std::make_pair("contextMenus", IDR_CONTEXT_MENUS_CUSTOM_BINDINGS_JS));
688 resources.push_back(
689 std::make_pair("contextMenusHandlers", IDR_CONTEXT_MENUS_HANDLERS_JS));
690 resources.push_back(
691 std::make_pair("extension", IDR_EXTENSION_CUSTOM_BINDINGS_JS));
692 resources.push_back(std::make_pair("i18n", IDR_I18N_CUSTOM_BINDINGS_JS));
693 resources.push_back(std::make_pair(
694 "mimeHandlerPrivate", IDR_MIME_HANDLER_PRIVATE_CUSTOM_BINDINGS_JS));
695 resources.push_back(std::make_pair("extensions/common/api/mime_handler.mojom",
696 IDR_MIME_HANDLER_MOJOM_JS));
697 resources.push_back(
698 std::make_pair("mojoPrivate", IDR_MOJO_PRIVATE_CUSTOM_BINDINGS_JS));
699 resources.push_back(
700 std::make_pair("permissions", IDR_PERMISSIONS_CUSTOM_BINDINGS_JS));
701 resources.push_back(std::make_pair("printerProvider",
702 IDR_PRINTER_PROVIDER_CUSTOM_BINDINGS_JS));
703 resources.push_back(
704 std::make_pair("runtime", IDR_RUNTIME_CUSTOM_BINDINGS_JS));
705 resources.push_back(std::make_pair("windowControls", IDR_WINDOW_CONTROLS_JS));
706 resources.push_back(
707 std::make_pair("webViewRequest",
708 IDR_WEB_VIEW_REQUEST_CUSTOM_BINDINGS_JS));
709 resources.push_back(std::make_pair("binding", IDR_BINDING_JS));
711 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
712 switches::kEnableMojoSerialService)) {
713 resources.push_back(
714 std::make_pair("serial", IDR_SERIAL_CUSTOM_BINDINGS_JS));
716 resources.push_back(std::make_pair("serial_service", IDR_SERIAL_SERVICE_JS));
717 resources.push_back(
718 std::make_pair("device/serial/serial.mojom", IDR_SERIAL_MOJOM_JS));
719 resources.push_back(std::make_pair("device/serial/serial_serialization.mojom",
720 IDR_SERIAL_SERIALIZATION_MOJOM_JS));
722 // Custom types sources.
723 resources.push_back(std::make_pair("StorageArea", IDR_STORAGE_AREA_JS));
725 // Platform app sources that are not API-specific..
726 resources.push_back(std::make_pair("platformApp", IDR_PLATFORM_APP_JS));
728 #if defined(ENABLE_MEDIA_ROUTER)
729 resources.push_back(
730 std::make_pair("chrome/browser/media/router/media_router.mojom",
731 IDR_MEDIA_ROUTER_MOJOM_JS));
732 resources.push_back(
733 std::make_pair("media_router_bindings", IDR_MEDIA_ROUTER_BINDINGS_JS));
734 #endif // defined(ENABLE_MEDIA_ROUTER)
736 return resources;
739 // NOTE: please use the naming convention "foo_natives" for these.
740 // static
741 void Dispatcher::RegisterNativeHandlers(ModuleSystem* module_system,
742 ScriptContext* context,
743 Dispatcher* dispatcher,
744 RequestSender* request_sender,
745 V8SchemaRegistry* v8_schema_registry) {
746 module_system->RegisterNativeHandler(
747 "chrome", scoped_ptr<NativeHandler>(new ChromeNativeHandler(context)));
748 module_system->RegisterNativeHandler(
749 "lazy_background_page",
750 scoped_ptr<NativeHandler>(new LazyBackgroundPageNativeHandler(context)));
751 module_system->RegisterNativeHandler(
752 "logging", scoped_ptr<NativeHandler>(new LoggingNativeHandler(context)));
753 module_system->RegisterNativeHandler("schema_registry",
754 v8_schema_registry->AsNativeHandler());
755 module_system->RegisterNativeHandler(
756 "print", scoped_ptr<NativeHandler>(new PrintNativeHandler(context)));
757 module_system->RegisterNativeHandler(
758 "test_features",
759 scoped_ptr<NativeHandler>(new TestFeaturesNativeHandler(context)));
760 module_system->RegisterNativeHandler(
761 "test_native_handler",
762 scoped_ptr<NativeHandler>(new TestNativeHandler(context)));
763 module_system->RegisterNativeHandler(
764 "user_gestures",
765 scoped_ptr<NativeHandler>(new UserGesturesNativeHandler(context)));
766 module_system->RegisterNativeHandler(
767 "utils", scoped_ptr<NativeHandler>(new UtilsNativeHandler(context)));
768 module_system->RegisterNativeHandler(
769 "v8_context",
770 scoped_ptr<NativeHandler>(
771 new V8ContextNativeHandler(context, dispatcher)));
772 module_system->RegisterNativeHandler(
773 "event_natives", scoped_ptr<NativeHandler>(new EventBindings(context)));
774 module_system->RegisterNativeHandler(
775 "messaging_natives",
776 scoped_ptr<NativeHandler>(MessagingBindings::Get(dispatcher, context)));
777 module_system->RegisterNativeHandler(
778 "apiDefinitions",
779 scoped_ptr<NativeHandler>(
780 new ApiDefinitionsNatives(dispatcher, context)));
781 module_system->RegisterNativeHandler(
782 "sendRequest",
783 scoped_ptr<NativeHandler>(
784 new SendRequestNatives(request_sender, context)));
785 module_system->RegisterNativeHandler(
786 "setIcon",
787 scoped_ptr<NativeHandler>(new SetIconNatives(context)));
788 module_system->RegisterNativeHandler(
789 "activityLogger",
790 scoped_ptr<NativeHandler>(new APIActivityLogger(context)));
791 module_system->RegisterNativeHandler(
792 "renderFrameObserverNatives",
793 scoped_ptr<NativeHandler>(new RenderFrameObserverNatives(context)));
795 // Natives used by multiple APIs.
796 module_system->RegisterNativeHandler(
797 "file_system_natives",
798 scoped_ptr<NativeHandler>(new FileSystemNatives(context)));
800 // Custom bindings.
801 // |dispatcher| is null in unit tests.
802 const ScriptContextSet* script_context_set = dispatcher ?
803 &dispatcher->script_context_set() : nullptr;
804 module_system->RegisterNativeHandler(
805 "app_window_natives",
806 scoped_ptr<NativeHandler>(new AppWindowCustomBindings(
807 script_context_set, context)));
808 module_system->RegisterNativeHandler(
809 "blob_natives",
810 scoped_ptr<NativeHandler>(new BlobNativeHandler(context)));
811 module_system->RegisterNativeHandler(
812 "context_menus",
813 scoped_ptr<NativeHandler>(new ContextMenusCustomBindings(context)));
814 module_system->RegisterNativeHandler(
815 "css_natives", scoped_ptr<NativeHandler>(new CssNativeHandler(context)));
816 module_system->RegisterNativeHandler(
817 "document_natives",
818 scoped_ptr<NativeHandler>(new DocumentCustomBindings(context)));
819 module_system->RegisterNativeHandler(
820 "guest_view_internal",
821 scoped_ptr<NativeHandler>(
822 new GuestViewInternalCustomBindings(context)));
823 module_system->RegisterNativeHandler(
824 "i18n", scoped_ptr<NativeHandler>(new I18NCustomBindings(context)));
825 module_system->RegisterNativeHandler(
826 "id_generator",
827 scoped_ptr<NativeHandler>(new IdGeneratorCustomBindings(context)));
828 module_system->RegisterNativeHandler(
829 "runtime", scoped_ptr<NativeHandler>(new RuntimeCustomBindings(context)));
832 bool Dispatcher::OnControlMessageReceived(const IPC::Message& message) {
833 bool handled = true;
834 IPC_BEGIN_MESSAGE_MAP(Dispatcher, message)
835 IPC_MESSAGE_HANDLER(ExtensionMsg_ActivateExtension, OnActivateExtension)
836 IPC_MESSAGE_HANDLER(ExtensionMsg_CancelSuspend, OnCancelSuspend)
837 IPC_MESSAGE_HANDLER(ExtensionMsg_DeliverMessage, OnDeliverMessage)
838 IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnConnect, OnDispatchOnConnect)
839 IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnDisconnect, OnDispatchOnDisconnect)
840 IPC_MESSAGE_HANDLER(ExtensionMsg_Loaded, OnLoaded)
841 IPC_MESSAGE_HANDLER(ExtensionMsg_MessageInvoke, OnMessageInvoke)
842 IPC_MESSAGE_HANDLER(ExtensionMsg_SetChannel, OnSetChannel)
843 IPC_MESSAGE_HANDLER(ExtensionMsg_SetScriptingWhitelist,
844 OnSetScriptingWhitelist)
845 IPC_MESSAGE_HANDLER(ExtensionMsg_SetSystemFont, OnSetSystemFont)
846 IPC_MESSAGE_HANDLER(ExtensionMsg_SetWebViewPartitionID,
847 OnSetWebViewPartitionID)
848 IPC_MESSAGE_HANDLER(ExtensionMsg_ShouldSuspend, OnShouldSuspend)
849 IPC_MESSAGE_HANDLER(ExtensionMsg_Suspend, OnSuspend)
850 IPC_MESSAGE_HANDLER(ExtensionMsg_TransferBlobs, OnTransferBlobs)
851 IPC_MESSAGE_HANDLER(ExtensionMsg_Unloaded, OnUnloaded)
852 IPC_MESSAGE_HANDLER(ExtensionMsg_UpdatePermissions, OnUpdatePermissions)
853 IPC_MESSAGE_HANDLER(ExtensionMsg_UpdateTabSpecificPermissions,
854 OnUpdateTabSpecificPermissions)
855 IPC_MESSAGE_HANDLER(ExtensionMsg_ClearTabSpecificPermissions,
856 OnClearTabSpecificPermissions)
857 IPC_MESSAGE_HANDLER(ExtensionMsg_UsingWebRequestAPI, OnUsingWebRequestAPI)
858 IPC_MESSAGE_FORWARD(ExtensionMsg_WatchPages,
859 content_watcher_.get(),
860 ContentWatcher::OnWatchPages)
861 IPC_MESSAGE_UNHANDLED(handled = false)
862 IPC_END_MESSAGE_MAP()
864 return handled;
867 void Dispatcher::WebKitInitialized() {
868 RenderThread::Get()->RegisterExtension(SafeBuiltins::CreateV8Extension());
870 // WebSecurityPolicy whitelists. They should be registered for both
871 // chrome-extension: and chrome-extension-resource.
872 using RegisterFunction = void (*)(const WebString&);
873 RegisterFunction register_functions[] = {
874 // Treat as secure because communication with them is entirely in the
875 // browser, so there is no danger of manipulation or eavesdropping on
876 // communication with them by third parties.
877 WebSecurityPolicy::registerURLSchemeAsSecure,
878 // As far as Blink is concerned, they should be allowed to receive CORS
879 // requests. At the Extensions layer, requests will actually be blocked
880 // unless overridden by the web_accessible_resources manifest key.
881 // TODO(kalman): See what happens with a service worker.
882 WebSecurityPolicy::registerURLSchemeAsCORSEnabled,
883 // Resources should bypass Content Security Policy checks when included in
884 // protected resources. TODO(kalman): What are "protected resources"?
885 WebSecurityPolicy::registerURLSchemeAsBypassingContentSecurityPolicy,
886 // Extension resources are HTTP-like and safe to expose to the fetch API.
887 // The rules for the fetch API are consistent with XHR.
888 WebSecurityPolicy::registerURLSchemeAsSupportingFetchAPI,
889 // Extension resources, when loaded as the top-level document, should
890 // bypass Blink's strict first-party origin checks.
891 WebSecurityPolicy::registerURLSchemeAsFirstPartyWhenTopLevel,
894 WebString extension_scheme(base::ASCIIToUTF16(kExtensionScheme));
895 WebString extension_resource_scheme(base::ASCIIToUTF16(
896 kExtensionResourceScheme));
897 for (RegisterFunction func : register_functions) {
898 func(extension_scheme);
899 func(extension_resource_scheme);
902 // For extensions, we want to ensure we call the IdleHandler every so often,
903 // even if the extension keeps up activity.
904 if (set_idle_notifications_) {
905 forced_idle_timer_.reset(new base::RepeatingTimer<RenderThread>);
906 forced_idle_timer_->Start(
907 FROM_HERE,
908 base::TimeDelta::FromMilliseconds(kMaxExtensionIdleHandlerDelayMs),
909 RenderThread::Get(),
910 &RenderThread::IdleHandler);
913 // Initialize host permissions for any extensions that were activated before
914 // WebKit was initialized.
915 for (const std::string& extension_id : active_extension_ids_) {
916 const Extension* extension =
917 RendererExtensionRegistry::Get()->GetByID(extension_id);
918 CHECK(extension);
919 InitOriginPermissions(extension);
922 EnableCustomElementWhiteList();
924 is_webkit_initialized_ = true;
927 void Dispatcher::IdleNotification() {
928 if (set_idle_notifications_ && forced_idle_timer_) {
929 // Dampen the forced delay as well if the extension stays idle for long
930 // periods of time. (forced_idle_timer_ can be NULL after
931 // OnRenderProcessShutdown has been called.)
932 int64 forced_delay_ms =
933 std::max(RenderThread::Get()->GetIdleNotificationDelayInMs(),
934 kMaxExtensionIdleHandlerDelayMs);
935 forced_idle_timer_->Stop();
936 forced_idle_timer_->Start(
937 FROM_HERE,
938 base::TimeDelta::FromMilliseconds(forced_delay_ms),
939 RenderThread::Get(),
940 &RenderThread::IdleHandler);
944 void Dispatcher::OnRenderProcessShutdown() {
945 v8_schema_registry_.reset();
946 forced_idle_timer_.reset();
947 content_watcher_.reset();
950 void Dispatcher::OnActivateExtension(const std::string& extension_id) {
951 const Extension* extension =
952 RendererExtensionRegistry::Get()->GetByID(extension_id);
953 if (!extension) {
954 // Extension was activated but was never loaded. This probably means that
955 // the renderer failed to load it (or the browser failed to tell us when it
956 // did). Failures shouldn't happen, but instead of crashing there (which
957 // executes on all renderers) be conservative and only crash in the renderer
958 // of the extension which failed to load; this one.
959 std::string& error = extension_load_errors_[extension_id];
960 char minidump[256];
961 base::debug::Alias(&minidump);
962 base::snprintf(minidump,
963 arraysize(minidump),
964 "e::dispatcher:%s:%s",
965 extension_id.c_str(),
966 error.c_str());
967 LOG(FATAL) << extension_id << " was never loaded: " << error;
970 active_extension_ids_.insert(extension_id);
972 // This is called when starting a new extension page, so start the idle
973 // handler ticking.
974 RenderThread::Get()->ScheduleIdleHandler(kInitialExtensionIdleHandlerDelayMs);
976 if (is_webkit_initialized_) {
977 DOMActivityLogger::AttachToWorld(
978 DOMActivityLogger::kMainWorldId, extension_id);
980 InitOriginPermissions(extension);
983 UpdateActiveExtensions();
986 void Dispatcher::OnCancelSuspend(const std::string& extension_id) {
987 DispatchEvent(extension_id, kOnSuspendCanceledEvent);
990 void Dispatcher::OnDeliverMessage(int target_port_id, const Message& message) {
991 scoped_ptr<RequestSender::ScopedTabID> scoped_tab_id;
992 std::map<int, int>::const_iterator it =
993 port_to_tab_id_map_.find(target_port_id);
994 if (it != port_to_tab_id_map_.end()) {
995 scoped_tab_id.reset(
996 new RequestSender::ScopedTabID(request_sender(), it->second));
999 MessagingBindings::DeliverMessage(*script_context_set_, target_port_id,
1000 message,
1001 NULL); // All render frames.
1004 void Dispatcher::OnDispatchOnConnect(
1005 int target_port_id,
1006 const std::string& channel_name,
1007 const ExtensionMsg_TabConnectionInfo& source,
1008 const ExtensionMsg_ExternalConnectionInfo& info,
1009 const std::string& tls_channel_id) {
1010 DCHECK(!ContainsKey(port_to_tab_id_map_, target_port_id));
1011 DCHECK_EQ(1, target_port_id % 2); // target renderer ports have odd IDs.
1012 int sender_tab_id = -1;
1013 source.tab.GetInteger("id", &sender_tab_id);
1014 port_to_tab_id_map_[target_port_id] = sender_tab_id;
1016 MessagingBindings::DispatchOnConnect(*script_context_set_, target_port_id,
1017 channel_name, source, info,
1018 tls_channel_id,
1019 NULL); // All render frames.
1022 void Dispatcher::OnDispatchOnDisconnect(int port_id,
1023 const std::string& error_message) {
1024 MessagingBindings::DispatchOnDisconnect(*script_context_set_, port_id,
1025 error_message,
1026 NULL); // All render frames.
1029 void Dispatcher::OnLoaded(
1030 const std::vector<ExtensionMsg_Loaded_Params>& loaded_extensions) {
1031 for (const auto& param : loaded_extensions) {
1032 std::string error;
1033 scoped_refptr<const Extension> extension = param.ConvertToExtension(&error);
1034 if (!extension.get()) {
1035 NOTREACHED() << error;
1036 // Note: in tests |param.id| has been observed to be empty (see comment
1037 // just below) so this isn't all that reliable.
1038 extension_load_errors_[param.id] = error;
1039 continue;
1042 RendererExtensionRegistry* extension_registry =
1043 RendererExtensionRegistry::Get();
1044 // TODO(kalman): This test is deliberately not a CHECK (though I wish it
1045 // could be) and uses extension->id() not params.id:
1046 // 1. For some reason params.id can be empty. I've only seen it with
1047 // the webstore extension, in tests, and I've spent some time trying to
1048 // figure out why - but cost/benefit won.
1049 // 2. The browser only sends this IPC to RenderProcessHosts once, but the
1050 // Dispatcher is attached to a RenderThread. Presumably there is a
1051 // mismatch there. In theory one would think it's possible for the
1052 // browser to figure this out itself - but again, cost/benefit.
1053 if (!extension_registry->Contains(extension->id()))
1054 extension_registry->Insert(extension);
1057 // Update the available bindings for all contexts. These may have changed if
1058 // an externally_connectable extension was loaded that can connect to an
1059 // open webpage.
1060 UpdateBindings("");
1063 void Dispatcher::OnMessageInvoke(const std::string& extension_id,
1064 const std::string& module_name,
1065 const std::string& function_name,
1066 const base::ListValue& args,
1067 bool user_gesture) {
1068 InvokeModuleSystemMethod(
1069 NULL, extension_id, module_name, function_name, args, user_gesture);
1072 void Dispatcher::OnSetChannel(int channel) {
1073 delegate_->SetChannel(channel);
1074 AddChannelSpecificFeatures();
1077 void Dispatcher::OnSetScriptingWhitelist(
1078 const ExtensionsClient::ScriptingWhitelist& extension_ids) {
1079 ExtensionsClient::Get()->SetScriptingWhitelist(extension_ids);
1082 void Dispatcher::OnSetSystemFont(const std::string& font_family,
1083 const std::string& font_size) {
1084 system_font_family_ = font_family;
1085 system_font_size_ = font_size;
1088 void Dispatcher::OnSetWebViewPartitionID(const std::string& partition_id) {
1089 // |webview_partition_id_| cannot be changed once set.
1090 CHECK(webview_partition_id_.empty() || webview_partition_id_ == partition_id);
1091 webview_partition_id_ = partition_id;
1094 void Dispatcher::OnShouldSuspend(const std::string& extension_id,
1095 uint64 sequence_id) {
1096 RenderThread::Get()->Send(
1097 new ExtensionHostMsg_ShouldSuspendAck(extension_id, sequence_id));
1100 void Dispatcher::OnSuspend(const std::string& extension_id) {
1101 // Dispatch the suspend event. This doesn't go through the standard event
1102 // dispatch machinery because it requires special handling. We need to let
1103 // the browser know when we are starting and stopping the event dispatch, so
1104 // that it still considers the extension idle despite any activity the suspend
1105 // event creates.
1106 DispatchEvent(extension_id, kOnSuspendEvent);
1107 RenderThread::Get()->Send(new ExtensionHostMsg_SuspendAck(extension_id));
1110 void Dispatcher::OnTransferBlobs(const std::vector<std::string>& blob_uuids) {
1111 RenderThread::Get()->Send(new ExtensionHostMsg_TransferBlobsAck(blob_uuids));
1114 void Dispatcher::OnUnloaded(const std::string& id) {
1115 // See comment in OnLoaded for why it would be nice, but perhaps incorrect,
1116 // to CHECK here rather than guarding.
1117 if (!RendererExtensionRegistry::Get()->Remove(id))
1118 return;
1120 active_extension_ids_.erase(id);
1122 script_injection_manager_->OnExtensionUnloaded(id);
1124 // If the extension is later reloaded with a different set of permissions,
1125 // we'd like it to get a new isolated world ID, so that it can pick up the
1126 // changed origin whitelist.
1127 ScriptInjection::RemoveIsolatedWorld(id);
1129 // Invalidate all of the contexts that were removed.
1130 // TODO(kalman): add an invalidation observer interface to ScriptContext.
1131 std::set<ScriptContext*> removed_contexts =
1132 script_context_set_->OnExtensionUnloaded(id);
1133 for (ScriptContext* context : removed_contexts) {
1134 request_sender_->InvalidateSource(context);
1137 // Update the available bindings for the remaining contexts. These may have
1138 // changed if an externally_connectable extension is unloaded and a webpage
1139 // is no longer accessible.
1140 UpdateBindings("");
1142 // Invalidates the messages map for the extension in case the extension is
1143 // reloaded with a new messages map.
1144 EraseL10nMessagesMap(id);
1146 // We don't do anything with existing platform-app stylesheets. They will
1147 // stay resident, but the URL pattern corresponding to the unloaded
1148 // extension's URL just won't match anything anymore.
1151 void Dispatcher::OnUpdatePermissions(
1152 const ExtensionMsg_UpdatePermissions_Params& params) {
1153 const Extension* extension =
1154 RendererExtensionRegistry::Get()->GetByID(params.extension_id);
1155 if (!extension)
1156 return;
1158 scoped_refptr<const PermissionSet> active =
1159 params.active_permissions.ToPermissionSet();
1160 scoped_refptr<const PermissionSet> withheld =
1161 params.withheld_permissions.ToPermissionSet();
1163 if (is_webkit_initialized_) {
1164 UpdateOriginPermissions(
1165 extension->url(),
1166 extension->permissions_data()->GetEffectiveHostPermissions(),
1167 active->effective_hosts());
1170 extension->permissions_data()->SetPermissions(active, withheld);
1171 UpdateBindings(extension->id());
1174 void Dispatcher::OnUpdateTabSpecificPermissions(const GURL& visible_url,
1175 const std::string& extension_id,
1176 const URLPatternSet& new_hosts,
1177 bool update_origin_whitelist,
1178 int tab_id) {
1179 const Extension* extension =
1180 RendererExtensionRegistry::Get()->GetByID(extension_id);
1181 if (!extension)
1182 return;
1184 URLPatternSet old_effective =
1185 extension->permissions_data()->GetEffectiveHostPermissions();
1186 extension->permissions_data()->UpdateTabSpecificPermissions(
1187 tab_id,
1188 new extensions::PermissionSet(extensions::APIPermissionSet(),
1189 extensions::ManifestPermissionSet(),
1190 new_hosts,
1191 extensions::URLPatternSet()));
1193 if (is_webkit_initialized_ && update_origin_whitelist) {
1194 UpdateOriginPermissions(
1195 extension->url(),
1196 old_effective,
1197 extension->permissions_data()->GetEffectiveHostPermissions());
1201 void Dispatcher::OnClearTabSpecificPermissions(
1202 const std::vector<std::string>& extension_ids,
1203 bool update_origin_whitelist,
1204 int tab_id) {
1205 for (const std::string& id : extension_ids) {
1206 const Extension* extension = RendererExtensionRegistry::Get()->GetByID(id);
1207 if (extension) {
1208 URLPatternSet old_effective =
1209 extension->permissions_data()->GetEffectiveHostPermissions();
1210 extension->permissions_data()->ClearTabSpecificPermissions(tab_id);
1211 if (is_webkit_initialized_ && update_origin_whitelist) {
1212 UpdateOriginPermissions(
1213 extension->url(),
1214 old_effective,
1215 extension->permissions_data()->GetEffectiveHostPermissions());
1221 void Dispatcher::OnUsingWebRequestAPI(bool webrequest_used) {
1222 webrequest_used_ = webrequest_used;
1225 void Dispatcher::OnUserScriptsUpdated(const std::set<HostID>& changed_hosts,
1226 const std::vector<UserScript*>& scripts) {
1227 UpdateActiveExtensions();
1230 void Dispatcher::UpdateActiveExtensions() {
1231 std::set<std::string> active_extensions = active_extension_ids_;
1232 user_script_set_manager_->GetAllActiveExtensionIds(&active_extensions);
1233 delegate_->OnActiveExtensionsUpdated(active_extensions);
1236 void Dispatcher::InitOriginPermissions(const Extension* extension) {
1237 delegate_->InitOriginPermissions(extension,
1238 IsExtensionActive(extension->id()));
1239 UpdateOriginPermissions(
1240 extension->url(),
1241 URLPatternSet(), // No old permissions.
1242 extension->permissions_data()->GetEffectiveHostPermissions());
1245 void Dispatcher::UpdateOriginPermissions(const GURL& extension_url,
1246 const URLPatternSet& old_patterns,
1247 const URLPatternSet& new_patterns) {
1248 static const char* kSchemes[] = {
1249 url::kHttpScheme,
1250 url::kHttpsScheme,
1251 url::kFileScheme,
1252 content::kChromeUIScheme,
1253 url::kFtpScheme,
1254 #if defined(OS_CHROMEOS)
1255 content::kExternalFileScheme,
1256 #endif
1257 extensions::kExtensionScheme,
1259 for (size_t i = 0; i < arraysize(kSchemes); ++i) {
1260 const char* scheme = kSchemes[i];
1261 // Remove all old patterns...
1262 for (URLPatternSet::const_iterator pattern = old_patterns.begin();
1263 pattern != old_patterns.end(); ++pattern) {
1264 if (pattern->MatchesScheme(scheme)) {
1265 WebSecurityPolicy::removeOriginAccessWhitelistEntry(
1266 extension_url,
1267 WebString::fromUTF8(scheme),
1268 WebString::fromUTF8(pattern->host()),
1269 pattern->match_subdomains());
1272 // ...And add the new ones.
1273 for (URLPatternSet::const_iterator pattern = new_patterns.begin();
1274 pattern != new_patterns.end(); ++pattern) {
1275 if (pattern->MatchesScheme(scheme)) {
1276 WebSecurityPolicy::addOriginAccessWhitelistEntry(
1277 extension_url,
1278 WebString::fromUTF8(scheme),
1279 WebString::fromUTF8(pattern->host()),
1280 pattern->match_subdomains());
1286 void Dispatcher::EnableCustomElementWhiteList() {
1287 blink::WebCustomElement::addEmbedderCustomElementName("appview");
1288 blink::WebCustomElement::addEmbedderCustomElementName("appviewbrowserplugin");
1289 blink::WebCustomElement::addEmbedderCustomElementName("extensionoptions");
1290 blink::WebCustomElement::addEmbedderCustomElementName(
1291 "extensionoptionsbrowserplugin");
1292 blink::WebCustomElement::addEmbedderCustomElementName("extensionview");
1293 blink::WebCustomElement::addEmbedderCustomElementName(
1294 "extensionviewbrowserplugin");
1295 blink::WebCustomElement::addEmbedderCustomElementName("webview");
1296 blink::WebCustomElement::addEmbedderCustomElementName("webviewbrowserplugin");
1299 void Dispatcher::UpdateBindings(const std::string& extension_id) {
1300 script_context_set().ForEach(extension_id,
1301 base::Bind(&Dispatcher::UpdateBindingsForContext,
1302 base::Unretained(this)));
1305 void Dispatcher::UpdateBindingsForContext(ScriptContext* context) {
1306 v8::HandleScope handle_scope(context->isolate());
1307 v8::Context::Scope context_scope(context->v8_context());
1309 // TODO(kalman): Make the bindings registration have zero overhead then run
1310 // the same code regardless of context type.
1311 switch (context->context_type()) {
1312 case Feature::UNSPECIFIED_CONTEXT:
1313 case Feature::WEB_PAGE_CONTEXT:
1314 case Feature::BLESSED_WEB_PAGE_CONTEXT:
1315 // Hard-code registration of any APIs that are exposed to webpage-like
1316 // contexts, because it's too expensive to run the full bindings code.
1317 // All of the same permission checks will still apply.
1318 if (context->GetAvailability("app").is_available())
1319 RegisterBinding("app", context);
1320 if (context->GetAvailability("webstore").is_available())
1321 RegisterBinding("webstore", context);
1322 if (context->GetAvailability("dashboardPrivate").is_available())
1323 RegisterBinding("dashboardPrivate", context);
1324 if (IsRuntimeAvailableToContext(context))
1325 RegisterBinding("runtime", context);
1326 UpdateContentCapabilities(context);
1327 break;
1329 case Feature::BLESSED_EXTENSION_CONTEXT:
1330 case Feature::UNBLESSED_EXTENSION_CONTEXT:
1331 case Feature::CONTENT_SCRIPT_CONTEXT:
1332 case Feature::WEBUI_CONTEXT: {
1333 // Extension context; iterate through all the APIs and bind the available
1334 // ones.
1335 const FeatureProvider* api_feature_provider =
1336 FeatureProvider::GetAPIFeatures();
1337 const std::vector<std::string>& apis =
1338 api_feature_provider->GetAllFeatureNames();
1339 for (const std::string& api_name : apis) {
1340 Feature* feature = api_feature_provider->GetFeature(api_name);
1341 DCHECK(feature);
1343 // Internal APIs are included via require(api_name) from internal code
1344 // rather than chrome[api_name].
1345 if (feature->IsInternal())
1346 continue;
1348 // If this API has a parent feature (and isn't marked 'noparent'),
1349 // then this must be a function or event, so we should not register.
1350 if (api_feature_provider->GetParent(feature) != NULL)
1351 continue;
1353 // Skip chrome.test if this isn't a test.
1354 if (api_name == "test" &&
1355 !base::CommandLine::ForCurrentProcess()->HasSwitch(
1356 ::switches::kTestType)) {
1357 continue;
1360 if (context->IsAnyFeatureAvailableToContext(*feature))
1361 RegisterBinding(api_name, context);
1363 break;
1365 case Feature::SERVICE_WORKER_CONTEXT:
1366 // Handled in DidInitializeServiceWorkerContextOnWorkerThread().
1367 NOTREACHED();
1368 break;
1372 void Dispatcher::RegisterBinding(const std::string& api_name,
1373 ScriptContext* context) {
1374 std::string bind_name;
1375 v8::Local<v8::Object> bind_object =
1376 GetOrCreateBindObjectIfAvailable(api_name, &bind_name, context);
1378 // Empty if the bind object failed to be created, probably because the
1379 // extension overrode chrome with a non-object, e.g. window.chrome = true.
1380 if (bind_object.IsEmpty())
1381 return;
1383 v8::Local<v8::String> v8_bind_name =
1384 v8::String::NewFromUtf8(context->isolate(), bind_name.c_str());
1385 if (bind_object->HasRealNamedProperty(v8_bind_name)) {
1386 // The bind object may already have the property if the API has been
1387 // registered before (or if the extension has put something there already,
1388 // but, whatevs).
1390 // In the former case, we need to re-register the bindings for the APIs
1391 // which the extension now has permissions for (if any), but not touch any
1392 // others so that we don't destroy state such as event listeners.
1394 // TODO(kalman): Only register available APIs to make this all moot.
1395 if (bind_object->HasRealNamedCallbackProperty(v8_bind_name))
1396 return; // lazy binding still there, nothing to do
1397 if (bind_object->Get(v8_bind_name)->IsObject())
1398 return; // binding has already been fully installed
1401 ModuleSystem* module_system = context->module_system();
1402 if (!source_map_.Contains(api_name)) {
1403 module_system->RegisterNativeHandler(
1404 api_name,
1405 scoped_ptr<NativeHandler>(new BindingGeneratingNativeHandler(
1406 context, api_name, "binding")));
1407 module_system->SetNativeLazyField(
1408 bind_object, bind_name, api_name, "binding");
1409 } else {
1410 module_system->SetLazyField(bind_object, bind_name, api_name, "binding");
1414 // NOTE: please use the naming convention "foo_natives" for these.
1415 void Dispatcher::RegisterNativeHandlers(ModuleSystem* module_system,
1416 ScriptContext* context) {
1417 RegisterNativeHandlers(module_system,
1418 context,
1419 this,
1420 request_sender_.get(),
1421 v8_schema_registry_.get());
1422 const Extension* extension = context->extension();
1423 int manifest_version = extension ? extension->manifest_version() : 1;
1424 bool is_component_extension =
1425 extension && Manifest::IsComponentLocation(extension->location());
1426 bool send_request_disabled =
1427 (extension && Manifest::IsUnpackedLocation(extension->location()) &&
1428 BackgroundInfo::HasLazyBackgroundPage(extension));
1429 module_system->RegisterNativeHandler(
1430 "process",
1431 scoped_ptr<NativeHandler>(new ProcessInfoNativeHandler(
1432 context,
1433 context->GetExtensionID(),
1434 context->GetContextTypeDescription(),
1435 ExtensionsRendererClient::Get()->IsIncognitoProcess(),
1436 is_component_extension,
1437 manifest_version,
1438 send_request_disabled)));
1440 delegate_->RegisterNativeHandlers(this, module_system, context);
1443 bool Dispatcher::IsRuntimeAvailableToContext(ScriptContext* context) {
1444 for (const auto& extension :
1445 *RendererExtensionRegistry::Get()->GetMainThreadExtensionSet()) {
1446 ExternallyConnectableInfo* info = static_cast<ExternallyConnectableInfo*>(
1447 extension->GetManifestData(manifest_keys::kExternallyConnectable));
1448 if (info && info->matches.MatchesURL(context->url()))
1449 return true;
1451 return false;
1454 void Dispatcher::UpdateContentCapabilities(ScriptContext* context) {
1455 APIPermissionSet permissions;
1456 for (const auto& extension :
1457 *RendererExtensionRegistry::Get()->GetMainThreadExtensionSet()) {
1458 const ContentCapabilitiesInfo& info =
1459 ContentCapabilitiesInfo::Get(extension.get());
1460 if (info.url_patterns.MatchesURL(context->url())) {
1461 APIPermissionSet new_permissions;
1462 APIPermissionSet::Union(permissions, info.permissions, &new_permissions);
1463 permissions = new_permissions;
1466 context->set_content_capabilities(permissions);
1469 void Dispatcher::PopulateSourceMap() {
1470 const std::vector<std::pair<std::string, int> > resources = GetJsResources();
1471 for (std::vector<std::pair<std::string, int> >::const_iterator resource =
1472 resources.begin();
1473 resource != resources.end();
1474 ++resource) {
1475 source_map_.RegisterSource(resource->first, resource->second);
1477 delegate_->PopulateSourceMap(&source_map_);
1480 bool Dispatcher::IsWithinPlatformApp() {
1481 for (std::set<std::string>::iterator iter = active_extension_ids_.begin();
1482 iter != active_extension_ids_.end();
1483 ++iter) {
1484 const Extension* extension =
1485 RendererExtensionRegistry::Get()->GetByID(*iter);
1486 if (extension && extension->is_platform_app())
1487 return true;
1489 return false;
1492 v8::Local<v8::Object> Dispatcher::GetOrCreateObject(
1493 const v8::Local<v8::Object>& object,
1494 const std::string& field,
1495 v8::Isolate* isolate) {
1496 v8::Local<v8::String> key = v8::String::NewFromUtf8(isolate, field.c_str());
1497 // If the object has a callback property, it is assumed it is an unavailable
1498 // API, so it is safe to delete. This is checked before GetOrCreateObject is
1499 // called.
1500 if (object->HasRealNamedCallbackProperty(key)) {
1501 object->Delete(key);
1502 } else if (object->HasRealNamedProperty(key)) {
1503 v8::Local<v8::Value> value = object->Get(key);
1504 CHECK(value->IsObject());
1505 return v8::Local<v8::Object>::Cast(value);
1508 v8::Local<v8::Object> new_object = v8::Object::New(isolate);
1509 object->Set(key, new_object);
1510 return new_object;
1513 v8::Local<v8::Object> Dispatcher::GetOrCreateBindObjectIfAvailable(
1514 const std::string& api_name,
1515 std::string* bind_name,
1516 ScriptContext* context) {
1517 std::vector<std::string> split = base::SplitString(
1518 api_name, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
1520 v8::Local<v8::Object> bind_object;
1522 // Check if this API has an ancestor. If the API's ancestor is available and
1523 // the API is not available, don't install the bindings for this API. If
1524 // the API is available and its ancestor is not, delete the ancestor and
1525 // install the bindings for the API. This is to prevent loading the ancestor
1526 // API schema if it will not be needed.
1528 // For example:
1529 // If app is available and app.window is not, just install app.
1530 // If app.window is available and app is not, delete app and install
1531 // app.window on a new object so app does not have to be loaded.
1532 const FeatureProvider* api_feature_provider =
1533 FeatureProvider::GetAPIFeatures();
1534 std::string ancestor_name;
1535 bool only_ancestor_available = false;
1537 for (size_t i = 0; i < split.size() - 1; ++i) {
1538 ancestor_name += (i ? "." : "") + split[i];
1539 if (api_feature_provider->GetFeature(ancestor_name) &&
1540 context->GetAvailability(ancestor_name).is_available() &&
1541 !context->GetAvailability(api_name).is_available()) {
1542 only_ancestor_available = true;
1543 break;
1546 if (bind_object.IsEmpty()) {
1547 bind_object = AsObjectOrEmpty(GetOrCreateChrome(context));
1548 if (bind_object.IsEmpty())
1549 return v8::Local<v8::Object>();
1551 bind_object = GetOrCreateObject(bind_object, split[i], context->isolate());
1554 if (only_ancestor_available)
1555 return v8::Local<v8::Object>();
1557 if (bind_name)
1558 *bind_name = split.back();
1560 return bind_object.IsEmpty() ? AsObjectOrEmpty(GetOrCreateChrome(context))
1561 : bind_object;
1564 void Dispatcher::RequireGuestViewModules(ScriptContext* context) {
1565 Feature::Context context_type = context->context_type();
1566 ModuleSystem* module_system = context->module_system();
1568 // Require AppView.
1569 if (context->GetAvailability("appViewEmbedderInternal").is_available()) {
1570 module_system->Require("appView");
1573 // Require ExtensionOptions.
1574 if (context->GetAvailability("extensionOptionsInternal").is_available()) {
1575 module_system->Require("extensionOptions");
1576 module_system->Require("extensionOptionsAttributes");
1579 // Require ExtensionView.
1580 if (context->GetAvailability("extensionViewInternal").is_available()) {
1581 module_system->Require("extensionView");
1582 module_system->Require("extensionViewApiMethods");
1583 module_system->Require("extensionViewAttributes");
1586 // Require WebView.
1587 if (context->GetAvailability("webViewInternal").is_available()) {
1588 module_system->Require("webView");
1589 module_system->Require("webViewApiMethods");
1590 module_system->Require("webViewAttributes");
1592 if (content::BrowserPluginGuestMode::UseCrossProcessFramesForGuests()) {
1593 module_system->Require("webViewIframe");
1597 // The "guestViewDeny" module must always be loaded last. It registers
1598 // error-providing custom elements for the GuestView types that are not
1599 // available, and thus all of those types must have been checked and loaded
1600 // (or not loaded) beforehand.
1601 if (context_type == Feature::BLESSED_EXTENSION_CONTEXT) {
1602 module_system->Require("guestViewDeny");
1606 void Dispatcher::AddChannelSpecificFeatures() {
1607 // chrome-extension: resources should be allowed to register a Service Worker.
1608 if (FeatureProvider::GetBehaviorFeature(BehaviorFeature::kServiceWorker)
1609 ->IsAvailableToEnvironment()
1610 .is_available())
1611 WebSecurityPolicy::registerURLSchemeAsAllowingServiceWorkers(
1612 WebString::fromUTF8(kExtensionScheme));
1615 } // namespace extensions