[sql] Remove _HAS_EXCEPTIONS=0 from build info.
[chromium-blink-merge.git] / chrome / renderer / chrome_content_renderer_client.cc
blobc8f067efd268c4e3c368302aa7b01ab0127536f8
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/plugins/shadow_dom_plugin_placeholder.h"
47 #include "chrome/renderer/prerender/prerender_dispatcher.h"
48 #include "chrome/renderer/prerender/prerender_helper.h"
49 #include "chrome/renderer/prerender/prerender_media_load_deferrer.h"
50 #include "chrome/renderer/prerender/prerenderer_client.h"
51 #include "chrome/renderer/safe_browsing/malware_dom_details.h"
52 #include "chrome/renderer/safe_browsing/phishing_classifier_delegate.h"
53 #include "chrome/renderer/searchbox/search_bouncer.h"
54 #include "chrome/renderer/searchbox/searchbox.h"
55 #include "chrome/renderer/searchbox/searchbox_extension.h"
56 #include "chrome/renderer/tts_dispatcher.h"
57 #include "chrome/renderer/worker_content_settings_client_proxy.h"
58 #include "components/autofill/content/renderer/autofill_agent.h"
59 #include "components/autofill/content/renderer/password_autofill_agent.h"
60 #include "components/autofill/content/renderer/password_generation_agent.h"
61 #include "components/content_settings/core/common/content_settings_pattern.h"
62 #include "components/data_reduction_proxy/core/common/data_reduction_proxy_headers.h"
63 #include "components/dom_distiller/core/url_constants.h"
64 #include "components/nacl/renderer/ppb_nacl_private.h"
65 #include "components/nacl/renderer/ppb_nacl_private_impl.h"
66 #include "components/network_hints/renderer/prescient_networking_dispatcher.h"
67 #include "components/password_manager/content/renderer/credential_manager_client.h"
68 #include "components/pdf/renderer/pepper_pdf_host.h"
69 #include "components/plugins/renderer/mobile_youtube_plugin.h"
70 #include "components/signin/core/common/profile_management_switches.h"
71 #include "components/version_info/version_info.h"
72 #include "components/visitedlink/renderer/visitedlink_slave.h"
73 #include "components/web_cache/renderer/web_cache_render_process_observer.h"
74 #include "content/public/common/content_constants.h"
75 #include "content/public/renderer/plugin_instance_throttler.h"
76 #include "content/public/renderer/render_frame.h"
77 #include "content/public/renderer/render_thread.h"
78 #include "content/public/renderer/render_view.h"
79 #include "content/public/renderer/render_view_visitor.h"
80 #include "extensions/common/constants.h"
81 #include "ipc/ipc_sync_channel.h"
82 #include "net/base/net_errors.h"
83 #include "ppapi/c/private/ppb_pdf.h"
84 #include "ppapi/shared_impl/ppapi_switches.h"
85 #include "third_party/WebKit/public/platform/WebURL.h"
86 #include "third_party/WebKit/public/platform/WebURLError.h"
87 #include "third_party/WebKit/public/platform/WebURLRequest.h"
88 #include "third_party/WebKit/public/platform/WebURLResponse.h"
89 #include "third_party/WebKit/public/web/WebCache.h"
90 #include "third_party/WebKit/public/web/WebDataSource.h"
91 #include "third_party/WebKit/public/web/WebDocument.h"
92 #include "third_party/WebKit/public/web/WebElement.h"
93 #include "third_party/WebKit/public/web/WebLocalFrame.h"
94 #include "third_party/WebKit/public/web/WebPluginContainer.h"
95 #include "third_party/WebKit/public/web/WebPluginParams.h"
96 #include "third_party/WebKit/public/web/WebPluginPlaceholder.h"
97 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
98 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
99 #include "ui/base/l10n/l10n_util.h"
100 #include "ui/base/layout.h"
101 #include "ui/base/resource/resource_bundle.h"
102 #include "ui/base/webui/jstemplate_builder.h"
103 #include "widevine_cdm_version.h" // In SHARED_INTERMEDIATE_DIR.
105 #if !defined(DISABLE_NACL)
106 #include "components/nacl/common/nacl_constants.h"
107 #include "components/nacl/renderer/nacl_helper.h"
108 #endif
110 #if defined(ENABLE_EXTENSIONS)
111 #include "chrome/common/extensions/chrome_extensions_client.h"
112 #include "chrome/common/extensions/extension_process_policy.h"
113 #include "chrome/renderer/extensions/chrome_extensions_dispatcher_delegate.h"
114 #include "chrome/renderer/extensions/chrome_extensions_renderer_client.h"
115 #include "chrome/renderer/extensions/renderer_permissions_policy_delegate.h"
116 #include "chrome/renderer/extensions/resource_request_policy.h"
117 #include "chrome/renderer/media/cast_ipc_dispatcher.h"
118 #include "extensions/common/extension.h"
119 #include "extensions/common/extension_set.h"
120 #include "extensions/common/extension_urls.h"
121 #include "extensions/common/switches.h"
122 #include "extensions/renderer/dispatcher.h"
123 #include "extensions/renderer/extension_frame_helper.h"
124 #include "extensions/renderer/extension_helper.h"
125 #include "extensions/renderer/extensions_render_frame_observer.h"
126 #include "extensions/renderer/guest_view/extensions_guest_view_container.h"
127 #include "extensions/renderer/guest_view/extensions_guest_view_container_dispatcher.h"
128 #include "extensions/renderer/guest_view/mime_handler_view/mime_handler_view_container.h"
129 #include "extensions/renderer/script_context.h"
130 #endif
132 #if defined(ENABLE_IPC_FUZZER)
133 #include "chrome/common/external_ipc_dumper.h"
134 #endif
136 #if defined(ENABLE_PLUGINS)
137 #include "chrome/renderer/plugins/chrome_plugin_placeholder.h"
138 #endif
140 #if defined(ENABLE_PRINTING)
141 #include "chrome/renderer/printing/chrome_print_web_view_helper_delegate.h"
142 #include "components/printing/renderer/print_web_view_helper.h"
143 #endif
145 #if defined(ENABLE_PRINT_PREVIEW)
146 #include "chrome/renderer/pepper/chrome_pdf_print_client.h"
147 #endif
149 #if defined(ENABLE_SPELLCHECK)
150 #include "chrome/renderer/spellchecker/spellcheck.h"
151 #include "chrome/renderer/spellchecker/spellcheck_provider.h"
152 #endif
154 #if defined(ENABLE_WEBRTC)
155 #include "chrome/renderer/media/webrtc_logging_message_filter.h"
156 #endif
158 using autofill::AutofillAgent;
159 using autofill::PasswordAutofillAgent;
160 using autofill::PasswordGenerationAgent;
161 using base::ASCIIToUTF16;
162 using base::UserMetricsAction;
163 using content::PluginInstanceThrottler;
164 using content::RenderFrame;
165 using content::RenderThread;
166 using content::WebPluginInfo;
167 using extensions::Extension;
168 using blink::WebCache;
169 using blink::WebConsoleMessage;
170 using blink::WebDataSource;
171 using blink::WebDocument;
172 using blink::WebLocalFrame;
173 using blink::WebPlugin;
174 using blink::WebPluginParams;
175 using blink::WebSecurityOrigin;
176 using blink::WebSecurityPolicy;
177 using blink::WebString;
178 using blink::WebURL;
179 using blink::WebURLError;
180 using blink::WebURLRequest;
181 using blink::WebURLResponse;
182 using blink::WebVector;
184 namespace {
186 ChromeContentRendererClient* g_current_client;
188 // Whitelist PPAPI for Android Runtime for Chromium. (See crbug.com/383937)
189 #if defined(ENABLE_PLUGINS)
190 const char* const kPredefinedAllowedCameraDeviceOrigins[] = {
191 "6EAED1924DB611B6EEF2A664BD077BE7EAD33B8F",
192 "4EB74897CB187C7633357C2FE832E0AD6A44883A"
195 const char* const kPredefinedAllowedCompositorOrigins[] = {
196 "6EAED1924DB611B6EEF2A664BD077BE7EAD33B8F",
197 "4EB74897CB187C7633357C2FE832E0AD6A44883A"
199 #endif
201 #if defined(ENABLE_PLUGINS)
202 void AppendParams(const std::vector<base::string16>& additional_names,
203 const std::vector<base::string16>& additional_values,
204 WebVector<WebString>* existing_names,
205 WebVector<WebString>* existing_values) {
206 DCHECK(additional_names.size() == additional_values.size());
207 DCHECK(existing_names->size() == existing_values->size());
209 size_t existing_size = existing_names->size();
210 size_t total_size = existing_size + additional_names.size();
212 WebVector<WebString> names(total_size);
213 WebVector<WebString> values(total_size);
215 for (size_t i = 0; i < existing_size; ++i) {
216 names[i] = (*existing_names)[i];
217 values[i] = (*existing_values)[i];
220 for (size_t i = 0; i < additional_names.size(); ++i) {
221 names[existing_size + i] = additional_names[i];
222 values[existing_size + i] = additional_values[i];
225 existing_names->swap(names);
226 existing_values->swap(values);
229 // For certain sandboxed Pepper plugins, use the JavaScript Content Settings.
230 bool ShouldUseJavaScriptSettingForPlugin(const WebPluginInfo& plugin) {
231 if (plugin.type != WebPluginInfo::PLUGIN_TYPE_PEPPER_IN_PROCESS &&
232 plugin.type != WebPluginInfo::PLUGIN_TYPE_PEPPER_OUT_OF_PROCESS) {
233 return false;
236 #if !defined(DISABLE_NACL)
237 // Treat Native Client invocations like JavaScript.
238 if (plugin.name == ASCIIToUTF16(nacl::kNaClPluginName))
239 return true;
240 #endif
242 #if defined(WIDEVINE_CDM_AVAILABLE) && defined(ENABLE_PEPPER_CDMS)
243 // Treat CDM invocations like JavaScript.
244 if (plugin.name == ASCIIToUTF16(kWidevineCdmDisplayName)) {
245 DCHECK(plugin.type == WebPluginInfo::PLUGIN_TYPE_PEPPER_OUT_OF_PROCESS);
246 return true;
248 #endif // defined(WIDEVINE_CDM_AVAILABLE) && defined(ENABLE_PEPPER_CDMS)
250 return false;
252 #endif // defined(ENABLE_PLUGINS)
254 #if defined(ENABLE_SPELLCHECK)
255 class SpellCheckReplacer : public content::RenderViewVisitor {
256 public:
257 explicit SpellCheckReplacer(SpellCheck* spellcheck)
258 : spellcheck_(spellcheck) {}
259 bool Visit(content::RenderView* render_view) override;
261 private:
262 SpellCheck* spellcheck_; // New shared spellcheck for all views. Weak Ptr.
263 DISALLOW_COPY_AND_ASSIGN(SpellCheckReplacer);
266 bool SpellCheckReplacer::Visit(content::RenderView* render_view) {
267 SpellCheckProvider* provider = SpellCheckProvider::Get(render_view);
268 DCHECK(provider);
269 provider->set_spellcheck(spellcheck_);
270 return true;
272 #endif
274 #if defined(ENABLE_EXTENSIONS)
275 void IsGuestViewApiAvailableToScriptContext(
276 bool* api_is_available,
277 extensions::ScriptContext* context) {
278 if (context->GetAvailability("guestViewInternal").is_available()) {
279 *api_is_available = true;
282 #endif
284 #if defined(ENABLE_PLUGINS)
285 // Presence of the poster param within plugin object tags.
286 // These numeric values are used in UMA logs; do not change them.
287 enum PosterParamPresence {
288 POSTER_PRESENCE_NO_PARAM_PPS_DISABLED = 0,
289 POSTER_PRESENCE_NO_PARAM_PPS_ENABLED = 1,
290 POSTER_PRESENCE_PARAM_EXISTS_PPS_DISABLED = 2,
291 POSTER_PRESENCE_PARAM_EXISTS_PPS_ENABLED = 3,
292 POSTER_PRESENCE_NUM_ITEMS
295 const char kPluginPowerSaverPosterParamPresenceHistogram[] =
296 "Plugin.PowerSaver.PosterParamPresence";
298 void RecordPosterParamPresence(PosterParamPresence presence) {
299 UMA_HISTOGRAM_ENUMERATION(kPluginPowerSaverPosterParamPresenceHistogram,
300 presence, POSTER_PRESENCE_NUM_ITEMS);
303 void TrackPosterParamPresence(const blink::WebPluginParams& params,
304 bool power_saver_enabled) {
305 DCHECK_EQ(params.attributeNames.size(), params.attributeValues.size());
307 for (size_t i = 0; i < params.attributeNames.size(); ++i) {
308 if (params.attributeNames[i].utf8() == "poster") {
309 if (power_saver_enabled)
310 RecordPosterParamPresence(POSTER_PRESENCE_PARAM_EXISTS_PPS_ENABLED);
311 else
312 RecordPosterParamPresence(POSTER_PRESENCE_PARAM_EXISTS_PPS_DISABLED);
314 return;
318 if (power_saver_enabled)
319 RecordPosterParamPresence(POSTER_PRESENCE_NO_PARAM_PPS_ENABLED);
320 else
321 RecordPosterParamPresence(POSTER_PRESENCE_NO_PARAM_PPS_DISABLED);
324 std::string GetPluginInstancePosterAttribute(
325 const blink::WebPluginParams& params) {
326 DCHECK_EQ(params.attributeNames.size(), params.attributeValues.size());
328 for (size_t i = 0; i < params.attributeNames.size(); ++i) {
329 if (params.attributeNames[i].utf8() == "poster" &&
330 !params.attributeValues[i].isEmpty()) {
331 return params.attributeValues[i].utf8();
334 return std::string();
336 #endif
338 #if defined(ENABLE_EXTENSIONS)
339 bool IsStandaloneExtensionProcess() {
340 return base::CommandLine::ForCurrentProcess()->HasSwitch(
341 extensions::switches::kExtensionProcess);
343 #endif
344 } // namespace
346 ChromeContentRendererClient::ChromeContentRendererClient() {
347 g_current_client = this;
349 #if defined(ENABLE_EXTENSIONS)
350 extensions::ExtensionsClient::Set(
351 extensions::ChromeExtensionsClient::GetInstance());
352 extensions::ExtensionsRendererClient::Set(
353 ChromeExtensionsRendererClient::GetInstance());
354 #endif
355 #if defined(ENABLE_PLUGINS)
356 for (size_t i = 0; i < arraysize(kPredefinedAllowedCameraDeviceOrigins); ++i)
357 allowed_camera_device_origins_.insert(
358 kPredefinedAllowedCameraDeviceOrigins[i]);
359 for (size_t i = 0; i < arraysize(kPredefinedAllowedCompositorOrigins); ++i)
360 allowed_compositor_origins_.insert(kPredefinedAllowedCompositorOrigins[i]);
361 #endif
364 ChromeContentRendererClient::~ChromeContentRendererClient() {
365 g_current_client = NULL;
368 void ChromeContentRendererClient::RenderThreadStarted() {
369 RenderThread* thread = RenderThread::Get();
371 chrome_observer_.reset(new ChromeRenderProcessObserver());
372 web_cache_observer_.reset(new web_cache::WebCacheRenderProcessObserver());
374 #if defined(ENABLE_EXTENSIONS)
375 extension_dispatcher_delegate_.reset(
376 new ChromeExtensionsDispatcherDelegate());
377 // ChromeRenderViewTest::SetUp() creates its own ExtensionDispatcher and
378 // injects it using SetExtensionDispatcher(). Don't overwrite it.
379 if (!extension_dispatcher_) {
380 extension_dispatcher_.reset(
381 new extensions::Dispatcher(extension_dispatcher_delegate_.get()));
383 permissions_policy_delegate_.reset(
384 new extensions::RendererPermissionsPolicyDelegate(
385 extension_dispatcher_.get()));
386 guest_view_container_dispatcher_.reset(
387 new extensions::ExtensionsGuestViewContainerDispatcher());
388 #endif
390 prescient_networking_dispatcher_.reset(
391 new network_hints::PrescientNetworkingDispatcher());
392 #if defined(ENABLE_SPELLCHECK)
393 // ChromeRenderViewTest::SetUp() creates a Spellcheck and injects it using
394 // SetSpellcheck(). Don't overwrite it.
395 if (!spellcheck_) {
396 spellcheck_.reset(new SpellCheck());
397 thread->AddObserver(spellcheck_.get());
399 #endif
400 visited_link_slave_.reset(new visitedlink::VisitedLinkSlave());
401 #if defined(FULL_SAFE_BROWSING)
402 phishing_classifier_.reset(safe_browsing::PhishingClassifierFilter::Create());
403 #endif
404 prerender_dispatcher_.reset(new prerender::PrerenderDispatcher());
405 #if defined(ENABLE_WEBRTC)
406 webrtc_logging_message_filter_ = new WebRtcLoggingMessageFilter(
407 RenderThread::Get()->GetIOMessageLoopProxy());
408 #endif
410 thread->AddObserver(chrome_observer_.get());
411 thread->AddObserver(web_cache_observer_.get());
412 #if defined(ENABLE_EXTENSIONS)
413 thread->AddObserver(extension_dispatcher_.get());
414 thread->AddObserver(guest_view_container_dispatcher_.get());
415 #endif
416 #if defined(FULL_SAFE_BROWSING)
417 thread->AddObserver(phishing_classifier_.get());
418 #endif
419 thread->AddObserver(visited_link_slave_.get());
420 thread->AddObserver(prerender_dispatcher_.get());
421 thread->AddObserver(SearchBouncer::GetInstance());
423 #if defined(ENABLE_WEBRTC)
424 thread->AddFilter(webrtc_logging_message_filter_.get());
425 #endif
426 #if defined(ENABLE_EXTENSIONS)
427 thread->AddFilter(new CastIPCDispatcher(
428 RenderThread::Get()->GetIOMessageLoopProxy()));
429 #endif
431 thread->RegisterExtension(extensions_v8::ExternalExtension::Get());
432 thread->RegisterExtension(extensions_v8::LoadTimesExtension::Get());
434 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
435 if (command_line->HasSwitch(switches::kEnableBenchmarking))
436 thread->RegisterExtension(extensions_v8::BenchmarkingExtension::Get());
437 if (command_line->HasSwitch(switches::kEnableNetBenchmarking))
438 thread->RegisterExtension(extensions_v8::NetBenchmarkingExtension::Get());
439 if (command_line->HasSwitch(switches::kInstantProcess))
440 thread->RegisterExtension(extensions_v8::SearchBoxExtension::Get());
442 // chrome-search: and chrome-distiller: pages should not be accessible by
443 // normal content, and should also be unable to script anything but themselves
444 // (to help limit the damage that a corrupt page could cause).
445 WebString chrome_search_scheme(ASCIIToUTF16(chrome::kChromeSearchScheme));
447 // The Instant process can only display the content but not read it. Other
448 // processes can't display it or read it.
449 if (!command_line->HasSwitch(switches::kInstantProcess))
450 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(chrome_search_scheme);
452 WebString dom_distiller_scheme(
453 ASCIIToUTF16(dom_distiller::kDomDistillerScheme));
454 // TODO(nyquist): Add test to ensure this happens when the flag is set.
455 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(dom_distiller_scheme);
457 #if defined(OS_CHROMEOS)
458 WebString external_file_scheme(ASCIIToUTF16(content::kExternalFileScheme));
459 WebSecurityPolicy::registerURLSchemeAsLocal(external_file_scheme);
460 #endif
462 #if defined(ENABLE_IPC_FUZZER)
463 if (command_line->HasSwitch(switches::kIpcDumpDirectory)) {
464 base::FilePath dump_directory =
465 command_line->GetSwitchValuePath(switches::kIpcDumpDirectory);
466 IPC::ChannelProxy::OutgoingMessageFilter* filter =
467 LoadExternalIPCDumper(dump_directory);
468 thread->GetChannel()->set_outgoing_message_filter(filter);
470 #endif
472 // chrome-search: pages should not be accessible by bookmarklets
473 // or javascript: URLs typed in the omnibox.
474 WebSecurityPolicy::registerURLSchemeAsNotAllowingJavascriptURLs(
475 chrome_search_scheme);
477 // chrome-search:, chrome-extension:, and chrome-extension-resource:
478 // resources shouldn't trigger insecure content warnings.
479 WebSecurityPolicy::registerURLSchemeAsSecure(chrome_search_scheme);
481 WebString extension_scheme(ASCIIToUTF16(extensions::kExtensionScheme));
482 WebSecurityPolicy::registerURLSchemeAsSecure(extension_scheme);
484 WebString extension_resource_scheme(
485 ASCIIToUTF16(extensions::kExtensionResourceScheme));
486 WebSecurityPolicy::registerURLSchemeAsSecure(extension_resource_scheme);
488 // chrome:, chrome-extension:, chrome-extension-resource: resources should be
489 // allowed to receive CORS requests.
490 WebSecurityPolicy::registerURLSchemeAsCORSEnabled(extension_scheme);
491 WebSecurityPolicy::registerURLSchemeAsCORSEnabled(extension_resource_scheme);
493 // chrome-extension: resources should bypass Content Security Policy checks
494 // when included in protected resources.
495 WebSecurityPolicy::registerURLSchemeAsBypassingContentSecurityPolicy(
496 extension_scheme);
497 WebSecurityPolicy::registerURLSchemeAsBypassingContentSecurityPolicy(
498 extension_resource_scheme);
500 #if defined(ENABLE_PRINT_PREVIEW)
501 pdf_print_client_.reset(new ChromePDFPrintClient());
502 pdf::PepperPDFHost::SetPrintClient(pdf_print_client_.get());
503 #endif
505 std::set<GURL> origins;
506 GetSecureOriginWhitelist(&origins);
507 for (const GURL& origin : origins) {
508 WebSecurityPolicy::addOriginTrustworthyWhiteList(
509 WebSecurityOrigin::create(origin));
513 void ChromeContentRendererClient::RenderFrameCreated(
514 content::RenderFrame* render_frame) {
515 new ChromeRenderFrameObserver(render_frame);
517 bool should_whitelist_for_content_settings =
518 base::CommandLine::ForCurrentProcess()->HasSwitch(
519 switches::kInstantProcess);
520 extensions::Dispatcher* ext_dispatcher = NULL;
521 #if defined(ENABLE_EXTENSIONS)
522 ext_dispatcher = extension_dispatcher_.get();
523 #endif
524 ContentSettingsObserver* content_settings = new ContentSettingsObserver(
525 render_frame, ext_dispatcher, should_whitelist_for_content_settings);
526 if (chrome_observer_.get()) {
527 content_settings->SetContentSettingRules(
528 chrome_observer_->content_setting_rules());
531 #if defined(ENABLE_EXTENSIONS)
532 new extensions::ExtensionsRenderFrameObserver(render_frame);
533 new extensions::ExtensionFrameHelper(render_frame, ext_dispatcher);
534 ext_dispatcher->OnRenderFrameCreated(render_frame);
535 #endif
537 #if defined(ENABLE_PLUGINS)
538 new PepperHelper(render_frame);
539 #endif
541 #if !defined(DISABLE_NACL)
542 new nacl::NaClHelper(render_frame);
543 #endif
545 // TODO(jam): when the frame tree moves into content and parent() works at
546 // RenderFrame construction, simplify this by just checking parent().
547 if (render_frame->GetRenderView()->GetMainRenderFrame() != render_frame) {
548 // Avoid any race conditions from having the browser tell subframes that
549 // they're prerendering.
550 if (prerender::PrerenderHelper::IsPrerendering(
551 render_frame->GetRenderView()->GetMainRenderFrame())) {
552 new prerender::PrerenderHelper(render_frame);
556 if (render_frame->GetRenderView()->GetMainRenderFrame() == render_frame) {
557 // Only attach NetErrorHelper to the main frame, since only the main frame
558 // should get error pages.
559 new NetErrorHelper(render_frame);
562 PasswordAutofillAgent* password_autofill_agent =
563 new PasswordAutofillAgent(render_frame);
564 PasswordGenerationAgent* password_generation_agent =
565 new PasswordGenerationAgent(render_frame, password_autofill_agent);
566 new AutofillAgent(render_frame, password_autofill_agent,
567 password_generation_agent);
570 void ChromeContentRendererClient::RenderViewCreated(
571 content::RenderView* render_view) {
573 #if defined(ENABLE_EXTENSIONS)
574 new extensions::ExtensionHelper(render_view, extension_dispatcher_.get());
575 #endif
576 new PageLoadHistograms(render_view);
577 #if defined(ENABLE_PRINTING)
578 new printing::PrintWebViewHelper(
579 render_view,
580 scoped_ptr<printing::PrintWebViewHelper::Delegate>(
581 new ChromePrintWebViewHelperDelegate()));
582 #endif
583 #if defined(ENABLE_SPELLCHECK)
584 new SpellCheckProvider(render_view, spellcheck_.get());
585 #endif
586 new prerender::PrerendererClient(render_view);
587 #if defined(FULL_SAFE_BROWSING)
588 safe_browsing::MalwareDOMDetails::Create(render_view);
589 #endif
591 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
592 if (command_line->HasSwitch(switches::kInstantProcess))
593 new SearchBox(render_view);
595 new ChromeRenderViewObserver(render_view, web_cache_observer_.get());
597 new password_manager::CredentialManagerClient(render_view);
601 SkBitmap* ChromeContentRendererClient::GetSadPluginBitmap() {
602 return const_cast<SkBitmap*>(ResourceBundle::GetSharedInstance().
603 GetImageNamed(IDR_SAD_PLUGIN).ToSkBitmap());
606 SkBitmap* ChromeContentRendererClient::GetSadWebViewBitmap() {
607 return const_cast<SkBitmap*>(ResourceBundle::GetSharedInstance().
608 GetImageNamed(IDR_SAD_WEBVIEW).ToSkBitmap());
611 #if defined(ENABLE_EXTENSIONS)
612 const Extension* ChromeContentRendererClient::GetExtensionByOrigin(
613 const WebSecurityOrigin& origin) const {
614 if (!base::EqualsASCII(base::StringPiece16(origin.protocol()),
615 extensions::kExtensionScheme))
616 return NULL;
618 const std::string extension_id = origin.host().utf8().data();
619 return extension_dispatcher_->extensions()->GetByID(extension_id);
621 #endif
623 scoped_ptr<blink::WebPluginPlaceholder>
624 ChromeContentRendererClient::CreatePluginPlaceholder(
625 content::RenderFrame* render_frame,
626 blink::WebLocalFrame* frame,
627 const blink::WebPluginParams& orig_params) {
628 return CreateShadowDOMPlaceholderForPluginInfo(
629 render_frame, frame, orig_params);
632 bool ChromeContentRendererClient::OverrideCreatePlugin(
633 content::RenderFrame* render_frame,
634 blink::WebLocalFrame* frame,
635 const WebPluginParams& params,
636 WebPlugin** plugin) {
637 std::string orig_mime_type = params.mimeType.utf8();
638 #if defined(ENABLE_EXTENSIONS)
639 if (orig_mime_type == content::kBrowserPluginMimeType) {
640 bool guest_view_api_available = false;
641 extension_dispatcher_->script_context_set().ForEach(
642 render_frame, base::Bind(&IsGuestViewApiAvailableToScriptContext,
643 &guest_view_api_available));
644 if (guest_view_api_available)
645 return false;
647 #endif
649 GURL url(params.url);
650 #if defined(ENABLE_PLUGINS)
651 ChromeViewHostMsg_GetPluginInfo_Output output;
652 render_frame->Send(new ChromeViewHostMsg_GetPluginInfo(
653 render_frame->GetRoutingID(), url, frame->top()->document().url(),
654 orig_mime_type, &output));
655 *plugin = CreatePlugin(render_frame, frame, params, output);
656 #else // !defined(ENABLE_PLUGINS)
658 #if defined(OS_ANDROID)
659 if (plugins::MobileYouTubePlugin::IsYouTubeURL(url, orig_mime_type)) {
660 base::StringPiece template_html(
661 ResourceBundle::GetSharedInstance().GetRawDataResource(
662 IDR_MOBILE_YOUTUBE_PLUGIN_HTML));
663 *plugin = (new plugins::MobileYouTubePlugin(render_frame, frame, params,
664 template_html))->plugin();
665 return true;
667 #endif // defined(OS_ANDROID)
669 PluginUMAReporter::GetInstance()->ReportPluginMissing(orig_mime_type, url);
670 *plugin = NonLoadablePluginPlaceholder::CreateNotSupportedPlugin(
671 render_frame, frame, params)->plugin();
673 #endif // defined(ENABLE_PLUGINS)
674 return true;
677 WebPlugin* ChromeContentRendererClient::CreatePluginReplacement(
678 content::RenderFrame* render_frame,
679 const base::FilePath& plugin_path) {
680 return NonLoadablePluginPlaceholder::CreateErrorPlugin(render_frame,
681 plugin_path)->plugin();
684 void ChromeContentRendererClient::DeferMediaLoad(
685 content::RenderFrame* render_frame,
686 const base::Closure& closure) {
687 #if defined(OS_ANDROID)
688 // Chromium for Android doesn't support prerender yet.
689 closure.Run();
690 return;
691 #else
692 if (!prerender::PrerenderHelper::IsPrerendering(render_frame)) {
693 closure.Run();
694 return;
697 // Lifetime is tied to |render_frame| via content::RenderFrameObserver.
698 new prerender::PrerenderMediaLoadDeferrer(render_frame, closure);
699 #endif
702 #if defined(ENABLE_PLUGINS)
703 WebPlugin* ChromeContentRendererClient::CreatePlugin(
704 content::RenderFrame* render_frame,
705 blink::WebLocalFrame* frame,
706 const WebPluginParams& original_params,
707 const ChromeViewHostMsg_GetPluginInfo_Output& output) {
708 const WebPluginInfo& info = output.plugin;
709 const std::string& actual_mime_type = output.actual_mime_type;
710 const base::string16& group_name = output.group_name;
711 const std::string& identifier = output.group_identifier;
712 ChromeViewHostMsg_GetPluginInfo_Status status = output.status;
713 GURL url(original_params.url);
714 std::string orig_mime_type = original_params.mimeType.utf8();
715 ChromePluginPlaceholder* placeholder = NULL;
717 // If the browser plugin is to be enabled, this should be handled by the
718 // renderer, so the code won't reach here due to the early exit in
719 // OverrideCreatePlugin.
720 if (status == ChromeViewHostMsg_GetPluginInfo_Status::kNotFound ||
721 orig_mime_type == content::kBrowserPluginMimeType) {
722 PluginUMAReporter::GetInstance()->ReportPluginMissing(orig_mime_type, url);
723 placeholder = ChromePluginPlaceholder::CreateLoadableMissingPlugin(
724 render_frame, frame, original_params);
725 } else {
726 // TODO(bauerb): This should be in content/.
727 WebPluginParams params(original_params);
728 for (size_t i = 0; i < info.mime_types.size(); ++i) {
729 if (info.mime_types[i].mime_type == actual_mime_type) {
730 AppendParams(info.mime_types[i].additional_param_names,
731 info.mime_types[i].additional_param_values,
732 &params.attributeNames, &params.attributeValues);
733 break;
736 if (params.mimeType.isNull() && (actual_mime_type.size() > 0)) {
737 // Webkit might say that mime type is null while we already know the
738 // actual mime type via ChromeViewHostMsg_GetPluginInfo. In that case
739 // we should use what we know since WebpluginDelegateProxy does some
740 // specific initializations based on this information.
741 params.mimeType = WebString::fromUTF8(actual_mime_type.c_str());
744 ContentSettingsObserver* observer =
745 ContentSettingsObserver::Get(render_frame);
747 const ContentSettingsType content_type =
748 ShouldUseJavaScriptSettingForPlugin(info)
749 ? CONTENT_SETTINGS_TYPE_JAVASCRIPT
750 : CONTENT_SETTINGS_TYPE_PLUGINS;
752 if ((status == ChromeViewHostMsg_GetPluginInfo_Status::kUnauthorized ||
753 status == ChromeViewHostMsg_GetPluginInfo_Status::kBlocked) &&
754 observer->IsPluginTemporarilyAllowed(identifier)) {
755 status = ChromeViewHostMsg_GetPluginInfo_Status::kAllowed;
758 #if defined(OS_WIN)
759 // In Windows we need to check if we can load NPAPI plugins.
760 // For example, if the render view is in the Ash desktop, we should not.
761 // If user is on ALLOW or DETECT setting, loading needs to be blocked here.
762 if ((status == ChromeViewHostMsg_GetPluginInfo_Status::kAllowed ||
763 status ==
764 ChromeViewHostMsg_GetPluginInfo_Status::kPlayImportantContent) &&
765 info.type == content::WebPluginInfo::PLUGIN_TYPE_NPAPI) {
766 if (observer->AreNPAPIPluginsBlocked())
767 status = ChromeViewHostMsg_GetPluginInfo_Status::kNPAPINotSupported;
769 #endif
771 auto create_blocked_plugin =
772 [&render_frame, &frame, &params, &info, &identifier, &group_name](
773 int template_id, const base::string16& message) {
774 return ChromePluginPlaceholder::CreateBlockedPlugin(
775 render_frame, frame, params, info, identifier, group_name,
776 template_id, message, PlaceholderPosterInfo());
778 switch (status) {
779 case ChromeViewHostMsg_GetPluginInfo_Status::kNotFound: {
780 NOTREACHED();
781 break;
783 case ChromeViewHostMsg_GetPluginInfo_Status::kAllowed:
784 case ChromeViewHostMsg_GetPluginInfo_Status::kPlayImportantContent: {
785 #if !defined(DISABLE_NACL) && defined(ENABLE_EXTENSIONS)
786 const bool is_nacl_plugin =
787 info.name == ASCIIToUTF16(nacl::kNaClPluginName);
788 const bool is_nacl_mime_type =
789 actual_mime_type == nacl::kNaClPluginMimeType;
790 const bool is_pnacl_mime_type =
791 actual_mime_type == nacl::kPnaclPluginMimeType;
792 if (is_nacl_plugin || is_nacl_mime_type || is_pnacl_mime_type) {
793 bool is_nacl_unrestricted = false;
794 if (is_nacl_mime_type) {
795 is_nacl_unrestricted =
796 base::CommandLine::ForCurrentProcess()->HasSwitch(
797 switches::kEnableNaCl);
798 } else if (is_pnacl_mime_type) {
799 is_nacl_unrestricted = true;
801 GURL manifest_url;
802 GURL app_url;
803 if (is_nacl_mime_type || is_pnacl_mime_type) {
804 // Normal NaCl/PNaCl embed. The app URL is the page URL.
805 manifest_url = url;
806 app_url = frame->top()->document().url();
807 } else {
808 // NaCl is being invoked as a content handler. Look up the NaCl
809 // module using the MIME type. The app URL is the manifest URL.
810 manifest_url = GetNaClContentHandlerURL(actual_mime_type, info);
811 app_url = manifest_url;
813 const Extension* extension =
814 g_current_client->extension_dispatcher_->extensions()->
815 GetExtensionOrAppByURL(manifest_url);
816 if (!IsNaClAllowed(manifest_url,
817 app_url,
818 is_nacl_unrestricted,
819 extension,
820 &params)) {
821 WebString error_message;
822 if (is_nacl_mime_type) {
823 error_message =
824 "Only unpacked extensions and apps installed from the Chrome "
825 "Web Store can load NaCl modules without enabling Native "
826 "Client in about:flags.";
827 } else if (is_pnacl_mime_type) {
828 error_message =
829 "Portable Native Client must not be disabled in about:flags.";
831 frame->addMessageToConsole(
832 WebConsoleMessage(WebConsoleMessage::LevelError,
833 error_message));
834 placeholder = create_blocked_plugin(
835 IDR_BLOCKED_PLUGIN_HTML,
836 #if defined(OS_CHROMEOS)
837 l10n_util::GetStringUTF16(IDS_NACL_PLUGIN_BLOCKED));
838 #else
839 l10n_util::GetStringFUTF16(IDS_PLUGIN_BLOCKED, group_name));
840 #endif
841 break;
844 #endif // !defined(DISABLE_NACL) && defined(ENABLE_EXTENSIONS)
846 // Delay loading plugins if prerendering.
847 // TODO(mmenke): In the case of prerendering, feed into
848 // ChromeContentRendererClient::CreatePlugin instead, to
849 // reduce the chance of future regressions.
850 bool is_prerendering =
851 prerender::PrerenderHelper::IsPrerendering(render_frame);
852 bool power_saver_enabled =
853 status ==
854 ChromeViewHostMsg_GetPluginInfo_Status::kPlayImportantContent;
855 bool blocked_for_background_tab =
856 render_frame->IsHidden() && power_saver_enabled;
858 if (info.name == ASCIIToUTF16(content::kFlashPluginName))
859 TrackPosterParamPresence(params, power_saver_enabled);
861 PlaceholderPosterInfo poster_info;
862 if (power_saver_enabled) {
863 poster_info.poster_attribute =
864 GetPluginInstancePosterAttribute(params);
865 poster_info.base_url = frame->document().url();
868 if (blocked_for_background_tab || is_prerendering ||
869 !poster_info.poster_attribute.empty()) {
870 placeholder = ChromePluginPlaceholder::CreateBlockedPlugin(
871 render_frame, frame, params, info, identifier, group_name,
872 poster_info.poster_attribute.empty() ? IDR_BLOCKED_PLUGIN_HTML
873 : IDR_PLUGIN_POSTER_HTML,
874 l10n_util::GetStringFUTF16(IDS_PLUGIN_BLOCKED, group_name),
875 poster_info);
876 placeholder->set_blocked_for_background_tab(
877 blocked_for_background_tab);
878 placeholder->set_blocked_for_prerendering(is_prerendering);
879 placeholder->set_power_saver_enabled(power_saver_enabled);
880 break;
883 scoped_ptr<content::PluginInstanceThrottler> throttler;
884 if (power_saver_enabled) {
885 throttler = PluginInstanceThrottler::Create();
886 // PluginPreroller manages its own lifetime.
887 new PluginPreroller(
888 render_frame, frame, params, info, identifier, group_name,
889 l10n_util::GetStringFUTF16(IDS_PLUGIN_BLOCKED, group_name),
890 throttler.get());
893 return render_frame->CreatePlugin(frame, info, params,
894 throttler.Pass());
896 case ChromeViewHostMsg_GetPluginInfo_Status::kNPAPINotSupported: {
897 RenderThread::Get()->RecordAction(
898 UserMetricsAction("Plugin_NPAPINotSupported"));
899 placeholder = create_blocked_plugin(
900 IDR_BLOCKED_PLUGIN_HTML,
901 l10n_util::GetStringUTF16(IDS_PLUGIN_NOT_SUPPORTED_METRO));
902 render_frame->Send(new ChromeViewHostMsg_NPAPINotSupported(
903 render_frame->GetRoutingID(), identifier));
904 break;
906 case ChromeViewHostMsg_GetPluginInfo_Status::kDisabled: {
907 PluginUMAReporter::GetInstance()->ReportPluginDisabled(orig_mime_type,
908 url);
909 placeholder = create_blocked_plugin(
910 IDR_DISABLED_PLUGIN_HTML,
911 l10n_util::GetStringFUTF16(IDS_PLUGIN_DISABLED, group_name));
912 break;
914 case ChromeViewHostMsg_GetPluginInfo_Status::kOutdatedBlocked: {
915 #if defined(ENABLE_PLUGIN_INSTALLATION)
916 placeholder = create_blocked_plugin(
917 IDR_BLOCKED_PLUGIN_HTML,
918 l10n_util::GetStringFUTF16(IDS_PLUGIN_OUTDATED, group_name));
919 render_frame->Send(new ChromeViewHostMsg_BlockedOutdatedPlugin(
920 render_frame->GetRoutingID(), placeholder->CreateRoutingId(),
921 identifier));
922 #else
923 NOTREACHED();
924 #endif
925 break;
927 case ChromeViewHostMsg_GetPluginInfo_Status::kOutdatedDisallowed: {
928 placeholder = create_blocked_plugin(
929 IDR_BLOCKED_PLUGIN_HTML,
930 l10n_util::GetStringFUTF16(IDS_PLUGIN_OUTDATED, group_name));
931 break;
933 case ChromeViewHostMsg_GetPluginInfo_Status::kUnauthorized: {
934 placeholder = create_blocked_plugin(
935 IDR_BLOCKED_PLUGIN_HTML,
936 l10n_util::GetStringFUTF16(IDS_PLUGIN_NOT_AUTHORIZED, group_name));
937 if (info.type != content::WebPluginInfo::PLUGIN_TYPE_NPAPI) {
938 render_frame->Send(new ChromeViewHostMsg_BlockedUnauthorizedPlugin(
939 render_frame->GetRoutingID(),
940 group_name,
941 identifier));
943 observer->DidBlockContentType(content_type, group_name);
944 break;
946 case ChromeViewHostMsg_GetPluginInfo_Status::kBlocked: {
947 placeholder = create_blocked_plugin(
948 IDR_BLOCKED_PLUGIN_HTML,
949 l10n_util::GetStringFUTF16(IDS_PLUGIN_BLOCKED, group_name));
950 RenderThread::Get()->RecordAction(UserMetricsAction("Plugin_Blocked"));
951 observer->DidBlockContentType(content_type, group_name);
952 break;
954 case ChromeViewHostMsg_GetPluginInfo_Status::kBlockedByPolicy: {
955 placeholder = create_blocked_plugin(
956 IDR_BLOCKED_PLUGIN_HTML,
957 l10n_util::GetStringFUTF16(IDS_PLUGIN_BLOCKED_BY_POLICY,
958 group_name));
959 placeholder->DisallowLoading();
960 RenderThread::Get()->RecordAction(
961 UserMetricsAction("Plugin_BlockedByPolicy"));
962 observer->DidBlockContentType(content_type, group_name);
963 break;
967 placeholder->SetStatus(status);
968 return placeholder->plugin();
970 #endif // defined(ENABLE_PLUGINS)
972 // For NaCl content handling plugins, the NaCl manifest is stored in an
973 // additonal 'nacl' param associated with the MIME type.
974 // static
975 GURL ChromeContentRendererClient::GetNaClContentHandlerURL(
976 const std::string& actual_mime_type,
977 const content::WebPluginInfo& plugin) {
978 // Look for the manifest URL among the MIME type's additonal parameters.
979 const char kNaClPluginManifestAttribute[] = "nacl";
980 base::string16 nacl_attr = ASCIIToUTF16(kNaClPluginManifestAttribute);
981 for (size_t i = 0; i < plugin.mime_types.size(); ++i) {
982 if (plugin.mime_types[i].mime_type == actual_mime_type) {
983 const content::WebPluginMimeType& content_type = plugin.mime_types[i];
984 for (size_t i = 0; i < content_type.additional_param_names.size(); ++i) {
985 if (content_type.additional_param_names[i] == nacl_attr)
986 return GURL(content_type.additional_param_values[i]);
988 break;
991 return GURL();
994 #if !defined(DISABLE_NACL)
995 // static
996 bool ChromeContentRendererClient::IsNaClAllowed(
997 const GURL& manifest_url,
998 const GURL& app_url,
999 bool is_nacl_unrestricted,
1000 const Extension* extension,
1001 WebPluginParams* params) {
1002 // Temporarily allow these whitelisted apps and WebUIs to use NaCl.
1003 std::string app_url_host = app_url.host();
1004 std::string manifest_url_path = manifest_url.path();
1006 bool is_whitelisted_web_ui =
1007 app_url.spec() == chrome::kChromeUIAppListStartPageURL;
1009 bool is_photo_app =
1010 // Whitelisted apps must be served over https.
1011 app_url.SchemeIsCryptographic() && manifest_url.SchemeIsCryptographic() &&
1012 (base::EndsWith(app_url_host, "plus.google.com",
1013 base::CompareCase::INSENSITIVE_ASCII) ||
1014 base::EndsWith(app_url_host, "plus.sandbox.google.com",
1015 base::CompareCase::INSENSITIVE_ASCII)) &&
1016 manifest_url.DomainIs("ssl.gstatic.com") &&
1017 (manifest_url_path.find("s2/oz/nacl/") == 1 ||
1018 manifest_url_path.find("photos/nacl/") == 1);
1020 std::string manifest_fs_host;
1021 if (manifest_url.SchemeIsFileSystem() && manifest_url.inner_url()) {
1022 manifest_fs_host = manifest_url.inner_url()->host();
1024 bool is_hangouts_app =
1025 // Whitelisted apps must be served over secure scheme.
1026 app_url.SchemeIsCryptographic() && manifest_url.SchemeIsFileSystem() &&
1027 manifest_url.inner_url()->SchemeIsCryptographic() &&
1028 (base::EndsWith(app_url_host, "talkgadget.google.com",
1029 base::CompareCase::INSENSITIVE_ASCII) ||
1030 base::EndsWith(app_url_host, "plus.google.com",
1031 base::CompareCase::INSENSITIVE_ASCII) ||
1032 base::EndsWith(app_url_host, "plus.sandbox.google.com",
1033 base::CompareCase::INSENSITIVE_ASCII)) &&
1034 // The manifest must be loaded from the host's FileSystem.
1035 (manifest_fs_host == app_url_host);
1037 bool is_whitelisted_app = is_photo_app || is_hangouts_app;
1039 bool is_invoked_by_webstore_installed_extension = false;
1040 bool is_extension_unrestricted = false;
1041 bool is_extension_force_installed = false;
1042 #if defined(ENABLE_EXTENSIONS)
1043 bool is_extension_from_webstore = extension && extension->from_webstore();
1045 bool is_invoked_by_extension = app_url.SchemeIs("chrome-extension");
1046 bool is_invoked_by_hosted_app = extension &&
1047 extension->is_hosted_app() &&
1048 extension->web_extent().MatchesURL(app_url);
1050 is_invoked_by_webstore_installed_extension = is_extension_from_webstore &&
1051 (is_invoked_by_extension || is_invoked_by_hosted_app);
1053 // Allow built-in extensions and developer mode extensions.
1054 is_extension_unrestricted = extension &&
1055 (extensions::Manifest::IsUnpackedLocation(extension->location()) ||
1056 extensions::Manifest::IsComponentLocation(extension->location()));
1057 // Allow extensions force installed by admin policy.
1058 is_extension_force_installed = extension &&
1059 extensions::Manifest::IsPolicyLocation(extension->location());
1060 #endif // defined(ENABLE_EXTENSIONS)
1062 // Allow NaCl under any of the following circumstances:
1063 // 1) An app or URL is explictly whitelisted above.
1064 // 2) An extension is loaded unpacked or built-in (component) to Chrome.
1065 // 3) An extension is force installed by policy.
1066 // 4) An extension is installed from the webstore, and invoked in that
1067 // context (hosted app URL or chrome-extension:// scheme).
1068 // 5) --enable-nacl is set.
1069 bool is_nacl_allowed_by_location =
1070 is_whitelisted_web_ui ||
1071 is_whitelisted_app ||
1072 is_extension_unrestricted ||
1073 is_extension_force_installed ||
1074 is_invoked_by_webstore_installed_extension;
1075 bool is_nacl_allowed = is_nacl_allowed_by_location || is_nacl_unrestricted;
1076 if (is_nacl_allowed) {
1077 // Make sure that PPAPI 'dev' interfaces are only available for unpacked
1078 // and component extensions. Also allow dev interfaces when --enable-nacl
1079 // is set, but do not allow --enable-nacl to provide dev interfaces to
1080 // webstore installed and other normally allowed URLs.
1081 WebString dev_attribute = WebString::fromUTF8("@dev");
1082 if (is_extension_unrestricted ||
1083 (is_nacl_unrestricted && !is_nacl_allowed_by_location)) {
1084 // Add the special '@dev' attribute.
1085 std::vector<base::string16> param_names;
1086 std::vector<base::string16> param_values;
1087 param_names.push_back(dev_attribute);
1088 param_values.push_back(WebString());
1089 AppendParams(
1090 param_names,
1091 param_values,
1092 &params->attributeNames,
1093 &params->attributeValues);
1094 } else {
1095 // If the params somehow contain '@dev', remove it.
1096 size_t attribute_count = params->attributeNames.size();
1097 for (size_t i = 0; i < attribute_count; ++i) {
1098 if (params->attributeNames[i].equals(dev_attribute))
1099 params->attributeNames[i] = WebString();
1103 return is_nacl_allowed;
1105 #endif // defined(DISABLE_NACL)
1107 bool ChromeContentRendererClient::HasErrorPage(int http_status_code,
1108 std::string* error_domain) {
1109 // Use an internal error page, if we have one for the status code.
1110 if (!LocalizedError::HasStrings(LocalizedError::kHttpErrorDomain,
1111 http_status_code)) {
1112 return false;
1115 *error_domain = LocalizedError::kHttpErrorDomain;
1116 return true;
1119 bool ChromeContentRendererClient::ShouldSuppressErrorPage(
1120 content::RenderFrame* render_frame,
1121 const GURL& url) {
1122 // Unit tests for ChromeContentRendererClient pass a NULL RenderFrame here.
1123 // Unfortunately it's very difficult to construct a mock RenderView, so skip
1124 // this functionality in this case.
1125 if (render_frame) {
1126 content::RenderView* render_view = render_frame->GetRenderView();
1127 content::RenderFrame* main_render_frame = render_view->GetMainRenderFrame();
1128 blink::WebFrame* web_frame = render_frame->GetWebFrame();
1129 NetErrorHelper* net_error_helper = NetErrorHelper::Get(main_render_frame);
1130 if (net_error_helper->ShouldSuppressErrorPage(web_frame, url))
1131 return true;
1133 // Do not flash an error page if the Instant new tab page fails to load.
1134 return SearchBouncer::GetInstance()->IsNewTabPage(url);
1137 void ChromeContentRendererClient::GetNavigationErrorStrings(
1138 content::RenderView* render_view,
1139 blink::WebFrame* frame,
1140 const blink::WebURLRequest& failed_request,
1141 const blink::WebURLError& error,
1142 std::string* error_html,
1143 base::string16* error_description) {
1144 const GURL failed_url = error.unreachableURL;
1146 bool is_post = base::EqualsASCII(
1147 base::StringPiece16(failed_request.httpMethod()), "POST");
1149 if (error_html) {
1150 // TODO(ellyjones): change GetNavigationErrorStrings to take a RenderFrame
1151 // instead of a RenderView, then pass that in.
1152 // This is safe for now because we only install the NetErrorHelper on the
1153 // main render frame anyway; see the TODO(ellyjones) in
1154 // RenderFrameCreated.
1155 content::RenderFrame* main_render_frame = render_view->GetMainRenderFrame();
1156 NetErrorHelper* helper = NetErrorHelper::Get(main_render_frame);
1157 helper->GetErrorHTML(frame, error, is_post, error_html);
1160 if (error_description)
1161 *error_description = LocalizedError::GetErrorDetails(error, is_post);
1164 bool ChromeContentRendererClient::RunIdleHandlerWhenWidgetsHidden() {
1165 #if defined(ENABLE_EXTENSIONS)
1166 return !IsStandaloneExtensionProcess();
1167 #else
1168 return true;
1169 #endif
1172 bool ChromeContentRendererClient::AllowPopup() {
1173 #if defined(ENABLE_EXTENSIONS)
1174 extensions::ScriptContext* current_context =
1175 extension_dispatcher_->script_context_set().GetCurrent();
1176 if (!current_context || !current_context->extension())
1177 return false;
1178 // See http://crbug.com/117446 for the subtlety of this check.
1179 switch (current_context->context_type()) {
1180 case extensions::Feature::UNSPECIFIED_CONTEXT:
1181 case extensions::Feature::WEB_PAGE_CONTEXT:
1182 case extensions::Feature::UNBLESSED_EXTENSION_CONTEXT:
1183 case extensions::Feature::WEBUI_CONTEXT:
1184 return false;
1185 case extensions::Feature::BLESSED_EXTENSION_CONTEXT:
1186 case extensions::Feature::CONTENT_SCRIPT_CONTEXT:
1187 return true;
1188 case extensions::Feature::BLESSED_WEB_PAGE_CONTEXT:
1189 return !current_context->web_frame()->parent();
1191 NOTREACHED();
1192 #endif
1193 return false;
1196 bool ChromeContentRendererClient::ShouldFork(blink::WebLocalFrame* frame,
1197 const GURL& url,
1198 const std::string& http_method,
1199 bool is_initial_navigation,
1200 bool is_server_redirect,
1201 bool* send_referrer) {
1202 DCHECK(!frame->parent());
1204 // If this is the Instant process, fork all navigations originating from the
1205 // renderer. The destination page will then be bucketed back to this Instant
1206 // process if it is an Instant url, or to another process if not. Conversely,
1207 // fork if this is a non-Instant process navigating to an Instant url, so that
1208 // such navigations can also be bucketed into an Instant renderer.
1209 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1210 switches::kInstantProcess) ||
1211 SearchBouncer::GetInstance()->ShouldFork(url)) {
1212 *send_referrer = true;
1213 return true;
1216 // For now, we skip the rest for POST submissions. This is because
1217 // http://crbug.com/101395 is more likely to cause compatibility issues
1218 // with hosted apps and extensions than WebUI pages. We will remove this
1219 // check when cross-process POST submissions are supported.
1220 if (http_method != "GET")
1221 return false;
1223 // If |url| matches one of the prerendered URLs, stop this navigation and try
1224 // to swap in the prerendered page on the browser process. If the prerendered
1225 // page no longer exists by the time the OpenURL IPC is handled, a normal
1226 // navigation is attempted.
1227 if (prerender_dispatcher_.get() &&
1228 prerender_dispatcher_->IsPrerenderURL(url)) {
1229 *send_referrer = true;
1230 return true;
1233 #if defined(ENABLE_EXTENSIONS)
1234 const extensions::ExtensionSet* extensions =
1235 extension_dispatcher_->extensions();
1237 // Determine if the new URL is an extension (excluding bookmark apps).
1238 const Extension* new_url_extension = extensions::GetNonBookmarkAppExtension(
1239 *extensions, url);
1240 bool is_extension_url = !!new_url_extension;
1242 // If the navigation would cross an app extent boundary, we also need
1243 // to defer to the browser to ensure process isolation. This is not necessary
1244 // for server redirects, which will be transferred to a new process by the
1245 // browser process when they are ready to commit. It is necessary for client
1246 // redirects, which won't be transferred in the same way.
1247 if (!is_server_redirect &&
1248 CrossesExtensionExtents(frame, url, *extensions, is_extension_url,
1249 is_initial_navigation)) {
1250 // Include the referrer in this case since we're going from a hosted web
1251 // page. (the packaged case is handled previously by the extension
1252 // navigation test)
1253 *send_referrer = true;
1255 const Extension* extension =
1256 extension_dispatcher_->extensions()->GetExtensionOrAppByURL(url);
1257 if (extension && extension->is_app()) {
1258 extensions::RecordAppLaunchType(
1259 extension_misc::APP_LAUNCH_CONTENT_NAVIGATION, extension->GetType());
1261 return true;
1264 // If this is a reload, check whether it has the wrong process type. We
1265 // should send it to the browser if it's an extension URL (e.g., hosted app)
1266 // in a normal process, or if it's a process for an extension that has been
1267 // uninstalled. Without --site-per-process mode, we never fork processes for
1268 // subframes, so this check only makes sense for top-level frames.
1269 // TODO(alexmos,nasko): Figure out how this check should work when reloading
1270 // subframes in --site-per-process mode.
1271 if (!frame->parent() && frame->document().url() == url) {
1272 if (is_extension_url != IsStandaloneExtensionProcess())
1273 return true;
1275 #endif // defined(ENABLE_EXTENSIONS)
1277 return false;
1280 bool ChromeContentRendererClient::WillSendRequest(
1281 blink::WebFrame* frame,
1282 ui::PageTransition transition_type,
1283 const GURL& url,
1284 const GURL& first_party_for_cookies,
1285 GURL* new_url) {
1286 // Check whether the request should be allowed. If not allowed, we reset the
1287 // URL to something invalid to prevent the request and cause an error.
1288 #if defined(ENABLE_EXTENSIONS)
1289 if (url.SchemeIs(extensions::kExtensionScheme) &&
1290 !extensions::ResourceRequestPolicy::CanRequestResource(
1291 url,
1292 frame,
1293 transition_type,
1294 extension_dispatcher_->extensions())) {
1295 *new_url = GURL(chrome::kExtensionInvalidRequestURL);
1296 return true;
1299 if (url.SchemeIs(extensions::kExtensionResourceScheme) &&
1300 !extensions::ResourceRequestPolicy::CanRequestExtensionResourceScheme(
1301 url,
1302 frame)) {
1303 *new_url = GURL(chrome::kExtensionResourceInvalidRequestURL);
1304 return true;
1306 #endif
1308 const content::RenderView* render_view =
1309 content::RenderView::FromWebView(frame->view());
1310 SearchBox* search_box = SearchBox::Get(render_view);
1311 if (search_box && url.SchemeIs(chrome::kChromeSearchScheme)) {
1312 SearchBox::ImageSourceType type = SearchBox::NONE;
1313 if (url.host() == chrome::kChromeUIFaviconHost)
1314 type = SearchBox::FAVICON;
1315 else if (url.host() == chrome::kChromeUILargeIconHost)
1316 type = SearchBox::LARGE_ICON;
1317 else if (url.host() == chrome::kChromeUIFallbackIconHost)
1318 type = SearchBox::FALLBACK_ICON;
1319 else if (url.host() == chrome::kChromeUIThumbnailHost)
1320 type = SearchBox::THUMB;
1321 if (type != SearchBox::NONE)
1322 return search_box->GenerateImageURLFromTransientURL(url, type, new_url);
1325 return false;
1328 unsigned long long ChromeContentRendererClient::VisitedLinkHash(
1329 const char* canonical_url, size_t length) {
1330 return visited_link_slave_->ComputeURLFingerprint(canonical_url, length);
1333 bool ChromeContentRendererClient::IsLinkVisited(unsigned long long link_hash) {
1334 return visited_link_slave_->IsVisited(link_hash);
1337 blink::WebPrescientNetworking*
1338 ChromeContentRendererClient::GetPrescientNetworking() {
1339 return prescient_networking_dispatcher_.get();
1342 bool ChromeContentRendererClient::ShouldOverridePageVisibilityState(
1343 const content::RenderFrame* render_frame,
1344 blink::WebPageVisibilityState* override_state) {
1345 if (!prerender::PrerenderHelper::IsPrerendering(render_frame))
1346 return false;
1348 *override_state = blink::WebPageVisibilityStatePrerender;
1349 return true;
1352 #if defined(ENABLE_EXTENSIONS)
1353 void ChromeContentRendererClient::SetExtensionDispatcherForTest(
1354 extensions::Dispatcher* extension_dispatcher) {
1355 extension_dispatcher_.reset(extension_dispatcher);
1356 permissions_policy_delegate_.reset(
1357 new extensions::RendererPermissionsPolicyDelegate(
1358 extension_dispatcher_.get()));
1361 extensions::Dispatcher*
1362 ChromeContentRendererClient::GetExtensionDispatcherForTest() {
1363 return extension_dispatcher_.get();
1366 bool ChromeContentRendererClient::CrossesExtensionExtents(
1367 blink::WebLocalFrame* frame,
1368 const GURL& new_url,
1369 const extensions::ExtensionSet& extensions,
1370 bool is_extension_url,
1371 bool is_initial_navigation) {
1372 DCHECK(!frame->parent());
1373 GURL old_url(frame->document().url());
1375 // If old_url is still empty and this is an initial navigation, then this is
1376 // a window.open operation. We should look at the opener URL. Note that the
1377 // opener is a local frame in this case.
1378 if (is_initial_navigation && old_url.is_empty() && frame->opener()) {
1379 WebLocalFrame* opener_frame = frame->opener()->toWebLocalFrame();
1381 // If we're about to open a normal web page from a same-origin opener stuck
1382 // in an extension process, we want to keep it in process to allow the
1383 // opener to script it.
1384 WebDocument opener_document = opener_frame->document();
1385 WebSecurityOrigin opener_origin = opener_document.securityOrigin();
1386 bool opener_is_extension_url =
1387 !opener_origin.isUnique() && extensions.GetExtensionOrAppByURL(
1388 opener_document.url()) != NULL;
1389 if (!is_extension_url &&
1390 !opener_is_extension_url &&
1391 IsStandaloneExtensionProcess() &&
1392 opener_origin.canRequest(WebURL(new_url)))
1393 return false;
1395 // In all other cases, we want to compare against the URL that determines
1396 // the type of process. In default Chrome, that's the URL of the opener's
1397 // top frame and not the opener frame itself. In --site-per-process, we
1398 // can use the opener frame itself.
1399 // TODO(nick): Either wire this up to SiteIsolationPolicy, or to state on
1400 // |opener_frame|/its ancestors.
1401 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1402 switches::kSitePerProcess))
1403 old_url = opener_frame->document().url();
1404 else
1405 old_url = opener_frame->top()->document().url();
1408 // Only consider keeping non-app URLs in an app process if this window
1409 // has an opener (in which case it might be an OAuth popup that tries to
1410 // script an iframe within the app).
1411 bool should_consider_workaround = !!frame->opener();
1413 return extensions::CrossesExtensionProcessBoundary(
1414 extensions, old_url, new_url, should_consider_workaround);
1416 #endif // defined(ENABLE_EXTENSIONS)
1418 #if defined(ENABLE_SPELLCHECK)
1419 void ChromeContentRendererClient::SetSpellcheck(SpellCheck* spellcheck) {
1420 RenderThread* thread = RenderThread::Get();
1421 if (spellcheck_.get() && thread)
1422 thread->RemoveObserver(spellcheck_.get());
1423 spellcheck_.reset(spellcheck);
1424 SpellCheckReplacer replacer(spellcheck_.get());
1425 content::RenderView::ForEach(&replacer);
1426 if (thread)
1427 thread->AddObserver(spellcheck_.get());
1429 #endif
1431 // static
1432 bool ChromeContentRendererClient::WasWebRequestUsedBySomeExtensions() {
1433 #if defined(ENABLE_EXTENSIONS)
1434 return g_current_client->extension_dispatcher_
1435 ->WasWebRequestUsedBySomeExtensions();
1436 #else
1437 return false;
1438 #endif
1441 const void* ChromeContentRendererClient::CreatePPAPIInterface(
1442 const std::string& interface_name) {
1443 #if defined(ENABLE_PLUGINS) && !defined(DISABLE_NACL)
1444 if (interface_name == PPB_NACL_PRIVATE_INTERFACE)
1445 return nacl::GetNaClPrivateInterface();
1446 #endif
1447 return NULL;
1450 bool ChromeContentRendererClient::IsExternalPepperPlugin(
1451 const std::string& module_name) {
1452 // TODO(bbudge) remove this when the trusted NaCl plugin has been removed.
1453 // We must defer certain plugin events for NaCl instances since we switch
1454 // from the in-process to the out-of-process proxy after instantiating them.
1455 return module_name == "Native Client";
1458 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
1459 bool ChromeContentRendererClient::IsExtensionOrSharedModuleWhitelisted(
1460 const GURL& url, const std::set<std::string>& whitelist) {
1461 const extensions::ExtensionSet* extension_set =
1462 g_current_client->extension_dispatcher_->extensions();
1463 return chrome::IsExtensionOrSharedModuleWhitelisted(url, extension_set,
1464 whitelist);
1466 #endif
1468 blink::WebSpeechSynthesizer*
1469 ChromeContentRendererClient::OverrideSpeechSynthesizer(
1470 blink::WebSpeechSynthesizerClient* client) {
1471 return new TtsDispatcher(client);
1474 bool ChromeContentRendererClient::AllowPepperMediaStreamAPI(
1475 const GURL& url) {
1476 #if !defined(OS_ANDROID)
1477 // Allow only the Hangouts app to use the MediaStream APIs. It's OK to check
1478 // the whitelist in the renderer, since we're only preventing access until
1479 // these APIs are public and stable.
1480 std::string url_host = url.host();
1481 if (url.SchemeIs("https") &&
1482 (base::EndsWith(url_host, "talkgadget.google.com",
1483 base::CompareCase::INSENSITIVE_ASCII) ||
1484 base::EndsWith(url_host, "plus.google.com",
1485 base::CompareCase::INSENSITIVE_ASCII) ||
1486 base::EndsWith(url_host, "plus.sandbox.google.com",
1487 base::CompareCase::INSENSITIVE_ASCII)) &&
1488 base::StartsWith(url.path(), "/hangouts/",
1489 base::CompareCase::INSENSITIVE_ASCII)) {
1490 return true;
1492 // Allow access for tests.
1493 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1494 switches::kEnablePepperTesting)) {
1495 return true;
1497 #endif // !defined(OS_ANDROID)
1498 return false;
1501 void ChromeContentRendererClient::AddKeySystems(
1502 std::vector<media::KeySystemInfo>* key_systems) {
1503 AddChromeKeySystems(key_systems);
1506 bool ChromeContentRendererClient::ShouldReportDetailedMessageForSource(
1507 const base::string16& source) const {
1508 #if defined(ENABLE_EXTENSIONS)
1509 return extensions::IsSourceFromAnExtension(source);
1510 #else
1511 return false;
1512 #endif
1515 bool ChromeContentRendererClient::ShouldGatherSiteIsolationStats() const {
1516 // Site isolation stats are gathered currently for non-extension renderer
1517 // processes running a normal web page from the Internet.
1518 // TODO(nick): https://crbug.com/268640 Gather stats for extension processes
1519 // too; we would need to check the extension's manifest to know which sites
1520 // it's allowed to access.
1521 #if defined(ENABLE_EXTENSIONS)
1522 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
1523 return !command_line->HasSwitch(extensions::switches::kExtensionProcess);
1524 #else
1525 return true;
1526 #endif
1529 blink::WebWorkerContentSettingsClientProxy*
1530 ChromeContentRendererClient::CreateWorkerContentSettingsClientProxy(
1531 content::RenderFrame* render_frame,
1532 blink::WebFrame* frame) {
1533 return new WorkerContentSettingsClientProxy(render_frame, frame);
1536 bool ChromeContentRendererClient::IsPluginAllowedToUseDevChannelAPIs() {
1537 #if defined(ENABLE_PLUGINS)
1538 // Allow access for tests.
1539 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1540 switches::kEnablePepperTesting)) {
1541 return true;
1544 version_info::Channel channel = chrome::GetChannel();
1545 // Allow dev channel APIs to be used on "Canary", "Dev", and "Unknown"
1546 // releases of Chrome. Permitting "Unknown" allows these APIs to be used on
1547 // Chromium builds as well.
1548 return channel <= version_info::Channel::DEV;
1549 #else
1550 return false;
1551 #endif
1554 bool ChromeContentRendererClient::IsPluginAllowedToUseCameraDeviceAPI(
1555 const GURL& url) {
1556 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
1557 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1558 switches::kEnablePepperTesting))
1559 return true;
1561 if (IsExtensionOrSharedModuleWhitelisted(url, allowed_camera_device_origins_))
1562 return true;
1563 #endif
1565 return false;
1568 bool ChromeContentRendererClient::IsPluginAllowedToUseCompositorAPI(
1569 const GURL& url) {
1570 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
1571 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1572 switches::kEnablePepperTesting))
1573 return true;
1574 if (IsExtensionOrSharedModuleWhitelisted(url, allowed_compositor_origins_))
1575 return true;
1577 version_info::Channel channel = chrome::GetChannel();
1578 return channel <= version_info::Channel::DEV;
1579 #else
1580 return false;
1581 #endif
1584 content::BrowserPluginDelegate*
1585 ChromeContentRendererClient::CreateBrowserPluginDelegate(
1586 content::RenderFrame* render_frame,
1587 const std::string& mime_type,
1588 const GURL& original_url) {
1589 #if defined(ENABLE_EXTENSIONS)
1590 if (mime_type == content::kBrowserPluginMimeType) {
1591 return new extensions::ExtensionsGuestViewContainer(render_frame);
1592 } else {
1593 return new extensions::MimeHandlerViewContainer(
1594 render_frame, mime_type, original_url);
1596 #else
1597 return NULL;
1598 #endif
1601 void ChromeContentRendererClient::RecordRappor(const std::string& metric,
1602 const std::string& sample) {
1603 RenderThread::Get()->Send(new ChromeViewHostMsg_RecordRappor(metric, sample));
1606 void ChromeContentRendererClient::RecordRapporURL(const std::string& metric,
1607 const GURL& url) {
1608 RenderThread::Get()->Send(new ChromeViewHostMsg_RecordRapporURL(metric, url));
1611 scoped_ptr<blink::WebAppBannerClient>
1612 ChromeContentRendererClient::CreateAppBannerClient(
1613 content::RenderFrame* render_frame) {
1614 return scoped_ptr<blink::WebAppBannerClient>(
1615 new AppBannerClient(render_frame));
1618 void ChromeContentRendererClient::AddImageContextMenuProperties(
1619 const blink::WebURLResponse& response,
1620 std::map<std::string, std::string>* properties) {
1621 DCHECK(properties);
1622 WebString header_key(ASCIIToUTF16(
1623 data_reduction_proxy::chrome_proxy_header()));
1624 if (!response.httpHeaderField(header_key).isNull() &&
1625 response.httpHeaderField(header_key).utf8().find(
1626 data_reduction_proxy::chrome_proxy_lo_fi_directive()) !=
1627 std::string::npos) {
1628 (*properties)[data_reduction_proxy::chrome_proxy_header()] =
1629 data_reduction_proxy::chrome_proxy_lo_fi_directive();