Revert "Revert of Revert of Revert of ChromeOS NetworkScreenHandler should not call...
[chromium-blink-merge.git] / extensions / renderer / dispatcher.cc
blobcfe247d67e347c42fd7b85096d9d4e253f062118
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/user_metrics_action.h"
13 #include "base/strings/string_piece.h"
14 #include "base/strings/string_split.h"
15 #include "base/strings/string_util.h"
16 #include "base/values.h"
17 #include "content/grit/content_resources.h"
18 #include "content/public/common/content_switches.h"
19 #include "content/public/common/url_constants.h"
20 #include "content/public/renderer/render_thread.h"
21 #include "content/public/renderer/render_view.h"
22 #include "content/public/renderer/v8_value_converter.h"
23 #include "extensions/common/api/messaging/message.h"
24 #include "extensions/common/constants.h"
25 #include "extensions/common/extension.h"
26 #include "extensions/common/extension_api.h"
27 #include "extensions/common/extension_messages.h"
28 #include "extensions/common/extension_urls.h"
29 #include "extensions/common/features/feature.h"
30 #include "extensions/common/features/feature_provider.h"
31 #include "extensions/common/manifest.h"
32 #include "extensions/common/manifest_constants.h"
33 #include "extensions/common/manifest_handlers/background_info.h"
34 #include "extensions/common/manifest_handlers/externally_connectable.h"
35 #include "extensions/common/manifest_handlers/options_page_info.h"
36 #include "extensions/common/manifest_handlers/sandboxed_page_info.h"
37 #include "extensions/common/message_bundle.h"
38 #include "extensions/common/permissions/permission_set.h"
39 #include "extensions/common/permissions/permissions_data.h"
40 #include "extensions/common/switches.h"
41 #include "extensions/common/view_type.h"
42 #include "extensions/renderer/api_activity_logger.h"
43 #include "extensions/renderer/api_definitions_natives.h"
44 #include "extensions/renderer/app_runtime_custom_bindings.h"
45 #include "extensions/renderer/app_window_custom_bindings.h"
46 #include "extensions/renderer/binding_generating_native_handler.h"
47 #include "extensions/renderer/blob_native_handler.h"
48 #include "extensions/renderer/content_watcher.h"
49 #include "extensions/renderer/context_menus_custom_bindings.h"
50 #include "extensions/renderer/css_native_handler.h"
51 #include "extensions/renderer/dispatcher_delegate.h"
52 #include "extensions/renderer/document_custom_bindings.h"
53 #include "extensions/renderer/dom_activity_logger.h"
54 #include "extensions/renderer/event_bindings.h"
55 #include "extensions/renderer/extension_groups.h"
56 #include "extensions/renderer/extension_helper.h"
57 #include "extensions/renderer/extensions_renderer_client.h"
58 #include "extensions/renderer/file_system_natives.h"
59 #include "extensions/renderer/guest_view/guest_view_internal_custom_bindings.h"
60 #include "extensions/renderer/i18n_custom_bindings.h"
61 #include "extensions/renderer/id_generator_custom_bindings.h"
62 #include "extensions/renderer/lazy_background_page_native_handler.h"
63 #include "extensions/renderer/logging_native_handler.h"
64 #include "extensions/renderer/messaging_bindings.h"
65 #include "extensions/renderer/module_system.h"
66 #include "extensions/renderer/print_native_handler.h"
67 #include "extensions/renderer/process_info_native_handler.h"
68 #include "extensions/renderer/render_view_observer_natives.h"
69 #include "extensions/renderer/request_sender.h"
70 #include "extensions/renderer/runtime_custom_bindings.h"
71 #include "extensions/renderer/safe_builtins.h"
72 #include "extensions/renderer/script_context.h"
73 #include "extensions/renderer/script_context_set.h"
74 #include "extensions/renderer/script_injection.h"
75 #include "extensions/renderer/script_injection_manager.h"
76 #include "extensions/renderer/send_request_natives.h"
77 #include "extensions/renderer/set_icon_natives.h"
78 #include "extensions/renderer/test_features_native_handler.h"
79 #include "extensions/renderer/user_gestures_native_handler.h"
80 #include "extensions/renderer/utils_native_handler.h"
81 #include "extensions/renderer/v8_context_native_handler.h"
82 #include "grit/extensions_renderer_resources.h"
83 #include "mojo/public/js/constants.h"
84 #include "third_party/WebKit/public/platform/WebString.h"
85 #include "third_party/WebKit/public/platform/WebURLRequest.h"
86 #include "third_party/WebKit/public/web/WebCustomElement.h"
87 #include "third_party/WebKit/public/web/WebDataSource.h"
88 #include "third_party/WebKit/public/web/WebDocument.h"
89 #include "third_party/WebKit/public/web/WebFrame.h"
90 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
91 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
92 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
93 #include "third_party/WebKit/public/web/WebView.h"
94 #include "ui/base/layout.h"
95 #include "ui/base/resource/resource_bundle.h"
96 #include "v8/include/v8.h"
98 using base::UserMetricsAction;
99 using blink::WebDataSource;
100 using blink::WebDocument;
101 using blink::WebFrame;
102 using blink::WebScopedUserGesture;
103 using blink::WebSecurityPolicy;
104 using blink::WebString;
105 using blink::WebVector;
106 using blink::WebView;
107 using content::RenderThread;
108 using content::RenderView;
110 namespace extensions {
112 namespace {
114 static const int64 kInitialExtensionIdleHandlerDelayMs = 5 * 1000;
115 static const int64 kMaxExtensionIdleHandlerDelayMs = 5 * 60 * 1000;
116 static const char kEventDispatchFunction[] = "dispatchEvent";
117 static const char kOnSuspendEvent[] = "runtime.onSuspend";
118 static const char kOnSuspendCanceledEvent[] = "runtime.onSuspendCanceled";
120 // Returns the global value for "chrome" from |context|. If one doesn't exist
121 // creates a new object for it.
123 // Note that this isn't necessarily an object, since webpages can write, for
124 // example, "window.chrome = true".
125 v8::Handle<v8::Value> GetOrCreateChrome(ScriptContext* context) {
126 v8::Handle<v8::String> chrome_string(
127 v8::String::NewFromUtf8(context->isolate(), "chrome"));
128 v8::Handle<v8::Object> global(context->v8_context()->Global());
129 v8::Handle<v8::Value> chrome(global->Get(chrome_string));
130 if (chrome->IsUndefined()) {
131 chrome = v8::Object::New(context->isolate());
132 global->Set(chrome_string, chrome);
134 return chrome;
137 // Returns |value| cast to an object if possible, else an empty handle.
138 v8::Handle<v8::Object> AsObjectOrEmpty(v8::Handle<v8::Value> value) {
139 return value->IsObject() ? value.As<v8::Object>() : v8::Handle<v8::Object>();
142 // Calls a method |method_name| in a module |module_name| belonging to the
143 // module system from |context|. Intended as a callback target from
144 // ScriptContextSet::ForEach.
145 void CallModuleMethod(const std::string& module_name,
146 const std::string& method_name,
147 const base::ListValue* args,
148 ScriptContext* context) {
149 v8::HandleScope handle_scope(context->isolate());
150 v8::Context::Scope context_scope(context->v8_context());
152 scoped_ptr<content::V8ValueConverter> converter(
153 content::V8ValueConverter::create());
155 std::vector<v8::Handle<v8::Value> > arguments;
156 for (base::ListValue::const_iterator it = args->begin(); it != args->end();
157 ++it) {
158 arguments.push_back(converter->ToV8Value(*it, context->v8_context()));
161 context->module_system()->CallModuleMethod(
162 module_name, method_name, &arguments);
165 // This handles the "chrome." root API object in script contexts.
166 class ChromeNativeHandler : public ObjectBackedNativeHandler {
167 public:
168 explicit ChromeNativeHandler(ScriptContext* context)
169 : ObjectBackedNativeHandler(context) {
170 RouteFunction(
171 "GetChrome",
172 base::Bind(&ChromeNativeHandler::GetChrome, base::Unretained(this)));
175 void GetChrome(const v8::FunctionCallbackInfo<v8::Value>& args) {
176 args.GetReturnValue().Set(GetOrCreateChrome(context()));
180 } // namespace
182 Dispatcher::Dispatcher(DispatcherDelegate* delegate)
183 : delegate_(delegate),
184 content_watcher_(new ContentWatcher()),
185 source_map_(&ResourceBundle::GetSharedInstance()),
186 v8_schema_registry_(new V8SchemaRegistry),
187 is_webkit_initialized_(false),
188 user_script_set_manager_observer_(this),
189 webrequest_used_(false) {
190 const CommandLine& command_line = *(CommandLine::ForCurrentProcess());
191 is_extension_process_ =
192 command_line.HasSwitch(switches::kExtensionProcess) ||
193 command_line.HasSwitch(::switches::kSingleProcess);
195 if (is_extension_process_) {
196 RenderThread::Get()->SetIdleNotificationDelayInMs(
197 kInitialExtensionIdleHandlerDelayMs);
200 RenderThread::Get()->RegisterExtension(SafeBuiltins::CreateV8Extension());
202 user_script_set_manager_.reset(new UserScriptSetManager(&extensions_));
203 script_injection_manager_.reset(
204 new ScriptInjectionManager(&extensions_, user_script_set_manager_.get()));
205 user_script_set_manager_observer_.Add(user_script_set_manager_.get());
206 request_sender_.reset(new RequestSender(this));
207 PopulateSourceMap();
210 Dispatcher::~Dispatcher() {
213 void Dispatcher::OnRenderViewCreated(content::RenderView* render_view) {
214 script_injection_manager_->OnRenderViewCreated(render_view);
217 bool Dispatcher::IsExtensionActive(const std::string& extension_id) const {
218 bool is_active =
219 active_extension_ids_.find(extension_id) != active_extension_ids_.end();
220 if (is_active)
221 CHECK(extensions_.Contains(extension_id));
222 return is_active;
225 const Extension* Dispatcher::GetExtensionFromFrameAndWorld(
226 const WebFrame* frame,
227 int world_id,
228 bool use_effective_url) {
229 std::string extension_id;
230 if (world_id != 0) {
231 // Isolated worlds (content script).
232 extension_id = ScriptInjection::GetExtensionIdForIsolatedWorld(world_id);
233 } else if (!frame->document().securityOrigin().isUnique()) {
234 // TODO(kalman): Delete the above check.
236 // Extension pages (chrome-extension:// URLs).
237 GURL frame_url = ScriptContext::GetDataSourceURLForFrame(frame);
238 frame_url = ScriptContext::GetEffectiveDocumentURL(
239 frame, frame_url, use_effective_url);
240 extension_id = extensions_.GetExtensionOrAppIDByURL(frame_url);
243 const Extension* extension = extensions_.GetByID(extension_id);
244 if (!extension && !extension_id.empty()) {
245 // There are conditions where despite a context being associated with an
246 // extension, no extension actually gets found. Ignore "invalid" because
247 // CSP blocks extension page loading by switching the extension ID to
248 // "invalid". This isn't interesting.
249 if (extension_id != "invalid") {
250 LOG(ERROR) << "Extension \"" << extension_id << "\" not found";
251 RenderThread::Get()->RecordAction(
252 UserMetricsAction("ExtensionNotFound_ED"));
255 return extension;
258 void Dispatcher::DidCreateScriptContext(
259 WebFrame* frame,
260 const v8::Handle<v8::Context>& v8_context,
261 int extension_group,
262 int world_id) {
263 const Extension* extension =
264 GetExtensionFromFrameAndWorld(frame, world_id, false);
265 const Extension* effective_extension =
266 GetExtensionFromFrameAndWorld(frame, world_id, true);
268 GURL frame_url = ScriptContext::GetDataSourceURLForFrame(frame);
269 Feature::Context context_type =
270 ClassifyJavaScriptContext(extension,
271 extension_group,
272 frame_url,
273 frame->document().securityOrigin());
274 Feature::Context effective_context_type = ClassifyJavaScriptContext(
275 effective_extension,
276 extension_group,
277 ScriptContext::GetEffectiveDocumentURL(frame, frame_url, true),
278 frame->document().securityOrigin());
280 ScriptContext* context =
281 delegate_->CreateScriptContext(v8_context,
282 frame,
283 extension,
284 context_type,
285 effective_extension,
286 effective_context_type).release();
287 script_context_set_.Add(context);
289 // Initialize origin permissions for content scripts, which can't be
290 // initialized in |OnActivateExtension|.
291 if (context_type == Feature::CONTENT_SCRIPT_CONTEXT)
292 InitOriginPermissions(extension);
295 scoped_ptr<ModuleSystem> module_system(
296 new ModuleSystem(context, &source_map_));
297 context->set_module_system(module_system.Pass());
299 ModuleSystem* module_system = context->module_system();
301 // Enable natives in startup.
302 ModuleSystem::NativesEnabledScope natives_enabled_scope(module_system);
304 RegisterNativeHandlers(module_system, context);
306 // chrome.Event is part of the public API (although undocumented). Make it
307 // lazily evalulate to Event from event_bindings.js. For extensions only
308 // though, not all webpages!
309 if (context->extension()) {
310 v8::Handle<v8::Object> chrome = AsObjectOrEmpty(GetOrCreateChrome(context));
311 if (!chrome.IsEmpty())
312 module_system->SetLazyField(chrome, "Event", kEventBindings, "Event");
315 UpdateBindingsForContext(context);
317 bool is_within_platform_app = IsWithinPlatformApp();
318 // Inject custom JS into the platform app context.
319 if (is_within_platform_app) {
320 module_system->Require("platformApp");
323 if (context->GetAvailability("appViewEmbedderInternal").is_available()) {
324 module_system->Require("appView");
325 } else if (context_type == Feature::BLESSED_EXTENSION_CONTEXT) {
326 module_system->Require("denyAppView");
329 // Note: setting up the WebView class here, not the chrome.webview API.
330 // The API will be automatically set up when first used.
331 if (context->GetAvailability("webViewInternal").is_available()) {
332 module_system->Require("webView");
333 module_system->Require("webViewConstants");
334 module_system->Require("webViewAttributes");
335 if (context->GetAvailability("webViewExperimentalInternal")
336 .is_available()) {
337 module_system->Require("webViewExperimental");
339 } else if (context_type == Feature::BLESSED_EXTENSION_CONTEXT) {
340 module_system->Require("denyWebView");
343 delegate_->RequireAdditionalModules(context, is_within_platform_app);
345 VLOG(1) << "Num tracked contexts: " << script_context_set_.size();
348 void Dispatcher::WillReleaseScriptContext(
349 WebFrame* frame,
350 const v8::Handle<v8::Context>& v8_context,
351 int world_id) {
352 ScriptContext* context = script_context_set_.GetByV8Context(v8_context);
353 if (!context)
354 return;
356 context->DispatchOnUnloadEvent();
357 // TODO(kalman): add an invalidation observer interface to ScriptContext.
358 request_sender_->InvalidateSource(context);
360 script_context_set_.Remove(context);
361 VLOG(1) << "Num tracked contexts: " << script_context_set_.size();
364 void Dispatcher::DidCreateDocumentElement(blink::WebFrame* frame) {
365 // Note: use GetEffectiveDocumentURL not just frame->document()->url()
366 // so that this also injects the stylesheet on about:blank frames that
367 // are hosted in the extension process.
368 GURL effective_document_url = ScriptContext::GetEffectiveDocumentURL(
369 frame, frame->document().url(), true /* match_about_blank */);
371 const Extension* extension =
372 extensions_.GetExtensionOrAppByURL(effective_document_url);
374 if (extension &&
375 (extension->is_extension() || extension->is_platform_app())) {
376 int resource_id = extension->is_platform_app() ? IDR_PLATFORM_APP_CSS
377 : IDR_EXTENSION_FONTS_CSS;
378 std::string stylesheet = ResourceBundle::GetSharedInstance()
379 .GetRawDataResource(resource_id)
380 .as_string();
381 ReplaceFirstSubstringAfterOffset(
382 &stylesheet, 0, "$FONTFAMILY", system_font_family_);
383 ReplaceFirstSubstringAfterOffset(
384 &stylesheet, 0, "$FONTSIZE", system_font_size_);
386 // Blink doesn't let us define an additional user agent stylesheet, so
387 // we insert the default platform app or extension stylesheet into all
388 // documents that are loaded in each app or extension.
389 frame->document().insertStyleSheet(WebString::fromUTF8(stylesheet));
392 // If this is an extension options page, and the extension has opted into
393 // using Chrome styles, then insert the Chrome extension stylesheet.
394 if (extension && extension->is_extension() &&
395 OptionsPageInfo::ShouldUseChromeStyle(extension) &&
396 effective_document_url == OptionsPageInfo::GetOptionsPage(extension)) {
397 frame->document().insertStyleSheet(
398 WebString::fromUTF8(ResourceBundle::GetSharedInstance()
399 .GetRawDataResource(IDR_EXTENSION_CSS)
400 .as_string()));
403 content_watcher_->DidCreateDocumentElement(frame);
406 void Dispatcher::DidMatchCSS(
407 blink::WebFrame* frame,
408 const blink::WebVector<blink::WebString>& newly_matching_selectors,
409 const blink::WebVector<blink::WebString>& stopped_matching_selectors) {
410 content_watcher_->DidMatchCSS(
411 frame, newly_matching_selectors, stopped_matching_selectors);
414 void Dispatcher::OnExtensionResponse(int request_id,
415 bool success,
416 const base::ListValue& response,
417 const std::string& error) {
418 request_sender_->HandleResponse(request_id, success, response, error);
421 bool Dispatcher::CheckContextAccessToExtensionAPI(
422 const std::string& function_name,
423 ScriptContext* context) const {
424 if (!context) {
425 DLOG(ERROR) << "Not in a v8::Context";
426 return false;
429 // Theoretically we could end up with bindings being injected into sandboxed
430 // frames, for example content scripts. Don't let them execute API functions.
431 blink::WebFrame* frame = context->web_frame();
432 if (IsSandboxedPage(ScriptContext::GetDataSourceURLForFrame(frame))) {
433 static const char kMessage[] =
434 "%s cannot be used within a sandboxed frame.";
435 std::string error_msg = base::StringPrintf(kMessage, function_name.c_str());
436 context->isolate()->ThrowException(v8::Exception::Error(
437 v8::String::NewFromUtf8(context->isolate(), error_msg.c_str())));
438 return false;
441 Feature::Availability availability = context->GetAvailability(function_name);
442 if (!availability.is_available()) {
443 context->isolate()->ThrowException(
444 v8::Exception::Error(v8::String::NewFromUtf8(
445 context->isolate(), availability.message().c_str())));
448 return availability.is_available();
451 void Dispatcher::DispatchEvent(const std::string& extension_id,
452 const std::string& event_name) const {
453 base::ListValue args;
454 args.Set(0, new base::StringValue(event_name));
455 args.Set(1, new base::ListValue());
457 // Needed for Windows compilation, since kEventBindings is declared extern.
458 const char* local_event_bindings = kEventBindings;
459 script_context_set_.ForEach(extension_id,
460 base::Bind(&CallModuleMethod,
461 local_event_bindings,
462 kEventDispatchFunction,
463 &args));
466 void Dispatcher::InvokeModuleSystemMethod(content::RenderView* render_view,
467 const std::string& extension_id,
468 const std::string& module_name,
469 const std::string& function_name,
470 const base::ListValue& args,
471 bool user_gesture) {
472 scoped_ptr<WebScopedUserGesture> web_user_gesture;
473 if (user_gesture)
474 web_user_gesture.reset(new WebScopedUserGesture);
476 script_context_set_.ForEach(
477 extension_id,
478 render_view,
479 base::Bind(&CallModuleMethod, module_name, function_name, &args));
481 // Reset the idle handler each time there's any activity like event or message
482 // dispatch, for which Invoke is the chokepoint.
483 if (is_extension_process_) {
484 RenderThread::Get()->ScheduleIdleHandler(
485 kInitialExtensionIdleHandlerDelayMs);
488 // Tell the browser process when an event has been dispatched with a lazy
489 // background page active.
490 const Extension* extension = extensions_.GetByID(extension_id);
491 if (extension && BackgroundInfo::HasLazyBackgroundPage(extension) &&
492 module_name == kEventBindings &&
493 function_name == kEventDispatchFunction) {
494 RenderView* background_view =
495 ExtensionHelper::GetBackgroundPage(extension_id);
496 if (background_view) {
497 background_view->Send(
498 new ExtensionHostMsg_EventAck(background_view->GetRoutingID()));
503 void Dispatcher::ClearPortData(int port_id) {
504 // Only the target port side has entries in |port_to_tab_id_map_|. If
505 // |port_id| is a source port, std::map::erase() will just silently fail
506 // here as a no-op.
507 port_to_tab_id_map_.erase(port_id);
510 // static
511 std::vector<std::pair<std::string, int> > Dispatcher::GetJsResources() {
512 std::vector<std::pair<std::string, int> > resources;
514 // Libraries.
515 resources.push_back(std::make_pair("appView", IDR_APP_VIEW_JS));
516 resources.push_back(std::make_pair("denyAppView", IDR_APP_VIEW_DENY_JS));
517 resources.push_back(std::make_pair("entryIdManager", IDR_ENTRY_ID_MANAGER));
518 resources.push_back(std::make_pair(kEventBindings, IDR_EVENT_BINDINGS_JS));
519 resources.push_back(std::make_pair("imageUtil", IDR_IMAGE_UTIL_JS));
520 resources.push_back(std::make_pair("json_schema", IDR_JSON_SCHEMA_JS));
521 resources.push_back(std::make_pair("lastError", IDR_LAST_ERROR_JS));
522 resources.push_back(std::make_pair("messaging", IDR_MESSAGING_JS));
523 resources.push_back(
524 std::make_pair("messaging_utils", IDR_MESSAGING_UTILS_JS));
525 resources.push_back(std::make_pair(kSchemaUtils, IDR_SCHEMA_UTILS_JS));
526 resources.push_back(std::make_pair("sendRequest", IDR_SEND_REQUEST_JS));
527 resources.push_back(std::make_pair("setIcon", IDR_SET_ICON_JS));
528 resources.push_back(std::make_pair("test", IDR_TEST_CUSTOM_BINDINGS_JS));
529 resources.push_back(
530 std::make_pair("test_environment_specific_bindings",
531 IDR_BROWSER_TEST_ENVIRONMENT_SPECIFIC_BINDINGS_JS));
532 resources.push_back(std::make_pair("uncaught_exception_handler",
533 IDR_UNCAUGHT_EXCEPTION_HANDLER_JS));
534 resources.push_back(std::make_pair("unload_event", IDR_UNLOAD_EVENT_JS));
535 resources.push_back(std::make_pair("utils", IDR_UTILS_JS));
536 resources.push_back(std::make_pair("webRequest",
537 IDR_WEB_REQUEST_CUSTOM_BINDINGS_JS));
538 resources.push_back(
539 std::make_pair("webRequestInternal",
540 IDR_WEB_REQUEST_INTERNAL_CUSTOM_BINDINGS_JS));
541 // Note: webView not webview so that this doesn't interfere with the
542 // chrome.webview API bindings.
543 resources.push_back(std::make_pair("webView", IDR_WEB_VIEW_JS));
544 resources.push_back(std::make_pair("webViewAttributes",
545 IDR_WEB_VIEW_ATTRIBUTES_JS));
546 resources.push_back(std::make_pair("webViewConstants",
547 IDR_WEB_VIEW_CONSTANTS_JS));
548 resources.push_back(std::make_pair("webViewEvents", IDR_WEB_VIEW_EVENTS_JS));
549 resources.push_back(
550 std::make_pair("webViewExperimental", IDR_WEB_VIEW_EXPERIMENTAL_JS));
551 resources.push_back(std::make_pair("webViewInternal",
552 IDR_WEB_VIEW_INTERNAL_CUSTOM_BINDINGS_JS));
553 resources.push_back(std::make_pair("denyWebView", IDR_WEB_VIEW_DENY_JS));
554 resources.push_back(
555 std::make_pair(mojo::kBufferModuleName, IDR_MOJO_BUFFER_JS));
556 resources.push_back(
557 std::make_pair(mojo::kCodecModuleName, IDR_MOJO_CODEC_JS));
558 resources.push_back(
559 std::make_pair(mojo::kConnectionModuleName, IDR_MOJO_CONNECTION_JS));
560 resources.push_back(
561 std::make_pair(mojo::kConnectorModuleName, IDR_MOJO_CONNECTOR_JS));
562 resources.push_back(
563 std::make_pair(mojo::kRouterModuleName, IDR_MOJO_ROUTER_JS));
564 resources.push_back(
565 std::make_pair(mojo::kUnicodeModuleName, IDR_MOJO_UNICODE_JS));
566 resources.push_back(
567 std::make_pair(mojo::kValidatorModuleName, IDR_MOJO_VALIDATOR_JS));
568 resources.push_back(std::make_pair("async_waiter", IDR_ASYNC_WAITER_JS));
569 resources.push_back(std::make_pair("data_receiver", IDR_DATA_RECEIVER_JS));
570 resources.push_back(std::make_pair("data_sender", IDR_DATA_SENDER_JS));
571 resources.push_back(std::make_pair("keep_alive", IDR_KEEP_ALIVE_JS));
572 resources.push_back(std::make_pair("extensions/common/mojo/keep_alive.mojom",
573 IDR_KEEP_ALIVE_MOJOM_JS));
574 resources.push_back(std::make_pair("device/serial/data_stream.mojom",
575 IDR_DATA_STREAM_MOJOM_JS));
576 resources.push_back(
577 std::make_pair("device/serial/data_stream_serialization.mojom",
578 IDR_DATA_STREAM_SERIALIZATION_MOJOM_JS));
580 // Custom bindings.
581 resources.push_back(
582 std::make_pair("app.runtime", IDR_APP_RUNTIME_CUSTOM_BINDINGS_JS));
583 resources.push_back(
584 std::make_pair("app.window", IDR_APP_WINDOW_CUSTOM_BINDINGS_JS));
585 resources.push_back(
586 std::make_pair("declarativeWebRequest",
587 IDR_DECLARATIVE_WEBREQUEST_CUSTOM_BINDINGS_JS));
588 resources.push_back(
589 std::make_pair("contextMenus", IDR_CONTEXT_MENUS_CUSTOM_BINDINGS_JS));
590 resources.push_back(
591 std::make_pair("extension", IDR_EXTENSION_CUSTOM_BINDINGS_JS));
592 resources.push_back(std::make_pair("i18n", IDR_I18N_CUSTOM_BINDINGS_JS));
593 resources.push_back(
594 std::make_pair("permissions", IDR_PERMISSIONS_CUSTOM_BINDINGS_JS));
595 resources.push_back(
596 std::make_pair("runtime", IDR_RUNTIME_CUSTOM_BINDINGS_JS));
597 resources.push_back(std::make_pair("windowControls", IDR_WINDOW_CONTROLS_JS));
598 resources.push_back(
599 std::make_pair("webViewRequest",
600 IDR_WEB_VIEW_REQUEST_CUSTOM_BINDINGS_JS));
601 resources.push_back(std::make_pair("binding", IDR_BINDING_JS));
603 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
604 switches::kEnableMojoSerialService)) {
605 resources.push_back(
606 std::make_pair("serial", IDR_SERIAL_CUSTOM_BINDINGS_JS));
608 resources.push_back(std::make_pair("serial_service", IDR_SERIAL_SERVICE_JS));
609 resources.push_back(
610 std::make_pair("device/serial/serial.mojom", IDR_SERIAL_MOJOM_JS));
611 resources.push_back(std::make_pair("device/serial/serial_serialization.mojom",
612 IDR_SERIAL_SERIALIZATION_MOJOM_JS));
614 // Custom types sources.
615 resources.push_back(std::make_pair("StorageArea", IDR_STORAGE_AREA_JS));
617 // Platform app sources that are not API-specific..
618 resources.push_back(std::make_pair("platformApp", IDR_PLATFORM_APP_JS));
620 return resources;
623 // NOTE: please use the naming convention "foo_natives" for these.
624 // static
625 void Dispatcher::RegisterNativeHandlers(ModuleSystem* module_system,
626 ScriptContext* context,
627 Dispatcher* dispatcher,
628 RequestSender* request_sender,
629 V8SchemaRegistry* v8_schema_registry) {
630 module_system->RegisterNativeHandler(
631 "chrome", scoped_ptr<NativeHandler>(new ChromeNativeHandler(context)));
632 module_system->RegisterNativeHandler(
633 "lazy_background_page",
634 scoped_ptr<NativeHandler>(new LazyBackgroundPageNativeHandler(context)));
635 module_system->RegisterNativeHandler(
636 "logging", scoped_ptr<NativeHandler>(new LoggingNativeHandler(context)));
637 module_system->RegisterNativeHandler("schema_registry",
638 v8_schema_registry->AsNativeHandler());
639 module_system->RegisterNativeHandler(
640 "print", scoped_ptr<NativeHandler>(new PrintNativeHandler(context)));
641 module_system->RegisterNativeHandler(
642 "test_features",
643 scoped_ptr<NativeHandler>(new TestFeaturesNativeHandler(context)));
644 module_system->RegisterNativeHandler(
645 "user_gestures",
646 scoped_ptr<NativeHandler>(new UserGesturesNativeHandler(context)));
647 module_system->RegisterNativeHandler(
648 "utils", scoped_ptr<NativeHandler>(new UtilsNativeHandler(context)));
649 module_system->RegisterNativeHandler(
650 "v8_context",
651 scoped_ptr<NativeHandler>(
652 new V8ContextNativeHandler(context, dispatcher)));
653 module_system->RegisterNativeHandler(
654 "event_natives",
655 scoped_ptr<NativeHandler>(new EventBindings(dispatcher, context)));
656 module_system->RegisterNativeHandler(
657 "messaging_natives",
658 scoped_ptr<NativeHandler>(MessagingBindings::Get(dispatcher, context)));
659 module_system->RegisterNativeHandler(
660 "apiDefinitions",
661 scoped_ptr<NativeHandler>(
662 new ApiDefinitionsNatives(dispatcher, context)));
663 module_system->RegisterNativeHandler(
664 "sendRequest",
665 scoped_ptr<NativeHandler>(
666 new SendRequestNatives(request_sender, context)));
667 module_system->RegisterNativeHandler(
668 "setIcon",
669 scoped_ptr<NativeHandler>(new SetIconNatives(request_sender, context)));
670 module_system->RegisterNativeHandler(
671 "activityLogger",
672 scoped_ptr<NativeHandler>(new APIActivityLogger(context)));
673 module_system->RegisterNativeHandler(
674 "renderViewObserverNatives",
675 scoped_ptr<NativeHandler>(new RenderViewObserverNatives(context)));
677 // Natives used by multiple APIs.
678 module_system->RegisterNativeHandler(
679 "file_system_natives",
680 scoped_ptr<NativeHandler>(new FileSystemNatives(context)));
682 // Custom bindings.
683 module_system->RegisterNativeHandler(
684 "app_runtime",
685 scoped_ptr<NativeHandler>(new AppRuntimeCustomBindings(context)));
686 module_system->RegisterNativeHandler(
687 "app_window_natives",
688 scoped_ptr<NativeHandler>(
689 new AppWindowCustomBindings(dispatcher, context)));
690 module_system->RegisterNativeHandler(
691 "blob_natives",
692 scoped_ptr<NativeHandler>(new BlobNativeHandler(context)));
693 module_system->RegisterNativeHandler(
694 "context_menus",
695 scoped_ptr<NativeHandler>(new ContextMenusCustomBindings(context)));
696 module_system->RegisterNativeHandler(
697 "css_natives", scoped_ptr<NativeHandler>(new CssNativeHandler(context)));
698 module_system->RegisterNativeHandler(
699 "document_natives",
700 scoped_ptr<NativeHandler>(new DocumentCustomBindings(context)));
701 module_system->RegisterNativeHandler(
702 "guest_view_internal",
703 scoped_ptr<NativeHandler>(
704 new GuestViewInternalCustomBindings(context)));
705 module_system->RegisterNativeHandler(
706 "i18n", scoped_ptr<NativeHandler>(new I18NCustomBindings(context)));
707 module_system->RegisterNativeHandler(
708 "id_generator",
709 scoped_ptr<NativeHandler>(new IdGeneratorCustomBindings(context)));
710 module_system->RegisterNativeHandler(
711 "runtime", scoped_ptr<NativeHandler>(new RuntimeCustomBindings(context)));
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_ClearTabSpecificPermissions,
720 OnClearTabSpecificPermissions)
721 IPC_MESSAGE_HANDLER(ExtensionMsg_DeliverMessage, OnDeliverMessage)
722 IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnConnect, OnDispatchOnConnect)
723 IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnDisconnect, OnDispatchOnDisconnect)
724 IPC_MESSAGE_HANDLER(ExtensionMsg_Loaded, OnLoaded)
725 IPC_MESSAGE_HANDLER(ExtensionMsg_MessageInvoke, OnMessageInvoke)
726 IPC_MESSAGE_HANDLER(ExtensionMsg_SetChannel, OnSetChannel)
727 IPC_MESSAGE_HANDLER(ExtensionMsg_SetFunctionNames, OnSetFunctionNames)
728 IPC_MESSAGE_HANDLER(ExtensionMsg_SetScriptingWhitelist,
729 OnSetScriptingWhitelist)
730 IPC_MESSAGE_HANDLER(ExtensionMsg_SetSystemFont, OnSetSystemFont)
731 IPC_MESSAGE_HANDLER(ExtensionMsg_ShouldSuspend, OnShouldSuspend)
732 IPC_MESSAGE_HANDLER(ExtensionMsg_Suspend, OnSuspend)
733 IPC_MESSAGE_HANDLER(ExtensionMsg_TransferBlobs, OnTransferBlobs)
734 IPC_MESSAGE_HANDLER(ExtensionMsg_Unloaded, OnUnloaded)
735 IPC_MESSAGE_HANDLER(ExtensionMsg_UpdatePermissions, OnUpdatePermissions)
736 IPC_MESSAGE_HANDLER(ExtensionMsg_UpdateTabSpecificPermissions,
737 OnUpdateTabSpecificPermissions)
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 (is_extension_process_) {
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 (std::set<std::string>::iterator iter = active_extension_ids_.begin();
763 iter != active_extension_ids_.end();
764 ++iter) {
765 const Extension* extension = extensions_.GetByID(*iter);
766 CHECK(extension);
768 InitOriginPermissions(extension);
771 EnableCustomElementWhiteList();
773 is_webkit_initialized_ = true;
776 void Dispatcher::IdleNotification() {
777 if (is_extension_process_ && forced_idle_timer_) {
778 // Dampen the forced delay as well if the extension stays idle for long
779 // periods of time. (forced_idle_timer_ can be NULL after
780 // OnRenderProcessShutdown has been called.)
781 int64 forced_delay_ms =
782 std::max(RenderThread::Get()->GetIdleNotificationDelayInMs(),
783 kMaxExtensionIdleHandlerDelayMs);
784 forced_idle_timer_->Stop();
785 forced_idle_timer_->Start(
786 FROM_HERE,
787 base::TimeDelta::FromMilliseconds(forced_delay_ms),
788 RenderThread::Get(),
789 &RenderThread::IdleHandler);
793 void Dispatcher::OnRenderProcessShutdown() {
794 v8_schema_registry_.reset();
795 forced_idle_timer_.reset();
798 void Dispatcher::OnActivateExtension(const std::string& extension_id) {
799 const Extension* extension = extensions_.GetByID(extension_id);
800 if (!extension) {
801 // Extension was activated but was never loaded. This probably means that
802 // the renderer failed to load it (or the browser failed to tell us when it
803 // did). Failures shouldn't happen, but instead of crashing there (which
804 // executes on all renderers) be conservative and only crash in the renderer
805 // of the extension which failed to load; this one.
806 std::string& error = extension_load_errors_[extension_id];
807 char minidump[256];
808 base::debug::Alias(&minidump);
809 base::snprintf(minidump,
810 arraysize(minidump),
811 "e::dispatcher:%s:%s",
812 extension_id.c_str(),
813 error.c_str());
814 CHECK(extension) << extension_id << " was never loaded: " << error;
817 active_extension_ids_.insert(extension_id);
819 // This is called when starting a new extension page, so start the idle
820 // handler ticking.
821 RenderThread::Get()->ScheduleIdleHandler(kInitialExtensionIdleHandlerDelayMs);
823 if (is_webkit_initialized_) {
824 DOMActivityLogger::AttachToWorld(
825 DOMActivityLogger::kMainWorldId, extension_id);
827 InitOriginPermissions(extension);
830 UpdateActiveExtensions();
833 void Dispatcher::OnCancelSuspend(const std::string& extension_id) {
834 DispatchEvent(extension_id, kOnSuspendCanceledEvent);
837 void Dispatcher::OnClearTabSpecificPermissions(
838 int tab_id,
839 const std::vector<std::string>& extension_ids) {
840 delegate_->ClearTabSpecificPermissions(this, tab_id, extension_ids);
843 void Dispatcher::OnDeliverMessage(int target_port_id, const Message& message) {
844 scoped_ptr<RequestSender::ScopedTabID> scoped_tab_id;
845 std::map<int, int>::const_iterator it =
846 port_to_tab_id_map_.find(target_port_id);
847 if (it != port_to_tab_id_map_.end()) {
848 scoped_tab_id.reset(
849 new RequestSender::ScopedTabID(request_sender(), it->second));
852 MessagingBindings::DeliverMessage(script_context_set_,
853 target_port_id,
854 message,
855 NULL); // All render views.
858 void Dispatcher::OnDispatchOnConnect(
859 int target_port_id,
860 const std::string& channel_name,
861 const base::DictionaryValue& source_tab,
862 const ExtensionMsg_ExternalConnectionInfo& info,
863 const std::string& tls_channel_id) {
864 DCHECK(!ContainsKey(port_to_tab_id_map_, target_port_id));
865 DCHECK_EQ(1, target_port_id % 2); // target renderer ports have odd IDs.
866 int sender_tab_id = -1;
867 source_tab.GetInteger("id", &sender_tab_id);
868 port_to_tab_id_map_[target_port_id] = sender_tab_id;
870 MessagingBindings::DispatchOnConnect(script_context_set_,
871 target_port_id,
872 channel_name,
873 source_tab,
874 info,
875 tls_channel_id,
876 NULL); // All render views.
879 void Dispatcher::OnDispatchOnDisconnect(int port_id,
880 const std::string& error_message) {
881 MessagingBindings::DispatchOnDisconnect(script_context_set_,
882 port_id,
883 error_message,
884 NULL); // All render views.
887 void Dispatcher::OnLoaded(
888 const std::vector<ExtensionMsg_Loaded_Params>& loaded_extensions) {
889 std::vector<ExtensionMsg_Loaded_Params>::const_iterator i;
890 for (i = loaded_extensions.begin(); i != loaded_extensions.end(); ++i) {
891 std::string error;
892 scoped_refptr<const Extension> extension = i->ConvertToExtension(&error);
893 if (!extension.get()) {
894 extension_load_errors_[i->id] = error;
895 continue;
897 OnLoadedInternal(extension);
899 // Update the available bindings for all contexts. These may have changed if
900 // an externally_connectable extension was loaded that can connect to an
901 // open webpage.
902 UpdateBindings("");
905 void Dispatcher::OnLoadedInternal(scoped_refptr<const Extension> extension) {
906 extensions_.Insert(extension);
909 void Dispatcher::OnMessageInvoke(const std::string& extension_id,
910 const std::string& module_name,
911 const std::string& function_name,
912 const base::ListValue& args,
913 bool user_gesture) {
914 InvokeModuleSystemMethod(
915 NULL, extension_id, module_name, function_name, args, user_gesture);
918 void Dispatcher::OnSetChannel(int channel) {
919 delegate_->SetChannel(channel);
922 void Dispatcher::OnSetFunctionNames(const std::vector<std::string>& names) {
923 function_names_.clear();
924 for (size_t i = 0; i < names.size(); ++i)
925 function_names_.insert(names[i]);
928 void Dispatcher::OnSetScriptingWhitelist(
929 const ExtensionsClient::ScriptingWhitelist& extension_ids) {
930 ExtensionsClient::Get()->SetScriptingWhitelist(extension_ids);
933 void Dispatcher::OnSetSystemFont(const std::string& font_family,
934 const std::string& font_size) {
935 system_font_family_ = font_family;
936 system_font_size_ = font_size;
939 void Dispatcher::OnShouldSuspend(const std::string& extension_id,
940 uint64 sequence_id) {
941 RenderThread::Get()->Send(
942 new ExtensionHostMsg_ShouldSuspendAck(extension_id, sequence_id));
945 void Dispatcher::OnSuspend(const std::string& extension_id) {
946 // Dispatch the suspend event. This doesn't go through the standard event
947 // dispatch machinery because it requires special handling. We need to let
948 // the browser know when we are starting and stopping the event dispatch, so
949 // that it still considers the extension idle despite any activity the suspend
950 // event creates.
951 DispatchEvent(extension_id, kOnSuspendEvent);
952 RenderThread::Get()->Send(new ExtensionHostMsg_SuspendAck(extension_id));
955 void Dispatcher::OnTransferBlobs(const std::vector<std::string>& blob_uuids) {
956 RenderThread::Get()->Send(new ExtensionHostMsg_TransferBlobsAck(blob_uuids));
959 void Dispatcher::OnUnloaded(const std::string& id) {
960 extensions_.Remove(id);
961 active_extension_ids_.erase(id);
963 // If the extension is later reloaded with a different set of permissions,
964 // we'd like it to get a new isolated world ID, so that it can pick up the
965 // changed origin whitelist.
966 ScriptInjection::RemoveIsolatedWorld(id);
968 // Invalidate all of the contexts that were removed.
969 // TODO(kalman): add an invalidation observer interface to ScriptContext.
970 ScriptContextSet::ContextSet removed_contexts =
971 script_context_set_.OnExtensionUnloaded(id);
972 for (ScriptContextSet::ContextSet::iterator it = removed_contexts.begin();
973 it != removed_contexts.end();
974 ++it) {
975 request_sender_->InvalidateSource(*it);
978 // Update the available bindings for the remaining contexts. These may have
979 // changed if an externally_connectable extension is unloaded and a webpage
980 // is no longer accessible.
981 UpdateBindings("");
983 // Invalidates the messages map for the extension in case the extension is
984 // reloaded with a new messages map.
985 EraseL10nMessagesMap(id);
987 // We don't do anything with existing platform-app stylesheets. They will
988 // stay resident, but the URL pattern corresponding to the unloaded
989 // extension's URL just won't match anything anymore.
992 void Dispatcher::OnUpdatePermissions(
993 const ExtensionMsg_UpdatePermissions_Params& params) {
994 const Extension* extension = extensions_.GetByID(params.extension_id);
995 if (!extension)
996 return;
998 scoped_refptr<const PermissionSet> active =
999 params.active_permissions.ToPermissionSet();
1000 scoped_refptr<const PermissionSet> withheld =
1001 params.withheld_permissions.ToPermissionSet();
1003 if (is_webkit_initialized_) {
1004 UpdateOriginPermissions(
1005 extension,
1006 extension->permissions_data()->GetEffectiveHostPermissions(),
1007 active->effective_hosts());
1010 extension->permissions_data()->SetPermissions(active, withheld);
1011 UpdateBindings(extension->id());
1014 void Dispatcher::OnUpdateTabSpecificPermissions(
1015 const GURL& url,
1016 int tab_id,
1017 const std::string& extension_id,
1018 const URLPatternSet& origin_set) {
1019 delegate_->UpdateTabSpecificPermissions(
1020 this, url, tab_id, extension_id, origin_set);
1023 void Dispatcher::OnUsingWebRequestAPI(bool webrequest_used) {
1024 webrequest_used_ = webrequest_used;
1027 void Dispatcher::OnUserScriptsUpdated(
1028 const std::set<std::string>& changed_extensions,
1029 const std::vector<UserScript*>& scripts) {
1030 UpdateActiveExtensions();
1033 void Dispatcher::UpdateActiveExtensions() {
1034 std::set<std::string> active_extensions = active_extension_ids_;
1035 user_script_set_manager_->GetAllActiveExtensionIds(&active_extensions);
1036 delegate_->OnActiveExtensionsUpdated(active_extensions);
1039 void Dispatcher::InitOriginPermissions(const Extension* extension) {
1040 delegate_->InitOriginPermissions(extension,
1041 IsExtensionActive(extension->id()));
1042 UpdateOriginPermissions(
1043 extension,
1044 URLPatternSet(), // No old permissions.
1045 extension->permissions_data()->GetEffectiveHostPermissions());
1048 void Dispatcher::UpdateOriginPermissions(
1049 const Extension* extension,
1050 const URLPatternSet& old_patterns,
1051 const URLPatternSet& new_patterns) {
1052 static const char* kSchemes[] = {
1053 url::kHttpScheme,
1054 url::kHttpsScheme,
1055 url::kFileScheme,
1056 content::kChromeUIScheme,
1057 url::kFtpScheme,
1059 for (size_t i = 0; i < arraysize(kSchemes); ++i) {
1060 const char* scheme = kSchemes[i];
1061 // Remove all old patterns...
1062 for (URLPatternSet::const_iterator pattern = old_patterns.begin();
1063 pattern != old_patterns.end(); ++pattern) {
1064 if (pattern->MatchesScheme(scheme)) {
1065 WebSecurityPolicy::removeOriginAccessWhitelistEntry(
1066 extension->url(),
1067 WebString::fromUTF8(scheme),
1068 WebString::fromUTF8(pattern->host()),
1069 pattern->match_subdomains());
1072 // ...And add the new ones.
1073 for (URLPatternSet::const_iterator pattern = new_patterns.begin();
1074 pattern != new_patterns.end(); ++pattern) {
1075 if (pattern->MatchesScheme(scheme)) {
1076 WebSecurityPolicy::addOriginAccessWhitelistEntry(
1077 extension->url(),
1078 WebString::fromUTF8(scheme),
1079 WebString::fromUTF8(pattern->host()),
1080 pattern->match_subdomains());
1086 void Dispatcher::EnableCustomElementWhiteList() {
1087 blink::WebCustomElement::addEmbedderCustomElementName("appplugin");
1088 blink::WebCustomElement::addEmbedderCustomElementName("appview");
1089 blink::WebCustomElement::addEmbedderCustomElementName("browserplugin");
1090 blink::WebCustomElement::addEmbedderCustomElementName("extensionoptions");
1091 blink::WebCustomElement::addEmbedderCustomElementName(
1092 "extensionoptionsplugin");
1093 blink::WebCustomElement::addEmbedderCustomElementName("webview");
1096 void Dispatcher::UpdateBindings(const std::string& extension_id) {
1097 script_context_set().ForEach(extension_id,
1098 base::Bind(&Dispatcher::UpdateBindingsForContext,
1099 base::Unretained(this)));
1102 void Dispatcher::UpdateBindingsForContext(ScriptContext* context) {
1103 v8::HandleScope handle_scope(context->isolate());
1104 v8::Context::Scope context_scope(context->v8_context());
1106 // TODO(kalman): Make the bindings registration have zero overhead then run
1107 // the same code regardless of context type.
1108 switch (context->context_type()) {
1109 case Feature::UNSPECIFIED_CONTEXT:
1110 case Feature::WEB_PAGE_CONTEXT:
1111 case Feature::BLESSED_WEB_PAGE_CONTEXT: {
1112 // Web page context; it's too expensive to run the full bindings code.
1113 // Hard-code that the app and webstore APIs are available...
1114 if (context->GetAvailability("app").is_available())
1115 RegisterBinding("app", context);
1117 if (context->GetAvailability("webstore").is_available())
1118 RegisterBinding("webstore", context);
1120 // ... and that the runtime API might be available if any extension can
1121 // connect to it.
1122 bool runtime_is_available = false;
1123 for (ExtensionSet::const_iterator it = extensions_.begin();
1124 it != extensions_.end();
1125 ++it) {
1126 ExternallyConnectableInfo* info =
1127 static_cast<ExternallyConnectableInfo*>(
1128 (*it)->GetManifestData(manifest_keys::kExternallyConnectable));
1129 if (info && info->matches.MatchesURL(context->GetURL())) {
1130 runtime_is_available = true;
1131 break;
1134 if (runtime_is_available)
1135 RegisterBinding("runtime", context);
1136 break;
1139 case Feature::BLESSED_EXTENSION_CONTEXT:
1140 case Feature::UNBLESSED_EXTENSION_CONTEXT:
1141 case Feature::CONTENT_SCRIPT_CONTEXT:
1142 case Feature::WEBUI_CONTEXT: {
1143 // Extension context; iterate through all the APIs and bind the available
1144 // ones.
1145 const FeatureProvider* api_feature_provider =
1146 FeatureProvider::GetAPIFeatures();
1147 const std::vector<std::string>& apis =
1148 api_feature_provider->GetAllFeatureNames();
1149 for (std::vector<std::string>::const_iterator it = apis.begin();
1150 it != apis.end();
1151 ++it) {
1152 const std::string& api_name = *it;
1153 Feature* feature = api_feature_provider->GetFeature(api_name);
1154 DCHECK(feature);
1156 // Internal APIs are included via require(api_name) from internal code
1157 // rather than chrome[api_name].
1158 if (feature->IsInternal())
1159 continue;
1161 // If this API has a parent feature (and isn't marked 'noparent'),
1162 // then this must be a function or event, so we should not register.
1163 if (api_feature_provider->GetParent(feature) != NULL)
1164 continue;
1166 // Skip chrome.test if this isn't a test.
1167 if (api_name == "test" &&
1168 !CommandLine::ForCurrentProcess()->HasSwitch(
1169 ::switches::kTestType)) {
1170 continue;
1173 if (context->IsAnyFeatureAvailableToContext(*feature))
1174 RegisterBinding(api_name, context);
1176 break;
1181 void Dispatcher::RegisterBinding(const std::string& api_name,
1182 ScriptContext* context) {
1183 std::string bind_name;
1184 v8::Handle<v8::Object> bind_object =
1185 GetOrCreateBindObjectIfAvailable(api_name, &bind_name, context);
1187 // Empty if the bind object failed to be created, probably because the
1188 // extension overrode chrome with a non-object, e.g. window.chrome = true.
1189 if (bind_object.IsEmpty())
1190 return;
1192 v8::Local<v8::String> v8_api_name =
1193 v8::String::NewFromUtf8(context->isolate(), api_name.c_str());
1194 if (bind_object->HasRealNamedProperty(v8_api_name)) {
1195 // The bind object may already have the property if the API has been
1196 // registered before (or if the extension has put something there already,
1197 // but, whatevs).
1199 // In the former case, we need to re-register the bindings for the APIs
1200 // which the extension now has permissions for (if any), but not touch any
1201 // others so that we don't destroy state such as event listeners.
1203 // TODO(kalman): Only register available APIs to make this all moot.
1204 if (bind_object->HasRealNamedCallbackProperty(v8_api_name))
1205 return; // lazy binding still there, nothing to do
1206 if (bind_object->Get(v8_api_name)->IsObject())
1207 return; // binding has already been fully installed
1210 ModuleSystem* module_system = context->module_system();
1211 if (!source_map_.Contains(api_name)) {
1212 module_system->RegisterNativeHandler(
1213 api_name,
1214 scoped_ptr<NativeHandler>(new BindingGeneratingNativeHandler(
1215 module_system, api_name, "binding")));
1216 module_system->SetNativeLazyField(
1217 bind_object, bind_name, api_name, "binding");
1218 } else {
1219 module_system->SetLazyField(bind_object, bind_name, api_name, "binding");
1223 // NOTE: please use the naming convention "foo_natives" for these.
1224 void Dispatcher::RegisterNativeHandlers(ModuleSystem* module_system,
1225 ScriptContext* context) {
1226 RegisterNativeHandlers(module_system,
1227 context,
1228 this,
1229 request_sender_.get(),
1230 v8_schema_registry_.get());
1231 const Extension* extension = context->extension();
1232 int manifest_version = extension ? extension->manifest_version() : 1;
1233 bool send_request_disabled =
1234 (extension && Manifest::IsUnpackedLocation(extension->location()) &&
1235 BackgroundInfo::HasLazyBackgroundPage(extension));
1236 module_system->RegisterNativeHandler(
1237 "process",
1238 scoped_ptr<NativeHandler>(new ProcessInfoNativeHandler(
1239 context,
1240 context->GetExtensionID(),
1241 context->GetContextTypeDescription(),
1242 ExtensionsRendererClient::Get()->IsIncognitoProcess(),
1243 manifest_version,
1244 send_request_disabled)));
1246 delegate_->RegisterNativeHandlers(this, module_system, context);
1249 void Dispatcher::PopulateSourceMap() {
1250 const std::vector<std::pair<std::string, int> > resources = GetJsResources();
1251 for (std::vector<std::pair<std::string, int> >::const_iterator resource =
1252 resources.begin();
1253 resource != resources.end();
1254 ++resource) {
1255 source_map_.RegisterSource(resource->first, resource->second);
1257 delegate_->PopulateSourceMap(&source_map_);
1260 bool Dispatcher::IsWithinPlatformApp() {
1261 for (std::set<std::string>::iterator iter = active_extension_ids_.begin();
1262 iter != active_extension_ids_.end();
1263 ++iter) {
1264 const Extension* extension = extensions_.GetByID(*iter);
1265 if (extension && extension->is_platform_app())
1266 return true;
1268 return false;
1271 // TODO(kalman): This is checking for the wrong thing, it should be checking if
1272 // the frame's security origin is unique. The extension sandbox directive is
1273 // checked for in extensions/common/manifest_handlers/csp_info.cc.
1274 bool Dispatcher::IsSandboxedPage(const GURL& url) const {
1275 if (url.SchemeIs(kExtensionScheme)) {
1276 const Extension* extension = extensions_.GetByID(url.host());
1277 if (extension) {
1278 return SandboxedPageInfo::IsSandboxedPage(extension, url.path());
1281 return false;
1284 Feature::Context Dispatcher::ClassifyJavaScriptContext(
1285 const Extension* extension,
1286 int extension_group,
1287 const GURL& url,
1288 const blink::WebSecurityOrigin& origin) {
1289 // WARNING: This logic must match ProcessMap::GetContextType, as much as
1290 // possible.
1292 DCHECK_GE(extension_group, 0);
1293 if (extension_group == EXTENSION_GROUP_CONTENT_SCRIPTS) {
1294 return extension ? // TODO(kalman): when does this happen?
1295 Feature::CONTENT_SCRIPT_CONTEXT
1296 : Feature::UNSPECIFIED_CONTEXT;
1299 // We have an explicit check for sandboxed pages before checking whether the
1300 // extension is active in this process because:
1301 // 1. Sandboxed pages run in the same process as regular extension pages, so
1302 // the extension is considered active.
1303 // 2. ScriptContext creation (which triggers bindings injection) happens
1304 // before the SecurityContext is updated with the sandbox flags (after
1305 // reading the CSP header), so the caller can't check if the context's
1306 // security origin is unique yet.
1307 if (IsSandboxedPage(url))
1308 return Feature::WEB_PAGE_CONTEXT;
1310 if (extension && IsExtensionActive(extension->id())) {
1311 // |extension| is active in this process, but it could be either a true
1312 // extension process or within the extent of a hosted app. In the latter
1313 // case this would usually be considered a (blessed) web page context,
1314 // unless the extension in question is a component extension, in which case
1315 // we cheat and call it blessed.
1316 return (extension->is_hosted_app() &&
1317 extension->location() != Manifest::COMPONENT)
1318 ? Feature::BLESSED_WEB_PAGE_CONTEXT
1319 : Feature::BLESSED_EXTENSION_CONTEXT;
1322 // TODO(kalman): This isUnique() check is wrong, it should be performed as
1323 // part of IsSandboxedPage().
1324 if (!origin.isUnique() && extensions_.ExtensionBindingsAllowed(url)) {
1325 if (!extension) // TODO(kalman): when does this happen?
1326 return Feature::UNSPECIFIED_CONTEXT;
1327 return extension->is_hosted_app() ? Feature::BLESSED_WEB_PAGE_CONTEXT
1328 : Feature::UNBLESSED_EXTENSION_CONTEXT;
1331 if (!url.is_valid())
1332 return Feature::UNSPECIFIED_CONTEXT;
1334 if (url.SchemeIs(content::kChromeUIScheme))
1335 return Feature::WEBUI_CONTEXT;
1337 return Feature::WEB_PAGE_CONTEXT;
1340 v8::Handle<v8::Object> Dispatcher::GetOrCreateObject(
1341 const v8::Handle<v8::Object>& object,
1342 const std::string& field,
1343 v8::Isolate* isolate) {
1344 v8::Handle<v8::String> key = v8::String::NewFromUtf8(isolate, field.c_str());
1345 // If the object has a callback property, it is assumed it is an unavailable
1346 // API, so it is safe to delete. This is checked before GetOrCreateObject is
1347 // called.
1348 if (object->HasRealNamedCallbackProperty(key)) {
1349 object->Delete(key);
1350 } else if (object->HasRealNamedProperty(key)) {
1351 v8::Handle<v8::Value> value = object->Get(key);
1352 CHECK(value->IsObject());
1353 return v8::Handle<v8::Object>::Cast(value);
1356 v8::Handle<v8::Object> new_object = v8::Object::New(isolate);
1357 object->Set(key, new_object);
1358 return new_object;
1361 v8::Handle<v8::Object> Dispatcher::GetOrCreateBindObjectIfAvailable(
1362 const std::string& api_name,
1363 std::string* bind_name,
1364 ScriptContext* context) {
1365 std::vector<std::string> split;
1366 base::SplitString(api_name, '.', &split);
1368 v8::Handle<v8::Object> bind_object;
1370 // Check if this API has an ancestor. If the API's ancestor is available and
1371 // the API is not available, don't install the bindings for this API. If
1372 // the API is available and its ancestor is not, delete the ancestor and
1373 // install the bindings for the API. This is to prevent loading the ancestor
1374 // API schema if it will not be needed.
1376 // For example:
1377 // If app is available and app.window is not, just install app.
1378 // If app.window is available and app is not, delete app and install
1379 // app.window on a new object so app does not have to be loaded.
1380 const FeatureProvider* api_feature_provider =
1381 FeatureProvider::GetAPIFeatures();
1382 std::string ancestor_name;
1383 bool only_ancestor_available = false;
1385 for (size_t i = 0; i < split.size() - 1; ++i) {
1386 ancestor_name += (i ? "." : "") + split[i];
1387 if (api_feature_provider->GetFeature(ancestor_name) &&
1388 context->GetAvailability(ancestor_name).is_available() &&
1389 !context->GetAvailability(api_name).is_available()) {
1390 only_ancestor_available = true;
1391 break;
1394 if (bind_object.IsEmpty()) {
1395 bind_object = AsObjectOrEmpty(GetOrCreateChrome(context));
1396 if (bind_object.IsEmpty())
1397 return v8::Handle<v8::Object>();
1399 bind_object = GetOrCreateObject(bind_object, split[i], context->isolate());
1402 if (only_ancestor_available)
1403 return v8::Handle<v8::Object>();
1405 if (bind_name)
1406 *bind_name = split.back();
1408 return bind_object.IsEmpty() ? AsObjectOrEmpty(GetOrCreateChrome(context))
1409 : bind_object;
1412 } // namespace extensions