Revert 291214 "Fixes three crashes" in an attempt to find the cause of Athena related...
[chromium-blink-merge.git] / chrome / renderer / chrome_content_renderer_client.cc
blobb122262248ba5aedc70ad68f28dec4eee65a0b39
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/path_service.h"
14 #include "base/strings/string_number_conversions.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "base/values.h"
18 #include "chrome/common/chrome_paths.h"
19 #include "chrome/common/chrome_switches.h"
20 #include "chrome/common/chrome_version_info.h"
21 #include "chrome/common/content_settings_pattern.h"
22 #include "chrome/common/crash_keys.h"
23 #include "chrome/common/extensions/chrome_extensions_client.h"
24 #include "chrome/common/extensions/extension_constants.h"
25 #include "chrome/common/extensions/extension_process_policy.h"
26 #include "chrome/common/localized_error.h"
27 #include "chrome/common/pepper_permission_util.h"
28 #include "chrome/common/render_messages.h"
29 #include "chrome/common/url_constants.h"
30 #include "chrome/grit/generated_resources.h"
31 #include "chrome/grit/locale_settings.h"
32 #include "chrome/grit/renderer_resources.h"
33 #include "chrome/renderer/benchmarking_extension.h"
34 #include "chrome/renderer/chrome_render_frame_observer.h"
35 #include "chrome/renderer/chrome_render_process_observer.h"
36 #include "chrome/renderer/chrome_render_view_observer.h"
37 #include "chrome/renderer/content_settings_observer.h"
38 #include "chrome/renderer/extensions/chrome_extension_helper.h"
39 #include "chrome/renderer/extensions/chrome_extensions_dispatcher_delegate.h"
40 #include "chrome/renderer/extensions/chrome_extensions_renderer_client.h"
41 #include "chrome/renderer/extensions/extension_frame_helper.h"
42 #include "chrome/renderer/extensions/renderer_permissions_policy_delegate.h"
43 #include "chrome/renderer/extensions/resource_request_policy.h"
44 #include "chrome/renderer/external_extension.h"
45 #include "chrome/renderer/loadtimes_extension_bindings.h"
46 #include "chrome/renderer/media/cast_ipc_dispatcher.h"
47 #include "chrome/renderer/media/chrome_key_systems.h"
48 #include "chrome/renderer/net/net_error_helper.h"
49 #include "chrome/renderer/net/prescient_networking_dispatcher.h"
50 #include "chrome/renderer/net/renderer_net_predictor.h"
51 #include "chrome/renderer/net_benchmarking_extension.h"
52 #include "chrome/renderer/page_load_histograms.h"
53 #include "chrome/renderer/pepper/pepper_helper.h"
54 #include "chrome/renderer/pepper/ppb_pdf_impl.h"
55 #include "chrome/renderer/playback_extension.h"
56 #include "chrome/renderer/plugins/chrome_plugin_placeholder.h"
57 #include "chrome/renderer/plugins/plugin_uma.h"
58 #include "chrome/renderer/prefetch_helper.h"
59 #include "chrome/renderer/prerender/prerender_dispatcher.h"
60 #include "chrome/renderer/prerender/prerender_helper.h"
61 #include "chrome/renderer/prerender/prerender_media_load_deferrer.h"
62 #include "chrome/renderer/prerender/prerenderer_client.h"
63 #include "chrome/renderer/principals_extension_bindings.h"
64 #include "chrome/renderer/printing/print_web_view_helper.h"
65 #include "chrome/renderer/safe_browsing/malware_dom_details.h"
66 #include "chrome/renderer/safe_browsing/phishing_classifier_delegate.h"
67 #include "chrome/renderer/searchbox/search_bouncer.h"
68 #include "chrome/renderer/searchbox/searchbox.h"
69 #include "chrome/renderer/searchbox/searchbox_extension.h"
70 #include "chrome/renderer/tts_dispatcher.h"
71 #include "chrome/renderer/worker_permission_client_proxy.h"
72 #include "components/autofill/content/renderer/autofill_agent.h"
73 #include "components/autofill/content/renderer/password_autofill_agent.h"
74 #include "components/autofill/content/renderer/password_generation_agent.h"
75 #include "components/dom_distiller/core/url_constants.h"
76 #include "components/nacl/renderer/ppb_nacl_private_impl.h"
77 #include "components/password_manager/content/renderer/credential_manager_client.h"
78 #include "components/plugins/renderer/mobile_youtube_plugin.h"
79 #include "components/signin/core/common/profile_management_switches.h"
80 #include "components/visitedlink/renderer/visitedlink_slave.h"
81 #include "content/public/common/content_constants.h"
82 #include "content/public/renderer/render_frame.h"
83 #include "content/public/renderer/render_thread.h"
84 #include "content/public/renderer/render_view.h"
85 #include "content/public/renderer/render_view_visitor.h"
86 #include "extensions/common/constants.h"
87 #include "extensions/common/extension.h"
88 #include "extensions/common/extension_set.h"
89 #include "extensions/common/extension_urls.h"
90 #include "extensions/common/switches.h"
91 #include "extensions/renderer/dispatcher.h"
92 #include "extensions/renderer/extension_helper.h"
93 #include "extensions/renderer/script_context.h"
94 #include "ipc/ipc_sync_channel.h"
95 #include "net/base/net_errors.h"
96 #include "ppapi/c/private/ppb_nacl_private.h"
97 #include "ppapi/c/private/ppb_pdf.h"
98 #include "ppapi/shared_impl/ppapi_switches.h"
99 #include "third_party/WebKit/public/platform/WebURL.h"
100 #include "third_party/WebKit/public/platform/WebURLError.h"
101 #include "third_party/WebKit/public/platform/WebURLRequest.h"
102 #include "third_party/WebKit/public/web/WebCache.h"
103 #include "third_party/WebKit/public/web/WebDataSource.h"
104 #include "third_party/WebKit/public/web/WebDocument.h"
105 #include "third_party/WebKit/public/web/WebElement.h"
106 #include "third_party/WebKit/public/web/WebLocalFrame.h"
107 #include "third_party/WebKit/public/web/WebPluginContainer.h"
108 #include "third_party/WebKit/public/web/WebPluginParams.h"
109 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
110 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
111 #include "ui/base/l10n/l10n_util.h"
112 #include "ui/base/layout.h"
113 #include "ui/base/resource/resource_bundle.h"
114 #include "ui/base/webui/jstemplate_builder.h"
115 #include "widevine_cdm_version.h" // In SHARED_INTERMEDIATE_DIR.
117 #if !defined(DISABLE_NACL)
118 #include "components/nacl/common/nacl_constants.h"
119 #include "components/nacl/renderer/nacl_helper.h"
120 #endif
122 #if defined(ENABLE_EXTENSIONS)
123 #include "extensions/renderer/extensions_render_frame_observer.h"
124 #endif
126 #if defined(ENABLE_SPELLCHECK)
127 #include "chrome/renderer/spellchecker/spellcheck.h"
128 #include "chrome/renderer/spellchecker/spellcheck_provider.h"
129 #endif
131 #if defined(ENABLE_WEBRTC)
132 #include "chrome/renderer/media/webrtc_logging_message_filter.h"
133 #endif
135 #if defined(OS_WIN)
136 #include "chrome_elf/blacklist/blacklist.h"
137 #endif
139 using autofill::AutofillAgent;
140 using autofill::PasswordAutofillAgent;
141 using autofill::PasswordGenerationAgent;
142 using base::ASCIIToUTF16;
143 using base::UserMetricsAction;
144 using content::RenderThread;
145 using content::WebPluginInfo;
146 using extensions::Extension;
147 using blink::WebCache;
148 using blink::WebConsoleMessage;
149 using blink::WebDataSource;
150 using blink::WebDocument;
151 using blink::WebFrame;
152 using blink::WebLocalFrame;
153 using blink::WebPlugin;
154 using blink::WebPluginParams;
155 using blink::WebSecurityOrigin;
156 using blink::WebSecurityPolicy;
157 using blink::WebString;
158 using blink::WebURL;
159 using blink::WebURLError;
160 using blink::WebURLRequest;
161 using blink::WebURLResponse;
162 using blink::WebVector;
164 namespace {
166 ChromeContentRendererClient* g_current_client;
168 #if defined(ENABLE_PLUGINS)
169 const char* const kPredefinedAllowedCompositorOrigins[] = {
170 "6EAED1924DB611B6EEF2A664BD077BE7EAD33B8F", // see crbug.com/383937
171 "4EB74897CB187C7633357C2FE832E0AD6A44883A" // see crbug.com/383937
174 const char* const kPredefinedAllowedVideoDecodeOrigins[] = {
175 "6EAED1924DB611B6EEF2A664BD077BE7EAD33B8F", // see crbug.com/383937
176 "4EB74897CB187C7633357C2FE832E0AD6A44883A" // see crbug.com/383937
178 #endif
180 static void AppendParams(const std::vector<base::string16>& additional_names,
181 const std::vector<base::string16>& additional_values,
182 WebVector<WebString>* existing_names,
183 WebVector<WebString>* existing_values) {
184 DCHECK(additional_names.size() == additional_values.size());
185 DCHECK(existing_names->size() == existing_values->size());
187 size_t existing_size = existing_names->size();
188 size_t total_size = existing_size + additional_names.size();
190 WebVector<WebString> names(total_size);
191 WebVector<WebString> values(total_size);
193 for (size_t i = 0; i < existing_size; ++i) {
194 names[i] = (*existing_names)[i];
195 values[i] = (*existing_values)[i];
198 for (size_t i = 0; i < additional_names.size(); ++i) {
199 names[existing_size + i] = additional_names[i];
200 values[existing_size + i] = additional_values[i];
203 existing_names->swap(names);
204 existing_values->swap(values);
207 #if defined(ENABLE_SPELLCHECK)
208 class SpellCheckReplacer : public content::RenderViewVisitor {
209 public:
210 explicit SpellCheckReplacer(SpellCheck* spellcheck)
211 : spellcheck_(spellcheck) {}
212 virtual bool Visit(content::RenderView* render_view) OVERRIDE;
214 private:
215 SpellCheck* spellcheck_; // New shared spellcheck for all views. Weak Ptr.
216 DISALLOW_COPY_AND_ASSIGN(SpellCheckReplacer);
219 bool SpellCheckReplacer::Visit(content::RenderView* render_view) {
220 SpellCheckProvider* provider = SpellCheckProvider::Get(render_view);
221 DCHECK(provider);
222 provider->set_spellcheck(spellcheck_);
223 return true;
225 #endif
227 // For certain sandboxed Pepper plugins, use the JavaScript Content Settings.
228 bool ShouldUseJavaScriptSettingForPlugin(const WebPluginInfo& plugin) {
229 if (plugin.type != WebPluginInfo::PLUGIN_TYPE_PEPPER_IN_PROCESS &&
230 plugin.type != WebPluginInfo::PLUGIN_TYPE_PEPPER_OUT_OF_PROCESS) {
231 return false;
234 #if !defined(DISABLE_NACL)
235 // Treat Native Client invocations like JavaScript.
236 if (plugin.name == ASCIIToUTF16(nacl::kNaClPluginName))
237 return true;
238 #endif
240 #if defined(WIDEVINE_CDM_AVAILABLE) && defined(ENABLE_PEPPER_CDMS)
241 // Treat CDM invocations like JavaScript.
242 if (plugin.name == ASCIIToUTF16(kWidevineCdmDisplayName)) {
243 DCHECK(plugin.type == WebPluginInfo::PLUGIN_TYPE_PEPPER_OUT_OF_PROCESS);
244 return true;
246 #endif // defined(WIDEVINE_CDM_AVAILABLE) && defined(ENABLE_PEPPER_CDMS)
248 return false;
251 void IsGuestViewApiAvailableToScriptContext(
252 bool* api_is_available,
253 extensions::ScriptContext* context) {
254 if (context->GetAvailability("guestViewInternal").is_available()) {
255 *api_is_available = true;
259 } // namespace
261 ChromeContentRendererClient::ChromeContentRendererClient() {
262 g_current_client = this;
264 extensions::ExtensionsClient::Set(
265 extensions::ChromeExtensionsClient::GetInstance());
266 extensions::ExtensionsRendererClient::Set(
267 ChromeExtensionsRendererClient::GetInstance());
268 #if defined(ENABLE_PLUGINS)
269 for (size_t i = 0; i < arraysize(kPredefinedAllowedCompositorOrigins); ++i)
270 allowed_compositor_origins_.insert(kPredefinedAllowedCompositorOrigins[i]);
271 for (size_t i = 0; i < arraysize(kPredefinedAllowedVideoDecodeOrigins); ++i)
272 allowed_video_decode_origins_.insert(
273 kPredefinedAllowedVideoDecodeOrigins[i]);
274 #endif
277 ChromeContentRendererClient::~ChromeContentRendererClient() {
278 g_current_client = NULL;
281 void ChromeContentRendererClient::RenderThreadStarted() {
282 RenderThread* thread = RenderThread::Get();
284 chrome_observer_.reset(new ChromeRenderProcessObserver(this));
286 extension_dispatcher_delegate_.reset(
287 new ChromeExtensionsDispatcherDelegate());
288 // ChromeRenderViewTest::SetUp() creates its own ExtensionDispatcher and
289 // injects it using SetExtensionDispatcher(). Don't overwrite it.
290 if (!extension_dispatcher_) {
291 extension_dispatcher_.reset(
292 new extensions::Dispatcher(extension_dispatcher_delegate_.get()));
294 permissions_policy_delegate_.reset(
295 new extensions::RendererPermissionsPolicyDelegate(
296 extension_dispatcher_.get()));
297 prescient_networking_dispatcher_.reset(new PrescientNetworkingDispatcher());
298 net_predictor_.reset(new RendererNetPredictor());
299 #if defined(ENABLE_SPELLCHECK)
300 // ChromeRenderViewTest::SetUp() creates a Spellcheck and injects it using
301 // SetSpellcheck(). Don't overwrite it.
302 if (!spellcheck_) {
303 spellcheck_.reset(new SpellCheck());
304 thread->AddObserver(spellcheck_.get());
306 #endif
307 visited_link_slave_.reset(new visitedlink::VisitedLinkSlave());
308 #if defined(FULL_SAFE_BROWSING)
309 phishing_classifier_.reset(safe_browsing::PhishingClassifierFilter::Create());
310 #endif
311 prerender_dispatcher_.reset(new prerender::PrerenderDispatcher());
312 #if defined(ENABLE_WEBRTC)
313 webrtc_logging_message_filter_ = new WebRtcLoggingMessageFilter(
314 content::RenderThread::Get()->GetIOMessageLoopProxy());
315 #endif
316 search_bouncer_.reset(new SearchBouncer());
318 credential_manager_client_.reset(
319 new password_manager::CredentialManagerClient());
321 thread->AddObserver(chrome_observer_.get());
322 thread->AddObserver(extension_dispatcher_.get());
323 #if defined(FULL_SAFE_BROWSING)
324 thread->AddObserver(phishing_classifier_.get());
325 #endif
326 thread->AddObserver(visited_link_slave_.get());
327 thread->AddObserver(prerender_dispatcher_.get());
328 thread->AddObserver(search_bouncer_.get());
329 thread->AddObserver(credential_manager_client_.get());
331 #if defined(ENABLE_WEBRTC)
332 thread->AddFilter(webrtc_logging_message_filter_.get());
333 #endif
334 thread->AddFilter(new CastIPCDispatcher(
335 content::RenderThread::Get()->GetIOMessageLoopProxy()));
337 thread->RegisterExtension(extensions_v8::ExternalExtension::Get());
338 thread->RegisterExtension(extensions_v8::LoadTimesExtension::Get());
340 CommandLine* command_line = CommandLine::ForCurrentProcess();
341 if (command_line->HasSwitch(switches::kEnableBenchmarking))
342 thread->RegisterExtension(extensions_v8::BenchmarkingExtension::Get());
343 if (command_line->HasSwitch(switches::kEnableNetBenchmarking))
344 thread->RegisterExtension(extensions_v8::NetBenchmarkingExtension::Get());
345 if (command_line->HasSwitch(switches::kInstantProcess))
346 thread->RegisterExtension(extensions_v8::SearchBoxExtension::Get());
348 if (command_line->HasSwitch(switches::kPlaybackMode) ||
349 command_line->HasSwitch(switches::kRecordMode)) {
350 thread->RegisterExtension(extensions_v8::PlaybackExtension::Get());
353 // TODO(guohui): needs to forward the new-profile-management switch to
354 // renderer processes.
355 if (switches::IsEnableAccountConsistency())
356 thread->RegisterExtension(extensions_v8::PrincipalsExtension::Get());
358 // chrome:, chrome-search:, chrome-devtools:, and chrome-distiller: pages
359 // should not be accessible by normal content, and should also be unable to
360 // script anything but themselves (to help limit the damage that a corrupt
361 // page could cause).
362 WebString chrome_ui_scheme(ASCIIToUTF16(content::kChromeUIScheme));
363 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(chrome_ui_scheme);
365 WebString chrome_search_scheme(ASCIIToUTF16(chrome::kChromeSearchScheme));
366 // The Instant process can only display the content but not read it. Other
367 // processes can't display it or read it.
368 if (!command_line->HasSwitch(switches::kInstantProcess))
369 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(chrome_search_scheme);
371 WebString dev_tools_scheme(ASCIIToUTF16(content::kChromeDevToolsScheme));
372 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(dev_tools_scheme);
374 WebString dom_distiller_scheme(
375 ASCIIToUTF16(dom_distiller::kDomDistillerScheme));
376 // TODO(nyquist): Add test to ensure this happens when the flag is set.
377 WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(dom_distiller_scheme);
379 #if defined(OS_CHROMEOS)
380 WebString drive_scheme(ASCIIToUTF16(chrome::kDriveScheme));
381 WebSecurityPolicy::registerURLSchemeAsLocal(drive_scheme);
382 #endif
384 // chrome: and chrome-search: pages should not be accessible by bookmarklets
385 // or javascript: URLs typed in the omnibox.
386 WebSecurityPolicy::registerURLSchemeAsNotAllowingJavascriptURLs(
387 chrome_ui_scheme);
388 WebSecurityPolicy::registerURLSchemeAsNotAllowingJavascriptURLs(
389 chrome_search_scheme);
391 // chrome:, chrome-search:, and chrome-extension: resources shouldn't trigger
392 // insecure content warnings.
393 WebSecurityPolicy::registerURLSchemeAsSecure(chrome_ui_scheme);
394 WebSecurityPolicy::registerURLSchemeAsSecure(chrome_search_scheme);
396 WebString extension_scheme(ASCIIToUTF16(extensions::kExtensionScheme));
397 WebSecurityPolicy::registerURLSchemeAsSecure(extension_scheme);
399 // chrome-extension: resources should be allowed to receive CORS requests.
400 WebSecurityPolicy::registerURLSchemeAsCORSEnabled(extension_scheme);
402 WebString extension_resource_scheme(
403 ASCIIToUTF16(extensions::kExtensionResourceScheme));
404 WebSecurityPolicy::registerURLSchemeAsSecure(extension_resource_scheme);
406 // chrome-extension-resource: resources should be allowed to receive CORS
407 // requests.
408 WebSecurityPolicy::registerURLSchemeAsCORSEnabled(extension_resource_scheme);
410 // chrome-extension: resources should bypass Content Security Policy checks
411 // when included in protected resources.
412 WebSecurityPolicy::registerURLSchemeAsBypassingContentSecurityPolicy(
413 extension_scheme);
414 WebSecurityPolicy::registerURLSchemeAsBypassingContentSecurityPolicy(
415 extension_resource_scheme);
417 #if defined(OS_WIN)
418 // Report if the renderer process has been patched by chrome_elf.
419 // TODO(csharp): Remove once the renderer is no longer getting
420 // patched this way.
421 if (blacklist::IsBlacklistInitialized())
422 UMA_HISTOGRAM_BOOLEAN("Blacklist.PatchedInRenderer", true);
423 #endif
426 void ChromeContentRendererClient::RenderFrameCreated(
427 content::RenderFrame* render_frame) {
428 new ChromeRenderFrameObserver(render_frame);
430 ContentSettingsObserver* content_settings =
431 new ContentSettingsObserver(render_frame, extension_dispatcher_.get());
432 if (chrome_observer_.get()) {
433 content_settings->SetContentSettingRules(
434 chrome_observer_->content_setting_rules());
437 #if defined(ENABLE_EXTENSIONS)
438 new extensions::ExtensionsRenderFrameObserver(render_frame);
439 #endif
440 new extensions::ExtensionFrameHelper(render_frame,
441 extension_dispatcher_.get());
443 #if defined(ENABLE_PLUGINS)
444 new PepperHelper(render_frame);
445 #endif
447 #if !defined(DISABLE_NACL)
448 new nacl::NaClHelper(render_frame);
449 #endif
451 // TODO(jam): when the frame tree moves into content and parent() works at
452 // RenderFrame construction, simplify this by just checking parent().
453 if (render_frame->GetRenderView()->GetMainRenderFrame() != render_frame) {
454 // Avoid any race conditions from having the browser tell subframes that
455 // they're prerendering.
456 if (prerender::PrerenderHelper::IsPrerendering(
457 render_frame->GetRenderView()->GetMainRenderFrame())) {
458 new prerender::PrerenderHelper(render_frame);
462 if (render_frame->GetRenderView()->GetMainRenderFrame() == render_frame) {
463 // Only attach NetErrorHelper to the main frame, since only the main frame
464 // should get error pages.
465 // PrefetchHelper is also needed only for main frames.
466 new NetErrorHelper(render_frame);
467 new prefetch::PrefetchHelper(render_frame);
471 void ChromeContentRendererClient::RenderViewCreated(
472 content::RenderView* render_view) {
473 new extensions::ExtensionHelper(render_view, extension_dispatcher_.get());
474 new extensions::ChromeExtensionHelper(render_view);
475 extension_dispatcher_->OnRenderViewCreated(render_view);
476 new PageLoadHistograms(render_view);
477 #if defined(ENABLE_PRINTING)
478 new printing::PrintWebViewHelper(render_view);
479 #endif
480 #if defined(ENABLE_SPELLCHECK)
481 new SpellCheckProvider(render_view, spellcheck_.get());
482 #endif
483 new prerender::PrerendererClient(render_view);
484 #if defined(FULL_SAFE_BROWSING)
485 safe_browsing::MalwareDOMDetails::Create(render_view);
486 #endif
488 PasswordGenerationAgent* password_generation_agent =
489 new PasswordGenerationAgent(render_view);
490 PasswordAutofillAgent* password_autofill_agent =
491 new PasswordAutofillAgent(render_view);
492 new AutofillAgent(render_view,
493 password_autofill_agent,
494 password_generation_agent);
496 CommandLine* command_line = CommandLine::ForCurrentProcess();
497 if (command_line->HasSwitch(switches::kInstantProcess))
498 new SearchBox(render_view);
500 new ChromeRenderViewObserver(render_view, chrome_observer_.get());
502 if (credential_manager_client_)
503 credential_manager_client_->OnRenderViewCreated(render_view);
506 void ChromeContentRendererClient::SetNumberOfViews(int number_of_views) {
507 base::debug::SetCrashKeyValue(crash_keys::kNumberOfViews,
508 base::IntToString(number_of_views));
511 SkBitmap* ChromeContentRendererClient::GetSadPluginBitmap() {
512 return const_cast<SkBitmap*>(ResourceBundle::GetSharedInstance().
513 GetImageNamed(IDR_SAD_PLUGIN).ToSkBitmap());
516 SkBitmap* ChromeContentRendererClient::GetSadWebViewBitmap() {
517 return const_cast<SkBitmap*>(ResourceBundle::GetSharedInstance().
518 GetImageNamed(IDR_SAD_WEBVIEW).ToSkBitmap());
521 std::string ChromeContentRendererClient::GetDefaultEncoding() {
522 return l10n_util::GetStringUTF8(IDS_DEFAULT_ENCODING);
525 const Extension* ChromeContentRendererClient::GetExtensionByOrigin(
526 const WebSecurityOrigin& origin) const {
527 if (!EqualsASCII(origin.protocol(), extensions::kExtensionScheme))
528 return NULL;
530 const std::string extension_id = origin.host().utf8().data();
531 return extension_dispatcher_->extensions()->GetByID(extension_id);
534 bool ChromeContentRendererClient::OverrideCreatePlugin(
535 content::RenderFrame* render_frame,
536 WebLocalFrame* frame,
537 const WebPluginParams& params,
538 WebPlugin** plugin) {
539 std::string orig_mime_type = params.mimeType.utf8();
540 if (orig_mime_type == content::kBrowserPluginMimeType) {
541 bool guest_view_api_available = false;
542 extension_dispatcher_->script_context_set().ForEach(
543 render_frame->GetRenderView(),
544 base::Bind(&IsGuestViewApiAvailableToScriptContext,
545 &guest_view_api_available));
546 if (guest_view_api_available)
547 return false;
550 ChromeViewHostMsg_GetPluginInfo_Output output;
551 #if defined(ENABLE_PLUGINS)
552 render_frame->Send(new ChromeViewHostMsg_GetPluginInfo(
553 render_frame->GetRoutingID(), GURL(params.url),
554 frame->top()->document().url(), orig_mime_type, &output));
556 if (output.plugin.type == content::WebPluginInfo::PLUGIN_TYPE_BROWSER_PLUGIN)
557 return false;
558 #else
559 output.status.value = ChromeViewHostMsg_GetPluginInfo_Status::kNotFound;
560 #endif
561 *plugin = CreatePlugin(render_frame, frame, params, output);
562 return true;
565 WebPlugin* ChromeContentRendererClient::CreatePluginReplacement(
566 content::RenderFrame* render_frame,
567 const base::FilePath& plugin_path) {
568 ChromePluginPlaceholder* placeholder =
569 ChromePluginPlaceholder::CreateErrorPlugin(render_frame, plugin_path);
570 return placeholder->plugin();
573 void ChromeContentRendererClient::DeferMediaLoad(
574 content::RenderFrame* render_frame,
575 const base::Closure& closure) {
576 #if defined(OS_ANDROID)
577 // Chromium for Android doesn't support prerender yet.
578 closure.Run();
579 return;
580 #else
581 if (!prerender::PrerenderHelper::IsPrerendering(render_frame)) {
582 closure.Run();
583 return;
586 // Lifetime is tied to |render_frame| via content::RenderFrameObserver.
587 new prerender::PrerenderMediaLoadDeferrer(render_frame, closure);
588 #endif
591 WebPlugin* ChromeContentRendererClient::CreatePlugin(
592 content::RenderFrame* render_frame,
593 WebLocalFrame* frame,
594 const WebPluginParams& original_params,
595 const ChromeViewHostMsg_GetPluginInfo_Output& output) {
596 const ChromeViewHostMsg_GetPluginInfo_Status& status = output.status;
597 const WebPluginInfo& plugin = output.plugin;
598 const std::string& actual_mime_type = output.actual_mime_type;
599 const base::string16& group_name = output.group_name;
600 const std::string& identifier = output.group_identifier;
601 ChromeViewHostMsg_GetPluginInfo_Status::Value status_value = status.value;
602 GURL url(original_params.url);
603 std::string orig_mime_type = original_params.mimeType.utf8();
604 ChromePluginPlaceholder* placeholder = NULL;
606 // If the browser plugin is to be enabled, this should be handled by the
607 // renderer, so the code won't reach here due to the early exit in
608 // OverrideCreatePlugin.
609 if (status_value == ChromeViewHostMsg_GetPluginInfo_Status::kNotFound ||
610 orig_mime_type == content::kBrowserPluginMimeType) {
611 #if defined(OS_ANDROID)
612 if (plugins::MobileYouTubePlugin::IsYouTubeURL(url, orig_mime_type)) {
613 base::StringPiece template_html(
614 ResourceBundle::GetSharedInstance().GetRawDataResource(
615 IDR_MOBILE_YOUTUBE_PLUGIN_HTML));
616 return (new plugins::MobileYouTubePlugin(
617 render_frame,
618 frame,
619 original_params,
620 template_html,
621 GURL(ChromePluginPlaceholder::kPluginPlaceholderDataURL)))
622 ->plugin();
624 #endif
625 PluginUMAReporter::GetInstance()->ReportPluginMissing(orig_mime_type, url);
626 placeholder = ChromePluginPlaceholder::CreateMissingPlugin(
627 render_frame, frame, original_params);
628 } else {
629 // TODO(bauerb): This should be in content/.
630 WebPluginParams params(original_params);
631 for (size_t i = 0; i < plugin.mime_types.size(); ++i) {
632 if (plugin.mime_types[i].mime_type == actual_mime_type) {
633 AppendParams(plugin.mime_types[i].additional_param_names,
634 plugin.mime_types[i].additional_param_values,
635 &params.attributeNames,
636 &params.attributeValues);
637 break;
640 if (params.mimeType.isNull() && (actual_mime_type.size() > 0)) {
641 // Webkit might say that mime type is null while we already know the
642 // actual mime type via ChromeViewHostMsg_GetPluginInfo. In that case
643 // we should use what we know since WebpluginDelegateProxy does some
644 // specific initializations based on this information.
645 params.mimeType = WebString::fromUTF8(actual_mime_type.c_str());
648 ContentSettingsObserver* observer =
649 ContentSettingsObserver::Get(render_frame);
651 const ContentSettingsType content_type =
652 ShouldUseJavaScriptSettingForPlugin(plugin) ?
653 CONTENT_SETTINGS_TYPE_JAVASCRIPT :
654 CONTENT_SETTINGS_TYPE_PLUGINS;
656 if ((status_value ==
657 ChromeViewHostMsg_GetPluginInfo_Status::kUnauthorized ||
658 status_value == ChromeViewHostMsg_GetPluginInfo_Status::kClickToPlay ||
659 status_value == ChromeViewHostMsg_GetPluginInfo_Status::kBlocked) &&
660 observer->IsPluginTemporarilyAllowed(identifier)) {
661 status_value = ChromeViewHostMsg_GetPluginInfo_Status::kAllowed;
664 // Allow full-page plug-ins for click-to-play.
665 if (status_value == ChromeViewHostMsg_GetPluginInfo_Status::kClickToPlay &&
666 !frame->parent() &&
667 !frame->opener() &&
668 frame->document().isPluginDocument()) {
669 status_value = ChromeViewHostMsg_GetPluginInfo_Status::kAllowed;
672 #if defined(OS_WIN)
673 // In Windows we need to check if we can load NPAPI plugins.
674 // For example, if the render view is in the Ash desktop, we should not.
675 if (status_value == ChromeViewHostMsg_GetPluginInfo_Status::kAllowed &&
676 plugin.type == content::WebPluginInfo::PLUGIN_TYPE_NPAPI) {
677 if (observer->AreNPAPIPluginsBlocked())
678 status_value =
679 ChromeViewHostMsg_GetPluginInfo_Status::kNPAPINotSupported;
681 #endif
683 switch (status_value) {
684 case ChromeViewHostMsg_GetPluginInfo_Status::kNotFound: {
685 NOTREACHED();
686 break;
688 case ChromeViewHostMsg_GetPluginInfo_Status::kAllowed: {
689 #if !defined(DISABLE_NACL)
690 const bool is_nacl_plugin =
691 plugin.name == ASCIIToUTF16(nacl::kNaClPluginName);
692 const bool is_nacl_mime_type =
693 actual_mime_type == nacl::kNaClPluginMimeType;
694 const bool is_pnacl_mime_type =
695 actual_mime_type == nacl::kPnaclPluginMimeType;
696 if (is_nacl_plugin || is_nacl_mime_type || is_pnacl_mime_type) {
697 bool is_nacl_unrestricted = false;
698 if (is_nacl_mime_type) {
699 is_nacl_unrestricted =
700 CommandLine::ForCurrentProcess()->HasSwitch(
701 switches::kEnableNaCl);
702 } else if (is_pnacl_mime_type) {
703 is_nacl_unrestricted = true;
705 GURL manifest_url;
706 GURL app_url;
707 if (is_nacl_mime_type || is_pnacl_mime_type) {
708 // Normal NaCl/PNaCl embed. The app URL is the page URL.
709 manifest_url = url;
710 app_url = frame->top()->document().url();
711 } else {
712 // NaCl is being invoked as a content handler. Look up the NaCl
713 // module using the MIME type. The app URL is the manifest URL.
714 manifest_url = GetNaClContentHandlerURL(actual_mime_type, plugin);
715 app_url = manifest_url;
717 const Extension* extension =
718 g_current_client->extension_dispatcher_->extensions()->
719 GetExtensionOrAppByURL(manifest_url);
720 if (!IsNaClAllowed(manifest_url,
721 app_url,
722 is_nacl_unrestricted,
723 extension,
724 &params)) {
725 WebString error_message;
726 if (is_nacl_mime_type) {
727 error_message =
728 "Only unpacked extensions and apps installed from the Chrome "
729 "Web Store can load NaCl modules without enabling Native "
730 "Client in about:flags.";
731 } else if (is_pnacl_mime_type) {
732 error_message =
733 "Portable Native Client must not be disabled in about:flags.";
735 frame->addMessageToConsole(
736 WebConsoleMessage(WebConsoleMessage::LevelError,
737 error_message));
738 placeholder = ChromePluginPlaceholder::CreateBlockedPlugin(
739 render_frame,
740 frame,
741 params,
742 plugin,
743 identifier,
744 group_name,
745 IDR_BLOCKED_PLUGIN_HTML,
746 #if defined(OS_CHROMEOS)
747 l10n_util::GetStringUTF16(IDS_NACL_PLUGIN_BLOCKED));
748 #else
749 l10n_util::GetStringFUTF16(IDS_PLUGIN_BLOCKED, group_name));
750 #endif
751 break;
754 #endif // !defined(DISABLE_NACL)
756 // Delay loading plugins if prerendering.
757 // TODO(mmenke): In the case of prerendering, feed into
758 // ChromeContentRendererClient::CreatePlugin instead, to
759 // reduce the chance of future regressions.
760 if (prerender::PrerenderHelper::IsPrerendering(render_frame)) {
761 placeholder = ChromePluginPlaceholder::CreateBlockedPlugin(
762 render_frame,
763 frame,
764 params,
765 plugin,
766 identifier,
767 group_name,
768 IDR_CLICK_TO_PLAY_PLUGIN_HTML,
769 l10n_util::GetStringFUTF16(IDS_PLUGIN_LOAD, group_name));
770 placeholder->set_blocked_for_prerendering(true);
771 placeholder->set_allow_loading(true);
772 break;
775 return render_frame->CreatePlugin(frame, plugin, params);
777 case ChromeViewHostMsg_GetPluginInfo_Status::kNPAPINotSupported: {
778 RenderThread::Get()->RecordAction(
779 UserMetricsAction("Plugin_NPAPINotSupported"));
780 placeholder = ChromePluginPlaceholder::CreateBlockedPlugin(
781 render_frame,
782 frame,
783 params,
784 plugin,
785 identifier,
786 group_name,
787 IDR_BLOCKED_PLUGIN_HTML,
788 l10n_util::GetStringUTF16(IDS_PLUGIN_NOT_SUPPORTED_METRO));
789 render_frame->Send(new ChromeViewHostMsg_NPAPINotSupported(
790 render_frame->GetRoutingID(), identifier));
791 break;
793 case ChromeViewHostMsg_GetPluginInfo_Status::kDisabled: {
794 PluginUMAReporter::GetInstance()->ReportPluginDisabled(orig_mime_type,
795 url);
796 placeholder = ChromePluginPlaceholder::CreateBlockedPlugin(
797 render_frame,
798 frame,
799 params,
800 plugin,
801 identifier,
802 group_name,
803 IDR_DISABLED_PLUGIN_HTML,
804 l10n_util::GetStringFUTF16(IDS_PLUGIN_DISABLED, group_name));
805 break;
807 case ChromeViewHostMsg_GetPluginInfo_Status::kOutdatedBlocked: {
808 #if defined(ENABLE_PLUGIN_INSTALLATION)
809 placeholder = ChromePluginPlaceholder::CreateBlockedPlugin(
810 render_frame,
811 frame,
812 params,
813 plugin,
814 identifier,
815 group_name,
816 IDR_BLOCKED_PLUGIN_HTML,
817 l10n_util::GetStringFUTF16(IDS_PLUGIN_OUTDATED, group_name));
818 placeholder->set_allow_loading(true);
819 render_frame->Send(new ChromeViewHostMsg_BlockedOutdatedPlugin(
820 render_frame->GetRoutingID(), placeholder->CreateRoutingId(),
821 identifier));
822 #else
823 NOTREACHED();
824 #endif
825 break;
827 case ChromeViewHostMsg_GetPluginInfo_Status::kOutdatedDisallowed: {
828 placeholder = ChromePluginPlaceholder::CreateBlockedPlugin(
829 render_frame,
830 frame,
831 params,
832 plugin,
833 identifier,
834 group_name,
835 IDR_BLOCKED_PLUGIN_HTML,
836 l10n_util::GetStringFUTF16(IDS_PLUGIN_OUTDATED, group_name));
837 break;
839 case ChromeViewHostMsg_GetPluginInfo_Status::kUnauthorized: {
840 placeholder = ChromePluginPlaceholder::CreateBlockedPlugin(
841 render_frame,
842 frame,
843 params,
844 plugin,
845 identifier,
846 group_name,
847 IDR_BLOCKED_PLUGIN_HTML,
848 l10n_util::GetStringFUTF16(IDS_PLUGIN_NOT_AUTHORIZED, group_name));
849 placeholder->set_allow_loading(true);
850 // Check to see if old infobar should be displayed.
851 std::string trial_group =
852 base::FieldTrialList::FindFullName("UnauthorizedPluginInfoBar");
853 if (plugin.type != content::WebPluginInfo::PLUGIN_TYPE_NPAPI ||
854 trial_group == "Enabled") {
855 render_frame->Send(new ChromeViewHostMsg_BlockedUnauthorizedPlugin(
856 render_frame->GetRoutingID(),
857 group_name,
858 identifier));
859 } else {
860 // Send IPC for showing blocked plugins page action.
861 observer->DidBlockContentType(content_type);
863 break;
865 case ChromeViewHostMsg_GetPluginInfo_Status::kClickToPlay: {
866 placeholder = ChromePluginPlaceholder::CreateBlockedPlugin(
867 render_frame,
868 frame,
869 params,
870 plugin,
871 identifier,
872 group_name,
873 IDR_CLICK_TO_PLAY_PLUGIN_HTML,
874 l10n_util::GetStringFUTF16(IDS_PLUGIN_LOAD, group_name));
875 placeholder->set_allow_loading(true);
876 RenderThread::Get()->RecordAction(
877 UserMetricsAction("Plugin_ClickToPlay"));
878 observer->DidBlockContentType(content_type);
879 break;
881 case ChromeViewHostMsg_GetPluginInfo_Status::kBlocked: {
882 placeholder = ChromePluginPlaceholder::CreateBlockedPlugin(
883 render_frame,
884 frame,
885 params,
886 plugin,
887 identifier,
888 group_name,
889 IDR_BLOCKED_PLUGIN_HTML,
890 l10n_util::GetStringFUTF16(IDS_PLUGIN_BLOCKED, group_name));
891 placeholder->set_allow_loading(true);
892 RenderThread::Get()->RecordAction(UserMetricsAction("Plugin_Blocked"));
893 observer->DidBlockContentType(content_type);
894 break;
896 case ChromeViewHostMsg_GetPluginInfo_Status::kBlockedByPolicy: {
897 placeholder = ChromePluginPlaceholder::CreateBlockedPlugin(
898 render_frame,
899 frame,
900 params,
901 plugin,
902 identifier,
903 group_name,
904 IDR_BLOCKED_PLUGIN_HTML,
905 l10n_util::GetStringFUTF16(IDS_PLUGIN_BLOCKED, group_name));
906 placeholder->set_allow_loading(false);
907 RenderThread::Get()->RecordAction(
908 UserMetricsAction("Plugin_BlockedByPolicy"));
909 observer->DidBlockContentType(content_type);
910 break;
914 placeholder->SetStatus(status);
915 return placeholder->plugin();
918 // For NaCl content handling plugins, the NaCl manifest is stored in an
919 // additonal 'nacl' param associated with the MIME type.
920 // static
921 GURL ChromeContentRendererClient::GetNaClContentHandlerURL(
922 const std::string& actual_mime_type,
923 const content::WebPluginInfo& plugin) {
924 // Look for the manifest URL among the MIME type's additonal parameters.
925 const char* kNaClPluginManifestAttribute = "nacl";
926 base::string16 nacl_attr = ASCIIToUTF16(kNaClPluginManifestAttribute);
927 for (size_t i = 0; i < plugin.mime_types.size(); ++i) {
928 if (plugin.mime_types[i].mime_type == actual_mime_type) {
929 const content::WebPluginMimeType& content_type = plugin.mime_types[i];
930 for (size_t i = 0; i < content_type.additional_param_names.size(); ++i) {
931 if (content_type.additional_param_names[i] == nacl_attr)
932 return GURL(content_type.additional_param_values[i]);
934 break;
937 return GURL();
940 // static
941 bool ChromeContentRendererClient::IsNaClAllowed(
942 const GURL& manifest_url,
943 const GURL& app_url,
944 bool is_nacl_unrestricted,
945 const Extension* extension,
946 WebPluginParams* params) {
947 // Temporarily allow these whitelisted apps and WebUIs to use NaCl.
948 std::string app_url_host = app_url.host();
949 std::string manifest_url_path = manifest_url.path();
951 bool is_whitelisted_web_ui =
952 app_url.spec() == chrome::kChromeUIAppListStartPageURL;
954 bool is_photo_app =
955 // Whitelisted apps must be served over https.
956 app_url.SchemeIs("https") &&
957 manifest_url.SchemeIs("https") &&
958 (EndsWith(app_url_host, "plus.google.com", false) ||
959 EndsWith(app_url_host, "plus.sandbox.google.com", false)) &&
960 manifest_url.DomainIs("ssl.gstatic.com") &&
961 (manifest_url_path.find("s2/oz/nacl/") == 1 ||
962 manifest_url_path.find("photos/nacl/") == 1);
964 std::string manifest_fs_host;
965 if (manifest_url.SchemeIsFileSystem() && manifest_url.inner_url()) {
966 manifest_fs_host = manifest_url.inner_url()->host();
968 bool is_hangouts_app =
969 // Whitelisted apps must be served over secure scheme.
970 app_url.SchemeIs("https") &&
971 manifest_url.SchemeIsSecure() &&
972 manifest_url.SchemeIsFileSystem() &&
973 (EndsWith(app_url_host, "talkgadget.google.com", false) ||
974 EndsWith(app_url_host, "plus.google.com", false) ||
975 EndsWith(app_url_host, "plus.sandbox.google.com", false)) &&
976 // The manifest must be loaded from the host's FileSystem.
977 (manifest_fs_host == app_url_host);
979 bool is_whitelisted_app = is_photo_app || is_hangouts_app;
981 bool is_extension_from_webstore = extension &&
982 extension->from_webstore();
984 bool is_invoked_by_hosted_app = extension &&
985 extension->is_hosted_app() &&
986 extension->web_extent().MatchesURL(app_url);
988 // Allow built-in extensions and extensions under development.
989 bool is_extension_unrestricted = extension &&
990 (extension->location() == extensions::Manifest::COMPONENT ||
991 extensions::Manifest::IsUnpackedLocation(extension->location()));
993 bool is_invoked_by_extension = app_url.SchemeIs("chrome-extension");
995 // The NaCl PDF viewer is always allowed and can use 'Dev' interfaces.
996 bool is_nacl_pdf_viewer =
997 (is_extension_from_webstore &&
998 manifest_url.SchemeIs("chrome-extension") &&
999 manifest_url.host() == "acadkphlmlegjaadjagenfimbpphcgnh");
1001 // Allow Chrome Web Store extensions, built-in extensions and extensions
1002 // under development if the invocation comes from a URL with an extension
1003 // scheme. Also allow invocations if they are from whitelisted URLs or
1004 // if --enable-nacl is set.
1005 bool is_nacl_allowed = is_nacl_unrestricted ||
1006 is_whitelisted_web_ui ||
1007 is_whitelisted_app ||
1008 is_nacl_pdf_viewer ||
1009 is_invoked_by_hosted_app ||
1010 (is_invoked_by_extension &&
1011 (is_extension_from_webstore ||
1012 is_extension_unrestricted));
1013 if (is_nacl_allowed) {
1014 bool app_can_use_dev_interfaces = is_nacl_pdf_viewer;
1015 // Make sure that PPAPI 'dev' interfaces aren't available for production
1016 // apps unless they're whitelisted.
1017 WebString dev_attribute = WebString::fromUTF8("@dev");
1018 if ((!is_whitelisted_app && !is_extension_from_webstore) ||
1019 app_can_use_dev_interfaces) {
1020 // Add the special '@dev' attribute.
1021 std::vector<base::string16> param_names;
1022 std::vector<base::string16> param_values;
1023 param_names.push_back(dev_attribute);
1024 param_values.push_back(WebString());
1025 AppendParams(
1026 param_names,
1027 param_values,
1028 &params->attributeNames,
1029 &params->attributeValues);
1030 } else {
1031 // If the params somehow contain '@dev', remove it.
1032 size_t attribute_count = params->attributeNames.size();
1033 for (size_t i = 0; i < attribute_count; ++i) {
1034 if (params->attributeNames[i].equals(dev_attribute))
1035 params->attributeNames[i] = WebString();
1039 return is_nacl_allowed;
1042 bool ChromeContentRendererClient::HasErrorPage(int http_status_code,
1043 std::string* error_domain) {
1044 // Use an internal error page, if we have one for the status code.
1045 if (!LocalizedError::HasStrings(LocalizedError::kHttpErrorDomain,
1046 http_status_code)) {
1047 return false;
1050 *error_domain = LocalizedError::kHttpErrorDomain;
1051 return true;
1054 bool ChromeContentRendererClient::ShouldSuppressErrorPage(
1055 content::RenderFrame* render_frame,
1056 const GURL& url) {
1057 // Unit tests for ChromeContentRendererClient pass a NULL RenderFrame here.
1058 // Unfortunately it's very difficult to construct a mock RenderView, so skip
1059 // this functionality in this case.
1060 if (render_frame) {
1061 content::RenderView* render_view = render_frame->GetRenderView();
1062 content::RenderFrame* main_render_frame = render_view->GetMainRenderFrame();
1063 blink::WebFrame* web_frame = render_frame->GetWebFrame();
1064 NetErrorHelper* net_error_helper = NetErrorHelper::Get(main_render_frame);
1065 if (net_error_helper->ShouldSuppressErrorPage(web_frame, url))
1066 return true;
1068 // Do not flash an error page if the Instant new tab page fails to load.
1069 return search_bouncer_.get() && search_bouncer_->IsNewTabPage(url);
1072 void ChromeContentRendererClient::GetNavigationErrorStrings(
1073 content::RenderView* render_view,
1074 blink::WebFrame* frame,
1075 const blink::WebURLRequest& failed_request,
1076 const blink::WebURLError& error,
1077 std::string* error_html,
1078 base::string16* error_description) {
1079 const GURL failed_url = error.unreachableURL;
1080 const Extension* extension = NULL;
1082 if (failed_url.is_valid() &&
1083 !failed_url.SchemeIs(extensions::kExtensionScheme)) {
1084 extension = extension_dispatcher_->extensions()->GetExtensionOrAppByURL(
1085 failed_url);
1088 bool is_post = EqualsASCII(failed_request.httpMethod(), "POST");
1090 if (error_html) {
1091 // Use a local error page.
1092 if (extension && !extension->from_bookmark()) {
1093 // TODO(erikkay): Should we use a different template for different
1094 // error messages?
1095 int resource_id = IDR_ERROR_APP_HTML;
1096 const base::StringPiece template_html(
1097 ResourceBundle::GetSharedInstance().GetRawDataResource(
1098 resource_id));
1099 if (template_html.empty()) {
1100 NOTREACHED() << "unable to load template. ID: " << resource_id;
1101 } else {
1102 base::DictionaryValue error_strings;
1103 LocalizedError::GetAppErrorStrings(failed_url, extension,
1104 &error_strings);
1105 // "t" is the id of the template's root node.
1106 *error_html = webui::GetTemplatesHtml(template_html, &error_strings,
1107 "t");
1109 } else {
1110 // TODO(ellyjones): change GetNavigationErrorStrings to take a RenderFrame
1111 // instead of a RenderView, then pass that in.
1112 // This is safe for now because we only install the NetErrorHelper on the
1113 // main render frame anyway; see the TODO(ellyjones) in
1114 // RenderFrameCreated.
1115 content::RenderFrame* main_render_frame =
1116 render_view->GetMainRenderFrame();
1117 NetErrorHelper* helper = NetErrorHelper::Get(main_render_frame);
1118 helper->GetErrorHTML(frame, error, is_post, error_html);
1122 if (error_description) {
1123 if (!extension)
1124 *error_description = LocalizedError::GetErrorDetails(error, is_post);
1128 bool ChromeContentRendererClient::RunIdleHandlerWhenWidgetsHidden() {
1129 return !extension_dispatcher_->is_extension_process();
1132 bool ChromeContentRendererClient::AllowPopup() {
1133 extensions::ScriptContext* current_context =
1134 extension_dispatcher_->script_context_set().GetCurrent();
1135 if (!current_context || !current_context->extension())
1136 return false;
1137 // See http://crbug.com/117446 for the subtlety of this check.
1138 switch (current_context->context_type()) {
1139 case extensions::Feature::UNSPECIFIED_CONTEXT:
1140 case extensions::Feature::WEB_PAGE_CONTEXT:
1141 case extensions::Feature::UNBLESSED_EXTENSION_CONTEXT:
1142 case extensions::Feature::WEBUI_CONTEXT:
1143 return false;
1144 case extensions::Feature::BLESSED_EXTENSION_CONTEXT:
1145 case extensions::Feature::CONTENT_SCRIPT_CONTEXT:
1146 return true;
1147 case extensions::Feature::BLESSED_WEB_PAGE_CONTEXT:
1148 return !current_context->web_frame()->parent();
1150 NOTREACHED();
1151 return false;
1154 bool ChromeContentRendererClient::ShouldFork(WebFrame* frame,
1155 const GURL& url,
1156 const std::string& http_method,
1157 bool is_initial_navigation,
1158 bool is_server_redirect,
1159 bool* send_referrer) {
1160 DCHECK(!frame->parent());
1162 // If this is the Instant process, fork all navigations originating from the
1163 // renderer. The destination page will then be bucketed back to this Instant
1164 // process if it is an Instant url, or to another process if not. Conversely,
1165 // fork if this is a non-Instant process navigating to an Instant url, so that
1166 // such navigations can also be bucketed into an Instant renderer.
1167 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kInstantProcess) ||
1168 (search_bouncer_.get() && search_bouncer_->ShouldFork(url))) {
1169 *send_referrer = true;
1170 return true;
1173 // For now, we skip the rest for POST submissions. This is because
1174 // http://crbug.com/101395 is more likely to cause compatibility issues
1175 // with hosted apps and extensions than WebUI pages. We will remove this
1176 // check when cross-process POST submissions are supported.
1177 if (http_method != "GET")
1178 return false;
1180 // If this is the Signin process, fork all navigations originating from the
1181 // renderer. The destination page will then be bucketed back to this Signin
1182 // process if it is a Signin url, or to another process if not.
1183 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSigninProcess)) {
1184 // We never want to allow non-signin pages to fork-on-POST to a
1185 // signin-related action URL. We'll need to handle this carefully once
1186 // http://crbug.com/101395 is fixed. The CHECK ensures we don't forget.
1187 CHECK_NE(http_method, "POST");
1188 return true;
1191 // If |url| matches one of the prerendered URLs, stop this navigation and try
1192 // to swap in the prerendered page on the browser process. If the prerendered
1193 // page no longer exists by the time the OpenURL IPC is handled, a normal
1194 // navigation is attempted.
1195 if (prerender_dispatcher_.get() &&
1196 prerender_dispatcher_->IsPrerenderURL(url)) {
1197 *send_referrer = true;
1198 return true;
1201 const extensions::ExtensionSet* extensions =
1202 extension_dispatcher_->extensions();
1204 // Determine if the new URL is an extension (excluding bookmark apps).
1205 const Extension* new_url_extension = extensions::GetNonBookmarkAppExtension(
1206 *extensions, url);
1207 bool is_extension_url = !!new_url_extension;
1209 // If the navigation would cross an app extent boundary, we also need
1210 // to defer to the browser to ensure process isolation. This is not necessary
1211 // for server redirects, which will be transferred to a new process by the
1212 // browser process when they are ready to commit. It is necessary for client
1213 // redirects, which won't be transferred in the same way.
1214 if (!is_server_redirect &&
1215 CrossesExtensionExtents(frame, url, *extensions, is_extension_url,
1216 is_initial_navigation)) {
1217 // Include the referrer in this case since we're going from a hosted web
1218 // page. (the packaged case is handled previously by the extension
1219 // navigation test)
1220 *send_referrer = true;
1222 const Extension* extension =
1223 extension_dispatcher_->extensions()->GetExtensionOrAppByURL(url);
1224 if (extension && extension->is_app()) {
1225 UMA_HISTOGRAM_ENUMERATION(
1226 extension->is_platform_app() ?
1227 extension_misc::kPlatformAppLaunchHistogram :
1228 extension_misc::kAppLaunchHistogram,
1229 extension_misc::APP_LAUNCH_CONTENT_NAVIGATION,
1230 extension_misc::APP_LAUNCH_BUCKET_BOUNDARY);
1232 return true;
1235 // If this is a reload, check whether it has the wrong process type. We
1236 // should send it to the browser if it's an extension URL (e.g., hosted app)
1237 // in a normal process, or if it's a process for an extension that has been
1238 // uninstalled.
1239 if (frame->top()->document().url() == url) {
1240 if (is_extension_url != extension_dispatcher_->is_extension_process())
1241 return true;
1244 return false;
1247 bool ChromeContentRendererClient::WillSendRequest(
1248 blink::WebFrame* frame,
1249 content::PageTransition transition_type,
1250 const GURL& url,
1251 const GURL& first_party_for_cookies,
1252 GURL* new_url) {
1253 // Check whether the request should be allowed. If not allowed, we reset the
1254 // URL to something invalid to prevent the request and cause an error.
1255 if (url.SchemeIs(extensions::kExtensionScheme) &&
1256 !extensions::ResourceRequestPolicy::CanRequestResource(
1257 url,
1258 frame,
1259 transition_type,
1260 extension_dispatcher_->extensions())) {
1261 *new_url = GURL(chrome::kExtensionInvalidRequestURL);
1262 return true;
1265 if (url.SchemeIs(extensions::kExtensionResourceScheme) &&
1266 !extensions::ResourceRequestPolicy::CanRequestExtensionResourceScheme(
1267 url,
1268 frame)) {
1269 *new_url = GURL(chrome::kExtensionResourceInvalidRequestURL);
1270 return true;
1273 const content::RenderView* render_view =
1274 content::RenderView::FromWebView(frame->view());
1275 SearchBox* search_box = SearchBox::Get(render_view);
1276 if (search_box && url.SchemeIs(chrome::kChromeSearchScheme)) {
1277 if (url.host() == chrome::kChromeUIThumbnailHost)
1278 return search_box->GenerateThumbnailURLFromTransientURL(url, new_url);
1279 else if (url.host() == chrome::kChromeUIFaviconHost)
1280 return search_box->GenerateFaviconURLFromTransientURL(url, new_url);
1283 return false;
1286 void ChromeContentRendererClient::DidCreateScriptContext(
1287 WebFrame* frame, v8::Handle<v8::Context> context, int extension_group,
1288 int world_id) {
1289 extension_dispatcher_->DidCreateScriptContext(
1290 frame, context, extension_group, world_id);
1293 unsigned long long ChromeContentRendererClient::VisitedLinkHash(
1294 const char* canonical_url, size_t length) {
1295 return visited_link_slave_->ComputeURLFingerprint(canonical_url, length);
1298 bool ChromeContentRendererClient::IsLinkVisited(unsigned long long link_hash) {
1299 return visited_link_slave_->IsVisited(link_hash);
1302 blink::WebPrescientNetworking*
1303 ChromeContentRendererClient::GetPrescientNetworking() {
1304 return prescient_networking_dispatcher_.get();
1307 bool ChromeContentRendererClient::ShouldOverridePageVisibilityState(
1308 const content::RenderFrame* render_frame,
1309 blink::WebPageVisibilityState* override_state) {
1310 if (!prerender::PrerenderHelper::IsPrerendering(render_frame))
1311 return false;
1313 *override_state = blink::WebPageVisibilityStatePrerender;
1314 return true;
1317 void ChromeContentRendererClient::SetExtensionDispatcherForTest(
1318 extensions::Dispatcher* extension_dispatcher) {
1319 extension_dispatcher_.reset(extension_dispatcher);
1320 permissions_policy_delegate_.reset(
1321 new extensions::RendererPermissionsPolicyDelegate(
1322 extension_dispatcher_.get()));
1325 extensions::Dispatcher*
1326 ChromeContentRendererClient::GetExtensionDispatcherForTest() {
1327 return extension_dispatcher_.get();
1330 bool ChromeContentRendererClient::CrossesExtensionExtents(
1331 WebFrame* frame,
1332 const GURL& new_url,
1333 const extensions::ExtensionSet& extensions,
1334 bool is_extension_url,
1335 bool is_initial_navigation) {
1336 GURL old_url(frame->top()->document().url());
1338 // If old_url is still empty and this is an initial navigation, then this is
1339 // a window.open operation. We should look at the opener URL.
1340 if (is_initial_navigation && old_url.is_empty() && frame->opener()) {
1341 // If we're about to open a normal web page from a same-origin opener stuck
1342 // in an extension process, we want to keep it in process to allow the
1343 // opener to script it.
1344 WebDocument opener_document = frame->opener()->document();
1345 WebSecurityOrigin opener = frame->opener()->document().securityOrigin();
1346 bool opener_is_extension_url =
1347 !opener.isUnique() && extensions.GetExtensionOrAppByURL(
1348 opener_document.url()) != NULL;
1349 if (!is_extension_url &&
1350 !opener_is_extension_url &&
1351 extension_dispatcher_->is_extension_process() &&
1352 opener.canRequest(WebURL(new_url)))
1353 return false;
1355 // In all other cases, we want to compare against the top frame's URL (as
1356 // opposed to the opener frame's), since that's what determines the type of
1357 // process. This allows iframes outside an app to open a popup in the app.
1358 old_url = frame->top()->opener()->top()->document().url();
1361 // Only consider keeping non-app URLs in an app process if this window
1362 // has an opener (in which case it might be an OAuth popup that tries to
1363 // script an iframe within the app).
1364 bool should_consider_workaround = !!frame->opener();
1366 return extensions::CrossesExtensionProcessBoundary(
1367 extensions, old_url, new_url, should_consider_workaround);
1370 #if defined(ENABLE_SPELLCHECK)
1371 void ChromeContentRendererClient::SetSpellcheck(SpellCheck* spellcheck) {
1372 RenderThread* thread = RenderThread::Get();
1373 if (spellcheck_.get() && thread)
1374 thread->RemoveObserver(spellcheck_.get());
1375 spellcheck_.reset(spellcheck);
1376 SpellCheckReplacer replacer(spellcheck_.get());
1377 content::RenderView::ForEach(&replacer);
1378 if (thread)
1379 thread->AddObserver(spellcheck_.get());
1381 #endif
1383 // static
1384 bool ChromeContentRendererClient::WasWebRequestUsedBySomeExtensions() {
1385 return g_current_client->extension_dispatcher_delegate_
1386 ->WasWebRequestUsedBySomeExtensions();
1389 const void* ChromeContentRendererClient::CreatePPAPIInterface(
1390 const std::string& interface_name) {
1391 #if defined(ENABLE_PLUGINS)
1392 #if !defined(DISABLE_NACL)
1393 if (interface_name == PPB_NACL_PRIVATE_INTERFACE)
1394 return nacl::GetNaClPrivateInterface();
1395 #endif // DISABLE_NACL
1396 if (interface_name == PPB_PDF_INTERFACE)
1397 return PPB_PDF_Impl::GetInterface();
1398 #endif
1399 return NULL;
1402 bool ChromeContentRendererClient::IsExternalPepperPlugin(
1403 const std::string& module_name) {
1404 // TODO(bbudge) remove this when the trusted NaCl plugin has been removed.
1405 // We must defer certain plugin events for NaCl instances since we switch
1406 // from the in-process to the out-of-process proxy after instantiating them.
1407 return module_name == "Native Client";
1410 bool ChromeContentRendererClient::IsExtensionOrSharedModuleWhitelisted(
1411 const GURL& url, const std::set<std::string>& whitelist) {
1412 const extensions::ExtensionSet* extension_set =
1413 g_current_client->extension_dispatcher_->extensions();
1414 return chrome::IsExtensionOrSharedModuleWhitelisted(url, extension_set,
1415 whitelist);
1418 blink::WebSpeechSynthesizer*
1419 ChromeContentRendererClient::OverrideSpeechSynthesizer(
1420 blink::WebSpeechSynthesizerClient* client) {
1421 return new TtsDispatcher(client);
1424 bool ChromeContentRendererClient::AllowPepperMediaStreamAPI(
1425 const GURL& url) {
1426 #if !defined(OS_ANDROID)
1427 // Allow only the Hangouts app to use the MediaStream APIs. It's OK to check
1428 // the whitelist in the renderer, since we're only preventing access until
1429 // these APIs are public and stable.
1430 std::string url_host = url.host();
1431 if (url.SchemeIs("https") &&
1432 (EndsWith(url_host, "talkgadget.google.com", false) ||
1433 EndsWith(url_host, "plus.google.com", false) ||
1434 EndsWith(url_host, "plus.sandbox.google.com", false)) &&
1435 StartsWithASCII(url.path(), "/hangouts/", false)) {
1436 return true;
1438 // Allow access for tests.
1439 if (CommandLine::ForCurrentProcess()->HasSwitch(
1440 switches::kEnablePepperTesting)) {
1441 return true;
1443 #endif // !defined(OS_ANDROID)
1444 return false;
1447 void ChromeContentRendererClient::AddKeySystems(
1448 std::vector<content::KeySystemInfo>* key_systems) {
1449 AddChromeKeySystems(key_systems);
1452 bool ChromeContentRendererClient::ShouldReportDetailedMessageForSource(
1453 const base::string16& source) const {
1454 return extensions::IsSourceFromAnExtension(source);
1457 bool ChromeContentRendererClient::ShouldEnableSiteIsolationPolicy() const {
1458 // SiteIsolationPolicy is off by default. We would like to activate cross-site
1459 // document blocking (for UMA data collection) for normal renderer processes
1460 // running a normal web page from the Internet. We only turn on
1461 // SiteIsolationPolicy for a renderer process that does not have the extension
1462 // flag on.
1463 CommandLine* command_line = CommandLine::ForCurrentProcess();
1464 return !command_line->HasSwitch(extensions::switches::kExtensionProcess);
1467 blink::WebWorkerPermissionClientProxy*
1468 ChromeContentRendererClient::CreateWorkerPermissionClientProxy(
1469 content::RenderFrame* render_frame,
1470 blink::WebFrame* frame) {
1471 return new WorkerPermissionClientProxy(render_frame, frame);
1474 bool ChromeContentRendererClient::IsPluginAllowedToUseDevChannelAPIs() {
1475 #if defined(ENABLE_PLUGINS)
1476 // Allow access for tests.
1477 if (CommandLine::ForCurrentProcess()->HasSwitch(
1478 switches::kEnablePepperTesting)) {
1479 return true;
1482 chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
1483 // Allow dev channel APIs to be used on "Canary", "Dev", and "Unknown"
1484 // releases of Chrome. Permitting "Unknown" allows these APIs to be used on
1485 // Chromium builds as well.
1486 return channel <= chrome::VersionInfo::CHANNEL_DEV;
1487 #else
1488 return false;
1489 #endif
1492 bool ChromeContentRendererClient::IsPluginAllowedToUseCompositorAPI(
1493 const GURL& url) {
1494 #if defined(ENABLE_PLUGINS)
1495 if (CommandLine::ForCurrentProcess()->HasSwitch(
1496 switches::kEnablePepperTesting))
1497 return true;
1498 if (IsExtensionOrSharedModuleWhitelisted(url, allowed_compositor_origins_))
1499 return true;
1501 chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
1502 return channel <= chrome::VersionInfo::CHANNEL_DEV;
1503 #else
1504 return false;
1505 #endif
1508 bool ChromeContentRendererClient::IsPluginAllowedToUseVideoDecodeAPI(
1509 const GURL& url) {
1510 #if defined(ENABLE_PLUGINS)
1511 if (CommandLine::ForCurrentProcess()->HasSwitch(
1512 switches::kEnablePepperTesting))
1513 return true;
1515 if (IsExtensionOrSharedModuleWhitelisted(url, allowed_video_decode_origins_))
1516 return true;
1518 chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
1519 return channel <= chrome::VersionInfo::CHANNEL_DEV;
1520 #else
1521 return false;
1522 #endif