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