Only grant permissions to new extensions from sync if they have the expected version
[chromium-blink-merge.git] / chrome / browser / chrome_content_browser_client.cc
blob63925193a9b2c8d249ce37bd116bda2aacf7bc76
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 #if !defined(OS_ANDROID) && !defined(OS_IOS)
263 #include "chrome/browser/usb/web_usb_permission_provider.h"
264 #endif
266 using base::FileDescriptor;
267 using blink::WebWindowFeatures;
268 using content::AccessTokenStore;
269 using content::BrowserThread;
270 using content::BrowserURLHandler;
271 using content::ChildProcessSecurityPolicy;
272 using content::QuotaPermissionContext;
273 using content::RenderFrameHost;
274 using content::RenderViewHost;
275 using content::ResourceType;
276 using content::SiteInstance;
277 using content::WebContents;
278 using content::WebPreferences;
279 using message_center::NotifierId;
281 #if defined(OS_POSIX)
282 using content::FileDescriptorInfo;
283 #endif
285 #if defined(ENABLE_EXTENSIONS)
286 using extensions::APIPermission;
287 using extensions::ChromeContentBrowserClientExtensionsPart;
288 using extensions::Extension;
289 using extensions::InfoMap;
290 using extensions::Manifest;
291 #endif
293 #if defined(ENABLE_PLUGINS)
294 using plugins::ChromeContentBrowserClientPluginsPart;
295 #endif
297 namespace {
299 // Cached version of the locale so we can return the locale on the I/O
300 // thread.
301 base::LazyInstance<std::string> g_io_thread_application_locale;
303 #if defined(ENABLE_PLUGINS)
304 // TODO(teravest): Add renderer-side API-specific checking for these APIs so
305 // that blanket permission isn't granted to all dev channel APIs for these.
306 // http://crbug.com/386743
307 const char* const kPredefinedAllowedDevChannelOrigins[] = {
308 "6EAED1924DB611B6EEF2A664BD077BE7EAD33B8F", // see crbug.com/383937
309 "4EB74897CB187C7633357C2FE832E0AD6A44883A" // see crbug.com/383937
312 const char* const kPredefinedAllowedFileHandleOrigins[] = {
313 "6EAED1924DB611B6EEF2A664BD077BE7EAD33B8F", // see crbug.com/234789
314 "4EB74897CB187C7633357C2FE832E0AD6A44883A" // see crbug.com/234789
317 const char* const kPredefinedAllowedSocketOrigins[] = {
318 "okddffdblfhhnmhodogpojmfkjmhinfp", // Test SSH Client
319 "pnhechapfaindjhompbnflcldabbghjo", // HTerm App (SSH Client)
320 "bglhmjfplikpjnfoegeomebmfnkjomhe", // see crbug.com/122126
321 "gbchcmhmhahfdphkhkmpfmihenigjmpp", // Chrome Remote Desktop
322 "kgngmbheleoaphbjbaiobfdepmghbfah", // Pre-release Chrome Remote Desktop
323 "odkaodonbgfohohmklejpjiejmcipmib", // Dogfood Chrome Remote Desktop
324 "ojoimpklfciegopdfgeenehpalipignm", // Chromoting canary
325 "cbkkbcmdlboombapidmoeolnmdacpkch", // see crbug.com/129089
326 "hhnbmknkdabfoieppbbljkhkfjcmcbjh", // see crbug.com/134099
327 "mablfbjkhmhkmefkjjacnbaikjkipphg", // see crbug.com/134099
328 "pdeelgamlgannhelgoegilelnnojegoh", // see crbug.com/134099
329 "cabapfdbkniadpollkckdnedaanlciaj", // see crbug.com/134099
330 "mapljbgnjledlpdmlchihnmeclmefbba", // see crbug.com/134099
331 "ghbfeebgmiidnnmeobbbaiamklmpbpii", // see crbug.com/134099
332 "jdfhpkjeckflbbleddjlpimecpbjdeep", // see crbug.com/142514
333 "iabmpiboiopbgfabjmgeedhcmjenhbla", // see crbug.com/165080
334 "B7CF8A292249681AF81771650BA4CEEAF19A4560", // see crbug.com/165080
335 "7525AF4F66763A70A883C4700529F647B470E4D2", // see crbug.com/238084
336 "0B549507088E1564D672F7942EB87CA4DAD73972", // see crbug.com/238084
337 "864288364E239573E777D3E0E36864E590E95C74" // see crbug.com/238084
339 #endif
341 // Returns a copy of the given url with its host set to given host and path set
342 // to given path. Other parts of the url will be the same.
343 GURL ReplaceURLHostAndPath(const GURL& url,
344 const std::string& host,
345 const std::string& path) {
346 url::Replacements<char> replacements;
347 replacements.SetHost(host.c_str(), url::Component(0, host.length()));
348 replacements.SetPath(path.c_str(), url::Component(0, path.length()));
349 return url.ReplaceComponents(replacements);
352 // Maps "foo://bar/baz/" to "foo://chrome/bar/baz/".
353 GURL AddUberHost(const GURL& url) {
354 const std::string uber_host = chrome::kChromeUIUberHost;
355 const std::string new_path = url.host() + url.path();
357 return ReplaceURLHostAndPath(url, uber_host, new_path);
360 // If url->host() is "chrome" and url->path() has characters other than the
361 // first slash, changes the url from "foo://chrome/bar/" to "foo://bar/" and
362 // returns true. Otherwise returns false.
363 bool RemoveUberHost(GURL* url) {
364 if (url->host() != chrome::kChromeUIUberHost)
365 return false;
367 if (url->path().empty() || url->path() == "/")
368 return false;
370 const std::string old_path = url->path();
372 const std::string::size_type separator = old_path.find('/', 1);
373 std::string new_host;
374 std::string new_path;
375 if (separator == std::string::npos) {
376 new_host = old_path.substr(1);
377 } else {
378 new_host = old_path.substr(1, separator - 1);
379 new_path = old_path.substr(separator);
382 // Do not allow URLs with paths empty before the first slash since we can't
383 // have an empty host. (e.g "foo://chrome//")
384 if (new_host.empty())
385 return false;
387 *url = ReplaceURLHostAndPath(*url, new_host, new_path);
389 DCHECK(url->is_valid());
391 return true;
394 // Handles rewriting Web UI URLs.
395 bool HandleWebUI(GURL* url, content::BrowserContext* browser_context) {
396 // Do not handle special URLs such as "about:foo"
397 if (!url->host().empty()) {
398 const GURL chrome_url = AddUberHost(*url);
400 // Handle valid "chrome://chrome/foo" URLs so the reverse handler will
401 // be called.
402 if (ChromeWebUIControllerFactory::GetInstance()->UseWebUIForURL(
403 browser_context, chrome_url))
404 return true;
407 if (!ChromeWebUIControllerFactory::GetInstance()->UseWebUIForURL(
408 browser_context, *url))
409 return false;
411 #if defined(OS_CHROMEOS)
412 // Special case : in ChromeOS in Guest mode bookmarks and history are
413 // disabled for security reasons. New tab page explains the reasons, so
414 // we redirect user to new tab page.
415 if (user_manager::UserManager::Get()->IsLoggedInAsGuest()) {
416 if (url->SchemeIs(content::kChromeUIScheme) &&
417 (url->DomainIs(chrome::kChromeUIBookmarksHost) ||
418 url->DomainIs(chrome::kChromeUIHistoryHost))) {
419 // Rewrite with new tab URL
420 *url = GURL(chrome::kChromeUINewTabURL);
423 #endif
425 return true;
428 // Reverse URL handler for Web UI. Maps "chrome://chrome/foo/" to
429 // "chrome://foo/".
430 bool HandleWebUIReverse(GURL* url, content::BrowserContext* browser_context) {
431 if (!url->is_valid() || !url->SchemeIs(content::kChromeUIScheme))
432 return false;
434 return RemoveUberHost(url);
437 bool CertMatchesFilter(const net::X509Certificate& cert,
438 const base::DictionaryValue& filter) {
439 // TODO(markusheintz): This is the minimal required filter implementation.
440 // Implement a better matcher.
442 // An empty filter matches any client certificate since no requirements are
443 // specified at all.
444 if (filter.empty())
445 return true;
447 std::string common_name;
448 if (filter.GetString("ISSUER.CN", &common_name) &&
449 (cert.issuer().common_name == common_name)) {
450 return true;
452 return false;
455 #if defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_MACOSX)
456 breakpad::CrashHandlerHostLinux* CreateCrashHandlerHost(
457 const std::string& process_type) {
458 base::FilePath dumps_path;
459 PathService::Get(chrome::DIR_CRASH_DUMPS, &dumps_path);
461 ANNOTATE_SCOPED_MEMORY_LEAK;
462 bool upload = (getenv(env_vars::kHeadless) == NULL);
463 breakpad::CrashHandlerHostLinux* crash_handler =
464 new breakpad::CrashHandlerHostLinux(process_type, dumps_path, upload);
465 crash_handler->StartUploaderThread();
466 return crash_handler;
470 int GetCrashSignalFD(const base::CommandLine& command_line) {
471 // Extensions have the same process type as renderers.
472 if (command_line.HasSwitch(extensions::switches::kExtensionProcess)) {
473 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
474 if (!crash_handler)
475 crash_handler = CreateCrashHandlerHost("extension");
476 return crash_handler->GetDeathSignalSocket();
479 std::string process_type =
480 command_line.GetSwitchValueASCII(switches::kProcessType);
482 if (process_type == switches::kRendererProcess) {
483 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
484 if (!crash_handler)
485 crash_handler = CreateCrashHandlerHost(process_type);
486 return crash_handler->GetDeathSignalSocket();
489 if (process_type == switches::kPluginProcess) {
490 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
491 if (!crash_handler)
492 crash_handler = CreateCrashHandlerHost(process_type);
493 return crash_handler->GetDeathSignalSocket();
496 if (process_type == switches::kPpapiPluginProcess) {
497 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
498 if (!crash_handler)
499 crash_handler = CreateCrashHandlerHost(process_type);
500 return crash_handler->GetDeathSignalSocket();
503 if (process_type == switches::kGpuProcess) {
504 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
505 if (!crash_handler)
506 crash_handler = CreateCrashHandlerHost(process_type);
507 return crash_handler->GetDeathSignalSocket();
510 return -1;
512 #endif // defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_MACOSX)
514 void SetApplicationLocaleOnIOThread(const std::string& locale) {
515 DCHECK_CURRENTLY_ON(BrowserThread::IO);
516 g_io_thread_application_locale.Get() = locale;
519 void HandleBlockedPopupOnUIThread(const BlockedWindowParams& params) {
520 RenderFrameHost* render_frame_host = RenderFrameHost::FromID(
521 params.render_process_id(), params.opener_render_frame_id());
522 if (!render_frame_host)
523 return;
524 WebContents* tab = WebContents::FromRenderFrameHost(render_frame_host);
525 // The tab might already have navigated away. We only need to do this check
526 // for main frames, since the RenderFrameHost for a subframe opener will have
527 // already been deleted if the main frame navigates away.
528 if (!tab ||
529 (!render_frame_host->GetParent() &&
530 tab->GetMainFrame() != render_frame_host))
531 return;
533 prerender::PrerenderContents* prerender_contents =
534 prerender::PrerenderContents::FromWebContents(tab);
535 if (prerender_contents) {
536 prerender_contents->Destroy(prerender::FINAL_STATUS_CREATE_NEW_WINDOW);
537 return;
540 PopupBlockerTabHelper* popup_helper =
541 PopupBlockerTabHelper::FromWebContents(tab);
542 if (!popup_helper)
543 return;
544 popup_helper->AddBlockedPopup(params);
547 // An implementation of the SSLCertReporter interface used by
548 // SSLErrorHandler. Uses the SafeBrowsing UI manager to send invalid
549 // certificate reports.
550 class SafeBrowsingSSLCertReporter : public SSLCertReporter {
551 public:
552 explicit SafeBrowsingSSLCertReporter(
553 const scoped_refptr<SafeBrowsingUIManager>& safe_browsing_ui_manager)
554 : safe_browsing_ui_manager_(safe_browsing_ui_manager) {}
555 ~SafeBrowsingSSLCertReporter() override {}
557 // SSLCertReporter implementation
558 void ReportInvalidCertificateChain(
559 const std::string& serialized_report) override {
560 if (safe_browsing_ui_manager_) {
561 safe_browsing_ui_manager_->ReportInvalidCertificateChain(
562 serialized_report, base::Bind(&base::DoNothing));
566 private:
567 const scoped_refptr<SafeBrowsingUIManager> safe_browsing_ui_manager_;
570 #if defined(OS_ANDROID)
572 void HandleSingleTabModeBlockOnUIThread(const BlockedWindowParams& params) {
573 WebContents* web_contents = tab_util::GetWebContentsByFrameID(
574 params.render_process_id(), params.opener_render_frame_id());
575 if (!web_contents)
576 return;
578 SingleTabModeTabHelper::FromWebContents(web_contents)->HandleOpenUrl(params);
581 float GetDeviceScaleAdjustment() {
582 static const float kMinFSM = 1.05f;
583 static const int kWidthForMinFSM = 320;
584 static const float kMaxFSM = 1.3f;
585 static const int kWidthForMaxFSM = 800;
587 gfx::DeviceDisplayInfo info;
588 int minWidth = info.GetSmallestDIPWidth();
590 if (minWidth <= kWidthForMinFSM)
591 return kMinFSM;
592 if (minWidth >= kWidthForMaxFSM)
593 return kMaxFSM;
595 // The font scale multiplier varies linearly between kMinFSM and kMaxFSM.
596 float ratio = static_cast<float>(minWidth - kWidthForMinFSM) /
597 (kWidthForMaxFSM - kWidthForMinFSM);
598 return ratio * (kMaxFSM - kMinFSM) + kMinFSM;
601 #endif // defined(OS_ANDROID)
603 #if defined(ENABLE_EXTENSIONS)
604 // By default, JavaScript and images are enabled in guest content.
605 void GetGuestViewDefaultContentSettingRules(
606 bool incognito,
607 RendererContentSettingRules* rules) {
608 rules->image_rules.push_back(
609 ContentSettingPatternSource(ContentSettingsPattern::Wildcard(),
610 ContentSettingsPattern::Wildcard(),
611 CONTENT_SETTING_ALLOW,
612 std::string(),
613 incognito));
615 rules->script_rules.push_back(
616 ContentSettingPatternSource(ContentSettingsPattern::Wildcard(),
617 ContentSettingsPattern::Wildcard(),
618 CONTENT_SETTING_ALLOW,
619 std::string(),
620 incognito));
622 #endif // defined(ENABLE_EXTENSIONS)
624 } // namespace
626 namespace chrome {
628 ChromeContentBrowserClient::ChromeContentBrowserClient()
630 weak_factory_(this) {
631 #if defined(ENABLE_PLUGINS)
632 for (size_t i = 0; i < arraysize(kPredefinedAllowedDevChannelOrigins); ++i)
633 allowed_dev_channel_origins_.insert(kPredefinedAllowedDevChannelOrigins[i]);
634 for (size_t i = 0; i < arraysize(kPredefinedAllowedFileHandleOrigins); ++i)
635 allowed_file_handle_origins_.insert(kPredefinedAllowedFileHandleOrigins[i]);
636 for (size_t i = 0; i < arraysize(kPredefinedAllowedSocketOrigins); ++i)
637 allowed_socket_origins_.insert(kPredefinedAllowedSocketOrigins[i]);
639 extra_parts_.push_back(new ChromeContentBrowserClientPluginsPart);
640 #endif
642 #if !defined(OS_ANDROID)
643 TtsExtensionEngine* tts_extension_engine = TtsExtensionEngine::GetInstance();
644 TtsController::GetInstance()->SetTtsEngineDelegate(tts_extension_engine);
645 #endif
647 #if defined(ENABLE_EXTENSIONS)
648 extra_parts_.push_back(new ChromeContentBrowserClientExtensionsPart);
649 #endif
652 ChromeContentBrowserClient::~ChromeContentBrowserClient() {
653 for (int i = static_cast<int>(extra_parts_.size()) - 1; i >= 0; --i)
654 delete extra_parts_[i];
655 extra_parts_.clear();
658 // static
659 void ChromeContentBrowserClient::RegisterProfilePrefs(
660 user_prefs::PrefRegistrySyncable* registry) {
661 registry->RegisterBooleanPref(prefs::kDisable3DAPIs, false);
662 registry->RegisterBooleanPref(prefs::kEnableHyperlinkAuditing, true);
663 registry->RegisterListPref(prefs::kEnableDeprecatedWebPlatformFeatures);
666 // static
667 void ChromeContentBrowserClient::SetApplicationLocale(
668 const std::string& locale) {
669 DCHECK_CURRENTLY_ON(BrowserThread::UI);
671 // This object is guaranteed to outlive all threads so we don't have to
672 // worry about the lack of refcounting and can just post as Unretained.
674 // The common case is that this function is called early in Chrome startup
675 // before any threads are created (it will also be called later if the user
676 // changes the pref). In this case, there will be no threads created and
677 // posting will fail. When there are no threads, we can just set the string
678 // without worrying about threadsafety.
679 if (!BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
680 base::Bind(&SetApplicationLocaleOnIOThread, locale))) {
681 g_io_thread_application_locale.Get() = locale;
685 content::BrowserMainParts* ChromeContentBrowserClient::CreateBrowserMainParts(
686 const content::MainFunctionParams& parameters) {
687 ChromeBrowserMainParts* main_parts;
688 // Construct the Main browser parts based on the OS type.
689 #if defined(OS_WIN)
690 main_parts = new ChromeBrowserMainPartsWin(parameters);
691 #elif defined(OS_MACOSX)
692 main_parts = new ChromeBrowserMainPartsMac(parameters);
693 #elif defined(OS_CHROMEOS)
694 main_parts = new chromeos::ChromeBrowserMainPartsChromeos(parameters);
695 #elif defined(OS_LINUX)
696 main_parts = new ChromeBrowserMainPartsLinux(parameters);
697 #elif defined(OS_ANDROID)
698 main_parts = new ChromeBrowserMainPartsAndroid(parameters);
699 #elif defined(OS_POSIX)
700 main_parts = new ChromeBrowserMainPartsPosix(parameters);
701 #else
702 NOTREACHED();
703 main_parts = new ChromeBrowserMainParts(parameters);
704 #endif
706 chrome::AddProfilesExtraParts(main_parts);
708 // Construct additional browser parts. Stages are called in the order in
709 // which they are added.
710 #if defined(TOOLKIT_VIEWS)
711 main_parts->AddParts(new ChromeBrowserMainExtraPartsViews());
712 #endif
714 // TODO(oshima): Athena on chrome currently requires USE_ASH to build.
715 // We should reduce the dependency as much as possible.
716 #if defined(USE_ASH)
717 main_parts->AddParts(new ChromeBrowserMainExtraPartsAsh());
718 #endif
720 #if defined(USE_AURA)
721 main_parts->AddParts(new ChromeBrowserMainExtraPartsAura());
722 #endif
724 #if defined(USE_X11)
725 main_parts->AddParts(new ChromeBrowserMainExtraPartsX11());
726 #endif
728 chrome::AddMetricsExtraParts(main_parts);
730 return main_parts;
733 void ChromeContentBrowserClient::PostAfterStartupTask(
734 const tracked_objects::Location& from_here,
735 const scoped_refptr<base::TaskRunner>& task_runner,
736 const base::Closure& task) {
737 AfterStartupTaskUtils::PostTask(from_here, task_runner, task);
740 std::string ChromeContentBrowserClient::GetStoragePartitionIdForSite(
741 content::BrowserContext* browser_context,
742 const GURL& site) {
743 std::string partition_id;
745 // The partition ID for webview guest processes is the string value of its
746 // SiteInstance URL - "chrome-guest://app_id/persist?partition".
747 if (site.SchemeIs(content::kGuestScheme)) {
748 partition_id = site.spec();
749 } else if (!switches::IsEnableWebviewBasedSignin() &&
750 site.GetOrigin().spec() == kChromeUIChromeSigninURL) {
751 // The non-webview Chrome signin page has an embedded iframe of extension
752 // and web content, thus it must be isolated from other webUI pages.
753 partition_id = site.GetOrigin().spec();
756 DCHECK(IsValidStoragePartitionId(browser_context, partition_id));
757 return partition_id;
760 bool ChromeContentBrowserClient::IsValidStoragePartitionId(
761 content::BrowserContext* browser_context,
762 const std::string& partition_id) {
763 // The default ID is empty and is always valid.
764 if (partition_id.empty())
765 return true;
767 return GURL(partition_id).is_valid();
770 void ChromeContentBrowserClient::GetStoragePartitionConfigForSite(
771 content::BrowserContext* browser_context,
772 const GURL& site,
773 bool can_be_default,
774 std::string* partition_domain,
775 std::string* partition_name,
776 bool* in_memory) {
777 // Default to the browser-wide storage partition and override based on |site|
778 // below.
779 partition_domain->clear();
780 partition_name->clear();
781 *in_memory = false;
783 bool success = false;
784 #if defined(ENABLE_EXTENSIONS)
785 success = extensions::WebViewGuest::GetGuestPartitionConfigForSite(
786 site, partition_domain, partition_name, in_memory);
788 if (!success && site.SchemeIs(extensions::kExtensionScheme)) {
789 // If |can_be_default| is false, the caller is stating that the |site|
790 // should be parsed as if it had isolated storage. In particular it is
791 // important to NOT check ExtensionService for the is_storage_isolated()
792 // attribute because this code path is run during Extension uninstall
793 // to do cleanup after the Extension has already been unloaded from the
794 // ExtensionService.
795 bool is_isolated = !can_be_default;
796 if (can_be_default) {
797 if (extensions::util::SiteHasIsolatedStorage(site, browser_context))
798 is_isolated = true;
801 if (is_isolated) {
802 CHECK(site.has_host());
803 // For extensions with isolated storage, the the host of the |site| is
804 // the |partition_domain|. The |in_memory| and |partition_name| are only
805 // used in guest schemes so they are cleared here.
806 *partition_domain = site.host();
807 *in_memory = false;
808 partition_name->clear();
810 success = true;
812 #endif
814 if (!success && (!switches::IsEnableWebviewBasedSignin() &&
815 site.GetOrigin().spec() == kChromeUIChromeSigninURL)) {
816 // The non-webview Chrome signin page has an embedded iframe of extension
817 // and web content, thus it must be isolated from other webUI pages.
818 *partition_domain = chrome::kChromeUIChromeSigninHost;
821 // Assert that if |can_be_default| is false, the code above must have found a
822 // non-default partition. If this fails, the caller has a serious logic
823 // error about which StoragePartition they expect to be in and it is not
824 // safe to continue.
825 CHECK(can_be_default || !partition_domain->empty());
828 content::WebContentsViewDelegate*
829 ChromeContentBrowserClient::GetWebContentsViewDelegate(
830 content::WebContents* web_contents) {
831 return chrome::CreateWebContentsViewDelegate(web_contents);
834 void ChromeContentBrowserClient::RenderProcessWillLaunch(
835 content::RenderProcessHost* host) {
836 int id = host->GetID();
837 Profile* profile = Profile::FromBrowserContext(host->GetBrowserContext());
838 net::URLRequestContextGetter* context =
839 profile->GetRequestContextForRenderProcess(id);
841 host->AddFilter(new ChromeRenderMessageFilter(id, profile));
842 #if defined(ENABLE_EXTENSIONS)
843 host->AddFilter(new cast::CastTransportHostFilter);
844 #endif
845 #if defined(ENABLE_PRINTING)
846 host->AddFilter(new printing::PrintingMessageFilter(id, profile));
847 #endif
848 host->AddFilter(new SearchProviderInstallStateMessageFilter(id, profile));
849 #if defined(ENABLE_SPELLCHECK)
850 host->AddFilter(new SpellCheckMessageFilter(id));
851 #endif
852 #if defined(USE_BROWSER_SPELLCHECKER)
853 host->AddFilter(new SpellCheckMessageFilterPlatform(id));
854 #endif
855 host->AddFilter(new ChromeNetBenchmarkingMessageFilter(profile, context));
856 host->AddFilter(new prerender::PrerenderMessageFilter(id, profile));
857 host->AddFilter(new TtsMessageFilter(host->GetBrowserContext()));
858 #if defined(ENABLE_WEBRTC)
859 WebRtcLoggingHandlerHost* webrtc_logging_handler_host =
860 new WebRtcLoggingHandlerHost(profile);
861 host->SetWebRtcLogMessageCallback(base::Bind(
862 &WebRtcLoggingHandlerHost::LogMessage, webrtc_logging_handler_host));
863 host->AddFilter(webrtc_logging_handler_host);
864 host->SetUserData(host, new base::UserDataAdapter<WebRtcLoggingHandlerHost>(
865 webrtc_logging_handler_host));
866 #endif
867 #if !defined(DISABLE_NACL)
868 host->AddFilter(new nacl::NaClHostMessageFilter(
869 id, profile->IsOffTheRecord(),
870 profile->GetPath(),
871 context));
872 #endif
873 #if defined(OS_ANDROID)
874 host->AddFilter(new cdm::CdmMessageFilterAndroid());
875 #endif
876 DataReductionProxyChromeSettings* data_reduction_proxy_settings =
877 DataReductionProxyChromeSettingsFactory::GetForBrowserContext(profile);
878 host->AddFilter(new data_reduction_proxy::DataReductionProxyMessageFilter(
879 data_reduction_proxy_settings));
881 host->Send(new ChromeViewMsg_SetIsIncognitoProcess(
882 profile->IsOffTheRecord()));
884 for (size_t i = 0; i < extra_parts_.size(); ++i)
885 extra_parts_[i]->RenderProcessWillLaunch(host);
887 RendererContentSettingRules rules;
888 if (host->IsForGuestsOnly()) {
889 #if defined(ENABLE_EXTENSIONS)
890 GetGuestViewDefaultContentSettingRules(profile->IsOffTheRecord(), &rules);
891 #else
892 NOTREACHED();
893 #endif
894 } else {
895 GetRendererContentSettingRules(
896 profile->GetHostContentSettingsMap(), &rules);
898 host->Send(new ChromeViewMsg_SetContentSettingRules(rules));
901 GURL ChromeContentBrowserClient::GetEffectiveURL(
902 content::BrowserContext* browser_context, const GURL& url) {
903 Profile* profile = Profile::FromBrowserContext(browser_context);
904 if (!profile)
905 return url;
907 // If the input |url| should be assigned to the Instant renderer, make its
908 // effective URL distinct from other URLs on the search provider's domain.
909 if (search::ShouldAssignURLToInstantRenderer(url, profile))
910 return search::GetEffectiveURLForInstant(url, profile);
912 #if defined(ENABLE_EXTENSIONS)
913 return ChromeContentBrowserClientExtensionsPart::GetEffectiveURL(
914 profile, url);
915 #else
916 return url;
917 #endif
920 bool ChromeContentBrowserClient::ShouldUseProcessPerSite(
921 content::BrowserContext* browser_context, const GURL& effective_url) {
922 // Non-extension, non-Instant URLs should generally use
923 // process-per-site-instance. Because we expect to use the effective URL,
924 // URLs for hosted apps (apart from bookmark apps) should have an extension
925 // scheme by now.
927 Profile* profile = Profile::FromBrowserContext(browser_context);
928 if (!profile)
929 return false;
931 if (search::ShouldUseProcessPerSiteForInstantURL(effective_url, profile))
932 return true;
934 #if defined(ENABLE_EXTENSIONS)
935 return ChromeContentBrowserClientExtensionsPart::ShouldUseProcessPerSite(
936 profile, effective_url);
937 #else
938 return false;
939 #endif
942 // TODO(creis, nick): https://crbug.com/160576 describes a weakness in our
943 // origin-lock enforcement, where we don't have a way to efficiently know
944 // effective URLs on the IO thread, and wind up killing processes that e.g.
945 // request cookies for their actual URL. This whole function (and its
946 // ExtensionsPart) should be removed once we add that ability to the IO thread.
947 bool ChromeContentBrowserClient::ShouldLockToOrigin(
948 content::BrowserContext* browser_context,
949 const GURL& effective_site_url) {
950 // Origin lock to the search scheme would kill processes upon legitimate
951 // requests for cookies from the search engine's domain.
952 if (effective_site_url.SchemeIs(chrome::kChromeSearchScheme))
953 return false;
955 #if defined(ENABLE_EXTENSIONS)
956 // Disable origin lock if this is an extension/app that applies effective URL
957 // mappings.
958 if (!ChromeContentBrowserClientExtensionsPart::ShouldLockToOrigin(
959 browser_context, effective_site_url)) {
960 return false;
962 #endif
963 return true;
966 // These are treated as WebUI schemes but do not get WebUI bindings. Also,
967 // view-source is allowed for these schemes.
968 void ChromeContentBrowserClient::GetAdditionalWebUISchemes(
969 std::vector<std::string>* additional_schemes) {
970 additional_schemes->push_back(chrome::kChromeSearchScheme);
971 additional_schemes->push_back(dom_distiller::kDomDistillerScheme);
974 void ChromeContentBrowserClient::GetAdditionalWebUIHostsToIgnoreParititionCheck(
975 std::vector<std::string>* hosts) {
976 hosts->push_back(chrome::kChromeUIExtensionIconHost);
977 hosts->push_back(chrome::kChromeUIFaviconHost);
978 hosts->push_back(chrome::kChromeUIThemeHost);
979 hosts->push_back(chrome::kChromeUIThumbnailHost);
980 hosts->push_back(chrome::kChromeUIThumbnailHost2);
981 hosts->push_back(chrome::kChromeUIThumbnailListHost);
984 net::URLRequestContextGetter*
985 ChromeContentBrowserClient::CreateRequestContext(
986 content::BrowserContext* browser_context,
987 content::ProtocolHandlerMap* protocol_handlers,
988 content::URLRequestInterceptorScopedVector request_interceptors) {
989 Profile* profile = Profile::FromBrowserContext(browser_context);
990 return profile->CreateRequestContext(protocol_handlers,
991 request_interceptors.Pass());
994 net::URLRequestContextGetter*
995 ChromeContentBrowserClient::CreateRequestContextForStoragePartition(
996 content::BrowserContext* browser_context,
997 const base::FilePath& partition_path,
998 bool in_memory,
999 content::ProtocolHandlerMap* protocol_handlers,
1000 content::URLRequestInterceptorScopedVector request_interceptors) {
1001 Profile* profile = Profile::FromBrowserContext(browser_context);
1002 return profile->CreateRequestContextForStoragePartition(
1003 partition_path,
1004 in_memory,
1005 protocol_handlers,
1006 request_interceptors.Pass());
1009 bool ChromeContentBrowserClient::IsHandledURL(const GURL& url) {
1010 return ProfileIOData::IsHandledURL(url);
1013 bool ChromeContentBrowserClient::CanCommitURL(
1014 content::RenderProcessHost* process_host,
1015 const GURL& url) {
1016 #if defined(ENABLE_EXTENSIONS)
1017 return ChromeContentBrowserClientExtensionsPart::CanCommitURL(
1018 process_host, url);
1019 #else
1020 return true;
1021 #endif
1024 bool ChromeContentBrowserClient::IsIllegalOrigin(
1025 content::ResourceContext* resource_context,
1026 int child_process_id,
1027 const GURL& origin) {
1028 #if defined(ENABLE_EXTENSIONS)
1029 return ChromeContentBrowserClientExtensionsPart::IsIllegalOrigin(
1030 resource_context, child_process_id, origin);
1031 #else
1032 return false;
1033 #endif
1036 bool ChromeContentBrowserClient::ShouldAllowOpenURL(
1037 content::SiteInstance* site_instance, const GURL& url) {
1038 GURL from_url = site_instance->GetSiteURL();
1040 #if defined(ENABLE_EXTENSIONS)
1041 bool result;
1042 if (ChromeContentBrowserClientExtensionsPart::ShouldAllowOpenURL(
1043 site_instance, from_url, url, &result))
1044 return result;
1045 #endif
1047 // Do not allow chrome://chrome-signin navigate to other chrome:// URLs, since
1048 // the signin page may host untrusted web content.
1049 if (from_url.GetOrigin().spec() == chrome::kChromeUIChromeSigninURL &&
1050 url.SchemeIs(content::kChromeUIScheme) &&
1051 url.host() != chrome::kChromeUIChromeSigninHost) {
1052 VLOG(1) << "Blocked navigation to " << url.spec() << " from "
1053 << chrome::kChromeUIChromeSigninURL;
1054 return false;
1057 return true;
1060 bool ChromeContentBrowserClient::IsSuitableHost(
1061 content::RenderProcessHost* process_host,
1062 const GURL& site_url) {
1063 Profile* profile =
1064 Profile::FromBrowserContext(process_host->GetBrowserContext());
1065 // This may be NULL during tests. In that case, just assume any site can
1066 // share any host.
1067 if (!profile)
1068 return true;
1070 // Instant URLs should only be in the instant process and instant process
1071 // should only have Instant URLs.
1072 InstantService* instant_service =
1073 InstantServiceFactory::GetForProfile(profile);
1074 if (instant_service) {
1075 bool is_instant_process = instant_service->IsInstantProcess(
1076 process_host->GetID());
1077 bool should_be_in_instant_process =
1078 search::ShouldAssignURLToInstantRenderer(site_url, profile);
1079 if (is_instant_process || should_be_in_instant_process)
1080 return is_instant_process && should_be_in_instant_process;
1083 #if defined(ENABLE_EXTENSIONS)
1084 return ChromeContentBrowserClientExtensionsPart::IsSuitableHost(
1085 profile, process_host, site_url);
1086 #else
1087 return true;
1088 #endif
1091 bool ChromeContentBrowserClient::MayReuseHost(
1092 content::RenderProcessHost* process_host) {
1093 // If there is currently a prerender in progress for the host provided,
1094 // it may not be shared. We require prerenders to be by themselves in a
1095 // separate process so that we can monitor their resource usage.
1096 Profile* profile = Profile::FromBrowserContext(
1097 process_host->GetBrowserContext());
1098 prerender::PrerenderManager* prerender_manager =
1099 prerender::PrerenderManagerFactory::GetForProfile(profile);
1100 if (prerender_manager &&
1101 !prerender_manager->MayReuseProcessHost(process_host)) {
1102 return false;
1105 return true;
1108 bool ChromeContentBrowserClient::ShouldTryToUseExistingProcessHost(
1109 content::BrowserContext* browser_context, const GURL& url) {
1110 // It has to be a valid URL for us to check for an extension.
1111 if (!url.is_valid())
1112 return false;
1114 #if defined(ENABLE_EXTENSIONS)
1115 Profile* profile = Profile::FromBrowserContext(browser_context);
1116 return ChromeContentBrowserClientExtensionsPart::
1117 ShouldTryToUseExistingProcessHost(
1118 profile, url);
1119 #else
1120 return false;
1121 #endif
1124 void ChromeContentBrowserClient::SiteInstanceGotProcess(
1125 SiteInstance* site_instance) {
1126 CHECK(site_instance->HasProcess());
1128 Profile* profile = Profile::FromBrowserContext(
1129 site_instance->GetBrowserContext());
1130 if (!profile)
1131 return;
1133 // Remember the ID of the Instant process to signal the renderer process
1134 // on startup in |AppendExtraCommandLineSwitches| below.
1135 if (search::ShouldAssignURLToInstantRenderer(site_instance->GetSiteURL(),
1136 profile)) {
1137 InstantService* instant_service =
1138 InstantServiceFactory::GetForProfile(profile);
1139 if (instant_service)
1140 instant_service->AddInstantProcess(site_instance->GetProcess()->GetID());
1143 for (size_t i = 0; i < extra_parts_.size(); ++i)
1144 extra_parts_[i]->SiteInstanceGotProcess(site_instance);
1147 void ChromeContentBrowserClient::SiteInstanceDeleting(
1148 SiteInstance* site_instance) {
1149 if (!site_instance->HasProcess())
1150 return;
1152 for (size_t i = 0; i < extra_parts_.size(); ++i)
1153 extra_parts_[i]->SiteInstanceDeleting(site_instance);
1156 bool ChromeContentBrowserClient::ShouldSwapBrowsingInstancesForNavigation(
1157 SiteInstance* site_instance,
1158 const GURL& current_url,
1159 const GURL& new_url) {
1160 #if defined(ENABLE_EXTENSIONS)
1161 return ChromeContentBrowserClientExtensionsPart::
1162 ShouldSwapBrowsingInstancesForNavigation(
1163 site_instance, current_url, new_url);
1164 #else
1165 return false;
1166 #endif
1169 bool ChromeContentBrowserClient::ShouldSwapProcessesForRedirect(
1170 content::ResourceContext* resource_context, const GURL& current_url,
1171 const GURL& new_url) {
1172 #if defined(ENABLE_EXTENSIONS)
1173 return ChromeContentBrowserClientExtensionsPart::
1174 ShouldSwapProcessesForRedirect(resource_context, current_url, new_url);
1175 #else
1176 return false;
1177 #endif
1180 bool ChromeContentBrowserClient::ShouldAssignSiteForURL(const GURL& url) {
1181 return !url.SchemeIs(chrome::kChromeNativeScheme);
1184 std::string ChromeContentBrowserClient::GetCanonicalEncodingNameByAliasName(
1185 const std::string& alias_name) {
1186 return CharacterEncoding::GetCanonicalEncodingNameByAliasName(alias_name);
1189 namespace {
1191 bool IsAutoReloadEnabled() {
1192 // Fetch the field trial, even though we don't use it. Calling FindFullName()
1193 // causes the field-trial mechanism to report which group we're in, which
1194 // might reflect a hard disable or hard enable via flag, both of which have
1195 // their own field trial groups. This lets us know what percentage of users
1196 // manually enable or disable auto-reload.
1197 std::string group = base::FieldTrialList::FindFullName(
1198 "AutoReloadExperiment");
1199 const base::CommandLine& browser_command_line =
1200 *base::CommandLine::ForCurrentProcess();
1201 if (browser_command_line.HasSwitch(switches::kEnableOfflineAutoReload))
1202 return true;
1203 if (browser_command_line.HasSwitch(switches::kDisableOfflineAutoReload))
1204 return false;
1205 return true;
1208 bool IsAutoReloadVisibleOnlyEnabled() {
1209 // See the block comment in IsAutoReloadEnabled().
1210 std::string group = base::FieldTrialList::FindFullName(
1211 "AutoReloadVisibleOnlyExperiment");
1212 const base::CommandLine& browser_command_line =
1213 *base::CommandLine::ForCurrentProcess();
1214 if (browser_command_line.HasSwitch(
1215 switches::kEnableOfflineAutoReloadVisibleOnly)) {
1216 return true;
1218 if (browser_command_line.HasSwitch(
1219 switches::kDisableOfflineAutoReloadVisibleOnly)) {
1220 return false;
1222 return true;
1225 void MaybeAppendBlinkSettingsSwitchForFieldTrial(
1226 const base::CommandLine& browser_command_line,
1227 base::CommandLine* command_line) {
1228 // List of field trials that modify the blink-settings command line flag. No
1229 // two field trials in the list should specify the same keys, otherwise one
1230 // field trial may overwrite another. See Source/core/frame/Settings.in in
1231 // Blink for the list of valid keys.
1232 static const char* const kBlinkSettingsFieldTrials[] = {
1233 // Keys: backgroundHtmlParserOutstandingTokenLimit
1234 // backgroundHtmlParserPendingTokenLimit
1235 "BackgroundHtmlParserTokenLimits",
1237 // Keys: doHtmlPreloadScanning
1238 "HtmlPreloadScanning",
1240 // Keys: lowPriorityIframes
1241 "LowPriorityIFrames",
1244 std::vector<std::string> blink_settings;
1245 for (const char* field_trial_name : kBlinkSettingsFieldTrials) {
1246 // Each blink-settings field trial should include a forcing_flag group,
1247 // to make sure that clients that specify the blink-settings flag on the
1248 // command line are excluded from the experiment groups. To make
1249 // sure we assign clients that specify this flag to the forcing_flag
1250 // group, we must call GetVariationParams for each field trial first
1251 // (for example, before checking HasSwitch() and returning), since
1252 // GetVariationParams has the side-effect of assigning the client to
1253 // a field trial group.
1254 std::map<std::string, std::string> params;
1255 if (variations::GetVariationParams(field_trial_name, &params)) {
1256 for (const auto& param : params) {
1257 blink_settings.push_back(base::StringPrintf(
1258 "%s=%s", param.first.c_str(), param.second.c_str()));
1263 // Flags for the ResourcePriorities field trial. The settings are
1264 // encoded in the field trial group name instead of as variations
1265 // because the variations code is not accessible from the loader.
1267 // The group name encoding looks like this:
1268 // <descriptiveName>_ABCDE_E2_F_G
1269 // A - fetchDeferLateScripts (1 for true, 0 for false)
1270 // B - fetchIncreaseFontPriority (1 for true, 0 for false)
1271 // C - fetchIncreaseAsyncScriptPriority (1 for true, 0 for false)
1272 // D - fetchIncreasePriorities (1 for true, 0 for false)
1273 // E - fetchEnableLayoutBlockingThreshold (1 for true, 0 for false)
1274 // E2 - fetchLayoutBlockingThreshold (Numeric)
1275 // F - fetchMaxNumDelayableWhileLayoutBlocking (Numeric)
1276 // G - fetchMaxNumDelayableRequests (Numeric)
1278 // Only A-D are relevant to blink and exposed as settings
1279 // Any group names (Control, Default, etc) will not match the pattern or
1280 // flags and will get the default settings which is the expected behavior.
1281 std::string resource_priorities_trial_group =
1282 base::FieldTrialList::FindFullName("ResourcePriorities");
1283 std::vector<std::string> split_group(
1284 base::SplitString(resource_priorities_trial_group, "_",
1285 base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL));
1286 if (split_group.size() == 5 && split_group[1].length() == 5) {
1287 if (split_group[1].at(0) == '1')
1288 blink_settings.push_back("fetchDeferLateScripts=true");
1289 if (split_group[1].at(1) == '1')
1290 blink_settings.push_back("fetchIncreaseFontPriority=true");
1291 if (split_group[1].at(2) == '1')
1292 blink_settings.push_back("fetchIncreaseAsyncScriptPriority=true");
1293 if (split_group[1].at(3) == '1')
1294 blink_settings.push_back("fetchIncreasePriorities=true");
1297 if (blink_settings.empty()) {
1298 return;
1301 if (browser_command_line.HasSwitch(switches::kBlinkSettings) ||
1302 command_line->HasSwitch(switches::kBlinkSettings)) {
1303 // The field trials should be configured to force users that specify the
1304 // blink-settings flag into a group with no params, and we return
1305 // above if no params were specified, so it's an error if we reach
1306 // this point.
1307 LOG(WARNING) << "Received field trial params, "
1308 "but blink-settings switch already specified.";
1309 return;
1312 command_line->AppendSwitchASCII(switches::kBlinkSettings,
1313 base::JoinString(blink_settings, ","));
1316 } // namespace
1318 void ChromeContentBrowserClient::AppendExtraCommandLineSwitches(
1319 base::CommandLine* command_line,
1320 int child_process_id) {
1321 #if defined(OS_MACOSX)
1322 scoped_ptr<metrics::ClientInfo> client_info =
1323 GoogleUpdateSettings::LoadMetricsClientInfo();
1324 if (client_info) {
1325 command_line->AppendSwitchASCII(switches::kMetricsClientID,
1326 client_info->client_id);
1328 #elif defined(OS_POSIX)
1329 if (breakpad::IsCrashReporterEnabled()) {
1330 scoped_ptr<metrics::ClientInfo> client_info =
1331 GoogleUpdateSettings::LoadMetricsClientInfo();
1332 command_line->AppendSwitchASCII(switches::kEnableCrashReporter,
1333 client_info ? client_info->client_id
1334 : std::string());
1336 #endif
1338 if (logging::DialogsAreSuppressed())
1339 command_line->AppendSwitch(switches::kNoErrorDialogs);
1341 std::string process_type =
1342 command_line->GetSwitchValueASCII(switches::kProcessType);
1343 const base::CommandLine& browser_command_line =
1344 *base::CommandLine::ForCurrentProcess();
1346 static const char* const kCommonSwitchNames[] = {
1347 switches::kUserAgent,
1348 switches::kUserDataDir, // Make logs go to the right file.
1350 command_line->CopySwitchesFrom(browser_command_line, kCommonSwitchNames,
1351 arraysize(kCommonSwitchNames));
1353 #if defined(ENABLE_IPC_FUZZER)
1354 static const char* const kIpcFuzzerSwitches[] = {
1355 switches::kIpcDumpDirectory,
1356 switches::kIpcFuzzerTestcase,
1358 command_line->CopySwitchesFrom(browser_command_line, kIpcFuzzerSwitches,
1359 arraysize(kIpcFuzzerSwitches));
1360 #endif
1362 #if defined(OS_CHROMEOS)
1363 static const char* const kChromeOSSwitches[] = {
1364 switches::kDisableDinosaurEasterEgg,
1366 command_line->CopySwitchesFrom(browser_command_line, kChromeOSSwitches,
1367 arraysize(kChromeOSSwitches));
1369 // On Chrome OS need to pass primary user homedir (in multi-profiles session).
1370 base::FilePath homedir;
1371 PathService::Get(base::DIR_HOME, &homedir);
1372 command_line->AppendSwitchASCII(chromeos::switches::kHomedir,
1373 homedir.value().c_str());
1374 #endif
1376 if (process_type == switches::kRendererProcess) {
1377 content::RenderProcessHost* process =
1378 content::RenderProcessHost::FromID(child_process_id);
1379 Profile* profile =
1380 process ? Profile::FromBrowserContext(process->GetBrowserContext())
1381 : NULL;
1382 for (size_t i = 0; i < extra_parts_.size(); ++i) {
1383 extra_parts_[i]->AppendExtraRendererCommandLineSwitches(
1384 command_line, process, profile);
1387 #if defined(OS_CHROMEOS)
1388 const std::string& login_profile =
1389 browser_command_line.GetSwitchValueASCII(
1390 chromeos::switches::kLoginProfile);
1391 if (!login_profile.empty())
1392 command_line->AppendSwitchASCII(
1393 chromeos::switches::kLoginProfile, login_profile);
1394 #endif
1396 #if defined(ENABLE_WEBRTC)
1397 MaybeCopyDisableWebRtcEncryptionSwitch(command_line,
1398 browser_command_line,
1399 chrome::GetChannel());
1400 #endif
1402 if (process) {
1403 PrefService* prefs = profile->GetPrefs();
1404 // Currently this pref is only registered if applied via a policy.
1405 if (prefs->HasPrefPath(prefs::kDisable3DAPIs) &&
1406 prefs->GetBoolean(prefs::kDisable3DAPIs)) {
1407 // Turn this policy into a command line switch.
1408 command_line->AppendSwitch(switches::kDisable3DAPIs);
1411 const base::ListValue* switches =
1412 prefs->GetList(prefs::kEnableDeprecatedWebPlatformFeatures);
1413 if (switches) {
1414 // Enable any deprecated features that have been re-enabled by policy.
1415 for (base::ListValue::const_iterator it = switches->begin();
1416 it != switches->end(); ++it) {
1417 std::string switch_to_enable;
1418 if ((*it)->GetAsString(&switch_to_enable))
1419 command_line->AppendSwitch(switch_to_enable);
1423 // Disable client-side phishing detection in the renderer if it is
1424 // disabled in the Profile preferences or the browser process.
1425 if (!prefs->GetBoolean(prefs::kSafeBrowsingEnabled) ||
1426 !g_browser_process->safe_browsing_detection_service()) {
1427 command_line->AppendSwitch(
1428 switches::kDisableClientSidePhishingDetection);
1431 if (prefs->GetBoolean(prefs::kPrintPreviewDisabled))
1432 command_line->AppendSwitch(switches::kDisablePrintPreview);
1434 InstantService* instant_service =
1435 InstantServiceFactory::GetForProfile(profile);
1436 if (instant_service &&
1437 instant_service->IsInstantProcess(process->GetID()))
1438 command_line->AppendSwitch(switches::kInstantProcess);
1441 if (IsAutoReloadEnabled())
1442 command_line->AppendSwitch(switches::kEnableOfflineAutoReload);
1443 if (IsAutoReloadVisibleOnlyEnabled()) {
1444 command_line->AppendSwitch(
1445 switches::kEnableOfflineAutoReloadVisibleOnly);
1449 // Enable showing a saved copy if this session is in the field trial
1450 // or the user explicitly enabled it. Note that as far as the
1451 // renderer is concerned, the feature is enabled if-and-only-if
1452 // one of the kEnableShowSavedCopy* switches is on the command
1453 // line; the yes/no/default behavior is only at the browser
1454 // command line level.
1456 // Command line switches override
1457 const std::string& show_saved_copy_value =
1458 browser_command_line.GetSwitchValueASCII(switches::kShowSavedCopy);
1459 if (show_saved_copy_value == switches::kEnableShowSavedCopyPrimary ||
1460 show_saved_copy_value == switches::kEnableShowSavedCopySecondary ||
1461 show_saved_copy_value == switches::kDisableShowSavedCopy) {
1462 command_line->AppendSwitchASCII(switches::kShowSavedCopy,
1463 show_saved_copy_value);
1464 } else {
1465 std::string group =
1466 base::FieldTrialList::FindFullName("LoadStaleCacheExperiment");
1468 if (group == "Primary") {
1469 command_line->AppendSwitchASCII(
1470 switches::kShowSavedCopy, switches::kEnableShowSavedCopyPrimary);
1471 } else if (group == "Secondary") {
1472 command_line->AppendSwitchASCII(
1473 switches::kShowSavedCopy,
1474 switches::kEnableShowSavedCopySecondary);
1479 MaybeAppendBlinkSettingsSwitchForFieldTrial(
1480 browser_command_line, command_line);
1482 // Please keep this in alphabetical order.
1483 static const char* const kSwitchNames[] = {
1484 #if defined(OS_ANDROID)
1485 autofill::switches::kDisableAccessorySuggestionView,
1486 autofill::switches::kEnableAccessorySuggestionView,
1487 #endif
1488 autofill::switches::kDisableFillOnAccountSelect,
1489 autofill::switches::kDisablePasswordGeneration,
1490 autofill::switches::kEnableFillOnAccountSelect,
1491 autofill::switches::kEnableFillOnAccountSelectNoHighlighting,
1492 autofill::switches::kEnablePasswordGeneration,
1493 autofill::switches::kEnableSingleClickAutofill,
1494 autofill::switches::kEnableSuggestionsWithSubstringMatch,
1495 autofill::switches::kIgnoreAutocompleteOffForAutofill,
1496 autofill::switches::kLocalHeuristicsOnlyForPasswordGeneration,
1497 #if defined(ENABLE_EXTENSIONS)
1498 extensions::switches::kAllowHTTPBackgroundPage,
1499 extensions::switches::kAllowLegacyExtensionManifests,
1500 extensions::switches::kEnableAppWindowControls,
1501 extensions::switches::kEnableEmbeddedExtensionOptions,
1502 extensions::switches::kEnableExperimentalExtensionApis,
1503 extensions::switches::kExtensionsOnChromeURLs,
1504 extensions::switches::kWhitelistedExtensionID,
1505 #endif
1506 switches::kAllowInsecureLocalhost,
1507 switches::kAppsGalleryURL,
1508 switches::kCloudPrintURL,
1509 switches::kCloudPrintXmppEndpoint,
1510 switches::kDisableBundledPpapiFlash,
1511 switches::kDisableCastStreamingHWEncoding,
1512 switches::kDisableJavaScriptHarmonyShipping,
1513 switches::kDisableNewBookmarkApps,
1514 #if defined(ENABLE_SPELLCHECK) && defined(OS_ANDROID)
1515 switches::kEnableAndroidSpellChecker,
1516 #endif
1517 switches::kEnableBenchmarking,
1518 switches::kEnableNaCl,
1519 #if !defined(DISABLE_NACL)
1520 switches::kEnableNaClDebug,
1521 switches::kEnableNaClNonSfiMode,
1522 switches::kEnablePNaClSubzero,
1523 #endif
1524 switches::kEnableNetBenchmarking,
1525 switches::kEnableNewBookmarkApps,
1526 switches::kJavaScriptHarmony,
1527 switches::kMessageLoopHistogrammer,
1528 switches::kPpapiFlashArgs,
1529 switches::kPpapiFlashPath,
1530 switches::kPpapiFlashVersion,
1531 switches::kProfilingAtStart,
1532 switches::kProfilingFile,
1533 switches::kProfilingFlush,
1534 switches::kUnsafelyTreatInsecureOriginAsSecure,
1535 translate::switches::kTranslateSecurityOrigin,
1538 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1539 arraysize(kSwitchNames));
1540 } else if (process_type == switches::kUtilityProcess) {
1541 #if defined(ENABLE_EXTENSIONS)
1542 static const char* const kSwitchNames[] = {
1543 extensions::switches::kAllowHTTPBackgroundPage,
1544 extensions::switches::kEnableExperimentalExtensionApis,
1545 extensions::switches::kExtensionsOnChromeURLs,
1546 extensions::switches::kWhitelistedExtensionID,
1549 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1550 arraysize(kSwitchNames));
1551 #endif
1552 } else if (process_type == switches::kPluginProcess) {
1553 #if defined(OS_CHROMEOS)
1554 static const char* const kSwitchNames[] = {
1555 chromeos::switches::kLoginProfile,
1558 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1559 arraysize(kSwitchNames));
1560 #endif
1561 } else if (process_type == switches::kZygoteProcess) {
1562 static const char* const kSwitchNames[] = {
1563 // Load (in-process) Pepper plugins in-process in the zygote pre-sandbox.
1564 switches::kDisableBundledPpapiFlash,
1565 #if !defined(DISABLE_NACL)
1566 switches::kEnableNaClDebug,
1567 switches::kEnableNaClNonSfiMode,
1568 switches::kEnablePNaClSubzero,
1569 switches::kNaClDangerousNoSandboxNonSfi,
1570 switches::kUseNaClHelperNonSfi,
1571 #endif
1572 switches::kPpapiFlashPath,
1573 switches::kPpapiFlashVersion,
1576 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1577 arraysize(kSwitchNames));
1578 } else if (process_type == switches::kGpuProcess) {
1579 // If --ignore-gpu-blacklist is passed in, don't send in crash reports
1580 // because GPU is expected to be unreliable.
1581 if (browser_command_line.HasSwitch(switches::kIgnoreGpuBlacklist) &&
1582 !command_line->HasSwitch(switches::kDisableBreakpad))
1583 command_line->AppendSwitch(switches::kDisableBreakpad);
1586 // The command line switch kEnableBenchmarking needs to be specified along
1587 // with the kEnableStatsTable switch to ensure that the stats table global
1588 // is initialized correctly.
1589 if (command_line->HasSwitch(switches::kEnableBenchmarking))
1590 DCHECK(command_line->HasSwitch(switches::kEnableStatsTable));
1593 std::string ChromeContentBrowserClient::GetApplicationLocale() {
1594 if (BrowserThread::CurrentlyOn(BrowserThread::IO))
1595 return g_io_thread_application_locale.Get();
1596 return g_browser_process->GetApplicationLocale();
1599 std::string ChromeContentBrowserClient::GetAcceptLangs(
1600 content::BrowserContext* context) {
1601 Profile* profile = Profile::FromBrowserContext(context);
1602 return profile->GetPrefs()->GetString(prefs::kAcceptLanguages);
1605 const gfx::ImageSkia* ChromeContentBrowserClient::GetDefaultFavicon() {
1606 ResourceBundle& rb = ResourceBundle::GetSharedInstance();
1607 return rb.GetNativeImageNamed(IDR_DEFAULT_FAVICON).ToImageSkia();
1610 bool ChromeContentBrowserClient::AllowAppCache(
1611 const GURL& manifest_url,
1612 const GURL& first_party,
1613 content::ResourceContext* context) {
1614 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1615 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1616 return io_data->GetCookieSettings()->
1617 IsSettingCookieAllowed(manifest_url, first_party);
1620 bool ChromeContentBrowserClient::AllowServiceWorker(
1621 const GURL& scope,
1622 const GURL& first_party_url,
1623 content::ResourceContext* context,
1624 int render_process_id,
1625 int render_frame_id) {
1626 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1628 #if defined(ENABLE_EXTENSIONS)
1629 // Check if this is an extension-related service worker, and, if so, if it's
1630 // allowed (this can return false if, e.g., the extension is disabled).
1631 // If it's not allowed, return immediately. We deliberately do *not* report
1632 // to the TabSpecificContentSettings, since the service worker is blocked
1633 // because of the extension, rather than because of the user's content
1634 // settings.
1635 if (!ChromeContentBrowserClientExtensionsPart::AllowServiceWorker(
1636 scope, first_party_url, context, render_process_id,
1637 render_frame_id)) {
1638 return false;
1640 #endif
1642 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1643 bool allow = io_data->GetCookieSettings()->IsSettingCookieAllowed(
1644 scope, first_party_url);
1646 // Record access to database for potential display in UI.
1647 // Only post the task if this is for a specific frame.
1648 if (render_process_id != -1 && render_frame_id != -1) {
1649 BrowserThread::PostTask(
1650 BrowserThread::UI, FROM_HERE,
1651 base::Bind(&TabSpecificContentSettings::ServiceWorkerAccessed,
1652 render_process_id, render_frame_id, scope, !allow));
1654 return allow;
1657 bool ChromeContentBrowserClient::AllowGetCookie(
1658 const GURL& url,
1659 const GURL& first_party,
1660 const net::CookieList& cookie_list,
1661 content::ResourceContext* context,
1662 int render_process_id,
1663 int render_frame_id) {
1664 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1665 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1666 bool allow = io_data->GetCookieSettings()->
1667 IsReadingCookieAllowed(url, first_party);
1669 BrowserThread::PostTask(
1670 BrowserThread::UI, FROM_HERE,
1671 base::Bind(&TabSpecificContentSettings::CookiesRead, render_process_id,
1672 render_frame_id, url, first_party, cookie_list, !allow));
1673 return allow;
1676 bool ChromeContentBrowserClient::AllowSetCookie(
1677 const GURL& url,
1678 const GURL& first_party,
1679 const std::string& cookie_line,
1680 content::ResourceContext* context,
1681 int render_process_id,
1682 int render_frame_id,
1683 net::CookieOptions* options) {
1684 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1685 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1686 content_settings::CookieSettings* cookie_settings =
1687 io_data->GetCookieSettings();
1688 bool allow = cookie_settings->IsSettingCookieAllowed(url, first_party);
1690 BrowserThread::PostTask(
1691 BrowserThread::UI, FROM_HERE,
1692 base::Bind(&TabSpecificContentSettings::CookieChanged, render_process_id,
1693 render_frame_id, url, first_party, cookie_line, *options,
1694 !allow));
1695 return allow;
1698 bool ChromeContentBrowserClient::AllowSaveLocalState(
1699 content::ResourceContext* context) {
1700 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1701 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1702 content_settings::CookieSettings* cookie_settings =
1703 io_data->GetCookieSettings();
1704 ContentSetting setting = cookie_settings->GetDefaultCookieSetting(NULL);
1706 // TODO(bauerb): Should we also disallow local state if the default is BLOCK?
1707 // Could we even support per-origin settings?
1708 return setting != CONTENT_SETTING_SESSION_ONLY;
1711 bool ChromeContentBrowserClient::AllowWorkerDatabase(
1712 const GURL& url,
1713 const base::string16& name,
1714 const base::string16& display_name,
1715 unsigned long estimated_size,
1716 content::ResourceContext* context,
1717 const std::vector<std::pair<int, int> >& render_frames) {
1718 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1719 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1720 content_settings::CookieSettings* cookie_settings =
1721 io_data->GetCookieSettings();
1722 bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1724 // Record access to database for potential display in UI.
1725 std::vector<std::pair<int, int> >::const_iterator i;
1726 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1727 BrowserThread::PostTask(
1728 BrowserThread::UI, FROM_HERE,
1729 base::Bind(&TabSpecificContentSettings::WebDatabaseAccessed,
1730 i->first, i->second, url, name, display_name, !allow));
1733 return allow;
1736 void ChromeContentBrowserClient::AllowWorkerFileSystem(
1737 const GURL& url,
1738 content::ResourceContext* context,
1739 const std::vector<std::pair<int, int> >& render_frames,
1740 base::Callback<void(bool)> callback) {
1741 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1742 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1743 content_settings::CookieSettings* cookie_settings =
1744 io_data->GetCookieSettings();
1745 bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1747 #if defined(ENABLE_EXTENSIONS)
1748 GuestPermissionRequestHelper(url, render_frames, callback, allow);
1749 #else
1750 FileSystemAccessed(url, render_frames, callback, allow);
1751 #endif
1754 #if defined(ENABLE_EXTENSIONS)
1755 void ChromeContentBrowserClient::GuestPermissionRequestHelper(
1756 const GURL& url,
1757 const std::vector<std::pair<int, int> >& render_frames,
1758 base::Callback<void(bool)> callback,
1759 bool allow) {
1760 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1761 std::vector<std::pair<int, int> >::const_iterator i;
1762 std::map<int, int> process_map;
1763 std::map<int, int>::const_iterator it;
1764 bool has_web_view_guest = false;
1765 // Record access to file system for potential display in UI.
1766 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1767 if (process_map.find(i->first) != process_map.end())
1768 continue;
1770 process_map.insert(std::pair<int, int>(i->first, i->second));
1772 if (extensions::WebViewRendererState::GetInstance()->IsGuest(i->first))
1773 has_web_view_guest = true;
1775 if (!has_web_view_guest) {
1776 FileSystemAccessed(url, render_frames, callback, allow);
1777 return;
1779 DCHECK_EQ(1U, process_map.size());
1780 it = process_map.begin();
1781 BrowserThread::PostTask(
1782 BrowserThread::UI,
1783 FROM_HERE,
1784 base::Bind(&ChromeContentBrowserClient::
1785 RequestFileSystemPermissionOnUIThread,
1786 it->first,
1787 it->second,
1788 url,
1789 allow,
1790 base::Bind(&ChromeContentBrowserClient::FileSystemAccessed,
1791 weak_factory_.GetWeakPtr(),
1792 url,
1793 render_frames,
1794 callback)));
1797 void ChromeContentBrowserClient::RequestFileSystemPermissionOnUIThread(
1798 int render_process_id,
1799 int render_frame_id,
1800 const GURL& url,
1801 bool allowed_by_default,
1802 const base::Callback<void(bool)>& callback) {
1803 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1804 extensions::WebViewPermissionHelper* web_view_permission_helper =
1805 extensions::WebViewPermissionHelper::FromFrameID(
1806 render_process_id, render_frame_id);
1807 web_view_permission_helper->RequestFileSystemPermission(url,
1808 allowed_by_default,
1809 callback);
1811 #endif
1813 void ChromeContentBrowserClient::FileSystemAccessed(
1814 const GURL& url,
1815 const std::vector<std::pair<int, int> >& render_frames,
1816 base::Callback<void(bool)> callback,
1817 bool allow) {
1818 // Record access to file system for potential display in UI.
1819 std::vector<std::pair<int, int> >::const_iterator i;
1820 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1821 BrowserThread::PostTask(
1822 BrowserThread::UI,
1823 FROM_HERE,
1824 base::Bind(&TabSpecificContentSettings::FileSystemAccessed,
1825 i->first, i->second, url, !allow));
1827 callback.Run(allow);
1830 bool ChromeContentBrowserClient::AllowWorkerIndexedDB(
1831 const GURL& url,
1832 const base::string16& name,
1833 content::ResourceContext* context,
1834 const std::vector<std::pair<int, int> >& render_frames) {
1835 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1836 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1837 content_settings::CookieSettings* cookie_settings =
1838 io_data->GetCookieSettings();
1839 bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1841 // Record access to IndexedDB for potential display in UI.
1842 std::vector<std::pair<int, int> >::const_iterator i;
1843 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1844 BrowserThread::PostTask(
1845 BrowserThread::UI, FROM_HERE,
1846 base::Bind(&TabSpecificContentSettings::IndexedDBAccessed,
1847 i->first, i->second, url, name, !allow));
1850 return allow;
1853 #if defined(ENABLE_WEBRTC)
1854 bool ChromeContentBrowserClient::AllowWebRTCIdentityCache(
1855 const GURL& url,
1856 const GURL& first_party_url,
1857 content::ResourceContext* context) {
1858 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1859 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1860 content_settings::CookieSettings* cookie_settings =
1861 io_data->GetCookieSettings();
1862 return cookie_settings->IsReadingCookieAllowed(url, first_party_url) &&
1863 cookie_settings->IsSettingCookieAllowed(url, first_party_url);
1865 #endif // defined(ENABLE_WEBRTC)
1867 net::URLRequestContext*
1868 ChromeContentBrowserClient::OverrideRequestContextForURL(
1869 const GURL& url, content::ResourceContext* context) {
1870 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1871 #if defined(ENABLE_EXTENSIONS)
1872 if (url.SchemeIs(extensions::kExtensionScheme)) {
1873 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1874 return io_data->extensions_request_context();
1876 #endif
1878 return NULL;
1881 QuotaPermissionContext*
1882 ChromeContentBrowserClient::CreateQuotaPermissionContext() {
1883 return new ChromeQuotaPermissionContext();
1886 void ChromeContentBrowserClient::AllowCertificateError(
1887 int render_process_id,
1888 int render_frame_id,
1889 int cert_error,
1890 const net::SSLInfo& ssl_info,
1891 const GURL& request_url,
1892 ResourceType resource_type,
1893 bool overridable,
1894 bool strict_enforcement,
1895 bool expired_previous_decision,
1896 const base::Callback<void(bool)>& callback,
1897 content::CertificateRequestResultType* result) {
1898 if (resource_type != content::RESOURCE_TYPE_MAIN_FRAME) {
1899 // A sub-resource has a certificate error. The user doesn't really
1900 // have a context for making the right decision, so block the
1901 // request hard, without an info bar to allow showing the insecure
1902 // content.
1903 *result = content::CERTIFICATE_REQUEST_RESULT_TYPE_DENY;
1904 return;
1907 // If the tab is being prerendered, cancel the prerender and the request.
1908 content::RenderFrameHost* render_frame_host =
1909 content::RenderFrameHost::FromID(render_process_id, render_frame_id);
1910 WebContents* tab = WebContents::FromRenderFrameHost(render_frame_host);
1911 if (!tab) {
1912 NOTREACHED();
1913 return;
1916 prerender::PrerenderContents* prerender_contents =
1917 prerender::PrerenderContents::FromWebContents(tab);
1918 if (prerender_contents) {
1919 prerender_contents->Destroy(prerender::FINAL_STATUS_SSL_ERROR);
1920 *result = content::CERTIFICATE_REQUEST_RESULT_TYPE_CANCEL;
1921 return;
1924 // Otherwise, display an SSL blocking page. The interstitial page takes
1925 // ownership of ssl_blocking_page.
1926 int options_mask = 0;
1927 if (overridable)
1928 options_mask |= SSLBlockingPage::OVERRIDABLE;
1929 if (strict_enforcement)
1930 options_mask |= SSLBlockingPage::STRICT_ENFORCEMENT;
1931 if (expired_previous_decision)
1932 options_mask |= SSLBlockingPage::EXPIRED_BUT_PREVIOUSLY_ALLOWED;
1934 SafeBrowsingService* safe_browsing_service =
1935 g_browser_process->safe_browsing_service();
1936 scoped_ptr<SafeBrowsingSSLCertReporter> cert_reporter(
1937 new SafeBrowsingSSLCertReporter(safe_browsing_service
1938 ? safe_browsing_service->ui_manager()
1939 : nullptr));
1940 SSLErrorHandler::HandleSSLError(tab, cert_error, ssl_info, request_url,
1941 options_mask, cert_reporter.Pass(), callback);
1944 void ChromeContentBrowserClient::SelectClientCertificate(
1945 content::WebContents* web_contents,
1946 net::SSLCertRequestInfo* cert_request_info,
1947 scoped_ptr<content::ClientCertificateDelegate> delegate) {
1948 prerender::PrerenderContents* prerender_contents =
1949 prerender::PrerenderContents::FromWebContents(web_contents);
1950 if (prerender_contents) {
1951 prerender_contents->Destroy(
1952 prerender::FINAL_STATUS_SSL_CLIENT_CERTIFICATE_REQUESTED);
1953 return;
1956 GURL requesting_url("https://" + cert_request_info->host_and_port.ToString());
1957 DCHECK(requesting_url.is_valid())
1958 << "Invalid URL string: https://"
1959 << cert_request_info->host_and_port.ToString();
1961 Profile* profile =
1962 Profile::FromBrowserContext(web_contents->GetBrowserContext());
1963 scoped_ptr<base::Value> filter =
1964 profile->GetHostContentSettingsMap()->GetWebsiteSetting(
1965 requesting_url,
1966 requesting_url,
1967 CONTENT_SETTINGS_TYPE_AUTO_SELECT_CERTIFICATE,
1968 std::string(),
1969 NULL);
1971 if (filter.get()) {
1972 // Try to automatically select a client certificate.
1973 if (filter->IsType(base::Value::TYPE_DICTIONARY)) {
1974 base::DictionaryValue* filter_dict =
1975 static_cast<base::DictionaryValue*>(filter.get());
1977 const std::vector<scoped_refptr<net::X509Certificate> >&
1978 all_client_certs = cert_request_info->client_certs;
1979 for (size_t i = 0; i < all_client_certs.size(); ++i) {
1980 if (CertMatchesFilter(*all_client_certs[i].get(), *filter_dict)) {
1981 // Use the first certificate that is matched by the filter.
1982 delegate->ContinueWithCertificate(all_client_certs[i].get());
1983 return;
1986 } else {
1987 NOTREACHED();
1991 chrome::ShowSSLClientCertificateSelector(web_contents, cert_request_info,
1992 delegate.Pass());
1995 void ChromeContentBrowserClient::AddCertificate(
1996 net::CertificateMimeType cert_type,
1997 const void* cert_data,
1998 size_t cert_size,
1999 int render_process_id,
2000 int render_frame_id) {
2001 chrome::SSLAddCertificate(cert_type, cert_data, cert_size,
2002 render_process_id, render_frame_id);
2005 content::MediaObserver* ChromeContentBrowserClient::GetMediaObserver() {
2006 return MediaCaptureDevicesDispatcher::GetInstance();
2009 content::PlatformNotificationService*
2010 ChromeContentBrowserClient::GetPlatformNotificationService() {
2011 #if defined(ENABLE_NOTIFICATIONS)
2012 return PlatformNotificationServiceImpl::GetInstance();
2013 #else
2014 NOTIMPLEMENTED();
2015 return NULL;
2016 #endif
2019 bool ChromeContentBrowserClient::CanCreateWindow(
2020 const GURL& opener_url,
2021 const GURL& opener_top_level_frame_url,
2022 const GURL& source_origin,
2023 WindowContainerType container_type,
2024 const GURL& target_url,
2025 const content::Referrer& referrer,
2026 WindowOpenDisposition disposition,
2027 const WebWindowFeatures& features,
2028 bool user_gesture,
2029 bool opener_suppressed,
2030 content::ResourceContext* context,
2031 int render_process_id,
2032 int opener_render_view_id,
2033 int opener_render_frame_id,
2034 bool* no_javascript_access) {
2035 DCHECK_CURRENTLY_ON(BrowserThread::IO);
2037 *no_javascript_access = false;
2039 // If the opener is trying to create a background window but doesn't have
2040 // the appropriate permission, fail the attempt.
2041 if (container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {
2042 #if defined(ENABLE_EXTENSIONS)
2043 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
2044 InfoMap* map = io_data->GetExtensionInfoMap();
2045 if (!map->SecurityOriginHasAPIPermission(
2046 source_origin,
2047 render_process_id,
2048 APIPermission::kBackground)) {
2049 return false;
2052 // Note: this use of GetExtensionOrAppByURL is safe but imperfect. It may
2053 // return a recently installed Extension even if this CanCreateWindow call
2054 // was made by an old copy of the page in a normal web process. That's ok,
2055 // because the permission check above would have caused an early return
2056 // already. We must use the full URL to find hosted apps, though, and not
2057 // just the origin.
2058 const Extension* extension =
2059 map->extensions().GetExtensionOrAppByURL(opener_url);
2060 if (extension && !extensions::BackgroundInfo::AllowJSAccess(extension))
2061 *no_javascript_access = true;
2062 #endif
2064 return true;
2067 #if defined(ENABLE_EXTENSIONS)
2068 if (extensions::WebViewRendererState::GetInstance()->IsGuest(
2069 render_process_id))
2070 return true;
2071 #endif
2073 HostContentSettingsMap* content_settings =
2074 ProfileIOData::FromResourceContext(context)->GetHostContentSettingsMap();
2075 BlockedWindowParams blocked_params(target_url,
2076 referrer,
2077 disposition,
2078 features,
2079 user_gesture,
2080 opener_suppressed,
2081 render_process_id,
2082 opener_render_frame_id);
2084 if (!user_gesture &&
2085 !base::CommandLine::ForCurrentProcess()->HasSwitch(
2086 switches::kDisablePopupBlocking)) {
2087 if (content_settings->GetContentSetting(opener_top_level_frame_url,
2088 opener_top_level_frame_url,
2089 CONTENT_SETTINGS_TYPE_POPUPS,
2090 std::string()) !=
2091 CONTENT_SETTING_ALLOW) {
2092 BrowserThread::PostTask(BrowserThread::UI,
2093 FROM_HERE,
2094 base::Bind(&HandleBlockedPopupOnUIThread,
2095 blocked_params));
2096 return false;
2100 #if defined(OS_ANDROID)
2101 if (SingleTabModeTabHelper::IsRegistered(render_process_id,
2102 opener_render_view_id)) {
2103 BrowserThread::PostTask(BrowserThread::UI,
2104 FROM_HERE,
2105 base::Bind(&HandleSingleTabModeBlockOnUIThread,
2106 blocked_params));
2107 return false;
2109 #endif
2111 return true;
2114 void ChromeContentBrowserClient::ResourceDispatcherHostCreated() {
2115 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2116 return g_browser_process->ResourceDispatcherHostCreated();
2119 content::SpeechRecognitionManagerDelegate*
2120 ChromeContentBrowserClient::CreateSpeechRecognitionManagerDelegate() {
2121 return new speech::ChromeSpeechRecognitionManagerDelegate();
2124 net::NetLog* ChromeContentBrowserClient::GetNetLog() {
2125 return g_browser_process->net_log();
2128 AccessTokenStore* ChromeContentBrowserClient::CreateAccessTokenStore() {
2129 return new ChromeAccessTokenStore();
2132 bool ChromeContentBrowserClient::IsFastShutdownPossible() {
2133 return true;
2136 void ChromeContentBrowserClient::OverrideWebkitPrefs(
2137 RenderViewHost* rvh, WebPreferences* web_prefs) {
2138 Profile* profile = Profile::FromBrowserContext(
2139 rvh->GetProcess()->GetBrowserContext());
2140 PrefService* prefs = profile->GetPrefs();
2142 // Fill per-script font preferences. These are not registered on Android
2143 // - http://crbug.com/308033.
2144 #if !defined(OS_ANDROID)
2145 FontFamilyCache::FillFontFamilyMap(profile,
2146 prefs::kWebKitStandardFontFamilyMap,
2147 &web_prefs->standard_font_family_map);
2148 FontFamilyCache::FillFontFamilyMap(profile,
2149 prefs::kWebKitFixedFontFamilyMap,
2150 &web_prefs->fixed_font_family_map);
2151 FontFamilyCache::FillFontFamilyMap(profile,
2152 prefs::kWebKitSerifFontFamilyMap,
2153 &web_prefs->serif_font_family_map);
2154 FontFamilyCache::FillFontFamilyMap(profile,
2155 prefs::kWebKitSansSerifFontFamilyMap,
2156 &web_prefs->sans_serif_font_family_map);
2157 FontFamilyCache::FillFontFamilyMap(profile,
2158 prefs::kWebKitCursiveFontFamilyMap,
2159 &web_prefs->cursive_font_family_map);
2160 FontFamilyCache::FillFontFamilyMap(profile,
2161 prefs::kWebKitFantasyFontFamilyMap,
2162 &web_prefs->fantasy_font_family_map);
2163 FontFamilyCache::FillFontFamilyMap(profile,
2164 prefs::kWebKitPictographFontFamilyMap,
2165 &web_prefs->pictograph_font_family_map);
2166 #endif
2168 web_prefs->default_font_size =
2169 prefs->GetInteger(prefs::kWebKitDefaultFontSize);
2170 web_prefs->default_fixed_font_size =
2171 prefs->GetInteger(prefs::kWebKitDefaultFixedFontSize);
2172 web_prefs->minimum_font_size =
2173 prefs->GetInteger(prefs::kWebKitMinimumFontSize);
2174 web_prefs->minimum_logical_font_size =
2175 prefs->GetInteger(prefs::kWebKitMinimumLogicalFontSize);
2177 web_prefs->default_encoding = prefs->GetString(prefs::kDefaultCharset);
2179 web_prefs->javascript_can_open_windows_automatically =
2180 prefs->GetBoolean(prefs::kWebKitJavascriptCanOpenWindowsAutomatically);
2181 web_prefs->dom_paste_enabled =
2182 prefs->GetBoolean(prefs::kWebKitDomPasteEnabled);
2183 web_prefs->tabs_to_links = prefs->GetBoolean(prefs::kWebkitTabsToLinks);
2185 if (!prefs->GetBoolean(prefs::kWebKitJavascriptEnabled))
2186 web_prefs->javascript_enabled = false;
2187 if (!prefs->GetBoolean(prefs::kWebKitWebSecurityEnabled))
2188 web_prefs->web_security_enabled = false;
2189 if (!prefs->GetBoolean(prefs::kWebKitPluginsEnabled))
2190 web_prefs->plugins_enabled = false;
2191 web_prefs->loads_images_automatically =
2192 prefs->GetBoolean(prefs::kWebKitLoadsImagesAutomatically);
2194 if (prefs->GetBoolean(prefs::kDisable3DAPIs))
2195 web_prefs->experimental_webgl_enabled = false;
2197 web_prefs->allow_displaying_insecure_content =
2198 prefs->GetBoolean(prefs::kWebKitAllowDisplayingInsecureContent);
2199 web_prefs->allow_running_insecure_content =
2200 prefs->GetBoolean(prefs::kWebKitAllowRunningInsecureContent);
2201 #if defined(OS_ANDROID)
2202 web_prefs->font_scale_factor =
2203 static_cast<float>(prefs->GetDouble(prefs::kWebKitFontScaleFactor));
2204 web_prefs->device_scale_adjustment = GetDeviceScaleAdjustment();
2205 web_prefs->force_enable_zoom =
2206 prefs->GetBoolean(prefs::kWebKitForceEnableZoom);
2207 #endif
2209 #if defined(OS_ANDROID)
2210 web_prefs->password_echo_enabled =
2211 prefs->GetBoolean(prefs::kWebKitPasswordEchoEnabled);
2212 #else
2213 web_prefs->password_echo_enabled = browser_defaults::kPasswordEchoEnabled;
2214 #endif
2216 web_prefs->asynchronous_spell_checking_enabled = true;
2217 web_prefs->unified_textchecker_enabled = true;
2219 web_prefs->uses_universal_detector =
2220 prefs->GetBoolean(prefs::kWebKitUsesUniversalDetector);
2221 web_prefs->text_areas_are_resizable =
2222 prefs->GetBoolean(prefs::kWebKitTextAreasAreResizable);
2223 web_prefs->hyperlink_auditing_enabled =
2224 prefs->GetBoolean(prefs::kEnableHyperlinkAuditing);
2226 #if defined(ENABLE_EXTENSIONS)
2227 std::string image_animation_policy =
2228 prefs->GetString(prefs::kAnimationPolicy);
2229 if (image_animation_policy == kAnimationPolicyOnce)
2230 web_prefs->animation_policy =
2231 content::IMAGE_ANIMATION_POLICY_ANIMATION_ONCE;
2232 else if (image_animation_policy == kAnimationPolicyNone)
2233 web_prefs->animation_policy = content::IMAGE_ANIMATION_POLICY_NO_ANIMATION;
2234 else
2235 web_prefs->animation_policy = content::IMAGE_ANIMATION_POLICY_ALLOWED;
2236 #endif
2238 // Make sure we will set the default_encoding with canonical encoding name.
2239 web_prefs->default_encoding =
2240 CharacterEncoding::GetCanonicalEncodingNameByAliasName(
2241 web_prefs->default_encoding);
2242 if (web_prefs->default_encoding.empty()) {
2243 prefs->ClearPref(prefs::kDefaultCharset);
2244 web_prefs->default_encoding = prefs->GetString(prefs::kDefaultCharset);
2246 DCHECK(!web_prefs->default_encoding.empty());
2248 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2249 switches::kEnablePotentiallyAnnoyingSecurityFeatures)) {
2250 web_prefs->disable_reading_from_canvas = true;
2251 web_prefs->strict_mixed_content_checking = true;
2252 web_prefs->strict_powerful_feature_restrictions = true;
2255 for (size_t i = 0; i < extra_parts_.size(); ++i)
2256 extra_parts_[i]->OverrideWebkitPrefs(rvh, web_prefs);
2259 void ChromeContentBrowserClient::BrowserURLHandlerCreated(
2260 BrowserURLHandler* handler) {
2261 for (size_t i = 0; i < extra_parts_.size(); ++i)
2262 extra_parts_[i]->BrowserURLHandlerCreated(handler);
2264 // about: handler. Must come before chrome: handler, since it will
2265 // rewrite about: urls to chrome: URLs and then expect chrome: to
2266 // actually handle them. Also relies on a preliminary fixup phase.
2267 handler->SetFixupHandler(&FixupBrowserAboutURL);
2268 handler->AddHandlerPair(&WillHandleBrowserAboutURL,
2269 BrowserURLHandler::null_handler());
2271 #if defined(OS_ANDROID)
2272 // Handler to rewrite chrome://newtab on Android.
2273 handler->AddHandlerPair(&chrome::android::HandleAndroidNativePageURL,
2274 BrowserURLHandler::null_handler());
2275 #else
2276 // Handler to rewrite chrome://newtab for InstantExtended.
2277 handler->AddHandlerPair(&search::HandleNewTabURLRewrite,
2278 &search::HandleNewTabURLReverseRewrite);
2279 #endif
2281 // chrome: & friends.
2282 handler->AddHandlerPair(&HandleWebUI, &HandleWebUIReverse);
2285 void ChromeContentBrowserClient::ClearCache(RenderFrameHost* rfh) {
2286 Profile* profile = Profile::FromBrowserContext(
2287 rfh->GetSiteInstance()->GetProcess()->GetBrowserContext());
2288 BrowsingDataRemover* remover =
2289 BrowsingDataRemover::CreateForUnboundedRange(profile);
2290 remover->Remove(BrowsingDataRemover::REMOVE_CACHE,
2291 BrowsingDataHelper::UNPROTECTED_WEB);
2292 // BrowsingDataRemover takes care of deleting itself when done.
2295 void ChromeContentBrowserClient::ClearCookies(RenderFrameHost* rfh) {
2296 Profile* profile = Profile::FromBrowserContext(
2297 rfh->GetSiteInstance()->GetProcess()->GetBrowserContext());
2298 BrowsingDataRemover* remover =
2299 BrowsingDataRemover::CreateForUnboundedRange(profile);
2300 int remove_mask = BrowsingDataRemover::REMOVE_SITE_DATA;
2301 remover->Remove(remove_mask, BrowsingDataHelper::UNPROTECTED_WEB);
2302 // BrowsingDataRemover takes care of deleting itself when done.
2305 base::FilePath ChromeContentBrowserClient::GetDefaultDownloadDirectory() {
2306 return DownloadPrefs::GetDefaultDownloadDirectory();
2309 std::string ChromeContentBrowserClient::GetDefaultDownloadName() {
2310 return l10n_util::GetStringUTF8(IDS_DEFAULT_DOWNLOAD_FILENAME);
2313 base::FilePath ChromeContentBrowserClient::GetShaderDiskCacheDirectory() {
2314 base::FilePath user_data_dir;
2315 PathService::Get(DIR_USER_DATA, &user_data_dir);
2316 DCHECK(!user_data_dir.empty());
2317 return user_data_dir.Append(FILE_PATH_LITERAL("ShaderCache"));
2320 void ChromeContentBrowserClient::DidCreatePpapiPlugin(
2321 content::BrowserPpapiHost* browser_host) {
2322 #if defined(ENABLE_PLUGINS)
2323 ChromeContentBrowserClientPluginsPart::DidCreatePpapiPlugin(browser_host);
2324 #endif
2327 content::BrowserPpapiHost*
2328 ChromeContentBrowserClient::GetExternalBrowserPpapiHost(
2329 int plugin_process_id) {
2330 #if !defined(DISABLE_NACL)
2331 content::BrowserChildProcessHostIterator iter(PROCESS_TYPE_NACL_LOADER);
2332 while (!iter.Done()) {
2333 nacl::NaClProcessHost* host = static_cast<nacl::NaClProcessHost*>(
2334 iter.GetDelegate());
2335 if (host->process() &&
2336 host->process()->GetData().id == plugin_process_id) {
2337 // Found the plugin.
2338 return host->browser_ppapi_host();
2340 ++iter;
2342 #endif
2343 return NULL;
2346 bool ChromeContentBrowserClient::AllowPepperSocketAPI(
2347 content::BrowserContext* browser_context,
2348 const GURL& url,
2349 bool private_api,
2350 const content::SocketPermissionRequest* params) {
2351 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
2352 return ChromeContentBrowserClientPluginsPart::AllowPepperSocketAPI(
2353 browser_context, url, private_api, params, allowed_socket_origins_);
2354 #else
2355 return false;
2356 #endif
2359 ui::SelectFilePolicy* ChromeContentBrowserClient::CreateSelectFilePolicy(
2360 WebContents* web_contents) {
2361 return new ChromeSelectFilePolicy(web_contents);
2364 void ChromeContentBrowserClient::GetAdditionalAllowedSchemesForFileSystem(
2365 std::vector<std::string>* additional_allowed_schemes) {
2366 ContentBrowserClient::GetAdditionalAllowedSchemesForFileSystem(
2367 additional_allowed_schemes);
2368 additional_allowed_schemes->push_back(content::kChromeDevToolsScheme);
2369 additional_allowed_schemes->push_back(content::kChromeUIScheme);
2370 for (size_t i = 0; i < extra_parts_.size(); ++i) {
2371 extra_parts_[i]->GetAdditionalAllowedSchemesForFileSystem(
2372 additional_allowed_schemes);
2376 void ChromeContentBrowserClient::GetURLRequestAutoMountHandlers(
2377 std::vector<storage::URLRequestAutoMountHandler>* handlers) {
2378 for (size_t i = 0; i < extra_parts_.size(); ++i)
2379 extra_parts_[i]->GetURLRequestAutoMountHandlers(handlers);
2382 void ChromeContentBrowserClient::GetAdditionalFileSystemBackends(
2383 content::BrowserContext* browser_context,
2384 const base::FilePath& storage_partition_path,
2385 ScopedVector<storage::FileSystemBackend>* additional_backends) {
2386 #if defined(OS_CHROMEOS)
2387 storage::ExternalMountPoints* external_mount_points =
2388 content::BrowserContext::GetMountPoints(browser_context);
2389 DCHECK(external_mount_points);
2390 chromeos::FileSystemBackend* backend = new chromeos::FileSystemBackend(
2391 new drive::FileSystemBackendDelegate,
2392 new chromeos::file_system_provider::BackendDelegate,
2393 new chromeos::MTPFileSystemBackendDelegate(storage_partition_path),
2394 external_mount_points,
2395 storage::ExternalMountPoints::GetSystemInstance());
2396 backend->AddSystemMountPoints();
2397 DCHECK(backend->CanHandleType(storage::kFileSystemTypeExternal));
2398 additional_backends->push_back(backend);
2399 #endif
2401 for (size_t i = 0; i < extra_parts_.size(); ++i) {
2402 extra_parts_[i]->GetAdditionalFileSystemBackends(
2403 browser_context, storage_partition_path, additional_backends);
2407 #if defined(OS_ANDROID)
2408 void ChromeContentBrowserClient::GetAdditionalMappedFilesForChildProcess(
2409 const base::CommandLine& command_line,
2410 int child_process_id,
2411 FileDescriptorInfo* mappings,
2412 std::map<int, base::MemoryMappedFile::Region>* regions) {
2413 int fd = ui::GetMainAndroidPackFd(
2414 &(*regions)[kAndroidUIResourcesPakDescriptor]);
2415 mappings->Share(kAndroidUIResourcesPakDescriptor, fd);
2417 fd = ui::GetCommonResourcesPackFd(
2418 &(*regions)[kAndroidChrome100PercentPakDescriptor]);
2419 mappings->Share(kAndroidChrome100PercentPakDescriptor, fd);
2421 fd = ui::GetLocalePackFd(&(*regions)[kAndroidLocalePakDescriptor]);
2422 mappings->Share(kAndroidLocalePakDescriptor, fd);
2424 if (breakpad::IsCrashReporterEnabled()) {
2425 base::File file =
2426 breakpad::CrashDumpManager::GetInstance()->CreateMinidumpFile(
2427 child_process_id);
2428 if (file.IsValid()) {
2429 mappings->Transfer(kAndroidMinidumpDescriptor,
2430 base::ScopedFD(file.TakePlatformFile()));
2431 } else {
2432 LOG(ERROR) << "Failed to create file for minidump, crash reporting will "
2433 "be disabled for this process.";
2437 base::FilePath app_data_path;
2438 PathService::Get(base::DIR_ANDROID_APP_DATA, &app_data_path);
2439 DCHECK(!app_data_path.empty());
2441 #elif defined(OS_POSIX) && !defined(OS_MACOSX)
2442 void ChromeContentBrowserClient::GetAdditionalMappedFilesForChildProcess(
2443 const base::CommandLine& command_line,
2444 int child_process_id,
2445 FileDescriptorInfo* mappings) {
2446 int crash_signal_fd = GetCrashSignalFD(command_line);
2447 if (crash_signal_fd >= 0) {
2448 mappings->Share(kCrashDumpSignal, crash_signal_fd);
2451 #endif // defined(OS_ANDROID)
2453 #if defined(OS_WIN)
2454 const wchar_t* ChromeContentBrowserClient::GetResourceDllName() {
2455 return chrome::kBrowserResourcesDll;
2458 base::string16 ChromeContentBrowserClient::GetAppContainerSidForSandboxType(
2459 int sandbox_type) const {
2460 base::string16 sid;
2462 #if defined(GOOGLE_CHROME_BUILD)
2463 const version_info::Channel channel = chrome::GetChannel();
2465 // It's possible to have a SxS installation running at the same time as a
2466 // non-SxS so isolate them from each other.
2467 if (channel == version_info::Channel::CANARY) {
2468 sid.assign(
2469 L"S-1-15-2-3251537155-1984446955-2931258699-841473695-1938553385-"
2470 L"924012150-");
2471 } else {
2472 sid.assign(
2473 L"S-1-15-2-3251537155-1984446955-2931258699-841473695-1938553385-"
2474 L"924012149-");
2476 #else
2477 sid.assign(
2478 L"S-1-15-2-3251537155-1984446955-2931258699-841473695-1938553385-"
2479 L"924012148-");
2480 #endif
2482 // TODO(wfh): Add support for more process types here. crbug.com/499523
2483 switch (sandbox_type) {
2484 case content::SANDBOX_TYPE_RENDERER:
2485 return sid + L"129201922";
2486 case content::SANDBOX_TYPE_UTILITY:
2487 return base::string16();
2488 case content::SANDBOX_TYPE_GPU:
2489 return base::string16();
2490 case content::SANDBOX_TYPE_PPAPI:
2491 return sid + L"129201925";
2492 #if !defined(DISABLE_NACL)
2493 case PROCESS_TYPE_NACL_LOADER:
2494 return base::string16();
2495 case PROCESS_TYPE_NACL_BROKER:
2496 return base::string16();
2497 #endif
2500 // Should never reach here.
2501 CHECK(0);
2502 return base::string16();
2505 void ChromeContentBrowserClient::PreSpawnRenderer(
2506 sandbox::TargetPolicy* policy,
2507 bool* success) {
2508 // This code is duplicated in nacl_exe_win_64.cc.
2509 // Allow the server side of a pipe restricted to the "chrome.nacl."
2510 // namespace so that it cannot impersonate other system or other chrome
2511 // service pipes.
2512 sandbox::ResultCode result = policy->AddRule(
2513 sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
2514 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
2515 L"\\\\.\\pipe\\chrome.nacl.*");
2516 if (result != sandbox::SBOX_ALL_OK) {
2517 *success = false;
2518 return;
2521 // Renderers need to send named pipe handles and shared memory
2522 // segment handles to NaCl loader processes.
2523 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
2524 sandbox::TargetPolicy::HANDLES_DUP_ANY,
2525 L"File");
2526 if (result != sandbox::SBOX_ALL_OK) {
2527 *success = false;
2528 return;
2531 #endif
2533 void ChromeContentBrowserClient::RegisterFrameMojoShellServices(
2534 content::ServiceRegistry* registry,
2535 content::RenderFrameHost* render_frame_host) {
2536 #if defined(OS_CHROMEOS)
2537 registry->AddService(
2538 base::Bind(&chromeos::attestation::PlatformVerificationImpl::Create,
2539 render_frame_host));
2540 #endif
2541 #if !defined(OS_ANDROID) && !defined(OS_IOS)
2542 registry->AddService(
2543 base::Bind(&WebUSBPermissionProvider::Create, render_frame_host));
2544 #endif
2547 void ChromeContentBrowserClient::RegisterInProcessMojoApplications(
2548 StaticMojoApplicationMap* apps) {
2549 #if !defined(OS_ANDROID) && !defined(OS_IOS)
2550 apps->insert(std::make_pair(GURL(device::kDevicesMojoAppUrl),
2551 base::Bind(&device::DevicesAppFactory::CreateApp,
2552 base::ThreadTaskRunnerHandle::Get())));
2553 #endif
2556 void ChromeContentBrowserClient::OpenURL(
2557 content::BrowserContext* browser_context,
2558 const content::OpenURLParams& params,
2559 const base::Callback<void(content::WebContents*)>& callback) {
2560 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2562 #if !defined(OS_ANDROID) && !defined(OS_IOS)
2563 NavigateParams nav_params(Profile::FromBrowserContext(browser_context),
2564 params.url,
2565 params.transition);
2566 FillNavigateParamsFromOpenURLParams(&nav_params, params);
2567 nav_params.user_gesture = params.user_gesture;
2569 Navigate(&nav_params);
2570 callback.Run(nav_params.target_contents);
2571 #elif defined(OS_ANDROID)
2572 service_tab_launcher::ServiceTabLauncher::GetInstance()->LaunchTab(
2573 browser_context, params, callback);
2574 #else
2575 NOTIMPLEMENTED();
2576 #endif
2579 content::PresentationServiceDelegate*
2580 ChromeContentBrowserClient::GetPresentationServiceDelegate(
2581 content::WebContents* web_contents) {
2582 #if defined(ENABLE_MEDIA_ROUTER)
2583 if (switches::MediaRouterEnabled() &&
2584 !web_contents->GetBrowserContext()->IsOffTheRecord()) {
2585 return media_router::PresentationServiceDelegateImpl::
2586 GetOrCreateForWebContents(web_contents);
2588 #endif
2589 return nullptr;
2592 void ChromeContentBrowserClient::RecordURLMetric(const std::string& metric,
2593 const GURL& url) {
2594 if (url.is_valid()) {
2595 rappor::SampleDomainAndRegistryFromGURL(g_browser_process->rappor_service(),
2596 metric, url);
2600 content::DevToolsManagerDelegate*
2601 ChromeContentBrowserClient::GetDevToolsManagerDelegate() {
2602 return new ChromeDevToolsManagerDelegate();
2605 content::TracingDelegate* ChromeContentBrowserClient::GetTracingDelegate() {
2606 #if !defined(OS_ANDROID)
2607 return new ChromeTracingDelegate();
2608 #else
2609 return nullptr;
2610 #endif
2613 bool ChromeContentBrowserClient::IsPluginAllowedToCallRequestOSFileHandle(
2614 content::BrowserContext* browser_context,
2615 const GURL& url) {
2616 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
2617 return ChromeContentBrowserClientPluginsPart::
2618 IsPluginAllowedToCallRequestOSFileHandle(browser_context, url,
2619 allowed_file_handle_origins_);
2620 #else
2621 return false;
2622 #endif
2625 bool ChromeContentBrowserClient::IsPluginAllowedToUseDevChannelAPIs(
2626 content::BrowserContext* browser_context,
2627 const GURL& url) {
2628 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
2629 return ChromeContentBrowserClientPluginsPart::
2630 IsPluginAllowedToUseDevChannelAPIs(browser_context, url,
2631 allowed_dev_channel_origins_);
2632 #else
2633 return false;
2634 #endif
2637 void ChromeContentBrowserClient::OverridePageVisibilityState(
2638 RenderFrameHost* render_frame_host,
2639 blink::WebPageVisibilityState* visibility_state) {
2640 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2642 WebContents* web_contents =
2643 WebContents::FromRenderFrameHost(render_frame_host);
2644 DCHECK(web_contents);
2646 Profile* profile =
2647 Profile::FromBrowserContext(web_contents->GetBrowserContext());
2648 prerender::PrerenderManager* prerender_manager =
2649 prerender::PrerenderManagerFactory::GetForProfile(profile);
2650 if (prerender_manager &&
2651 prerender_manager->IsWebContentsPrerendering(web_contents, nullptr)) {
2652 *visibility_state = blink::WebPageVisibilityStatePrerender;
2656 #if defined(ENABLE_WEBRTC)
2657 void ChromeContentBrowserClient::MaybeCopyDisableWebRtcEncryptionSwitch(
2658 base::CommandLine* to_command_line,
2659 const base::CommandLine& from_command_line,
2660 version_info::Channel channel) {
2661 #if defined(OS_ANDROID)
2662 const version_info::Channel kMaxDisableEncryptionChannel =
2663 version_info::Channel::BETA;
2664 #else
2665 const version_info::Channel kMaxDisableEncryptionChannel =
2666 version_info::Channel::DEV;
2667 #endif
2668 if (channel <= kMaxDisableEncryptionChannel) {
2669 static const char* const kWebRtcDevSwitchNames[] = {
2670 switches::kDisableWebRtcEncryption,
2672 to_command_line->CopySwitchesFrom(from_command_line,
2673 kWebRtcDevSwitchNames,
2674 arraysize(kWebRtcDevSwitchNames));
2677 #endif // defined(ENABLE_WEBRTC)
2679 } // namespace chrome