Componentize ShortcutsBackend
[chromium-blink-merge.git] / chrome / renderer / chrome_content_renderer_client.cc
blobb879e3e4afeae593e863600ecd13f69271969c7b
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/chrome_paths.h"
18 #include "chrome/common/chrome_switches.h"
19 #include "chrome/common/chrome_version_info.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/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/WebPluginPlaceholder.h"
96 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
97 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
98 #include "ui/base/l10n/l10n_util.h"
99 #include "ui/base/layout.h"
100 #include "ui/base/resource/resource_bundle.h"
101 #include "ui/base/webui/jstemplate_builder.h"
102 #include "widevine_cdm_version.h" // In SHARED_INTERMEDIATE_DIR.
104 #if !defined(DISABLE_NACL)
105 #include "components/nacl/common/nacl_constants.h"
106 #include "components/nacl/renderer/nacl_helper.h"
107 #endif
109 #if defined(ENABLE_EXTENSIONS)
110 #include "chrome/common/extensions/chrome_extensions_client.h"
111 #include "chrome/common/extensions/extension_process_policy.h"
112 #include "chrome/renderer/extensions/chrome_extensions_dispatcher_delegate.h"
113 #include "chrome/renderer/extensions/chrome_extensions_renderer_client.h"
114 #include "chrome/renderer/extensions/renderer_permissions_policy_delegate.h"
115 #include "chrome/renderer/extensions/resource_request_policy.h"
116 #include "chrome/renderer/media/cast_ipc_dispatcher.h"
117 #include "extensions/common/extension.h"
118 #include "extensions/common/extension_set.h"
119 #include "extensions/common/extension_urls.h"
120 #include "extensions/common/switches.h"
121 #include "extensions/renderer/dispatcher.h"
122 #include "extensions/renderer/extension_frame_helper.h"
123 #include "extensions/renderer/extension_helper.h"
124 #include "extensions/renderer/extensions_render_frame_observer.h"
125 #include "extensions/renderer/guest_view/extensions_guest_view_container.h"
126 #include "extensions/renderer/guest_view/extensions_guest_view_container_dispatcher.h"
127 #include "extensions/renderer/guest_view/mime_handler_view/mime_handler_view_container.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 #if defined(OS_WIN)
158 #include "chrome_elf/blacklist/blacklist.h"
159 #endif
161 using autofill::AutofillAgent;
162 using autofill::PasswordAutofillAgent;
163 using autofill::PasswordGenerationAgent;
164 using base::ASCIIToUTF16;
165 using base::UserMetricsAction;
166 using content::PluginInstanceThrottler;
167 using content::RenderFrame;
168 using content::RenderThread;
169 using content::WebPluginInfo;
170 using extensions::Extension;
171 using blink::WebCache;
172 using blink::WebConsoleMessage;
173 using blink::WebDataSource;
174 using blink::WebDocument;
175 using blink::WebLocalFrame;
176 using blink::WebPlugin;
177 using blink::WebPluginParams;
178 using blink::WebSecurityOrigin;
179 using blink::WebSecurityPolicy;
180 using blink::WebString;
181 using blink::WebURL;
182 using blink::WebURLError;
183 using blink::WebURLRequest;
184 using blink::WebURLResponse;
185 using blink::WebVector;
187 namespace {
189 ChromeContentRendererClient* g_current_client;
191 // Whitelist PPAPI for Android Runtime for Chromium. (See crbug.com/383937)
192 #if defined(ENABLE_PLUGINS)
193 const char* const kPredefinedAllowedCameraDeviceOrigins[] = {
194 "6EAED1924DB611B6EEF2A664BD077BE7EAD33B8F",
195 "4EB74897CB187C7633357C2FE832E0AD6A44883A"
198 const char* const kPredefinedAllowedCompositorOrigins[] = {
199 "6EAED1924DB611B6EEF2A664BD077BE7EAD33B8F",
200 "4EB74897CB187C7633357C2FE832E0AD6A44883A"
202 #endif
204 #if defined(ENABLE_PLUGINS)
205 void AppendParams(const std::vector<base::string16>& additional_names,
206 const std::vector<base::string16>& additional_values,
207 WebVector<WebString>* existing_names,
208 WebVector<WebString>* existing_values) {
209 DCHECK(additional_names.size() == additional_values.size());
210 DCHECK(existing_names->size() == existing_values->size());
212 size_t existing_size = existing_names->size();
213 size_t total_size = existing_size + additional_names.size();
215 WebVector<WebString> names(total_size);
216 WebVector<WebString> values(total_size);
218 for (size_t i = 0; i < existing_size; ++i) {
219 names[i] = (*existing_names)[i];
220 values[i] = (*existing_values)[i];
223 for (size_t i = 0; i < additional_names.size(); ++i) {
224 names[existing_size + i] = additional_names[i];
225 values[existing_size + i] = additional_values[i];
228 existing_names->swap(names);
229 existing_values->swap(values);
232 // For certain sandboxed Pepper plugins, use the JavaScript Content Settings.
233 bool ShouldUseJavaScriptSettingForPlugin(const WebPluginInfo& plugin) {
234 if (plugin.type != WebPluginInfo::PLUGIN_TYPE_PEPPER_IN_PROCESS &&
235 plugin.type != WebPluginInfo::PLUGIN_TYPE_PEPPER_OUT_OF_PROCESS) {
236 return false;
239 #if !defined(DISABLE_NACL)
240 // Treat Native Client invocations like JavaScript.
241 if (plugin.name == ASCIIToUTF16(nacl::kNaClPluginName))
242 return true;
243 #endif
245 #if defined(WIDEVINE_CDM_AVAILABLE) && defined(ENABLE_PEPPER_CDMS)
246 // Treat CDM invocations like JavaScript.
247 if (plugin.name == ASCIIToUTF16(kWidevineCdmDisplayName)) {
248 DCHECK(plugin.type == WebPluginInfo::PLUGIN_TYPE_PEPPER_OUT_OF_PROCESS);
249 return true;
251 #endif // defined(WIDEVINE_CDM_AVAILABLE) && defined(ENABLE_PEPPER_CDMS)
253 return false;
255 #endif // defined(ENABLE_PLUGINS)
257 #if defined(ENABLE_SPELLCHECK)
258 class SpellCheckReplacer : public content::RenderViewVisitor {
259 public:
260 explicit SpellCheckReplacer(SpellCheck* spellcheck)
261 : spellcheck_(spellcheck) {}
262 bool Visit(content::RenderView* render_view) override;
264 private:
265 SpellCheck* spellcheck_; // New shared spellcheck for all views. Weak Ptr.
266 DISALLOW_COPY_AND_ASSIGN(SpellCheckReplacer);
269 bool SpellCheckReplacer::Visit(content::RenderView* render_view) {
270 SpellCheckProvider* provider = SpellCheckProvider::Get(render_view);
271 DCHECK(provider);
272 provider->set_spellcheck(spellcheck_);
273 return true;
275 #endif
277 #if defined(ENABLE_EXTENSIONS)
278 void IsGuestViewApiAvailableToScriptContext(
279 bool* api_is_available,
280 extensions::ScriptContext* context) {
281 if (context->GetAvailability("guestViewInternal").is_available()) {
282 *api_is_available = true;
285 #endif
287 #if defined(ENABLE_PLUGINS)
288 // Presence of the poster param within plugin object tags.
289 // These numeric values are used in UMA logs; do not change them.
290 enum PosterParamPresence {
291 POSTER_PRESENCE_NO_PARAM_PPS_DISABLED = 0,
292 POSTER_PRESENCE_NO_PARAM_PPS_ENABLED = 1,
293 POSTER_PRESENCE_PARAM_EXISTS_PPS_DISABLED = 2,
294 POSTER_PRESENCE_PARAM_EXISTS_PPS_ENABLED = 3,
295 POSTER_PRESENCE_NUM_ITEMS
298 const char kPluginPowerSaverPosterParamPresenceHistogram[] =
299 "Plugin.PowerSaver.PosterParamPresence";
301 void RecordPosterParamPresence(PosterParamPresence presence) {
302 UMA_HISTOGRAM_ENUMERATION(kPluginPowerSaverPosterParamPresenceHistogram,
303 presence, POSTER_PRESENCE_NUM_ITEMS);
306 void TrackPosterParamPresence(const blink::WebPluginParams& params,
307 bool power_saver_enabled) {
308 DCHECK_EQ(params.attributeNames.size(), params.attributeValues.size());
310 for (size_t i = 0; i < params.attributeNames.size(); ++i) {
311 if (params.attributeNames[i].utf8() == "poster") {
312 if (power_saver_enabled)
313 RecordPosterParamPresence(POSTER_PRESENCE_PARAM_EXISTS_PPS_ENABLED);
314 else
315 RecordPosterParamPresence(POSTER_PRESENCE_PARAM_EXISTS_PPS_DISABLED);
317 return;
321 if (power_saver_enabled)
322 RecordPosterParamPresence(POSTER_PRESENCE_NO_PARAM_PPS_ENABLED);
323 else
324 RecordPosterParamPresence(POSTER_PRESENCE_NO_PARAM_PPS_DISABLED);
327 std::string GetPluginInstancePosterAttribute(
328 const blink::WebPluginParams& params) {
329 DCHECK_EQ(params.attributeNames.size(), params.attributeValues.size());
331 for (size_t i = 0; i < params.attributeNames.size(); ++i) {
332 if (params.attributeNames[i].utf8() == "poster" &&
333 !params.attributeValues[i].isEmpty()) {
334 return params.attributeValues[i].utf8();
337 return std::string();
339 #endif
341 #if defined(ENABLE_EXTENSIONS)
342 bool IsStandaloneExtensionProcess() {
343 return base::CommandLine::ForCurrentProcess()->HasSwitch(
344 extensions::switches::kExtensionProcess);
346 #endif
347 } // namespace
349 ChromeContentRendererClient::ChromeContentRendererClient() {
350 g_current_client = this;
352 #if defined(ENABLE_EXTENSIONS)
353 extensions::ExtensionsClient::Set(
354 extensions::ChromeExtensionsClient::GetInstance());
355 extensions::ExtensionsRendererClient::Set(
356 ChromeExtensionsRendererClient::GetInstance());
357 #endif
358 #if defined(ENABLE_PLUGINS)
359 for (size_t i = 0; i < arraysize(kPredefinedAllowedCameraDeviceOrigins); ++i)
360 allowed_camera_device_origins_.insert(
361 kPredefinedAllowedCameraDeviceOrigins[i]);
362 for (size_t i = 0; i < arraysize(kPredefinedAllowedCompositorOrigins); ++i)
363 allowed_compositor_origins_.insert(kPredefinedAllowedCompositorOrigins[i]);
364 #endif
367 ChromeContentRendererClient::~ChromeContentRendererClient() {
368 g_current_client = NULL;
371 void ChromeContentRendererClient::RenderThreadStarted() {
372 RenderThread* thread = RenderThread::Get();
374 chrome_observer_.reset(new ChromeRenderProcessObserver());
375 web_cache_observer_.reset(new web_cache::WebCacheRenderProcessObserver());
377 #if defined(ENABLE_EXTENSIONS)
378 extension_dispatcher_delegate_.reset(
379 new ChromeExtensionsDispatcherDelegate());
380 // ChromeRenderViewTest::SetUp() creates its own ExtensionDispatcher and
381 // injects it using SetExtensionDispatcher(). Don't overwrite it.
382 if (!extension_dispatcher_) {
383 extension_dispatcher_.reset(
384 new extensions::Dispatcher(extension_dispatcher_delegate_.get()));
386 permissions_policy_delegate_.reset(
387 new extensions::RendererPermissionsPolicyDelegate(
388 extension_dispatcher_.get()));
389 guest_view_container_dispatcher_.reset(
390 new extensions::ExtensionsGuestViewContainerDispatcher());
391 #endif
393 prescient_networking_dispatcher_.reset(
394 new network_hints::PrescientNetworkingDispatcher());
395 #if defined(ENABLE_SPELLCHECK)
396 // ChromeRenderViewTest::SetUp() creates a Spellcheck and injects it using
397 // SetSpellcheck(). Don't overwrite it.
398 if (!spellcheck_) {
399 spellcheck_.reset(new SpellCheck());
400 thread->AddObserver(spellcheck_.get());
402 #endif
403 visited_link_slave_.reset(new visitedlink::VisitedLinkSlave());
404 #if defined(FULL_SAFE_BROWSING)
405 phishing_classifier_.reset(safe_browsing::PhishingClassifierFilter::Create());
406 #endif
407 prerender_dispatcher_.reset(new prerender::PrerenderDispatcher());
408 #if defined(ENABLE_WEBRTC)
409 webrtc_logging_message_filter_ = new WebRtcLoggingMessageFilter(
410 RenderThread::Get()->GetIOMessageLoopProxy());
411 #endif
412 search_bouncer_.reset(new SearchBouncer());
414 thread->AddObserver(chrome_observer_.get());
415 thread->AddObserver(web_cache_observer_.get());
416 #if defined(ENABLE_EXTENSIONS)
417 thread->AddObserver(extension_dispatcher_.get());
418 thread->AddObserver(guest_view_container_dispatcher_.get());
419 #endif
420 #if defined(FULL_SAFE_BROWSING)
421 thread->AddObserver(phishing_classifier_.get());
422 #endif
423 thread->AddObserver(visited_link_slave_.get());
424 thread->AddObserver(prerender_dispatcher_.get());
425 thread->AddObserver(search_bouncer_.get());
427 #if defined(ENABLE_WEBRTC)
428 thread->AddFilter(webrtc_logging_message_filter_.get());
429 #endif
430 #if defined(ENABLE_EXTENSIONS)
431 thread->AddFilter(new CastIPCDispatcher(
432 RenderThread::Get()->GetIOMessageLoopProxy()));
433 #endif
435 thread->RegisterExtension(extensions_v8::ExternalExtension::Get());
436 thread->RegisterExtension(extensions_v8::LoadTimesExtension::Get());
438 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
439 if (command_line->HasSwitch(switches::kEnableBenchmarking))
440 thread->RegisterExtension(extensions_v8::BenchmarkingExtension::Get());
441 if (command_line->HasSwitch(switches::kEnableNetBenchmarking))
442 thread->RegisterExtension(extensions_v8::NetBenchmarkingExtension::Get());
443 if (command_line->HasSwitch(switches::kInstantProcess))
444 thread->RegisterExtension(extensions_v8::SearchBoxExtension::Get());
446 // chrome-search: and chrome-distiller: pages should not be accessible by
447 // normal content, and should also be unable to script anything but themselves
448 // (to help limit the damage that a corrupt page could cause).
449 WebString chrome_search_scheme(ASCIIToUTF16(chrome::kChromeSearchScheme));
451 // The Instant process can only display the content but not read it. Other
452 // processes can't display it or read it.
453 if (!command_line->HasSwitch(switches::kInstantProcess))
454 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(chrome_search_scheme);
456 WebString dom_distiller_scheme(
457 ASCIIToUTF16(dom_distiller::kDomDistillerScheme));
458 // TODO(nyquist): Add test to ensure this happens when the flag is set.
459 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(dom_distiller_scheme);
461 #if defined(OS_CHROMEOS)
462 WebString external_file_scheme(ASCIIToUTF16(content::kExternalFileScheme));
463 WebSecurityPolicy::registerURLSchemeAsLocal(external_file_scheme);
464 #endif
466 #if defined(ENABLE_IPC_FUZZER)
467 if (command_line->HasSwitch(switches::kIpcDumpDirectory)) {
468 base::FilePath dump_directory =
469 command_line->GetSwitchValuePath(switches::kIpcDumpDirectory);
470 IPC::ChannelProxy::OutgoingMessageFilter* filter =
471 LoadExternalIPCDumper(dump_directory);
472 thread->GetChannel()->set_outgoing_message_filter(filter);
474 #endif
476 // chrome-search: pages should not be accessible by bookmarklets
477 // or javascript: URLs typed in the omnibox.
478 WebSecurityPolicy::registerURLSchemeAsNotAllowingJavascriptURLs(
479 chrome_search_scheme);
481 // chrome-search:, chrome-extension:, and chrome-extension-resource:
482 // resources shouldn't trigger insecure content warnings.
483 WebSecurityPolicy::registerURLSchemeAsSecure(chrome_search_scheme);
485 WebString extension_scheme(ASCIIToUTF16(extensions::kExtensionScheme));
486 WebSecurityPolicy::registerURLSchemeAsSecure(extension_scheme);
488 WebString extension_resource_scheme(
489 ASCIIToUTF16(extensions::kExtensionResourceScheme));
490 WebSecurityPolicy::registerURLSchemeAsSecure(extension_resource_scheme);
492 // chrome:, chrome-extension:, chrome-extension-resource: resources should be
493 // allowed to receive CORS requests.
494 WebSecurityPolicy::registerURLSchemeAsCORSEnabled(extension_scheme);
495 WebSecurityPolicy::registerURLSchemeAsCORSEnabled(extension_resource_scheme);
497 // chrome-extension: resources should bypass Content Security Policy checks
498 // when included in protected resources.
499 WebSecurityPolicy::registerURLSchemeAsBypassingContentSecurityPolicy(
500 extension_scheme);
501 WebSecurityPolicy::registerURLSchemeAsBypassingContentSecurityPolicy(
502 extension_resource_scheme);
504 #if defined(OS_WIN)
505 // Report if the renderer process has been patched by chrome_elf.
506 // TODO(csharp): Remove once the renderer is no longer getting
507 // patched this way.
508 if (blacklist::IsBlacklistInitialized())
509 UMA_HISTOGRAM_BOOLEAN("Blacklist.PatchedInRenderer", true);
510 #endif
511 #if defined(ENABLE_PRINT_PREVIEW)
512 pdf_print_client_.reset(new ChromePDFPrintClient());
513 pdf::PepperPDFHost::SetPrintClient(pdf_print_client_.get());
514 #endif
516 std::set<GURL> origins;
517 GetSecureOriginWhitelist(&origins);
518 for (const GURL& origin : origins) {
519 WebSecurityPolicy::addOriginTrustworthyWhiteList(
520 WebSecurityOrigin::create(origin));
524 void ChromeContentRendererClient::RenderFrameCreated(
525 content::RenderFrame* render_frame) {
526 new ChromeRenderFrameObserver(render_frame);
528 bool should_whitelist_for_content_settings =
529 base::CommandLine::ForCurrentProcess()->HasSwitch(
530 switches::kInstantProcess);
531 extensions::Dispatcher* ext_dispatcher = NULL;
532 #if defined(ENABLE_EXTENSIONS)
533 ext_dispatcher = extension_dispatcher_.get();
534 #endif
535 ContentSettingsObserver* content_settings = new ContentSettingsObserver(
536 render_frame, ext_dispatcher, should_whitelist_for_content_settings);
537 if (chrome_observer_.get()) {
538 content_settings->SetContentSettingRules(
539 chrome_observer_->content_setting_rules());
542 #if defined(ENABLE_EXTENSIONS)
543 new extensions::ExtensionsRenderFrameObserver(render_frame);
544 new extensions::ExtensionFrameHelper(render_frame, ext_dispatcher);
545 ext_dispatcher->OnRenderFrameCreated(render_frame);
546 #endif
548 #if defined(ENABLE_PLUGINS)
549 new PepperHelper(render_frame);
550 #endif
552 #if !defined(DISABLE_NACL)
553 new nacl::NaClHelper(render_frame);
554 #endif
556 // TODO(jam): when the frame tree moves into content and parent() works at
557 // RenderFrame construction, simplify this by just checking parent().
558 if (render_frame->GetRenderView()->GetMainRenderFrame() != render_frame) {
559 // Avoid any race conditions from having the browser tell subframes that
560 // they're prerendering.
561 if (prerender::PrerenderHelper::IsPrerendering(
562 render_frame->GetRenderView()->GetMainRenderFrame())) {
563 new prerender::PrerenderHelper(render_frame);
567 if (render_frame->GetRenderView()->GetMainRenderFrame() == render_frame) {
568 // Only attach NetErrorHelper to the main frame, since only the main frame
569 // should get error pages.
570 new NetErrorHelper(render_frame);
573 PasswordAutofillAgent* password_autofill_agent =
574 new PasswordAutofillAgent(render_frame);
575 PasswordGenerationAgent* password_generation_agent =
576 new PasswordGenerationAgent(render_frame, password_autofill_agent);
577 new AutofillAgent(render_frame, password_autofill_agent,
578 password_generation_agent);
581 void ChromeContentRendererClient::RenderViewCreated(
582 content::RenderView* render_view) {
584 #if defined(ENABLE_EXTENSIONS)
585 new extensions::ExtensionHelper(render_view, extension_dispatcher_.get());
586 #endif
587 new PageLoadHistograms(render_view);
588 #if defined(ENABLE_PRINTING)
589 new printing::PrintWebViewHelper(
590 render_view,
591 scoped_ptr<printing::PrintWebViewHelper::Delegate>(
592 new ChromePrintWebViewHelperDelegate()));
593 #endif
594 #if defined(ENABLE_SPELLCHECK)
595 new SpellCheckProvider(render_view, spellcheck_.get());
596 #endif
597 new prerender::PrerendererClient(render_view);
598 #if defined(FULL_SAFE_BROWSING)
599 safe_browsing::MalwareDOMDetails::Create(render_view);
600 #endif
602 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
603 if (command_line->HasSwitch(switches::kInstantProcess))
604 new SearchBox(render_view);
606 new ChromeRenderViewObserver(render_view, web_cache_observer_.get());
608 new password_manager::CredentialManagerClient(render_view);
612 SkBitmap* ChromeContentRendererClient::GetSadPluginBitmap() {
613 return const_cast<SkBitmap*>(ResourceBundle::GetSharedInstance().
614 GetImageNamed(IDR_SAD_PLUGIN).ToSkBitmap());
617 SkBitmap* ChromeContentRendererClient::GetSadWebViewBitmap() {
618 return const_cast<SkBitmap*>(ResourceBundle::GetSharedInstance().
619 GetImageNamed(IDR_SAD_WEBVIEW).ToSkBitmap());
622 #if defined(ENABLE_EXTENSIONS)
623 const Extension* ChromeContentRendererClient::GetExtensionByOrigin(
624 const WebSecurityOrigin& origin) const {
625 if (!base::EqualsASCII(origin.protocol(), extensions::kExtensionScheme))
626 return NULL;
628 const std::string extension_id = origin.host().utf8().data();
629 return extension_dispatcher_->extensions()->GetByID(extension_id);
631 #endif
633 scoped_ptr<blink::WebPluginPlaceholder>
634 ChromeContentRendererClient::CreatePluginPlaceholder(
635 content::RenderFrame* render_frame,
636 blink::WebLocalFrame* frame,
637 const blink::WebPluginParams& orig_params) {
638 return CreateShadowDOMPlaceholderForPluginInfo(
639 render_frame, frame, orig_params);
642 bool ChromeContentRendererClient::OverrideCreatePlugin(
643 content::RenderFrame* render_frame,
644 blink::WebLocalFrame* frame,
645 const WebPluginParams& params,
646 WebPlugin** plugin) {
647 std::string orig_mime_type = params.mimeType.utf8();
648 #if defined(ENABLE_EXTENSIONS)
649 if (orig_mime_type == content::kBrowserPluginMimeType) {
650 bool guest_view_api_available = false;
651 extension_dispatcher_->script_context_set().ForEach(
652 render_frame->GetRenderView(),
653 base::Bind(&IsGuestViewApiAvailableToScriptContext,
654 &guest_view_api_available));
655 if (guest_view_api_available)
656 return false;
658 #endif
660 GURL url(params.url);
661 #if defined(ENABLE_PLUGINS)
662 ChromeViewHostMsg_GetPluginInfo_Output output;
663 render_frame->Send(new ChromeViewHostMsg_GetPluginInfo(
664 render_frame->GetRoutingID(), url, frame->top()->document().url(),
665 orig_mime_type, &output));
666 *plugin = CreatePlugin(render_frame, frame, params, output);
667 #else // !defined(ENABLE_PLUGINS)
669 #if defined(OS_ANDROID)
670 if (plugins::MobileYouTubePlugin::IsYouTubeURL(url, orig_mime_type)) {
671 base::StringPiece template_html(
672 ResourceBundle::GetSharedInstance().GetRawDataResource(
673 IDR_MOBILE_YOUTUBE_PLUGIN_HTML));
674 *plugin = (new plugins::MobileYouTubePlugin(render_frame, frame, params,
675 template_html))->plugin();
676 return true;
678 #endif // defined(OS_ANDROID)
680 PluginUMAReporter::GetInstance()->ReportPluginMissing(orig_mime_type, url);
681 *plugin = NonLoadablePluginPlaceholder::CreateNotSupportedPlugin(
682 render_frame, frame, params)->plugin();
684 #endif // defined(ENABLE_PLUGINS)
685 return true;
688 WebPlugin* ChromeContentRendererClient::CreatePluginReplacement(
689 content::RenderFrame* render_frame,
690 const base::FilePath& plugin_path) {
691 return NonLoadablePluginPlaceholder::CreateErrorPlugin(render_frame,
692 plugin_path)->plugin();
695 void ChromeContentRendererClient::DeferMediaLoad(
696 content::RenderFrame* render_frame,
697 const base::Closure& closure) {
698 #if defined(OS_ANDROID)
699 // Chromium for Android doesn't support prerender yet.
700 closure.Run();
701 return;
702 #else
703 if (!prerender::PrerenderHelper::IsPrerendering(render_frame)) {
704 closure.Run();
705 return;
708 // Lifetime is tied to |render_frame| via content::RenderFrameObserver.
709 new prerender::PrerenderMediaLoadDeferrer(render_frame, closure);
710 #endif
713 #if defined(ENABLE_PLUGINS)
714 WebPlugin* ChromeContentRendererClient::CreatePlugin(
715 content::RenderFrame* render_frame,
716 blink::WebLocalFrame* frame,
717 const WebPluginParams& original_params,
718 const ChromeViewHostMsg_GetPluginInfo_Output& output) {
719 const WebPluginInfo& info = output.plugin;
720 const std::string& actual_mime_type = output.actual_mime_type;
721 const base::string16& group_name = output.group_name;
722 const std::string& identifier = output.group_identifier;
723 ChromeViewHostMsg_GetPluginInfo_Status status = output.status;
724 GURL url(original_params.url);
725 std::string orig_mime_type = original_params.mimeType.utf8();
726 ChromePluginPlaceholder* placeholder = NULL;
728 // If the browser plugin is to be enabled, this should be handled by the
729 // renderer, so the code won't reach here due to the early exit in
730 // OverrideCreatePlugin.
731 if (status == ChromeViewHostMsg_GetPluginInfo_Status::kNotFound ||
732 orig_mime_type == content::kBrowserPluginMimeType) {
733 PluginUMAReporter::GetInstance()->ReportPluginMissing(orig_mime_type, url);
734 placeholder = ChromePluginPlaceholder::CreateLoadableMissingPlugin(
735 render_frame, frame, original_params);
736 } else {
737 // TODO(bauerb): This should be in content/.
738 WebPluginParams params(original_params);
739 for (size_t i = 0; i < info.mime_types.size(); ++i) {
740 if (info.mime_types[i].mime_type == actual_mime_type) {
741 AppendParams(info.mime_types[i].additional_param_names,
742 info.mime_types[i].additional_param_values,
743 &params.attributeNames, &params.attributeValues);
744 break;
747 if (params.mimeType.isNull() && (actual_mime_type.size() > 0)) {
748 // Webkit might say that mime type is null while we already know the
749 // actual mime type via ChromeViewHostMsg_GetPluginInfo. In that case
750 // we should use what we know since WebpluginDelegateProxy does some
751 // specific initializations based on this information.
752 params.mimeType = WebString::fromUTF8(actual_mime_type.c_str());
755 ContentSettingsObserver* observer =
756 ContentSettingsObserver::Get(render_frame);
758 const ContentSettingsType content_type =
759 ShouldUseJavaScriptSettingForPlugin(info)
760 ? CONTENT_SETTINGS_TYPE_JAVASCRIPT
761 : CONTENT_SETTINGS_TYPE_PLUGINS;
763 if ((status == ChromeViewHostMsg_GetPluginInfo_Status::kUnauthorized ||
764 status == ChromeViewHostMsg_GetPluginInfo_Status::kBlocked) &&
765 observer->IsPluginTemporarilyAllowed(identifier)) {
766 status = ChromeViewHostMsg_GetPluginInfo_Status::kAllowed;
769 #if defined(OS_WIN)
770 // In Windows we need to check if we can load NPAPI plugins.
771 // For example, if the render view is in the Ash desktop, we should not.
772 // If user is on ALLOW or DETECT setting, loading needs to be blocked here.
773 if ((status == ChromeViewHostMsg_GetPluginInfo_Status::kAllowed ||
774 status ==
775 ChromeViewHostMsg_GetPluginInfo_Status::kPlayImportantContent) &&
776 info.type == content::WebPluginInfo::PLUGIN_TYPE_NPAPI) {
777 if (observer->AreNPAPIPluginsBlocked())
778 status = ChromeViewHostMsg_GetPluginInfo_Status::kNPAPINotSupported;
780 #endif
782 auto create_blocked_plugin =
783 [&render_frame, &frame, &params, &info, &identifier, &group_name](
784 int template_id, const base::string16& message) {
785 return ChromePluginPlaceholder::CreateBlockedPlugin(
786 render_frame, frame, params, info, identifier, group_name,
787 template_id, message, PlaceholderPosterInfo());
789 switch (status) {
790 case ChromeViewHostMsg_GetPluginInfo_Status::kNotFound: {
791 NOTREACHED();
792 break;
794 case ChromeViewHostMsg_GetPluginInfo_Status::kAllowed:
795 case ChromeViewHostMsg_GetPluginInfo_Status::kPlayImportantContent: {
796 #if !defined(DISABLE_NACL) && defined(ENABLE_EXTENSIONS)
797 const bool is_nacl_plugin =
798 info.name == ASCIIToUTF16(nacl::kNaClPluginName);
799 const bool is_nacl_mime_type =
800 actual_mime_type == nacl::kNaClPluginMimeType;
801 const bool is_pnacl_mime_type =
802 actual_mime_type == nacl::kPnaclPluginMimeType;
803 if (is_nacl_plugin || is_nacl_mime_type || is_pnacl_mime_type) {
804 bool is_nacl_unrestricted = false;
805 if (is_nacl_mime_type) {
806 is_nacl_unrestricted =
807 base::CommandLine::ForCurrentProcess()->HasSwitch(
808 switches::kEnableNaCl);
809 } else if (is_pnacl_mime_type) {
810 is_nacl_unrestricted = true;
812 GURL manifest_url;
813 GURL app_url;
814 if (is_nacl_mime_type || is_pnacl_mime_type) {
815 // Normal NaCl/PNaCl embed. The app URL is the page URL.
816 manifest_url = url;
817 app_url = frame->top()->document().url();
818 } else {
819 // NaCl is being invoked as a content handler. Look up the NaCl
820 // module using the MIME type. The app URL is the manifest URL.
821 manifest_url = GetNaClContentHandlerURL(actual_mime_type, info);
822 app_url = manifest_url;
824 const Extension* extension =
825 g_current_client->extension_dispatcher_->extensions()->
826 GetExtensionOrAppByURL(manifest_url);
827 if (!IsNaClAllowed(manifest_url,
828 app_url,
829 is_nacl_unrestricted,
830 extension,
831 &params)) {
832 WebString error_message;
833 if (is_nacl_mime_type) {
834 error_message =
835 "Only unpacked extensions and apps installed from the Chrome "
836 "Web Store can load NaCl modules without enabling Native "
837 "Client in about:flags.";
838 } else if (is_pnacl_mime_type) {
839 error_message =
840 "Portable Native Client must not be disabled in about:flags.";
842 frame->addMessageToConsole(
843 WebConsoleMessage(WebConsoleMessage::LevelError,
844 error_message));
845 placeholder = create_blocked_plugin(
846 IDR_BLOCKED_PLUGIN_HTML,
847 #if defined(OS_CHROMEOS)
848 l10n_util::GetStringUTF16(IDS_NACL_PLUGIN_BLOCKED));
849 #else
850 l10n_util::GetStringFUTF16(IDS_PLUGIN_BLOCKED, group_name));
851 #endif
852 break;
855 #endif // !defined(DISABLE_NACL) && defined(ENABLE_EXTENSIONS)
857 // Delay loading plugins if prerendering.
858 // TODO(mmenke): In the case of prerendering, feed into
859 // ChromeContentRendererClient::CreatePlugin instead, to
860 // reduce the chance of future regressions.
861 bool is_prerendering =
862 prerender::PrerenderHelper::IsPrerendering(render_frame);
863 bool power_saver_enabled =
864 status ==
865 ChromeViewHostMsg_GetPluginInfo_Status::kPlayImportantContent;
866 bool blocked_for_background_tab =
867 render_frame->IsHidden() && power_saver_enabled;
869 if (info.name == ASCIIToUTF16(content::kFlashPluginName))
870 TrackPosterParamPresence(params, power_saver_enabled);
872 PlaceholderPosterInfo poster_info;
873 if (power_saver_enabled) {
874 poster_info.poster_attribute =
875 GetPluginInstancePosterAttribute(params);
876 poster_info.base_url = frame->document().url();
879 if (blocked_for_background_tab || is_prerendering ||
880 !poster_info.poster_attribute.empty()) {
881 placeholder = ChromePluginPlaceholder::CreateBlockedPlugin(
882 render_frame, frame, params, info, identifier, group_name,
883 poster_info.poster_attribute.empty() ? IDR_BLOCKED_PLUGIN_HTML
884 : IDR_PLUGIN_POSTER_HTML,
885 l10n_util::GetStringFUTF16(IDS_PLUGIN_BLOCKED, group_name),
886 poster_info);
887 placeholder->set_blocked_for_background_tab(
888 blocked_for_background_tab);
889 placeholder->set_blocked_for_prerendering(is_prerendering);
890 placeholder->set_power_saver_enabled(power_saver_enabled);
891 break;
894 scoped_ptr<content::PluginInstanceThrottler> throttler;
895 if (power_saver_enabled) {
896 throttler = PluginInstanceThrottler::Create();
897 // PluginPreroller manages its own lifetime.
898 new PluginPreroller(
899 render_frame, frame, params, info, identifier, group_name,
900 l10n_util::GetStringFUTF16(IDS_PLUGIN_BLOCKED, group_name),
901 throttler.get());
904 return render_frame->CreatePlugin(frame, info, params,
905 throttler.Pass());
907 case ChromeViewHostMsg_GetPluginInfo_Status::kNPAPINotSupported: {
908 RenderThread::Get()->RecordAction(
909 UserMetricsAction("Plugin_NPAPINotSupported"));
910 placeholder = create_blocked_plugin(
911 IDR_BLOCKED_PLUGIN_HTML,
912 l10n_util::GetStringUTF16(IDS_PLUGIN_NOT_SUPPORTED_METRO));
913 render_frame->Send(new ChromeViewHostMsg_NPAPINotSupported(
914 render_frame->GetRoutingID(), identifier));
915 break;
917 case ChromeViewHostMsg_GetPluginInfo_Status::kDisabled: {
918 PluginUMAReporter::GetInstance()->ReportPluginDisabled(orig_mime_type,
919 url);
920 placeholder = create_blocked_plugin(
921 IDR_DISABLED_PLUGIN_HTML,
922 l10n_util::GetStringFUTF16(IDS_PLUGIN_DISABLED, group_name));
923 break;
925 case ChromeViewHostMsg_GetPluginInfo_Status::kOutdatedBlocked: {
926 #if defined(ENABLE_PLUGIN_INSTALLATION)
927 placeholder = create_blocked_plugin(
928 IDR_BLOCKED_PLUGIN_HTML,
929 l10n_util::GetStringFUTF16(IDS_PLUGIN_OUTDATED, group_name));
930 render_frame->Send(new ChromeViewHostMsg_BlockedOutdatedPlugin(
931 render_frame->GetRoutingID(), placeholder->CreateRoutingId(),
932 identifier));
933 #else
934 NOTREACHED();
935 #endif
936 break;
938 case ChromeViewHostMsg_GetPluginInfo_Status::kOutdatedDisallowed: {
939 placeholder = create_blocked_plugin(
940 IDR_BLOCKED_PLUGIN_HTML,
941 l10n_util::GetStringFUTF16(IDS_PLUGIN_OUTDATED, group_name));
942 break;
944 case ChromeViewHostMsg_GetPluginInfo_Status::kUnauthorized: {
945 placeholder = create_blocked_plugin(
946 IDR_BLOCKED_PLUGIN_HTML,
947 l10n_util::GetStringFUTF16(IDS_PLUGIN_NOT_AUTHORIZED, group_name));
948 if (info.type != content::WebPluginInfo::PLUGIN_TYPE_NPAPI) {
949 render_frame->Send(new ChromeViewHostMsg_BlockedUnauthorizedPlugin(
950 render_frame->GetRoutingID(),
951 group_name,
952 identifier));
954 observer->DidBlockContentType(content_type, group_name);
955 break;
957 case ChromeViewHostMsg_GetPluginInfo_Status::kBlocked: {
958 placeholder = create_blocked_plugin(
959 IDR_BLOCKED_PLUGIN_HTML,
960 l10n_util::GetStringFUTF16(IDS_PLUGIN_BLOCKED, group_name));
961 RenderThread::Get()->RecordAction(UserMetricsAction("Plugin_Blocked"));
962 observer->DidBlockContentType(content_type, group_name);
963 break;
965 case ChromeViewHostMsg_GetPluginInfo_Status::kBlockedByPolicy: {
966 placeholder = create_blocked_plugin(
967 IDR_BLOCKED_PLUGIN_HTML,
968 l10n_util::GetStringFUTF16(IDS_PLUGIN_BLOCKED_BY_POLICY,
969 group_name));
970 placeholder->DisallowLoading();
971 RenderThread::Get()->RecordAction(
972 UserMetricsAction("Plugin_BlockedByPolicy"));
973 observer->DidBlockContentType(content_type, group_name);
974 break;
978 placeholder->SetStatus(status);
979 return placeholder->plugin();
981 #endif // defined(ENABLE_PLUGINS)
983 // For NaCl content handling plugins, the NaCl manifest is stored in an
984 // additonal 'nacl' param associated with the MIME type.
985 // static
986 GURL ChromeContentRendererClient::GetNaClContentHandlerURL(
987 const std::string& actual_mime_type,
988 const content::WebPluginInfo& plugin) {
989 // Look for the manifest URL among the MIME type's additonal parameters.
990 const char kNaClPluginManifestAttribute[] = "nacl";
991 base::string16 nacl_attr = ASCIIToUTF16(kNaClPluginManifestAttribute);
992 for (size_t i = 0; i < plugin.mime_types.size(); ++i) {
993 if (plugin.mime_types[i].mime_type == actual_mime_type) {
994 const content::WebPluginMimeType& content_type = plugin.mime_types[i];
995 for (size_t i = 0; i < content_type.additional_param_names.size(); ++i) {
996 if (content_type.additional_param_names[i] == nacl_attr)
997 return GURL(content_type.additional_param_values[i]);
999 break;
1002 return GURL();
1005 #if !defined(DISABLE_NACL)
1006 // static
1007 bool ChromeContentRendererClient::IsNaClAllowed(
1008 const GURL& manifest_url,
1009 const GURL& app_url,
1010 bool is_nacl_unrestricted,
1011 const Extension* extension,
1012 WebPluginParams* params) {
1013 // Temporarily allow these whitelisted apps and WebUIs to use NaCl.
1014 std::string app_url_host = app_url.host();
1015 std::string manifest_url_path = manifest_url.path();
1017 bool is_whitelisted_web_ui =
1018 app_url.spec() == chrome::kChromeUIAppListStartPageURL;
1020 bool is_photo_app =
1021 // Whitelisted apps must be served over https.
1022 app_url.SchemeIsCryptographic() && manifest_url.SchemeIsCryptographic() &&
1023 (base::EndsWith(app_url_host, "plus.google.com", false) ||
1024 base::EndsWith(app_url_host, "plus.sandbox.google.com", false)) &&
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", false) ||
1038 base::EndsWith(app_url_host, "plus.google.com", false) ||
1039 base::EndsWith(app_url_host, "plus.sandbox.google.com", false)) &&
1040 // The manifest must be loaded from the host's FileSystem.
1041 (manifest_fs_host == app_url_host);
1043 bool is_whitelisted_app = is_photo_app || is_hangouts_app;
1045 bool is_extension_from_webstore = false;
1046 bool is_invoked_by_hosted_app = false;
1047 bool is_extension_unrestricted = false;
1048 #if defined(ENABLE_EXTENSIONS)
1049 is_extension_from_webstore = extension && extension->from_webstore();
1051 is_invoked_by_hosted_app = extension &&
1052 extension->is_hosted_app() &&
1053 extension->web_extent().MatchesURL(app_url);
1055 // Allow built-in extensions and extensions under development.
1056 is_extension_unrestricted = extension &&
1057 (extension->location() == extensions::Manifest::COMPONENT ||
1058 extensions::Manifest::IsUnpackedLocation(extension->location()));
1059 #endif // defined(ENABLE_EXTENSIONS)
1061 bool is_invoked_by_extension = app_url.SchemeIs("chrome-extension");
1063 // The NaCl PDF viewer is always allowed and can use 'Dev' interfaces.
1064 bool is_nacl_pdf_viewer =
1065 (is_extension_from_webstore &&
1066 manifest_url.SchemeIs("chrome-extension") &&
1067 manifest_url.host() == "acadkphlmlegjaadjagenfimbpphcgnh");
1069 // Allow Chrome Web Store extensions, built-in extensions and extensions
1070 // under development if the invocation comes from a URL with an extension
1071 // scheme. Also allow invocations if they are from whitelisted URLs or
1072 // if --enable-nacl is set.
1073 bool is_nacl_allowed = is_nacl_unrestricted ||
1074 is_whitelisted_web_ui ||
1075 is_whitelisted_app ||
1076 is_nacl_pdf_viewer ||
1077 is_invoked_by_hosted_app ||
1078 (is_invoked_by_extension &&
1079 (is_extension_from_webstore ||
1080 is_extension_unrestricted));
1081 if (is_nacl_allowed) {
1082 bool app_can_use_dev_interfaces = is_nacl_pdf_viewer;
1083 // Make sure that PPAPI 'dev' interfaces aren't available for production
1084 // apps unless they're whitelisted.
1085 WebString dev_attribute = WebString::fromUTF8("@dev");
1086 if ((!is_whitelisted_app && !is_extension_from_webstore) ||
1087 app_can_use_dev_interfaces) {
1088 // Add the special '@dev' attribute.
1089 std::vector<base::string16> param_names;
1090 std::vector<base::string16> param_values;
1091 param_names.push_back(dev_attribute);
1092 param_values.push_back(WebString());
1093 AppendParams(
1094 param_names,
1095 param_values,
1096 &params->attributeNames,
1097 &params->attributeValues);
1098 } else {
1099 // If the params somehow contain '@dev', remove it.
1100 size_t attribute_count = params->attributeNames.size();
1101 for (size_t i = 0; i < attribute_count; ++i) {
1102 if (params->attributeNames[i].equals(dev_attribute))
1103 params->attributeNames[i] = WebString();
1107 return is_nacl_allowed;
1109 #endif // defined(DISABLE_NACL)
1111 bool ChromeContentRendererClient::HasErrorPage(int http_status_code,
1112 std::string* error_domain) {
1113 // Use an internal error page, if we have one for the status code.
1114 if (!LocalizedError::HasStrings(LocalizedError::kHttpErrorDomain,
1115 http_status_code)) {
1116 return false;
1119 *error_domain = LocalizedError::kHttpErrorDomain;
1120 return true;
1123 bool ChromeContentRendererClient::ShouldSuppressErrorPage(
1124 content::RenderFrame* render_frame,
1125 const GURL& url) {
1126 // Unit tests for ChromeContentRendererClient pass a NULL RenderFrame here.
1127 // Unfortunately it's very difficult to construct a mock RenderView, so skip
1128 // this functionality in this case.
1129 if (render_frame) {
1130 content::RenderView* render_view = render_frame->GetRenderView();
1131 content::RenderFrame* main_render_frame = render_view->GetMainRenderFrame();
1132 blink::WebFrame* web_frame = render_frame->GetWebFrame();
1133 NetErrorHelper* net_error_helper = NetErrorHelper::Get(main_render_frame);
1134 if (net_error_helper->ShouldSuppressErrorPage(web_frame, url))
1135 return true;
1137 // Do not flash an error page if the Instant new tab page fails to load.
1138 return search_bouncer_.get() && search_bouncer_->IsNewTabPage(url);
1141 void ChromeContentRendererClient::GetNavigationErrorStrings(
1142 content::RenderView* render_view,
1143 blink::WebFrame* frame,
1144 const blink::WebURLRequest& failed_request,
1145 const blink::WebURLError& error,
1146 std::string* error_html,
1147 base::string16* error_description) {
1148 const GURL failed_url = error.unreachableURL;
1150 bool is_post = base::EqualsASCII(failed_request.httpMethod(), "POST");
1152 if (error_html) {
1153 // TODO(ellyjones): change GetNavigationErrorStrings to take a RenderFrame
1154 // instead of a RenderView, then pass that in.
1155 // This is safe for now because we only install the NetErrorHelper on the
1156 // main render frame anyway; see the TODO(ellyjones) in
1157 // RenderFrameCreated.
1158 content::RenderFrame* main_render_frame = render_view->GetMainRenderFrame();
1159 NetErrorHelper* helper = NetErrorHelper::Get(main_render_frame);
1160 helper->GetErrorHTML(frame, error, is_post, error_html);
1163 if (error_description)
1164 *error_description = LocalizedError::GetErrorDetails(error, is_post);
1167 bool ChromeContentRendererClient::RunIdleHandlerWhenWidgetsHidden() {
1168 #if defined(ENABLE_EXTENSIONS)
1169 return !IsStandaloneExtensionProcess();
1170 #else
1171 return true;
1172 #endif
1175 bool ChromeContentRendererClient::AllowPopup() {
1176 #if defined(ENABLE_EXTENSIONS)
1177 extensions::ScriptContext* current_context =
1178 extension_dispatcher_->script_context_set().GetCurrent();
1179 if (!current_context || !current_context->extension())
1180 return false;
1181 // See http://crbug.com/117446 for the subtlety of this check.
1182 switch (current_context->context_type()) {
1183 case extensions::Feature::UNSPECIFIED_CONTEXT:
1184 case extensions::Feature::WEB_PAGE_CONTEXT:
1185 case extensions::Feature::UNBLESSED_EXTENSION_CONTEXT:
1186 case extensions::Feature::WEBUI_CONTEXT:
1187 return false;
1188 case extensions::Feature::BLESSED_EXTENSION_CONTEXT:
1189 case extensions::Feature::CONTENT_SCRIPT_CONTEXT:
1190 return true;
1191 case extensions::Feature::BLESSED_WEB_PAGE_CONTEXT:
1192 return !current_context->web_frame()->parent();
1194 NOTREACHED();
1195 #endif
1196 return false;
1199 bool ChromeContentRendererClient::ShouldFork(blink::WebLocalFrame* frame,
1200 const GURL& url,
1201 const std::string& http_method,
1202 bool is_initial_navigation,
1203 bool is_server_redirect,
1204 bool* send_referrer) {
1205 DCHECK(!frame->parent());
1207 // If this is the Instant process, fork all navigations originating from the
1208 // renderer. The destination page will then be bucketed back to this Instant
1209 // process if it is an Instant url, or to another process if not. Conversely,
1210 // fork if this is a non-Instant process navigating to an Instant url, so that
1211 // such navigations can also be bucketed into an Instant renderer.
1212 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1213 switches::kInstantProcess) ||
1214 (search_bouncer_.get() && search_bouncer_->ShouldFork(url))) {
1215 *send_referrer = true;
1216 return true;
1219 // For now, we skip the rest for POST submissions. This is because
1220 // http://crbug.com/101395 is more likely to cause compatibility issues
1221 // with hosted apps and extensions than WebUI pages. We will remove this
1222 // check when cross-process POST submissions are supported.
1223 if (http_method != "GET")
1224 return false;
1226 // If |url| matches one of the prerendered URLs, stop this navigation and try
1227 // to swap in the prerendered page on the browser process. If the prerendered
1228 // page no longer exists by the time the OpenURL IPC is handled, a normal
1229 // navigation is attempted.
1230 if (prerender_dispatcher_.get() &&
1231 prerender_dispatcher_->IsPrerenderURL(url)) {
1232 *send_referrer = true;
1233 return true;
1236 #if defined(ENABLE_EXTENSIONS)
1237 const extensions::ExtensionSet* extensions =
1238 extension_dispatcher_->extensions();
1240 // Determine if the new URL is an extension (excluding bookmark apps).
1241 const Extension* new_url_extension = extensions::GetNonBookmarkAppExtension(
1242 *extensions, url);
1243 bool is_extension_url = !!new_url_extension;
1245 // If the navigation would cross an app extent boundary, we also need
1246 // to defer to the browser to ensure process isolation. This is not necessary
1247 // for server redirects, which will be transferred to a new process by the
1248 // browser process when they are ready to commit. It is necessary for client
1249 // redirects, which won't be transferred in the same way.
1250 if (!is_server_redirect &&
1251 CrossesExtensionExtents(frame, url, *extensions, is_extension_url,
1252 is_initial_navigation)) {
1253 // Include the referrer in this case since we're going from a hosted web
1254 // page. (the packaged case is handled previously by the extension
1255 // navigation test)
1256 *send_referrer = true;
1258 const Extension* extension =
1259 extension_dispatcher_->extensions()->GetExtensionOrAppByURL(url);
1260 if (extension && extension->is_app()) {
1261 extensions::RecordAppLaunchType(
1262 extension_misc::APP_LAUNCH_CONTENT_NAVIGATION, extension->GetType());
1264 return true;
1267 // If this is a reload, check whether it has the wrong process type. We
1268 // should send it to the browser if it's an extension URL (e.g., hosted app)
1269 // in a normal process, or if it's a process for an extension that has been
1270 // uninstalled. Without --site-per-process mode, we never fork processes for
1271 // subframes, so this check only makes sense for top-level frames.
1272 // TODO(alexmos,nasko): Figure out how this check should work when reloading
1273 // subframes in --site-per-process mode.
1274 if (!frame->parent() && frame->document().url() == url) {
1275 if (is_extension_url != IsStandaloneExtensionProcess())
1276 return true;
1278 #endif // defined(ENABLE_EXTENSIONS)
1280 return false;
1283 bool ChromeContentRendererClient::WillSendRequest(
1284 blink::WebFrame* frame,
1285 ui::PageTransition transition_type,
1286 const GURL& url,
1287 const GURL& first_party_for_cookies,
1288 GURL* new_url) {
1289 // Check whether the request should be allowed. If not allowed, we reset the
1290 // URL to something invalid to prevent the request and cause an error.
1291 #if defined(ENABLE_EXTENSIONS)
1292 if (url.SchemeIs(extensions::kExtensionScheme) &&
1293 !extensions::ResourceRequestPolicy::CanRequestResource(
1294 url,
1295 frame,
1296 transition_type,
1297 extension_dispatcher_->extensions())) {
1298 *new_url = GURL(chrome::kExtensionInvalidRequestURL);
1299 return true;
1302 if (url.SchemeIs(extensions::kExtensionResourceScheme) &&
1303 !extensions::ResourceRequestPolicy::CanRequestExtensionResourceScheme(
1304 url,
1305 frame)) {
1306 *new_url = GURL(chrome::kExtensionResourceInvalidRequestURL);
1307 return true;
1309 #endif
1311 const content::RenderView* render_view =
1312 content::RenderView::FromWebView(frame->view());
1313 SearchBox* search_box = SearchBox::Get(render_view);
1314 if (search_box && url.SchemeIs(chrome::kChromeSearchScheme)) {
1315 SearchBox::ImageSourceType type = SearchBox::NONE;
1316 if (url.host() == chrome::kChromeUIFaviconHost)
1317 type = SearchBox::FAVICON;
1318 else if (url.host() == chrome::kChromeUILargeIconHost)
1319 type = SearchBox::LARGE_ICON;
1320 else if (url.host() == chrome::kChromeUIFallbackIconHost)
1321 type = SearchBox::FALLBACK_ICON;
1322 else if (url.host() == chrome::kChromeUIThumbnailHost)
1323 type = SearchBox::THUMB;
1324 if (type != SearchBox::NONE)
1325 return search_box->GenerateImageURLFromTransientURL(url, type, new_url);
1328 return false;
1331 unsigned long long ChromeContentRendererClient::VisitedLinkHash(
1332 const char* canonical_url, size_t length) {
1333 return visited_link_slave_->ComputeURLFingerprint(canonical_url, length);
1336 bool ChromeContentRendererClient::IsLinkVisited(unsigned long long link_hash) {
1337 return visited_link_slave_->IsVisited(link_hash);
1340 blink::WebPrescientNetworking*
1341 ChromeContentRendererClient::GetPrescientNetworking() {
1342 return prescient_networking_dispatcher_.get();
1345 bool ChromeContentRendererClient::ShouldOverridePageVisibilityState(
1346 const content::RenderFrame* render_frame,
1347 blink::WebPageVisibilityState* override_state) {
1348 if (!prerender::PrerenderHelper::IsPrerendering(render_frame))
1349 return false;
1351 *override_state = blink::WebPageVisibilityStatePrerender;
1352 return true;
1355 #if defined(ENABLE_EXTENSIONS)
1356 void ChromeContentRendererClient::SetExtensionDispatcherForTest(
1357 extensions::Dispatcher* extension_dispatcher) {
1358 extension_dispatcher_.reset(extension_dispatcher);
1359 permissions_policy_delegate_.reset(
1360 new extensions::RendererPermissionsPolicyDelegate(
1361 extension_dispatcher_.get()));
1364 extensions::Dispatcher*
1365 ChromeContentRendererClient::GetExtensionDispatcherForTest() {
1366 return extension_dispatcher_.get();
1369 bool ChromeContentRendererClient::CrossesExtensionExtents(
1370 blink::WebLocalFrame* frame,
1371 const GURL& new_url,
1372 const extensions::ExtensionSet& extensions,
1373 bool is_extension_url,
1374 bool is_initial_navigation) {
1375 DCHECK(!frame->parent());
1376 GURL old_url(frame->document().url());
1378 // If old_url is still empty and this is an initial navigation, then this is
1379 // a window.open operation. We should look at the opener URL. Note that the
1380 // opener is a local frame in this case.
1381 if (is_initial_navigation && old_url.is_empty() && frame->opener()) {
1382 WebLocalFrame* opener_frame = frame->opener()->toWebLocalFrame();
1384 // If we're about to open a normal web page from a same-origin opener stuck
1385 // in an extension process, we want to keep it in process to allow the
1386 // opener to script it.
1387 WebDocument opener_document = opener_frame->document();
1388 WebSecurityOrigin opener_origin = opener_document.securityOrigin();
1389 bool opener_is_extension_url =
1390 !opener_origin.isUnique() && extensions.GetExtensionOrAppByURL(
1391 opener_document.url()) != NULL;
1392 if (!is_extension_url &&
1393 !opener_is_extension_url &&
1394 IsStandaloneExtensionProcess() &&
1395 opener_origin.canRequest(WebURL(new_url)))
1396 return false;
1398 // In all other cases, we want to compare against the URL that determines
1399 // the type of process. In default Chrome, that's the URL of the opener's
1400 // top frame and not the opener frame itself. In --site-per-process, we
1401 // can use the opener frame itself.
1402 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1403 switches::kSitePerProcess))
1404 old_url = opener_frame->document().url();
1405 else
1406 old_url = opener_frame->top()->document().url();
1409 // Only consider keeping non-app URLs in an app process if this window
1410 // has an opener (in which case it might be an OAuth popup that tries to
1411 // script an iframe within the app).
1412 bool should_consider_workaround = !!frame->opener();
1414 return extensions::CrossesExtensionProcessBoundary(
1415 extensions, old_url, new_url, should_consider_workaround);
1417 #endif // defined(ENABLE_EXTENSIONS)
1419 #if defined(ENABLE_SPELLCHECK)
1420 void ChromeContentRendererClient::SetSpellcheck(SpellCheck* spellcheck) {
1421 RenderThread* thread = RenderThread::Get();
1422 if (spellcheck_.get() && thread)
1423 thread->RemoveObserver(spellcheck_.get());
1424 spellcheck_.reset(spellcheck);
1425 SpellCheckReplacer replacer(spellcheck_.get());
1426 content::RenderView::ForEach(&replacer);
1427 if (thread)
1428 thread->AddObserver(spellcheck_.get());
1430 #endif
1432 // static
1433 bool ChromeContentRendererClient::WasWebRequestUsedBySomeExtensions() {
1434 #if defined(ENABLE_EXTENSIONS)
1435 return g_current_client->extension_dispatcher_
1436 ->WasWebRequestUsedBySomeExtensions();
1437 #else
1438 return false;
1439 #endif
1442 const void* ChromeContentRendererClient::CreatePPAPIInterface(
1443 const std::string& interface_name) {
1444 #if defined(ENABLE_PLUGINS) && !defined(DISABLE_NACL)
1445 if (interface_name == PPB_NACL_PRIVATE_INTERFACE)
1446 return nacl::GetNaClPrivateInterface();
1447 #endif
1448 return NULL;
1451 bool ChromeContentRendererClient::IsExternalPepperPlugin(
1452 const std::string& module_name) {
1453 // TODO(bbudge) remove this when the trusted NaCl plugin has been removed.
1454 // We must defer certain plugin events for NaCl instances since we switch
1455 // from the in-process to the out-of-process proxy after instantiating them.
1456 return module_name == "Native Client";
1459 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
1460 bool ChromeContentRendererClient::IsExtensionOrSharedModuleWhitelisted(
1461 const GURL& url, const std::set<std::string>& whitelist) {
1462 const extensions::ExtensionSet* extension_set =
1463 g_current_client->extension_dispatcher_->extensions();
1464 return chrome::IsExtensionOrSharedModuleWhitelisted(url, extension_set,
1465 whitelist);
1467 #endif
1469 blink::WebSpeechSynthesizer*
1470 ChromeContentRendererClient::OverrideSpeechSynthesizer(
1471 blink::WebSpeechSynthesizerClient* client) {
1472 return new TtsDispatcher(client);
1475 bool ChromeContentRendererClient::AllowPepperMediaStreamAPI(
1476 const GURL& url) {
1477 #if !defined(OS_ANDROID)
1478 // Allow only the Hangouts app to use the MediaStream APIs. It's OK to check
1479 // the whitelist in the renderer, since we're only preventing access until
1480 // these APIs are public and stable.
1481 std::string url_host = url.host();
1482 if (url.SchemeIs("https") &&
1483 (base::EndsWith(url_host, "talkgadget.google.com", false) ||
1484 base::EndsWith(url_host, "plus.google.com", false) ||
1485 base::EndsWith(url_host, "plus.sandbox.google.com", false)) &&
1486 base::StartsWithASCII(url.path(), "/hangouts/", false)) {
1487 return true;
1489 // Allow access for tests.
1490 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1491 switches::kEnablePepperTesting)) {
1492 return true;
1494 #endif // !defined(OS_ANDROID)
1495 return false;
1498 void ChromeContentRendererClient::AddKeySystems(
1499 std::vector<media::KeySystemInfo>* key_systems) {
1500 AddChromeKeySystems(key_systems);
1503 bool ChromeContentRendererClient::ShouldReportDetailedMessageForSource(
1504 const base::string16& source) const {
1505 #if defined(ENABLE_EXTENSIONS)
1506 return extensions::IsSourceFromAnExtension(source);
1507 #else
1508 return false;
1509 #endif
1512 bool ChromeContentRendererClient::ShouldGatherSiteIsolationStats() const {
1513 // Site isolation stats are gathered currently for non-extension renderer
1514 // processes running a normal web page from the Internet.
1515 // TODO(nick): https://crbug.com/268640 Gather stats for extension processes
1516 // too; we would need to check the extension's manifest to know which sites
1517 // it's allowed to access.
1518 #if defined(ENABLE_EXTENSIONS)
1519 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
1520 return !command_line->HasSwitch(extensions::switches::kExtensionProcess);
1521 #else
1522 return true;
1523 #endif
1526 blink::WebWorkerContentSettingsClientProxy*
1527 ChromeContentRendererClient::CreateWorkerContentSettingsClientProxy(
1528 content::RenderFrame* render_frame,
1529 blink::WebFrame* frame) {
1530 return new WorkerContentSettingsClientProxy(render_frame, frame);
1533 bool ChromeContentRendererClient::IsPluginAllowedToUseDevChannelAPIs() {
1534 #if defined(ENABLE_PLUGINS)
1535 // Allow access for tests.
1536 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1537 switches::kEnablePepperTesting)) {
1538 return true;
1541 chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
1542 // Allow dev channel APIs to be used on "Canary", "Dev", and "Unknown"
1543 // releases of Chrome. Permitting "Unknown" allows these APIs to be used on
1544 // Chromium builds as well.
1545 return channel <= chrome::VersionInfo::CHANNEL_DEV;
1546 #else
1547 return false;
1548 #endif
1551 bool ChromeContentRendererClient::IsPluginAllowedToUseCameraDeviceAPI(
1552 const GURL& url) {
1553 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
1554 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1555 switches::kEnablePepperTesting))
1556 return true;
1558 if (IsExtensionOrSharedModuleWhitelisted(url, allowed_camera_device_origins_))
1559 return true;
1560 #endif
1562 return false;
1565 bool ChromeContentRendererClient::IsPluginAllowedToUseCompositorAPI(
1566 const GURL& url) {
1567 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
1568 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1569 switches::kEnablePepperTesting))
1570 return true;
1571 if (IsExtensionOrSharedModuleWhitelisted(url, allowed_compositor_origins_))
1572 return true;
1574 chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
1575 return channel <= chrome::VersionInfo::CHANNEL_DEV;
1576 #else
1577 return false;
1578 #endif
1581 content::BrowserPluginDelegate*
1582 ChromeContentRendererClient::CreateBrowserPluginDelegate(
1583 content::RenderFrame* render_frame,
1584 const std::string& mime_type,
1585 const GURL& original_url) {
1586 #if defined(ENABLE_EXTENSIONS)
1587 if (mime_type == content::kBrowserPluginMimeType) {
1588 return new extensions::ExtensionsGuestViewContainer(render_frame);
1589 } else {
1590 return new extensions::MimeHandlerViewContainer(
1591 render_frame, mime_type, original_url);
1593 #else
1594 return NULL;
1595 #endif
1598 void ChromeContentRendererClient::RecordRappor(const std::string& metric,
1599 const std::string& sample) {
1600 RenderThread::Get()->Send(new ChromeViewHostMsg_RecordRappor(metric, sample));
1603 void ChromeContentRendererClient::RecordRapporURL(const std::string& metric,
1604 const GURL& url) {
1605 RenderThread::Get()->Send(new ChromeViewHostMsg_RecordRapporURL(metric, url));
1608 scoped_ptr<blink::WebAppBannerClient>
1609 ChromeContentRendererClient::CreateAppBannerClient(
1610 content::RenderFrame* render_frame) {
1611 return scoped_ptr<blink::WebAppBannerClient>(
1612 new AppBannerClient(render_frame));
1615 void ChromeContentRendererClient::AddImageContextMenuProperties(
1616 const blink::WebURLResponse& response,
1617 std::map<std::string, std::string>* properties) {
1618 DCHECK(properties);
1619 WebString header_key(ASCIIToUTF16(
1620 data_reduction_proxy::chrome_proxy_header()));
1621 if (!response.httpHeaderField(header_key).isNull() &&
1622 response.httpHeaderField(header_key).utf8().find(
1623 data_reduction_proxy::chrome_proxy_lo_fi_directive()) !=
1624 std::string::npos) {
1625 (*properties)[data_reduction_proxy::chrome_proxy_header()] =
1626 data_reduction_proxy::chrome_proxy_lo_fi_directive();