Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / extensions / renderer / dispatcher.cc
blob4abecfe05698d6223dcf4671b84a05bf79c9f867
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 RenderThread::Get()->RegisterExtension(SafeBuiltins::CreateV8Extension());
206 script_context_set_.reset(
207 new ScriptContextSet(&extensions_, &active_extension_ids_));
208 user_script_set_manager_.reset(new UserScriptSetManager(&extensions_));
209 script_injection_manager_.reset(
210 new ScriptInjectionManager(&extensions_, user_script_set_manager_.get()));
211 user_script_set_manager_observer_.Add(user_script_set_manager_.get());
212 request_sender_.reset(new RequestSender(this));
213 PopulateSourceMap();
216 Dispatcher::~Dispatcher() {
219 void Dispatcher::OnRenderFrameCreated(content::RenderFrame* render_frame) {
220 script_injection_manager_->OnRenderFrameCreated(render_frame);
223 bool Dispatcher::IsExtensionActive(const std::string& extension_id) const {
224 bool is_active =
225 active_extension_ids_.find(extension_id) != active_extension_ids_.end();
226 if (is_active)
227 CHECK(extensions_.Contains(extension_id));
228 return is_active;
231 void Dispatcher::DidCreateScriptContext(
232 blink::WebLocalFrame* frame,
233 const v8::Local<v8::Context>& v8_context,
234 int extension_group,
235 int world_id) {
236 const base::TimeTicks start_time = base::TimeTicks::Now();
238 ScriptContext* context = script_context_set_->Register(
239 frame, v8_context, extension_group, world_id);
241 // Initialize origin permissions for content scripts, which can't be
242 // initialized in |OnActivateExtension|.
243 if (context->context_type() == Feature::CONTENT_SCRIPT_CONTEXT)
244 InitOriginPermissions(context->extension());
247 scoped_ptr<ModuleSystem> module_system(
248 new ModuleSystem(context, &source_map_));
249 context->set_module_system(module_system.Pass());
251 ModuleSystem* module_system = context->module_system();
253 // Enable natives in startup.
254 ModuleSystem::NativesEnabledScope natives_enabled_scope(module_system);
256 RegisterNativeHandlers(module_system, context);
258 // chrome.Event is part of the public API (although undocumented). Make it
259 // lazily evalulate to Event from event_bindings.js. For extensions only
260 // though, not all webpages!
261 if (context->extension()) {
262 v8::Local<v8::Object> chrome = AsObjectOrEmpty(GetOrCreateChrome(context));
263 if (!chrome.IsEmpty())
264 module_system->SetLazyField(chrome, "Event", kEventBindings, "Event");
267 UpdateBindingsForContext(context);
269 bool is_within_platform_app = IsWithinPlatformApp();
270 // Inject custom JS into the platform app context.
271 if (is_within_platform_app) {
272 module_system->Require("platformApp");
275 RequireGuestViewModules(context);
276 delegate_->RequireAdditionalModules(context, is_within_platform_app);
278 const base::TimeDelta elapsed = base::TimeTicks::Now() - start_time;
279 switch (context->context_type()) {
280 case Feature::UNSPECIFIED_CONTEXT:
281 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Unspecified",
282 elapsed);
283 break;
284 case Feature::BLESSED_EXTENSION_CONTEXT:
285 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Blessed", elapsed);
286 break;
287 case Feature::UNBLESSED_EXTENSION_CONTEXT:
288 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Unblessed",
289 elapsed);
290 break;
291 case Feature::CONTENT_SCRIPT_CONTEXT:
292 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_ContentScript",
293 elapsed);
294 break;
295 case Feature::WEB_PAGE_CONTEXT:
296 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_WebPage", elapsed);
297 break;
298 case Feature::BLESSED_WEB_PAGE_CONTEXT:
299 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_BlessedWebPage",
300 elapsed);
301 break;
302 case Feature::WEBUI_CONTEXT:
303 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_WebUI", elapsed);
304 break;
307 VLOG(1) << "Num tracked contexts: " << script_context_set_->size();
310 void Dispatcher::WillReleaseScriptContext(
311 blink::WebLocalFrame* frame,
312 const v8::Local<v8::Context>& v8_context,
313 int world_id) {
314 ScriptContext* context = script_context_set_->GetByV8Context(v8_context);
315 if (!context)
316 return;
318 context->DispatchOnUnloadEvent();
319 // TODO(kalman): Make |request_sender| use |context->AddInvalidationObserver|.
320 // In fact |request_sender_| should really be owned by ScriptContext.
321 request_sender_->InvalidateSource(context);
323 script_context_set_->Remove(context);
324 VLOG(1) << "Num tracked contexts: " << script_context_set_->size();
327 void Dispatcher::DidCreateDocumentElement(blink::WebLocalFrame* frame) {
328 // Note: use GetEffectiveDocumentURL not just frame->document()->url()
329 // so that this also injects the stylesheet on about:blank frames that
330 // are hosted in the extension process.
331 GURL effective_document_url = ScriptContext::GetEffectiveDocumentURL(
332 frame, frame->document().url(), true /* match_about_blank */);
334 const Extension* extension =
335 extensions_.GetExtensionOrAppByURL(effective_document_url);
337 if (extension &&
338 (extension->is_extension() || extension->is_platform_app())) {
339 int resource_id = extension->is_platform_app() ? IDR_PLATFORM_APP_CSS
340 : IDR_EXTENSION_FONTS_CSS;
341 std::string stylesheet = ResourceBundle::GetSharedInstance()
342 .GetRawDataResource(resource_id)
343 .as_string();
344 base::ReplaceFirstSubstringAfterOffset(
345 &stylesheet, 0, "$FONTFAMILY", system_font_family_);
346 base::ReplaceFirstSubstringAfterOffset(
347 &stylesheet, 0, "$FONTSIZE", system_font_size_);
349 // Blink doesn't let us define an additional user agent stylesheet, so
350 // we insert the default platform app or extension stylesheet into all
351 // documents that are loaded in each app or extension.
352 frame->document().insertStyleSheet(WebString::fromUTF8(stylesheet));
355 // If this is an extension options page, and the extension has opted into
356 // using Chrome styles, then insert the Chrome extension stylesheet.
357 if (extension && extension->is_extension() &&
358 OptionsPageInfo::ShouldUseChromeStyle(extension) &&
359 effective_document_url == OptionsPageInfo::GetOptionsPage(extension)) {
360 frame->document().insertStyleSheet(
361 WebString::fromUTF8(ResourceBundle::GetSharedInstance()
362 .GetRawDataResource(IDR_EXTENSION_CSS)
363 .as_string()));
366 // In testing, the document lifetime events can happen after the render
367 // process shutdown event.
368 // See: http://crbug.com/21508 and http://crbug.com/500851
369 if (content_watcher_) {
370 content_watcher_->DidCreateDocumentElement(frame);
374 void Dispatcher::OnExtensionResponse(int request_id,
375 bool success,
376 const base::ListValue& response,
377 const std::string& error) {
378 request_sender_->HandleResponse(request_id, success, response, error);
381 void Dispatcher::DispatchEvent(const std::string& extension_id,
382 const std::string& event_name) const {
383 base::ListValue args;
384 args.Set(0, new base::StringValue(event_name));
385 args.Set(1, new base::ListValue());
387 // Needed for Windows compilation, since kEventBindings is declared extern.
388 const char* local_event_bindings = kEventBindings;
389 script_context_set_->ForEach(
390 extension_id, base::Bind(&CallModuleMethod, local_event_bindings,
391 kEventDispatchFunction, &args));
394 void Dispatcher::InvokeModuleSystemMethod(content::RenderFrame* render_frame,
395 const std::string& extension_id,
396 const std::string& module_name,
397 const std::string& function_name,
398 const base::ListValue& args,
399 bool user_gesture) {
400 scoped_ptr<WebScopedUserGesture> web_user_gesture;
401 if (user_gesture)
402 web_user_gesture.reset(new WebScopedUserGesture);
404 script_context_set_->ForEach(
405 extension_id, render_frame,
406 base::Bind(&CallModuleMethod, module_name, function_name, &args));
408 // Reset the idle handler each time there's any activity like event or message
409 // dispatch, for which Invoke is the chokepoint.
410 if (set_idle_notifications_) {
411 RenderThread::Get()->ScheduleIdleHandler(
412 kInitialExtensionIdleHandlerDelayMs);
415 // Tell the browser process when an event has been dispatched with a lazy
416 // background page active.
417 const Extension* extension = extensions_.GetByID(extension_id);
418 if (extension && BackgroundInfo::HasLazyBackgroundPage(extension) &&
419 module_name == kEventBindings &&
420 function_name == kEventDispatchFunction) {
421 content::RenderFrame* background_frame =
422 ExtensionFrameHelper::GetBackgroundPageFrame(extension_id);
423 if (background_frame) {
424 int message_id;
425 args.GetInteger(3, &message_id);
426 background_frame->Send(new ExtensionHostMsg_EventAck(
427 background_frame->GetRoutingID(), message_id));
432 void Dispatcher::ClearPortData(int port_id) {
433 // Only the target port side has entries in |port_to_tab_id_map_|. If
434 // |port_id| is a source port, std::map::erase() will just silently fail
435 // here as a no-op.
436 port_to_tab_id_map_.erase(port_id);
439 // static
440 std::vector<std::pair<std::string, int> > Dispatcher::GetJsResources() {
441 std::vector<std::pair<std::string, int> > resources;
443 // Libraries.
444 resources.push_back(std::make_pair("appView", IDR_APP_VIEW_JS));
445 resources.push_back(std::make_pair("entryIdManager", IDR_ENTRY_ID_MANAGER));
446 resources.push_back(std::make_pair(kEventBindings, IDR_EVENT_BINDINGS_JS));
447 resources.push_back(std::make_pair("extensionOptions",
448 IDR_EXTENSION_OPTIONS_JS));
449 resources.push_back(std::make_pair("extensionOptionsAttributes",
450 IDR_EXTENSION_OPTIONS_ATTRIBUTES_JS));
451 resources.push_back(std::make_pair("extensionOptionsConstants",
452 IDR_EXTENSION_OPTIONS_CONSTANTS_JS));
453 resources.push_back(std::make_pair("extensionOptionsEvents",
454 IDR_EXTENSION_OPTIONS_EVENTS_JS));
455 resources.push_back(std::make_pair("extensionView", IDR_EXTENSION_VIEW_JS));
456 resources.push_back(std::make_pair("extensionViewApiMethods",
457 IDR_EXTENSION_VIEW_API_METHODS_JS));
458 resources.push_back(std::make_pair("extensionViewAttributes",
459 IDR_EXTENSION_VIEW_ATTRIBUTES_JS));
460 resources.push_back(std::make_pair("extensionViewConstants",
461 IDR_EXTENSION_VIEW_CONSTANTS_JS));
462 resources.push_back(std::make_pair("extensionViewEvents",
463 IDR_EXTENSION_VIEW_EVENTS_JS));
464 resources.push_back(std::make_pair(
465 "extensionViewInternal", IDR_EXTENSION_VIEW_INTERNAL_CUSTOM_BINDINGS_JS));
466 resources.push_back(std::make_pair("guestView", IDR_GUEST_VIEW_JS));
467 resources.push_back(std::make_pair("guestViewAttributes",
468 IDR_GUEST_VIEW_ATTRIBUTES_JS));
469 resources.push_back(std::make_pair("guestViewContainer",
470 IDR_GUEST_VIEW_CONTAINER_JS));
471 resources.push_back(std::make_pair("guestViewDeny", IDR_GUEST_VIEW_DENY_JS));
472 resources.push_back(std::make_pair("guestViewEvents",
473 IDR_GUEST_VIEW_EVENTS_JS));
475 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
476 ::switches::kSitePerProcess)) {
477 resources.push_back(std::make_pair("guestViewIframe",
478 IDR_GUEST_VIEW_IFRAME_JS));
479 resources.push_back(std::make_pair("guestViewIframeContainer",
480 IDR_GUEST_VIEW_IFRAME_CONTAINER_JS));
483 resources.push_back(std::make_pair("imageUtil", IDR_IMAGE_UTIL_JS));
484 resources.push_back(std::make_pair("json_schema", IDR_JSON_SCHEMA_JS));
485 resources.push_back(std::make_pair("lastError", IDR_LAST_ERROR_JS));
486 resources.push_back(std::make_pair("messaging", IDR_MESSAGING_JS));
487 resources.push_back(std::make_pair("messaging_utils",
488 IDR_MESSAGING_UTILS_JS));
489 resources.push_back(std::make_pair(kSchemaUtils, IDR_SCHEMA_UTILS_JS));
490 resources.push_back(std::make_pair("sendRequest", IDR_SEND_REQUEST_JS));
491 resources.push_back(std::make_pair("setIcon", IDR_SET_ICON_JS));
492 resources.push_back(std::make_pair("surfaceWorker", IDR_SURFACE_VIEW_JS));
493 resources.push_back(std::make_pair("test", IDR_TEST_CUSTOM_BINDINGS_JS));
494 resources.push_back(
495 std::make_pair("test_environment_specific_bindings",
496 IDR_BROWSER_TEST_ENVIRONMENT_SPECIFIC_BINDINGS_JS));
497 resources.push_back(std::make_pair("uncaught_exception_handler",
498 IDR_UNCAUGHT_EXCEPTION_HANDLER_JS));
499 resources.push_back(std::make_pair("unload_event", IDR_UNLOAD_EVENT_JS));
500 resources.push_back(std::make_pair("utils", IDR_UTILS_JS));
501 resources.push_back(std::make_pair("webRequest",
502 IDR_WEB_REQUEST_CUSTOM_BINDINGS_JS));
503 resources.push_back(
504 std::make_pair("webRequestInternal",
505 IDR_WEB_REQUEST_INTERNAL_CUSTOM_BINDINGS_JS));
506 // Note: webView not webview so that this doesn't interfere with the
507 // chrome.webview API bindings.
508 resources.push_back(std::make_pair("webView", IDR_WEB_VIEW_JS));
509 resources.push_back(std::make_pair("webViewActionRequests",
510 IDR_WEB_VIEW_ACTION_REQUESTS_JS));
511 resources.push_back(std::make_pair("webViewApiMethods",
512 IDR_WEB_VIEW_API_METHODS_JS));
513 resources.push_back(std::make_pair("webViewAttributes",
514 IDR_WEB_VIEW_ATTRIBUTES_JS));
515 resources.push_back(std::make_pair("webViewConstants",
516 IDR_WEB_VIEW_CONSTANTS_JS));
517 resources.push_back(std::make_pair("webViewEvents", IDR_WEB_VIEW_EVENTS_JS));
518 resources.push_back(std::make_pair("webViewInternal",
519 IDR_WEB_VIEW_INTERNAL_CUSTOM_BINDINGS_JS));
520 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
521 ::switches::kSitePerProcess)) {
522 resources.push_back(std::make_pair("webViewIframe",
523 IDR_WEB_VIEW_IFRAME_JS));
525 resources.push_back(
526 std::make_pair(mojo::kBindingsModuleName, IDR_MOJO_BINDINGS_JS));
527 resources.push_back(
528 std::make_pair(mojo::kBufferModuleName, IDR_MOJO_BUFFER_JS));
529 resources.push_back(
530 std::make_pair(mojo::kCodecModuleName, IDR_MOJO_CODEC_JS));
531 resources.push_back(
532 std::make_pair(mojo::kConnectionModuleName, IDR_MOJO_CONNECTION_JS));
533 resources.push_back(
534 std::make_pair(mojo::kConnectorModuleName, IDR_MOJO_CONNECTOR_JS));
535 resources.push_back(
536 std::make_pair(mojo::kRouterModuleName, IDR_MOJO_ROUTER_JS));
537 resources.push_back(
538 std::make_pair(mojo::kUnicodeModuleName, IDR_MOJO_UNICODE_JS));
539 resources.push_back(
540 std::make_pair(mojo::kValidatorModuleName, IDR_MOJO_VALIDATOR_JS));
541 resources.push_back(std::make_pair("async_waiter", IDR_ASYNC_WAITER_JS));
542 resources.push_back(std::make_pair("data_receiver", IDR_DATA_RECEIVER_JS));
543 resources.push_back(std::make_pair("data_sender", IDR_DATA_SENDER_JS));
544 resources.push_back(std::make_pair("keep_alive", IDR_KEEP_ALIVE_JS));
545 resources.push_back(std::make_pair("extensions/common/mojo/keep_alive.mojom",
546 IDR_KEEP_ALIVE_MOJOM_JS));
547 resources.push_back(std::make_pair("device/serial/data_stream.mojom",
548 IDR_DATA_STREAM_MOJOM_JS));
549 resources.push_back(
550 std::make_pair("device/serial/data_stream_serialization.mojom",
551 IDR_DATA_STREAM_SERIALIZATION_MOJOM_JS));
552 resources.push_back(std::make_pair("stash_client", IDR_STASH_CLIENT_JS));
553 resources.push_back(
554 std::make_pair("extensions/common/mojo/stash.mojom", IDR_STASH_MOJOM_JS));
556 // Custom bindings.
557 resources.push_back(
558 std::make_pair("app.runtime", IDR_APP_RUNTIME_CUSTOM_BINDINGS_JS));
559 resources.push_back(
560 std::make_pair("app.window", IDR_APP_WINDOW_CUSTOM_BINDINGS_JS));
561 resources.push_back(
562 std::make_pair("declarativeWebRequest",
563 IDR_DECLARATIVE_WEBREQUEST_CUSTOM_BINDINGS_JS));
564 resources.push_back(
565 std::make_pair("contextMenus", IDR_CONTEXT_MENUS_CUSTOM_BINDINGS_JS));
566 resources.push_back(
567 std::make_pair("contextMenusHandlers", IDR_CONTEXT_MENUS_HANDLERS_JS));
568 resources.push_back(
569 std::make_pair("extension", IDR_EXTENSION_CUSTOM_BINDINGS_JS));
570 resources.push_back(std::make_pair("i18n", IDR_I18N_CUSTOM_BINDINGS_JS));
571 resources.push_back(std::make_pair(
572 "mimeHandlerPrivate", IDR_MIME_HANDLER_PRIVATE_CUSTOM_BINDINGS_JS));
573 resources.push_back(std::make_pair("extensions/common/api/mime_handler.mojom",
574 IDR_MIME_HANDLER_MOJOM_JS));
575 resources.push_back(
576 std::make_pair("mojoPrivate", IDR_MOJO_PRIVATE_CUSTOM_BINDINGS_JS));
577 resources.push_back(
578 std::make_pair("permissions", IDR_PERMISSIONS_CUSTOM_BINDINGS_JS));
579 resources.push_back(std::make_pair("printerProvider",
580 IDR_PRINTER_PROVIDER_CUSTOM_BINDINGS_JS));
581 resources.push_back(
582 std::make_pair("runtime", IDR_RUNTIME_CUSTOM_BINDINGS_JS));
583 resources.push_back(std::make_pair("windowControls", IDR_WINDOW_CONTROLS_JS));
584 resources.push_back(
585 std::make_pair("webViewRequest",
586 IDR_WEB_VIEW_REQUEST_CUSTOM_BINDINGS_JS));
587 resources.push_back(std::make_pair("binding", IDR_BINDING_JS));
589 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
590 switches::kEnableMojoSerialService)) {
591 resources.push_back(
592 std::make_pair("serial", IDR_SERIAL_CUSTOM_BINDINGS_JS));
594 resources.push_back(std::make_pair("serial_service", IDR_SERIAL_SERVICE_JS));
595 resources.push_back(
596 std::make_pair("device/serial/serial.mojom", IDR_SERIAL_MOJOM_JS));
597 resources.push_back(std::make_pair("device/serial/serial_serialization.mojom",
598 IDR_SERIAL_SERIALIZATION_MOJOM_JS));
600 // Custom types sources.
601 resources.push_back(std::make_pair("StorageArea", IDR_STORAGE_AREA_JS));
603 // Platform app sources that are not API-specific..
604 resources.push_back(std::make_pair("platformApp", IDR_PLATFORM_APP_JS));
606 #if defined(ENABLE_MEDIA_ROUTER)
607 resources.push_back(
608 std::make_pair("chrome/browser/media/router/media_router.mojom",
609 IDR_MEDIA_ROUTER_MOJOM_JS));
610 resources.push_back(
611 std::make_pair("media_router_bindings", IDR_MEDIA_ROUTER_BINDINGS_JS));
612 #endif // defined(ENABLE_MEDIA_ROUTER)
614 return resources;
617 // NOTE: please use the naming convention "foo_natives" for these.
618 // static
619 void Dispatcher::RegisterNativeHandlers(ModuleSystem* module_system,
620 ScriptContext* context,
621 Dispatcher* dispatcher,
622 RequestSender* request_sender,
623 V8SchemaRegistry* v8_schema_registry) {
624 module_system->RegisterNativeHandler(
625 "chrome", scoped_ptr<NativeHandler>(new ChromeNativeHandler(context)));
626 module_system->RegisterNativeHandler(
627 "lazy_background_page",
628 scoped_ptr<NativeHandler>(new LazyBackgroundPageNativeHandler(context)));
629 module_system->RegisterNativeHandler(
630 "logging", scoped_ptr<NativeHandler>(new LoggingNativeHandler(context)));
631 module_system->RegisterNativeHandler("schema_registry",
632 v8_schema_registry->AsNativeHandler());
633 module_system->RegisterNativeHandler(
634 "print", scoped_ptr<NativeHandler>(new PrintNativeHandler(context)));
635 module_system->RegisterNativeHandler(
636 "test_features",
637 scoped_ptr<NativeHandler>(new TestFeaturesNativeHandler(context)));
638 module_system->RegisterNativeHandler(
639 "user_gestures",
640 scoped_ptr<NativeHandler>(new UserGesturesNativeHandler(context)));
641 module_system->RegisterNativeHandler(
642 "utils", scoped_ptr<NativeHandler>(new UtilsNativeHandler(context)));
643 module_system->RegisterNativeHandler(
644 "v8_context",
645 scoped_ptr<NativeHandler>(
646 new V8ContextNativeHandler(context, dispatcher)));
647 module_system->RegisterNativeHandler(
648 "event_natives", scoped_ptr<NativeHandler>(new EventBindings(context)));
649 module_system->RegisterNativeHandler(
650 "messaging_natives",
651 scoped_ptr<NativeHandler>(MessagingBindings::Get(dispatcher, context)));
652 module_system->RegisterNativeHandler(
653 "apiDefinitions",
654 scoped_ptr<NativeHandler>(
655 new ApiDefinitionsNatives(dispatcher, context)));
656 module_system->RegisterNativeHandler(
657 "sendRequest",
658 scoped_ptr<NativeHandler>(
659 new SendRequestNatives(request_sender, context)));
660 module_system->RegisterNativeHandler(
661 "setIcon",
662 scoped_ptr<NativeHandler>(new SetIconNatives(context)));
663 module_system->RegisterNativeHandler(
664 "activityLogger",
665 scoped_ptr<NativeHandler>(new APIActivityLogger(context)));
666 module_system->RegisterNativeHandler(
667 "renderFrameObserverNatives",
668 scoped_ptr<NativeHandler>(new RenderFrameObserverNatives(context)));
670 // Natives used by multiple APIs.
671 module_system->RegisterNativeHandler(
672 "file_system_natives",
673 scoped_ptr<NativeHandler>(new FileSystemNatives(context)));
675 // Custom bindings.
676 module_system->RegisterNativeHandler(
677 "app_runtime",
678 scoped_ptr<NativeHandler>(new AppRuntimeCustomBindings(context)));
679 // |dispatcher| is null in unit tests.
680 const ScriptContextSet* script_context_set = dispatcher ?
681 &dispatcher->script_context_set() : nullptr;
682 module_system->RegisterNativeHandler(
683 "app_window_natives",
684 scoped_ptr<NativeHandler>(new AppWindowCustomBindings(
685 script_context_set, context)));
686 module_system->RegisterNativeHandler(
687 "blob_natives",
688 scoped_ptr<NativeHandler>(new BlobNativeHandler(context)));
689 module_system->RegisterNativeHandler(
690 "context_menus",
691 scoped_ptr<NativeHandler>(new ContextMenusCustomBindings(context)));
692 module_system->RegisterNativeHandler(
693 "css_natives", scoped_ptr<NativeHandler>(new CssNativeHandler(context)));
694 module_system->RegisterNativeHandler(
695 "document_natives",
696 scoped_ptr<NativeHandler>(new DocumentCustomBindings(context)));
697 module_system->RegisterNativeHandler(
698 "guest_view_internal",
699 scoped_ptr<NativeHandler>(
700 new GuestViewInternalCustomBindings(context)));
701 module_system->RegisterNativeHandler(
702 "i18n", scoped_ptr<NativeHandler>(new I18NCustomBindings(context)));
703 module_system->RegisterNativeHandler(
704 "id_generator",
705 scoped_ptr<NativeHandler>(new IdGeneratorCustomBindings(context)));
706 module_system->RegisterNativeHandler(
707 "runtime", scoped_ptr<NativeHandler>(new RuntimeCustomBindings(context)));
710 void Dispatcher::LoadExtensionForTest(const Extension* extension) {
711 CHECK(extensions_.Insert(extension));
714 bool Dispatcher::OnControlMessageReceived(const IPC::Message& message) {
715 bool handled = true;
716 IPC_BEGIN_MESSAGE_MAP(Dispatcher, message)
717 IPC_MESSAGE_HANDLER(ExtensionMsg_ActivateExtension, OnActivateExtension)
718 IPC_MESSAGE_HANDLER(ExtensionMsg_CancelSuspend, OnCancelSuspend)
719 IPC_MESSAGE_HANDLER(ExtensionMsg_DeliverMessage, OnDeliverMessage)
720 IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnConnect, OnDispatchOnConnect)
721 IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnDisconnect, OnDispatchOnDisconnect)
722 IPC_MESSAGE_HANDLER(ExtensionMsg_Loaded, OnLoaded)
723 IPC_MESSAGE_HANDLER(ExtensionMsg_MessageInvoke, OnMessageInvoke)
724 IPC_MESSAGE_HANDLER(ExtensionMsg_SetChannel, OnSetChannel)
725 IPC_MESSAGE_HANDLER(ExtensionMsg_SetFunctionNames, OnSetFunctionNames)
726 IPC_MESSAGE_HANDLER(ExtensionMsg_SetScriptingWhitelist,
727 OnSetScriptingWhitelist)
728 IPC_MESSAGE_HANDLER(ExtensionMsg_SetSystemFont, OnSetSystemFont)
729 IPC_MESSAGE_HANDLER(ExtensionMsg_ShouldSuspend, OnShouldSuspend)
730 IPC_MESSAGE_HANDLER(ExtensionMsg_Suspend, OnSuspend)
731 IPC_MESSAGE_HANDLER(ExtensionMsg_TransferBlobs, OnTransferBlobs)
732 IPC_MESSAGE_HANDLER(ExtensionMsg_Unloaded, OnUnloaded)
733 IPC_MESSAGE_HANDLER(ExtensionMsg_UpdatePermissions, OnUpdatePermissions)
734 IPC_MESSAGE_HANDLER(ExtensionMsg_UpdateTabSpecificPermissions,
735 OnUpdateTabSpecificPermissions)
736 IPC_MESSAGE_HANDLER(ExtensionMsg_ClearTabSpecificPermissions,
737 OnClearTabSpecificPermissions)
738 IPC_MESSAGE_HANDLER(ExtensionMsg_UsingWebRequestAPI, OnUsingWebRequestAPI)
739 IPC_MESSAGE_FORWARD(ExtensionMsg_WatchPages,
740 content_watcher_.get(),
741 ContentWatcher::OnWatchPages)
742 IPC_MESSAGE_UNHANDLED(handled = false)
743 IPC_END_MESSAGE_MAP()
745 return handled;
748 void Dispatcher::WebKitInitialized() {
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