Update broken references to image assets
[chromium-blink-merge.git] / chrome / browser / chrome_content_browser_client.cc
blob17b00c74b490b1b7c99d0d141c5121db6c4de03a
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/browser_about_handler.h"
28 #include "chrome/browser/browser_process.h"
29 #include "chrome/browser/browser_shutdown.h"
30 #include "chrome/browser/browsing_data/browsing_data_helper.h"
31 #include "chrome/browser/browsing_data/browsing_data_remover.h"
32 #include "chrome/browser/character_encoding.h"
33 #include "chrome/browser/chrome_content_browser_client_parts.h"
34 #include "chrome/browser/chrome_net_benchmarking_message_filter.h"
35 #include "chrome/browser/chrome_quota_permission_context.h"
36 #include "chrome/browser/content_settings/cookie_settings_factory.h"
37 #include "chrome/browser/content_settings/tab_specific_content_settings.h"
38 #include "chrome/browser/defaults.h"
39 #include "chrome/browser/devtools/chrome_devtools_manager_delegate.h"
40 #include "chrome/browser/download/download_prefs.h"
41 #include "chrome/browser/font_family_cache.h"
42 #include "chrome/browser/geolocation/chrome_access_token_store.h"
43 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
44 #include "chrome/browser/metrics/chrome_browser_main_extra_parts_metrics.h"
45 #include "chrome/browser/nacl_host/nacl_browser_delegate_impl.h"
46 #include "chrome/browser/net/chrome_net_log.h"
47 #include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings.h"
48 #include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings_factory.h"
49 #include "chrome/browser/notifications/platform_notification_service_impl.h"
50 #include "chrome/browser/platform_util.h"
51 #include "chrome/browser/prerender/prerender_final_status.h"
52 #include "chrome/browser/prerender/prerender_manager.h"
53 #include "chrome/browser/prerender/prerender_manager_factory.h"
54 #include "chrome/browser/prerender/prerender_message_filter.h"
55 #include "chrome/browser/printing/printing_message_filter.h"
56 #include "chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.h"
57 #include "chrome/browser/profiles/profile.h"
58 #include "chrome/browser/profiles/profile_io_data.h"
59 #include "chrome/browser/renderer_host/chrome_render_message_filter.h"
60 #include "chrome/browser/renderer_host/pepper/chrome_browser_pepper_host_factory.h"
61 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
62 #include "chrome/browser/safe_browsing/ui_manager.h"
63 #include "chrome/browser/search/instant_service.h"
64 #include "chrome/browser/search/instant_service_factory.h"
65 #include "chrome/browser/search/search.h"
66 #include "chrome/browser/search_engines/search_provider_install_state_message_filter.h"
67 #include "chrome/browser/speech/chrome_speech_recognition_manager_delegate.h"
68 #include "chrome/browser/speech/tts_controller.h"
69 #include "chrome/browser/speech/tts_message_filter.h"
70 #include "chrome/browser/ssl/ssl_add_certificate.h"
71 #include "chrome/browser/ssl/ssl_blocking_page.h"
72 #include "chrome/browser/ssl/ssl_cert_reporter.h"
73 #include "chrome/browser/ssl/ssl_client_certificate_selector.h"
74 #include "chrome/browser/ssl/ssl_error_handler.h"
75 #include "chrome/browser/sync_file_system/local/sync_file_system_backend.h"
76 #include "chrome/browser/tab_contents/tab_util.h"
77 #include "chrome/browser/tracing/chrome_tracing_delegate.h"
78 #include "chrome/browser/ui/blocked_content/blocked_window_params.h"
79 #include "chrome/browser/ui/blocked_content/popup_blocker_tab_helper.h"
80 #include "chrome/browser/ui/chrome_select_file_policy.h"
81 #include "chrome/browser/ui/sync/sync_promo_ui.h"
82 #include "chrome/browser/ui/tab_contents/chrome_web_contents_view_delegate.h"
83 #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
84 #include "chrome/common/channel_info.h"
85 #include "chrome/common/chrome_constants.h"
86 #include "chrome/common/chrome_paths.h"
87 #include "chrome/common/chrome_switches.h"
88 #include "chrome/common/env_vars.h"
89 #include "chrome/common/logging_chrome.h"
90 #include "chrome/common/pepper_permission_util.h"
91 #include "chrome/common/pref_names.h"
92 #include "chrome/common/render_messages.h"
93 #include "chrome/common/url_constants.h"
94 #include "chrome/grit/generated_resources.h"
95 #include "chrome/installer/util/google_update_settings.h"
96 #include "chromeos/chromeos_constants.h"
97 #include "components/cdm/browser/cdm_message_filter_android.h"
98 #include "components/cloud_devices/common/cloud_devices_switches.h"
99 #include "components/content_settings/core/browser/content_settings_utils.h"
100 #include "components/content_settings/core/browser/cookie_settings.h"
101 #include "components/content_settings/core/browser/host_content_settings_map.h"
102 #include "components/content_settings/core/common/content_settings.h"
103 #include "components/data_reduction_proxy/content/browser/data_reduction_proxy_message_filter.h"
104 #include "components/dom_distiller/core/url_constants.h"
105 #include "components/google/core/browser/google_util.h"
106 #include "components/metrics/client_info.h"
107 #include "components/pref_registry/pref_registry_syncable.h"
108 #include "components/rappor/rappor_utils.h"
109 #include "components/signin/core/common/profile_management_switches.h"
110 #include "components/translate/core/common/translate_switches.h"
111 #include "components/url_formatter/url_fixer.h"
112 #include "components/variations/variations_associated_data.h"
113 #include "components/version_info/version_info.h"
114 #include "content/public/browser/browser_child_process_host.h"
115 #include "content/public/browser/browser_main_parts.h"
116 #include "content/public/browser/browser_ppapi_host.h"
117 #include "content/public/browser/browser_thread.h"
118 #include "content/public/browser/browser_url_handler.h"
119 #include "content/public/browser/child_process_data.h"
120 #include "content/public/browser/child_process_security_policy.h"
121 #include "content/public/browser/client_certificate_delegate.h"
122 #include "content/public/browser/render_frame_host.h"
123 #include "content/public/browser/render_process_host.h"
124 #include "content/public/browser/render_view_host.h"
125 #include "content/public/browser/resource_context.h"
126 #include "content/public/browser/site_instance.h"
127 #include "content/public/browser/web_contents.h"
128 #include "content/public/common/child_process_host.h"
129 #include "content/public/common/content_descriptors.h"
130 #include "content/public/common/sandbox_type.h"
131 #include "content/public/common/service_registry.h"
132 #include "content/public/common/url_utils.h"
133 #include "content/public/common/web_preferences.h"
134 #include "device/devices_app/public/cpp/constants.h"
135 #include "device/devices_app/public/cpp/devices_app_factory.h"
136 #include "gin/v8_initializer.h"
137 #include "mojo/application/public/cpp/application_delegate.h"
138 #include "net/base/mime_util.h"
139 #include "net/cookies/canonical_cookie.h"
140 #include "net/cookies/cookie_options.h"
141 #include "net/ssl/ssl_cert_request_info.h"
142 #include "ppapi/host/ppapi_host.h"
143 #include "storage/browser/fileapi/external_mount_points.h"
144 #include "ui/base/l10n/l10n_util.h"
145 #include "ui/base/resource/resource_bundle.h"
146 #include "ui/resources/grit/ui_resources.h"
148 #if defined(OS_WIN)
149 #include "base/win/windows_version.h"
150 #include "chrome/browser/chrome_browser_main_win.h"
151 #include "sandbox/win/src/sandbox_policy.h"
152 #elif defined(OS_MACOSX)
153 #include "chrome/browser/chrome_browser_main_mac.h"
154 #elif defined(OS_CHROMEOS)
155 #include "chrome/browser/chromeos/attestation/platform_verification_impl.h"
156 #include "chrome/browser/chromeos/chrome_browser_main_chromeos.h"
157 #include "chrome/browser/chromeos/drive/fileapi/file_system_backend_delegate.h"
158 #include "chrome/browser/chromeos/file_manager/app_id.h"
159 #include "chrome/browser/chromeos/file_system_provider/fileapi/backend_delegate.h"
160 #include "chrome/browser/chromeos/fileapi/file_system_backend.h"
161 #include "chrome/browser/chromeos/fileapi/mtp_file_system_backend_delegate.h"
162 #include "chrome/browser/chromeos/login/startup_utils.h"
163 #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
164 #include "chrome/browser/chromeos/system/input_device_settings.h"
165 #include "chromeos/chromeos_switches.h"
166 #include "components/user_manager/user_manager.h"
167 #elif defined(OS_LINUX)
168 #include "chrome/browser/chrome_browser_main_linux.h"
169 #elif defined(OS_ANDROID)
170 #include "chrome/browser/android/new_tab_page_url_handler.h"
171 #include "chrome/browser/android/webapps/single_tab_mode_tab_helper.h"
172 #include "chrome/browser/chrome_browser_main_android.h"
173 #include "chrome/common/descriptors_android.h"
174 #include "components/crash/browser/crash_dump_manager_android.h"
175 #include "components/service_tab_launcher/browser/android/service_tab_launcher.h"
176 #include "ui/base/resource/resource_bundle_android.h"
177 #elif defined(OS_POSIX)
178 #include "chrome/browser/chrome_browser_main_posix.h"
179 #endif
181 #if defined(OS_POSIX) && !defined(OS_MACOSX)
182 #include "base/debug/leak_annotations.h"
183 #include "components/crash/app/breakpad_linux.h"
184 #include "components/crash/browser/crash_handler_host_linux.h"
185 #endif
187 #if defined(OS_ANDROID)
188 #include "ui/base/ui_base_paths.h"
189 #include "ui/gfx/android/device_display_info.h"
190 #endif
192 #if defined(TOOLKIT_VIEWS)
193 #include "chrome/browser/ui/views/chrome_browser_main_extra_parts_views.h"
194 #endif
196 #if defined(USE_ASH)
197 #include "chrome/browser/ui/views/ash/chrome_browser_main_extra_parts_ash.h"
198 #endif
200 #if defined(USE_AURA)
201 #include "chrome/browser/ui/aura/chrome_browser_main_extra_parts_aura.h"
202 #endif
204 #if defined(USE_X11)
205 #include "chrome/browser/chrome_browser_main_extra_parts_x11.h"
206 #endif
208 #if defined(ENABLE_CAPTIVE_PORTAL_DETECTION)
209 #include "chrome/browser/captive_portal/captive_portal_tab_helper.h"
210 #endif
212 #if !defined(DISABLE_NACL)
213 #include "components/nacl/browser/nacl_browser.h"
214 #include "components/nacl/browser/nacl_host_message_filter.h"
215 #include "components/nacl/browser/nacl_process_host.h"
216 #include "components/nacl/common/nacl_process_type.h"
217 #include "components/nacl/common/nacl_switches.h"
218 #endif
220 #if defined(ENABLE_EXTENSIONS)
221 #include "chrome/browser/accessibility/animation_policy_prefs.h"
222 #include "chrome/browser/extensions/chrome_content_browser_client_extensions_part.h"
223 #include "chrome/browser/media/cast_transport_host_filter.h"
224 #include "chrome/browser/speech/extension_api/tts_engine_extension_api.h"
225 #include "components/guest_view/browser/guest_view_base.h"
226 #include "components/guest_view/browser/guest_view_manager.h"
227 #include "extensions/browser/extension_registry.h"
228 #include "extensions/browser/extension_util.h"
229 #include "extensions/browser/guest_view/web_view/web_view_guest.h"
230 #include "extensions/browser/guest_view/web_view/web_view_permission_helper.h"
231 #include "extensions/browser/guest_view/web_view/web_view_renderer_state.h"
232 #include "extensions/common/constants.h"
233 #include "extensions/common/extension.h"
234 #include "extensions/common/extension_set.h"
235 #include "extensions/common/manifest_handlers/background_info.h"
236 #include "extensions/common/manifest_handlers/shared_module_info.h"
237 #include "extensions/common/permissions/permissions_data.h"
238 #include "extensions/common/permissions/socket_permission.h"
239 #include "extensions/common/switches.h"
240 #endif
242 #if defined(ENABLE_PLUGINS)
243 #include "chrome/browser/plugins/chrome_content_browser_client_plugins_part.h"
244 #endif
246 #if defined(ENABLE_SPELLCHECK)
247 #include "chrome/browser/spellchecker/spellcheck_message_filter.h"
248 #endif
250 #if defined(USE_BROWSER_SPELLCHECKER)
251 #include "chrome/browser/spellchecker/spellcheck_message_filter_platform.h"
252 #endif
254 #if defined(ENABLE_WEBRTC)
255 #include "chrome/browser/media/webrtc_logging_handler_host.h"
256 #endif
258 #if defined(ENABLE_MEDIA_ROUTER)
259 #include "chrome/browser/media/router/presentation_service_delegate_impl.h"
260 #endif
262 using base::FileDescriptor;
263 using blink::WebWindowFeatures;
264 using content::AccessTokenStore;
265 using content::BrowserThread;
266 using content::BrowserURLHandler;
267 using content::ChildProcessSecurityPolicy;
268 using content::QuotaPermissionContext;
269 using content::RenderFrameHost;
270 using content::RenderViewHost;
271 using content::ResourceType;
272 using content::SiteInstance;
273 using content::WebContents;
274 using content::WebPreferences;
275 using message_center::NotifierId;
277 #if defined(OS_POSIX)
278 using content::FileDescriptorInfo;
279 #endif
281 #if defined(ENABLE_EXTENSIONS)
282 using extensions::APIPermission;
283 using extensions::ChromeContentBrowserClientExtensionsPart;
284 using extensions::Extension;
285 using extensions::InfoMap;
286 using extensions::Manifest;
287 #endif
289 #if defined(ENABLE_PLUGINS)
290 using plugins::ChromeContentBrowserClientPluginsPart;
291 #endif
293 namespace {
295 // Cached version of the locale so we can return the locale on the I/O
296 // thread.
297 base::LazyInstance<std::string> g_io_thread_application_locale;
299 #if defined(ENABLE_PLUGINS)
300 // TODO(teravest): Add renderer-side API-specific checking for these APIs so
301 // that blanket permission isn't granted to all dev channel APIs for these.
302 // http://crbug.com/386743
303 const char* const kPredefinedAllowedDevChannelOrigins[] = {
304 "6EAED1924DB611B6EEF2A664BD077BE7EAD33B8F", // see crbug.com/383937
305 "4EB74897CB187C7633357C2FE832E0AD6A44883A" // see crbug.com/383937
308 const char* const kPredefinedAllowedFileHandleOrigins[] = {
309 "6EAED1924DB611B6EEF2A664BD077BE7EAD33B8F", // see crbug.com/234789
310 "4EB74897CB187C7633357C2FE832E0AD6A44883A" // see crbug.com/234789
313 const char* const kPredefinedAllowedSocketOrigins[] = {
314 "okddffdblfhhnmhodogpojmfkjmhinfp", // Test SSH Client
315 "pnhechapfaindjhompbnflcldabbghjo", // HTerm App (SSH Client)
316 "bglhmjfplikpjnfoegeomebmfnkjomhe", // see crbug.com/122126
317 "gbchcmhmhahfdphkhkmpfmihenigjmpp", // Chrome Remote Desktop
318 "kgngmbheleoaphbjbaiobfdepmghbfah", // Pre-release Chrome Remote Desktop
319 "odkaodonbgfohohmklejpjiejmcipmib", // Dogfood Chrome Remote Desktop
320 "ojoimpklfciegopdfgeenehpalipignm", // Chromoting canary
321 "cbkkbcmdlboombapidmoeolnmdacpkch", // see crbug.com/129089
322 "hhnbmknkdabfoieppbbljkhkfjcmcbjh", // see crbug.com/134099
323 "mablfbjkhmhkmefkjjacnbaikjkipphg", // see crbug.com/134099
324 "pdeelgamlgannhelgoegilelnnojegoh", // see crbug.com/134099
325 "cabapfdbkniadpollkckdnedaanlciaj", // see crbug.com/134099
326 "mapljbgnjledlpdmlchihnmeclmefbba", // see crbug.com/134099
327 "ghbfeebgmiidnnmeobbbaiamklmpbpii", // see crbug.com/134099
328 "jdfhpkjeckflbbleddjlpimecpbjdeep", // see crbug.com/142514
329 "iabmpiboiopbgfabjmgeedhcmjenhbla", // see crbug.com/165080
330 "B7CF8A292249681AF81771650BA4CEEAF19A4560", // see crbug.com/165080
331 "7525AF4F66763A70A883C4700529F647B470E4D2", // see crbug.com/238084
332 "0B549507088E1564D672F7942EB87CA4DAD73972", // see crbug.com/238084
333 "864288364E239573E777D3E0E36864E590E95C74" // see crbug.com/238084
335 #endif
337 // Returns a copy of the given url with its host set to given host and path set
338 // to given path. Other parts of the url will be the same.
339 GURL ReplaceURLHostAndPath(const GURL& url,
340 const std::string& host,
341 const std::string& path) {
342 url::Replacements<char> replacements;
343 replacements.SetHost(host.c_str(), url::Component(0, host.length()));
344 replacements.SetPath(path.c_str(), url::Component(0, path.length()));
345 return url.ReplaceComponents(replacements);
348 // Maps "foo://bar/baz/" to "foo://chrome/bar/baz/".
349 GURL AddUberHost(const GURL& url) {
350 const std::string uber_host = chrome::kChromeUIUberHost;
351 const std::string new_path = url.host() + url.path();
353 return ReplaceURLHostAndPath(url, uber_host, new_path);
356 // If url->host() is "chrome" and url->path() has characters other than the
357 // first slash, changes the url from "foo://chrome/bar/" to "foo://bar/" and
358 // returns true. Otherwise returns false.
359 bool RemoveUberHost(GURL* url) {
360 if (url->host() != chrome::kChromeUIUberHost)
361 return false;
363 if (url->path().empty() || url->path() == "/")
364 return false;
366 const std::string old_path = url->path();
368 const std::string::size_type separator = old_path.find('/', 1);
369 std::string new_host;
370 std::string new_path;
371 if (separator == std::string::npos) {
372 new_host = old_path.substr(1);
373 } else {
374 new_host = old_path.substr(1, separator - 1);
375 new_path = old_path.substr(separator);
378 // Do not allow URLs with paths empty before the first slash since we can't
379 // have an empty host. (e.g "foo://chrome//")
380 if (new_host.empty())
381 return false;
383 *url = ReplaceURLHostAndPath(*url, new_host, new_path);
385 DCHECK(url->is_valid());
387 return true;
390 // Handles rewriting Web UI URLs.
391 bool HandleWebUI(GURL* url, content::BrowserContext* browser_context) {
392 // Do not handle special URLs such as "about:foo"
393 if (!url->host().empty()) {
394 const GURL chrome_url = AddUberHost(*url);
396 // Handle valid "chrome://chrome/foo" URLs so the reverse handler will
397 // be called.
398 if (ChromeWebUIControllerFactory::GetInstance()->UseWebUIForURL(
399 browser_context, chrome_url))
400 return true;
403 if (!ChromeWebUIControllerFactory::GetInstance()->UseWebUIForURL(
404 browser_context, *url))
405 return false;
407 #if defined(OS_CHROMEOS)
408 // Special case : in ChromeOS in Guest mode bookmarks and history are
409 // disabled for security reasons. New tab page explains the reasons, so
410 // we redirect user to new tab page.
411 if (user_manager::UserManager::Get()->IsLoggedInAsGuest()) {
412 if (url->SchemeIs(content::kChromeUIScheme) &&
413 (url->DomainIs(chrome::kChromeUIBookmarksHost) ||
414 url->DomainIs(chrome::kChromeUIHistoryHost))) {
415 // Rewrite with new tab URL
416 *url = GURL(chrome::kChromeUINewTabURL);
419 #endif
421 return true;
424 // Reverse URL handler for Web UI. Maps "chrome://chrome/foo/" to
425 // "chrome://foo/".
426 bool HandleWebUIReverse(GURL* url, content::BrowserContext* browser_context) {
427 if (!url->is_valid() || !url->SchemeIs(content::kChromeUIScheme))
428 return false;
430 return RemoveUberHost(url);
433 bool CertMatchesFilter(const net::X509Certificate& cert,
434 const base::DictionaryValue& filter) {
435 // TODO(markusheintz): This is the minimal required filter implementation.
436 // Implement a better matcher.
438 // An empty filter matches any client certificate since no requirements are
439 // specified at all.
440 if (filter.empty())
441 return true;
443 std::string common_name;
444 if (filter.GetString("ISSUER.CN", &common_name) &&
445 (cert.issuer().common_name == common_name)) {
446 return true;
448 return false;
451 #if defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_MACOSX)
452 breakpad::CrashHandlerHostLinux* CreateCrashHandlerHost(
453 const std::string& process_type) {
454 base::FilePath dumps_path;
455 PathService::Get(chrome::DIR_CRASH_DUMPS, &dumps_path);
457 ANNOTATE_SCOPED_MEMORY_LEAK;
458 bool upload = (getenv(env_vars::kHeadless) == NULL);
459 breakpad::CrashHandlerHostLinux* crash_handler =
460 new breakpad::CrashHandlerHostLinux(process_type, dumps_path, upload);
461 crash_handler->StartUploaderThread();
462 return crash_handler;
466 int GetCrashSignalFD(const base::CommandLine& command_line) {
467 // Extensions have the same process type as renderers.
468 if (command_line.HasSwitch(extensions::switches::kExtensionProcess)) {
469 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
470 if (!crash_handler)
471 crash_handler = CreateCrashHandlerHost("extension");
472 return crash_handler->GetDeathSignalSocket();
475 std::string process_type =
476 command_line.GetSwitchValueASCII(switches::kProcessType);
478 if (process_type == switches::kRendererProcess) {
479 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
480 if (!crash_handler)
481 crash_handler = CreateCrashHandlerHost(process_type);
482 return crash_handler->GetDeathSignalSocket();
485 if (process_type == switches::kPluginProcess) {
486 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
487 if (!crash_handler)
488 crash_handler = CreateCrashHandlerHost(process_type);
489 return crash_handler->GetDeathSignalSocket();
492 if (process_type == switches::kPpapiPluginProcess) {
493 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
494 if (!crash_handler)
495 crash_handler = CreateCrashHandlerHost(process_type);
496 return crash_handler->GetDeathSignalSocket();
499 if (process_type == switches::kGpuProcess) {
500 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
501 if (!crash_handler)
502 crash_handler = CreateCrashHandlerHost(process_type);
503 return crash_handler->GetDeathSignalSocket();
506 return -1;
508 #endif // defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_MACOSX)
510 void SetApplicationLocaleOnIOThread(const std::string& locale) {
511 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
512 g_io_thread_application_locale.Get() = locale;
515 void HandleBlockedPopupOnUIThread(const BlockedWindowParams& params) {
516 RenderFrameHost* render_frame_host = RenderFrameHost::FromID(
517 params.render_process_id(), params.opener_render_frame_id());
518 if (!render_frame_host)
519 return;
520 WebContents* tab = WebContents::FromRenderFrameHost(render_frame_host);
521 // The tab might already have navigated away. We only need to do this check
522 // for main frames, since the RenderFrameHost for a subframe opener will have
523 // already been deleted if the main frame navigates away.
524 if (!tab ||
525 (!render_frame_host->GetParent() &&
526 tab->GetMainFrame() != render_frame_host))
527 return;
529 prerender::PrerenderContents* prerender_contents =
530 prerender::PrerenderContents::FromWebContents(tab);
531 if (prerender_contents) {
532 prerender_contents->Destroy(prerender::FINAL_STATUS_CREATE_NEW_WINDOW);
533 return;
536 PopupBlockerTabHelper* popup_helper =
537 PopupBlockerTabHelper::FromWebContents(tab);
538 if (!popup_helper)
539 return;
540 popup_helper->AddBlockedPopup(params);
543 // An implementation of the SSLCertReporter interface used by
544 // SSLErrorHandler. Uses the SafeBrowsing UI manager to send invalid
545 // certificate reports.
546 class SafeBrowsingSSLCertReporter : public SSLCertReporter {
547 public:
548 explicit SafeBrowsingSSLCertReporter(
549 const scoped_refptr<SafeBrowsingUIManager>& safe_browsing_ui_manager)
550 : safe_browsing_ui_manager_(safe_browsing_ui_manager) {}
551 ~SafeBrowsingSSLCertReporter() override {}
553 // SSLCertReporter implementation
554 void ReportInvalidCertificateChain(
555 const std::string& serialized_report) override {
556 if (safe_browsing_ui_manager_) {
557 safe_browsing_ui_manager_->ReportInvalidCertificateChain(
558 serialized_report, base::Bind(&base::DoNothing));
562 private:
563 const scoped_refptr<SafeBrowsingUIManager> safe_browsing_ui_manager_;
566 #if defined(OS_ANDROID)
568 void HandleSingleTabModeBlockOnUIThread(const BlockedWindowParams& params) {
569 WebContents* web_contents = tab_util::GetWebContentsByFrameID(
570 params.render_process_id(), params.opener_render_frame_id());
571 if (!web_contents)
572 return;
574 SingleTabModeTabHelper::FromWebContents(web_contents)->HandleOpenUrl(params);
577 float GetDeviceScaleAdjustment() {
578 static const float kMinFSM = 1.05f;
579 static const int kWidthForMinFSM = 320;
580 static const float kMaxFSM = 1.3f;
581 static const int kWidthForMaxFSM = 800;
583 gfx::DeviceDisplayInfo info;
584 int minWidth = info.GetSmallestDIPWidth();
586 if (minWidth <= kWidthForMinFSM)
587 return kMinFSM;
588 if (minWidth >= kWidthForMaxFSM)
589 return kMaxFSM;
591 // The font scale multiplier varies linearly between kMinFSM and kMaxFSM.
592 float ratio = static_cast<float>(minWidth - kWidthForMinFSM) /
593 (kWidthForMaxFSM - kWidthForMinFSM);
594 return ratio * (kMaxFSM - kMinFSM) + kMinFSM;
597 #endif // defined(OS_ANDROID)
599 #if defined(ENABLE_EXTENSIONS)
600 // By default, JavaScript and images are enabled in guest content.
601 void GetGuestViewDefaultContentSettingRules(
602 bool incognito,
603 RendererContentSettingRules* rules) {
604 rules->image_rules.push_back(
605 ContentSettingPatternSource(ContentSettingsPattern::Wildcard(),
606 ContentSettingsPattern::Wildcard(),
607 CONTENT_SETTING_ALLOW,
608 std::string(),
609 incognito));
611 rules->script_rules.push_back(
612 ContentSettingPatternSource(ContentSettingsPattern::Wildcard(),
613 ContentSettingsPattern::Wildcard(),
614 CONTENT_SETTING_ALLOW,
615 std::string(),
616 incognito));
618 #endif // defined(ENABLE_EXTENSIONS)
620 } // namespace
622 namespace chrome {
624 ChromeContentBrowserClient::ChromeContentBrowserClient()
626 weak_factory_(this) {
627 #if defined(ENABLE_PLUGINS)
628 for (size_t i = 0; i < arraysize(kPredefinedAllowedDevChannelOrigins); ++i)
629 allowed_dev_channel_origins_.insert(kPredefinedAllowedDevChannelOrigins[i]);
630 for (size_t i = 0; i < arraysize(kPredefinedAllowedFileHandleOrigins); ++i)
631 allowed_file_handle_origins_.insert(kPredefinedAllowedFileHandleOrigins[i]);
632 for (size_t i = 0; i < arraysize(kPredefinedAllowedSocketOrigins); ++i)
633 allowed_socket_origins_.insert(kPredefinedAllowedSocketOrigins[i]);
635 extra_parts_.push_back(new ChromeContentBrowserClientPluginsPart);
636 #endif
638 #if !defined(OS_ANDROID)
639 TtsExtensionEngine* tts_extension_engine = TtsExtensionEngine::GetInstance();
640 TtsController::GetInstance()->SetTtsEngineDelegate(tts_extension_engine);
641 #endif
643 #if defined(ENABLE_EXTENSIONS)
644 extra_parts_.push_back(new ChromeContentBrowserClientExtensionsPart);
645 #endif
648 ChromeContentBrowserClient::~ChromeContentBrowserClient() {
649 for (int i = static_cast<int>(extra_parts_.size()) - 1; i >= 0; --i)
650 delete extra_parts_[i];
651 extra_parts_.clear();
654 // static
655 void ChromeContentBrowserClient::RegisterProfilePrefs(
656 user_prefs::PrefRegistrySyncable* registry) {
657 registry->RegisterBooleanPref(prefs::kDisable3DAPIs, false);
658 registry->RegisterBooleanPref(prefs::kEnableHyperlinkAuditing, true);
659 registry->RegisterListPref(prefs::kEnableDeprecatedWebPlatformFeatures);
662 // static
663 void ChromeContentBrowserClient::SetApplicationLocale(
664 const std::string& locale) {
665 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
667 // This object is guaranteed to outlive all threads so we don't have to
668 // worry about the lack of refcounting and can just post as Unretained.
670 // The common case is that this function is called early in Chrome startup
671 // before any threads are created (it will also be called later if the user
672 // changes the pref). In this case, there will be no threads created and
673 // posting will fail. When there are no threads, we can just set the string
674 // without worrying about threadsafety.
675 if (!BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
676 base::Bind(&SetApplicationLocaleOnIOThread, locale))) {
677 g_io_thread_application_locale.Get() = locale;
681 content::BrowserMainParts* ChromeContentBrowserClient::CreateBrowserMainParts(
682 const content::MainFunctionParams& parameters) {
683 ChromeBrowserMainParts* main_parts;
684 // Construct the Main browser parts based on the OS type.
685 #if defined(OS_WIN)
686 main_parts = new ChromeBrowserMainPartsWin(parameters);
687 #elif defined(OS_MACOSX)
688 main_parts = new ChromeBrowserMainPartsMac(parameters);
689 #elif defined(OS_CHROMEOS)
690 main_parts = new chromeos::ChromeBrowserMainPartsChromeos(parameters);
691 #elif defined(OS_LINUX)
692 main_parts = new ChromeBrowserMainPartsLinux(parameters);
693 #elif defined(OS_ANDROID)
694 main_parts = new ChromeBrowserMainPartsAndroid(parameters);
695 #elif defined(OS_POSIX)
696 main_parts = new ChromeBrowserMainPartsPosix(parameters);
697 #else
698 NOTREACHED();
699 main_parts = new ChromeBrowserMainParts(parameters);
700 #endif
702 chrome::AddProfilesExtraParts(main_parts);
704 // Construct additional browser parts. Stages are called in the order in
705 // which they are added.
706 #if defined(TOOLKIT_VIEWS)
707 main_parts->AddParts(new ChromeBrowserMainExtraPartsViews());
708 #endif
710 // TODO(oshima): Athena on chrome currently requires USE_ASH to build.
711 // We should reduce the dependency as much as possible.
712 #if defined(USE_ASH)
713 main_parts->AddParts(new ChromeBrowserMainExtraPartsAsh());
714 #endif
716 #if defined(USE_AURA)
717 main_parts->AddParts(new ChromeBrowserMainExtraPartsAura());
718 #endif
720 #if defined(USE_X11)
721 main_parts->AddParts(new ChromeBrowserMainExtraPartsX11());
722 #endif
724 chrome::AddMetricsExtraParts(main_parts);
726 return main_parts;
729 void ChromeContentBrowserClient::PostAfterStartupTask(
730 const tracked_objects::Location& from_here,
731 const scoped_refptr<base::TaskRunner>& task_runner,
732 const base::Closure& task) {
733 AfterStartupTaskUtils::PostTask(from_here, task_runner, task);
736 std::string ChromeContentBrowserClient::GetStoragePartitionIdForSite(
737 content::BrowserContext* browser_context,
738 const GURL& site) {
739 std::string partition_id;
741 // The partition ID for webview guest processes is the string value of its
742 // SiteInstance URL - "chrome-guest://app_id/persist?partition".
743 if (site.SchemeIs(content::kGuestScheme)) {
744 partition_id = site.spec();
745 } else if (!switches::IsEnableWebviewBasedSignin() &&
746 site.GetOrigin().spec() == kChromeUIChromeSigninURL) {
747 // The non-webview Chrome signin page has an embedded iframe of extension
748 // and web content, thus it must be isolated from other webUI pages.
749 partition_id = site.GetOrigin().spec();
752 DCHECK(IsValidStoragePartitionId(browser_context, partition_id));
753 return partition_id;
756 bool ChromeContentBrowserClient::IsValidStoragePartitionId(
757 content::BrowserContext* browser_context,
758 const std::string& partition_id) {
759 // The default ID is empty and is always valid.
760 if (partition_id.empty())
761 return true;
763 return GURL(partition_id).is_valid();
766 void ChromeContentBrowserClient::GetStoragePartitionConfigForSite(
767 content::BrowserContext* browser_context,
768 const GURL& site,
769 bool can_be_default,
770 std::string* partition_domain,
771 std::string* partition_name,
772 bool* in_memory) {
773 // Default to the browser-wide storage partition and override based on |site|
774 // below.
775 partition_domain->clear();
776 partition_name->clear();
777 *in_memory = false;
779 bool success = false;
780 #if defined(ENABLE_EXTENSIONS)
781 success = extensions::WebViewGuest::GetGuestPartitionConfigForSite(
782 site, partition_domain, partition_name, in_memory);
784 if (!success && site.SchemeIs(extensions::kExtensionScheme)) {
785 // If |can_be_default| is false, the caller is stating that the |site|
786 // should be parsed as if it had isolated storage. In particular it is
787 // important to NOT check ExtensionService for the is_storage_isolated()
788 // attribute because this code path is run during Extension uninstall
789 // to do cleanup after the Extension has already been unloaded from the
790 // ExtensionService.
791 bool is_isolated = !can_be_default;
792 if (can_be_default) {
793 if (extensions::util::SiteHasIsolatedStorage(site, browser_context))
794 is_isolated = true;
797 if (is_isolated) {
798 CHECK(site.has_host());
799 // For extensions with isolated storage, the the host of the |site| is
800 // the |partition_domain|. The |in_memory| and |partition_name| are only
801 // used in guest schemes so they are cleared here.
802 *partition_domain = site.host();
803 *in_memory = false;
804 partition_name->clear();
806 success = true;
808 #endif
810 if (!success && (!switches::IsEnableWebviewBasedSignin() &&
811 site.GetOrigin().spec() == kChromeUIChromeSigninURL)) {
812 // The non-webview Chrome signin page has an embedded iframe of extension
813 // and web content, thus it must be isolated from other webUI pages.
814 *partition_domain = chrome::kChromeUIChromeSigninHost;
817 // Assert that if |can_be_default| is false, the code above must have found a
818 // non-default partition. If this fails, the caller has a serious logic
819 // error about which StoragePartition they expect to be in and it is not
820 // safe to continue.
821 CHECK(can_be_default || !partition_domain->empty());
824 content::WebContentsViewDelegate*
825 ChromeContentBrowserClient::GetWebContentsViewDelegate(
826 content::WebContents* web_contents) {
827 return chrome::CreateWebContentsViewDelegate(web_contents);
830 void ChromeContentBrowserClient::RenderProcessWillLaunch(
831 content::RenderProcessHost* host) {
832 int id = host->GetID();
833 Profile* profile = Profile::FromBrowserContext(host->GetBrowserContext());
834 net::URLRequestContextGetter* context =
835 profile->GetRequestContextForRenderProcess(id);
837 host->AddFilter(new ChromeRenderMessageFilter(id, profile));
838 #if defined(ENABLE_EXTENSIONS)
839 host->AddFilter(new cast::CastTransportHostFilter);
840 #endif
841 #if defined(ENABLE_PRINTING)
842 host->AddFilter(new printing::PrintingMessageFilter(id, profile));
843 #endif
844 host->AddFilter(new SearchProviderInstallStateMessageFilter(id, profile));
845 #if defined(ENABLE_SPELLCHECK)
846 host->AddFilter(new SpellCheckMessageFilter(id));
847 #endif
848 #if defined(USE_BROWSER_SPELLCHECKER)
849 host->AddFilter(new SpellCheckMessageFilterPlatform(id));
850 #endif
851 host->AddFilter(new ChromeNetBenchmarkingMessageFilter(profile, context));
852 host->AddFilter(new prerender::PrerenderMessageFilter(id, profile));
853 host->AddFilter(new TtsMessageFilter(host->GetBrowserContext()));
854 #if defined(ENABLE_WEBRTC)
855 WebRtcLoggingHandlerHost* webrtc_logging_handler_host =
856 new WebRtcLoggingHandlerHost(profile);
857 host->SetWebRtcLogMessageCallback(base::Bind(
858 &WebRtcLoggingHandlerHost::LogMessage, webrtc_logging_handler_host));
859 host->AddFilter(webrtc_logging_handler_host);
860 host->SetUserData(host, new base::UserDataAdapter<WebRtcLoggingHandlerHost>(
861 webrtc_logging_handler_host));
862 #endif
863 #if !defined(DISABLE_NACL)
864 host->AddFilter(new nacl::NaClHostMessageFilter(
865 id, profile->IsOffTheRecord(),
866 profile->GetPath(),
867 context));
868 #endif
869 #if defined(OS_ANDROID)
870 host->AddFilter(new cdm::CdmMessageFilterAndroid());
871 #endif
872 DataReductionProxyChromeSettings* data_reduction_proxy_settings =
873 DataReductionProxyChromeSettingsFactory::GetForBrowserContext(profile);
874 host->AddFilter(new data_reduction_proxy::DataReductionProxyMessageFilter(
875 data_reduction_proxy_settings));
877 host->Send(new ChromeViewMsg_SetIsIncognitoProcess(
878 profile->IsOffTheRecord()));
880 for (size_t i = 0; i < extra_parts_.size(); ++i)
881 extra_parts_[i]->RenderProcessWillLaunch(host);
883 RendererContentSettingRules rules;
884 if (host->IsForGuestsOnly()) {
885 #if defined(ENABLE_EXTENSIONS)
886 GetGuestViewDefaultContentSettingRules(profile->IsOffTheRecord(), &rules);
887 #else
888 NOTREACHED();
889 #endif
890 } else {
891 GetRendererContentSettingRules(
892 profile->GetHostContentSettingsMap(), &rules);
894 host->Send(new ChromeViewMsg_SetContentSettingRules(rules));
897 GURL ChromeContentBrowserClient::GetEffectiveURL(
898 content::BrowserContext* browser_context, const GURL& url) {
899 Profile* profile = Profile::FromBrowserContext(browser_context);
900 if (!profile)
901 return url;
903 // If the input |url| should be assigned to the Instant renderer, make its
904 // effective URL distinct from other URLs on the search provider's domain.
905 if (search::ShouldAssignURLToInstantRenderer(url, profile))
906 return search::GetEffectiveURLForInstant(url, profile);
908 #if defined(ENABLE_EXTENSIONS)
909 return ChromeContentBrowserClientExtensionsPart::GetEffectiveURL(
910 profile, url);
911 #else
912 return url;
913 #endif
916 bool ChromeContentBrowserClient::ShouldUseProcessPerSite(
917 content::BrowserContext* browser_context, const GURL& effective_url) {
918 // Non-extension, non-Instant URLs should generally use
919 // process-per-site-instance. Because we expect to use the effective URL,
920 // URLs for hosted apps (apart from bookmark apps) should have an extension
921 // scheme by now.
923 Profile* profile = Profile::FromBrowserContext(browser_context);
924 if (!profile)
925 return false;
927 if (search::ShouldUseProcessPerSiteForInstantURL(effective_url, profile))
928 return true;
930 #if defined(ENABLE_EXTENSIONS)
931 return ChromeContentBrowserClientExtensionsPart::ShouldUseProcessPerSite(
932 profile, effective_url);
933 #else
934 return false;
935 #endif
938 // These are treated as WebUI schemes but do not get WebUI bindings. Also,
939 // view-source is allowed for these schemes.
940 void ChromeContentBrowserClient::GetAdditionalWebUISchemes(
941 std::vector<std::string>* additional_schemes) {
942 additional_schemes->push_back(chrome::kChromeSearchScheme);
943 additional_schemes->push_back(dom_distiller::kDomDistillerScheme);
946 void ChromeContentBrowserClient::GetAdditionalWebUIHostsToIgnoreParititionCheck(
947 std::vector<std::string>* hosts) {
948 hosts->push_back(chrome::kChromeUIExtensionIconHost);
949 hosts->push_back(chrome::kChromeUIFaviconHost);
950 hosts->push_back(chrome::kChromeUIThemeHost);
951 hosts->push_back(chrome::kChromeUIThumbnailHost);
952 hosts->push_back(chrome::kChromeUIThumbnailHost2);
953 hosts->push_back(chrome::kChromeUIThumbnailListHost);
956 net::URLRequestContextGetter*
957 ChromeContentBrowserClient::CreateRequestContext(
958 content::BrowserContext* browser_context,
959 content::ProtocolHandlerMap* protocol_handlers,
960 content::URLRequestInterceptorScopedVector request_interceptors) {
961 Profile* profile = Profile::FromBrowserContext(browser_context);
962 return profile->CreateRequestContext(protocol_handlers,
963 request_interceptors.Pass());
966 net::URLRequestContextGetter*
967 ChromeContentBrowserClient::CreateRequestContextForStoragePartition(
968 content::BrowserContext* browser_context,
969 const base::FilePath& partition_path,
970 bool in_memory,
971 content::ProtocolHandlerMap* protocol_handlers,
972 content::URLRequestInterceptorScopedVector request_interceptors) {
973 Profile* profile = Profile::FromBrowserContext(browser_context);
974 return profile->CreateRequestContextForStoragePartition(
975 partition_path,
976 in_memory,
977 protocol_handlers,
978 request_interceptors.Pass());
981 bool ChromeContentBrowserClient::IsHandledURL(const GURL& url) {
982 return ProfileIOData::IsHandledURL(url);
985 bool ChromeContentBrowserClient::CanCommitURL(
986 content::RenderProcessHost* process_host,
987 const GURL& url) {
988 #if defined(ENABLE_EXTENSIONS)
989 return ChromeContentBrowserClientExtensionsPart::CanCommitURL(
990 process_host, url);
991 #else
992 return true;
993 #endif
996 bool ChromeContentBrowserClient::IsIllegalOrigin(
997 content::ResourceContext* resource_context,
998 int child_process_id,
999 const GURL& origin) {
1000 #if defined(ENABLE_EXTENSIONS)
1001 return ChromeContentBrowserClientExtensionsPart::IsIllegalOrigin(
1002 resource_context, child_process_id, origin);
1003 #else
1004 return false;
1005 #endif
1008 bool ChromeContentBrowserClient::ShouldAllowOpenURL(
1009 content::SiteInstance* site_instance, const GURL& url) {
1010 GURL from_url = site_instance->GetSiteURL();
1012 #if defined(ENABLE_EXTENSIONS)
1013 bool result;
1014 if (ChromeContentBrowserClientExtensionsPart::ShouldAllowOpenURL(
1015 site_instance, from_url, url, &result))
1016 return result;
1017 #endif
1019 // Do not allow chrome://chrome-signin navigate to other chrome:// URLs, since
1020 // the signin page may host untrusted web content.
1021 if (from_url.GetOrigin().spec() == chrome::kChromeUIChromeSigninURL &&
1022 url.SchemeIs(content::kChromeUIScheme) &&
1023 url.host() != chrome::kChromeUIChromeSigninHost) {
1024 VLOG(1) << "Blocked navigation to " << url.spec() << " from "
1025 << chrome::kChromeUIChromeSigninURL;
1026 return false;
1029 return true;
1032 bool ChromeContentBrowserClient::IsSuitableHost(
1033 content::RenderProcessHost* process_host,
1034 const GURL& site_url) {
1035 Profile* profile =
1036 Profile::FromBrowserContext(process_host->GetBrowserContext());
1037 // This may be NULL during tests. In that case, just assume any site can
1038 // share any host.
1039 if (!profile)
1040 return true;
1042 // Instant URLs should only be in the instant process and instant process
1043 // should only have Instant URLs.
1044 InstantService* instant_service =
1045 InstantServiceFactory::GetForProfile(profile);
1046 if (instant_service) {
1047 bool is_instant_process = instant_service->IsInstantProcess(
1048 process_host->GetID());
1049 bool should_be_in_instant_process =
1050 search::ShouldAssignURLToInstantRenderer(site_url, profile);
1051 if (is_instant_process || should_be_in_instant_process)
1052 return is_instant_process && should_be_in_instant_process;
1055 #if defined(ENABLE_EXTENSIONS)
1056 return ChromeContentBrowserClientExtensionsPart::IsSuitableHost(
1057 profile, process_host, site_url);
1058 #else
1059 return true;
1060 #endif
1063 bool ChromeContentBrowserClient::MayReuseHost(
1064 content::RenderProcessHost* process_host) {
1065 // If there is currently a prerender in progress for the host provided,
1066 // it may not be shared. We require prerenders to be by themselves in a
1067 // separate process so that we can monitor their resource usage.
1068 Profile* profile = Profile::FromBrowserContext(
1069 process_host->GetBrowserContext());
1070 prerender::PrerenderManager* prerender_manager =
1071 prerender::PrerenderManagerFactory::GetForProfile(profile);
1072 if (prerender_manager &&
1073 !prerender_manager->MayReuseProcessHost(process_host)) {
1074 return false;
1077 return true;
1080 bool ChromeContentBrowserClient::ShouldTryToUseExistingProcessHost(
1081 content::BrowserContext* browser_context, const GURL& url) {
1082 // It has to be a valid URL for us to check for an extension.
1083 if (!url.is_valid())
1084 return false;
1086 #if defined(ENABLE_EXTENSIONS)
1087 Profile* profile = Profile::FromBrowserContext(browser_context);
1088 return ChromeContentBrowserClientExtensionsPart::
1089 ShouldTryToUseExistingProcessHost(
1090 profile, url);
1091 #else
1092 return false;
1093 #endif
1096 void ChromeContentBrowserClient::SiteInstanceGotProcess(
1097 SiteInstance* site_instance) {
1098 CHECK(site_instance->HasProcess());
1100 Profile* profile = Profile::FromBrowserContext(
1101 site_instance->GetBrowserContext());
1102 if (!profile)
1103 return;
1105 // Remember the ID of the Instant process to signal the renderer process
1106 // on startup in |AppendExtraCommandLineSwitches| below.
1107 if (search::ShouldAssignURLToInstantRenderer(site_instance->GetSiteURL(),
1108 profile)) {
1109 InstantService* instant_service =
1110 InstantServiceFactory::GetForProfile(profile);
1111 if (instant_service)
1112 instant_service->AddInstantProcess(site_instance->GetProcess()->GetID());
1115 for (size_t i = 0; i < extra_parts_.size(); ++i)
1116 extra_parts_[i]->SiteInstanceGotProcess(site_instance);
1119 void ChromeContentBrowserClient::SiteInstanceDeleting(
1120 SiteInstance* site_instance) {
1121 if (!site_instance->HasProcess())
1122 return;
1124 for (size_t i = 0; i < extra_parts_.size(); ++i)
1125 extra_parts_[i]->SiteInstanceDeleting(site_instance);
1128 bool ChromeContentBrowserClient::ShouldSwapBrowsingInstancesForNavigation(
1129 SiteInstance* site_instance,
1130 const GURL& current_url,
1131 const GURL& new_url) {
1132 #if defined(ENABLE_EXTENSIONS)
1133 return ChromeContentBrowserClientExtensionsPart::
1134 ShouldSwapBrowsingInstancesForNavigation(
1135 site_instance, current_url, new_url);
1136 #else
1137 return false;
1138 #endif
1141 bool ChromeContentBrowserClient::ShouldSwapProcessesForRedirect(
1142 content::ResourceContext* resource_context, const GURL& current_url,
1143 const GURL& new_url) {
1144 #if defined(ENABLE_EXTENSIONS)
1145 return ChromeContentBrowserClientExtensionsPart::
1146 ShouldSwapProcessesForRedirect(resource_context, current_url, new_url);
1147 #else
1148 return false;
1149 #endif
1152 bool ChromeContentBrowserClient::ShouldAssignSiteForURL(const GURL& url) {
1153 return !url.SchemeIs(chrome::kChromeNativeScheme);
1156 std::string ChromeContentBrowserClient::GetCanonicalEncodingNameByAliasName(
1157 const std::string& alias_name) {
1158 return CharacterEncoding::GetCanonicalEncodingNameByAliasName(alias_name);
1161 namespace {
1163 bool IsAutoReloadEnabled() {
1164 // Fetch the field trial, even though we don't use it. Calling FindFullName()
1165 // causes the field-trial mechanism to report which group we're in, which
1166 // might reflect a hard disable or hard enable via flag, both of which have
1167 // their own field trial groups. This lets us know what percentage of users
1168 // manually enable or disable auto-reload.
1169 std::string group = base::FieldTrialList::FindFullName(
1170 "AutoReloadExperiment");
1171 const base::CommandLine& browser_command_line =
1172 *base::CommandLine::ForCurrentProcess();
1173 if (browser_command_line.HasSwitch(switches::kEnableOfflineAutoReload))
1174 return true;
1175 if (browser_command_line.HasSwitch(switches::kDisableOfflineAutoReload))
1176 return false;
1177 return true;
1180 bool IsAutoReloadVisibleOnlyEnabled() {
1181 // See the block comment in IsAutoReloadEnabled().
1182 std::string group = base::FieldTrialList::FindFullName(
1183 "AutoReloadVisibleOnlyExperiment");
1184 const base::CommandLine& browser_command_line =
1185 *base::CommandLine::ForCurrentProcess();
1186 if (browser_command_line.HasSwitch(
1187 switches::kEnableOfflineAutoReloadVisibleOnly)) {
1188 return true;
1190 if (browser_command_line.HasSwitch(
1191 switches::kDisableOfflineAutoReloadVisibleOnly)) {
1192 return false;
1194 return true;
1197 void MaybeAppendBlinkSettingsSwitchForFieldTrial(
1198 const base::CommandLine& browser_command_line,
1199 base::CommandLine* command_line) {
1200 // List of field trials that modify the blink-settings command line flag. No
1201 // two field trials in the list should specify the same keys, otherwise one
1202 // field trial may overwrite another. See Source/core/frame/Settings.in in
1203 // Blink for the list of valid keys.
1204 static const char* const kBlinkSettingsFieldTrials[] = {
1205 // Keys: backgroundHtmlParserOutstandingTokenLimit
1206 // backgroundHtmlParserPendingTokenLimit
1207 "BackgroundHtmlParserTokenLimits",
1209 // Keys: doHtmlPreloadScanning
1210 "HtmlPreloadScanning",
1212 // Keys: lowPriorityIframes
1213 "LowPriorityIFrames",
1216 std::vector<std::string> blink_settings;
1217 for (const char* field_trial_name : kBlinkSettingsFieldTrials) {
1218 // Each blink-settings field trial should include a forcing_flag group,
1219 // to make sure that clients that specify the blink-settings flag on the
1220 // command line are excluded from the experiment groups. To make
1221 // sure we assign clients that specify this flag to the forcing_flag
1222 // group, we must call GetVariationParams for each field trial first
1223 // (for example, before checking HasSwitch() and returning), since
1224 // GetVariationParams has the side-effect of assigning the client to
1225 // a field trial group.
1226 std::map<std::string, std::string> params;
1227 if (variations::GetVariationParams(field_trial_name, &params)) {
1228 for (const auto& param : params) {
1229 blink_settings.push_back(base::StringPrintf(
1230 "%s=%s", param.first.c_str(), param.second.c_str()));
1235 // Flags for the ResourcePriorities field trial. The settings are
1236 // encoded in the field trial group name instead of as variations
1237 // because the variations code is not accessible from the loader.
1239 // The group name encoding looks like this:
1240 // <descriptiveName>_ABCDE_E2_F_G
1241 // A - fetchDeferLateScripts (1 for true, 0 for false)
1242 // B - fetchIncreaseFontPriority (1 for true, 0 for false)
1243 // C - fetchIncreaseAsyncScriptPriority (1 for true, 0 for false)
1244 // D - fetchIncreasePriorities (1 for true, 0 for false)
1245 // E - fetchEnableLayoutBlockingThreshold (1 for true, 0 for false)
1246 // E2 - fetchLayoutBlockingThreshold (Numeric)
1247 // F - fetchMaxNumDelayableWhileLayoutBlocking (Numeric)
1248 // G - fetchMaxNumDelayableRequests (Numeric)
1250 // Only A-D are relevant to blink and exposed as settings
1251 // Any group names (Control, Default, etc) will not match the pattern or
1252 // flags and will get the default settings which is the expected behavior.
1253 std::string resource_priorities_trial_group =
1254 base::FieldTrialList::FindFullName("ResourcePriorities");
1255 std::vector<std::string> split_group(
1256 base::SplitString(resource_priorities_trial_group, "_",
1257 base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL));
1258 if (split_group.size() == 5 && split_group[1].length() == 5) {
1259 if (split_group[1].at(0) == '1')
1260 blink_settings.push_back("fetchDeferLateScripts=true");
1261 if (split_group[1].at(1) == '1')
1262 blink_settings.push_back("fetchIncreaseFontPriority=true");
1263 if (split_group[1].at(2) == '1')
1264 blink_settings.push_back("fetchIncreaseAsyncScriptPriority=true");
1265 if (split_group[1].at(3) == '1')
1266 blink_settings.push_back("fetchIncreasePriorities=true");
1269 if (blink_settings.empty()) {
1270 return;
1273 if (browser_command_line.HasSwitch(switches::kBlinkSettings) ||
1274 command_line->HasSwitch(switches::kBlinkSettings)) {
1275 // The field trials should be configured to force users that specify the
1276 // blink-settings flag into a group with no params, and we return
1277 // above if no params were specified, so it's an error if we reach
1278 // this point.
1279 LOG(WARNING) << "Received field trial params, "
1280 "but blink-settings switch already specified.";
1281 return;
1284 command_line->AppendSwitchASCII(switches::kBlinkSettings,
1285 base::JoinString(blink_settings, ","));
1288 } // namespace
1290 void ChromeContentBrowserClient::AppendExtraCommandLineSwitches(
1291 base::CommandLine* command_line,
1292 int child_process_id) {
1293 #if defined(OS_MACOSX)
1294 scoped_ptr<metrics::ClientInfo> client_info =
1295 GoogleUpdateSettings::LoadMetricsClientInfo();
1296 if (client_info) {
1297 command_line->AppendSwitchASCII(switches::kMetricsClientID,
1298 client_info->client_id);
1300 #elif defined(OS_POSIX)
1301 if (breakpad::IsCrashReporterEnabled()) {
1302 scoped_ptr<metrics::ClientInfo> client_info =
1303 GoogleUpdateSettings::LoadMetricsClientInfo();
1304 command_line->AppendSwitchASCII(switches::kEnableCrashReporter,
1305 client_info ? client_info->client_id
1306 : std::string());
1308 #endif
1310 if (logging::DialogsAreSuppressed())
1311 command_line->AppendSwitch(switches::kNoErrorDialogs);
1313 std::string process_type =
1314 command_line->GetSwitchValueASCII(switches::kProcessType);
1315 const base::CommandLine& browser_command_line =
1316 *base::CommandLine::ForCurrentProcess();
1318 static const char* const kCommonSwitchNames[] = {
1319 switches::kUserAgent,
1320 switches::kUserDataDir, // Make logs go to the right file.
1322 command_line->CopySwitchesFrom(browser_command_line, kCommonSwitchNames,
1323 arraysize(kCommonSwitchNames));
1325 #if defined(ENABLE_IPC_FUZZER)
1326 static const char* const kIpcFuzzerSwitches[] = {
1327 switches::kIpcDumpDirectory,
1328 switches::kIpcFuzzerTestcase,
1330 command_line->CopySwitchesFrom(browser_command_line, kIpcFuzzerSwitches,
1331 arraysize(kIpcFuzzerSwitches));
1332 #endif
1334 #if defined(OS_CHROMEOS)
1335 static const char* const kChromeOSSwitches[] = {
1336 switches::kDisableDinosaurEasterEgg,
1338 command_line->CopySwitchesFrom(browser_command_line, kChromeOSSwitches,
1339 arraysize(kChromeOSSwitches));
1341 // On Chrome OS need to pass primary user homedir (in multi-profiles session).
1342 base::FilePath homedir;
1343 PathService::Get(base::DIR_HOME, &homedir);
1344 command_line->AppendSwitchASCII(chromeos::switches::kHomedir,
1345 homedir.value().c_str());
1346 #endif
1348 if (process_type == switches::kRendererProcess) {
1349 content::RenderProcessHost* process =
1350 content::RenderProcessHost::FromID(child_process_id);
1351 Profile* profile =
1352 process ? Profile::FromBrowserContext(process->GetBrowserContext())
1353 : NULL;
1354 for (size_t i = 0; i < extra_parts_.size(); ++i) {
1355 extra_parts_[i]->AppendExtraRendererCommandLineSwitches(
1356 command_line, process, profile);
1359 #if defined(OS_CHROMEOS)
1360 const std::string& login_profile =
1361 browser_command_line.GetSwitchValueASCII(
1362 chromeos::switches::kLoginProfile);
1363 if (!login_profile.empty())
1364 command_line->AppendSwitchASCII(
1365 chromeos::switches::kLoginProfile, login_profile);
1366 #endif
1368 #if defined(ENABLE_WEBRTC)
1369 MaybeCopyDisableWebRtcEncryptionSwitch(command_line,
1370 browser_command_line,
1371 chrome::GetChannel());
1372 #endif
1374 if (process) {
1375 PrefService* prefs = profile->GetPrefs();
1376 // Currently this pref is only registered if applied via a policy.
1377 if (prefs->HasPrefPath(prefs::kDisable3DAPIs) &&
1378 prefs->GetBoolean(prefs::kDisable3DAPIs)) {
1379 // Turn this policy into a command line switch.
1380 command_line->AppendSwitch(switches::kDisable3DAPIs);
1383 const base::ListValue* switches =
1384 prefs->GetList(prefs::kEnableDeprecatedWebPlatformFeatures);
1385 if (switches) {
1386 // Enable any deprecated features that have been re-enabled by policy.
1387 for (base::ListValue::const_iterator it = switches->begin();
1388 it != switches->end(); ++it) {
1389 std::string switch_to_enable;
1390 if ((*it)->GetAsString(&switch_to_enable))
1391 command_line->AppendSwitch(switch_to_enable);
1395 // Disable client-side phishing detection in the renderer if it is
1396 // disabled in the Profile preferences or the browser process.
1397 if (!prefs->GetBoolean(prefs::kSafeBrowsingEnabled) ||
1398 !g_browser_process->safe_browsing_detection_service()) {
1399 command_line->AppendSwitch(
1400 switches::kDisableClientSidePhishingDetection);
1403 if (prefs->GetBoolean(prefs::kPrintPreviewDisabled))
1404 command_line->AppendSwitch(switches::kDisablePrintPreview);
1406 InstantService* instant_service =
1407 InstantServiceFactory::GetForProfile(profile);
1408 if (instant_service &&
1409 instant_service->IsInstantProcess(process->GetID()))
1410 command_line->AppendSwitch(switches::kInstantProcess);
1413 if (IsAutoReloadEnabled())
1414 command_line->AppendSwitch(switches::kEnableOfflineAutoReload);
1415 if (IsAutoReloadVisibleOnlyEnabled()) {
1416 command_line->AppendSwitch(
1417 switches::kEnableOfflineAutoReloadVisibleOnly);
1421 // Enable showing a saved copy if this session is in the field trial
1422 // or the user explicitly enabled it. Note that as far as the
1423 // renderer is concerned, the feature is enabled if-and-only-if
1424 // one of the kEnableShowSavedCopy* switches is on the command
1425 // line; the yes/no/default behavior is only at the browser
1426 // command line level.
1428 // Command line switches override
1429 const std::string& show_saved_copy_value =
1430 browser_command_line.GetSwitchValueASCII(switches::kShowSavedCopy);
1431 if (show_saved_copy_value == switches::kEnableShowSavedCopyPrimary ||
1432 show_saved_copy_value == switches::kEnableShowSavedCopySecondary ||
1433 show_saved_copy_value == switches::kDisableShowSavedCopy) {
1434 command_line->AppendSwitchASCII(switches::kShowSavedCopy,
1435 show_saved_copy_value);
1436 } else {
1437 std::string group =
1438 base::FieldTrialList::FindFullName("LoadStaleCacheExperiment");
1440 if (group == "Primary") {
1441 command_line->AppendSwitchASCII(
1442 switches::kShowSavedCopy, switches::kEnableShowSavedCopyPrimary);
1443 } else if (group == "Secondary") {
1444 command_line->AppendSwitchASCII(
1445 switches::kShowSavedCopy,
1446 switches::kEnableShowSavedCopySecondary);
1451 MaybeAppendBlinkSettingsSwitchForFieldTrial(
1452 browser_command_line, command_line);
1454 // Please keep this in alphabetical order.
1455 static const char* const kSwitchNames[] = {
1456 autofill::switches::kDisableFillOnAccountSelect,
1457 autofill::switches::kDisablePasswordGeneration,
1458 autofill::switches::kEnableAccessorySuggestionView,
1459 autofill::switches::kEnableFillOnAccountSelect,
1460 autofill::switches::kEnableFillOnAccountSelectNoHighlighting,
1461 autofill::switches::kEnablePasswordGeneration,
1462 autofill::switches::kEnableSingleClickAutofill,
1463 autofill::switches::kEnableSuggestionsWithSubstringMatch,
1464 autofill::switches::kIgnoreAutocompleteOffForAutofill,
1465 autofill::switches::kLocalHeuristicsOnlyForPasswordGeneration,
1466 #if defined(ENABLE_EXTENSIONS)
1467 extensions::switches::kAllowHTTPBackgroundPage,
1468 extensions::switches::kAllowLegacyExtensionManifests,
1469 extensions::switches::kEnableAppWindowControls,
1470 extensions::switches::kEnableEmbeddedExtensionOptions,
1471 extensions::switches::kEnableExperimentalExtensionApis,
1472 extensions::switches::kExtensionsOnChromeURLs,
1473 extensions::switches::kWhitelistedExtensionID,
1474 #endif
1475 switches::kAllowInsecureLocalhost,
1476 switches::kAppsGalleryURL,
1477 switches::kCloudPrintURL,
1478 switches::kCloudPrintXmppEndpoint,
1479 switches::kDisableBundledPpapiFlash,
1480 switches::kDisableCastStreamingHWEncoding,
1481 switches::kDisableJavaScriptHarmonyShipping,
1482 switches::kDisableNewBookmarkApps,
1483 #if defined(ENABLE_SPELLCHECK) && defined(OS_ANDROID)
1484 switches::kEnableAndroidSpellChecker,
1485 #endif
1486 switches::kEnableBenchmarking,
1487 switches::kEnableNaCl,
1488 #if !defined(DISABLE_NACL)
1489 switches::kEnableNaClDebug,
1490 switches::kEnableNaClNonSfiMode,
1491 switches::kEnablePNaClSubzero,
1492 #endif
1493 switches::kEnableNetBenchmarking,
1494 switches::kEnableNewBookmarkApps,
1495 switches::kEnablePluginPlaceholderShadowDom,
1496 switches::kJavaScriptHarmony,
1497 switches::kMessageLoopHistogrammer,
1498 switches::kPpapiFlashArgs,
1499 switches::kPpapiFlashPath,
1500 switches::kPpapiFlashVersion,
1501 switches::kProfilingAtStart,
1502 switches::kProfilingFile,
1503 switches::kProfilingFlush,
1504 switches::kUnsafelyTreatInsecureOriginAsSecure,
1505 translate::switches::kTranslateSecurityOrigin,
1508 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1509 arraysize(kSwitchNames));
1510 } else if (process_type == switches::kUtilityProcess) {
1511 #if defined(ENABLE_EXTENSIONS)
1512 static const char* const kSwitchNames[] = {
1513 extensions::switches::kAllowHTTPBackgroundPage,
1514 extensions::switches::kEnableExperimentalExtensionApis,
1515 extensions::switches::kExtensionsOnChromeURLs,
1516 extensions::switches::kWhitelistedExtensionID,
1519 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1520 arraysize(kSwitchNames));
1521 #endif
1522 } else if (process_type == switches::kPluginProcess) {
1523 #if defined(OS_CHROMEOS)
1524 static const char* const kSwitchNames[] = {
1525 chromeos::switches::kLoginProfile,
1528 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1529 arraysize(kSwitchNames));
1530 #endif
1531 } else if (process_type == switches::kZygoteProcess) {
1532 static const char* const kSwitchNames[] = {
1533 // Load (in-process) Pepper plugins in-process in the zygote pre-sandbox.
1534 switches::kDisableBundledPpapiFlash,
1535 #if !defined(DISABLE_NACL)
1536 switches::kEnableNaClDebug,
1537 switches::kEnableNaClNonSfiMode,
1538 switches::kEnablePNaClSubzero,
1539 switches::kNaClDangerousNoSandboxNonSfi,
1540 switches::kUseNaClHelperNonSfi,
1541 #endif
1542 switches::kPpapiFlashPath,
1543 switches::kPpapiFlashVersion,
1546 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1547 arraysize(kSwitchNames));
1548 } else if (process_type == switches::kGpuProcess) {
1549 // If --ignore-gpu-blacklist is passed in, don't send in crash reports
1550 // because GPU is expected to be unreliable.
1551 if (browser_command_line.HasSwitch(switches::kIgnoreGpuBlacklist) &&
1552 !command_line->HasSwitch(switches::kDisableBreakpad))
1553 command_line->AppendSwitch(switches::kDisableBreakpad);
1556 // The command line switch kEnableBenchmarking needs to be specified along
1557 // with the kEnableStatsTable switch to ensure that the stats table global
1558 // is initialized correctly.
1559 if (command_line->HasSwitch(switches::kEnableBenchmarking))
1560 DCHECK(command_line->HasSwitch(switches::kEnableStatsTable));
1563 std::string ChromeContentBrowserClient::GetApplicationLocale() {
1564 if (BrowserThread::CurrentlyOn(BrowserThread::IO))
1565 return g_io_thread_application_locale.Get();
1566 return g_browser_process->GetApplicationLocale();
1569 std::string ChromeContentBrowserClient::GetAcceptLangs(
1570 content::BrowserContext* context) {
1571 Profile* profile = Profile::FromBrowserContext(context);
1572 return profile->GetPrefs()->GetString(prefs::kAcceptLanguages);
1575 const gfx::ImageSkia* ChromeContentBrowserClient::GetDefaultFavicon() {
1576 ResourceBundle& rb = ResourceBundle::GetSharedInstance();
1577 return rb.GetNativeImageNamed(IDR_DEFAULT_FAVICON).ToImageSkia();
1580 bool ChromeContentBrowserClient::AllowAppCache(
1581 const GURL& manifest_url,
1582 const GURL& first_party,
1583 content::ResourceContext* context) {
1584 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1585 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1586 return io_data->GetCookieSettings()->
1587 IsSettingCookieAllowed(manifest_url, first_party);
1590 bool ChromeContentBrowserClient::AllowServiceWorker(
1591 const GURL& scope,
1592 const GURL& first_party_url,
1593 content::ResourceContext* context,
1594 int render_process_id,
1595 int render_frame_id) {
1596 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1597 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1598 bool allow = io_data->GetCookieSettings()->IsSettingCookieAllowed(
1599 scope, first_party_url);
1601 // Record access to database for potential display in UI.
1602 BrowserThread::PostTask(
1603 BrowserThread::UI, FROM_HERE,
1604 base::Bind(&TabSpecificContentSettings::ServiceWorkerAccessed,
1605 render_process_id, render_frame_id, scope, !allow));
1606 return allow;
1609 bool ChromeContentBrowserClient::AllowGetCookie(
1610 const GURL& url,
1611 const GURL& first_party,
1612 const net::CookieList& cookie_list,
1613 content::ResourceContext* context,
1614 int render_process_id,
1615 int render_frame_id) {
1616 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1617 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1618 bool allow = io_data->GetCookieSettings()->
1619 IsReadingCookieAllowed(url, first_party);
1621 BrowserThread::PostTask(
1622 BrowserThread::UI, FROM_HERE,
1623 base::Bind(&TabSpecificContentSettings::CookiesRead, render_process_id,
1624 render_frame_id, url, first_party, cookie_list, !allow));
1625 return allow;
1628 bool ChromeContentBrowserClient::AllowSetCookie(
1629 const GURL& url,
1630 const GURL& first_party,
1631 const std::string& cookie_line,
1632 content::ResourceContext* context,
1633 int render_process_id,
1634 int render_frame_id,
1635 net::CookieOptions* options) {
1636 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1637 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1638 content_settings::CookieSettings* cookie_settings =
1639 io_data->GetCookieSettings();
1640 bool allow = cookie_settings->IsSettingCookieAllowed(url, first_party);
1642 BrowserThread::PostTask(
1643 BrowserThread::UI, FROM_HERE,
1644 base::Bind(&TabSpecificContentSettings::CookieChanged, render_process_id,
1645 render_frame_id, url, first_party, cookie_line, *options,
1646 !allow));
1647 return allow;
1650 bool ChromeContentBrowserClient::AllowSaveLocalState(
1651 content::ResourceContext* context) {
1652 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1653 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1654 content_settings::CookieSettings* cookie_settings =
1655 io_data->GetCookieSettings();
1656 ContentSetting setting = cookie_settings->GetDefaultCookieSetting(NULL);
1658 // TODO(bauerb): Should we also disallow local state if the default is BLOCK?
1659 // Could we even support per-origin settings?
1660 return setting != CONTENT_SETTING_SESSION_ONLY;
1663 bool ChromeContentBrowserClient::AllowWorkerDatabase(
1664 const GURL& url,
1665 const base::string16& name,
1666 const base::string16& display_name,
1667 unsigned long estimated_size,
1668 content::ResourceContext* context,
1669 const std::vector<std::pair<int, int> >& render_frames) {
1670 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1671 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1672 content_settings::CookieSettings* cookie_settings =
1673 io_data->GetCookieSettings();
1674 bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1676 // Record access to database for potential display in UI.
1677 std::vector<std::pair<int, int> >::const_iterator i;
1678 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1679 BrowserThread::PostTask(
1680 BrowserThread::UI, FROM_HERE,
1681 base::Bind(&TabSpecificContentSettings::WebDatabaseAccessed,
1682 i->first, i->second, url, name, display_name, !allow));
1685 return allow;
1688 void ChromeContentBrowserClient::AllowWorkerFileSystem(
1689 const GURL& url,
1690 content::ResourceContext* context,
1691 const std::vector<std::pair<int, int> >& render_frames,
1692 base::Callback<void(bool)> callback) {
1693 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1694 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1695 content_settings::CookieSettings* cookie_settings =
1696 io_data->GetCookieSettings();
1697 bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1699 #if defined(ENABLE_EXTENSIONS)
1700 GuestPermissionRequestHelper(url, render_frames, callback, allow);
1701 #else
1702 FileSystemAccessed(url, render_frames, callback, allow);
1703 #endif
1706 #if defined(ENABLE_EXTENSIONS)
1707 void ChromeContentBrowserClient::GuestPermissionRequestHelper(
1708 const GURL& url,
1709 const std::vector<std::pair<int, int> >& render_frames,
1710 base::Callback<void(bool)> callback,
1711 bool allow) {
1712 DCHECK(BrowserThread:: CurrentlyOn(BrowserThread::IO));
1713 std::vector<std::pair<int, int> >::const_iterator i;
1714 std::map<int, int> process_map;
1715 std::map<int, int>::const_iterator it;
1716 bool has_web_view_guest = false;
1717 // Record access to file system for potential display in UI.
1718 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1719 if (process_map.find(i->first) != process_map.end())
1720 continue;
1722 process_map.insert(std::pair<int, int>(i->first, i->second));
1724 if (extensions::WebViewRendererState::GetInstance()->IsGuest(i->first))
1725 has_web_view_guest = true;
1727 if (!has_web_view_guest) {
1728 FileSystemAccessed(url, render_frames, callback, allow);
1729 return;
1731 DCHECK_EQ(1U, process_map.size());
1732 it = process_map.begin();
1733 BrowserThread::PostTask(
1734 BrowserThread::UI,
1735 FROM_HERE,
1736 base::Bind(&ChromeContentBrowserClient::
1737 RequestFileSystemPermissionOnUIThread,
1738 it->first,
1739 it->second,
1740 url,
1741 allow,
1742 base::Bind(&ChromeContentBrowserClient::FileSystemAccessed,
1743 weak_factory_.GetWeakPtr(),
1744 url,
1745 render_frames,
1746 callback)));
1749 void ChromeContentBrowserClient::RequestFileSystemPermissionOnUIThread(
1750 int render_process_id,
1751 int render_frame_id,
1752 const GURL& url,
1753 bool allowed_by_default,
1754 const base::Callback<void(bool)>& callback) {
1755 DCHECK(BrowserThread:: CurrentlyOn(BrowserThread::UI));
1756 extensions::WebViewPermissionHelper* web_view_permission_helper =
1757 extensions::WebViewPermissionHelper::FromFrameID(
1758 render_process_id, render_frame_id);
1759 web_view_permission_helper->RequestFileSystemPermission(url,
1760 allowed_by_default,
1761 callback);
1763 #endif
1765 void ChromeContentBrowserClient::FileSystemAccessed(
1766 const GURL& url,
1767 const std::vector<std::pair<int, int> >& render_frames,
1768 base::Callback<void(bool)> callback,
1769 bool allow) {
1770 // Record access to file system for potential display in UI.
1771 std::vector<std::pair<int, int> >::const_iterator i;
1772 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1773 BrowserThread::PostTask(
1774 BrowserThread::UI,
1775 FROM_HERE,
1776 base::Bind(&TabSpecificContentSettings::FileSystemAccessed,
1777 i->first, i->second, url, !allow));
1779 callback.Run(allow);
1782 bool ChromeContentBrowserClient::AllowWorkerIndexedDB(
1783 const GURL& url,
1784 const base::string16& name,
1785 content::ResourceContext* context,
1786 const std::vector<std::pair<int, int> >& render_frames) {
1787 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1788 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1789 content_settings::CookieSettings* cookie_settings =
1790 io_data->GetCookieSettings();
1791 bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1793 // Record access to IndexedDB for potential display in UI.
1794 std::vector<std::pair<int, int> >::const_iterator i;
1795 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1796 BrowserThread::PostTask(
1797 BrowserThread::UI, FROM_HERE,
1798 base::Bind(&TabSpecificContentSettings::IndexedDBAccessed,
1799 i->first, i->second, url, name, !allow));
1802 return allow;
1805 #if defined(ENABLE_WEBRTC)
1806 bool ChromeContentBrowserClient::AllowWebRTCIdentityCache(
1807 const GURL& url,
1808 const GURL& first_party_url,
1809 content::ResourceContext* context) {
1810 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1811 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1812 content_settings::CookieSettings* cookie_settings =
1813 io_data->GetCookieSettings();
1814 return cookie_settings->IsReadingCookieAllowed(url, first_party_url) &&
1815 cookie_settings->IsSettingCookieAllowed(url, first_party_url);
1817 #endif // defined(ENABLE_WEBRTC)
1819 net::URLRequestContext*
1820 ChromeContentBrowserClient::OverrideRequestContextForURL(
1821 const GURL& url, content::ResourceContext* context) {
1822 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1823 #if defined(ENABLE_EXTENSIONS)
1824 if (url.SchemeIs(extensions::kExtensionScheme)) {
1825 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1826 return io_data->extensions_request_context();
1828 #endif
1830 return NULL;
1833 QuotaPermissionContext*
1834 ChromeContentBrowserClient::CreateQuotaPermissionContext() {
1835 return new ChromeQuotaPermissionContext();
1838 void ChromeContentBrowserClient::AllowCertificateError(
1839 int render_process_id,
1840 int render_frame_id,
1841 int cert_error,
1842 const net::SSLInfo& ssl_info,
1843 const GURL& request_url,
1844 ResourceType resource_type,
1845 bool overridable,
1846 bool strict_enforcement,
1847 bool expired_previous_decision,
1848 const base::Callback<void(bool)>& callback,
1849 content::CertificateRequestResultType* result) {
1850 if (resource_type != content::RESOURCE_TYPE_MAIN_FRAME) {
1851 // A sub-resource has a certificate error. The user doesn't really
1852 // have a context for making the right decision, so block the
1853 // request hard, without an info bar to allow showing the insecure
1854 // content.
1855 *result = content::CERTIFICATE_REQUEST_RESULT_TYPE_DENY;
1856 return;
1859 // If the tab is being prerendered, cancel the prerender and the request.
1860 content::RenderFrameHost* render_frame_host =
1861 content::RenderFrameHost::FromID(render_process_id, render_frame_id);
1862 WebContents* tab = WebContents::FromRenderFrameHost(render_frame_host);
1863 if (!tab) {
1864 NOTREACHED();
1865 return;
1868 prerender::PrerenderContents* prerender_contents =
1869 prerender::PrerenderContents::FromWebContents(tab);
1870 if (prerender_contents) {
1871 prerender_contents->Destroy(prerender::FINAL_STATUS_SSL_ERROR);
1872 *result = content::CERTIFICATE_REQUEST_RESULT_TYPE_CANCEL;
1873 return;
1876 // Otherwise, display an SSL blocking page. The interstitial page takes
1877 // ownership of ssl_blocking_page.
1878 int options_mask = 0;
1879 if (overridable)
1880 options_mask |= SSLBlockingPage::OVERRIDABLE;
1881 if (strict_enforcement)
1882 options_mask |= SSLBlockingPage::STRICT_ENFORCEMENT;
1883 if (expired_previous_decision)
1884 options_mask |= SSLBlockingPage::EXPIRED_BUT_PREVIOUSLY_ALLOWED;
1886 SafeBrowsingService* safe_browsing_service =
1887 g_browser_process->safe_browsing_service();
1888 scoped_ptr<SafeBrowsingSSLCertReporter> cert_reporter(
1889 new SafeBrowsingSSLCertReporter(safe_browsing_service
1890 ? safe_browsing_service->ui_manager()
1891 : nullptr));
1892 SSLErrorHandler::HandleSSLError(tab, cert_error, ssl_info, request_url,
1893 options_mask, cert_reporter.Pass(), callback);
1896 void ChromeContentBrowserClient::SelectClientCertificate(
1897 content::WebContents* web_contents,
1898 net::SSLCertRequestInfo* cert_request_info,
1899 scoped_ptr<content::ClientCertificateDelegate> delegate) {
1900 prerender::PrerenderContents* prerender_contents =
1901 prerender::PrerenderContents::FromWebContents(web_contents);
1902 if (prerender_contents) {
1903 prerender_contents->Destroy(
1904 prerender::FINAL_STATUS_SSL_CLIENT_CERTIFICATE_REQUESTED);
1905 return;
1908 GURL requesting_url("https://" + cert_request_info->host_and_port.ToString());
1909 DCHECK(requesting_url.is_valid())
1910 << "Invalid URL string: https://"
1911 << cert_request_info->host_and_port.ToString();
1913 Profile* profile =
1914 Profile::FromBrowserContext(web_contents->GetBrowserContext());
1915 scoped_ptr<base::Value> filter =
1916 profile->GetHostContentSettingsMap()->GetWebsiteSetting(
1917 requesting_url,
1918 requesting_url,
1919 CONTENT_SETTINGS_TYPE_AUTO_SELECT_CERTIFICATE,
1920 std::string(),
1921 NULL);
1923 if (filter.get()) {
1924 // Try to automatically select a client certificate.
1925 if (filter->IsType(base::Value::TYPE_DICTIONARY)) {
1926 base::DictionaryValue* filter_dict =
1927 static_cast<base::DictionaryValue*>(filter.get());
1929 const std::vector<scoped_refptr<net::X509Certificate> >&
1930 all_client_certs = cert_request_info->client_certs;
1931 for (size_t i = 0; i < all_client_certs.size(); ++i) {
1932 if (CertMatchesFilter(*all_client_certs[i].get(), *filter_dict)) {
1933 // Use the first certificate that is matched by the filter.
1934 delegate->ContinueWithCertificate(all_client_certs[i].get());
1935 return;
1938 } else {
1939 NOTREACHED();
1943 chrome::ShowSSLClientCertificateSelector(web_contents, cert_request_info,
1944 delegate.Pass());
1947 void ChromeContentBrowserClient::AddCertificate(
1948 net::CertificateMimeType cert_type,
1949 const void* cert_data,
1950 size_t cert_size,
1951 int render_process_id,
1952 int render_frame_id) {
1953 chrome::SSLAddCertificate(cert_type, cert_data, cert_size,
1954 render_process_id, render_frame_id);
1957 content::MediaObserver* ChromeContentBrowserClient::GetMediaObserver() {
1958 return MediaCaptureDevicesDispatcher::GetInstance();
1961 content::PlatformNotificationService*
1962 ChromeContentBrowserClient::GetPlatformNotificationService() {
1963 #if defined(ENABLE_NOTIFICATIONS)
1964 return PlatformNotificationServiceImpl::GetInstance();
1965 #else
1966 NOTIMPLEMENTED();
1967 return NULL;
1968 #endif
1971 bool ChromeContentBrowserClient::CanCreateWindow(
1972 const GURL& opener_url,
1973 const GURL& opener_top_level_frame_url,
1974 const GURL& source_origin,
1975 WindowContainerType container_type,
1976 const GURL& target_url,
1977 const content::Referrer& referrer,
1978 WindowOpenDisposition disposition,
1979 const WebWindowFeatures& features,
1980 bool user_gesture,
1981 bool opener_suppressed,
1982 content::ResourceContext* context,
1983 int render_process_id,
1984 int opener_render_view_id,
1985 int opener_render_frame_id,
1986 bool* no_javascript_access) {
1987 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1989 *no_javascript_access = false;
1991 // If the opener is trying to create a background window but doesn't have
1992 // the appropriate permission, fail the attempt.
1993 if (container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {
1994 #if defined(ENABLE_EXTENSIONS)
1995 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1996 InfoMap* map = io_data->GetExtensionInfoMap();
1997 if (!map->SecurityOriginHasAPIPermission(
1998 source_origin,
1999 render_process_id,
2000 APIPermission::kBackground)) {
2001 return false;
2004 // Note: this use of GetExtensionOrAppByURL is safe but imperfect. It may
2005 // return a recently installed Extension even if this CanCreateWindow call
2006 // was made by an old copy of the page in a normal web process. That's ok,
2007 // because the permission check above would have caused an early return
2008 // already. We must use the full URL to find hosted apps, though, and not
2009 // just the origin.
2010 const Extension* extension =
2011 map->extensions().GetExtensionOrAppByURL(opener_url);
2012 if (extension && !extensions::BackgroundInfo::AllowJSAccess(extension))
2013 *no_javascript_access = true;
2014 #endif
2016 return true;
2019 #if defined(ENABLE_EXTENSIONS)
2020 if (extensions::WebViewRendererState::GetInstance()->IsGuest(
2021 render_process_id))
2022 return true;
2023 #endif
2025 HostContentSettingsMap* content_settings =
2026 ProfileIOData::FromResourceContext(context)->GetHostContentSettingsMap();
2027 BlockedWindowParams blocked_params(target_url,
2028 referrer,
2029 disposition,
2030 features,
2031 user_gesture,
2032 opener_suppressed,
2033 render_process_id,
2034 opener_render_frame_id);
2036 if (!user_gesture &&
2037 !base::CommandLine::ForCurrentProcess()->HasSwitch(
2038 switches::kDisablePopupBlocking)) {
2039 if (content_settings->GetContentSetting(opener_top_level_frame_url,
2040 opener_top_level_frame_url,
2041 CONTENT_SETTINGS_TYPE_POPUPS,
2042 std::string()) !=
2043 CONTENT_SETTING_ALLOW) {
2044 BrowserThread::PostTask(BrowserThread::UI,
2045 FROM_HERE,
2046 base::Bind(&HandleBlockedPopupOnUIThread,
2047 blocked_params));
2048 return false;
2052 #if defined(OS_ANDROID)
2053 if (SingleTabModeTabHelper::IsRegistered(render_process_id,
2054 opener_render_view_id)) {
2055 BrowserThread::PostTask(BrowserThread::UI,
2056 FROM_HERE,
2057 base::Bind(&HandleSingleTabModeBlockOnUIThread,
2058 blocked_params));
2059 return false;
2061 #endif
2063 return true;
2066 void ChromeContentBrowserClient::ResourceDispatcherHostCreated() {
2067 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
2068 return g_browser_process->ResourceDispatcherHostCreated();
2071 content::SpeechRecognitionManagerDelegate*
2072 ChromeContentBrowserClient::CreateSpeechRecognitionManagerDelegate() {
2073 return new speech::ChromeSpeechRecognitionManagerDelegate();
2076 net::NetLog* ChromeContentBrowserClient::GetNetLog() {
2077 return g_browser_process->net_log();
2080 AccessTokenStore* ChromeContentBrowserClient::CreateAccessTokenStore() {
2081 return new ChromeAccessTokenStore();
2084 bool ChromeContentBrowserClient::IsFastShutdownPossible() {
2085 return true;
2088 void ChromeContentBrowserClient::OverrideWebkitPrefs(
2089 RenderViewHost* rvh, WebPreferences* web_prefs) {
2090 Profile* profile = Profile::FromBrowserContext(
2091 rvh->GetProcess()->GetBrowserContext());
2092 PrefService* prefs = profile->GetPrefs();
2094 // Fill per-script font preferences. These are not registered on Android
2095 // - http://crbug.com/308033.
2096 #if !defined(OS_ANDROID)
2097 FontFamilyCache::FillFontFamilyMap(profile,
2098 prefs::kWebKitStandardFontFamilyMap,
2099 &web_prefs->standard_font_family_map);
2100 FontFamilyCache::FillFontFamilyMap(profile,
2101 prefs::kWebKitFixedFontFamilyMap,
2102 &web_prefs->fixed_font_family_map);
2103 FontFamilyCache::FillFontFamilyMap(profile,
2104 prefs::kWebKitSerifFontFamilyMap,
2105 &web_prefs->serif_font_family_map);
2106 FontFamilyCache::FillFontFamilyMap(profile,
2107 prefs::kWebKitSansSerifFontFamilyMap,
2108 &web_prefs->sans_serif_font_family_map);
2109 FontFamilyCache::FillFontFamilyMap(profile,
2110 prefs::kWebKitCursiveFontFamilyMap,
2111 &web_prefs->cursive_font_family_map);
2112 FontFamilyCache::FillFontFamilyMap(profile,
2113 prefs::kWebKitFantasyFontFamilyMap,
2114 &web_prefs->fantasy_font_family_map);
2115 FontFamilyCache::FillFontFamilyMap(profile,
2116 prefs::kWebKitPictographFontFamilyMap,
2117 &web_prefs->pictograph_font_family_map);
2118 #endif
2120 web_prefs->default_font_size =
2121 prefs->GetInteger(prefs::kWebKitDefaultFontSize);
2122 web_prefs->default_fixed_font_size =
2123 prefs->GetInteger(prefs::kWebKitDefaultFixedFontSize);
2124 web_prefs->minimum_font_size =
2125 prefs->GetInteger(prefs::kWebKitMinimumFontSize);
2126 web_prefs->minimum_logical_font_size =
2127 prefs->GetInteger(prefs::kWebKitMinimumLogicalFontSize);
2129 web_prefs->default_encoding = prefs->GetString(prefs::kDefaultCharset);
2131 web_prefs->javascript_can_open_windows_automatically =
2132 prefs->GetBoolean(prefs::kWebKitJavascriptCanOpenWindowsAutomatically);
2133 web_prefs->dom_paste_enabled =
2134 prefs->GetBoolean(prefs::kWebKitDomPasteEnabled);
2135 web_prefs->tabs_to_links = prefs->GetBoolean(prefs::kWebkitTabsToLinks);
2137 if (!prefs->GetBoolean(prefs::kWebKitJavascriptEnabled))
2138 web_prefs->javascript_enabled = false;
2139 if (!prefs->GetBoolean(prefs::kWebKitWebSecurityEnabled))
2140 web_prefs->web_security_enabled = false;
2141 if (!prefs->GetBoolean(prefs::kWebKitPluginsEnabled))
2142 web_prefs->plugins_enabled = false;
2143 if (!prefs->GetBoolean(prefs::kWebKitJavaEnabled))
2144 web_prefs->java_enabled = false;
2145 web_prefs->loads_images_automatically =
2146 prefs->GetBoolean(prefs::kWebKitLoadsImagesAutomatically);
2148 if (prefs->GetBoolean(prefs::kDisable3DAPIs))
2149 web_prefs->experimental_webgl_enabled = false;
2151 web_prefs->allow_displaying_insecure_content =
2152 prefs->GetBoolean(prefs::kWebKitAllowDisplayingInsecureContent);
2153 web_prefs->allow_running_insecure_content =
2154 prefs->GetBoolean(prefs::kWebKitAllowRunningInsecureContent);
2155 #if defined(OS_ANDROID)
2156 web_prefs->font_scale_factor =
2157 static_cast<float>(prefs->GetDouble(prefs::kWebKitFontScaleFactor));
2158 web_prefs->device_scale_adjustment = GetDeviceScaleAdjustment();
2159 web_prefs->force_enable_zoom =
2160 prefs->GetBoolean(prefs::kWebKitForceEnableZoom);
2161 #endif
2163 #if defined(OS_ANDROID)
2164 web_prefs->password_echo_enabled =
2165 prefs->GetBoolean(prefs::kWebKitPasswordEchoEnabled);
2166 #else
2167 web_prefs->password_echo_enabled = browser_defaults::kPasswordEchoEnabled;
2168 #endif
2170 web_prefs->asynchronous_spell_checking_enabled = true;
2171 web_prefs->unified_textchecker_enabled = true;
2173 web_prefs->uses_universal_detector =
2174 prefs->GetBoolean(prefs::kWebKitUsesUniversalDetector);
2175 web_prefs->text_areas_are_resizable =
2176 prefs->GetBoolean(prefs::kWebKitTextAreasAreResizable);
2177 web_prefs->hyperlink_auditing_enabled =
2178 prefs->GetBoolean(prefs::kEnableHyperlinkAuditing);
2180 #if defined(ENABLE_EXTENSIONS)
2181 std::string image_animation_policy =
2182 prefs->GetString(prefs::kAnimationPolicy);
2183 if (image_animation_policy == kAnimationPolicyOnce)
2184 web_prefs->animation_policy =
2185 content::IMAGE_ANIMATION_POLICY_ANIMATION_ONCE;
2186 else if (image_animation_policy == kAnimationPolicyNone)
2187 web_prefs->animation_policy = content::IMAGE_ANIMATION_POLICY_NO_ANIMATION;
2188 else
2189 web_prefs->animation_policy = content::IMAGE_ANIMATION_POLICY_ALLOWED;
2190 #endif
2192 // Make sure we will set the default_encoding with canonical encoding name.
2193 web_prefs->default_encoding =
2194 CharacterEncoding::GetCanonicalEncodingNameByAliasName(
2195 web_prefs->default_encoding);
2196 if (web_prefs->default_encoding.empty()) {
2197 prefs->ClearPref(prefs::kDefaultCharset);
2198 web_prefs->default_encoding = prefs->GetString(prefs::kDefaultCharset);
2200 DCHECK(!web_prefs->default_encoding.empty());
2202 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2203 switches::kEnablePotentiallyAnnoyingSecurityFeatures)) {
2204 web_prefs->disable_reading_from_canvas = true;
2205 web_prefs->strict_mixed_content_checking = true;
2206 web_prefs->strict_powerful_feature_restrictions = true;
2209 for (size_t i = 0; i < extra_parts_.size(); ++i)
2210 extra_parts_[i]->OverrideWebkitPrefs(rvh, web_prefs);
2213 void ChromeContentBrowserClient::BrowserURLHandlerCreated(
2214 BrowserURLHandler* handler) {
2215 for (size_t i = 0; i < extra_parts_.size(); ++i)
2216 extra_parts_[i]->BrowserURLHandlerCreated(handler);
2218 // about: handler. Must come before chrome: handler, since it will
2219 // rewrite about: urls to chrome: URLs and then expect chrome: to
2220 // actually handle them. Also relies on a preliminary fixup phase.
2221 handler->SetFixupHandler(&FixupBrowserAboutURL);
2222 handler->AddHandlerPair(&WillHandleBrowserAboutURL,
2223 BrowserURLHandler::null_handler());
2225 #if defined(OS_ANDROID)
2226 // Handler to rewrite chrome://newtab on Android.
2227 handler->AddHandlerPair(&chrome::android::HandleAndroidNativePageURL,
2228 BrowserURLHandler::null_handler());
2229 #else
2230 // Handler to rewrite chrome://newtab for InstantExtended.
2231 handler->AddHandlerPair(&search::HandleNewTabURLRewrite,
2232 &search::HandleNewTabURLReverseRewrite);
2233 #endif
2235 // chrome: & friends.
2236 handler->AddHandlerPair(&HandleWebUI, &HandleWebUIReverse);
2239 void ChromeContentBrowserClient::ClearCache(RenderFrameHost* rfh) {
2240 Profile* profile = Profile::FromBrowserContext(
2241 rfh->GetSiteInstance()->GetProcess()->GetBrowserContext());
2242 BrowsingDataRemover* remover =
2243 BrowsingDataRemover::CreateForUnboundedRange(profile);
2244 remover->Remove(BrowsingDataRemover::REMOVE_CACHE,
2245 BrowsingDataHelper::UNPROTECTED_WEB);
2246 // BrowsingDataRemover takes care of deleting itself when done.
2249 void ChromeContentBrowserClient::ClearCookies(RenderFrameHost* rfh) {
2250 Profile* profile = Profile::FromBrowserContext(
2251 rfh->GetSiteInstance()->GetProcess()->GetBrowserContext());
2252 BrowsingDataRemover* remover =
2253 BrowsingDataRemover::CreateForUnboundedRange(profile);
2254 int remove_mask = BrowsingDataRemover::REMOVE_SITE_DATA;
2255 remover->Remove(remove_mask, BrowsingDataHelper::UNPROTECTED_WEB);
2256 // BrowsingDataRemover takes care of deleting itself when done.
2259 base::FilePath ChromeContentBrowserClient::GetDefaultDownloadDirectory() {
2260 return DownloadPrefs::GetDefaultDownloadDirectory();
2263 std::string ChromeContentBrowserClient::GetDefaultDownloadName() {
2264 return l10n_util::GetStringUTF8(IDS_DEFAULT_DOWNLOAD_FILENAME);
2267 void ChromeContentBrowserClient::DidCreatePpapiPlugin(
2268 content::BrowserPpapiHost* browser_host) {
2269 #if defined(ENABLE_PLUGINS)
2270 ChromeContentBrowserClientPluginsPart::DidCreatePpapiPlugin(browser_host);
2271 #endif
2274 content::BrowserPpapiHost*
2275 ChromeContentBrowserClient::GetExternalBrowserPpapiHost(
2276 int plugin_process_id) {
2277 #if !defined(DISABLE_NACL)
2278 content::BrowserChildProcessHostIterator iter(PROCESS_TYPE_NACL_LOADER);
2279 while (!iter.Done()) {
2280 nacl::NaClProcessHost* host = static_cast<nacl::NaClProcessHost*>(
2281 iter.GetDelegate());
2282 if (host->process() &&
2283 host->process()->GetData().id == plugin_process_id) {
2284 // Found the plugin.
2285 return host->browser_ppapi_host();
2287 ++iter;
2289 #endif
2290 return NULL;
2293 bool ChromeContentBrowserClient::AllowPepperSocketAPI(
2294 content::BrowserContext* browser_context,
2295 const GURL& url,
2296 bool private_api,
2297 const content::SocketPermissionRequest* params) {
2298 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
2299 return ChromeContentBrowserClientPluginsPart::AllowPepperSocketAPI(
2300 browser_context, url, private_api, params, allowed_socket_origins_);
2301 #else
2302 return false;
2303 #endif
2306 ui::SelectFilePolicy* ChromeContentBrowserClient::CreateSelectFilePolicy(
2307 WebContents* web_contents) {
2308 return new ChromeSelectFilePolicy(web_contents);
2311 void ChromeContentBrowserClient::GetAdditionalAllowedSchemesForFileSystem(
2312 std::vector<std::string>* additional_allowed_schemes) {
2313 ContentBrowserClient::GetAdditionalAllowedSchemesForFileSystem(
2314 additional_allowed_schemes);
2315 additional_allowed_schemes->push_back(content::kChromeDevToolsScheme);
2316 additional_allowed_schemes->push_back(content::kChromeUIScheme);
2317 for (size_t i = 0; i < extra_parts_.size(); ++i) {
2318 extra_parts_[i]->GetAdditionalAllowedSchemesForFileSystem(
2319 additional_allowed_schemes);
2323 void ChromeContentBrowserClient::GetURLRequestAutoMountHandlers(
2324 std::vector<storage::URLRequestAutoMountHandler>* handlers) {
2325 for (size_t i = 0; i < extra_parts_.size(); ++i)
2326 extra_parts_[i]->GetURLRequestAutoMountHandlers(handlers);
2329 void ChromeContentBrowserClient::GetAdditionalFileSystemBackends(
2330 content::BrowserContext* browser_context,
2331 const base::FilePath& storage_partition_path,
2332 ScopedVector<storage::FileSystemBackend>* additional_backends) {
2333 #if defined(OS_CHROMEOS)
2334 storage::ExternalMountPoints* external_mount_points =
2335 content::BrowserContext::GetMountPoints(browser_context);
2336 DCHECK(external_mount_points);
2337 chromeos::FileSystemBackend* backend = new chromeos::FileSystemBackend(
2338 new drive::FileSystemBackendDelegate,
2339 new chromeos::file_system_provider::BackendDelegate,
2340 new chromeos::MTPFileSystemBackendDelegate(storage_partition_path),
2341 external_mount_points,
2342 storage::ExternalMountPoints::GetSystemInstance());
2343 backend->AddSystemMountPoints();
2344 DCHECK(backend->CanHandleType(storage::kFileSystemTypeExternal));
2345 additional_backends->push_back(backend);
2346 #endif
2348 for (size_t i = 0; i < extra_parts_.size(); ++i) {
2349 extra_parts_[i]->GetAdditionalFileSystemBackends(
2350 browser_context, storage_partition_path, additional_backends);
2354 #if defined(OS_ANDROID)
2355 void ChromeContentBrowserClient::GetAdditionalMappedFilesForChildProcess(
2356 const base::CommandLine& command_line,
2357 int child_process_id,
2358 FileDescriptorInfo* mappings,
2359 std::map<int, base::MemoryMappedFile::Region>* regions) {
2360 int fd = ui::GetMainAndroidPackFd(
2361 &(*regions)[kAndroidUIResourcesPakDescriptor]);
2362 mappings->Share(kAndroidUIResourcesPakDescriptor, fd);
2364 fd = ui::GetCommonResourcesPackFd(
2365 &(*regions)[kAndroidChrome100PercentPakDescriptor]);
2366 mappings->Share(kAndroidChrome100PercentPakDescriptor, fd);
2368 fd = ui::GetLocalePackFd(&(*regions)[kAndroidLocalePakDescriptor]);
2369 mappings->Share(kAndroidLocalePakDescriptor, fd);
2371 if (breakpad::IsCrashReporterEnabled()) {
2372 base::File file =
2373 breakpad::CrashDumpManager::GetInstance()->CreateMinidumpFile(
2374 child_process_id);
2375 if (file.IsValid()) {
2376 mappings->Transfer(kAndroidMinidumpDescriptor,
2377 base::ScopedFD(file.TakePlatformFile()));
2378 } else {
2379 LOG(ERROR) << "Failed to create file for minidump, crash reporting will "
2380 "be disabled for this process.";
2384 base::FilePath app_data_path;
2385 PathService::Get(base::DIR_ANDROID_APP_DATA, &app_data_path);
2386 DCHECK(!app_data_path.empty());
2388 #elif defined(OS_POSIX) && !defined(OS_MACOSX)
2389 void ChromeContentBrowserClient::GetAdditionalMappedFilesForChildProcess(
2390 const base::CommandLine& command_line,
2391 int child_process_id,
2392 FileDescriptorInfo* mappings) {
2393 int crash_signal_fd = GetCrashSignalFD(command_line);
2394 if (crash_signal_fd >= 0) {
2395 mappings->Share(kCrashDumpSignal, crash_signal_fd);
2398 #endif // defined(OS_ANDROID)
2400 #if defined(OS_WIN)
2401 const wchar_t* ChromeContentBrowserClient::GetResourceDllName() {
2402 return chrome::kBrowserResourcesDll;
2405 base::string16 ChromeContentBrowserClient::GetAppContainerSidForSandboxType(
2406 int sandbox_type) const {
2407 base::string16 sid;
2409 #if defined(GOOGLE_CHROME_BUILD)
2410 const version_info::Channel channel = chrome::GetChannel();
2412 // It's possible to have a SxS installation running at the same time as a
2413 // non-SxS so isolate them from each other.
2414 if (channel == version_info::Channel::CANARY) {
2415 sid.assign(
2416 L"S-1-15-2-3251537155-1984446955-2931258699-841473695-1938553385-"
2417 L"924012150-");
2418 } else {
2419 sid.assign(
2420 L"S-1-15-2-3251537155-1984446955-2931258699-841473695-1938553385-"
2421 L"924012149-");
2423 #else
2424 sid.assign(
2425 L"S-1-15-2-3251537155-1984446955-2931258699-841473695-1938553385-"
2426 L"924012148-");
2427 #endif
2429 // TODO(wfh): Add support for more process types here. crbug.com/499523
2430 switch (sandbox_type) {
2431 case content::SANDBOX_TYPE_RENDERER:
2432 return sid + L"129201922";
2433 case content::SANDBOX_TYPE_UTILITY:
2434 return base::string16();
2435 case content::SANDBOX_TYPE_GPU:
2436 return base::string16();
2437 case content::SANDBOX_TYPE_PPAPI:
2438 return sid + L"129201925";
2439 #if !defined(DISABLE_NACL)
2440 case PROCESS_TYPE_NACL_LOADER:
2441 return base::string16();
2442 case PROCESS_TYPE_NACL_BROKER:
2443 return base::string16();
2444 #endif
2447 // Should never reach here.
2448 CHECK(0);
2449 return base::string16();
2452 void ChromeContentBrowserClient::PreSpawnRenderer(
2453 sandbox::TargetPolicy* policy,
2454 bool* success) {
2455 // This code is duplicated in nacl_exe_win_64.cc.
2456 // Allow the server side of a pipe restricted to the "chrome.nacl."
2457 // namespace so that it cannot impersonate other system or other chrome
2458 // service pipes.
2459 sandbox::ResultCode result = policy->AddRule(
2460 sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
2461 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
2462 L"\\\\.\\pipe\\chrome.nacl.*");
2463 if (result != sandbox::SBOX_ALL_OK) {
2464 *success = false;
2465 return;
2468 // Renderers need to send named pipe handles and shared memory
2469 // segment handles to NaCl loader processes.
2470 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
2471 sandbox::TargetPolicy::HANDLES_DUP_ANY,
2472 L"File");
2473 if (result != sandbox::SBOX_ALL_OK) {
2474 *success = false;
2475 return;
2478 #endif
2480 void ChromeContentBrowserClient::RegisterFrameMojoShellServices(
2481 content::ServiceRegistry* registry,
2482 content::RenderFrameHost* render_frame_host) {
2483 #if defined(OS_CHROMEOS)
2484 registry->AddService(
2485 base::Bind(&chromeos::attestation::PlatformVerificationImpl::Create,
2486 render_frame_host));
2487 #endif
2490 void ChromeContentBrowserClient::RegisterInProcessMojoApplications(
2491 StaticMojoApplicationMap* apps) {
2492 #if !defined(OS_ANDROID) && !defined(OS_IOS)
2493 apps->insert(std::make_pair(GURL(device::kDevicesMojoAppUrl),
2494 base::Bind(&device::DevicesAppFactory::CreateApp,
2495 base::ThreadTaskRunnerHandle::Get())));
2496 #endif
2499 void ChromeContentBrowserClient::OpenURL(
2500 content::BrowserContext* browser_context,
2501 const content::OpenURLParams& params,
2502 const base::Callback<void(content::WebContents*)>& callback) {
2503 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2505 #if !defined(OS_ANDROID) && !defined(OS_IOS)
2506 NavigateParams nav_params(Profile::FromBrowserContext(browser_context),
2507 params.url,
2508 params.transition);
2509 FillNavigateParamsFromOpenURLParams(&nav_params, params);
2510 nav_params.user_gesture = params.user_gesture;
2512 Navigate(&nav_params);
2513 callback.Run(nav_params.target_contents);
2514 #elif defined(OS_ANDROID)
2515 service_tab_launcher::ServiceTabLauncher::GetInstance()->LaunchTab(
2516 browser_context, params, callback);
2517 #else
2518 NOTIMPLEMENTED();
2519 #endif
2522 content::PresentationServiceDelegate*
2523 ChromeContentBrowserClient::GetPresentationServiceDelegate(
2524 content::WebContents* web_contents) {
2525 #if defined(ENABLE_MEDIA_ROUTER)
2526 if (switches::MediaRouterEnabled()) {
2527 return media_router::PresentationServiceDelegateImpl::
2528 GetOrCreateForWebContents(web_contents);
2530 #endif
2531 return nullptr;
2534 void ChromeContentBrowserClient::RecordURLMetric(const std::string& metric,
2535 const GURL& url) {
2536 if (url.is_valid()) {
2537 rappor::SampleDomainAndRegistryFromGURL(g_browser_process->rappor_service(),
2538 metric, url);
2542 content::DevToolsManagerDelegate*
2543 ChromeContentBrowserClient::GetDevToolsManagerDelegate() {
2544 return new ChromeDevToolsManagerDelegate();
2547 content::TracingDelegate* ChromeContentBrowserClient::GetTracingDelegate() {
2548 #if !defined(OS_ANDROID)
2549 return new ChromeTracingDelegate();
2550 #else
2551 return nullptr;
2552 #endif
2555 bool ChromeContentBrowserClient::IsPluginAllowedToCallRequestOSFileHandle(
2556 content::BrowserContext* browser_context,
2557 const GURL& url) {
2558 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
2559 return ChromeContentBrowserClientPluginsPart::
2560 IsPluginAllowedToCallRequestOSFileHandle(browser_context, url,
2561 allowed_file_handle_origins_);
2562 #else
2563 return false;
2564 #endif
2567 bool ChromeContentBrowserClient::IsPluginAllowedToUseDevChannelAPIs(
2568 content::BrowserContext* browser_context,
2569 const GURL& url) {
2570 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
2571 return ChromeContentBrowserClientPluginsPart::
2572 IsPluginAllowedToUseDevChannelAPIs(browser_context, url,
2573 allowed_dev_channel_origins_);
2574 #else
2575 return false;
2576 #endif
2579 void ChromeContentBrowserClient::OverridePageVisibilityState(
2580 RenderFrameHost* render_frame_host,
2581 blink::WebPageVisibilityState* visibility_state) {
2582 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
2584 WebContents* web_contents =
2585 WebContents::FromRenderFrameHost(render_frame_host);
2586 DCHECK(web_contents);
2588 Profile* profile =
2589 Profile::FromBrowserContext(web_contents->GetBrowserContext());
2590 prerender::PrerenderManager* prerender_manager =
2591 prerender::PrerenderManagerFactory::GetForProfile(profile);
2592 if (prerender_manager &&
2593 prerender_manager->IsWebContentsPrerendering(web_contents, nullptr)) {
2594 *visibility_state = blink::WebPageVisibilityStatePrerender;
2598 #if defined(ENABLE_WEBRTC)
2599 void ChromeContentBrowserClient::MaybeCopyDisableWebRtcEncryptionSwitch(
2600 base::CommandLine* to_command_line,
2601 const base::CommandLine& from_command_line,
2602 version_info::Channel channel) {
2603 #if defined(OS_ANDROID)
2604 const version_info::Channel kMaxDisableEncryptionChannel =
2605 version_info::Channel::BETA;
2606 #else
2607 const version_info::Channel kMaxDisableEncryptionChannel =
2608 version_info::Channel::DEV;
2609 #endif
2610 if (channel <= kMaxDisableEncryptionChannel) {
2611 static const char* const kWebRtcDevSwitchNames[] = {
2612 switches::kDisableWebRtcEncryption,
2614 to_command_line->CopySwitchesFrom(from_command_line,
2615 kWebRtcDevSwitchNames,
2616 arraysize(kWebRtcDevSwitchNames));
2619 #endif // defined(ENABLE_WEBRTC)
2621 } // namespace chrome