ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / chrome / browser / chrome_content_browser_client.cc
blob36f525707379bc4c3bdcf3feb3195de37f2fd331
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 <set>
8 #include <utility>
9 #include <vector>
11 #include "base/bind.h"
12 #include "base/command_line.h"
13 #include "base/files/scoped_file.h"
14 #include "base/i18n/icu_util.h"
15 #include "base/lazy_instance.h"
16 #include "base/path_service.h"
17 #include "base/prefs/pref_service.h"
18 #include "base/prefs/scoped_user_pref_update.h"
19 #include "base/strings/string_number_conversions.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "base/threading/sequenced_worker_pool.h"
22 #include "chrome/browser/browser_about_handler.h"
23 #include "chrome/browser/browser_process.h"
24 #include "chrome/browser/browser_shutdown.h"
25 #include "chrome/browser/browsing_data/browsing_data_helper.h"
26 #include "chrome/browser/browsing_data/browsing_data_remover.h"
27 #include "chrome/browser/character_encoding.h"
28 #include "chrome/browser/chrome_content_browser_client_parts.h"
29 #include "chrome/browser/chrome_net_benchmarking_message_filter.h"
30 #include "chrome/browser/chrome_quota_permission_context.h"
31 #include "chrome/browser/content_settings/cookie_settings.h"
32 #include "chrome/browser/content_settings/tab_specific_content_settings.h"
33 #include "chrome/browser/defaults.h"
34 #include "chrome/browser/download/download_prefs.h"
35 #include "chrome/browser/font_family_cache.h"
36 #include "chrome/browser/geolocation/chrome_access_token_store.h"
37 #include "chrome/browser/geolocation/geolocation_permission_context.h"
38 #include "chrome/browser/geolocation/geolocation_permission_context_factory.h"
39 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
40 #include "chrome/browser/media/midi_permission_context.h"
41 #include "chrome/browser/media/midi_permission_context_factory.h"
42 #include "chrome/browser/metrics/chrome_browser_main_extra_parts_metrics.h"
43 #include "chrome/browser/metrics/rappor/sampling.h"
44 #include "chrome/browser/nacl_host/nacl_browser_delegate_impl.h"
45 #include "chrome/browser/net/chrome_net_log.h"
46 #include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings.h"
47 #include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings_factory.h"
48 #include "chrome/browser/notifications/desktop_notification_service.h"
49 #include "chrome/browser/notifications/desktop_notification_service_factory.h"
50 #include "chrome/browser/notifications/platform_notification_service_impl.h"
51 #include "chrome/browser/platform_util.h"
52 #include "chrome/browser/prerender/prerender_final_status.h"
53 #include "chrome/browser/prerender/prerender_manager.h"
54 #include "chrome/browser/prerender/prerender_manager_factory.h"
55 #include "chrome/browser/prerender/prerender_message_filter.h"
56 #include "chrome/browser/prerender/prerender_tracker.h"
57 #include "chrome/browser/printing/printing_message_filter.h"
58 #include "chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.h"
59 #include "chrome/browser/profiles/profile.h"
60 #include "chrome/browser/profiles/profile_io_data.h"
61 #include "chrome/browser/renderer_host/chrome_render_message_filter.h"
62 #include "chrome/browser/renderer_host/pepper/chrome_browser_pepper_host_factory.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/services/gcm/push_messaging_permission_context.h"
68 #include "chrome/browser/services/gcm/push_messaging_permission_context_factory.h"
69 #include "chrome/browser/signin/principals_message_filter.h"
70 #include "chrome/browser/speech/chrome_speech_recognition_manager_delegate.h"
71 #include "chrome/browser/speech/tts_controller.h"
72 #include "chrome/browser/speech/tts_message_filter.h"
73 #include "chrome/browser/ssl/ssl_add_certificate.h"
74 #include "chrome/browser/ssl/ssl_blocking_page.h"
75 #include "chrome/browser/ssl/ssl_client_certificate_selector.h"
76 #include "chrome/browser/ssl/ssl_error_handler.h"
77 #include "chrome/browser/sync_file_system/local/sync_file_system_backend.h"
78 #include "chrome/browser/tab_contents/tab_util.h"
79 #include "chrome/browser/tracing/chrome_tracing_delegate.h"
80 #include "chrome/browser/ui/blocked_content/blocked_window_params.h"
81 #include "chrome/browser/ui/blocked_content/popup_blocker_tab_helper.h"
82 #include "chrome/browser/ui/chrome_select_file_policy.h"
83 #include "chrome/browser/ui/sync/sync_promo_ui.h"
84 #include "chrome/browser/ui/tab_contents/chrome_web_contents_view_delegate.h"
85 #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
86 #include "chrome/common/chrome_constants.h"
87 #include "chrome/common/chrome_paths.h"
88 #include "chrome/common/chrome_switches.h"
89 #include "chrome/common/env_vars.h"
90 #include "chrome/common/logging_chrome.h"
91 #include "chrome/common/pepper_permission_util.h"
92 #include "chrome/common/pref_names.h"
93 #include "chrome/common/render_messages.h"
94 #include "chrome/common/url_constants.h"
95 #include "chrome/grit/generated_resources.h"
96 #include "chrome/installer/util/google_update_settings.h"
97 #include "chromeos/chromeos_constants.h"
98 #include "components/cdm/browser/cdm_message_filter_android.h"
99 #include "components/cloud_devices/common/cloud_devices_switches.h"
100 #include "components/content_settings/core/browser/content_settings_provider.h"
101 #include "components/content_settings/core/browser/content_settings_utils.h"
102 #include "components/content_settings/core/browser/host_content_settings_map.h"
103 #include "components/content_settings/core/common/content_settings.h"
104 #include "components/content_settings/core/common/permission_request_id.h"
105 #include "components/data_reduction_proxy/content/browser/data_reduction_proxy_message_filter.h"
106 #include "components/dom_distiller/core/url_constants.h"
107 #include "components/google/core/browser/google_util.h"
108 #include "components/metrics/client_info.h"
109 #include "components/pref_registry/pref_registry_syncable.h"
110 #include "components/signin/core/common/profile_management_switches.h"
111 #include "components/translate/core/common/translate_switches.h"
112 #include "components/url_fixer/url_fixer.h"
113 #include "content/public/browser/browser_child_process_host.h"
114 #include "content/public/browser/browser_main_parts.h"
115 #include "content/public/browser/browser_ppapi_host.h"
116 #include "content/public/browser/browser_thread.h"
117 #include "content/public/browser/browser_url_handler.h"
118 #include "content/public/browser/child_process_data.h"
119 #include "content/public/browser/child_process_security_policy.h"
120 #include "content/public/browser/permission_type.h"
121 #include "content/public/browser/render_frame_host.h"
122 #include "content/public/browser/render_process_host.h"
123 #include "content/public/browser/render_view_host.h"
124 #include "content/public/browser/resource_context.h"
125 #include "content/public/browser/site_instance.h"
126 #include "content/public/browser/web_contents.h"
127 #include "content/public/common/child_process_host.h"
128 #include "content/public/common/content_descriptors.h"
129 #include "content/public/common/url_utils.h"
130 #include "content/public/common/web_preferences.h"
131 #include "gin/public/isolate_holder.h"
132 #include "net/base/mime_util.h"
133 #include "net/cookies/canonical_cookie.h"
134 #include "net/cookies/cookie_options.h"
135 #include "net/ssl/ssl_cert_request_info.h"
136 #include "ppapi/host/ppapi_host.h"
137 #include "storage/browser/fileapi/external_mount_points.h"
138 #include "ui/base/l10n/l10n_util.h"
139 #include "ui/base/resource/resource_bundle.h"
140 #include "ui/resources/grit/ui_resources.h"
142 #if defined(OS_WIN)
143 #include "base/win/windows_version.h"
144 #include "chrome/browser/chrome_browser_main_win.h"
145 #include "sandbox/win/src/sandbox_policy.h"
146 #elif defined(OS_MACOSX)
147 #include "chrome/browser/chrome_browser_main_mac.h"
148 #include "chrome/browser/spellchecker/spellcheck_message_filter_mac.h"
149 #include "components/crash/app/breakpad_mac.h"
150 #elif defined(OS_CHROMEOS)
151 #include "chrome/browser/chromeos/chrome_browser_main_chromeos.h"
152 #include "chrome/browser/chromeos/drive/fileapi/file_system_backend_delegate.h"
153 #include "chrome/browser/chromeos/file_manager/app_id.h"
154 #include "chrome/browser/chromeos/file_system_provider/fileapi/backend_delegate.h"
155 #include "chrome/browser/chromeos/fileapi/file_system_backend.h"
156 #include "chrome/browser/chromeos/fileapi/mtp_file_system_backend_delegate.h"
157 #include "chrome/browser/chromeos/login/startup_utils.h"
158 #include "chrome/browser/chromeos/system/input_device_settings.h"
159 #include "chromeos/chromeos_switches.h"
160 #include "components/user_manager/user_manager.h"
161 #elif defined(OS_LINUX)
162 #include "chrome/browser/chrome_browser_main_linux.h"
163 #elif defined(OS_ANDROID)
164 #include "chrome/browser/android/new_tab_page_url_handler.h"
165 #include "chrome/browser/android/service_tab_launcher.h"
166 #include "chrome/browser/android/webapps/single_tab_mode_tab_helper.h"
167 #include "chrome/browser/chrome_browser_main_android.h"
168 #include "chrome/common/descriptors_android.h"
169 #include "components/crash/browser/crash_dump_manager_android.h"
170 #elif defined(OS_POSIX)
171 #include "chrome/browser/chrome_browser_main_posix.h"
172 #endif
174 #if defined(OS_ANDROID) || defined(OS_CHROMEOS)
175 #include "chrome/browser/media/protected_media_identifier_permission_context.h"
176 #include "chrome/browser/media/protected_media_identifier_permission_context_factory.h"
177 #endif
179 #if defined(OS_POSIX) && !defined(OS_MACOSX)
180 #include "base/debug/leak_annotations.h"
181 #include "components/crash/app/breakpad_linux.h"
182 #include "components/crash/browser/crash_handler_host_linux.h"
183 #endif
185 #if defined(OS_ANDROID)
186 #include "ui/base/ui_base_paths.h"
187 #include "ui/gfx/android/device_display_info.h"
188 #endif
190 #if defined(OS_ANDROID)
191 #include "chrome/browser/android/dev_tools_manager_delegate_android.h"
192 #else
193 #include "chrome/browser/devtools/chrome_devtools_manager_delegate.h"
194 #endif
196 #if !defined(OS_CHROMEOS)
197 #include "chrome/browser/signin/chrome_signin_client.h"
198 #include "chrome/browser/signin/chrome_signin_client_factory.h"
199 #include "chrome/browser/signin/signin_manager_factory.h"
200 #include "components/signin/core/browser/signin_manager.h"
201 #endif
203 #if defined(TOOLKIT_VIEWS)
204 #include "chrome/browser/ui/views/chrome_browser_main_extra_parts_views.h"
205 #endif
207 #if defined(USE_ASH)
208 #include "chrome/browser/ui/views/ash/chrome_browser_main_extra_parts_ash.h"
209 #endif
211 #if defined(USE_AURA)
212 #include "chrome/browser/ui/aura/chrome_browser_main_extra_parts_aura.h"
213 #endif
215 #if defined(USE_X11)
216 #include "chrome/browser/chrome_browser_main_extra_parts_x11.h"
217 #endif
219 #if defined(ENABLE_CAPTIVE_PORTAL_DETECTION)
220 #include "chrome/browser/captive_portal/captive_portal_tab_helper.h"
221 #endif
223 #if !defined(DISABLE_NACL)
224 #include "components/nacl/browser/nacl_browser.h"
225 #include "components/nacl/browser/nacl_host_message_filter.h"
226 #include "components/nacl/browser/nacl_process_host.h"
227 #include "components/nacl/common/nacl_process_type.h"
228 #include "components/nacl/common/nacl_switches.h"
229 #endif
231 #if defined(ENABLE_EXTENSIONS)
232 #include "chrome/browser/accessibility/animation_policy_prefs.h"
233 #include "chrome/browser/extensions/chrome_content_browser_client_extensions_part.h"
234 #include "chrome/browser/extensions/extension_util.h"
235 #include "chrome/browser/media/cast_transport_host_filter.h"
236 #include "chrome/browser/speech/extension_api/tts_engine_extension_api.h"
237 #include "extensions/browser/extension_registry.h"
238 #include "extensions/browser/guest_view/guest_view_base.h"
239 #include "extensions/browser/guest_view/guest_view_manager.h"
240 #include "extensions/browser/guest_view/web_view/web_view_guest.h"
241 #include "extensions/browser/guest_view/web_view/web_view_permission_helper.h"
242 #include "extensions/browser/guest_view/web_view/web_view_renderer_state.h"
243 #include "extensions/common/constants.h"
244 #include "extensions/common/extension.h"
245 #include "extensions/common/extension_set.h"
246 #include "extensions/common/manifest_handlers/background_info.h"
247 #include "extensions/common/manifest_handlers/shared_module_info.h"
248 #include "extensions/common/permissions/permissions_data.h"
249 #include "extensions/common/permissions/socket_permission.h"
250 #include "extensions/common/switches.h"
251 #endif
253 #if defined(ENABLE_PLUGINS)
254 #include "chrome/browser/plugins/chrome_content_browser_client_plugins_part.h"
255 #endif
257 #if defined(ENABLE_SPELLCHECK)
258 #include "chrome/browser/spellchecker/spellcheck_message_filter.h"
259 #endif
261 #if defined(ENABLE_WEBRTC)
262 #include "chrome/browser/media/webrtc_logging_handler_host.h"
263 #endif
265 using base::FileDescriptor;
266 using blink::WebWindowFeatures;
267 using content::AccessTokenStore;
268 using content::BrowserThread;
269 using content::BrowserURLHandler;
270 using content::ChildProcessSecurityPolicy;
271 using content::QuotaPermissionContext;
272 using content::RenderFrameHost;
273 using content::RenderViewHost;
274 using content::ResourceType;
275 using content::SiteInstance;
276 using content::WebContents;
277 using content::WebPreferences;
278 using message_center::NotifierId;
280 #if defined(OS_POSIX)
281 using content::FileDescriptorInfo;
282 #endif
284 #if defined(ENABLE_EXTENSIONS)
285 using extensions::APIPermission;
286 using extensions::ChromeContentBrowserClientExtensionsPart;
287 using extensions::Extension;
288 using extensions::InfoMap;
289 using extensions::Manifest;
290 #endif
292 #if defined(ENABLE_PLUGINS)
293 using plugins::ChromeContentBrowserClientPluginsPart;
294 #endif
296 namespace {
298 // Cached version of the locale so we can return the locale on the I/O
299 // thread.
300 base::LazyInstance<std::string> g_io_thread_application_locale;
302 #if defined(ENABLE_PLUGINS)
303 // TODO(teravest): Add renderer-side API-specific checking for these APIs so
304 // that blanket permission isn't granted to all dev channel APIs for these.
305 // http://crbug.com/386743
306 const char* const kPredefinedAllowedDevChannelOrigins[] = {
307 "6EAED1924DB611B6EEF2A664BD077BE7EAD33B8F", // see crbug.com/383937
308 "4EB74897CB187C7633357C2FE832E0AD6A44883A" // see crbug.com/383937
311 const char* const kPredefinedAllowedFileHandleOrigins[] = {
312 "6EAED1924DB611B6EEF2A664BD077BE7EAD33B8F", // see crbug.com/234789
313 "4EB74897CB187C7633357C2FE832E0AD6A44883A" // see crbug.com/234789
316 const char* const kPredefinedAllowedSocketOrigins[] = {
317 "okddffdblfhhnmhodogpojmfkjmhinfp", // Test SSH Client
318 "pnhechapfaindjhompbnflcldabbghjo", // HTerm App (SSH Client)
319 "bglhmjfplikpjnfoegeomebmfnkjomhe", // see crbug.com/122126
320 "gbchcmhmhahfdphkhkmpfmihenigjmpp", // Chrome Remote Desktop
321 "kgngmbheleoaphbjbaiobfdepmghbfah", // Pre-release Chrome Remote Desktop
322 "odkaodonbgfohohmklejpjiejmcipmib", // Dogfood Chrome Remote Desktop
323 "ojoimpklfciegopdfgeenehpalipignm", // Chromoting canary
324 "cbkkbcmdlboombapidmoeolnmdacpkch", // see crbug.com/129089
325 "hhnbmknkdabfoieppbbljkhkfjcmcbjh", // see crbug.com/134099
326 "mablfbjkhmhkmefkjjacnbaikjkipphg", // see crbug.com/134099
327 "pdeelgamlgannhelgoegilelnnojegoh", // see crbug.com/134099
328 "cabapfdbkniadpollkckdnedaanlciaj", // see crbug.com/134099
329 "mapljbgnjledlpdmlchihnmeclmefbba", // see crbug.com/134099
330 "ghbfeebgmiidnnmeobbbaiamklmpbpii", // see crbug.com/134099
331 "jdfhpkjeckflbbleddjlpimecpbjdeep", // see crbug.com/142514
332 "iabmpiboiopbgfabjmgeedhcmjenhbla", // see crbug.com/165080
333 "B7CF8A292249681AF81771650BA4CEEAF19A4560", // see crbug.com/165080
334 "7525AF4F66763A70A883C4700529F647B470E4D2", // see crbug.com/238084
335 "0B549507088E1564D672F7942EB87CA4DAD73972", // see crbug.com/238084
336 "864288364E239573E777D3E0E36864E590E95C74" // see crbug.com/238084
338 #endif
340 // Returns a copy of the given url with its host set to given host and path set
341 // to given path. Other parts of the url will be the same.
342 GURL ReplaceURLHostAndPath(const GURL& url,
343 const std::string& host,
344 const std::string& path) {
345 url::Replacements<char> replacements;
346 replacements.SetHost(host.c_str(), url::Component(0, host.length()));
347 replacements.SetPath(path.c_str(), url::Component(0, path.length()));
348 return url.ReplaceComponents(replacements);
351 // Maps "foo://bar/baz/" to "foo://chrome/bar/baz/".
352 GURL AddUberHost(const GURL& url) {
353 const std::string uber_host = chrome::kChromeUIUberHost;
354 const std::string new_path = url.host() + url.path();
356 return ReplaceURLHostAndPath(url, uber_host, new_path);
359 // If url->host() is "chrome" and url->path() has characters other than the
360 // first slash, changes the url from "foo://chrome/bar/" to "foo://bar/" and
361 // returns true. Otherwise returns false.
362 bool RemoveUberHost(GURL* url) {
363 if (url->host() != chrome::kChromeUIUberHost)
364 return false;
366 if (url->path().empty() || url->path() == "/")
367 return false;
369 const std::string old_path = url->path();
371 const std::string::size_type separator = old_path.find('/', 1);
372 std::string new_host;
373 std::string new_path;
374 if (separator == std::string::npos) {
375 new_host = old_path.substr(1);
376 } else {
377 new_host = old_path.substr(1, separator - 1);
378 new_path = old_path.substr(separator);
381 // Do not allow URLs with paths empty before the first slash since we can't
382 // have an empty host. (e.g "foo://chrome//")
383 if (new_host.empty())
384 return false;
386 *url = ReplaceURLHostAndPath(*url, new_host, new_path);
388 DCHECK(url->is_valid());
390 return true;
393 // Handles rewriting Web UI URLs.
394 bool HandleWebUI(GURL* url, content::BrowserContext* browser_context) {
395 // Do not handle special URLs such as "about:foo"
396 if (!url->host().empty()) {
397 const GURL chrome_url = AddUberHost(*url);
399 // Handle valid "chrome://chrome/foo" URLs so the reverse handler will
400 // be called.
401 if (ChromeWebUIControllerFactory::GetInstance()->UseWebUIForURL(
402 browser_context, chrome_url))
403 return true;
406 if (!ChromeWebUIControllerFactory::GetInstance()->UseWebUIForURL(
407 browser_context, *url))
408 return false;
410 #if defined(OS_CHROMEOS)
411 // Special case : in ChromeOS in Guest mode bookmarks and history are
412 // disabled for security reasons. New tab page explains the reasons, so
413 // we redirect user to new tab page.
414 if (user_manager::UserManager::Get()->IsLoggedInAsGuest()) {
415 if (url->SchemeIs(content::kChromeUIScheme) &&
416 (url->DomainIs(chrome::kChromeUIBookmarksHost) ||
417 url->DomainIs(chrome::kChromeUIHistoryHost))) {
418 // Rewrite with new tab URL
419 *url = GURL(chrome::kChromeUINewTabURL);
422 #endif
424 return true;
427 // Reverse URL handler for Web UI. Maps "chrome://chrome/foo/" to
428 // "chrome://foo/".
429 bool HandleWebUIReverse(GURL* url, content::BrowserContext* browser_context) {
430 if (!url->is_valid() || !url->SchemeIs(content::kChromeUIScheme))
431 return false;
433 return RemoveUberHost(url);
436 bool CertMatchesFilter(const net::X509Certificate& cert,
437 const base::DictionaryValue& filter) {
438 // TODO(markusheintz): This is the minimal required filter implementation.
439 // Implement a better matcher.
441 // An empty filter matches any client certificate since no requirements are
442 // specified at all.
443 if (filter.empty())
444 return true;
446 std::string common_name;
447 if (filter.GetString("ISSUER.CN", &common_name) &&
448 (cert.issuer().common_name == common_name)) {
449 return true;
451 return false;
454 #if defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_MACOSX)
455 breakpad::CrashHandlerHostLinux* CreateCrashHandlerHost(
456 const std::string& process_type) {
457 base::FilePath dumps_path;
458 PathService::Get(chrome::DIR_CRASH_DUMPS, &dumps_path);
460 ANNOTATE_SCOPED_MEMORY_LEAK;
461 bool upload = (getenv(env_vars::kHeadless) == NULL);
462 breakpad::CrashHandlerHostLinux* crash_handler =
463 new breakpad::CrashHandlerHostLinux(process_type, dumps_path, upload);
464 crash_handler->StartUploaderThread();
465 return crash_handler;
469 int GetCrashSignalFD(const base::CommandLine& command_line) {
470 // Extensions have the same process type as renderers.
471 if (command_line.HasSwitch(extensions::switches::kExtensionProcess)) {
472 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
473 if (!crash_handler)
474 crash_handler = CreateCrashHandlerHost("extension");
475 return crash_handler->GetDeathSignalSocket();
478 std::string process_type =
479 command_line.GetSwitchValueASCII(switches::kProcessType);
481 if (process_type == switches::kRendererProcess) {
482 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
483 if (!crash_handler)
484 crash_handler = CreateCrashHandlerHost(process_type);
485 return crash_handler->GetDeathSignalSocket();
488 if (process_type == switches::kPluginProcess) {
489 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
490 if (!crash_handler)
491 crash_handler = CreateCrashHandlerHost(process_type);
492 return crash_handler->GetDeathSignalSocket();
495 if (process_type == switches::kPpapiPluginProcess) {
496 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
497 if (!crash_handler)
498 crash_handler = CreateCrashHandlerHost(process_type);
499 return crash_handler->GetDeathSignalSocket();
502 if (process_type == switches::kGpuProcess) {
503 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
504 if (!crash_handler)
505 crash_handler = CreateCrashHandlerHost(process_type);
506 return crash_handler->GetDeathSignalSocket();
509 return -1;
511 #endif // defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_MACOSX)
513 #if !defined(OS_CHROMEOS)
514 GURL GetEffectiveURLForSignin(const GURL& url) {
515 CHECK(SigninManager::IsWebBasedSigninFlowURL(url));
517 GURL effective_url(SigninManager::kChromeSigninEffectiveSite);
518 // Copy the path because the argument to SetPathStr must outlive
519 // the Replacements object.
520 const std::string path_copy(url.path());
521 GURL::Replacements replacements;
522 replacements.SetPathStr(path_copy);
523 effective_url = effective_url.ReplaceComponents(replacements);
524 return effective_url;
526 #endif
528 void SetApplicationLocaleOnIOThread(const std::string& locale) {
529 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
530 g_io_thread_application_locale.Get() = locale;
533 void HandleBlockedPopupOnUIThread(const BlockedWindowParams& params) {
534 // TODO(jochen): This code path should use RenderFrameHosts. See
535 // http://crbug.com/431769 for details.
536 RenderViewHost* render_view_host =
537 RenderViewHost::FromID(params.render_process_id(), params.opener_id());
538 if (!render_view_host)
539 return;
540 WebContents* tab = WebContents::FromRenderViewHost(render_view_host);
541 // The tab might already have navigated away.
542 if (!tab || tab->GetRenderViewHost() != render_view_host)
543 return;
545 prerender::PrerenderContents* prerender_contents =
546 prerender::PrerenderContents::FromWebContents(tab);
547 if (prerender_contents) {
548 prerender_contents->Destroy(prerender::FINAL_STATUS_CREATE_NEW_WINDOW);
549 return;
552 PopupBlockerTabHelper* popup_helper =
553 PopupBlockerTabHelper::FromWebContents(tab);
554 if (!popup_helper)
555 return;
556 popup_helper->AddBlockedPopup(params);
559 #if defined(OS_ANDROID)
561 void HandleSingleTabModeBlockOnUIThread(const BlockedWindowParams& params) {
562 WebContents* web_contents =
563 tab_util::GetWebContentsByID(params.render_process_id(),
564 params.opener_id());
565 if (!web_contents)
566 return;
568 SingleTabModeTabHelper::FromWebContents(web_contents)->HandleOpenUrl(params);
571 float GetDeviceScaleAdjustment() {
572 static const float kMinFSM = 1.05f;
573 static const int kWidthForMinFSM = 320;
574 static const float kMaxFSM = 1.3f;
575 static const int kWidthForMaxFSM = 800;
577 gfx::DeviceDisplayInfo info;
578 int minWidth = info.GetSmallestDIPWidth();
580 if (minWidth <= kWidthForMinFSM)
581 return kMinFSM;
582 if (minWidth >= kWidthForMaxFSM)
583 return kMaxFSM;
585 // The font scale multiplier varies linearly between kMinFSM and kMaxFSM.
586 float ratio = static_cast<float>(minWidth - kWidthForMinFSM) /
587 (kWidthForMaxFSM - kWidthForMinFSM);
588 return ratio * (kMaxFSM - kMinFSM) + kMinFSM;
591 #endif // defined(OS_ANDROID)
593 #if defined(ENABLE_EXTENSIONS)
594 // By default, JavaScript and images are enabled in guest content.
595 void GetGuestViewDefaultContentSettingRules(
596 bool incognito,
597 RendererContentSettingRules* rules) {
598 rules->image_rules.push_back(
599 ContentSettingPatternSource(ContentSettingsPattern::Wildcard(),
600 ContentSettingsPattern::Wildcard(),
601 CONTENT_SETTING_ALLOW,
602 std::string(),
603 incognito));
605 rules->script_rules.push_back(
606 ContentSettingPatternSource(ContentSettingsPattern::Wildcard(),
607 ContentSettingsPattern::Wildcard(),
608 CONTENT_SETTING_ALLOW,
609 std::string(),
610 incognito));
612 #endif // defined(ENALBE_EXTENSIONS)
614 content::PermissionStatus
615 ContentSettingToPermissionStatus(ContentSetting setting) {
616 switch (setting) {
617 case CONTENT_SETTING_ALLOW:
618 case CONTENT_SETTING_SESSION_ONLY:
619 return content::PERMISSION_STATUS_GRANTED;
620 case CONTENT_SETTING_BLOCK:
621 return content::PERMISSION_STATUS_DENIED;
622 case CONTENT_SETTING_ASK:
623 return content::PERMISSION_STATUS_ASK;
624 case CONTENT_SETTING_DETECT_IMPORTANT_CONTENT:
625 case CONTENT_SETTING_DEFAULT:
626 case CONTENT_SETTING_NUM_SETTINGS:
627 break;
629 NOTREACHED();
630 return content::PERMISSION_STATUS_DENIED;
633 PermissionContextBase* GetPermissionContext(Profile* profile,
634 content::PermissionType permission) {
635 switch (permission) {
636 case content::PERMISSION_MIDI_SYSEX:
637 return MidiPermissionContextFactory::GetForProfile(profile);
638 case content::PERMISSION_NOTIFICATIONS:
639 #if defined(ENABLE_NOTIFICATIONS)
640 return DesktopNotificationServiceFactory::GetForProfile(profile);
641 #else
642 NOTIMPLEMENTED();
643 break;
644 #endif
645 case content::PERMISSION_GEOLOCATION:
646 return GeolocationPermissionContextFactory::GetForProfile(profile);
647 case content::PERMISSION_PROTECTED_MEDIA_IDENTIFIER:
648 #if defined(OS_ANDROID) || defined(OS_CHROMEOS)
649 return ProtectedMediaIdentifierPermissionContextFactory::GetForProfile(
650 profile);
651 #else
652 NOTIMPLEMENTED();
653 break;
654 #endif
655 case content::PERMISSION_PUSH_MESSAGING:
656 return gcm::PushMessagingPermissionContextFactory::GetForProfile(profile);
657 case content::PERMISSION_NUM:
658 NOTREACHED() << "Invalid RequestPermission for " << permission;
659 break;
661 return nullptr;
664 // Helper method to translate from Permissions to ContentSettings
665 ContentSettingsType PermissionToContentSetting(
666 content::PermissionType permission) {
667 switch (permission) {
668 case content::PERMISSION_MIDI_SYSEX:
669 return CONTENT_SETTINGS_TYPE_MIDI_SYSEX;
670 case content::PERMISSION_PUSH_MESSAGING:
671 return CONTENT_SETTINGS_TYPE_PUSH_MESSAGING;
672 case content::PERMISSION_NOTIFICATIONS:
673 return CONTENT_SETTINGS_TYPE_NOTIFICATIONS;
674 case content::PERMISSION_GEOLOCATION:
675 return CONTENT_SETTINGS_TYPE_GEOLOCATION;
676 #if defined(OS_ANDROID) || defined(OS_CHROMEOS)
677 case content::PERMISSION_PROTECTED_MEDIA_IDENTIFIER:
678 return CONTENT_SETTINGS_TYPE_PROTECTED_MEDIA_IDENTIFIER;
679 #endif
680 default:
681 NOTREACHED() << "Unknown content setting for permission " << permission;
682 return CONTENT_SETTINGS_TYPE_DEFAULT;
686 void OnRequestPermission(
687 const base::Callback<void(content::PermissionStatus)>& callback,
688 ContentSetting content_setting) {
689 callback.Run(ContentSettingToPermissionStatus(content_setting));
692 } // namespace
694 namespace chrome {
696 ChromeContentBrowserClient::ChromeContentBrowserClient()
697 : prerender_tracker_(NULL),
698 #if defined(OS_POSIX) && !defined(OS_MACOSX)
699 v8_natives_fd_(-1),
700 v8_snapshot_fd_(-1),
701 #endif // OS_POSIX && !OS_MACOSX
702 weak_factory_(this) {
703 #if defined(ENABLE_PLUGINS)
704 for (size_t i = 0; i < arraysize(kPredefinedAllowedDevChannelOrigins); ++i)
705 allowed_dev_channel_origins_.insert(kPredefinedAllowedDevChannelOrigins[i]);
706 for (size_t i = 0; i < arraysize(kPredefinedAllowedFileHandleOrigins); ++i)
707 allowed_file_handle_origins_.insert(kPredefinedAllowedFileHandleOrigins[i]);
708 for (size_t i = 0; i < arraysize(kPredefinedAllowedSocketOrigins); ++i)
709 allowed_socket_origins_.insert(kPredefinedAllowedSocketOrigins[i]);
711 extra_parts_.push_back(new ChromeContentBrowserClientPluginsPart);
712 #endif
714 #if !defined(OS_ANDROID)
715 TtsExtensionEngine* tts_extension_engine = TtsExtensionEngine::GetInstance();
716 TtsController::GetInstance()->SetTtsEngineDelegate(tts_extension_engine);
717 #endif
719 #if defined(ENABLE_EXTENSIONS)
720 extra_parts_.push_back(new ChromeContentBrowserClientExtensionsPart);
721 #endif
724 ChromeContentBrowserClient::~ChromeContentBrowserClient() {
725 for (int i = static_cast<int>(extra_parts_.size()) - 1; i >= 0; --i)
726 delete extra_parts_[i];
727 extra_parts_.clear();
730 // static
731 void ChromeContentBrowserClient::RegisterProfilePrefs(
732 user_prefs::PrefRegistrySyncable* registry) {
733 registry->RegisterBooleanPref(
734 prefs::kDisable3DAPIs,
735 false,
736 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
737 registry->RegisterBooleanPref(
738 prefs::kEnableHyperlinkAuditing,
739 true,
740 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
741 registry->RegisterListPref(
742 prefs::kEnableDeprecatedWebPlatformFeatures,
743 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
746 // static
747 void ChromeContentBrowserClient::SetApplicationLocale(
748 const std::string& locale) {
749 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
751 // This object is guaranteed to outlive all threads so we don't have to
752 // worry about the lack of refcounting and can just post as Unretained.
754 // The common case is that this function is called early in Chrome startup
755 // before any threads are created (it will also be called later if the user
756 // changes the pref). In this case, there will be no threads created and
757 // posting will fail. When there are no threads, we can just set the string
758 // without worrying about threadsafety.
759 if (!BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
760 base::Bind(&SetApplicationLocaleOnIOThread, locale))) {
761 g_io_thread_application_locale.Get() = locale;
765 content::BrowserMainParts* ChromeContentBrowserClient::CreateBrowserMainParts(
766 const content::MainFunctionParams& parameters) {
767 ChromeBrowserMainParts* main_parts;
768 // Construct the Main browser parts based on the OS type.
769 #if defined(OS_WIN)
770 main_parts = new ChromeBrowserMainPartsWin(parameters);
771 #elif defined(OS_MACOSX)
772 main_parts = new ChromeBrowserMainPartsMac(parameters);
773 #elif defined(OS_CHROMEOS)
774 main_parts = new chromeos::ChromeBrowserMainPartsChromeos(parameters);
775 #elif defined(OS_LINUX)
776 main_parts = new ChromeBrowserMainPartsLinux(parameters);
777 #elif defined(OS_ANDROID)
778 main_parts = new ChromeBrowserMainPartsAndroid(parameters);
779 #elif defined(OS_POSIX)
780 main_parts = new ChromeBrowserMainPartsPosix(parameters);
781 #else
782 NOTREACHED();
783 main_parts = new ChromeBrowserMainParts(parameters);
784 #endif
786 chrome::AddProfilesExtraParts(main_parts);
788 // Construct additional browser parts. Stages are called in the order in
789 // which they are added.
790 #if defined(TOOLKIT_VIEWS)
791 main_parts->AddParts(new ChromeBrowserMainExtraPartsViews());
792 #endif
794 // TODO(oshima): Athena on chrome currently requires USE_ASH to build.
795 // We should reduce the dependency as much as possible.
796 #if defined(USE_ASH)
797 main_parts->AddParts(new ChromeBrowserMainExtraPartsAsh());
798 #endif
800 #if defined(USE_AURA)
801 main_parts->AddParts(new ChromeBrowserMainExtraPartsAura());
802 #endif
804 #if defined(USE_X11)
805 main_parts->AddParts(new ChromeBrowserMainExtraPartsX11());
806 #endif
808 chrome::AddMetricsExtraParts(main_parts);
810 return main_parts;
813 std::string ChromeContentBrowserClient::GetStoragePartitionIdForSite(
814 content::BrowserContext* browser_context,
815 const GURL& site) {
816 std::string partition_id;
818 // The partition ID for webview guest processes is the string value of its
819 // SiteInstance URL - "chrome-guest://app_id/persist?partition".
820 if (site.SchemeIs(content::kGuestScheme)) {
821 partition_id = site.spec();
822 } else if (site.GetOrigin().spec() == kChromeUIChromeSigninURL) {
823 // Chrome signin page has an embedded iframe of extension and web content,
824 // thus it must be isolated from other webUI pages.
825 partition_id = site.GetOrigin().spec();
828 DCHECK(IsValidStoragePartitionId(browser_context, partition_id));
829 return partition_id;
832 bool ChromeContentBrowserClient::IsValidStoragePartitionId(
833 content::BrowserContext* browser_context,
834 const std::string& partition_id) {
835 // The default ID is empty and is always valid.
836 if (partition_id.empty())
837 return true;
839 return GURL(partition_id).is_valid();
842 void ChromeContentBrowserClient::GetStoragePartitionConfigForSite(
843 content::BrowserContext* browser_context,
844 const GURL& site,
845 bool can_be_default,
846 std::string* partition_domain,
847 std::string* partition_name,
848 bool* in_memory) {
849 // Default to the browser-wide storage partition and override based on |site|
850 // below.
851 partition_domain->clear();
852 partition_name->clear();
853 *in_memory = false;
855 bool success = false;
856 #if defined(ENABLE_EXTENSIONS)
857 success = extensions::WebViewGuest::GetGuestPartitionConfigForSite(
858 site, partition_domain, partition_name, in_memory);
860 if (!success && site.SchemeIs(extensions::kExtensionScheme)) {
861 // If |can_be_default| is false, the caller is stating that the |site|
862 // should be parsed as if it had isolated storage. In particular it is
863 // important to NOT check ExtensionService for the is_storage_isolated()
864 // attribute because this code path is run during Extension uninstall
865 // to do cleanup after the Extension has already been unloaded from the
866 // ExtensionService.
867 bool is_isolated = !can_be_default;
868 if (can_be_default) {
869 if (extensions::util::SiteHasIsolatedStorage(site, browser_context))
870 is_isolated = true;
873 if (is_isolated) {
874 CHECK(site.has_host());
875 // For extensions with isolated storage, the the host of the |site| is
876 // the |partition_domain|. The |in_memory| and |partition_name| are only
877 // used in guest schemes so they are cleared here.
878 *partition_domain = site.host();
879 *in_memory = false;
880 partition_name->clear();
882 success = true;
884 #endif
886 if (!success && (site.GetOrigin().spec() == kChromeUIChromeSigninURL)) {
887 // Chrome signin page has an embedded iframe of extension and web content,
888 // thus it must be isolated from other webUI pages.
889 *partition_domain = chrome::kChromeUIChromeSigninHost;
892 // Assert that if |can_be_default| is false, the code above must have found a
893 // non-default partition. If this fails, the caller has a serious logic
894 // error about which StoragePartition they expect to be in and it is not
895 // safe to continue.
896 CHECK(can_be_default || !partition_domain->empty());
899 content::WebContentsViewDelegate*
900 ChromeContentBrowserClient::GetWebContentsViewDelegate(
901 content::WebContents* web_contents) {
902 return chrome::CreateWebContentsViewDelegate(web_contents);
905 void ChromeContentBrowserClient::RenderProcessWillLaunch(
906 content::RenderProcessHost* host) {
907 int id = host->GetID();
908 Profile* profile = Profile::FromBrowserContext(host->GetBrowserContext());
909 net::URLRequestContextGetter* context =
910 profile->GetRequestContextForRenderProcess(id);
912 host->AddFilter(new ChromeRenderMessageFilter(id, profile));
913 #if defined(ENABLE_EXTENSIONS)
914 host->AddFilter(new cast::CastTransportHostFilter);
915 #endif
916 #if defined(ENABLE_PRINTING)
917 host->AddFilter(new printing::PrintingMessageFilter(id, profile));
918 #endif
919 host->AddFilter(new SearchProviderInstallStateMessageFilter(id, profile));
920 #if defined(ENABLE_SPELLCHECK)
921 host->AddFilter(new SpellCheckMessageFilter(id));
922 #endif
923 #if defined(OS_MACOSX)
924 host->AddFilter(new SpellCheckMessageFilterMac(id));
925 #endif
926 host->AddFilter(new ChromeNetBenchmarkingMessageFilter(profile, context));
927 host->AddFilter(new prerender::PrerenderMessageFilter(id, profile));
928 host->AddFilter(new TtsMessageFilter(id, host->GetBrowserContext()));
929 #if defined(ENABLE_WEBRTC)
930 WebRtcLoggingHandlerHost* webrtc_logging_handler_host =
931 new WebRtcLoggingHandlerHost(profile);
932 host->SetWebRtcLogMessageCallback(base::Bind(
933 &WebRtcLoggingHandlerHost::LogMessage, webrtc_logging_handler_host));
934 host->AddFilter(webrtc_logging_handler_host);
935 host->SetUserData(host, new base::UserDataAdapter<WebRtcLoggingHandlerHost>(
936 webrtc_logging_handler_host));
937 #endif
938 #if !defined(DISABLE_NACL)
939 host->AddFilter(new nacl::NaClHostMessageFilter(
940 id, profile->IsOffTheRecord(),
941 profile->GetPath(),
942 context));
943 #endif
944 #if defined(OS_ANDROID)
945 host->AddFilter(new cdm::CdmMessageFilterAndroid());
946 #endif
947 if (switches::IsEnableAccountConsistency())
948 host->AddFilter(new PrincipalsMessageFilter(id));
950 DataReductionProxyChromeSettings* data_reduction_proxy_settings =
951 DataReductionProxyChromeSettingsFactory::GetForBrowserContext(profile);
952 if (data_reduction_proxy_settings) {
953 host->AddFilter(new data_reduction_proxy::DataReductionProxyMessageFilter(
954 data_reduction_proxy_settings));
957 host->Send(new ChromeViewMsg_SetIsIncognitoProcess(
958 profile->IsOffTheRecord()));
960 for (size_t i = 0; i < extra_parts_.size(); ++i)
961 extra_parts_[i]->RenderProcessWillLaunch(host);
963 RendererContentSettingRules rules;
964 if (host->IsIsolatedGuest()) {
965 #if defined(ENABLE_EXTENSIONS)
966 GetGuestViewDefaultContentSettingRules(profile->IsOffTheRecord(), &rules);
967 #else
968 NOTREACHED();
969 #endif
970 } else {
971 GetRendererContentSettingRules(
972 profile->GetHostContentSettingsMap(), &rules);
974 host->Send(new ChromeViewMsg_SetContentSettingRules(rules));
977 GURL ChromeContentBrowserClient::GetEffectiveURL(
978 content::BrowserContext* browser_context, const GURL& url) {
979 Profile* profile = Profile::FromBrowserContext(browser_context);
980 if (!profile)
981 return url;
983 // If the input |url| should be assigned to the Instant renderer, make its
984 // effective URL distinct from other URLs on the search provider's domain.
985 if (chrome::ShouldAssignURLToInstantRenderer(url, profile))
986 return chrome::GetEffectiveURLForInstant(url, profile);
988 #if !defined(OS_CHROMEOS)
989 // If the input |url| should be assigned to the Signin renderer, make its
990 // effective URL distinct from other URLs on the signin service's domain.
991 // Note that the signin renderer will be allowed to sign the user in to
992 // Chrome.
993 if (SigninManager::IsWebBasedSigninFlowURL(url))
994 return GetEffectiveURLForSignin(url);
995 #endif
997 #if defined(ENABLE_EXTENSIONS)
998 return ChromeContentBrowserClientExtensionsPart::GetEffectiveURL(
999 profile, url);
1000 #else
1001 return url;
1002 #endif
1005 bool ChromeContentBrowserClient::ShouldUseProcessPerSite(
1006 content::BrowserContext* browser_context, const GURL& effective_url) {
1007 // Non-extension, non-Instant URLs should generally use
1008 // process-per-site-instance. Because we expect to use the effective URL,
1009 // URLs for hosted apps (apart from bookmark apps) should have an extension
1010 // scheme by now.
1012 Profile* profile = Profile::FromBrowserContext(browser_context);
1013 if (!profile)
1014 return false;
1016 if (chrome::ShouldUseProcessPerSiteForInstantURL(effective_url, profile))
1017 return true;
1019 #if !defined(OS_CHROMEOS)
1020 if (SigninManager::IsWebBasedSigninFlowURL(effective_url))
1021 return true;
1022 #endif
1024 #if defined(ENABLE_EXTENSIONS)
1025 return ChromeContentBrowserClientExtensionsPart::ShouldUseProcessPerSite(
1026 profile, effective_url);
1027 #else
1028 return false;
1029 #endif
1032 // These are treated as WebUI schemes but do not get WebUI bindings. Also,
1033 // view-source is allowed for these schemes.
1034 void ChromeContentBrowserClient::GetAdditionalWebUISchemes(
1035 std::vector<std::string>* additional_schemes) {
1036 additional_schemes->push_back(chrome::kChromeSearchScheme);
1037 additional_schemes->push_back(dom_distiller::kDomDistillerScheme);
1040 void ChromeContentBrowserClient::GetAdditionalWebUIHostsToIgnoreParititionCheck(
1041 std::vector<std::string>* hosts) {
1042 hosts->push_back(chrome::kChromeUIExtensionIconHost);
1043 hosts->push_back(chrome::kChromeUIFaviconHost);
1044 hosts->push_back(chrome::kChromeUIThemeHost);
1045 hosts->push_back(chrome::kChromeUIThumbnailHost);
1046 hosts->push_back(chrome::kChromeUIThumbnailHost2);
1047 hosts->push_back(chrome::kChromeUIThumbnailListHost);
1050 net::URLRequestContextGetter*
1051 ChromeContentBrowserClient::CreateRequestContext(
1052 content::BrowserContext* browser_context,
1053 content::ProtocolHandlerMap* protocol_handlers,
1054 content::URLRequestInterceptorScopedVector request_interceptors) {
1055 Profile* profile = Profile::FromBrowserContext(browser_context);
1056 return profile->CreateRequestContext(protocol_handlers,
1057 request_interceptors.Pass());
1060 net::URLRequestContextGetter*
1061 ChromeContentBrowserClient::CreateRequestContextForStoragePartition(
1062 content::BrowserContext* browser_context,
1063 const base::FilePath& partition_path,
1064 bool in_memory,
1065 content::ProtocolHandlerMap* protocol_handlers,
1066 content::URLRequestInterceptorScopedVector request_interceptors) {
1067 Profile* profile = Profile::FromBrowserContext(browser_context);
1068 return profile->CreateRequestContextForStoragePartition(
1069 partition_path,
1070 in_memory,
1071 protocol_handlers,
1072 request_interceptors.Pass());
1075 bool ChromeContentBrowserClient::IsHandledURL(const GURL& url) {
1076 return ProfileIOData::IsHandledURL(url);
1079 bool ChromeContentBrowserClient::CanCommitURL(
1080 content::RenderProcessHost* process_host,
1081 const GURL& url) {
1082 #if defined(ENABLE_EXTENSIONS)
1083 return ChromeContentBrowserClientExtensionsPart::CanCommitURL(
1084 process_host, url);
1085 #else
1086 return true;
1087 #endif
1090 bool ChromeContentBrowserClient::ShouldAllowOpenURL(
1091 content::SiteInstance* site_instance, const GURL& url) {
1092 GURL from_url = site_instance->GetSiteURL();
1094 #if defined(ENABLE_EXTENSIONS)
1095 bool result;
1096 if (ChromeContentBrowserClientExtensionsPart::ShouldAllowOpenURL(
1097 site_instance, from_url, url, &result))
1098 return result;
1099 #endif
1101 // Do not allow chrome://chrome-signin navigate to other chrome:// URLs, since
1102 // the signin page may host untrusted web content.
1103 if (from_url.GetOrigin().spec() == chrome::kChromeUIChromeSigninURL &&
1104 url.SchemeIs(content::kChromeUIScheme) &&
1105 url.host() != chrome::kChromeUIChromeSigninHost) {
1106 VLOG(1) << "Blocked navigation to " << url.spec() << " from "
1107 << chrome::kChromeUIChromeSigninURL;
1108 return false;
1111 return true;
1114 bool ChromeContentBrowserClient::IsSuitableHost(
1115 content::RenderProcessHost* process_host,
1116 const GURL& site_url) {
1117 Profile* profile =
1118 Profile::FromBrowserContext(process_host->GetBrowserContext());
1119 // This may be NULL during tests. In that case, just assume any site can
1120 // share any host.
1121 if (!profile)
1122 return true;
1124 // Instant URLs should only be in the instant process and instant process
1125 // should only have Instant URLs.
1126 InstantService* instant_service =
1127 InstantServiceFactory::GetForProfile(profile);
1128 if (instant_service) {
1129 bool is_instant_process = instant_service->IsInstantProcess(
1130 process_host->GetID());
1131 bool should_be_in_instant_process =
1132 chrome::ShouldAssignURLToInstantRenderer(site_url, profile);
1133 if (is_instant_process || should_be_in_instant_process)
1134 return is_instant_process && should_be_in_instant_process;
1137 #if !defined(OS_CHROMEOS)
1138 SigninClient* signin_client =
1139 ChromeSigninClientFactory::GetForProfile(profile);
1140 if (signin_client && signin_client->IsSigninProcess(process_host->GetID()))
1141 return SigninManager::IsWebBasedSigninFlowURL(site_url);
1142 #endif
1144 #if defined(ENABLE_EXTENSIONS)
1145 return ChromeContentBrowserClientExtensionsPart::IsSuitableHost(
1146 profile, process_host, site_url);
1147 #else
1148 return true;
1149 #endif
1152 bool ChromeContentBrowserClient::MayReuseHost(
1153 content::RenderProcessHost* process_host) {
1154 // If there is currently a prerender in progress for the host provided,
1155 // it may not be shared. We require prerenders to be by themselves in a
1156 // separate process, so that we can monitor their resource usage, and so that
1157 // we can track the cookies that they change.
1158 Profile* profile = Profile::FromBrowserContext(
1159 process_host->GetBrowserContext());
1160 prerender::PrerenderManager* prerender_manager =
1161 prerender::PrerenderManagerFactory::GetForProfile(profile);
1162 if (prerender_manager &&
1163 !prerender_manager->MayReuseProcessHost(process_host)) {
1164 return false;
1167 return true;
1170 bool ChromeContentBrowserClient::ShouldTryToUseExistingProcessHost(
1171 content::BrowserContext* browser_context, const GURL& url) {
1172 // It has to be a valid URL for us to check for an extension.
1173 if (!url.is_valid())
1174 return false;
1176 #if defined(ENABLE_EXTENSIONS)
1177 Profile* profile = Profile::FromBrowserContext(browser_context);
1178 return ChromeContentBrowserClientExtensionsPart::
1179 ShouldTryToUseExistingProcessHost(
1180 profile, url);
1181 #else
1182 return false;
1183 #endif
1186 void ChromeContentBrowserClient::SiteInstanceGotProcess(
1187 SiteInstance* site_instance) {
1188 CHECK(site_instance->HasProcess());
1190 Profile* profile = Profile::FromBrowserContext(
1191 site_instance->GetBrowserContext());
1192 if (!profile)
1193 return;
1195 // Remember the ID of the Instant process to signal the renderer process
1196 // on startup in |AppendExtraCommandLineSwitches| below.
1197 if (chrome::ShouldAssignURLToInstantRenderer(
1198 site_instance->GetSiteURL(), profile)) {
1199 InstantService* instant_service =
1200 InstantServiceFactory::GetForProfile(profile);
1201 if (instant_service)
1202 instant_service->AddInstantProcess(site_instance->GetProcess()->GetID());
1205 #if !defined(OS_CHROMEOS)
1206 // We only expect there to be one signin process as we use process-per-site
1207 // for signin URLs. The signin process will be cleared from SigninManager
1208 // when the renderer is destroyed.
1209 if (SigninManager::IsWebBasedSigninFlowURL(site_instance->GetSiteURL())) {
1210 SigninClient* signin_client =
1211 ChromeSigninClientFactory::GetForProfile(profile);
1212 if (signin_client)
1213 signin_client->SetSigninProcess(site_instance->GetProcess()->GetID());
1214 #if defined(ENABLE_EXTENSIONS)
1215 ChromeContentBrowserClientExtensionsPart::SetSigninProcess(site_instance);
1216 #endif
1218 #endif
1220 for (size_t i = 0; i < extra_parts_.size(); ++i)
1221 extra_parts_[i]->SiteInstanceGotProcess(site_instance);
1224 void ChromeContentBrowserClient::SiteInstanceDeleting(
1225 SiteInstance* site_instance) {
1226 if (!site_instance->HasProcess())
1227 return;
1229 for (size_t i = 0; i < extra_parts_.size(); ++i)
1230 extra_parts_[i]->SiteInstanceDeleting(site_instance);
1233 bool ChromeContentBrowserClient::ShouldSwapBrowsingInstancesForNavigation(
1234 SiteInstance* site_instance,
1235 const GURL& current_url,
1236 const GURL& new_url) {
1237 #if defined(ENABLE_EXTENSIONS)
1238 return ChromeContentBrowserClientExtensionsPart::
1239 ShouldSwapBrowsingInstancesForNavigation(
1240 site_instance, current_url, new_url);
1241 #else
1242 return false;
1243 #endif
1246 bool ChromeContentBrowserClient::ShouldSwapProcessesForRedirect(
1247 content::ResourceContext* resource_context, const GURL& current_url,
1248 const GURL& new_url) {
1249 #if defined(ENABLE_EXTENSIONS)
1250 return ChromeContentBrowserClientExtensionsPart::
1251 ShouldSwapProcessesForRedirect(resource_context, current_url, new_url);
1252 #else
1253 return false;
1254 #endif
1257 bool ChromeContentBrowserClient::ShouldAssignSiteForURL(const GURL& url) {
1258 return !url.SchemeIs(chrome::kChromeNativeScheme);
1261 std::string ChromeContentBrowserClient::GetCanonicalEncodingNameByAliasName(
1262 const std::string& alias_name) {
1263 return CharacterEncoding::GetCanonicalEncodingNameByAliasName(alias_name);
1266 namespace {
1268 bool IsAutoReloadEnabled() {
1269 // Fetch the field trial, even though we don't use it. Calling FindFullName()
1270 // causes the field-trial mechanism to report which group we're in, which
1271 // might reflect a hard disable or hard enable via flag, both of which have
1272 // their own field trial groups. This lets us know what percentage of users
1273 // manually enable or disable auto-reload.
1274 std::string group = base::FieldTrialList::FindFullName(
1275 "AutoReloadExperiment");
1276 const base::CommandLine& browser_command_line =
1277 *base::CommandLine::ForCurrentProcess();
1278 if (browser_command_line.HasSwitch(switches::kEnableOfflineAutoReload))
1279 return true;
1280 if (browser_command_line.HasSwitch(switches::kDisableOfflineAutoReload))
1281 return false;
1282 return true;
1285 bool IsAutoReloadVisibleOnlyEnabled() {
1286 // See the block comment in IsAutoReloadEnabled().
1287 std::string group = base::FieldTrialList::FindFullName(
1288 "AutoReloadVisibleOnlyExperiment");
1289 const base::CommandLine& browser_command_line =
1290 *base::CommandLine::ForCurrentProcess();
1291 if (browser_command_line.HasSwitch(
1292 switches::kEnableOfflineAutoReloadVisibleOnly)) {
1293 return true;
1295 if (browser_command_line.HasSwitch(
1296 switches::kDisableOfflineAutoReloadVisibleOnly)) {
1297 return false;
1299 return true;
1302 } // namespace
1304 void ChromeContentBrowserClient::AppendExtraCommandLineSwitches(
1305 base::CommandLine* command_line,
1306 int child_process_id) {
1307 #if defined(OS_POSIX)
1308 if (breakpad::IsCrashReporterEnabled()) {
1309 scoped_ptr<metrics::ClientInfo> client_info =
1310 GoogleUpdateSettings::LoadMetricsClientInfo();
1311 command_line->AppendSwitchASCII(switches::kEnableCrashReporter,
1312 client_info ? client_info->client_id
1313 : std::string());
1315 #endif // defined(OS_POSIX)
1317 if (logging::DialogsAreSuppressed())
1318 command_line->AppendSwitch(switches::kNoErrorDialogs);
1320 std::string process_type =
1321 command_line->GetSwitchValueASCII(switches::kProcessType);
1322 const base::CommandLine& browser_command_line =
1323 *base::CommandLine::ForCurrentProcess();
1325 static const char* const kCommonSwitchNames[] = {
1326 switches::kUserAgent,
1327 switches::kUserDataDir, // Make logs go to the right file.
1329 command_line->CopySwitchesFrom(browser_command_line, kCommonSwitchNames,
1330 arraysize(kCommonSwitchNames));
1332 #if defined(ENABLE_IPC_FUZZER)
1333 static const char* const kIpcFuzzerSwitches[] = {
1334 switches::kIpcFuzzerTestcase,
1336 command_line->CopySwitchesFrom(browser_command_line, kIpcFuzzerSwitches,
1337 arraysize(kIpcFuzzerSwitches));
1338 #endif
1340 #if defined(OS_CHROMEOS)
1341 // On Chrome OS need to pass primary user homedir (in multi-profiles session).
1342 base::FilePath homedir;
1343 PathService::Get(base::DIR_HOME, &homedir);
1344 command_line->AppendSwitchASCII(chromeos::switches::kHomedir,
1345 homedir.value().c_str());
1346 #endif
1348 if (process_type == switches::kRendererProcess) {
1349 content::RenderProcessHost* process =
1350 content::RenderProcessHost::FromID(child_process_id);
1351 Profile* profile =
1352 process ? Profile::FromBrowserContext(process->GetBrowserContext())
1353 : NULL;
1354 for (size_t i = 0; i < extra_parts_.size(); ++i) {
1355 extra_parts_[i]->AppendExtraRendererCommandLineSwitches(
1356 command_line, process, profile);
1359 #if defined(OS_CHROMEOS)
1360 const std::string& login_profile =
1361 browser_command_line.GetSwitchValueASCII(
1362 chromeos::switches::kLoginProfile);
1363 if (!login_profile.empty())
1364 command_line->AppendSwitchASCII(
1365 chromeos::switches::kLoginProfile, login_profile);
1366 #endif
1368 #if defined(ENABLE_WEBRTC)
1369 MaybeCopyDisableWebRtcEncryptionSwitch(command_line,
1370 browser_command_line,
1371 VersionInfo::GetChannel());
1372 #endif
1374 if (process) {
1375 PrefService* prefs = profile->GetPrefs();
1376 // Currently this pref is only registered if applied via a policy.
1377 if (prefs->HasPrefPath(prefs::kDisable3DAPIs) &&
1378 prefs->GetBoolean(prefs::kDisable3DAPIs)) {
1379 // Turn this policy into a command line switch.
1380 command_line->AppendSwitch(switches::kDisable3DAPIs);
1383 const base::ListValue* switches =
1384 prefs->GetList(prefs::kEnableDeprecatedWebPlatformFeatures);
1385 if (switches) {
1386 // Enable any deprecated features that have been re-enabled by policy.
1387 for (base::ListValue::const_iterator it = switches->begin();
1388 it != switches->end(); ++it) {
1389 std::string switch_to_enable;
1390 if ((*it)->GetAsString(&switch_to_enable))
1391 command_line->AppendSwitch(switch_to_enable);
1395 // Disable client-side phishing detection in the renderer if it is
1396 // disabled in the Profile preferences or the browser process.
1397 if (!prefs->GetBoolean(prefs::kSafeBrowsingEnabled) ||
1398 !g_browser_process->safe_browsing_detection_service()) {
1399 command_line->AppendSwitch(
1400 switches::kDisableClientSidePhishingDetection);
1403 if (prefs->GetBoolean(prefs::kPrintPreviewDisabled))
1404 command_line->AppendSwitch(switches::kDisablePrintPreview);
1406 InstantService* instant_service =
1407 InstantServiceFactory::GetForProfile(profile);
1408 if (instant_service &&
1409 instant_service->IsInstantProcess(process->GetID()))
1410 command_line->AppendSwitch(switches::kInstantProcess);
1412 #if !defined(OS_CHROMEOS)
1413 SigninClient* signin_client =
1414 ChromeSigninClientFactory::GetForProfile(profile);
1415 if (signin_client && signin_client->IsSigninProcess(process->GetID()))
1416 command_line->AppendSwitch(switches::kSigninProcess);
1417 #endif
1420 if (IsAutoReloadEnabled())
1421 command_line->AppendSwitch(switches::kEnableOfflineAutoReload);
1422 if (IsAutoReloadVisibleOnlyEnabled()) {
1423 command_line->AppendSwitch(
1424 switches::kEnableOfflineAutoReloadVisibleOnly);
1428 // Enable load stale cache if this session is in the field trial or
1429 // the user explicitly enabled it. Note that as far as the renderer
1430 // is concerned, the feature is enabled if-and-only-if the
1431 // kEnableOfflineLoadStaleCache flag is on the command line;
1432 // the yes/no/default behavior is only at the browser command line
1433 // level.
1435 // Command line switches override
1436 if (browser_command_line.HasSwitch(
1437 switches::kEnableOfflineLoadStaleCache)) {
1438 command_line->AppendSwitch(switches::kEnableOfflineLoadStaleCache);
1439 } else if (!browser_command_line.HasSwitch(
1440 switches::kDisableOfflineLoadStaleCache)) {
1441 std::string group =
1442 base::FieldTrialList::FindFullName("LoadStaleCacheExperiment");
1444 if (group == "Enabled")
1445 command_line->AppendSwitch(switches::kEnableOfflineLoadStaleCache);
1449 // Please keep this in alphabetical order.
1450 static const char* const kSwitchNames[] = {
1451 autofill::switches::kDisableFillOnAccountSelect,
1452 autofill::switches::kDisablePasswordGeneration,
1453 autofill::switches::kEnableFillOnAccountSelect,
1454 autofill::switches::kEnableFillOnAccountSelectNoHighlighting,
1455 autofill::switches::kEnablePasswordGeneration,
1456 autofill::switches::kEnablePasswordSaveOnInPageNavigation,
1457 autofill::switches::kEnableSingleClickAutofill,
1458 autofill::switches::kIgnoreAutocompleteOffForAutofill,
1459 autofill::switches::kLocalHeuristicsOnlyForPasswordGeneration,
1460 autofill::switches::kRespectAutocompleteOffForAutofill,
1461 #if defined(ENABLE_EXTENSIONS)
1462 extensions::switches::kAllowHTTPBackgroundPage,
1463 extensions::switches::kAllowLegacyExtensionManifests,
1464 extensions::switches::kEnableSurfaceWorker,
1465 extensions::switches::kEnableAppWindowControls,
1466 extensions::switches::kEnableEmbeddedExtensionOptions,
1467 extensions::switches::kEnableExperimentalExtensionApis,
1468 extensions::switches::kExtensionsOnChromeURLs,
1469 extensions::switches::kWhitelistedExtensionID,
1470 #endif
1471 switches::kAllowInsecureLocalhost,
1472 switches::kAppsCheckoutURL,
1473 switches::kAppsGalleryURL,
1474 switches::kCloudPrintURL,
1475 switches::kCloudPrintXmppEndpoint,
1476 switches::kDisableBundledPpapiFlash,
1477 switches::kDisableCastStreamingHWEncoding,
1478 switches::kDisableJavaScriptHarmonyShipping,
1479 switches::kDisableNewBookmarkApps,
1480 switches::kDisableOutOfProcessPdf,
1481 switches::kEnableBenchmarking,
1482 switches::kEnableNaCl,
1483 #if !defined(DISABLE_NACL)
1484 switches::kEnableNaClDebug,
1485 switches::kEnableNaClNonSfiMode,
1486 #endif
1487 switches::kEnableNetBenchmarking,
1488 switches::kEnableNewBookmarkApps,
1489 switches::kEnableOutOfProcessPdf,
1490 switches::kEnablePluginPlaceholderShadowDom,
1491 switches::kJavaScriptHarmony,
1492 switches::kMessageLoopHistogrammer,
1493 switches::kPlaybackMode,
1494 switches::kPpapiFlashArgs,
1495 switches::kPpapiFlashPath,
1496 switches::kPpapiFlashVersion,
1497 switches::kProfilingAtStart,
1498 switches::kProfilingFile,
1499 switches::kProfilingFlush,
1500 switches::kRecordMode,
1501 translate::switches::kTranslateSecurityOrigin,
1504 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1505 arraysize(kSwitchNames));
1506 } else if (process_type == switches::kUtilityProcess) {
1507 #if defined(ENABLE_EXTENSIONS)
1508 static const char* const kSwitchNames[] = {
1509 extensions::switches::kAllowHTTPBackgroundPage,
1510 extensions::switches::kEnableExperimentalExtensionApis,
1511 extensions::switches::kExtensionsOnChromeURLs,
1512 extensions::switches::kWhitelistedExtensionID,
1515 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1516 arraysize(kSwitchNames));
1517 #endif
1518 } else if (process_type == switches::kPluginProcess) {
1519 #if defined(OS_CHROMEOS)
1520 static const char* const kSwitchNames[] = {
1521 chromeos::switches::kLoginProfile,
1524 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1525 arraysize(kSwitchNames));
1526 #endif
1527 } else if (process_type == switches::kZygoteProcess) {
1528 static const char* const kSwitchNames[] = {
1529 // Load (in-process) Pepper plugins in-process in the zygote pre-sandbox.
1530 switches::kDisableBundledPpapiFlash,
1531 #if !defined(DISABLE_NACL)
1532 switches::kEnableNaClDebug,
1533 switches::kEnableNaClNonSfiMode,
1534 switches::kNaClDangerousNoSandboxNonSfi,
1535 switches::kUseNaClHelperNonSfi,
1536 #endif
1537 switches::kPpapiFlashPath,
1538 switches::kPpapiFlashVersion,
1541 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1542 arraysize(kSwitchNames));
1543 } else if (process_type == switches::kGpuProcess) {
1544 // If --ignore-gpu-blacklist is passed in, don't send in crash reports
1545 // because GPU is expected to be unreliable.
1546 if (browser_command_line.HasSwitch(switches::kIgnoreGpuBlacklist) &&
1547 !command_line->HasSwitch(switches::kDisableBreakpad))
1548 command_line->AppendSwitch(switches::kDisableBreakpad);
1551 // The command line switch kEnableBenchmarking needs to be specified along
1552 // with the kEnableStatsTable switch to ensure that the stats table global
1553 // is initialized correctly.
1554 if (command_line->HasSwitch(switches::kEnableBenchmarking))
1555 DCHECK(command_line->HasSwitch(switches::kEnableStatsTable));
1558 std::string ChromeContentBrowserClient::GetApplicationLocale() {
1559 if (BrowserThread::CurrentlyOn(BrowserThread::IO))
1560 return g_io_thread_application_locale.Get();
1561 return g_browser_process->GetApplicationLocale();
1564 std::string ChromeContentBrowserClient::GetAcceptLangs(
1565 content::BrowserContext* context) {
1566 Profile* profile = Profile::FromBrowserContext(context);
1567 return profile->GetPrefs()->GetString(prefs::kAcceptLanguages);
1570 const gfx::ImageSkia* ChromeContentBrowserClient::GetDefaultFavicon() {
1571 ResourceBundle& rb = ResourceBundle::GetSharedInstance();
1572 return rb.GetNativeImageNamed(IDR_DEFAULT_FAVICON).ToImageSkia();
1575 bool ChromeContentBrowserClient::AllowAppCache(
1576 const GURL& manifest_url,
1577 const GURL& first_party,
1578 content::ResourceContext* context) {
1579 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1580 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1581 return io_data->GetCookieSettings()->
1582 IsSettingCookieAllowed(manifest_url, first_party);
1585 bool ChromeContentBrowserClient::AllowServiceWorker(
1586 const GURL& scope,
1587 const GURL& first_party_url,
1588 content::ResourceContext* context) {
1589 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1590 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1591 return io_data->GetCookieSettings()->
1592 IsSettingCookieAllowed(scope, first_party_url);
1595 bool ChromeContentBrowserClient::AllowGetCookie(
1596 const GURL& url,
1597 const GURL& first_party,
1598 const net::CookieList& cookie_list,
1599 content::ResourceContext* context,
1600 int render_process_id,
1601 int render_frame_id) {
1602 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1603 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1604 bool allow = io_data->GetCookieSettings()->
1605 IsReadingCookieAllowed(url, first_party);
1607 BrowserThread::PostTask(
1608 BrowserThread::UI, FROM_HERE,
1609 base::Bind(&TabSpecificContentSettings::CookiesRead, render_process_id,
1610 render_frame_id, url, first_party, cookie_list, !allow, true));
1611 return allow;
1614 bool ChromeContentBrowserClient::AllowSetCookie(
1615 const GURL& url,
1616 const GURL& first_party,
1617 const std::string& cookie_line,
1618 content::ResourceContext* context,
1619 int render_process_id,
1620 int render_frame_id,
1621 net::CookieOptions* options) {
1622 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1623 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1624 CookieSettings* cookie_settings = io_data->GetCookieSettings();
1625 bool allow = cookie_settings->IsSettingCookieAllowed(url, first_party);
1627 if (prerender_tracker_) {
1628 prerender_tracker_->OnCookieChangedForURL(
1629 render_process_id,
1630 context->GetRequestContext()->cookie_store()->GetCookieMonster(),
1631 url);
1634 BrowserThread::PostTask(
1635 BrowserThread::UI, FROM_HERE,
1636 base::Bind(&TabSpecificContentSettings::CookieChanged, render_process_id,
1637 render_frame_id, url, first_party, cookie_line, *options,
1638 !allow));
1639 return allow;
1642 bool ChromeContentBrowserClient::AllowSaveLocalState(
1643 content::ResourceContext* context) {
1644 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1645 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1646 CookieSettings* cookie_settings = io_data->GetCookieSettings();
1647 ContentSetting setting = cookie_settings->GetDefaultCookieSetting(NULL);
1649 // TODO(bauerb): Should we also disallow local state if the default is BLOCK?
1650 // Could we even support per-origin settings?
1651 return setting != CONTENT_SETTING_SESSION_ONLY;
1654 bool ChromeContentBrowserClient::AllowWorkerDatabase(
1655 const GURL& url,
1656 const base::string16& name,
1657 const base::string16& display_name,
1658 unsigned long estimated_size,
1659 content::ResourceContext* context,
1660 const std::vector<std::pair<int, int> >& render_frames) {
1661 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1662 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1663 CookieSettings* cookie_settings = io_data->GetCookieSettings();
1664 bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1666 // Record access to database for potential display in UI.
1667 std::vector<std::pair<int, int> >::const_iterator i;
1668 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1669 BrowserThread::PostTask(
1670 BrowserThread::UI, FROM_HERE,
1671 base::Bind(&TabSpecificContentSettings::WebDatabaseAccessed,
1672 i->first, i->second, url, name, display_name, !allow));
1675 return allow;
1678 void ChromeContentBrowserClient::AllowWorkerFileSystem(
1679 const GURL& url,
1680 content::ResourceContext* context,
1681 const std::vector<std::pair<int, int> >& render_frames,
1682 base::Callback<void(bool)> callback) {
1683 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1684 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1685 CookieSettings* cookie_settings = io_data->GetCookieSettings();
1686 bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1688 #if defined(ENABLE_EXTENSIONS)
1689 GuestPermissionRequestHelper(url, render_frames, callback, allow);
1690 #else
1691 FileSystemAccessed(url, render_frames, callback, allow);
1692 #endif
1695 #if defined(ENABLE_EXTENSIONS)
1696 void ChromeContentBrowserClient::GuestPermissionRequestHelper(
1697 const GURL& url,
1698 const std::vector<std::pair<int, int> >& render_frames,
1699 base::Callback<void(bool)> callback,
1700 bool allow) {
1701 DCHECK(BrowserThread:: CurrentlyOn(BrowserThread::IO));
1702 std::vector<std::pair<int, int> >::const_iterator i;
1703 std::map<int, int> process_map;
1704 std::map<int, int>::const_iterator it;
1705 bool has_web_view_guest = false;
1706 // Record access to file system for potential display in UI.
1707 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1708 if (process_map.find(i->first) != process_map.end())
1709 continue;
1711 process_map.insert(std::pair<int, int>(i->first, i->second));
1713 if (extensions::WebViewRendererState::GetInstance()->IsGuest(i->first))
1714 has_web_view_guest = true;
1716 if (!has_web_view_guest) {
1717 FileSystemAccessed(url, render_frames, callback, allow);
1718 return;
1720 DCHECK_EQ(1U, process_map.size());
1721 it = process_map.begin();
1722 BrowserThread::PostTask(
1723 BrowserThread::UI,
1724 FROM_HERE,
1725 base::Bind(&ChromeContentBrowserClient::
1726 RequestFileSystemPermissionOnUIThread,
1727 it->first,
1728 it->second,
1729 url,
1730 allow,
1731 base::Bind(&ChromeContentBrowserClient::FileSystemAccessed,
1732 weak_factory_.GetWeakPtr(),
1733 url,
1734 render_frames,
1735 callback)));
1738 void ChromeContentBrowserClient::RequestFileSystemPermissionOnUIThread(
1739 int render_process_id,
1740 int render_frame_id,
1741 const GURL& url,
1742 bool allowed_by_default,
1743 const base::Callback<void(bool)>& callback) {
1744 DCHECK(BrowserThread:: CurrentlyOn(BrowserThread::UI));
1745 extensions::WebViewPermissionHelper* web_view_permission_helper =
1746 extensions::WebViewPermissionHelper::FromFrameID(
1747 render_process_id, render_frame_id);
1748 web_view_permission_helper->RequestFileSystemPermission(url,
1749 allowed_by_default,
1750 callback);
1752 #endif
1754 void ChromeContentBrowserClient::FileSystemAccessed(
1755 const GURL& url,
1756 const std::vector<std::pair<int, int> >& render_frames,
1757 base::Callback<void(bool)> callback,
1758 bool allow) {
1759 // Record access to file system for potential display in UI.
1760 std::vector<std::pair<int, int> >::const_iterator i;
1761 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1762 BrowserThread::PostTask(
1763 BrowserThread::UI,
1764 FROM_HERE,
1765 base::Bind(&TabSpecificContentSettings::FileSystemAccessed,
1766 i->first, i->second, url, !allow));
1768 callback.Run(allow);
1771 bool ChromeContentBrowserClient::AllowWorkerIndexedDB(
1772 const GURL& url,
1773 const base::string16& name,
1774 content::ResourceContext* context,
1775 const std::vector<std::pair<int, int> >& render_frames) {
1776 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1777 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1778 CookieSettings* cookie_settings = io_data->GetCookieSettings();
1779 bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1781 // Record access to IndexedDB for potential display in UI.
1782 std::vector<std::pair<int, int> >::const_iterator i;
1783 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1784 BrowserThread::PostTask(
1785 BrowserThread::UI, FROM_HERE,
1786 base::Bind(&TabSpecificContentSettings::IndexedDBAccessed,
1787 i->first, i->second, url, name, !allow));
1790 return allow;
1793 net::URLRequestContext*
1794 ChromeContentBrowserClient::OverrideRequestContextForURL(
1795 const GURL& url, content::ResourceContext* context) {
1796 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1797 #if defined(ENABLE_EXTENSIONS)
1798 if (url.SchemeIs(extensions::kExtensionScheme)) {
1799 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1800 return io_data->extensions_request_context();
1802 #endif
1804 return NULL;
1807 QuotaPermissionContext*
1808 ChromeContentBrowserClient::CreateQuotaPermissionContext() {
1809 return new ChromeQuotaPermissionContext();
1812 void ChromeContentBrowserClient::AllowCertificateError(
1813 int render_process_id,
1814 int render_frame_id,
1815 int cert_error,
1816 const net::SSLInfo& ssl_info,
1817 const GURL& request_url,
1818 ResourceType resource_type,
1819 bool overridable,
1820 bool strict_enforcement,
1821 bool expired_previous_decision,
1822 const base::Callback<void(bool)>& callback,
1823 content::CertificateRequestResultType* result) {
1824 if (resource_type != content::RESOURCE_TYPE_MAIN_FRAME) {
1825 // A sub-resource has a certificate error. The user doesn't really
1826 // have a context for making the right decision, so block the
1827 // request hard, without an info bar to allow showing the insecure
1828 // content.
1829 *result = content::CERTIFICATE_REQUEST_RESULT_TYPE_DENY;
1830 return;
1833 // If the tab is being prerendered, cancel the prerender and the request.
1834 content::RenderFrameHost* render_frame_host =
1835 content::RenderFrameHost::FromID(render_process_id, render_frame_id);
1836 WebContents* tab = WebContents::FromRenderFrameHost(render_frame_host);
1837 if (!tab) {
1838 NOTREACHED();
1839 return;
1842 prerender::PrerenderContents* prerender_contents =
1843 prerender::PrerenderContents::FromWebContents(tab);
1844 if (prerender_contents) {
1845 prerender_contents->Destroy(prerender::FINAL_STATUS_SSL_ERROR);
1846 *result = content::CERTIFICATE_REQUEST_RESULT_TYPE_CANCEL;
1847 return;
1850 // Otherwise, display an SSL blocking page. The interstitial page takes
1851 // ownership of ssl_blocking_page.
1852 int options_mask = 0;
1853 if (overridable)
1854 options_mask |= SSLBlockingPage::OVERRIDABLE;
1855 if (strict_enforcement)
1856 options_mask |= SSLBlockingPage::STRICT_ENFORCEMENT;
1857 if (expired_previous_decision)
1858 options_mask |= SSLBlockingPage::EXPIRED_BUT_PREVIOUSLY_ALLOWED;
1860 SSLErrorHandler::HandleSSLError(
1861 tab, cert_error, ssl_info, request_url, options_mask, callback);
1864 void ChromeContentBrowserClient::SelectClientCertificate(
1865 int render_process_id,
1866 int render_frame_id,
1867 net::SSLCertRequestInfo* cert_request_info,
1868 const base::Callback<void(net::X509Certificate*)>& callback) {
1869 content::RenderFrameHost* rfh = content::RenderFrameHost::FromID(
1870 render_process_id, render_frame_id);
1871 WebContents* tab = WebContents::FromRenderFrameHost(rfh);
1872 if (!tab) {
1873 // TODO(davidben): This makes the request hang, but returning no certificate
1874 // also breaks. It should abort the request. See https://crbug.com/417092
1875 return;
1878 prerender::PrerenderContents* prerender_contents =
1879 prerender::PrerenderContents::FromWebContents(tab);
1880 if (prerender_contents) {
1881 prerender_contents->Destroy(
1882 prerender::FINAL_STATUS_SSL_CLIENT_CERTIFICATE_REQUESTED);
1883 return;
1886 GURL requesting_url("https://" + cert_request_info->host_and_port.ToString());
1887 DCHECK(requesting_url.is_valid())
1888 << "Invalid URL string: https://"
1889 << cert_request_info->host_and_port.ToString();
1891 Profile* profile = Profile::FromBrowserContext(tab->GetBrowserContext());
1892 scoped_ptr<base::Value> filter =
1893 profile->GetHostContentSettingsMap()->GetWebsiteSetting(
1894 requesting_url,
1895 requesting_url,
1896 CONTENT_SETTINGS_TYPE_AUTO_SELECT_CERTIFICATE,
1897 std::string(),
1898 NULL);
1900 if (filter.get()) {
1901 // Try to automatically select a client certificate.
1902 if (filter->IsType(base::Value::TYPE_DICTIONARY)) {
1903 base::DictionaryValue* filter_dict =
1904 static_cast<base::DictionaryValue*>(filter.get());
1906 const std::vector<scoped_refptr<net::X509Certificate> >&
1907 all_client_certs = cert_request_info->client_certs;
1908 for (size_t i = 0; i < all_client_certs.size(); ++i) {
1909 if (CertMatchesFilter(*all_client_certs[i].get(), *filter_dict)) {
1910 // Use the first certificate that is matched by the filter.
1911 callback.Run(all_client_certs[i].get());
1912 return;
1915 } else {
1916 NOTREACHED();
1920 chrome::ShowSSLClientCertificateSelector(tab, cert_request_info, callback);
1923 void ChromeContentBrowserClient::AddCertificate(
1924 net::CertificateMimeType cert_type,
1925 const void* cert_data,
1926 size_t cert_size,
1927 int render_process_id,
1928 int render_frame_id) {
1929 chrome::SSLAddCertificate(cert_type, cert_data, cert_size,
1930 render_process_id, render_frame_id);
1933 content::MediaObserver* ChromeContentBrowserClient::GetMediaObserver() {
1934 return MediaCaptureDevicesDispatcher::GetInstance();
1937 content::PlatformNotificationService*
1938 ChromeContentBrowserClient::GetPlatformNotificationService() {
1939 #if defined(ENABLE_NOTIFICATIONS)
1940 return PlatformNotificationServiceImpl::GetInstance();
1941 #else
1942 NOTIMPLEMENTED();
1943 return NULL;
1944 #endif
1947 void ChromeContentBrowserClient::RequestPermission(
1948 content::PermissionType permission,
1949 content::WebContents* web_contents,
1950 int bridge_id,
1951 const GURL& requesting_frame,
1952 bool user_gesture,
1953 const base::Callback<void(content::PermissionStatus)>& result_callback) {
1954 int render_process_id = web_contents->GetRenderProcessHost()->GetID();
1955 int render_view_id = web_contents->GetRenderViewHost()->GetRoutingID();
1956 const PermissionRequestID request_id(render_process_id,
1957 render_view_id,
1958 bridge_id,
1959 requesting_frame);
1960 Profile* profile =
1961 Profile::FromBrowserContext(web_contents->GetBrowserContext());
1962 PermissionContextBase* context = GetPermissionContext(profile, permission);
1964 if (!context)
1965 return;
1967 context->RequestPermission(web_contents, request_id, requesting_frame,
1968 user_gesture,
1969 base::Bind(&OnRequestPermission, result_callback));
1972 content::PermissionStatus ChromeContentBrowserClient::GetPermissionStatus(
1973 content::PermissionType permission,
1974 content::BrowserContext* browser_context,
1975 const GURL& requesting_origin,
1976 const GURL& embedding_origin) {
1977 DCHECK(browser_context);
1978 Profile* profile = Profile::FromBrowserContext(browser_context);
1979 PermissionContextBase* context = GetPermissionContext(profile, permission);
1981 if (!context)
1982 return content::PERMISSION_STATUS_ASK;
1984 return ContentSettingToPermissionStatus(
1985 context->GetPermissionStatus(requesting_origin.GetOrigin(),
1986 embedding_origin.GetOrigin()));
1989 void ChromeContentBrowserClient::ResetPermission(
1990 content::PermissionType permission,
1991 content::BrowserContext* browser_context,
1992 const GURL& requesting_origin,
1993 const GURL& embedding_origin) {
1994 DCHECK(browser_context);
1995 Profile* profile = Profile::FromBrowserContext(browser_context);
1996 PermissionContextBase* context = GetPermissionContext(profile, permission);
1998 if (!context)
1999 return;
2001 context->ResetPermission(requesting_origin.GetOrigin(),
2002 embedding_origin.GetOrigin());
2005 void ChromeContentBrowserClient::CancelPermissionRequest(
2006 content::PermissionType permission,
2007 content::WebContents* web_contents,
2008 int bridge_id,
2009 const GURL& requesting_frame) {
2010 int render_process_id = web_contents->GetRenderProcessHost()->GetID();
2011 int render_view_id = web_contents->GetRenderViewHost()->GetRoutingID();
2012 const PermissionRequestID request_id(render_process_id,
2013 render_view_id,
2014 bridge_id,
2015 requesting_frame);
2016 Profile* profile =
2017 Profile::FromBrowserContext(web_contents->GetBrowserContext());
2018 PermissionContextBase* context = GetPermissionContext(profile, permission);
2019 if (!context)
2020 return;
2021 context->CancelPermissionRequest(web_contents, request_id);
2024 void ChromeContentBrowserClient::RegisterPermissionUsage(
2025 content::PermissionType permission,
2026 content::WebContents* web_contents,
2027 const GURL& frame_url,
2028 const GURL& main_frame_url) {
2029 Profile::FromBrowserContext(web_contents->GetBrowserContext())
2030 ->GetHostContentSettingsMap()
2031 ->UpdateLastUsage(
2032 frame_url, main_frame_url, PermissionToContentSetting(permission));
2035 bool ChromeContentBrowserClient::CanCreateWindow(
2036 const GURL& opener_url,
2037 const GURL& opener_top_level_frame_url,
2038 const GURL& source_origin,
2039 WindowContainerType container_type,
2040 const GURL& target_url,
2041 const content::Referrer& referrer,
2042 WindowOpenDisposition disposition,
2043 const WebWindowFeatures& features,
2044 bool user_gesture,
2045 bool opener_suppressed,
2046 content::ResourceContext* context,
2047 int render_process_id,
2048 int opener_id,
2049 bool* no_javascript_access) {
2050 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
2052 *no_javascript_access = false;
2054 // If the opener is trying to create a background window but doesn't have
2055 // the appropriate permission, fail the attempt.
2056 if (container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {
2057 #if defined(ENABLE_EXTENSIONS)
2058 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
2059 InfoMap* map = io_data->GetExtensionInfoMap();
2060 if (!map->SecurityOriginHasAPIPermission(
2061 source_origin,
2062 render_process_id,
2063 APIPermission::kBackground)) {
2064 return false;
2067 // Note: this use of GetExtensionOrAppByURL is safe but imperfect. It may
2068 // return a recently installed Extension even if this CanCreateWindow call
2069 // was made by an old copy of the page in a normal web process. That's ok,
2070 // because the permission check above would have caused an early return
2071 // already. We must use the full URL to find hosted apps, though, and not
2072 // just the origin.
2073 const Extension* extension =
2074 map->extensions().GetExtensionOrAppByURL(opener_url);
2075 if (extension && !extensions::BackgroundInfo::AllowJSAccess(extension))
2076 *no_javascript_access = true;
2077 #endif
2079 return true;
2082 #if defined(ENABLE_EXTENSIONS)
2083 if (extensions::WebViewRendererState::GetInstance()->IsGuest(
2084 render_process_id))
2085 return true;
2086 #endif
2088 HostContentSettingsMap* content_settings =
2089 ProfileIOData::FromResourceContext(context)->GetHostContentSettingsMap();
2090 BlockedWindowParams blocked_params(target_url,
2091 referrer,
2092 disposition,
2093 features,
2094 user_gesture,
2095 opener_suppressed,
2096 render_process_id,
2097 opener_id);
2099 if (!user_gesture &&
2100 !base::CommandLine::ForCurrentProcess()->HasSwitch(
2101 switches::kDisablePopupBlocking)) {
2102 if (content_settings->GetContentSetting(opener_top_level_frame_url,
2103 opener_top_level_frame_url,
2104 CONTENT_SETTINGS_TYPE_POPUPS,
2105 std::string()) !=
2106 CONTENT_SETTING_ALLOW) {
2107 BrowserThread::PostTask(BrowserThread::UI,
2108 FROM_HERE,
2109 base::Bind(&HandleBlockedPopupOnUIThread,
2110 blocked_params));
2111 return false;
2115 #if defined(OS_ANDROID)
2116 if (SingleTabModeTabHelper::IsRegistered(render_process_id, opener_id)) {
2117 BrowserThread::PostTask(BrowserThread::UI,
2118 FROM_HERE,
2119 base::Bind(&HandleSingleTabModeBlockOnUIThread,
2120 blocked_params));
2121 return false;
2123 #endif
2125 return true;
2128 void ChromeContentBrowserClient::ResourceDispatcherHostCreated() {
2129 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
2130 prerender_tracker_ = g_browser_process->prerender_tracker();
2131 return g_browser_process->ResourceDispatcherHostCreated();
2134 content::SpeechRecognitionManagerDelegate*
2135 ChromeContentBrowserClient::CreateSpeechRecognitionManagerDelegate() {
2136 return new speech::ChromeSpeechRecognitionManagerDelegate();
2139 net::NetLog* ChromeContentBrowserClient::GetNetLog() {
2140 return g_browser_process->net_log();
2143 AccessTokenStore* ChromeContentBrowserClient::CreateAccessTokenStore() {
2144 return new ChromeAccessTokenStore();
2147 bool ChromeContentBrowserClient::IsFastShutdownPossible() {
2148 return true;
2151 void ChromeContentBrowserClient::OverrideWebkitPrefs(
2152 RenderViewHost* rvh, WebPreferences* web_prefs) {
2153 Profile* profile = Profile::FromBrowserContext(
2154 rvh->GetProcess()->GetBrowserContext());
2155 PrefService* prefs = profile->GetPrefs();
2157 // Fill per-script font preferences. These are not registered on Android
2158 // - http://crbug.com/308033.
2159 #if !defined(OS_ANDROID)
2160 FontFamilyCache::FillFontFamilyMap(profile,
2161 prefs::kWebKitStandardFontFamilyMap,
2162 &web_prefs->standard_font_family_map);
2163 FontFamilyCache::FillFontFamilyMap(profile,
2164 prefs::kWebKitFixedFontFamilyMap,
2165 &web_prefs->fixed_font_family_map);
2166 FontFamilyCache::FillFontFamilyMap(profile,
2167 prefs::kWebKitSerifFontFamilyMap,
2168 &web_prefs->serif_font_family_map);
2169 FontFamilyCache::FillFontFamilyMap(profile,
2170 prefs::kWebKitSansSerifFontFamilyMap,
2171 &web_prefs->sans_serif_font_family_map);
2172 FontFamilyCache::FillFontFamilyMap(profile,
2173 prefs::kWebKitCursiveFontFamilyMap,
2174 &web_prefs->cursive_font_family_map);
2175 FontFamilyCache::FillFontFamilyMap(profile,
2176 prefs::kWebKitFantasyFontFamilyMap,
2177 &web_prefs->fantasy_font_family_map);
2178 FontFamilyCache::FillFontFamilyMap(profile,
2179 prefs::kWebKitPictographFontFamilyMap,
2180 &web_prefs->pictograph_font_family_map);
2181 #endif
2183 web_prefs->default_font_size =
2184 prefs->GetInteger(prefs::kWebKitDefaultFontSize);
2185 web_prefs->default_fixed_font_size =
2186 prefs->GetInteger(prefs::kWebKitDefaultFixedFontSize);
2187 web_prefs->minimum_font_size =
2188 prefs->GetInteger(prefs::kWebKitMinimumFontSize);
2189 web_prefs->minimum_logical_font_size =
2190 prefs->GetInteger(prefs::kWebKitMinimumLogicalFontSize);
2192 web_prefs->default_encoding = prefs->GetString(prefs::kDefaultCharset);
2194 web_prefs->javascript_can_open_windows_automatically =
2195 prefs->GetBoolean(prefs::kWebKitJavascriptCanOpenWindowsAutomatically);
2196 web_prefs->dom_paste_enabled =
2197 prefs->GetBoolean(prefs::kWebKitDomPasteEnabled);
2198 web_prefs->shrinks_standalone_images_to_fit =
2199 prefs->GetBoolean(prefs::kWebKitShrinksStandaloneImagesToFit);
2200 web_prefs->tabs_to_links = prefs->GetBoolean(prefs::kWebkitTabsToLinks);
2202 if (!prefs->GetBoolean(prefs::kWebKitJavascriptEnabled))
2203 web_prefs->javascript_enabled = false;
2204 if (!prefs->GetBoolean(prefs::kWebKitWebSecurityEnabled))
2205 web_prefs->web_security_enabled = false;
2206 if (!prefs->GetBoolean(prefs::kWebKitPluginsEnabled))
2207 web_prefs->plugins_enabled = false;
2208 if (!prefs->GetBoolean(prefs::kWebKitJavaEnabled))
2209 web_prefs->java_enabled = false;
2210 web_prefs->loads_images_automatically =
2211 prefs->GetBoolean(prefs::kWebKitLoadsImagesAutomatically);
2213 if (prefs->GetBoolean(prefs::kDisable3DAPIs))
2214 web_prefs->experimental_webgl_enabled = false;
2216 web_prefs->allow_displaying_insecure_content =
2217 prefs->GetBoolean(prefs::kWebKitAllowDisplayingInsecureContent);
2218 web_prefs->allow_running_insecure_content =
2219 prefs->GetBoolean(prefs::kWebKitAllowRunningInsecureContent);
2220 #if defined(OS_ANDROID)
2221 web_prefs->font_scale_factor =
2222 static_cast<float>(prefs->GetDouble(prefs::kWebKitFontScaleFactor));
2223 web_prefs->device_scale_adjustment = GetDeviceScaleAdjustment();
2224 web_prefs->force_enable_zoom =
2225 prefs->GetBoolean(prefs::kWebKitForceEnableZoom);
2226 #endif
2228 #if defined(OS_ANDROID)
2229 web_prefs->password_echo_enabled =
2230 prefs->GetBoolean(prefs::kWebKitPasswordEchoEnabled);
2231 #else
2232 web_prefs->password_echo_enabled = browser_defaults::kPasswordEchoEnabled;
2233 #endif
2235 web_prefs->asynchronous_spell_checking_enabled = true;
2236 web_prefs->unified_textchecker_enabled = true;
2238 web_prefs->uses_universal_detector =
2239 prefs->GetBoolean(prefs::kWebKitUsesUniversalDetector);
2240 web_prefs->text_areas_are_resizable =
2241 prefs->GetBoolean(prefs::kWebKitTextAreasAreResizable);
2242 web_prefs->hyperlink_auditing_enabled =
2243 prefs->GetBoolean(prefs::kEnableHyperlinkAuditing);
2245 #if defined(ENABLE_EXTENSIONS)
2246 std::string image_animation_policy =
2247 prefs->GetString(prefs::kAnimationPolicy);
2248 if (image_animation_policy == kAnimationPolicyOnce)
2249 web_prefs->animation_policy =
2250 content::IMAGE_ANIMATION_POLICY_ANIMATION_ONCE;
2251 else if (image_animation_policy == kAnimationPolicyNone)
2252 web_prefs->animation_policy = content::IMAGE_ANIMATION_POLICY_NO_ANIMATION;
2253 else
2254 web_prefs->animation_policy = content::IMAGE_ANIMATION_POLICY_ALLOWED;
2255 #endif
2257 // Make sure we will set the default_encoding with canonical encoding name.
2258 web_prefs->default_encoding =
2259 CharacterEncoding::GetCanonicalEncodingNameByAliasName(
2260 web_prefs->default_encoding);
2261 if (web_prefs->default_encoding.empty()) {
2262 prefs->ClearPref(prefs::kDefaultCharset);
2263 web_prefs->default_encoding = prefs->GetString(prefs::kDefaultCharset);
2265 DCHECK(!web_prefs->default_encoding.empty());
2267 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2268 switches::kEnablePotentiallyAnnoyingSecurityFeatures)) {
2269 web_prefs->disable_reading_from_canvas = true;
2270 web_prefs->strict_mixed_content_checking = true;
2271 web_prefs->strict_powerful_feature_restrictions = true;
2274 for (size_t i = 0; i < extra_parts_.size(); ++i)
2275 extra_parts_[i]->OverrideWebkitPrefs(rvh, web_prefs);
2278 void ChromeContentBrowserClient::BrowserURLHandlerCreated(
2279 BrowserURLHandler* handler) {
2280 for (size_t i = 0; i < extra_parts_.size(); ++i)
2281 extra_parts_[i]->BrowserURLHandlerCreated(handler);
2283 // about: handler. Must come before chrome: handler, since it will
2284 // rewrite about: urls to chrome: URLs and then expect chrome: to
2285 // actually handle them. Also relies on a preliminary fixup phase.
2286 handler->SetFixupHandler(&FixupBrowserAboutURL);
2287 handler->AddHandlerPair(&WillHandleBrowserAboutURL,
2288 BrowserURLHandler::null_handler());
2290 #if defined(OS_ANDROID)
2291 // Handler to rewrite chrome://newtab on Android.
2292 handler->AddHandlerPair(&chrome::android::HandleAndroidNativePageURL,
2293 BrowserURLHandler::null_handler());
2294 #else
2295 // Handler to rewrite chrome://newtab for InstantExtended.
2296 handler->AddHandlerPair(&chrome::HandleNewTabURLRewrite,
2297 &chrome::HandleNewTabURLReverseRewrite);
2298 #endif
2300 // chrome: & friends.
2301 handler->AddHandlerPair(&HandleWebUI, &HandleWebUIReverse);
2304 void ChromeContentBrowserClient::ClearCache(RenderViewHost* rvh) {
2305 Profile* profile = Profile::FromBrowserContext(
2306 rvh->GetSiteInstance()->GetProcess()->GetBrowserContext());
2307 BrowsingDataRemover* remover =
2308 BrowsingDataRemover::CreateForUnboundedRange(profile);
2309 remover->Remove(BrowsingDataRemover::REMOVE_CACHE,
2310 BrowsingDataHelper::UNPROTECTED_WEB);
2311 // BrowsingDataRemover takes care of deleting itself when done.
2314 void ChromeContentBrowserClient::ClearCookies(RenderViewHost* rvh) {
2315 Profile* profile = Profile::FromBrowserContext(
2316 rvh->GetSiteInstance()->GetProcess()->GetBrowserContext());
2317 BrowsingDataRemover* remover =
2318 BrowsingDataRemover::CreateForUnboundedRange(profile);
2319 int remove_mask = BrowsingDataRemover::REMOVE_SITE_DATA;
2320 remover->Remove(remove_mask, BrowsingDataHelper::UNPROTECTED_WEB);
2321 // BrowsingDataRemover takes care of deleting itself when done.
2324 base::FilePath ChromeContentBrowserClient::GetDefaultDownloadDirectory() {
2325 return DownloadPrefs::GetDefaultDownloadDirectory();
2328 std::string ChromeContentBrowserClient::GetDefaultDownloadName() {
2329 return l10n_util::GetStringUTF8(IDS_DEFAULT_DOWNLOAD_FILENAME);
2332 void ChromeContentBrowserClient::DidCreatePpapiPlugin(
2333 content::BrowserPpapiHost* browser_host) {
2334 #if defined(ENABLE_PLUGINS)
2335 ChromeContentBrowserClientPluginsPart::DidCreatePpapiPlugin(browser_host);
2336 #endif
2339 content::BrowserPpapiHost*
2340 ChromeContentBrowserClient::GetExternalBrowserPpapiHost(
2341 int plugin_process_id) {
2342 #if !defined(DISABLE_NACL)
2343 content::BrowserChildProcessHostIterator iter(PROCESS_TYPE_NACL_LOADER);
2344 while (!iter.Done()) {
2345 nacl::NaClProcessHost* host = static_cast<nacl::NaClProcessHost*>(
2346 iter.GetDelegate());
2347 if (host->process() &&
2348 host->process()->GetData().id == plugin_process_id) {
2349 // Found the plugin.
2350 return host->browser_ppapi_host();
2352 ++iter;
2354 #endif
2355 return NULL;
2358 bool ChromeContentBrowserClient::AllowPepperSocketAPI(
2359 content::BrowserContext* browser_context,
2360 const GURL& url,
2361 bool private_api,
2362 const content::SocketPermissionRequest* params) {
2363 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
2364 return ChromeContentBrowserClientPluginsPart::AllowPepperSocketAPI(
2365 browser_context, url, private_api, params, allowed_socket_origins_);
2366 #else
2367 return false;
2368 #endif
2371 ui::SelectFilePolicy* ChromeContentBrowserClient::CreateSelectFilePolicy(
2372 WebContents* web_contents) {
2373 return new ChromeSelectFilePolicy(web_contents);
2376 void ChromeContentBrowserClient::GetAdditionalAllowedSchemesForFileSystem(
2377 std::vector<std::string>* additional_allowed_schemes) {
2378 ContentBrowserClient::GetAdditionalAllowedSchemesForFileSystem(
2379 additional_allowed_schemes);
2380 additional_allowed_schemes->push_back(content::kChromeDevToolsScheme);
2381 additional_allowed_schemes->push_back(content::kChromeUIScheme);
2382 for (size_t i = 0; i < extra_parts_.size(); ++i) {
2383 extra_parts_[i]->GetAdditionalAllowedSchemesForFileSystem(
2384 additional_allowed_schemes);
2388 void ChromeContentBrowserClient::GetURLRequestAutoMountHandlers(
2389 std::vector<storage::URLRequestAutoMountHandler>* handlers) {
2390 for (size_t i = 0; i < extra_parts_.size(); ++i)
2391 extra_parts_[i]->GetURLRequestAutoMountHandlers(handlers);
2394 void ChromeContentBrowserClient::GetAdditionalFileSystemBackends(
2395 content::BrowserContext* browser_context,
2396 const base::FilePath& storage_partition_path,
2397 ScopedVector<storage::FileSystemBackend>* additional_backends) {
2398 #if defined(OS_CHROMEOS)
2399 storage::ExternalMountPoints* external_mount_points =
2400 content::BrowserContext::GetMountPoints(browser_context);
2401 DCHECK(external_mount_points);
2402 chromeos::FileSystemBackend* backend = new chromeos::FileSystemBackend(
2403 new drive::FileSystemBackendDelegate,
2404 new chromeos::file_system_provider::BackendDelegate,
2405 new chromeos::MTPFileSystemBackendDelegate(storage_partition_path),
2406 browser_context->GetSpecialStoragePolicy(),
2407 external_mount_points,
2408 storage::ExternalMountPoints::GetSystemInstance());
2409 backend->AddSystemMountPoints();
2410 DCHECK(backend->CanHandleType(storage::kFileSystemTypeExternal));
2411 additional_backends->push_back(backend);
2412 #endif
2414 for (size_t i = 0; i < extra_parts_.size(); ++i) {
2415 extra_parts_[i]->GetAdditionalFileSystemBackends(
2416 browser_context, storage_partition_path, additional_backends);
2420 #if defined(OS_POSIX) && !defined(OS_MACOSX)
2421 void ChromeContentBrowserClient::GetAdditionalMappedFilesForChildProcess(
2422 const base::CommandLine& command_line,
2423 int child_process_id,
2424 FileDescriptorInfo* mappings) {
2425 #if defined(V8_USE_EXTERNAL_STARTUP_DATA)
2426 if (v8_snapshot_fd_.get() == -1 && v8_natives_fd_.get() == -1) {
2427 base::FilePath v8_data_path;
2428 PathService::Get(gin::IsolateHolder::kV8SnapshotBasePathKey, &v8_data_path);
2429 DCHECK(!v8_data_path.empty());
2431 int file_flags = base::File::FLAG_OPEN | base::File::FLAG_READ;
2432 base::FilePath v8_natives_data_path =
2433 v8_data_path.AppendASCII(gin::IsolateHolder::kNativesFileName);
2434 base::FilePath v8_snapshot_data_path =
2435 v8_data_path.AppendASCII(gin::IsolateHolder::kSnapshotFileName);
2436 base::File v8_natives_data_file(v8_natives_data_path, file_flags);
2437 base::File v8_snapshot_data_file(v8_snapshot_data_path, file_flags);
2438 DCHECK(v8_natives_data_file.IsValid());
2439 DCHECK(v8_snapshot_data_file.IsValid());
2440 v8_natives_fd_.reset(v8_natives_data_file.TakePlatformFile());
2441 v8_snapshot_fd_.reset(v8_snapshot_data_file.TakePlatformFile());
2443 mappings->Share(kV8NativesDataDescriptor, v8_natives_fd_.get());
2444 mappings->Share(kV8SnapshotDataDescriptor, v8_snapshot_fd_.get());
2445 #endif // V8_USE_EXTERNAL_STARTUP_DATA
2447 #if defined(OS_ANDROID)
2448 base::FilePath data_path;
2449 PathService::Get(ui::DIR_RESOURCE_PAKS_ANDROID, &data_path);
2450 DCHECK(!data_path.empty());
2452 int flags = base::File::FLAG_OPEN | base::File::FLAG_READ;
2453 base::FilePath chrome_resources_pak =
2454 data_path.AppendASCII("chrome_100_percent.pak");
2455 base::File file(chrome_resources_pak, flags);
2456 DCHECK(file.IsValid());
2457 mappings->Transfer(kAndroidChrome100PercentPakDescriptor,
2458 base::ScopedFD(file.TakePlatformFile()));
2460 const std::string locale = GetApplicationLocale();
2461 base::FilePath locale_pak = ResourceBundle::GetSharedInstance().
2462 GetLocaleFilePath(locale, false);
2463 file.Initialize(locale_pak, flags);
2464 DCHECK(file.IsValid());
2465 mappings->Transfer(kAndroidLocalePakDescriptor,
2466 base::ScopedFD(file.TakePlatformFile()));
2468 base::FilePath resources_pack_path;
2469 PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
2470 file.Initialize(resources_pack_path, flags);
2471 DCHECK(file.IsValid());
2472 mappings->Transfer(kAndroidUIResourcesPakDescriptor,
2473 base::ScopedFD(file.TakePlatformFile()));
2475 if (breakpad::IsCrashReporterEnabled()) {
2476 file = breakpad::CrashDumpManager::GetInstance()->CreateMinidumpFile(
2477 child_process_id);
2478 if (file.IsValid()) {
2479 mappings->Transfer(kAndroidMinidumpDescriptor,
2480 base::ScopedFD(file.TakePlatformFile()));
2481 } else {
2482 LOG(ERROR) << "Failed to create file for minidump, crash reporting will "
2483 "be disabled for this process.";
2487 base::FilePath app_data_path;
2488 PathService::Get(base::DIR_ANDROID_APP_DATA, &app_data_path);
2489 DCHECK(!app_data_path.empty());
2491 flags = base::File::FLAG_OPEN | base::File::FLAG_READ;
2492 base::FilePath icudata_path =
2493 app_data_path.AppendASCII(base::i18n::kIcuDataFileName);
2494 base::File icudata_file(icudata_path, flags);
2495 DCHECK(icudata_file.IsValid());
2496 mappings->Transfer(kAndroidICUDataDescriptor,
2497 base::ScopedFD(icudata_file.TakePlatformFile()));
2498 #else
2499 int crash_signal_fd = GetCrashSignalFD(command_line);
2500 if (crash_signal_fd >= 0) {
2501 mappings->Share(kCrashDumpSignal, crash_signal_fd);
2503 #endif // defined(OS_ANDROID)
2505 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
2507 #if defined(OS_WIN)
2508 const wchar_t* ChromeContentBrowserClient::GetResourceDllName() {
2509 return chrome::kBrowserResourcesDll;
2512 void ChromeContentBrowserClient::PreSpawnRenderer(
2513 sandbox::TargetPolicy* policy,
2514 bool* success) {
2515 // This code is duplicated in nacl_exe_win_64.cc.
2516 // Allow the server side of a pipe restricted to the "chrome.nacl."
2517 // namespace so that it cannot impersonate other system or other chrome
2518 // service pipes.
2519 sandbox::ResultCode result = policy->AddRule(
2520 sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
2521 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
2522 L"\\\\.\\pipe\\chrome.nacl.*");
2523 if (result != sandbox::SBOX_ALL_OK) {
2524 *success = false;
2525 return;
2528 // Renderers need to send named pipe handles and shared memory
2529 // segment handles to NaCl loader processes.
2530 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
2531 sandbox::TargetPolicy::HANDLES_DUP_ANY,
2532 L"File");
2533 if (result != sandbox::SBOX_ALL_OK) {
2534 *success = false;
2535 return;
2538 #endif
2540 bool ChromeContentBrowserClient::CheckMediaAccessPermission(
2541 content::BrowserContext* browser_context,
2542 const GURL& security_origin,
2543 content::MediaStreamType type) {
2544 return MediaCaptureDevicesDispatcher::GetInstance()
2545 ->CheckMediaAccessPermission(
2546 browser_context, security_origin, type);
2549 void ChromeContentBrowserClient::OpenURL(
2550 content::BrowserContext* browser_context,
2551 const content::OpenURLParams& params,
2552 const base::Callback<void(content::WebContents*)>& callback) {
2553 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2555 #if !defined(OS_ANDROID) && !defined(OS_IOS)
2556 NavigateParams nav_params(Profile::FromBrowserContext(browser_context),
2557 params.url,
2558 params.transition);
2559 FillNavigateParamsFromOpenURLParams(&nav_params, params);
2560 nav_params.user_gesture = params.user_gesture;
2562 Navigate(&nav_params);
2563 callback.Run(nav_params.target_contents);
2564 #elif defined(OS_ANDROID)
2565 chrome::android::ServiceTabLauncher::GetInstance()->LaunchTab(
2566 browser_context, params, callback);
2567 #else
2568 NOTIMPLEMENTED();
2569 #endif
2572 void ChromeContentBrowserClient::RecordURLMetric(const std::string& metric,
2573 const GURL& url) {
2574 if (url.is_valid())
2575 rappor::SampleDomainAndRegistryFromGURL(metric, url);
2578 content::DevToolsManagerDelegate*
2579 ChromeContentBrowserClient::GetDevToolsManagerDelegate() {
2580 #if defined(OS_ANDROID)
2581 return new DevToolsManagerDelegateAndroid();
2582 #else
2583 return new ChromeDevToolsManagerDelegate();
2584 #endif
2587 content::TracingDelegate* ChromeContentBrowserClient::GetTracingDelegate() {
2588 #if !defined(OS_ANDROID)
2589 return new ChromeTracingDelegate();
2590 #else
2591 return nullptr;
2592 #endif
2595 bool ChromeContentBrowserClient::IsPluginAllowedToCallRequestOSFileHandle(
2596 content::BrowserContext* browser_context,
2597 const GURL& url) {
2598 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
2599 return ChromeContentBrowserClientPluginsPart::
2600 IsPluginAllowedToCallRequestOSFileHandle(browser_context, url,
2601 allowed_file_handle_origins_);
2602 #else
2603 return false;
2604 #endif
2607 bool ChromeContentBrowserClient::IsPluginAllowedToUseDevChannelAPIs(
2608 content::BrowserContext* browser_context,
2609 const GURL& url) {
2610 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
2611 return ChromeContentBrowserClientPluginsPart::
2612 IsPluginAllowedToUseDevChannelAPIs(browser_context, url,
2613 allowed_dev_channel_origins_);
2614 #else
2615 return false;
2616 #endif
2619 net::CookieStore*
2620 ChromeContentBrowserClient::OverrideCookieStoreForRenderProcess(
2621 int render_process_id) {
2622 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
2623 if (!prerender_tracker_)
2624 return NULL;
2625 return prerender_tracker_->GetPrerenderCookieStoreForRenderProcess(
2626 render_process_id).get();
2629 void ChromeContentBrowserClient::OverridePageVisibilityState(
2630 RenderFrameHost* render_frame_host,
2631 blink::WebPageVisibilityState* visibility_state) {
2632 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
2634 WebContents* web_contents =
2635 WebContents::FromRenderFrameHost(render_frame_host);
2636 DCHECK(web_contents);
2638 Profile* profile =
2639 Profile::FromBrowserContext(web_contents->GetBrowserContext());
2640 prerender::PrerenderManager* prerender_manager =
2641 prerender::PrerenderManagerFactory::GetForProfile(profile);
2642 if (prerender_manager &&
2643 prerender_manager->IsWebContentsPrerendering(web_contents, nullptr)) {
2644 *visibility_state = blink::WebPageVisibilityStatePrerender;
2648 #if defined(ENABLE_WEBRTC)
2649 void ChromeContentBrowserClient::MaybeCopyDisableWebRtcEncryptionSwitch(
2650 base::CommandLine* to_command_line,
2651 const base::CommandLine& from_command_line,
2652 VersionInfo::Channel channel) {
2653 #if defined(OS_ANDROID)
2654 const VersionInfo::Channel kMaxDisableEncryptionChannel =
2655 VersionInfo::CHANNEL_BETA;
2656 #else
2657 const VersionInfo::Channel kMaxDisableEncryptionChannel =
2658 VersionInfo::CHANNEL_DEV;
2659 #endif
2660 if (channel <= kMaxDisableEncryptionChannel) {
2661 static const char* const kWebRtcDevSwitchNames[] = {
2662 switches::kDisableWebRtcEncryption,
2664 to_command_line->CopySwitchesFrom(from_command_line,
2665 kWebRtcDevSwitchNames,
2666 arraysize(kWebRtcDevSwitchNames));
2669 #endif // defined(ENABLE_WEBRTC)
2671 } // namespace chrome