Popular sites on the NTP: re-download popular suggestions once per Chrome run
[chromium-blink-merge.git] / chrome / browser / chrome_content_browser_client.cc
blobbbe1c07e906f1ad7b85ba0f40cef7f22d033dab2
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.
5 #include "chrome/browser/chrome_content_browser_client.h"
7 #include <map>
8 #include <set>
9 #include <utility>
10 #include <vector>
12 #include "base/bind.h"
13 #include "base/bind_helpers.h"
14 #include "base/command_line.h"
15 #include "base/files/scoped_file.h"
16 #include "base/lazy_instance.h"
17 #include "base/path_service.h"
18 #include "base/prefs/pref_service.h"
19 #include "base/prefs/scoped_user_pref_update.h"
20 #include "base/strings/string_number_conversions.h"
21 #include "base/strings/string_util.h"
22 #include "base/strings/stringprintf.h"
23 #include "base/strings/utf_string_conversions.h"
24 #include "base/thread_task_runner_handle.h"
25 #include "base/threading/sequenced_worker_pool.h"
26 #include "chrome/browser/after_startup_task_utils.h"
27 #include "chrome/browser/apps/app_url_redirector.h"
28 #include "chrome/browser/browser_about_handler.h"
29 #include "chrome/browser/browser_process.h"
30 #include "chrome/browser/browser_shutdown.h"
31 #include "chrome/browser/browsing_data/browsing_data_helper.h"
32 #include "chrome/browser/browsing_data/browsing_data_remover.h"
33 #include "chrome/browser/character_encoding.h"
34 #include "chrome/browser/chrome_content_browser_client_parts.h"
35 #include "chrome/browser/chrome_net_benchmarking_message_filter.h"
36 #include "chrome/browser/chrome_quota_permission_context.h"
37 #include "chrome/browser/content_settings/cookie_settings_factory.h"
38 #include "chrome/browser/content_settings/host_content_settings_map_factory.h"
39 #include "chrome/browser/content_settings/tab_specific_content_settings.h"
40 #include "chrome/browser/defaults.h"
41 #include "chrome/browser/devtools/chrome_devtools_manager_delegate.h"
42 #include "chrome/browser/download/download_prefs.h"
43 #include "chrome/browser/font_family_cache.h"
44 #include "chrome/browser/geolocation/chrome_access_token_store.h"
45 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
46 #include "chrome/browser/metrics/chrome_browser_main_extra_parts_metrics.h"
47 #include "chrome/browser/nacl_host/nacl_browser_delegate_impl.h"
48 #include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings.h"
49 #include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings_factory.h"
50 #include "chrome/browser/notifications/platform_notification_service_impl.h"
51 #include "chrome/browser/platform_util.h"
52 #include "chrome/browser/prerender/prerender_final_status.h"
53 #include "chrome/browser/prerender/prerender_manager.h"
54 #include "chrome/browser/prerender/prerender_manager_factory.h"
55 #include "chrome/browser/prerender/prerender_message_filter.h"
56 #include "chrome/browser/printing/printing_message_filter.h"
57 #include "chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.h"
58 #include "chrome/browser/profiles/profile.h"
59 #include "chrome/browser/profiles/profile_io_data.h"
60 #include "chrome/browser/renderer_host/chrome_render_message_filter.h"
61 #include "chrome/browser/renderer_host/pepper/chrome_browser_pepper_host_factory.h"
62 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
63 #include "chrome/browser/safe_browsing/ui_manager.h"
64 #include "chrome/browser/search/instant_service.h"
65 #include "chrome/browser/search/instant_service_factory.h"
66 #include "chrome/browser/search/search.h"
67 #include "chrome/browser/search_engines/search_provider_install_state_message_filter.h"
68 #include "chrome/browser/speech/chrome_speech_recognition_manager_delegate.h"
69 #include "chrome/browser/speech/tts_controller.h"
70 #include "chrome/browser/speech/tts_message_filter.h"
71 #include "chrome/browser/ssl/ssl_add_certificate.h"
72 #include "chrome/browser/ssl/ssl_blocking_page.h"
73 #include "chrome/browser/ssl/ssl_cert_reporter.h"
74 #include "chrome/browser/ssl/ssl_client_certificate_selector.h"
75 #include "chrome/browser/ssl/ssl_error_handler.h"
76 #include "chrome/browser/sync_file_system/local/sync_file_system_backend.h"
77 #include "chrome/browser/tab_contents/tab_util.h"
78 #include "chrome/browser/tracing/chrome_tracing_delegate.h"
79 #include "chrome/browser/ui/blocked_content/blocked_window_params.h"
80 #include "chrome/browser/ui/blocked_content/popup_blocker_tab_helper.h"
81 #include "chrome/browser/ui/chrome_select_file_policy.h"
82 #include "chrome/browser/ui/sync/sync_promo_ui.h"
83 #include "chrome/browser/ui/tab_contents/chrome_web_contents_view_delegate.h"
84 #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
85 #include "chrome/common/channel_info.h"
86 #include "chrome/common/chrome_constants.h"
87 #include "chrome/common/chrome_paths.h"
88 #include "chrome/common/chrome_switches.h"
89 #include "chrome/common/env_vars.h"
90 #include "chrome/common/logging_chrome.h"
91 #include "chrome/common/pepper_permission_util.h"
92 #include "chrome/common/pref_names.h"
93 #include "chrome/common/render_messages.h"
94 #include "chrome/common/url_constants.h"
95 #include "chrome/grit/generated_resources.h"
96 #include "chrome/installer/util/google_update_settings.h"
97 #include "chromeos/chromeos_constants.h"
98 #include "components/cdm/browser/cdm_message_filter_android.h"
99 #include "components/cloud_devices/common/cloud_devices_switches.h"
100 #include "components/content_settings/core/browser/content_settings_utils.h"
101 #include "components/content_settings/core/browser/cookie_settings.h"
102 #include "components/content_settings/core/browser/host_content_settings_map.h"
103 #include "components/content_settings/core/common/content_settings.h"
104 #include "components/data_reduction_proxy/content/browser/data_reduction_proxy_message_filter.h"
105 #include "components/dom_distiller/core/url_constants.h"
106 #include "components/google/core/browser/google_util.h"
107 #include "components/metrics/client_info.h"
108 #include "components/net_log/chrome_net_log.h"
109 #include "components/pref_registry/pref_registry_syncable.h"
110 #include "components/rappor/rappor_utils.h"
111 #include "components/signin/core/common/profile_management_switches.h"
112 #include "components/translate/core/common/translate_switches.h"
113 #include "components/url_formatter/url_fixer.h"
114 #include "components/variations/variations_associated_data.h"
115 #include "components/version_info/version_info.h"
116 #include "content/public/browser/browser_child_process_host.h"
117 #include "content/public/browser/browser_main_parts.h"
118 #include "content/public/browser/browser_ppapi_host.h"
119 #include "content/public/browser/browser_thread.h"
120 #include "content/public/browser/browser_url_handler.h"
121 #include "content/public/browser/child_process_data.h"
122 #include "content/public/browser/child_process_security_policy.h"
123 #include "content/public/browser/client_certificate_delegate.h"
124 #include "content/public/browser/navigation_handle.h"
125 #include "content/public/browser/navigation_throttle.h"
126 #include "content/public/browser/render_frame_host.h"
127 #include "content/public/browser/render_process_host.h"
128 #include "content/public/browser/render_view_host.h"
129 #include "content/public/browser/resource_context.h"
130 #include "content/public/browser/site_instance.h"
131 #include "content/public/browser/web_contents.h"
132 #include "content/public/common/child_process_host.h"
133 #include "content/public/common/content_descriptors.h"
134 #include "content/public/common/sandbox_type.h"
135 #include "content/public/common/service_registry.h"
136 #include "content/public/common/url_utils.h"
137 #include "content/public/common/web_preferences.h"
138 #include "device/devices_app/public/cpp/constants.h"
139 #include "device/devices_app/public/cpp/devices_app_factory.h"
140 #include "gin/v8_initializer.h"
141 #include "mojo/application/public/cpp/application_delegate.h"
142 #include "net/base/mime_util.h"
143 #include "net/cookies/canonical_cookie.h"
144 #include "net/cookies/cookie_options.h"
145 #include "net/ssl/ssl_cert_request_info.h"
146 #include "ppapi/host/ppapi_host.h"
147 #include "storage/browser/fileapi/external_mount_points.h"
148 #include "ui/base/l10n/l10n_util.h"
149 #include "ui/base/resource/resource_bundle.h"
150 #include "ui/resources/grit/ui_resources.h"
152 #if defined(OS_WIN)
153 #include "base/win/windows_version.h"
154 #include "chrome/browser/chrome_browser_main_win.h"
155 #include "sandbox/win/src/sandbox_policy.h"
156 #elif defined(OS_MACOSX)
157 #include "chrome/browser/chrome_browser_main_mac.h"
158 #elif defined(OS_CHROMEOS)
159 #include "chrome/browser/chromeos/attestation/platform_verification_impl.h"
160 #include "chrome/browser/chromeos/chrome_browser_main_chromeos.h"
161 #include "chrome/browser/chromeos/drive/fileapi/file_system_backend_delegate.h"
162 #include "chrome/browser/chromeos/file_manager/app_id.h"
163 #include "chrome/browser/chromeos/file_system_provider/fileapi/backend_delegate.h"
164 #include "chrome/browser/chromeos/fileapi/file_system_backend.h"
165 #include "chrome/browser/chromeos/fileapi/mtp_file_system_backend_delegate.h"
166 #include "chrome/browser/chromeos/login/startup_utils.h"
167 #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
168 #include "chrome/browser/chromeos/system/input_device_settings.h"
169 #include "chromeos/chromeos_switches.h"
170 #include "components/user_manager/user_manager.h"
171 #elif defined(OS_LINUX)
172 #include "chrome/browser/chrome_browser_main_linux.h"
173 #elif defined(OS_ANDROID)
174 #include "chrome/browser/android/new_tab_page_url_handler.h"
175 #include "chrome/browser/android/webapps/single_tab_mode_tab_helper.h"
176 #include "chrome/browser/chrome_browser_main_android.h"
177 #include "chrome/common/descriptors_android.h"
178 #include "components/crash/content/browser/crash_dump_manager_android.h"
179 #include "components/navigation_interception/intercept_navigation_delegate.h"
180 #include "components/service_tab_launcher/browser/android/service_tab_launcher.h"
181 #include "ui/base/resource/resource_bundle_android.h"
182 #elif defined(OS_POSIX)
183 #include "chrome/browser/chrome_browser_main_posix.h"
184 #endif
186 #if defined(OS_POSIX) && !defined(OS_MACOSX)
187 #include "base/debug/leak_annotations.h"
188 #include "components/crash/content/app/breakpad_linux.h"
189 #include "components/crash/content/browser/crash_handler_host_linux.h"
190 #endif
192 #if defined(OS_ANDROID)
193 #include "ui/base/ui_base_paths.h"
194 #include "ui/gfx/android/device_display_info.h"
195 #endif
197 #if defined(TOOLKIT_VIEWS)
198 #include "chrome/browser/ui/views/chrome_browser_main_extra_parts_views.h"
199 #endif
201 #if defined(USE_ASH)
202 #include "chrome/browser/ui/views/ash/chrome_browser_main_extra_parts_ash.h"
203 #endif
205 #if defined(USE_AURA)
206 #include "chrome/browser/ui/aura/chrome_browser_main_extra_parts_aura.h"
207 #endif
209 #if defined(USE_X11)
210 #include "chrome/browser/chrome_browser_main_extra_parts_x11.h"
211 #endif
213 #if defined(ENABLE_CAPTIVE_PORTAL_DETECTION)
214 #include "chrome/browser/captive_portal/captive_portal_tab_helper.h"
215 #endif
217 #if !defined(DISABLE_NACL)
218 #include "components/nacl/browser/nacl_browser.h"
219 #include "components/nacl/browser/nacl_host_message_filter.h"
220 #include "components/nacl/browser/nacl_process_host.h"
221 #include "components/nacl/common/nacl_process_type.h"
222 #include "components/nacl/common/nacl_switches.h"
223 #endif
225 #if defined(ENABLE_EXTENSIONS)
226 #include "chrome/browser/accessibility/animation_policy_prefs.h"
227 #include "chrome/browser/extensions/chrome_content_browser_client_extensions_part.h"
228 #include "chrome/browser/media/cast_transport_host_filter.h"
229 #include "chrome/browser/speech/extension_api/tts_engine_extension_api.h"
230 #include "components/guest_view/browser/guest_view_base.h"
231 #include "components/guest_view/browser/guest_view_manager.h"
232 #include "extensions/browser/extension_registry.h"
233 #include "extensions/browser/extension_util.h"
234 #include "extensions/browser/guest_view/web_view/web_view_guest.h"
235 #include "extensions/browser/guest_view/web_view/web_view_permission_helper.h"
236 #include "extensions/browser/guest_view/web_view/web_view_renderer_state.h"
237 #include "extensions/common/constants.h"
238 #include "extensions/common/extension.h"
239 #include "extensions/common/extension_set.h"
240 #include "extensions/common/manifest_handlers/background_info.h"
241 #include "extensions/common/manifest_handlers/shared_module_info.h"
242 #include "extensions/common/permissions/permissions_data.h"
243 #include "extensions/common/permissions/socket_permission.h"
244 #include "extensions/common/switches.h"
245 #endif
247 #if defined(ENABLE_PLUGINS)
248 #include "chrome/browser/plugins/chrome_content_browser_client_plugins_part.h"
249 #endif
251 #if defined(ENABLE_SPELLCHECK)
252 #include "chrome/browser/spellchecker/spellcheck_message_filter.h"
253 #endif
255 #if defined(USE_BROWSER_SPELLCHECKER)
256 #include "chrome/browser/spellchecker/spellcheck_message_filter_platform.h"
257 #endif
259 #if defined(ENABLE_WEBRTC)
260 #include "chrome/browser/media/webrtc_logging_handler_host.h"
261 #endif
263 #if defined(ENABLE_MEDIA_ROUTER)
264 #include "chrome/browser/media/router/presentation_service_delegate_impl.h"
265 #endif
267 #if !defined(OS_ANDROID) && !defined(OS_IOS)
268 #include "chrome/browser/usb/web_usb_permission_provider.h"
269 #endif
271 using base::FileDescriptor;
272 using blink::WebWindowFeatures;
273 using content::AccessTokenStore;
274 using content::BrowserThread;
275 using content::BrowserURLHandler;
276 using content::ChildProcessSecurityPolicy;
277 using content::QuotaPermissionContext;
278 using content::RenderFrameHost;
279 using content::RenderViewHost;
280 using content::ResourceType;
281 using content::SiteInstance;
282 using content::WebContents;
283 using content::WebPreferences;
284 using message_center::NotifierId;
286 #if defined(OS_POSIX)
287 using content::FileDescriptorInfo;
288 #endif
290 #if defined(ENABLE_EXTENSIONS)
291 using extensions::APIPermission;
292 using extensions::ChromeContentBrowserClientExtensionsPart;
293 using extensions::Extension;
294 using extensions::InfoMap;
295 using extensions::Manifest;
296 #endif
298 #if defined(ENABLE_PLUGINS)
299 using plugins::ChromeContentBrowserClientPluginsPart;
300 #endif
302 namespace {
304 // Cached version of the locale so we can return the locale on the I/O
305 // thread.
306 base::LazyInstance<std::string> g_io_thread_application_locale;
308 #if defined(ENABLE_PLUGINS)
309 // TODO(teravest): Add renderer-side API-specific checking for these APIs so
310 // that blanket permission isn't granted to all dev channel APIs for these.
311 // http://crbug.com/386743
312 const char* const kPredefinedAllowedDevChannelOrigins[] = {
313 "6EAED1924DB611B6EEF2A664BD077BE7EAD33B8F", // see crbug.com/383937
314 "4EB74897CB187C7633357C2FE832E0AD6A44883A" // see crbug.com/383937
317 const char* const kPredefinedAllowedFileHandleOrigins[] = {
318 "6EAED1924DB611B6EEF2A664BD077BE7EAD33B8F", // see crbug.com/234789
319 "4EB74897CB187C7633357C2FE832E0AD6A44883A" // see crbug.com/234789
322 const char* const kPredefinedAllowedSocketOrigins[] = {
323 "okddffdblfhhnmhodogpojmfkjmhinfp", // Test SSH Client
324 "pnhechapfaindjhompbnflcldabbghjo", // HTerm App (SSH Client)
325 "bglhmjfplikpjnfoegeomebmfnkjomhe", // see crbug.com/122126
326 "gbchcmhmhahfdphkhkmpfmihenigjmpp", // Chrome Remote Desktop
327 "kgngmbheleoaphbjbaiobfdepmghbfah", // Pre-release Chrome Remote Desktop
328 "odkaodonbgfohohmklejpjiejmcipmib", // Dogfood Chrome Remote Desktop
329 "ojoimpklfciegopdfgeenehpalipignm", // Chromoting canary
330 "cbkkbcmdlboombapidmoeolnmdacpkch", // see crbug.com/129089
331 "hhnbmknkdabfoieppbbljkhkfjcmcbjh", // see crbug.com/134099
332 "mablfbjkhmhkmefkjjacnbaikjkipphg", // see crbug.com/134099
333 "pdeelgamlgannhelgoegilelnnojegoh", // see crbug.com/134099
334 "cabapfdbkniadpollkckdnedaanlciaj", // see crbug.com/134099
335 "mapljbgnjledlpdmlchihnmeclmefbba", // see crbug.com/134099
336 "ghbfeebgmiidnnmeobbbaiamklmpbpii", // see crbug.com/134099
337 "jdfhpkjeckflbbleddjlpimecpbjdeep", // see crbug.com/142514
338 "iabmpiboiopbgfabjmgeedhcmjenhbla", // see crbug.com/165080
339 "B7CF8A292249681AF81771650BA4CEEAF19A4560", // see crbug.com/165080
340 "7525AF4F66763A70A883C4700529F647B470E4D2", // see crbug.com/238084
341 "0B549507088E1564D672F7942EB87CA4DAD73972", // see crbug.com/238084
342 "864288364E239573E777D3E0E36864E590E95C74" // see crbug.com/238084
344 #endif
346 // Returns a copy of the given url with its host set to given host and path set
347 // to given path. Other parts of the url will be the same.
348 GURL ReplaceURLHostAndPath(const GURL& url,
349 const std::string& host,
350 const std::string& path) {
351 url::Replacements<char> replacements;
352 replacements.SetHost(host.c_str(), url::Component(0, host.length()));
353 replacements.SetPath(path.c_str(), url::Component(0, path.length()));
354 return url.ReplaceComponents(replacements);
357 // Maps "foo://bar/baz/" to "foo://chrome/bar/baz/".
358 GURL AddUberHost(const GURL& url) {
359 const std::string uber_host = chrome::kChromeUIUberHost;
360 const std::string new_path = url.host() + url.path();
362 return ReplaceURLHostAndPath(url, uber_host, new_path);
365 // If url->host() is "chrome" and url->path() has characters other than the
366 // first slash, changes the url from "foo://chrome/bar/" to "foo://bar/" and
367 // returns true. Otherwise returns false.
368 bool RemoveUberHost(GURL* url) {
369 if (url->host() != chrome::kChromeUIUberHost)
370 return false;
372 if (url->path().empty() || url->path() == "/")
373 return false;
375 const std::string old_path = url->path();
377 const std::string::size_type separator = old_path.find('/', 1);
378 std::string new_host;
379 std::string new_path;
380 if (separator == std::string::npos) {
381 new_host = old_path.substr(1);
382 } else {
383 new_host = old_path.substr(1, separator - 1);
384 new_path = old_path.substr(separator);
387 // Do not allow URLs with paths empty before the first slash since we can't
388 // have an empty host. (e.g "foo://chrome//")
389 if (new_host.empty())
390 return false;
392 *url = ReplaceURLHostAndPath(*url, new_host, new_path);
394 DCHECK(url->is_valid());
396 return true;
399 // Handles rewriting Web UI URLs.
400 bool HandleWebUI(GURL* url, content::BrowserContext* browser_context) {
401 // Do not handle special URLs such as "about:foo"
402 if (!url->host().empty()) {
403 const GURL chrome_url = AddUberHost(*url);
405 // Handle valid "chrome://chrome/foo" URLs so the reverse handler will
406 // be called.
407 if (ChromeWebUIControllerFactory::GetInstance()->UseWebUIForURL(
408 browser_context, chrome_url))
409 return true;
412 if (!ChromeWebUIControllerFactory::GetInstance()->UseWebUIForURL(
413 browser_context, *url))
414 return false;
416 #if defined(OS_CHROMEOS)
417 // Special case : in ChromeOS in Guest mode bookmarks and history are
418 // disabled for security reasons. New tab page explains the reasons, so
419 // we redirect user to new tab page.
420 if (user_manager::UserManager::Get()->IsLoggedInAsGuest()) {
421 if (url->SchemeIs(content::kChromeUIScheme) &&
422 (url->DomainIs(chrome::kChromeUIBookmarksHost) ||
423 url->DomainIs(chrome::kChromeUIHistoryHost))) {
424 // Rewrite with new tab URL
425 *url = GURL(chrome::kChromeUINewTabURL);
428 #endif
430 return true;
433 // Reverse URL handler for Web UI. Maps "chrome://chrome/foo/" to
434 // "chrome://foo/".
435 bool HandleWebUIReverse(GURL* url, content::BrowserContext* browser_context) {
436 if (!url->is_valid() || !url->SchemeIs(content::kChromeUIScheme))
437 return false;
439 return RemoveUberHost(url);
442 bool CertMatchesFilter(const net::X509Certificate& cert,
443 const base::DictionaryValue& filter) {
444 // TODO(markusheintz): This is the minimal required filter implementation.
445 // Implement a better matcher.
447 // An empty filter matches any client certificate since no requirements are
448 // specified at all.
449 if (filter.empty())
450 return true;
452 std::string common_name;
453 if (filter.GetString("ISSUER.CN", &common_name) &&
454 (cert.issuer().common_name == common_name)) {
455 return true;
457 return false;
460 #if defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_MACOSX)
461 breakpad::CrashHandlerHostLinux* CreateCrashHandlerHost(
462 const std::string& process_type) {
463 base::FilePath dumps_path;
464 PathService::Get(chrome::DIR_CRASH_DUMPS, &dumps_path);
466 ANNOTATE_SCOPED_MEMORY_LEAK;
467 bool upload = (getenv(env_vars::kHeadless) == NULL);
468 breakpad::CrashHandlerHostLinux* crash_handler =
469 new breakpad::CrashHandlerHostLinux(process_type, dumps_path, upload);
470 crash_handler->StartUploaderThread();
471 return crash_handler;
475 int GetCrashSignalFD(const base::CommandLine& command_line) {
476 // Extensions have the same process type as renderers.
477 if (command_line.HasSwitch(extensions::switches::kExtensionProcess)) {
478 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
479 if (!crash_handler)
480 crash_handler = CreateCrashHandlerHost("extension");
481 return crash_handler->GetDeathSignalSocket();
484 std::string process_type =
485 command_line.GetSwitchValueASCII(switches::kProcessType);
487 if (process_type == switches::kRendererProcess) {
488 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
489 if (!crash_handler)
490 crash_handler = CreateCrashHandlerHost(process_type);
491 return crash_handler->GetDeathSignalSocket();
494 if (process_type == switches::kPluginProcess) {
495 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
496 if (!crash_handler)
497 crash_handler = CreateCrashHandlerHost(process_type);
498 return crash_handler->GetDeathSignalSocket();
501 if (process_type == switches::kPpapiPluginProcess) {
502 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
503 if (!crash_handler)
504 crash_handler = CreateCrashHandlerHost(process_type);
505 return crash_handler->GetDeathSignalSocket();
508 if (process_type == switches::kGpuProcess) {
509 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
510 if (!crash_handler)
511 crash_handler = CreateCrashHandlerHost(process_type);
512 return crash_handler->GetDeathSignalSocket();
515 return -1;
517 #endif // defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_MACOSX)
519 void SetApplicationLocaleOnIOThread(const std::string& locale) {
520 DCHECK_CURRENTLY_ON(BrowserThread::IO);
521 g_io_thread_application_locale.Get() = locale;
524 void HandleBlockedPopupOnUIThread(const BlockedWindowParams& params) {
525 RenderFrameHost* render_frame_host = RenderFrameHost::FromID(
526 params.render_process_id(), params.opener_render_frame_id());
527 if (!render_frame_host)
528 return;
529 WebContents* tab = WebContents::FromRenderFrameHost(render_frame_host);
530 // The tab might already have navigated away. We only need to do this check
531 // for main frames, since the RenderFrameHost for a subframe opener will have
532 // already been deleted if the main frame navigates away.
533 if (!tab ||
534 (!render_frame_host->GetParent() &&
535 tab->GetMainFrame() != render_frame_host))
536 return;
538 prerender::PrerenderContents* prerender_contents =
539 prerender::PrerenderContents::FromWebContents(tab);
540 if (prerender_contents) {
541 prerender_contents->Destroy(prerender::FINAL_STATUS_CREATE_NEW_WINDOW);
542 return;
545 PopupBlockerTabHelper* popup_helper =
546 PopupBlockerTabHelper::FromWebContents(tab);
547 if (!popup_helper)
548 return;
549 popup_helper->AddBlockedPopup(params);
552 // An implementation of the SSLCertReporter interface used by
553 // SSLErrorHandler. Uses the SafeBrowsing UI manager to send invalid
554 // certificate reports.
555 class SafeBrowsingSSLCertReporter : public SSLCertReporter {
556 public:
557 explicit SafeBrowsingSSLCertReporter(
558 const scoped_refptr<SafeBrowsingUIManager>& safe_browsing_ui_manager)
559 : safe_browsing_ui_manager_(safe_browsing_ui_manager) {}
560 ~SafeBrowsingSSLCertReporter() override {}
562 // SSLCertReporter implementation
563 void ReportInvalidCertificateChain(
564 const std::string& serialized_report) override {
565 if (safe_browsing_ui_manager_) {
566 safe_browsing_ui_manager_->ReportInvalidCertificateChain(
567 serialized_report, base::Bind(&base::DoNothing));
571 private:
572 const scoped_refptr<SafeBrowsingUIManager> safe_browsing_ui_manager_;
575 #if defined(OS_ANDROID)
577 void HandleSingleTabModeBlockOnUIThread(const BlockedWindowParams& params) {
578 WebContents* web_contents = tab_util::GetWebContentsByFrameID(
579 params.render_process_id(), params.opener_render_frame_id());
580 if (!web_contents)
581 return;
583 SingleTabModeTabHelper::FromWebContents(web_contents)->HandleOpenUrl(params);
586 float GetDeviceScaleAdjustment() {
587 static const float kMinFSM = 1.05f;
588 static const int kWidthForMinFSM = 320;
589 static const float kMaxFSM = 1.3f;
590 static const int kWidthForMaxFSM = 800;
592 gfx::DeviceDisplayInfo info;
593 int minWidth = info.GetSmallestDIPWidth();
595 if (minWidth <= kWidthForMinFSM)
596 return kMinFSM;
597 if (minWidth >= kWidthForMaxFSM)
598 return kMaxFSM;
600 // The font scale multiplier varies linearly between kMinFSM and kMaxFSM.
601 float ratio = static_cast<float>(minWidth - kWidthForMinFSM) /
602 (kWidthForMaxFSM - kWidthForMinFSM);
603 return ratio * (kMaxFSM - kMinFSM) + kMinFSM;
606 #endif // defined(OS_ANDROID)
608 #if defined(ENABLE_EXTENSIONS)
609 // By default, JavaScript and images are enabled in guest content.
610 void GetGuestViewDefaultContentSettingRules(
611 bool incognito,
612 RendererContentSettingRules* rules) {
613 rules->image_rules.push_back(
614 ContentSettingPatternSource(ContentSettingsPattern::Wildcard(),
615 ContentSettingsPattern::Wildcard(),
616 CONTENT_SETTING_ALLOW,
617 std::string(),
618 incognito));
620 rules->script_rules.push_back(
621 ContentSettingPatternSource(ContentSettingsPattern::Wildcard(),
622 ContentSettingsPattern::Wildcard(),
623 CONTENT_SETTING_ALLOW,
624 std::string(),
625 incognito));
627 #endif // defined(ENABLE_EXTENSIONS)
629 } // namespace
631 ChromeContentBrowserClient::ChromeContentBrowserClient()
633 weak_factory_(this) {
634 #if defined(ENABLE_PLUGINS)
635 for (size_t i = 0; i < arraysize(kPredefinedAllowedDevChannelOrigins); ++i)
636 allowed_dev_channel_origins_.insert(kPredefinedAllowedDevChannelOrigins[i]);
637 for (size_t i = 0; i < arraysize(kPredefinedAllowedFileHandleOrigins); ++i)
638 allowed_file_handle_origins_.insert(kPredefinedAllowedFileHandleOrigins[i]);
639 for (size_t i = 0; i < arraysize(kPredefinedAllowedSocketOrigins); ++i)
640 allowed_socket_origins_.insert(kPredefinedAllowedSocketOrigins[i]);
642 extra_parts_.push_back(new ChromeContentBrowserClientPluginsPart);
643 #endif
645 #if !defined(OS_ANDROID)
646 TtsExtensionEngine* tts_extension_engine = TtsExtensionEngine::GetInstance();
647 TtsController::GetInstance()->SetTtsEngineDelegate(tts_extension_engine);
648 #endif
650 #if defined(ENABLE_EXTENSIONS)
651 extra_parts_.push_back(new ChromeContentBrowserClientExtensionsPart);
652 #endif
655 ChromeContentBrowserClient::~ChromeContentBrowserClient() {
656 for (int i = static_cast<int>(extra_parts_.size()) - 1; i >= 0; --i)
657 delete extra_parts_[i];
658 extra_parts_.clear();
661 // static
662 void ChromeContentBrowserClient::RegisterProfilePrefs(
663 user_prefs::PrefRegistrySyncable* registry) {
664 registry->RegisterBooleanPref(prefs::kDisable3DAPIs, false);
665 registry->RegisterBooleanPref(prefs::kEnableHyperlinkAuditing, true);
666 registry->RegisterListPref(prefs::kEnableDeprecatedWebPlatformFeatures);
669 // static
670 void ChromeContentBrowserClient::SetApplicationLocale(
671 const std::string& locale) {
672 DCHECK_CURRENTLY_ON(BrowserThread::UI);
674 // This object is guaranteed to outlive all threads so we don't have to
675 // worry about the lack of refcounting and can just post as Unretained.
677 // The common case is that this function is called early in Chrome startup
678 // before any threads are created (it will also be called later if the user
679 // changes the pref). In this case, there will be no threads created and
680 // posting will fail. When there are no threads, we can just set the string
681 // without worrying about threadsafety.
682 if (!BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
683 base::Bind(&SetApplicationLocaleOnIOThread, locale))) {
684 g_io_thread_application_locale.Get() = locale;
688 content::BrowserMainParts* ChromeContentBrowserClient::CreateBrowserMainParts(
689 const content::MainFunctionParams& parameters) {
690 ChromeBrowserMainParts* main_parts;
691 // Construct the Main browser parts based on the OS type.
692 #if defined(OS_WIN)
693 main_parts = new ChromeBrowserMainPartsWin(parameters);
694 #elif defined(OS_MACOSX)
695 main_parts = new ChromeBrowserMainPartsMac(parameters);
696 #elif defined(OS_CHROMEOS)
697 main_parts = new chromeos::ChromeBrowserMainPartsChromeos(parameters);
698 #elif defined(OS_LINUX)
699 main_parts = new ChromeBrowserMainPartsLinux(parameters);
700 #elif defined(OS_ANDROID)
701 main_parts = new ChromeBrowserMainPartsAndroid(parameters);
702 #elif defined(OS_POSIX)
703 main_parts = new ChromeBrowserMainPartsPosix(parameters);
704 #else
705 NOTREACHED();
706 main_parts = new ChromeBrowserMainParts(parameters);
707 #endif
709 chrome::AddProfilesExtraParts(main_parts);
711 // Construct additional browser parts. Stages are called in the order in
712 // which they are added.
713 #if defined(TOOLKIT_VIEWS)
714 main_parts->AddParts(new ChromeBrowserMainExtraPartsViews());
715 #endif
717 // TODO(oshima): Athena on chrome currently requires USE_ASH to build.
718 // We should reduce the dependency as much as possible.
719 #if defined(USE_ASH)
720 main_parts->AddParts(new ChromeBrowserMainExtraPartsAsh());
721 #endif
723 #if defined(USE_AURA)
724 main_parts->AddParts(new ChromeBrowserMainExtraPartsAura());
725 #endif
727 #if defined(USE_X11)
728 main_parts->AddParts(new ChromeBrowserMainExtraPartsX11());
729 #endif
731 chrome::AddMetricsExtraParts(main_parts);
733 return main_parts;
736 void ChromeContentBrowserClient::PostAfterStartupTask(
737 const tracked_objects::Location& from_here,
738 const scoped_refptr<base::TaskRunner>& task_runner,
739 const base::Closure& task) {
740 AfterStartupTaskUtils::PostTask(from_here, task_runner, task);
743 std::string ChromeContentBrowserClient::GetStoragePartitionIdForSite(
744 content::BrowserContext* browser_context,
745 const GURL& site) {
746 std::string partition_id;
748 // The partition ID for webview guest processes is the string value of its
749 // SiteInstance URL - "chrome-guest://app_id/persist?partition".
750 if (site.SchemeIs(content::kGuestScheme)) {
751 partition_id = site.spec();
752 } else if (!switches::IsEnableWebviewBasedSignin() &&
753 site.GetOrigin().spec() == chrome::kChromeUIChromeSigninURL) {
754 // The non-webview Chrome signin page has an embedded iframe of extension
755 // and web content, thus it must be isolated from other webUI pages.
756 partition_id = site.GetOrigin().spec();
759 DCHECK(IsValidStoragePartitionId(browser_context, partition_id));
760 return partition_id;
763 bool ChromeContentBrowserClient::IsValidStoragePartitionId(
764 content::BrowserContext* browser_context,
765 const std::string& partition_id) {
766 // The default ID is empty and is always valid.
767 if (partition_id.empty())
768 return true;
770 return GURL(partition_id).is_valid();
773 void ChromeContentBrowserClient::GetStoragePartitionConfigForSite(
774 content::BrowserContext* browser_context,
775 const GURL& site,
776 bool can_be_default,
777 std::string* partition_domain,
778 std::string* partition_name,
779 bool* in_memory) {
780 // Default to the browser-wide storage partition and override based on |site|
781 // below.
782 partition_domain->clear();
783 partition_name->clear();
784 *in_memory = false;
786 bool success = false;
787 #if defined(ENABLE_EXTENSIONS)
788 success = extensions::WebViewGuest::GetGuestPartitionConfigForSite(
789 site, partition_domain, partition_name, in_memory);
791 if (!success && site.SchemeIs(extensions::kExtensionScheme)) {
792 // If |can_be_default| is false, the caller is stating that the |site|
793 // should be parsed as if it had isolated storage. In particular it is
794 // important to NOT check ExtensionService for the is_storage_isolated()
795 // attribute because this code path is run during Extension uninstall
796 // to do cleanup after the Extension has already been unloaded from the
797 // ExtensionService.
798 bool is_isolated = !can_be_default;
799 if (can_be_default) {
800 if (extensions::util::SiteHasIsolatedStorage(site, browser_context))
801 is_isolated = true;
804 if (is_isolated) {
805 CHECK(site.has_host());
806 // For extensions with isolated storage, the the host of the |site| is
807 // the |partition_domain|. The |in_memory| and |partition_name| are only
808 // used in guest schemes so they are cleared here.
809 *partition_domain = site.host();
810 *in_memory = false;
811 partition_name->clear();
813 success = true;
815 #endif
817 if (!success &&
818 (!switches::IsEnableWebviewBasedSignin() &&
819 site.GetOrigin().spec() == chrome::kChromeUIChromeSigninURL)) {
820 // The non-webview Chrome signin page has an embedded iframe of extension
821 // and web content, thus it must be isolated from other webUI pages.
822 *partition_domain = chrome::kChromeUIChromeSigninHost;
825 // Assert that if |can_be_default| is false, the code above must have found a
826 // non-default partition. If this fails, the caller has a serious logic
827 // error about which StoragePartition they expect to be in and it is not
828 // safe to continue.
829 CHECK(can_be_default || !partition_domain->empty());
832 content::WebContentsViewDelegate*
833 ChromeContentBrowserClient::GetWebContentsViewDelegate(
834 content::WebContents* web_contents) {
835 return chrome::CreateWebContentsViewDelegate(web_contents);
838 void ChromeContentBrowserClient::RenderProcessWillLaunch(
839 content::RenderProcessHost* host) {
840 int id = host->GetID();
841 Profile* profile = Profile::FromBrowserContext(host->GetBrowserContext());
842 net::URLRequestContextGetter* context =
843 profile->GetRequestContextForRenderProcess(id);
845 host->AddFilter(new ChromeRenderMessageFilter(id, profile));
846 #if defined(ENABLE_EXTENSIONS)
847 host->AddFilter(new cast::CastTransportHostFilter);
848 #endif
849 #if defined(ENABLE_PRINTING)
850 host->AddFilter(new printing::PrintingMessageFilter(id, profile));
851 #endif
852 host->AddFilter(new SearchProviderInstallStateMessageFilter(id, profile));
853 #if defined(ENABLE_SPELLCHECK)
854 host->AddFilter(new SpellCheckMessageFilter(id));
855 #endif
856 #if defined(USE_BROWSER_SPELLCHECKER)
857 host->AddFilter(new SpellCheckMessageFilterPlatform(id));
858 #endif
859 host->AddFilter(new ChromeNetBenchmarkingMessageFilter(profile, context));
860 host->AddFilter(new prerender::PrerenderMessageFilter(id, profile));
861 host->AddFilter(new TtsMessageFilter(host->GetBrowserContext()));
862 #if defined(ENABLE_WEBRTC)
863 WebRtcLoggingHandlerHost* webrtc_logging_handler_host =
864 new WebRtcLoggingHandlerHost(profile);
865 host->SetWebRtcLogMessageCallback(base::Bind(
866 &WebRtcLoggingHandlerHost::LogMessage, webrtc_logging_handler_host));
867 host->AddFilter(webrtc_logging_handler_host);
868 host->SetUserData(host, new base::UserDataAdapter<WebRtcLoggingHandlerHost>(
869 webrtc_logging_handler_host));
870 #endif
871 #if !defined(DISABLE_NACL)
872 host->AddFilter(new nacl::NaClHostMessageFilter(
873 id, profile->IsOffTheRecord(),
874 profile->GetPath(),
875 context));
876 #endif
877 #if defined(OS_ANDROID)
878 host->AddFilter(new cdm::CdmMessageFilterAndroid());
879 #endif
880 DataReductionProxyChromeSettings* data_reduction_proxy_settings =
881 DataReductionProxyChromeSettingsFactory::GetForBrowserContext(profile);
882 host->AddFilter(new data_reduction_proxy::DataReductionProxyMessageFilter(
883 data_reduction_proxy_settings));
885 host->Send(new ChromeViewMsg_SetIsIncognitoProcess(
886 profile->IsOffTheRecord()));
888 for (size_t i = 0; i < extra_parts_.size(); ++i)
889 extra_parts_[i]->RenderProcessWillLaunch(host);
891 RendererContentSettingRules rules;
892 if (host->IsForGuestsOnly()) {
893 #if defined(ENABLE_EXTENSIONS)
894 GetGuestViewDefaultContentSettingRules(profile->IsOffTheRecord(), &rules);
895 #else
896 NOTREACHED();
897 #endif
898 } else {
899 GetRendererContentSettingRules(
900 HostContentSettingsMapFactory::GetForProfile(profile), &rules);
902 host->Send(new ChromeViewMsg_SetContentSettingRules(rules));
905 GURL ChromeContentBrowserClient::GetEffectiveURL(
906 content::BrowserContext* browser_context, const GURL& url) {
907 Profile* profile = Profile::FromBrowserContext(browser_context);
908 if (!profile)
909 return url;
911 // If the input |url| should be assigned to the Instant renderer, make its
912 // effective URL distinct from other URLs on the search provider's domain.
913 if (search::ShouldAssignURLToInstantRenderer(url, profile))
914 return search::GetEffectiveURLForInstant(url, profile);
916 #if defined(ENABLE_EXTENSIONS)
917 return ChromeContentBrowserClientExtensionsPart::GetEffectiveURL(
918 profile, url);
919 #else
920 return url;
921 #endif
924 bool ChromeContentBrowserClient::ShouldUseProcessPerSite(
925 content::BrowserContext* browser_context, const GURL& effective_url) {
926 // Non-extension, non-Instant URLs should generally use
927 // process-per-site-instance. Because we expect to use the effective URL,
928 // URLs for hosted apps (apart from bookmark apps) should have an extension
929 // scheme by now.
931 Profile* profile = Profile::FromBrowserContext(browser_context);
932 if (!profile)
933 return false;
935 if (search::ShouldUseProcessPerSiteForInstantURL(effective_url, profile))
936 return true;
938 #if defined(ENABLE_EXTENSIONS)
939 return ChromeContentBrowserClientExtensionsPart::ShouldUseProcessPerSite(
940 profile, effective_url);
941 #else
942 return false;
943 #endif
946 // TODO(creis, nick): https://crbug.com/160576 describes a weakness in our
947 // origin-lock enforcement, where we don't have a way to efficiently know
948 // effective URLs on the IO thread, and wind up killing processes that e.g.
949 // request cookies for their actual URL. This whole function (and its
950 // ExtensionsPart) should be removed once we add that ability to the IO thread.
951 bool ChromeContentBrowserClient::ShouldLockToOrigin(
952 content::BrowserContext* browser_context,
953 const GURL& effective_site_url) {
954 // Origin lock to the search scheme would kill processes upon legitimate
955 // requests for cookies from the search engine's domain.
956 if (effective_site_url.SchemeIs(chrome::kChromeSearchScheme))
957 return false;
959 #if defined(ENABLE_EXTENSIONS)
960 // Disable origin lock if this is an extension/app that applies effective URL
961 // mappings.
962 if (!ChromeContentBrowserClientExtensionsPart::ShouldLockToOrigin(
963 browser_context, effective_site_url)) {
964 return false;
966 #endif
967 return true;
970 // These are treated as WebUI schemes but do not get WebUI bindings. Also,
971 // view-source is allowed for these schemes.
972 void ChromeContentBrowserClient::GetAdditionalWebUISchemes(
973 std::vector<std::string>* additional_schemes) {
974 additional_schemes->push_back(chrome::kChromeSearchScheme);
975 additional_schemes->push_back(dom_distiller::kDomDistillerScheme);
978 void ChromeContentBrowserClient::GetAdditionalWebUIHostsToIgnoreParititionCheck(
979 std::vector<std::string>* hosts) {
980 hosts->push_back(chrome::kChromeUIExtensionIconHost);
981 hosts->push_back(chrome::kChromeUIFaviconHost);
982 hosts->push_back(chrome::kChromeUIThemeHost);
983 hosts->push_back(chrome::kChromeUIThumbnailHost);
984 hosts->push_back(chrome::kChromeUIThumbnailHost2);
985 hosts->push_back(chrome::kChromeUIThumbnailListHost);
988 net::URLRequestContextGetter*
989 ChromeContentBrowserClient::CreateRequestContext(
990 content::BrowserContext* browser_context,
991 content::ProtocolHandlerMap* protocol_handlers,
992 content::URLRequestInterceptorScopedVector request_interceptors) {
993 Profile* profile = Profile::FromBrowserContext(browser_context);
994 return profile->CreateRequestContext(protocol_handlers,
995 request_interceptors.Pass());
998 net::URLRequestContextGetter*
999 ChromeContentBrowserClient::CreateRequestContextForStoragePartition(
1000 content::BrowserContext* browser_context,
1001 const base::FilePath& partition_path,
1002 bool in_memory,
1003 content::ProtocolHandlerMap* protocol_handlers,
1004 content::URLRequestInterceptorScopedVector request_interceptors) {
1005 Profile* profile = Profile::FromBrowserContext(browser_context);
1006 return profile->CreateRequestContextForStoragePartition(
1007 partition_path,
1008 in_memory,
1009 protocol_handlers,
1010 request_interceptors.Pass());
1013 bool ChromeContentBrowserClient::IsHandledURL(const GURL& url) {
1014 return ProfileIOData::IsHandledURL(url);
1017 bool ChromeContentBrowserClient::CanCommitURL(
1018 content::RenderProcessHost* process_host,
1019 const GURL& url) {
1020 #if defined(ENABLE_EXTENSIONS)
1021 return ChromeContentBrowserClientExtensionsPart::CanCommitURL(
1022 process_host, url);
1023 #else
1024 return true;
1025 #endif
1028 bool ChromeContentBrowserClient::IsIllegalOrigin(
1029 content::ResourceContext* resource_context,
1030 int child_process_id,
1031 const GURL& origin) {
1032 #if defined(ENABLE_EXTENSIONS)
1033 return ChromeContentBrowserClientExtensionsPart::IsIllegalOrigin(
1034 resource_context, child_process_id, origin);
1035 #else
1036 return false;
1037 #endif
1040 bool ChromeContentBrowserClient::ShouldAllowOpenURL(
1041 content::SiteInstance* site_instance, const GURL& url) {
1042 GURL from_url = site_instance->GetSiteURL();
1044 #if defined(ENABLE_EXTENSIONS)
1045 bool result;
1046 if (ChromeContentBrowserClientExtensionsPart::ShouldAllowOpenURL(
1047 site_instance, from_url, url, &result))
1048 return result;
1049 #endif
1051 // Do not allow chrome://chrome-signin navigate to other chrome:// URLs, since
1052 // the signin page may host untrusted web content.
1053 if (from_url.GetOrigin().spec() == chrome::kChromeUIChromeSigninURL &&
1054 url.SchemeIs(content::kChromeUIScheme) &&
1055 url.host() != chrome::kChromeUIChromeSigninHost) {
1056 VLOG(1) << "Blocked navigation to " << url.spec() << " from "
1057 << chrome::kChromeUIChromeSigninURL;
1058 return false;
1061 return true;
1064 bool ChromeContentBrowserClient::IsSuitableHost(
1065 content::RenderProcessHost* process_host,
1066 const GURL& site_url) {
1067 Profile* profile =
1068 Profile::FromBrowserContext(process_host->GetBrowserContext());
1069 // This may be NULL during tests. In that case, just assume any site can
1070 // share any host.
1071 if (!profile)
1072 return true;
1074 // Instant URLs should only be in the instant process and instant process
1075 // should only have Instant URLs.
1076 InstantService* instant_service =
1077 InstantServiceFactory::GetForProfile(profile);
1078 if (instant_service) {
1079 bool is_instant_process = instant_service->IsInstantProcess(
1080 process_host->GetID());
1081 bool should_be_in_instant_process =
1082 search::ShouldAssignURLToInstantRenderer(site_url, profile);
1083 if (is_instant_process || should_be_in_instant_process)
1084 return is_instant_process && should_be_in_instant_process;
1087 #if defined(ENABLE_EXTENSIONS)
1088 return ChromeContentBrowserClientExtensionsPart::IsSuitableHost(
1089 profile, process_host, site_url);
1090 #else
1091 return true;
1092 #endif
1095 bool ChromeContentBrowserClient::MayReuseHost(
1096 content::RenderProcessHost* process_host) {
1097 // If there is currently a prerender in progress for the host provided,
1098 // it may not be shared. We require prerenders to be by themselves in a
1099 // separate process so that we can monitor their resource usage.
1100 Profile* profile = Profile::FromBrowserContext(
1101 process_host->GetBrowserContext());
1102 prerender::PrerenderManager* prerender_manager =
1103 prerender::PrerenderManagerFactory::GetForProfile(profile);
1104 if (prerender_manager &&
1105 !prerender_manager->MayReuseProcessHost(process_host)) {
1106 return false;
1109 return true;
1112 bool ChromeContentBrowserClient::ShouldTryToUseExistingProcessHost(
1113 content::BrowserContext* browser_context, const GURL& url) {
1114 // It has to be a valid URL for us to check for an extension.
1115 if (!url.is_valid())
1116 return false;
1118 #if defined(ENABLE_EXTENSIONS)
1119 Profile* profile = Profile::FromBrowserContext(browser_context);
1120 return ChromeContentBrowserClientExtensionsPart::
1121 ShouldTryToUseExistingProcessHost(
1122 profile, url);
1123 #else
1124 return false;
1125 #endif
1128 void ChromeContentBrowserClient::SiteInstanceGotProcess(
1129 SiteInstance* site_instance) {
1130 CHECK(site_instance->HasProcess());
1132 Profile* profile = Profile::FromBrowserContext(
1133 site_instance->GetBrowserContext());
1134 if (!profile)
1135 return;
1137 // Remember the ID of the Instant process to signal the renderer process
1138 // on startup in |AppendExtraCommandLineSwitches| below.
1139 if (search::ShouldAssignURLToInstantRenderer(site_instance->GetSiteURL(),
1140 profile)) {
1141 InstantService* instant_service =
1142 InstantServiceFactory::GetForProfile(profile);
1143 if (instant_service)
1144 instant_service->AddInstantProcess(site_instance->GetProcess()->GetID());
1147 for (size_t i = 0; i < extra_parts_.size(); ++i)
1148 extra_parts_[i]->SiteInstanceGotProcess(site_instance);
1151 void ChromeContentBrowserClient::SiteInstanceDeleting(
1152 SiteInstance* site_instance) {
1153 if (!site_instance->HasProcess())
1154 return;
1156 for (size_t i = 0; i < extra_parts_.size(); ++i)
1157 extra_parts_[i]->SiteInstanceDeleting(site_instance);
1160 bool ChromeContentBrowserClient::ShouldSwapBrowsingInstancesForNavigation(
1161 SiteInstance* site_instance,
1162 const GURL& current_url,
1163 const GURL& new_url) {
1164 #if defined(ENABLE_EXTENSIONS)
1165 return ChromeContentBrowserClientExtensionsPart::
1166 ShouldSwapBrowsingInstancesForNavigation(
1167 site_instance, current_url, new_url);
1168 #else
1169 return false;
1170 #endif
1173 bool ChromeContentBrowserClient::ShouldSwapProcessesForRedirect(
1174 content::ResourceContext* resource_context, const GURL& current_url,
1175 const GURL& new_url) {
1176 #if defined(ENABLE_EXTENSIONS)
1177 return ChromeContentBrowserClientExtensionsPart::
1178 ShouldSwapProcessesForRedirect(resource_context, current_url, new_url);
1179 #else
1180 return false;
1181 #endif
1184 bool ChromeContentBrowserClient::ShouldAssignSiteForURL(const GURL& url) {
1185 return !url.SchemeIs(chrome::kChromeNativeScheme);
1188 std::string ChromeContentBrowserClient::GetCanonicalEncodingNameByAliasName(
1189 const std::string& alias_name) {
1190 return CharacterEncoding::GetCanonicalEncodingNameByAliasName(alias_name);
1193 namespace {
1195 bool IsAutoReloadEnabled() {
1196 // Fetch the field trial, even though we don't use it. Calling FindFullName()
1197 // causes the field-trial mechanism to report which group we're in, which
1198 // might reflect a hard disable or hard enable via flag, both of which have
1199 // their own field trial groups. This lets us know what percentage of users
1200 // manually enable or disable auto-reload.
1201 std::string group = base::FieldTrialList::FindFullName(
1202 "AutoReloadExperiment");
1203 const base::CommandLine& browser_command_line =
1204 *base::CommandLine::ForCurrentProcess();
1205 if (browser_command_line.HasSwitch(switches::kEnableOfflineAutoReload))
1206 return true;
1207 if (browser_command_line.HasSwitch(switches::kDisableOfflineAutoReload))
1208 return false;
1209 return true;
1212 bool IsAutoReloadVisibleOnlyEnabled() {
1213 // See the block comment in IsAutoReloadEnabled().
1214 std::string group = base::FieldTrialList::FindFullName(
1215 "AutoReloadVisibleOnlyExperiment");
1216 const base::CommandLine& browser_command_line =
1217 *base::CommandLine::ForCurrentProcess();
1218 if (browser_command_line.HasSwitch(
1219 switches::kEnableOfflineAutoReloadVisibleOnly)) {
1220 return true;
1222 if (browser_command_line.HasSwitch(
1223 switches::kDisableOfflineAutoReloadVisibleOnly)) {
1224 return false;
1226 return true;
1229 void MaybeAppendBlinkSettingsSwitchForFieldTrial(
1230 const base::CommandLine& browser_command_line,
1231 base::CommandLine* command_line) {
1232 // List of field trials that modify the blink-settings command line flag. No
1233 // two field trials in the list should specify the same keys, otherwise one
1234 // field trial may overwrite another. See Source/core/frame/Settings.in in
1235 // Blink for the list of valid keys.
1236 static const char* const kBlinkSettingsFieldTrials[] = {
1237 // Keys: backgroundHtmlParserOutstandingTokenLimit
1238 // backgroundHtmlParserPendingTokenLimit
1239 "BackgroundHtmlParserTokenLimits",
1241 // Keys: doHtmlPreloadScanning
1242 "HtmlPreloadScanning",
1244 // Keys: lowPriorityIframes
1245 "LowPriorityIFrames",
1248 std::vector<std::string> blink_settings;
1249 for (const char* field_trial_name : kBlinkSettingsFieldTrials) {
1250 // Each blink-settings field trial should include a forcing_flag group,
1251 // to make sure that clients that specify the blink-settings flag on the
1252 // command line are excluded from the experiment groups. To make
1253 // sure we assign clients that specify this flag to the forcing_flag
1254 // group, we must call GetVariationParams for each field trial first
1255 // (for example, before checking HasSwitch() and returning), since
1256 // GetVariationParams has the side-effect of assigning the client to
1257 // a field trial group.
1258 std::map<std::string, std::string> params;
1259 if (variations::GetVariationParams(field_trial_name, &params)) {
1260 for (const auto& param : params) {
1261 blink_settings.push_back(base::StringPrintf(
1262 "%s=%s", param.first.c_str(), param.second.c_str()));
1267 // Flags for the ResourcePriorities field trial. The settings are
1268 // encoded in the field trial group name instead of as variations
1269 // because the variations code is not accessible from the loader.
1271 // The group name encoding looks like this:
1272 // <descriptiveName>_ABCDE_E2_F_G
1273 // A - fetchDeferLateScripts (1 for true, 0 for false)
1274 // B - fetchIncreaseFontPriority (1 for true, 0 for false)
1275 // C - fetchIncreaseAsyncScriptPriority (1 for true, 0 for false)
1276 // D - fetchIncreasePriorities (1 for true, 0 for false)
1277 // E - fetchEnableLayoutBlockingThreshold (1 for true, 0 for false)
1278 // E2 - fetchLayoutBlockingThreshold (Numeric)
1279 // F - fetchMaxNumDelayableWhileLayoutBlocking (Numeric)
1280 // G - fetchMaxNumDelayableRequests (Numeric)
1282 // Only A-D are relevant to blink and exposed as settings
1283 // Any group names (Control, Default, etc) will not match the pattern or
1284 // flags and will get the default settings which is the expected behavior.
1285 std::string resource_priorities_trial_group =
1286 base::FieldTrialList::FindFullName("ResourcePriorities");
1287 std::vector<std::string> split_group(
1288 base::SplitString(resource_priorities_trial_group, "_",
1289 base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL));
1290 if (split_group.size() == 5 && split_group[1].length() == 5) {
1291 if (split_group[1].at(0) == '1')
1292 blink_settings.push_back("fetchDeferLateScripts=true");
1293 if (split_group[1].at(1) == '1')
1294 blink_settings.push_back("fetchIncreaseFontPriority=true");
1295 if (split_group[1].at(2) == '1')
1296 blink_settings.push_back("fetchIncreaseAsyncScriptPriority=true");
1297 if (split_group[1].at(3) == '1')
1298 blink_settings.push_back("fetchIncreasePriorities=true");
1301 if (blink_settings.empty()) {
1302 return;
1305 if (browser_command_line.HasSwitch(switches::kBlinkSettings) ||
1306 command_line->HasSwitch(switches::kBlinkSettings)) {
1307 // The field trials should be configured to force users that specify the
1308 // blink-settings flag into a group with no params, and we return
1309 // above if no params were specified, so it's an error if we reach
1310 // this point.
1311 LOG(WARNING) << "Received field trial params, "
1312 "but blink-settings switch already specified.";
1313 return;
1316 command_line->AppendSwitchASCII(switches::kBlinkSettings,
1317 base::JoinString(blink_settings, ","));
1320 } // namespace
1322 void ChromeContentBrowserClient::AppendExtraCommandLineSwitches(
1323 base::CommandLine* command_line,
1324 int child_process_id) {
1325 #if defined(OS_MACOSX)
1326 scoped_ptr<metrics::ClientInfo> client_info =
1327 GoogleUpdateSettings::LoadMetricsClientInfo();
1328 if (client_info) {
1329 command_line->AppendSwitchASCII(switches::kMetricsClientID,
1330 client_info->client_id);
1332 #elif defined(OS_POSIX)
1333 if (breakpad::IsCrashReporterEnabled()) {
1334 scoped_ptr<metrics::ClientInfo> client_info =
1335 GoogleUpdateSettings::LoadMetricsClientInfo();
1336 command_line->AppendSwitchASCII(switches::kEnableCrashReporter,
1337 client_info ? client_info->client_id
1338 : std::string());
1340 #endif
1342 if (logging::DialogsAreSuppressed())
1343 command_line->AppendSwitch(switches::kNoErrorDialogs);
1345 std::string process_type =
1346 command_line->GetSwitchValueASCII(switches::kProcessType);
1347 const base::CommandLine& browser_command_line =
1348 *base::CommandLine::ForCurrentProcess();
1350 static const char* const kCommonSwitchNames[] = {
1351 switches::kUserAgent,
1352 switches::kUserDataDir, // Make logs go to the right file.
1354 command_line->CopySwitchesFrom(browser_command_line, kCommonSwitchNames,
1355 arraysize(kCommonSwitchNames));
1357 #if defined(ENABLE_IPC_FUZZER)
1358 static const char* const kIpcFuzzerSwitches[] = {
1359 switches::kIpcDumpDirectory,
1360 switches::kIpcFuzzerTestcase,
1362 command_line->CopySwitchesFrom(browser_command_line, kIpcFuzzerSwitches,
1363 arraysize(kIpcFuzzerSwitches));
1364 #endif
1366 #if defined(OS_CHROMEOS)
1367 static const char* const kChromeOSSwitches[] = {
1368 switches::kDisableDinosaurEasterEgg,
1370 command_line->CopySwitchesFrom(browser_command_line, kChromeOSSwitches,
1371 arraysize(kChromeOSSwitches));
1373 // On Chrome OS need to pass primary user homedir (in multi-profiles session).
1374 base::FilePath homedir;
1375 PathService::Get(base::DIR_HOME, &homedir);
1376 command_line->AppendSwitchASCII(chromeos::switches::kHomedir,
1377 homedir.value().c_str());
1378 #endif
1380 if (process_type == switches::kRendererProcess) {
1381 content::RenderProcessHost* process =
1382 content::RenderProcessHost::FromID(child_process_id);
1383 Profile* profile =
1384 process ? Profile::FromBrowserContext(process->GetBrowserContext())
1385 : NULL;
1386 for (size_t i = 0; i < extra_parts_.size(); ++i) {
1387 extra_parts_[i]->AppendExtraRendererCommandLineSwitches(
1388 command_line, process, profile);
1391 #if defined(OS_CHROMEOS)
1392 const std::string& login_profile =
1393 browser_command_line.GetSwitchValueASCII(
1394 chromeos::switches::kLoginProfile);
1395 if (!login_profile.empty())
1396 command_line->AppendSwitchASCII(
1397 chromeos::switches::kLoginProfile, login_profile);
1398 #endif
1400 #if defined(ENABLE_WEBRTC)
1401 MaybeCopyDisableWebRtcEncryptionSwitch(command_line,
1402 browser_command_line,
1403 chrome::GetChannel());
1404 #endif
1406 if (process) {
1407 PrefService* prefs = profile->GetPrefs();
1408 // Currently this pref is only registered if applied via a policy.
1409 if (prefs->HasPrefPath(prefs::kDisable3DAPIs) &&
1410 prefs->GetBoolean(prefs::kDisable3DAPIs)) {
1411 // Turn this policy into a command line switch.
1412 command_line->AppendSwitch(switches::kDisable3DAPIs);
1415 const base::ListValue* switches =
1416 prefs->GetList(prefs::kEnableDeprecatedWebPlatformFeatures);
1417 if (switches) {
1418 // Enable any deprecated features that have been re-enabled by policy.
1419 for (base::ListValue::const_iterator it = switches->begin();
1420 it != switches->end(); ++it) {
1421 std::string switch_to_enable;
1422 if ((*it)->GetAsString(&switch_to_enable))
1423 command_line->AppendSwitch(switch_to_enable);
1427 // Disable client-side phishing detection in the renderer if it is
1428 // disabled in the Profile preferences or the browser process.
1429 if (!prefs->GetBoolean(prefs::kSafeBrowsingEnabled) ||
1430 !g_browser_process->safe_browsing_detection_service()) {
1431 command_line->AppendSwitch(
1432 switches::kDisableClientSidePhishingDetection);
1435 if (prefs->GetBoolean(prefs::kPrintPreviewDisabled))
1436 command_line->AppendSwitch(switches::kDisablePrintPreview);
1438 InstantService* instant_service =
1439 InstantServiceFactory::GetForProfile(profile);
1440 if (instant_service &&
1441 instant_service->IsInstantProcess(process->GetID()))
1442 command_line->AppendSwitch(switches::kInstantProcess);
1445 if (IsAutoReloadEnabled())
1446 command_line->AppendSwitch(switches::kEnableOfflineAutoReload);
1447 if (IsAutoReloadVisibleOnlyEnabled()) {
1448 command_line->AppendSwitch(
1449 switches::kEnableOfflineAutoReloadVisibleOnly);
1453 // Enable showing a saved copy if this session is in the field trial
1454 // or the user explicitly enabled it. Note that as far as the
1455 // renderer is concerned, the feature is enabled if-and-only-if
1456 // one of the kEnableShowSavedCopy* switches is on the command
1457 // line; the yes/no/default behavior is only at the browser
1458 // command line level.
1460 // Command line switches override
1461 const std::string& show_saved_copy_value =
1462 browser_command_line.GetSwitchValueASCII(switches::kShowSavedCopy);
1463 if (show_saved_copy_value == switches::kEnableShowSavedCopyPrimary ||
1464 show_saved_copy_value == switches::kEnableShowSavedCopySecondary ||
1465 show_saved_copy_value == switches::kDisableShowSavedCopy) {
1466 command_line->AppendSwitchASCII(switches::kShowSavedCopy,
1467 show_saved_copy_value);
1468 } else {
1469 std::string group =
1470 base::FieldTrialList::FindFullName("LoadStaleCacheExperiment");
1472 if (group == "Primary") {
1473 command_line->AppendSwitchASCII(
1474 switches::kShowSavedCopy, switches::kEnableShowSavedCopyPrimary);
1475 } else if (group == "Secondary") {
1476 command_line->AppendSwitchASCII(
1477 switches::kShowSavedCopy,
1478 switches::kEnableShowSavedCopySecondary);
1483 MaybeAppendBlinkSettingsSwitchForFieldTrial(
1484 browser_command_line, command_line);
1486 // Please keep this in alphabetical order.
1487 static const char* const kSwitchNames[] = {
1488 #if defined(OS_ANDROID)
1489 autofill::switches::kDisableAccessorySuggestionView,
1490 autofill::switches::kEnableAccessorySuggestionView,
1491 #endif
1492 autofill::switches::kDisableFillOnAccountSelect,
1493 autofill::switches::kDisablePasswordGeneration,
1494 autofill::switches::kEnableFillOnAccountSelect,
1495 autofill::switches::kEnableFillOnAccountSelectNoHighlighting,
1496 autofill::switches::kEnablePasswordGeneration,
1497 autofill::switches::kEnableSingleClickAutofill,
1498 autofill::switches::kEnableSuggestionsWithSubstringMatch,
1499 autofill::switches::kIgnoreAutocompleteOffForAutofill,
1500 autofill::switches::kLocalHeuristicsOnlyForPasswordGeneration,
1501 #if defined(ENABLE_EXTENSIONS)
1502 extensions::switches::kAllowHTTPBackgroundPage,
1503 extensions::switches::kAllowLegacyExtensionManifests,
1504 extensions::switches::kEnableAppWindowControls,
1505 extensions::switches::kEnableEmbeddedExtensionOptions,
1506 extensions::switches::kEnableExperimentalExtensionApis,
1507 extensions::switches::kExtensionsOnChromeURLs,
1508 extensions::switches::kWhitelistedExtensionID,
1509 #endif
1510 switches::kAllowInsecureLocalhost,
1511 switches::kAppsGalleryURL,
1512 switches::kCloudPrintURL,
1513 switches::kCloudPrintXmppEndpoint,
1514 switches::kDisableBundledPpapiFlash,
1515 switches::kDisableCastStreamingHWEncoding,
1516 switches::kDisableJavaScriptHarmonyShipping,
1517 switches::kDisableNewBookmarkApps,
1518 #if defined(ENABLE_SPELLCHECK) && defined(OS_ANDROID)
1519 switches::kEnableAndroidSpellChecker,
1520 #endif
1521 switches::kEnableBenchmarking,
1522 switches::kEnableNaCl,
1523 #if !defined(DISABLE_NACL)
1524 switches::kEnableNaClDebug,
1525 switches::kEnableNaClNonSfiMode,
1526 switches::kEnablePNaClSubzero,
1527 #endif
1528 switches::kEnableNetBenchmarking,
1529 switches::kEnableNewBookmarkApps,
1530 switches::kJavaScriptHarmony,
1531 switches::kMessageLoopHistogrammer,
1532 switches::kPpapiFlashArgs,
1533 switches::kPpapiFlashPath,
1534 switches::kPpapiFlashVersion,
1535 switches::kProfilingAtStart,
1536 switches::kProfilingFile,
1537 switches::kProfilingFlush,
1538 switches::kUnsafelyTreatInsecureOriginAsSecure,
1539 translate::switches::kTranslateSecurityOrigin,
1542 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1543 arraysize(kSwitchNames));
1544 } else if (process_type == switches::kUtilityProcess) {
1545 #if defined(ENABLE_EXTENSIONS)
1546 static const char* const kSwitchNames[] = {
1547 extensions::switches::kAllowHTTPBackgroundPage,
1548 extensions::switches::kEnableExperimentalExtensionApis,
1549 extensions::switches::kExtensionsOnChromeURLs,
1550 extensions::switches::kWhitelistedExtensionID,
1553 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1554 arraysize(kSwitchNames));
1555 #endif
1556 } else if (process_type == switches::kPluginProcess) {
1557 #if defined(OS_CHROMEOS)
1558 static const char* const kSwitchNames[] = {
1559 chromeos::switches::kLoginProfile,
1562 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1563 arraysize(kSwitchNames));
1564 #endif
1565 } else if (process_type == switches::kZygoteProcess) {
1566 static const char* const kSwitchNames[] = {
1567 // Load (in-process) Pepper plugins in-process in the zygote pre-sandbox.
1568 switches::kDisableBundledPpapiFlash,
1569 #if !defined(DISABLE_NACL)
1570 switches::kEnableNaClDebug,
1571 switches::kEnableNaClNonSfiMode,
1572 switches::kEnablePNaClSubzero,
1573 switches::kNaClDangerousNoSandboxNonSfi,
1574 switches::kUseNaClHelperNonSfi,
1575 #endif
1576 switches::kPpapiFlashPath,
1577 switches::kPpapiFlashVersion,
1580 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1581 arraysize(kSwitchNames));
1582 } else if (process_type == switches::kGpuProcess) {
1583 // If --ignore-gpu-blacklist is passed in, don't send in crash reports
1584 // because GPU is expected to be unreliable.
1585 if (browser_command_line.HasSwitch(switches::kIgnoreGpuBlacklist) &&
1586 !command_line->HasSwitch(switches::kDisableBreakpad))
1587 command_line->AppendSwitch(switches::kDisableBreakpad);
1590 // The command line switch kEnableBenchmarking needs to be specified along
1591 // with the kEnableStatsTable switch to ensure that the stats table global
1592 // is initialized correctly.
1593 if (command_line->HasSwitch(switches::kEnableBenchmarking))
1594 DCHECK(command_line->HasSwitch(switches::kEnableStatsTable));
1597 std::string ChromeContentBrowserClient::GetApplicationLocale() {
1598 if (BrowserThread::CurrentlyOn(BrowserThread::IO))
1599 return g_io_thread_application_locale.Get();
1600 return g_browser_process->GetApplicationLocale();
1603 std::string ChromeContentBrowserClient::GetAcceptLangs(
1604 content::BrowserContext* context) {
1605 Profile* profile = Profile::FromBrowserContext(context);
1606 return profile->GetPrefs()->GetString(prefs::kAcceptLanguages);
1609 const gfx::ImageSkia* ChromeContentBrowserClient::GetDefaultFavicon() {
1610 ResourceBundle& rb = ResourceBundle::GetSharedInstance();
1611 return rb.GetNativeImageNamed(IDR_DEFAULT_FAVICON).ToImageSkia();
1614 bool ChromeContentBrowserClient::AllowAppCache(
1615 const GURL& manifest_url,
1616 const GURL& first_party,
1617 content::ResourceContext* context) {
1618 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1619 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1620 return io_data->GetCookieSettings()->
1621 IsSettingCookieAllowed(manifest_url, first_party);
1624 bool ChromeContentBrowserClient::AllowServiceWorker(
1625 const GURL& scope,
1626 const GURL& first_party_url,
1627 content::ResourceContext* context,
1628 int render_process_id,
1629 int render_frame_id) {
1630 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1632 #if defined(ENABLE_EXTENSIONS)
1633 // Check if this is an extension-related service worker, and, if so, if it's
1634 // allowed (this can return false if, e.g., the extension is disabled).
1635 // If it's not allowed, return immediately. We deliberately do *not* report
1636 // to the TabSpecificContentSettings, since the service worker is blocked
1637 // because of the extension, rather than because of the user's content
1638 // settings.
1639 if (!ChromeContentBrowserClientExtensionsPart::AllowServiceWorker(
1640 scope, first_party_url, context, render_process_id,
1641 render_frame_id)) {
1642 return false;
1644 #endif
1646 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1647 bool allow = io_data->GetCookieSettings()->IsSettingCookieAllowed(
1648 scope, first_party_url);
1650 // Record access to database for potential display in UI.
1651 // Only post the task if this is for a specific frame.
1652 if (render_process_id != -1 && render_frame_id != -1) {
1653 BrowserThread::PostTask(
1654 BrowserThread::UI, FROM_HERE,
1655 base::Bind(&TabSpecificContentSettings::ServiceWorkerAccessed,
1656 render_process_id, render_frame_id, scope, !allow));
1658 return allow;
1661 bool ChromeContentBrowserClient::AllowGetCookie(
1662 const GURL& url,
1663 const GURL& first_party,
1664 const net::CookieList& cookie_list,
1665 content::ResourceContext* context,
1666 int render_process_id,
1667 int render_frame_id) {
1668 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1669 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1670 bool allow = io_data->GetCookieSettings()->
1671 IsReadingCookieAllowed(url, first_party);
1673 BrowserThread::PostTask(
1674 BrowserThread::UI, FROM_HERE,
1675 base::Bind(&TabSpecificContentSettings::CookiesRead, render_process_id,
1676 render_frame_id, url, first_party, cookie_list, !allow));
1677 return allow;
1680 bool ChromeContentBrowserClient::AllowSetCookie(
1681 const GURL& url,
1682 const GURL& first_party,
1683 const std::string& cookie_line,
1684 content::ResourceContext* context,
1685 int render_process_id,
1686 int render_frame_id,
1687 net::CookieOptions* options) {
1688 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1689 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1690 content_settings::CookieSettings* cookie_settings =
1691 io_data->GetCookieSettings();
1692 bool allow = cookie_settings->IsSettingCookieAllowed(url, first_party);
1694 BrowserThread::PostTask(
1695 BrowserThread::UI, FROM_HERE,
1696 base::Bind(&TabSpecificContentSettings::CookieChanged, render_process_id,
1697 render_frame_id, url, first_party, cookie_line, *options,
1698 !allow));
1699 return allow;
1702 bool ChromeContentBrowserClient::AllowSaveLocalState(
1703 content::ResourceContext* context) {
1704 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1705 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1706 content_settings::CookieSettings* cookie_settings =
1707 io_data->GetCookieSettings();
1708 ContentSetting setting = cookie_settings->GetDefaultCookieSetting(NULL);
1710 // TODO(bauerb): Should we also disallow local state if the default is BLOCK?
1711 // Could we even support per-origin settings?
1712 return setting != CONTENT_SETTING_SESSION_ONLY;
1715 bool ChromeContentBrowserClient::AllowWorkerDatabase(
1716 const GURL& url,
1717 const base::string16& name,
1718 const base::string16& display_name,
1719 unsigned long estimated_size,
1720 content::ResourceContext* context,
1721 const std::vector<std::pair<int, int> >& render_frames) {
1722 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1723 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1724 content_settings::CookieSettings* cookie_settings =
1725 io_data->GetCookieSettings();
1726 bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1728 // Record access to database for potential display in UI.
1729 std::vector<std::pair<int, int> >::const_iterator i;
1730 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1731 BrowserThread::PostTask(
1732 BrowserThread::UI, FROM_HERE,
1733 base::Bind(&TabSpecificContentSettings::WebDatabaseAccessed,
1734 i->first, i->second, url, name, display_name, !allow));
1737 return allow;
1740 void ChromeContentBrowserClient::AllowWorkerFileSystem(
1741 const GURL& url,
1742 content::ResourceContext* context,
1743 const std::vector<std::pair<int, int> >& render_frames,
1744 base::Callback<void(bool)> callback) {
1745 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1746 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1747 content_settings::CookieSettings* cookie_settings =
1748 io_data->GetCookieSettings();
1749 bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1751 #if defined(ENABLE_EXTENSIONS)
1752 GuestPermissionRequestHelper(url, render_frames, callback, allow);
1753 #else
1754 FileSystemAccessed(url, render_frames, callback, allow);
1755 #endif
1758 #if defined(ENABLE_EXTENSIONS)
1759 void ChromeContentBrowserClient::GuestPermissionRequestHelper(
1760 const GURL& url,
1761 const std::vector<std::pair<int, int> >& render_frames,
1762 base::Callback<void(bool)> callback,
1763 bool allow) {
1764 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1765 std::vector<std::pair<int, int> >::const_iterator i;
1766 std::map<int, int> process_map;
1767 std::map<int, int>::const_iterator it;
1768 bool has_web_view_guest = false;
1769 // Record access to file system for potential display in UI.
1770 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1771 if (process_map.find(i->first) != process_map.end())
1772 continue;
1774 process_map.insert(std::pair<int, int>(i->first, i->second));
1776 if (extensions::WebViewRendererState::GetInstance()->IsGuest(i->first))
1777 has_web_view_guest = true;
1779 if (!has_web_view_guest) {
1780 FileSystemAccessed(url, render_frames, callback, allow);
1781 return;
1783 DCHECK_EQ(1U, process_map.size());
1784 it = process_map.begin();
1785 BrowserThread::PostTask(
1786 BrowserThread::UI,
1787 FROM_HERE,
1788 base::Bind(&ChromeContentBrowserClient::
1789 RequestFileSystemPermissionOnUIThread,
1790 it->first,
1791 it->second,
1792 url,
1793 allow,
1794 base::Bind(&ChromeContentBrowserClient::FileSystemAccessed,
1795 weak_factory_.GetWeakPtr(),
1796 url,
1797 render_frames,
1798 callback)));
1801 void ChromeContentBrowserClient::RequestFileSystemPermissionOnUIThread(
1802 int render_process_id,
1803 int render_frame_id,
1804 const GURL& url,
1805 bool allowed_by_default,
1806 const base::Callback<void(bool)>& callback) {
1807 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1808 extensions::WebViewPermissionHelper* web_view_permission_helper =
1809 extensions::WebViewPermissionHelper::FromFrameID(
1810 render_process_id, render_frame_id);
1811 web_view_permission_helper->RequestFileSystemPermission(url,
1812 allowed_by_default,
1813 callback);
1815 #endif
1817 void ChromeContentBrowserClient::FileSystemAccessed(
1818 const GURL& url,
1819 const std::vector<std::pair<int, int> >& render_frames,
1820 base::Callback<void(bool)> callback,
1821 bool allow) {
1822 // Record access to file system for potential display in UI.
1823 std::vector<std::pair<int, int> >::const_iterator i;
1824 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1825 BrowserThread::PostTask(
1826 BrowserThread::UI,
1827 FROM_HERE,
1828 base::Bind(&TabSpecificContentSettings::FileSystemAccessed,
1829 i->first, i->second, url, !allow));
1831 callback.Run(allow);
1834 bool ChromeContentBrowserClient::AllowWorkerIndexedDB(
1835 const GURL& url,
1836 const base::string16& name,
1837 content::ResourceContext* context,
1838 const std::vector<std::pair<int, int> >& render_frames) {
1839 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1840 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1841 content_settings::CookieSettings* cookie_settings =
1842 io_data->GetCookieSettings();
1843 bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1845 // Record access to IndexedDB for potential display in UI.
1846 std::vector<std::pair<int, int> >::const_iterator i;
1847 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1848 BrowserThread::PostTask(
1849 BrowserThread::UI, FROM_HERE,
1850 base::Bind(&TabSpecificContentSettings::IndexedDBAccessed,
1851 i->first, i->second, url, name, !allow));
1854 return allow;
1857 #if defined(ENABLE_WEBRTC)
1858 bool ChromeContentBrowserClient::AllowWebRTCIdentityCache(
1859 const GURL& url,
1860 const GURL& first_party_url,
1861 content::ResourceContext* context) {
1862 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1863 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1864 content_settings::CookieSettings* cookie_settings =
1865 io_data->GetCookieSettings();
1866 return cookie_settings->IsReadingCookieAllowed(url, first_party_url) &&
1867 cookie_settings->IsSettingCookieAllowed(url, first_party_url);
1869 #endif // defined(ENABLE_WEBRTC)
1871 net::URLRequestContext*
1872 ChromeContentBrowserClient::OverrideRequestContextForURL(
1873 const GURL& url, content::ResourceContext* context) {
1874 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1875 #if defined(ENABLE_EXTENSIONS)
1876 if (url.SchemeIs(extensions::kExtensionScheme)) {
1877 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1878 return io_data->extensions_request_context();
1880 #endif
1882 return NULL;
1885 QuotaPermissionContext*
1886 ChromeContentBrowserClient::CreateQuotaPermissionContext() {
1887 return new ChromeQuotaPermissionContext();
1890 void ChromeContentBrowserClient::AllowCertificateError(
1891 int render_process_id,
1892 int render_frame_id,
1893 int cert_error,
1894 const net::SSLInfo& ssl_info,
1895 const GURL& request_url,
1896 ResourceType resource_type,
1897 bool overridable,
1898 bool strict_enforcement,
1899 bool expired_previous_decision,
1900 const base::Callback<void(bool)>& callback,
1901 content::CertificateRequestResultType* result) {
1902 if (resource_type != content::RESOURCE_TYPE_MAIN_FRAME) {
1903 // A sub-resource has a certificate error. The user doesn't really
1904 // have a context for making the right decision, so block the
1905 // request hard, without an info bar to allow showing the insecure
1906 // content.
1907 *result = content::CERTIFICATE_REQUEST_RESULT_TYPE_DENY;
1908 return;
1911 // If the tab is being prerendered, cancel the prerender and the request.
1912 content::RenderFrameHost* render_frame_host =
1913 content::RenderFrameHost::FromID(render_process_id, render_frame_id);
1914 WebContents* tab = WebContents::FromRenderFrameHost(render_frame_host);
1915 if (!tab) {
1916 NOTREACHED();
1917 return;
1920 prerender::PrerenderContents* prerender_contents =
1921 prerender::PrerenderContents::FromWebContents(tab);
1922 if (prerender_contents) {
1923 prerender_contents->Destroy(prerender::FINAL_STATUS_SSL_ERROR);
1924 *result = content::CERTIFICATE_REQUEST_RESULT_TYPE_CANCEL;
1925 return;
1928 // Otherwise, display an SSL blocking page. The interstitial page takes
1929 // ownership of ssl_blocking_page.
1930 int options_mask = 0;
1931 if (overridable)
1932 options_mask |= SSLBlockingPage::OVERRIDABLE;
1933 if (strict_enforcement)
1934 options_mask |= SSLBlockingPage::STRICT_ENFORCEMENT;
1935 if (expired_previous_decision)
1936 options_mask |= SSLBlockingPage::EXPIRED_BUT_PREVIOUSLY_ALLOWED;
1938 SafeBrowsingService* safe_browsing_service =
1939 g_browser_process->safe_browsing_service();
1940 scoped_ptr<SafeBrowsingSSLCertReporter> cert_reporter(
1941 new SafeBrowsingSSLCertReporter(safe_browsing_service
1942 ? safe_browsing_service->ui_manager()
1943 : nullptr));
1944 SSLErrorHandler::HandleSSLError(tab, cert_error, ssl_info, request_url,
1945 options_mask, cert_reporter.Pass(), callback);
1948 void ChromeContentBrowserClient::SelectClientCertificate(
1949 content::WebContents* web_contents,
1950 net::SSLCertRequestInfo* cert_request_info,
1951 scoped_ptr<content::ClientCertificateDelegate> delegate) {
1952 prerender::PrerenderContents* prerender_contents =
1953 prerender::PrerenderContents::FromWebContents(web_contents);
1954 if (prerender_contents) {
1955 prerender_contents->Destroy(
1956 prerender::FINAL_STATUS_SSL_CLIENT_CERTIFICATE_REQUESTED);
1957 return;
1960 GURL requesting_url("https://" + cert_request_info->host_and_port.ToString());
1961 DCHECK(requesting_url.is_valid())
1962 << "Invalid URL string: https://"
1963 << cert_request_info->host_and_port.ToString();
1965 Profile* profile =
1966 Profile::FromBrowserContext(web_contents->GetBrowserContext());
1967 scoped_ptr<base::Value> filter =
1968 HostContentSettingsMapFactory::GetForProfile(profile)->GetWebsiteSetting(
1969 requesting_url,
1970 requesting_url,
1971 CONTENT_SETTINGS_TYPE_AUTO_SELECT_CERTIFICATE,
1972 std::string(),
1973 NULL);
1975 if (filter.get()) {
1976 // Try to automatically select a client certificate.
1977 if (filter->IsType(base::Value::TYPE_DICTIONARY)) {
1978 base::DictionaryValue* filter_dict =
1979 static_cast<base::DictionaryValue*>(filter.get());
1981 const std::vector<scoped_refptr<net::X509Certificate> >&
1982 all_client_certs = cert_request_info->client_certs;
1983 for (size_t i = 0; i < all_client_certs.size(); ++i) {
1984 if (CertMatchesFilter(*all_client_certs[i].get(), *filter_dict)) {
1985 // Use the first certificate that is matched by the filter.
1986 delegate->ContinueWithCertificate(all_client_certs[i].get());
1987 return;
1990 } else {
1991 NOTREACHED();
1995 chrome::ShowSSLClientCertificateSelector(web_contents, cert_request_info,
1996 delegate.Pass());
1999 void ChromeContentBrowserClient::AddCertificate(
2000 net::CertificateMimeType cert_type,
2001 const void* cert_data,
2002 size_t cert_size,
2003 int render_process_id,
2004 int render_frame_id) {
2005 chrome::SSLAddCertificate(cert_type, cert_data, cert_size,
2006 render_process_id, render_frame_id);
2009 content::MediaObserver* ChromeContentBrowserClient::GetMediaObserver() {
2010 return MediaCaptureDevicesDispatcher::GetInstance();
2013 content::PlatformNotificationService*
2014 ChromeContentBrowserClient::GetPlatformNotificationService() {
2015 #if defined(ENABLE_NOTIFICATIONS)
2016 return PlatformNotificationServiceImpl::GetInstance();
2017 #else
2018 NOTIMPLEMENTED();
2019 return NULL;
2020 #endif
2023 bool ChromeContentBrowserClient::CanCreateWindow(
2024 const GURL& opener_url,
2025 const GURL& opener_top_level_frame_url,
2026 const GURL& source_origin,
2027 WindowContainerType container_type,
2028 const GURL& target_url,
2029 const content::Referrer& referrer,
2030 WindowOpenDisposition disposition,
2031 const WebWindowFeatures& features,
2032 bool user_gesture,
2033 bool opener_suppressed,
2034 content::ResourceContext* context,
2035 int render_process_id,
2036 int opener_render_view_id,
2037 int opener_render_frame_id,
2038 bool* no_javascript_access) {
2039 DCHECK_CURRENTLY_ON(BrowserThread::IO);
2041 *no_javascript_access = false;
2043 // If the opener is trying to create a background window but doesn't have
2044 // the appropriate permission, fail the attempt.
2045 if (container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {
2046 #if defined(ENABLE_EXTENSIONS)
2047 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
2048 InfoMap* map = io_data->GetExtensionInfoMap();
2049 if (!map->SecurityOriginHasAPIPermission(
2050 source_origin,
2051 render_process_id,
2052 APIPermission::kBackground)) {
2053 return false;
2056 // Note: this use of GetExtensionOrAppByURL is safe but imperfect. It may
2057 // return a recently installed Extension even if this CanCreateWindow call
2058 // was made by an old copy of the page in a normal web process. That's ok,
2059 // because the permission check above would have caused an early return
2060 // already. We must use the full URL to find hosted apps, though, and not
2061 // just the origin.
2062 const Extension* extension =
2063 map->extensions().GetExtensionOrAppByURL(opener_url);
2064 if (extension && !extensions::BackgroundInfo::AllowJSAccess(extension))
2065 *no_javascript_access = true;
2066 #endif
2068 return true;
2071 #if defined(ENABLE_EXTENSIONS)
2072 if (extensions::WebViewRendererState::GetInstance()->IsGuest(
2073 render_process_id))
2074 return true;
2075 #endif
2077 HostContentSettingsMap* content_settings =
2078 ProfileIOData::FromResourceContext(context)->GetHostContentSettingsMap();
2079 BlockedWindowParams blocked_params(target_url,
2080 referrer,
2081 disposition,
2082 features,
2083 user_gesture,
2084 opener_suppressed,
2085 render_process_id,
2086 opener_render_frame_id);
2088 if (!user_gesture &&
2089 !base::CommandLine::ForCurrentProcess()->HasSwitch(
2090 switches::kDisablePopupBlocking)) {
2091 if (content_settings->GetContentSetting(opener_top_level_frame_url,
2092 opener_top_level_frame_url,
2093 CONTENT_SETTINGS_TYPE_POPUPS,
2094 std::string()) !=
2095 CONTENT_SETTING_ALLOW) {
2096 BrowserThread::PostTask(BrowserThread::UI,
2097 FROM_HERE,
2098 base::Bind(&HandleBlockedPopupOnUIThread,
2099 blocked_params));
2100 return false;
2104 #if defined(OS_ANDROID)
2105 if (SingleTabModeTabHelper::IsRegistered(render_process_id,
2106 opener_render_view_id)) {
2107 BrowserThread::PostTask(BrowserThread::UI,
2108 FROM_HERE,
2109 base::Bind(&HandleSingleTabModeBlockOnUIThread,
2110 blocked_params));
2111 return false;
2113 #endif
2115 return true;
2118 void ChromeContentBrowserClient::ResourceDispatcherHostCreated() {
2119 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2120 return g_browser_process->ResourceDispatcherHostCreated();
2123 content::SpeechRecognitionManagerDelegate*
2124 ChromeContentBrowserClient::CreateSpeechRecognitionManagerDelegate() {
2125 return new speech::ChromeSpeechRecognitionManagerDelegate();
2128 net::NetLog* ChromeContentBrowserClient::GetNetLog() {
2129 return g_browser_process->net_log();
2132 AccessTokenStore* ChromeContentBrowserClient::CreateAccessTokenStore() {
2133 return new ChromeAccessTokenStore();
2136 bool ChromeContentBrowserClient::IsFastShutdownPossible() {
2137 return true;
2140 void ChromeContentBrowserClient::OverrideWebkitPrefs(
2141 RenderViewHost* rvh, WebPreferences* web_prefs) {
2142 Profile* profile = Profile::FromBrowserContext(
2143 rvh->GetProcess()->GetBrowserContext());
2144 PrefService* prefs = profile->GetPrefs();
2146 // Fill per-script font preferences. These are not registered on Android
2147 // - http://crbug.com/308033.
2148 #if !defined(OS_ANDROID)
2149 FontFamilyCache::FillFontFamilyMap(profile,
2150 prefs::kWebKitStandardFontFamilyMap,
2151 &web_prefs->standard_font_family_map);
2152 FontFamilyCache::FillFontFamilyMap(profile,
2153 prefs::kWebKitFixedFontFamilyMap,
2154 &web_prefs->fixed_font_family_map);
2155 FontFamilyCache::FillFontFamilyMap(profile,
2156 prefs::kWebKitSerifFontFamilyMap,
2157 &web_prefs->serif_font_family_map);
2158 FontFamilyCache::FillFontFamilyMap(profile,
2159 prefs::kWebKitSansSerifFontFamilyMap,
2160 &web_prefs->sans_serif_font_family_map);
2161 FontFamilyCache::FillFontFamilyMap(profile,
2162 prefs::kWebKitCursiveFontFamilyMap,
2163 &web_prefs->cursive_font_family_map);
2164 FontFamilyCache::FillFontFamilyMap(profile,
2165 prefs::kWebKitFantasyFontFamilyMap,
2166 &web_prefs->fantasy_font_family_map);
2167 FontFamilyCache::FillFontFamilyMap(profile,
2168 prefs::kWebKitPictographFontFamilyMap,
2169 &web_prefs->pictograph_font_family_map);
2170 #endif
2172 web_prefs->default_font_size =
2173 prefs->GetInteger(prefs::kWebKitDefaultFontSize);
2174 web_prefs->default_fixed_font_size =
2175 prefs->GetInteger(prefs::kWebKitDefaultFixedFontSize);
2176 web_prefs->minimum_font_size =
2177 prefs->GetInteger(prefs::kWebKitMinimumFontSize);
2178 web_prefs->minimum_logical_font_size =
2179 prefs->GetInteger(prefs::kWebKitMinimumLogicalFontSize);
2181 web_prefs->default_encoding = prefs->GetString(prefs::kDefaultCharset);
2183 web_prefs->javascript_can_open_windows_automatically =
2184 prefs->GetBoolean(prefs::kWebKitJavascriptCanOpenWindowsAutomatically);
2185 web_prefs->dom_paste_enabled =
2186 prefs->GetBoolean(prefs::kWebKitDomPasteEnabled);
2187 web_prefs->tabs_to_links = prefs->GetBoolean(prefs::kWebkitTabsToLinks);
2189 if (!prefs->GetBoolean(prefs::kWebKitJavascriptEnabled))
2190 web_prefs->javascript_enabled = false;
2191 if (!prefs->GetBoolean(prefs::kWebKitWebSecurityEnabled))
2192 web_prefs->web_security_enabled = false;
2193 if (!prefs->GetBoolean(prefs::kWebKitPluginsEnabled))
2194 web_prefs->plugins_enabled = false;
2195 web_prefs->loads_images_automatically =
2196 prefs->GetBoolean(prefs::kWebKitLoadsImagesAutomatically);
2198 if (prefs->GetBoolean(prefs::kDisable3DAPIs))
2199 web_prefs->experimental_webgl_enabled = false;
2201 web_prefs->allow_displaying_insecure_content =
2202 prefs->GetBoolean(prefs::kWebKitAllowDisplayingInsecureContent);
2203 web_prefs->allow_running_insecure_content =
2204 prefs->GetBoolean(prefs::kWebKitAllowRunningInsecureContent);
2205 #if defined(OS_ANDROID)
2206 web_prefs->font_scale_factor =
2207 static_cast<float>(prefs->GetDouble(prefs::kWebKitFontScaleFactor));
2208 web_prefs->device_scale_adjustment = GetDeviceScaleAdjustment();
2209 web_prefs->force_enable_zoom =
2210 prefs->GetBoolean(prefs::kWebKitForceEnableZoom);
2211 #endif
2213 #if defined(OS_ANDROID)
2214 web_prefs->password_echo_enabled =
2215 prefs->GetBoolean(prefs::kWebKitPasswordEchoEnabled);
2216 #else
2217 web_prefs->password_echo_enabled = browser_defaults::kPasswordEchoEnabled;
2218 #endif
2220 web_prefs->asynchronous_spell_checking_enabled = true;
2221 web_prefs->unified_textchecker_enabled = true;
2223 web_prefs->uses_universal_detector =
2224 prefs->GetBoolean(prefs::kWebKitUsesUniversalDetector);
2225 web_prefs->text_areas_are_resizable =
2226 prefs->GetBoolean(prefs::kWebKitTextAreasAreResizable);
2227 web_prefs->hyperlink_auditing_enabled =
2228 prefs->GetBoolean(prefs::kEnableHyperlinkAuditing);
2230 #if defined(ENABLE_EXTENSIONS)
2231 std::string image_animation_policy =
2232 prefs->GetString(prefs::kAnimationPolicy);
2233 if (image_animation_policy == kAnimationPolicyOnce)
2234 web_prefs->animation_policy =
2235 content::IMAGE_ANIMATION_POLICY_ANIMATION_ONCE;
2236 else if (image_animation_policy == kAnimationPolicyNone)
2237 web_prefs->animation_policy = content::IMAGE_ANIMATION_POLICY_NO_ANIMATION;
2238 else
2239 web_prefs->animation_policy = content::IMAGE_ANIMATION_POLICY_ALLOWED;
2240 #endif
2242 // Make sure we will set the default_encoding with canonical encoding name.
2243 web_prefs->default_encoding =
2244 CharacterEncoding::GetCanonicalEncodingNameByAliasName(
2245 web_prefs->default_encoding);
2246 if (web_prefs->default_encoding.empty()) {
2247 prefs->ClearPref(prefs::kDefaultCharset);
2248 web_prefs->default_encoding = prefs->GetString(prefs::kDefaultCharset);
2250 DCHECK(!web_prefs->default_encoding.empty());
2252 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2253 switches::kEnablePotentiallyAnnoyingSecurityFeatures)) {
2254 web_prefs->disable_reading_from_canvas = true;
2255 web_prefs->strict_mixed_content_checking = true;
2256 web_prefs->strict_powerful_feature_restrictions = true;
2259 for (size_t i = 0; i < extra_parts_.size(); ++i)
2260 extra_parts_[i]->OverrideWebkitPrefs(rvh, web_prefs);
2263 void ChromeContentBrowserClient::BrowserURLHandlerCreated(
2264 BrowserURLHandler* handler) {
2265 for (size_t i = 0; i < extra_parts_.size(); ++i)
2266 extra_parts_[i]->BrowserURLHandlerCreated(handler);
2268 // about: handler. Must come before chrome: handler, since it will
2269 // rewrite about: urls to chrome: URLs and then expect chrome: to
2270 // actually handle them. Also relies on a preliminary fixup phase.
2271 handler->SetFixupHandler(&FixupBrowserAboutURL);
2272 handler->AddHandlerPair(&WillHandleBrowserAboutURL,
2273 BrowserURLHandler::null_handler());
2275 #if defined(OS_ANDROID)
2276 // Handler to rewrite chrome://newtab on Android.
2277 handler->AddHandlerPair(&chrome::android::HandleAndroidNativePageURL,
2278 BrowserURLHandler::null_handler());
2279 #else
2280 // Handler to rewrite chrome://newtab for InstantExtended.
2281 handler->AddHandlerPair(&search::HandleNewTabURLRewrite,
2282 &search::HandleNewTabURLReverseRewrite);
2283 #endif
2285 // chrome: & friends.
2286 handler->AddHandlerPair(&HandleWebUI, &HandleWebUIReverse);
2289 void ChromeContentBrowserClient::ClearCache(RenderFrameHost* rfh) {
2290 Profile* profile = Profile::FromBrowserContext(
2291 rfh->GetSiteInstance()->GetProcess()->GetBrowserContext());
2292 BrowsingDataRemover* remover =
2293 BrowsingDataRemover::CreateForUnboundedRange(profile);
2294 remover->Remove(BrowsingDataRemover::REMOVE_CACHE,
2295 BrowsingDataHelper::UNPROTECTED_WEB);
2296 // BrowsingDataRemover takes care of deleting itself when done.
2299 void ChromeContentBrowserClient::ClearCookies(RenderFrameHost* rfh) {
2300 Profile* profile = Profile::FromBrowserContext(
2301 rfh->GetSiteInstance()->GetProcess()->GetBrowserContext());
2302 BrowsingDataRemover* remover =
2303 BrowsingDataRemover::CreateForUnboundedRange(profile);
2304 int remove_mask = BrowsingDataRemover::REMOVE_SITE_DATA;
2305 remover->Remove(remove_mask, BrowsingDataHelper::UNPROTECTED_WEB);
2306 // BrowsingDataRemover takes care of deleting itself when done.
2309 base::FilePath ChromeContentBrowserClient::GetDefaultDownloadDirectory() {
2310 return DownloadPrefs::GetDefaultDownloadDirectory();
2313 std::string ChromeContentBrowserClient::GetDefaultDownloadName() {
2314 return l10n_util::GetStringUTF8(IDS_DEFAULT_DOWNLOAD_FILENAME);
2317 base::FilePath ChromeContentBrowserClient::GetShaderDiskCacheDirectory() {
2318 base::FilePath user_data_dir;
2319 PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
2320 DCHECK(!user_data_dir.empty());
2321 return user_data_dir.Append(FILE_PATH_LITERAL("ShaderCache"));
2324 void ChromeContentBrowserClient::DidCreatePpapiPlugin(
2325 content::BrowserPpapiHost* browser_host) {
2326 #if defined(ENABLE_PLUGINS)
2327 ChromeContentBrowserClientPluginsPart::DidCreatePpapiPlugin(browser_host);
2328 #endif
2331 content::BrowserPpapiHost*
2332 ChromeContentBrowserClient::GetExternalBrowserPpapiHost(
2333 int plugin_process_id) {
2334 #if !defined(DISABLE_NACL)
2335 content::BrowserChildProcessHostIterator iter(PROCESS_TYPE_NACL_LOADER);
2336 while (!iter.Done()) {
2337 nacl::NaClProcessHost* host = static_cast<nacl::NaClProcessHost*>(
2338 iter.GetDelegate());
2339 if (host->process() &&
2340 host->process()->GetData().id == plugin_process_id) {
2341 // Found the plugin.
2342 return host->browser_ppapi_host();
2344 ++iter;
2346 #endif
2347 return NULL;
2350 bool ChromeContentBrowserClient::AllowPepperSocketAPI(
2351 content::BrowserContext* browser_context,
2352 const GURL& url,
2353 bool private_api,
2354 const content::SocketPermissionRequest* params) {
2355 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
2356 return ChromeContentBrowserClientPluginsPart::AllowPepperSocketAPI(
2357 browser_context, url, private_api, params, allowed_socket_origins_);
2358 #else
2359 return false;
2360 #endif
2363 ui::SelectFilePolicy* ChromeContentBrowserClient::CreateSelectFilePolicy(
2364 WebContents* web_contents) {
2365 return new ChromeSelectFilePolicy(web_contents);
2368 void ChromeContentBrowserClient::GetAdditionalAllowedSchemesForFileSystem(
2369 std::vector<std::string>* additional_allowed_schemes) {
2370 ContentBrowserClient::GetAdditionalAllowedSchemesForFileSystem(
2371 additional_allowed_schemes);
2372 additional_allowed_schemes->push_back(content::kChromeDevToolsScheme);
2373 additional_allowed_schemes->push_back(content::kChromeUIScheme);
2374 for (size_t i = 0; i < extra_parts_.size(); ++i) {
2375 extra_parts_[i]->GetAdditionalAllowedSchemesForFileSystem(
2376 additional_allowed_schemes);
2380 void ChromeContentBrowserClient::GetURLRequestAutoMountHandlers(
2381 std::vector<storage::URLRequestAutoMountHandler>* handlers) {
2382 for (size_t i = 0; i < extra_parts_.size(); ++i)
2383 extra_parts_[i]->GetURLRequestAutoMountHandlers(handlers);
2386 void ChromeContentBrowserClient::GetAdditionalFileSystemBackends(
2387 content::BrowserContext* browser_context,
2388 const base::FilePath& storage_partition_path,
2389 ScopedVector<storage::FileSystemBackend>* additional_backends) {
2390 #if defined(OS_CHROMEOS)
2391 storage::ExternalMountPoints* external_mount_points =
2392 content::BrowserContext::GetMountPoints(browser_context);
2393 DCHECK(external_mount_points);
2394 chromeos::FileSystemBackend* backend = new chromeos::FileSystemBackend(
2395 new drive::FileSystemBackendDelegate,
2396 new chromeos::file_system_provider::BackendDelegate,
2397 new chromeos::MTPFileSystemBackendDelegate(storage_partition_path),
2398 external_mount_points,
2399 storage::ExternalMountPoints::GetSystemInstance());
2400 backend->AddSystemMountPoints();
2401 DCHECK(backend->CanHandleType(storage::kFileSystemTypeExternal));
2402 additional_backends->push_back(backend);
2403 #endif
2405 for (size_t i = 0; i < extra_parts_.size(); ++i) {
2406 extra_parts_[i]->GetAdditionalFileSystemBackends(
2407 browser_context, storage_partition_path, additional_backends);
2411 #if defined(OS_ANDROID)
2412 void ChromeContentBrowserClient::GetAdditionalMappedFilesForChildProcess(
2413 const base::CommandLine& command_line,
2414 int child_process_id,
2415 FileDescriptorInfo* mappings,
2416 std::map<int, base::MemoryMappedFile::Region>* regions) {
2417 int fd = ui::GetMainAndroidPackFd(
2418 &(*regions)[kAndroidUIResourcesPakDescriptor]);
2419 mappings->Share(kAndroidUIResourcesPakDescriptor, fd);
2421 fd = ui::GetCommonResourcesPackFd(
2422 &(*regions)[kAndroidChrome100PercentPakDescriptor]);
2423 mappings->Share(kAndroidChrome100PercentPakDescriptor, fd);
2425 fd = ui::GetLocalePackFd(&(*regions)[kAndroidLocalePakDescriptor]);
2426 mappings->Share(kAndroidLocalePakDescriptor, fd);
2428 if (breakpad::IsCrashReporterEnabled()) {
2429 base::File file =
2430 breakpad::CrashDumpManager::GetInstance()->CreateMinidumpFile(
2431 child_process_id);
2432 if (file.IsValid()) {
2433 mappings->Transfer(kAndroidMinidumpDescriptor,
2434 base::ScopedFD(file.TakePlatformFile()));
2435 } else {
2436 LOG(ERROR) << "Failed to create file for minidump, crash reporting will "
2437 "be disabled for this process.";
2441 base::FilePath app_data_path;
2442 PathService::Get(base::DIR_ANDROID_APP_DATA, &app_data_path);
2443 DCHECK(!app_data_path.empty());
2445 #elif defined(OS_POSIX) && !defined(OS_MACOSX)
2446 void ChromeContentBrowserClient::GetAdditionalMappedFilesForChildProcess(
2447 const base::CommandLine& command_line,
2448 int child_process_id,
2449 FileDescriptorInfo* mappings) {
2450 int crash_signal_fd = GetCrashSignalFD(command_line);
2451 if (crash_signal_fd >= 0) {
2452 mappings->Share(kCrashDumpSignal, crash_signal_fd);
2455 #endif // defined(OS_ANDROID)
2457 #if defined(OS_WIN)
2458 const wchar_t* ChromeContentBrowserClient::GetResourceDllName() {
2459 return chrome::kBrowserResourcesDll;
2462 base::string16 ChromeContentBrowserClient::GetAppContainerSidForSandboxType(
2463 int sandbox_type) const {
2464 base::string16 sid;
2466 #if defined(GOOGLE_CHROME_BUILD)
2467 const version_info::Channel channel = chrome::GetChannel();
2469 // It's possible to have a SxS installation running at the same time as a
2470 // non-SxS so isolate them from each other.
2471 if (channel == version_info::Channel::CANARY) {
2472 sid.assign(
2473 L"S-1-15-2-3251537155-1984446955-2931258699-841473695-1938553385-"
2474 L"924012150-");
2475 } else {
2476 sid.assign(
2477 L"S-1-15-2-3251537155-1984446955-2931258699-841473695-1938553385-"
2478 L"924012149-");
2480 #else
2481 sid.assign(
2482 L"S-1-15-2-3251537155-1984446955-2931258699-841473695-1938553385-"
2483 L"924012148-");
2484 #endif
2486 // TODO(wfh): Add support for more process types here. crbug.com/499523
2487 switch (sandbox_type) {
2488 case content::SANDBOX_TYPE_RENDERER:
2489 return sid + L"129201922";
2490 case content::SANDBOX_TYPE_UTILITY:
2491 return base::string16();
2492 case content::SANDBOX_TYPE_GPU:
2493 return base::string16();
2494 case content::SANDBOX_TYPE_PPAPI:
2495 return sid + L"129201925";
2496 #if !defined(DISABLE_NACL)
2497 case PROCESS_TYPE_NACL_LOADER:
2498 return base::string16();
2499 case PROCESS_TYPE_NACL_BROKER:
2500 return base::string16();
2501 #endif
2504 // Should never reach here.
2505 CHECK(0);
2506 return base::string16();
2509 void ChromeContentBrowserClient::PreSpawnRenderer(
2510 sandbox::TargetPolicy* policy,
2511 bool* success) {
2512 // This code is duplicated in nacl_exe_win_64.cc.
2513 // Allow the server side of a pipe restricted to the "chrome.nacl."
2514 // namespace so that it cannot impersonate other system or other chrome
2515 // service pipes.
2516 sandbox::ResultCode result = policy->AddRule(
2517 sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
2518 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
2519 L"\\\\.\\pipe\\chrome.nacl.*");
2520 if (result != sandbox::SBOX_ALL_OK) {
2521 *success = false;
2522 return;
2525 // Renderers need to send named pipe handles and shared memory
2526 // segment handles to NaCl loader processes.
2527 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
2528 sandbox::TargetPolicy::HANDLES_DUP_ANY,
2529 L"File");
2530 if (result != sandbox::SBOX_ALL_OK) {
2531 *success = false;
2532 return;
2535 #endif
2537 void ChromeContentBrowserClient::RegisterFrameMojoShellServices(
2538 content::ServiceRegistry* registry,
2539 content::RenderFrameHost* render_frame_host) {
2540 #if defined(OS_CHROMEOS)
2541 registry->AddService(
2542 base::Bind(&chromeos::attestation::PlatformVerificationImpl::Create,
2543 render_frame_host));
2544 #endif
2545 #if !defined(OS_ANDROID) && !defined(OS_IOS)
2546 registry->AddService(
2547 base::Bind(&WebUSBPermissionProvider::Create, render_frame_host));
2548 #endif
2551 void ChromeContentBrowserClient::RegisterInProcessMojoApplications(
2552 StaticMojoApplicationMap* apps) {
2553 #if !defined(OS_ANDROID) && !defined(OS_IOS)
2554 apps->insert(std::make_pair(GURL(device::kDevicesMojoAppUrl),
2555 base::Bind(&device::DevicesAppFactory::CreateApp,
2556 base::ThreadTaskRunnerHandle::Get())));
2557 #endif
2560 void ChromeContentBrowserClient::OpenURL(
2561 content::BrowserContext* browser_context,
2562 const content::OpenURLParams& params,
2563 const base::Callback<void(content::WebContents*)>& callback) {
2564 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2566 #if !defined(OS_ANDROID) && !defined(OS_IOS)
2567 chrome::NavigateParams nav_params(
2568 Profile::FromBrowserContext(browser_context),
2569 params.url,
2570 params.transition);
2571 FillNavigateParamsFromOpenURLParams(&nav_params, params);
2572 nav_params.user_gesture = params.user_gesture;
2574 Navigate(&nav_params);
2575 callback.Run(nav_params.target_contents);
2576 #elif defined(OS_ANDROID)
2577 service_tab_launcher::ServiceTabLauncher::GetInstance()->LaunchTab(
2578 browser_context, params, callback);
2579 #else
2580 NOTIMPLEMENTED();
2581 #endif
2584 content::PresentationServiceDelegate*
2585 ChromeContentBrowserClient::GetPresentationServiceDelegate(
2586 content::WebContents* web_contents) {
2587 #if defined(ENABLE_MEDIA_ROUTER)
2588 if (switches::MediaRouterEnabled() &&
2589 !web_contents->GetBrowserContext()->IsOffTheRecord()) {
2590 return media_router::PresentationServiceDelegateImpl::
2591 GetOrCreateForWebContents(web_contents);
2593 #endif
2594 return nullptr;
2597 void ChromeContentBrowserClient::RecordURLMetric(const std::string& metric,
2598 const GURL& url) {
2599 if (url.is_valid()) {
2600 rappor::SampleDomainAndRegistryFromGURL(g_browser_process->rappor_service(),
2601 metric, url);
2605 ScopedVector<content::NavigationThrottle>
2606 ChromeContentBrowserClient::CreateThrottlesForNavigation(
2607 content::NavigationHandle* handle) {
2608 ScopedVector<content::NavigationThrottle> throttles;
2609 #if defined(OS_ANDROID)
2610 // TODO(davidben): This is insufficient to integrate with prerender properly.
2611 // https://crbug.com/370595
2612 prerender::PrerenderContents* prerender_contents =
2613 prerender::PrerenderContents::FromWebContents(handle->GetWebContents());
2614 if (!prerender_contents && handle->IsInMainFrame()) {
2615 throttles.push_back(
2616 navigation_interception::InterceptNavigationDelegate::CreateThrottleFor(
2617 handle)
2618 .Pass());
2620 #else
2621 if (handle->IsInMainFrame()) {
2622 // Redirect some navigations to apps that have registered matching URL
2623 // handlers ('url_handlers' in the manifest).
2624 scoped_ptr<content::NavigationThrottle> url_to_app_throttle =
2625 AppUrlRedirector::MaybeCreateThrottleFor(handle);
2626 if (url_to_app_throttle)
2627 throttles.push_back(url_to_app_throttle.Pass());
2629 #endif
2630 return throttles.Pass();
2633 content::DevToolsManagerDelegate*
2634 ChromeContentBrowserClient::GetDevToolsManagerDelegate() {
2635 return new ChromeDevToolsManagerDelegate();
2638 content::TracingDelegate* ChromeContentBrowserClient::GetTracingDelegate() {
2639 #if !defined(OS_ANDROID)
2640 return new ChromeTracingDelegate();
2641 #else
2642 return nullptr;
2643 #endif
2646 bool ChromeContentBrowserClient::IsPluginAllowedToCallRequestOSFileHandle(
2647 content::BrowserContext* browser_context,
2648 const GURL& url) {
2649 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
2650 return ChromeContentBrowserClientPluginsPart::
2651 IsPluginAllowedToCallRequestOSFileHandle(browser_context, url,
2652 allowed_file_handle_origins_);
2653 #else
2654 return false;
2655 #endif
2658 bool ChromeContentBrowserClient::IsPluginAllowedToUseDevChannelAPIs(
2659 content::BrowserContext* browser_context,
2660 const GURL& url) {
2661 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
2662 return ChromeContentBrowserClientPluginsPart::
2663 IsPluginAllowedToUseDevChannelAPIs(browser_context, url,
2664 allowed_dev_channel_origins_);
2665 #else
2666 return false;
2667 #endif
2670 void ChromeContentBrowserClient::OverridePageVisibilityState(
2671 RenderFrameHost* render_frame_host,
2672 blink::WebPageVisibilityState* visibility_state) {
2673 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2675 WebContents* web_contents =
2676 WebContents::FromRenderFrameHost(render_frame_host);
2677 DCHECK(web_contents);
2679 Profile* profile =
2680 Profile::FromBrowserContext(web_contents->GetBrowserContext());
2681 prerender::PrerenderManager* prerender_manager =
2682 prerender::PrerenderManagerFactory::GetForProfile(profile);
2683 if (prerender_manager &&
2684 prerender_manager->IsWebContentsPrerendering(web_contents, nullptr)) {
2685 *visibility_state = blink::WebPageVisibilityStatePrerender;
2689 #if defined(ENABLE_WEBRTC)
2690 void ChromeContentBrowserClient::MaybeCopyDisableWebRtcEncryptionSwitch(
2691 base::CommandLine* to_command_line,
2692 const base::CommandLine& from_command_line,
2693 version_info::Channel channel) {
2694 #if defined(OS_ANDROID)
2695 const version_info::Channel kMaxDisableEncryptionChannel =
2696 version_info::Channel::BETA;
2697 #else
2698 const version_info::Channel kMaxDisableEncryptionChannel =
2699 version_info::Channel::DEV;
2700 #endif
2701 if (channel <= kMaxDisableEncryptionChannel) {
2702 static const char* const kWebRtcDevSwitchNames[] = {
2703 switches::kDisableWebRtcEncryption,
2705 to_command_line->CopySwitchesFrom(from_command_line,
2706 kWebRtcDevSwitchNames,
2707 arraysize(kWebRtcDevSwitchNames));
2710 #endif // defined(ENABLE_WEBRTC)