Roll WebRTC 9217:9227, Libjingle 9216:9227
[chromium-blink-merge.git] / extensions / renderer / dispatcher.cc
blobf210e27e2b0f290c16be549822ba72fb78076561
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/debug/alias.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/metrics/histogram_macros.h"
13 #include "base/metrics/user_metrics_action.h"
14 #include "base/strings/string_piece.h"
15 #include "base/strings/string_split.h"
16 #include "base/strings/string_util.h"
17 #include "base/time/time.h"
18 #include "base/values.h"
19 #include "content/grit/content_resources.h"
20 #include "content/public/child/v8_value_converter.h"
21 #include "content/public/common/content_switches.h"
22 #include "content/public/common/url_constants.h"
23 #include "content/public/renderer/render_thread.h"
24 #include "content/public/renderer/render_view.h"
25 #include "extensions/common/api/messaging/message.h"
26 #include "extensions/common/constants.h"
27 #include "extensions/common/extension_api.h"
28 #include "extensions/common/extension_messages.h"
29 #include "extensions/common/extension_urls.h"
30 #include "extensions/common/feature_switch.h"
31 #include "extensions/common/features/feature.h"
32 #include "extensions/common/features/feature_provider.h"
33 #include "extensions/common/manifest.h"
34 #include "extensions/common/manifest_constants.h"
35 #include "extensions/common/manifest_handlers/background_info.h"
36 #include "extensions/common/manifest_handlers/content_capabilities_handler.h"
37 #include "extensions/common/manifest_handlers/externally_connectable.h"
38 #include "extensions/common/manifest_handlers/options_page_info.h"
39 #include "extensions/common/message_bundle.h"
40 #include "extensions/common/permissions/permission_set.h"
41 #include "extensions/common/permissions/permissions_data.h"
42 #include "extensions/common/switches.h"
43 #include "extensions/common/view_type.h"
44 #include "extensions/renderer/api_activity_logger.h"
45 #include "extensions/renderer/api_definitions_natives.h"
46 #include "extensions/renderer/app_runtime_custom_bindings.h"
47 #include "extensions/renderer/app_window_custom_bindings.h"
48 #include "extensions/renderer/binding_generating_native_handler.h"
49 #include "extensions/renderer/blob_native_handler.h"
50 #include "extensions/renderer/content_watcher.h"
51 #include "extensions/renderer/context_menus_custom_bindings.h"
52 #include "extensions/renderer/css_native_handler.h"
53 #include "extensions/renderer/dispatcher_delegate.h"
54 #include "extensions/renderer/document_custom_bindings.h"
55 #include "extensions/renderer/dom_activity_logger.h"
56 #include "extensions/renderer/event_bindings.h"
57 #include "extensions/renderer/extension_helper.h"
58 #include "extensions/renderer/extensions_renderer_client.h"
59 #include "extensions/renderer/file_system_natives.h"
60 #include "extensions/renderer/guest_view/guest_view_internal_custom_bindings.h"
61 #include "extensions/renderer/i18n_custom_bindings.h"
62 #include "extensions/renderer/id_generator_custom_bindings.h"
63 #include "extensions/renderer/lazy_background_page_native_handler.h"
64 #include "extensions/renderer/logging_native_handler.h"
65 #include "extensions/renderer/messaging_bindings.h"
66 #include "extensions/renderer/module_system.h"
67 #include "extensions/renderer/print_native_handler.h"
68 #include "extensions/renderer/process_info_native_handler.h"
69 #include "extensions/renderer/render_view_observer_natives.h"
70 #include "extensions/renderer/request_sender.h"
71 #include "extensions/renderer/runtime_custom_bindings.h"
72 #include "extensions/renderer/safe_builtins.h"
73 #include "extensions/renderer/script_context.h"
74 #include "extensions/renderer/script_context_set.h"
75 #include "extensions/renderer/script_injection.h"
76 #include "extensions/renderer/script_injection_manager.h"
77 #include "extensions/renderer/send_request_natives.h"
78 #include "extensions/renderer/set_icon_natives.h"
79 #include "extensions/renderer/tab_finder.h"
80 #include "extensions/renderer/test_features_native_handler.h"
81 #include "extensions/renderer/user_gestures_native_handler.h"
82 #include "extensions/renderer/utils_native_handler.h"
83 #include "extensions/renderer/v8_context_native_handler.h"
84 #include "grit/extensions_renderer_resources.h"
85 #include "third_party/WebKit/public/platform/WebString.h"
86 #include "third_party/WebKit/public/platform/WebURLRequest.h"
87 #include "third_party/WebKit/public/web/WebCustomElement.h"
88 #include "third_party/WebKit/public/web/WebDataSource.h"
89 #include "third_party/WebKit/public/web/WebDocument.h"
90 #include "third_party/WebKit/public/web/WebFrame.h"
91 #include "third_party/WebKit/public/web/WebLocalFrame.h"
92 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
93 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
94 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
95 #include "third_party/WebKit/public/web/WebView.h"
96 #include "third_party/mojo/src/mojo/public/js/constants.h"
97 #include "ui/base/layout.h"
98 #include "ui/base/resource/resource_bundle.h"
99 #include "v8/include/v8.h"
101 using base::UserMetricsAction;
102 using blink::WebDataSource;
103 using blink::WebDocument;
104 using blink::WebScopedUserGesture;
105 using blink::WebSecurityPolicy;
106 using blink::WebString;
107 using blink::WebVector;
108 using blink::WebView;
109 using content::RenderThread;
110 using content::RenderView;
112 namespace extensions {
114 namespace {
116 static const int64 kInitialExtensionIdleHandlerDelayMs = 5 * 1000;
117 static const int64 kMaxExtensionIdleHandlerDelayMs = 5 * 60 * 1000;
118 static const char kEventDispatchFunction[] = "dispatchEvent";
119 static const char kOnSuspendEvent[] = "runtime.onSuspend";
120 static const char kOnSuspendCanceledEvent[] = "runtime.onSuspendCanceled";
122 // Returns the global value for "chrome" from |context|. If one doesn't exist
123 // creates a new object for it.
125 // Note that this isn't necessarily an object, since webpages can write, for
126 // example, "window.chrome = true".
127 v8::Local<v8::Value> GetOrCreateChrome(ScriptContext* context) {
128 v8::Local<v8::String> chrome_string(
129 v8::String::NewFromUtf8(context->isolate(), "chrome"));
130 v8::Local<v8::Object> global(context->v8_context()->Global());
131 v8::Local<v8::Value> chrome(global->Get(chrome_string));
132 if (chrome->IsUndefined()) {
133 chrome = v8::Object::New(context->isolate());
134 global->Set(chrome_string, chrome);
136 return chrome;
139 // Returns |value| cast to an object if possible, else an empty handle.
140 v8::Local<v8::Object> AsObjectOrEmpty(v8::Local<v8::Value> value) {
141 return value->IsObject() ? value.As<v8::Object>() : v8::Local<v8::Object>();
144 // Calls a method |method_name| in a module |module_name| belonging to the
145 // module system from |context|. Intended as a callback target from
146 // ScriptContextSet::ForEach.
147 void CallModuleMethod(const std::string& module_name,
148 const std::string& method_name,
149 const base::ListValue* args,
150 ScriptContext* context) {
151 v8::HandleScope handle_scope(context->isolate());
152 v8::Context::Scope context_scope(context->v8_context());
154 scoped_ptr<content::V8ValueConverter> converter(
155 content::V8ValueConverter::create());
157 std::vector<v8::Local<v8::Value>> arguments;
158 for (base::ListValue::const_iterator it = args->begin(); it != args->end();
159 ++it) {
160 arguments.push_back(converter->ToV8Value(*it, context->v8_context()));
163 context->module_system()->CallModuleMethod(
164 module_name, method_name, &arguments);
167 // This handles the "chrome." root API object in script contexts.
168 class ChromeNativeHandler : public ObjectBackedNativeHandler {
169 public:
170 explicit ChromeNativeHandler(ScriptContext* context)
171 : ObjectBackedNativeHandler(context) {
172 RouteFunction(
173 "GetChrome",
174 base::Bind(&ChromeNativeHandler::GetChrome, base::Unretained(this)));
177 void GetChrome(const v8::FunctionCallbackInfo<v8::Value>& args) {
178 args.GetReturnValue().Set(GetOrCreateChrome(context()));
182 } // namespace
184 Dispatcher::Dispatcher(DispatcherDelegate* delegate)
185 : delegate_(delegate),
186 content_watcher_(new ContentWatcher()),
187 source_map_(&ResourceBundle::GetSharedInstance()),
188 v8_schema_registry_(new V8SchemaRegistry),
189 is_webkit_initialized_(false),
190 user_script_set_manager_observer_(this),
191 webrequest_used_(false) {
192 const base::CommandLine& command_line =
193 *(base::CommandLine::ForCurrentProcess());
194 set_idle_notifications_ =
195 command_line.HasSwitch(switches::kExtensionProcess) ||
196 command_line.HasSwitch(::switches::kSingleProcess);
198 if (set_idle_notifications_) {
199 RenderThread::Get()->SetIdleNotificationDelayInMs(
200 kInitialExtensionIdleHandlerDelayMs);
203 RenderThread::Get()->RegisterExtension(SafeBuiltins::CreateV8Extension());
205 script_context_set_.reset(
206 new ScriptContextSet(&extensions_, &active_extension_ids_));
207 user_script_set_manager_.reset(new UserScriptSetManager(&extensions_));
208 script_injection_manager_.reset(
209 new ScriptInjectionManager(&extensions_, user_script_set_manager_.get()));
210 user_script_set_manager_observer_.Add(user_script_set_manager_.get());
211 request_sender_.reset(new RequestSender(this));
212 PopulateSourceMap();
215 Dispatcher::~Dispatcher() {
218 void Dispatcher::OnRenderViewCreated(content::RenderView* render_view) {
219 script_injection_manager_->OnRenderViewCreated(render_view);
222 bool Dispatcher::IsExtensionActive(const std::string& extension_id) const {
223 bool is_active =
224 active_extension_ids_.find(extension_id) != active_extension_ids_.end();
225 if (is_active)
226 CHECK(extensions_.Contains(extension_id));
227 return is_active;
230 void Dispatcher::DidCreateScriptContext(
231 blink::WebLocalFrame* frame,
232 const v8::Local<v8::Context>& v8_context,
233 int extension_group,
234 int world_id) {
235 const base::TimeTicks start_time = base::TimeTicks::Now();
237 ScriptContext* context = script_context_set_->Register(
238 frame, v8_context, extension_group, world_id);
240 // Initialize origin permissions for content scripts, which can't be
241 // initialized in |OnActivateExtension|.
242 if (context->context_type() == Feature::CONTENT_SCRIPT_CONTEXT)
243 InitOriginPermissions(context->extension());
246 scoped_ptr<ModuleSystem> module_system(
247 new ModuleSystem(context, &source_map_));
248 context->set_module_system(module_system.Pass());
250 ModuleSystem* module_system = context->module_system();
252 // Enable natives in startup.
253 ModuleSystem::NativesEnabledScope natives_enabled_scope(module_system);
255 RegisterNativeHandlers(module_system, context);
257 // chrome.Event is part of the public API (although undocumented). Make it
258 // lazily evalulate to Event from event_bindings.js. For extensions only
259 // though, not all webpages!
260 if (context->extension()) {
261 v8::Local<v8::Object> chrome = AsObjectOrEmpty(GetOrCreateChrome(context));
262 if (!chrome.IsEmpty())
263 module_system->SetLazyField(chrome, "Event", kEventBindings, "Event");
266 UpdateBindingsForContext(context);
268 bool is_within_platform_app = IsWithinPlatformApp();
269 // Inject custom JS into the platform app context.
270 if (is_within_platform_app) {
271 module_system->Require("platformApp");
274 RequireGuestViewModules(context);
275 delegate_->RequireAdditionalModules(context, is_within_platform_app);
277 const base::TimeDelta elapsed = base::TimeTicks::Now() - start_time;
278 switch (context->context_type()) {
279 case Feature::UNSPECIFIED_CONTEXT:
280 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Unspecified",
281 elapsed);
282 break;
283 case Feature::BLESSED_EXTENSION_CONTEXT:
284 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Blessed", elapsed);
285 break;
286 case Feature::UNBLESSED_EXTENSION_CONTEXT:
287 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Unblessed",
288 elapsed);
289 break;
290 case Feature::CONTENT_SCRIPT_CONTEXT:
291 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_ContentScript",
292 elapsed);
293 break;
294 case Feature::WEB_PAGE_CONTEXT:
295 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_WebPage", elapsed);
296 break;
297 case Feature::BLESSED_WEB_PAGE_CONTEXT:
298 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_BlessedWebPage",
299 elapsed);
300 break;
301 case Feature::WEBUI_CONTEXT:
302 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_WebUI", elapsed);
303 break;
306 VLOG(1) << "Num tracked contexts: " << script_context_set_->size();
309 void Dispatcher::WillReleaseScriptContext(
310 blink::WebLocalFrame* frame,
311 const v8::Local<v8::Context>& v8_context,
312 int world_id) {
313 ScriptContext* context = script_context_set_->GetByV8Context(v8_context);
314 if (!context)
315 return;
317 context->DispatchOnUnloadEvent();
318 // TODO(kalman): Make |request_sender| use |context->AddInvalidationObserver|.
319 // In fact |request_sender_| should really be owned by ScriptContext.
320 request_sender_->InvalidateSource(context);
322 script_context_set_->Remove(context);
323 VLOG(1) << "Num tracked contexts: " << script_context_set_->size();
326 void Dispatcher::DidCreateDocumentElement(blink::WebFrame* frame) {
327 // Note: use GetEffectiveDocumentURL not just frame->document()->url()
328 // so that this also injects the stylesheet on about:blank frames that
329 // are hosted in the extension process.
330 GURL effective_document_url = ScriptContext::GetEffectiveDocumentURL(
331 frame, frame->document().url(), true /* match_about_blank */);
333 const Extension* extension =
334 extensions_.GetExtensionOrAppByURL(effective_document_url);
336 if (extension &&
337 (extension->is_extension() || extension->is_platform_app())) {
338 int resource_id = extension->is_platform_app() ? IDR_PLATFORM_APP_CSS
339 : IDR_EXTENSION_FONTS_CSS;
340 std::string stylesheet = ResourceBundle::GetSharedInstance()
341 .GetRawDataResource(resource_id)
342 .as_string();
343 ReplaceFirstSubstringAfterOffset(
344 &stylesheet, 0, "$FONTFAMILY", system_font_family_);
345 ReplaceFirstSubstringAfterOffset(
346 &stylesheet, 0, "$FONTSIZE", system_font_size_);
348 // Blink doesn't let us define an additional user agent stylesheet, so
349 // we insert the default platform app or extension stylesheet into all
350 // documents that are loaded in each app or extension.
351 frame->document().insertStyleSheet(WebString::fromUTF8(stylesheet));
354 // If this is an extension options page, and the extension has opted into
355 // using Chrome styles, then insert the Chrome extension stylesheet.
356 if (extension && extension->is_extension() &&
357 OptionsPageInfo::ShouldUseChromeStyle(extension) &&
358 effective_document_url == OptionsPageInfo::GetOptionsPage(extension)) {
359 frame->document().insertStyleSheet(
360 WebString::fromUTF8(ResourceBundle::GetSharedInstance()
361 .GetRawDataResource(IDR_EXTENSION_CSS)
362 .as_string()));
365 content_watcher_->DidCreateDocumentElement(frame);
368 void Dispatcher::DidMatchCSS(
369 blink::WebFrame* frame,
370 const blink::WebVector<blink::WebString>& newly_matching_selectors,
371 const blink::WebVector<blink::WebString>& stopped_matching_selectors) {
372 content_watcher_->DidMatchCSS(
373 frame, newly_matching_selectors, stopped_matching_selectors);
376 void Dispatcher::OnExtensionResponse(int request_id,
377 bool success,
378 const base::ListValue& response,
379 const std::string& error) {
380 request_sender_->HandleResponse(request_id, success, response, error);
383 void Dispatcher::DispatchEvent(const std::string& extension_id,
384 const std::string& event_name) const {
385 base::ListValue args;
386 args.Set(0, new base::StringValue(event_name));
387 args.Set(1, new base::ListValue());
389 // Needed for Windows compilation, since kEventBindings is declared extern.
390 const char* local_event_bindings = kEventBindings;
391 script_context_set_->ForEach(
392 extension_id, base::Bind(&CallModuleMethod, local_event_bindings,
393 kEventDispatchFunction, &args));
396 void Dispatcher::InvokeModuleSystemMethod(content::RenderView* render_view,
397 const std::string& extension_id,
398 const std::string& module_name,
399 const std::string& function_name,
400 const base::ListValue& args,
401 bool user_gesture) {
402 scoped_ptr<WebScopedUserGesture> web_user_gesture;
403 if (user_gesture)
404 web_user_gesture.reset(new WebScopedUserGesture);
406 script_context_set_->ForEach(
407 extension_id, render_view,
408 base::Bind(&CallModuleMethod, module_name, function_name, &args));
410 // Reset the idle handler each time there's any activity like event or message
411 // dispatch, for which Invoke is the chokepoint.
412 if (set_idle_notifications_) {
413 RenderThread::Get()->ScheduleIdleHandler(
414 kInitialExtensionIdleHandlerDelayMs);
417 // Tell the browser process when an event has been dispatched with a lazy
418 // background page active.
419 const Extension* extension = extensions_.GetByID(extension_id);
420 if (extension && BackgroundInfo::HasLazyBackgroundPage(extension) &&
421 module_name == kEventBindings &&
422 function_name == kEventDispatchFunction) {
423 RenderView* background_view =
424 ExtensionHelper::GetBackgroundPage(extension_id);
425 if (background_view) {
426 int message_id;
427 args.GetInteger(3, &message_id);
428 background_view->Send(new ExtensionHostMsg_EventAck(
429 background_view->GetRoutingID(), message_id));
434 void Dispatcher::ClearPortData(int port_id) {
435 // Only the target port side has entries in |port_to_tab_id_map_|. If
436 // |port_id| is a source port, std::map::erase() will just silently fail
437 // here as a no-op.
438 port_to_tab_id_map_.erase(port_id);
441 // static
442 std::vector<std::pair<std::string, int> > Dispatcher::GetJsResources() {
443 std::vector<std::pair<std::string, int> > resources;
445 // Libraries.
446 resources.push_back(std::make_pair("appView", IDR_APP_VIEW_JS));
447 resources.push_back(std::make_pair("entryIdManager", IDR_ENTRY_ID_MANAGER));
448 resources.push_back(std::make_pair(kEventBindings, IDR_EVENT_BINDINGS_JS));
449 resources.push_back(std::make_pair("extensionOptions",
450 IDR_EXTENSION_OPTIONS_JS));
451 resources.push_back(std::make_pair("extensionOptionsAttributes",
452 IDR_EXTENSION_OPTIONS_ATTRIBUTES_JS));
453 resources.push_back(std::make_pair("extensionOptionsConstants",
454 IDR_EXTENSION_OPTIONS_CONSTANTS_JS));
455 resources.push_back(std::make_pair("extensionOptionsEvents",
456 IDR_EXTENSION_OPTIONS_EVENTS_JS));
457 resources.push_back(std::make_pair("extensionView", IDR_EXTENSION_VIEW_JS));
458 resources.push_back(std::make_pair("extensionViewApiMethods",
459 IDR_EXTENSION_VIEW_API_METHODS_JS));
460 resources.push_back(std::make_pair("extensionViewAttributes",
461 IDR_EXTENSION_VIEW_ATTRIBUTES_JS));
462 resources.push_back(std::make_pair("extensionViewConstants",
463 IDR_EXTENSION_VIEW_CONSTANTS_JS));
464 resources.push_back(std::make_pair("extensionViewEvents",
465 IDR_EXTENSION_VIEW_EVENTS_JS));
466 resources.push_back(std::make_pair(
467 "extensionViewInternal", IDR_EXTENSION_VIEW_INTERNAL_CUSTOM_BINDINGS_JS));
468 resources.push_back(std::make_pair("guestView", IDR_GUEST_VIEW_JS));
469 resources.push_back(std::make_pair("guestViewAttributes",
470 IDR_GUEST_VIEW_ATTRIBUTES_JS));
471 resources.push_back(std::make_pair("guestViewContainer",
472 IDR_GUEST_VIEW_CONTAINER_JS));
473 resources.push_back(std::make_pair("guestViewDeny", IDR_GUEST_VIEW_DENY_JS));
474 resources.push_back(std::make_pair("guestViewEvents",
475 IDR_GUEST_VIEW_EVENTS_JS));
476 resources.push_back(std::make_pair("imageUtil", IDR_IMAGE_UTIL_JS));
477 resources.push_back(std::make_pair("json_schema", IDR_JSON_SCHEMA_JS));
478 resources.push_back(std::make_pair("lastError", IDR_LAST_ERROR_JS));
479 resources.push_back(std::make_pair("messaging", IDR_MESSAGING_JS));
480 resources.push_back(std::make_pair("messaging_utils",
481 IDR_MESSAGING_UTILS_JS));
482 resources.push_back(std::make_pair(kSchemaUtils, IDR_SCHEMA_UTILS_JS));
483 resources.push_back(std::make_pair("sendRequest", IDR_SEND_REQUEST_JS));
484 resources.push_back(std::make_pair("setIcon", IDR_SET_ICON_JS));
485 resources.push_back(std::make_pair("surfaceWorker", IDR_SURFACE_VIEW_JS));
486 resources.push_back(std::make_pair("test", IDR_TEST_CUSTOM_BINDINGS_JS));
487 resources.push_back(
488 std::make_pair("test_environment_specific_bindings",
489 IDR_BROWSER_TEST_ENVIRONMENT_SPECIFIC_BINDINGS_JS));
490 resources.push_back(std::make_pair("uncaught_exception_handler",
491 IDR_UNCAUGHT_EXCEPTION_HANDLER_JS));
492 resources.push_back(std::make_pair("unload_event", IDR_UNLOAD_EVENT_JS));
493 resources.push_back(std::make_pair("utils", IDR_UTILS_JS));
494 resources.push_back(std::make_pair("webRequest",
495 IDR_WEB_REQUEST_CUSTOM_BINDINGS_JS));
496 resources.push_back(
497 std::make_pair("webRequestInternal",
498 IDR_WEB_REQUEST_INTERNAL_CUSTOM_BINDINGS_JS));
499 // Note: webView not webview so that this doesn't interfere with the
500 // chrome.webview API bindings.
501 resources.push_back(std::make_pair("webView", IDR_WEB_VIEW_JS));
502 resources.push_back(std::make_pair("webViewActionRequests",
503 IDR_WEB_VIEW_ACTION_REQUESTS_JS));
504 resources.push_back(std::make_pair("webViewApiMethods",
505 IDR_WEB_VIEW_API_METHODS_JS));
506 resources.push_back(std::make_pair("webViewAttributes",
507 IDR_WEB_VIEW_ATTRIBUTES_JS));
508 resources.push_back(std::make_pair("webViewConstants",
509 IDR_WEB_VIEW_CONSTANTS_JS));
510 resources.push_back(std::make_pair("webViewEvents", IDR_WEB_VIEW_EVENTS_JS));
511 resources.push_back(std::make_pair("webViewInternal",
512 IDR_WEB_VIEW_INTERNAL_CUSTOM_BINDINGS_JS));
513 resources.push_back(
514 std::make_pair(mojo::kBindingsModuleName, IDR_MOJO_BINDINGS_JS));
515 resources.push_back(
516 std::make_pair(mojo::kBufferModuleName, IDR_MOJO_BUFFER_JS));
517 resources.push_back(
518 std::make_pair(mojo::kCodecModuleName, IDR_MOJO_CODEC_JS));
519 resources.push_back(
520 std::make_pair(mojo::kConnectionModuleName, IDR_MOJO_CONNECTION_JS));
521 resources.push_back(
522 std::make_pair(mojo::kConnectorModuleName, IDR_MOJO_CONNECTOR_JS));
523 resources.push_back(
524 std::make_pair(mojo::kRouterModuleName, IDR_MOJO_ROUTER_JS));
525 resources.push_back(
526 std::make_pair(mojo::kUnicodeModuleName, IDR_MOJO_UNICODE_JS));
527 resources.push_back(
528 std::make_pair(mojo::kValidatorModuleName, IDR_MOJO_VALIDATOR_JS));
529 resources.push_back(std::make_pair("async_waiter", IDR_ASYNC_WAITER_JS));
530 resources.push_back(std::make_pair("data_receiver", IDR_DATA_RECEIVER_JS));
531 resources.push_back(std::make_pair("data_sender", IDR_DATA_SENDER_JS));
532 resources.push_back(std::make_pair("keep_alive", IDR_KEEP_ALIVE_JS));
533 resources.push_back(std::make_pair("extensions/common/mojo/keep_alive.mojom",
534 IDR_KEEP_ALIVE_MOJOM_JS));
535 resources.push_back(std::make_pair("device/serial/data_stream.mojom",
536 IDR_DATA_STREAM_MOJOM_JS));
537 resources.push_back(
538 std::make_pair("device/serial/data_stream_serialization.mojom",
539 IDR_DATA_STREAM_SERIALIZATION_MOJOM_JS));
540 resources.push_back(std::make_pair("stash_client", IDR_STASH_CLIENT_JS));
541 resources.push_back(
542 std::make_pair("extensions/common/mojo/stash.mojom", IDR_STASH_MOJOM_JS));
544 // Custom bindings.
545 resources.push_back(
546 std::make_pair("app.runtime", IDR_APP_RUNTIME_CUSTOM_BINDINGS_JS));
547 resources.push_back(
548 std::make_pair("app.window", IDR_APP_WINDOW_CUSTOM_BINDINGS_JS));
549 resources.push_back(
550 std::make_pair("declarativeWebRequest",
551 IDR_DECLARATIVE_WEBREQUEST_CUSTOM_BINDINGS_JS));
552 resources.push_back(
553 std::make_pair("contextMenus", IDR_CONTEXT_MENUS_CUSTOM_BINDINGS_JS));
554 resources.push_back(
555 std::make_pair("contextMenusHandlers", IDR_CONTEXT_MENUS_HANDLERS_JS));
556 resources.push_back(
557 std::make_pair("extension", IDR_EXTENSION_CUSTOM_BINDINGS_JS));
558 resources.push_back(std::make_pair("i18n", IDR_I18N_CUSTOM_BINDINGS_JS));
559 resources.push_back(std::make_pair(
560 "mimeHandlerPrivate", IDR_MIME_HANDLER_PRIVATE_CUSTOM_BINDINGS_JS));
561 resources.push_back(std::make_pair("extensions/common/api/mime_handler.mojom",
562 IDR_MIME_HANDLER_MOJOM_JS));
563 resources.push_back(
564 std::make_pair("mojoPrivate", IDR_MOJO_PRIVATE_CUSTOM_BINDINGS_JS));
565 resources.push_back(
566 std::make_pair("permissions", IDR_PERMISSIONS_CUSTOM_BINDINGS_JS));
567 resources.push_back(std::make_pair("printerProvider",
568 IDR_PRINTER_PROVIDER_CUSTOM_BINDINGS_JS));
569 resources.push_back(
570 std::make_pair("runtime", IDR_RUNTIME_CUSTOM_BINDINGS_JS));
571 resources.push_back(std::make_pair("windowControls", IDR_WINDOW_CONTROLS_JS));
572 resources.push_back(
573 std::make_pair("webViewRequest",
574 IDR_WEB_VIEW_REQUEST_CUSTOM_BINDINGS_JS));
575 resources.push_back(std::make_pair("binding", IDR_BINDING_JS));
577 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
578 switches::kEnableMojoSerialService)) {
579 resources.push_back(
580 std::make_pair("serial", IDR_SERIAL_CUSTOM_BINDINGS_JS));
582 resources.push_back(std::make_pair("serial_service", IDR_SERIAL_SERVICE_JS));
583 resources.push_back(
584 std::make_pair("device/serial/serial.mojom", IDR_SERIAL_MOJOM_JS));
585 resources.push_back(std::make_pair("device/serial/serial_serialization.mojom",
586 IDR_SERIAL_SERIALIZATION_MOJOM_JS));
588 // Custom types sources.
589 resources.push_back(std::make_pair("StorageArea", IDR_STORAGE_AREA_JS));
591 // Platform app sources that are not API-specific..
592 resources.push_back(std::make_pair("platformApp", IDR_PLATFORM_APP_JS));
594 return resources;
597 // NOTE: please use the naming convention "foo_natives" for these.
598 // static
599 void Dispatcher::RegisterNativeHandlers(ModuleSystem* module_system,
600 ScriptContext* context,
601 Dispatcher* dispatcher,
602 RequestSender* request_sender,
603 V8SchemaRegistry* v8_schema_registry) {
604 module_system->RegisterNativeHandler(
605 "chrome", scoped_ptr<NativeHandler>(new ChromeNativeHandler(context)));
606 module_system->RegisterNativeHandler(
607 "lazy_background_page",
608 scoped_ptr<NativeHandler>(new LazyBackgroundPageNativeHandler(context)));
609 module_system->RegisterNativeHandler(
610 "logging", scoped_ptr<NativeHandler>(new LoggingNativeHandler(context)));
611 module_system->RegisterNativeHandler("schema_registry",
612 v8_schema_registry->AsNativeHandler());
613 module_system->RegisterNativeHandler(
614 "print", scoped_ptr<NativeHandler>(new PrintNativeHandler(context)));
615 module_system->RegisterNativeHandler(
616 "test_features",
617 scoped_ptr<NativeHandler>(new TestFeaturesNativeHandler(context)));
618 module_system->RegisterNativeHandler(
619 "user_gestures",
620 scoped_ptr<NativeHandler>(new UserGesturesNativeHandler(context)));
621 module_system->RegisterNativeHandler(
622 "utils", scoped_ptr<NativeHandler>(new UtilsNativeHandler(context)));
623 module_system->RegisterNativeHandler(
624 "v8_context",
625 scoped_ptr<NativeHandler>(
626 new V8ContextNativeHandler(context, dispatcher)));
627 module_system->RegisterNativeHandler(
628 "event_natives", scoped_ptr<NativeHandler>(new EventBindings(context)));
629 module_system->RegisterNativeHandler(
630 "messaging_natives",
631 scoped_ptr<NativeHandler>(MessagingBindings::Get(dispatcher, context)));
632 module_system->RegisterNativeHandler(
633 "apiDefinitions",
634 scoped_ptr<NativeHandler>(
635 new ApiDefinitionsNatives(dispatcher, context)));
636 module_system->RegisterNativeHandler(
637 "sendRequest",
638 scoped_ptr<NativeHandler>(
639 new SendRequestNatives(request_sender, context)));
640 module_system->RegisterNativeHandler(
641 "setIcon",
642 scoped_ptr<NativeHandler>(new SetIconNatives(context)));
643 module_system->RegisterNativeHandler(
644 "activityLogger",
645 scoped_ptr<NativeHandler>(new APIActivityLogger(context)));
646 module_system->RegisterNativeHandler(
647 "renderViewObserverNatives",
648 scoped_ptr<NativeHandler>(new RenderViewObserverNatives(context)));
650 // Natives used by multiple APIs.
651 module_system->RegisterNativeHandler(
652 "file_system_natives",
653 scoped_ptr<NativeHandler>(new FileSystemNatives(context)));
655 // Custom bindings.
656 module_system->RegisterNativeHandler(
657 "app_runtime",
658 scoped_ptr<NativeHandler>(new AppRuntimeCustomBindings(context)));
659 module_system->RegisterNativeHandler(
660 "app_window_natives",
661 scoped_ptr<NativeHandler>(
662 new AppWindowCustomBindings(dispatcher, context)));
663 module_system->RegisterNativeHandler(
664 "blob_natives",
665 scoped_ptr<NativeHandler>(new BlobNativeHandler(context)));
666 module_system->RegisterNativeHandler(
667 "context_menus",
668 scoped_ptr<NativeHandler>(new ContextMenusCustomBindings(context)));
669 module_system->RegisterNativeHandler(
670 "css_natives", scoped_ptr<NativeHandler>(new CssNativeHandler(context)));
671 module_system->RegisterNativeHandler(
672 "document_natives",
673 scoped_ptr<NativeHandler>(new DocumentCustomBindings(context)));
674 module_system->RegisterNativeHandler(
675 "guest_view_internal",
676 scoped_ptr<NativeHandler>(
677 new GuestViewInternalCustomBindings(context)));
678 module_system->RegisterNativeHandler(
679 "i18n", scoped_ptr<NativeHandler>(new I18NCustomBindings(context)));
680 module_system->RegisterNativeHandler(
681 "id_generator",
682 scoped_ptr<NativeHandler>(new IdGeneratorCustomBindings(context)));
683 module_system->RegisterNativeHandler(
684 "runtime", scoped_ptr<NativeHandler>(new RuntimeCustomBindings(context)));
687 bool Dispatcher::OnControlMessageReceived(const IPC::Message& message) {
688 bool handled = true;
689 IPC_BEGIN_MESSAGE_MAP(Dispatcher, message)
690 IPC_MESSAGE_HANDLER(ExtensionMsg_ActivateExtension, OnActivateExtension)
691 IPC_MESSAGE_HANDLER(ExtensionMsg_CancelSuspend, OnCancelSuspend)
692 IPC_MESSAGE_HANDLER(ExtensionMsg_DeliverMessage, OnDeliverMessage)
693 IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnConnect, OnDispatchOnConnect)
694 IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnDisconnect, OnDispatchOnDisconnect)
695 IPC_MESSAGE_HANDLER(ExtensionMsg_Loaded, OnLoaded)
696 IPC_MESSAGE_HANDLER(ExtensionMsg_MessageInvoke, OnMessageInvoke)
697 IPC_MESSAGE_HANDLER(ExtensionMsg_SetChannel, OnSetChannel)
698 IPC_MESSAGE_HANDLER(ExtensionMsg_SetFunctionNames, OnSetFunctionNames)
699 IPC_MESSAGE_HANDLER(ExtensionMsg_SetScriptingWhitelist,
700 OnSetScriptingWhitelist)
701 IPC_MESSAGE_HANDLER(ExtensionMsg_SetSystemFont, OnSetSystemFont)
702 IPC_MESSAGE_HANDLER(ExtensionMsg_ShouldSuspend, OnShouldSuspend)
703 IPC_MESSAGE_HANDLER(ExtensionMsg_Suspend, OnSuspend)
704 IPC_MESSAGE_HANDLER(ExtensionMsg_TransferBlobs, OnTransferBlobs)
705 IPC_MESSAGE_HANDLER(ExtensionMsg_Unloaded, OnUnloaded)
706 IPC_MESSAGE_HANDLER(ExtensionMsg_UpdatePermissions, OnUpdatePermissions)
707 IPC_MESSAGE_HANDLER(ExtensionMsg_UpdateTabSpecificPermissions,
708 OnUpdateTabSpecificPermissions)
709 IPC_MESSAGE_HANDLER(ExtensionMsg_ClearTabSpecificPermissions,
710 OnClearTabSpecificPermissions)
711 IPC_MESSAGE_HANDLER(ExtensionMsg_UsingWebRequestAPI, OnUsingWebRequestAPI)
712 IPC_MESSAGE_FORWARD(ExtensionMsg_WatchPages,
713 content_watcher_.get(),
714 ContentWatcher::OnWatchPages)
715 IPC_MESSAGE_UNHANDLED(handled = false)
716 IPC_END_MESSAGE_MAP()
718 return handled;
721 void Dispatcher::WebKitInitialized() {
722 // For extensions, we want to ensure we call the IdleHandler every so often,
723 // even if the extension keeps up activity.
724 if (set_idle_notifications_) {
725 forced_idle_timer_.reset(new base::RepeatingTimer<content::RenderThread>);
726 forced_idle_timer_->Start(
727 FROM_HERE,
728 base::TimeDelta::FromMilliseconds(kMaxExtensionIdleHandlerDelayMs),
729 RenderThread::Get(),
730 &RenderThread::IdleHandler);
733 // Initialize host permissions for any extensions that were activated before
734 // WebKit was initialized.
735 for (std::set<std::string>::iterator iter = active_extension_ids_.begin();
736 iter != active_extension_ids_.end();
737 ++iter) {
738 const Extension* extension = extensions_.GetByID(*iter);
739 CHECK(extension);
741 InitOriginPermissions(extension);
744 EnableCustomElementWhiteList();
746 is_webkit_initialized_ = true;
749 void Dispatcher::IdleNotification() {
750 if (set_idle_notifications_ && forced_idle_timer_) {
751 // Dampen the forced delay as well if the extension stays idle for long
752 // periods of time. (forced_idle_timer_ can be NULL after
753 // OnRenderProcessShutdown has been called.)
754 int64 forced_delay_ms =
755 std::max(RenderThread::Get()->GetIdleNotificationDelayInMs(),
756 kMaxExtensionIdleHandlerDelayMs);
757 forced_idle_timer_->Stop();
758 forced_idle_timer_->Start(
759 FROM_HERE,
760 base::TimeDelta::FromMilliseconds(forced_delay_ms),
761 RenderThread::Get(),
762 &RenderThread::IdleHandler);
766 void Dispatcher::OnRenderProcessShutdown() {
767 v8_schema_registry_.reset();
768 forced_idle_timer_.reset();
771 void Dispatcher::OnActivateExtension(const std::string& extension_id) {
772 const Extension* extension = extensions_.GetByID(extension_id);
773 if (!extension) {
774 // Extension was activated but was never loaded. This probably means that
775 // the renderer failed to load it (or the browser failed to tell us when it
776 // did). Failures shouldn't happen, but instead of crashing there (which
777 // executes on all renderers) be conservative and only crash in the renderer
778 // of the extension which failed to load; this one.
779 std::string& error = extension_load_errors_[extension_id];
780 char minidump[256];
781 base::debug::Alias(&minidump);
782 base::snprintf(minidump,
783 arraysize(minidump),
784 "e::dispatcher:%s:%s",
785 extension_id.c_str(),
786 error.c_str());
787 CHECK(extension) << extension_id << " was never loaded: " << error;
790 active_extension_ids_.insert(extension_id);
792 // This is called when starting a new extension page, so start the idle
793 // handler ticking.
794 RenderThread::Get()->ScheduleIdleHandler(kInitialExtensionIdleHandlerDelayMs);
796 if (is_webkit_initialized_) {
797 DOMActivityLogger::AttachToWorld(
798 DOMActivityLogger::kMainWorldId, extension_id);
800 InitOriginPermissions(extension);
803 UpdateActiveExtensions();
806 void Dispatcher::OnCancelSuspend(const std::string& extension_id) {
807 DispatchEvent(extension_id, kOnSuspendCanceledEvent);
810 void Dispatcher::OnDeliverMessage(int target_port_id, const Message& message) {
811 scoped_ptr<RequestSender::ScopedTabID> scoped_tab_id;
812 std::map<int, int>::const_iterator it =
813 port_to_tab_id_map_.find(target_port_id);
814 if (it != port_to_tab_id_map_.end()) {
815 scoped_tab_id.reset(
816 new RequestSender::ScopedTabID(request_sender(), it->second));
819 MessagingBindings::DeliverMessage(*script_context_set_, target_port_id,
820 message,
821 NULL); // All render frames.
824 void Dispatcher::OnDispatchOnConnect(
825 int target_port_id,
826 const std::string& channel_name,
827 const ExtensionMsg_TabConnectionInfo& source,
828 const ExtensionMsg_ExternalConnectionInfo& info,
829 const std::string& tls_channel_id) {
830 DCHECK(!ContainsKey(port_to_tab_id_map_, target_port_id));
831 DCHECK_EQ(1, target_port_id % 2); // target renderer ports have odd IDs.
832 int sender_tab_id = -1;
833 source.tab.GetInteger("id", &sender_tab_id);
834 port_to_tab_id_map_[target_port_id] = sender_tab_id;
836 MessagingBindings::DispatchOnConnect(*script_context_set_, target_port_id,
837 channel_name, source, info,
838 tls_channel_id,
839 NULL); // All render frames.
842 void Dispatcher::OnDispatchOnDisconnect(int port_id,
843 const std::string& error_message) {
844 MessagingBindings::DispatchOnDisconnect(*script_context_set_, port_id,
845 error_message,
846 NULL); // All render frames.
849 void Dispatcher::OnLoaded(
850 const std::vector<ExtensionMsg_Loaded_Params>& loaded_extensions) {
851 std::vector<ExtensionMsg_Loaded_Params>::const_iterator i;
852 for (i = loaded_extensions.begin(); i != loaded_extensions.end(); ++i) {
853 std::string error;
854 scoped_refptr<const Extension> extension = i->ConvertToExtension(&error);
855 if (!extension.get()) {
856 extension_load_errors_[i->id] = error;
857 continue;
859 OnLoadedInternal(extension);
861 // Update the available bindings for all contexts. These may have changed if
862 // an externally_connectable extension was loaded that can connect to an
863 // open webpage.
864 UpdateBindings("");
867 void Dispatcher::OnLoadedInternal(scoped_refptr<const Extension> extension) {
868 extensions_.Insert(extension);
871 void Dispatcher::OnMessageInvoke(const std::string& extension_id,
872 const std::string& module_name,
873 const std::string& function_name,
874 const base::ListValue& args,
875 bool user_gesture) {
876 InvokeModuleSystemMethod(
877 NULL, extension_id, module_name, function_name, args, user_gesture);
880 void Dispatcher::OnSetChannel(int channel) {
881 delegate_->SetChannel(channel);
884 void Dispatcher::OnSetFunctionNames(const std::vector<std::string>& names) {
885 function_names_.clear();
886 for (size_t i = 0; i < names.size(); ++i)
887 function_names_.insert(names[i]);
890 void Dispatcher::OnSetScriptingWhitelist(
891 const ExtensionsClient::ScriptingWhitelist& extension_ids) {
892 ExtensionsClient::Get()->SetScriptingWhitelist(extension_ids);
895 void Dispatcher::OnSetSystemFont(const std::string& font_family,
896 const std::string& font_size) {
897 system_font_family_ = font_family;
898 system_font_size_ = font_size;
901 void Dispatcher::OnShouldSuspend(const std::string& extension_id,
902 uint64 sequence_id) {
903 RenderThread::Get()->Send(
904 new ExtensionHostMsg_ShouldSuspendAck(extension_id, sequence_id));
907 void Dispatcher::OnSuspend(const std::string& extension_id) {
908 // Dispatch the suspend event. This doesn't go through the standard event
909 // dispatch machinery because it requires special handling. We need to let
910 // the browser know when we are starting and stopping the event dispatch, so
911 // that it still considers the extension idle despite any activity the suspend
912 // event creates.
913 DispatchEvent(extension_id, kOnSuspendEvent);
914 RenderThread::Get()->Send(new ExtensionHostMsg_SuspendAck(extension_id));
917 void Dispatcher::OnTransferBlobs(const std::vector<std::string>& blob_uuids) {
918 RenderThread::Get()->Send(new ExtensionHostMsg_TransferBlobsAck(blob_uuids));
921 void Dispatcher::OnUnloaded(const std::string& id) {
922 extensions_.Remove(id);
923 active_extension_ids_.erase(id);
925 script_injection_manager_->OnExtensionUnloaded(id);
927 // If the extension is later reloaded with a different set of permissions,
928 // we'd like it to get a new isolated world ID, so that it can pick up the
929 // changed origin whitelist.
930 ScriptInjection::RemoveIsolatedWorld(id);
932 // Invalidate all of the contexts that were removed.
933 // TODO(kalman): add an invalidation observer interface to ScriptContext.
934 std::set<ScriptContext*> removed_contexts =
935 script_context_set_->OnExtensionUnloaded(id);
936 for (ScriptContext* context : removed_contexts) {
937 request_sender_->InvalidateSource(context);
940 // Update the available bindings for the remaining contexts. These may have
941 // changed if an externally_connectable extension is unloaded and a webpage
942 // is no longer accessible.
943 UpdateBindings("");
945 // Invalidates the messages map for the extension in case the extension is
946 // reloaded with a new messages map.
947 EraseL10nMessagesMap(id);
949 // We don't do anything with existing platform-app stylesheets. They will
950 // stay resident, but the URL pattern corresponding to the unloaded
951 // extension's URL just won't match anything anymore.
954 void Dispatcher::OnUpdatePermissions(
955 const ExtensionMsg_UpdatePermissions_Params& params) {
956 const Extension* extension = extensions_.GetByID(params.extension_id);
957 if (!extension)
958 return;
960 scoped_refptr<const PermissionSet> active =
961 params.active_permissions.ToPermissionSet();
962 scoped_refptr<const PermissionSet> withheld =
963 params.withheld_permissions.ToPermissionSet();
965 if (is_webkit_initialized_) {
966 UpdateOriginPermissions(
967 extension->url(),
968 extension->permissions_data()->GetEffectiveHostPermissions(),
969 active->effective_hosts());
972 extension->permissions_data()->SetPermissions(active, withheld);
973 UpdateBindings(extension->id());
976 void Dispatcher::OnUpdateTabSpecificPermissions(const GURL& visible_url,
977 const std::string& extension_id,
978 const URLPatternSet& new_hosts,
979 bool update_origin_whitelist,
980 int tab_id) {
981 // Check against the URL to avoid races. If we can't find the tab, it's
982 // because this is an extension's background page (run in a different
983 // process) - in this case, we can't perform the security check. However,
984 // since activeTab is only granted via user action, this isn't a huge concern.
985 content::RenderView* render_view = TabFinder::Find(tab_id);
986 if (render_view &&
987 render_view->GetWebView()->mainFrame()->document().url() != visible_url) {
988 return;
991 const Extension* extension = extensions_.GetByID(extension_id);
992 if (!extension)
993 return;
995 URLPatternSet old_effective =
996 extension->permissions_data()->GetEffectiveHostPermissions();
997 extension->permissions_data()->UpdateTabSpecificPermissions(
998 tab_id,
999 new extensions::PermissionSet(extensions::APIPermissionSet(),
1000 extensions::ManifestPermissionSet(),
1001 new_hosts,
1002 extensions::URLPatternSet()));
1004 if (is_webkit_initialized_ && update_origin_whitelist) {
1005 UpdateOriginPermissions(
1006 extension->url(),
1007 old_effective,
1008 extension->permissions_data()->GetEffectiveHostPermissions());
1012 void Dispatcher::OnClearTabSpecificPermissions(
1013 const std::vector<std::string>& extension_ids,
1014 bool update_origin_whitelist,
1015 int tab_id) {
1016 for (const std::string& id : extension_ids) {
1017 const Extension* extension = extensions_.GetByID(id);
1018 if (extension) {
1019 URLPatternSet old_effective =
1020 extension->permissions_data()->GetEffectiveHostPermissions();
1021 extension->permissions_data()->ClearTabSpecificPermissions(tab_id);
1022 if (is_webkit_initialized_ && update_origin_whitelist) {
1023 UpdateOriginPermissions(
1024 extension->url(),
1025 old_effective,
1026 extension->permissions_data()->GetEffectiveHostPermissions());
1032 void Dispatcher::OnUsingWebRequestAPI(bool webrequest_used) {
1033 webrequest_used_ = webrequest_used;
1036 void Dispatcher::OnUserScriptsUpdated(const std::set<HostID>& changed_hosts,
1037 const std::vector<UserScript*>& scripts) {
1038 UpdateActiveExtensions();
1041 void Dispatcher::UpdateActiveExtensions() {
1042 std::set<std::string> active_extensions = active_extension_ids_;
1043 user_script_set_manager_->GetAllActiveExtensionIds(&active_extensions);
1044 delegate_->OnActiveExtensionsUpdated(active_extensions);
1047 void Dispatcher::InitOriginPermissions(const Extension* extension) {
1048 delegate_->InitOriginPermissions(extension,
1049 IsExtensionActive(extension->id()));
1050 UpdateOriginPermissions(
1051 extension->url(),
1052 URLPatternSet(), // No old permissions.
1053 extension->permissions_data()->GetEffectiveHostPermissions());
1056 void Dispatcher::UpdateOriginPermissions(const GURL& extension_url,
1057 const URLPatternSet& old_patterns,
1058 const URLPatternSet& new_patterns) {
1059 static const char* kSchemes[] = {
1060 url::kHttpScheme,
1061 url::kHttpsScheme,
1062 url::kFileScheme,
1063 content::kChromeUIScheme,
1064 url::kFtpScheme,
1065 #if defined(OS_CHROMEOS)
1066 content::kExternalFileScheme,
1067 #endif
1068 extensions::kExtensionScheme,
1070 for (size_t i = 0; i < arraysize(kSchemes); ++i) {
1071 const char* scheme = kSchemes[i];
1072 // Remove all old patterns...
1073 for (URLPatternSet::const_iterator pattern = old_patterns.begin();
1074 pattern != old_patterns.end(); ++pattern) {
1075 if (pattern->MatchesScheme(scheme)) {
1076 WebSecurityPolicy::removeOriginAccessWhitelistEntry(
1077 extension_url,
1078 WebString::fromUTF8(scheme),
1079 WebString::fromUTF8(pattern->host()),
1080 pattern->match_subdomains());
1083 // ...And add the new ones.
1084 for (URLPatternSet::const_iterator pattern = new_patterns.begin();
1085 pattern != new_patterns.end(); ++pattern) {
1086 if (pattern->MatchesScheme(scheme)) {
1087 WebSecurityPolicy::addOriginAccessWhitelistEntry(
1088 extension_url,
1089 WebString::fromUTF8(scheme),
1090 WebString::fromUTF8(pattern->host()),
1091 pattern->match_subdomains());
1097 void Dispatcher::EnableCustomElementWhiteList() {
1098 blink::WebCustomElement::addEmbedderCustomElementName("appview");
1099 blink::WebCustomElement::addEmbedderCustomElementName("appviewbrowserplugin");
1100 blink::WebCustomElement::addEmbedderCustomElementName("extensionoptions");
1101 blink::WebCustomElement::addEmbedderCustomElementName(
1102 "extensionoptionsbrowserplugin");
1103 blink::WebCustomElement::addEmbedderCustomElementName("extensionview");
1104 blink::WebCustomElement::addEmbedderCustomElementName(
1105 "extensionviewbrowserplugin");
1106 blink::WebCustomElement::addEmbedderCustomElementName("webview");
1107 blink::WebCustomElement::addEmbedderCustomElementName("webviewbrowserplugin");
1108 blink::WebCustomElement::addEmbedderCustomElementName("surfaceview");
1109 blink::WebCustomElement::addEmbedderCustomElementName(
1110 "surfaceviewbrowserplugin");
1113 void Dispatcher::UpdateBindings(const std::string& extension_id) {
1114 script_context_set().ForEach(extension_id,
1115 base::Bind(&Dispatcher::UpdateBindingsForContext,
1116 base::Unretained(this)));
1119 void Dispatcher::UpdateBindingsForContext(ScriptContext* context) {
1120 v8::HandleScope handle_scope(context->isolate());
1121 v8::Context::Scope context_scope(context->v8_context());
1123 // TODO(kalman): Make the bindings registration have zero overhead then run
1124 // the same code regardless of context type.
1125 switch (context->context_type()) {
1126 case Feature::UNSPECIFIED_CONTEXT:
1127 case Feature::WEB_PAGE_CONTEXT:
1128 case Feature::BLESSED_WEB_PAGE_CONTEXT:
1129 // Web page context; it's too expensive to run the full bindings code.
1130 // Hard-code that the app and webstore APIs are available...
1131 if (context->GetAvailability("app").is_available())
1132 RegisterBinding("app", context);
1133 if (context->GetAvailability("webstore").is_available())
1134 RegisterBinding("webstore", context);
1135 if (IsRuntimeAvailableToContext(context))
1136 RegisterBinding("runtime", context);
1137 UpdateContentCapabilities(context);
1138 break;
1140 case Feature::BLESSED_EXTENSION_CONTEXT:
1141 case Feature::UNBLESSED_EXTENSION_CONTEXT:
1142 case Feature::CONTENT_SCRIPT_CONTEXT:
1143 case Feature::WEBUI_CONTEXT: {
1144 // Extension context; iterate through all the APIs and bind the available
1145 // ones.
1146 const FeatureProvider* api_feature_provider =
1147 FeatureProvider::GetAPIFeatures();
1148 const std::vector<std::string>& apis =
1149 api_feature_provider->GetAllFeatureNames();
1150 for (std::vector<std::string>::const_iterator it = apis.begin();
1151 it != apis.end();
1152 ++it) {
1153 const std::string& api_name = *it;
1154 Feature* feature = api_feature_provider->GetFeature(api_name);
1155 DCHECK(feature);
1157 // Internal APIs are included via require(api_name) from internal code
1158 // rather than chrome[api_name].
1159 if (feature->IsInternal())
1160 continue;
1162 // If this API has a parent feature (and isn't marked 'noparent'),
1163 // then this must be a function or event, so we should not register.
1164 if (api_feature_provider->GetParent(feature) != NULL)
1165 continue;
1167 // Skip chrome.test if this isn't a test.
1168 if (api_name == "test" &&
1169 !base::CommandLine::ForCurrentProcess()->HasSwitch(
1170 ::switches::kTestType)) {
1171 continue;
1174 if (context->IsAnyFeatureAvailableToContext(*feature))
1175 RegisterBinding(api_name, context);
1177 break;
1182 void Dispatcher::RegisterBinding(const std::string& api_name,
1183 ScriptContext* context) {
1184 std::string bind_name;
1185 v8::Local<v8::Object> bind_object =
1186 GetOrCreateBindObjectIfAvailable(api_name, &bind_name, context);
1188 // Empty if the bind object failed to be created, probably because the
1189 // extension overrode chrome with a non-object, e.g. window.chrome = true.
1190 if (bind_object.IsEmpty())
1191 return;
1193 v8::Local<v8::String> v8_bind_name =
1194 v8::String::NewFromUtf8(context->isolate(), bind_name.c_str());
1195 if (bind_object->HasRealNamedProperty(v8_bind_name)) {
1196 // The bind object may already have the property if the API has been
1197 // registered before (or if the extension has put something there already,
1198 // but, whatevs).
1200 // In the former case, we need to re-register the bindings for the APIs
1201 // which the extension now has permissions for (if any), but not touch any
1202 // others so that we don't destroy state such as event listeners.
1204 // TODO(kalman): Only register available APIs to make this all moot.
1205 if (bind_object->HasRealNamedCallbackProperty(v8_bind_name))
1206 return; // lazy binding still there, nothing to do
1207 if (bind_object->Get(v8_bind_name)->IsObject())
1208 return; // binding has already been fully installed
1211 ModuleSystem* module_system = context->module_system();
1212 if (!source_map_.Contains(api_name)) {
1213 module_system->RegisterNativeHandler(
1214 api_name,
1215 scoped_ptr<NativeHandler>(new BindingGeneratingNativeHandler(
1216 module_system, api_name, "binding")));
1217 module_system->SetNativeLazyField(
1218 bind_object, bind_name, api_name, "binding");
1219 } else {
1220 module_system->SetLazyField(bind_object, bind_name, api_name, "binding");
1224 // NOTE: please use the naming convention "foo_natives" for these.
1225 void Dispatcher::RegisterNativeHandlers(ModuleSystem* module_system,
1226 ScriptContext* context) {
1227 RegisterNativeHandlers(module_system,
1228 context,
1229 this,
1230 request_sender_.get(),
1231 v8_schema_registry_.get());
1232 const Extension* extension = context->extension();
1233 int manifest_version = extension ? extension->manifest_version() : 1;
1234 bool is_component_extension =
1235 extension && Manifest::IsComponentLocation(extension->location());
1236 bool send_request_disabled =
1237 (extension && Manifest::IsUnpackedLocation(extension->location()) &&
1238 BackgroundInfo::HasLazyBackgroundPage(extension));
1239 module_system->RegisterNativeHandler(
1240 "process",
1241 scoped_ptr<NativeHandler>(new ProcessInfoNativeHandler(
1242 context,
1243 context->GetExtensionID(),
1244 context->GetContextTypeDescription(),
1245 ExtensionsRendererClient::Get()->IsIncognitoProcess(),
1246 is_component_extension,
1247 manifest_version,
1248 send_request_disabled)));
1250 delegate_->RegisterNativeHandlers(this, module_system, context);
1253 bool Dispatcher::IsRuntimeAvailableToContext(ScriptContext* context) {
1254 if (extensions::FeatureSwitch::surface_worker()->IsEnabled() &&
1255 context->GetAvailability("surfaceWorkerInternal").is_available()) {
1256 return true;
1258 for (const auto& extension : extensions_) {
1259 ExternallyConnectableInfo* info = static_cast<ExternallyConnectableInfo*>(
1260 extension->GetManifestData(manifest_keys::kExternallyConnectable));
1261 if (info && info->matches.MatchesURL(context->GetURL()))
1262 return true;
1264 return false;
1267 void Dispatcher::UpdateContentCapabilities(ScriptContext* context) {
1268 APIPermissionSet permissions;
1269 for (const auto& extension : extensions_) {
1270 const ContentCapabilitiesInfo& info =
1271 ContentCapabilitiesInfo::Get(extension.get());
1272 if (info.url_patterns.MatchesURL(context->GetURL())) {
1273 APIPermissionSet new_permissions;
1274 APIPermissionSet::Union(permissions, info.permissions, &new_permissions);
1275 permissions = new_permissions;
1278 context->SetContentCapabilities(permissions);
1281 void Dispatcher::PopulateSourceMap() {
1282 const std::vector<std::pair<std::string, int> > resources = GetJsResources();
1283 for (std::vector<std::pair<std::string, int> >::const_iterator resource =
1284 resources.begin();
1285 resource != resources.end();
1286 ++resource) {
1287 source_map_.RegisterSource(resource->first, resource->second);
1289 delegate_->PopulateSourceMap(&source_map_);
1292 bool Dispatcher::IsWithinPlatformApp() {
1293 for (std::set<std::string>::iterator iter = active_extension_ids_.begin();
1294 iter != active_extension_ids_.end();
1295 ++iter) {
1296 const Extension* extension = extensions_.GetByID(*iter);
1297 if (extension && extension->is_platform_app())
1298 return true;
1300 return false;
1303 v8::Local<v8::Object> Dispatcher::GetOrCreateObject(
1304 const v8::Local<v8::Object>& object,
1305 const std::string& field,
1306 v8::Isolate* isolate) {
1307 v8::Local<v8::String> key = v8::String::NewFromUtf8(isolate, field.c_str());
1308 // If the object has a callback property, it is assumed it is an unavailable
1309 // API, so it is safe to delete. This is checked before GetOrCreateObject is
1310 // called.
1311 if (object->HasRealNamedCallbackProperty(key)) {
1312 object->Delete(key);
1313 } else if (object->HasRealNamedProperty(key)) {
1314 v8::Local<v8::Value> value = object->Get(key);
1315 CHECK(value->IsObject());
1316 return v8::Local<v8::Object>::Cast(value);
1319 v8::Local<v8::Object> new_object = v8::Object::New(isolate);
1320 object->Set(key, new_object);
1321 return new_object;
1324 v8::Local<v8::Object> Dispatcher::GetOrCreateBindObjectIfAvailable(
1325 const std::string& api_name,
1326 std::string* bind_name,
1327 ScriptContext* context) {
1328 std::vector<std::string> split;
1329 base::SplitString(api_name, '.', &split);
1331 v8::Local<v8::Object> bind_object;
1333 // Check if this API has an ancestor. If the API's ancestor is available and
1334 // the API is not available, don't install the bindings for this API. If
1335 // the API is available and its ancestor is not, delete the ancestor and
1336 // install the bindings for the API. This is to prevent loading the ancestor
1337 // API schema if it will not be needed.
1339 // For example:
1340 // If app is available and app.window is not, just install app.
1341 // If app.window is available and app is not, delete app and install
1342 // app.window on a new object so app does not have to be loaded.
1343 const FeatureProvider* api_feature_provider =
1344 FeatureProvider::GetAPIFeatures();
1345 std::string ancestor_name;
1346 bool only_ancestor_available = false;
1348 for (size_t i = 0; i < split.size() - 1; ++i) {
1349 ancestor_name += (i ? "." : "") + split[i];
1350 if (api_feature_provider->GetFeature(ancestor_name) &&
1351 context->GetAvailability(ancestor_name).is_available() &&
1352 !context->GetAvailability(api_name).is_available()) {
1353 only_ancestor_available = true;
1354 break;
1357 if (bind_object.IsEmpty()) {
1358 bind_object = AsObjectOrEmpty(GetOrCreateChrome(context));
1359 if (bind_object.IsEmpty())
1360 return v8::Local<v8::Object>();
1362 bind_object = GetOrCreateObject(bind_object, split[i], context->isolate());
1365 if (only_ancestor_available)
1366 return v8::Local<v8::Object>();
1368 if (bind_name)
1369 *bind_name = split.back();
1371 return bind_object.IsEmpty() ? AsObjectOrEmpty(GetOrCreateChrome(context))
1372 : bind_object;
1375 void Dispatcher::RequireGuestViewModules(ScriptContext* context) {
1376 Feature::Context context_type = context->context_type();
1377 ModuleSystem* module_system = context->module_system();
1379 // Require AppView.
1380 if (context->GetAvailability("appViewEmbedderInternal").is_available()) {
1381 module_system->Require("appView");
1384 // Require ExtensionOptions.
1385 if (context->GetAvailability("extensionOptionsInternal").is_available()) {
1386 module_system->Require("extensionOptions");
1387 module_system->Require("extensionOptionsAttributes");
1390 // Require ExtensionView.
1391 if (context->GetAvailability("extensionViewInternal").is_available()) {
1392 module_system->Require("extensionView");
1393 module_system->Require("extensionViewApiMethods");
1394 module_system->Require("extensionViewAttributes");
1397 // Require SurfaceView.
1398 if (extensions::FeatureSwitch::surface_worker()->IsEnabled() &&
1399 context->GetAvailability("surfaceWorkerInternal").is_available()) {
1400 module_system->Require("surfaceWorker");
1403 // Require WebView.
1404 if (context->GetAvailability("webViewInternal").is_available()) {
1405 module_system->Require("webView");
1406 module_system->Require("webViewApiMethods");
1407 module_system->Require("webViewAttributes");
1410 // The "guestViewDeny" module must always be loaded last. It registers
1411 // error-providing custom elements for the GuestView types that are not
1412 // available, and thus all of those types must have been checked and loaded
1413 // (or not loaded) beforehand.
1414 if (context_type == Feature::BLESSED_EXTENSION_CONTEXT) {
1415 module_system->Require("guestViewDeny");
1419 } // namespace extensions