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