Mechanical rename of base::debug -> base::trace_event for /content
[chromium-blink-merge.git] / chrome / browser / chrome_content_browser_client.cc
blob83b62c9740b6ff4b62972d7c5675376ab7a252b2
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/nacl_host/nacl_browser_delegate_impl.h"
44 #include "chrome/browser/net/chrome_net_log.h"
45 #include "chrome/browser/notifications/desktop_notification_service.h"
46 #include "chrome/browser/notifications/desktop_notification_service_factory.h"
47 #include "chrome/browser/notifications/platform_notification_service_impl.h"
48 #include "chrome/browser/platform_util.h"
49 #include "chrome/browser/prerender/prerender_final_status.h"
50 #include "chrome/browser/prerender/prerender_manager.h"
51 #include "chrome/browser/prerender/prerender_manager_factory.h"
52 #include "chrome/browser/prerender/prerender_message_filter.h"
53 #include "chrome/browser/prerender/prerender_tracker.h"
54 #include "chrome/browser/printing/printing_message_filter.h"
55 #include "chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.h"
56 #include "chrome/browser/profiles/profile.h"
57 #include "chrome/browser/profiles/profile_io_data.h"
58 #include "chrome/browser/renderer_host/chrome_render_message_filter.h"
59 #include "chrome/browser/renderer_host/pepper/chrome_browser_pepper_host_factory.h"
60 #include "chrome/browser/search/instant_service.h"
61 #include "chrome/browser/search/instant_service_factory.h"
62 #include "chrome/browser/search/search.h"
63 #include "chrome/browser/search_engines/search_provider_install_state_message_filter.h"
64 #include "chrome/browser/services/gcm/push_messaging_permission_context.h"
65 #include "chrome/browser/services/gcm/push_messaging_permission_context_factory.h"
66 #include "chrome/browser/signin/principals_message_filter.h"
67 #include "chrome/browser/speech/chrome_speech_recognition_manager_delegate.h"
68 #include "chrome/browser/speech/tts_controller.h"
69 #include "chrome/browser/speech/tts_message_filter.h"
70 #include "chrome/browser/ssl/ssl_add_certificate.h"
71 #include "chrome/browser/ssl/ssl_blocking_page.h"
72 #include "chrome/browser/ssl/ssl_client_certificate_selector.h"
73 #include "chrome/browser/ssl/ssl_error_handler.h"
74 #include "chrome/browser/sync_file_system/local/sync_file_system_backend.h"
75 #include "chrome/browser/tab_contents/tab_util.h"
76 #include "chrome/browser/ui/blocked_content/blocked_window_params.h"
77 #include "chrome/browser/ui/blocked_content/popup_blocker_tab_helper.h"
78 #include "chrome/browser/ui/chrome_select_file_policy.h"
79 #include "chrome/browser/ui/sync/sync_promo_ui.h"
80 #include "chrome/browser/ui/tab_contents/chrome_web_contents_view_delegate.h"
81 #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
82 #include "chrome/common/chrome_constants.h"
83 #include "chrome/common/chrome_paths.h"
84 #include "chrome/common/chrome_switches.h"
85 #include "chrome/common/env_vars.h"
86 #include "chrome/common/logging_chrome.h"
87 #include "chrome/common/pepper_permission_util.h"
88 #include "chrome/common/pref_names.h"
89 #include "chrome/common/render_messages.h"
90 #include "chrome/common/url_constants.h"
91 #include "chrome/grit/generated_resources.h"
92 #include "chrome/installer/util/google_update_settings.h"
93 #include "chromeos/chromeos_constants.h"
94 #include "components/cdm/browser/cdm_message_filter_android.h"
95 #include "components/cloud_devices/common/cloud_devices_switches.h"
96 #include "components/content_settings/core/browser/content_settings_provider.h"
97 #include "components/content_settings/core/browser/content_settings_utils.h"
98 #include "components/content_settings/core/browser/host_content_settings_map.h"
99 #include "components/content_settings/core/common/content_settings.h"
100 #include "components/content_settings/core/common/permission_request_id.h"
101 #include "components/dom_distiller/core/url_constants.h"
102 #include "components/google/core/browser/google_util.h"
103 #include "components/metrics/client_info.h"
104 #include "components/pref_registry/pref_registry_syncable.h"
105 #include "components/signin/core/common/profile_management_switches.h"
106 #include "components/translate/core/common/translate_switches.h"
107 #include "content/public/browser/browser_child_process_host.h"
108 #include "content/public/browser/browser_main_parts.h"
109 #include "content/public/browser/browser_ppapi_host.h"
110 #include "content/public/browser/browser_thread.h"
111 #include "content/public/browser/browser_url_handler.h"
112 #include "content/public/browser/child_process_data.h"
113 #include "content/public/browser/child_process_security_policy.h"
114 #include "content/public/browser/permission_type.h"
115 #include "content/public/browser/render_frame_host.h"
116 #include "content/public/browser/render_process_host.h"
117 #include "content/public/browser/render_view_host.h"
118 #include "content/public/browser/resource_context.h"
119 #include "content/public/browser/site_instance.h"
120 #include "content/public/browser/web_contents.h"
121 #include "content/public/common/child_process_host.h"
122 #include "content/public/common/content_descriptors.h"
123 #include "content/public/common/url_utils.h"
124 #include "content/public/common/web_preferences.h"
125 #include "gin/public/isolate_holder.h"
126 #include "net/base/mime_util.h"
127 #include "net/cookies/canonical_cookie.h"
128 #include "net/cookies/cookie_options.h"
129 #include "net/ssl/ssl_cert_request_info.h"
130 #include "ppapi/host/ppapi_host.h"
131 #include "storage/browser/fileapi/external_mount_points.h"
132 #include "ui/base/l10n/l10n_util.h"
133 #include "ui/base/resource/resource_bundle.h"
134 #include "ui/resources/grit/ui_resources.h"
136 #if defined(OS_WIN)
137 #include "base/win/windows_version.h"
138 #include "chrome/browser/chrome_browser_main_win.h"
139 #include "sandbox/win/src/sandbox_policy.h"
140 #elif defined(OS_MACOSX)
141 #include "chrome/browser/chrome_browser_main_mac.h"
142 #include "chrome/browser/spellchecker/spellcheck_message_filter_mac.h"
143 #include "components/crash/app/breakpad_mac.h"
144 #elif defined(OS_CHROMEOS)
145 #include "chrome/browser/chromeos/chrome_browser_main_chromeos.h"
146 #include "chrome/browser/chromeos/drive/fileapi/file_system_backend_delegate.h"
147 #include "chrome/browser/chromeos/file_manager/app_id.h"
148 #include "chrome/browser/chromeos/file_system_provider/fileapi/backend_delegate.h"
149 #include "chrome/browser/chromeos/fileapi/file_system_backend.h"
150 #include "chrome/browser/chromeos/fileapi/mtp_file_system_backend_delegate.h"
151 #include "chrome/browser/chromeos/login/startup_utils.h"
152 #include "chrome/browser/chromeos/system/input_device_settings.h"
153 #include "chromeos/chromeos_switches.h"
154 #include "components/user_manager/user_manager.h"
155 #elif defined(OS_LINUX)
156 #include "chrome/browser/chrome_browser_main_linux.h"
157 #elif defined(OS_ANDROID)
158 #include "chrome/browser/android/new_tab_page_url_handler.h"
159 #include "chrome/browser/android/webapps/single_tab_mode_tab_helper.h"
160 #include "chrome/browser/chrome_browser_main_android.h"
161 #include "chrome/common/descriptors_android.h"
162 #include "components/crash/browser/crash_dump_manager_android.h"
163 #elif defined(OS_POSIX)
164 #include "chrome/browser/chrome_browser_main_posix.h"
165 #endif
167 #if defined(OS_ANDROID) || defined(OS_CHROMEOS)
168 #include "chrome/browser/media/protected_media_identifier_permission_context.h"
169 #include "chrome/browser/media/protected_media_identifier_permission_context_factory.h"
170 #endif
172 #if defined(OS_POSIX) && !defined(OS_MACOSX)
173 #include "base/debug/leak_annotations.h"
174 #include "components/crash/app/breakpad_linux.h"
175 #include "components/crash/browser/crash_handler_host_linux.h"
176 #endif
178 #if defined(OS_ANDROID)
179 #include "ui/base/ui_base_paths.h"
180 #include "ui/gfx/android/device_display_info.h"
181 #endif
183 #if defined(OS_ANDROID)
184 #include "chrome/browser/android/dev_tools_manager_delegate_android.h"
185 #else
186 #include "chrome/browser/devtools/chrome_devtools_manager_delegate.h"
187 #endif
189 #if !defined(OS_CHROMEOS)
190 #include "chrome/browser/signin/chrome_signin_client.h"
191 #include "chrome/browser/signin/chrome_signin_client_factory.h"
192 #include "chrome/browser/signin/signin_manager_factory.h"
193 #include "components/signin/core/browser/signin_manager.h"
194 #endif
196 #if defined(TOOLKIT_VIEWS)
197 #include "chrome/browser/ui/views/chrome_browser_main_extra_parts_views.h"
198 #endif
200 #if defined(USE_ASH)
201 #include "chrome/browser/ui/views/ash/chrome_browser_main_extra_parts_ash.h"
202 #endif
204 #if defined(USE_AURA)
205 #include "chrome/browser/ui/aura/chrome_browser_main_extra_parts_aura.h"
206 #endif
208 #if defined(USE_X11)
209 #include "chrome/browser/chrome_browser_main_extra_parts_x11.h"
210 #endif
212 #if defined(ENABLE_CAPTIVE_PORTAL_DETECTION)
213 #include "chrome/browser/captive_portal/captive_portal_tab_helper.h"
214 #endif
216 #if !defined(DISABLE_NACL)
217 #include "components/nacl/browser/nacl_browser.h"
218 #include "components/nacl/browser/nacl_host_message_filter.h"
219 #include "components/nacl/browser/nacl_process_host.h"
220 #include "components/nacl/common/nacl_process_type.h"
221 #include "components/nacl/common/nacl_switches.h"
222 #endif
224 #if defined(ENABLE_EXTENSIONS)
225 #include "chrome/browser/extensions/chrome_content_browser_client_extensions_part.h"
226 #include "chrome/browser/extensions/extension_util.h"
227 #include "chrome/browser/media/cast_transport_host_filter.h"
228 #include "chrome/browser/speech/extension_api/tts_engine_extension_api.h"
229 #include "extensions/browser/extension_registry.h"
230 #include "extensions/browser/guest_view/guest_view_base.h"
231 #include "extensions/browser/guest_view/guest_view_manager.h"
232 #include "extensions/browser/guest_view/web_view/web_view_guest.h"
233 #include "extensions/browser/guest_view/web_view/web_view_permission_helper.h"
234 #include "extensions/browser/guest_view/web_view/web_view_renderer_state.h"
235 #include "extensions/common/constants.h"
236 #include "extensions/common/extension.h"
237 #include "extensions/common/extension_set.h"
238 #include "extensions/common/manifest_handlers/background_info.h"
239 #include "extensions/common/manifest_handlers/shared_module_info.h"
240 #include "extensions/common/permissions/permissions_data.h"
241 #include "extensions/common/permissions/socket_permission.h"
242 #include "extensions/common/switches.h"
243 #endif
245 #if defined(ENABLE_PLUGINS)
246 #include "chrome/browser/plugins/chrome_content_browser_client_plugins_part.h"
247 #endif
249 #if defined(ENABLE_SPELLCHECK)
250 #include "chrome/browser/spellchecker/spellcheck_message_filter.h"
251 #endif
253 #if defined(ENABLE_WEBRTC)
254 #include "chrome/browser/media/webrtc_logging_handler_host.h"
255 #endif
257 using base::FileDescriptor;
258 using blink::WebWindowFeatures;
259 using content::AccessTokenStore;
260 using content::BrowserThread;
261 using content::BrowserURLHandler;
262 using content::ChildProcessSecurityPolicy;
263 using content::QuotaPermissionContext;
264 using content::RenderFrameHost;
265 using content::RenderViewHost;
266 using content::ResourceType;
267 using content::SiteInstance;
268 using content::WebContents;
269 using content::WebPreferences;
270 using message_center::NotifierId;
272 #if defined(OS_POSIX)
273 using content::FileDescriptorInfo;
274 #endif
276 #if defined(ENABLE_EXTENSIONS)
277 using extensions::APIPermission;
278 using extensions::ChromeContentBrowserClientExtensionsPart;
279 using extensions::Extension;
280 using extensions::InfoMap;
281 using extensions::Manifest;
282 #endif
284 #if defined(ENABLE_PLUGINS)
285 using plugins::ChromeContentBrowserClientPluginsPart;
286 #endif
288 namespace {
290 // Cached version of the locale so we can return the locale on the I/O
291 // thread.
292 base::LazyInstance<std::string> g_io_thread_application_locale;
294 #if defined(ENABLE_PLUGINS)
295 // TODO(teravest): Add renderer-side API-specific checking for these APIs so
296 // that blanket permission isn't granted to all dev channel APIs for these.
297 // http://crbug.com/386743
298 const char* const kPredefinedAllowedDevChannelOrigins[] = {
299 "6EAED1924DB611B6EEF2A664BD077BE7EAD33B8F", // see crbug.com/383937
300 "4EB74897CB187C7633357C2FE832E0AD6A44883A" // see crbug.com/383937
303 const char* const kPredefinedAllowedFileHandleOrigins[] = {
304 "6EAED1924DB611B6EEF2A664BD077BE7EAD33B8F", // see crbug.com/234789
305 "4EB74897CB187C7633357C2FE832E0AD6A44883A" // see crbug.com/234789
308 const char* const kPredefinedAllowedSocketOrigins[] = {
309 "okddffdblfhhnmhodogpojmfkjmhinfp", // Test SSH Client
310 "pnhechapfaindjhompbnflcldabbghjo", // HTerm App (SSH Client)
311 "bglhmjfplikpjnfoegeomebmfnkjomhe", // see crbug.com/122126
312 "gbchcmhmhahfdphkhkmpfmihenigjmpp", // Chrome Remote Desktop
313 "kgngmbheleoaphbjbaiobfdepmghbfah", // Pre-release Chrome Remote Desktop
314 "odkaodonbgfohohmklejpjiejmcipmib", // Dogfood Chrome Remote Desktop
315 "ojoimpklfciegopdfgeenehpalipignm", // Chromoting canary
316 "cbkkbcmdlboombapidmoeolnmdacpkch", // see crbug.com/129089
317 "hhnbmknkdabfoieppbbljkhkfjcmcbjh", // see crbug.com/134099
318 "mablfbjkhmhkmefkjjacnbaikjkipphg", // see crbug.com/134099
319 "pdeelgamlgannhelgoegilelnnojegoh", // see crbug.com/134099
320 "cabapfdbkniadpollkckdnedaanlciaj", // see crbug.com/134099
321 "mapljbgnjledlpdmlchihnmeclmefbba", // see crbug.com/134099
322 "ghbfeebgmiidnnmeobbbaiamklmpbpii", // see crbug.com/134099
323 "jdfhpkjeckflbbleddjlpimecpbjdeep", // see crbug.com/142514
324 "iabmpiboiopbgfabjmgeedhcmjenhbla", // see crbug.com/165080
325 "B7CF8A292249681AF81771650BA4CEEAF19A4560", // see crbug.com/165080
326 "7525AF4F66763A70A883C4700529F647B470E4D2", // see crbug.com/238084
327 "0B549507088E1564D672F7942EB87CA4DAD73972", // see crbug.com/238084
328 "864288364E239573E777D3E0E36864E590E95C74" // see crbug.com/238084
330 #endif
332 // Returns a copy of the given url with its host set to given host and path set
333 // to given path. Other parts of the url will be the same.
334 GURL ReplaceURLHostAndPath(const GURL& url,
335 const std::string& host,
336 const std::string& path) {
337 url::Replacements<char> replacements;
338 replacements.SetHost(host.c_str(), url::Component(0, host.length()));
339 replacements.SetPath(path.c_str(), url::Component(0, path.length()));
340 return url.ReplaceComponents(replacements);
343 // Maps "foo://bar/baz/" to "foo://chrome/bar/baz/".
344 GURL AddUberHost(const GURL& url) {
345 const std::string uber_host = chrome::kChromeUIUberHost;
346 const std::string new_path = url.host() + url.path();
348 return ReplaceURLHostAndPath(url, uber_host, new_path);
351 // If url->host() is "chrome" and url->path() has characters other than the
352 // first slash, changes the url from "foo://chrome/bar/" to "foo://bar/" and
353 // returns true. Otherwise returns false.
354 bool RemoveUberHost(GURL* url) {
355 if (url->host() != chrome::kChromeUIUberHost)
356 return false;
358 if (url->path().empty() || url->path() == "/")
359 return false;
361 const std::string old_path = url->path();
363 const std::string::size_type separator = old_path.find('/', 1);
364 std::string new_host;
365 std::string new_path;
366 if (separator == std::string::npos) {
367 new_host = old_path.substr(1);
368 } else {
369 new_host = old_path.substr(1, separator - 1);
370 new_path = old_path.substr(separator);
373 // Do not allow URLs with paths empty before the first slash since we can't
374 // have an empty host. (e.g "foo://chrome//")
375 if (new_host.empty())
376 return false;
378 *url = ReplaceURLHostAndPath(*url, new_host, new_path);
380 DCHECK(url->is_valid());
382 return true;
385 // Handles rewriting Web UI URLs.
386 bool HandleWebUI(GURL* url, content::BrowserContext* browser_context) {
387 // Do not handle special URLs such as "about:foo"
388 if (!url->host().empty()) {
389 const GURL chrome_url = AddUberHost(*url);
391 // Handle valid "chrome://chrome/foo" URLs so the reverse handler will
392 // be called.
393 if (ChromeWebUIControllerFactory::GetInstance()->UseWebUIForURL(
394 browser_context, chrome_url))
395 return true;
398 if (!ChromeWebUIControllerFactory::GetInstance()->UseWebUIForURL(
399 browser_context, *url))
400 return false;
402 #if defined(OS_CHROMEOS)
403 // Special case : in ChromeOS in Guest mode bookmarks and history are
404 // disabled for security reasons. New tab page explains the reasons, so
405 // we redirect user to new tab page.
406 if (user_manager::UserManager::Get()->IsLoggedInAsGuest()) {
407 if (url->SchemeIs(content::kChromeUIScheme) &&
408 (url->DomainIs(chrome::kChromeUIBookmarksHost) ||
409 url->DomainIs(chrome::kChromeUIHistoryHost))) {
410 // Rewrite with new tab URL
411 *url = GURL(chrome::kChromeUINewTabURL);
414 #endif
416 return true;
419 // Reverse URL handler for Web UI. Maps "chrome://chrome/foo/" to
420 // "chrome://foo/".
421 bool HandleWebUIReverse(GURL* url, content::BrowserContext* browser_context) {
422 if (!url->is_valid() || !url->SchemeIs(content::kChromeUIScheme))
423 return false;
425 return RemoveUberHost(url);
428 bool CertMatchesFilter(const net::X509Certificate& cert,
429 const base::DictionaryValue& filter) {
430 // TODO(markusheintz): This is the minimal required filter implementation.
431 // Implement a better matcher.
433 // An empty filter matches any client certificate since no requirements are
434 // specified at all.
435 if (filter.empty())
436 return true;
438 std::string common_name;
439 if (filter.GetString("ISSUER.CN", &common_name) &&
440 (cert.issuer().common_name == common_name)) {
441 return true;
443 return false;
446 #if defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_MACOSX)
447 breakpad::CrashHandlerHostLinux* CreateCrashHandlerHost(
448 const std::string& process_type) {
449 base::FilePath dumps_path;
450 PathService::Get(chrome::DIR_CRASH_DUMPS, &dumps_path);
452 ANNOTATE_SCOPED_MEMORY_LEAK;
453 bool upload = (getenv(env_vars::kHeadless) == NULL);
454 breakpad::CrashHandlerHostLinux* crash_handler =
455 new breakpad::CrashHandlerHostLinux(process_type, dumps_path, upload);
456 crash_handler->StartUploaderThread();
457 return crash_handler;
461 int GetCrashSignalFD(const base::CommandLine& command_line) {
462 // Extensions have the same process type as renderers.
463 if (command_line.HasSwitch(extensions::switches::kExtensionProcess)) {
464 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
465 if (!crash_handler)
466 crash_handler = CreateCrashHandlerHost("extension");
467 return crash_handler->GetDeathSignalSocket();
470 std::string process_type =
471 command_line.GetSwitchValueASCII(switches::kProcessType);
473 if (process_type == switches::kRendererProcess) {
474 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
475 if (!crash_handler)
476 crash_handler = CreateCrashHandlerHost(process_type);
477 return crash_handler->GetDeathSignalSocket();
480 if (process_type == switches::kPluginProcess) {
481 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
482 if (!crash_handler)
483 crash_handler = CreateCrashHandlerHost(process_type);
484 return crash_handler->GetDeathSignalSocket();
487 if (process_type == switches::kPpapiPluginProcess) {
488 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
489 if (!crash_handler)
490 crash_handler = CreateCrashHandlerHost(process_type);
491 return crash_handler->GetDeathSignalSocket();
494 if (process_type == switches::kGpuProcess) {
495 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
496 if (!crash_handler)
497 crash_handler = CreateCrashHandlerHost(process_type);
498 return crash_handler->GetDeathSignalSocket();
501 return -1;
503 #endif // defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_MACOSX)
505 #if !defined(OS_CHROMEOS)
506 GURL GetEffectiveURLForSignin(const GURL& url) {
507 CHECK(SigninManager::IsWebBasedSigninFlowURL(url));
509 GURL effective_url(SigninManager::kChromeSigninEffectiveSite);
510 // Copy the path because the argument to SetPathStr must outlive
511 // the Replacements object.
512 const std::string path_copy(url.path());
513 GURL::Replacements replacements;
514 replacements.SetPathStr(path_copy);
515 effective_url = effective_url.ReplaceComponents(replacements);
516 return effective_url;
518 #endif
520 void SetApplicationLocaleOnIOThread(const std::string& locale) {
521 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
522 g_io_thread_application_locale.Get() = locale;
525 void HandleBlockedPopupOnUIThread(const BlockedWindowParams& params) {
526 // TODO(jochen): This code path should use RenderFrameHosts. See
527 // http://crbug.com/431769 for details.
528 RenderViewHost* render_view_host =
529 RenderViewHost::FromID(params.render_process_id(), params.opener_id());
530 if (!render_view_host)
531 return;
532 WebContents* tab = WebContents::FromRenderViewHost(render_view_host);
533 // The tab might already have navigated away.
534 if (!tab || tab->GetRenderViewHost() != render_view_host)
535 return;
537 prerender::PrerenderContents* prerender_contents =
538 prerender::PrerenderContents::FromWebContents(tab);
539 if (prerender_contents) {
540 prerender_contents->Destroy(prerender::FINAL_STATUS_CREATE_NEW_WINDOW);
541 return;
544 PopupBlockerTabHelper* popup_helper =
545 PopupBlockerTabHelper::FromWebContents(tab);
546 if (!popup_helper)
547 return;
548 popup_helper->AddBlockedPopup(params);
551 #if defined(OS_ANDROID)
553 void HandleSingleTabModeBlockOnUIThread(const BlockedWindowParams& params) {
554 WebContents* web_contents =
555 tab_util::GetWebContentsByID(params.render_process_id(),
556 params.opener_id());
557 if (!web_contents)
558 return;
560 SingleTabModeTabHelper::FromWebContents(web_contents)->HandleOpenUrl(params);
563 float GetDeviceScaleAdjustment() {
564 static const float kMinFSM = 1.05f;
565 static const int kWidthForMinFSM = 320;
566 static const float kMaxFSM = 1.3f;
567 static const int kWidthForMaxFSM = 800;
569 gfx::DeviceDisplayInfo info;
570 int minWidth = info.GetSmallestDIPWidth();
572 if (minWidth <= kWidthForMinFSM)
573 return kMinFSM;
574 if (minWidth >= kWidthForMaxFSM)
575 return kMaxFSM;
577 // The font scale multiplier varies linearly between kMinFSM and kMaxFSM.
578 float ratio = static_cast<float>(minWidth - kWidthForMinFSM) /
579 (kWidthForMaxFSM - kWidthForMinFSM);
580 return ratio * (kMaxFSM - kMinFSM) + kMinFSM;
583 #endif // defined(OS_ANDROID)
585 #if defined(ENABLE_EXTENSIONS)
586 // By default, JavaScript and images are enabled in guest content.
587 void GetGuestViewDefaultContentSettingRules(
588 bool incognito,
589 RendererContentSettingRules* rules) {
590 rules->image_rules.push_back(
591 ContentSettingPatternSource(ContentSettingsPattern::Wildcard(),
592 ContentSettingsPattern::Wildcard(),
593 CONTENT_SETTING_ALLOW,
594 std::string(),
595 incognito));
597 rules->script_rules.push_back(
598 ContentSettingPatternSource(ContentSettingsPattern::Wildcard(),
599 ContentSettingsPattern::Wildcard(),
600 CONTENT_SETTING_ALLOW,
601 std::string(),
602 incognito));
604 #endif // defined(ENALBE_EXTENSIONS)
606 content::PermissionStatus
607 ContentSettingToPermissionStatus(ContentSetting setting) {
608 switch (setting) {
609 case CONTENT_SETTING_ALLOW:
610 case CONTENT_SETTING_SESSION_ONLY:
611 return content::PERMISSION_STATUS_GRANTED;
612 case CONTENT_SETTING_BLOCK:
613 return content::PERMISSION_STATUS_DENIED;
614 case CONTENT_SETTING_ASK:
615 return content::PERMISSION_STATUS_ASK;
616 case CONTENT_SETTING_DETECT_IMPORTANT_CONTENT:
617 case CONTENT_SETTING_DEFAULT:
618 case CONTENT_SETTING_NUM_SETTINGS:
619 break;
621 NOTREACHED();
622 return content::PERMISSION_STATUS_DENIED;
625 PermissionContextBase* GetPermissionContext(Profile* profile,
626 content::PermissionType permission) {
627 switch (permission) {
628 case content::PERMISSION_MIDI_SYSEX:
629 return MidiPermissionContextFactory::GetForProfile(profile);
630 case content::PERMISSION_NOTIFICATIONS:
631 #if defined(ENABLE_NOTIFICATIONS)
632 return DesktopNotificationServiceFactory::GetForProfile(profile);
633 #else
634 NOTIMPLEMENTED();
635 break;
636 #endif
637 case content::PERMISSION_GEOLOCATION:
638 return GeolocationPermissionContextFactory::GetForProfile(profile);
639 case content::PERMISSION_PROTECTED_MEDIA_IDENTIFIER:
640 #if defined(OS_ANDROID) || defined(OS_CHROMEOS)
641 return ProtectedMediaIdentifierPermissionContextFactory::GetForProfile(
642 profile);
643 #else
644 NOTIMPLEMENTED();
645 break;
646 #endif
647 case content::PERMISSION_PUSH_MESSAGING:
648 return gcm::PushMessagingPermissionContextFactory::GetForProfile(profile);
649 case content::PERMISSION_NUM:
650 NOTREACHED() << "Invalid RequestPermission for " << permission;
651 break;
653 return nullptr;
656 // Helper method to translate from Permissions to ContentSettings
657 ContentSettingsType PermissionToContentSetting(
658 content::PermissionType permission) {
659 switch (permission) {
660 case content::PERMISSION_MIDI_SYSEX:
661 return CONTENT_SETTINGS_TYPE_MIDI_SYSEX;
662 case content::PERMISSION_PUSH_MESSAGING:
663 return CONTENT_SETTINGS_TYPE_PUSH_MESSAGING;
664 case content::PERMISSION_NOTIFICATIONS:
665 return CONTENT_SETTINGS_TYPE_NOTIFICATIONS;
666 case content::PERMISSION_GEOLOCATION:
667 return CONTENT_SETTINGS_TYPE_GEOLOCATION;
668 #if defined(OS_ANDROID) || defined(OS_CHROMEOS)
669 case content::PERMISSION_PROTECTED_MEDIA_IDENTIFIER:
670 return CONTENT_SETTINGS_TYPE_PROTECTED_MEDIA_IDENTIFIER;
671 #endif
672 default:
673 NOTREACHED() << "Unknown content setting for permission " << permission;
674 return CONTENT_SETTINGS_TYPE_DEFAULT;
678 } // namespace
680 namespace chrome {
682 ChromeContentBrowserClient::ChromeContentBrowserClient()
683 : prerender_tracker_(NULL),
684 weak_factory_(this) {
685 #if defined(ENABLE_PLUGINS)
686 for (size_t i = 0; i < arraysize(kPredefinedAllowedDevChannelOrigins); ++i)
687 allowed_dev_channel_origins_.insert(kPredefinedAllowedDevChannelOrigins[i]);
688 for (size_t i = 0; i < arraysize(kPredefinedAllowedFileHandleOrigins); ++i)
689 allowed_file_handle_origins_.insert(kPredefinedAllowedFileHandleOrigins[i]);
690 for (size_t i = 0; i < arraysize(kPredefinedAllowedSocketOrigins); ++i)
691 allowed_socket_origins_.insert(kPredefinedAllowedSocketOrigins[i]);
693 extra_parts_.push_back(new ChromeContentBrowserClientPluginsPart);
694 #endif
696 #if !defined(OS_ANDROID)
697 TtsExtensionEngine* tts_extension_engine = TtsExtensionEngine::GetInstance();
698 TtsController::GetInstance()->SetTtsEngineDelegate(tts_extension_engine);
699 #endif
701 #if defined(ENABLE_EXTENSIONS)
702 extra_parts_.push_back(new ChromeContentBrowserClientExtensionsPart);
703 #endif
706 ChromeContentBrowserClient::~ChromeContentBrowserClient() {
707 for (int i = static_cast<int>(extra_parts_.size()) - 1; i >= 0; --i)
708 delete extra_parts_[i];
709 extra_parts_.clear();
712 // static
713 void ChromeContentBrowserClient::RegisterProfilePrefs(
714 user_prefs::PrefRegistrySyncable* registry) {
715 registry->RegisterBooleanPref(
716 prefs::kDisable3DAPIs,
717 false,
718 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
719 registry->RegisterBooleanPref(
720 prefs::kEnableHyperlinkAuditing,
721 true,
722 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
723 registry->RegisterListPref(
724 prefs::kEnableDeprecatedWebPlatformFeatures,
725 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
728 // static
729 void ChromeContentBrowserClient::SetApplicationLocale(
730 const std::string& locale) {
731 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
733 // This object is guaranteed to outlive all threads so we don't have to
734 // worry about the lack of refcounting and can just post as Unretained.
736 // The common case is that this function is called early in Chrome startup
737 // before any threads are created (it will also be called later if the user
738 // changes the pref). In this case, there will be no threads created and
739 // posting will fail. When there are no threads, we can just set the string
740 // without worrying about threadsafety.
741 if (!BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
742 base::Bind(&SetApplicationLocaleOnIOThread, locale))) {
743 g_io_thread_application_locale.Get() = locale;
747 content::BrowserMainParts* ChromeContentBrowserClient::CreateBrowserMainParts(
748 const content::MainFunctionParams& parameters) {
749 ChromeBrowserMainParts* main_parts;
750 // Construct the Main browser parts based on the OS type.
751 #if defined(OS_WIN)
752 main_parts = new ChromeBrowserMainPartsWin(parameters);
753 #elif defined(OS_MACOSX)
754 main_parts = new ChromeBrowserMainPartsMac(parameters);
755 #elif defined(OS_CHROMEOS)
756 main_parts = new chromeos::ChromeBrowserMainPartsChromeos(parameters);
757 #elif defined(OS_LINUX)
758 main_parts = new ChromeBrowserMainPartsLinux(parameters);
759 #elif defined(OS_ANDROID)
760 main_parts = new ChromeBrowserMainPartsAndroid(parameters);
761 #elif defined(OS_POSIX)
762 main_parts = new ChromeBrowserMainPartsPosix(parameters);
763 #else
764 NOTREACHED();
765 main_parts = new ChromeBrowserMainParts(parameters);
766 #endif
768 chrome::AddProfilesExtraParts(main_parts);
770 // Construct additional browser parts. Stages are called in the order in
771 // which they are added.
772 #if defined(TOOLKIT_VIEWS)
773 main_parts->AddParts(new ChromeBrowserMainExtraPartsViews());
774 #endif
776 // TODO(oshima): Athena on chrome currently requires USE_ASH to build.
777 // We should reduce the dependency as much as possible.
778 #if defined(USE_ASH)
779 main_parts->AddParts(new ChromeBrowserMainExtraPartsAsh());
780 #endif
782 #if defined(USE_AURA)
783 main_parts->AddParts(new ChromeBrowserMainExtraPartsAura());
784 #endif
786 #if defined(USE_X11)
787 main_parts->AddParts(new ChromeBrowserMainExtraPartsX11());
788 #endif
790 chrome::AddMetricsExtraParts(main_parts);
792 return main_parts;
795 std::string ChromeContentBrowserClient::GetStoragePartitionIdForSite(
796 content::BrowserContext* browser_context,
797 const GURL& site) {
798 std::string partition_id;
800 // The partition ID for webview guest processes is the string value of its
801 // SiteInstance URL - "chrome-guest://app_id/persist?partition".
802 if (site.SchemeIs(content::kGuestScheme)) {
803 partition_id = site.spec();
804 } else if (site.GetOrigin().spec() == kChromeUIChromeSigninURL &&
805 !switches::IsEnableWebviewBasedSignin()) {
806 // Chrome signin page has an embedded iframe of extension and web content,
807 // thus it must be isolated from other webUI pages.
808 partition_id = site.GetOrigin().spec();
811 DCHECK(IsValidStoragePartitionId(browser_context, partition_id));
812 return partition_id;
815 bool ChromeContentBrowserClient::IsValidStoragePartitionId(
816 content::BrowserContext* browser_context,
817 const std::string& partition_id) {
818 // The default ID is empty and is always valid.
819 if (partition_id.empty())
820 return true;
822 return GURL(partition_id).is_valid();
825 void ChromeContentBrowserClient::GetStoragePartitionConfigForSite(
826 content::BrowserContext* browser_context,
827 const GURL& site,
828 bool can_be_default,
829 std::string* partition_domain,
830 std::string* partition_name,
831 bool* in_memory) {
832 // Default to the browser-wide storage partition and override based on |site|
833 // below.
834 partition_domain->clear();
835 partition_name->clear();
836 *in_memory = false;
838 bool success = false;
839 #if defined(ENABLE_EXTENSIONS)
840 success = extensions::WebViewGuest::GetGuestPartitionConfigForSite(
841 site, partition_domain, partition_name, in_memory);
843 if (!success && site.SchemeIs(extensions::kExtensionScheme)) {
844 // If |can_be_default| is false, the caller is stating that the |site|
845 // should be parsed as if it had isolated storage. In particular it is
846 // important to NOT check ExtensionService for the is_storage_isolated()
847 // attribute because this code path is run during Extension uninstall
848 // to do cleanup after the Extension has already been unloaded from the
849 // ExtensionService.
850 bool is_isolated = !can_be_default;
851 if (can_be_default) {
852 if (extensions::util::SiteHasIsolatedStorage(site, browser_context))
853 is_isolated = true;
856 if (is_isolated) {
857 CHECK(site.has_host());
858 // For extensions with isolated storage, the the host of the |site| is
859 // the |partition_domain|. The |in_memory| and |partition_name| are only
860 // used in guest schemes so they are cleared here.
861 *partition_domain = site.host();
862 *in_memory = false;
863 partition_name->clear();
865 success = true;
867 #endif
869 if (!success && (site.GetOrigin().spec() == kChromeUIChromeSigninURL) &&
870 !switches::IsEnableWebviewBasedSignin()) {
871 // Chrome signin page has an embedded iframe of extension and web content,
872 // thus it must be isolated from other webUI pages.
873 *partition_domain = chrome::kChromeUIChromeSigninHost;
876 // Assert that if |can_be_default| is false, the code above must have found a
877 // non-default partition. If this fails, the caller has a serious logic
878 // error about which StoragePartition they expect to be in and it is not
879 // safe to continue.
880 CHECK(can_be_default || !partition_domain->empty());
883 content::WebContentsViewDelegate*
884 ChromeContentBrowserClient::GetWebContentsViewDelegate(
885 content::WebContents* web_contents) {
886 return chrome::CreateWebContentsViewDelegate(web_contents);
889 void ChromeContentBrowserClient::RenderProcessWillLaunch(
890 content::RenderProcessHost* host) {
891 int id = host->GetID();
892 Profile* profile = Profile::FromBrowserContext(host->GetBrowserContext());
893 net::URLRequestContextGetter* context =
894 profile->GetRequestContextForRenderProcess(id);
896 host->AddFilter(new ChromeRenderMessageFilter(id, profile));
897 #if defined(ENABLE_EXTENSIONS)
898 host->AddFilter(new cast::CastTransportHostFilter);
899 #endif
900 #if defined(ENABLE_PRINTING)
901 host->AddFilter(new printing::PrintingMessageFilter(id, profile));
902 #endif
903 host->AddFilter(new SearchProviderInstallStateMessageFilter(id, profile));
904 #if defined(ENABLE_SPELLCHECK)
905 host->AddFilter(new SpellCheckMessageFilter(id));
906 #endif
907 #if defined(OS_MACOSX)
908 host->AddFilter(new SpellCheckMessageFilterMac(id));
909 #endif
910 host->AddFilter(new ChromeNetBenchmarkingMessageFilter(profile, context));
911 host->AddFilter(new prerender::PrerenderMessageFilter(id, profile));
912 host->AddFilter(new TtsMessageFilter(id, host->GetBrowserContext()));
913 #if defined(ENABLE_WEBRTC)
914 WebRtcLoggingHandlerHost* webrtc_logging_handler_host =
915 new WebRtcLoggingHandlerHost(profile);
916 host->SetWebRtcLogMessageCallback(base::Bind(
917 &WebRtcLoggingHandlerHost::LogMessage, webrtc_logging_handler_host));
918 host->AddFilter(webrtc_logging_handler_host);
919 host->SetUserData(host, new base::UserDataAdapter<WebRtcLoggingHandlerHost>(
920 webrtc_logging_handler_host));
921 #endif
922 #if !defined(DISABLE_NACL)
923 host->AddFilter(new nacl::NaClHostMessageFilter(
924 id, profile->IsOffTheRecord(),
925 profile->GetPath(),
926 context));
927 #endif
928 #if defined(OS_ANDROID)
929 host->AddFilter(new cdm::CdmMessageFilterAndroid());
930 #endif
931 if (switches::IsEnableAccountConsistency())
932 host->AddFilter(new PrincipalsMessageFilter(id));
934 host->Send(new ChromeViewMsg_SetIsIncognitoProcess(
935 profile->IsOffTheRecord()));
937 for (size_t i = 0; i < extra_parts_.size(); ++i)
938 extra_parts_[i]->RenderProcessWillLaunch(host);
940 RendererContentSettingRules rules;
941 if (host->IsIsolatedGuest()) {
942 #if defined(ENABLE_EXTENSIONS)
943 GetGuestViewDefaultContentSettingRules(profile->IsOffTheRecord(), &rules);
944 #else
945 NOTREACHED();
946 #endif
947 } else {
948 GetRendererContentSettingRules(
949 profile->GetHostContentSettingsMap(), &rules);
951 host->Send(new ChromeViewMsg_SetContentSettingRules(rules));
954 GURL ChromeContentBrowserClient::GetEffectiveURL(
955 content::BrowserContext* browser_context, const GURL& url) {
956 Profile* profile = Profile::FromBrowserContext(browser_context);
957 if (!profile)
958 return url;
960 // If the input |url| should be assigned to the Instant renderer, make its
961 // effective URL distinct from other URLs on the search provider's domain.
962 if (chrome::ShouldAssignURLToInstantRenderer(url, profile))
963 return chrome::GetEffectiveURLForInstant(url, profile);
965 #if !defined(OS_CHROMEOS)
966 // If the input |url| should be assigned to the Signin renderer, make its
967 // effective URL distinct from other URLs on the signin service's domain.
968 // Note that the signin renderer will be allowed to sign the user in to
969 // Chrome.
970 if (SigninManager::IsWebBasedSigninFlowURL(url))
971 return GetEffectiveURLForSignin(url);
972 #endif
974 #if defined(ENABLE_EXTENSIONS)
975 return ChromeContentBrowserClientExtensionsPart::GetEffectiveURL(
976 profile, url);
977 #else
978 return url;
979 #endif
982 bool ChromeContentBrowserClient::ShouldUseProcessPerSite(
983 content::BrowserContext* browser_context, const GURL& effective_url) {
984 // Non-extension, non-Instant URLs should generally use
985 // process-per-site-instance. Because we expect to use the effective URL,
986 // URLs for hosted apps (apart from bookmark apps) should have an extension
987 // scheme by now.
989 Profile* profile = Profile::FromBrowserContext(browser_context);
990 if (!profile)
991 return false;
993 if (chrome::ShouldUseProcessPerSiteForInstantURL(effective_url, profile))
994 return true;
996 #if !defined(OS_CHROMEOS)
997 if (SigninManager::IsWebBasedSigninFlowURL(effective_url))
998 return true;
999 #endif
1001 #if defined(ENABLE_EXTENSIONS)
1002 return ChromeContentBrowserClientExtensionsPart::ShouldUseProcessPerSite(
1003 profile, effective_url);
1004 #else
1005 return false;
1006 #endif
1009 // These are treated as WebUI schemes but do not get WebUI bindings. Also,
1010 // view-source is allowed for these schemes.
1011 void ChromeContentBrowserClient::GetAdditionalWebUISchemes(
1012 std::vector<std::string>* additional_schemes) {
1013 additional_schemes->push_back(chrome::kChromeSearchScheme);
1014 additional_schemes->push_back(dom_distiller::kDomDistillerScheme);
1017 void ChromeContentBrowserClient::GetAdditionalWebUIHostsToIgnoreParititionCheck(
1018 std::vector<std::string>* hosts) {
1019 hosts->push_back(chrome::kChromeUIExtensionIconHost);
1020 hosts->push_back(chrome::kChromeUIFaviconHost);
1021 hosts->push_back(chrome::kChromeUIThemeHost);
1022 hosts->push_back(chrome::kChromeUIThumbnailHost);
1023 hosts->push_back(chrome::kChromeUIThumbnailHost2);
1024 hosts->push_back(chrome::kChromeUIThumbnailListHost);
1027 net::URLRequestContextGetter*
1028 ChromeContentBrowserClient::CreateRequestContext(
1029 content::BrowserContext* browser_context,
1030 content::ProtocolHandlerMap* protocol_handlers,
1031 content::URLRequestInterceptorScopedVector request_interceptors) {
1032 Profile* profile = Profile::FromBrowserContext(browser_context);
1033 return profile->CreateRequestContext(protocol_handlers,
1034 request_interceptors.Pass());
1037 net::URLRequestContextGetter*
1038 ChromeContentBrowserClient::CreateRequestContextForStoragePartition(
1039 content::BrowserContext* browser_context,
1040 const base::FilePath& partition_path,
1041 bool in_memory,
1042 content::ProtocolHandlerMap* protocol_handlers,
1043 content::URLRequestInterceptorScopedVector request_interceptors) {
1044 Profile* profile = Profile::FromBrowserContext(browser_context);
1045 return profile->CreateRequestContextForStoragePartition(
1046 partition_path,
1047 in_memory,
1048 protocol_handlers,
1049 request_interceptors.Pass());
1052 bool ChromeContentBrowserClient::IsHandledURL(const GURL& url) {
1053 return ProfileIOData::IsHandledURL(url);
1056 bool ChromeContentBrowserClient::CanCommitURL(
1057 content::RenderProcessHost* process_host,
1058 const GURL& url) {
1059 #if defined(ENABLE_EXTENSIONS)
1060 return ChromeContentBrowserClientExtensionsPart::CanCommitURL(
1061 process_host, url);
1062 #else
1063 return true;
1064 #endif
1067 bool ChromeContentBrowserClient::ShouldAllowOpenURL(
1068 content::SiteInstance* site_instance, const GURL& url) {
1069 GURL from_url = site_instance->GetSiteURL();
1071 #if defined(ENABLE_EXTENSIONS)
1072 bool result;
1073 if (ChromeContentBrowserClientExtensionsPart::ShouldAllowOpenURL(
1074 site_instance, from_url, url, &result))
1075 return result;
1076 #endif
1078 // Do not allow chrome://chrome-signin navigate to other chrome:// URLs, since
1079 // the signin page may host untrusted web content.
1080 if (from_url.GetOrigin().spec() == chrome::kChromeUIChromeSigninURL &&
1081 url.SchemeIs(content::kChromeUIScheme) &&
1082 url.host() != chrome::kChromeUIChromeSigninHost) {
1083 VLOG(1) << "Blocked navigation to " << url.spec() << " from "
1084 << chrome::kChromeUIChromeSigninURL;
1085 return false;
1088 return true;
1091 bool ChromeContentBrowserClient::IsSuitableHost(
1092 content::RenderProcessHost* process_host,
1093 const GURL& site_url) {
1094 Profile* profile =
1095 Profile::FromBrowserContext(process_host->GetBrowserContext());
1096 // This may be NULL during tests. In that case, just assume any site can
1097 // share any host.
1098 if (!profile)
1099 return true;
1101 // Instant URLs should only be in the instant process and instant process
1102 // should only have Instant URLs.
1103 InstantService* instant_service =
1104 InstantServiceFactory::GetForProfile(profile);
1105 if (instant_service) {
1106 bool is_instant_process = instant_service->IsInstantProcess(
1107 process_host->GetID());
1108 bool should_be_in_instant_process =
1109 chrome::ShouldAssignURLToInstantRenderer(site_url, profile);
1110 if (is_instant_process || should_be_in_instant_process)
1111 return is_instant_process && should_be_in_instant_process;
1114 #if !defined(OS_CHROMEOS)
1115 SigninClient* signin_client =
1116 ChromeSigninClientFactory::GetForProfile(profile);
1117 if (signin_client && signin_client->IsSigninProcess(process_host->GetID()))
1118 return SigninManager::IsWebBasedSigninFlowURL(site_url);
1119 #endif
1121 #if defined(ENABLE_EXTENSIONS)
1122 return ChromeContentBrowserClientExtensionsPart::IsSuitableHost(
1123 profile, process_host, site_url);
1124 #else
1125 return true;
1126 #endif
1129 bool ChromeContentBrowserClient::MayReuseHost(
1130 content::RenderProcessHost* process_host) {
1131 // If there is currently a prerender in progress for the host provided,
1132 // it may not be shared. We require prerenders to be by themselves in a
1133 // separate process, so that we can monitor their resource usage, and so that
1134 // we can track the cookies that they change.
1135 Profile* profile = Profile::FromBrowserContext(
1136 process_host->GetBrowserContext());
1137 prerender::PrerenderManager* prerender_manager =
1138 prerender::PrerenderManagerFactory::GetForProfile(profile);
1139 if (prerender_manager &&
1140 !prerender_manager->MayReuseProcessHost(process_host)) {
1141 return false;
1144 return true;
1147 bool ChromeContentBrowserClient::ShouldTryToUseExistingProcessHost(
1148 content::BrowserContext* browser_context, const GURL& url) {
1149 // It has to be a valid URL for us to check for an extension.
1150 if (!url.is_valid())
1151 return false;
1153 #if defined(ENABLE_EXTENSIONS)
1154 Profile* profile = Profile::FromBrowserContext(browser_context);
1155 return ChromeContentBrowserClientExtensionsPart::
1156 ShouldTryToUseExistingProcessHost(
1157 profile, url);
1158 #else
1159 return false;
1160 #endif
1163 void ChromeContentBrowserClient::SiteInstanceGotProcess(
1164 SiteInstance* site_instance) {
1165 CHECK(site_instance->HasProcess());
1167 Profile* profile = Profile::FromBrowserContext(
1168 site_instance->GetBrowserContext());
1169 if (!profile)
1170 return;
1172 // Remember the ID of the Instant process to signal the renderer process
1173 // on startup in |AppendExtraCommandLineSwitches| below.
1174 if (chrome::ShouldAssignURLToInstantRenderer(
1175 site_instance->GetSiteURL(), profile)) {
1176 InstantService* instant_service =
1177 InstantServiceFactory::GetForProfile(profile);
1178 if (instant_service)
1179 instant_service->AddInstantProcess(site_instance->GetProcess()->GetID());
1182 #if !defined(OS_CHROMEOS)
1183 // We only expect there to be one signin process as we use process-per-site
1184 // for signin URLs. The signin process will be cleared from SigninManager
1185 // when the renderer is destroyed.
1186 if (SigninManager::IsWebBasedSigninFlowURL(site_instance->GetSiteURL())) {
1187 SigninClient* signin_client =
1188 ChromeSigninClientFactory::GetForProfile(profile);
1189 if (signin_client)
1190 signin_client->SetSigninProcess(site_instance->GetProcess()->GetID());
1191 #if defined(ENABLE_EXTENSIONS)
1192 ChromeContentBrowserClientExtensionsPart::SetSigninProcess(site_instance);
1193 #endif
1195 #endif
1197 for (size_t i = 0; i < extra_parts_.size(); ++i)
1198 extra_parts_[i]->SiteInstanceGotProcess(site_instance);
1201 void ChromeContentBrowserClient::SiteInstanceDeleting(
1202 SiteInstance* site_instance) {
1203 if (!site_instance->HasProcess())
1204 return;
1206 for (size_t i = 0; i < extra_parts_.size(); ++i)
1207 extra_parts_[i]->SiteInstanceDeleting(site_instance);
1210 bool ChromeContentBrowserClient::ShouldSwapBrowsingInstancesForNavigation(
1211 SiteInstance* site_instance,
1212 const GURL& current_url,
1213 const GURL& new_url) {
1214 #if defined(ENABLE_EXTENSIONS)
1215 return ChromeContentBrowserClientExtensionsPart::
1216 ShouldSwapBrowsingInstancesForNavigation(
1217 site_instance, current_url, new_url);
1218 #else
1219 return false;
1220 #endif
1223 bool ChromeContentBrowserClient::ShouldSwapProcessesForRedirect(
1224 content::ResourceContext* resource_context, const GURL& current_url,
1225 const GURL& new_url) {
1226 #if defined(ENABLE_EXTENSIONS)
1227 return ChromeContentBrowserClientExtensionsPart::
1228 ShouldSwapProcessesForRedirect(resource_context, current_url, new_url);
1229 #else
1230 return false;
1231 #endif
1234 bool ChromeContentBrowserClient::ShouldAssignSiteForURL(const GURL& url) {
1235 return !url.SchemeIs(chrome::kChromeNativeScheme);
1238 std::string ChromeContentBrowserClient::GetCanonicalEncodingNameByAliasName(
1239 const std::string& alias_name) {
1240 return CharacterEncoding::GetCanonicalEncodingNameByAliasName(alias_name);
1243 namespace {
1245 bool IsAutoReloadEnabled() {
1246 // Fetch the field trial, even though we don't use it. Calling FindFullName()
1247 // causes the field-trial mechanism to report which group we're in, which
1248 // might reflect a hard disable or hard enable via flag, both of which have
1249 // their own field trial groups. This lets us know what percentage of users
1250 // manually enable or disable auto-reload.
1251 std::string group = base::FieldTrialList::FindFullName(
1252 "AutoReloadExperiment");
1253 const base::CommandLine& browser_command_line =
1254 *base::CommandLine::ForCurrentProcess();
1255 if (browser_command_line.HasSwitch(switches::kEnableOfflineAutoReload))
1256 return true;
1257 if (browser_command_line.HasSwitch(switches::kDisableOfflineAutoReload))
1258 return false;
1259 return true;
1262 bool IsAutoReloadVisibleOnlyEnabled() {
1263 // See the block comment in IsAutoReloadEnabled().
1264 std::string group = base::FieldTrialList::FindFullName(
1265 "AutoReloadVisibleOnlyExperiment");
1266 const base::CommandLine& browser_command_line =
1267 *base::CommandLine::ForCurrentProcess();
1268 if (browser_command_line.HasSwitch(
1269 switches::kEnableOfflineAutoReloadVisibleOnly)) {
1270 return true;
1272 if (browser_command_line.HasSwitch(
1273 switches::kDisableOfflineAutoReloadVisibleOnly)) {
1274 return false;
1276 return true;
1279 } // namespace
1281 void ChromeContentBrowserClient::AppendExtraCommandLineSwitches(
1282 base::CommandLine* command_line,
1283 int child_process_id) {
1284 #if defined(OS_POSIX)
1285 if (breakpad::IsCrashReporterEnabled()) {
1286 scoped_ptr<metrics::ClientInfo> client_info =
1287 GoogleUpdateSettings::LoadMetricsClientInfo();
1288 command_line->AppendSwitchASCII(switches::kEnableCrashReporter,
1289 client_info ? client_info->client_id
1290 : std::string());
1292 #endif // defined(OS_POSIX)
1294 if (logging::DialogsAreSuppressed())
1295 command_line->AppendSwitch(switches::kNoErrorDialogs);
1297 std::string process_type =
1298 command_line->GetSwitchValueASCII(switches::kProcessType);
1299 const base::CommandLine& browser_command_line =
1300 *base::CommandLine::ForCurrentProcess();
1302 static const char* const kCommonSwitchNames[] = {
1303 switches::kUserAgent,
1304 switches::kUserDataDir, // Make logs go to the right file.
1306 command_line->CopySwitchesFrom(browser_command_line, kCommonSwitchNames,
1307 arraysize(kCommonSwitchNames));
1309 #if defined(ENABLE_IPC_FUZZER)
1310 static const char* const kIpcFuzzerSwitches[] = {
1311 switches::kIpcFuzzerTestcase,
1313 command_line->CopySwitchesFrom(browser_command_line, kIpcFuzzerSwitches,
1314 arraysize(kIpcFuzzerSwitches));
1315 #endif
1317 #if defined(OS_CHROMEOS)
1318 // On Chrome OS need to pass primary user homedir (in multi-profiles session).
1319 base::FilePath homedir;
1320 PathService::Get(base::DIR_HOME, &homedir);
1321 command_line->AppendSwitchASCII(chromeos::switches::kHomedir,
1322 homedir.value().c_str());
1323 #endif
1325 if (process_type == switches::kRendererProcess) {
1326 content::RenderProcessHost* process =
1327 content::RenderProcessHost::FromID(child_process_id);
1328 Profile* profile =
1329 process ? Profile::FromBrowserContext(process->GetBrowserContext())
1330 : NULL;
1331 for (size_t i = 0; i < extra_parts_.size(); ++i) {
1332 extra_parts_[i]->AppendExtraRendererCommandLineSwitches(
1333 command_line, process, profile);
1336 #if defined(OS_CHROMEOS)
1337 const std::string& login_profile =
1338 browser_command_line.GetSwitchValueASCII(
1339 chromeos::switches::kLoginProfile);
1340 if (!login_profile.empty())
1341 command_line->AppendSwitchASCII(
1342 chromeos::switches::kLoginProfile, login_profile);
1343 #endif
1345 #if defined(ENABLE_WEBRTC)
1346 MaybeCopyDisableWebRtcEncryptionSwitch(command_line,
1347 browser_command_line,
1348 VersionInfo::GetChannel());
1349 #endif
1351 if (process) {
1352 PrefService* prefs = profile->GetPrefs();
1353 // Currently this pref is only registered if applied via a policy.
1354 if (prefs->HasPrefPath(prefs::kDisable3DAPIs) &&
1355 prefs->GetBoolean(prefs::kDisable3DAPIs)) {
1356 // Turn this policy into a command line switch.
1357 command_line->AppendSwitch(switches::kDisable3DAPIs);
1360 const base::ListValue* switches =
1361 prefs->GetList(prefs::kEnableDeprecatedWebPlatformFeatures);
1362 if (switches) {
1363 // Enable any deprecated features that have been re-enabled by policy.
1364 for (base::ListValue::const_iterator it = switches->begin();
1365 it != switches->end(); ++it) {
1366 std::string switch_to_enable;
1367 if ((*it)->GetAsString(&switch_to_enable))
1368 command_line->AppendSwitch(switch_to_enable);
1372 // Disable client-side phishing detection in the renderer if it is
1373 // disabled in the Profile preferences or the browser process.
1374 if (!prefs->GetBoolean(prefs::kSafeBrowsingEnabled) ||
1375 !g_browser_process->safe_browsing_detection_service()) {
1376 command_line->AppendSwitch(
1377 switches::kDisableClientSidePhishingDetection);
1380 if (prefs->GetBoolean(prefs::kPrintPreviewDisabled))
1381 command_line->AppendSwitch(switches::kDisablePrintPreview);
1383 InstantService* instant_service =
1384 InstantServiceFactory::GetForProfile(profile);
1385 if (instant_service &&
1386 instant_service->IsInstantProcess(process->GetID()))
1387 command_line->AppendSwitch(switches::kInstantProcess);
1389 #if !defined(OS_CHROMEOS)
1390 SigninClient* signin_client =
1391 ChromeSigninClientFactory::GetForProfile(profile);
1392 if (signin_client && signin_client->IsSigninProcess(process->GetID()))
1393 command_line->AppendSwitch(switches::kSigninProcess);
1394 #endif
1397 if (IsAutoReloadEnabled())
1398 command_line->AppendSwitch(switches::kEnableOfflineAutoReload);
1399 if (IsAutoReloadVisibleOnlyEnabled()) {
1400 command_line->AppendSwitch(
1401 switches::kEnableOfflineAutoReloadVisibleOnly);
1405 // Enable load stale cache if this session is in the field trial or
1406 // the user explicitly enabled it. Note that as far as the renderer
1407 // is concerned, the feature is enabled if-and-only-if the
1408 // kEnableOfflineLoadStaleCache flag is on the command line;
1409 // the yes/no/default behavior is only at the browser command line
1410 // level.
1412 // Command line switches override
1413 if (browser_command_line.HasSwitch(
1414 switches::kEnableOfflineLoadStaleCache)) {
1415 command_line->AppendSwitch(switches::kEnableOfflineLoadStaleCache);
1416 } else if (!browser_command_line.HasSwitch(
1417 switches::kDisableOfflineLoadStaleCache)) {
1418 std::string group =
1419 base::FieldTrialList::FindFullName("LoadStaleCacheExperiment");
1421 if (group == "Enabled")
1422 command_line->AppendSwitch(switches::kEnableOfflineLoadStaleCache);
1426 // Please keep this in alphabetical order.
1427 static const char* const kSwitchNames[] = {
1428 autofill::switches::kDisableFillOnAccountSelect,
1429 autofill::switches::kDisablePasswordGeneration,
1430 autofill::switches::kEnableFillOnAccountSelect,
1431 autofill::switches::kEnableFillOnAccountSelectNoHighlighting,
1432 autofill::switches::kEnablePasswordGeneration,
1433 autofill::switches::kEnablePasswordSaveOnInPageNavigation,
1434 autofill::switches::kEnableSingleClickAutofill,
1435 autofill::switches::kIgnoreAutocompleteOffForAutofill,
1436 autofill::switches::kLocalHeuristicsOnlyForPasswordGeneration,
1437 autofill::switches::kRespectAutocompleteOffForAutofill,
1438 #if defined(ENABLE_EXTENSIONS)
1439 extensions::switches::kAllowHTTPBackgroundPage,
1440 extensions::switches::kAllowLegacyExtensionManifests,
1441 extensions::switches::kEnableSurfaceWorker,
1442 extensions::switches::kEnableAppWindowControls,
1443 extensions::switches::kEnableEmbeddedExtensionOptions,
1444 extensions::switches::kEnableExperimentalExtensionApis,
1445 extensions::switches::kEnableScriptsRequireAction,
1446 extensions::switches::kExtensionsOnChromeURLs,
1447 extensions::switches::kWhitelistedExtensionID,
1448 #endif
1449 switches::kAppsCheckoutURL,
1450 switches::kAppsGalleryURL,
1451 switches::kCloudPrintURL,
1452 switches::kCloudPrintXmppEndpoint,
1453 switches::kDisableBundledPpapiFlash,
1454 switches::kDisableCastStreamingHWEncoding,
1455 switches::kDisableJavaScriptHarmonyShipping,
1456 switches::kDisableNewBookmarkApps,
1457 switches::kDisableOutOfProcessPdf,
1458 switches::kEnableBenchmarking,
1459 switches::kEnableNaCl,
1460 #if !defined(DISABLE_NACL)
1461 switches::kEnableNaClDebug,
1462 switches::kEnableNaClNonSfiMode,
1463 #endif
1464 switches::kEnableNetBenchmarking,
1465 switches::kEnableOutOfProcessPdf,
1466 switches::kEnablePluginPlaceholderShadowDom,
1467 switches::kEnableShowModalDialog,
1468 switches::kEnableWebBasedSignin,
1469 switches::kJavaScriptHarmony,
1470 switches::kMessageLoopHistogrammer,
1471 switches::kPlaybackMode,
1472 switches::kPpapiFlashArgs,
1473 switches::kPpapiFlashPath,
1474 switches::kPpapiFlashVersion,
1475 switches::kProfilingAtStart,
1476 switches::kProfilingFile,
1477 switches::kProfilingFlush,
1478 switches::kRecordMode,
1479 translate::switches::kTranslateSecurityOrigin,
1482 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1483 arraysize(kSwitchNames));
1484 } else if (process_type == switches::kUtilityProcess) {
1485 #if defined(ENABLE_EXTENSIONS)
1486 static const char* const kSwitchNames[] = {
1487 extensions::switches::kAllowHTTPBackgroundPage,
1488 extensions::switches::kEnableExperimentalExtensionApis,
1489 extensions::switches::kExtensionsOnChromeURLs,
1490 extensions::switches::kWhitelistedExtensionID,
1493 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1494 arraysize(kSwitchNames));
1495 #endif
1496 } else if (process_type == switches::kPluginProcess) {
1497 #if defined(OS_CHROMEOS)
1498 static const char* const kSwitchNames[] = {
1499 chromeos::switches::kLoginProfile,
1502 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1503 arraysize(kSwitchNames));
1504 #endif
1505 } else if (process_type == switches::kZygoteProcess) {
1506 static const char* const kSwitchNames[] = {
1507 // Load (in-process) Pepper plugins in-process in the zygote pre-sandbox.
1508 switches::kDisableBundledPpapiFlash,
1509 #if !defined(DISABLE_NACL)
1510 switches::kEnableNaClDebug,
1511 switches::kEnableNaClNonSfiMode,
1512 switches::kNaClDangerousNoSandboxNonSfi,
1513 switches::kUseNaClHelperNonSfi,
1514 #endif
1515 switches::kPpapiFlashPath,
1516 switches::kPpapiFlashVersion,
1519 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1520 arraysize(kSwitchNames));
1521 } else if (process_type == switches::kGpuProcess) {
1522 // If --ignore-gpu-blacklist is passed in, don't send in crash reports
1523 // because GPU is expected to be unreliable.
1524 if (browser_command_line.HasSwitch(switches::kIgnoreGpuBlacklist) &&
1525 !command_line->HasSwitch(switches::kDisableBreakpad))
1526 command_line->AppendSwitch(switches::kDisableBreakpad);
1529 // The command line switch kEnableBenchmarking needs to be specified along
1530 // with the kEnableStatsTable switch to ensure that the stats table global
1531 // is initialized correctly.
1532 if (command_line->HasSwitch(switches::kEnableBenchmarking))
1533 DCHECK(command_line->HasSwitch(switches::kEnableStatsTable));
1536 std::string ChromeContentBrowserClient::GetApplicationLocale() {
1537 if (BrowserThread::CurrentlyOn(BrowserThread::IO))
1538 return g_io_thread_application_locale.Get();
1539 return g_browser_process->GetApplicationLocale();
1542 std::string ChromeContentBrowserClient::GetAcceptLangs(
1543 content::BrowserContext* context) {
1544 Profile* profile = Profile::FromBrowserContext(context);
1545 return profile->GetPrefs()->GetString(prefs::kAcceptLanguages);
1548 const gfx::ImageSkia* ChromeContentBrowserClient::GetDefaultFavicon() {
1549 ResourceBundle& rb = ResourceBundle::GetSharedInstance();
1550 return rb.GetNativeImageNamed(IDR_DEFAULT_FAVICON).ToImageSkia();
1553 bool ChromeContentBrowserClient::AllowAppCache(
1554 const GURL& manifest_url,
1555 const GURL& first_party,
1556 content::ResourceContext* context) {
1557 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1558 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1559 return io_data->GetCookieSettings()->
1560 IsSettingCookieAllowed(manifest_url, first_party);
1563 bool ChromeContentBrowserClient::AllowServiceWorker(
1564 const GURL& scope,
1565 const GURL& first_party_url,
1566 content::ResourceContext* context) {
1567 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1568 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1569 return io_data->GetCookieSettings()->
1570 IsSettingCookieAllowed(scope, first_party_url);
1573 bool ChromeContentBrowserClient::AllowGetCookie(
1574 const GURL& url,
1575 const GURL& first_party,
1576 const net::CookieList& cookie_list,
1577 content::ResourceContext* context,
1578 int render_process_id,
1579 int render_frame_id) {
1580 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1581 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1582 bool allow = io_data->GetCookieSettings()->
1583 IsReadingCookieAllowed(url, first_party);
1585 BrowserThread::PostTask(
1586 BrowserThread::UI, FROM_HERE,
1587 base::Bind(&TabSpecificContentSettings::CookiesRead, render_process_id,
1588 render_frame_id, url, first_party, cookie_list, !allow, true));
1589 return allow;
1592 bool ChromeContentBrowserClient::AllowSetCookie(
1593 const GURL& url,
1594 const GURL& first_party,
1595 const std::string& cookie_line,
1596 content::ResourceContext* context,
1597 int render_process_id,
1598 int render_frame_id,
1599 net::CookieOptions* options) {
1600 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1601 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1602 CookieSettings* cookie_settings = io_data->GetCookieSettings();
1603 bool allow = cookie_settings->IsSettingCookieAllowed(url, first_party);
1605 if (prerender_tracker_) {
1606 prerender_tracker_->OnCookieChangedForURL(
1607 render_process_id,
1608 context->GetRequestContext()->cookie_store()->GetCookieMonster(),
1609 url);
1612 BrowserThread::PostTask(
1613 BrowserThread::UI, FROM_HERE,
1614 base::Bind(&TabSpecificContentSettings::CookieChanged, render_process_id,
1615 render_frame_id, url, first_party, cookie_line, *options,
1616 !allow));
1617 return allow;
1620 bool ChromeContentBrowserClient::AllowSaveLocalState(
1621 content::ResourceContext* context) {
1622 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1623 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1624 CookieSettings* cookie_settings = io_data->GetCookieSettings();
1625 ContentSetting setting = cookie_settings->GetDefaultCookieSetting(NULL);
1627 // TODO(bauerb): Should we also disallow local state if the default is BLOCK?
1628 // Could we even support per-origin settings?
1629 return setting != CONTENT_SETTING_SESSION_ONLY;
1632 bool ChromeContentBrowserClient::AllowWorkerDatabase(
1633 const GURL& url,
1634 const base::string16& name,
1635 const base::string16& display_name,
1636 unsigned long estimated_size,
1637 content::ResourceContext* context,
1638 const std::vector<std::pair<int, int> >& render_frames) {
1639 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1640 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1641 CookieSettings* cookie_settings = io_data->GetCookieSettings();
1642 bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1644 // Record access to database for potential display in UI.
1645 std::vector<std::pair<int, int> >::const_iterator i;
1646 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1647 BrowserThread::PostTask(
1648 BrowserThread::UI, FROM_HERE,
1649 base::Bind(&TabSpecificContentSettings::WebDatabaseAccessed,
1650 i->first, i->second, url, name, display_name, !allow));
1653 return allow;
1656 void ChromeContentBrowserClient::AllowWorkerFileSystem(
1657 const GURL& url,
1658 content::ResourceContext* context,
1659 const std::vector<std::pair<int, int> >& render_frames,
1660 base::Callback<void(bool)> callback) {
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 #if defined(ENABLE_EXTENSIONS)
1667 GuestPermissionRequestHelper(url, render_frames, callback, allow);
1668 #else
1669 FileSystemAccessed(url, render_frames, callback, allow);
1670 #endif
1673 #if defined(ENABLE_EXTENSIONS)
1674 void ChromeContentBrowserClient::GuestPermissionRequestHelper(
1675 const GURL& url,
1676 const std::vector<std::pair<int, int> >& render_frames,
1677 base::Callback<void(bool)> callback,
1678 bool allow) {
1679 DCHECK(BrowserThread:: CurrentlyOn(BrowserThread::IO));
1680 std::vector<std::pair<int, int> >::const_iterator i;
1681 std::map<int, int> process_map;
1682 std::map<int, int>::const_iterator it;
1683 bool has_web_view_guest = false;
1684 // Record access to file system for potential display in UI.
1685 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1686 if (process_map.find(i->first) != process_map.end())
1687 continue;
1689 process_map.insert(std::pair<int, int>(i->first, i->second));
1691 if (extensions::WebViewRendererState::GetInstance()->IsGuest(i->first))
1692 has_web_view_guest = true;
1694 if (!has_web_view_guest) {
1695 FileSystemAccessed(url, render_frames, callback, allow);
1696 return;
1698 DCHECK_EQ(1U, process_map.size());
1699 it = process_map.begin();
1700 BrowserThread::PostTask(
1701 BrowserThread::UI,
1702 FROM_HERE,
1703 base::Bind(&ChromeContentBrowserClient::
1704 RequestFileSystemPermissionOnUIThread,
1705 it->first,
1706 it->second,
1707 url,
1708 allow,
1709 base::Bind(&ChromeContentBrowserClient::FileSystemAccessed,
1710 weak_factory_.GetWeakPtr(),
1711 url,
1712 render_frames,
1713 callback)));
1716 void ChromeContentBrowserClient::RequestFileSystemPermissionOnUIThread(
1717 int render_process_id,
1718 int render_frame_id,
1719 const GURL& url,
1720 bool allowed_by_default,
1721 const base::Callback<void(bool)>& callback) {
1722 DCHECK(BrowserThread:: CurrentlyOn(BrowserThread::UI));
1723 extensions::WebViewPermissionHelper* web_view_permission_helper =
1724 extensions::WebViewPermissionHelper::FromFrameID(
1725 render_process_id, render_frame_id);
1726 web_view_permission_helper->RequestFileSystemPermission(url,
1727 allowed_by_default,
1728 callback);
1730 #endif
1732 void ChromeContentBrowserClient::FileSystemAccessed(
1733 const GURL& url,
1734 const std::vector<std::pair<int, int> >& render_frames,
1735 base::Callback<void(bool)> callback,
1736 bool allow) {
1737 // Record access to file system for potential display in UI.
1738 std::vector<std::pair<int, int> >::const_iterator i;
1739 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1740 BrowserThread::PostTask(
1741 BrowserThread::UI,
1742 FROM_HERE,
1743 base::Bind(&TabSpecificContentSettings::FileSystemAccessed,
1744 i->first, i->second, url, !allow));
1746 callback.Run(allow);
1749 bool ChromeContentBrowserClient::AllowWorkerIndexedDB(
1750 const GURL& url,
1751 const base::string16& name,
1752 content::ResourceContext* context,
1753 const std::vector<std::pair<int, int> >& render_frames) {
1754 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1755 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1756 CookieSettings* cookie_settings = io_data->GetCookieSettings();
1757 bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1759 // Record access to IndexedDB 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, FROM_HERE,
1764 base::Bind(&TabSpecificContentSettings::IndexedDBAccessed,
1765 i->first, i->second, url, name, !allow));
1768 return allow;
1771 net::URLRequestContext*
1772 ChromeContentBrowserClient::OverrideRequestContextForURL(
1773 const GURL& url, content::ResourceContext* context) {
1774 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1775 #if defined(ENABLE_EXTENSIONS)
1776 if (url.SchemeIs(extensions::kExtensionScheme)) {
1777 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1778 return io_data->extensions_request_context();
1780 #endif
1782 return NULL;
1785 QuotaPermissionContext*
1786 ChromeContentBrowserClient::CreateQuotaPermissionContext() {
1787 return new ChromeQuotaPermissionContext();
1790 void ChromeContentBrowserClient::AllowCertificateError(
1791 int render_process_id,
1792 int render_frame_id,
1793 int cert_error,
1794 const net::SSLInfo& ssl_info,
1795 const GURL& request_url,
1796 ResourceType resource_type,
1797 bool overridable,
1798 bool strict_enforcement,
1799 bool expired_previous_decision,
1800 const base::Callback<void(bool)>& callback,
1801 content::CertificateRequestResultType* result) {
1802 if (resource_type != content::RESOURCE_TYPE_MAIN_FRAME) {
1803 // A sub-resource has a certificate error. The user doesn't really
1804 // have a context for making the right decision, so block the
1805 // request hard, without an info bar to allow showing the insecure
1806 // content.
1807 *result = content::CERTIFICATE_REQUEST_RESULT_TYPE_DENY;
1808 return;
1811 // If the tab is being prerendered, cancel the prerender and the request.
1812 content::RenderFrameHost* render_frame_host =
1813 content::RenderFrameHost::FromID(render_process_id, render_frame_id);
1814 WebContents* tab = WebContents::FromRenderFrameHost(render_frame_host);
1815 if (!tab) {
1816 NOTREACHED();
1817 return;
1820 prerender::PrerenderContents* prerender_contents =
1821 prerender::PrerenderContents::FromWebContents(tab);
1822 if (prerender_contents) {
1823 prerender_contents->Destroy(prerender::FINAL_STATUS_SSL_ERROR);
1824 *result = content::CERTIFICATE_REQUEST_RESULT_TYPE_CANCEL;
1825 return;
1828 // Otherwise, display an SSL blocking page. The interstitial page takes
1829 // ownership of ssl_blocking_page.
1830 int options_mask = 0;
1831 if (overridable)
1832 options_mask |= SSLBlockingPage::OVERRIDABLE;
1833 if (strict_enforcement)
1834 options_mask |= SSLBlockingPage::STRICT_ENFORCEMENT;
1835 if (expired_previous_decision)
1836 options_mask |= SSLBlockingPage::EXPIRED_BUT_PREVIOUSLY_ALLOWED;
1838 SSLErrorHandler::HandleSSLError(
1839 tab, cert_error, ssl_info, request_url, options_mask, callback);
1842 void ChromeContentBrowserClient::SelectClientCertificate(
1843 int render_process_id,
1844 int render_frame_id,
1845 net::SSLCertRequestInfo* cert_request_info,
1846 const base::Callback<void(net::X509Certificate*)>& callback) {
1847 content::RenderFrameHost* rfh = content::RenderFrameHost::FromID(
1848 render_process_id, render_frame_id);
1849 WebContents* tab = WebContents::FromRenderFrameHost(rfh);
1850 if (!tab) {
1851 // TODO(davidben): This makes the request hang, but returning no certificate
1852 // also breaks. It should abort the request. See https://crbug.com/417092
1853 return;
1856 prerender::PrerenderContents* prerender_contents =
1857 prerender::PrerenderContents::FromWebContents(tab);
1858 if (prerender_contents) {
1859 prerender_contents->Destroy(
1860 prerender::FINAL_STATUS_SSL_CLIENT_CERTIFICATE_REQUESTED);
1861 return;
1864 GURL requesting_url("https://" + cert_request_info->host_and_port.ToString());
1865 DCHECK(requesting_url.is_valid())
1866 << "Invalid URL string: https://"
1867 << cert_request_info->host_and_port.ToString();
1869 Profile* profile = Profile::FromBrowserContext(tab->GetBrowserContext());
1870 scoped_ptr<base::Value> filter =
1871 profile->GetHostContentSettingsMap()->GetWebsiteSetting(
1872 requesting_url,
1873 requesting_url,
1874 CONTENT_SETTINGS_TYPE_AUTO_SELECT_CERTIFICATE,
1875 std::string(),
1876 NULL);
1878 if (filter.get()) {
1879 // Try to automatically select a client certificate.
1880 if (filter->IsType(base::Value::TYPE_DICTIONARY)) {
1881 base::DictionaryValue* filter_dict =
1882 static_cast<base::DictionaryValue*>(filter.get());
1884 const std::vector<scoped_refptr<net::X509Certificate> >&
1885 all_client_certs = cert_request_info->client_certs;
1886 for (size_t i = 0; i < all_client_certs.size(); ++i) {
1887 if (CertMatchesFilter(*all_client_certs[i].get(), *filter_dict)) {
1888 // Use the first certificate that is matched by the filter.
1889 callback.Run(all_client_certs[i].get());
1890 return;
1893 } else {
1894 NOTREACHED();
1898 chrome::ShowSSLClientCertificateSelector(tab, cert_request_info, callback);
1901 void ChromeContentBrowserClient::AddCertificate(
1902 net::CertificateMimeType cert_type,
1903 const void* cert_data,
1904 size_t cert_size,
1905 int render_process_id,
1906 int render_frame_id) {
1907 chrome::SSLAddCertificate(cert_type, cert_data, cert_size,
1908 render_process_id, render_frame_id);
1911 content::MediaObserver* ChromeContentBrowserClient::GetMediaObserver() {
1912 return MediaCaptureDevicesDispatcher::GetInstance();
1915 content::PlatformNotificationService*
1916 ChromeContentBrowserClient::GetPlatformNotificationService() {
1917 #if defined(ENABLE_NOTIFICATIONS)
1918 return PlatformNotificationServiceImpl::GetInstance();
1919 #else
1920 NOTIMPLEMENTED();
1921 return NULL;
1922 #endif
1925 void ChromeContentBrowserClient::RequestPermission(
1926 content::PermissionType permission,
1927 content::WebContents* web_contents,
1928 int bridge_id,
1929 const GURL& requesting_frame,
1930 bool user_gesture,
1931 const base::Callback<void(bool)>& result_callback) {
1932 int render_process_id = web_contents->GetRenderProcessHost()->GetID();
1933 int render_view_id = web_contents->GetRenderViewHost()->GetRoutingID();
1934 const PermissionRequestID request_id(render_process_id,
1935 render_view_id,
1936 bridge_id,
1937 requesting_frame);
1938 Profile* profile =
1939 Profile::FromBrowserContext(web_contents->GetBrowserContext());
1940 PermissionContextBase* context = GetPermissionContext(profile, permission);
1942 if (!context)
1943 return;
1945 context->RequestPermission(web_contents, request_id, requesting_frame,
1946 user_gesture, result_callback);
1949 content::PermissionStatus ChromeContentBrowserClient::GetPermissionStatus(
1950 content::PermissionType permission,
1951 content::BrowserContext* browser_context,
1952 const GURL& requesting_origin,
1953 const GURL& embedding_origin) {
1954 DCHECK(browser_context);
1955 Profile* profile = Profile::FromBrowserContext(browser_context);
1956 PermissionContextBase* context = GetPermissionContext(profile, permission);
1958 if (!context)
1959 return content::PERMISSION_STATUS_ASK;
1961 return ContentSettingToPermissionStatus(
1962 context->GetPermissionStatus(requesting_origin.GetOrigin(),
1963 embedding_origin.GetOrigin()));
1966 void ChromeContentBrowserClient::ResetPermission(
1967 content::PermissionType permission,
1968 content::BrowserContext* browser_context,
1969 const GURL& requesting_origin,
1970 const GURL& embedding_origin) {
1971 DCHECK(browser_context);
1972 Profile* profile = Profile::FromBrowserContext(browser_context);
1973 PermissionContextBase* context = GetPermissionContext(profile, permission);
1975 if (!context)
1976 return;
1978 context->ResetPermission(requesting_origin.GetOrigin(),
1979 embedding_origin.GetOrigin());
1982 void ChromeContentBrowserClient::CancelPermissionRequest(
1983 content::PermissionType permission,
1984 content::WebContents* web_contents,
1985 int bridge_id,
1986 const GURL& requesting_frame) {
1987 int render_process_id = web_contents->GetRenderProcessHost()->GetID();
1988 int render_view_id = web_contents->GetRenderViewHost()->GetRoutingID();
1989 const PermissionRequestID request_id(render_process_id,
1990 render_view_id,
1991 bridge_id,
1992 requesting_frame);
1993 Profile* profile =
1994 Profile::FromBrowserContext(web_contents->GetBrowserContext());
1995 PermissionContextBase* context = GetPermissionContext(profile, permission);
1996 if (!context)
1997 return;
1998 context->CancelPermissionRequest(web_contents, request_id);
2001 void ChromeContentBrowserClient::RegisterPermissionUsage(
2002 content::PermissionType permission,
2003 content::WebContents* web_contents,
2004 const GURL& frame_url,
2005 const GURL& main_frame_url) {
2006 Profile::FromBrowserContext(web_contents->GetBrowserContext())
2007 ->GetHostContentSettingsMap()
2008 ->UpdateLastUsage(
2009 frame_url, main_frame_url, PermissionToContentSetting(permission));
2012 bool ChromeContentBrowserClient::CanCreateWindow(
2013 const GURL& opener_url,
2014 const GURL& opener_top_level_frame_url,
2015 const GURL& source_origin,
2016 WindowContainerType container_type,
2017 const GURL& target_url,
2018 const content::Referrer& referrer,
2019 WindowOpenDisposition disposition,
2020 const WebWindowFeatures& features,
2021 bool user_gesture,
2022 bool opener_suppressed,
2023 content::ResourceContext* context,
2024 int render_process_id,
2025 int opener_id,
2026 bool* no_javascript_access) {
2027 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
2029 *no_javascript_access = false;
2031 // If the opener is trying to create a background window but doesn't have
2032 // the appropriate permission, fail the attempt.
2033 if (container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {
2034 #if defined(ENABLE_EXTENSIONS)
2035 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
2036 InfoMap* map = io_data->GetExtensionInfoMap();
2037 if (!map->SecurityOriginHasAPIPermission(
2038 source_origin,
2039 render_process_id,
2040 APIPermission::kBackground)) {
2041 return false;
2044 // Note: this use of GetExtensionOrAppByURL is safe but imperfect. It may
2045 // return a recently installed Extension even if this CanCreateWindow call
2046 // was made by an old copy of the page in a normal web process. That's ok,
2047 // because the permission check above would have caused an early return
2048 // already. We must use the full URL to find hosted apps, though, and not
2049 // just the origin.
2050 const Extension* extension =
2051 map->extensions().GetExtensionOrAppByURL(opener_url);
2052 if (extension && !extensions::BackgroundInfo::AllowJSAccess(extension))
2053 *no_javascript_access = true;
2054 #endif
2056 return true;
2059 #if defined(ENABLE_EXTENSIONS)
2060 if (extensions::WebViewRendererState::GetInstance()->IsGuest(
2061 render_process_id))
2062 return true;
2063 #endif
2065 HostContentSettingsMap* content_settings =
2066 ProfileIOData::FromResourceContext(context)->GetHostContentSettingsMap();
2067 BlockedWindowParams blocked_params(target_url,
2068 referrer,
2069 disposition,
2070 features,
2071 user_gesture,
2072 opener_suppressed,
2073 render_process_id,
2074 opener_id);
2076 if (!user_gesture &&
2077 !base::CommandLine::ForCurrentProcess()->HasSwitch(
2078 switches::kDisablePopupBlocking)) {
2079 if (content_settings->GetContentSetting(opener_top_level_frame_url,
2080 opener_top_level_frame_url,
2081 CONTENT_SETTINGS_TYPE_POPUPS,
2082 std::string()) !=
2083 CONTENT_SETTING_ALLOW) {
2084 BrowserThread::PostTask(BrowserThread::UI,
2085 FROM_HERE,
2086 base::Bind(&HandleBlockedPopupOnUIThread,
2087 blocked_params));
2088 return false;
2092 #if defined(OS_ANDROID)
2093 if (SingleTabModeTabHelper::IsRegistered(render_process_id, opener_id)) {
2094 BrowserThread::PostTask(BrowserThread::UI,
2095 FROM_HERE,
2096 base::Bind(&HandleSingleTabModeBlockOnUIThread,
2097 blocked_params));
2098 return false;
2100 #endif
2102 return true;
2105 void ChromeContentBrowserClient::ResourceDispatcherHostCreated() {
2106 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
2107 prerender_tracker_ = g_browser_process->prerender_tracker();
2108 return g_browser_process->ResourceDispatcherHostCreated();
2111 content::SpeechRecognitionManagerDelegate*
2112 ChromeContentBrowserClient::CreateSpeechRecognitionManagerDelegate() {
2113 return new speech::ChromeSpeechRecognitionManagerDelegate();
2116 net::NetLog* ChromeContentBrowserClient::GetNetLog() {
2117 return g_browser_process->net_log();
2120 AccessTokenStore* ChromeContentBrowserClient::CreateAccessTokenStore() {
2121 return new ChromeAccessTokenStore();
2124 bool ChromeContentBrowserClient::IsFastShutdownPossible() {
2125 return true;
2128 void ChromeContentBrowserClient::OverrideWebkitPrefs(
2129 RenderViewHost* rvh, const GURL& url, WebPreferences* web_prefs) {
2130 Profile* profile = Profile::FromBrowserContext(
2131 rvh->GetProcess()->GetBrowserContext());
2132 PrefService* prefs = profile->GetPrefs();
2134 // Fill per-script font preferences. These are not registered on Android
2135 // - http://crbug.com/308033.
2136 #if !defined(OS_ANDROID)
2137 FontFamilyCache::FillFontFamilyMap(profile,
2138 prefs::kWebKitStandardFontFamilyMap,
2139 &web_prefs->standard_font_family_map);
2140 FontFamilyCache::FillFontFamilyMap(profile,
2141 prefs::kWebKitFixedFontFamilyMap,
2142 &web_prefs->fixed_font_family_map);
2143 FontFamilyCache::FillFontFamilyMap(profile,
2144 prefs::kWebKitSerifFontFamilyMap,
2145 &web_prefs->serif_font_family_map);
2146 FontFamilyCache::FillFontFamilyMap(profile,
2147 prefs::kWebKitSansSerifFontFamilyMap,
2148 &web_prefs->sans_serif_font_family_map);
2149 FontFamilyCache::FillFontFamilyMap(profile,
2150 prefs::kWebKitCursiveFontFamilyMap,
2151 &web_prefs->cursive_font_family_map);
2152 FontFamilyCache::FillFontFamilyMap(profile,
2153 prefs::kWebKitFantasyFontFamilyMap,
2154 &web_prefs->fantasy_font_family_map);
2155 FontFamilyCache::FillFontFamilyMap(profile,
2156 prefs::kWebKitPictographFontFamilyMap,
2157 &web_prefs->pictograph_font_family_map);
2158 #endif
2160 web_prefs->default_font_size =
2161 prefs->GetInteger(prefs::kWebKitDefaultFontSize);
2162 web_prefs->default_fixed_font_size =
2163 prefs->GetInteger(prefs::kWebKitDefaultFixedFontSize);
2164 web_prefs->minimum_font_size =
2165 prefs->GetInteger(prefs::kWebKitMinimumFontSize);
2166 web_prefs->minimum_logical_font_size =
2167 prefs->GetInteger(prefs::kWebKitMinimumLogicalFontSize);
2169 web_prefs->default_encoding = prefs->GetString(prefs::kDefaultCharset);
2171 web_prefs->javascript_can_open_windows_automatically =
2172 prefs->GetBoolean(prefs::kWebKitJavascriptCanOpenWindowsAutomatically);
2173 web_prefs->dom_paste_enabled =
2174 prefs->GetBoolean(prefs::kWebKitDomPasteEnabled);
2175 web_prefs->shrinks_standalone_images_to_fit =
2176 prefs->GetBoolean(prefs::kWebKitShrinksStandaloneImagesToFit);
2177 web_prefs->tabs_to_links = prefs->GetBoolean(prefs::kWebkitTabsToLinks);
2179 if (!prefs->GetBoolean(prefs::kWebKitJavascriptEnabled))
2180 web_prefs->javascript_enabled = false;
2181 if (!prefs->GetBoolean(prefs::kWebKitWebSecurityEnabled))
2182 web_prefs->web_security_enabled = false;
2183 if (!prefs->GetBoolean(prefs::kWebKitPluginsEnabled))
2184 web_prefs->plugins_enabled = false;
2185 if (!prefs->GetBoolean(prefs::kWebKitJavaEnabled))
2186 web_prefs->java_enabled = false;
2187 web_prefs->loads_images_automatically =
2188 prefs->GetBoolean(prefs::kWebKitLoadsImagesAutomatically);
2190 if (prefs->GetBoolean(prefs::kDisable3DAPIs))
2191 web_prefs->experimental_webgl_enabled = false;
2193 web_prefs->allow_displaying_insecure_content =
2194 prefs->GetBoolean(prefs::kWebKitAllowDisplayingInsecureContent);
2195 web_prefs->allow_running_insecure_content =
2196 prefs->GetBoolean(prefs::kWebKitAllowRunningInsecureContent);
2197 #if defined(OS_ANDROID)
2198 web_prefs->font_scale_factor =
2199 static_cast<float>(prefs->GetDouble(prefs::kWebKitFontScaleFactor));
2200 web_prefs->device_scale_adjustment = GetDeviceScaleAdjustment();
2201 web_prefs->force_enable_zoom =
2202 prefs->GetBoolean(prefs::kWebKitForceEnableZoom);
2203 #endif
2205 #if defined(OS_ANDROID)
2206 web_prefs->password_echo_enabled =
2207 prefs->GetBoolean(prefs::kWebKitPasswordEchoEnabled);
2208 #else
2209 web_prefs->password_echo_enabled = browser_defaults::kPasswordEchoEnabled;
2210 #endif
2212 web_prefs->asynchronous_spell_checking_enabled = true;
2213 web_prefs->unified_textchecker_enabled = true;
2215 web_prefs->uses_universal_detector =
2216 prefs->GetBoolean(prefs::kWebKitUsesUniversalDetector);
2217 web_prefs->text_areas_are_resizable =
2218 prefs->GetBoolean(prefs::kWebKitTextAreasAreResizable);
2219 web_prefs->hyperlink_auditing_enabled =
2220 prefs->GetBoolean(prefs::kEnableHyperlinkAuditing);
2222 // Make sure we will set the default_encoding with canonical encoding name.
2223 web_prefs->default_encoding =
2224 CharacterEncoding::GetCanonicalEncodingNameByAliasName(
2225 web_prefs->default_encoding);
2226 if (web_prefs->default_encoding.empty()) {
2227 prefs->ClearPref(prefs::kDefaultCharset);
2228 web_prefs->default_encoding = prefs->GetString(prefs::kDefaultCharset);
2230 DCHECK(!web_prefs->default_encoding.empty());
2232 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2233 switches::kEnablePotentiallyAnnoyingSecurityFeatures)) {
2234 web_prefs->disable_reading_from_canvas = true;
2235 web_prefs->strict_mixed_content_checking = true;
2236 web_prefs->strict_powerful_feature_restrictions = true;
2239 for (size_t i = 0; i < extra_parts_.size(); ++i)
2240 extra_parts_[i]->OverrideWebkitPrefs(rvh, url, web_prefs);
2243 void ChromeContentBrowserClient::BrowserURLHandlerCreated(
2244 BrowserURLHandler* handler) {
2245 for (size_t i = 0; i < extra_parts_.size(); ++i)
2246 extra_parts_[i]->BrowserURLHandlerCreated(handler);
2248 // about: handler. Must come before chrome: handler, since it will
2249 // rewrite about: urls to chrome: URLs and then expect chrome: to
2250 // actually handle them.
2251 handler->AddHandlerPair(&WillHandleBrowserAboutURL,
2252 BrowserURLHandler::null_handler());
2254 #if defined(OS_ANDROID)
2255 // Handler to rewrite chrome://newtab on Android.
2256 handler->AddHandlerPair(&chrome::android::HandleAndroidNativePageURL,
2257 BrowserURLHandler::null_handler());
2258 #else
2259 // Handler to rewrite chrome://newtab for InstantExtended.
2260 handler->AddHandlerPair(&chrome::HandleNewTabURLRewrite,
2261 &chrome::HandleNewTabURLReverseRewrite);
2262 #endif
2264 // chrome: & friends.
2265 handler->AddHandlerPair(&HandleWebUI, &HandleWebUIReverse);
2268 void ChromeContentBrowserClient::ClearCache(RenderViewHost* rvh) {
2269 Profile* profile = Profile::FromBrowserContext(
2270 rvh->GetSiteInstance()->GetProcess()->GetBrowserContext());
2271 BrowsingDataRemover* remover =
2272 BrowsingDataRemover::CreateForUnboundedRange(profile);
2273 remover->Remove(BrowsingDataRemover::REMOVE_CACHE,
2274 BrowsingDataHelper::UNPROTECTED_WEB);
2275 // BrowsingDataRemover takes care of deleting itself when done.
2278 void ChromeContentBrowserClient::ClearCookies(RenderViewHost* rvh) {
2279 Profile* profile = Profile::FromBrowserContext(
2280 rvh->GetSiteInstance()->GetProcess()->GetBrowserContext());
2281 BrowsingDataRemover* remover =
2282 BrowsingDataRemover::CreateForUnboundedRange(profile);
2283 int remove_mask = BrowsingDataRemover::REMOVE_SITE_DATA;
2284 remover->Remove(remove_mask, BrowsingDataHelper::UNPROTECTED_WEB);
2285 // BrowsingDataRemover takes care of deleting itself when done.
2288 base::FilePath ChromeContentBrowserClient::GetDefaultDownloadDirectory() {
2289 return DownloadPrefs::GetDefaultDownloadDirectory();
2292 std::string ChromeContentBrowserClient::GetDefaultDownloadName() {
2293 return l10n_util::GetStringUTF8(IDS_DEFAULT_DOWNLOAD_FILENAME);
2296 void ChromeContentBrowserClient::DidCreatePpapiPlugin(
2297 content::BrowserPpapiHost* browser_host) {
2298 #if defined(ENABLE_PLUGINS)
2299 ChromeContentBrowserClientPluginsPart::DidCreatePpapiPlugin(browser_host);
2300 #endif
2303 content::BrowserPpapiHost*
2304 ChromeContentBrowserClient::GetExternalBrowserPpapiHost(
2305 int plugin_process_id) {
2306 #if !defined(DISABLE_NACL)
2307 content::BrowserChildProcessHostIterator iter(PROCESS_TYPE_NACL_LOADER);
2308 while (!iter.Done()) {
2309 nacl::NaClProcessHost* host = static_cast<nacl::NaClProcessHost*>(
2310 iter.GetDelegate());
2311 if (host->process() &&
2312 host->process()->GetData().id == plugin_process_id) {
2313 // Found the plugin.
2314 return host->browser_ppapi_host();
2316 ++iter;
2318 #endif
2319 return NULL;
2322 bool ChromeContentBrowserClient::AllowPepperSocketAPI(
2323 content::BrowserContext* browser_context,
2324 const GURL& url,
2325 bool private_api,
2326 const content::SocketPermissionRequest* params) {
2327 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
2328 return ChromeContentBrowserClientPluginsPart::AllowPepperSocketAPI(
2329 browser_context, url, private_api, params, allowed_socket_origins_);
2330 #else
2331 return false;
2332 #endif
2335 ui::SelectFilePolicy* ChromeContentBrowserClient::CreateSelectFilePolicy(
2336 WebContents* web_contents) {
2337 return new ChromeSelectFilePolicy(web_contents);
2340 void ChromeContentBrowserClient::GetAdditionalAllowedSchemesForFileSystem(
2341 std::vector<std::string>* additional_allowed_schemes) {
2342 ContentBrowserClient::GetAdditionalAllowedSchemesForFileSystem(
2343 additional_allowed_schemes);
2344 additional_allowed_schemes->push_back(content::kChromeDevToolsScheme);
2345 additional_allowed_schemes->push_back(content::kChromeUIScheme);
2346 for (size_t i = 0; i < extra_parts_.size(); ++i) {
2347 extra_parts_[i]->GetAdditionalAllowedSchemesForFileSystem(
2348 additional_allowed_schemes);
2352 void ChromeContentBrowserClient::GetURLRequestAutoMountHandlers(
2353 std::vector<storage::URLRequestAutoMountHandler>* handlers) {
2354 for (size_t i = 0; i < extra_parts_.size(); ++i)
2355 extra_parts_[i]->GetURLRequestAutoMountHandlers(handlers);
2358 void ChromeContentBrowserClient::GetAdditionalFileSystemBackends(
2359 content::BrowserContext* browser_context,
2360 const base::FilePath& storage_partition_path,
2361 ScopedVector<storage::FileSystemBackend>* additional_backends) {
2362 #if defined(OS_CHROMEOS)
2363 storage::ExternalMountPoints* external_mount_points =
2364 content::BrowserContext::GetMountPoints(browser_context);
2365 DCHECK(external_mount_points);
2366 chromeos::FileSystemBackend* backend = new chromeos::FileSystemBackend(
2367 new drive::FileSystemBackendDelegate,
2368 new chromeos::file_system_provider::BackendDelegate,
2369 new chromeos::MTPFileSystemBackendDelegate(storage_partition_path),
2370 browser_context->GetSpecialStoragePolicy(),
2371 external_mount_points,
2372 storage::ExternalMountPoints::GetSystemInstance());
2373 backend->AddSystemMountPoints();
2374 DCHECK(backend->CanHandleType(storage::kFileSystemTypeExternal));
2375 additional_backends->push_back(backend);
2376 #endif
2378 for (size_t i = 0; i < extra_parts_.size(); ++i) {
2379 extra_parts_[i]->GetAdditionalFileSystemBackends(
2380 browser_context, storage_partition_path, additional_backends);
2384 #if defined(OS_POSIX) && !defined(OS_MACOSX)
2385 void ChromeContentBrowserClient::GetAdditionalMappedFilesForChildProcess(
2386 const base::CommandLine& command_line,
2387 int child_process_id,
2388 FileDescriptorInfo* mappings) {
2389 #if defined(OS_ANDROID)
2390 base::FilePath data_path;
2391 PathService::Get(ui::DIR_RESOURCE_PAKS_ANDROID, &data_path);
2392 DCHECK(!data_path.empty());
2394 int flags = base::File::FLAG_OPEN | base::File::FLAG_READ;
2395 base::FilePath chrome_resources_pak =
2396 data_path.AppendASCII("chrome_100_percent.pak");
2397 base::File file(chrome_resources_pak, flags);
2398 DCHECK(file.IsValid());
2399 mappings->Transfer(kAndroidChrome100PercentPakDescriptor,
2400 base::ScopedFD(file.TakePlatformFile()));
2402 const std::string locale = GetApplicationLocale();
2403 base::FilePath locale_pak = ResourceBundle::GetSharedInstance().
2404 GetLocaleFilePath(locale, false);
2405 file.Initialize(locale_pak, flags);
2406 DCHECK(file.IsValid());
2407 mappings->Transfer(kAndroidLocalePakDescriptor,
2408 base::ScopedFD(file.TakePlatformFile()));
2410 base::FilePath resources_pack_path;
2411 PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
2412 file.Initialize(resources_pack_path, flags);
2413 DCHECK(file.IsValid());
2414 mappings->Transfer(kAndroidUIResourcesPakDescriptor,
2415 base::ScopedFD(file.TakePlatformFile()));
2417 if (breakpad::IsCrashReporterEnabled()) {
2418 file = breakpad::CrashDumpManager::GetInstance()->CreateMinidumpFile(
2419 child_process_id);
2420 if (file.IsValid()) {
2421 mappings->Transfer(kAndroidMinidumpDescriptor,
2422 base::ScopedFD(file.TakePlatformFile()));
2423 } else {
2424 LOG(ERROR) << "Failed to create file for minidump, crash reporting will "
2425 "be disabled for this process.";
2429 base::FilePath app_data_path;
2430 PathService::Get(base::DIR_ANDROID_APP_DATA, &app_data_path);
2431 DCHECK(!app_data_path.empty());
2433 flags = base::File::FLAG_OPEN | base::File::FLAG_READ;
2434 base::FilePath icudata_path =
2435 app_data_path.AppendASCII(base::i18n::kIcuDataFileName);
2436 base::File icudata_file(icudata_path, flags);
2437 DCHECK(icudata_file.IsValid());
2438 mappings->Transfer(kAndroidICUDataDescriptor,
2439 base::ScopedFD(icudata_file.TakePlatformFile()));
2441 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
2442 base::FilePath v8_data_path;
2443 PathService::Get(base::DIR_ANDROID_APP_DATA, &v8_data_path);
2444 DCHECK(!v8_data_path.empty());
2446 int file_flags = base::File::FLAG_OPEN | base::File::FLAG_READ;
2447 base::FilePath v8_natives_data_path =
2448 v8_data_path.AppendASCII(gin::IsolateHolder::kNativesFileName);
2449 base::FilePath v8_snapshot_data_path =
2450 v8_data_path.AppendASCII(gin::IsolateHolder::kSnapshotFileName);
2451 base::File v8_natives_data_file(v8_natives_data_path, file_flags);
2452 base::File v8_snapshot_data_file(v8_snapshot_data_path, file_flags);
2453 DCHECK(v8_natives_data_file.IsValid());
2454 DCHECK(v8_snapshot_data_file.IsValid());
2455 mappings->Transfer(kV8NativesDataDescriptor,
2456 base::ScopedFD(v8_natives_data_file.TakePlatformFile()));
2457 mappings->Transfer(kV8SnapshotDataDescriptor,
2458 base::ScopedFD(v8_snapshot_data_file.TakePlatformFile()));
2459 #endif // V8_USE_EXTERNAL_STARTUP_DATA
2461 #else
2462 int crash_signal_fd = GetCrashSignalFD(command_line);
2463 if (crash_signal_fd >= 0) {
2464 mappings->Share(kCrashDumpSignal, crash_signal_fd);
2466 #endif // defined(OS_ANDROID)
2468 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
2470 #if defined(OS_WIN)
2471 const wchar_t* ChromeContentBrowserClient::GetResourceDllName() {
2472 return chrome::kBrowserResourcesDll;
2475 void ChromeContentBrowserClient::PreSpawnRenderer(
2476 sandbox::TargetPolicy* policy,
2477 bool* success) {
2478 // This code is duplicated in nacl_exe_win_64.cc.
2479 // Allow the server side of a pipe restricted to the "chrome.nacl."
2480 // namespace so that it cannot impersonate other system or other chrome
2481 // service pipes.
2482 sandbox::ResultCode result = policy->AddRule(
2483 sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
2484 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
2485 L"\\\\.\\pipe\\chrome.nacl.*");
2486 if (result != sandbox::SBOX_ALL_OK) {
2487 *success = false;
2488 return;
2491 // Renderers need to send named pipe handles and shared memory
2492 // segment handles to NaCl loader processes.
2493 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
2494 sandbox::TargetPolicy::HANDLES_DUP_ANY,
2495 L"File");
2496 if (result != sandbox::SBOX_ALL_OK) {
2497 *success = false;
2498 return;
2501 #endif
2503 bool ChromeContentBrowserClient::CheckMediaAccessPermission(
2504 content::BrowserContext* browser_context,
2505 const GURL& security_origin,
2506 content::MediaStreamType type) {
2507 return MediaCaptureDevicesDispatcher::GetInstance()
2508 ->CheckMediaAccessPermission(
2509 browser_context, security_origin, type);
2512 content::WebContents* ChromeContentBrowserClient::OpenURL(
2513 content::BrowserContext* browser_context,
2514 const content::OpenURLParams& params) {
2515 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2517 #if !defined(OS_ANDROID) && !defined(OS_IOS)
2518 NavigateParams nav_params(Profile::FromBrowserContext(browser_context),
2519 params.url,
2520 params.transition);
2521 FillNavigateParamsFromOpenURLParams(&nav_params, params);
2522 nav_params.user_gesture = params.user_gesture;
2524 Navigate(&nav_params);
2525 return nav_params.target_contents;
2526 #else
2527 // TODO(mlamouri): write a chrome::Navigate() method for Android and iOS.
2528 // See https://crbug.com/448409.
2529 return nullptr;
2530 #endif // !defined(OS_ANDROID) && !defined(OS_IOS)
2533 content::DevToolsManagerDelegate*
2534 ChromeContentBrowserClient::GetDevToolsManagerDelegate() {
2535 #if defined(OS_ANDROID)
2536 return new DevToolsManagerDelegateAndroid();
2537 #else
2538 return new ChromeDevToolsManagerDelegate();
2539 #endif
2542 bool ChromeContentBrowserClient::IsPluginAllowedToCallRequestOSFileHandle(
2543 content::BrowserContext* browser_context,
2544 const GURL& url) {
2545 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
2546 return ChromeContentBrowserClientPluginsPart::
2547 IsPluginAllowedToCallRequestOSFileHandle(browser_context, url,
2548 allowed_file_handle_origins_);
2549 #else
2550 return false;
2551 #endif
2554 bool ChromeContentBrowserClient::IsPluginAllowedToUseDevChannelAPIs(
2555 content::BrowserContext* browser_context,
2556 const GURL& url) {
2557 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
2558 return ChromeContentBrowserClientPluginsPart::
2559 IsPluginAllowedToUseDevChannelAPIs(browser_context, url,
2560 allowed_dev_channel_origins_);
2561 #else
2562 return false;
2563 #endif
2566 net::CookieStore*
2567 ChromeContentBrowserClient::OverrideCookieStoreForRenderProcess(
2568 int render_process_id) {
2569 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
2570 if (!prerender_tracker_)
2571 return NULL;
2572 return prerender_tracker_->GetPrerenderCookieStoreForRenderProcess(
2573 render_process_id).get();
2576 void ChromeContentBrowserClient::OverridePageVisibilityState(
2577 RenderFrameHost* render_frame_host,
2578 blink::WebPageVisibilityState* visibility_state) {
2579 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
2581 WebContents* web_contents =
2582 WebContents::FromRenderFrameHost(render_frame_host);
2583 DCHECK(web_contents);
2585 Profile* profile =
2586 Profile::FromBrowserContext(web_contents->GetBrowserContext());
2587 prerender::PrerenderManager* prerender_manager =
2588 prerender::PrerenderManagerFactory::GetForProfile(profile);
2589 if (prerender_manager &&
2590 prerender_manager->IsWebContentsPrerendering(web_contents, nullptr)) {
2591 *visibility_state = blink::WebPageVisibilityStatePrerender;
2595 #if defined(ENABLE_WEBRTC)
2596 void ChromeContentBrowserClient::MaybeCopyDisableWebRtcEncryptionSwitch(
2597 base::CommandLine* to_command_line,
2598 const base::CommandLine& from_command_line,
2599 VersionInfo::Channel channel) {
2600 #if defined(OS_ANDROID)
2601 const VersionInfo::Channel kMaxDisableEncryptionChannel =
2602 VersionInfo::CHANNEL_BETA;
2603 #else
2604 const VersionInfo::Channel kMaxDisableEncryptionChannel =
2605 VersionInfo::CHANNEL_DEV;
2606 #endif
2607 if (channel <= kMaxDisableEncryptionChannel) {
2608 static const char* const kWebRtcDevSwitchNames[] = {
2609 switches::kDisableWebRtcEncryption,
2611 to_command_line->CopySwitchesFrom(from_command_line,
2612 kWebRtcDevSwitchNames,
2613 arraysize(kWebRtcDevSwitchNames));
2616 #endif // defined(ENABLE_WEBRTC)
2618 } // namespace chrome