Update V8 to version 4.6.21.
[chromium-blink-merge.git] / extensions / renderer / dispatcher.cc
blobb38afc0e536edf04e7f7334f6e63fd977f25bfb2
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/strings/utf_string_conversions.h"
18 #include "base/time/time.h"
19 #include "base/values.h"
20 #include "content/grit/content_resources.h"
21 #include "content/public/child/v8_value_converter.h"
22 #include "content/public/common/content_switches.h"
23 #include "content/public/common/url_constants.h"
24 #include "content/public/renderer/render_frame.h"
25 #include "content/public/renderer/render_thread.h"
26 #include "extensions/common/api/messaging/message.h"
27 #include "extensions/common/constants.h"
28 #include "extensions/common/extension_api.h"
29 #include "extensions/common/extension_messages.h"
30 #include "extensions/common/extension_urls.h"
31 #include "extensions/common/feature_switch.h"
32 #include "extensions/common/features/behavior_feature.h"
33 #include "extensions/common/features/feature.h"
34 #include "extensions/common/features/feature_provider.h"
35 #include "extensions/common/manifest.h"
36 #include "extensions/common/manifest_constants.h"
37 #include "extensions/common/manifest_handlers/background_info.h"
38 #include "extensions/common/manifest_handlers/content_capabilities_handler.h"
39 #include "extensions/common/manifest_handlers/externally_connectable.h"
40 #include "extensions/common/manifest_handlers/options_page_info.h"
41 #include "extensions/common/message_bundle.h"
42 #include "extensions/common/permissions/permission_set.h"
43 #include "extensions/common/permissions/permissions_data.h"
44 #include "extensions/common/switches.h"
45 #include "extensions/common/view_type.h"
46 #include "extensions/renderer/api_activity_logger.h"
47 #include "extensions/renderer/api_definitions_natives.h"
48 #include "extensions/renderer/app_runtime_custom_bindings.h"
49 #include "extensions/renderer/app_window_custom_bindings.h"
50 #include "extensions/renderer/binding_generating_native_handler.h"
51 #include "extensions/renderer/blob_native_handler.h"
52 #include "extensions/renderer/content_watcher.h"
53 #include "extensions/renderer/context_menus_custom_bindings.h"
54 #include "extensions/renderer/css_native_handler.h"
55 #include "extensions/renderer/dispatcher_delegate.h"
56 #include "extensions/renderer/document_custom_bindings.h"
57 #include "extensions/renderer/dom_activity_logger.h"
58 #include "extensions/renderer/event_bindings.h"
59 #include "extensions/renderer/extension_frame_helper.h"
60 #include "extensions/renderer/extension_helper.h"
61 #include "extensions/renderer/extensions_renderer_client.h"
62 #include "extensions/renderer/file_system_natives.h"
63 #include "extensions/renderer/guest_view/guest_view_internal_custom_bindings.h"
64 #include "extensions/renderer/i18n_custom_bindings.h"
65 #include "extensions/renderer/id_generator_custom_bindings.h"
66 #include "extensions/renderer/lazy_background_page_native_handler.h"
67 #include "extensions/renderer/logging_native_handler.h"
68 #include "extensions/renderer/messaging_bindings.h"
69 #include "extensions/renderer/module_system.h"
70 #include "extensions/renderer/print_native_handler.h"
71 #include "extensions/renderer/process_info_native_handler.h"
72 #include "extensions/renderer/render_frame_observer_natives.h"
73 #include "extensions/renderer/request_sender.h"
74 #include "extensions/renderer/runtime_custom_bindings.h"
75 #include "extensions/renderer/safe_builtins.h"
76 #include "extensions/renderer/script_context.h"
77 #include "extensions/renderer/script_context_set.h"
78 #include "extensions/renderer/script_injection.h"
79 #include "extensions/renderer/script_injection_manager.h"
80 #include "extensions/renderer/send_request_natives.h"
81 #include "extensions/renderer/set_icon_natives.h"
82 #include "extensions/renderer/test_features_native_handler.h"
83 #include "extensions/renderer/user_gestures_native_handler.h"
84 #include "extensions/renderer/utils_native_handler.h"
85 #include "extensions/renderer/v8_context_native_handler.h"
86 #include "grit/extensions_renderer_resources.h"
87 #include "third_party/WebKit/public/platform/WebString.h"
88 #include "third_party/WebKit/public/platform/WebURLRequest.h"
89 #include "third_party/WebKit/public/web/WebCustomElement.h"
90 #include "third_party/WebKit/public/web/WebDataSource.h"
91 #include "third_party/WebKit/public/web/WebDocument.h"
92 #include "third_party/WebKit/public/web/WebFrame.h"
93 #include "third_party/WebKit/public/web/WebLocalFrame.h"
94 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
95 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
96 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
97 #include "third_party/WebKit/public/web/WebView.h"
98 #include "third_party/mojo/src/mojo/public/js/constants.h"
99 #include "ui/base/layout.h"
100 #include "ui/base/resource/resource_bundle.h"
101 #include "v8/include/v8.h"
103 using base::UserMetricsAction;
104 using blink::WebDataSource;
105 using blink::WebDocument;
106 using blink::WebScopedUserGesture;
107 using blink::WebSecurityPolicy;
108 using blink::WebString;
109 using blink::WebVector;
110 using blink::WebView;
111 using content::RenderThread;
113 namespace extensions {
115 namespace {
117 static const int64 kInitialExtensionIdleHandlerDelayMs = 5 * 1000;
118 static const int64 kMaxExtensionIdleHandlerDelayMs = 5 * 60 * 1000;
119 static const char kEventDispatchFunction[] = "dispatchEvent";
120 static const char kOnSuspendEvent[] = "runtime.onSuspend";
121 static const char kOnSuspendCanceledEvent[] = "runtime.onSuspendCanceled";
123 // Returns the global value for "chrome" from |context|. If one doesn't exist
124 // creates a new object for it.
126 // Note that this isn't necessarily an object, since webpages can write, for
127 // example, "window.chrome = true".
128 v8::Local<v8::Value> GetOrCreateChrome(ScriptContext* context) {
129 v8::Local<v8::String> chrome_string(
130 v8::String::NewFromUtf8(context->isolate(), "chrome"));
131 v8::Local<v8::Object> global(context->v8_context()->Global());
132 v8::Local<v8::Value> chrome(global->Get(chrome_string));
133 if (chrome->IsUndefined()) {
134 chrome = v8::Object::New(context->isolate());
135 global->Set(chrome_string, chrome);
137 return chrome;
140 // Returns |value| cast to an object if possible, else an empty handle.
141 v8::Local<v8::Object> AsObjectOrEmpty(v8::Local<v8::Value> value) {
142 return value->IsObject() ? value.As<v8::Object>() : v8::Local<v8::Object>();
145 // Calls a method |method_name| in a module |module_name| belonging to the
146 // module system from |context|. Intended as a callback target from
147 // ScriptContextSet::ForEach.
148 void CallModuleMethod(const std::string& module_name,
149 const std::string& method_name,
150 const base::ListValue* args,
151 ScriptContext* context) {
152 v8::HandleScope handle_scope(context->isolate());
153 v8::Context::Scope context_scope(context->v8_context());
155 scoped_ptr<content::V8ValueConverter> converter(
156 content::V8ValueConverter::create());
158 std::vector<v8::Local<v8::Value>> arguments;
159 for (base::ListValue::const_iterator it = args->begin(); it != args->end();
160 ++it) {
161 arguments.push_back(converter->ToV8Value(*it, context->v8_context()));
164 context->module_system()->CallModuleMethod(
165 module_name, method_name, &arguments);
168 // This handles the "chrome." root API object in script contexts.
169 class ChromeNativeHandler : public ObjectBackedNativeHandler {
170 public:
171 explicit ChromeNativeHandler(ScriptContext* context)
172 : ObjectBackedNativeHandler(context) {
173 RouteFunction(
174 "GetChrome",
175 base::Bind(&ChromeNativeHandler::GetChrome, base::Unretained(this)));
178 void GetChrome(const v8::FunctionCallbackInfo<v8::Value>& args) {
179 args.GetReturnValue().Set(GetOrCreateChrome(context()));
183 } // namespace
185 Dispatcher::Dispatcher(DispatcherDelegate* delegate)
186 : delegate_(delegate),
187 content_watcher_(new ContentWatcher()),
188 source_map_(&ResourceBundle::GetSharedInstance()),
189 v8_schema_registry_(new V8SchemaRegistry),
190 is_webkit_initialized_(false),
191 user_script_set_manager_observer_(this),
192 webrequest_used_(false) {
193 const base::CommandLine& command_line =
194 *(base::CommandLine::ForCurrentProcess());
195 set_idle_notifications_ =
196 command_line.HasSwitch(switches::kExtensionProcess) ||
197 command_line.HasSwitch(::switches::kSingleProcess);
199 if (set_idle_notifications_) {
200 RenderThread::Get()->SetIdleNotificationDelayInMs(
201 kInitialExtensionIdleHandlerDelayMs);
204 script_context_set_.reset(
205 new ScriptContextSet(&extensions_, &active_extension_ids_));
206 user_script_set_manager_.reset(new UserScriptSetManager(&extensions_));
207 script_injection_manager_.reset(
208 new ScriptInjectionManager(&extensions_, user_script_set_manager_.get()));
209 user_script_set_manager_observer_.Add(user_script_set_manager_.get());
210 request_sender_.reset(new RequestSender(this));
211 PopulateSourceMap();
214 Dispatcher::~Dispatcher() {
217 void Dispatcher::OnRenderFrameCreated(content::RenderFrame* render_frame) {
218 script_injection_manager_->OnRenderFrameCreated(render_frame);
221 bool Dispatcher::IsExtensionActive(const std::string& extension_id) const {
222 bool is_active =
223 active_extension_ids_.find(extension_id) != active_extension_ids_.end();
224 if (is_active)
225 CHECK(extensions_.Contains(extension_id));
226 return is_active;
229 void Dispatcher::DidCreateScriptContext(
230 blink::WebLocalFrame* frame,
231 const v8::Local<v8::Context>& v8_context,
232 int extension_group,
233 int world_id) {
234 const base::TimeTicks start_time = base::TimeTicks::Now();
236 ScriptContext* context = script_context_set_->Register(
237 frame, v8_context, extension_group, world_id);
239 // Initialize origin permissions for content scripts, which can't be
240 // initialized in |OnActivateExtension|.
241 if (context->context_type() == Feature::CONTENT_SCRIPT_CONTEXT)
242 InitOriginPermissions(context->extension());
245 scoped_ptr<ModuleSystem> module_system(
246 new ModuleSystem(context, &source_map_));
247 context->set_module_system(module_system.Pass());
249 ModuleSystem* module_system = context->module_system();
251 // Enable natives in startup.
252 ModuleSystem::NativesEnabledScope natives_enabled_scope(module_system);
254 RegisterNativeHandlers(module_system, context);
256 // chrome.Event is part of the public API (although undocumented). Make it
257 // lazily evalulate to Event from event_bindings.js. For extensions only
258 // though, not all webpages!
259 if (context->extension()) {
260 v8::Local<v8::Object> chrome = AsObjectOrEmpty(GetOrCreateChrome(context));
261 if (!chrome.IsEmpty())
262 module_system->SetLazyField(chrome, "Event", kEventBindings, "Event");
265 UpdateBindingsForContext(context);
267 bool is_within_platform_app = IsWithinPlatformApp();
268 // Inject custom JS into the platform app context.
269 if (is_within_platform_app) {
270 module_system->Require("platformApp");
273 RequireGuestViewModules(context);
274 delegate_->RequireAdditionalModules(context, is_within_platform_app);
276 const base::TimeDelta elapsed = base::TimeTicks::Now() - start_time;
277 switch (context->context_type()) {
278 case Feature::UNSPECIFIED_CONTEXT:
279 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Unspecified",
280 elapsed);
281 break;
282 case Feature::BLESSED_EXTENSION_CONTEXT:
283 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Blessed", elapsed);
284 break;
285 case Feature::UNBLESSED_EXTENSION_CONTEXT:
286 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Unblessed",
287 elapsed);
288 break;
289 case Feature::CONTENT_SCRIPT_CONTEXT:
290 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_ContentScript",
291 elapsed);
292 break;
293 case Feature::WEB_PAGE_CONTEXT:
294 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_WebPage", elapsed);
295 break;
296 case Feature::BLESSED_WEB_PAGE_CONTEXT:
297 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_BlessedWebPage",
298 elapsed);
299 break;
300 case Feature::WEBUI_CONTEXT:
301 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_WebUI", elapsed);
302 break;
305 VLOG(1) << "Num tracked contexts: " << script_context_set_->size();
308 void Dispatcher::WillReleaseScriptContext(
309 blink::WebLocalFrame* frame,
310 const v8::Local<v8::Context>& v8_context,
311 int world_id) {
312 ScriptContext* context = script_context_set_->GetByV8Context(v8_context);
313 if (!context)
314 return;
316 context->DispatchOnUnloadEvent();
317 // TODO(kalman): Make |request_sender| use |context->AddInvalidationObserver|.
318 // In fact |request_sender_| should really be owned by ScriptContext.
319 request_sender_->InvalidateSource(context);
321 script_context_set_->Remove(context);
322 VLOG(1) << "Num tracked contexts: " << script_context_set_->size();
325 void Dispatcher::DidCreateDocumentElement(blink::WebLocalFrame* frame) {
326 // Note: use GetEffectiveDocumentURL not just frame->document()->url()
327 // so that this also injects the stylesheet on about:blank frames that
328 // are hosted in the extension process.
329 GURL effective_document_url = ScriptContext::GetEffectiveDocumentURL(
330 frame, frame->document().url(), true /* match_about_blank */);
332 const Extension* extension =
333 extensions_.GetExtensionOrAppByURL(effective_document_url);
335 if (extension &&
336 (extension->is_extension() || extension->is_platform_app())) {
337 int resource_id = extension->is_platform_app() ? IDR_PLATFORM_APP_CSS
338 : IDR_EXTENSION_FONTS_CSS;
339 std::string stylesheet = ResourceBundle::GetSharedInstance()
340 .GetRawDataResource(resource_id)
341 .as_string();
342 base::ReplaceFirstSubstringAfterOffset(
343 &stylesheet, 0, "$FONTFAMILY", system_font_family_);
344 base::ReplaceFirstSubstringAfterOffset(
345 &stylesheet, 0, "$FONTSIZE", system_font_size_);
347 // Blink doesn't let us define an additional user agent stylesheet, so
348 // we insert the default platform app or extension stylesheet into all
349 // documents that are loaded in each app or extension.
350 frame->document().insertStyleSheet(WebString::fromUTF8(stylesheet));
353 // If this is an extension options page, and the extension has opted into
354 // using Chrome styles, then insert the Chrome extension stylesheet.
355 if (extension && extension->is_extension() &&
356 OptionsPageInfo::ShouldUseChromeStyle(extension) &&
357 effective_document_url == OptionsPageInfo::GetOptionsPage(extension)) {
358 frame->document().insertStyleSheet(
359 WebString::fromUTF8(ResourceBundle::GetSharedInstance()
360 .GetRawDataResource(IDR_EXTENSION_CSS)
361 .as_string()));
364 // In testing, the document lifetime events can happen after the render
365 // process shutdown event.
366 // See: http://crbug.com/21508 and http://crbug.com/500851
367 if (content_watcher_) {
368 content_watcher_->DidCreateDocumentElement(frame);
372 void Dispatcher::OnExtensionResponse(int request_id,
373 bool success,
374 const base::ListValue& response,
375 const std::string& error) {
376 request_sender_->HandleResponse(request_id, success, response, error);
379 void Dispatcher::DispatchEvent(const std::string& extension_id,
380 const std::string& event_name) const {
381 base::ListValue args;
382 args.Set(0, new base::StringValue(event_name));
383 args.Set(1, new base::ListValue());
385 // Needed for Windows compilation, since kEventBindings is declared extern.
386 const char* local_event_bindings = kEventBindings;
387 script_context_set_->ForEach(
388 extension_id, base::Bind(&CallModuleMethod, local_event_bindings,
389 kEventDispatchFunction, &args));
392 void Dispatcher::InvokeModuleSystemMethod(content::RenderFrame* render_frame,
393 const std::string& extension_id,
394 const std::string& module_name,
395 const std::string& function_name,
396 const base::ListValue& args,
397 bool user_gesture) {
398 scoped_ptr<WebScopedUserGesture> web_user_gesture;
399 if (user_gesture)
400 web_user_gesture.reset(new WebScopedUserGesture);
402 script_context_set_->ForEach(
403 extension_id, render_frame,
404 base::Bind(&CallModuleMethod, module_name, function_name, &args));
406 // Reset the idle handler each time there's any activity like event or message
407 // dispatch, for which Invoke is the chokepoint.
408 if (set_idle_notifications_) {
409 RenderThread::Get()->ScheduleIdleHandler(
410 kInitialExtensionIdleHandlerDelayMs);
413 // Tell the browser process when an event has been dispatched with a lazy
414 // background page active.
415 const Extension* extension = extensions_.GetByID(extension_id);
416 if (extension && BackgroundInfo::HasLazyBackgroundPage(extension) &&
417 module_name == kEventBindings &&
418 function_name == kEventDispatchFunction) {
419 content::RenderFrame* background_frame =
420 ExtensionFrameHelper::GetBackgroundPageFrame(extension_id);
421 if (background_frame) {
422 int message_id;
423 args.GetInteger(3, &message_id);
424 background_frame->Send(new ExtensionHostMsg_EventAck(
425 background_frame->GetRoutingID(), message_id));
430 void Dispatcher::ClearPortData(int port_id) {
431 // Only the target port side has entries in |port_to_tab_id_map_|. If
432 // |port_id| is a source port, std::map::erase() will just silently fail
433 // here as a no-op.
434 port_to_tab_id_map_.erase(port_id);
437 // static
438 std::vector<std::pair<std::string, int> > Dispatcher::GetJsResources() {
439 std::vector<std::pair<std::string, int> > resources;
441 // Libraries.
442 resources.push_back(std::make_pair("appView", IDR_APP_VIEW_JS));
443 resources.push_back(std::make_pair("entryIdManager", IDR_ENTRY_ID_MANAGER));
444 resources.push_back(std::make_pair(kEventBindings, IDR_EVENT_BINDINGS_JS));
445 resources.push_back(std::make_pair("extensionOptions",
446 IDR_EXTENSION_OPTIONS_JS));
447 resources.push_back(std::make_pair("extensionOptionsAttributes",
448 IDR_EXTENSION_OPTIONS_ATTRIBUTES_JS));
449 resources.push_back(std::make_pair("extensionOptionsConstants",
450 IDR_EXTENSION_OPTIONS_CONSTANTS_JS));
451 resources.push_back(std::make_pair("extensionOptionsEvents",
452 IDR_EXTENSION_OPTIONS_EVENTS_JS));
453 resources.push_back(std::make_pair("extensionView", IDR_EXTENSION_VIEW_JS));
454 resources.push_back(std::make_pair("extensionViewApiMethods",
455 IDR_EXTENSION_VIEW_API_METHODS_JS));
456 resources.push_back(std::make_pair("extensionViewAttributes",
457 IDR_EXTENSION_VIEW_ATTRIBUTES_JS));
458 resources.push_back(std::make_pair("extensionViewConstants",
459 IDR_EXTENSION_VIEW_CONSTANTS_JS));
460 resources.push_back(std::make_pair("extensionViewEvents",
461 IDR_EXTENSION_VIEW_EVENTS_JS));
462 resources.push_back(std::make_pair(
463 "extensionViewInternal", IDR_EXTENSION_VIEW_INTERNAL_CUSTOM_BINDINGS_JS));
464 resources.push_back(std::make_pair("guestView", IDR_GUEST_VIEW_JS));
465 resources.push_back(std::make_pair("guestViewAttributes",
466 IDR_GUEST_VIEW_ATTRIBUTES_JS));
467 resources.push_back(std::make_pair("guestViewContainer",
468 IDR_GUEST_VIEW_CONTAINER_JS));
469 resources.push_back(std::make_pair("guestViewDeny", IDR_GUEST_VIEW_DENY_JS));
470 resources.push_back(std::make_pair("guestViewEvents",
471 IDR_GUEST_VIEW_EVENTS_JS));
473 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
474 ::switches::kSitePerProcess)) {
475 resources.push_back(std::make_pair("guestViewIframe",
476 IDR_GUEST_VIEW_IFRAME_JS));
477 resources.push_back(std::make_pair("guestViewIframeContainer",
478 IDR_GUEST_VIEW_IFRAME_CONTAINER_JS));
481 resources.push_back(std::make_pair("imageUtil", IDR_IMAGE_UTIL_JS));
482 resources.push_back(std::make_pair("json_schema", IDR_JSON_SCHEMA_JS));
483 resources.push_back(std::make_pair("lastError", IDR_LAST_ERROR_JS));
484 resources.push_back(std::make_pair("messaging", IDR_MESSAGING_JS));
485 resources.push_back(std::make_pair("messaging_utils",
486 IDR_MESSAGING_UTILS_JS));
487 resources.push_back(std::make_pair(kSchemaUtils, IDR_SCHEMA_UTILS_JS));
488 resources.push_back(std::make_pair("sendRequest", IDR_SEND_REQUEST_JS));
489 resources.push_back(std::make_pair("setIcon", IDR_SET_ICON_JS));
490 resources.push_back(std::make_pair("surfaceWorker", IDR_SURFACE_VIEW_JS));
491 resources.push_back(std::make_pair("test", IDR_TEST_CUSTOM_BINDINGS_JS));
492 resources.push_back(
493 std::make_pair("test_environment_specific_bindings",
494 IDR_BROWSER_TEST_ENVIRONMENT_SPECIFIC_BINDINGS_JS));
495 resources.push_back(std::make_pair("uncaught_exception_handler",
496 IDR_UNCAUGHT_EXCEPTION_HANDLER_JS));
497 resources.push_back(std::make_pair("unload_event", IDR_UNLOAD_EVENT_JS));
498 resources.push_back(std::make_pair("utils", IDR_UTILS_JS));
499 resources.push_back(std::make_pair("webRequest",
500 IDR_WEB_REQUEST_CUSTOM_BINDINGS_JS));
501 resources.push_back(
502 std::make_pair("webRequestInternal",
503 IDR_WEB_REQUEST_INTERNAL_CUSTOM_BINDINGS_JS));
504 // Note: webView not webview so that this doesn't interfere with the
505 // chrome.webview API bindings.
506 resources.push_back(std::make_pair("webView", IDR_WEB_VIEW_JS));
507 resources.push_back(std::make_pair("webViewActionRequests",
508 IDR_WEB_VIEW_ACTION_REQUESTS_JS));
509 resources.push_back(std::make_pair("webViewApiMethods",
510 IDR_WEB_VIEW_API_METHODS_JS));
511 resources.push_back(std::make_pair("webViewAttributes",
512 IDR_WEB_VIEW_ATTRIBUTES_JS));
513 resources.push_back(std::make_pair("webViewConstants",
514 IDR_WEB_VIEW_CONSTANTS_JS));
515 resources.push_back(std::make_pair("webViewEvents", IDR_WEB_VIEW_EVENTS_JS));
516 resources.push_back(std::make_pair("webViewInternal",
517 IDR_WEB_VIEW_INTERNAL_CUSTOM_BINDINGS_JS));
518 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
519 ::switches::kSitePerProcess)) {
520 resources.push_back(std::make_pair("webViewIframe",
521 IDR_WEB_VIEW_IFRAME_JS));
523 resources.push_back(
524 std::make_pair(mojo::kBindingsModuleName, IDR_MOJO_BINDINGS_JS));
525 resources.push_back(
526 std::make_pair(mojo::kBufferModuleName, IDR_MOJO_BUFFER_JS));
527 resources.push_back(
528 std::make_pair(mojo::kCodecModuleName, IDR_MOJO_CODEC_JS));
529 resources.push_back(
530 std::make_pair(mojo::kConnectionModuleName, IDR_MOJO_CONNECTION_JS));
531 resources.push_back(
532 std::make_pair(mojo::kConnectorModuleName, IDR_MOJO_CONNECTOR_JS));
533 resources.push_back(
534 std::make_pair(mojo::kRouterModuleName, IDR_MOJO_ROUTER_JS));
535 resources.push_back(
536 std::make_pair(mojo::kUnicodeModuleName, IDR_MOJO_UNICODE_JS));
537 resources.push_back(
538 std::make_pair(mojo::kValidatorModuleName, IDR_MOJO_VALIDATOR_JS));
539 resources.push_back(std::make_pair("async_waiter", IDR_ASYNC_WAITER_JS));
540 resources.push_back(std::make_pair("data_receiver", IDR_DATA_RECEIVER_JS));
541 resources.push_back(std::make_pair("data_sender", IDR_DATA_SENDER_JS));
542 resources.push_back(std::make_pair("keep_alive", IDR_KEEP_ALIVE_JS));
543 resources.push_back(std::make_pair("extensions/common/mojo/keep_alive.mojom",
544 IDR_KEEP_ALIVE_MOJOM_JS));
545 resources.push_back(std::make_pair("device/serial/data_stream.mojom",
546 IDR_DATA_STREAM_MOJOM_JS));
547 resources.push_back(
548 std::make_pair("device/serial/data_stream_serialization.mojom",
549 IDR_DATA_STREAM_SERIALIZATION_MOJOM_JS));
550 resources.push_back(std::make_pair("stash_client", IDR_STASH_CLIENT_JS));
551 resources.push_back(
552 std::make_pair("extensions/common/mojo/stash.mojom", IDR_STASH_MOJOM_JS));
554 // Custom bindings.
555 resources.push_back(
556 std::make_pair("app.runtime", IDR_APP_RUNTIME_CUSTOM_BINDINGS_JS));
557 resources.push_back(
558 std::make_pair("app.window", IDR_APP_WINDOW_CUSTOM_BINDINGS_JS));
559 resources.push_back(
560 std::make_pair("declarativeWebRequest",
561 IDR_DECLARATIVE_WEBREQUEST_CUSTOM_BINDINGS_JS));
562 resources.push_back(
563 std::make_pair("contextMenus", IDR_CONTEXT_MENUS_CUSTOM_BINDINGS_JS));
564 resources.push_back(
565 std::make_pair("contextMenusHandlers", IDR_CONTEXT_MENUS_HANDLERS_JS));
566 resources.push_back(
567 std::make_pair("extension", IDR_EXTENSION_CUSTOM_BINDINGS_JS));
568 resources.push_back(std::make_pair("i18n", IDR_I18N_CUSTOM_BINDINGS_JS));
569 resources.push_back(std::make_pair(
570 "mimeHandlerPrivate", IDR_MIME_HANDLER_PRIVATE_CUSTOM_BINDINGS_JS));
571 resources.push_back(std::make_pair("extensions/common/api/mime_handler.mojom",
572 IDR_MIME_HANDLER_MOJOM_JS));
573 resources.push_back(
574 std::make_pair("mojoPrivate", IDR_MOJO_PRIVATE_CUSTOM_BINDINGS_JS));
575 resources.push_back(
576 std::make_pair("permissions", IDR_PERMISSIONS_CUSTOM_BINDINGS_JS));
577 resources.push_back(std::make_pair("printerProvider",
578 IDR_PRINTER_PROVIDER_CUSTOM_BINDINGS_JS));
579 resources.push_back(
580 std::make_pair("runtime", IDR_RUNTIME_CUSTOM_BINDINGS_JS));
581 resources.push_back(std::make_pair("windowControls", IDR_WINDOW_CONTROLS_JS));
582 resources.push_back(
583 std::make_pair("webViewRequest",
584 IDR_WEB_VIEW_REQUEST_CUSTOM_BINDINGS_JS));
585 resources.push_back(std::make_pair("binding", IDR_BINDING_JS));
587 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
588 switches::kEnableMojoSerialService)) {
589 resources.push_back(
590 std::make_pair("serial", IDR_SERIAL_CUSTOM_BINDINGS_JS));
592 resources.push_back(std::make_pair("serial_service", IDR_SERIAL_SERVICE_JS));
593 resources.push_back(
594 std::make_pair("device/serial/serial.mojom", IDR_SERIAL_MOJOM_JS));
595 resources.push_back(std::make_pair("device/serial/serial_serialization.mojom",
596 IDR_SERIAL_SERIALIZATION_MOJOM_JS));
598 // Custom types sources.
599 resources.push_back(std::make_pair("StorageArea", IDR_STORAGE_AREA_JS));
601 // Platform app sources that are not API-specific..
602 resources.push_back(std::make_pair("platformApp", IDR_PLATFORM_APP_JS));
604 #if defined(ENABLE_MEDIA_ROUTER)
605 resources.push_back(
606 std::make_pair("chrome/browser/media/router/media_router.mojom",
607 IDR_MEDIA_ROUTER_MOJOM_JS));
608 resources.push_back(
609 std::make_pair("media_router_bindings", IDR_MEDIA_ROUTER_BINDINGS_JS));
610 #endif // defined(ENABLE_MEDIA_ROUTER)
612 return resources;
615 // NOTE: please use the naming convention "foo_natives" for these.
616 // static
617 void Dispatcher::RegisterNativeHandlers(ModuleSystem* module_system,
618 ScriptContext* context,
619 Dispatcher* dispatcher,
620 RequestSender* request_sender,
621 V8SchemaRegistry* v8_schema_registry) {
622 module_system->RegisterNativeHandler(
623 "chrome", scoped_ptr<NativeHandler>(new ChromeNativeHandler(context)));
624 module_system->RegisterNativeHandler(
625 "lazy_background_page",
626 scoped_ptr<NativeHandler>(new LazyBackgroundPageNativeHandler(context)));
627 module_system->RegisterNativeHandler(
628 "logging", scoped_ptr<NativeHandler>(new LoggingNativeHandler(context)));
629 module_system->RegisterNativeHandler("schema_registry",
630 v8_schema_registry->AsNativeHandler());
631 module_system->RegisterNativeHandler(
632 "print", scoped_ptr<NativeHandler>(new PrintNativeHandler(context)));
633 module_system->RegisterNativeHandler(
634 "test_features",
635 scoped_ptr<NativeHandler>(new TestFeaturesNativeHandler(context)));
636 module_system->RegisterNativeHandler(
637 "user_gestures",
638 scoped_ptr<NativeHandler>(new UserGesturesNativeHandler(context)));
639 module_system->RegisterNativeHandler(
640 "utils", scoped_ptr<NativeHandler>(new UtilsNativeHandler(context)));
641 module_system->RegisterNativeHandler(
642 "v8_context",
643 scoped_ptr<NativeHandler>(
644 new V8ContextNativeHandler(context, dispatcher)));
645 module_system->RegisterNativeHandler(
646 "event_natives", scoped_ptr<NativeHandler>(new EventBindings(context)));
647 module_system->RegisterNativeHandler(
648 "messaging_natives",
649 scoped_ptr<NativeHandler>(MessagingBindings::Get(dispatcher, context)));
650 module_system->RegisterNativeHandler(
651 "apiDefinitions",
652 scoped_ptr<NativeHandler>(
653 new ApiDefinitionsNatives(dispatcher, context)));
654 module_system->RegisterNativeHandler(
655 "sendRequest",
656 scoped_ptr<NativeHandler>(
657 new SendRequestNatives(request_sender, context)));
658 module_system->RegisterNativeHandler(
659 "setIcon",
660 scoped_ptr<NativeHandler>(new SetIconNatives(context)));
661 module_system->RegisterNativeHandler(
662 "activityLogger",
663 scoped_ptr<NativeHandler>(new APIActivityLogger(context)));
664 module_system->RegisterNativeHandler(
665 "renderFrameObserverNatives",
666 scoped_ptr<NativeHandler>(new RenderFrameObserverNatives(context)));
668 // Natives used by multiple APIs.
669 module_system->RegisterNativeHandler(
670 "file_system_natives",
671 scoped_ptr<NativeHandler>(new FileSystemNatives(context)));
673 // Custom bindings.
674 module_system->RegisterNativeHandler(
675 "app_runtime",
676 scoped_ptr<NativeHandler>(new AppRuntimeCustomBindings(context)));
677 // |dispatcher| is null in unit tests.
678 const ScriptContextSet* script_context_set = dispatcher ?
679 &dispatcher->script_context_set() : nullptr;
680 module_system->RegisterNativeHandler(
681 "app_window_natives",
682 scoped_ptr<NativeHandler>(new AppWindowCustomBindings(
683 script_context_set, context)));
684 module_system->RegisterNativeHandler(
685 "blob_natives",
686 scoped_ptr<NativeHandler>(new BlobNativeHandler(context)));
687 module_system->RegisterNativeHandler(
688 "context_menus",
689 scoped_ptr<NativeHandler>(new ContextMenusCustomBindings(context)));
690 module_system->RegisterNativeHandler(
691 "css_natives", scoped_ptr<NativeHandler>(new CssNativeHandler(context)));
692 module_system->RegisterNativeHandler(
693 "document_natives",
694 scoped_ptr<NativeHandler>(new DocumentCustomBindings(context)));
695 module_system->RegisterNativeHandler(
696 "guest_view_internal",
697 scoped_ptr<NativeHandler>(
698 new GuestViewInternalCustomBindings(context)));
699 module_system->RegisterNativeHandler(
700 "i18n", scoped_ptr<NativeHandler>(new I18NCustomBindings(context)));
701 module_system->RegisterNativeHandler(
702 "id_generator",
703 scoped_ptr<NativeHandler>(new IdGeneratorCustomBindings(context)));
704 module_system->RegisterNativeHandler(
705 "runtime", scoped_ptr<NativeHandler>(new RuntimeCustomBindings(context)));
708 void Dispatcher::LoadExtensionForTest(const Extension* extension) {
709 CHECK(extensions_.Insert(extension));
712 bool Dispatcher::OnControlMessageReceived(const IPC::Message& message) {
713 bool handled = true;
714 IPC_BEGIN_MESSAGE_MAP(Dispatcher, message)
715 IPC_MESSAGE_HANDLER(ExtensionMsg_ActivateExtension, OnActivateExtension)
716 IPC_MESSAGE_HANDLER(ExtensionMsg_CancelSuspend, OnCancelSuspend)
717 IPC_MESSAGE_HANDLER(ExtensionMsg_DeliverMessage, OnDeliverMessage)
718 IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnConnect, OnDispatchOnConnect)
719 IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnDisconnect, OnDispatchOnDisconnect)
720 IPC_MESSAGE_HANDLER(ExtensionMsg_Loaded, OnLoaded)
721 IPC_MESSAGE_HANDLER(ExtensionMsg_MessageInvoke, OnMessageInvoke)
722 IPC_MESSAGE_HANDLER(ExtensionMsg_SetChannel, OnSetChannel)
723 IPC_MESSAGE_HANDLER(ExtensionMsg_SetFunctionNames, OnSetFunctionNames)
724 IPC_MESSAGE_HANDLER(ExtensionMsg_SetScriptingWhitelist,
725 OnSetScriptingWhitelist)
726 IPC_MESSAGE_HANDLER(ExtensionMsg_SetSystemFont, OnSetSystemFont)
727 IPC_MESSAGE_HANDLER(ExtensionMsg_ShouldSuspend, OnShouldSuspend)
728 IPC_MESSAGE_HANDLER(ExtensionMsg_Suspend, OnSuspend)
729 IPC_MESSAGE_HANDLER(ExtensionMsg_TransferBlobs, OnTransferBlobs)
730 IPC_MESSAGE_HANDLER(ExtensionMsg_Unloaded, OnUnloaded)
731 IPC_MESSAGE_HANDLER(ExtensionMsg_UpdatePermissions, OnUpdatePermissions)
732 IPC_MESSAGE_HANDLER(ExtensionMsg_UpdateTabSpecificPermissions,
733 OnUpdateTabSpecificPermissions)
734 IPC_MESSAGE_HANDLER(ExtensionMsg_ClearTabSpecificPermissions,
735 OnClearTabSpecificPermissions)
736 IPC_MESSAGE_HANDLER(ExtensionMsg_UsingWebRequestAPI, OnUsingWebRequestAPI)
737 IPC_MESSAGE_FORWARD(ExtensionMsg_WatchPages,
738 content_watcher_.get(),
739 ContentWatcher::OnWatchPages)
740 IPC_MESSAGE_UNHANDLED(handled = false)
741 IPC_END_MESSAGE_MAP()
743 return handled;
746 void Dispatcher::WebKitInitialized() {
747 RenderThread::Get()->RegisterExtension(SafeBuiltins::CreateV8Extension());
749 // For extensions, we want to ensure we call the IdleHandler every so often,
750 // even if the extension keeps up activity.
751 if (set_idle_notifications_) {
752 forced_idle_timer_.reset(new base::RepeatingTimer<content::RenderThread>);
753 forced_idle_timer_->Start(
754 FROM_HERE,
755 base::TimeDelta::FromMilliseconds(kMaxExtensionIdleHandlerDelayMs),
756 RenderThread::Get(),
757 &RenderThread::IdleHandler);
760 // Initialize host permissions for any extensions that were activated before
761 // WebKit was initialized.
762 for (const std::string& extension_id : active_extension_ids_) {
763 const Extension* extension = extensions_.GetByID(extension_id);
764 CHECK(extension);
765 InitOriginPermissions(extension);
768 EnableCustomElementWhiteList();
770 is_webkit_initialized_ = true;
773 void Dispatcher::IdleNotification() {
774 if (set_idle_notifications_ && forced_idle_timer_) {
775 // Dampen the forced delay as well if the extension stays idle for long
776 // periods of time. (forced_idle_timer_ can be NULL after
777 // OnRenderProcessShutdown has been called.)
778 int64 forced_delay_ms =
779 std::max(RenderThread::Get()->GetIdleNotificationDelayInMs(),
780 kMaxExtensionIdleHandlerDelayMs);
781 forced_idle_timer_->Stop();
782 forced_idle_timer_->Start(
783 FROM_HERE,
784 base::TimeDelta::FromMilliseconds(forced_delay_ms),
785 RenderThread::Get(),
786 &RenderThread::IdleHandler);
790 void Dispatcher::OnRenderProcessShutdown() {
791 v8_schema_registry_.reset();
792 forced_idle_timer_.reset();
793 content_watcher_.reset();
796 void Dispatcher::OnActivateExtension(const std::string& extension_id) {
797 const Extension* extension = extensions_.GetByID(extension_id);
798 if (!extension) {
799 // Extension was activated but was never loaded. This probably means that
800 // the renderer failed to load it (or the browser failed to tell us when it
801 // did). Failures shouldn't happen, but instead of crashing there (which
802 // executes on all renderers) be conservative and only crash in the renderer
803 // of the extension which failed to load; this one.
804 std::string& error = extension_load_errors_[extension_id];
805 char minidump[256];
806 base::debug::Alias(&minidump);
807 base::snprintf(minidump,
808 arraysize(minidump),
809 "e::dispatcher:%s:%s",
810 extension_id.c_str(),
811 error.c_str());
812 LOG(FATAL) << extension_id << " was never loaded: " << error;
815 active_extension_ids_.insert(extension_id);
817 // This is called when starting a new extension page, so start the idle
818 // handler ticking.
819 RenderThread::Get()->ScheduleIdleHandler(kInitialExtensionIdleHandlerDelayMs);
821 if (is_webkit_initialized_) {
822 DOMActivityLogger::AttachToWorld(
823 DOMActivityLogger::kMainWorldId, extension_id);
825 InitOriginPermissions(extension);
828 UpdateActiveExtensions();
831 void Dispatcher::OnCancelSuspend(const std::string& extension_id) {
832 DispatchEvent(extension_id, kOnSuspendCanceledEvent);
835 void Dispatcher::OnDeliverMessage(int target_port_id, const Message& message) {
836 scoped_ptr<RequestSender::ScopedTabID> scoped_tab_id;
837 std::map<int, int>::const_iterator it =
838 port_to_tab_id_map_.find(target_port_id);
839 if (it != port_to_tab_id_map_.end()) {
840 scoped_tab_id.reset(
841 new RequestSender::ScopedTabID(request_sender(), it->second));
844 MessagingBindings::DeliverMessage(*script_context_set_, target_port_id,
845 message,
846 NULL); // All render frames.
849 void Dispatcher::OnDispatchOnConnect(
850 int target_port_id,
851 const std::string& channel_name,
852 const ExtensionMsg_TabConnectionInfo& source,
853 const ExtensionMsg_ExternalConnectionInfo& info,
854 const std::string& tls_channel_id) {
855 DCHECK(!ContainsKey(port_to_tab_id_map_, target_port_id));
856 DCHECK_EQ(1, target_port_id % 2); // target renderer ports have odd IDs.
857 int sender_tab_id = -1;
858 source.tab.GetInteger("id", &sender_tab_id);
859 port_to_tab_id_map_[target_port_id] = sender_tab_id;
861 MessagingBindings::DispatchOnConnect(*script_context_set_, target_port_id,
862 channel_name, source, info,
863 tls_channel_id,
864 NULL); // All render frames.
867 void Dispatcher::OnDispatchOnDisconnect(int port_id,
868 const std::string& error_message) {
869 MessagingBindings::DispatchOnDisconnect(*script_context_set_, port_id,
870 error_message,
871 NULL); // All render frames.
874 void Dispatcher::OnLoaded(
875 const std::vector<ExtensionMsg_Loaded_Params>& loaded_extensions) {
876 for (const auto& param : loaded_extensions) {
877 std::string error;
878 scoped_refptr<const Extension> extension = param.ConvertToExtension(&error);
879 if (!extension.get()) {
880 NOTREACHED() << error;
881 // Note: in tests |param.id| has been observed to be empty (see comment
882 // just below) so this isn't all that reliable.
883 extension_load_errors_[param.id] = error;
884 continue;
887 // TODO(kalman): This test is deliberately not a CHECK (though I wish it
888 // could be) and uses extension->id() not params.id:
889 // 1. For some reason params.id can be empty. I've only seen it with
890 // the webstore extension, in tests, and I've spent some time trying to
891 // figure out why - but cost/benefit won.
892 // 2. The browser only sends this IPC to RenderProcessHosts once, but the
893 // Dispatcher is attached to a RenderThread. Presumably there is a
894 // mismatch there. In theory one would think it's possible for the
895 // browser to figure this out itself - but again, cost/benefit.
896 if (!extensions_.Contains(extension->id()))
897 extensions_.Insert(extension);
900 // Update the available bindings for all contexts. These may have changed if
901 // an externally_connectable extension was loaded that can connect to an
902 // open webpage.
903 UpdateBindings("");
906 void Dispatcher::OnMessageInvoke(const std::string& extension_id,
907 const std::string& module_name,
908 const std::string& function_name,
909 const base::ListValue& args,
910 bool user_gesture) {
911 InvokeModuleSystemMethod(
912 NULL, extension_id, module_name, function_name, args, user_gesture);
915 void Dispatcher::OnSetChannel(int channel) {
916 delegate_->SetChannel(channel);
917 AddChannelSpecificFeatures();
920 void Dispatcher::OnSetFunctionNames(const std::vector<std::string>& names) {
921 function_names_.clear();
922 for (size_t i = 0; i < names.size(); ++i)
923 function_names_.insert(names[i]);
926 void Dispatcher::OnSetScriptingWhitelist(
927 const ExtensionsClient::ScriptingWhitelist& extension_ids) {
928 ExtensionsClient::Get()->SetScriptingWhitelist(extension_ids);
931 void Dispatcher::OnSetSystemFont(const std::string& font_family,
932 const std::string& font_size) {
933 system_font_family_ = font_family;
934 system_font_size_ = font_size;
937 void Dispatcher::OnShouldSuspend(const std::string& extension_id,
938 uint64 sequence_id) {
939 RenderThread::Get()->Send(
940 new ExtensionHostMsg_ShouldSuspendAck(extension_id, sequence_id));
943 void Dispatcher::OnSuspend(const std::string& extension_id) {
944 // Dispatch the suspend event. This doesn't go through the standard event
945 // dispatch machinery because it requires special handling. We need to let
946 // the browser know when we are starting and stopping the event dispatch, so
947 // that it still considers the extension idle despite any activity the suspend
948 // event creates.
949 DispatchEvent(extension_id, kOnSuspendEvent);
950 RenderThread::Get()->Send(new ExtensionHostMsg_SuspendAck(extension_id));
953 void Dispatcher::OnTransferBlobs(const std::vector<std::string>& blob_uuids) {
954 RenderThread::Get()->Send(new ExtensionHostMsg_TransferBlobsAck(blob_uuids));
957 void Dispatcher::OnUnloaded(const std::string& id) {
958 // See comment in OnLoaded for why it would be nice, but perhaps incorrect,
959 // to CHECK here rather than guarding.
960 if (!extensions_.Remove(id))
961 return;
963 active_extension_ids_.erase(id);
965 script_injection_manager_->OnExtensionUnloaded(id);
967 // If the extension is later reloaded with a different set of permissions,
968 // we'd like it to get a new isolated world ID, so that it can pick up the
969 // changed origin whitelist.
970 ScriptInjection::RemoveIsolatedWorld(id);
972 // Invalidate all of the contexts that were removed.
973 // TODO(kalman): add an invalidation observer interface to ScriptContext.
974 std::set<ScriptContext*> removed_contexts =
975 script_context_set_->OnExtensionUnloaded(id);
976 for (ScriptContext* context : removed_contexts) {
977 request_sender_->InvalidateSource(context);
980 // Update the available bindings for the remaining contexts. These may have
981 // changed if an externally_connectable extension is unloaded and a webpage
982 // is no longer accessible.
983 UpdateBindings("");
985 // Invalidates the messages map for the extension in case the extension is
986 // reloaded with a new messages map.
987 EraseL10nMessagesMap(id);
989 // We don't do anything with existing platform-app stylesheets. They will
990 // stay resident, but the URL pattern corresponding to the unloaded
991 // extension's URL just won't match anything anymore.
994 void Dispatcher::OnUpdatePermissions(
995 const ExtensionMsg_UpdatePermissions_Params& params) {
996 const Extension* extension = extensions_.GetByID(params.extension_id);
997 if (!extension)
998 return;
1000 scoped_refptr<const PermissionSet> active =
1001 params.active_permissions.ToPermissionSet();
1002 scoped_refptr<const PermissionSet> withheld =
1003 params.withheld_permissions.ToPermissionSet();
1005 if (is_webkit_initialized_) {
1006 UpdateOriginPermissions(
1007 extension->url(),
1008 extension->permissions_data()->GetEffectiveHostPermissions(),
1009 active->effective_hosts());
1012 extension->permissions_data()->SetPermissions(active, withheld);
1013 UpdateBindings(extension->id());
1016 void Dispatcher::OnUpdateTabSpecificPermissions(const GURL& visible_url,
1017 const std::string& extension_id,
1018 const URLPatternSet& new_hosts,
1019 bool update_origin_whitelist,
1020 int tab_id) {
1021 const Extension* extension = extensions_.GetByID(extension_id);
1022 if (!extension)
1023 return;
1025 URLPatternSet old_effective =
1026 extension->permissions_data()->GetEffectiveHostPermissions();
1027 extension->permissions_data()->UpdateTabSpecificPermissions(
1028 tab_id,
1029 new extensions::PermissionSet(extensions::APIPermissionSet(),
1030 extensions::ManifestPermissionSet(),
1031 new_hosts,
1032 extensions::URLPatternSet()));
1034 if (is_webkit_initialized_ && update_origin_whitelist) {
1035 UpdateOriginPermissions(
1036 extension->url(),
1037 old_effective,
1038 extension->permissions_data()->GetEffectiveHostPermissions());
1042 void Dispatcher::OnClearTabSpecificPermissions(
1043 const std::vector<std::string>& extension_ids,
1044 bool update_origin_whitelist,
1045 int tab_id) {
1046 for (const std::string& id : extension_ids) {
1047 const Extension* extension = extensions_.GetByID(id);
1048 if (extension) {
1049 URLPatternSet old_effective =
1050 extension->permissions_data()->GetEffectiveHostPermissions();
1051 extension->permissions_data()->ClearTabSpecificPermissions(tab_id);
1052 if (is_webkit_initialized_ && update_origin_whitelist) {
1053 UpdateOriginPermissions(
1054 extension->url(),
1055 old_effective,
1056 extension->permissions_data()->GetEffectiveHostPermissions());
1062 void Dispatcher::OnUsingWebRequestAPI(bool webrequest_used) {
1063 webrequest_used_ = webrequest_used;
1066 void Dispatcher::OnUserScriptsUpdated(const std::set<HostID>& changed_hosts,
1067 const std::vector<UserScript*>& scripts) {
1068 UpdateActiveExtensions();
1071 void Dispatcher::UpdateActiveExtensions() {
1072 std::set<std::string> active_extensions = active_extension_ids_;
1073 user_script_set_manager_->GetAllActiveExtensionIds(&active_extensions);
1074 delegate_->OnActiveExtensionsUpdated(active_extensions);
1077 void Dispatcher::InitOriginPermissions(const Extension* extension) {
1078 delegate_->InitOriginPermissions(extension,
1079 IsExtensionActive(extension->id()));
1080 UpdateOriginPermissions(
1081 extension->url(),
1082 URLPatternSet(), // No old permissions.
1083 extension->permissions_data()->GetEffectiveHostPermissions());
1086 void Dispatcher::UpdateOriginPermissions(const GURL& extension_url,
1087 const URLPatternSet& old_patterns,
1088 const URLPatternSet& new_patterns) {
1089 static const char* kSchemes[] = {
1090 url::kHttpScheme,
1091 url::kHttpsScheme,
1092 url::kFileScheme,
1093 content::kChromeUIScheme,
1094 url::kFtpScheme,
1095 #if defined(OS_CHROMEOS)
1096 content::kExternalFileScheme,
1097 #endif
1098 extensions::kExtensionScheme,
1100 for (size_t i = 0; i < arraysize(kSchemes); ++i) {
1101 const char* scheme = kSchemes[i];
1102 // Remove all old patterns...
1103 for (URLPatternSet::const_iterator pattern = old_patterns.begin();
1104 pattern != old_patterns.end(); ++pattern) {
1105 if (pattern->MatchesScheme(scheme)) {
1106 WebSecurityPolicy::removeOriginAccessWhitelistEntry(
1107 extension_url,
1108 WebString::fromUTF8(scheme),
1109 WebString::fromUTF8(pattern->host()),
1110 pattern->match_subdomains());
1113 // ...And add the new ones.
1114 for (URLPatternSet::const_iterator pattern = new_patterns.begin();
1115 pattern != new_patterns.end(); ++pattern) {
1116 if (pattern->MatchesScheme(scheme)) {
1117 WebSecurityPolicy::addOriginAccessWhitelistEntry(
1118 extension_url,
1119 WebString::fromUTF8(scheme),
1120 WebString::fromUTF8(pattern->host()),
1121 pattern->match_subdomains());
1127 void Dispatcher::EnableCustomElementWhiteList() {
1128 blink::WebCustomElement::addEmbedderCustomElementName("appview");
1129 blink::WebCustomElement::addEmbedderCustomElementName("appviewbrowserplugin");
1130 blink::WebCustomElement::addEmbedderCustomElementName("extensionoptions");
1131 blink::WebCustomElement::addEmbedderCustomElementName(
1132 "extensionoptionsbrowserplugin");
1133 blink::WebCustomElement::addEmbedderCustomElementName("extensionview");
1134 blink::WebCustomElement::addEmbedderCustomElementName(
1135 "extensionviewbrowserplugin");
1136 blink::WebCustomElement::addEmbedderCustomElementName("webview");
1137 blink::WebCustomElement::addEmbedderCustomElementName("webviewbrowserplugin");
1138 blink::WebCustomElement::addEmbedderCustomElementName("surfaceview");
1139 blink::WebCustomElement::addEmbedderCustomElementName(
1140 "surfaceviewbrowserplugin");
1143 void Dispatcher::UpdateBindings(const std::string& extension_id) {
1144 script_context_set().ForEach(extension_id,
1145 base::Bind(&Dispatcher::UpdateBindingsForContext,
1146 base::Unretained(this)));
1149 void Dispatcher::UpdateBindingsForContext(ScriptContext* context) {
1150 v8::HandleScope handle_scope(context->isolate());
1151 v8::Context::Scope context_scope(context->v8_context());
1153 // TODO(kalman): Make the bindings registration have zero overhead then run
1154 // the same code regardless of context type.
1155 switch (context->context_type()) {
1156 case Feature::UNSPECIFIED_CONTEXT:
1157 case Feature::WEB_PAGE_CONTEXT:
1158 case Feature::BLESSED_WEB_PAGE_CONTEXT:
1159 // Web page context; it's too expensive to run the full bindings code.
1160 // Hard-code that the app and webstore APIs are available...
1161 if (context->GetAvailability("app").is_available())
1162 RegisterBinding("app", context);
1163 if (context->GetAvailability("webstore").is_available())
1164 RegisterBinding("webstore", context);
1165 if (IsRuntimeAvailableToContext(context))
1166 RegisterBinding("runtime", context);
1167 UpdateContentCapabilities(context);
1168 break;
1170 case Feature::BLESSED_EXTENSION_CONTEXT:
1171 case Feature::UNBLESSED_EXTENSION_CONTEXT:
1172 case Feature::CONTENT_SCRIPT_CONTEXT:
1173 case Feature::WEBUI_CONTEXT: {
1174 // Extension context; iterate through all the APIs and bind the available
1175 // ones.
1176 const FeatureProvider* api_feature_provider =
1177 FeatureProvider::GetAPIFeatures();
1178 const std::vector<std::string>& apis =
1179 api_feature_provider->GetAllFeatureNames();
1180 for (std::vector<std::string>::const_iterator it = apis.begin();
1181 it != apis.end();
1182 ++it) {
1183 const std::string& api_name = *it;
1184 Feature* feature = api_feature_provider->GetFeature(api_name);
1185 DCHECK(feature);
1187 // Internal APIs are included via require(api_name) from internal code
1188 // rather than chrome[api_name].
1189 if (feature->IsInternal())
1190 continue;
1192 // If this API has a parent feature (and isn't marked 'noparent'),
1193 // then this must be a function or event, so we should not register.
1194 if (api_feature_provider->GetParent(feature) != NULL)
1195 continue;
1197 // Skip chrome.test if this isn't a test.
1198 if (api_name == "test" &&
1199 !base::CommandLine::ForCurrentProcess()->HasSwitch(
1200 ::switches::kTestType)) {
1201 continue;
1204 if (context->IsAnyFeatureAvailableToContext(*feature))
1205 RegisterBinding(api_name, context);
1207 break;
1212 void Dispatcher::RegisterBinding(const std::string& api_name,
1213 ScriptContext* context) {
1214 std::string bind_name;
1215 v8::Local<v8::Object> bind_object =
1216 GetOrCreateBindObjectIfAvailable(api_name, &bind_name, context);
1218 // Empty if the bind object failed to be created, probably because the
1219 // extension overrode chrome with a non-object, e.g. window.chrome = true.
1220 if (bind_object.IsEmpty())
1221 return;
1223 v8::Local<v8::String> v8_bind_name =
1224 v8::String::NewFromUtf8(context->isolate(), bind_name.c_str());
1225 if (bind_object->HasRealNamedProperty(v8_bind_name)) {
1226 // The bind object may already have the property if the API has been
1227 // registered before (or if the extension has put something there already,
1228 // but, whatevs).
1230 // In the former case, we need to re-register the bindings for the APIs
1231 // which the extension now has permissions for (if any), but not touch any
1232 // others so that we don't destroy state such as event listeners.
1234 // TODO(kalman): Only register available APIs to make this all moot.
1235 if (bind_object->HasRealNamedCallbackProperty(v8_bind_name))
1236 return; // lazy binding still there, nothing to do
1237 if (bind_object->Get(v8_bind_name)->IsObject())
1238 return; // binding has already been fully installed
1241 ModuleSystem* module_system = context->module_system();
1242 if (!source_map_.Contains(api_name)) {
1243 module_system->RegisterNativeHandler(
1244 api_name,
1245 scoped_ptr<NativeHandler>(new BindingGeneratingNativeHandler(
1246 context, api_name, "binding")));
1247 module_system->SetNativeLazyField(
1248 bind_object, bind_name, api_name, "binding");
1249 } else {
1250 module_system->SetLazyField(bind_object, bind_name, api_name, "binding");
1254 // NOTE: please use the naming convention "foo_natives" for these.
1255 void Dispatcher::RegisterNativeHandlers(ModuleSystem* module_system,
1256 ScriptContext* context) {
1257 RegisterNativeHandlers(module_system,
1258 context,
1259 this,
1260 request_sender_.get(),
1261 v8_schema_registry_.get());
1262 const Extension* extension = context->extension();
1263 int manifest_version = extension ? extension->manifest_version() : 1;
1264 bool is_component_extension =
1265 extension && Manifest::IsComponentLocation(extension->location());
1266 bool send_request_disabled =
1267 (extension && Manifest::IsUnpackedLocation(extension->location()) &&
1268 BackgroundInfo::HasLazyBackgroundPage(extension));
1269 module_system->RegisterNativeHandler(
1270 "process",
1271 scoped_ptr<NativeHandler>(new ProcessInfoNativeHandler(
1272 context,
1273 context->GetExtensionID(),
1274 context->GetContextTypeDescription(),
1275 ExtensionsRendererClient::Get()->IsIncognitoProcess(),
1276 is_component_extension,
1277 manifest_version,
1278 send_request_disabled)));
1280 delegate_->RegisterNativeHandlers(this, module_system, context);
1283 bool Dispatcher::IsRuntimeAvailableToContext(ScriptContext* context) {
1284 if (extensions::FeatureSwitch::surface_worker()->IsEnabled() &&
1285 context->GetAvailability("surfaceWorkerInternal").is_available()) {
1286 return true;
1288 for (const auto& extension : extensions_) {
1289 ExternallyConnectableInfo* info = static_cast<ExternallyConnectableInfo*>(
1290 extension->GetManifestData(manifest_keys::kExternallyConnectable));
1291 if (info && info->matches.MatchesURL(context->GetURL()))
1292 return true;
1294 return false;
1297 void Dispatcher::UpdateContentCapabilities(ScriptContext* context) {
1298 APIPermissionSet permissions;
1299 for (const auto& extension : extensions_) {
1300 const ContentCapabilitiesInfo& info =
1301 ContentCapabilitiesInfo::Get(extension.get());
1302 if (info.url_patterns.MatchesURL(context->GetURL())) {
1303 APIPermissionSet new_permissions;
1304 APIPermissionSet::Union(permissions, info.permissions, &new_permissions);
1305 permissions = new_permissions;
1308 context->SetContentCapabilities(permissions);
1311 void Dispatcher::PopulateSourceMap() {
1312 const std::vector<std::pair<std::string, int> > resources = GetJsResources();
1313 for (std::vector<std::pair<std::string, int> >::const_iterator resource =
1314 resources.begin();
1315 resource != resources.end();
1316 ++resource) {
1317 source_map_.RegisterSource(resource->first, resource->second);
1319 delegate_->PopulateSourceMap(&source_map_);
1322 bool Dispatcher::IsWithinPlatformApp() {
1323 for (std::set<std::string>::iterator iter = active_extension_ids_.begin();
1324 iter != active_extension_ids_.end();
1325 ++iter) {
1326 const Extension* extension = extensions_.GetByID(*iter);
1327 if (extension && extension->is_platform_app())
1328 return true;
1330 return false;
1333 v8::Local<v8::Object> Dispatcher::GetOrCreateObject(
1334 const v8::Local<v8::Object>& object,
1335 const std::string& field,
1336 v8::Isolate* isolate) {
1337 v8::Local<v8::String> key = v8::String::NewFromUtf8(isolate, field.c_str());
1338 // If the object has a callback property, it is assumed it is an unavailable
1339 // API, so it is safe to delete. This is checked before GetOrCreateObject is
1340 // called.
1341 if (object->HasRealNamedCallbackProperty(key)) {
1342 object->Delete(key);
1343 } else if (object->HasRealNamedProperty(key)) {
1344 v8::Local<v8::Value> value = object->Get(key);
1345 CHECK(value->IsObject());
1346 return v8::Local<v8::Object>::Cast(value);
1349 v8::Local<v8::Object> new_object = v8::Object::New(isolate);
1350 object->Set(key, new_object);
1351 return new_object;
1354 v8::Local<v8::Object> Dispatcher::GetOrCreateBindObjectIfAvailable(
1355 const std::string& api_name,
1356 std::string* bind_name,
1357 ScriptContext* context) {
1358 std::vector<std::string> split;
1359 base::SplitString(api_name, '.', &split);
1361 v8::Local<v8::Object> bind_object;
1363 // Check if this API has an ancestor. If the API's ancestor is available and
1364 // the API is not available, don't install the bindings for this API. If
1365 // the API is available and its ancestor is not, delete the ancestor and
1366 // install the bindings for the API. This is to prevent loading the ancestor
1367 // API schema if it will not be needed.
1369 // For example:
1370 // If app is available and app.window is not, just install app.
1371 // If app.window is available and app is not, delete app and install
1372 // app.window on a new object so app does not have to be loaded.
1373 const FeatureProvider* api_feature_provider =
1374 FeatureProvider::GetAPIFeatures();
1375 std::string ancestor_name;
1376 bool only_ancestor_available = false;
1378 for (size_t i = 0; i < split.size() - 1; ++i) {
1379 ancestor_name += (i ? "." : "") + split[i];
1380 if (api_feature_provider->GetFeature(ancestor_name) &&
1381 context->GetAvailability(ancestor_name).is_available() &&
1382 !context->GetAvailability(api_name).is_available()) {
1383 only_ancestor_available = true;
1384 break;
1387 if (bind_object.IsEmpty()) {
1388 bind_object = AsObjectOrEmpty(GetOrCreateChrome(context));
1389 if (bind_object.IsEmpty())
1390 return v8::Local<v8::Object>();
1392 bind_object = GetOrCreateObject(bind_object, split[i], context->isolate());
1395 if (only_ancestor_available)
1396 return v8::Local<v8::Object>();
1398 if (bind_name)
1399 *bind_name = split.back();
1401 return bind_object.IsEmpty() ? AsObjectOrEmpty(GetOrCreateChrome(context))
1402 : bind_object;
1405 void Dispatcher::RequireGuestViewModules(ScriptContext* context) {
1406 Feature::Context context_type = context->context_type();
1407 ModuleSystem* module_system = context->module_system();
1409 // Require AppView.
1410 if (context->GetAvailability("appViewEmbedderInternal").is_available()) {
1411 module_system->Require("appView");
1414 // Require ExtensionOptions.
1415 if (context->GetAvailability("extensionOptionsInternal").is_available()) {
1416 module_system->Require("extensionOptions");
1417 module_system->Require("extensionOptionsAttributes");
1420 // Require ExtensionView.
1421 if (context->GetAvailability("extensionViewInternal").is_available()) {
1422 module_system->Require("extensionView");
1423 module_system->Require("extensionViewApiMethods");
1424 module_system->Require("extensionViewAttributes");
1427 // Require SurfaceView.
1428 if (extensions::FeatureSwitch::surface_worker()->IsEnabled() &&
1429 context->GetAvailability("surfaceWorkerInternal").is_available()) {
1430 module_system->Require("surfaceWorker");
1433 // Require WebView.
1434 if (context->GetAvailability("webViewInternal").is_available()) {
1435 module_system->Require("webView");
1436 module_system->Require("webViewApiMethods");
1437 module_system->Require("webViewAttributes");
1439 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1440 ::switches::kSitePerProcess)) {
1441 module_system->Require("webViewIframe");
1445 // The "guestViewDeny" module must always be loaded last. It registers
1446 // error-providing custom elements for the GuestView types that are not
1447 // available, and thus all of those types must have been checked and loaded
1448 // (or not loaded) beforehand.
1449 if (context_type == Feature::BLESSED_EXTENSION_CONTEXT) {
1450 module_system->Require("guestViewDeny");
1454 void Dispatcher::AddChannelSpecificFeatures() {
1455 // chrome-extension: resources should be allowed to register a Service Worker.
1456 if (FeatureProvider::GetBehaviorFeature(BehaviorFeature::kServiceWorker)
1457 ->IsAvailableToEnvironment()
1458 .is_available())
1459 WebSecurityPolicy::registerURLSchemeAsAllowingServiceWorkers(
1460 WebString::fromUTF8(kExtensionScheme));
1463 } // namespace extensions