Supervised user whitelists: Cleanup
[chromium-blink-merge.git] / extensions / renderer / dispatcher.cc
blobe2821a947da2e234a6921fd270426d3e10bec177
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::Handle<v8::Value> GetOrCreateChrome(ScriptContext* context) {
128 v8::Handle<v8::String> chrome_string(
129 v8::String::NewFromUtf8(context->isolate(), "chrome"));
130 v8::Handle<v8::Object> global(context->v8_context()->Global());
131 v8::Handle<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::Handle<v8::Object> AsObjectOrEmpty(v8::Handle<v8::Value> value) {
141 return value->IsObject() ? value.As<v8::Object>() : v8::Handle<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::Handle<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::Handle<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::Handle<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::Handle<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("port", IDR_PORT_JS));
483 resources.push_back(std::make_pair(kSchemaUtils, IDR_SCHEMA_UTILS_JS));
484 resources.push_back(std::make_pair("sendRequest", IDR_SEND_REQUEST_JS));
485 resources.push_back(std::make_pair("setIcon", IDR_SET_ICON_JS));
486 resources.push_back(std::make_pair("surfaceWorker", IDR_SURFACE_VIEW_JS));
487 resources.push_back(std::make_pair("test", IDR_TEST_CUSTOM_BINDINGS_JS));
488 resources.push_back(
489 std::make_pair("test_environment_specific_bindings",
490 IDR_BROWSER_TEST_ENVIRONMENT_SPECIFIC_BINDINGS_JS));
491 resources.push_back(std::make_pair("uncaught_exception_handler",
492 IDR_UNCAUGHT_EXCEPTION_HANDLER_JS));
493 resources.push_back(std::make_pair("unload_event", IDR_UNLOAD_EVENT_JS));
494 resources.push_back(std::make_pair("utils", IDR_UTILS_JS));
495 resources.push_back(std::make_pair("webRequest",
496 IDR_WEB_REQUEST_CUSTOM_BINDINGS_JS));
497 resources.push_back(
498 std::make_pair("webRequestInternal",
499 IDR_WEB_REQUEST_INTERNAL_CUSTOM_BINDINGS_JS));
500 // Note: webView not webview so that this doesn't interfere with the
501 // chrome.webview API bindings.
502 resources.push_back(std::make_pair("webView", IDR_WEB_VIEW_JS));
503 resources.push_back(std::make_pair("webViewActionRequests",
504 IDR_WEB_VIEW_ACTION_REQUESTS_JS));
505 resources.push_back(std::make_pair("webViewApiMethods",
506 IDR_WEB_VIEW_API_METHODS_JS));
507 resources.push_back(std::make_pair("webViewAttributes",
508 IDR_WEB_VIEW_ATTRIBUTES_JS));
509 resources.push_back(std::make_pair("webViewConstants",
510 IDR_WEB_VIEW_CONSTANTS_JS));
511 resources.push_back(std::make_pair("webViewEvents", IDR_WEB_VIEW_EVENTS_JS));
512 resources.push_back(std::make_pair("webViewInternal",
513 IDR_WEB_VIEW_INTERNAL_CUSTOM_BINDINGS_JS));
514 resources.push_back(
515 std::make_pair(mojo::kBindingsModuleName, IDR_MOJO_BINDINGS_JS));
516 resources.push_back(
517 std::make_pair(mojo::kBufferModuleName, IDR_MOJO_BUFFER_JS));
518 resources.push_back(
519 std::make_pair(mojo::kCodecModuleName, IDR_MOJO_CODEC_JS));
520 resources.push_back(
521 std::make_pair(mojo::kConnectionModuleName, IDR_MOJO_CONNECTION_JS));
522 resources.push_back(
523 std::make_pair(mojo::kConnectorModuleName, IDR_MOJO_CONNECTOR_JS));
524 resources.push_back(
525 std::make_pair(mojo::kRouterModuleName, IDR_MOJO_ROUTER_JS));
526 resources.push_back(
527 std::make_pair(mojo::kUnicodeModuleName, IDR_MOJO_UNICODE_JS));
528 resources.push_back(
529 std::make_pair(mojo::kValidatorModuleName, IDR_MOJO_VALIDATOR_JS));
530 resources.push_back(std::make_pair("async_waiter", IDR_ASYNC_WAITER_JS));
531 resources.push_back(std::make_pair("data_receiver", IDR_DATA_RECEIVER_JS));
532 resources.push_back(std::make_pair("data_sender", IDR_DATA_SENDER_JS));
533 resources.push_back(std::make_pair("keep_alive", IDR_KEEP_ALIVE_JS));
534 resources.push_back(std::make_pair("extensions/common/mojo/keep_alive.mojom",
535 IDR_KEEP_ALIVE_MOJOM_JS));
536 resources.push_back(std::make_pair("device/serial/data_stream.mojom",
537 IDR_DATA_STREAM_MOJOM_JS));
538 resources.push_back(
539 std::make_pair("device/serial/data_stream_serialization.mojom",
540 IDR_DATA_STREAM_SERIALIZATION_MOJOM_JS));
541 resources.push_back(std::make_pair("stash_client", IDR_STASH_CLIENT_JS));
542 resources.push_back(
543 std::make_pair("extensions/common/mojo/stash.mojom", IDR_STASH_MOJOM_JS));
545 // Custom bindings.
546 resources.push_back(
547 std::make_pair("app.runtime", IDR_APP_RUNTIME_CUSTOM_BINDINGS_JS));
548 resources.push_back(
549 std::make_pair("app.window", IDR_APP_WINDOW_CUSTOM_BINDINGS_JS));
550 resources.push_back(
551 std::make_pair("declarativeWebRequest",
552 IDR_DECLARATIVE_WEBREQUEST_CUSTOM_BINDINGS_JS));
553 resources.push_back(
554 std::make_pair("contextMenus", IDR_CONTEXT_MENUS_CUSTOM_BINDINGS_JS));
555 resources.push_back(
556 std::make_pair("contextMenusHandlers", IDR_CONTEXT_MENUS_HANDLERS_JS));
557 resources.push_back(
558 std::make_pair("extension", IDR_EXTENSION_CUSTOM_BINDINGS_JS));
559 resources.push_back(std::make_pair("i18n", IDR_I18N_CUSTOM_BINDINGS_JS));
560 resources.push_back(std::make_pair(
561 "mimeHandlerPrivate", IDR_MIME_HANDLER_PRIVATE_CUSTOM_BINDINGS_JS));
562 resources.push_back(std::make_pair("extensions/common/api/mime_handler.mojom",
563 IDR_MIME_HANDLER_MOJOM_JS));
564 resources.push_back(
565 std::make_pair("mojoPrivate", IDR_MOJO_PRIVATE_CUSTOM_BINDINGS_JS));
566 resources.push_back(
567 std::make_pair("permissions", IDR_PERMISSIONS_CUSTOM_BINDINGS_JS));
568 resources.push_back(std::make_pair("printerProvider",
569 IDR_PRINTER_PROVIDER_CUSTOM_BINDINGS_JS));
570 resources.push_back(
571 std::make_pair("runtime", IDR_RUNTIME_CUSTOM_BINDINGS_JS));
572 resources.push_back(std::make_pair("windowControls", IDR_WINDOW_CONTROLS_JS));
573 resources.push_back(
574 std::make_pair("webViewRequest",
575 IDR_WEB_VIEW_REQUEST_CUSTOM_BINDINGS_JS));
576 resources.push_back(std::make_pair("binding", IDR_BINDING_JS));
578 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
579 switches::kEnableMojoSerialService)) {
580 resources.push_back(
581 std::make_pair("serial", IDR_SERIAL_CUSTOM_BINDINGS_JS));
583 resources.push_back(std::make_pair("serial_service", IDR_SERIAL_SERVICE_JS));
584 resources.push_back(
585 std::make_pair("device/serial/serial.mojom", IDR_SERIAL_MOJOM_JS));
586 resources.push_back(std::make_pair("device/serial/serial_serialization.mojom",
587 IDR_SERIAL_SERIALIZATION_MOJOM_JS));
589 // Custom types sources.
590 resources.push_back(std::make_pair("StorageArea", IDR_STORAGE_AREA_JS));
592 // Platform app sources that are not API-specific..
593 resources.push_back(std::make_pair("platformApp", IDR_PLATFORM_APP_JS));
595 return resources;
598 // NOTE: please use the naming convention "foo_natives" for these.
599 // static
600 void Dispatcher::RegisterNativeHandlers(ModuleSystem* module_system,
601 ScriptContext* context,
602 Dispatcher* dispatcher,
603 RequestSender* request_sender,
604 V8SchemaRegistry* v8_schema_registry) {
605 module_system->RegisterNativeHandler(
606 "chrome", scoped_ptr<NativeHandler>(new ChromeNativeHandler(context)));
607 module_system->RegisterNativeHandler(
608 "lazy_background_page",
609 scoped_ptr<NativeHandler>(new LazyBackgroundPageNativeHandler(context)));
610 module_system->RegisterNativeHandler(
611 "logging", scoped_ptr<NativeHandler>(new LoggingNativeHandler(context)));
612 module_system->RegisterNativeHandler("schema_registry",
613 v8_schema_registry->AsNativeHandler());
614 module_system->RegisterNativeHandler(
615 "print", scoped_ptr<NativeHandler>(new PrintNativeHandler(context)));
616 module_system->RegisterNativeHandler(
617 "test_features",
618 scoped_ptr<NativeHandler>(new TestFeaturesNativeHandler(context)));
619 module_system->RegisterNativeHandler(
620 "user_gestures",
621 scoped_ptr<NativeHandler>(new UserGesturesNativeHandler(context)));
622 module_system->RegisterNativeHandler(
623 "utils", scoped_ptr<NativeHandler>(new UtilsNativeHandler(context)));
624 module_system->RegisterNativeHandler(
625 "v8_context",
626 scoped_ptr<NativeHandler>(
627 new V8ContextNativeHandler(context, dispatcher)));
628 module_system->RegisterNativeHandler(
629 "event_natives", scoped_ptr<NativeHandler>(new EventBindings(context)));
630 module_system->RegisterNativeHandler(
631 "messaging_natives",
632 scoped_ptr<NativeHandler>(MessagingBindings::Get(dispatcher, context)));
633 module_system->RegisterNativeHandler(
634 "apiDefinitions",
635 scoped_ptr<NativeHandler>(
636 new ApiDefinitionsNatives(dispatcher, context)));
637 module_system->RegisterNativeHandler(
638 "sendRequest",
639 scoped_ptr<NativeHandler>(
640 new SendRequestNatives(request_sender, context)));
641 module_system->RegisterNativeHandler(
642 "setIcon",
643 scoped_ptr<NativeHandler>(new SetIconNatives(context)));
644 module_system->RegisterNativeHandler(
645 "activityLogger",
646 scoped_ptr<NativeHandler>(new APIActivityLogger(context)));
647 module_system->RegisterNativeHandler(
648 "renderViewObserverNatives",
649 scoped_ptr<NativeHandler>(new RenderViewObserverNatives(context)));
651 // Natives used by multiple APIs.
652 module_system->RegisterNativeHandler(
653 "file_system_natives",
654 scoped_ptr<NativeHandler>(new FileSystemNatives(context)));
656 // Custom bindings.
657 module_system->RegisterNativeHandler(
658 "app_runtime",
659 scoped_ptr<NativeHandler>(new AppRuntimeCustomBindings(context)));
660 module_system->RegisterNativeHandler(
661 "app_window_natives",
662 scoped_ptr<NativeHandler>(
663 new AppWindowCustomBindings(dispatcher, context)));
664 module_system->RegisterNativeHandler(
665 "blob_natives",
666 scoped_ptr<NativeHandler>(new BlobNativeHandler(context)));
667 module_system->RegisterNativeHandler(
668 "context_menus",
669 scoped_ptr<NativeHandler>(new ContextMenusCustomBindings(context)));
670 module_system->RegisterNativeHandler(
671 "css_natives", scoped_ptr<NativeHandler>(new CssNativeHandler(context)));
672 module_system->RegisterNativeHandler(
673 "document_natives",
674 scoped_ptr<NativeHandler>(new DocumentCustomBindings(context)));
675 module_system->RegisterNativeHandler(
676 "guest_view_internal",
677 scoped_ptr<NativeHandler>(
678 new GuestViewInternalCustomBindings(context)));
679 module_system->RegisterNativeHandler(
680 "i18n", scoped_ptr<NativeHandler>(new I18NCustomBindings(context)));
681 module_system->RegisterNativeHandler(
682 "id_generator",
683 scoped_ptr<NativeHandler>(new IdGeneratorCustomBindings(context)));
684 module_system->RegisterNativeHandler(
685 "runtime", scoped_ptr<NativeHandler>(new RuntimeCustomBindings(context)));
688 bool Dispatcher::OnControlMessageReceived(const IPC::Message& message) {
689 bool handled = true;
690 IPC_BEGIN_MESSAGE_MAP(Dispatcher, message)
691 IPC_MESSAGE_HANDLER(ExtensionMsg_ActivateExtension, OnActivateExtension)
692 IPC_MESSAGE_HANDLER(ExtensionMsg_CancelSuspend, OnCancelSuspend)
693 IPC_MESSAGE_HANDLER(ExtensionMsg_DeliverMessage, OnDeliverMessage)
694 IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnConnect, OnDispatchOnConnect)
695 IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnDisconnect, OnDispatchOnDisconnect)
696 IPC_MESSAGE_HANDLER(ExtensionMsg_Loaded, OnLoaded)
697 IPC_MESSAGE_HANDLER(ExtensionMsg_MessageInvoke, OnMessageInvoke)
698 IPC_MESSAGE_HANDLER(ExtensionMsg_SetChannel, OnSetChannel)
699 IPC_MESSAGE_HANDLER(ExtensionMsg_SetFunctionNames, OnSetFunctionNames)
700 IPC_MESSAGE_HANDLER(ExtensionMsg_SetScriptingWhitelist,
701 OnSetScriptingWhitelist)
702 IPC_MESSAGE_HANDLER(ExtensionMsg_SetSystemFont, OnSetSystemFont)
703 IPC_MESSAGE_HANDLER(ExtensionMsg_ShouldSuspend, OnShouldSuspend)
704 IPC_MESSAGE_HANDLER(ExtensionMsg_Suspend, OnSuspend)
705 IPC_MESSAGE_HANDLER(ExtensionMsg_TransferBlobs, OnTransferBlobs)
706 IPC_MESSAGE_HANDLER(ExtensionMsg_Unloaded, OnUnloaded)
707 IPC_MESSAGE_HANDLER(ExtensionMsg_UpdatePermissions, OnUpdatePermissions)
708 IPC_MESSAGE_HANDLER(ExtensionMsg_UpdateTabSpecificPermissions,
709 OnUpdateTabSpecificPermissions)
710 IPC_MESSAGE_HANDLER(ExtensionMsg_ClearTabSpecificPermissions,
711 OnClearTabSpecificPermissions)
712 IPC_MESSAGE_HANDLER(ExtensionMsg_UsingWebRequestAPI, OnUsingWebRequestAPI)
713 IPC_MESSAGE_FORWARD(ExtensionMsg_WatchPages,
714 content_watcher_.get(),
715 ContentWatcher::OnWatchPages)
716 IPC_MESSAGE_UNHANDLED(handled = false)
717 IPC_END_MESSAGE_MAP()
719 return handled;
722 void Dispatcher::WebKitInitialized() {
723 // For extensions, we want to ensure we call the IdleHandler every so often,
724 // even if the extension keeps up activity.
725 if (set_idle_notifications_) {
726 forced_idle_timer_.reset(new base::RepeatingTimer<content::RenderThread>);
727 forced_idle_timer_->Start(
728 FROM_HERE,
729 base::TimeDelta::FromMilliseconds(kMaxExtensionIdleHandlerDelayMs),
730 RenderThread::Get(),
731 &RenderThread::IdleHandler);
734 // Initialize host permissions for any extensions that were activated before
735 // WebKit was initialized.
736 for (std::set<std::string>::iterator iter = active_extension_ids_.begin();
737 iter != active_extension_ids_.end();
738 ++iter) {
739 const Extension* extension = extensions_.GetByID(*iter);
740 CHECK(extension);
742 InitOriginPermissions(extension);
745 EnableCustomElementWhiteList();
747 is_webkit_initialized_ = true;
750 void Dispatcher::IdleNotification() {
751 if (set_idle_notifications_ && forced_idle_timer_) {
752 // Dampen the forced delay as well if the extension stays idle for long
753 // periods of time. (forced_idle_timer_ can be NULL after
754 // OnRenderProcessShutdown has been called.)
755 int64 forced_delay_ms =
756 std::max(RenderThread::Get()->GetIdleNotificationDelayInMs(),
757 kMaxExtensionIdleHandlerDelayMs);
758 forced_idle_timer_->Stop();
759 forced_idle_timer_->Start(
760 FROM_HERE,
761 base::TimeDelta::FromMilliseconds(forced_delay_ms),
762 RenderThread::Get(),
763 &RenderThread::IdleHandler);
767 void Dispatcher::OnRenderProcessShutdown() {
768 v8_schema_registry_.reset();
769 forced_idle_timer_.reset();
772 void Dispatcher::OnActivateExtension(const std::string& extension_id) {
773 const Extension* extension = extensions_.GetByID(extension_id);
774 if (!extension) {
775 // Extension was activated but was never loaded. This probably means that
776 // the renderer failed to load it (or the browser failed to tell us when it
777 // did). Failures shouldn't happen, but instead of crashing there (which
778 // executes on all renderers) be conservative and only crash in the renderer
779 // of the extension which failed to load; this one.
780 std::string& error = extension_load_errors_[extension_id];
781 char minidump[256];
782 base::debug::Alias(&minidump);
783 base::snprintf(minidump,
784 arraysize(minidump),
785 "e::dispatcher:%s:%s",
786 extension_id.c_str(),
787 error.c_str());
788 CHECK(extension) << extension_id << " was never loaded: " << error;
791 active_extension_ids_.insert(extension_id);
793 // This is called when starting a new extension page, so start the idle
794 // handler ticking.
795 RenderThread::Get()->ScheduleIdleHandler(kInitialExtensionIdleHandlerDelayMs);
797 if (is_webkit_initialized_) {
798 DOMActivityLogger::AttachToWorld(
799 DOMActivityLogger::kMainWorldId, extension_id);
801 InitOriginPermissions(extension);
804 UpdateActiveExtensions();
807 void Dispatcher::OnCancelSuspend(const std::string& extension_id) {
808 DispatchEvent(extension_id, kOnSuspendCanceledEvent);
811 void Dispatcher::OnDeliverMessage(int target_port_id, const Message& message) {
812 scoped_ptr<RequestSender::ScopedTabID> scoped_tab_id;
813 std::map<int, int>::const_iterator it =
814 port_to_tab_id_map_.find(target_port_id);
815 if (it != port_to_tab_id_map_.end()) {
816 scoped_tab_id.reset(
817 new RequestSender::ScopedTabID(request_sender(), it->second));
820 MessagingBindings::DeliverMessage(*script_context_set_, target_port_id,
821 message,
822 NULL); // All render frames.
825 void Dispatcher::OnDispatchOnConnect(
826 int target_port_id,
827 const std::string& channel_name,
828 const ExtensionMsg_TabConnectionInfo& source,
829 const ExtensionMsg_ExternalConnectionInfo& info,
830 const std::string& tls_channel_id) {
831 DCHECK(!ContainsKey(port_to_tab_id_map_, target_port_id));
832 DCHECK_EQ(1, target_port_id % 2); // target renderer ports have odd IDs.
833 int sender_tab_id = -1;
834 source.tab.GetInteger("id", &sender_tab_id);
835 port_to_tab_id_map_[target_port_id] = sender_tab_id;
837 MessagingBindings::DispatchOnConnect(*script_context_set_, target_port_id,
838 channel_name, source, info,
839 tls_channel_id,
840 NULL); // All render frames.
843 void Dispatcher::OnDispatchOnDisconnect(int port_id,
844 const std::string& error_message) {
845 MessagingBindings::DispatchOnDisconnect(*script_context_set_, port_id,
846 error_message,
847 NULL); // All render frames.
850 void Dispatcher::OnLoaded(
851 const std::vector<ExtensionMsg_Loaded_Params>& loaded_extensions) {
852 std::vector<ExtensionMsg_Loaded_Params>::const_iterator i;
853 for (i = loaded_extensions.begin(); i != loaded_extensions.end(); ++i) {
854 std::string error;
855 scoped_refptr<const Extension> extension = i->ConvertToExtension(&error);
856 if (!extension.get()) {
857 extension_load_errors_[i->id] = error;
858 continue;
860 OnLoadedInternal(extension);
862 // Update the available bindings for all contexts. These may have changed if
863 // an externally_connectable extension was loaded that can connect to an
864 // open webpage.
865 UpdateBindings("");
868 void Dispatcher::OnLoadedInternal(scoped_refptr<const Extension> extension) {
869 extensions_.Insert(extension);
872 void Dispatcher::OnMessageInvoke(const std::string& extension_id,
873 const std::string& module_name,
874 const std::string& function_name,
875 const base::ListValue& args,
876 bool user_gesture) {
877 InvokeModuleSystemMethod(
878 NULL, extension_id, module_name, function_name, args, user_gesture);
881 void Dispatcher::OnSetChannel(int channel) {
882 delegate_->SetChannel(channel);
885 void Dispatcher::OnSetFunctionNames(const std::vector<std::string>& names) {
886 function_names_.clear();
887 for (size_t i = 0; i < names.size(); ++i)
888 function_names_.insert(names[i]);
891 void Dispatcher::OnSetScriptingWhitelist(
892 const ExtensionsClient::ScriptingWhitelist& extension_ids) {
893 ExtensionsClient::Get()->SetScriptingWhitelist(extension_ids);
896 void Dispatcher::OnSetSystemFont(const std::string& font_family,
897 const std::string& font_size) {
898 system_font_family_ = font_family;
899 system_font_size_ = font_size;
902 void Dispatcher::OnShouldSuspend(const std::string& extension_id,
903 uint64 sequence_id) {
904 RenderThread::Get()->Send(
905 new ExtensionHostMsg_ShouldSuspendAck(extension_id, sequence_id));
908 void Dispatcher::OnSuspend(const std::string& extension_id) {
909 // Dispatch the suspend event. This doesn't go through the standard event
910 // dispatch machinery because it requires special handling. We need to let
911 // the browser know when we are starting and stopping the event dispatch, so
912 // that it still considers the extension idle despite any activity the suspend
913 // event creates.
914 DispatchEvent(extension_id, kOnSuspendEvent);
915 RenderThread::Get()->Send(new ExtensionHostMsg_SuspendAck(extension_id));
918 void Dispatcher::OnTransferBlobs(const std::vector<std::string>& blob_uuids) {
919 RenderThread::Get()->Send(new ExtensionHostMsg_TransferBlobsAck(blob_uuids));
922 void Dispatcher::OnUnloaded(const std::string& id) {
923 extensions_.Remove(id);
924 active_extension_ids_.erase(id);
926 script_injection_manager_->OnExtensionUnloaded(id);
928 // If the extension is later reloaded with a different set of permissions,
929 // we'd like it to get a new isolated world ID, so that it can pick up the
930 // changed origin whitelist.
931 ScriptInjection::RemoveIsolatedWorld(id);
933 // Invalidate all of the contexts that were removed.
934 // TODO(kalman): add an invalidation observer interface to ScriptContext.
935 std::set<ScriptContext*> removed_contexts =
936 script_context_set_->OnExtensionUnloaded(id);
937 for (ScriptContext* context : removed_contexts) {
938 request_sender_->InvalidateSource(context);
941 // Update the available bindings for the remaining contexts. These may have
942 // changed if an externally_connectable extension is unloaded and a webpage
943 // is no longer accessible.
944 UpdateBindings("");
946 // Invalidates the messages map for the extension in case the extension is
947 // reloaded with a new messages map.
948 EraseL10nMessagesMap(id);
950 // We don't do anything with existing platform-app stylesheets. They will
951 // stay resident, but the URL pattern corresponding to the unloaded
952 // extension's URL just won't match anything anymore.
955 void Dispatcher::OnUpdatePermissions(
956 const ExtensionMsg_UpdatePermissions_Params& params) {
957 const Extension* extension = extensions_.GetByID(params.extension_id);
958 if (!extension)
959 return;
961 scoped_refptr<const PermissionSet> active =
962 params.active_permissions.ToPermissionSet();
963 scoped_refptr<const PermissionSet> withheld =
964 params.withheld_permissions.ToPermissionSet();
966 if (is_webkit_initialized_) {
967 UpdateOriginPermissions(
968 extension->url(),
969 extension->permissions_data()->GetEffectiveHostPermissions(),
970 active->effective_hosts());
973 extension->permissions_data()->SetPermissions(active, withheld);
974 UpdateBindings(extension->id());
977 void Dispatcher::OnUpdateTabSpecificPermissions(const GURL& visible_url,
978 const std::string& extension_id,
979 const URLPatternSet& new_hosts,
980 bool update_origin_whitelist,
981 int tab_id) {
982 // Check against the URL to avoid races. If we can't find the tab, it's
983 // because this is an extension's background page (run in a different
984 // process) - in this case, we can't perform the security check. However,
985 // since activeTab is only granted via user action, this isn't a huge concern.
986 content::RenderView* render_view = TabFinder::Find(tab_id);
987 if (render_view &&
988 render_view->GetWebView()->mainFrame()->document().url() != visible_url) {
989 return;
992 const Extension* extension = extensions_.GetByID(extension_id);
993 if (!extension)
994 return;
996 URLPatternSet old_effective =
997 extension->permissions_data()->GetEffectiveHostPermissions();
998 extension->permissions_data()->UpdateTabSpecificPermissions(
999 tab_id,
1000 new extensions::PermissionSet(extensions::APIPermissionSet(),
1001 extensions::ManifestPermissionSet(),
1002 new_hosts,
1003 extensions::URLPatternSet()));
1005 if (is_webkit_initialized_ && update_origin_whitelist) {
1006 UpdateOriginPermissions(
1007 extension->url(),
1008 old_effective,
1009 extension->permissions_data()->GetEffectiveHostPermissions());
1013 void Dispatcher::OnClearTabSpecificPermissions(
1014 const std::vector<std::string>& extension_ids,
1015 bool update_origin_whitelist,
1016 int tab_id) {
1017 for (const std::string& id : extension_ids) {
1018 const Extension* extension = extensions_.GetByID(id);
1019 if (extension) {
1020 URLPatternSet old_effective =
1021 extension->permissions_data()->GetEffectiveHostPermissions();
1022 extension->permissions_data()->ClearTabSpecificPermissions(tab_id);
1023 if (is_webkit_initialized_ && update_origin_whitelist) {
1024 UpdateOriginPermissions(
1025 extension->url(),
1026 old_effective,
1027 extension->permissions_data()->GetEffectiveHostPermissions());
1033 void Dispatcher::OnUsingWebRequestAPI(bool webrequest_used) {
1034 webrequest_used_ = webrequest_used;
1037 void Dispatcher::OnUserScriptsUpdated(const std::set<HostID>& changed_hosts,
1038 const std::vector<UserScript*>& scripts) {
1039 UpdateActiveExtensions();
1042 void Dispatcher::UpdateActiveExtensions() {
1043 std::set<std::string> active_extensions = active_extension_ids_;
1044 user_script_set_manager_->GetAllActiveExtensionIds(&active_extensions);
1045 delegate_->OnActiveExtensionsUpdated(active_extensions);
1048 void Dispatcher::InitOriginPermissions(const Extension* extension) {
1049 delegate_->InitOriginPermissions(extension,
1050 IsExtensionActive(extension->id()));
1051 UpdateOriginPermissions(
1052 extension->url(),
1053 URLPatternSet(), // No old permissions.
1054 extension->permissions_data()->GetEffectiveHostPermissions());
1057 void Dispatcher::UpdateOriginPermissions(const GURL& extension_url,
1058 const URLPatternSet& old_patterns,
1059 const URLPatternSet& new_patterns) {
1060 static const char* kSchemes[] = {
1061 url::kHttpScheme,
1062 url::kHttpsScheme,
1063 url::kFileScheme,
1064 content::kChromeUIScheme,
1065 url::kFtpScheme,
1066 #if defined(OS_CHROMEOS)
1067 content::kExternalFileScheme,
1068 #endif
1069 extensions::kExtensionScheme,
1071 for (size_t i = 0; i < arraysize(kSchemes); ++i) {
1072 const char* scheme = kSchemes[i];
1073 // Remove all old patterns...
1074 for (URLPatternSet::const_iterator pattern = old_patterns.begin();
1075 pattern != old_patterns.end(); ++pattern) {
1076 if (pattern->MatchesScheme(scheme)) {
1077 WebSecurityPolicy::removeOriginAccessWhitelistEntry(
1078 extension_url,
1079 WebString::fromUTF8(scheme),
1080 WebString::fromUTF8(pattern->host()),
1081 pattern->match_subdomains());
1084 // ...And add the new ones.
1085 for (URLPatternSet::const_iterator pattern = new_patterns.begin();
1086 pattern != new_patterns.end(); ++pattern) {
1087 if (pattern->MatchesScheme(scheme)) {
1088 WebSecurityPolicy::addOriginAccessWhitelistEntry(
1089 extension_url,
1090 WebString::fromUTF8(scheme),
1091 WebString::fromUTF8(pattern->host()),
1092 pattern->match_subdomains());
1098 void Dispatcher::EnableCustomElementWhiteList() {
1099 blink::WebCustomElement::addEmbedderCustomElementName("appview");
1100 blink::WebCustomElement::addEmbedderCustomElementName("appviewbrowserplugin");
1101 blink::WebCustomElement::addEmbedderCustomElementName("extensionoptions");
1102 blink::WebCustomElement::addEmbedderCustomElementName(
1103 "extensionoptionsbrowserplugin");
1104 blink::WebCustomElement::addEmbedderCustomElementName("extensionview");
1105 blink::WebCustomElement::addEmbedderCustomElementName(
1106 "extensionviewbrowserplugin");
1107 blink::WebCustomElement::addEmbedderCustomElementName("webview");
1108 blink::WebCustomElement::addEmbedderCustomElementName("webviewbrowserplugin");
1109 blink::WebCustomElement::addEmbedderCustomElementName("surfaceview");
1110 blink::WebCustomElement::addEmbedderCustomElementName(
1111 "surfaceviewbrowserplugin");
1114 void Dispatcher::UpdateBindings(const std::string& extension_id) {
1115 script_context_set().ForEach(extension_id,
1116 base::Bind(&Dispatcher::UpdateBindingsForContext,
1117 base::Unretained(this)));
1120 void Dispatcher::UpdateBindingsForContext(ScriptContext* context) {
1121 v8::HandleScope handle_scope(context->isolate());
1122 v8::Context::Scope context_scope(context->v8_context());
1124 // TODO(kalman): Make the bindings registration have zero overhead then run
1125 // the same code regardless of context type.
1126 switch (context->context_type()) {
1127 case Feature::UNSPECIFIED_CONTEXT:
1128 case Feature::WEB_PAGE_CONTEXT:
1129 case Feature::BLESSED_WEB_PAGE_CONTEXT:
1130 // Web page context; it's too expensive to run the full bindings code.
1131 // Hard-code that the app and webstore APIs are available...
1132 if (context->GetAvailability("app").is_available())
1133 RegisterBinding("app", context);
1134 if (context->GetAvailability("webstore").is_available())
1135 RegisterBinding("webstore", context);
1136 if (IsRuntimeAvailableToContext(context))
1137 RegisterBinding("runtime", context);
1138 UpdateContentCapabilities(context);
1139 break;
1141 case Feature::BLESSED_EXTENSION_CONTEXT:
1142 case Feature::UNBLESSED_EXTENSION_CONTEXT:
1143 case Feature::CONTENT_SCRIPT_CONTEXT:
1144 case Feature::WEBUI_CONTEXT: {
1145 // Extension context; iterate through all the APIs and bind the available
1146 // ones.
1147 const FeatureProvider* api_feature_provider =
1148 FeatureProvider::GetAPIFeatures();
1149 const std::vector<std::string>& apis =
1150 api_feature_provider->GetAllFeatureNames();
1151 for (std::vector<std::string>::const_iterator it = apis.begin();
1152 it != apis.end();
1153 ++it) {
1154 const std::string& api_name = *it;
1155 Feature* feature = api_feature_provider->GetFeature(api_name);
1156 DCHECK(feature);
1158 // Internal APIs are included via require(api_name) from internal code
1159 // rather than chrome[api_name].
1160 if (feature->IsInternal())
1161 continue;
1163 // If this API has a parent feature (and isn't marked 'noparent'),
1164 // then this must be a function or event, so we should not register.
1165 if (api_feature_provider->GetParent(feature) != NULL)
1166 continue;
1168 // Skip chrome.test if this isn't a test.
1169 if (api_name == "test" &&
1170 !base::CommandLine::ForCurrentProcess()->HasSwitch(
1171 ::switches::kTestType)) {
1172 continue;
1175 if (context->IsAnyFeatureAvailableToContext(*feature))
1176 RegisterBinding(api_name, context);
1178 break;
1183 void Dispatcher::RegisterBinding(const std::string& api_name,
1184 ScriptContext* context) {
1185 std::string bind_name;
1186 v8::Handle<v8::Object> bind_object =
1187 GetOrCreateBindObjectIfAvailable(api_name, &bind_name, context);
1189 // Empty if the bind object failed to be created, probably because the
1190 // extension overrode chrome with a non-object, e.g. window.chrome = true.
1191 if (bind_object.IsEmpty())
1192 return;
1194 v8::Local<v8::String> v8_bind_name =
1195 v8::String::NewFromUtf8(context->isolate(), bind_name.c_str());
1196 if (bind_object->HasRealNamedProperty(v8_bind_name)) {
1197 // The bind object may already have the property if the API has been
1198 // registered before (or if the extension has put something there already,
1199 // but, whatevs).
1201 // In the former case, we need to re-register the bindings for the APIs
1202 // which the extension now has permissions for (if any), but not touch any
1203 // others so that we don't destroy state such as event listeners.
1205 // TODO(kalman): Only register available APIs to make this all moot.
1206 if (bind_object->HasRealNamedCallbackProperty(v8_bind_name))
1207 return; // lazy binding still there, nothing to do
1208 if (bind_object->Get(v8_bind_name)->IsObject())
1209 return; // binding has already been fully installed
1212 ModuleSystem* module_system = context->module_system();
1213 if (!source_map_.Contains(api_name)) {
1214 module_system->RegisterNativeHandler(
1215 api_name,
1216 scoped_ptr<NativeHandler>(new BindingGeneratingNativeHandler(
1217 module_system, api_name, "binding")));
1218 module_system->SetNativeLazyField(
1219 bind_object, bind_name, api_name, "binding");
1220 } else {
1221 module_system->SetLazyField(bind_object, bind_name, api_name, "binding");
1225 // NOTE: please use the naming convention "foo_natives" for these.
1226 void Dispatcher::RegisterNativeHandlers(ModuleSystem* module_system,
1227 ScriptContext* context) {
1228 RegisterNativeHandlers(module_system,
1229 context,
1230 this,
1231 request_sender_.get(),
1232 v8_schema_registry_.get());
1233 const Extension* extension = context->extension();
1234 int manifest_version = extension ? extension->manifest_version() : 1;
1235 bool is_component_extension =
1236 extension && Manifest::IsComponentLocation(extension->location());
1237 bool send_request_disabled =
1238 (extension && Manifest::IsUnpackedLocation(extension->location()) &&
1239 BackgroundInfo::HasLazyBackgroundPage(extension));
1240 module_system->RegisterNativeHandler(
1241 "process",
1242 scoped_ptr<NativeHandler>(new ProcessInfoNativeHandler(
1243 context,
1244 context->GetExtensionID(),
1245 context->GetContextTypeDescription(),
1246 ExtensionsRendererClient::Get()->IsIncognitoProcess(),
1247 is_component_extension,
1248 manifest_version,
1249 send_request_disabled)));
1251 delegate_->RegisterNativeHandlers(this, module_system, context);
1254 bool Dispatcher::IsRuntimeAvailableToContext(ScriptContext* context) {
1255 if (extensions::FeatureSwitch::surface_worker()->IsEnabled() &&
1256 context->GetAvailability("surfaceWorkerInternal").is_available()) {
1257 return true;
1259 for (const auto& extension : extensions_) {
1260 ExternallyConnectableInfo* info = static_cast<ExternallyConnectableInfo*>(
1261 extension->GetManifestData(manifest_keys::kExternallyConnectable));
1262 if (info && info->matches.MatchesURL(context->GetURL()))
1263 return true;
1265 return false;
1268 void Dispatcher::UpdateContentCapabilities(ScriptContext* context) {
1269 APIPermissionSet permissions;
1270 for (const auto& extension : extensions_) {
1271 const ContentCapabilitiesInfo& info =
1272 ContentCapabilitiesInfo::Get(extension.get());
1273 if (info.url_patterns.MatchesURL(context->GetURL())) {
1274 APIPermissionSet new_permissions;
1275 APIPermissionSet::Union(permissions, info.permissions, &new_permissions);
1276 permissions = new_permissions;
1279 context->SetContentCapabilities(permissions);
1282 void Dispatcher::PopulateSourceMap() {
1283 const std::vector<std::pair<std::string, int> > resources = GetJsResources();
1284 for (std::vector<std::pair<std::string, int> >::const_iterator resource =
1285 resources.begin();
1286 resource != resources.end();
1287 ++resource) {
1288 source_map_.RegisterSource(resource->first, resource->second);
1290 delegate_->PopulateSourceMap(&source_map_);
1293 bool Dispatcher::IsWithinPlatformApp() {
1294 for (std::set<std::string>::iterator iter = active_extension_ids_.begin();
1295 iter != active_extension_ids_.end();
1296 ++iter) {
1297 const Extension* extension = extensions_.GetByID(*iter);
1298 if (extension && extension->is_platform_app())
1299 return true;
1301 return false;
1304 v8::Handle<v8::Object> Dispatcher::GetOrCreateObject(
1305 const v8::Handle<v8::Object>& object,
1306 const std::string& field,
1307 v8::Isolate* isolate) {
1308 v8::Handle<v8::String> key = v8::String::NewFromUtf8(isolate, field.c_str());
1309 // If the object has a callback property, it is assumed it is an unavailable
1310 // API, so it is safe to delete. This is checked before GetOrCreateObject is
1311 // called.
1312 if (object->HasRealNamedCallbackProperty(key)) {
1313 object->Delete(key);
1314 } else if (object->HasRealNamedProperty(key)) {
1315 v8::Handle<v8::Value> value = object->Get(key);
1316 CHECK(value->IsObject());
1317 return v8::Handle<v8::Object>::Cast(value);
1320 v8::Handle<v8::Object> new_object = v8::Object::New(isolate);
1321 object->Set(key, new_object);
1322 return new_object;
1325 v8::Handle<v8::Object> Dispatcher::GetOrCreateBindObjectIfAvailable(
1326 const std::string& api_name,
1327 std::string* bind_name,
1328 ScriptContext* context) {
1329 std::vector<std::string> split;
1330 base::SplitString(api_name, '.', &split);
1332 v8::Handle<v8::Object> bind_object;
1334 // Check if this API has an ancestor. If the API's ancestor is available and
1335 // the API is not available, don't install the bindings for this API. If
1336 // the API is available and its ancestor is not, delete the ancestor and
1337 // install the bindings for the API. This is to prevent loading the ancestor
1338 // API schema if it will not be needed.
1340 // For example:
1341 // If app is available and app.window is not, just install app.
1342 // If app.window is available and app is not, delete app and install
1343 // app.window on a new object so app does not have to be loaded.
1344 const FeatureProvider* api_feature_provider =
1345 FeatureProvider::GetAPIFeatures();
1346 std::string ancestor_name;
1347 bool only_ancestor_available = false;
1349 for (size_t i = 0; i < split.size() - 1; ++i) {
1350 ancestor_name += (i ? "." : "") + split[i];
1351 if (api_feature_provider->GetFeature(ancestor_name) &&
1352 context->GetAvailability(ancestor_name).is_available() &&
1353 !context->GetAvailability(api_name).is_available()) {
1354 only_ancestor_available = true;
1355 break;
1358 if (bind_object.IsEmpty()) {
1359 bind_object = AsObjectOrEmpty(GetOrCreateChrome(context));
1360 if (bind_object.IsEmpty())
1361 return v8::Handle<v8::Object>();
1363 bind_object = GetOrCreateObject(bind_object, split[i], context->isolate());
1366 if (only_ancestor_available)
1367 return v8::Handle<v8::Object>();
1369 if (bind_name)
1370 *bind_name = split.back();
1372 return bind_object.IsEmpty() ? AsObjectOrEmpty(GetOrCreateChrome(context))
1373 : bind_object;
1376 void Dispatcher::RequireGuestViewModules(ScriptContext* context) {
1377 Feature::Context context_type = context->context_type();
1378 ModuleSystem* module_system = context->module_system();
1380 // Require AppView.
1381 if (context->GetAvailability("appViewEmbedderInternal").is_available()) {
1382 module_system->Require("appView");
1385 // Require ExtensionOptions.
1386 if (context->GetAvailability("extensionOptionsInternal").is_available()) {
1387 module_system->Require("extensionOptions");
1388 module_system->Require("extensionOptionsAttributes");
1391 // Require ExtensionView.
1392 if (context->GetAvailability("extensionViewInternal").is_available()) {
1393 module_system->Require("extensionView");
1394 module_system->Require("extensionViewApiMethods");
1395 module_system->Require("extensionViewAttributes");
1398 // Require SurfaceView.
1399 if (extensions::FeatureSwitch::surface_worker()->IsEnabled() &&
1400 context->GetAvailability("surfaceWorkerInternal").is_available()) {
1401 module_system->Require("surfaceWorker");
1404 // Require WebView.
1405 if (context->GetAvailability("webViewInternal").is_available()) {
1406 module_system->Require("webView");
1407 module_system->Require("webViewApiMethods");
1408 module_system->Require("webViewAttributes");
1411 // The "guestViewDeny" module must always be loaded last. It registers
1412 // error-providing custom elements for the GuestView types that are not
1413 // available, and thus all of those types must have been checked and loaded
1414 // (or not loaded) beforehand.
1415 if (context_type == Feature::BLESSED_EXTENSION_CONTEXT) {
1416 module_system->Require("guestViewDeny");
1420 } // namespace extensions