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