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