Roll src/third_party/WebKit eac3800:0237a66 (svn 202606:202607)
[chromium-blink-merge.git] / chrome / renderer / chrome_content_renderer_client.cc
blob779a8a4cb55243d3705dd389a118073b3d0f2d88
1 // Copyright (c) 2012 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 "chrome/renderer/chrome_content_renderer_client.h"
7 #include "base/command_line.h"
8 #include "base/debug/crash_logging.h"
9 #include "base/logging.h"
10 #include "base/metrics/field_trial.h"
11 #include "base/metrics/histogram.h"
12 #include "base/metrics/user_metrics_action.h"
13 #include "base/strings/string_number_conversions.h"
14 #include "base/strings/string_util.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "base/values.h"
17 #include "chrome/common/channel_info.h"
18 #include "chrome/common/chrome_paths.h"
19 #include "chrome/common/chrome_switches.h"
20 #include "chrome/common/crash_keys.h"
21 #include "chrome/common/extensions/extension_metrics.h"
22 #include "chrome/common/localized_error.h"
23 #include "chrome/common/pepper_permission_util.h"
24 #include "chrome/common/render_messages.h"
25 #include "chrome/common/secure_origin_whitelist.h"
26 #include "chrome/common/url_constants.h"
27 #include "chrome/grit/generated_resources.h"
28 #include "chrome/grit/locale_settings.h"
29 #include "chrome/grit/renderer_resources.h"
30 #include "chrome/renderer/banners/app_banner_client.h"
31 #include "chrome/renderer/benchmarking_extension.h"
32 #include "chrome/renderer/chrome_render_frame_observer.h"
33 #include "chrome/renderer/chrome_render_process_observer.h"
34 #include "chrome/renderer/chrome_render_view_observer.h"
35 #include "chrome/renderer/content_settings_observer.h"
36 #include "chrome/renderer/external_extension.h"
37 #include "chrome/renderer/loadtimes_extension_bindings.h"
38 #include "chrome/renderer/media/chrome_key_systems.h"
39 #include "chrome/renderer/net/net_error_helper.h"
40 #include "chrome/renderer/net_benchmarking_extension.h"
41 #include "chrome/renderer/page_load_histograms.h"
42 #include "chrome/renderer/pepper/pepper_helper.h"
43 #include "chrome/renderer/plugins/non_loadable_plugin_placeholder.h"
44 #include "chrome/renderer/plugins/plugin_preroller.h"
45 #include "chrome/renderer/plugins/plugin_uma.h"
46 #include "chrome/renderer/prerender/prerender_dispatcher.h"
47 #include "chrome/renderer/prerender/prerender_helper.h"
48 #include "chrome/renderer/prerender/prerenderer_client.h"
49 #include "chrome/renderer/safe_browsing/malware_dom_details.h"
50 #include "chrome/renderer/safe_browsing/phishing_classifier_delegate.h"
51 #include "chrome/renderer/searchbox/search_bouncer.h"
52 #include "chrome/renderer/searchbox/searchbox.h"
53 #include "chrome/renderer/searchbox/searchbox_extension.h"
54 #include "chrome/renderer/tts_dispatcher.h"
55 #include "chrome/renderer/worker_content_settings_client_proxy.h"
56 #include "components/autofill/content/renderer/autofill_agent.h"
57 #include "components/autofill/content/renderer/password_autofill_agent.h"
58 #include "components/autofill/content/renderer/password_generation_agent.h"
59 #include "components/content_settings/core/common/content_settings_pattern.h"
60 #include "components/data_reduction_proxy/core/common/data_reduction_proxy_headers.h"
61 #include "components/dom_distiller/core/url_constants.h"
62 #include "components/nacl/renderer/ppb_nacl_private.h"
63 #include "components/nacl/renderer/ppb_nacl_private_impl.h"
64 #include "components/network_hints/renderer/prescient_networking_dispatcher.h"
65 #include "components/page_load_metrics/renderer/metrics_render_frame_observer.h"
66 #include "components/password_manager/content/renderer/credential_manager_client.h"
67 #include "components/pdf/renderer/pepper_pdf_host.h"
68 #include "components/plugins/renderer/mobile_youtube_plugin.h"
69 #include "components/signin/core/common/profile_management_switches.h"
70 #include "components/version_info/version_info.h"
71 #include "components/visitedlink/renderer/visitedlink_slave.h"
72 #include "components/web_cache/renderer/web_cache_render_process_observer.h"
73 #include "content/public/common/content_constants.h"
74 #include "content/public/renderer/plugin_instance_throttler.h"
75 #include "content/public/renderer/render_frame.h"
76 #include "content/public/renderer/render_thread.h"
77 #include "content/public/renderer/render_view.h"
78 #include "content/public/renderer/render_view_visitor.h"
79 #include "extensions/common/constants.h"
80 #include "ipc/ipc_sync_channel.h"
81 #include "net/base/net_errors.h"
82 #include "ppapi/c/private/ppb_pdf.h"
83 #include "ppapi/shared_impl/ppapi_switches.h"
84 #include "third_party/WebKit/public/platform/WebURL.h"
85 #include "third_party/WebKit/public/platform/WebURLError.h"
86 #include "third_party/WebKit/public/platform/WebURLRequest.h"
87 #include "third_party/WebKit/public/platform/WebURLResponse.h"
88 #include "third_party/WebKit/public/web/WebCache.h"
89 #include "third_party/WebKit/public/web/WebDataSource.h"
90 #include "third_party/WebKit/public/web/WebDocument.h"
91 #include "third_party/WebKit/public/web/WebElement.h"
92 #include "third_party/WebKit/public/web/WebLocalFrame.h"
93 #include "third_party/WebKit/public/web/WebPluginContainer.h"
94 #include "third_party/WebKit/public/web/WebPluginParams.h"
95 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
96 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
97 #include "ui/base/l10n/l10n_util.h"
98 #include "ui/base/layout.h"
99 #include "ui/base/resource/resource_bundle.h"
100 #include "ui/base/webui/jstemplate_builder.h"
101 #include "widevine_cdm_version.h" // In SHARED_INTERMEDIATE_DIR.
103 #if !defined(DISABLE_NACL)
104 #include "components/nacl/common/nacl_constants.h"
105 #include "components/nacl/renderer/nacl_helper.h"
106 #endif
108 #if defined(ENABLE_EXTENSIONS)
109 #include "chrome/common/extensions/chrome_extensions_client.h"
110 #include "chrome/common/extensions/extension_process_policy.h"
111 #include "chrome/renderer/extensions/chrome_extensions_dispatcher_delegate.h"
112 #include "chrome/renderer/extensions/chrome_extensions_renderer_client.h"
113 #include "chrome/renderer/extensions/renderer_permissions_policy_delegate.h"
114 #include "chrome/renderer/extensions/resource_request_policy.h"
115 #include "chrome/renderer/media/cast_ipc_dispatcher.h"
116 #include "extensions/common/extension.h"
117 #include "extensions/common/extension_set.h"
118 #include "extensions/common/extension_urls.h"
119 #include "extensions/common/switches.h"
120 #include "extensions/renderer/dispatcher.h"
121 #include "extensions/renderer/extension_frame_helper.h"
122 #include "extensions/renderer/extension_helper.h"
123 #include "extensions/renderer/extensions_render_frame_observer.h"
124 #include "extensions/renderer/guest_view/extensions_guest_view_container.h"
125 #include "extensions/renderer/guest_view/extensions_guest_view_container_dispatcher.h"
126 #include "extensions/renderer/guest_view/mime_handler_view/mime_handler_view_container.h"
127 #include "extensions/renderer/renderer_extension_registry.h"
128 #include "extensions/renderer/script_context.h"
129 #endif
131 #if defined(ENABLE_IPC_FUZZER)
132 #include "chrome/common/external_ipc_dumper.h"
133 #endif
135 #if defined(ENABLE_PLUGINS)
136 #include "chrome/renderer/plugins/chrome_plugin_placeholder.h"
137 #endif
139 #if defined(ENABLE_PRINTING)
140 #include "chrome/renderer/printing/chrome_print_web_view_helper_delegate.h"
141 #include "components/printing/renderer/print_web_view_helper.h"
142 #endif
144 #if defined(ENABLE_PRINT_PREVIEW)
145 #include "chrome/renderer/pepper/chrome_pdf_print_client.h"
146 #endif
148 #if defined(ENABLE_SPELLCHECK)
149 #include "chrome/renderer/spellchecker/spellcheck.h"
150 #include "chrome/renderer/spellchecker/spellcheck_provider.h"
151 #endif
153 #if defined(ENABLE_WEBRTC)
154 #include "chrome/renderer/media/webrtc_logging_message_filter.h"
155 #endif
157 using autofill::AutofillAgent;
158 using autofill::PasswordAutofillAgent;
159 using autofill::PasswordGenerationAgent;
160 using base::ASCIIToUTF16;
161 using base::UserMetricsAction;
162 using content::PluginInstanceThrottler;
163 using content::RenderFrame;
164 using content::RenderThread;
165 using content::WebPluginInfo;
166 using extensions::Extension;
167 using blink::WebCache;
168 using blink::WebConsoleMessage;
169 using blink::WebDataSource;
170 using blink::WebDocument;
171 using blink::WebLocalFrame;
172 using blink::WebPlugin;
173 using blink::WebPluginParams;
174 using blink::WebSecurityOrigin;
175 using blink::WebSecurityPolicy;
176 using blink::WebString;
177 using blink::WebURL;
178 using blink::WebURLError;
179 using blink::WebURLRequest;
180 using blink::WebURLResponse;
181 using blink::WebVector;
183 namespace {
185 ChromeContentRendererClient* g_current_client;
187 // Whitelist PPAPI for Android Runtime for Chromium. (See crbug.com/383937)
188 #if defined(ENABLE_PLUGINS)
189 const char* const kPredefinedAllowedCameraDeviceOrigins[] = {
190 "6EAED1924DB611B6EEF2A664BD077BE7EAD33B8F",
191 "4EB74897CB187C7633357C2FE832E0AD6A44883A"
194 const char* const kPredefinedAllowedCompositorOrigins[] = {
195 "6EAED1924DB611B6EEF2A664BD077BE7EAD33B8F",
196 "4EB74897CB187C7633357C2FE832E0AD6A44883A"
198 #endif
200 #if defined(ENABLE_PLUGINS)
201 void AppendParams(const std::vector<base::string16>& additional_names,
202 const std::vector<base::string16>& additional_values,
203 WebVector<WebString>* existing_names,
204 WebVector<WebString>* existing_values) {
205 DCHECK(additional_names.size() == additional_values.size());
206 DCHECK(existing_names->size() == existing_values->size());
208 size_t existing_size = existing_names->size();
209 size_t total_size = existing_size + additional_names.size();
211 WebVector<WebString> names(total_size);
212 WebVector<WebString> values(total_size);
214 for (size_t i = 0; i < existing_size; ++i) {
215 names[i] = (*existing_names)[i];
216 values[i] = (*existing_values)[i];
219 for (size_t i = 0; i < additional_names.size(); ++i) {
220 names[existing_size + i] = additional_names[i];
221 values[existing_size + i] = additional_values[i];
224 existing_names->swap(names);
225 existing_values->swap(values);
228 // For certain sandboxed Pepper plugins, use the JavaScript Content Settings.
229 bool ShouldUseJavaScriptSettingForPlugin(const WebPluginInfo& plugin) {
230 if (plugin.type != WebPluginInfo::PLUGIN_TYPE_PEPPER_IN_PROCESS &&
231 plugin.type != WebPluginInfo::PLUGIN_TYPE_PEPPER_OUT_OF_PROCESS) {
232 return false;
235 #if !defined(DISABLE_NACL)
236 // Treat Native Client invocations like JavaScript.
237 if (plugin.name == ASCIIToUTF16(nacl::kNaClPluginName))
238 return true;
239 #endif
241 #if defined(WIDEVINE_CDM_AVAILABLE) && defined(ENABLE_PEPPER_CDMS)
242 // Treat CDM invocations like JavaScript.
243 if (plugin.name == ASCIIToUTF16(kWidevineCdmDisplayName)) {
244 DCHECK(plugin.type == WebPluginInfo::PLUGIN_TYPE_PEPPER_OUT_OF_PROCESS);
245 return true;
247 #endif // defined(WIDEVINE_CDM_AVAILABLE) && defined(ENABLE_PEPPER_CDMS)
249 return false;
251 #endif // defined(ENABLE_PLUGINS)
253 #if defined(ENABLE_SPELLCHECK)
254 class SpellCheckReplacer : public content::RenderViewVisitor {
255 public:
256 explicit SpellCheckReplacer(SpellCheck* spellcheck)
257 : spellcheck_(spellcheck) {}
258 bool Visit(content::RenderView* render_view) override;
260 private:
261 SpellCheck* spellcheck_; // New shared spellcheck for all views. Weak Ptr.
262 DISALLOW_COPY_AND_ASSIGN(SpellCheckReplacer);
265 bool SpellCheckReplacer::Visit(content::RenderView* render_view) {
266 SpellCheckProvider* provider = SpellCheckProvider::Get(render_view);
267 DCHECK(provider);
268 provider->set_spellcheck(spellcheck_);
269 return true;
271 #endif
273 #if defined(ENABLE_EXTENSIONS)
274 void IsGuestViewApiAvailableToScriptContext(
275 bool* api_is_available,
276 extensions::ScriptContext* context) {
277 if (context->GetAvailability("guestViewInternal").is_available()) {
278 *api_is_available = true;
281 #endif
283 #if defined(ENABLE_PLUGINS)
284 // Presence of the poster param within plugin object tags.
285 // These numeric values are used in UMA logs; do not change them.
286 enum PosterParamPresence {
287 POSTER_PRESENCE_NO_PARAM_PPS_DISABLED = 0,
288 POSTER_PRESENCE_NO_PARAM_PPS_ENABLED = 1,
289 POSTER_PRESENCE_PARAM_EXISTS_PPS_DISABLED = 2,
290 POSTER_PRESENCE_PARAM_EXISTS_PPS_ENABLED = 3,
291 POSTER_PRESENCE_NUM_ITEMS
294 const char kPluginPowerSaverPosterParamPresenceHistogram[] =
295 "Plugin.PowerSaver.PosterParamPresence";
297 void RecordPosterParamPresence(PosterParamPresence presence) {
298 UMA_HISTOGRAM_ENUMERATION(kPluginPowerSaverPosterParamPresenceHistogram,
299 presence, POSTER_PRESENCE_NUM_ITEMS);
302 void TrackPosterParamPresence(const blink::WebPluginParams& params,
303 bool power_saver_enabled) {
304 DCHECK_EQ(params.attributeNames.size(), params.attributeValues.size());
306 for (size_t i = 0; i < params.attributeNames.size(); ++i) {
307 if (params.attributeNames[i].utf8() == "poster") {
308 if (power_saver_enabled)
309 RecordPosterParamPresence(POSTER_PRESENCE_PARAM_EXISTS_PPS_ENABLED);
310 else
311 RecordPosterParamPresence(POSTER_PRESENCE_PARAM_EXISTS_PPS_DISABLED);
313 return;
317 if (power_saver_enabled)
318 RecordPosterParamPresence(POSTER_PRESENCE_NO_PARAM_PPS_ENABLED);
319 else
320 RecordPosterParamPresence(POSTER_PRESENCE_NO_PARAM_PPS_DISABLED);
323 std::string GetPluginInstancePosterAttribute(
324 const blink::WebPluginParams& params) {
325 DCHECK_EQ(params.attributeNames.size(), params.attributeValues.size());
327 for (size_t i = 0; i < params.attributeNames.size(); ++i) {
328 if (params.attributeNames[i].utf8() == "poster" &&
329 !params.attributeValues[i].isEmpty()) {
330 return params.attributeValues[i].utf8();
333 return std::string();
335 #endif
337 #if defined(ENABLE_EXTENSIONS)
338 bool IsStandaloneExtensionProcess() {
339 return base::CommandLine::ForCurrentProcess()->HasSwitch(
340 extensions::switches::kExtensionProcess);
342 #endif
344 // Defers media player loading in background pages until they're visible.
345 // TODO(dalecurtis): Include an idle listener too. http://crbug.com/509135
346 class MediaLoadDeferrer : public content::RenderFrameObserver {
347 public:
348 MediaLoadDeferrer(content::RenderFrame* render_frame,
349 const base::Closure& continue_loading_cb)
350 : content::RenderFrameObserver(render_frame),
351 continue_loading_cb_(continue_loading_cb) {}
352 ~MediaLoadDeferrer() override {}
354 private:
355 // content::RenderFrameObserver implementation:
356 void WasShown() override {
357 continue_loading_cb_.Run();
358 delete this;
361 const base::Closure continue_loading_cb_;
363 DISALLOW_COPY_AND_ASSIGN(MediaLoadDeferrer);
366 } // namespace
368 ChromeContentRendererClient::ChromeContentRendererClient() {
369 g_current_client = this;
371 #if defined(ENABLE_EXTENSIONS)
372 extensions::ExtensionsClient::Set(
373 extensions::ChromeExtensionsClient::GetInstance());
374 extensions::ExtensionsRendererClient::Set(
375 ChromeExtensionsRendererClient::GetInstance());
376 #endif
377 #if defined(ENABLE_PLUGINS)
378 for (size_t i = 0; i < arraysize(kPredefinedAllowedCameraDeviceOrigins); ++i)
379 allowed_camera_device_origins_.insert(
380 kPredefinedAllowedCameraDeviceOrigins[i]);
381 for (size_t i = 0; i < arraysize(kPredefinedAllowedCompositorOrigins); ++i)
382 allowed_compositor_origins_.insert(kPredefinedAllowedCompositorOrigins[i]);
383 #endif
386 ChromeContentRendererClient::~ChromeContentRendererClient() {
387 g_current_client = NULL;
390 void ChromeContentRendererClient::RenderThreadStarted() {
391 RenderThread* thread = RenderThread::Get();
393 chrome_observer_.reset(new ChromeRenderProcessObserver());
394 web_cache_observer_.reset(new web_cache::WebCacheRenderProcessObserver());
396 #if defined(ENABLE_EXTENSIONS)
397 extension_dispatcher_delegate_.reset(
398 new ChromeExtensionsDispatcherDelegate());
399 // ChromeRenderViewTest::SetUp() creates its own ExtensionDispatcher and
400 // injects it using SetExtensionDispatcher(). Don't overwrite it.
401 if (!extension_dispatcher_) {
402 extension_dispatcher_.reset(
403 new extensions::Dispatcher(extension_dispatcher_delegate_.get()));
405 permissions_policy_delegate_.reset(
406 new extensions::RendererPermissionsPolicyDelegate(
407 extension_dispatcher_.get()));
408 resource_request_policy_.reset(
409 new extensions::ResourceRequestPolicy(extension_dispatcher_.get()));
410 guest_view_container_dispatcher_.reset(
411 new extensions::ExtensionsGuestViewContainerDispatcher());
412 #endif
414 prescient_networking_dispatcher_.reset(
415 new network_hints::PrescientNetworkingDispatcher());
416 #if defined(ENABLE_SPELLCHECK)
417 // ChromeRenderViewTest::SetUp() creates a Spellcheck and injects it using
418 // SetSpellcheck(). Don't overwrite it.
419 if (!spellcheck_) {
420 spellcheck_.reset(new SpellCheck());
421 thread->AddObserver(spellcheck_.get());
423 #endif
424 visited_link_slave_.reset(new visitedlink::VisitedLinkSlave());
425 #if defined(FULL_SAFE_BROWSING)
426 phishing_classifier_.reset(safe_browsing::PhishingClassifierFilter::Create());
427 #endif
428 prerender_dispatcher_.reset(new prerender::PrerenderDispatcher());
429 #if defined(ENABLE_WEBRTC)
430 webrtc_logging_message_filter_ = new WebRtcLoggingMessageFilter(
431 RenderThread::Get()->GetIOMessageLoopProxy());
432 #endif
434 thread->AddObserver(chrome_observer_.get());
435 thread->AddObserver(web_cache_observer_.get());
436 #if defined(ENABLE_EXTENSIONS)
437 thread->AddObserver(extension_dispatcher_.get());
438 thread->AddObserver(guest_view_container_dispatcher_.get());
439 #endif
440 #if defined(FULL_SAFE_BROWSING)
441 thread->AddObserver(phishing_classifier_.get());
442 #endif
443 thread->AddObserver(visited_link_slave_.get());
444 thread->AddObserver(prerender_dispatcher_.get());
445 thread->AddObserver(SearchBouncer::GetInstance());
447 #if defined(ENABLE_WEBRTC)
448 thread->AddFilter(webrtc_logging_message_filter_.get());
449 #endif
450 #if defined(ENABLE_EXTENSIONS)
451 thread->AddFilter(new CastIPCDispatcher(
452 RenderThread::Get()->GetIOMessageLoopProxy()));
453 #endif
455 thread->RegisterExtension(extensions_v8::ExternalExtension::Get());
456 thread->RegisterExtension(extensions_v8::LoadTimesExtension::Get());
458 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
459 if (command_line->HasSwitch(switches::kEnableBenchmarking))
460 thread->RegisterExtension(extensions_v8::BenchmarkingExtension::Get());
461 if (command_line->HasSwitch(switches::kEnableNetBenchmarking))
462 thread->RegisterExtension(extensions_v8::NetBenchmarkingExtension::Get());
463 if (command_line->HasSwitch(switches::kInstantProcess))
464 thread->RegisterExtension(extensions_v8::SearchBoxExtension::Get());
466 // chrome-search: and chrome-distiller: pages should not be accessible by
467 // normal content, and should also be unable to script anything but themselves
468 // (to help limit the damage that a corrupt page could cause).
469 WebString chrome_search_scheme(ASCIIToUTF16(chrome::kChromeSearchScheme));
471 // The Instant process can only display the content but not read it. Other
472 // processes can't display it or read it.
473 if (!command_line->HasSwitch(switches::kInstantProcess))
474 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(chrome_search_scheme);
476 WebString dom_distiller_scheme(
477 ASCIIToUTF16(dom_distiller::kDomDistillerScheme));
478 // TODO(nyquist): Add test to ensure this happens when the flag is set.
479 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(dom_distiller_scheme);
481 #if defined(OS_CHROMEOS)
482 WebString external_file_scheme(ASCIIToUTF16(content::kExternalFileScheme));
483 WebSecurityPolicy::registerURLSchemeAsLocal(external_file_scheme);
484 #endif
486 #if defined(ENABLE_IPC_FUZZER)
487 if (command_line->HasSwitch(switches::kIpcDumpDirectory)) {
488 base::FilePath dump_directory =
489 command_line->GetSwitchValuePath(switches::kIpcDumpDirectory);
490 IPC::ChannelProxy::OutgoingMessageFilter* filter =
491 LoadExternalIPCDumper(dump_directory);
492 thread->GetChannel()->set_outgoing_message_filter(filter);
494 #endif
496 // chrome-search: pages should not be accessible by bookmarklets
497 // or javascript: URLs typed in the omnibox.
498 WebSecurityPolicy::registerURLSchemeAsNotAllowingJavascriptURLs(
499 chrome_search_scheme);
501 // chrome-search: resources shouldn't trigger insecure content warnings. Note
502 // that chrome-extension: and chrome-extension-resource: schemes are taken
503 // care of in extensions::Dispatcher.
504 WebSecurityPolicy::registerURLSchemeAsSecure(chrome_search_scheme);
506 #if defined(ENABLE_PRINT_PREVIEW)
507 pdf_print_client_.reset(new ChromePDFPrintClient());
508 pdf::PepperPDFHost::SetPrintClient(pdf_print_client_.get());
509 #endif
511 std::set<GURL> origins;
512 GetSecureOriginWhitelist(&origins);
513 for (const GURL& origin : origins) {
514 WebSecurityPolicy::addOriginTrustworthyWhiteList(
515 WebSecurityOrigin::create(origin));
519 void ChromeContentRendererClient::RenderFrameCreated(
520 content::RenderFrame* render_frame) {
521 new ChromeRenderFrameObserver(render_frame);
523 bool should_whitelist_for_content_settings =
524 base::CommandLine::ForCurrentProcess()->HasSwitch(
525 switches::kInstantProcess);
526 extensions::Dispatcher* ext_dispatcher = NULL;
527 #if defined(ENABLE_EXTENSIONS)
528 ext_dispatcher = extension_dispatcher_.get();
529 #endif
530 ContentSettingsObserver* content_settings = new ContentSettingsObserver(
531 render_frame, ext_dispatcher, should_whitelist_for_content_settings);
532 if (chrome_observer_.get()) {
533 content_settings->SetContentSettingRules(
534 chrome_observer_->content_setting_rules());
537 #if defined(ENABLE_EXTENSIONS)
538 new extensions::ExtensionsRenderFrameObserver(render_frame);
539 new extensions::ExtensionFrameHelper(render_frame, ext_dispatcher);
540 ext_dispatcher->OnRenderFrameCreated(render_frame);
541 #endif
543 #if defined(ENABLE_PLUGINS)
544 new PepperHelper(render_frame);
545 #endif
547 #if !defined(DISABLE_NACL)
548 new nacl::NaClHelper(render_frame);
549 #endif
551 // TODO(jam): when the frame tree moves into content and parent() works at
552 // RenderFrame construction, simplify this by just checking parent().
553 if (render_frame->GetRenderView()->GetMainRenderFrame() != render_frame) {
554 // Avoid any race conditions from having the browser tell subframes that
555 // they're prerendering.
556 if (prerender::PrerenderHelper::IsPrerendering(
557 render_frame->GetRenderView()->GetMainRenderFrame())) {
558 new prerender::PrerenderHelper(render_frame);
562 if (render_frame->GetRenderView()->GetMainRenderFrame() == render_frame) {
563 // Only attach NetErrorHelper to the main frame, since only the main frame
564 // should get error pages.
565 new NetErrorHelper(render_frame);
568 if (render_frame->GetWebFrame()->parent() == nullptr) {
569 // Only attach MainRenderFrameObserver to the main frame, since
570 // we only want to log page load metrics for the main frame.
571 new page_load_metrics::MetricsRenderFrameObserver(render_frame);
574 PasswordAutofillAgent* password_autofill_agent =
575 new PasswordAutofillAgent(render_frame);
576 PasswordGenerationAgent* password_generation_agent =
577 new PasswordGenerationAgent(render_frame, password_autofill_agent);
578 new AutofillAgent(render_frame, password_autofill_agent,
579 password_generation_agent);
582 void ChromeContentRendererClient::RenderViewCreated(
583 content::RenderView* render_view) {
585 #if defined(ENABLE_EXTENSIONS)
586 new extensions::ExtensionHelper(render_view, extension_dispatcher_.get());
587 #endif
588 new PageLoadHistograms(render_view);
589 #if defined(ENABLE_PRINTING)
590 new printing::PrintWebViewHelper(
591 render_view,
592 scoped_ptr<printing::PrintWebViewHelper::Delegate>(
593 new ChromePrintWebViewHelperDelegate()));
594 #endif
595 #if defined(ENABLE_SPELLCHECK)
596 new SpellCheckProvider(render_view, spellcheck_.get());
597 #endif
598 new prerender::PrerendererClient(render_view);
599 #if defined(FULL_SAFE_BROWSING)
600 safe_browsing::MalwareDOMDetails::Create(render_view);
601 #endif
603 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
604 if (command_line->HasSwitch(switches::kInstantProcess))
605 new SearchBox(render_view);
607 new ChromeRenderViewObserver(render_view, web_cache_observer_.get());
609 new password_manager::CredentialManagerClient(render_view);
613 SkBitmap* ChromeContentRendererClient::GetSadPluginBitmap() {
614 return const_cast<SkBitmap*>(ResourceBundle::GetSharedInstance().
615 GetImageNamed(IDR_SAD_PLUGIN).ToSkBitmap());
618 SkBitmap* ChromeContentRendererClient::GetSadWebViewBitmap() {
619 return const_cast<SkBitmap*>(ResourceBundle::GetSharedInstance().
620 GetImageNamed(IDR_SAD_WEBVIEW).ToSkBitmap());
623 #if defined(ENABLE_EXTENSIONS)
624 const Extension* ChromeContentRendererClient::GetExtensionByOrigin(
625 const WebSecurityOrigin& origin) const {
626 if (!base::EqualsASCII(base::StringPiece16(origin.protocol()),
627 extensions::kExtensionScheme))
628 return NULL;
630 const std::string extension_id = origin.host().utf8().data();
631 return extensions::RendererExtensionRegistry::Get()->GetByID(extension_id);
633 #endif
635 bool ChromeContentRendererClient::OverrideCreatePlugin(
636 content::RenderFrame* render_frame,
637 blink::WebLocalFrame* frame,
638 const WebPluginParams& params,
639 WebPlugin** plugin) {
640 std::string orig_mime_type = params.mimeType.utf8();
641 #if defined(ENABLE_EXTENSIONS)
642 if (orig_mime_type == content::kBrowserPluginMimeType) {
643 bool guest_view_api_available = false;
644 extension_dispatcher_->script_context_set().ForEach(
645 render_frame, base::Bind(&IsGuestViewApiAvailableToScriptContext,
646 &guest_view_api_available));
647 if (guest_view_api_available)
648 return false;
650 #endif
652 GURL url(params.url);
653 #if defined(ENABLE_PLUGINS)
654 ChromeViewHostMsg_GetPluginInfo_Output output;
655 WebString top_origin = frame->top()->securityOrigin().toString();
656 render_frame->Send(new ChromeViewHostMsg_GetPluginInfo(
657 render_frame->GetRoutingID(), url, GURL(top_origin), orig_mime_type,
658 &output));
659 *plugin = CreatePlugin(render_frame, frame, params, output);
660 #else // !defined(ENABLE_PLUGINS)
662 #if defined(OS_ANDROID)
663 if (plugins::MobileYouTubePlugin::IsYouTubeURL(url, orig_mime_type)) {
664 base::StringPiece template_html(
665 ResourceBundle::GetSharedInstance().GetRawDataResource(
666 IDR_MOBILE_YOUTUBE_PLUGIN_HTML));
667 *plugin = (new plugins::MobileYouTubePlugin(render_frame, frame, params,
668 template_html))->plugin();
669 return true;
671 #endif // defined(OS_ANDROID)
673 PluginUMAReporter::GetInstance()->ReportPluginMissing(orig_mime_type, url);
674 *plugin = NonLoadablePluginPlaceholder::CreateNotSupportedPlugin(
675 render_frame, frame, params)->plugin();
677 #endif // defined(ENABLE_PLUGINS)
678 return true;
681 WebPlugin* ChromeContentRendererClient::CreatePluginReplacement(
682 content::RenderFrame* render_frame,
683 const base::FilePath& plugin_path) {
684 return NonLoadablePluginPlaceholder::CreateErrorPlugin(render_frame,
685 plugin_path)->plugin();
688 void ChromeContentRendererClient::DeferMediaLoad(
689 content::RenderFrame* render_frame,
690 bool has_played_media_before,
691 const base::Closure& closure) {
692 // Don't allow autoplay/autoload of media resources in a RenderFrame that is
693 // hidden and has never played any media before. We want to allow future
694 // loads even when hidden to allow playlist-like functionality.
696 // NOTE: This is also used to defer media loading for prerender.
698 // TODO(dalecurtis): Include an idle check too. http://crbug.com/509135
699 if (render_frame->IsHidden() && !has_played_media_before) {
700 // Lifetime is tied to |render_frame| via content::RenderFrameObserver.
701 new MediaLoadDeferrer(render_frame, closure);
702 return;
705 closure.Run();
708 #if defined(ENABLE_PLUGINS)
709 WebPlugin* ChromeContentRendererClient::CreatePlugin(
710 content::RenderFrame* render_frame,
711 blink::WebLocalFrame* frame,
712 const WebPluginParams& original_params,
713 const ChromeViewHostMsg_GetPluginInfo_Output& output) {
714 const WebPluginInfo& info = output.plugin;
715 const std::string& actual_mime_type = output.actual_mime_type;
716 const base::string16& group_name = output.group_name;
717 const std::string& identifier = output.group_identifier;
718 ChromeViewHostMsg_GetPluginInfo_Status status = output.status;
719 GURL url(original_params.url);
720 std::string orig_mime_type = original_params.mimeType.utf8();
721 ChromePluginPlaceholder* placeholder = NULL;
723 // If the browser plugin is to be enabled, this should be handled by the
724 // renderer, so the code won't reach here due to the early exit in
725 // OverrideCreatePlugin.
726 if (status == ChromeViewHostMsg_GetPluginInfo_Status::kNotFound ||
727 orig_mime_type == content::kBrowserPluginMimeType) {
728 PluginUMAReporter::GetInstance()->ReportPluginMissing(orig_mime_type, url);
729 placeholder = ChromePluginPlaceholder::CreateLoadableMissingPlugin(
730 render_frame, frame, original_params);
731 } else {
732 // TODO(bauerb): This should be in content/.
733 WebPluginParams params(original_params);
734 for (size_t i = 0; i < info.mime_types.size(); ++i) {
735 if (info.mime_types[i].mime_type == actual_mime_type) {
736 AppendParams(info.mime_types[i].additional_param_names,
737 info.mime_types[i].additional_param_values,
738 &params.attributeNames, &params.attributeValues);
739 break;
742 if (params.mimeType.isNull() && (actual_mime_type.size() > 0)) {
743 // Webkit might say that mime type is null while we already know the
744 // actual mime type via ChromeViewHostMsg_GetPluginInfo. In that case
745 // we should use what we know since WebpluginDelegateProxy does some
746 // specific initializations based on this information.
747 params.mimeType = WebString::fromUTF8(actual_mime_type.c_str());
750 ContentSettingsObserver* observer =
751 ContentSettingsObserver::Get(render_frame);
753 const ContentSettingsType content_type =
754 ShouldUseJavaScriptSettingForPlugin(info)
755 ? CONTENT_SETTINGS_TYPE_JAVASCRIPT
756 : CONTENT_SETTINGS_TYPE_PLUGINS;
758 if ((status == ChromeViewHostMsg_GetPluginInfo_Status::kUnauthorized ||
759 status == ChromeViewHostMsg_GetPluginInfo_Status::kBlocked) &&
760 observer->IsPluginTemporarilyAllowed(identifier)) {
761 status = ChromeViewHostMsg_GetPluginInfo_Status::kAllowed;
764 #if defined(OS_WIN)
765 // In Windows we need to check if we can load NPAPI plugins.
766 // For example, if the render view is in the Ash desktop, we should not.
767 // If user is on ALLOW or DETECT setting, loading needs to be blocked here.
768 if ((status == ChromeViewHostMsg_GetPluginInfo_Status::kAllowed ||
769 status ==
770 ChromeViewHostMsg_GetPluginInfo_Status::kPlayImportantContent) &&
771 info.type == content::WebPluginInfo::PLUGIN_TYPE_NPAPI) {
772 if (observer->AreNPAPIPluginsBlocked())
773 status = ChromeViewHostMsg_GetPluginInfo_Status::kNPAPINotSupported;
775 #endif
777 auto create_blocked_plugin =
778 [&render_frame, &frame, &params, &info, &identifier, &group_name](
779 int template_id, const base::string16& message) {
780 return ChromePluginPlaceholder::CreateBlockedPlugin(
781 render_frame, frame, params, info, identifier, group_name,
782 template_id, message, PlaceholderPosterInfo());
784 switch (status) {
785 case ChromeViewHostMsg_GetPluginInfo_Status::kNotFound: {
786 NOTREACHED();
787 break;
789 case ChromeViewHostMsg_GetPluginInfo_Status::kAllowed:
790 case ChromeViewHostMsg_GetPluginInfo_Status::kPlayImportantContent: {
791 #if !defined(DISABLE_NACL) && defined(ENABLE_EXTENSIONS)
792 const bool is_nacl_plugin =
793 info.name == ASCIIToUTF16(nacl::kNaClPluginName);
794 const bool is_nacl_mime_type =
795 actual_mime_type == nacl::kNaClPluginMimeType;
796 const bool is_pnacl_mime_type =
797 actual_mime_type == nacl::kPnaclPluginMimeType;
798 if (is_nacl_plugin || is_nacl_mime_type || is_pnacl_mime_type) {
799 bool is_nacl_unrestricted = false;
800 if (is_nacl_mime_type) {
801 is_nacl_unrestricted =
802 base::CommandLine::ForCurrentProcess()->HasSwitch(
803 switches::kEnableNaCl);
804 } else if (is_pnacl_mime_type) {
805 is_nacl_unrestricted = true;
807 GURL manifest_url;
808 GURL app_url;
809 if (is_nacl_mime_type || is_pnacl_mime_type) {
810 // Normal NaCl/PNaCl embed. The app URL is the page URL.
811 manifest_url = url;
812 app_url = frame->top()->document().url();
813 } else {
814 // NaCl is being invoked as a content handler. Look up the NaCl
815 // module using the MIME type. The app URL is the manifest URL.
816 manifest_url = GetNaClContentHandlerURL(actual_mime_type, info);
817 app_url = manifest_url;
819 const Extension* extension =
820 extensions::RendererExtensionRegistry::Get()
821 ->GetExtensionOrAppByURL(manifest_url);
822 if (!IsNaClAllowed(manifest_url,
823 app_url,
824 is_nacl_unrestricted,
825 extension,
826 &params)) {
827 WebString error_message;
828 if (is_nacl_mime_type) {
829 error_message =
830 "Only unpacked extensions and apps installed from the Chrome "
831 "Web Store can load NaCl modules without enabling Native "
832 "Client in about:flags.";
833 } else if (is_pnacl_mime_type) {
834 error_message =
835 "Portable Native Client must not be disabled in about:flags.";
837 frame->addMessageToConsole(
838 WebConsoleMessage(WebConsoleMessage::LevelError,
839 error_message));
840 placeholder = create_blocked_plugin(
841 IDR_BLOCKED_PLUGIN_HTML,
842 #if defined(OS_CHROMEOS)
843 l10n_util::GetStringUTF16(IDS_NACL_PLUGIN_BLOCKED));
844 #else
845 l10n_util::GetStringFUTF16(IDS_PLUGIN_BLOCKED, group_name));
846 #endif
847 break;
850 #endif // !defined(DISABLE_NACL) && defined(ENABLE_EXTENSIONS)
852 // Delay loading plugins if prerendering.
853 // TODO(mmenke): In the case of prerendering, feed into
854 // ChromeContentRendererClient::CreatePlugin instead, to
855 // reduce the chance of future regressions.
856 bool is_prerendering =
857 prerender::PrerenderHelper::IsPrerendering(render_frame);
858 bool power_saver_enabled =
859 status ==
860 ChromeViewHostMsg_GetPluginInfo_Status::kPlayImportantContent;
861 bool blocked_for_background_tab =
862 render_frame->IsHidden() && power_saver_enabled;
864 if (info.name == ASCIIToUTF16(content::kFlashPluginName))
865 TrackPosterParamPresence(params, power_saver_enabled);
867 PlaceholderPosterInfo poster_info;
868 if (power_saver_enabled) {
869 poster_info.poster_attribute =
870 GetPluginInstancePosterAttribute(params);
871 poster_info.base_url = frame->document().url();
874 if (blocked_for_background_tab || is_prerendering ||
875 !poster_info.poster_attribute.empty()) {
876 placeholder = ChromePluginPlaceholder::CreateBlockedPlugin(
877 render_frame, frame, params, info, identifier, group_name,
878 poster_info.poster_attribute.empty() ? IDR_BLOCKED_PLUGIN_HTML
879 : IDR_PLUGIN_POSTER_HTML,
880 l10n_util::GetStringFUTF16(IDS_PLUGIN_BLOCKED, group_name),
881 poster_info);
882 placeholder->set_blocked_for_background_tab(
883 blocked_for_background_tab);
884 placeholder->set_blocked_for_prerendering(is_prerendering);
885 placeholder->set_power_saver_enabled(power_saver_enabled);
886 placeholder->AllowLoading();
887 break;
890 scoped_ptr<content::PluginInstanceThrottler> throttler;
891 if (power_saver_enabled) {
892 throttler = PluginInstanceThrottler::Create();
893 // PluginPreroller manages its own lifetime.
894 new PluginPreroller(
895 render_frame, frame, params, info, identifier, group_name,
896 l10n_util::GetStringFUTF16(IDS_PLUGIN_BLOCKED, group_name),
897 throttler.get());
900 return render_frame->CreatePlugin(frame, info, params,
901 throttler.Pass());
903 case ChromeViewHostMsg_GetPluginInfo_Status::kNPAPINotSupported: {
904 RenderThread::Get()->RecordAction(
905 UserMetricsAction("Plugin_NPAPINotSupported"));
906 placeholder = create_blocked_plugin(
907 IDR_BLOCKED_PLUGIN_HTML,
908 l10n_util::GetStringUTF16(IDS_PLUGIN_NOT_SUPPORTED_METRO));
909 render_frame->Send(new ChromeViewHostMsg_NPAPINotSupported(
910 render_frame->GetRoutingID(), identifier));
911 break;
913 case ChromeViewHostMsg_GetPluginInfo_Status::kDisabled: {
914 PluginUMAReporter::GetInstance()->ReportPluginDisabled(orig_mime_type,
915 url);
916 placeholder = create_blocked_plugin(
917 IDR_DISABLED_PLUGIN_HTML,
918 l10n_util::GetStringFUTF16(IDS_PLUGIN_DISABLED, group_name));
919 break;
921 case ChromeViewHostMsg_GetPluginInfo_Status::kOutdatedBlocked: {
922 #if defined(ENABLE_PLUGIN_INSTALLATION)
923 placeholder = create_blocked_plugin(
924 IDR_BLOCKED_PLUGIN_HTML,
925 l10n_util::GetStringFUTF16(IDS_PLUGIN_OUTDATED, group_name));
926 placeholder->AllowLoading();
927 render_frame->Send(new ChromeViewHostMsg_BlockedOutdatedPlugin(
928 render_frame->GetRoutingID(), placeholder->CreateRoutingId(),
929 identifier));
930 #else
931 NOTREACHED();
932 #endif
933 break;
935 case ChromeViewHostMsg_GetPluginInfo_Status::kOutdatedDisallowed: {
936 placeholder = create_blocked_plugin(
937 IDR_BLOCKED_PLUGIN_HTML,
938 l10n_util::GetStringFUTF16(IDS_PLUGIN_OUTDATED, group_name));
939 break;
941 case ChromeViewHostMsg_GetPluginInfo_Status::kUnauthorized: {
942 placeholder = create_blocked_plugin(
943 IDR_BLOCKED_PLUGIN_HTML,
944 l10n_util::GetStringFUTF16(IDS_PLUGIN_NOT_AUTHORIZED, group_name));
945 placeholder->AllowLoading();
946 if (info.type != content::WebPluginInfo::PLUGIN_TYPE_NPAPI) {
947 render_frame->Send(new ChromeViewHostMsg_BlockedUnauthorizedPlugin(
948 render_frame->GetRoutingID(),
949 group_name,
950 identifier));
952 observer->DidBlockContentType(content_type, group_name);
953 break;
955 case ChromeViewHostMsg_GetPluginInfo_Status::kBlocked: {
956 placeholder = create_blocked_plugin(
957 IDR_BLOCKED_PLUGIN_HTML,
958 l10n_util::GetStringFUTF16(IDS_PLUGIN_BLOCKED, group_name));
959 placeholder->AllowLoading();
960 RenderThread::Get()->RecordAction(UserMetricsAction("Plugin_Blocked"));
961 observer->DidBlockContentType(content_type, group_name);
962 break;
964 case ChromeViewHostMsg_GetPluginInfo_Status::kBlockedByPolicy: {
965 placeholder = create_blocked_plugin(
966 IDR_BLOCKED_PLUGIN_HTML,
967 l10n_util::GetStringFUTF16(IDS_PLUGIN_BLOCKED_BY_POLICY,
968 group_name));
969 RenderThread::Get()->RecordAction(
970 UserMetricsAction("Plugin_BlockedByPolicy"));
971 observer->DidBlockContentType(content_type, group_name);
972 break;
976 placeholder->SetStatus(status);
977 return placeholder->plugin();
979 #endif // defined(ENABLE_PLUGINS)
981 // For NaCl content handling plugins, the NaCl manifest is stored in an
982 // additonal 'nacl' param associated with the MIME type.
983 // static
984 GURL ChromeContentRendererClient::GetNaClContentHandlerURL(
985 const std::string& actual_mime_type,
986 const content::WebPluginInfo& plugin) {
987 // Look for the manifest URL among the MIME type's additonal parameters.
988 const char kNaClPluginManifestAttribute[] = "nacl";
989 base::string16 nacl_attr = ASCIIToUTF16(kNaClPluginManifestAttribute);
990 for (size_t i = 0; i < plugin.mime_types.size(); ++i) {
991 if (plugin.mime_types[i].mime_type == actual_mime_type) {
992 const content::WebPluginMimeType& content_type = plugin.mime_types[i];
993 for (size_t i = 0; i < content_type.additional_param_names.size(); ++i) {
994 if (content_type.additional_param_names[i] == nacl_attr)
995 return GURL(content_type.additional_param_values[i]);
997 break;
1000 return GURL();
1003 #if !defined(DISABLE_NACL)
1004 // static
1005 bool ChromeContentRendererClient::IsNaClAllowed(
1006 const GURL& manifest_url,
1007 const GURL& app_url,
1008 bool is_nacl_unrestricted,
1009 const Extension* extension,
1010 WebPluginParams* params) {
1011 // Temporarily allow these whitelisted apps and WebUIs to use NaCl.
1012 std::string app_url_host = app_url.host();
1013 std::string manifest_url_path = manifest_url.path();
1015 bool is_whitelisted_web_ui =
1016 app_url.spec() == chrome::kChromeUIAppListStartPageURL;
1018 bool is_photo_app =
1019 // Whitelisted apps must be served over https.
1020 app_url.SchemeIsCryptographic() && manifest_url.SchemeIsCryptographic() &&
1021 (base::EndsWith(app_url_host, "plus.google.com",
1022 base::CompareCase::INSENSITIVE_ASCII) ||
1023 base::EndsWith(app_url_host, "plus.sandbox.google.com",
1024 base::CompareCase::INSENSITIVE_ASCII)) &&
1025 manifest_url.DomainIs("ssl.gstatic.com") &&
1026 (manifest_url_path.find("s2/oz/nacl/") == 1 ||
1027 manifest_url_path.find("photos/nacl/") == 1);
1029 std::string manifest_fs_host;
1030 if (manifest_url.SchemeIsFileSystem() && manifest_url.inner_url()) {
1031 manifest_fs_host = manifest_url.inner_url()->host();
1033 bool is_hangouts_app =
1034 // Whitelisted apps must be served over secure scheme.
1035 app_url.SchemeIsCryptographic() && manifest_url.SchemeIsFileSystem() &&
1036 manifest_url.inner_url()->SchemeIsCryptographic() &&
1037 (base::EndsWith(app_url_host, "talkgadget.google.com",
1038 base::CompareCase::INSENSITIVE_ASCII) ||
1039 base::EndsWith(app_url_host, "plus.google.com",
1040 base::CompareCase::INSENSITIVE_ASCII) ||
1041 base::EndsWith(app_url_host, "plus.sandbox.google.com",
1042 base::CompareCase::INSENSITIVE_ASCII)) &&
1043 // The manifest must be loaded from the host's FileSystem.
1044 (manifest_fs_host == app_url_host);
1046 bool is_whitelisted_app = is_photo_app || is_hangouts_app;
1048 bool is_invoked_by_webstore_installed_extension = false;
1049 bool is_extension_unrestricted = false;
1050 bool is_extension_force_installed = false;
1051 #if defined(ENABLE_EXTENSIONS)
1052 bool is_extension_from_webstore = extension && extension->from_webstore();
1054 bool is_invoked_by_extension = app_url.SchemeIs("chrome-extension");
1055 bool is_invoked_by_hosted_app = extension &&
1056 extension->is_hosted_app() &&
1057 extension->web_extent().MatchesURL(app_url);
1059 is_invoked_by_webstore_installed_extension = is_extension_from_webstore &&
1060 (is_invoked_by_extension || is_invoked_by_hosted_app);
1062 // Allow built-in extensions and developer mode extensions.
1063 is_extension_unrestricted = extension &&
1064 (extensions::Manifest::IsUnpackedLocation(extension->location()) ||
1065 extensions::Manifest::IsComponentLocation(extension->location()));
1066 // Allow extensions force installed by admin policy.
1067 is_extension_force_installed = extension &&
1068 extensions::Manifest::IsPolicyLocation(extension->location());
1069 #endif // defined(ENABLE_EXTENSIONS)
1071 // Allow NaCl under any of the following circumstances:
1072 // 1) An app or URL is explictly whitelisted above.
1073 // 2) An extension is loaded unpacked or built-in (component) to Chrome.
1074 // 3) An extension is force installed by policy.
1075 // 4) An extension is installed from the webstore, and invoked in that
1076 // context (hosted app URL or chrome-extension:// scheme).
1077 // 5) --enable-nacl is set.
1078 bool is_nacl_allowed_by_location =
1079 is_whitelisted_web_ui ||
1080 is_whitelisted_app ||
1081 is_extension_unrestricted ||
1082 is_extension_force_installed ||
1083 is_invoked_by_webstore_installed_extension;
1084 bool is_nacl_allowed = is_nacl_allowed_by_location || is_nacl_unrestricted;
1085 if (is_nacl_allowed) {
1086 // Make sure that PPAPI 'dev' interfaces are only available for unpacked
1087 // and component extensions. Also allow dev interfaces when --enable-nacl
1088 // is set, but do not allow --enable-nacl to provide dev interfaces to
1089 // webstore installed and other normally allowed URLs.
1090 WebString dev_attribute = WebString::fromUTF8("@dev");
1091 if (is_extension_unrestricted ||
1092 (is_nacl_unrestricted && !is_nacl_allowed_by_location)) {
1093 // Add the special '@dev' attribute.
1094 std::vector<base::string16> param_names;
1095 std::vector<base::string16> param_values;
1096 param_names.push_back(dev_attribute);
1097 param_values.push_back(WebString());
1098 AppendParams(
1099 param_names,
1100 param_values,
1101 &params->attributeNames,
1102 &params->attributeValues);
1103 } else {
1104 // If the params somehow contain '@dev', remove it.
1105 size_t attribute_count = params->attributeNames.size();
1106 for (size_t i = 0; i < attribute_count; ++i) {
1107 if (params->attributeNames[i].equals(dev_attribute))
1108 params->attributeNames[i] = WebString();
1112 return is_nacl_allowed;
1114 #endif // defined(DISABLE_NACL)
1116 bool ChromeContentRendererClient::HasErrorPage(int http_status_code,
1117 std::string* error_domain) {
1118 // Use an internal error page, if we have one for the status code.
1119 if (!LocalizedError::HasStrings(LocalizedError::kHttpErrorDomain,
1120 http_status_code)) {
1121 return false;
1124 *error_domain = LocalizedError::kHttpErrorDomain;
1125 return true;
1128 bool ChromeContentRendererClient::ShouldSuppressErrorPage(
1129 content::RenderFrame* render_frame,
1130 const GURL& url) {
1131 // Unit tests for ChromeContentRendererClient pass a NULL RenderFrame here.
1132 // Unfortunately it's very difficult to construct a mock RenderView, so skip
1133 // this functionality in this case.
1134 if (render_frame) {
1135 content::RenderView* render_view = render_frame->GetRenderView();
1136 content::RenderFrame* main_render_frame = render_view->GetMainRenderFrame();
1137 blink::WebFrame* web_frame = render_frame->GetWebFrame();
1138 NetErrorHelper* net_error_helper = NetErrorHelper::Get(main_render_frame);
1139 if (net_error_helper->ShouldSuppressErrorPage(web_frame, url))
1140 return true;
1142 // Do not flash an error page if the Instant new tab page fails to load.
1143 return SearchBouncer::GetInstance()->IsNewTabPage(url);
1146 void ChromeContentRendererClient::GetNavigationErrorStrings(
1147 content::RenderView* render_view,
1148 blink::WebFrame* frame,
1149 const blink::WebURLRequest& failed_request,
1150 const blink::WebURLError& error,
1151 std::string* error_html,
1152 base::string16* error_description) {
1153 const GURL failed_url = error.unreachableURL;
1155 bool is_post = base::EqualsASCII(
1156 base::StringPiece16(failed_request.httpMethod()), "POST");
1158 if (error_html) {
1159 // TODO(ellyjones): change GetNavigationErrorStrings to take a RenderFrame
1160 // instead of a RenderView, then pass that in.
1161 // This is safe for now because we only install the NetErrorHelper on the
1162 // main render frame anyway; see the TODO(ellyjones) in
1163 // RenderFrameCreated.
1164 content::RenderFrame* main_render_frame = render_view->GetMainRenderFrame();
1165 NetErrorHelper* helper = NetErrorHelper::Get(main_render_frame);
1166 helper->GetErrorHTML(frame, error, is_post, error_html);
1169 if (error_description)
1170 *error_description = LocalizedError::GetErrorDetails(error, is_post);
1173 bool ChromeContentRendererClient::RunIdleHandlerWhenWidgetsHidden() {
1174 #if defined(ENABLE_EXTENSIONS)
1175 return !IsStandaloneExtensionProcess();
1176 #else
1177 return true;
1178 #endif
1181 bool ChromeContentRendererClient::
1182 AllowTimerSuspensionWhenProcessBackgrounded() {
1183 #if defined(OS_ANDROID)
1184 return true;
1185 #else
1186 return false;
1187 #endif
1190 bool ChromeContentRendererClient::AllowPopup() {
1191 #if defined(ENABLE_EXTENSIONS)
1192 extensions::ScriptContext* current_context =
1193 extension_dispatcher_->script_context_set().GetCurrent();
1194 if (!current_context || !current_context->extension())
1195 return false;
1196 // See http://crbug.com/117446 for the subtlety of this check.
1197 switch (current_context->context_type()) {
1198 case extensions::Feature::UNSPECIFIED_CONTEXT:
1199 case extensions::Feature::WEB_PAGE_CONTEXT:
1200 case extensions::Feature::UNBLESSED_EXTENSION_CONTEXT:
1201 case extensions::Feature::WEBUI_CONTEXT:
1202 case extensions::Feature::SERVICE_WORKER_CONTEXT:
1203 return false;
1204 case extensions::Feature::BLESSED_EXTENSION_CONTEXT:
1205 case extensions::Feature::CONTENT_SCRIPT_CONTEXT:
1206 return true;
1207 case extensions::Feature::BLESSED_WEB_PAGE_CONTEXT:
1208 return !current_context->web_frame()->parent();
1210 NOTREACHED();
1211 #endif
1212 return false;
1215 bool ChromeContentRendererClient::ShouldFork(blink::WebLocalFrame* frame,
1216 const GURL& url,
1217 const std::string& http_method,
1218 bool is_initial_navigation,
1219 bool is_server_redirect,
1220 bool* send_referrer) {
1221 DCHECK(!frame->parent());
1223 // If this is the Instant process, fork all navigations originating from the
1224 // renderer. The destination page will then be bucketed back to this Instant
1225 // process if it is an Instant url, or to another process if not. Conversely,
1226 // fork if this is a non-Instant process navigating to an Instant url, so that
1227 // such navigations can also be bucketed into an Instant renderer.
1228 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1229 switches::kInstantProcess) ||
1230 SearchBouncer::GetInstance()->ShouldFork(url)) {
1231 *send_referrer = true;
1232 return true;
1235 // For now, we skip the rest for POST submissions. This is because
1236 // http://crbug.com/101395 is more likely to cause compatibility issues
1237 // with hosted apps and extensions than WebUI pages. We will remove this
1238 // check when cross-process POST submissions are supported.
1239 if (http_method != "GET")
1240 return false;
1242 // If |url| matches one of the prerendered URLs, stop this navigation and try
1243 // to swap in the prerendered page on the browser process. If the prerendered
1244 // page no longer exists by the time the OpenURL IPC is handled, a normal
1245 // navigation is attempted.
1246 if (prerender_dispatcher_.get() &&
1247 prerender_dispatcher_->IsPrerenderURL(url)) {
1248 *send_referrer = true;
1249 return true;
1252 #if defined(ENABLE_EXTENSIONS)
1253 const extensions::RendererExtensionRegistry* extension_registry =
1254 extensions::RendererExtensionRegistry::Get();
1256 // Determine if the new URL is an extension (excluding bookmark apps).
1257 const Extension* new_url_extension = extensions::GetNonBookmarkAppExtension(
1258 *extension_registry->GetMainThreadExtensionSet(), url);
1259 bool is_extension_url = !!new_url_extension;
1261 // If the navigation would cross an app extent boundary, we also need
1262 // to defer to the browser to ensure process isolation. This is not necessary
1263 // for server redirects, which will be transferred to a new process by the
1264 // browser process when they are ready to commit. It is necessary for client
1265 // redirects, which won't be transferred in the same way.
1266 if (!is_server_redirect &&
1267 CrossesExtensionExtents(frame, url, is_extension_url,
1268 is_initial_navigation)) {
1269 // Include the referrer in this case since we're going from a hosted web
1270 // page. (the packaged case is handled previously by the extension
1271 // navigation test)
1272 *send_referrer = true;
1274 const Extension* extension =
1275 extension_registry->GetExtensionOrAppByURL(url);
1276 if (extension && extension->is_app()) {
1277 extensions::RecordAppLaunchType(
1278 extension_misc::APP_LAUNCH_CONTENT_NAVIGATION, extension->GetType());
1280 return true;
1283 // If this is a reload, check whether it has the wrong process type. We
1284 // should send it to the browser if it's an extension URL (e.g., hosted app)
1285 // in a normal process, or if it's a process for an extension that has been
1286 // uninstalled. Without --site-per-process mode, we never fork processes for
1287 // subframes, so this check only makes sense for top-level frames.
1288 // TODO(alexmos,nasko): Figure out how this check should work when reloading
1289 // subframes in --site-per-process mode.
1290 if (!frame->parent() && frame->document().url() == url) {
1291 if (is_extension_url != IsStandaloneExtensionProcess())
1292 return true;
1294 #endif // defined(ENABLE_EXTENSIONS)
1296 return false;
1299 bool ChromeContentRendererClient::WillSendRequest(
1300 blink::WebFrame* frame,
1301 ui::PageTransition transition_type,
1302 const GURL& url,
1303 const GURL& first_party_for_cookies,
1304 GURL* new_url) {
1305 // Check whether the request should be allowed. If not allowed, we reset the
1306 // URL to something invalid to prevent the request and cause an error.
1307 #if defined(ENABLE_EXTENSIONS)
1308 if (url.SchemeIs(extensions::kExtensionScheme) &&
1309 !resource_request_policy_->CanRequestResource(url, frame,
1310 transition_type)) {
1311 *new_url = GURL(chrome::kExtensionInvalidRequestURL);
1312 return true;
1315 if (url.SchemeIs(extensions::kExtensionResourceScheme) &&
1316 !resource_request_policy_->CanRequestExtensionResourceScheme(url,
1317 frame)) {
1318 *new_url = GURL(chrome::kExtensionResourceInvalidRequestURL);
1319 return true;
1321 #endif
1323 const content::RenderView* render_view =
1324 content::RenderView::FromWebView(frame->view());
1325 SearchBox* search_box = SearchBox::Get(render_view);
1326 if (search_box && url.SchemeIs(chrome::kChromeSearchScheme)) {
1327 SearchBox::ImageSourceType type = SearchBox::NONE;
1328 if (url.host() == chrome::kChromeUIFaviconHost)
1329 type = SearchBox::FAVICON;
1330 else if (url.host() == chrome::kChromeUILargeIconHost)
1331 type = SearchBox::LARGE_ICON;
1332 else if (url.host() == chrome::kChromeUIFallbackIconHost)
1333 type = SearchBox::FALLBACK_ICON;
1334 else if (url.host() == chrome::kChromeUIThumbnailHost)
1335 type = SearchBox::THUMB;
1336 if (type != SearchBox::NONE)
1337 return search_box->GenerateImageURLFromTransientURL(url, type, new_url);
1340 return false;
1343 unsigned long long ChromeContentRendererClient::VisitedLinkHash(
1344 const char* canonical_url, size_t length) {
1345 return visited_link_slave_->ComputeURLFingerprint(canonical_url, length);
1348 bool ChromeContentRendererClient::IsLinkVisited(unsigned long long link_hash) {
1349 return visited_link_slave_->IsVisited(link_hash);
1352 blink::WebPrescientNetworking*
1353 ChromeContentRendererClient::GetPrescientNetworking() {
1354 return prescient_networking_dispatcher_.get();
1357 bool ChromeContentRendererClient::ShouldOverridePageVisibilityState(
1358 const content::RenderFrame* render_frame,
1359 blink::WebPageVisibilityState* override_state) {
1360 if (!prerender::PrerenderHelper::IsPrerendering(render_frame))
1361 return false;
1363 *override_state = blink::WebPageVisibilityStatePrerender;
1364 return true;
1367 #if defined(ENABLE_EXTENSIONS)
1368 void ChromeContentRendererClient::SetExtensionDispatcherForTest(
1369 extensions::Dispatcher* extension_dispatcher) {
1370 extension_dispatcher_.reset(extension_dispatcher);
1371 permissions_policy_delegate_.reset(
1372 new extensions::RendererPermissionsPolicyDelegate(
1373 extension_dispatcher_.get()));
1374 RenderThread::Get()->RegisterExtension(
1375 extensions::SafeBuiltins::CreateV8Extension());
1378 extensions::Dispatcher*
1379 ChromeContentRendererClient::GetExtensionDispatcherForTest() {
1380 return extension_dispatcher_.get();
1383 bool ChromeContentRendererClient::CrossesExtensionExtents(
1384 blink::WebLocalFrame* frame,
1385 const GURL& new_url,
1386 bool is_extension_url,
1387 bool is_initial_navigation) {
1388 DCHECK(!frame->parent());
1389 GURL old_url(frame->document().url());
1391 extensions::RendererExtensionRegistry* extension_registry =
1392 extensions::RendererExtensionRegistry::Get();
1394 // If old_url is still empty and this is an initial navigation, then this is
1395 // a window.open operation. We should look at the opener URL. Note that the
1396 // opener is a local frame in this case.
1397 if (is_initial_navigation && old_url.is_empty() && frame->opener()) {
1398 WebLocalFrame* opener_frame = frame->opener()->toWebLocalFrame();
1400 // If we're about to open a normal web page from a same-origin opener stuck
1401 // in an extension process, we want to keep it in process to allow the
1402 // opener to script it.
1403 WebDocument opener_document = opener_frame->document();
1404 WebSecurityOrigin opener_origin = opener_document.securityOrigin();
1405 bool opener_is_extension_url = !opener_origin.isUnique() &&
1406 extension_registry->GetExtensionOrAppByURL(
1407 opener_document.url()) != NULL;
1408 if (!is_extension_url &&
1409 !opener_is_extension_url &&
1410 IsStandaloneExtensionProcess() &&
1411 opener_origin.canRequest(WebURL(new_url)))
1412 return false;
1414 // In all other cases, we want to compare against the URL that determines
1415 // the type of process. In default Chrome, that's the URL of the opener's
1416 // top frame and not the opener frame itself. In --site-per-process, we
1417 // can use the opener frame itself.
1418 // TODO(nick): Either wire this up to SiteIsolationPolicy, or to state on
1419 // |opener_frame|/its ancestors.
1420 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1421 switches::kSitePerProcess))
1422 old_url = opener_frame->document().url();
1423 else
1424 old_url = opener_frame->top()->document().url();
1427 // Only consider keeping non-app URLs in an app process if this window
1428 // has an opener (in which case it might be an OAuth popup that tries to
1429 // script an iframe within the app).
1430 bool should_consider_workaround = !!frame->opener();
1432 return extensions::CrossesExtensionProcessBoundary(
1433 *extension_registry->GetMainThreadExtensionSet(), old_url, new_url,
1434 should_consider_workaround);
1436 #endif // defined(ENABLE_EXTENSIONS)
1438 #if defined(ENABLE_SPELLCHECK)
1439 void ChromeContentRendererClient::SetSpellcheck(SpellCheck* spellcheck) {
1440 RenderThread* thread = RenderThread::Get();
1441 if (spellcheck_.get() && thread)
1442 thread->RemoveObserver(spellcheck_.get());
1443 spellcheck_.reset(spellcheck);
1444 SpellCheckReplacer replacer(spellcheck_.get());
1445 content::RenderView::ForEach(&replacer);
1446 if (thread)
1447 thread->AddObserver(spellcheck_.get());
1449 #endif
1451 // static
1452 bool ChromeContentRendererClient::WasWebRequestUsedBySomeExtensions() {
1453 #if defined(ENABLE_EXTENSIONS)
1454 return g_current_client->extension_dispatcher_
1455 ->WasWebRequestUsedBySomeExtensions();
1456 #else
1457 return false;
1458 #endif
1461 const void* ChromeContentRendererClient::CreatePPAPIInterface(
1462 const std::string& interface_name) {
1463 #if defined(ENABLE_PLUGINS) && !defined(DISABLE_NACL)
1464 if (interface_name == PPB_NACL_PRIVATE_INTERFACE)
1465 return nacl::GetNaClPrivateInterface();
1466 #endif
1467 return NULL;
1470 bool ChromeContentRendererClient::IsExternalPepperPlugin(
1471 const std::string& module_name) {
1472 // TODO(bbudge) remove this when the trusted NaCl plugin has been removed.
1473 // We must defer certain plugin events for NaCl instances since we switch
1474 // from the in-process to the out-of-process proxy after instantiating them.
1475 return module_name == "Native Client";
1478 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
1479 bool ChromeContentRendererClient::IsExtensionOrSharedModuleWhitelisted(
1480 const GURL& url, const std::set<std::string>& whitelist) {
1481 const extensions::ExtensionSet* extension_set =
1482 extensions::RendererExtensionRegistry::Get()->GetMainThreadExtensionSet();
1483 return chrome::IsExtensionOrSharedModuleWhitelisted(url, extension_set,
1484 whitelist);
1486 #endif
1488 blink::WebSpeechSynthesizer*
1489 ChromeContentRendererClient::OverrideSpeechSynthesizer(
1490 blink::WebSpeechSynthesizerClient* client) {
1491 return new TtsDispatcher(client);
1494 bool ChromeContentRendererClient::AllowPepperMediaStreamAPI(
1495 const GURL& url) {
1496 #if !defined(OS_ANDROID)
1497 // Allow only the Hangouts app to use the MediaStream APIs. It's OK to check
1498 // the whitelist in the renderer, since we're only preventing access until
1499 // these APIs are public and stable.
1500 std::string url_host = url.host();
1501 if (url.SchemeIs("https") &&
1502 (base::EndsWith(url_host, "talkgadget.google.com",
1503 base::CompareCase::INSENSITIVE_ASCII) ||
1504 base::EndsWith(url_host, "plus.google.com",
1505 base::CompareCase::INSENSITIVE_ASCII) ||
1506 base::EndsWith(url_host, "plus.sandbox.google.com",
1507 base::CompareCase::INSENSITIVE_ASCII)) &&
1508 base::StartsWith(url.path(), "/hangouts/",
1509 base::CompareCase::INSENSITIVE_ASCII)) {
1510 return true;
1512 // Allow access for tests.
1513 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1514 switches::kEnablePepperTesting)) {
1515 return true;
1517 #endif // !defined(OS_ANDROID)
1518 return false;
1521 void ChromeContentRendererClient::AddKeySystems(
1522 std::vector<media::KeySystemInfo>* key_systems) {
1523 AddChromeKeySystems(key_systems);
1526 bool ChromeContentRendererClient::ShouldReportDetailedMessageForSource(
1527 const base::string16& source) const {
1528 #if defined(ENABLE_EXTENSIONS)
1529 return extensions::IsSourceFromAnExtension(source);
1530 #else
1531 return false;
1532 #endif
1535 bool ChromeContentRendererClient::ShouldGatherSiteIsolationStats() const {
1536 // Site isolation stats are gathered currently for non-extension renderer
1537 // processes running a normal web page from the Internet.
1538 // TODO(nick): https://crbug.com/268640 Gather stats for extension processes
1539 // too; we would need to check the extension's manifest to know which sites
1540 // it's allowed to access.
1541 #if defined(ENABLE_EXTENSIONS)
1542 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
1543 return !command_line->HasSwitch(extensions::switches::kExtensionProcess);
1544 #else
1545 return true;
1546 #endif
1549 blink::WebWorkerContentSettingsClientProxy*
1550 ChromeContentRendererClient::CreateWorkerContentSettingsClientProxy(
1551 content::RenderFrame* render_frame,
1552 blink::WebFrame* frame) {
1553 return new WorkerContentSettingsClientProxy(render_frame, frame);
1556 bool ChromeContentRendererClient::IsPluginAllowedToUseDevChannelAPIs() {
1557 #if defined(ENABLE_PLUGINS)
1558 // Allow access for tests.
1559 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1560 switches::kEnablePepperTesting)) {
1561 return true;
1564 version_info::Channel channel = chrome::GetChannel();
1565 // Allow dev channel APIs to be used on "Canary", "Dev", and "Unknown"
1566 // releases of Chrome. Permitting "Unknown" allows these APIs to be used on
1567 // Chromium builds as well.
1568 return channel <= version_info::Channel::DEV;
1569 #else
1570 return false;
1571 #endif
1574 bool ChromeContentRendererClient::IsPluginAllowedToUseCameraDeviceAPI(
1575 const GURL& url) {
1576 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
1577 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1578 switches::kEnablePepperTesting))
1579 return true;
1581 if (IsExtensionOrSharedModuleWhitelisted(url, allowed_camera_device_origins_))
1582 return true;
1583 #endif
1585 return false;
1588 bool ChromeContentRendererClient::IsPluginAllowedToUseCompositorAPI(
1589 const GURL& url) {
1590 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
1591 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1592 switches::kEnablePepperTesting))
1593 return true;
1594 if (IsExtensionOrSharedModuleWhitelisted(url, allowed_compositor_origins_))
1595 return true;
1597 version_info::Channel channel = chrome::GetChannel();
1598 return channel <= version_info::Channel::DEV;
1599 #else
1600 return false;
1601 #endif
1604 content::BrowserPluginDelegate*
1605 ChromeContentRendererClient::CreateBrowserPluginDelegate(
1606 content::RenderFrame* render_frame,
1607 const std::string& mime_type,
1608 const GURL& original_url) {
1609 #if defined(ENABLE_EXTENSIONS)
1610 if (mime_type == content::kBrowserPluginMimeType) {
1611 return new extensions::ExtensionsGuestViewContainer(render_frame);
1612 } else {
1613 return new extensions::MimeHandlerViewContainer(
1614 render_frame, mime_type, original_url);
1616 #else
1617 return NULL;
1618 #endif
1621 void ChromeContentRendererClient::RecordRappor(const std::string& metric,
1622 const std::string& sample) {
1623 RenderThread::Get()->Send(new ChromeViewHostMsg_RecordRappor(metric, sample));
1626 void ChromeContentRendererClient::RecordRapporURL(const std::string& metric,
1627 const GURL& url) {
1628 RenderThread::Get()->Send(new ChromeViewHostMsg_RecordRapporURL(metric, url));
1631 scoped_ptr<blink::WebAppBannerClient>
1632 ChromeContentRendererClient::CreateAppBannerClient(
1633 content::RenderFrame* render_frame) {
1634 return scoped_ptr<blink::WebAppBannerClient>(
1635 new AppBannerClient(render_frame));
1638 void ChromeContentRendererClient::AddImageContextMenuProperties(
1639 const blink::WebURLResponse& response,
1640 std::map<std::string, std::string>* properties) {
1641 DCHECK(properties);
1642 WebString header_key(ASCIIToUTF16(
1643 data_reduction_proxy::chrome_proxy_header()));
1644 if (!response.httpHeaderField(header_key).isNull() &&
1645 response.httpHeaderField(header_key).utf8().find(
1646 data_reduction_proxy::chrome_proxy_lo_fi_directive()) !=
1647 std::string::npos) {
1648 (*properties)[data_reduction_proxy::chrome_proxy_header()] =
1649 data_reduction_proxy::chrome_proxy_lo_fi_directive();
1653 void
1654 ChromeContentRendererClient::DidInitializeServiceWorkerContextOnWorkerThread(
1655 v8::Local<v8::Context> context,
1656 const GURL& url) {
1657 #if defined(ENABLE_EXTENSIONS)
1658 extensions::Dispatcher::DidInitializeServiceWorkerContextOnWorkerThread(
1659 context, url);
1660 #endif
1663 void ChromeContentRendererClient::WillDestroyServiceWorkerContextOnWorkerThread(
1664 v8::Local<v8::Context> context,
1665 const GURL& url) {
1666 #if defined(ENABLE_EXTENSIONS)
1667 extensions::Dispatcher::WillDestroyServiceWorkerContextOnWorkerThread(context,
1668 url);
1669 #endif