Updating trunk VERSION from 2139.0 to 2140.0
[chromium-blink-merge.git] / extensions / renderer / dispatcher.cc
blobd52d1505c06bfe2a7da38acde2639c831bf5fa29
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/sandboxed_page_info.h"
36 #include "extensions/common/message_bundle.h"
37 #include "extensions/common/permissions/permission_set.h"
38 #include "extensions/common/permissions/permissions_data.h"
39 #include "extensions/common/switches.h"
40 #include "extensions/common/view_type.h"
41 #include "extensions/renderer/api_activity_logger.h"
42 #include "extensions/renderer/api_definitions_natives.h"
43 #include "extensions/renderer/app_runtime_custom_bindings.h"
44 #include "extensions/renderer/binding_generating_native_handler.h"
45 #include "extensions/renderer/blob_native_handler.h"
46 #include "extensions/renderer/content_watcher.h"
47 #include "extensions/renderer/context_menus_custom_bindings.h"
48 #include "extensions/renderer/css_native_handler.h"
49 #include "extensions/renderer/dispatcher_delegate.h"
50 #include "extensions/renderer/document_custom_bindings.h"
51 #include "extensions/renderer/dom_activity_logger.h"
52 #include "extensions/renderer/event_bindings.h"
53 #include "extensions/renderer/extension_groups.h"
54 #include "extensions/renderer/extension_helper.h"
55 #include "extensions/renderer/extensions_renderer_client.h"
56 #include "extensions/renderer/file_system_natives.h"
57 #include "extensions/renderer/guest_view/guest_view_internal_custom_bindings.h"
58 #include "extensions/renderer/i18n_custom_bindings.h"
59 #include "extensions/renderer/id_generator_custom_bindings.h"
60 #include "extensions/renderer/lazy_background_page_native_handler.h"
61 #include "extensions/renderer/logging_native_handler.h"
62 #include "extensions/renderer/messaging_bindings.h"
63 #include "extensions/renderer/module_system.h"
64 #include "extensions/renderer/print_native_handler.h"
65 #include "extensions/renderer/process_info_native_handler.h"
66 #include "extensions/renderer/render_view_observer_natives.h"
67 #include "extensions/renderer/request_sender.h"
68 #include "extensions/renderer/runtime_custom_bindings.h"
69 #include "extensions/renderer/safe_builtins.h"
70 #include "extensions/renderer/script_context.h"
71 #include "extensions/renderer/script_context_set.h"
72 #include "extensions/renderer/script_injection.h"
73 #include "extensions/renderer/script_injection_manager.h"
74 #include "extensions/renderer/send_request_natives.h"
75 #include "extensions/renderer/set_icon_natives.h"
76 #include "extensions/renderer/test_features_native_handler.h"
77 #include "extensions/renderer/user_gestures_native_handler.h"
78 #include "extensions/renderer/utils_native_handler.h"
79 #include "extensions/renderer/v8_context_native_handler.h"
80 #include "grit/extensions_renderer_resources.h"
81 #include "mojo/public/js/bindings/constants.h"
82 #include "third_party/WebKit/public/platform/WebString.h"
83 #include "third_party/WebKit/public/platform/WebURLRequest.h"
84 #include "third_party/WebKit/public/web/WebCustomElement.h"
85 #include "third_party/WebKit/public/web/WebDataSource.h"
86 #include "third_party/WebKit/public/web/WebDocument.h"
87 #include "third_party/WebKit/public/web/WebFrame.h"
88 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
89 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
90 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
91 #include "third_party/WebKit/public/web/WebView.h"
92 #include "ui/base/layout.h"
93 #include "ui/base/resource/resource_bundle.h"
94 #include "v8/include/v8.h"
96 using base::UserMetricsAction;
97 using blink::WebDataSource;
98 using blink::WebDocument;
99 using blink::WebFrame;
100 using blink::WebScopedUserGesture;
101 using blink::WebSecurityPolicy;
102 using blink::WebString;
103 using blink::WebVector;
104 using blink::WebView;
105 using content::RenderThread;
106 using content::RenderView;
108 namespace extensions {
110 namespace {
112 static const int64 kInitialExtensionIdleHandlerDelayMs = 5 * 1000;
113 static const int64 kMaxExtensionIdleHandlerDelayMs = 5 * 60 * 1000;
114 static const char kEventDispatchFunction[] = "dispatchEvent";
115 static const char kOnSuspendEvent[] = "runtime.onSuspend";
116 static const char kOnSuspendCanceledEvent[] = "runtime.onSuspendCanceled";
118 // Returns the global value for "chrome" from |context|. If one doesn't exist
119 // creates a new object for it.
121 // Note that this isn't necessarily an object, since webpages can write, for
122 // example, "window.chrome = true".
123 v8::Handle<v8::Value> GetOrCreateChrome(ScriptContext* context) {
124 v8::Handle<v8::String> chrome_string(
125 v8::String::NewFromUtf8(context->isolate(), "chrome"));
126 v8::Handle<v8::Object> global(context->v8_context()->Global());
127 v8::Handle<v8::Value> chrome(global->Get(chrome_string));
128 if (chrome->IsUndefined()) {
129 chrome = v8::Object::New(context->isolate());
130 global->Set(chrome_string, chrome);
132 return chrome;
135 // Returns |value| cast to an object if possible, else an empty handle.
136 v8::Handle<v8::Object> AsObjectOrEmpty(v8::Handle<v8::Value> value) {
137 return value->IsObject() ? value.As<v8::Object>() : v8::Handle<v8::Object>();
140 // Calls a method |method_name| in a module |module_name| belonging to the
141 // module system from |context|. Intended as a callback target from
142 // ScriptContextSet::ForEach.
143 void CallModuleMethod(const std::string& module_name,
144 const std::string& method_name,
145 const base::ListValue* args,
146 ScriptContext* context) {
147 v8::HandleScope handle_scope(context->isolate());
148 v8::Context::Scope context_scope(context->v8_context());
150 scoped_ptr<content::V8ValueConverter> converter(
151 content::V8ValueConverter::create());
153 std::vector<v8::Handle<v8::Value> > arguments;
154 for (base::ListValue::const_iterator it = args->begin(); it != args->end();
155 ++it) {
156 arguments.push_back(converter->ToV8Value(*it, context->v8_context()));
159 context->module_system()->CallModuleMethod(
160 module_name, method_name, &arguments);
163 // This handles the "chrome." root API object in script contexts.
164 class ChromeNativeHandler : public ObjectBackedNativeHandler {
165 public:
166 explicit ChromeNativeHandler(ScriptContext* context)
167 : ObjectBackedNativeHandler(context) {
168 RouteFunction(
169 "GetChrome",
170 base::Bind(&ChromeNativeHandler::GetChrome, base::Unretained(this)));
173 void GetChrome(const v8::FunctionCallbackInfo<v8::Value>& args) {
174 args.GetReturnValue().Set(GetOrCreateChrome(context()));
178 } // namespace
180 Dispatcher::Dispatcher(DispatcherDelegate* delegate)
181 : delegate_(delegate),
182 content_watcher_(new ContentWatcher()),
183 source_map_(&ResourceBundle::GetSharedInstance()),
184 v8_schema_registry_(new V8SchemaRegistry),
185 is_webkit_initialized_(false),
186 user_script_set_manager_observer_(this) {
187 const CommandLine& command_line = *(CommandLine::ForCurrentProcess());
188 is_extension_process_ =
189 command_line.HasSwitch(extensions::switches::kExtensionProcess) ||
190 command_line.HasSwitch(::switches::kSingleProcess);
192 if (is_extension_process_) {
193 RenderThread::Get()->SetIdleNotificationDelayInMs(
194 kInitialExtensionIdleHandlerDelayMs);
197 RenderThread::Get()->RegisterExtension(SafeBuiltins::CreateV8Extension());
199 user_script_set_manager_.reset(new UserScriptSetManager(&extensions_));
200 script_injection_manager_.reset(
201 new ScriptInjectionManager(&extensions_, user_script_set_manager_.get()));
202 user_script_set_manager_observer_.Add(user_script_set_manager_.get());
203 request_sender_.reset(new RequestSender(this));
204 PopulateSourceMap();
207 Dispatcher::~Dispatcher() {
210 void Dispatcher::OnRenderViewCreated(content::RenderView* render_view) {
211 script_injection_manager_->OnRenderViewCreated(render_view);
214 bool Dispatcher::IsExtensionActive(const std::string& extension_id) const {
215 bool is_active =
216 active_extension_ids_.find(extension_id) != active_extension_ids_.end();
217 if (is_active)
218 CHECK(extensions_.Contains(extension_id));
219 return is_active;
222 std::string Dispatcher::GetExtensionID(const WebFrame* frame, int world_id) {
223 if (world_id != 0) {
224 // Isolated worlds (content script).
225 return ScriptInjection::GetExtensionIdForIsolatedWorld(world_id);
228 // TODO(kalman): Delete this check.
229 if (frame->document().securityOrigin().isUnique())
230 return std::string();
232 // Extension pages (chrome-extension:// URLs).
233 GURL frame_url = ScriptContext::GetDataSourceURLForFrame(frame);
234 return extensions_.GetExtensionOrAppIDByURL(frame_url);
237 void Dispatcher::DidCreateScriptContext(
238 WebFrame* frame,
239 const v8::Handle<v8::Context>& v8_context,
240 int extension_group,
241 int world_id) {
242 #if !defined(ENABLE_EXTENSIONS)
243 return;
244 #endif
246 std::string extension_id = GetExtensionID(frame, world_id);
248 const Extension* extension = extensions_.GetByID(extension_id);
249 if (!extension && !extension_id.empty()) {
250 // There are conditions where despite a context being associated with an
251 // extension, no extension actually gets found. Ignore "invalid" because
252 // CSP blocks extension page loading by switching the extension ID to
253 // "invalid". This isn't interesting.
254 if (extension_id != "invalid") {
255 LOG(ERROR) << "Extension \"" << extension_id << "\" not found";
256 RenderThread::Get()->RecordAction(
257 UserMetricsAction("ExtensionNotFound_ED"));
260 extension_id = "";
263 Feature::Context context_type =
264 ClassifyJavaScriptContext(extension,
265 extension_group,
266 ScriptContext::GetDataSourceURLForFrame(frame),
267 frame->document().securityOrigin());
269 ScriptContext* context =
270 delegate_->CreateScriptContext(v8_context, frame, extension, context_type)
271 .release();
272 script_context_set_.Add(context);
274 // Initialize origin permissions for content scripts, which can't be
275 // initialized in |OnActivateExtension|.
276 if (context_type == Feature::CONTENT_SCRIPT_CONTEXT)
277 InitOriginPermissions(extension);
280 scoped_ptr<ModuleSystem> module_system(
281 new ModuleSystem(context, &source_map_));
282 context->set_module_system(module_system.Pass());
284 ModuleSystem* module_system = context->module_system();
286 // Enable natives in startup.
287 ModuleSystem::NativesEnabledScope natives_enabled_scope(module_system);
289 RegisterNativeHandlers(module_system, context);
291 // chrome.Event is part of the public API (although undocumented). Make it
292 // lazily evalulate to Event from event_bindings.js. For extensions only
293 // though, not all webpages!
294 if (context->extension()) {
295 v8::Handle<v8::Object> chrome = AsObjectOrEmpty(GetOrCreateChrome(context));
296 if (!chrome.IsEmpty())
297 module_system->SetLazyField(chrome, "Event", kEventBindings, "Event");
300 UpdateBindingsForContext(context);
302 bool is_within_platform_app = IsWithinPlatformApp();
303 // Inject custom JS into the platform app context.
304 if (is_within_platform_app) {
305 module_system->Require("platformApp");
308 delegate_->RequireAdditionalModules(context, is_within_platform_app);
310 VLOG(1) << "Num tracked contexts: " << script_context_set_.size();
313 void Dispatcher::WillReleaseScriptContext(
314 WebFrame* frame,
315 const v8::Handle<v8::Context>& v8_context,
316 int world_id) {
317 ScriptContext* context = script_context_set_.GetByV8Context(v8_context);
318 if (!context)
319 return;
321 context->DispatchOnUnloadEvent();
322 // TODO(kalman): add an invalidation observer interface to ScriptContext.
323 request_sender_->InvalidateSource(context);
325 script_context_set_.Remove(context);
326 VLOG(1) << "Num tracked contexts: " << script_context_set_.size();
329 void Dispatcher::DidCreateDocumentElement(blink::WebFrame* frame) {
330 // Note: use GetEffectiveDocumentURL not just frame->document()->url()
331 // so that this also injects the stylesheet on about:blank frames that
332 // are hosted in the extension process.
333 GURL effective_document_url = ScriptContext::GetEffectiveDocumentURL(
334 frame, frame->document().url(), true /* match_about_blank */);
335 const Extension* extension =
336 extensions_.GetExtensionOrAppByURL(effective_document_url);
338 if (extension &&
339 (extension->is_extension() || extension->is_platform_app())) {
340 int resource_id =
341 extension->is_platform_app() ? IDR_PLATFORM_APP_CSS : IDR_EXTENSION_CSS;
342 std::string stylesheet = ResourceBundle::GetSharedInstance()
343 .GetRawDataResource(resource_id)
344 .as_string();
345 ReplaceFirstSubstringAfterOffset(
346 &stylesheet, 0, "$FONTFAMILY", system_font_family_);
347 ReplaceFirstSubstringAfterOffset(
348 &stylesheet, 0, "$FONTSIZE", system_font_size_);
350 // Blink doesn't let us define an additional user agent stylesheet, so
351 // we insert the default platform app or extension stylesheet into all
352 // documents that are loaded in each app or extension.
353 frame->document().insertStyleSheet(WebString::fromUTF8(stylesheet));
355 content_watcher_->DidCreateDocumentElement(frame);
358 void Dispatcher::DidMatchCSS(
359 blink::WebFrame* frame,
360 const blink::WebVector<blink::WebString>& newly_matching_selectors,
361 const blink::WebVector<blink::WebString>& stopped_matching_selectors) {
362 content_watcher_->DidMatchCSS(
363 frame, newly_matching_selectors, stopped_matching_selectors);
366 void Dispatcher::OnExtensionResponse(int request_id,
367 bool success,
368 const base::ListValue& response,
369 const std::string& error) {
370 request_sender_->HandleResponse(request_id, success, response, error);
373 bool Dispatcher::CheckContextAccessToExtensionAPI(
374 const std::string& function_name,
375 ScriptContext* context) const {
376 if (!context) {
377 DLOG(ERROR) << "Not in a v8::Context";
378 return false;
381 // Theoretically we could end up with bindings being injected into sandboxed
382 // frames, for example content scripts. Don't let them execute API functions.
383 blink::WebFrame* frame = context->web_frame();
384 if (IsSandboxedPage(ScriptContext::GetDataSourceURLForFrame(frame))) {
385 static const char kMessage[] =
386 "%s cannot be used within a sandboxed frame.";
387 std::string error_msg = base::StringPrintf(kMessage, function_name.c_str());
388 context->isolate()->ThrowException(v8::Exception::Error(
389 v8::String::NewFromUtf8(context->isolate(), error_msg.c_str())));
390 return false;
393 Feature::Availability availability = context->GetAvailability(function_name);
394 if (!availability.is_available()) {
395 context->isolate()->ThrowException(
396 v8::Exception::Error(v8::String::NewFromUtf8(
397 context->isolate(), availability.message().c_str())));
400 return availability.is_available();
403 void Dispatcher::DispatchEvent(const std::string& extension_id,
404 const std::string& event_name) const {
405 base::ListValue args;
406 args.Set(0, new base::StringValue(event_name));
407 args.Set(1, new base::ListValue());
409 // Needed for Windows compilation, since kEventBindings is declared extern.
410 const char* local_event_bindings = kEventBindings;
411 script_context_set_.ForEach(extension_id,
412 base::Bind(&CallModuleMethod,
413 local_event_bindings,
414 kEventDispatchFunction,
415 &args));
418 void Dispatcher::InvokeModuleSystemMethod(content::RenderView* render_view,
419 const std::string& extension_id,
420 const std::string& module_name,
421 const std::string& function_name,
422 const base::ListValue& args,
423 bool user_gesture) {
424 scoped_ptr<WebScopedUserGesture> web_user_gesture;
425 if (user_gesture)
426 web_user_gesture.reset(new WebScopedUserGesture);
428 script_context_set_.ForEach(
429 extension_id,
430 render_view,
431 base::Bind(&CallModuleMethod, module_name, function_name, &args));
433 // Reset the idle handler each time there's any activity like event or message
434 // dispatch, for which Invoke is the chokepoint.
435 if (is_extension_process_) {
436 RenderThread::Get()->ScheduleIdleHandler(
437 kInitialExtensionIdleHandlerDelayMs);
440 // Tell the browser process when an event has been dispatched with a lazy
441 // background page active.
442 const Extension* extension = extensions_.GetByID(extension_id);
443 if (extension && BackgroundInfo::HasLazyBackgroundPage(extension) &&
444 module_name == kEventBindings &&
445 function_name == kEventDispatchFunction) {
446 RenderView* background_view =
447 ExtensionHelper::GetBackgroundPage(extension_id);
448 if (background_view) {
449 background_view->Send(
450 new ExtensionHostMsg_EventAck(background_view->GetRoutingID()));
455 void Dispatcher::ClearPortData(int port_id) {
456 // Only the target port side has entries in |port_to_tab_id_map_|. If
457 // |port_id| is a source port, std::map::erase() will just silently fail
458 // here as a no-op.
459 port_to_tab_id_map_.erase(port_id);
462 // static
463 std::vector<std::pair<std::string, int> > Dispatcher::GetJsResources() {
464 std::vector<std::pair<std::string, int> > resources;
466 // Libraries.
467 resources.push_back(std::make_pair("entryIdManager", IDR_ENTRY_ID_MANAGER));
468 resources.push_back(std::make_pair(kEventBindings, IDR_EVENT_BINDINGS_JS));
469 resources.push_back(std::make_pair("imageUtil", IDR_IMAGE_UTIL_JS));
470 resources.push_back(std::make_pair("json_schema", IDR_JSON_SCHEMA_JS));
471 resources.push_back(std::make_pair("lastError", IDR_LAST_ERROR_JS));
472 resources.push_back(std::make_pair("messaging", IDR_MESSAGING_JS));
473 resources.push_back(
474 std::make_pair("messaging_utils", IDR_MESSAGING_UTILS_JS));
475 resources.push_back(std::make_pair(kSchemaUtils, IDR_SCHEMA_UTILS_JS));
476 resources.push_back(std::make_pair("sendRequest", IDR_SEND_REQUEST_JS));
477 resources.push_back(std::make_pair("setIcon", IDR_SET_ICON_JS));
478 resources.push_back(std::make_pair("test", IDR_TEST_CUSTOM_BINDINGS_JS));
479 resources.push_back(
480 std::make_pair("test_environment_specific_bindings",
481 IDR_BROWSER_TEST_ENVIRONMENT_SPECIFIC_BINDINGS_JS));
482 resources.push_back(std::make_pair("uncaught_exception_handler",
483 IDR_UNCAUGHT_EXCEPTION_HANDLER_JS));
484 resources.push_back(std::make_pair("unload_event", IDR_UNLOAD_EVENT_JS));
485 resources.push_back(std::make_pair("utils", IDR_UTILS_JS));
486 resources.push_back(
487 std::make_pair(mojo::kBufferModuleName, IDR_MOJO_BUFFER_JS));
488 resources.push_back(
489 std::make_pair(mojo::kCodecModuleName, IDR_MOJO_CODEC_JS));
490 resources.push_back(
491 std::make_pair(mojo::kConnectionModuleName, IDR_MOJO_CONNECTION_JS));
492 resources.push_back(
493 std::make_pair(mojo::kConnectorModuleName, IDR_MOJO_CONNECTOR_JS));
494 resources.push_back(
495 std::make_pair(mojo::kRouterModuleName, IDR_MOJO_ROUTER_JS));
496 resources.push_back(
497 std::make_pair(mojo::kUnicodeModuleName, IDR_MOJO_UNICODE_JS));
498 resources.push_back(
499 std::make_pair(mojo::kValidatorModuleName, IDR_MOJO_VALIDATOR_JS));
501 // Custom bindings.
502 resources.push_back(
503 std::make_pair("app.runtime", IDR_APP_RUNTIME_CUSTOM_BINDINGS_JS));
504 resources.push_back(
505 std::make_pair("contextMenus", IDR_CONTEXT_MENUS_CUSTOM_BINDINGS_JS));
506 resources.push_back(
507 std::make_pair("extension", IDR_EXTENSION_CUSTOM_BINDINGS_JS));
508 resources.push_back(std::make_pair("i18n", IDR_I18N_CUSTOM_BINDINGS_JS));
509 resources.push_back(
510 std::make_pair("permissions", IDR_PERMISSIONS_CUSTOM_BINDINGS_JS));
511 resources.push_back(
512 std::make_pair("runtime", IDR_RUNTIME_CUSTOM_BINDINGS_JS));
513 resources.push_back(std::make_pair("binding", IDR_BINDING_JS));
515 // Custom types sources.
516 resources.push_back(std::make_pair("StorageArea", IDR_STORAGE_AREA_JS));
518 // Platform app sources that are not API-specific..
519 resources.push_back(std::make_pair("platformApp", IDR_PLATFORM_APP_JS));
521 return resources;
524 // NOTE: please use the naming convention "foo_natives" for these.
525 // static
526 void Dispatcher::RegisterNativeHandlers(ModuleSystem* module_system,
527 ScriptContext* context,
528 Dispatcher* dispatcher,
529 RequestSender* request_sender,
530 V8SchemaRegistry* v8_schema_registry) {
531 module_system->RegisterNativeHandler(
532 "chrome", scoped_ptr<NativeHandler>(new ChromeNativeHandler(context)));
533 module_system->RegisterNativeHandler(
534 "lazy_background_page",
535 scoped_ptr<NativeHandler>(new LazyBackgroundPageNativeHandler(context)));
536 module_system->RegisterNativeHandler(
537 "logging", scoped_ptr<NativeHandler>(new LoggingNativeHandler(context)));
538 module_system->RegisterNativeHandler("schema_registry",
539 v8_schema_registry->AsNativeHandler());
540 module_system->RegisterNativeHandler(
541 "print", scoped_ptr<NativeHandler>(new PrintNativeHandler(context)));
542 module_system->RegisterNativeHandler(
543 "test_features",
544 scoped_ptr<NativeHandler>(new TestFeaturesNativeHandler(context)));
545 module_system->RegisterNativeHandler(
546 "user_gestures",
547 scoped_ptr<NativeHandler>(new UserGesturesNativeHandler(context)));
548 module_system->RegisterNativeHandler(
549 "utils", scoped_ptr<NativeHandler>(new UtilsNativeHandler(context)));
550 module_system->RegisterNativeHandler(
551 "v8_context",
552 scoped_ptr<NativeHandler>(
553 new V8ContextNativeHandler(context, dispatcher)));
554 module_system->RegisterNativeHandler(
555 "event_natives",
556 scoped_ptr<NativeHandler>(new EventBindings(dispatcher, context)));
557 module_system->RegisterNativeHandler(
558 "messaging_natives",
559 scoped_ptr<NativeHandler>(MessagingBindings::Get(dispatcher, context)));
560 module_system->RegisterNativeHandler(
561 "apiDefinitions",
562 scoped_ptr<NativeHandler>(
563 new ApiDefinitionsNatives(dispatcher, context)));
564 module_system->RegisterNativeHandler(
565 "sendRequest",
566 scoped_ptr<NativeHandler>(
567 new SendRequestNatives(request_sender, context)));
568 module_system->RegisterNativeHandler(
569 "setIcon",
570 scoped_ptr<NativeHandler>(new SetIconNatives(request_sender, context)));
571 module_system->RegisterNativeHandler(
572 "activityLogger",
573 scoped_ptr<NativeHandler>(new APIActivityLogger(context)));
574 module_system->RegisterNativeHandler(
575 "renderViewObserverNatives",
576 scoped_ptr<NativeHandler>(new RenderViewObserverNatives(context)));
578 // Natives used by multiple APIs.
579 module_system->RegisterNativeHandler(
580 "file_system_natives",
581 scoped_ptr<NativeHandler>(new FileSystemNatives(context)));
583 // Custom bindings.
584 module_system->RegisterNativeHandler(
585 "app_runtime",
586 scoped_ptr<NativeHandler>(new AppRuntimeCustomBindings(context)));
587 module_system->RegisterNativeHandler(
588 "blob_natives",
589 scoped_ptr<NativeHandler>(new BlobNativeHandler(context)));
590 module_system->RegisterNativeHandler(
591 "context_menus",
592 scoped_ptr<NativeHandler>(new ContextMenusCustomBindings(context)));
593 module_system->RegisterNativeHandler(
594 "css_natives", scoped_ptr<NativeHandler>(new CssNativeHandler(context)));
595 module_system->RegisterNativeHandler(
596 "document_natives",
597 scoped_ptr<NativeHandler>(new DocumentCustomBindings(context)));
598 module_system->RegisterNativeHandler(
599 "guest_view_internal",
600 scoped_ptr<NativeHandler>(
601 new GuestViewInternalCustomBindings(context)));
602 module_system->RegisterNativeHandler(
603 "i18n", scoped_ptr<NativeHandler>(new I18NCustomBindings(context)));
604 module_system->RegisterNativeHandler(
605 "id_generator",
606 scoped_ptr<NativeHandler>(new IdGeneratorCustomBindings(context)));
607 module_system->RegisterNativeHandler(
608 "runtime", scoped_ptr<NativeHandler>(new RuntimeCustomBindings(context)));
611 bool Dispatcher::OnControlMessageReceived(const IPC::Message& message) {
612 bool handled = true;
613 IPC_BEGIN_MESSAGE_MAP(Dispatcher, message)
614 IPC_MESSAGE_HANDLER(ExtensionMsg_ActivateExtension, OnActivateExtension)
615 IPC_MESSAGE_HANDLER(ExtensionMsg_CancelSuspend, OnCancelSuspend)
616 IPC_MESSAGE_HANDLER(ExtensionMsg_ClearTabSpecificPermissions,
617 OnClearTabSpecificPermissions)
618 IPC_MESSAGE_HANDLER(ExtensionMsg_DeliverMessage, OnDeliverMessage)
619 IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnConnect, OnDispatchOnConnect)
620 IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnDisconnect, OnDispatchOnDisconnect)
621 IPC_MESSAGE_HANDLER(ExtensionMsg_Loaded, OnLoaded)
622 IPC_MESSAGE_HANDLER(ExtensionMsg_MessageInvoke, OnMessageInvoke)
623 IPC_MESSAGE_HANDLER(ExtensionMsg_SetChannel, OnSetChannel)
624 IPC_MESSAGE_HANDLER(ExtensionMsg_SetFunctionNames, OnSetFunctionNames)
625 IPC_MESSAGE_HANDLER(ExtensionMsg_SetScriptingWhitelist,
626 OnSetScriptingWhitelist)
627 IPC_MESSAGE_HANDLER(ExtensionMsg_SetSystemFont, OnSetSystemFont)
628 IPC_MESSAGE_HANDLER(ExtensionMsg_ShouldSuspend, OnShouldSuspend)
629 IPC_MESSAGE_HANDLER(ExtensionMsg_Suspend, OnSuspend)
630 IPC_MESSAGE_HANDLER(ExtensionMsg_TransferBlobs, OnTransferBlobs)
631 IPC_MESSAGE_HANDLER(ExtensionMsg_Unloaded, OnUnloaded)
632 IPC_MESSAGE_HANDLER(ExtensionMsg_UpdatePermissions, OnUpdatePermissions)
633 IPC_MESSAGE_HANDLER(ExtensionMsg_UpdateTabSpecificPermissions,
634 OnUpdateTabSpecificPermissions)
635 IPC_MESSAGE_HANDLER(ExtensionMsg_UsingWebRequestAPI, OnUsingWebRequestAPI)
636 IPC_MESSAGE_FORWARD(ExtensionMsg_WatchPages,
637 content_watcher_.get(),
638 ContentWatcher::OnWatchPages)
639 IPC_MESSAGE_UNHANDLED(handled = false)
640 IPC_END_MESSAGE_MAP()
642 return handled;
645 void Dispatcher::WebKitInitialized() {
646 // For extensions, we want to ensure we call the IdleHandler every so often,
647 // even if the extension keeps up activity.
648 if (is_extension_process_) {
649 forced_idle_timer_.reset(new base::RepeatingTimer<content::RenderThread>);
650 forced_idle_timer_->Start(
651 FROM_HERE,
652 base::TimeDelta::FromMilliseconds(kMaxExtensionIdleHandlerDelayMs),
653 RenderThread::Get(),
654 &RenderThread::IdleHandler);
657 // Initialize host permissions for any extensions that were activated before
658 // WebKit was initialized.
659 for (std::set<std::string>::iterator iter = active_extension_ids_.begin();
660 iter != active_extension_ids_.end();
661 ++iter) {
662 const Extension* extension = extensions_.GetByID(*iter);
663 CHECK(extension);
665 InitOriginPermissions(extension);
668 EnableCustomElementWhiteList();
670 is_webkit_initialized_ = true;
673 void Dispatcher::IdleNotification() {
674 if (is_extension_process_ && forced_idle_timer_) {
675 // Dampen the forced delay as well if the extension stays idle for long
676 // periods of time. (forced_idle_timer_ can be NULL after
677 // OnRenderProcessShutdown has been called.)
678 int64 forced_delay_ms =
679 std::max(RenderThread::Get()->GetIdleNotificationDelayInMs(),
680 kMaxExtensionIdleHandlerDelayMs);
681 forced_idle_timer_->Stop();
682 forced_idle_timer_->Start(
683 FROM_HERE,
684 base::TimeDelta::FromMilliseconds(forced_delay_ms),
685 RenderThread::Get(),
686 &RenderThread::IdleHandler);
690 void Dispatcher::OnRenderProcessShutdown() {
691 v8_schema_registry_.reset();
692 forced_idle_timer_.reset();
695 void Dispatcher::OnActivateExtension(const std::string& extension_id) {
696 const Extension* extension = extensions_.GetByID(extension_id);
697 if (!extension) {
698 // Extension was activated but was never loaded. This probably means that
699 // the renderer failed to load it (or the browser failed to tell us when it
700 // did). Failures shouldn't happen, but instead of crashing there (which
701 // executes on all renderers) be conservative and only crash in the renderer
702 // of the extension which failed to load; this one.
703 std::string& error = extension_load_errors_[extension_id];
704 char minidump[256];
705 base::debug::Alias(&minidump);
706 base::snprintf(minidump,
707 arraysize(minidump),
708 "e::dispatcher:%s:%s",
709 extension_id.c_str(),
710 error.c_str());
711 CHECK(extension) << extension_id << " was never loaded: " << error;
714 active_extension_ids_.insert(extension_id);
716 // This is called when starting a new extension page, so start the idle
717 // handler ticking.
718 RenderThread::Get()->ScheduleIdleHandler(kInitialExtensionIdleHandlerDelayMs);
720 if (is_webkit_initialized_) {
721 extensions::DOMActivityLogger::AttachToWorld(
722 extensions::DOMActivityLogger::kMainWorldId, extension_id);
724 InitOriginPermissions(extension);
727 UpdateActiveExtensions();
730 void Dispatcher::OnCancelSuspend(const std::string& extension_id) {
731 DispatchEvent(extension_id, kOnSuspendCanceledEvent);
734 void Dispatcher::OnClearTabSpecificPermissions(
735 int tab_id,
736 const std::vector<std::string>& extension_ids) {
737 delegate_->ClearTabSpecificPermissions(this, tab_id, extension_ids);
740 void Dispatcher::OnDeliverMessage(int target_port_id, const Message& message) {
741 scoped_ptr<RequestSender::ScopedTabID> scoped_tab_id;
742 std::map<int, int>::const_iterator it =
743 port_to_tab_id_map_.find(target_port_id);
744 if (it != port_to_tab_id_map_.end()) {
745 scoped_tab_id.reset(
746 new RequestSender::ScopedTabID(request_sender(), it->second));
749 MessagingBindings::DeliverMessage(script_context_set_,
750 target_port_id,
751 message,
752 NULL); // All render views.
755 void Dispatcher::OnDispatchOnConnect(
756 int target_port_id,
757 const std::string& channel_name,
758 const base::DictionaryValue& source_tab,
759 const ExtensionMsg_ExternalConnectionInfo& info,
760 const std::string& tls_channel_id) {
761 DCHECK(!ContainsKey(port_to_tab_id_map_, target_port_id));
762 DCHECK_EQ(1, target_port_id % 2); // target renderer ports have odd IDs.
763 int sender_tab_id = -1;
764 source_tab.GetInteger("id", &sender_tab_id);
765 port_to_tab_id_map_[target_port_id] = sender_tab_id;
767 MessagingBindings::DispatchOnConnect(script_context_set_,
768 target_port_id,
769 channel_name,
770 source_tab,
771 info,
772 tls_channel_id,
773 NULL); // All render views.
776 void Dispatcher::OnDispatchOnDisconnect(int port_id,
777 const std::string& error_message) {
778 MessagingBindings::DispatchOnDisconnect(script_context_set_,
779 port_id,
780 error_message,
781 NULL); // All render views.
784 void Dispatcher::OnLoaded(
785 const std::vector<ExtensionMsg_Loaded_Params>& loaded_extensions) {
786 std::vector<ExtensionMsg_Loaded_Params>::const_iterator i;
787 for (i = loaded_extensions.begin(); i != loaded_extensions.end(); ++i) {
788 std::string error;
789 scoped_refptr<const Extension> extension = i->ConvertToExtension(&error);
790 if (!extension.get()) {
791 extension_load_errors_[i->id] = error;
792 continue;
794 OnLoadedInternal(extension);
796 // Update the available bindings for all contexts. These may have changed if
797 // an externally_connectable extension was loaded that can connect to an
798 // open webpage.
799 UpdateBindings("");
802 void Dispatcher::OnLoadedInternal(scoped_refptr<const Extension> extension) {
803 extensions_.Insert(extension);
806 void Dispatcher::OnMessageInvoke(const std::string& extension_id,
807 const std::string& module_name,
808 const std::string& function_name,
809 const base::ListValue& args,
810 bool user_gesture) {
811 InvokeModuleSystemMethod(
812 NULL, extension_id, module_name, function_name, args, user_gesture);
815 void Dispatcher::OnSetChannel(int channel) {
816 delegate_->SetChannel(channel);
819 void Dispatcher::OnSetFunctionNames(const std::vector<std::string>& names) {
820 function_names_.clear();
821 for (size_t i = 0; i < names.size(); ++i)
822 function_names_.insert(names[i]);
825 void Dispatcher::OnSetScriptingWhitelist(
826 const ExtensionsClient::ScriptingWhitelist& extension_ids) {
827 ExtensionsClient::Get()->SetScriptingWhitelist(extension_ids);
830 void Dispatcher::OnSetSystemFont(const std::string& font_family,
831 const std::string& font_size) {
832 system_font_family_ = font_family;
833 system_font_size_ = font_size;
836 void Dispatcher::OnShouldSuspend(const std::string& extension_id,
837 uint64 sequence_id) {
838 RenderThread::Get()->Send(
839 new ExtensionHostMsg_ShouldSuspendAck(extension_id, sequence_id));
842 void Dispatcher::OnSuspend(const std::string& extension_id) {
843 // Dispatch the suspend event. This doesn't go through the standard event
844 // dispatch machinery because it requires special handling. We need to let
845 // the browser know when we are starting and stopping the event dispatch, so
846 // that it still considers the extension idle despite any activity the suspend
847 // event creates.
848 DispatchEvent(extension_id, kOnSuspendEvent);
849 RenderThread::Get()->Send(new ExtensionHostMsg_SuspendAck(extension_id));
852 void Dispatcher::OnTransferBlobs(const std::vector<std::string>& blob_uuids) {
853 RenderThread::Get()->Send(new ExtensionHostMsg_TransferBlobsAck(blob_uuids));
856 void Dispatcher::OnUnloaded(const std::string& id) {
857 extensions_.Remove(id);
858 active_extension_ids_.erase(id);
860 // If the extension is later reloaded with a different set of permissions,
861 // we'd like it to get a new isolated world ID, so that it can pick up the
862 // changed origin whitelist.
863 ScriptInjection::RemoveIsolatedWorld(id);
865 // Invalidate all of the contexts that were removed.
866 // TODO(kalman): add an invalidation observer interface to ScriptContext.
867 ScriptContextSet::ContextSet removed_contexts =
868 script_context_set_.OnExtensionUnloaded(id);
869 for (ScriptContextSet::ContextSet::iterator it = removed_contexts.begin();
870 it != removed_contexts.end();
871 ++it) {
872 request_sender_->InvalidateSource(*it);
875 // Update the available bindings for the remaining contexts. These may have
876 // changed if an externally_connectable extension is unloaded and a webpage
877 // is no longer accessible.
878 UpdateBindings("");
880 // Invalidates the messages map for the extension in case the extension is
881 // reloaded with a new messages map.
882 EraseL10nMessagesMap(id);
884 // We don't do anything with existing platform-app stylesheets. They will
885 // stay resident, but the URL pattern corresponding to the unloaded
886 // extension's URL just won't match anything anymore.
889 void Dispatcher::OnUpdatePermissions(
890 const ExtensionMsg_UpdatePermissions_Params& params) {
891 const Extension* extension = extensions_.GetByID(params.extension_id);
892 if (!extension)
893 return;
895 scoped_refptr<const PermissionSet> active =
896 params.active_permissions.ToPermissionSet();
897 scoped_refptr<const PermissionSet> withheld =
898 params.withheld_permissions.ToPermissionSet();
900 if (is_webkit_initialized_) {
901 UpdateOriginPermissions(
902 extension,
903 extension->permissions_data()->GetEffectiveHostPermissions(),
904 active->effective_hosts());
907 extension->permissions_data()->SetPermissions(active, withheld);
908 UpdateBindings(extension->id());
911 void Dispatcher::OnUpdateTabSpecificPermissions(
912 const GURL& url,
913 int tab_id,
914 const std::string& extension_id,
915 const URLPatternSet& origin_set) {
916 delegate_->UpdateTabSpecificPermissions(
917 this, url, tab_id, extension_id, origin_set);
920 void Dispatcher::OnUsingWebRequestAPI(bool webrequest_used) {
921 delegate_->HandleWebRequestAPIUsage(webrequest_used);
924 void Dispatcher::OnUserScriptsUpdated(
925 const std::set<std::string>& changed_extensions,
926 const std::vector<UserScript*>& scripts) {
927 UpdateActiveExtensions();
930 void Dispatcher::UpdateActiveExtensions() {
931 std::set<std::string> active_extensions = active_extension_ids_;
932 user_script_set_manager_->GetAllActiveExtensionIds(&active_extensions);
933 delegate_->OnActiveExtensionsUpdated(active_extensions);
936 void Dispatcher::InitOriginPermissions(const Extension* extension) {
937 delegate_->InitOriginPermissions(extension,
938 IsExtensionActive(extension->id()));
939 UpdateOriginPermissions(
940 extension,
941 URLPatternSet(), // No old permissions.
942 extension->permissions_data()->GetEffectiveHostPermissions());
945 void Dispatcher::UpdateOriginPermissions(
946 const Extension* extension,
947 const URLPatternSet& old_patterns,
948 const URLPatternSet& new_patterns) {
949 static const char* kSchemes[] = {
950 url::kHttpScheme,
951 url::kHttpsScheme,
952 url::kFileScheme,
953 content::kChromeUIScheme,
954 url::kFtpScheme,
956 for (size_t i = 0; i < arraysize(kSchemes); ++i) {
957 const char* scheme = kSchemes[i];
958 // Remove all old patterns...
959 for (URLPatternSet::const_iterator pattern = old_patterns.begin();
960 pattern != old_patterns.end(); ++pattern) {
961 if (pattern->MatchesScheme(scheme)) {
962 WebSecurityPolicy::removeOriginAccessWhitelistEntry(
963 extension->url(),
964 WebString::fromUTF8(scheme),
965 WebString::fromUTF8(pattern->host()),
966 pattern->match_subdomains());
969 // ...And add the new ones.
970 for (URLPatternSet::const_iterator pattern = new_patterns.begin();
971 pattern != new_patterns.end(); ++pattern) {
972 if (pattern->MatchesScheme(scheme)) {
973 WebSecurityPolicy::addOriginAccessWhitelistEntry(
974 extension->url(),
975 WebString::fromUTF8(scheme),
976 WebString::fromUTF8(pattern->host()),
977 pattern->match_subdomains());
983 void Dispatcher::EnableCustomElementWhiteList() {
984 blink::WebCustomElement::addEmbedderCustomElementName("appplugin");
985 blink::WebCustomElement::addEmbedderCustomElementName("appview");
986 blink::WebCustomElement::addEmbedderCustomElementName("browserplugin");
987 blink::WebCustomElement::addEmbedderCustomElementName("extensionoptions");
988 blink::WebCustomElement::addEmbedderCustomElementName(
989 "extensionoptionsplugin");
990 blink::WebCustomElement::addEmbedderCustomElementName("webview");
993 void Dispatcher::UpdateBindings(const std::string& extension_id) {
994 script_context_set().ForEach(extension_id,
995 base::Bind(&Dispatcher::UpdateBindingsForContext,
996 base::Unretained(this)));
999 void Dispatcher::UpdateBindingsForContext(ScriptContext* context) {
1000 v8::HandleScope handle_scope(context->isolate());
1001 v8::Context::Scope context_scope(context->v8_context());
1003 // TODO(kalman): Make the bindings registration have zero overhead then run
1004 // the same code regardless of context type.
1005 switch (context->context_type()) {
1006 case Feature::UNSPECIFIED_CONTEXT:
1007 case Feature::WEB_PAGE_CONTEXT:
1008 case Feature::BLESSED_WEB_PAGE_CONTEXT: {
1009 // Web page context; it's too expensive to run the full bindings code.
1010 // Hard-code that the app and webstore APIs are available...
1011 if (context->GetAvailability("app").is_available())
1012 RegisterBinding("app", context);
1014 if (context->GetAvailability("webstore").is_available())
1015 RegisterBinding("webstore", context);
1017 // ... and that the runtime API might be available if any extension can
1018 // connect to it.
1019 bool runtime_is_available = false;
1020 for (ExtensionSet::const_iterator it = extensions_.begin();
1021 it != extensions_.end();
1022 ++it) {
1023 ExternallyConnectableInfo* info =
1024 static_cast<ExternallyConnectableInfo*>(
1025 (*it)->GetManifestData(manifest_keys::kExternallyConnectable));
1026 if (info && info->matches.MatchesURL(context->GetURL())) {
1027 runtime_is_available = true;
1028 break;
1031 if (runtime_is_available)
1032 RegisterBinding("runtime", context);
1033 break;
1036 case Feature::BLESSED_EXTENSION_CONTEXT:
1037 case Feature::UNBLESSED_EXTENSION_CONTEXT:
1038 case Feature::CONTENT_SCRIPT_CONTEXT:
1039 case Feature::WEBUI_CONTEXT: {
1040 // Extension context; iterate through all the APIs and bind the available
1041 // ones.
1042 const FeatureProvider* api_feature_provider =
1043 FeatureProvider::GetAPIFeatures();
1044 const std::vector<std::string>& apis =
1045 api_feature_provider->GetAllFeatureNames();
1046 for (std::vector<std::string>::const_iterator it = apis.begin();
1047 it != apis.end();
1048 ++it) {
1049 const std::string& api_name = *it;
1050 Feature* feature = api_feature_provider->GetFeature(api_name);
1051 DCHECK(feature);
1053 // Internal APIs are included via require(api_name) from internal code
1054 // rather than chrome[api_name].
1055 if (feature->IsInternal())
1056 continue;
1058 // If this API has a parent feature (and isn't marked 'noparent'),
1059 // then this must be a function or event, so we should not register.
1060 if (api_feature_provider->GetParent(feature) != NULL)
1061 continue;
1063 // Skip chrome.test if this isn't a test.
1064 if (api_name == "test" &&
1065 !CommandLine::ForCurrentProcess()->HasSwitch(
1066 ::switches::kTestType)) {
1067 continue;
1070 if (context->IsAnyFeatureAvailableToContext(*feature))
1071 RegisterBinding(api_name, context);
1073 break;
1078 void Dispatcher::RegisterBinding(const std::string& api_name,
1079 ScriptContext* context) {
1080 std::string bind_name;
1081 v8::Handle<v8::Object> bind_object =
1082 GetOrCreateBindObjectIfAvailable(api_name, &bind_name, context);
1084 // Empty if the bind object failed to be created, probably because the
1085 // extension overrode chrome with a non-object, e.g. window.chrome = true.
1086 if (bind_object.IsEmpty())
1087 return;
1089 v8::Local<v8::String> v8_api_name =
1090 v8::String::NewFromUtf8(context->isolate(), api_name.c_str());
1091 if (bind_object->HasRealNamedProperty(v8_api_name)) {
1092 // The bind object may already have the property if the API has been
1093 // registered before (or if the extension has put something there already,
1094 // but, whatevs).
1096 // In the former case, we need to re-register the bindings for the APIs
1097 // which the extension now has permissions for (if any), but not touch any
1098 // others so that we don't destroy state such as event listeners.
1100 // TODO(kalman): Only register available APIs to make this all moot.
1101 if (bind_object->HasRealNamedCallbackProperty(v8_api_name))
1102 return; // lazy binding still there, nothing to do
1103 if (bind_object->Get(v8_api_name)->IsObject())
1104 return; // binding has already been fully installed
1107 ModuleSystem* module_system = context->module_system();
1108 if (!source_map_.Contains(api_name)) {
1109 module_system->RegisterNativeHandler(
1110 api_name,
1111 scoped_ptr<NativeHandler>(new BindingGeneratingNativeHandler(
1112 module_system, api_name, "binding")));
1113 module_system->SetNativeLazyField(
1114 bind_object, bind_name, api_name, "binding");
1115 } else {
1116 module_system->SetLazyField(bind_object, bind_name, api_name, "binding");
1120 // NOTE: please use the naming convention "foo_natives" for these.
1121 void Dispatcher::RegisterNativeHandlers(ModuleSystem* module_system,
1122 ScriptContext* context) {
1123 RegisterNativeHandlers(module_system,
1124 context,
1125 this,
1126 request_sender_.get(),
1127 v8_schema_registry_.get());
1128 const Extension* extension = context->extension();
1129 int manifest_version = extension ? extension->manifest_version() : 1;
1130 bool send_request_disabled =
1131 (extension && Manifest::IsUnpackedLocation(extension->location()) &&
1132 BackgroundInfo::HasLazyBackgroundPage(extension));
1133 module_system->RegisterNativeHandler(
1134 "process",
1135 scoped_ptr<NativeHandler>(new ProcessInfoNativeHandler(
1136 context,
1137 context->GetExtensionID(),
1138 context->GetContextTypeDescription(),
1139 ExtensionsRendererClient::Get()->IsIncognitoProcess(),
1140 manifest_version,
1141 send_request_disabled)));
1143 delegate_->RegisterNativeHandlers(this, module_system, context);
1146 void Dispatcher::PopulateSourceMap() {
1147 const std::vector<std::pair<std::string, int> > resources = GetJsResources();
1148 for (std::vector<std::pair<std::string, int> >::const_iterator resource =
1149 resources.begin();
1150 resource != resources.end();
1151 ++resource) {
1152 source_map_.RegisterSource(resource->first, resource->second);
1154 delegate_->PopulateSourceMap(&source_map_);
1157 bool Dispatcher::IsWithinPlatformApp() {
1158 for (std::set<std::string>::iterator iter = active_extension_ids_.begin();
1159 iter != active_extension_ids_.end();
1160 ++iter) {
1161 const Extension* extension = extensions_.GetByID(*iter);
1162 if (extension && extension->is_platform_app())
1163 return true;
1165 return false;
1168 // TODO(kalman): This is checking for the wrong thing, it should be checking if
1169 // the frame's security origin is unique. The extension sandbox directive is
1170 // checked for in extensions/common/manifest_handlers/csp_info.cc.
1171 bool Dispatcher::IsSandboxedPage(const GURL& url) const {
1172 if (url.SchemeIs(kExtensionScheme)) {
1173 const Extension* extension = extensions_.GetByID(url.host());
1174 if (extension) {
1175 return SandboxedPageInfo::IsSandboxedPage(extension, url.path());
1178 return false;
1181 Feature::Context Dispatcher::ClassifyJavaScriptContext(
1182 const Extension* extension,
1183 int extension_group,
1184 const GURL& url,
1185 const blink::WebSecurityOrigin& origin) {
1186 // WARNING: This logic must match ProcessMap::GetContextType, as much as
1187 // possible.
1189 DCHECK_GE(extension_group, 0);
1190 if (extension_group == EXTENSION_GROUP_CONTENT_SCRIPTS) {
1191 return extension ? // TODO(kalman): when does this happen?
1192 Feature::CONTENT_SCRIPT_CONTEXT
1193 : Feature::UNSPECIFIED_CONTEXT;
1196 // We have an explicit check for sandboxed pages before checking whether the
1197 // extension is active in this process because:
1198 // 1. Sandboxed pages run in the same process as regular extension pages, so
1199 // the extension is considered active.
1200 // 2. ScriptContext creation (which triggers bindings injection) happens
1201 // before the SecurityContext is updated with the sandbox flags (after
1202 // reading the CSP header), so the caller can't check if the context's
1203 // security origin is unique yet.
1204 if (IsSandboxedPage(url))
1205 return Feature::WEB_PAGE_CONTEXT;
1207 if (extension && IsExtensionActive(extension->id())) {
1208 // |extension| is active in this process, but it could be either a true
1209 // extension process or within the extent of a hosted app. In the latter
1210 // case this would usually be considered a (blessed) web page context,
1211 // unless the extension in question is a component extension, in which case
1212 // we cheat and call it blessed.
1213 return (extension->is_hosted_app() &&
1214 extension->location() != Manifest::COMPONENT)
1215 ? Feature::BLESSED_WEB_PAGE_CONTEXT
1216 : Feature::BLESSED_EXTENSION_CONTEXT;
1219 // TODO(kalman): This isUnique() check is wrong, it should be performed as
1220 // part of IsSandboxedPage().
1221 if (!origin.isUnique() && extensions_.ExtensionBindingsAllowed(url)) {
1222 if (!extension) // TODO(kalman): when does this happen?
1223 return Feature::UNSPECIFIED_CONTEXT;
1224 return extension->is_hosted_app() ? Feature::BLESSED_WEB_PAGE_CONTEXT
1225 : Feature::UNBLESSED_EXTENSION_CONTEXT;
1228 if (!url.is_valid())
1229 return Feature::UNSPECIFIED_CONTEXT;
1231 if (url.SchemeIs(content::kChromeUIScheme))
1232 return Feature::WEBUI_CONTEXT;
1234 return Feature::WEB_PAGE_CONTEXT;
1237 v8::Handle<v8::Object> Dispatcher::GetOrCreateObject(
1238 const v8::Handle<v8::Object>& object,
1239 const std::string& field,
1240 v8::Isolate* isolate) {
1241 v8::Handle<v8::String> key = v8::String::NewFromUtf8(isolate, field.c_str());
1242 // If the object has a callback property, it is assumed it is an unavailable
1243 // API, so it is safe to delete. This is checked before GetOrCreateObject is
1244 // called.
1245 if (object->HasRealNamedCallbackProperty(key)) {
1246 object->Delete(key);
1247 } else if (object->HasRealNamedProperty(key)) {
1248 v8::Handle<v8::Value> value = object->Get(key);
1249 CHECK(value->IsObject());
1250 return v8::Handle<v8::Object>::Cast(value);
1253 v8::Handle<v8::Object> new_object = v8::Object::New(isolate);
1254 object->Set(key, new_object);
1255 return new_object;
1258 v8::Handle<v8::Object> Dispatcher::GetOrCreateBindObjectIfAvailable(
1259 const std::string& api_name,
1260 std::string* bind_name,
1261 ScriptContext* context) {
1262 std::vector<std::string> split;
1263 base::SplitString(api_name, '.', &split);
1265 v8::Handle<v8::Object> bind_object;
1267 // Check if this API has an ancestor. If the API's ancestor is available and
1268 // the API is not available, don't install the bindings for this API. If
1269 // the API is available and its ancestor is not, delete the ancestor and
1270 // install the bindings for the API. This is to prevent loading the ancestor
1271 // API schema if it will not be needed.
1273 // For example:
1274 // If app is available and app.window is not, just install app.
1275 // If app.window is available and app is not, delete app and install
1276 // app.window on a new object so app does not have to be loaded.
1277 const FeatureProvider* api_feature_provider =
1278 FeatureProvider::GetAPIFeatures();
1279 std::string ancestor_name;
1280 bool only_ancestor_available = false;
1282 for (size_t i = 0; i < split.size() - 1; ++i) {
1283 ancestor_name += (i ? "." : "") + split[i];
1284 if (api_feature_provider->GetFeature(ancestor_name) &&
1285 context->GetAvailability(ancestor_name).is_available() &&
1286 !context->GetAvailability(api_name).is_available()) {
1287 only_ancestor_available = true;
1288 break;
1291 if (bind_object.IsEmpty()) {
1292 bind_object = AsObjectOrEmpty(GetOrCreateChrome(context));
1293 if (bind_object.IsEmpty())
1294 return v8::Handle<v8::Object>();
1296 bind_object = GetOrCreateObject(bind_object, split[i], context->isolate());
1299 if (only_ancestor_available)
1300 return v8::Handle<v8::Object>();
1302 if (bind_name)
1303 *bind_name = split.back();
1305 return bind_object.IsEmpty() ? AsObjectOrEmpty(GetOrCreateChrome(context))
1306 : bind_object;
1309 } // namespace extensions