Remove unused parameter.
[chromium-blink-merge.git] / extensions / renderer / dispatcher.cc
blobc61b18897e8f8a1156f08a285d020203422925c4
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "extensions/renderer/dispatcher.h"
7 #include "base/bind.h"
8 #include "base/callback.h"
9 #include "base/command_line.h"
10 #include "base/debug/alias.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/metrics/histogram_macros.h"
13 #include "base/metrics/user_metrics_action.h"
14 #include "base/strings/string_piece.h"
15 #include "base/strings/string_split.h"
16 #include "base/strings/string_util.h"
17 #include "base/time/time.h"
18 #include "base/values.h"
19 #include "content/grit/content_resources.h"
20 #include "content/public/child/v8_value_converter.h"
21 #include "content/public/common/content_switches.h"
22 #include "content/public/common/url_constants.h"
23 #include "content/public/renderer/render_thread.h"
24 #include "content/public/renderer/render_view.h"
25 #include "extensions/common/api/messaging/message.h"
26 #include "extensions/common/constants.h"
27 #include "extensions/common/extension.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/feature.h"
33 #include "extensions/common/features/feature_provider.h"
34 #include "extensions/common/manifest.h"
35 #include "extensions/common/manifest_constants.h"
36 #include "extensions/common/manifest_handlers/background_info.h"
37 #include "extensions/common/manifest_handlers/content_capabilities_handler.h"
38 #include "extensions/common/manifest_handlers/externally_connectable.h"
39 #include "extensions/common/manifest_handlers/options_page_info.h"
40 #include "extensions/common/manifest_handlers/sandboxed_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_groups.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_view_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/tab_finder.h"
83 #include "extensions/renderer/test_features_native_handler.h"
84 #include "extensions/renderer/user_gestures_native_handler.h"
85 #include "extensions/renderer/utils_native_handler.h"
86 #include "extensions/renderer/v8_context_native_handler.h"
87 #include "grit/extensions_renderer_resources.h"
88 #include "third_party/WebKit/public/platform/WebString.h"
89 #include "third_party/WebKit/public/platform/WebURLRequest.h"
90 #include "third_party/WebKit/public/web/WebCustomElement.h"
91 #include "third_party/WebKit/public/web/WebDataSource.h"
92 #include "third_party/WebKit/public/web/WebDocument.h"
93 #include "third_party/WebKit/public/web/WebFrame.h"
94 #include "third_party/WebKit/public/web/WebLocalFrame.h"
95 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
96 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
97 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
98 #include "third_party/WebKit/public/web/WebView.h"
99 #include "third_party/mojo/src/mojo/public/js/constants.h"
100 #include "ui/base/layout.h"
101 #include "ui/base/resource/resource_bundle.h"
102 #include "v8/include/v8.h"
104 using base::UserMetricsAction;
105 using blink::WebDataSource;
106 using blink::WebDocument;
107 using blink::WebScopedUserGesture;
108 using blink::WebSecurityPolicy;
109 using blink::WebString;
110 using blink::WebVector;
111 using blink::WebView;
112 using content::RenderThread;
113 using content::RenderView;
115 namespace extensions {
117 namespace {
119 static const int64 kInitialExtensionIdleHandlerDelayMs = 5 * 1000;
120 static const int64 kMaxExtensionIdleHandlerDelayMs = 5 * 60 * 1000;
121 static const char kEventDispatchFunction[] = "dispatchEvent";
122 static const char kOnSuspendEvent[] = "runtime.onSuspend";
123 static const char kOnSuspendCanceledEvent[] = "runtime.onSuspendCanceled";
125 // Returns the global value for "chrome" from |context|. If one doesn't exist
126 // creates a new object for it.
128 // Note that this isn't necessarily an object, since webpages can write, for
129 // example, "window.chrome = true".
130 v8::Handle<v8::Value> GetOrCreateChrome(ScriptContext* context) {
131 v8::Handle<v8::String> chrome_string(
132 v8::String::NewFromUtf8(context->isolate(), "chrome"));
133 v8::Handle<v8::Object> global(context->v8_context()->Global());
134 v8::Handle<v8::Value> chrome(global->Get(chrome_string));
135 if (chrome->IsUndefined()) {
136 chrome = v8::Object::New(context->isolate());
137 global->Set(chrome_string, chrome);
139 return chrome;
142 // Returns |value| cast to an object if possible, else an empty handle.
143 v8::Handle<v8::Object> AsObjectOrEmpty(v8::Handle<v8::Value> value) {
144 return value->IsObject() ? value.As<v8::Object>() : v8::Handle<v8::Object>();
147 // Calls a method |method_name| in a module |module_name| belonging to the
148 // module system from |context|. Intended as a callback target from
149 // ScriptContextSet::ForEach.
150 void CallModuleMethod(const std::string& module_name,
151 const std::string& method_name,
152 const base::ListValue* args,
153 ScriptContext* context) {
154 v8::HandleScope handle_scope(context->isolate());
155 v8::Context::Scope context_scope(context->v8_context());
157 scoped_ptr<content::V8ValueConverter> converter(
158 content::V8ValueConverter::create());
160 std::vector<v8::Handle<v8::Value> > arguments;
161 for (base::ListValue::const_iterator it = args->begin(); it != args->end();
162 ++it) {
163 arguments.push_back(converter->ToV8Value(*it, context->v8_context()));
166 context->module_system()->CallModuleMethod(
167 module_name, method_name, &arguments);
170 // This handles the "chrome." root API object in script contexts.
171 class ChromeNativeHandler : public ObjectBackedNativeHandler {
172 public:
173 explicit ChromeNativeHandler(ScriptContext* context)
174 : ObjectBackedNativeHandler(context) {
175 RouteFunction(
176 "GetChrome",
177 base::Bind(&ChromeNativeHandler::GetChrome, base::Unretained(this)));
180 void GetChrome(const v8::FunctionCallbackInfo<v8::Value>& args) {
181 args.GetReturnValue().Set(GetOrCreateChrome(context()));
185 } // namespace
187 Dispatcher::Dispatcher(DispatcherDelegate* delegate)
188 : delegate_(delegate),
189 content_watcher_(new ContentWatcher()),
190 source_map_(&ResourceBundle::GetSharedInstance()),
191 v8_schema_registry_(new V8SchemaRegistry),
192 is_webkit_initialized_(false),
193 user_script_set_manager_observer_(this),
194 webrequest_used_(false) {
195 const base::CommandLine& command_line =
196 *(base::CommandLine::ForCurrentProcess());
197 set_idle_notifications_ =
198 command_line.HasSwitch(switches::kExtensionProcess) ||
199 command_line.HasSwitch(::switches::kSingleProcess);
201 if (set_idle_notifications_) {
202 RenderThread::Get()->SetIdleNotificationDelayInMs(
203 kInitialExtensionIdleHandlerDelayMs);
206 RenderThread::Get()->RegisterExtension(SafeBuiltins::CreateV8Extension());
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::OnRenderViewCreated(content::RenderView* render_view) {
220 script_injection_manager_->OnRenderViewCreated(render_view);
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 const Extension* Dispatcher::GetExtensionFromFrameAndWorld(
232 const blink::WebFrame* frame,
233 int world_id,
234 bool use_effective_url) {
235 std::string extension_id;
236 if (world_id != 0) {
237 // Isolated worlds (content script).
238 extension_id = ScriptInjection::GetHostIdForIsolatedWorld(world_id);
239 } else if (!frame->document().securityOrigin().isUnique()) {
240 // TODO(kalman): Delete the above check.
242 // Extension pages (chrome-extension:// URLs).
243 GURL frame_url = ScriptContext::GetDataSourceURLForFrame(frame);
244 frame_url = ScriptContext::GetEffectiveDocumentURL(frame, frame_url,
245 use_effective_url);
246 extension_id = extensions_.GetExtensionOrAppIDByURL(frame_url);
249 const Extension* extension = extensions_.GetByID(extension_id);
250 if (!extension && !extension_id.empty()) {
251 // There are conditions where despite a context being associated with an
252 // extension, no extension actually gets found. Ignore "invalid" because
253 // CSP blocks extension page loading by switching the extension ID to
254 // "invalid". This isn't interesting.
255 if (extension_id != "invalid") {
256 LOG(ERROR) << "Extension \"" << extension_id << "\" not found";
257 RenderThread::Get()->RecordAction(
258 UserMetricsAction("ExtensionNotFound_ED"));
261 return extension;
264 void Dispatcher::DidCreateScriptContext(
265 blink::WebLocalFrame* frame,
266 const v8::Handle<v8::Context>& v8_context,
267 int extension_group,
268 int world_id) {
269 const base::TimeTicks start_time = base::TimeTicks::Now();
271 const Extension* extension =
272 GetExtensionFromFrameAndWorld(frame, world_id, false);
273 const Extension* effective_extension =
274 GetExtensionFromFrameAndWorld(frame, world_id, true);
276 GURL frame_url = ScriptContext::GetDataSourceURLForFrame(frame);
277 Feature::Context context_type =
278 ClassifyJavaScriptContext(extension, extension_group, frame_url,
279 frame->document().securityOrigin());
280 Feature::Context effective_context_type = ClassifyJavaScriptContext(
281 effective_extension, extension_group,
282 ScriptContext::GetEffectiveDocumentURL(frame, frame_url, true),
283 frame->document().securityOrigin());
285 ScriptContext* context =
286 new ScriptContext(v8_context, frame, extension, context_type,
287 effective_extension, effective_context_type);
288 script_context_set_.Add(context);
290 // Initialize origin permissions for content scripts, which can't be
291 // initialized in |OnActivateExtension|.
292 if (context_type == Feature::CONTENT_SCRIPT_CONTEXT)
293 InitOriginPermissions(extension);
296 scoped_ptr<ModuleSystem> module_system(
297 new ModuleSystem(context, &source_map_));
298 context->set_module_system(module_system.Pass());
300 ModuleSystem* module_system = context->module_system();
302 // Enable natives in startup.
303 ModuleSystem::NativesEnabledScope natives_enabled_scope(module_system);
305 RegisterNativeHandlers(module_system, context);
307 // chrome.Event is part of the public API (although undocumented). Make it
308 // lazily evalulate to Event from event_bindings.js. For extensions only
309 // though, not all webpages!
310 if (context->extension()) {
311 v8::Handle<v8::Object> chrome = AsObjectOrEmpty(GetOrCreateChrome(context));
312 if (!chrome.IsEmpty())
313 module_system->SetLazyField(chrome, "Event", kEventBindings, "Event");
316 UpdateBindingsForContext(context);
318 bool is_within_platform_app = IsWithinPlatformApp();
319 // Inject custom JS into the platform app context.
320 if (is_within_platform_app) {
321 module_system->Require("platformApp");
324 RequireGuestViewModules(context);
325 delegate_->RequireAdditionalModules(context, is_within_platform_app);
327 const base::TimeDelta elapsed = base::TimeTicks::Now() - start_time;
328 switch (context_type) {
329 case Feature::UNSPECIFIED_CONTEXT:
330 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Unspecified",
331 elapsed);
332 break;
333 case Feature::BLESSED_EXTENSION_CONTEXT:
334 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Blessed", elapsed);
335 break;
336 case Feature::UNBLESSED_EXTENSION_CONTEXT:
337 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Unblessed",
338 elapsed);
339 break;
340 case Feature::CONTENT_SCRIPT_CONTEXT:
341 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_ContentScript",
342 elapsed);
343 break;
344 case Feature::WEB_PAGE_CONTEXT:
345 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_WebPage", elapsed);
346 break;
347 case Feature::BLESSED_WEB_PAGE_CONTEXT:
348 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_BlessedWebPage",
349 elapsed);
350 break;
351 case Feature::WEBUI_CONTEXT:
352 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_WebUI", elapsed);
353 break;
356 VLOG(1) << "Num tracked contexts: " << script_context_set_.size();
359 void Dispatcher::WillReleaseScriptContext(
360 blink::WebLocalFrame* frame,
361 const v8::Handle<v8::Context>& v8_context,
362 int world_id) {
363 ScriptContext* context = script_context_set_.GetByV8Context(v8_context);
364 if (!context)
365 return;
367 context->DispatchOnUnloadEvent();
368 // TODO(kalman): add an invalidation observer interface to ScriptContext.
369 request_sender_->InvalidateSource(context);
371 script_context_set_.Remove(context);
372 VLOG(1) << "Num tracked contexts: " << script_context_set_.size();
375 void Dispatcher::DidCreateDocumentElement(blink::WebFrame* frame) {
376 // Note: use GetEffectiveDocumentURL not just frame->document()->url()
377 // so that this also injects the stylesheet on about:blank frames that
378 // are hosted in the extension process.
379 GURL effective_document_url = ScriptContext::GetEffectiveDocumentURL(
380 frame, frame->document().url(), true /* match_about_blank */);
382 const Extension* extension =
383 extensions_.GetExtensionOrAppByURL(effective_document_url);
385 if (extension &&
386 (extension->is_extension() || extension->is_platform_app())) {
387 int resource_id = extension->is_platform_app() ? IDR_PLATFORM_APP_CSS
388 : IDR_EXTENSION_FONTS_CSS;
389 std::string stylesheet = ResourceBundle::GetSharedInstance()
390 .GetRawDataResource(resource_id)
391 .as_string();
392 ReplaceFirstSubstringAfterOffset(
393 &stylesheet, 0, "$FONTFAMILY", system_font_family_);
394 ReplaceFirstSubstringAfterOffset(
395 &stylesheet, 0, "$FONTSIZE", system_font_size_);
397 // Blink doesn't let us define an additional user agent stylesheet, so
398 // we insert the default platform app or extension stylesheet into all
399 // documents that are loaded in each app or extension.
400 frame->document().insertStyleSheet(WebString::fromUTF8(stylesheet));
403 // If this is an extension options page, and the extension has opted into
404 // using Chrome styles, then insert the Chrome extension stylesheet.
405 if (extension && extension->is_extension() &&
406 OptionsPageInfo::ShouldUseChromeStyle(extension) &&
407 effective_document_url == OptionsPageInfo::GetOptionsPage(extension)) {
408 frame->document().insertStyleSheet(
409 WebString::fromUTF8(ResourceBundle::GetSharedInstance()
410 .GetRawDataResource(IDR_EXTENSION_CSS)
411 .as_string()));
414 content_watcher_->DidCreateDocumentElement(frame);
417 void Dispatcher::DidMatchCSS(
418 blink::WebFrame* frame,
419 const blink::WebVector<blink::WebString>& newly_matching_selectors,
420 const blink::WebVector<blink::WebString>& stopped_matching_selectors) {
421 content_watcher_->DidMatchCSS(
422 frame, newly_matching_selectors, stopped_matching_selectors);
425 void Dispatcher::OnExtensionResponse(int request_id,
426 bool success,
427 const base::ListValue& response,
428 const std::string& error) {
429 request_sender_->HandleResponse(request_id, success, response, error);
432 bool Dispatcher::CheckContextAccessToExtensionAPI(
433 const std::string& function_name,
434 ScriptContext* context) const {
435 if (!context) {
436 DLOG(ERROR) << "Not in a v8::Context";
437 return false;
440 // Theoretically we could end up with bindings being injected into sandboxed
441 // frames, for example content scripts. Don't let them execute API functions.
442 blink::WebFrame* frame = context->web_frame();
443 if (IsSandboxedPage(ScriptContext::GetDataSourceURLForFrame(frame))) {
444 static const char kMessage[] =
445 "%s cannot be used within a sandboxed frame.";
446 std::string error_msg = base::StringPrintf(kMessage, function_name.c_str());
447 context->isolate()->ThrowException(v8::Exception::Error(
448 v8::String::NewFromUtf8(context->isolate(), error_msg.c_str())));
449 return false;
452 Feature::Availability availability = context->GetAvailability(function_name);
453 if (!availability.is_available()) {
454 context->isolate()->ThrowException(
455 v8::Exception::Error(v8::String::NewFromUtf8(
456 context->isolate(), availability.message().c_str())));
459 return availability.is_available();
462 void Dispatcher::DispatchEvent(const std::string& extension_id,
463 const std::string& event_name) const {
464 base::ListValue args;
465 args.Set(0, new base::StringValue(event_name));
466 args.Set(1, new base::ListValue());
468 // Needed for Windows compilation, since kEventBindings is declared extern.
469 const char* local_event_bindings = kEventBindings;
470 script_context_set_.ForEach(
471 extension_id, base::Bind(&CallModuleMethod, local_event_bindings,
472 kEventDispatchFunction, &args));
475 void Dispatcher::InvokeModuleSystemMethod(content::RenderView* render_view,
476 const std::string& extension_id,
477 const std::string& module_name,
478 const std::string& function_name,
479 const base::ListValue& args,
480 bool user_gesture) {
481 scoped_ptr<WebScopedUserGesture> web_user_gesture;
482 if (user_gesture)
483 web_user_gesture.reset(new WebScopedUserGesture);
485 script_context_set_.ForEach(
486 extension_id, render_view,
487 base::Bind(&CallModuleMethod, module_name, function_name, &args));
489 // Reset the idle handler each time there's any activity like event or message
490 // dispatch, for which Invoke is the chokepoint.
491 if (set_idle_notifications_) {
492 RenderThread::Get()->ScheduleIdleHandler(
493 kInitialExtensionIdleHandlerDelayMs);
496 // Tell the browser process when an event has been dispatched with a lazy
497 // background page active.
498 const Extension* extension = extensions_.GetByID(extension_id);
499 if (extension && BackgroundInfo::HasLazyBackgroundPage(extension) &&
500 module_name == kEventBindings &&
501 function_name == kEventDispatchFunction) {
502 RenderView* background_view =
503 ExtensionHelper::GetBackgroundPage(extension_id);
504 if (background_view) {
505 int message_id;
506 args.GetInteger(3, &message_id);
507 background_view->Send(new ExtensionHostMsg_EventAck(
508 background_view->GetRoutingID(), message_id));
513 void Dispatcher::ClearPortData(int port_id) {
514 // Only the target port side has entries in |port_to_tab_id_map_|. If
515 // |port_id| is a source port, std::map::erase() will just silently fail
516 // here as a no-op.
517 port_to_tab_id_map_.erase(port_id);
520 // static
521 std::vector<std::pair<std::string, int> > Dispatcher::GetJsResources() {
522 std::vector<std::pair<std::string, int> > resources;
524 // Libraries.
525 resources.push_back(std::make_pair("appView", IDR_APP_VIEW_JS));
526 resources.push_back(std::make_pair("entryIdManager", IDR_ENTRY_ID_MANAGER));
527 resources.push_back(std::make_pair(kEventBindings, IDR_EVENT_BINDINGS_JS));
528 resources.push_back(std::make_pair("extensionOptions",
529 IDR_EXTENSION_OPTIONS_JS));
530 resources.push_back(std::make_pair("extensionOptionsAttributes",
531 IDR_EXTENSION_OPTIONS_ATTRIBUTES_JS));
532 resources.push_back(std::make_pair("extensionOptionsConstants",
533 IDR_EXTENSION_OPTIONS_CONSTANTS_JS));
534 resources.push_back(std::make_pair("extensionOptionsEvents",
535 IDR_EXTENSION_OPTIONS_EVENTS_JS));
536 resources.push_back(std::make_pair("extensionView", IDR_EXTENSION_VIEW_JS));
537 resources.push_back(std::make_pair("extensionViewApiMethods",
538 IDR_EXTENSION_VIEW_API_METHODS_JS));
539 resources.push_back(std::make_pair("extensionViewAttributes",
540 IDR_EXTENSION_VIEW_ATTRIBUTES_JS));
541 resources.push_back(std::make_pair("extensionViewConstants",
542 IDR_EXTENSION_VIEW_CONSTANTS_JS));
543 resources.push_back(std::make_pair("extensionViewEvents",
544 IDR_EXTENSION_VIEW_EVENTS_JS));
545 resources.push_back(std::make_pair(
546 "extensionViewInternal", IDR_EXTENSION_VIEW_INTERNAL_CUSTOM_BINDINGS_JS));
547 resources.push_back(std::make_pair("guestView", IDR_GUEST_VIEW_JS));
548 resources.push_back(std::make_pair("guestViewAttributes",
549 IDR_GUEST_VIEW_ATTRIBUTES_JS));
550 resources.push_back(std::make_pair("guestViewContainer",
551 IDR_GUEST_VIEW_CONTAINER_JS));
552 resources.push_back(std::make_pair("guestViewDeny", IDR_GUEST_VIEW_DENY_JS));
553 resources.push_back(std::make_pair("guestViewEvents",
554 IDR_GUEST_VIEW_EVENTS_JS));
555 resources.push_back(std::make_pair("imageUtil", IDR_IMAGE_UTIL_JS));
556 resources.push_back(std::make_pair("json_schema", IDR_JSON_SCHEMA_JS));
557 resources.push_back(std::make_pair("lastError", IDR_LAST_ERROR_JS));
558 resources.push_back(std::make_pair("messaging", IDR_MESSAGING_JS));
559 resources.push_back(std::make_pair("messaging_utils",
560 IDR_MESSAGING_UTILS_JS));
561 resources.push_back(std::make_pair(kSchemaUtils, IDR_SCHEMA_UTILS_JS));
562 resources.push_back(std::make_pair("sendRequest", IDR_SEND_REQUEST_JS));
563 resources.push_back(std::make_pair("setIcon", IDR_SET_ICON_JS));
564 resources.push_back(std::make_pair("surfaceWorker", IDR_SURFACE_VIEW_JS));
565 resources.push_back(std::make_pair("test", IDR_TEST_CUSTOM_BINDINGS_JS));
566 resources.push_back(
567 std::make_pair("test_environment_specific_bindings",
568 IDR_BROWSER_TEST_ENVIRONMENT_SPECIFIC_BINDINGS_JS));
569 resources.push_back(std::make_pair("uncaught_exception_handler",
570 IDR_UNCAUGHT_EXCEPTION_HANDLER_JS));
571 resources.push_back(std::make_pair("unload_event", IDR_UNLOAD_EVENT_JS));
572 resources.push_back(std::make_pair("utils", IDR_UTILS_JS));
573 resources.push_back(std::make_pair("webRequest",
574 IDR_WEB_REQUEST_CUSTOM_BINDINGS_JS));
575 resources.push_back(
576 std::make_pair("webRequestInternal",
577 IDR_WEB_REQUEST_INTERNAL_CUSTOM_BINDINGS_JS));
578 // Note: webView not webview so that this doesn't interfere with the
579 // chrome.webview API bindings.
580 resources.push_back(std::make_pair("webView", IDR_WEB_VIEW_JS));
581 resources.push_back(std::make_pair("webViewActionRequests",
582 IDR_WEB_VIEW_ACTION_REQUESTS_JS));
583 resources.push_back(std::make_pair("webViewApiMethods",
584 IDR_WEB_VIEW_API_METHODS_JS));
585 resources.push_back(std::make_pair("webViewAttributes",
586 IDR_WEB_VIEW_ATTRIBUTES_JS));
587 resources.push_back(std::make_pair("webViewConstants",
588 IDR_WEB_VIEW_CONSTANTS_JS));
589 resources.push_back(std::make_pair("webViewEvents", IDR_WEB_VIEW_EVENTS_JS));
590 resources.push_back(std::make_pair("webViewInternal",
591 IDR_WEB_VIEW_INTERNAL_CUSTOM_BINDINGS_JS));
592 resources.push_back(
593 std::make_pair(mojo::kBindingsModuleName, IDR_MOJO_BINDINGS_JS));
594 resources.push_back(
595 std::make_pair(mojo::kBufferModuleName, IDR_MOJO_BUFFER_JS));
596 resources.push_back(
597 std::make_pair(mojo::kCodecModuleName, IDR_MOJO_CODEC_JS));
598 resources.push_back(
599 std::make_pair(mojo::kConnectionModuleName, IDR_MOJO_CONNECTION_JS));
600 resources.push_back(
601 std::make_pair(mojo::kConnectorModuleName, IDR_MOJO_CONNECTOR_JS));
602 resources.push_back(
603 std::make_pair(mojo::kRouterModuleName, IDR_MOJO_ROUTER_JS));
604 resources.push_back(
605 std::make_pair(mojo::kUnicodeModuleName, IDR_MOJO_UNICODE_JS));
606 resources.push_back(
607 std::make_pair(mojo::kValidatorModuleName, IDR_MOJO_VALIDATOR_JS));
608 resources.push_back(std::make_pair("async_waiter", IDR_ASYNC_WAITER_JS));
609 resources.push_back(std::make_pair("data_receiver", IDR_DATA_RECEIVER_JS));
610 resources.push_back(std::make_pair("data_sender", IDR_DATA_SENDER_JS));
611 resources.push_back(std::make_pair("keep_alive", IDR_KEEP_ALIVE_JS));
612 resources.push_back(std::make_pair("extensions/common/mojo/keep_alive.mojom",
613 IDR_KEEP_ALIVE_MOJOM_JS));
614 resources.push_back(std::make_pair("device/serial/data_stream.mojom",
615 IDR_DATA_STREAM_MOJOM_JS));
616 resources.push_back(
617 std::make_pair("device/serial/data_stream_serialization.mojom",
618 IDR_DATA_STREAM_SERIALIZATION_MOJOM_JS));
619 resources.push_back(std::make_pair("stash_client", IDR_STASH_CLIENT_JS));
620 resources.push_back(
621 std::make_pair("extensions/common/mojo/stash.mojom", IDR_STASH_MOJOM_JS));
623 // Custom bindings.
624 resources.push_back(
625 std::make_pair("app.runtime", IDR_APP_RUNTIME_CUSTOM_BINDINGS_JS));
626 resources.push_back(
627 std::make_pair("app.window", IDR_APP_WINDOW_CUSTOM_BINDINGS_JS));
628 resources.push_back(
629 std::make_pair("declarativeWebRequest",
630 IDR_DECLARATIVE_WEBREQUEST_CUSTOM_BINDINGS_JS));
631 resources.push_back(
632 std::make_pair("contextMenus", IDR_CONTEXT_MENUS_CUSTOM_BINDINGS_JS));
633 resources.push_back(
634 std::make_pair("contextMenusHandlers", IDR_CONTEXT_MENUS_HANDLERS_JS));
635 resources.push_back(
636 std::make_pair("extension", IDR_EXTENSION_CUSTOM_BINDINGS_JS));
637 resources.push_back(std::make_pair("i18n", IDR_I18N_CUSTOM_BINDINGS_JS));
638 resources.push_back(std::make_pair(
639 "mimeHandlerPrivate", IDR_MIME_HANDLER_PRIVATE_CUSTOM_BINDINGS_JS));
640 resources.push_back(std::make_pair("extensions/common/api/mime_handler.mojom",
641 IDR_MIME_HANDLER_MOJOM_JS));
642 resources.push_back(
643 std::make_pair("mojoPrivate", IDR_MOJO_PRIVATE_CUSTOM_BINDINGS_JS));
644 resources.push_back(
645 std::make_pair("permissions", IDR_PERMISSIONS_CUSTOM_BINDINGS_JS));
646 resources.push_back(std::make_pair("printerProvider",
647 IDR_PRINTER_PROVIDER_CUSTOM_BINDINGS_JS));
648 resources.push_back(
649 std::make_pair("runtime", IDR_RUNTIME_CUSTOM_BINDINGS_JS));
650 resources.push_back(std::make_pair("windowControls", IDR_WINDOW_CONTROLS_JS));
651 resources.push_back(
652 std::make_pair("webViewRequest",
653 IDR_WEB_VIEW_REQUEST_CUSTOM_BINDINGS_JS));
654 resources.push_back(std::make_pair("binding", IDR_BINDING_JS));
656 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
657 switches::kEnableMojoSerialService)) {
658 resources.push_back(
659 std::make_pair("serial", IDR_SERIAL_CUSTOM_BINDINGS_JS));
661 resources.push_back(std::make_pair("serial_service", IDR_SERIAL_SERVICE_JS));
662 resources.push_back(
663 std::make_pair("device/serial/serial.mojom", IDR_SERIAL_MOJOM_JS));
664 resources.push_back(std::make_pair("device/serial/serial_serialization.mojom",
665 IDR_SERIAL_SERIALIZATION_MOJOM_JS));
667 // Custom types sources.
668 resources.push_back(std::make_pair("StorageArea", IDR_STORAGE_AREA_JS));
670 // Platform app sources that are not API-specific..
671 resources.push_back(std::make_pair("platformApp", IDR_PLATFORM_APP_JS));
673 return resources;
676 // NOTE: please use the naming convention "foo_natives" for these.
677 // static
678 void Dispatcher::RegisterNativeHandlers(ModuleSystem* module_system,
679 ScriptContext* context,
680 Dispatcher* dispatcher,
681 RequestSender* request_sender,
682 V8SchemaRegistry* v8_schema_registry) {
683 module_system->RegisterNativeHandler(
684 "chrome", scoped_ptr<NativeHandler>(new ChromeNativeHandler(context)));
685 module_system->RegisterNativeHandler(
686 "lazy_background_page",
687 scoped_ptr<NativeHandler>(new LazyBackgroundPageNativeHandler(context)));
688 module_system->RegisterNativeHandler(
689 "logging", scoped_ptr<NativeHandler>(new LoggingNativeHandler(context)));
690 module_system->RegisterNativeHandler("schema_registry",
691 v8_schema_registry->AsNativeHandler());
692 module_system->RegisterNativeHandler(
693 "print", scoped_ptr<NativeHandler>(new PrintNativeHandler(context)));
694 module_system->RegisterNativeHandler(
695 "test_features",
696 scoped_ptr<NativeHandler>(new TestFeaturesNativeHandler(context)));
697 module_system->RegisterNativeHandler(
698 "user_gestures",
699 scoped_ptr<NativeHandler>(new UserGesturesNativeHandler(context)));
700 module_system->RegisterNativeHandler(
701 "utils", scoped_ptr<NativeHandler>(new UtilsNativeHandler(context)));
702 module_system->RegisterNativeHandler(
703 "v8_context",
704 scoped_ptr<NativeHandler>(
705 new V8ContextNativeHandler(context, dispatcher)));
706 module_system->RegisterNativeHandler(
707 "event_natives",
708 scoped_ptr<NativeHandler>(new EventBindings(dispatcher, context)));
709 module_system->RegisterNativeHandler(
710 "messaging_natives",
711 scoped_ptr<NativeHandler>(MessagingBindings::Get(dispatcher, context)));
712 module_system->RegisterNativeHandler(
713 "apiDefinitions",
714 scoped_ptr<NativeHandler>(
715 new ApiDefinitionsNatives(dispatcher, context)));
716 module_system->RegisterNativeHandler(
717 "sendRequest",
718 scoped_ptr<NativeHandler>(
719 new SendRequestNatives(request_sender, context)));
720 module_system->RegisterNativeHandler(
721 "setIcon",
722 scoped_ptr<NativeHandler>(new SetIconNatives(context)));
723 module_system->RegisterNativeHandler(
724 "activityLogger",
725 scoped_ptr<NativeHandler>(new APIActivityLogger(context)));
726 module_system->RegisterNativeHandler(
727 "renderViewObserverNatives",
728 scoped_ptr<NativeHandler>(new RenderViewObserverNatives(context)));
730 // Natives used by multiple APIs.
731 module_system->RegisterNativeHandler(
732 "file_system_natives",
733 scoped_ptr<NativeHandler>(new FileSystemNatives(context)));
735 // Custom bindings.
736 module_system->RegisterNativeHandler(
737 "app_runtime",
738 scoped_ptr<NativeHandler>(new AppRuntimeCustomBindings(context)));
739 module_system->RegisterNativeHandler(
740 "app_window_natives",
741 scoped_ptr<NativeHandler>(
742 new AppWindowCustomBindings(dispatcher, context)));
743 module_system->RegisterNativeHandler(
744 "blob_natives",
745 scoped_ptr<NativeHandler>(new BlobNativeHandler(context)));
746 module_system->RegisterNativeHandler(
747 "context_menus",
748 scoped_ptr<NativeHandler>(new ContextMenusCustomBindings(context)));
749 module_system->RegisterNativeHandler(
750 "css_natives", scoped_ptr<NativeHandler>(new CssNativeHandler(context)));
751 module_system->RegisterNativeHandler(
752 "document_natives",
753 scoped_ptr<NativeHandler>(new DocumentCustomBindings(context)));
754 module_system->RegisterNativeHandler(
755 "guest_view_internal",
756 scoped_ptr<NativeHandler>(
757 new GuestViewInternalCustomBindings(context)));
758 module_system->RegisterNativeHandler(
759 "i18n", scoped_ptr<NativeHandler>(new I18NCustomBindings(context)));
760 module_system->RegisterNativeHandler(
761 "id_generator",
762 scoped_ptr<NativeHandler>(new IdGeneratorCustomBindings(context)));
763 module_system->RegisterNativeHandler(
764 "runtime", scoped_ptr<NativeHandler>(new RuntimeCustomBindings(context)));
767 bool Dispatcher::OnControlMessageReceived(const IPC::Message& message) {
768 bool handled = true;
769 IPC_BEGIN_MESSAGE_MAP(Dispatcher, message)
770 IPC_MESSAGE_HANDLER(ExtensionMsg_ActivateExtension, OnActivateExtension)
771 IPC_MESSAGE_HANDLER(ExtensionMsg_CancelSuspend, OnCancelSuspend)
772 IPC_MESSAGE_HANDLER(ExtensionMsg_DeliverMessage, OnDeliverMessage)
773 IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnConnect, OnDispatchOnConnect)
774 IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnDisconnect, OnDispatchOnDisconnect)
775 IPC_MESSAGE_HANDLER(ExtensionMsg_Loaded, OnLoaded)
776 IPC_MESSAGE_HANDLER(ExtensionMsg_MessageInvoke, OnMessageInvoke)
777 IPC_MESSAGE_HANDLER(ExtensionMsg_SetChannel, OnSetChannel)
778 IPC_MESSAGE_HANDLER(ExtensionMsg_SetFunctionNames, OnSetFunctionNames)
779 IPC_MESSAGE_HANDLER(ExtensionMsg_SetScriptingWhitelist,
780 OnSetScriptingWhitelist)
781 IPC_MESSAGE_HANDLER(ExtensionMsg_SetSystemFont, OnSetSystemFont)
782 IPC_MESSAGE_HANDLER(ExtensionMsg_ShouldSuspend, OnShouldSuspend)
783 IPC_MESSAGE_HANDLER(ExtensionMsg_Suspend, OnSuspend)
784 IPC_MESSAGE_HANDLER(ExtensionMsg_TransferBlobs, OnTransferBlobs)
785 IPC_MESSAGE_HANDLER(ExtensionMsg_Unloaded, OnUnloaded)
786 IPC_MESSAGE_HANDLER(ExtensionMsg_UpdatePermissions, OnUpdatePermissions)
787 IPC_MESSAGE_HANDLER(ExtensionMsg_UpdateTabSpecificPermissions,
788 OnUpdateTabSpecificPermissions)
789 IPC_MESSAGE_HANDLER(ExtensionMsg_ClearTabSpecificPermissions,
790 OnClearTabSpecificPermissions)
791 IPC_MESSAGE_HANDLER(ExtensionMsg_UsingWebRequestAPI, OnUsingWebRequestAPI)
792 IPC_MESSAGE_FORWARD(ExtensionMsg_WatchPages,
793 content_watcher_.get(),
794 ContentWatcher::OnWatchPages)
795 IPC_MESSAGE_UNHANDLED(handled = false)
796 IPC_END_MESSAGE_MAP()
798 return handled;
801 void Dispatcher::WebKitInitialized() {
802 // For extensions, we want to ensure we call the IdleHandler every so often,
803 // even if the extension keeps up activity.
804 if (set_idle_notifications_) {
805 forced_idle_timer_.reset(new base::RepeatingTimer<content::RenderThread>);
806 forced_idle_timer_->Start(
807 FROM_HERE,
808 base::TimeDelta::FromMilliseconds(kMaxExtensionIdleHandlerDelayMs),
809 RenderThread::Get(),
810 &RenderThread::IdleHandler);
813 // Initialize host permissions for any extensions that were activated before
814 // WebKit was initialized.
815 for (std::set<std::string>::iterator iter = active_extension_ids_.begin();
816 iter != active_extension_ids_.end();
817 ++iter) {
818 const Extension* extension = extensions_.GetByID(*iter);
819 CHECK(extension);
821 InitOriginPermissions(extension);
824 EnableCustomElementWhiteList();
826 is_webkit_initialized_ = true;
829 void Dispatcher::IdleNotification() {
830 if (set_idle_notifications_ && forced_idle_timer_) {
831 // Dampen the forced delay as well if the extension stays idle for long
832 // periods of time. (forced_idle_timer_ can be NULL after
833 // OnRenderProcessShutdown has been called.)
834 int64 forced_delay_ms =
835 std::max(RenderThread::Get()->GetIdleNotificationDelayInMs(),
836 kMaxExtensionIdleHandlerDelayMs);
837 forced_idle_timer_->Stop();
838 forced_idle_timer_->Start(
839 FROM_HERE,
840 base::TimeDelta::FromMilliseconds(forced_delay_ms),
841 RenderThread::Get(),
842 &RenderThread::IdleHandler);
846 void Dispatcher::OnRenderProcessShutdown() {
847 v8_schema_registry_.reset();
848 forced_idle_timer_.reset();
851 void Dispatcher::OnActivateExtension(const std::string& extension_id) {
852 const Extension* extension = extensions_.GetByID(extension_id);
853 if (!extension) {
854 // Extension was activated but was never loaded. This probably means that
855 // the renderer failed to load it (or the browser failed to tell us when it
856 // did). Failures shouldn't happen, but instead of crashing there (which
857 // executes on all renderers) be conservative and only crash in the renderer
858 // of the extension which failed to load; this one.
859 std::string& error = extension_load_errors_[extension_id];
860 char minidump[256];
861 base::debug::Alias(&minidump);
862 base::snprintf(minidump,
863 arraysize(minidump),
864 "e::dispatcher:%s:%s",
865 extension_id.c_str(),
866 error.c_str());
867 CHECK(extension) << extension_id << " was never loaded: " << error;
870 active_extension_ids_.insert(extension_id);
872 // This is called when starting a new extension page, so start the idle
873 // handler ticking.
874 RenderThread::Get()->ScheduleIdleHandler(kInitialExtensionIdleHandlerDelayMs);
876 if (is_webkit_initialized_) {
877 DOMActivityLogger::AttachToWorld(
878 DOMActivityLogger::kMainWorldId, extension_id);
880 InitOriginPermissions(extension);
883 UpdateActiveExtensions();
886 void Dispatcher::OnCancelSuspend(const std::string& extension_id) {
887 DispatchEvent(extension_id, kOnSuspendCanceledEvent);
890 void Dispatcher::OnDeliverMessage(int target_port_id, const Message& message) {
891 scoped_ptr<RequestSender::ScopedTabID> scoped_tab_id;
892 std::map<int, int>::const_iterator it =
893 port_to_tab_id_map_.find(target_port_id);
894 if (it != port_to_tab_id_map_.end()) {
895 scoped_tab_id.reset(
896 new RequestSender::ScopedTabID(request_sender(), it->second));
899 MessagingBindings::DeliverMessage(script_context_set_, target_port_id,
900 message,
901 NULL); // All render frames.
904 void Dispatcher::OnDispatchOnConnect(
905 int target_port_id,
906 const std::string& channel_name,
907 const ExtensionMsg_TabConnectionInfo& source,
908 const ExtensionMsg_ExternalConnectionInfo& info,
909 const std::string& tls_channel_id) {
910 DCHECK(!ContainsKey(port_to_tab_id_map_, target_port_id));
911 DCHECK_EQ(1, target_port_id % 2); // target renderer ports have odd IDs.
912 int sender_tab_id = -1;
913 source.tab.GetInteger("id", &sender_tab_id);
914 port_to_tab_id_map_[target_port_id] = sender_tab_id;
916 MessagingBindings::DispatchOnConnect(script_context_set_, target_port_id,
917 channel_name, source, info,
918 tls_channel_id,
919 NULL); // All render frames.
922 void Dispatcher::OnDispatchOnDisconnect(int port_id,
923 const std::string& error_message) {
924 MessagingBindings::DispatchOnDisconnect(script_context_set_, port_id,
925 error_message,
926 NULL); // All render frames.
929 void Dispatcher::OnLoaded(
930 const std::vector<ExtensionMsg_Loaded_Params>& loaded_extensions) {
931 std::vector<ExtensionMsg_Loaded_Params>::const_iterator i;
932 for (i = loaded_extensions.begin(); i != loaded_extensions.end(); ++i) {
933 std::string error;
934 scoped_refptr<const Extension> extension = i->ConvertToExtension(&error);
935 if (!extension.get()) {
936 extension_load_errors_[i->id] = error;
937 continue;
939 OnLoadedInternal(extension);
941 // Update the available bindings for all contexts. These may have changed if
942 // an externally_connectable extension was loaded that can connect to an
943 // open webpage.
944 UpdateBindings("");
947 void Dispatcher::OnLoadedInternal(scoped_refptr<const Extension> extension) {
948 extensions_.Insert(extension);
951 void Dispatcher::OnMessageInvoke(const std::string& extension_id,
952 const std::string& module_name,
953 const std::string& function_name,
954 const base::ListValue& args,
955 bool user_gesture) {
956 InvokeModuleSystemMethod(
957 NULL, extension_id, module_name, function_name, args, user_gesture);
960 void Dispatcher::OnSetChannel(int channel) {
961 delegate_->SetChannel(channel);
964 void Dispatcher::OnSetFunctionNames(const std::vector<std::string>& names) {
965 function_names_.clear();
966 for (size_t i = 0; i < names.size(); ++i)
967 function_names_.insert(names[i]);
970 void Dispatcher::OnSetScriptingWhitelist(
971 const ExtensionsClient::ScriptingWhitelist& extension_ids) {
972 ExtensionsClient::Get()->SetScriptingWhitelist(extension_ids);
975 void Dispatcher::OnSetSystemFont(const std::string& font_family,
976 const std::string& font_size) {
977 system_font_family_ = font_family;
978 system_font_size_ = font_size;
981 void Dispatcher::OnShouldSuspend(const std::string& extension_id,
982 uint64 sequence_id) {
983 RenderThread::Get()->Send(
984 new ExtensionHostMsg_ShouldSuspendAck(extension_id, sequence_id));
987 void Dispatcher::OnSuspend(const std::string& extension_id) {
988 // Dispatch the suspend event. This doesn't go through the standard event
989 // dispatch machinery because it requires special handling. We need to let
990 // the browser know when we are starting and stopping the event dispatch, so
991 // that it still considers the extension idle despite any activity the suspend
992 // event creates.
993 DispatchEvent(extension_id, kOnSuspendEvent);
994 RenderThread::Get()->Send(new ExtensionHostMsg_SuspendAck(extension_id));
997 void Dispatcher::OnTransferBlobs(const std::vector<std::string>& blob_uuids) {
998 RenderThread::Get()->Send(new ExtensionHostMsg_TransferBlobsAck(blob_uuids));
1001 void Dispatcher::OnUnloaded(const std::string& id) {
1002 extensions_.Remove(id);
1003 active_extension_ids_.erase(id);
1005 script_injection_manager_->OnExtensionUnloaded(id);
1007 // If the extension is later reloaded with a different set of permissions,
1008 // we'd like it to get a new isolated world ID, so that it can pick up the
1009 // changed origin whitelist.
1010 ScriptInjection::RemoveIsolatedWorld(id);
1012 // Invalidate all of the contexts that were removed.
1013 // TODO(kalman): add an invalidation observer interface to ScriptContext.
1014 ScriptContextSet::ContextSet removed_contexts =
1015 script_context_set_.OnExtensionUnloaded(id);
1016 for (ScriptContextSet::ContextSet::iterator it = removed_contexts.begin();
1017 it != removed_contexts.end(); ++it) {
1018 request_sender_->InvalidateSource(*it);
1021 // Update the available bindings for the remaining contexts. These may have
1022 // changed if an externally_connectable extension is unloaded and a webpage
1023 // is no longer accessible.
1024 UpdateBindings("");
1026 // Invalidates the messages map for the extension in case the extension is
1027 // reloaded with a new messages map.
1028 EraseL10nMessagesMap(id);
1030 // We don't do anything with existing platform-app stylesheets. They will
1031 // stay resident, but the URL pattern corresponding to the unloaded
1032 // extension's URL just won't match anything anymore.
1035 void Dispatcher::OnUpdatePermissions(
1036 const ExtensionMsg_UpdatePermissions_Params& params) {
1037 const Extension* extension = extensions_.GetByID(params.extension_id);
1038 if (!extension)
1039 return;
1041 scoped_refptr<const PermissionSet> active =
1042 params.active_permissions.ToPermissionSet();
1043 scoped_refptr<const PermissionSet> withheld =
1044 params.withheld_permissions.ToPermissionSet();
1046 if (is_webkit_initialized_) {
1047 UpdateOriginPermissions(
1048 extension->url(),
1049 extension->permissions_data()->GetEffectiveHostPermissions(),
1050 active->effective_hosts());
1053 extension->permissions_data()->SetPermissions(active, withheld);
1054 UpdateBindings(extension->id());
1057 void Dispatcher::OnUpdateTabSpecificPermissions(const GURL& visible_url,
1058 const std::string& extension_id,
1059 const URLPatternSet& new_hosts,
1060 bool update_origin_whitelist,
1061 int tab_id) {
1062 // Check against the URL to avoid races. If we can't find the tab, it's
1063 // because this is an extension's background page (run in a different
1064 // process) - in this case, we can't perform the security check. However,
1065 // since activeTab is only granted via user action, this isn't a huge concern.
1066 content::RenderView* render_view = TabFinder::Find(tab_id);
1067 if (render_view &&
1068 render_view->GetWebView()->mainFrame()->document().url() != visible_url) {
1069 return;
1072 const Extension* extension = extensions_.GetByID(extension_id);
1073 if (!extension)
1074 return;
1076 URLPatternSet old_effective =
1077 extension->permissions_data()->GetEffectiveHostPermissions();
1078 extension->permissions_data()->UpdateTabSpecificPermissions(
1079 tab_id,
1080 new extensions::PermissionSet(extensions::APIPermissionSet(),
1081 extensions::ManifestPermissionSet(),
1082 new_hosts,
1083 extensions::URLPatternSet()));
1085 if (is_webkit_initialized_ && update_origin_whitelist) {
1086 UpdateOriginPermissions(
1087 extension->url(),
1088 old_effective,
1089 extension->permissions_data()->GetEffectiveHostPermissions());
1093 void Dispatcher::OnClearTabSpecificPermissions(
1094 const std::vector<std::string>& extension_ids,
1095 bool update_origin_whitelist,
1096 int tab_id) {
1097 for (const std::string& id : extension_ids) {
1098 const Extension* extension = extensions_.GetByID(id);
1099 if (extension) {
1100 URLPatternSet old_effective =
1101 extension->permissions_data()->GetEffectiveHostPermissions();
1102 extension->permissions_data()->ClearTabSpecificPermissions(tab_id);
1103 if (is_webkit_initialized_ && update_origin_whitelist) {
1104 UpdateOriginPermissions(
1105 extension->url(),
1106 old_effective,
1107 extension->permissions_data()->GetEffectiveHostPermissions());
1113 void Dispatcher::OnUsingWebRequestAPI(bool webrequest_used) {
1114 webrequest_used_ = webrequest_used;
1117 void Dispatcher::OnUserScriptsUpdated(const std::set<HostID>& changed_hosts,
1118 const std::vector<UserScript*>& scripts) {
1119 UpdateActiveExtensions();
1122 void Dispatcher::UpdateActiveExtensions() {
1123 std::set<std::string> active_extensions = active_extension_ids_;
1124 user_script_set_manager_->GetAllActiveExtensionIds(&active_extensions);
1125 delegate_->OnActiveExtensionsUpdated(active_extensions);
1128 void Dispatcher::InitOriginPermissions(const Extension* extension) {
1129 delegate_->InitOriginPermissions(extension,
1130 IsExtensionActive(extension->id()));
1131 UpdateOriginPermissions(
1132 extension->url(),
1133 URLPatternSet(), // No old permissions.
1134 extension->permissions_data()->GetEffectiveHostPermissions());
1137 void Dispatcher::UpdateOriginPermissions(const GURL& extension_url,
1138 const URLPatternSet& old_patterns,
1139 const URLPatternSet& new_patterns) {
1140 static const char* kSchemes[] = {
1141 url::kHttpScheme,
1142 url::kHttpsScheme,
1143 url::kFileScheme,
1144 content::kChromeUIScheme,
1145 url::kFtpScheme,
1146 #if defined(OS_CHROMEOS)
1147 content::kExternalFileScheme,
1148 #endif
1149 extensions::kExtensionScheme,
1151 for (size_t i = 0; i < arraysize(kSchemes); ++i) {
1152 const char* scheme = kSchemes[i];
1153 // Remove all old patterns...
1154 for (URLPatternSet::const_iterator pattern = old_patterns.begin();
1155 pattern != old_patterns.end(); ++pattern) {
1156 if (pattern->MatchesScheme(scheme)) {
1157 WebSecurityPolicy::removeOriginAccessWhitelistEntry(
1158 extension_url,
1159 WebString::fromUTF8(scheme),
1160 WebString::fromUTF8(pattern->host()),
1161 pattern->match_subdomains());
1164 // ...And add the new ones.
1165 for (URLPatternSet::const_iterator pattern = new_patterns.begin();
1166 pattern != new_patterns.end(); ++pattern) {
1167 if (pattern->MatchesScheme(scheme)) {
1168 WebSecurityPolicy::addOriginAccessWhitelistEntry(
1169 extension_url,
1170 WebString::fromUTF8(scheme),
1171 WebString::fromUTF8(pattern->host()),
1172 pattern->match_subdomains());
1178 void Dispatcher::EnableCustomElementWhiteList() {
1179 blink::WebCustomElement::addEmbedderCustomElementName("appview");
1180 blink::WebCustomElement::addEmbedderCustomElementName("appviewbrowserplugin");
1181 blink::WebCustomElement::addEmbedderCustomElementName("extensionoptions");
1182 blink::WebCustomElement::addEmbedderCustomElementName(
1183 "extensionoptionsbrowserplugin");
1184 blink::WebCustomElement::addEmbedderCustomElementName("extensionview");
1185 blink::WebCustomElement::addEmbedderCustomElementName(
1186 "extensionviewbrowserplugin");
1187 blink::WebCustomElement::addEmbedderCustomElementName("webview");
1188 blink::WebCustomElement::addEmbedderCustomElementName("webviewbrowserplugin");
1189 blink::WebCustomElement::addEmbedderCustomElementName("surfaceview");
1190 blink::WebCustomElement::addEmbedderCustomElementName(
1191 "surfaceviewbrowserplugin");
1194 void Dispatcher::UpdateBindings(const std::string& extension_id) {
1195 script_context_set().ForEach(extension_id,
1196 base::Bind(&Dispatcher::UpdateBindingsForContext,
1197 base::Unretained(this)));
1200 void Dispatcher::UpdateBindingsForContext(ScriptContext* context) {
1201 v8::HandleScope handle_scope(context->isolate());
1202 v8::Context::Scope context_scope(context->v8_context());
1204 // TODO(kalman): Make the bindings registration have zero overhead then run
1205 // the same code regardless of context type.
1206 switch (context->context_type()) {
1207 case Feature::UNSPECIFIED_CONTEXT:
1208 case Feature::WEB_PAGE_CONTEXT:
1209 case Feature::BLESSED_WEB_PAGE_CONTEXT:
1210 // Web page context; it's too expensive to run the full bindings code.
1211 // Hard-code that the app and webstore APIs are available...
1212 if (context->GetAvailability("app").is_available())
1213 RegisterBinding("app", context);
1214 if (context->GetAvailability("webstore").is_available())
1215 RegisterBinding("webstore", context);
1216 if (IsRuntimeAvailableToContext(context))
1217 RegisterBinding("runtime", context);
1218 UpdateContentCapabilities(context);
1219 break;
1221 case Feature::BLESSED_EXTENSION_CONTEXT:
1222 case Feature::UNBLESSED_EXTENSION_CONTEXT:
1223 case Feature::CONTENT_SCRIPT_CONTEXT:
1224 case Feature::WEBUI_CONTEXT: {
1225 // Extension context; iterate through all the APIs and bind the available
1226 // ones.
1227 const FeatureProvider* api_feature_provider =
1228 FeatureProvider::GetAPIFeatures();
1229 const std::vector<std::string>& apis =
1230 api_feature_provider->GetAllFeatureNames();
1231 for (std::vector<std::string>::const_iterator it = apis.begin();
1232 it != apis.end();
1233 ++it) {
1234 const std::string& api_name = *it;
1235 Feature* feature = api_feature_provider->GetFeature(api_name);
1236 DCHECK(feature);
1238 // Internal APIs are included via require(api_name) from internal code
1239 // rather than chrome[api_name].
1240 if (feature->IsInternal())
1241 continue;
1243 // If this API has a parent feature (and isn't marked 'noparent'),
1244 // then this must be a function or event, so we should not register.
1245 if (api_feature_provider->GetParent(feature) != NULL)
1246 continue;
1248 // Skip chrome.test if this isn't a test.
1249 if (api_name == "test" &&
1250 !base::CommandLine::ForCurrentProcess()->HasSwitch(
1251 ::switches::kTestType)) {
1252 continue;
1255 if (context->IsAnyFeatureAvailableToContext(*feature))
1256 RegisterBinding(api_name, context);
1258 break;
1263 void Dispatcher::RegisterBinding(const std::string& api_name,
1264 ScriptContext* context) {
1265 std::string bind_name;
1266 v8::Handle<v8::Object> bind_object =
1267 GetOrCreateBindObjectIfAvailable(api_name, &bind_name, context);
1269 // Empty if the bind object failed to be created, probably because the
1270 // extension overrode chrome with a non-object, e.g. window.chrome = true.
1271 if (bind_object.IsEmpty())
1272 return;
1274 v8::Local<v8::String> v8_bind_name =
1275 v8::String::NewFromUtf8(context->isolate(), bind_name.c_str());
1276 if (bind_object->HasRealNamedProperty(v8_bind_name)) {
1277 // The bind object may already have the property if the API has been
1278 // registered before (or if the extension has put something there already,
1279 // but, whatevs).
1281 // In the former case, we need to re-register the bindings for the APIs
1282 // which the extension now has permissions for (if any), but not touch any
1283 // others so that we don't destroy state such as event listeners.
1285 // TODO(kalman): Only register available APIs to make this all moot.
1286 if (bind_object->HasRealNamedCallbackProperty(v8_bind_name))
1287 return; // lazy binding still there, nothing to do
1288 if (bind_object->Get(v8_bind_name)->IsObject())
1289 return; // binding has already been fully installed
1292 ModuleSystem* module_system = context->module_system();
1293 if (!source_map_.Contains(api_name)) {
1294 module_system->RegisterNativeHandler(
1295 api_name,
1296 scoped_ptr<NativeHandler>(new BindingGeneratingNativeHandler(
1297 module_system, api_name, "binding")));
1298 module_system->SetNativeLazyField(
1299 bind_object, bind_name, api_name, "binding");
1300 } else {
1301 module_system->SetLazyField(bind_object, bind_name, api_name, "binding");
1305 // NOTE: please use the naming convention "foo_natives" for these.
1306 void Dispatcher::RegisterNativeHandlers(ModuleSystem* module_system,
1307 ScriptContext* context) {
1308 RegisterNativeHandlers(module_system,
1309 context,
1310 this,
1311 request_sender_.get(),
1312 v8_schema_registry_.get());
1313 const Extension* extension = context->extension();
1314 int manifest_version = extension ? extension->manifest_version() : 1;
1315 bool is_component_extension =
1316 extension && Manifest::IsComponentLocation(extension->location());
1317 bool send_request_disabled =
1318 (extension && Manifest::IsUnpackedLocation(extension->location()) &&
1319 BackgroundInfo::HasLazyBackgroundPage(extension));
1320 module_system->RegisterNativeHandler(
1321 "process",
1322 scoped_ptr<NativeHandler>(new ProcessInfoNativeHandler(
1323 context,
1324 context->GetExtensionID(),
1325 context->GetContextTypeDescription(),
1326 ExtensionsRendererClient::Get()->IsIncognitoProcess(),
1327 is_component_extension,
1328 manifest_version,
1329 send_request_disabled)));
1331 delegate_->RegisterNativeHandlers(this, module_system, context);
1334 bool Dispatcher::IsRuntimeAvailableToContext(ScriptContext* context) {
1335 if (extensions::FeatureSwitch::surface_worker()->IsEnabled() &&
1336 context->GetAvailability("surfaceWorkerInternal").is_available()) {
1337 return true;
1339 for (const auto& extension : extensions_) {
1340 ExternallyConnectableInfo* info = static_cast<ExternallyConnectableInfo*>(
1341 extension->GetManifestData(manifest_keys::kExternallyConnectable));
1342 if (info && info->matches.MatchesURL(context->GetURL()))
1343 return true;
1345 return false;
1348 void Dispatcher::UpdateContentCapabilities(ScriptContext* context) {
1349 APIPermissionSet permissions;
1350 for (const auto& extension : extensions_) {
1351 const ContentCapabilitiesInfo& info =
1352 ContentCapabilitiesInfo::Get(extension.get());
1353 if (info.url_patterns.MatchesURL(context->GetURL())) {
1354 APIPermissionSet new_permissions;
1355 APIPermissionSet::Union(permissions, info.permissions, &new_permissions);
1356 permissions = new_permissions;
1359 context->SetContentCapabilities(permissions);
1362 void Dispatcher::PopulateSourceMap() {
1363 const std::vector<std::pair<std::string, int> > resources = GetJsResources();
1364 for (std::vector<std::pair<std::string, int> >::const_iterator resource =
1365 resources.begin();
1366 resource != resources.end();
1367 ++resource) {
1368 source_map_.RegisterSource(resource->first, resource->second);
1370 delegate_->PopulateSourceMap(&source_map_);
1373 bool Dispatcher::IsWithinPlatformApp() {
1374 for (std::set<std::string>::iterator iter = active_extension_ids_.begin();
1375 iter != active_extension_ids_.end();
1376 ++iter) {
1377 const Extension* extension = extensions_.GetByID(*iter);
1378 if (extension && extension->is_platform_app())
1379 return true;
1381 return false;
1384 // TODO(kalman): This is checking for the wrong thing, it should be checking if
1385 // the frame's security origin is unique. The extension sandbox directive is
1386 // checked for in extensions/common/manifest_handlers/csp_info.cc.
1387 bool Dispatcher::IsSandboxedPage(const GURL& url) const {
1388 if (url.SchemeIs(kExtensionScheme)) {
1389 const Extension* extension = extensions_.GetByID(url.host());
1390 if (extension) {
1391 return SandboxedPageInfo::IsSandboxedPage(extension, url.path());
1394 return false;
1397 Feature::Context Dispatcher::ClassifyJavaScriptContext(
1398 const Extension* extension,
1399 int extension_group,
1400 const GURL& url,
1401 const blink::WebSecurityOrigin& origin) {
1402 // WARNING: This logic must match ProcessMap::GetContextType, as much as
1403 // possible.
1405 DCHECK_GE(extension_group, 0);
1406 if (extension_group == EXTENSION_GROUP_CONTENT_SCRIPTS) {
1407 return extension ? // TODO(kalman): when does this happen?
1408 Feature::CONTENT_SCRIPT_CONTEXT
1409 : Feature::UNSPECIFIED_CONTEXT;
1412 // We have an explicit check for sandboxed pages before checking whether the
1413 // extension is active in this process because:
1414 // 1. Sandboxed pages run in the same process as regular extension pages, so
1415 // the extension is considered active.
1416 // 2. ScriptContext creation (which triggers bindings injection) happens
1417 // before the SecurityContext is updated with the sandbox flags (after
1418 // reading the CSP header), so the caller can't check if the context's
1419 // security origin is unique yet.
1420 if (IsSandboxedPage(url))
1421 return Feature::WEB_PAGE_CONTEXT;
1423 if (extension && IsExtensionActive(extension->id())) {
1424 // |extension| is active in this process, but it could be either a true
1425 // extension process or within the extent of a hosted app. In the latter
1426 // case this would usually be considered a (blessed) web page context,
1427 // unless the extension in question is a component extension, in which case
1428 // we cheat and call it blessed.
1429 return (extension->is_hosted_app() &&
1430 extension->location() != Manifest::COMPONENT)
1431 ? Feature::BLESSED_WEB_PAGE_CONTEXT
1432 : Feature::BLESSED_EXTENSION_CONTEXT;
1435 // TODO(kalman): This isUnique() check is wrong, it should be performed as
1436 // part of IsSandboxedPage().
1437 if (!origin.isUnique() && extensions_.ExtensionBindingsAllowed(url)) {
1438 if (!extension) // TODO(kalman): when does this happen?
1439 return Feature::UNSPECIFIED_CONTEXT;
1440 return extension->is_hosted_app() ? Feature::BLESSED_WEB_PAGE_CONTEXT
1441 : Feature::UNBLESSED_EXTENSION_CONTEXT;
1444 if (!url.is_valid())
1445 return Feature::UNSPECIFIED_CONTEXT;
1447 if (url.SchemeIs(content::kChromeUIScheme))
1448 return Feature::WEBUI_CONTEXT;
1450 return Feature::WEB_PAGE_CONTEXT;
1453 v8::Handle<v8::Object> Dispatcher::GetOrCreateObject(
1454 const v8::Handle<v8::Object>& object,
1455 const std::string& field,
1456 v8::Isolate* isolate) {
1457 v8::Handle<v8::String> key = v8::String::NewFromUtf8(isolate, field.c_str());
1458 // If the object has a callback property, it is assumed it is an unavailable
1459 // API, so it is safe to delete. This is checked before GetOrCreateObject is
1460 // called.
1461 if (object->HasRealNamedCallbackProperty(key)) {
1462 object->Delete(key);
1463 } else if (object->HasRealNamedProperty(key)) {
1464 v8::Handle<v8::Value> value = object->Get(key);
1465 CHECK(value->IsObject());
1466 return v8::Handle<v8::Object>::Cast(value);
1469 v8::Handle<v8::Object> new_object = v8::Object::New(isolate);
1470 object->Set(key, new_object);
1471 return new_object;
1474 v8::Handle<v8::Object> Dispatcher::GetOrCreateBindObjectIfAvailable(
1475 const std::string& api_name,
1476 std::string* bind_name,
1477 ScriptContext* context) {
1478 std::vector<std::string> split;
1479 base::SplitString(api_name, '.', &split);
1481 v8::Handle<v8::Object> bind_object;
1483 // Check if this API has an ancestor. If the API's ancestor is available and
1484 // the API is not available, don't install the bindings for this API. If
1485 // the API is available and its ancestor is not, delete the ancestor and
1486 // install the bindings for the API. This is to prevent loading the ancestor
1487 // API schema if it will not be needed.
1489 // For example:
1490 // If app is available and app.window is not, just install app.
1491 // If app.window is available and app is not, delete app and install
1492 // app.window on a new object so app does not have to be loaded.
1493 const FeatureProvider* api_feature_provider =
1494 FeatureProvider::GetAPIFeatures();
1495 std::string ancestor_name;
1496 bool only_ancestor_available = false;
1498 for (size_t i = 0; i < split.size() - 1; ++i) {
1499 ancestor_name += (i ? "." : "") + split[i];
1500 if (api_feature_provider->GetFeature(ancestor_name) &&
1501 context->GetAvailability(ancestor_name).is_available() &&
1502 !context->GetAvailability(api_name).is_available()) {
1503 only_ancestor_available = true;
1504 break;
1507 if (bind_object.IsEmpty()) {
1508 bind_object = AsObjectOrEmpty(GetOrCreateChrome(context));
1509 if (bind_object.IsEmpty())
1510 return v8::Handle<v8::Object>();
1512 bind_object = GetOrCreateObject(bind_object, split[i], context->isolate());
1515 if (only_ancestor_available)
1516 return v8::Handle<v8::Object>();
1518 if (bind_name)
1519 *bind_name = split.back();
1521 return bind_object.IsEmpty() ? AsObjectOrEmpty(GetOrCreateChrome(context))
1522 : bind_object;
1525 void Dispatcher::RequireGuestViewModules(ScriptContext* context) {
1526 Feature::Context context_type = context->context_type();
1527 ModuleSystem* module_system = context->module_system();
1529 // Require AppView.
1530 if (context->GetAvailability("appViewEmbedderInternal").is_available()) {
1531 module_system->Require("appView");
1534 // Require ExtensionOptions.
1535 if (context->GetAvailability("extensionOptionsInternal").is_available()) {
1536 module_system->Require("extensionOptions");
1537 module_system->Require("extensionOptionsAttributes");
1540 // Require ExtensionView.
1541 if (context->GetAvailability("extensionViewInternal").is_available()) {
1542 module_system->Require("extensionView");
1543 module_system->Require("extensionViewApiMethods");
1544 module_system->Require("extensionViewAttributes");
1547 // Require SurfaceView.
1548 if (extensions::FeatureSwitch::surface_worker()->IsEnabled() &&
1549 context->GetAvailability("surfaceWorkerInternal").is_available()) {
1550 module_system->Require("surfaceWorker");
1553 // Require WebView.
1554 if (context->GetAvailability("webViewInternal").is_available()) {
1555 module_system->Require("webView");
1556 module_system->Require("webViewApiMethods");
1557 module_system->Require("webViewAttributes");
1560 // The "guestViewDeny" module must always be loaded last. It registers
1561 // error-providing custom elements for the GuestView types that are not
1562 // available, and thus all of those types must have been checked and loaded
1563 // (or not loaded) beforehand.
1564 if (context_type == Feature::BLESSED_EXTENSION_CONTEXT) {
1565 module_system->Require("guestViewDeny");
1569 } // namespace extensions