ExtensionSyncService cleanup: process uninstalls in one step
[chromium-blink-merge.git] / chrome / renderer / chrome_content_renderer_client.cc
blob48bc0a03a8d6c08e0b4d839a8606e632ac7071c1
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 using autofill::AutofillAgent;
158 using autofill::PasswordAutofillAgent;
159 using autofill::PasswordGenerationAgent;
160 using base::ASCIIToUTF16;
161 using base::UserMetricsAction;
162 using content::PluginInstanceThrottler;
163 using content::RenderFrame;
164 using content::RenderThread;
165 using content::WebPluginInfo;
166 using extensions::Extension;
167 using blink::WebCache;
168 using blink::WebConsoleMessage;
169 using blink::WebDataSource;
170 using blink::WebDocument;
171 using blink::WebLocalFrame;
172 using blink::WebPlugin;
173 using blink::WebPluginParams;
174 using blink::WebSecurityOrigin;
175 using blink::WebSecurityPolicy;
176 using blink::WebString;
177 using blink::WebURL;
178 using blink::WebURLError;
179 using blink::WebURLRequest;
180 using blink::WebURLResponse;
181 using blink::WebVector;
183 namespace {
185 ChromeContentRendererClient* g_current_client;
187 // Whitelist PPAPI for Android Runtime for Chromium. (See crbug.com/383937)
188 #if defined(ENABLE_PLUGINS)
189 const char* const kPredefinedAllowedCameraDeviceOrigins[] = {
190 "6EAED1924DB611B6EEF2A664BD077BE7EAD33B8F",
191 "4EB74897CB187C7633357C2FE832E0AD6A44883A"
194 const char* const kPredefinedAllowedCompositorOrigins[] = {
195 "6EAED1924DB611B6EEF2A664BD077BE7EAD33B8F",
196 "4EB74897CB187C7633357C2FE832E0AD6A44883A"
198 #endif
200 #if defined(ENABLE_PLUGINS)
201 void AppendParams(const std::vector<base::string16>& additional_names,
202 const std::vector<base::string16>& additional_values,
203 WebVector<WebString>* existing_names,
204 WebVector<WebString>* existing_values) {
205 DCHECK(additional_names.size() == additional_values.size());
206 DCHECK(existing_names->size() == existing_values->size());
208 size_t existing_size = existing_names->size();
209 size_t total_size = existing_size + additional_names.size();
211 WebVector<WebString> names(total_size);
212 WebVector<WebString> values(total_size);
214 for (size_t i = 0; i < existing_size; ++i) {
215 names[i] = (*existing_names)[i];
216 values[i] = (*existing_values)[i];
219 for (size_t i = 0; i < additional_names.size(); ++i) {
220 names[existing_size + i] = additional_names[i];
221 values[existing_size + i] = additional_values[i];
224 existing_names->swap(names);
225 existing_values->swap(values);
228 // For certain sandboxed Pepper plugins, use the JavaScript Content Settings.
229 bool ShouldUseJavaScriptSettingForPlugin(const WebPluginInfo& plugin) {
230 if (plugin.type != WebPluginInfo::PLUGIN_TYPE_PEPPER_IN_PROCESS &&
231 plugin.type != WebPluginInfo::PLUGIN_TYPE_PEPPER_OUT_OF_PROCESS) {
232 return false;
235 #if !defined(DISABLE_NACL)
236 // Treat Native Client invocations like JavaScript.
237 if (plugin.name == ASCIIToUTF16(nacl::kNaClPluginName))
238 return true;
239 #endif
241 #if defined(WIDEVINE_CDM_AVAILABLE) && defined(ENABLE_PEPPER_CDMS)
242 // Treat CDM invocations like JavaScript.
243 if (plugin.name == ASCIIToUTF16(kWidevineCdmDisplayName)) {
244 DCHECK(plugin.type == WebPluginInfo::PLUGIN_TYPE_PEPPER_OUT_OF_PROCESS);
245 return true;
247 #endif // defined(WIDEVINE_CDM_AVAILABLE) && defined(ENABLE_PEPPER_CDMS)
249 return false;
251 #endif // defined(ENABLE_PLUGINS)
253 #if defined(ENABLE_SPELLCHECK)
254 class SpellCheckReplacer : public content::RenderViewVisitor {
255 public:
256 explicit SpellCheckReplacer(SpellCheck* spellcheck)
257 : spellcheck_(spellcheck) {}
258 bool Visit(content::RenderView* render_view) override;
260 private:
261 SpellCheck* spellcheck_; // New shared spellcheck for all views. Weak Ptr.
262 DISALLOW_COPY_AND_ASSIGN(SpellCheckReplacer);
265 bool SpellCheckReplacer::Visit(content::RenderView* render_view) {
266 SpellCheckProvider* provider = SpellCheckProvider::Get(render_view);
267 DCHECK(provider);
268 provider->set_spellcheck(spellcheck_);
269 return true;
271 #endif
273 #if defined(ENABLE_EXTENSIONS)
274 void IsGuestViewApiAvailableToScriptContext(
275 bool* api_is_available,
276 extensions::ScriptContext* context) {
277 if (context->GetAvailability("guestViewInternal").is_available()) {
278 *api_is_available = true;
281 #endif
283 #if defined(ENABLE_PLUGINS)
284 // Presence of the poster param within plugin object tags.
285 // These numeric values are used in UMA logs; do not change them.
286 enum PosterParamPresence {
287 POSTER_PRESENCE_NO_PARAM_PPS_DISABLED = 0,
288 POSTER_PRESENCE_NO_PARAM_PPS_ENABLED = 1,
289 POSTER_PRESENCE_PARAM_EXISTS_PPS_DISABLED = 2,
290 POSTER_PRESENCE_PARAM_EXISTS_PPS_ENABLED = 3,
291 POSTER_PRESENCE_NUM_ITEMS
294 const char kPluginPowerSaverPosterParamPresenceHistogram[] =
295 "Plugin.PowerSaver.PosterParamPresence";
297 void RecordPosterParamPresence(PosterParamPresence presence) {
298 UMA_HISTOGRAM_ENUMERATION(kPluginPowerSaverPosterParamPresenceHistogram,
299 presence, POSTER_PRESENCE_NUM_ITEMS);
302 void TrackPosterParamPresence(const blink::WebPluginParams& params,
303 bool power_saver_enabled) {
304 DCHECK_EQ(params.attributeNames.size(), params.attributeValues.size());
306 for (size_t i = 0; i < params.attributeNames.size(); ++i) {
307 if (params.attributeNames[i].utf8() == "poster") {
308 if (power_saver_enabled)
309 RecordPosterParamPresence(POSTER_PRESENCE_PARAM_EXISTS_PPS_ENABLED);
310 else
311 RecordPosterParamPresence(POSTER_PRESENCE_PARAM_EXISTS_PPS_DISABLED);
313 return;
317 if (power_saver_enabled)
318 RecordPosterParamPresence(POSTER_PRESENCE_NO_PARAM_PPS_ENABLED);
319 else
320 RecordPosterParamPresence(POSTER_PRESENCE_NO_PARAM_PPS_DISABLED);
323 std::string GetPluginInstancePosterAttribute(
324 const blink::WebPluginParams& params) {
325 DCHECK_EQ(params.attributeNames.size(), params.attributeValues.size());
327 for (size_t i = 0; i < params.attributeNames.size(); ++i) {
328 if (params.attributeNames[i].utf8() == "poster" &&
329 !params.attributeValues[i].isEmpty()) {
330 return params.attributeValues[i].utf8();
333 return std::string();
335 #endif
337 #if defined(ENABLE_EXTENSIONS)
338 bool IsStandaloneExtensionProcess() {
339 return base::CommandLine::ForCurrentProcess()->HasSwitch(
340 extensions::switches::kExtensionProcess);
342 #endif
343 } // namespace
345 ChromeContentRendererClient::ChromeContentRendererClient() {
346 g_current_client = this;
348 #if defined(ENABLE_EXTENSIONS)
349 extensions::ExtensionsClient::Set(
350 extensions::ChromeExtensionsClient::GetInstance());
351 extensions::ExtensionsRendererClient::Set(
352 ChromeExtensionsRendererClient::GetInstance());
353 #endif
354 #if defined(ENABLE_PLUGINS)
355 for (size_t i = 0; i < arraysize(kPredefinedAllowedCameraDeviceOrigins); ++i)
356 allowed_camera_device_origins_.insert(
357 kPredefinedAllowedCameraDeviceOrigins[i]);
358 for (size_t i = 0; i < arraysize(kPredefinedAllowedCompositorOrigins); ++i)
359 allowed_compositor_origins_.insert(kPredefinedAllowedCompositorOrigins[i]);
360 #endif
363 ChromeContentRendererClient::~ChromeContentRendererClient() {
364 g_current_client = NULL;
367 void ChromeContentRendererClient::RenderThreadStarted() {
368 RenderThread* thread = RenderThread::Get();
370 chrome_observer_.reset(new ChromeRenderProcessObserver());
371 web_cache_observer_.reset(new web_cache::WebCacheRenderProcessObserver());
373 #if defined(ENABLE_EXTENSIONS)
374 extension_dispatcher_delegate_.reset(
375 new ChromeExtensionsDispatcherDelegate());
376 // ChromeRenderViewTest::SetUp() creates its own ExtensionDispatcher and
377 // injects it using SetExtensionDispatcher(). Don't overwrite it.
378 if (!extension_dispatcher_) {
379 extension_dispatcher_.reset(
380 new extensions::Dispatcher(extension_dispatcher_delegate_.get()));
382 permissions_policy_delegate_.reset(
383 new extensions::RendererPermissionsPolicyDelegate(
384 extension_dispatcher_.get()));
385 guest_view_container_dispatcher_.reset(
386 new extensions::ExtensionsGuestViewContainerDispatcher());
387 #endif
389 prescient_networking_dispatcher_.reset(
390 new network_hints::PrescientNetworkingDispatcher());
391 #if defined(ENABLE_SPELLCHECK)
392 // ChromeRenderViewTest::SetUp() creates a Spellcheck and injects it using
393 // SetSpellcheck(). Don't overwrite it.
394 if (!spellcheck_) {
395 spellcheck_.reset(new SpellCheck());
396 thread->AddObserver(spellcheck_.get());
398 #endif
399 visited_link_slave_.reset(new visitedlink::VisitedLinkSlave());
400 #if defined(FULL_SAFE_BROWSING)
401 phishing_classifier_.reset(safe_browsing::PhishingClassifierFilter::Create());
402 #endif
403 prerender_dispatcher_.reset(new prerender::PrerenderDispatcher());
404 #if defined(ENABLE_WEBRTC)
405 webrtc_logging_message_filter_ = new WebRtcLoggingMessageFilter(
406 RenderThread::Get()->GetIOMessageLoopProxy());
407 #endif
409 thread->AddObserver(chrome_observer_.get());
410 thread->AddObserver(web_cache_observer_.get());
411 #if defined(ENABLE_EXTENSIONS)
412 thread->AddObserver(extension_dispatcher_.get());
413 thread->AddObserver(guest_view_container_dispatcher_.get());
414 #endif
415 #if defined(FULL_SAFE_BROWSING)
416 thread->AddObserver(phishing_classifier_.get());
417 #endif
418 thread->AddObserver(visited_link_slave_.get());
419 thread->AddObserver(prerender_dispatcher_.get());
420 thread->AddObserver(SearchBouncer::GetInstance());
422 #if defined(ENABLE_WEBRTC)
423 thread->AddFilter(webrtc_logging_message_filter_.get());
424 #endif
425 #if defined(ENABLE_EXTENSIONS)
426 thread->AddFilter(new CastIPCDispatcher(
427 RenderThread::Get()->GetIOMessageLoopProxy()));
428 #endif
430 thread->RegisterExtension(extensions_v8::ExternalExtension::Get());
431 thread->RegisterExtension(extensions_v8::LoadTimesExtension::Get());
433 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
434 if (command_line->HasSwitch(switches::kEnableBenchmarking))
435 thread->RegisterExtension(extensions_v8::BenchmarkingExtension::Get());
436 if (command_line->HasSwitch(switches::kEnableNetBenchmarking))
437 thread->RegisterExtension(extensions_v8::NetBenchmarkingExtension::Get());
438 if (command_line->HasSwitch(switches::kInstantProcess))
439 thread->RegisterExtension(extensions_v8::SearchBoxExtension::Get());
441 // chrome-search: and chrome-distiller: pages should not be accessible by
442 // normal content, and should also be unable to script anything but themselves
443 // (to help limit the damage that a corrupt page could cause).
444 WebString chrome_search_scheme(ASCIIToUTF16(chrome::kChromeSearchScheme));
446 // The Instant process can only display the content but not read it. Other
447 // processes can't display it or read it.
448 if (!command_line->HasSwitch(switches::kInstantProcess))
449 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(chrome_search_scheme);
451 WebString dom_distiller_scheme(
452 ASCIIToUTF16(dom_distiller::kDomDistillerScheme));
453 // TODO(nyquist): Add test to ensure this happens when the flag is set.
454 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(dom_distiller_scheme);
456 #if defined(OS_CHROMEOS)
457 WebString external_file_scheme(ASCIIToUTF16(content::kExternalFileScheme));
458 WebSecurityPolicy::registerURLSchemeAsLocal(external_file_scheme);
459 #endif
461 #if defined(ENABLE_IPC_FUZZER)
462 if (command_line->HasSwitch(switches::kIpcDumpDirectory)) {
463 base::FilePath dump_directory =
464 command_line->GetSwitchValuePath(switches::kIpcDumpDirectory);
465 IPC::ChannelProxy::OutgoingMessageFilter* filter =
466 LoadExternalIPCDumper(dump_directory);
467 thread->GetChannel()->set_outgoing_message_filter(filter);
469 #endif
471 // chrome-search: pages should not be accessible by bookmarklets
472 // or javascript: URLs typed in the omnibox.
473 WebSecurityPolicy::registerURLSchemeAsNotAllowingJavascriptURLs(
474 chrome_search_scheme);
476 // chrome-search:, chrome-extension:, and chrome-extension-resource:
477 // resources shouldn't trigger insecure content warnings.
478 WebSecurityPolicy::registerURLSchemeAsSecure(chrome_search_scheme);
480 WebString extension_scheme(ASCIIToUTF16(extensions::kExtensionScheme));
481 WebSecurityPolicy::registerURLSchemeAsSecure(extension_scheme);
483 WebString extension_resource_scheme(
484 ASCIIToUTF16(extensions::kExtensionResourceScheme));
485 WebSecurityPolicy::registerURLSchemeAsSecure(extension_resource_scheme);
487 // chrome:, chrome-extension:, chrome-extension-resource: resources should be
488 // allowed to receive CORS requests.
489 WebSecurityPolicy::registerURLSchemeAsCORSEnabled(extension_scheme);
490 WebSecurityPolicy::registerURLSchemeAsCORSEnabled(extension_resource_scheme);
492 // chrome-extension: resources should bypass Content Security Policy checks
493 // when included in protected resources.
494 WebSecurityPolicy::registerURLSchemeAsBypassingContentSecurityPolicy(
495 extension_scheme);
496 WebSecurityPolicy::registerURLSchemeAsBypassingContentSecurityPolicy(
497 extension_resource_scheme);
499 #if defined(ENABLE_PRINT_PREVIEW)
500 pdf_print_client_.reset(new ChromePDFPrintClient());
501 pdf::PepperPDFHost::SetPrintClient(pdf_print_client_.get());
502 #endif
504 std::set<GURL> origins;
505 GetSecureOriginWhitelist(&origins);
506 for (const GURL& origin : origins) {
507 WebSecurityPolicy::addOriginTrustworthyWhiteList(
508 WebSecurityOrigin::create(origin));
512 void ChromeContentRendererClient::RenderFrameCreated(
513 content::RenderFrame* render_frame) {
514 new ChromeRenderFrameObserver(render_frame);
516 bool should_whitelist_for_content_settings =
517 base::CommandLine::ForCurrentProcess()->HasSwitch(
518 switches::kInstantProcess);
519 extensions::Dispatcher* ext_dispatcher = NULL;
520 #if defined(ENABLE_EXTENSIONS)
521 ext_dispatcher = extension_dispatcher_.get();
522 #endif
523 ContentSettingsObserver* content_settings = new ContentSettingsObserver(
524 render_frame, ext_dispatcher, should_whitelist_for_content_settings);
525 if (chrome_observer_.get()) {
526 content_settings->SetContentSettingRules(
527 chrome_observer_->content_setting_rules());
530 #if defined(ENABLE_EXTENSIONS)
531 new extensions::ExtensionsRenderFrameObserver(render_frame);
532 new extensions::ExtensionFrameHelper(render_frame, ext_dispatcher);
533 ext_dispatcher->OnRenderFrameCreated(render_frame);
534 #endif
536 #if defined(ENABLE_PLUGINS)
537 new PepperHelper(render_frame);
538 #endif
540 #if !defined(DISABLE_NACL)
541 new nacl::NaClHelper(render_frame);
542 #endif
544 // TODO(jam): when the frame tree moves into content and parent() works at
545 // RenderFrame construction, simplify this by just checking parent().
546 if (render_frame->GetRenderView()->GetMainRenderFrame() != render_frame) {
547 // Avoid any race conditions from having the browser tell subframes that
548 // they're prerendering.
549 if (prerender::PrerenderHelper::IsPrerendering(
550 render_frame->GetRenderView()->GetMainRenderFrame())) {
551 new prerender::PrerenderHelper(render_frame);
555 if (render_frame->GetRenderView()->GetMainRenderFrame() == render_frame) {
556 // Only attach NetErrorHelper to the main frame, since only the main frame
557 // should get error pages.
558 new NetErrorHelper(render_frame);
561 PasswordAutofillAgent* password_autofill_agent =
562 new PasswordAutofillAgent(render_frame);
563 PasswordGenerationAgent* password_generation_agent =
564 new PasswordGenerationAgent(render_frame, password_autofill_agent);
565 new AutofillAgent(render_frame, password_autofill_agent,
566 password_generation_agent);
569 void ChromeContentRendererClient::RenderViewCreated(
570 content::RenderView* render_view) {
572 #if defined(ENABLE_EXTENSIONS)
573 new extensions::ExtensionHelper(render_view, extension_dispatcher_.get());
574 #endif
575 new PageLoadHistograms(render_view);
576 #if defined(ENABLE_PRINTING)
577 new printing::PrintWebViewHelper(
578 render_view,
579 scoped_ptr<printing::PrintWebViewHelper::Delegate>(
580 new ChromePrintWebViewHelperDelegate()));
581 #endif
582 #if defined(ENABLE_SPELLCHECK)
583 new SpellCheckProvider(render_view, spellcheck_.get());
584 #endif
585 new prerender::PrerendererClient(render_view);
586 #if defined(FULL_SAFE_BROWSING)
587 safe_browsing::MalwareDOMDetails::Create(render_view);
588 #endif
590 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
591 if (command_line->HasSwitch(switches::kInstantProcess))
592 new SearchBox(render_view);
594 new ChromeRenderViewObserver(render_view, web_cache_observer_.get());
596 new password_manager::CredentialManagerClient(render_view);
600 SkBitmap* ChromeContentRendererClient::GetSadPluginBitmap() {
601 return const_cast<SkBitmap*>(ResourceBundle::GetSharedInstance().
602 GetImageNamed(IDR_SAD_PLUGIN).ToSkBitmap());
605 SkBitmap* ChromeContentRendererClient::GetSadWebViewBitmap() {
606 return const_cast<SkBitmap*>(ResourceBundle::GetSharedInstance().
607 GetImageNamed(IDR_SAD_WEBVIEW).ToSkBitmap());
610 #if defined(ENABLE_EXTENSIONS)
611 const Extension* ChromeContentRendererClient::GetExtensionByOrigin(
612 const WebSecurityOrigin& origin) const {
613 if (!base::EqualsASCII(origin.protocol(), extensions::kExtensionScheme))
614 return NULL;
616 const std::string extension_id = origin.host().utf8().data();
617 return extension_dispatcher_->extensions()->GetByID(extension_id);
619 #endif
621 scoped_ptr<blink::WebPluginPlaceholder>
622 ChromeContentRendererClient::CreatePluginPlaceholder(
623 content::RenderFrame* render_frame,
624 blink::WebLocalFrame* frame,
625 const blink::WebPluginParams& orig_params) {
626 return CreateShadowDOMPlaceholderForPluginInfo(
627 render_frame, frame, orig_params);
630 bool ChromeContentRendererClient::OverrideCreatePlugin(
631 content::RenderFrame* render_frame,
632 blink::WebLocalFrame* frame,
633 const WebPluginParams& params,
634 WebPlugin** plugin) {
635 std::string orig_mime_type = params.mimeType.utf8();
636 #if defined(ENABLE_EXTENSIONS)
637 if (orig_mime_type == content::kBrowserPluginMimeType) {
638 bool guest_view_api_available = false;
639 extension_dispatcher_->script_context_set().ForEach(
640 render_frame, base::Bind(&IsGuestViewApiAvailableToScriptContext,
641 &guest_view_api_available));
642 if (guest_view_api_available)
643 return false;
645 #endif
647 GURL url(params.url);
648 #if defined(ENABLE_PLUGINS)
649 ChromeViewHostMsg_GetPluginInfo_Output output;
650 render_frame->Send(new ChromeViewHostMsg_GetPluginInfo(
651 render_frame->GetRoutingID(), url, frame->top()->document().url(),
652 orig_mime_type, &output));
653 *plugin = CreatePlugin(render_frame, frame, params, output);
654 #else // !defined(ENABLE_PLUGINS)
656 #if defined(OS_ANDROID)
657 if (plugins::MobileYouTubePlugin::IsYouTubeURL(url, orig_mime_type)) {
658 base::StringPiece template_html(
659 ResourceBundle::GetSharedInstance().GetRawDataResource(
660 IDR_MOBILE_YOUTUBE_PLUGIN_HTML));
661 *plugin = (new plugins::MobileYouTubePlugin(render_frame, frame, params,
662 template_html))->plugin();
663 return true;
665 #endif // defined(OS_ANDROID)
667 PluginUMAReporter::GetInstance()->ReportPluginMissing(orig_mime_type, url);
668 *plugin = NonLoadablePluginPlaceholder::CreateNotSupportedPlugin(
669 render_frame, frame, params)->plugin();
671 #endif // defined(ENABLE_PLUGINS)
672 return true;
675 WebPlugin* ChromeContentRendererClient::CreatePluginReplacement(
676 content::RenderFrame* render_frame,
677 const base::FilePath& plugin_path) {
678 return NonLoadablePluginPlaceholder::CreateErrorPlugin(render_frame,
679 plugin_path)->plugin();
682 void ChromeContentRendererClient::DeferMediaLoad(
683 content::RenderFrame* render_frame,
684 const base::Closure& closure) {
685 #if defined(OS_ANDROID)
686 // Chromium for Android doesn't support prerender yet.
687 closure.Run();
688 return;
689 #else
690 if (!prerender::PrerenderHelper::IsPrerendering(render_frame)) {
691 closure.Run();
692 return;
695 // Lifetime is tied to |render_frame| via content::RenderFrameObserver.
696 new prerender::PrerenderMediaLoadDeferrer(render_frame, closure);
697 #endif
700 #if defined(ENABLE_PLUGINS)
701 WebPlugin* ChromeContentRendererClient::CreatePlugin(
702 content::RenderFrame* render_frame,
703 blink::WebLocalFrame* frame,
704 const WebPluginParams& original_params,
705 const ChromeViewHostMsg_GetPluginInfo_Output& output) {
706 const WebPluginInfo& info = output.plugin;
707 const std::string& actual_mime_type = output.actual_mime_type;
708 const base::string16& group_name = output.group_name;
709 const std::string& identifier = output.group_identifier;
710 ChromeViewHostMsg_GetPluginInfo_Status status = output.status;
711 GURL url(original_params.url);
712 std::string orig_mime_type = original_params.mimeType.utf8();
713 ChromePluginPlaceholder* placeholder = NULL;
715 // If the browser plugin is to be enabled, this should be handled by the
716 // renderer, so the code won't reach here due to the early exit in
717 // OverrideCreatePlugin.
718 if (status == ChromeViewHostMsg_GetPluginInfo_Status::kNotFound ||
719 orig_mime_type == content::kBrowserPluginMimeType) {
720 PluginUMAReporter::GetInstance()->ReportPluginMissing(orig_mime_type, url);
721 placeholder = ChromePluginPlaceholder::CreateLoadableMissingPlugin(
722 render_frame, frame, original_params);
723 } else {
724 // TODO(bauerb): This should be in content/.
725 WebPluginParams params(original_params);
726 for (size_t i = 0; i < info.mime_types.size(); ++i) {
727 if (info.mime_types[i].mime_type == actual_mime_type) {
728 AppendParams(info.mime_types[i].additional_param_names,
729 info.mime_types[i].additional_param_values,
730 &params.attributeNames, &params.attributeValues);
731 break;
734 if (params.mimeType.isNull() && (actual_mime_type.size() > 0)) {
735 // Webkit might say that mime type is null while we already know the
736 // actual mime type via ChromeViewHostMsg_GetPluginInfo. In that case
737 // we should use what we know since WebpluginDelegateProxy does some
738 // specific initializations based on this information.
739 params.mimeType = WebString::fromUTF8(actual_mime_type.c_str());
742 ContentSettingsObserver* observer =
743 ContentSettingsObserver::Get(render_frame);
745 const ContentSettingsType content_type =
746 ShouldUseJavaScriptSettingForPlugin(info)
747 ? CONTENT_SETTINGS_TYPE_JAVASCRIPT
748 : CONTENT_SETTINGS_TYPE_PLUGINS;
750 if ((status == ChromeViewHostMsg_GetPluginInfo_Status::kUnauthorized ||
751 status == ChromeViewHostMsg_GetPluginInfo_Status::kBlocked) &&
752 observer->IsPluginTemporarilyAllowed(identifier)) {
753 status = ChromeViewHostMsg_GetPluginInfo_Status::kAllowed;
756 #if defined(OS_WIN)
757 // In Windows we need to check if we can load NPAPI plugins.
758 // For example, if the render view is in the Ash desktop, we should not.
759 // If user is on ALLOW or DETECT setting, loading needs to be blocked here.
760 if ((status == ChromeViewHostMsg_GetPluginInfo_Status::kAllowed ||
761 status ==
762 ChromeViewHostMsg_GetPluginInfo_Status::kPlayImportantContent) &&
763 info.type == content::WebPluginInfo::PLUGIN_TYPE_NPAPI) {
764 if (observer->AreNPAPIPluginsBlocked())
765 status = ChromeViewHostMsg_GetPluginInfo_Status::kNPAPINotSupported;
767 #endif
769 auto create_blocked_plugin =
770 [&render_frame, &frame, &params, &info, &identifier, &group_name](
771 int template_id, const base::string16& message) {
772 return ChromePluginPlaceholder::CreateBlockedPlugin(
773 render_frame, frame, params, info, identifier, group_name,
774 template_id, message, PlaceholderPosterInfo());
776 switch (status) {
777 case ChromeViewHostMsg_GetPluginInfo_Status::kNotFound: {
778 NOTREACHED();
779 break;
781 case ChromeViewHostMsg_GetPluginInfo_Status::kAllowed:
782 case ChromeViewHostMsg_GetPluginInfo_Status::kPlayImportantContent: {
783 #if !defined(DISABLE_NACL) && defined(ENABLE_EXTENSIONS)
784 const bool is_nacl_plugin =
785 info.name == ASCIIToUTF16(nacl::kNaClPluginName);
786 const bool is_nacl_mime_type =
787 actual_mime_type == nacl::kNaClPluginMimeType;
788 const bool is_pnacl_mime_type =
789 actual_mime_type == nacl::kPnaclPluginMimeType;
790 if (is_nacl_plugin || is_nacl_mime_type || is_pnacl_mime_type) {
791 bool is_nacl_unrestricted = false;
792 if (is_nacl_mime_type) {
793 is_nacl_unrestricted =
794 base::CommandLine::ForCurrentProcess()->HasSwitch(
795 switches::kEnableNaCl);
796 } else if (is_pnacl_mime_type) {
797 is_nacl_unrestricted = true;
799 GURL manifest_url;
800 GURL app_url;
801 if (is_nacl_mime_type || is_pnacl_mime_type) {
802 // Normal NaCl/PNaCl embed. The app URL is the page URL.
803 manifest_url = url;
804 app_url = frame->top()->document().url();
805 } else {
806 // NaCl is being invoked as a content handler. Look up the NaCl
807 // module using the MIME type. The app URL is the manifest URL.
808 manifest_url = GetNaClContentHandlerURL(actual_mime_type, info);
809 app_url = manifest_url;
811 const Extension* extension =
812 g_current_client->extension_dispatcher_->extensions()->
813 GetExtensionOrAppByURL(manifest_url);
814 if (!IsNaClAllowed(manifest_url,
815 app_url,
816 is_nacl_unrestricted,
817 extension,
818 &params)) {
819 WebString error_message;
820 if (is_nacl_mime_type) {
821 error_message =
822 "Only unpacked extensions and apps installed from the Chrome "
823 "Web Store can load NaCl modules without enabling Native "
824 "Client in about:flags.";
825 } else if (is_pnacl_mime_type) {
826 error_message =
827 "Portable Native Client must not be disabled in about:flags.";
829 frame->addMessageToConsole(
830 WebConsoleMessage(WebConsoleMessage::LevelError,
831 error_message));
832 placeholder = create_blocked_plugin(
833 IDR_BLOCKED_PLUGIN_HTML,
834 #if defined(OS_CHROMEOS)
835 l10n_util::GetStringUTF16(IDS_NACL_PLUGIN_BLOCKED));
836 #else
837 l10n_util::GetStringFUTF16(IDS_PLUGIN_BLOCKED, group_name));
838 #endif
839 break;
842 #endif // !defined(DISABLE_NACL) && defined(ENABLE_EXTENSIONS)
844 // Delay loading plugins if prerendering.
845 // TODO(mmenke): In the case of prerendering, feed into
846 // ChromeContentRendererClient::CreatePlugin instead, to
847 // reduce the chance of future regressions.
848 bool is_prerendering =
849 prerender::PrerenderHelper::IsPrerendering(render_frame);
850 bool power_saver_enabled =
851 status ==
852 ChromeViewHostMsg_GetPluginInfo_Status::kPlayImportantContent;
853 bool blocked_for_background_tab =
854 render_frame->IsHidden() && power_saver_enabled;
856 if (info.name == ASCIIToUTF16(content::kFlashPluginName))
857 TrackPosterParamPresence(params, power_saver_enabled);
859 PlaceholderPosterInfo poster_info;
860 if (power_saver_enabled) {
861 poster_info.poster_attribute =
862 GetPluginInstancePosterAttribute(params);
863 poster_info.base_url = frame->document().url();
866 if (blocked_for_background_tab || is_prerendering ||
867 !poster_info.poster_attribute.empty()) {
868 placeholder = ChromePluginPlaceholder::CreateBlockedPlugin(
869 render_frame, frame, params, info, identifier, group_name,
870 poster_info.poster_attribute.empty() ? IDR_BLOCKED_PLUGIN_HTML
871 : IDR_PLUGIN_POSTER_HTML,
872 l10n_util::GetStringFUTF16(IDS_PLUGIN_BLOCKED, group_name),
873 poster_info);
874 placeholder->set_blocked_for_background_tab(
875 blocked_for_background_tab);
876 placeholder->set_blocked_for_prerendering(is_prerendering);
877 placeholder->set_power_saver_enabled(power_saver_enabled);
878 break;
881 scoped_ptr<content::PluginInstanceThrottler> throttler;
882 if (power_saver_enabled) {
883 throttler = PluginInstanceThrottler::Create();
884 // PluginPreroller manages its own lifetime.
885 new PluginPreroller(
886 render_frame, frame, params, info, identifier, group_name,
887 l10n_util::GetStringFUTF16(IDS_PLUGIN_BLOCKED, group_name),
888 throttler.get());
891 return render_frame->CreatePlugin(frame, info, params,
892 throttler.Pass());
894 case ChromeViewHostMsg_GetPluginInfo_Status::kNPAPINotSupported: {
895 RenderThread::Get()->RecordAction(
896 UserMetricsAction("Plugin_NPAPINotSupported"));
897 placeholder = create_blocked_plugin(
898 IDR_BLOCKED_PLUGIN_HTML,
899 l10n_util::GetStringUTF16(IDS_PLUGIN_NOT_SUPPORTED_METRO));
900 render_frame->Send(new ChromeViewHostMsg_NPAPINotSupported(
901 render_frame->GetRoutingID(), identifier));
902 break;
904 case ChromeViewHostMsg_GetPluginInfo_Status::kDisabled: {
905 PluginUMAReporter::GetInstance()->ReportPluginDisabled(orig_mime_type,
906 url);
907 placeholder = create_blocked_plugin(
908 IDR_DISABLED_PLUGIN_HTML,
909 l10n_util::GetStringFUTF16(IDS_PLUGIN_DISABLED, group_name));
910 break;
912 case ChromeViewHostMsg_GetPluginInfo_Status::kOutdatedBlocked: {
913 #if defined(ENABLE_PLUGIN_INSTALLATION)
914 placeholder = create_blocked_plugin(
915 IDR_BLOCKED_PLUGIN_HTML,
916 l10n_util::GetStringFUTF16(IDS_PLUGIN_OUTDATED, group_name));
917 render_frame->Send(new ChromeViewHostMsg_BlockedOutdatedPlugin(
918 render_frame->GetRoutingID(), placeholder->CreateRoutingId(),
919 identifier));
920 #else
921 NOTREACHED();
922 #endif
923 break;
925 case ChromeViewHostMsg_GetPluginInfo_Status::kOutdatedDisallowed: {
926 placeholder = create_blocked_plugin(
927 IDR_BLOCKED_PLUGIN_HTML,
928 l10n_util::GetStringFUTF16(IDS_PLUGIN_OUTDATED, group_name));
929 break;
931 case ChromeViewHostMsg_GetPluginInfo_Status::kUnauthorized: {
932 placeholder = create_blocked_plugin(
933 IDR_BLOCKED_PLUGIN_HTML,
934 l10n_util::GetStringFUTF16(IDS_PLUGIN_NOT_AUTHORIZED, group_name));
935 if (info.type != content::WebPluginInfo::PLUGIN_TYPE_NPAPI) {
936 render_frame->Send(new ChromeViewHostMsg_BlockedUnauthorizedPlugin(
937 render_frame->GetRoutingID(),
938 group_name,
939 identifier));
941 observer->DidBlockContentType(content_type, group_name);
942 break;
944 case ChromeViewHostMsg_GetPluginInfo_Status::kBlocked: {
945 placeholder = create_blocked_plugin(
946 IDR_BLOCKED_PLUGIN_HTML,
947 l10n_util::GetStringFUTF16(IDS_PLUGIN_BLOCKED, group_name));
948 RenderThread::Get()->RecordAction(UserMetricsAction("Plugin_Blocked"));
949 observer->DidBlockContentType(content_type, group_name);
950 break;
952 case ChromeViewHostMsg_GetPluginInfo_Status::kBlockedByPolicy: {
953 placeholder = create_blocked_plugin(
954 IDR_BLOCKED_PLUGIN_HTML,
955 l10n_util::GetStringFUTF16(IDS_PLUGIN_BLOCKED_BY_POLICY,
956 group_name));
957 placeholder->DisallowLoading();
958 RenderThread::Get()->RecordAction(
959 UserMetricsAction("Plugin_BlockedByPolicy"));
960 observer->DidBlockContentType(content_type, group_name);
961 break;
965 placeholder->SetStatus(status);
966 return placeholder->plugin();
968 #endif // defined(ENABLE_PLUGINS)
970 // For NaCl content handling plugins, the NaCl manifest is stored in an
971 // additonal 'nacl' param associated with the MIME type.
972 // static
973 GURL ChromeContentRendererClient::GetNaClContentHandlerURL(
974 const std::string& actual_mime_type,
975 const content::WebPluginInfo& plugin) {
976 // Look for the manifest URL among the MIME type's additonal parameters.
977 const char kNaClPluginManifestAttribute[] = "nacl";
978 base::string16 nacl_attr = ASCIIToUTF16(kNaClPluginManifestAttribute);
979 for (size_t i = 0; i < plugin.mime_types.size(); ++i) {
980 if (plugin.mime_types[i].mime_type == actual_mime_type) {
981 const content::WebPluginMimeType& content_type = plugin.mime_types[i];
982 for (size_t i = 0; i < content_type.additional_param_names.size(); ++i) {
983 if (content_type.additional_param_names[i] == nacl_attr)
984 return GURL(content_type.additional_param_values[i]);
986 break;
989 return GURL();
992 #if !defined(DISABLE_NACL)
993 // static
994 bool ChromeContentRendererClient::IsNaClAllowed(
995 const GURL& manifest_url,
996 const GURL& app_url,
997 bool is_nacl_unrestricted,
998 const Extension* extension,
999 WebPluginParams* params) {
1000 // Temporarily allow these whitelisted apps and WebUIs to use NaCl.
1001 std::string app_url_host = app_url.host();
1002 std::string manifest_url_path = manifest_url.path();
1004 bool is_whitelisted_web_ui =
1005 app_url.spec() == chrome::kChromeUIAppListStartPageURL;
1007 bool is_photo_app =
1008 // Whitelisted apps must be served over https.
1009 app_url.SchemeIsCryptographic() && manifest_url.SchemeIsCryptographic() &&
1010 (base::EndsWith(app_url_host, "plus.google.com", false) ||
1011 base::EndsWith(app_url_host, "plus.sandbox.google.com", false)) &&
1012 manifest_url.DomainIs("ssl.gstatic.com") &&
1013 (manifest_url_path.find("s2/oz/nacl/") == 1 ||
1014 manifest_url_path.find("photos/nacl/") == 1);
1016 std::string manifest_fs_host;
1017 if (manifest_url.SchemeIsFileSystem() && manifest_url.inner_url()) {
1018 manifest_fs_host = manifest_url.inner_url()->host();
1020 bool is_hangouts_app =
1021 // Whitelisted apps must be served over secure scheme.
1022 app_url.SchemeIsCryptographic() && manifest_url.SchemeIsFileSystem() &&
1023 manifest_url.inner_url()->SchemeIsCryptographic() &&
1024 (base::EndsWith(app_url_host, "talkgadget.google.com", false) ||
1025 base::EndsWith(app_url_host, "plus.google.com", false) ||
1026 base::EndsWith(app_url_host, "plus.sandbox.google.com", false)) &&
1027 // The manifest must be loaded from the host's FileSystem.
1028 (manifest_fs_host == app_url_host);
1030 bool is_whitelisted_app = is_photo_app || is_hangouts_app;
1032 bool is_invoked_by_webstore_installed_extension = false;
1033 bool is_extension_unrestricted = false;
1034 bool is_extension_force_installed = false;
1035 #if defined(ENABLE_EXTENSIONS)
1036 bool is_extension_from_webstore = extension && extension->from_webstore();
1038 bool is_invoked_by_extension = app_url.SchemeIs("chrome-extension");
1039 bool is_invoked_by_hosted_app = extension &&
1040 extension->is_hosted_app() &&
1041 extension->web_extent().MatchesURL(app_url);
1043 is_invoked_by_webstore_installed_extension = is_extension_from_webstore &&
1044 (is_invoked_by_extension || is_invoked_by_hosted_app);
1046 // Allow built-in extensions and developer mode extensions.
1047 is_extension_unrestricted = extension &&
1048 (extensions::Manifest::IsUnpackedLocation(extension->location()) ||
1049 extensions::Manifest::IsComponentLocation(extension->location()));
1050 // Allow extensions force installed by admin policy.
1051 is_extension_force_installed = extension &&
1052 extensions::Manifest::IsPolicyLocation(extension->location());
1053 #endif // defined(ENABLE_EXTENSIONS)
1055 // Allow NaCl under any of the following circumstances:
1056 // 1) An app or URL is explictly whitelisted above.
1057 // 2) An extension is loaded unpacked or built-in (component) to Chrome.
1058 // 3) An extension is force installed by policy.
1059 // 4) An extension is installed from the webstore, and invoked in that
1060 // context (hosted app URL or chrome-extension:// scheme).
1061 // 5) --enable-nacl is set.
1062 bool is_nacl_allowed_by_location =
1063 is_whitelisted_web_ui ||
1064 is_whitelisted_app ||
1065 is_extension_unrestricted ||
1066 is_extension_force_installed ||
1067 is_invoked_by_webstore_installed_extension;
1068 bool is_nacl_allowed = is_nacl_allowed_by_location || is_nacl_unrestricted;
1069 if (is_nacl_allowed) {
1070 // Make sure that PPAPI 'dev' interfaces are only available for unpacked
1071 // and component extensions. Also allow dev interfaces when --enable-nacl
1072 // is set, but do not allow --enable-nacl to provide dev interfaces to
1073 // webstore installed and other normally allowed URLs.
1074 WebString dev_attribute = WebString::fromUTF8("@dev");
1075 if (is_extension_unrestricted ||
1076 (is_nacl_unrestricted && !is_nacl_allowed_by_location)) {
1077 // Add the special '@dev' attribute.
1078 std::vector<base::string16> param_names;
1079 std::vector<base::string16> param_values;
1080 param_names.push_back(dev_attribute);
1081 param_values.push_back(WebString());
1082 AppendParams(
1083 param_names,
1084 param_values,
1085 &params->attributeNames,
1086 &params->attributeValues);
1087 } else {
1088 // If the params somehow contain '@dev', remove it.
1089 size_t attribute_count = params->attributeNames.size();
1090 for (size_t i = 0; i < attribute_count; ++i) {
1091 if (params->attributeNames[i].equals(dev_attribute))
1092 params->attributeNames[i] = WebString();
1096 return is_nacl_allowed;
1098 #endif // defined(DISABLE_NACL)
1100 bool ChromeContentRendererClient::HasErrorPage(int http_status_code,
1101 std::string* error_domain) {
1102 // Use an internal error page, if we have one for the status code.
1103 if (!LocalizedError::HasStrings(LocalizedError::kHttpErrorDomain,
1104 http_status_code)) {
1105 return false;
1108 *error_domain = LocalizedError::kHttpErrorDomain;
1109 return true;
1112 bool ChromeContentRendererClient::ShouldSuppressErrorPage(
1113 content::RenderFrame* render_frame,
1114 const GURL& url) {
1115 // Unit tests for ChromeContentRendererClient pass a NULL RenderFrame here.
1116 // Unfortunately it's very difficult to construct a mock RenderView, so skip
1117 // this functionality in this case.
1118 if (render_frame) {
1119 content::RenderView* render_view = render_frame->GetRenderView();
1120 content::RenderFrame* main_render_frame = render_view->GetMainRenderFrame();
1121 blink::WebFrame* web_frame = render_frame->GetWebFrame();
1122 NetErrorHelper* net_error_helper = NetErrorHelper::Get(main_render_frame);
1123 if (net_error_helper->ShouldSuppressErrorPage(web_frame, url))
1124 return true;
1126 // Do not flash an error page if the Instant new tab page fails to load.
1127 return SearchBouncer::GetInstance()->IsNewTabPage(url);
1130 void ChromeContentRendererClient::GetNavigationErrorStrings(
1131 content::RenderView* render_view,
1132 blink::WebFrame* frame,
1133 const blink::WebURLRequest& failed_request,
1134 const blink::WebURLError& error,
1135 std::string* error_html,
1136 base::string16* error_description) {
1137 const GURL failed_url = error.unreachableURL;
1139 bool is_post = base::EqualsASCII(failed_request.httpMethod(), "POST");
1141 if (error_html) {
1142 // TODO(ellyjones): change GetNavigationErrorStrings to take a RenderFrame
1143 // instead of a RenderView, then pass that in.
1144 // This is safe for now because we only install the NetErrorHelper on the
1145 // main render frame anyway; see the TODO(ellyjones) in
1146 // RenderFrameCreated.
1147 content::RenderFrame* main_render_frame = render_view->GetMainRenderFrame();
1148 NetErrorHelper* helper = NetErrorHelper::Get(main_render_frame);
1149 helper->GetErrorHTML(frame, error, is_post, error_html);
1152 if (error_description)
1153 *error_description = LocalizedError::GetErrorDetails(error, is_post);
1156 bool ChromeContentRendererClient::RunIdleHandlerWhenWidgetsHidden() {
1157 #if defined(ENABLE_EXTENSIONS)
1158 return !IsStandaloneExtensionProcess();
1159 #else
1160 return true;
1161 #endif
1164 bool ChromeContentRendererClient::AllowPopup() {
1165 #if defined(ENABLE_EXTENSIONS)
1166 extensions::ScriptContext* current_context =
1167 extension_dispatcher_->script_context_set().GetCurrent();
1168 if (!current_context || !current_context->extension())
1169 return false;
1170 // See http://crbug.com/117446 for the subtlety of this check.
1171 switch (current_context->context_type()) {
1172 case extensions::Feature::UNSPECIFIED_CONTEXT:
1173 case extensions::Feature::WEB_PAGE_CONTEXT:
1174 case extensions::Feature::UNBLESSED_EXTENSION_CONTEXT:
1175 case extensions::Feature::WEBUI_CONTEXT:
1176 return false;
1177 case extensions::Feature::BLESSED_EXTENSION_CONTEXT:
1178 case extensions::Feature::CONTENT_SCRIPT_CONTEXT:
1179 return true;
1180 case extensions::Feature::BLESSED_WEB_PAGE_CONTEXT:
1181 return !current_context->web_frame()->parent();
1183 NOTREACHED();
1184 #endif
1185 return false;
1188 bool ChromeContentRendererClient::ShouldFork(blink::WebLocalFrame* frame,
1189 const GURL& url,
1190 const std::string& http_method,
1191 bool is_initial_navigation,
1192 bool is_server_redirect,
1193 bool* send_referrer) {
1194 DCHECK(!frame->parent());
1196 // If this is the Instant process, fork all navigations originating from the
1197 // renderer. The destination page will then be bucketed back to this Instant
1198 // process if it is an Instant url, or to another process if not. Conversely,
1199 // fork if this is a non-Instant process navigating to an Instant url, so that
1200 // such navigations can also be bucketed into an Instant renderer.
1201 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1202 switches::kInstantProcess) ||
1203 SearchBouncer::GetInstance()->ShouldFork(url)) {
1204 *send_referrer = true;
1205 return true;
1208 // For now, we skip the rest for POST submissions. This is because
1209 // http://crbug.com/101395 is more likely to cause compatibility issues
1210 // with hosted apps and extensions than WebUI pages. We will remove this
1211 // check when cross-process POST submissions are supported.
1212 if (http_method != "GET")
1213 return false;
1215 // If |url| matches one of the prerendered URLs, stop this navigation and try
1216 // to swap in the prerendered page on the browser process. If the prerendered
1217 // page no longer exists by the time the OpenURL IPC is handled, a normal
1218 // navigation is attempted.
1219 if (prerender_dispatcher_.get() &&
1220 prerender_dispatcher_->IsPrerenderURL(url)) {
1221 *send_referrer = true;
1222 return true;
1225 #if defined(ENABLE_EXTENSIONS)
1226 const extensions::ExtensionSet* extensions =
1227 extension_dispatcher_->extensions();
1229 // Determine if the new URL is an extension (excluding bookmark apps).
1230 const Extension* new_url_extension = extensions::GetNonBookmarkAppExtension(
1231 *extensions, url);
1232 bool is_extension_url = !!new_url_extension;
1234 // If the navigation would cross an app extent boundary, we also need
1235 // to defer to the browser to ensure process isolation. This is not necessary
1236 // for server redirects, which will be transferred to a new process by the
1237 // browser process when they are ready to commit. It is necessary for client
1238 // redirects, which won't be transferred in the same way.
1239 if (!is_server_redirect &&
1240 CrossesExtensionExtents(frame, url, *extensions, is_extension_url,
1241 is_initial_navigation)) {
1242 // Include the referrer in this case since we're going from a hosted web
1243 // page. (the packaged case is handled previously by the extension
1244 // navigation test)
1245 *send_referrer = true;
1247 const Extension* extension =
1248 extension_dispatcher_->extensions()->GetExtensionOrAppByURL(url);
1249 if (extension && extension->is_app()) {
1250 extensions::RecordAppLaunchType(
1251 extension_misc::APP_LAUNCH_CONTENT_NAVIGATION, extension->GetType());
1253 return true;
1256 // If this is a reload, check whether it has the wrong process type. We
1257 // should send it to the browser if it's an extension URL (e.g., hosted app)
1258 // in a normal process, or if it's a process for an extension that has been
1259 // uninstalled. Without --site-per-process mode, we never fork processes for
1260 // subframes, so this check only makes sense for top-level frames.
1261 // TODO(alexmos,nasko): Figure out how this check should work when reloading
1262 // subframes in --site-per-process mode.
1263 if (!frame->parent() && frame->document().url() == url) {
1264 if (is_extension_url != IsStandaloneExtensionProcess())
1265 return true;
1267 #endif // defined(ENABLE_EXTENSIONS)
1269 return false;
1272 bool ChromeContentRendererClient::WillSendRequest(
1273 blink::WebFrame* frame,
1274 ui::PageTransition transition_type,
1275 const GURL& url,
1276 const GURL& first_party_for_cookies,
1277 GURL* new_url) {
1278 // Check whether the request should be allowed. If not allowed, we reset the
1279 // URL to something invalid to prevent the request and cause an error.
1280 #if defined(ENABLE_EXTENSIONS)
1281 if (url.SchemeIs(extensions::kExtensionScheme) &&
1282 !extensions::ResourceRequestPolicy::CanRequestResource(
1283 url,
1284 frame,
1285 transition_type,
1286 extension_dispatcher_->extensions())) {
1287 *new_url = GURL(chrome::kExtensionInvalidRequestURL);
1288 return true;
1291 if (url.SchemeIs(extensions::kExtensionResourceScheme) &&
1292 !extensions::ResourceRequestPolicy::CanRequestExtensionResourceScheme(
1293 url,
1294 frame)) {
1295 *new_url = GURL(chrome::kExtensionResourceInvalidRequestURL);
1296 return true;
1298 #endif
1300 const content::RenderView* render_view =
1301 content::RenderView::FromWebView(frame->view());
1302 SearchBox* search_box = SearchBox::Get(render_view);
1303 if (search_box && url.SchemeIs(chrome::kChromeSearchScheme)) {
1304 SearchBox::ImageSourceType type = SearchBox::NONE;
1305 if (url.host() == chrome::kChromeUIFaviconHost)
1306 type = SearchBox::FAVICON;
1307 else if (url.host() == chrome::kChromeUILargeIconHost)
1308 type = SearchBox::LARGE_ICON;
1309 else if (url.host() == chrome::kChromeUIFallbackIconHost)
1310 type = SearchBox::FALLBACK_ICON;
1311 else if (url.host() == chrome::kChromeUIThumbnailHost)
1312 type = SearchBox::THUMB;
1313 if (type != SearchBox::NONE)
1314 return search_box->GenerateImageURLFromTransientURL(url, type, new_url);
1317 return false;
1320 unsigned long long ChromeContentRendererClient::VisitedLinkHash(
1321 const char* canonical_url, size_t length) {
1322 return visited_link_slave_->ComputeURLFingerprint(canonical_url, length);
1325 bool ChromeContentRendererClient::IsLinkVisited(unsigned long long link_hash) {
1326 return visited_link_slave_->IsVisited(link_hash);
1329 blink::WebPrescientNetworking*
1330 ChromeContentRendererClient::GetPrescientNetworking() {
1331 return prescient_networking_dispatcher_.get();
1334 bool ChromeContentRendererClient::ShouldOverridePageVisibilityState(
1335 const content::RenderFrame* render_frame,
1336 blink::WebPageVisibilityState* override_state) {
1337 if (!prerender::PrerenderHelper::IsPrerendering(render_frame))
1338 return false;
1340 *override_state = blink::WebPageVisibilityStatePrerender;
1341 return true;
1344 #if defined(ENABLE_EXTENSIONS)
1345 void ChromeContentRendererClient::SetExtensionDispatcherForTest(
1346 extensions::Dispatcher* extension_dispatcher) {
1347 extension_dispatcher_.reset(extension_dispatcher);
1348 permissions_policy_delegate_.reset(
1349 new extensions::RendererPermissionsPolicyDelegate(
1350 extension_dispatcher_.get()));
1353 extensions::Dispatcher*
1354 ChromeContentRendererClient::GetExtensionDispatcherForTest() {
1355 return extension_dispatcher_.get();
1358 bool ChromeContentRendererClient::CrossesExtensionExtents(
1359 blink::WebLocalFrame* frame,
1360 const GURL& new_url,
1361 const extensions::ExtensionSet& extensions,
1362 bool is_extension_url,
1363 bool is_initial_navigation) {
1364 DCHECK(!frame->parent());
1365 GURL old_url(frame->document().url());
1367 // If old_url is still empty and this is an initial navigation, then this is
1368 // a window.open operation. We should look at the opener URL. Note that the
1369 // opener is a local frame in this case.
1370 if (is_initial_navigation && old_url.is_empty() && frame->opener()) {
1371 WebLocalFrame* opener_frame = frame->opener()->toWebLocalFrame();
1373 // If we're about to open a normal web page from a same-origin opener stuck
1374 // in an extension process, we want to keep it in process to allow the
1375 // opener to script it.
1376 WebDocument opener_document = opener_frame->document();
1377 WebSecurityOrigin opener_origin = opener_document.securityOrigin();
1378 bool opener_is_extension_url =
1379 !opener_origin.isUnique() && extensions.GetExtensionOrAppByURL(
1380 opener_document.url()) != NULL;
1381 if (!is_extension_url &&
1382 !opener_is_extension_url &&
1383 IsStandaloneExtensionProcess() &&
1384 opener_origin.canRequest(WebURL(new_url)))
1385 return false;
1387 // In all other cases, we want to compare against the URL that determines
1388 // the type of process. In default Chrome, that's the URL of the opener's
1389 // top frame and not the opener frame itself. In --site-per-process, we
1390 // can use the opener frame itself.
1391 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1392 switches::kSitePerProcess))
1393 old_url = opener_frame->document().url();
1394 else
1395 old_url = opener_frame->top()->document().url();
1398 // Only consider keeping non-app URLs in an app process if this window
1399 // has an opener (in which case it might be an OAuth popup that tries to
1400 // script an iframe within the app).
1401 bool should_consider_workaround = !!frame->opener();
1403 return extensions::CrossesExtensionProcessBoundary(
1404 extensions, old_url, new_url, should_consider_workaround);
1406 #endif // defined(ENABLE_EXTENSIONS)
1408 #if defined(ENABLE_SPELLCHECK)
1409 void ChromeContentRendererClient::SetSpellcheck(SpellCheck* spellcheck) {
1410 RenderThread* thread = RenderThread::Get();
1411 if (spellcheck_.get() && thread)
1412 thread->RemoveObserver(spellcheck_.get());
1413 spellcheck_.reset(spellcheck);
1414 SpellCheckReplacer replacer(spellcheck_.get());
1415 content::RenderView::ForEach(&replacer);
1416 if (thread)
1417 thread->AddObserver(spellcheck_.get());
1419 #endif
1421 // static
1422 bool ChromeContentRendererClient::WasWebRequestUsedBySomeExtensions() {
1423 #if defined(ENABLE_EXTENSIONS)
1424 return g_current_client->extension_dispatcher_
1425 ->WasWebRequestUsedBySomeExtensions();
1426 #else
1427 return false;
1428 #endif
1431 const void* ChromeContentRendererClient::CreatePPAPIInterface(
1432 const std::string& interface_name) {
1433 #if defined(ENABLE_PLUGINS) && !defined(DISABLE_NACL)
1434 if (interface_name == PPB_NACL_PRIVATE_INTERFACE)
1435 return nacl::GetNaClPrivateInterface();
1436 #endif
1437 return NULL;
1440 bool ChromeContentRendererClient::IsExternalPepperPlugin(
1441 const std::string& module_name) {
1442 // TODO(bbudge) remove this when the trusted NaCl plugin has been removed.
1443 // We must defer certain plugin events for NaCl instances since we switch
1444 // from the in-process to the out-of-process proxy after instantiating them.
1445 return module_name == "Native Client";
1448 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
1449 bool ChromeContentRendererClient::IsExtensionOrSharedModuleWhitelisted(
1450 const GURL& url, const std::set<std::string>& whitelist) {
1451 const extensions::ExtensionSet* extension_set =
1452 g_current_client->extension_dispatcher_->extensions();
1453 return chrome::IsExtensionOrSharedModuleWhitelisted(url, extension_set,
1454 whitelist);
1456 #endif
1458 blink::WebSpeechSynthesizer*
1459 ChromeContentRendererClient::OverrideSpeechSynthesizer(
1460 blink::WebSpeechSynthesizerClient* client) {
1461 return new TtsDispatcher(client);
1464 bool ChromeContentRendererClient::AllowPepperMediaStreamAPI(
1465 const GURL& url) {
1466 #if !defined(OS_ANDROID)
1467 // Allow only the Hangouts app to use the MediaStream APIs. It's OK to check
1468 // the whitelist in the renderer, since we're only preventing access until
1469 // these APIs are public and stable.
1470 std::string url_host = url.host();
1471 if (url.SchemeIs("https") &&
1472 (base::EndsWith(url_host, "talkgadget.google.com",
1473 base::CompareCase::INSENSITIVE_ASCII) ||
1474 base::EndsWith(url_host, "plus.google.com",
1475 base::CompareCase::INSENSITIVE_ASCII) ||
1476 base::EndsWith(url_host, "plus.sandbox.google.com",
1477 base::CompareCase::INSENSITIVE_ASCII)) &&
1478 base::StartsWith(url.path(), "/hangouts/",
1479 base::CompareCase::INSENSITIVE_ASCII)) {
1480 return true;
1482 // Allow access for tests.
1483 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1484 switches::kEnablePepperTesting)) {
1485 return true;
1487 #endif // !defined(OS_ANDROID)
1488 return false;
1491 void ChromeContentRendererClient::AddKeySystems(
1492 std::vector<media::KeySystemInfo>* key_systems) {
1493 AddChromeKeySystems(key_systems);
1496 bool ChromeContentRendererClient::ShouldReportDetailedMessageForSource(
1497 const base::string16& source) const {
1498 #if defined(ENABLE_EXTENSIONS)
1499 return extensions::IsSourceFromAnExtension(source);
1500 #else
1501 return false;
1502 #endif
1505 bool ChromeContentRendererClient::ShouldGatherSiteIsolationStats() const {
1506 // Site isolation stats are gathered currently for non-extension renderer
1507 // processes running a normal web page from the Internet.
1508 // TODO(nick): https://crbug.com/268640 Gather stats for extension processes
1509 // too; we would need to check the extension's manifest to know which sites
1510 // it's allowed to access.
1511 #if defined(ENABLE_EXTENSIONS)
1512 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
1513 return !command_line->HasSwitch(extensions::switches::kExtensionProcess);
1514 #else
1515 return true;
1516 #endif
1519 blink::WebWorkerContentSettingsClientProxy*
1520 ChromeContentRendererClient::CreateWorkerContentSettingsClientProxy(
1521 content::RenderFrame* render_frame,
1522 blink::WebFrame* frame) {
1523 return new WorkerContentSettingsClientProxy(render_frame, frame);
1526 bool ChromeContentRendererClient::IsPluginAllowedToUseDevChannelAPIs() {
1527 #if defined(ENABLE_PLUGINS)
1528 // Allow access for tests.
1529 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1530 switches::kEnablePepperTesting)) {
1531 return true;
1534 chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
1535 // Allow dev channel APIs to be used on "Canary", "Dev", and "Unknown"
1536 // releases of Chrome. Permitting "Unknown" allows these APIs to be used on
1537 // Chromium builds as well.
1538 return channel <= chrome::VersionInfo::CHANNEL_DEV;
1539 #else
1540 return false;
1541 #endif
1544 bool ChromeContentRendererClient::IsPluginAllowedToUseCameraDeviceAPI(
1545 const GURL& url) {
1546 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
1547 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1548 switches::kEnablePepperTesting))
1549 return true;
1551 if (IsExtensionOrSharedModuleWhitelisted(url, allowed_camera_device_origins_))
1552 return true;
1553 #endif
1555 return false;
1558 bool ChromeContentRendererClient::IsPluginAllowedToUseCompositorAPI(
1559 const GURL& url) {
1560 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
1561 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1562 switches::kEnablePepperTesting))
1563 return true;
1564 if (IsExtensionOrSharedModuleWhitelisted(url, allowed_compositor_origins_))
1565 return true;
1567 chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
1568 return channel <= chrome::VersionInfo::CHANNEL_DEV;
1569 #else
1570 return false;
1571 #endif
1574 content::BrowserPluginDelegate*
1575 ChromeContentRendererClient::CreateBrowserPluginDelegate(
1576 content::RenderFrame* render_frame,
1577 const std::string& mime_type,
1578 const GURL& original_url) {
1579 #if defined(ENABLE_EXTENSIONS)
1580 if (mime_type == content::kBrowserPluginMimeType) {
1581 return new extensions::ExtensionsGuestViewContainer(render_frame);
1582 } else {
1583 return new extensions::MimeHandlerViewContainer(
1584 render_frame, mime_type, original_url);
1586 #else
1587 return NULL;
1588 #endif
1591 void ChromeContentRendererClient::RecordRappor(const std::string& metric,
1592 const std::string& sample) {
1593 RenderThread::Get()->Send(new ChromeViewHostMsg_RecordRappor(metric, sample));
1596 void ChromeContentRendererClient::RecordRapporURL(const std::string& metric,
1597 const GURL& url) {
1598 RenderThread::Get()->Send(new ChromeViewHostMsg_RecordRapporURL(metric, url));
1601 scoped_ptr<blink::WebAppBannerClient>
1602 ChromeContentRendererClient::CreateAppBannerClient(
1603 content::RenderFrame* render_frame) {
1604 return scoped_ptr<blink::WebAppBannerClient>(
1605 new AppBannerClient(render_frame));
1608 void ChromeContentRendererClient::AddImageContextMenuProperties(
1609 const blink::WebURLResponse& response,
1610 std::map<std::string, std::string>* properties) {
1611 DCHECK(properties);
1612 WebString header_key(ASCIIToUTF16(
1613 data_reduction_proxy::chrome_proxy_header()));
1614 if (!response.httpHeaderField(header_key).isNull() &&
1615 response.httpHeaderField(header_key).utf8().find(
1616 data_reduction_proxy::chrome_proxy_lo_fi_directive()) !=
1617 std::string::npos) {
1618 (*properties)[data_reduction_proxy::chrome_proxy_header()] =
1619 data_reduction_proxy::chrome_proxy_lo_fi_directive();