chrome_content_browser_client.cc revision a3f7b4e666c476898878fa745f637129375cd889
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/browser/chrome_content_browser_client.h"
6
7#include <set>
8#include <utility>
9#include <vector>
10
11#include "base/bind.h"
12#include "base/command_line.h"
13#include "base/lazy_instance.h"
14#include "base/path_service.h"
15#include "base/prefs/pref_service.h"
16#include "base/strings/string_number_conversions.h"
17#include "base/strings/utf_string_conversions.h"
18#include "base/threading/sequenced_worker_pool.h"
19#include "chrome/app/breakpad_mac.h"
20#include "chrome/browser/app_mode/app_mode_utils.h"
21#include "chrome/browser/browser_about_handler.h"
22#include "chrome/browser/browser_process.h"
23#include "chrome/browser/browser_shutdown.h"
24#include "chrome/browser/browsing_data/browsing_data_helper.h"
25#include "chrome/browser/browsing_data/browsing_data_remover.h"
26#include "chrome/browser/character_encoding.h"
27#include "chrome/browser/chrome_net_benchmarking_message_filter.h"
28#include "chrome/browser/chrome_quota_permission_context.h"
29#include "chrome/browser/content_settings/content_settings_utils.h"
30#include "chrome/browser/content_settings/cookie_settings.h"
31#include "chrome/browser/content_settings/host_content_settings_map.h"
32#include "chrome/browser/content_settings/tab_specific_content_settings.h"
33#include "chrome/browser/defaults.h"
34#include "chrome/browser/download/download_util.h"
35#include "chrome/browser/extensions/activity_log/activity_log.h"
36#include "chrome/browser/extensions/api/web_request/web_request_api.h"
37#include "chrome/browser/extensions/browser_permissions_policy_delegate.h"
38#include "chrome/browser/extensions/extension_host.h"
39#include "chrome/browser/extensions/extension_info_map.h"
40#include "chrome/browser/extensions/extension_process_manager.h"
41#include "chrome/browser/extensions/extension_service.h"
42#include "chrome/browser/extensions/extension_system.h"
43#include "chrome/browser/extensions/extension_web_ui.h"
44#include "chrome/browser/extensions/extension_webkit_preferences.h"
45#include "chrome/browser/extensions/suggest_permission_util.h"
46#include "chrome/browser/geolocation/chrome_access_token_store.h"
47#include "chrome/browser/google/google_util.h"
48#include "chrome/browser/guestview/adview/adview_guest.h"
49#include "chrome/browser/guestview/guestview_constants.h"
50#include "chrome/browser/guestview/webview/webview_guest.h"
51#include "chrome/browser/media/media_capture_devices_dispatcher.h"
52#include "chrome/browser/metrics/chrome_browser_main_extra_parts_metrics.h"
53#include "chrome/browser/nacl_host/nacl_host_message_filter.h"
54#include "chrome/browser/nacl_host/nacl_process_host.h"
55#include "chrome/browser/net/chrome_net_log.h"
56#include "chrome/browser/notifications/desktop_notification_service.h"
57#include "chrome/browser/notifications/desktop_notification_service_factory.h"
58#include "chrome/browser/platform_util.h"
59#include "chrome/browser/plugins/plugin_info_message_filter.h"
60#include "chrome/browser/prefs/scoped_user_pref_update.h"
61#include "chrome/browser/prerender/prerender_manager.h"
62#include "chrome/browser/prerender/prerender_manager_factory.h"
63#include "chrome/browser/prerender/prerender_message_filter.h"
64#include "chrome/browser/prerender/prerender_tracker.h"
65#include "chrome/browser/printing/printing_message_filter.h"
66#include "chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.h"
67#include "chrome/browser/profiles/profile.h"
68#include "chrome/browser/profiles/profile_io_data.h"
69#include "chrome/browser/profiles/profile_manager.h"
70#include "chrome/browser/renderer_host/chrome_render_message_filter.h"
71#include "chrome/browser/renderer_host/pepper/chrome_browser_pepper_host_factory.h"
72#include "chrome/browser/search/instant_service.h"
73#include "chrome/browser/search/instant_service_factory.h"
74#include "chrome/browser/search/search.h"
75#include "chrome/browser/search_engines/search_provider_install_state_message_filter.h"
76#include "chrome/browser/speech/chrome_speech_recognition_manager_delegate.h"
77#include "chrome/browser/speech/tts_message_filter.h"
78#include "chrome/browser/spellchecker/spellcheck_message_filter.h"
79#include "chrome/browser/ssl/ssl_add_certificate.h"
80#include "chrome/browser/ssl/ssl_blocking_page.h"
81#include "chrome/browser/ssl/ssl_tab_helper.h"
82#include "chrome/browser/tab_contents/tab_util.h"
83#include "chrome/browser/ui/chrome_select_file_policy.h"
84#include "chrome/browser/ui/sync/sync_promo_ui.h"
85#include "chrome/browser/ui/tab_contents/chrome_web_contents_view_delegate.h"
86#include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
87#include "chrome/browser/user_style_sheet_watcher.h"
88#include "chrome/browser/user_style_sheet_watcher_factory.h"
89#include "chrome/browser/validation_message_message_filter.h"
90#include "chrome/common/child_process_logging.h"
91#include "chrome/common/chrome_constants.h"
92#include "chrome/common/chrome_paths.h"
93#include "chrome/common/chrome_switches.h"
94#include "chrome/common/extensions/background_info.h"
95#include "chrome/common/extensions/extension.h"
96#include "chrome/common/extensions/extension_process_policy.h"
97#include "chrome/common/extensions/extension_set.h"
98#include "chrome/common/extensions/manifest_handlers/app_isolation_info.h"
99#include "chrome/common/extensions/manifest_handlers/shared_module_info.h"
100#include "chrome/common/extensions/permissions/permissions_data.h"
101#include "chrome/common/extensions/permissions/socket_permission.h"
102#include "chrome/common/logging_chrome.h"
103#include "chrome/common/pepper_permission_util.h"
104#include "chrome/common/pref_names.h"
105#include "chrome/common/render_messages.h"
106#include "chrome/common/url_constants.h"
107#include "chromeos/chromeos_constants.h"
108#include "components/nacl/common/nacl_process_type.h"
109#include "components/user_prefs/pref_registry_syncable.h"
110#include "content/public/browser/browser_child_process_host.h"
111#include "content/public/browser/browser_main_parts.h"
112#include "content/public/browser/browser_ppapi_host.h"
113#include "content/public/browser/browser_thread.h"
114#include "content/public/browser/browser_url_handler.h"
115#include "content/public/browser/child_process_data.h"
116#include "content/public/browser/child_process_security_policy.h"
117#include "content/public/browser/compositor_util.h"
118#include "content/public/browser/render_process_host.h"
119#include "content/public/browser/render_view_host.h"
120#include "content/public/browser/resource_context.h"
121#include "content/public/browser/site_instance.h"
122#include "content/public/browser/web_contents.h"
123#include "content/public/browser/web_contents_view.h"
124#include "content/public/common/child_process_host.h"
125#include "content/public/common/content_descriptors.h"
126#include "extensions/browser/view_type_utils.h"
127#include "extensions/common/constants.h"
128#include "extensions/common/switches.h"
129#include "grit/generated_resources.h"
130#include "grit/ui_resources.h"
131#include "net/base/escape.h"
132#include "net/base/mime_util.h"
133#include "net/cookies/canonical_cookie.h"
134#include "net/cookies/cookie_options.h"
135#include "net/ssl/ssl_cert_request_info.h"
136#include "ppapi/host/ppapi_host.h"
137#include "ui/base/l10n/l10n_util.h"
138#include "ui/base/resource/resource_bundle.h"
139#include "ui/message_center/message_center_util.h"
140#include "webkit/browser/fileapi/external_mount_points.h"
141#include "webkit/common/webpreferences.h"
142#include "webkit/plugins/plugin_switches.h"
143
144#if defined(OS_WIN)
145#include "chrome/browser/chrome_browser_main_win.h"
146#include "sandbox/win/src/sandbox_policy.h"
147#elif defined(OS_MACOSX)
148#include "chrome/browser/chrome_browser_main_mac.h"
149#include "chrome/browser/spellchecker/spellcheck_message_filter_mac.h"
150#elif defined(OS_CHROMEOS)
151#include "chrome/browser/chromeos/chrome_browser_main_chromeos.h"
152#include "chrome/browser/chromeos/drive/file_system_backend_delegate.h"
153#include "chrome/browser/chromeos/fileapi/file_system_backend.h"
154#include "chrome/browser/chromeos/login/startup_utils.h"
155#include "chrome/browser/chromeos/login/user_manager.h"
156#include "chrome/browser/chromeos/system/statistics_provider.h"
157#include "chromeos/chromeos_switches.h"
158#elif defined(OS_LINUX)
159#include "chrome/browser/chrome_browser_main_linux.h"
160#elif defined(OS_ANDROID)
161#include "chrome/browser/android/crash_dump_manager.h"
162#include "chrome/browser/chrome_browser_main_android.h"
163#include "chrome/common/descriptors_android.h"
164#elif defined(OS_POSIX)
165#include "chrome/browser/chrome_browser_main_posix.h"
166#endif
167
168#if defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_ANDROID)
169#include "base/linux_util.h"
170#include "chrome/browser/crash_handler_host_linux.h"
171#endif
172
173#if defined(ENABLE_CAPTIVE_PORTAL_DETECTION)
174#include "chrome/browser/captive_portal/captive_portal_tab_helper.h"
175#endif
176
177#if defined(OS_ANDROID)
178#include "ui/base/ui_base_paths.h"
179#endif
180
181#if defined(USE_NSS)
182#include "chrome/browser/ui/crypto_module_password_dialog.h"
183#endif
184
185#if !defined(OS_CHROMEOS)
186#include "chrome/browser/signin/signin_manager.h"
187#include "chrome/browser/signin/signin_manager_factory.h"
188#endif
189
190#if !defined(OS_ANDROID)
191#include "chrome/browser/media_galleries/fileapi/media_file_system_backend.h"
192#endif
193
194#if defined(ENABLE_WEBRTC)
195#include "chrome/browser/media/webrtc_logging_handler_host.h"
196#endif
197
198#if defined(ENABLE_INPUT_SPEECH)
199#include "chrome/browser/speech/chrome_speech_recognition_manager_delegate_bubble_ui.h"
200#endif
201
202#if defined(FILE_MANAGER_EXTENSION)
203#include "chrome/browser/chromeos/extensions/file_manager/file_manager_util.h"
204#endif
205
206#if defined(TOOLKIT_GTK)
207#include "chrome/browser/ui/gtk/chrome_browser_main_extra_parts_gtk.h"
208#endif
209
210#if defined(TOOLKIT_VIEWS)
211#include "chrome/browser/ui/views/chrome_browser_main_extra_parts_views.h"
212#endif
213
214#if defined(USE_ASH)
215#include "chrome/browser/ui/views/ash/chrome_browser_main_extra_parts_ash.h"
216#endif
217
218#if defined(USE_AURA)
219#include "chrome/browser/ui/aura/chrome_browser_main_extra_parts_aura.h"
220#endif
221
222#if defined(USE_X11)
223#include "chrome/browser/chrome_browser_main_extra_parts_x11.h"
224#endif
225
226using base::FileDescriptor;
227using content::AccessTokenStore;
228using content::BrowserChildProcessHostIterator;
229using content::BrowserThread;
230using content::BrowserURLHandler;
231using content::ChildProcessSecurityPolicy;
232using content::FileDescriptorInfo;
233using content::QuotaPermissionContext;
234using content::RenderViewHost;
235using content::SiteInstance;
236using content::WebContents;
237using extensions::APIPermission;
238using extensions::Extension;
239using extensions::Manifest;
240
241namespace {
242
243// Cached version of the locale so we can return the locale on the I/O
244// thread.
245base::LazyInstance<std::string> g_io_thread_application_locale;
246
247#if defined(ENABLE_PLUGINS)
248const char* kPredefinedAllowedSocketOrigins[] = {
249  "okddffdblfhhnmhodogpojmfkjmhinfp",  // Test SSH Client
250  "pnhechapfaindjhompbnflcldabbghjo",  // HTerm App (SSH Client)
251  "bglhmjfplikpjnfoegeomebmfnkjomhe",  // see crbug.com/122126
252  "gbchcmhmhahfdphkhkmpfmihenigjmpp",  // Chrome Remote Desktop
253  "kgngmbheleoaphbjbaiobfdepmghbfah",  // Pre-release Chrome Remote Desktop
254  "odkaodonbgfohohmklejpjiejmcipmib",  // Dogfood Chrome Remote Desktop
255  "ojoimpklfciegopdfgeenehpalipignm",  // Chromoting canary
256  "cbkkbcmdlboombapidmoeolnmdacpkch",  // see crbug.com/129089
257  "hhnbmknkdabfoieppbbljkhkfjcmcbjh",  // see crbug.com/134099
258  "mablfbjkhmhkmefkjjacnbaikjkipphg",  // see crbug.com/134099
259  "pdeelgamlgannhelgoegilelnnojegoh",  // see crbug.com/134099
260  "cabapfdbkniadpollkckdnedaanlciaj",  // see crbug.com/134099
261  "mapljbgnjledlpdmlchihnmeclmefbba",  // see crbug.com/134099
262  "ghbfeebgmiidnnmeobbbaiamklmpbpii",  // see crbug.com/134099
263  "jdfhpkjeckflbbleddjlpimecpbjdeep",  // see crbug.com/142514
264  "iabmpiboiopbgfabjmgeedhcmjenhbla",  // see crbug.com/165080
265  "B7CF8A292249681AF81771650BA4CEEAF19A4560", // see crbug.com/165080
266  "6EAED1924DB611B6EEF2A664BD077BE7EAD33B8F", // see crbug.com/234789
267  "7525AF4F66763A70A883C4700529F647B470E4D2", // see crbug.com/238084
268  "0B549507088E1564D672F7942EB87CA4DAD73972", // see crbug.com/238084
269  "864288364E239573E777D3E0E36864E590E95C74"  // see crbug.com/238084
270};
271#endif
272
273// Returns a copy of the given url with its host set to given host and path set
274// to given path. Other parts of the url will be the same.
275GURL ReplaceURLHostAndPath(const GURL& url,
276                           const std::string& host,
277                           const std::string& path) {
278  url_canon::Replacements<char> replacements;
279  replacements.SetHost(host.c_str(),
280                       url_parse::Component(0, host.length()));
281  replacements.SetPath(path.c_str(),
282                       url_parse::Component(0, path.length()));
283  return url.ReplaceComponents(replacements);
284}
285
286// Maps "foo://bar/baz/" to "foo://chrome/bar/baz/".
287GURL AddUberHost(const GURL& url) {
288  const std::string uber_host = chrome::kChromeUIUberHost;
289  const std::string new_path = url.host() + url.path();
290
291  return ReplaceURLHostAndPath(url, uber_host, new_path);
292}
293
294// If url->host() is "chrome" and url->path() has characters other than the
295// first slash, changes the url from "foo://chrome/bar/" to "foo://bar/" and
296// returns true. Otherwise returns false.
297bool RemoveUberHost(GURL* url) {
298  if (url->host() != chrome::kChromeUIUberHost)
299    return false;
300
301  if (url->path().empty() || url->path() == "/")
302    return false;
303
304  const std::string old_path = url->path();
305
306  const std::string::size_type separator = old_path.find('/', 1);
307  std::string new_host;
308  std::string new_path;
309  if (separator == std::string::npos) {
310    new_host = old_path.substr(1);
311  } else {
312    new_host = old_path.substr(1, separator - 1);
313    new_path = old_path.substr(separator);
314  }
315
316  // Do not allow URLs with paths empty before the first slash since we can't
317  // have an empty host. (e.g "foo://chrome//")
318  if (new_host.empty())
319    return false;
320
321  *url = ReplaceURLHostAndPath(*url, new_host, new_path);
322
323  DCHECK(url->is_valid());
324
325  return true;
326}
327
328// Handles rewriting Web UI URLs.
329bool HandleWebUI(GURL* url, content::BrowserContext* browser_context) {
330  // Do not handle special URLs such as "about:foo"
331  if (!url->host().empty()) {
332    const GURL chrome_url = AddUberHost(*url);
333
334    // Handle valid "chrome://chrome/foo" URLs so the reverse handler will
335    // be called.
336    if (ChromeWebUIControllerFactory::GetInstance()->UseWebUIForURL(
337            browser_context, chrome_url))
338      return true;
339  }
340
341  if (!ChromeWebUIControllerFactory::GetInstance()->UseWebUIForURL(
342          browser_context, *url))
343    return false;
344
345#if defined(OS_CHROMEOS)
346  // Special case : in ChromeOS in Guest mode bookmarks and history are
347  // disabled for security reasons. New tab page explains the reasons, so
348  // we redirect user to new tab page.
349  if (chromeos::UserManager::Get()->IsLoggedInAsGuest()) {
350    if (url->SchemeIs(chrome::kChromeUIScheme) &&
351        (url->DomainIs(chrome::kChromeUIBookmarksHost) ||
352         url->DomainIs(chrome::kChromeUIHistoryHost))) {
353      // Rewrite with new tab URL
354      *url = GURL(chrome::kChromeUINewTabURL);
355    }
356  }
357#endif
358
359  // Special case the new tab page. In older versions of Chrome, the new tab
360  // page was hosted at chrome-internal:<blah>. This might be in people's saved
361  // sessions or bookmarks, so we say any URL with that scheme triggers the new
362  // tab page.
363  if (url->SchemeIs(chrome::kChromeInternalScheme)) {
364    // Rewrite it with the proper new tab URL.
365    *url = GURL(chrome::kChromeUINewTabURL);
366  }
367
368  return true;
369}
370
371// Reverse URL handler for Web UI. Maps "chrome://chrome/foo/" to
372// "chrome://foo/".
373bool HandleWebUIReverse(GURL* url, content::BrowserContext* browser_context) {
374  if (!url->is_valid() || !url->SchemeIs(chrome::kChromeUIScheme))
375    return false;
376
377  return RemoveUberHost(url);
378}
379
380// Used by the GetPrivilegeRequiredByUrl() and GetProcessPrivilege() functions
381// below.  Extension, and isolated apps require different privileges to be
382// granted to their RenderProcessHosts.  This classification allows us to make
383// sure URLs are served by hosts with the right set of privileges.
384enum RenderProcessHostPrivilege {
385  PRIV_NORMAL,
386  PRIV_HOSTED,
387  PRIV_ISOLATED,
388  PRIV_EXTENSION,
389};
390
391RenderProcessHostPrivilege GetPrivilegeRequiredByUrl(
392    const GURL& url,
393    ExtensionService* service) {
394  // Default to a normal renderer cause it is lower privileged. This should only
395  // occur if the URL on a site instance is either malformed, or uninitialized.
396  // If it is malformed, then there is no need for better privileges anyways.
397  // If it is uninitialized, but eventually settles on being an a scheme other
398  // than normal webrenderer, the navigation logic will correct us out of band
399  // anyways.
400  if (!url.is_valid())
401    return PRIV_NORMAL;
402
403  if (url.SchemeIs(extensions::kExtensionScheme)) {
404    const Extension* extension =
405        service->extensions()->GetByID(url.host());
406    if (extension &&
407        extensions::AppIsolationInfo::HasIsolatedStorage(extension))
408      return PRIV_ISOLATED;
409    if (extension && extension->is_hosted_app())
410      return PRIV_HOSTED;
411
412    return PRIV_EXTENSION;
413  }
414
415  return PRIV_NORMAL;
416}
417
418RenderProcessHostPrivilege GetProcessPrivilege(
419    content::RenderProcessHost* process_host,
420    extensions::ProcessMap* process_map,
421    ExtensionService* service) {
422  std::set<std::string> extension_ids =
423      process_map->GetExtensionsInProcess(process_host->GetID());
424  if (extension_ids.empty())
425    return PRIV_NORMAL;
426
427  for (std::set<std::string>::iterator iter = extension_ids.begin();
428       iter != extension_ids.end(); ++iter) {
429    const Extension* extension = service->GetExtensionById(*iter, false);
430    if (extension &&
431        extensions::AppIsolationInfo::HasIsolatedStorage(extension))
432      return PRIV_ISOLATED;
433    if (extension && extension->is_hosted_app())
434      return PRIV_HOSTED;
435  }
436
437  return PRIV_EXTENSION;
438}
439
440bool CertMatchesFilter(const net::X509Certificate& cert,
441                       const base::DictionaryValue& filter) {
442  // TODO(markusheintz): This is the minimal required filter implementation.
443  // Implement a better matcher.
444
445  // An empty filter matches any client certificate since no requirements are
446  // specified at all.
447  if (filter.empty())
448    return true;
449
450  std::string common_name;
451  if (filter.GetString("ISSUER.CN", &common_name) &&
452      (cert.issuer().common_name == common_name)) {
453    return true;
454  }
455  return false;
456}
457
458// Fills |map| with the per-script font prefs under path |map_name|.
459void FillFontFamilyMap(const PrefService* prefs,
460                       const char* map_name,
461                       webkit_glue::ScriptFontFamilyMap* map) {
462  for (size_t i = 0; i < prefs::kWebKitScriptsForFontFamilyMapsLength; ++i) {
463    const char* script = prefs::kWebKitScriptsForFontFamilyMaps[i];
464    std::string pref_name = base::StringPrintf("%s.%s", map_name, script);
465    std::string font_family = prefs->GetString(pref_name.c_str());
466    if (!font_family.empty())
467      (*map)[script] = UTF8ToUTF16(font_family);
468  }
469}
470
471#if defined(OS_POSIX) && !defined(OS_MACOSX)
472int GetCrashSignalFD(const CommandLine& command_line) {
473  if (command_line.HasSwitch(switches::kExtensionProcess)) {
474    ExtensionCrashHandlerHostLinux* crash_handler =
475        ExtensionCrashHandlerHostLinux::GetInstance();
476    return crash_handler->GetDeathSignalSocket();
477  }
478
479  std::string process_type =
480      command_line.GetSwitchValueASCII(switches::kProcessType);
481
482  if (process_type == switches::kRendererProcess)
483    return RendererCrashHandlerHostLinux::GetInstance()->GetDeathSignalSocket();
484
485  if (process_type == switches::kPluginProcess)
486    return PluginCrashHandlerHostLinux::GetInstance()->GetDeathSignalSocket();
487
488  if (process_type == switches::kPpapiPluginProcess)
489    return PpapiCrashHandlerHostLinux::GetInstance()->GetDeathSignalSocket();
490
491  if (process_type == switches::kGpuProcess)
492    return GpuCrashHandlerHostLinux::GetInstance()->GetDeathSignalSocket();
493
494  return -1;
495}
496#endif  // defined(OS_POSIX) && !defined(OS_MACOSX)
497
498#if !defined(OS_CHROMEOS)
499GURL GetEffectiveURLForSignin(const GURL& url) {
500  CHECK(SigninManager::IsWebBasedSigninFlowURL(url));
501
502  GURL effective_url(SigninManager::kChromeSigninEffectiveSite);
503  // Copy the path because the argument to SetPathStr must outlive
504  // the Replacements object.
505  const std::string path_copy(url.path());
506  GURL::Replacements replacements;
507  replacements.SetPathStr(path_copy);
508  effective_url = effective_url.ReplaceComponents(replacements);
509  return effective_url;
510}
511#endif
512
513void SetApplicationLocaleOnIOThread(const std::string& locale) {
514  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
515  g_io_thread_application_locale.Get() = locale;
516}
517
518}  // namespace
519
520namespace chrome {
521
522ChromeContentBrowserClient::ChromeContentBrowserClient() {
523#if defined(ENABLE_PLUGINS)
524  for (size_t i = 0; i < arraysize(kPredefinedAllowedSocketOrigins); ++i)
525    allowed_socket_origins_.insert(kPredefinedAllowedSocketOrigins[i]);
526#endif
527
528  permissions_policy_delegate_.reset(
529      new extensions::BrowserPermissionsPolicyDelegate());
530}
531
532ChromeContentBrowserClient::~ChromeContentBrowserClient() {
533}
534
535// static
536void ChromeContentBrowserClient::RegisterProfilePrefs(
537    user_prefs::PrefRegistrySyncable* registry) {
538  registry->RegisterBooleanPref(
539      prefs::kDisable3DAPIs,
540      false,
541      user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
542  registry->RegisterBooleanPref(
543      prefs::kEnableHyperlinkAuditing,
544      true,
545      user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
546  registry->RegisterBooleanPref(
547      prefs::kEnableMemoryInfo,
548      false,
549      user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
550}
551
552// static
553void ChromeContentBrowserClient::SetApplicationLocale(
554    const std::string& locale) {
555  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
556
557  // This object is guaranteed to outlive all threads so we don't have to
558  // worry about the lack of refcounting and can just post as Unretained.
559  //
560  // The common case is that this function is called early in Chrome startup
561  // before any threads are created (it will also be called later if the user
562  // changes the pref). In this case, there will be no threads created and
563  // posting will fail. When there are no threads, we can just set the string
564  // without worrying about threadsafety.
565  if (!BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
566          base::Bind(&SetApplicationLocaleOnIOThread, locale))) {
567    g_io_thread_application_locale.Get() = locale;
568  }
569}
570
571content::BrowserMainParts* ChromeContentBrowserClient::CreateBrowserMainParts(
572    const content::MainFunctionParams& parameters) {
573  ChromeBrowserMainParts* main_parts;
574  // Construct the Main browser parts based on the OS type.
575#if defined(OS_WIN)
576  main_parts = new ChromeBrowserMainPartsWin(parameters);
577#elif defined(OS_MACOSX)
578  main_parts = new ChromeBrowserMainPartsMac(parameters);
579#elif defined(OS_CHROMEOS)
580  main_parts = new chromeos::ChromeBrowserMainPartsChromeos(parameters);
581#elif defined(OS_LINUX)
582  main_parts = new ChromeBrowserMainPartsLinux(parameters);
583#elif defined(OS_ANDROID)
584  main_parts = new ChromeBrowserMainPartsAndroid(parameters);
585#elif defined(OS_POSIX)
586  main_parts = new ChromeBrowserMainPartsPosix(parameters);
587#else
588  NOTREACHED();
589  main_parts = new ChromeBrowserMainParts(parameters);
590#endif
591
592  chrome::AddProfilesExtraParts(main_parts);
593
594  // Construct additional browser parts. Stages are called in the order in
595  // which they are added.
596#if defined(TOOLKIT_GTK)
597  main_parts->AddParts(new ChromeBrowserMainExtraPartsGtk());
598#endif
599
600#if defined(TOOLKIT_VIEWS)
601  main_parts->AddParts(new ChromeBrowserMainExtraPartsViews());
602#endif
603
604#if defined(USE_ASH)
605  main_parts->AddParts(new ChromeBrowserMainExtraPartsAsh());
606#endif
607
608#if defined(USE_AURA)
609  main_parts->AddParts(new ChromeBrowserMainExtraPartsAura());
610#endif
611
612#if defined(USE_X11)
613  main_parts->AddParts(new ChromeBrowserMainExtraPartsX11());
614#endif
615
616  chrome::AddMetricsExtraParts(main_parts);
617
618  return main_parts;
619}
620
621std::string ChromeContentBrowserClient::GetStoragePartitionIdForSite(
622    content::BrowserContext* browser_context,
623    const GURL& site) {
624  std::string partition_id;
625
626  // The partition ID for webview guest processes is the string value of its
627  // SiteInstance URL - "chrome-guest://app_id/persist?partition".
628  if (site.SchemeIs(chrome::kGuestScheme))
629    partition_id = site.spec();
630
631  DCHECK(IsValidStoragePartitionId(browser_context, partition_id));
632  return partition_id;
633}
634
635bool ChromeContentBrowserClient::IsValidStoragePartitionId(
636    content::BrowserContext* browser_context,
637    const std::string& partition_id) {
638  // The default ID is empty and is always valid.
639  if (partition_id.empty())
640    return true;
641
642  return GURL(partition_id).is_valid();
643}
644
645void ChromeContentBrowserClient::GetStoragePartitionConfigForSite(
646    content::BrowserContext* browser_context,
647    const GURL& site,
648    bool can_be_default,
649    std::string* partition_domain,
650    std::string* partition_name,
651    bool* in_memory) {
652  // Default to the browser-wide storage partition and override based on |site|
653  // below.
654  partition_domain->clear();
655  partition_name->clear();
656  *in_memory = false;
657
658  // For the webview tag, we create special guest processes, which host the
659  // tag content separately from the main application that embeds the tag.
660  // A webview tag can specify both the partition name and whether the storage
661  // for that partition should be persisted. Each tag gets a SiteInstance with
662  // a specially formatted URL, based on the application it is hosted by and
663  // the partition requested by it. The format for that URL is:
664  // chrome-guest://partition_domain/persist?partition_name
665  if (site.SchemeIs(chrome::kGuestScheme)) {
666    // Since guest URLs are only used for packaged apps, there must be an app
667    // id in the URL.
668    CHECK(site.has_host());
669    *partition_domain = site.host();
670    // Since persistence is optional, the path must either be empty or the
671    // literal string.
672    *in_memory = (site.path() != "/persist");
673    // The partition name is user supplied value, which we have encoded when the
674    // URL was created, so it needs to be decoded.
675    *partition_name = net::UnescapeURLComponent(site.query(),
676                                                net::UnescapeRule::NORMAL);
677  } else if (site.SchemeIs(extensions::kExtensionScheme)) {
678    // If |can_be_default| is false, the caller is stating that the |site|
679    // should be parsed as if it had isolated storage. In particular it is
680    // important to NOT check ExtensionService for the is_storage_isolated()
681    // attribute because this code path is run during Extension uninstall
682    // to do cleanup after the Extension has already been unloaded from the
683    // ExtensionService.
684    bool is_isolated = !can_be_default;
685    if (can_be_default) {
686      const Extension* extension = NULL;
687      Profile* profile = Profile::FromBrowserContext(browser_context);
688      ExtensionService* extension_service =
689          extensions::ExtensionSystem::Get(profile)->extension_service();
690      if (extension_service) {
691        extension =
692            extension_service->extensions()->GetExtensionOrAppByURL(site);
693        if (extension &&
694            extensions::AppIsolationInfo::HasIsolatedStorage(extension)) {
695          is_isolated = true;
696        }
697      }
698    }
699
700    if (is_isolated) {
701      CHECK(site.has_host());
702      // For extensions with isolated storage, the the host of the |site| is
703      // the |partition_domain|. The |in_memory| and |partition_name| are only
704      // used in guest schemes so they are cleared here.
705      *partition_domain = site.host();
706      *in_memory = false;
707      partition_name->clear();
708    }
709  }
710
711  // Assert that if |can_be_default| is false, the code above must have found a
712  // non-default partition.  If this fails, the caller has a serious logic
713  // error about which StoragePartition they expect to be in and it is not
714  // safe to continue.
715  CHECK(can_be_default || !partition_domain->empty());
716}
717
718content::WebContentsViewDelegate*
719    ChromeContentBrowserClient::GetWebContentsViewDelegate(
720        content::WebContents* web_contents) {
721  return chrome::CreateWebContentsViewDelegate(web_contents);
722}
723
724// Check if the extension activity log is enabled for the profile.
725static bool IsExtensionActivityLogEnabledForProfile(Profile* profile) {
726  // crbug.com/247908 - This should be IsLogEnabled except for an issue
727  // in chrome_frame_net_tests
728  return extensions::ActivityLog::IsLogEnabledOnAnyProfile();
729}
730
731void ChromeContentBrowserClient::GuestWebContentsCreated(
732    WebContents* guest_web_contents,
733    WebContents* opener_web_contents,
734    content::BrowserPluginGuestDelegate** guest_delegate,
735    scoped_ptr<base::DictionaryValue> extra_params) {
736  if (opener_web_contents) {
737    GuestView* guest = GuestView::FromWebContents(opener_web_contents);
738    if (!guest) {
739      NOTREACHED();
740      return;
741    }
742
743    switch (guest->GetViewType()) {
744      case GuestView::WEBVIEW: {
745        *guest_delegate = new WebViewGuest(guest_web_contents);
746        break;
747      }
748      case GuestView::ADVIEW: {
749        *guest_delegate = new AdViewGuest(guest_web_contents);
750        break;
751      }
752      default:
753        NOTREACHED();
754        break;
755    }
756    return;
757  }
758
759  if (!extra_params) {
760    NOTREACHED();
761    return;
762  }
763  std::string api_type;
764  extra_params->GetString(guestview::kAttributeApi, &api_type);
765
766  if (api_type == "adview") {
767    *guest_delegate  = new AdViewGuest(guest_web_contents);
768  } else if (api_type == "webview") {
769    *guest_delegate = new WebViewGuest(guest_web_contents);
770  } else {
771    NOTREACHED();
772  }
773}
774
775void ChromeContentBrowserClient::GuestWebContentsAttached(
776    WebContents* guest_web_contents,
777    WebContents* embedder_web_contents,
778    int browser_plugin_instance_id,
779    const base::DictionaryValue& extra_params) {
780  Profile* profile = Profile::FromBrowserContext(
781      embedder_web_contents->GetBrowserContext());
782  ExtensionService* service =
783      extensions::ExtensionSystem::Get(profile)->extension_service();
784  if (!service) {
785    NOTREACHED();
786    return;
787  }
788  const GURL& url = embedder_web_contents->GetSiteInstance()->GetSiteURL();
789  const Extension* extension =
790      service->extensions()->GetExtensionOrAppByURL(url);
791  if (!extension) {
792    NOTREACHED();
793    return;
794  }
795
796  GuestView* guest = GuestView::FromWebContents(guest_web_contents);
797  if (!guest) {
798    NOTREACHED();
799    return;
800  }
801  guest->Attach(embedder_web_contents,
802                extension->id(),
803                browser_plugin_instance_id,
804                extra_params);
805}
806
807void ChromeContentBrowserClient::RenderProcessHostCreated(
808    content::RenderProcessHost* host) {
809  int id = host->GetID();
810  Profile* profile = Profile::FromBrowserContext(host->GetBrowserContext());
811  net::URLRequestContextGetter* context =
812      profile->GetRequestContextForRenderProcess(id);
813
814  host->GetChannel()->AddFilter(new ChromeRenderMessageFilter(
815      id, profile, context));
816#if defined(ENABLE_PLUGINS)
817  host->GetChannel()->AddFilter(new PluginInfoMessageFilter(id, profile));
818#endif
819#if defined(ENABLE_PRINTING)
820  host->GetChannel()->AddFilter(new PrintingMessageFilter(id, profile));
821#endif
822  host->GetChannel()->AddFilter(
823      new SearchProviderInstallStateMessageFilter(id, profile));
824  host->GetChannel()->AddFilter(new SpellCheckMessageFilter(id));
825#if defined(OS_MACOSX)
826  host->GetChannel()->AddFilter(new SpellCheckMessageFilterMac(id));
827#endif
828  host->GetChannel()->AddFilter(new ChromeNetBenchmarkingMessageFilter(
829      id, profile, context));
830  host->GetChannel()->AddFilter(
831      new prerender::PrerenderMessageFilter(id, profile));
832  host->GetChannel()->AddFilter(new ValidationMessageMessageFilter(id));
833  host->GetChannel()->AddFilter(new TtsMessageFilter(id, profile));
834#if defined(ENABLE_WEBRTC)
835  host->GetChannel()->AddFilter(new WebRtcLoggingHandlerHost());
836#endif
837#if !defined(DISABLE_NACL)
838  ExtensionInfoMap* extension_info_map =
839      extensions::ExtensionSystem::Get(profile)->info_map();
840  host->GetChannel()->AddFilter(new NaClHostMessageFilter(
841      id, profile->IsOffTheRecord(),
842      profile->GetPath(), extension_info_map,
843      context));
844#endif
845
846  host->Send(new ChromeViewMsg_SetIsIncognitoProcess(
847      profile->IsOffTheRecord()));
848
849  host->Send(new ChromeViewMsg_SetExtensionActivityLogEnabled(
850      IsExtensionActivityLogEnabledForProfile(profile)));
851
852  SendExtensionWebRequestStatusToHost(host);
853
854  RendererContentSettingRules rules;
855  GetRendererContentSettingRules(profile->GetHostContentSettingsMap(), &rules);
856  host->Send(new ChromeViewMsg_SetContentSettingRules(rules));
857}
858
859GURL ChromeContentBrowserClient::GetPossiblyPrivilegedURL(
860    content::BrowserContext* browser_context,
861    const GURL& url,
862    bool is_renderer_initiated,
863    content::SiteInstance* current_instance) {
864  Profile* profile = Profile::FromBrowserContext(browser_context);
865  if (!profile)
866    return url;
867
868  // Only return the privileged instant URL if we are entering from a browser-
869  // initiated navigation or if we are already in the instant process.
870  bool is_instant_process = false;
871  int process_id = current_instance->GetProcess()->GetID();
872  InstantService* instant_service =
873      InstantServiceFactory::GetForProfile(profile);
874  if (instant_service)
875    is_instant_process = instant_service->IsInstantProcess(process_id);
876
877  DCHECK_EQ(is_instant_process,
878            chrome::IsPrivilegedURLForInstant(current_instance->GetSiteURL()));
879  if (!is_renderer_initiated || is_instant_process) {
880    // If the input |url| should be assigned to the Instant renderer, make its
881    // privileged URL distinct from other URLs on the search provider's domain.
882    if (chrome::ShouldAssignURLToInstantRenderer(url, profile))
883      return chrome::GetPrivilegedURLForInstant(url, profile);
884  }
885
886  return url;
887}
888
889GURL ChromeContentBrowserClient::GetEffectiveURL(
890    content::BrowserContext* browser_context, const GURL& url) {
891  Profile* profile = Profile::FromBrowserContext(browser_context);
892  if (!profile)
893    return url;
894
895#if !defined(OS_CHROMEOS)
896  // If the input |url| should be assigned to the Signin renderer, make its
897  // effective URL distinct from other URLs on the signin service's domain.
898  // Note that the signin renderer will be allowed to sign the user in to
899  // Chrome.
900  if (SigninManager::IsWebBasedSigninFlowURL(url))
901    return GetEffectiveURLForSignin(url);
902#endif
903
904  // If the input |url| is part of an installed app, the effective URL is an
905  // extension URL with the ID of that extension as the host. This has the
906  // effect of grouping apps together in a common SiteInstance.
907  ExtensionService* extension_service =
908      extensions::ExtensionSystem::Get(profile)->extension_service();
909  if (!extension_service)
910    return url;
911
912  const Extension* extension = extension_service->extensions()->
913      GetHostedAppByURL(url);
914  if (!extension)
915    return url;
916
917  // Bookmark apps do not use the hosted app process model, and should be
918  // treated as normal URLs.
919  if (extension->from_bookmark())
920    return url;
921
922  // If the URL is part of an extension's web extent, convert it to an
923  // extension URL.
924  return extension->GetResourceURL(url.path());
925}
926
927bool ChromeContentBrowserClient::ShouldUseProcessPerSite(
928    content::BrowserContext* browser_context, const GURL& effective_url) {
929  // Non-extension, non-Instant URLs should generally use
930  // process-per-site-instance.  Because we expect to use the effective URL,
931  // URLs for hosted apps (apart from bookmark apps) should have an extension
932  // scheme by now.
933
934  Profile* profile = Profile::FromBrowserContext(browser_context);
935  if (!profile)
936    return false;
937
938  if (chrome::ShouldUseProcessPerSiteForInstantURL(effective_url, profile))
939    return true;
940
941#if !defined(OS_CHROMEOS)
942  if (SigninManager::IsWebBasedSigninFlowURL(effective_url))
943    return true;
944#endif
945
946  if (!effective_url.SchemeIs(extensions::kExtensionScheme))
947    return false;
948
949  ExtensionService* extension_service =
950      extensions::ExtensionSystem::Get(profile)->extension_service();
951  if (!extension_service)
952    return false;
953
954  const Extension* extension =
955      extension_service->extensions()->GetExtensionOrAppByURL(effective_url);
956  if (!extension)
957    return false;
958
959  // If the URL is part of a hosted app that does not have the background
960  // permission, or that does not allow JavaScript access to the background
961  // page, we want to give each instance its own process to improve
962  // responsiveness.
963  if (extension->GetType() == Manifest::TYPE_HOSTED_APP) {
964    if (!extension->HasAPIPermission(APIPermission::kBackground) ||
965        !extensions::BackgroundInfo::AllowJSAccess(extension)) {
966      return false;
967    }
968  }
969
970  // Hosted apps that have script access to their background page must use
971  // process per site, since all instances can make synchronous calls to the
972  // background window.  Other extensions should use process per site as well.
973  return true;
974}
975
976// These are treated as WebUI schemes but do not get WebUI bindings.
977void ChromeContentBrowserClient::GetAdditionalWebUISchemes(
978    std::vector<std::string>* additional_schemes) {
979  additional_schemes->push_back(chrome::kChromeSearchScheme);
980}
981
982net::URLRequestContextGetter*
983ChromeContentBrowserClient::CreateRequestContext(
984    content::BrowserContext* browser_context,
985    content::ProtocolHandlerMap* protocol_handlers) {
986  Profile* profile = Profile::FromBrowserContext(browser_context);
987  return profile->CreateRequestContext(protocol_handlers);
988}
989
990net::URLRequestContextGetter*
991ChromeContentBrowserClient::CreateRequestContextForStoragePartition(
992    content::BrowserContext* browser_context,
993    const base::FilePath& partition_path,
994    bool in_memory,
995    content::ProtocolHandlerMap* protocol_handlers) {
996  Profile* profile = Profile::FromBrowserContext(browser_context);
997  return profile->CreateRequestContextForStoragePartition(
998      partition_path, in_memory, protocol_handlers);
999}
1000
1001bool ChromeContentBrowserClient::IsHandledURL(const GURL& url) {
1002  return ProfileIOData::IsHandledURL(url);
1003}
1004
1005bool ChromeContentBrowserClient::CanCommitURL(
1006    content::RenderProcessHost* process_host,
1007    const GURL& url) {
1008  // We need to let most extension URLs commit in any process, since this can
1009  // be allowed due to web_accessible_resources.  Most hosted app URLs may also
1010  // load in any process (e.g., in an iframe).  However, the Chrome Web Store
1011  // cannot be loaded in iframes and should never be requested outside its
1012  // process.
1013  Profile* profile =
1014      Profile::FromBrowserContext(process_host->GetBrowserContext());
1015  ExtensionService* service =
1016      extensions::ExtensionSystem::Get(profile)->extension_service();
1017  if (!service)
1018    return true;
1019  const Extension* new_extension =
1020      service->extensions()->GetExtensionOrAppByURL(url);
1021  if (new_extension &&
1022      new_extension->is_hosted_app() &&
1023      new_extension->id() == extension_misc::kWebStoreAppId &&
1024      !service->process_map()->Contains(new_extension->id(),
1025                                        process_host->GetID())) {
1026    return false;
1027  }
1028
1029  return true;
1030}
1031
1032bool ChromeContentBrowserClient::IsSuitableHost(
1033    content::RenderProcessHost* process_host,
1034    const GURL& site_url) {
1035  Profile* profile =
1036      Profile::FromBrowserContext(process_host->GetBrowserContext());
1037  // This may be NULL during tests. In that case, just assume any site can
1038  // share any host.
1039  if (!profile)
1040    return true;
1041
1042  // Instant URLs should only be in the instant process and instant process
1043  // should only have Instant URLs.
1044  InstantService* instant_service =
1045      InstantServiceFactory::GetForProfile(profile);
1046  if (instant_service) {
1047    bool is_instant_process = instant_service->IsInstantProcess(
1048        process_host->GetID());
1049    bool should_be_in_instant_process =
1050        chrome::ShouldAssignURLToInstantRenderer(site_url, profile);
1051    if (is_instant_process || should_be_in_instant_process)
1052      return is_instant_process && should_be_in_instant_process;
1053  }
1054
1055#if !defined(OS_CHROMEOS)
1056  SigninManager* signin_manager = SigninManagerFactory::GetForProfile(profile);
1057  if (signin_manager && signin_manager->IsSigninProcess(process_host->GetID()))
1058    return SigninManager::IsWebBasedSigninFlowURL(site_url);
1059#endif
1060
1061  ExtensionService* service =
1062      extensions::ExtensionSystem::Get(profile)->extension_service();
1063  extensions::ProcessMap* process_map = service->process_map();
1064
1065  // Don't allow the Task Manager to share a process with anything else.
1066  // Otherwise it can affect the renderers it is observing.
1067  // Note: we could create another RenderProcessHostPrivilege bucket for
1068  // this to allow multiple chrome://tasks instances to share, but that's
1069  // a very unlikely case without serious consequences.
1070  if (site_url.GetOrigin() == GURL(chrome::kChromeUITaskManagerURL).GetOrigin())
1071    return false;
1072
1073  // These may be NULL during tests. In that case, just assume any site can
1074  // share any host.
1075  if (!service || !process_map)
1076    return true;
1077
1078  // Otherwise, just make sure the process privilege matches the privilege
1079  // required by the site.
1080  RenderProcessHostPrivilege privilege_required =
1081      GetPrivilegeRequiredByUrl(site_url, service);
1082  return GetProcessPrivilege(process_host, process_map, service) ==
1083      privilege_required;
1084}
1085
1086// This function is trying to limit the amount of processes used by extensions
1087// with background pages. It uses a globally set percentage of processes to
1088// run such extensions and if the limit is exceeded, it returns true, to
1089// indicate to the content module to group extensions together.
1090bool ChromeContentBrowserClient::ShouldTryToUseExistingProcessHost(
1091    content::BrowserContext* browser_context, const GURL& url) {
1092  // It has to be a valid URL for us to check for an extension.
1093  if (!url.is_valid())
1094    return false;
1095
1096  Profile* profile = Profile::FromBrowserContext(browser_context);
1097  ExtensionService* service = !profile ? NULL :
1098      extensions::ExtensionSystem::Get(profile)->extension_service();
1099  if (!service)
1100    return false;
1101
1102  // We have to have a valid extension with background page to proceed.
1103  const Extension* extension =
1104      service->extensions()->GetExtensionOrAppByURL(url);
1105  if (!extension)
1106    return false;
1107  if (!extensions::BackgroundInfo::HasBackgroundPage(extension))
1108    return false;
1109
1110  std::set<int> process_ids;
1111  size_t max_process_count =
1112      content::RenderProcessHost::GetMaxRendererProcessCount();
1113
1114  // Go through all profiles to ensure we have total count of extension
1115  // processes containing background pages, otherwise one profile can
1116  // starve the other.
1117  std::vector<Profile*> profiles = g_browser_process->profile_manager()->
1118      GetLoadedProfiles();
1119  for (size_t i = 0; i < profiles.size(); ++i) {
1120    ExtensionProcessManager* epm =
1121        extensions::ExtensionSystem::Get(profiles[i])->process_manager();
1122    for (ExtensionProcessManager::const_iterator iter =
1123             epm->background_hosts().begin();
1124         iter != epm->background_hosts().end(); ++iter) {
1125      const extensions::ExtensionHost* host = *iter;
1126      process_ids.insert(host->render_process_host()->GetID());
1127    }
1128  }
1129
1130  if (process_ids.size() >
1131      (max_process_count * chrome::kMaxShareOfExtensionProcesses)) {
1132    return true;
1133  }
1134
1135  return false;
1136}
1137
1138void ChromeContentBrowserClient::SiteInstanceGotProcess(
1139    SiteInstance* site_instance) {
1140  CHECK(site_instance->HasProcess());
1141
1142  Profile* profile = Profile::FromBrowserContext(
1143      site_instance->GetBrowserContext());
1144  if (!profile)
1145    return;
1146
1147  // Remember the ID of the Instant process to signal the renderer process
1148  // on startup in |AppendExtraCommandLineSwitches| below.
1149  if (chrome::ShouldAssignURLToInstantRenderer(
1150          site_instance->GetSiteURL(), profile)) {
1151    InstantService* instant_service =
1152        InstantServiceFactory::GetForProfile(profile);
1153    if (instant_service)
1154      instant_service->AddInstantProcess(site_instance->GetProcess()->GetID());
1155  }
1156
1157#if !defined(OS_CHROMEOS)
1158  // We only expect there to be one signin process as we use process-per-site
1159  // for signin URLs. The signin process will be cleared from SigninManager
1160  // when the renderer is destroyed.
1161  if (SigninManager::IsWebBasedSigninFlowURL(site_instance->GetSiteURL())) {
1162    SigninManager* signin_manager =
1163        SigninManagerFactory::GetForProfile(profile);
1164    if (signin_manager)
1165      signin_manager->SetSigninProcess(site_instance->GetProcess()->GetID());
1166    BrowserThread::PostTask(
1167        BrowserThread::IO, FROM_HERE,
1168        base::Bind(&ExtensionInfoMap::SetSigninProcess,
1169                   extensions::ExtensionSystem::Get(profile)->info_map(),
1170                   site_instance->GetProcess()->GetID()));
1171  }
1172#endif
1173
1174  ExtensionService* service =
1175      extensions::ExtensionSystem::Get(profile)->extension_service();
1176  if (!service)
1177    return;
1178
1179  const Extension* extension = service->extensions()->GetExtensionOrAppByURL(
1180      site_instance->GetSiteURL());
1181  if (!extension)
1182    return;
1183
1184  service->process_map()->Insert(extension->id(),
1185                                 site_instance->GetProcess()->GetID(),
1186                                 site_instance->GetId());
1187  BrowserThread::PostTask(
1188      BrowserThread::IO, FROM_HERE,
1189      base::Bind(&ExtensionInfoMap::RegisterExtensionProcess,
1190                 extensions::ExtensionSystem::Get(profile)->info_map(),
1191                 extension->id(),
1192                 site_instance->GetProcess()->GetID(),
1193                 site_instance->GetId()));
1194}
1195
1196void ChromeContentBrowserClient::SiteInstanceDeleting(
1197    SiteInstance* site_instance) {
1198  if (!site_instance->HasProcess())
1199    return;
1200
1201  Profile* profile = Profile::FromBrowserContext(
1202      site_instance->GetBrowserContext());
1203  ExtensionService* service =
1204      extensions::ExtensionSystem::Get(profile)->extension_service();
1205  if (!service)
1206    return;
1207
1208  const Extension* extension = service->extensions()->GetExtensionOrAppByURL(
1209      site_instance->GetSiteURL());
1210  if (!extension)
1211    return;
1212
1213  service->process_map()->Remove(extension->id(),
1214                                 site_instance->GetProcess()->GetID(),
1215                                 site_instance->GetId());
1216  BrowserThread::PostTask(
1217      BrowserThread::IO, FROM_HERE,
1218      base::Bind(&ExtensionInfoMap::UnregisterExtensionProcess,
1219                 extensions::ExtensionSystem::Get(profile)->info_map(),
1220                 extension->id(),
1221                 site_instance->GetProcess()->GetID(),
1222                 site_instance->GetId()));
1223}
1224
1225bool ChromeContentBrowserClient::ShouldSwapProcessesForNavigation(
1226    SiteInstance* site_instance,
1227    const GURL& current_url,
1228    const GURL& new_url) {
1229  if (current_url.is_empty()) {
1230    // Always choose a new process when navigating to extension URLs. The
1231    // process grouping logic will combine all of a given extension's pages
1232    // into the same process.
1233    if (new_url.SchemeIs(extensions::kExtensionScheme))
1234      return true;
1235
1236    return false;
1237  }
1238
1239  // Also, we must switch if one is an extension and the other is not the exact
1240  // same extension.
1241  if (current_url.SchemeIs(extensions::kExtensionScheme) ||
1242      new_url.SchemeIs(extensions::kExtensionScheme)) {
1243    if (current_url.GetOrigin() != new_url.GetOrigin())
1244      return true;
1245  }
1246
1247  // The checks below only matter if we can retrieve which extensions are
1248  // installed.
1249  Profile* profile =
1250      Profile::FromBrowserContext(site_instance->GetBrowserContext());
1251  ExtensionService* service =
1252      extensions::ExtensionSystem::Get(profile)->extension_service();
1253  if (!service)
1254    return false;
1255
1256  // We must swap if the URL is for an extension and we are not using an
1257  // extension process.
1258  const Extension* new_extension =
1259      service->extensions()->GetExtensionOrAppByURL(new_url);
1260  // Ignore all hosted apps except the Chrome Web Store, since they do not
1261  // require their own BrowsingInstance (e.g., postMessage is ok).
1262  if (new_extension &&
1263      new_extension->is_hosted_app() &&
1264      new_extension->id() != extension_misc::kWebStoreAppId)
1265    new_extension = NULL;
1266  if (new_extension &&
1267      site_instance->HasProcess() &&
1268      !service->process_map()->Contains(new_extension->id(),
1269                                        site_instance->GetProcess()->GetID()))
1270    return true;
1271
1272  return false;
1273}
1274
1275bool ChromeContentBrowserClient::ShouldSwapProcessesForRedirect(
1276    content::ResourceContext* resource_context, const GURL& current_url,
1277    const GURL& new_url) {
1278  ProfileIOData* io_data = ProfileIOData::FromResourceContext(resource_context);
1279  return extensions::CrossesExtensionProcessBoundary(
1280      io_data->GetExtensionInfoMap()->extensions(),
1281      current_url, new_url, false);
1282}
1283
1284bool ChromeContentBrowserClient::ShouldAssignSiteForURL(const GURL& url) {
1285  return !url.SchemeIs(chrome::kChromeNativeScheme);
1286}
1287
1288std::string ChromeContentBrowserClient::GetCanonicalEncodingNameByAliasName(
1289    const std::string& alias_name) {
1290  return CharacterEncoding::GetCanonicalEncodingNameByAliasName(alias_name);
1291}
1292
1293void ChromeContentBrowserClient::AppendExtraCommandLineSwitches(
1294    CommandLine* command_line, int child_process_id) {
1295#if defined(OS_MACOSX)
1296  if (IsCrashReporterEnabled()) {
1297    command_line->AppendSwitchASCII(switches::kEnableCrashReporter,
1298                                    child_process_logging::GetClientId());
1299  }
1300#elif defined(OS_POSIX)
1301  if (IsCrashReporterEnabled()) {
1302    command_line->AppendSwitchASCII(switches::kEnableCrashReporter,
1303        child_process_logging::GetClientId() + "," + base::GetLinuxDistro());
1304  }
1305
1306#endif  // OS_MACOSX
1307
1308  if (logging::DialogsAreSuppressed())
1309    command_line->AppendSwitch(switches::kNoErrorDialogs);
1310
1311  std::string process_type =
1312      command_line->GetSwitchValueASCII(switches::kProcessType);
1313  const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
1314
1315  if (browser_command_line.HasSwitch(switches::kChromeFrame))
1316    command_line->AppendSwitch(switches::kChromeFrame);
1317
1318  if (process_type == switches::kRendererProcess) {
1319    base::FilePath user_data_dir =
1320        browser_command_line.GetSwitchValuePath(switches::kUserDataDir);
1321    if (!user_data_dir.empty())
1322      command_line->AppendSwitchPath(switches::kUserDataDir, user_data_dir);
1323#if defined(OS_CHROMEOS)
1324    const std::string& login_profile =
1325        browser_command_line.GetSwitchValueASCII(
1326            chromeos::switches::kLoginProfile);
1327    if (!login_profile.empty())
1328      command_line->AppendSwitchASCII(
1329          chromeos::switches::kLoginProfile, login_profile);
1330#endif
1331
1332    content::RenderProcessHost* process =
1333        content::RenderProcessHost::FromID(child_process_id);
1334    if (process) {
1335      Profile* profile = Profile::FromBrowserContext(
1336          process->GetBrowserContext());
1337      ExtensionService* extension_service =
1338          extensions::ExtensionSystem::Get(profile)->extension_service();
1339      if (extension_service) {
1340        extensions::ProcessMap* process_map = extension_service->process_map();
1341        if (process_map && process_map->Contains(process->GetID()))
1342          command_line->AppendSwitch(switches::kExtensionProcess);
1343      }
1344
1345      PrefService* prefs = profile->GetPrefs();
1346      // Currently this pref is only registered if applied via a policy.
1347      if (prefs->HasPrefPath(prefs::kDisable3DAPIs) &&
1348          prefs->GetBoolean(prefs::kDisable3DAPIs)) {
1349        // Turn this policy into a command line switch.
1350        command_line->AppendSwitch(switches::kDisable3DAPIs);
1351      }
1352
1353      // Disable client-side phishing detection in the renderer if it is
1354      // disabled in the Profile preferences or the browser process.
1355      if (!prefs->GetBoolean(prefs::kSafeBrowsingEnabled) ||
1356          !g_browser_process->safe_browsing_detection_service()) {
1357        command_line->AppendSwitch(
1358            switches::kDisableClientSidePhishingDetection);
1359      }
1360
1361      if (!prefs->GetBoolean(prefs::kPrintPreviewDisabled))
1362        command_line->AppendSwitch(switches::kRendererPrintPreview);
1363
1364      InstantService* instant_service =
1365          InstantServiceFactory::GetForProfile(profile);
1366      if (instant_service &&
1367          instant_service->IsInstantProcess(process->GetID()))
1368        command_line->AppendSwitch(switches::kInstantProcess);
1369
1370#if !defined(OS_CHROMEOS)
1371      SigninManager* signin_manager =
1372          SigninManagerFactory::GetForProfile(profile);
1373      if (signin_manager && signin_manager->IsSigninProcess(process->GetID()))
1374        command_line->AppendSwitch(switches::kSigninProcess);
1375#endif
1376    }
1377
1378    if (content::IsThreadedCompositingEnabled())
1379      command_line->AppendSwitch(switches::kEnableThreadedCompositing);
1380
1381    if (message_center::IsRichNotificationEnabled())
1382      command_line->AppendSwitch(switches::kDisableHTMLNotifications);
1383
1384    // Please keep this in alphabetical order.
1385    static const char* const kSwitchNames[] = {
1386      autofill::switches::kDisableInteractiveAutocomplete,
1387      autofill::switches::kEnableExperimentalFormFilling,
1388      autofill::switches::kEnableInteractiveAutocomplete,
1389      extensions::switches::kAllowLegacyExtensionManifests,
1390      extensions::switches::kAllowScriptingGallery,
1391      extensions::switches::kExtensionsOnChromeURLs,
1392      switches::kAllowHTTPBackgroundPage,
1393      // TODO(victorhsieh): remove the following flag once we move PPAPI FileIO
1394      // to browser.
1395      switches::kAllowNaClFileHandleAPI,
1396      switches::kAppsCheckoutURL,
1397      switches::kAppsGalleryURL,
1398      switches::kCloudPrintServiceURL,
1399      switches::kDebugPrint,
1400      switches::kDisableBundledPpapiFlash,
1401      switches::kDisableExtensionsResourceWhitelist,
1402      switches::kDisableScriptedPrintThrottling,
1403      switches::kEnableAdview,
1404      switches::kEnableAdviewSrcAttribute,
1405      switches::kEnableAppWindowControls,
1406      switches::kEnableBenchmarking,
1407      switches::kEnableExperimentalExtensionApis,
1408      switches::kEnableIPCFuzzing,
1409      switches::kEnableNaCl,
1410      switches::kEnableNetBenchmarking,
1411      switches::kEnablePasswordGeneration,
1412      switches::kEnablePnacl,
1413      switches::kEnableWatchdog,
1414      switches::kMemoryProfiling,
1415      switches::kMessageLoopHistogrammer,
1416      switches::kNoJsRandomness,
1417      switches::kPlaybackMode,
1418      switches::kPpapiFlashArgs,
1419      switches::kPpapiFlashInProcess,
1420      switches::kPpapiFlashPath,
1421      switches::kPpapiFlashVersion,
1422      switches::kProfilingAtStart,
1423      switches::kProfilingFile,
1424      switches::kProfilingFlush,
1425      switches::kRecordMode,
1426      switches::kSilentDumpOnDCHECK,
1427      switches::kSpdyProxyAuthOrigin,
1428      switches::kWhitelistedExtensionID,
1429    };
1430
1431    command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1432                                   arraysize(kSwitchNames));
1433  } else if (process_type == switches::kUtilityProcess) {
1434    static const char* const kSwitchNames[] = {
1435      extensions::switches::kExtensionsOnChromeURLs,
1436      switches::kAllowHTTPBackgroundPage,
1437      switches::kEnableExperimentalExtensionApis,
1438      switches::kWhitelistedExtensionID,
1439    };
1440
1441    command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1442                                   arraysize(kSwitchNames));
1443  } else if (process_type == switches::kPluginProcess) {
1444    static const char* const kSwitchNames[] = {
1445#if defined(OS_CHROMEOS)
1446      chromeos::switches::kLoginProfile,
1447#endif
1448      switches::kMemoryProfiling,
1449      switches::kSilentDumpOnDCHECK,
1450      switches::kUserDataDir,
1451    };
1452
1453    command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1454                                   arraysize(kSwitchNames));
1455  } else if (process_type == switches::kZygoteProcess) {
1456    static const char* const kSwitchNames[] = {
1457      switches::kUserDataDir,  // Make logs go to the right file.
1458      // Load (in-process) Pepper plugins in-process in the zygote pre-sandbox.
1459      switches::kDisableBundledPpapiFlash,
1460      switches::kPpapiFlashInProcess,
1461      switches::kPpapiFlashPath,
1462      switches::kPpapiFlashVersion,
1463    };
1464
1465    command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1466                                   arraysize(kSwitchNames));
1467  } else if (process_type == switches::kGpuProcess) {
1468    base::FilePath user_data_dir =
1469        browser_command_line.GetSwitchValuePath(switches::kUserDataDir);
1470    if (!user_data_dir.empty())
1471      command_line->AppendSwitchPath(switches::kUserDataDir, user_data_dir);
1472    // If --ignore-gpu-blacklist is passed in, don't send in crash reports
1473    // because GPU is expected to be unreliable.
1474    if (browser_command_line.HasSwitch(switches::kIgnoreGpuBlacklist) &&
1475        !command_line->HasSwitch(switches::kDisableBreakpad))
1476      command_line->AppendSwitch(switches::kDisableBreakpad);
1477  }
1478
1479  // The command line switch kEnableBenchmarking needs to be specified along
1480  // with the kEnableStatsTable switch to ensure that the stats table global
1481  // is initialized correctly.
1482  if (command_line->HasSwitch(switches::kEnableBenchmarking))
1483    DCHECK(command_line->HasSwitch(switches::kEnableStatsTable));
1484}
1485
1486std::string ChromeContentBrowserClient::GetApplicationLocale() {
1487  if (BrowserThread::CurrentlyOn(BrowserThread::IO))
1488    return g_io_thread_application_locale.Get();
1489  return g_browser_process->GetApplicationLocale();
1490}
1491
1492std::string ChromeContentBrowserClient::GetAcceptLangs(
1493    content::BrowserContext* context) {
1494  Profile* profile = Profile::FromBrowserContext(context);
1495  return profile->GetPrefs()->GetString(prefs::kAcceptLanguages);
1496}
1497
1498gfx::ImageSkia* ChromeContentBrowserClient::GetDefaultFavicon() {
1499  ResourceBundle& rb = ResourceBundle::GetSharedInstance();
1500  return rb.GetImageSkiaNamed(IDR_DEFAULT_FAVICON);
1501}
1502
1503bool ChromeContentBrowserClient::AllowAppCache(
1504    const GURL& manifest_url,
1505    const GURL& first_party,
1506    content::ResourceContext* context) {
1507  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1508  ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1509  return io_data->GetCookieSettings()->
1510      IsSettingCookieAllowed(manifest_url, first_party);
1511}
1512
1513bool ChromeContentBrowserClient::AllowGetCookie(
1514    const GURL& url,
1515    const GURL& first_party,
1516    const net::CookieList& cookie_list,
1517    content::ResourceContext* context,
1518    int render_process_id,
1519    int render_view_id) {
1520  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1521  ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1522  bool allow = io_data->GetCookieSettings()->
1523      IsReadingCookieAllowed(url, first_party);
1524
1525  BrowserThread::PostTask(
1526      BrowserThread::UI, FROM_HERE,
1527      base::Bind(&TabSpecificContentSettings::CookiesRead, render_process_id,
1528                 render_view_id, url, first_party, cookie_list, !allow));
1529  return allow;
1530}
1531
1532bool ChromeContentBrowserClient::AllowSetCookie(
1533    const GURL& url,
1534    const GURL& first_party,
1535    const std::string& cookie_line,
1536    content::ResourceContext* context,
1537    int render_process_id,
1538    int render_view_id,
1539    net::CookieOptions* options) {
1540  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1541  ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1542  CookieSettings* cookie_settings = io_data->GetCookieSettings();
1543  bool allow = cookie_settings->IsSettingCookieAllowed(url, first_party);
1544
1545  BrowserThread::PostTask(
1546      BrowserThread::UI, FROM_HERE,
1547      base::Bind(&TabSpecificContentSettings::CookieChanged, render_process_id,
1548                 render_view_id, url, first_party, cookie_line, *options,
1549                 !allow));
1550  return allow;
1551}
1552
1553bool ChromeContentBrowserClient::AllowSaveLocalState(
1554    content::ResourceContext* context) {
1555  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1556  ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1557  CookieSettings* cookie_settings = io_data->GetCookieSettings();
1558  ContentSetting setting = cookie_settings->GetDefaultCookieSetting(NULL);
1559
1560  // TODO(bauerb): Should we also disallow local state if the default is BLOCK?
1561  // Could we even support per-origin settings?
1562  return setting != CONTENT_SETTING_SESSION_ONLY;
1563}
1564
1565bool ChromeContentBrowserClient::AllowWorkerDatabase(
1566    const GURL& url,
1567    const string16& name,
1568    const string16& display_name,
1569    unsigned long estimated_size,
1570    content::ResourceContext* context,
1571    const std::vector<std::pair<int, int> >& render_views) {
1572  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1573  ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1574  CookieSettings* cookie_settings = io_data->GetCookieSettings();
1575  bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1576
1577  // Record access to database for potential display in UI.
1578  std::vector<std::pair<int, int> >::const_iterator i;
1579  for (i = render_views.begin(); i != render_views.end(); ++i) {
1580    BrowserThread::PostTask(
1581        BrowserThread::UI, FROM_HERE,
1582        base::Bind(&TabSpecificContentSettings::WebDatabaseAccessed,
1583                   i->first, i->second, url, name, display_name, !allow));
1584  }
1585
1586  return allow;
1587}
1588
1589bool ChromeContentBrowserClient::AllowWorkerFileSystem(
1590    const GURL& url,
1591    content::ResourceContext* context,
1592    const std::vector<std::pair<int, int> >& render_views) {
1593  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1594  ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1595  CookieSettings* cookie_settings = io_data->GetCookieSettings();
1596  bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1597
1598  // Record access to file system for potential display in UI.
1599  std::vector<std::pair<int, int> >::const_iterator i;
1600  for (i = render_views.begin(); i != render_views.end(); ++i) {
1601    BrowserThread::PostTask(
1602        BrowserThread::UI, FROM_HERE,
1603        base::Bind(&TabSpecificContentSettings::FileSystemAccessed,
1604                   i->first, i->second, url, !allow));
1605  }
1606
1607  return allow;
1608}
1609
1610bool ChromeContentBrowserClient::AllowWorkerIndexedDB(
1611    const GURL& url,
1612    const string16& name,
1613    content::ResourceContext* context,
1614    const std::vector<std::pair<int, int> >& render_views) {
1615  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1616  ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1617  CookieSettings* cookie_settings = io_data->GetCookieSettings();
1618  bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1619
1620  // Record access to IndexedDB for potential display in UI.
1621  std::vector<std::pair<int, int> >::const_iterator i;
1622  for (i = render_views.begin(); i != render_views.end(); ++i) {
1623    BrowserThread::PostTask(
1624        BrowserThread::UI, FROM_HERE,
1625        base::Bind(&TabSpecificContentSettings::IndexedDBAccessed,
1626                   i->first, i->second, url, name, !allow));
1627  }
1628
1629  return allow;
1630}
1631
1632net::URLRequestContext*
1633ChromeContentBrowserClient::OverrideRequestContextForURL(
1634    const GURL& url, content::ResourceContext* context) {
1635  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1636  if (url.SchemeIs(extensions::kExtensionScheme)) {
1637    ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1638    return io_data->extensions_request_context();
1639  }
1640
1641  return NULL;
1642}
1643
1644QuotaPermissionContext*
1645ChromeContentBrowserClient::CreateQuotaPermissionContext() {
1646  return new ChromeQuotaPermissionContext();
1647}
1648
1649void ChromeContentBrowserClient::AllowCertificateError(
1650    int render_process_id,
1651    int render_view_id,
1652    int cert_error,
1653    const net::SSLInfo& ssl_info,
1654    const GURL& request_url,
1655    ResourceType::Type resource_type,
1656    bool overridable,
1657    bool strict_enforcement,
1658    const base::Callback<void(bool)>& callback,
1659    content::CertificateRequestResultType* result) {
1660  if (resource_type != ResourceType::MAIN_FRAME) {
1661    // A sub-resource has a certificate error.  The user doesn't really
1662    // have a context for making the right decision, so block the
1663    // request hard, without an info bar to allow showing the insecure
1664    // content.
1665    *result = content::CERTIFICATE_REQUEST_RESULT_TYPE_DENY;
1666    return;
1667  }
1668
1669  // If the tab is being prerendered, cancel the prerender and the request.
1670  WebContents* tab = tab_util::GetWebContentsByID(
1671      render_process_id, render_view_id);
1672  if (!tab) {
1673    NOTREACHED();
1674    return;
1675  }
1676  prerender::PrerenderManager* prerender_manager =
1677      prerender::PrerenderManagerFactory::GetForProfile(
1678          Profile::FromBrowserContext(tab->GetBrowserContext()));
1679  if (prerender_manager && prerender_manager->IsWebContentsPrerendering(tab,
1680                                                                        NULL)) {
1681    if (prerender_manager->prerender_tracker()->TryCancel(
1682            render_process_id, render_view_id,
1683            prerender::FINAL_STATUS_SSL_ERROR)) {
1684      *result = content::CERTIFICATE_REQUEST_RESULT_TYPE_CANCEL;
1685      return;
1686    }
1687  }
1688
1689#if defined(ENABLE_CAPTIVE_PORTAL_DETECTION)
1690  captive_portal::CaptivePortalTabHelper* captive_portal_tab_helper =
1691      captive_portal::CaptivePortalTabHelper::FromWebContents(tab);
1692  if (captive_portal_tab_helper)
1693    captive_portal_tab_helper->OnSSLCertError(ssl_info);
1694#endif
1695
1696  // Otherwise, display an SSL blocking page.
1697  new SSLBlockingPage(tab, cert_error, ssl_info, request_url, overridable,
1698                      strict_enforcement, callback);
1699}
1700
1701void ChromeContentBrowserClient::SelectClientCertificate(
1702    int render_process_id,
1703    int render_view_id,
1704    const net::HttpNetworkSession* network_session,
1705    net::SSLCertRequestInfo* cert_request_info,
1706    const base::Callback<void(net::X509Certificate*)>& callback) {
1707  WebContents* tab = tab_util::GetWebContentsByID(
1708      render_process_id, render_view_id);
1709  if (!tab) {
1710    NOTREACHED();
1711    return;
1712  }
1713
1714  GURL requesting_url("https://" + cert_request_info->host_and_port);
1715  DCHECK(requesting_url.is_valid()) << "Invalid URL string: https://"
1716                                    << cert_request_info->host_and_port;
1717
1718  Profile* profile = Profile::FromBrowserContext(tab->GetBrowserContext());
1719  scoped_ptr<Value> filter(
1720      profile->GetHostContentSettingsMap()->GetWebsiteSetting(
1721          requesting_url,
1722          requesting_url,
1723          CONTENT_SETTINGS_TYPE_AUTO_SELECT_CERTIFICATE,
1724          std::string(), NULL));
1725
1726  if (filter.get()) {
1727    // Try to automatically select a client certificate.
1728    if (filter->IsType(Value::TYPE_DICTIONARY)) {
1729      DictionaryValue* filter_dict =
1730          static_cast<DictionaryValue*>(filter.get());
1731
1732      const std::vector<scoped_refptr<net::X509Certificate> >&
1733          all_client_certs = cert_request_info->client_certs;
1734      for (size_t i = 0; i < all_client_certs.size(); ++i) {
1735        if (CertMatchesFilter(*all_client_certs[i].get(), *filter_dict)) {
1736          // Use the first certificate that is matched by the filter.
1737          callback.Run(all_client_certs[i].get());
1738          return;
1739        }
1740      }
1741    } else {
1742      NOTREACHED();
1743    }
1744  }
1745
1746  SSLTabHelper* ssl_tab_helper = SSLTabHelper::FromWebContents(tab);
1747  if (!ssl_tab_helper) {
1748    // If there is no SSLTabHelper for the given WebContents then we can't
1749    // show the user a dialog to select a client certificate. So we simply
1750    // proceed with no client certificate.
1751    callback.Run(NULL);
1752    return;
1753  }
1754  ssl_tab_helper->ShowClientCertificateRequestDialog(
1755      network_session, cert_request_info, callback);
1756}
1757
1758void ChromeContentBrowserClient::AddCertificate(
1759    net::URLRequest* request,
1760    net::CertificateMimeType cert_type,
1761    const void* cert_data,
1762    size_t cert_size,
1763    int render_process_id,
1764    int render_view_id) {
1765  chrome::SSLAddCertificate(request, cert_type, cert_data, cert_size,
1766      render_process_id, render_view_id);
1767}
1768
1769content::MediaObserver* ChromeContentBrowserClient::GetMediaObserver() {
1770  return MediaCaptureDevicesDispatcher::GetInstance();
1771}
1772
1773void ChromeContentBrowserClient::RequestDesktopNotificationPermission(
1774    const GURL& source_origin,
1775    int callback_context,
1776    int render_process_id,
1777    int render_view_id) {
1778#if defined(ENABLE_NOTIFICATIONS)
1779  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1780  WebContents* contents =
1781      tab_util::GetWebContentsByID(render_process_id, render_view_id);
1782  if (!contents) {
1783    NOTREACHED();
1784    return;
1785  }
1786
1787  // Skip showing the infobar if the request comes from an extension, and that
1788  // extension has the 'notify' permission. (If the extension does not have the
1789  // permission, the user will still be prompted.)
1790  Profile* profile = Profile::FromBrowserContext(contents->GetBrowserContext());
1791  ExtensionInfoMap* extension_info_map =
1792      extensions::ExtensionSystem::Get(profile)->info_map();
1793  DesktopNotificationService* notification_service =
1794      DesktopNotificationServiceFactory::GetForProfile(profile);
1795  const Extension* extension = NULL;
1796  if (extension_info_map) {
1797    ExtensionSet extensions;
1798    extension_info_map->GetExtensionsWithAPIPermissionForSecurityOrigin(
1799        source_origin, render_process_id,
1800        extensions::APIPermission::kNotification, &extensions);
1801    for (ExtensionSet::const_iterator iter = extensions.begin();
1802         iter != extensions.end(); ++iter) {
1803      if (notification_service->IsExtensionEnabled((*iter)->id())) {
1804        extension = iter->get();
1805        break;
1806      }
1807    }
1808  }
1809  RenderViewHost* rvh =
1810      RenderViewHost::FromID(render_process_id, render_view_id);
1811  if (IsExtensionWithPermissionOrSuggestInConsole(
1812      APIPermission::kNotification, extension, rvh)) {
1813    if (rvh)
1814      rvh->DesktopNotificationPermissionRequestDone(callback_context);
1815    return;
1816  }
1817
1818  notification_service->RequestPermission(source_origin, render_process_id,
1819      render_view_id, callback_context, contents);
1820#else
1821  NOTIMPLEMENTED();
1822#endif
1823}
1824
1825WebKit::WebNotificationPresenter::Permission
1826    ChromeContentBrowserClient::CheckDesktopNotificationPermission(
1827        const GURL& source_origin,
1828        content::ResourceContext* context,
1829        int render_process_id) {
1830#if defined(ENABLE_NOTIFICATIONS)
1831  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1832  // Sometimes a notification may be invoked during the shutdown.
1833  // See http://crbug.com/256638
1834  if (browser_shutdown::IsTryingToQuit())
1835    return WebKit::WebNotificationPresenter::PermissionNotAllowed;
1836
1837  ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1838
1839  DesktopNotificationService* notification_service =
1840      io_data->GetNotificationService();
1841  if (notification_service) {
1842    ExtensionInfoMap* extension_info_map = io_data->GetExtensionInfoMap();
1843    ExtensionSet extensions;
1844    extension_info_map->GetExtensionsWithAPIPermissionForSecurityOrigin(
1845        source_origin, render_process_id,
1846        extensions::APIPermission::kNotification, &extensions);
1847    for (ExtensionSet::const_iterator iter = extensions.begin();
1848         iter != extensions.end(); ++iter) {
1849      if (notification_service->IsExtensionEnabled((*iter)->id()))
1850        return WebKit::WebNotificationPresenter::PermissionAllowed;
1851    }
1852
1853    return notification_service->HasPermission(source_origin);
1854  }
1855
1856  return WebKit::WebNotificationPresenter::PermissionNotAllowed;
1857#else
1858  return WebKit::WebNotificationPresenter::PermissionAllowed;
1859#endif
1860}
1861
1862void ChromeContentBrowserClient::ShowDesktopNotification(
1863    const content::ShowDesktopNotificationHostMsgParams& params,
1864    int render_process_id,
1865    int render_view_id,
1866    bool worker) {
1867#if defined(ENABLE_NOTIFICATIONS)
1868  RenderViewHost* rvh = RenderViewHost::FromID(
1869      render_process_id, render_view_id);
1870  if (!rvh) {
1871    NOTREACHED();
1872    return;
1873  }
1874
1875  content::RenderProcessHost* process = rvh->GetProcess();
1876  Profile* profile = Profile::FromBrowserContext(process->GetBrowserContext());
1877  DesktopNotificationService* service =
1878      DesktopNotificationServiceFactory::GetForProfile(profile);
1879  service->ShowDesktopNotification(
1880    params, render_process_id, render_view_id,
1881    worker ? DesktopNotificationService::WorkerNotification :
1882        DesktopNotificationService::PageNotification);
1883#else
1884  NOTIMPLEMENTED();
1885#endif
1886}
1887
1888void ChromeContentBrowserClient::CancelDesktopNotification(
1889    int render_process_id,
1890    int render_view_id,
1891    int notification_id) {
1892#if defined(ENABLE_NOTIFICATIONS)
1893  RenderViewHost* rvh = RenderViewHost::FromID(
1894      render_process_id, render_view_id);
1895  if (!rvh) {
1896    NOTREACHED();
1897    return;
1898  }
1899
1900  content::RenderProcessHost* process = rvh->GetProcess();
1901  Profile* profile = Profile::FromBrowserContext(process->GetBrowserContext());
1902  DesktopNotificationService* service =
1903      DesktopNotificationServiceFactory::GetForProfile(profile);
1904  service->CancelDesktopNotification(
1905      render_process_id, render_view_id, notification_id);
1906#else
1907  NOTIMPLEMENTED();
1908#endif
1909}
1910
1911bool ChromeContentBrowserClient::CanCreateWindow(
1912    const GURL& opener_url,
1913    const GURL& source_origin,
1914    WindowContainerType container_type,
1915    content::ResourceContext* context,
1916    int render_process_id,
1917    bool* no_javascript_access) {
1918  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1919
1920  *no_javascript_access = false;
1921
1922  // If the opener is trying to create a background window but doesn't have
1923  // the appropriate permission, fail the attempt.
1924  if (container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {
1925    ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1926    ExtensionInfoMap* map = io_data->GetExtensionInfoMap();
1927
1928    if (!map->SecurityOriginHasAPIPermission(
1929            source_origin,
1930            render_process_id,
1931            APIPermission::kBackground)) {
1932      return false;
1933    }
1934
1935    // Note: this use of GetExtensionOrAppByURL is safe but imperfect.  It may
1936    // return a recently installed Extension even if this CanCreateWindow call
1937    // was made by an old copy of the page in a normal web process.  That's ok,
1938    // because the permission check above would have caused an early return
1939    // already. We must use the full URL to find hosted apps, though, and not
1940    // just the origin.
1941    const Extension* extension =
1942        map->extensions().GetExtensionOrAppByURL(opener_url);
1943    if (extension && !extensions::BackgroundInfo::AllowJSAccess(extension))
1944      *no_javascript_access = true;
1945  }
1946
1947  // No new browser window (popup or tab) in app mode.
1948  if (container_type == WINDOW_CONTAINER_TYPE_NORMAL &&
1949      chrome::IsRunningInForcedAppMode()) {
1950    return false;
1951  }
1952
1953  return true;
1954}
1955
1956std::string ChromeContentBrowserClient::GetWorkerProcessTitle(
1957    const GURL& url, content::ResourceContext* context) {
1958  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1959  // Check if it's an extension-created worker, in which case we want to use
1960  // the name of the extension.
1961  ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1962  const Extension* extension =
1963      io_data->GetExtensionInfoMap()->extensions().GetByID(url.host());
1964  return extension ? extension->name() : std::string();
1965}
1966
1967void ChromeContentBrowserClient::ResourceDispatcherHostCreated() {
1968  return g_browser_process->ResourceDispatcherHostCreated();
1969}
1970
1971// TODO(tommi): Rename from Get to Create.
1972content::SpeechRecognitionManagerDelegate*
1973    ChromeContentBrowserClient::GetSpeechRecognitionManagerDelegate() {
1974#if defined(ENABLE_INPUT_SPEECH)
1975  return new speech::ChromeSpeechRecognitionManagerDelegateBubbleUI();
1976#else
1977  // Platforms who don't implement x-webkit-speech (a.k.a INPUT_SPEECH) just
1978  // need the base delegate without the bubble UI.
1979  return new speech::ChromeSpeechRecognitionManagerDelegate();
1980#endif
1981}
1982
1983net::NetLog* ChromeContentBrowserClient::GetNetLog() {
1984  return g_browser_process->net_log();
1985}
1986
1987AccessTokenStore* ChromeContentBrowserClient::CreateAccessTokenStore() {
1988  return new ChromeAccessTokenStore();
1989}
1990
1991bool ChromeContentBrowserClient::IsFastShutdownPossible() {
1992  return true;
1993}
1994
1995void ChromeContentBrowserClient::OverrideWebkitPrefs(
1996    RenderViewHost* rvh, const GURL& url, WebPreferences* web_prefs) {
1997  Profile* profile = Profile::FromBrowserContext(
1998      rvh->GetProcess()->GetBrowserContext());
1999  PrefService* prefs = profile->GetPrefs();
2000
2001  FillFontFamilyMap(prefs, prefs::kWebKitStandardFontFamilyMap,
2002                    &web_prefs->standard_font_family_map);
2003  FillFontFamilyMap(prefs, prefs::kWebKitFixedFontFamilyMap,
2004                    &web_prefs->fixed_font_family_map);
2005  FillFontFamilyMap(prefs, prefs::kWebKitSerifFontFamilyMap,
2006                    &web_prefs->serif_font_family_map);
2007  FillFontFamilyMap(prefs, prefs::kWebKitSansSerifFontFamilyMap,
2008                    &web_prefs->sans_serif_font_family_map);
2009  FillFontFamilyMap(prefs, prefs::kWebKitCursiveFontFamilyMap,
2010                    &web_prefs->cursive_font_family_map);
2011  FillFontFamilyMap(prefs, prefs::kWebKitFantasyFontFamilyMap,
2012                    &web_prefs->fantasy_font_family_map);
2013  FillFontFamilyMap(prefs, prefs::kWebKitPictographFontFamilyMap,
2014                    &web_prefs->pictograph_font_family_map);
2015
2016  web_prefs->default_font_size =
2017      prefs->GetInteger(prefs::kWebKitDefaultFontSize);
2018  web_prefs->default_fixed_font_size =
2019      prefs->GetInteger(prefs::kWebKitDefaultFixedFontSize);
2020  web_prefs->minimum_font_size =
2021      prefs->GetInteger(prefs::kWebKitMinimumFontSize);
2022  web_prefs->minimum_logical_font_size =
2023      prefs->GetInteger(prefs::kWebKitMinimumLogicalFontSize);
2024
2025  web_prefs->default_encoding = prefs->GetString(prefs::kDefaultCharset);
2026
2027  web_prefs->javascript_can_open_windows_automatically =
2028      prefs->GetBoolean(prefs::kWebKitJavascriptCanOpenWindowsAutomatically);
2029  web_prefs->dom_paste_enabled =
2030      prefs->GetBoolean(prefs::kWebKitDomPasteEnabled);
2031  web_prefs->shrinks_standalone_images_to_fit =
2032      prefs->GetBoolean(prefs::kWebKitShrinksStandaloneImagesToFit);
2033  const DictionaryValue* inspector_settings =
2034      prefs->GetDictionary(prefs::kWebKitInspectorSettings);
2035  if (inspector_settings) {
2036    for (DictionaryValue::Iterator iter(*inspector_settings); !iter.IsAtEnd();
2037         iter.Advance()) {
2038      std::string value;
2039      if (iter.value().GetAsString(&value)) {
2040          web_prefs->inspector_settings.push_back(
2041              std::make_pair(iter.key(), value));
2042      }
2043    }
2044  }
2045  web_prefs->tabs_to_links = prefs->GetBoolean(prefs::kWebkitTabsToLinks);
2046
2047  if (!prefs->GetBoolean(prefs::kWebKitJavascriptEnabled))
2048    web_prefs->javascript_enabled = false;
2049  if (!prefs->GetBoolean(prefs::kWebKitWebSecurityEnabled))
2050    web_prefs->web_security_enabled = false;
2051  if (!prefs->GetBoolean(prefs::kWebKitPluginsEnabled))
2052    web_prefs->plugins_enabled = false;
2053  if (!prefs->GetBoolean(prefs::kWebKitJavaEnabled))
2054    web_prefs->java_enabled = false;
2055  web_prefs->loads_images_automatically =
2056      prefs->GetBoolean(prefs::kWebKitLoadsImagesAutomatically);
2057
2058  if (prefs->GetBoolean(prefs::kDisable3DAPIs))
2059    web_prefs->experimental_webgl_enabled = false;
2060
2061  web_prefs->memory_info_enabled =
2062      prefs->GetBoolean(prefs::kEnableMemoryInfo);
2063  web_prefs->allow_displaying_insecure_content =
2064      prefs->GetBoolean(prefs::kWebKitAllowDisplayingInsecureContent);
2065  web_prefs->allow_running_insecure_content =
2066      prefs->GetBoolean(prefs::kWebKitAllowRunningInsecureContent);
2067#if defined(OS_ANDROID)
2068  web_prefs->font_scale_factor =
2069      static_cast<float>(prefs->GetDouble(prefs::kWebKitFontScaleFactor));
2070  web_prefs->force_enable_zoom =
2071      prefs->GetBoolean(prefs::kWebKitForceEnableZoom);
2072#if defined(GOOGLE_TV)
2073  web_prefs->user_gesture_required_for_media_playback = false;
2074#endif
2075#endif
2076
2077#if defined(OS_ANDROID)
2078  web_prefs->password_echo_enabled =
2079      prefs->GetBoolean(prefs::kWebKitPasswordEchoEnabled);
2080#else
2081  web_prefs->password_echo_enabled = browser_defaults::kPasswordEchoEnabled;
2082#endif
2083
2084#if defined(OS_CHROMEOS)
2085  // Enable password echo during OOBE when keyboard driven flag is set.
2086  if (chromeos::UserManager::IsInitialized() &&
2087      !chromeos::UserManager::Get()->IsUserLoggedIn() &&
2088      !chromeos::StartupUtils::IsOobeCompleted()) {
2089    bool keyboard_driven_oobe = false;
2090    chromeos::system::StatisticsProvider::GetInstance()->GetMachineFlag(
2091        chromeos::system::kOemKeyboardDrivenOobeKey, &keyboard_driven_oobe);
2092    if (keyboard_driven_oobe)
2093       web_prefs->password_echo_enabled = true;
2094  }
2095#endif
2096
2097#if defined(OS_ANDROID)
2098  web_prefs->user_style_sheet_enabled = false;
2099#else
2100  // The user stylesheet watcher may not exist in a testing profile.
2101  UserStyleSheetWatcher* user_style_sheet_watcher =
2102      UserStyleSheetWatcherFactory::GetForProfile(profile).get();
2103  if (user_style_sheet_watcher) {
2104    web_prefs->user_style_sheet_enabled = true;
2105    web_prefs->user_style_sheet_location =
2106        user_style_sheet_watcher->user_style_sheet();
2107  } else {
2108    web_prefs->user_style_sheet_enabled = false;
2109  }
2110#endif
2111
2112  web_prefs->asynchronous_spell_checking_enabled = true;
2113  web_prefs->unified_textchecker_enabled = true;
2114
2115  web_prefs->uses_universal_detector =
2116      prefs->GetBoolean(prefs::kWebKitUsesUniversalDetector);
2117  web_prefs->text_areas_are_resizable =
2118      prefs->GetBoolean(prefs::kWebKitTextAreasAreResizable);
2119  web_prefs->hyperlink_auditing_enabled =
2120      prefs->GetBoolean(prefs::kEnableHyperlinkAuditing);
2121
2122  // Make sure we will set the default_encoding with canonical encoding name.
2123  web_prefs->default_encoding =
2124      CharacterEncoding::GetCanonicalEncodingNameByAliasName(
2125          web_prefs->default_encoding);
2126  if (web_prefs->default_encoding.empty()) {
2127    prefs->ClearPref(prefs::kDefaultCharset);
2128    web_prefs->default_encoding = prefs->GetString(prefs::kDefaultCharset);
2129  }
2130  DCHECK(!web_prefs->default_encoding.empty());
2131
2132  if (content::IsForceCompositingModeEnabled())
2133    web_prefs->force_compositing_mode = true;
2134
2135  WebContents* web_contents = WebContents::FromRenderViewHost(rvh);
2136  extensions::ViewType view_type = extensions::GetViewType(web_contents);
2137  ExtensionService* service =
2138      extensions::ExtensionSystem::Get(profile)->extension_service();
2139  if (service) {
2140    const GURL& url = rvh->GetSiteInstance()->GetSiteURL();
2141    const Extension* extension = service->extensions()->GetByID(url.host());
2142    // Ensure that we are only granting extension preferences to URLs with
2143    // the correct scheme. Without this check, chrome-guest:// schemes used by
2144    // webview tags as well as hosts that happen to match the id of an
2145    // installed extension would get the wrong preferences.
2146    if (url.SchemeIs(extensions::kExtensionScheme)) {
2147      extension_webkit_preferences::SetPreferences(
2148          extension, view_type, web_prefs);
2149    }
2150  }
2151
2152  if (view_type == extensions::VIEW_TYPE_NOTIFICATION) {
2153    web_prefs->allow_scripts_to_close_windows = true;
2154  } else if (view_type == extensions::VIEW_TYPE_BACKGROUND_CONTENTS) {
2155    // Disable all kinds of acceleration for background pages.
2156    // See http://crbug.com/96005 and http://crbug.com/96006
2157    web_prefs->force_compositing_mode = false;
2158    web_prefs->accelerated_compositing_enabled = false;
2159  }
2160
2161#if defined(FILE_MANAGER_EXTENSION)
2162  // Override the default of suppressing HW compositing for WebUI pages for the
2163  // file manager, which is implemented using WebUI but wants HW acceleration
2164  // for video decode & render.
2165  if (url.SchemeIs(extensions::kExtensionScheme) &&
2166      url.host() == kFileBrowserDomain) {
2167    web_prefs->accelerated_compositing_enabled = true;
2168    web_prefs->accelerated_2d_canvas_enabled = true;
2169  }
2170#endif
2171}
2172
2173void ChromeContentBrowserClient::UpdateInspectorSetting(
2174    RenderViewHost* rvh, const std::string& key, const std::string& value) {
2175  content::BrowserContext* browser_context =
2176      rvh->GetProcess()->GetBrowserContext();
2177  DictionaryPrefUpdate update(
2178      Profile::FromBrowserContext(browser_context)->GetPrefs(),
2179      prefs::kWebKitInspectorSettings);
2180  DictionaryValue* inspector_settings = update.Get();
2181  inspector_settings->SetWithoutPathExpansion(key,
2182                                              Value::CreateStringValue(value));
2183}
2184
2185void ChromeContentBrowserClient::BrowserURLHandlerCreated(
2186    BrowserURLHandler* handler) {
2187  // Add the default URL handlers.
2188  handler->AddHandlerPair(&ExtensionWebUI::HandleChromeURLOverride,
2189                          BrowserURLHandler::null_handler());
2190  handler->AddHandlerPair(BrowserURLHandler::null_handler(),
2191                          &ExtensionWebUI::HandleChromeURLOverrideReverse);
2192
2193  // about: handler. Must come before chrome: handler, since it will
2194  // rewrite about: urls to chrome: URLs and then expect chrome: to
2195  // actually handle them.
2196  handler->AddHandlerPair(&WillHandleBrowserAboutURL,
2197                          BrowserURLHandler::null_handler());
2198  // chrome: & friends.
2199  handler->AddHandlerPair(&HandleWebUI, &HandleWebUIReverse);
2200}
2201
2202void ChromeContentBrowserClient::ClearCache(RenderViewHost* rvh) {
2203  Profile* profile = Profile::FromBrowserContext(
2204      rvh->GetSiteInstance()->GetProcess()->GetBrowserContext());
2205  BrowsingDataRemover* remover =
2206      BrowsingDataRemover::CreateForUnboundedRange(profile);
2207  remover->Remove(BrowsingDataRemover::REMOVE_CACHE,
2208                  BrowsingDataHelper::UNPROTECTED_WEB);
2209  // BrowsingDataRemover takes care of deleting itself when done.
2210}
2211
2212void ChromeContentBrowserClient::ClearCookies(RenderViewHost* rvh) {
2213  Profile* profile = Profile::FromBrowserContext(
2214      rvh->GetSiteInstance()->GetProcess()->GetBrowserContext());
2215  BrowsingDataRemover* remover =
2216      BrowsingDataRemover::CreateForUnboundedRange(profile);
2217  int remove_mask = BrowsingDataRemover::REMOVE_SITE_DATA;
2218  remover->Remove(remove_mask, BrowsingDataHelper::UNPROTECTED_WEB);
2219  // BrowsingDataRemover takes care of deleting itself when done.
2220}
2221
2222base::FilePath ChromeContentBrowserClient::GetDefaultDownloadDirectory() {
2223  return download_util::GetDefaultDownloadDirectory();
2224}
2225
2226std::string ChromeContentBrowserClient::GetDefaultDownloadName() {
2227  return l10n_util::GetStringUTF8(IDS_DEFAULT_DOWNLOAD_FILENAME);
2228}
2229
2230void ChromeContentBrowserClient::DidCreatePpapiPlugin(
2231    content::BrowserPpapiHost* browser_host) {
2232#if defined(ENABLE_PLUGINS)
2233  browser_host->GetPpapiHost()->AddHostFactoryFilter(
2234      scoped_ptr<ppapi::host::HostFactory>(
2235          new ChromeBrowserPepperHostFactory(browser_host)));
2236#endif
2237}
2238
2239content::BrowserPpapiHost*
2240    ChromeContentBrowserClient::GetExternalBrowserPpapiHost(
2241        int plugin_process_id) {
2242  BrowserChildProcessHostIterator iter(PROCESS_TYPE_NACL_LOADER);
2243  while (!iter.Done()) {
2244    NaClProcessHost* host = static_cast<NaClProcessHost*>(iter.GetDelegate());
2245    if (host->process() &&
2246        host->process()->GetData().id == plugin_process_id) {
2247      // Found the plugin.
2248      return host->browser_ppapi_host();
2249    }
2250    ++iter;
2251  }
2252  return NULL;
2253}
2254
2255bool ChromeContentBrowserClient::SupportsBrowserPlugin(
2256    content::BrowserContext* browser_context, const GURL& site_url) {
2257  if (CommandLine::ForCurrentProcess()->HasSwitch(
2258          switches::kEnableBrowserPluginForAllViewTypes))
2259    return true;
2260
2261  Profile* profile = Profile::FromBrowserContext(browser_context);
2262  ExtensionService* service =
2263      extensions::ExtensionSystem::Get(profile)->extension_service();
2264  if (!service)
2265    return false;
2266
2267  const Extension* extension =
2268      service->extensions()->GetExtensionOrAppByURL(site_url);
2269  if (!extension)
2270    return false;
2271
2272  return extension->HasAPIPermission(APIPermission::kWebView) ||
2273         extension->HasAPIPermission(APIPermission::kAdView);
2274}
2275
2276bool ChromeContentBrowserClient::AllowPepperSocketAPI(
2277    content::BrowserContext* browser_context,
2278    const GURL& url,
2279    bool private_api,
2280    const content::SocketPermissionRequest& params) {
2281#if defined(ENABLE_PLUGINS)
2282  Profile* profile = Profile::FromBrowserContext(browser_context);
2283  const ExtensionSet* extension_set = NULL;
2284  if (profile) {
2285    extension_set = extensions::ExtensionSystem::Get(profile)->
2286        extension_service()->extensions();
2287  }
2288
2289  if (private_api) {
2290    // Access to private socket APIs is controlled by the whitelist.
2291    if (IsExtensionOrSharedModuleWhitelisted(url, extension_set,
2292                                             allowed_socket_origins_)) {
2293      return true;
2294    }
2295  } else {
2296    // Access to public socket APIs is controlled by extension permissions.
2297    if (url.is_valid() && url.SchemeIs(extensions::kExtensionScheme) &&
2298        extension_set) {
2299      const Extension* extension = extension_set->GetByID(url.host());
2300      if (extension) {
2301        extensions::SocketPermission::CheckParam check_params(
2302            params.type, params.host, params.port);
2303        if (extensions::PermissionsData::CheckAPIPermissionWithParam(
2304                extension, extensions::APIPermission::kSocket, &check_params)) {
2305          return true;
2306        }
2307      }
2308    }
2309  }
2310
2311  // Allow both public and private APIs if the command line says so.
2312  return IsHostAllowedByCommandLine(url, extension_set,
2313                                    switches::kAllowNaClSocketAPI);
2314#else
2315  return false;
2316#endif
2317}
2318
2319base::FilePath ChromeContentBrowserClient::GetHyphenDictionaryDirectory() {
2320  base::FilePath directory;
2321  PathService::Get(chrome::DIR_APP_DICTIONARIES, &directory);
2322  return directory.Append(FILE_PATH_LITERAL("Hyphen"));
2323}
2324
2325ui::SelectFilePolicy* ChromeContentBrowserClient::CreateSelectFilePolicy(
2326    WebContents* web_contents) {
2327  return new ChromeSelectFilePolicy(web_contents);
2328}
2329
2330void ChromeContentBrowserClient::GetAdditionalAllowedSchemesForFileSystem(
2331    std::vector<std::string>* additional_allowed_schemes) {
2332  ContentBrowserClient::GetAdditionalAllowedSchemesForFileSystem(
2333      additional_allowed_schemes);
2334  additional_allowed_schemes->push_back(kChromeUIScheme);
2335  additional_allowed_schemes->push_back(extensions::kExtensionScheme);
2336}
2337
2338void ChromeContentBrowserClient::GetAdditionalFileSystemBackends(
2339    content::BrowserContext* browser_context,
2340    const base::FilePath& storage_partition_path,
2341    ScopedVector<fileapi::FileSystemBackend>* additional_backends) {
2342#if !defined(OS_ANDROID)
2343  base::SequencedWorkerPool* pool = content::BrowserThread::GetBlockingPool();
2344  additional_backends->push_back(new MediaFileSystemBackend(
2345      storage_partition_path,
2346      pool->GetSequencedTaskRunner(pool->GetNamedSequenceToken(
2347          MediaFileSystemBackend::kMediaTaskRunnerName)).get()));
2348#endif
2349#if defined(OS_CHROMEOS)
2350  fileapi::ExternalMountPoints* external_mount_points =
2351      content::BrowserContext::GetMountPoints(browser_context);
2352  DCHECK(external_mount_points);
2353  chromeos::FileSystemBackend* backend =
2354      new chromeos::FileSystemBackend(
2355          new drive::FileSystemBackendDelegate(browser_context),
2356          browser_context->GetSpecialStoragePolicy(),
2357          external_mount_points,
2358          fileapi::ExternalMountPoints::GetSystemInstance());
2359  backend->AddSystemMountPoints();
2360  DCHECK(backend->CanHandleType(fileapi::kFileSystemTypeExternal));
2361  additional_backends->push_back(backend);
2362#endif
2363}
2364
2365#if defined(OS_POSIX) && !defined(OS_MACOSX)
2366void ChromeContentBrowserClient::GetAdditionalMappedFilesForChildProcess(
2367    const CommandLine& command_line,
2368    int child_process_id,
2369    std::vector<FileDescriptorInfo>* mappings) {
2370#if defined(OS_ANDROID)
2371  base::FilePath data_path;
2372  PathService::Get(ui::DIR_RESOURCE_PAKS_ANDROID, &data_path);
2373  DCHECK(!data_path.empty());
2374
2375  int flags = base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ;
2376  base::FilePath chrome_pak = data_path.AppendASCII("chrome.pak");
2377  base::PlatformFile f =
2378      base::CreatePlatformFile(chrome_pak, flags, NULL, NULL);
2379  DCHECK(f != base::kInvalidPlatformFileValue);
2380  mappings->push_back(FileDescriptorInfo(kAndroidChromePakDescriptor,
2381                                         FileDescriptor(f, true)));
2382
2383  base::FilePath chrome_resources_pak =
2384      data_path.AppendASCII("chrome_100_percent.pak");
2385  f = base::CreatePlatformFile(chrome_resources_pak, flags, NULL, NULL);
2386  DCHECK(f != base::kInvalidPlatformFileValue);
2387  mappings->push_back(FileDescriptorInfo(kAndroidChrome100PercentPakDescriptor,
2388                                         FileDescriptor(f, true)));
2389
2390  const std::string locale = GetApplicationLocale();
2391  base::FilePath locale_pak = ResourceBundle::GetSharedInstance().
2392      GetLocaleFilePath(locale, false);
2393  f = base::CreatePlatformFile(locale_pak, flags, NULL, NULL);
2394  DCHECK(f != base::kInvalidPlatformFileValue);
2395  mappings->push_back(FileDescriptorInfo(kAndroidLocalePakDescriptor,
2396                                         FileDescriptor(f, true)));
2397
2398  base::FilePath resources_pack_path;
2399  PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
2400  f = base::CreatePlatformFile(resources_pack_path, flags, NULL, NULL);
2401  DCHECK(f != base::kInvalidPlatformFileValue);
2402  mappings->push_back(FileDescriptorInfo(kAndroidUIResourcesPakDescriptor,
2403                                         FileDescriptor(f, true)));
2404
2405  if (IsCrashReporterEnabled()) {
2406    f = CrashDumpManager::GetInstance()->CreateMinidumpFile(child_process_id);
2407    if (f == base::kInvalidPlatformFileValue) {
2408      LOG(ERROR) << "Failed to create file for minidump, crash reporting will "
2409                 "be disabled for this process.";
2410    } else {
2411      mappings->push_back(FileDescriptorInfo(kAndroidMinidumpDescriptor,
2412                                             FileDescriptor(f, true)));
2413    }
2414  }
2415
2416#else
2417  int crash_signal_fd = GetCrashSignalFD(command_line);
2418  if (crash_signal_fd >= 0) {
2419    mappings->push_back(FileDescriptorInfo(kCrashDumpSignal,
2420                                           FileDescriptor(crash_signal_fd,
2421                                                          false)));
2422  }
2423#endif  // defined(OS_ANDROID)
2424}
2425#endif  // defined(OS_POSIX) && !defined(OS_MACOSX)
2426
2427#if defined(OS_WIN)
2428const wchar_t* ChromeContentBrowserClient::GetResourceDllName() {
2429  return chrome::kBrowserResourcesDll;
2430}
2431
2432void ChromeContentBrowserClient::PreSpawnRenderer(
2433    sandbox::TargetPolicy* policy,
2434    bool* success) {
2435  // This code is duplicated in nacl_exe_win_64.cc.
2436  // Allow the server side of a pipe restricted to the "chrome.nacl."
2437  // namespace so that it cannot impersonate other system or other chrome
2438  // service pipes.
2439  sandbox::ResultCode result = policy->AddRule(
2440      sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
2441      sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
2442      L"\\\\.\\pipe\\chrome.nacl.*");
2443  if (result != sandbox::SBOX_ALL_OK) {
2444    *success = false;
2445    return;
2446  }
2447
2448  // Renderers need to send named pipe handles and shared memory
2449  // segment handles to NaCl loader processes.
2450  result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
2451                           sandbox::TargetPolicy::HANDLES_DUP_ANY,
2452                           L"File");
2453  if (result != sandbox::SBOX_ALL_OK) {
2454    *success = false;
2455    return;
2456  }
2457}
2458#endif
2459
2460#if defined(USE_NSS)
2461crypto::CryptoModuleBlockingPasswordDelegate*
2462    ChromeContentBrowserClient::GetCryptoPasswordDelegate(
2463        const GURL& url) {
2464  return chrome::NewCryptoModuleBlockingDialogDelegate(
2465      chrome::kCryptoModulePasswordKeygen, url.host());
2466}
2467#endif
2468
2469}  // namespace chrome
2470