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