app_list: Re-enable people search.
[chromium-blink-merge.git] / chrome / browser / chrome_content_browser_client.cc
blob27f668fcc9ccc8a95712ec9c6610174e3442d2bb
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/browser/media/protected_media_identifier_permission_context.h"
162 #include "chrome/browser/media/protected_media_identifier_permission_context_factory.h"
163 #include "chrome/common/descriptors_android.h"
164 #include "components/crash/browser/crash_dump_manager_android.h"
165 #elif defined(OS_POSIX)
166 #include "chrome/browser/chrome_browser_main_posix.h"
167 #endif
169 #if defined(OS_POSIX) && !defined(OS_MACOSX)
170 #include "base/debug/leak_annotations.h"
171 #include "components/crash/app/breakpad_linux.h"
172 #include "components/crash/browser/crash_handler_host_linux.h"
173 #endif
175 #if defined(OS_ANDROID)
176 #include "ui/base/ui_base_paths.h"
177 #include "ui/gfx/android/device_display_info.h"
178 #endif
180 #if defined(OS_ANDROID)
181 #include "chrome/browser/android/dev_tools_manager_delegate_android.h"
182 #else
183 #include "chrome/browser/devtools/chrome_devtools_manager_delegate.h"
184 #endif
186 #if !defined(OS_CHROMEOS)
187 #include "chrome/browser/signin/chrome_signin_client.h"
188 #include "chrome/browser/signin/chrome_signin_client_factory.h"
189 #include "chrome/browser/signin/signin_manager_factory.h"
190 #include "components/signin/core/browser/signin_manager.h"
191 #endif
193 #if defined(TOOLKIT_VIEWS)
194 #include "chrome/browser/ui/views/chrome_browser_main_extra_parts_views.h"
195 #endif
197 #if defined(USE_ATHENA)
198 #include "athena/content/public/web_contents_view_delegate_creator.h"
199 #include "chrome/browser/ui/views/athena/chrome_browser_main_extra_parts_athena.h"
200 #elif 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 } // namespace
627 namespace chrome {
629 ChromeContentBrowserClient::ChromeContentBrowserClient()
630 : prerender_tracker_(NULL),
631 weak_factory_(this) {
632 #if defined(ENABLE_PLUGINS)
633 for (size_t i = 0; i < arraysize(kPredefinedAllowedDevChannelOrigins); ++i)
634 allowed_dev_channel_origins_.insert(kPredefinedAllowedDevChannelOrigins[i]);
635 for (size_t i = 0; i < arraysize(kPredefinedAllowedFileHandleOrigins); ++i)
636 allowed_file_handle_origins_.insert(kPredefinedAllowedFileHandleOrigins[i]);
637 for (size_t i = 0; i < arraysize(kPredefinedAllowedSocketOrigins); ++i)
638 allowed_socket_origins_.insert(kPredefinedAllowedSocketOrigins[i]);
640 extra_parts_.push_back(new ChromeContentBrowserClientPluginsPart);
641 #endif
643 #if !defined(OS_ANDROID)
644 TtsExtensionEngine* tts_extension_engine = TtsExtensionEngine::GetInstance();
645 TtsController::GetInstance()->SetTtsEngineDelegate(tts_extension_engine);
646 #endif
648 #if defined(ENABLE_EXTENSIONS)
649 extra_parts_.push_back(new ChromeContentBrowserClientExtensionsPart);
650 #endif
653 ChromeContentBrowserClient::~ChromeContentBrowserClient() {
654 for (int i = static_cast<int>(extra_parts_.size()) - 1; i >= 0; --i)
655 delete extra_parts_[i];
656 extra_parts_.clear();
659 // static
660 void ChromeContentBrowserClient::RegisterProfilePrefs(
661 user_prefs::PrefRegistrySyncable* registry) {
662 registry->RegisterBooleanPref(
663 prefs::kDisable3DAPIs,
664 false,
665 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
666 registry->RegisterBooleanPref(
667 prefs::kEnableHyperlinkAuditing,
668 true,
669 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
670 registry->RegisterListPref(
671 prefs::kEnableDeprecatedWebPlatformFeatures,
672 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
675 // static
676 void ChromeContentBrowserClient::SetApplicationLocale(
677 const std::string& locale) {
678 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
680 // This object is guaranteed to outlive all threads so we don't have to
681 // worry about the lack of refcounting and can just post as Unretained.
683 // The common case is that this function is called early in Chrome startup
684 // before any threads are created (it will also be called later if the user
685 // changes the pref). In this case, there will be no threads created and
686 // posting will fail. When there are no threads, we can just set the string
687 // without worrying about threadsafety.
688 if (!BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
689 base::Bind(&SetApplicationLocaleOnIOThread, locale))) {
690 g_io_thread_application_locale.Get() = locale;
694 content::BrowserMainParts* ChromeContentBrowserClient::CreateBrowserMainParts(
695 const content::MainFunctionParams& parameters) {
696 ChromeBrowserMainParts* main_parts;
697 // Construct the Main browser parts based on the OS type.
698 #if defined(OS_WIN)
699 main_parts = new ChromeBrowserMainPartsWin(parameters);
700 #elif defined(OS_MACOSX)
701 main_parts = new ChromeBrowserMainPartsMac(parameters);
702 #elif defined(OS_CHROMEOS)
703 main_parts = new chromeos::ChromeBrowserMainPartsChromeos(parameters);
704 #elif defined(OS_LINUX)
705 main_parts = new ChromeBrowserMainPartsLinux(parameters);
706 #elif defined(OS_ANDROID)
707 main_parts = new ChromeBrowserMainPartsAndroid(parameters);
708 #elif defined(OS_POSIX)
709 main_parts = new ChromeBrowserMainPartsPosix(parameters);
710 #else
711 NOTREACHED();
712 main_parts = new ChromeBrowserMainParts(parameters);
713 #endif
715 chrome::AddProfilesExtraParts(main_parts);
717 // Construct additional browser parts. Stages are called in the order in
718 // which they are added.
719 #if defined(TOOLKIT_VIEWS)
720 main_parts->AddParts(new ChromeBrowserMainExtraPartsViews());
721 #endif
723 // TODO(oshima): Athena on chrome currently requires USE_ASH to build.
724 // We should reduce the dependency as much as possible.
725 #if defined(USE_ATHENA)
726 main_parts->AddParts(CreateChromeBrowserMainExtraPartsAthena());
727 #elif defined(USE_ASH)
728 main_parts->AddParts(new ChromeBrowserMainExtraPartsAsh());
729 #endif
731 #if defined(USE_AURA)
732 main_parts->AddParts(new ChromeBrowserMainExtraPartsAura());
733 #endif
735 #if defined(USE_X11)
736 main_parts->AddParts(new ChromeBrowserMainExtraPartsX11());
737 #endif
739 chrome::AddMetricsExtraParts(main_parts);
741 return main_parts;
744 std::string ChromeContentBrowserClient::GetStoragePartitionIdForSite(
745 content::BrowserContext* browser_context,
746 const GURL& site) {
747 std::string partition_id;
749 // The partition ID for webview guest processes is the string value of its
750 // SiteInstance URL - "chrome-guest://app_id/persist?partition".
751 if (site.SchemeIs(content::kGuestScheme)) {
752 partition_id = site.spec();
753 } else if (site.GetOrigin().spec() == kChromeUIChromeSigninURL &&
754 !switches::IsEnableWebviewBasedSignin()) {
755 // Chrome signin page has an embedded iframe of extension and web content,
756 // thus it must be isolated from other webUI pages.
757 partition_id = site.GetOrigin().spec();
760 DCHECK(IsValidStoragePartitionId(browser_context, partition_id));
761 return partition_id;
764 bool ChromeContentBrowserClient::IsValidStoragePartitionId(
765 content::BrowserContext* browser_context,
766 const std::string& partition_id) {
767 // The default ID is empty and is always valid.
768 if (partition_id.empty())
769 return true;
771 return GURL(partition_id).is_valid();
774 void ChromeContentBrowserClient::GetStoragePartitionConfigForSite(
775 content::BrowserContext* browser_context,
776 const GURL& site,
777 bool can_be_default,
778 std::string* partition_domain,
779 std::string* partition_name,
780 bool* in_memory) {
781 // Default to the browser-wide storage partition and override based on |site|
782 // below.
783 partition_domain->clear();
784 partition_name->clear();
785 *in_memory = false;
787 bool success = false;
788 #if defined(ENABLE_EXTENSIONS)
789 success = extensions::WebViewGuest::GetGuestPartitionConfigForSite(
790 site, partition_domain, partition_name, in_memory);
792 if (!success && site.SchemeIs(extensions::kExtensionScheme)) {
793 // If |can_be_default| is false, the caller is stating that the |site|
794 // should be parsed as if it had isolated storage. In particular it is
795 // important to NOT check ExtensionService for the is_storage_isolated()
796 // attribute because this code path is run during Extension uninstall
797 // to do cleanup after the Extension has already been unloaded from the
798 // ExtensionService.
799 bool is_isolated = !can_be_default;
800 if (can_be_default) {
801 if (extensions::util::SiteHasIsolatedStorage(site, browser_context))
802 is_isolated = true;
805 if (is_isolated) {
806 CHECK(site.has_host());
807 // For extensions with isolated storage, the the host of the |site| is
808 // the |partition_domain|. The |in_memory| and |partition_name| are only
809 // used in guest schemes so they are cleared here.
810 *partition_domain = site.host();
811 *in_memory = false;
812 partition_name->clear();
814 success = true;
816 #endif
818 if (!success && (site.GetOrigin().spec() == kChromeUIChromeSigninURL) &&
819 !switches::IsEnableWebviewBasedSignin()) {
820 // Chrome signin page has an embedded iframe of extension and web content,
821 // thus it must be isolated from other webUI pages.
822 *partition_domain = chrome::kChromeUIChromeSigninHost;
825 // Assert that if |can_be_default| is false, the code above must have found a
826 // non-default partition. If this fails, the caller has a serious logic
827 // error about which StoragePartition they expect to be in and it is not
828 // safe to continue.
829 CHECK(can_be_default || !partition_domain->empty());
832 content::WebContentsViewDelegate*
833 ChromeContentBrowserClient::GetWebContentsViewDelegate(
834 content::WebContents* web_contents) {
835 #if defined(USE_ATHENA)
836 return athena::CreateWebContentsViewDelegate(web_contents);
837 #else
838 return chrome::CreateWebContentsViewDelegate(web_contents);
839 #endif
842 void ChromeContentBrowserClient::RenderProcessWillLaunch(
843 content::RenderProcessHost* host) {
844 int id = host->GetID();
845 Profile* profile = Profile::FromBrowserContext(host->GetBrowserContext());
846 net::URLRequestContextGetter* context =
847 profile->GetRequestContextForRenderProcess(id);
849 host->AddFilter(new ChromeRenderMessageFilter(id, profile));
850 #if defined(ENABLE_EXTENSIONS)
851 host->AddFilter(new cast::CastTransportHostFilter);
852 #endif
853 #if defined(ENABLE_PRINTING)
854 host->AddFilter(new printing::PrintingMessageFilter(id, profile));
855 #endif
856 host->AddFilter(new SearchProviderInstallStateMessageFilter(id, profile));
857 #if defined(ENABLE_SPELLCHECK)
858 host->AddFilter(new SpellCheckMessageFilter(id));
859 #endif
860 #if defined(OS_MACOSX)
861 host->AddFilter(new SpellCheckMessageFilterMac(id));
862 #endif
863 host->AddFilter(new ChromeNetBenchmarkingMessageFilter(profile, context));
864 host->AddFilter(new prerender::PrerenderMessageFilter(id, profile));
865 host->AddFilter(new TtsMessageFilter(id, host->GetBrowserContext()));
866 #if defined(ENABLE_WEBRTC)
867 WebRtcLoggingHandlerHost* webrtc_logging_handler_host =
868 new WebRtcLoggingHandlerHost(profile);
869 host->SetWebRtcLogMessageCallback(base::Bind(
870 &WebRtcLoggingHandlerHost::LogMessage, webrtc_logging_handler_host));
871 host->AddFilter(webrtc_logging_handler_host);
872 host->SetUserData(host, new base::UserDataAdapter<WebRtcLoggingHandlerHost>(
873 webrtc_logging_handler_host));
874 #endif
875 #if !defined(DISABLE_NACL)
876 host->AddFilter(new nacl::NaClHostMessageFilter(
877 id, profile->IsOffTheRecord(),
878 profile->GetPath(),
879 context));
880 #endif
881 #if defined(OS_ANDROID)
882 host->AddFilter(new cdm::CdmMessageFilterAndroid());
883 #endif
884 if (switches::IsEnableAccountConsistency())
885 host->AddFilter(new PrincipalsMessageFilter(id));
887 host->Send(new ChromeViewMsg_SetIsIncognitoProcess(
888 profile->IsOffTheRecord()));
890 for (size_t i = 0; i < extra_parts_.size(); ++i)
891 extra_parts_[i]->RenderProcessWillLaunch(host);
893 RendererContentSettingRules rules;
894 if (host->IsIsolatedGuest()) {
895 #if defined(ENABLE_EXTENSIONS)
896 GetGuestViewDefaultContentSettingRules(profile->IsOffTheRecord(), &rules);
897 #else
898 NOTREACHED();
899 #endif
900 } else {
901 GetRendererContentSettingRules(
902 profile->GetHostContentSettingsMap(), &rules);
904 host->Send(new ChromeViewMsg_SetContentSettingRules(rules));
907 GURL ChromeContentBrowserClient::GetEffectiveURL(
908 content::BrowserContext* browser_context, const GURL& url) {
909 Profile* profile = Profile::FromBrowserContext(browser_context);
910 if (!profile)
911 return url;
913 // If the input |url| should be assigned to the Instant renderer, make its
914 // effective URL distinct from other URLs on the search provider's domain.
915 if (chrome::ShouldAssignURLToInstantRenderer(url, profile))
916 return chrome::GetEffectiveURLForInstant(url, profile);
918 #if !defined(OS_CHROMEOS)
919 // If the input |url| should be assigned to the Signin renderer, make its
920 // effective URL distinct from other URLs on the signin service's domain.
921 // Note that the signin renderer will be allowed to sign the user in to
922 // Chrome.
923 if (SigninManager::IsWebBasedSigninFlowURL(url))
924 return GetEffectiveURLForSignin(url);
925 #endif
927 #if defined(ENABLE_EXTENSIONS)
928 return ChromeContentBrowserClientExtensionsPart::GetEffectiveURL(
929 profile, url);
930 #else
931 return url;
932 #endif
935 bool ChromeContentBrowserClient::ShouldUseProcessPerSite(
936 content::BrowserContext* browser_context, const GURL& effective_url) {
937 // Non-extension, non-Instant URLs should generally use
938 // process-per-site-instance. Because we expect to use the effective URL,
939 // URLs for hosted apps (apart from bookmark apps) should have an extension
940 // scheme by now.
942 Profile* profile = Profile::FromBrowserContext(browser_context);
943 if (!profile)
944 return false;
946 if (chrome::ShouldUseProcessPerSiteForInstantURL(effective_url, profile))
947 return true;
949 #if !defined(OS_CHROMEOS)
950 if (SigninManager::IsWebBasedSigninFlowURL(effective_url))
951 return true;
952 #endif
954 #if defined(ENABLE_EXTENSIONS)
955 return ChromeContentBrowserClientExtensionsPart::ShouldUseProcessPerSite(
956 profile, effective_url);
957 #else
958 return false;
959 #endif
962 // These are treated as WebUI schemes but do not get WebUI bindings. Also,
963 // view-source is allowed for these schemes.
964 void ChromeContentBrowserClient::GetAdditionalWebUISchemes(
965 std::vector<std::string>* additional_schemes) {
966 additional_schemes->push_back(chrome::kChromeSearchScheme);
967 additional_schemes->push_back(dom_distiller::kDomDistillerScheme);
970 void ChromeContentBrowserClient::GetAdditionalWebUIHostsToIgnoreParititionCheck(
971 std::vector<std::string>* hosts) {
972 hosts->push_back(chrome::kChromeUIExtensionIconHost);
973 hosts->push_back(chrome::kChromeUIFaviconHost);
974 hosts->push_back(chrome::kChromeUIThemeHost);
975 hosts->push_back(chrome::kChromeUIThumbnailHost);
976 hosts->push_back(chrome::kChromeUIThumbnailHost2);
977 hosts->push_back(chrome::kChromeUIThumbnailListHost);
980 net::URLRequestContextGetter*
981 ChromeContentBrowserClient::CreateRequestContext(
982 content::BrowserContext* browser_context,
983 content::ProtocolHandlerMap* protocol_handlers,
984 content::URLRequestInterceptorScopedVector request_interceptors) {
985 Profile* profile = Profile::FromBrowserContext(browser_context);
986 return profile->CreateRequestContext(protocol_handlers,
987 request_interceptors.Pass());
990 net::URLRequestContextGetter*
991 ChromeContentBrowserClient::CreateRequestContextForStoragePartition(
992 content::BrowserContext* browser_context,
993 const base::FilePath& partition_path,
994 bool in_memory,
995 content::ProtocolHandlerMap* protocol_handlers,
996 content::URLRequestInterceptorScopedVector request_interceptors) {
997 Profile* profile = Profile::FromBrowserContext(browser_context);
998 return profile->CreateRequestContextForStoragePartition(
999 partition_path,
1000 in_memory,
1001 protocol_handlers,
1002 request_interceptors.Pass());
1005 bool ChromeContentBrowserClient::IsHandledURL(const GURL& url) {
1006 return ProfileIOData::IsHandledURL(url);
1009 bool ChromeContentBrowserClient::CanCommitURL(
1010 content::RenderProcessHost* process_host,
1011 const GURL& url) {
1012 #if defined(ENABLE_EXTENSIONS)
1013 return ChromeContentBrowserClientExtensionsPart::CanCommitURL(
1014 process_host, url);
1015 #else
1016 return true;
1017 #endif
1020 bool ChromeContentBrowserClient::ShouldAllowOpenURL(
1021 content::SiteInstance* site_instance, const GURL& url) {
1022 GURL from_url = site_instance->GetSiteURL();
1024 #if defined(ENABLE_EXTENSIONS)
1025 bool result;
1026 if (ChromeContentBrowserClientExtensionsPart::ShouldAllowOpenURL(
1027 site_instance, from_url, url, &result))
1028 return result;
1029 #endif
1031 // Do not allow chrome://chrome-signin navigate to other chrome:// URLs, since
1032 // the signin page may host untrusted web content.
1033 if (from_url.GetOrigin().spec() == chrome::kChromeUIChromeSigninURL &&
1034 url.SchemeIs(content::kChromeUIScheme) &&
1035 url.host() != chrome::kChromeUIChromeSigninHost) {
1036 VLOG(1) << "Blocked navigation to " << url.spec() << " from "
1037 << chrome::kChromeUIChromeSigninURL;
1038 return false;
1041 return true;
1044 bool ChromeContentBrowserClient::IsSuitableHost(
1045 content::RenderProcessHost* process_host,
1046 const GURL& site_url) {
1047 Profile* profile =
1048 Profile::FromBrowserContext(process_host->GetBrowserContext());
1049 // This may be NULL during tests. In that case, just assume any site can
1050 // share any host.
1051 if (!profile)
1052 return true;
1054 // Instant URLs should only be in the instant process and instant process
1055 // should only have Instant URLs.
1056 InstantService* instant_service =
1057 InstantServiceFactory::GetForProfile(profile);
1058 if (instant_service) {
1059 bool is_instant_process = instant_service->IsInstantProcess(
1060 process_host->GetID());
1061 bool should_be_in_instant_process =
1062 chrome::ShouldAssignURLToInstantRenderer(site_url, profile);
1063 if (is_instant_process || should_be_in_instant_process)
1064 return is_instant_process && should_be_in_instant_process;
1067 #if !defined(OS_CHROMEOS)
1068 SigninClient* signin_client =
1069 ChromeSigninClientFactory::GetForProfile(profile);
1070 if (signin_client && signin_client->IsSigninProcess(process_host->GetID()))
1071 return SigninManager::IsWebBasedSigninFlowURL(site_url);
1072 #endif
1074 #if defined(ENABLE_EXTENSIONS)
1075 return ChromeContentBrowserClientExtensionsPart::IsSuitableHost(
1076 profile, process_host, site_url);
1077 #else
1078 return true;
1079 #endif
1082 bool ChromeContentBrowserClient::MayReuseHost(
1083 content::RenderProcessHost* process_host) {
1084 // If there is currently a prerender in progress for the host provided,
1085 // it may not be shared. We require prerenders to be by themselves in a
1086 // separate process, so that we can monitor their resource usage, and so that
1087 // we can track the cookies that they change.
1088 Profile* profile = Profile::FromBrowserContext(
1089 process_host->GetBrowserContext());
1090 prerender::PrerenderManager* prerender_manager =
1091 prerender::PrerenderManagerFactory::GetForProfile(profile);
1092 if (prerender_manager &&
1093 !prerender_manager->MayReuseProcessHost(process_host)) {
1094 return false;
1097 return true;
1100 bool ChromeContentBrowserClient::ShouldTryToUseExistingProcessHost(
1101 content::BrowserContext* browser_context, const GURL& url) {
1102 // It has to be a valid URL for us to check for an extension.
1103 if (!url.is_valid())
1104 return false;
1106 #if defined(ENABLE_EXTENSIONS)
1107 Profile* profile = Profile::FromBrowserContext(browser_context);
1108 return ChromeContentBrowserClientExtensionsPart::
1109 ShouldTryToUseExistingProcessHost(
1110 profile, url);
1111 #else
1112 return false;
1113 #endif
1116 void ChromeContentBrowserClient::SiteInstanceGotProcess(
1117 SiteInstance* site_instance) {
1118 CHECK(site_instance->HasProcess());
1120 Profile* profile = Profile::FromBrowserContext(
1121 site_instance->GetBrowserContext());
1122 if (!profile)
1123 return;
1125 // Remember the ID of the Instant process to signal the renderer process
1126 // on startup in |AppendExtraCommandLineSwitches| below.
1127 if (chrome::ShouldAssignURLToInstantRenderer(
1128 site_instance->GetSiteURL(), profile)) {
1129 InstantService* instant_service =
1130 InstantServiceFactory::GetForProfile(profile);
1131 if (instant_service)
1132 instant_service->AddInstantProcess(site_instance->GetProcess()->GetID());
1135 #if !defined(OS_CHROMEOS)
1136 // We only expect there to be one signin process as we use process-per-site
1137 // for signin URLs. The signin process will be cleared from SigninManager
1138 // when the renderer is destroyed.
1139 if (SigninManager::IsWebBasedSigninFlowURL(site_instance->GetSiteURL())) {
1140 SigninClient* signin_client =
1141 ChromeSigninClientFactory::GetForProfile(profile);
1142 if (signin_client)
1143 signin_client->SetSigninProcess(site_instance->GetProcess()->GetID());
1144 #if defined(ENABLE_EXTENSIONS)
1145 ChromeContentBrowserClientExtensionsPart::SetSigninProcess(site_instance);
1146 #endif
1148 #endif
1150 for (size_t i = 0; i < extra_parts_.size(); ++i)
1151 extra_parts_[i]->SiteInstanceGotProcess(site_instance);
1154 void ChromeContentBrowserClient::SiteInstanceDeleting(
1155 SiteInstance* site_instance) {
1156 if (!site_instance->HasProcess())
1157 return;
1159 for (size_t i = 0; i < extra_parts_.size(); ++i)
1160 extra_parts_[i]->SiteInstanceDeleting(site_instance);
1163 bool ChromeContentBrowserClient::ShouldSwapBrowsingInstancesForNavigation(
1164 SiteInstance* site_instance,
1165 const GURL& current_url,
1166 const GURL& new_url) {
1167 #if defined(ENABLE_EXTENSIONS)
1168 return ChromeContentBrowserClientExtensionsPart::
1169 ShouldSwapBrowsingInstancesForNavigation(
1170 site_instance, current_url, new_url);
1171 #else
1172 return false;
1173 #endif
1176 bool ChromeContentBrowserClient::ShouldSwapProcessesForRedirect(
1177 content::ResourceContext* resource_context, const GURL& current_url,
1178 const GURL& new_url) {
1179 #if defined(ENABLE_EXTENSIONS)
1180 return ChromeContentBrowserClientExtensionsPart::
1181 ShouldSwapProcessesForRedirect(resource_context, current_url, new_url);
1182 #else
1183 return false;
1184 #endif
1187 bool ChromeContentBrowserClient::ShouldAssignSiteForURL(const GURL& url) {
1188 return !url.SchemeIs(chrome::kChromeNativeScheme);
1191 std::string ChromeContentBrowserClient::GetCanonicalEncodingNameByAliasName(
1192 const std::string& alias_name) {
1193 return CharacterEncoding::GetCanonicalEncodingNameByAliasName(alias_name);
1196 namespace {
1198 bool IsAutoReloadEnabled() {
1199 // Fetch the field trial, even though we don't use it. Calling FindFullName()
1200 // causes the field-trial mechanism to report which group we're in, which
1201 // might reflect a hard disable or hard enable via flag, both of which have
1202 // their own field trial groups. This lets us know what percentage of users
1203 // manually enable or disable auto-reload.
1204 std::string group = base::FieldTrialList::FindFullName(
1205 "AutoReloadExperiment");
1206 const base::CommandLine& browser_command_line =
1207 *base::CommandLine::ForCurrentProcess();
1208 if (browser_command_line.HasSwitch(switches::kEnableOfflineAutoReload))
1209 return true;
1210 if (browser_command_line.HasSwitch(switches::kDisableOfflineAutoReload))
1211 return false;
1212 return true;
1215 bool IsAutoReloadVisibleOnlyEnabled() {
1216 // See the block comment in IsAutoReloadEnabled().
1217 std::string group = base::FieldTrialList::FindFullName(
1218 "AutoReloadVisibleOnlyExperiment");
1219 const base::CommandLine& browser_command_line =
1220 *base::CommandLine::ForCurrentProcess();
1221 if (browser_command_line.HasSwitch(
1222 switches::kEnableOfflineAutoReloadVisibleOnly)) {
1223 return true;
1225 if (browser_command_line.HasSwitch(
1226 switches::kDisableOfflineAutoReloadVisibleOnly)) {
1227 return false;
1229 return true;
1232 } // namespace
1234 void ChromeContentBrowserClient::AppendExtraCommandLineSwitches(
1235 base::CommandLine* command_line,
1236 int child_process_id) {
1237 #if defined(OS_POSIX)
1238 if (breakpad::IsCrashReporterEnabled()) {
1239 scoped_ptr<metrics::ClientInfo> client_info =
1240 GoogleUpdateSettings::LoadMetricsClientInfo();
1241 command_line->AppendSwitchASCII(switches::kEnableCrashReporter,
1242 client_info ? client_info->client_id
1243 : std::string());
1245 #endif // defined(OS_POSIX)
1247 if (logging::DialogsAreSuppressed())
1248 command_line->AppendSwitch(switches::kNoErrorDialogs);
1250 std::string process_type =
1251 command_line->GetSwitchValueASCII(switches::kProcessType);
1252 const base::CommandLine& browser_command_line =
1253 *base::CommandLine::ForCurrentProcess();
1255 static const char* const kCommonSwitchNames[] = {
1256 switches::kUserAgent,
1257 switches::kUserDataDir, // Make logs go to the right file.
1259 command_line->CopySwitchesFrom(browser_command_line, kCommonSwitchNames,
1260 arraysize(kCommonSwitchNames));
1262 #if defined(ENABLE_IPC_FUZZER)
1263 static const char* const kIpcFuzzerSwitches[] = {
1264 switches::kIpcFuzzerTestcase,
1266 command_line->CopySwitchesFrom(browser_command_line, kIpcFuzzerSwitches,
1267 arraysize(kIpcFuzzerSwitches));
1268 #endif
1270 #if defined(OS_CHROMEOS)
1271 // On Chrome OS need to pass primary user homedir (in multi-profiles session).
1272 base::FilePath homedir;
1273 PathService::Get(base::DIR_HOME, &homedir);
1274 command_line->AppendSwitchASCII(chromeos::switches::kHomedir,
1275 homedir.value().c_str());
1276 #endif
1278 if (process_type == switches::kRendererProcess) {
1279 content::RenderProcessHost* process =
1280 content::RenderProcessHost::FromID(child_process_id);
1281 Profile* profile =
1282 process ? Profile::FromBrowserContext(process->GetBrowserContext())
1283 : NULL;
1284 for (size_t i = 0; i < extra_parts_.size(); ++i) {
1285 extra_parts_[i]->AppendExtraRendererCommandLineSwitches(
1286 command_line, process, profile);
1289 #if defined(OS_CHROMEOS)
1290 const std::string& login_profile =
1291 browser_command_line.GetSwitchValueASCII(
1292 chromeos::switches::kLoginProfile);
1293 if (!login_profile.empty())
1294 command_line->AppendSwitchASCII(
1295 chromeos::switches::kLoginProfile, login_profile);
1296 #endif
1298 #if defined(ENABLE_WEBRTC)
1299 MaybeCopyDisableWebRtcEncryptionSwitch(command_line,
1300 browser_command_line,
1301 VersionInfo::GetChannel());
1302 #endif
1304 if (process) {
1305 PrefService* prefs = profile->GetPrefs();
1306 // Currently this pref is only registered if applied via a policy.
1307 if (prefs->HasPrefPath(prefs::kDisable3DAPIs) &&
1308 prefs->GetBoolean(prefs::kDisable3DAPIs)) {
1309 // Turn this policy into a command line switch.
1310 command_line->AppendSwitch(switches::kDisable3DAPIs);
1313 const base::ListValue* switches =
1314 prefs->GetList(prefs::kEnableDeprecatedWebPlatformFeatures);
1315 if (switches) {
1316 // Enable any deprecated features that have been re-enabled by policy.
1317 for (base::ListValue::const_iterator it = switches->begin();
1318 it != switches->end(); ++it) {
1319 std::string switch_to_enable;
1320 if ((*it)->GetAsString(&switch_to_enable))
1321 command_line->AppendSwitch(switch_to_enable);
1325 // Disable client-side phishing detection in the renderer if it is
1326 // disabled in the Profile preferences or the browser process.
1327 if (!prefs->GetBoolean(prefs::kSafeBrowsingEnabled) ||
1328 !g_browser_process->safe_browsing_detection_service()) {
1329 command_line->AppendSwitch(
1330 switches::kDisableClientSidePhishingDetection);
1333 if (prefs->GetBoolean(prefs::kPrintPreviewDisabled))
1334 command_line->AppendSwitch(switches::kDisablePrintPreview);
1336 InstantService* instant_service =
1337 InstantServiceFactory::GetForProfile(profile);
1338 if (instant_service &&
1339 instant_service->IsInstantProcess(process->GetID()))
1340 command_line->AppendSwitch(switches::kInstantProcess);
1342 #if !defined(OS_CHROMEOS)
1343 SigninClient* signin_client =
1344 ChromeSigninClientFactory::GetForProfile(profile);
1345 if (signin_client && signin_client->IsSigninProcess(process->GetID()))
1346 command_line->AppendSwitch(switches::kSigninProcess);
1347 #endif
1350 if (IsAutoReloadEnabled())
1351 command_line->AppendSwitch(switches::kEnableOfflineAutoReload);
1352 if (IsAutoReloadVisibleOnlyEnabled()) {
1353 command_line->AppendSwitch(
1354 switches::kEnableOfflineAutoReloadVisibleOnly);
1358 // Enable load stale cache if this session is in the field trial or
1359 // the user explicitly enabled it. Note that as far as the renderer
1360 // is concerned, the feature is enabled if-and-only-if the
1361 // kEnableOfflineLoadStaleCache flag is on the command line;
1362 // the yes/no/default behavior is only at the browser command line
1363 // level.
1365 // Command line switches override
1366 if (browser_command_line.HasSwitch(
1367 switches::kEnableOfflineLoadStaleCache)) {
1368 command_line->AppendSwitch(switches::kEnableOfflineLoadStaleCache);
1369 } else if (!browser_command_line.HasSwitch(
1370 switches::kDisableOfflineLoadStaleCache)) {
1371 std::string group =
1372 base::FieldTrialList::FindFullName("LoadStaleCacheExperiment");
1374 if (group == "Enabled")
1375 command_line->AppendSwitch(switches::kEnableOfflineLoadStaleCache);
1379 // Please keep this in alphabetical order.
1380 static const char* const kSwitchNames[] = {
1381 autofill::switches::kDisableFillOnAccountSelect,
1382 autofill::switches::kDisablePasswordGeneration,
1383 autofill::switches::kEnableFillOnAccountSelect,
1384 autofill::switches::kEnableFillOnAccountSelectNoHighlighting,
1385 autofill::switches::kEnablePasswordGeneration,
1386 autofill::switches::kEnablePasswordSaveOnInPageNavigation,
1387 autofill::switches::kEnableSingleClickAutofill,
1388 autofill::switches::kIgnoreAutocompleteOffForAutofill,
1389 autofill::switches::kLocalHeuristicsOnlyForPasswordGeneration,
1390 autofill::switches::kRespectAutocompleteOffForAutofill,
1391 #if defined(ENABLE_EXTENSIONS)
1392 extensions::switches::kAllowHTTPBackgroundPage,
1393 extensions::switches::kAllowLegacyExtensionManifests,
1394 extensions::switches::kEnableSurfaceWorker,
1395 extensions::switches::kEnableAppWindowControls,
1396 extensions::switches::kEnableEmbeddedExtensionOptions,
1397 extensions::switches::kEnableExperimentalExtensionApis,
1398 extensions::switches::kEnableScriptsRequireAction,
1399 extensions::switches::kExtensionsOnChromeURLs,
1400 extensions::switches::kWhitelistedExtensionID,
1401 #endif
1402 switches::kAppsCheckoutURL,
1403 switches::kAppsGalleryURL,
1404 switches::kCloudPrintURL,
1405 switches::kCloudPrintXmppEndpoint,
1406 switches::kDisableBundledPpapiFlash,
1407 switches::kDisableCastStreamingHWEncoding,
1408 switches::kDisableJavaScriptHarmonyShipping,
1409 switches::kDisableOutOfProcessPdf,
1410 switches::kEnableBenchmarking,
1411 switches::kEnableNaCl,
1412 #if !defined(DISABLE_NACL)
1413 switches::kEnableNaClDebug,
1414 switches::kEnableNaClNonSfiMode,
1415 #endif
1416 switches::kEnableNetBenchmarking,
1417 switches::kEnableNewBookmarkApps,
1418 switches::kEnableOutOfProcessPdf,
1419 switches::kEnablePluginPlaceholderShadowDom,
1420 switches::kEnableShowModalDialog,
1421 switches::kEnableWebBasedSignin,
1422 switches::kJavaScriptHarmony,
1423 switches::kMessageLoopHistogrammer,
1424 switches::kPlaybackMode,
1425 switches::kPpapiFlashArgs,
1426 switches::kPpapiFlashPath,
1427 switches::kPpapiFlashVersion,
1428 switches::kProfilingAtStart,
1429 switches::kProfilingFile,
1430 switches::kProfilingFlush,
1431 switches::kRecordMode,
1432 translate::switches::kTranslateSecurityOrigin,
1435 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1436 arraysize(kSwitchNames));
1437 } else if (process_type == switches::kUtilityProcess) {
1438 #if defined(ENABLE_EXTENSIONS)
1439 static const char* const kSwitchNames[] = {
1440 extensions::switches::kAllowHTTPBackgroundPage,
1441 extensions::switches::kEnableExperimentalExtensionApis,
1442 extensions::switches::kExtensionsOnChromeURLs,
1443 extensions::switches::kWhitelistedExtensionID,
1446 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1447 arraysize(kSwitchNames));
1448 #endif
1449 } else if (process_type == switches::kPluginProcess) {
1450 #if defined(OS_CHROMEOS)
1451 static const char* const kSwitchNames[] = {
1452 chromeos::switches::kLoginProfile,
1455 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1456 arraysize(kSwitchNames));
1457 #endif
1458 } else if (process_type == switches::kZygoteProcess) {
1459 static const char* const kSwitchNames[] = {
1460 // Load (in-process) Pepper plugins in-process in the zygote pre-sandbox.
1461 switches::kDisableBundledPpapiFlash,
1462 #if !defined(DISABLE_NACL)
1463 switches::kEnableNaClDebug,
1464 switches::kEnableNaClNonSfiMode,
1465 switches::kNaClDangerousNoSandboxNonSfi,
1466 switches::kUseNaClHelperNonSfi,
1467 #endif
1468 switches::kPpapiFlashPath,
1469 switches::kPpapiFlashVersion,
1472 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1473 arraysize(kSwitchNames));
1474 } else if (process_type == switches::kGpuProcess) {
1475 // If --ignore-gpu-blacklist is passed in, don't send in crash reports
1476 // because GPU is expected to be unreliable.
1477 if (browser_command_line.HasSwitch(switches::kIgnoreGpuBlacklist) &&
1478 !command_line->HasSwitch(switches::kDisableBreakpad))
1479 command_line->AppendSwitch(switches::kDisableBreakpad);
1482 // The command line switch kEnableBenchmarking needs to be specified along
1483 // with the kEnableStatsTable switch to ensure that the stats table global
1484 // is initialized correctly.
1485 if (command_line->HasSwitch(switches::kEnableBenchmarking))
1486 DCHECK(command_line->HasSwitch(switches::kEnableStatsTable));
1489 std::string ChromeContentBrowserClient::GetApplicationLocale() {
1490 if (BrowserThread::CurrentlyOn(BrowserThread::IO))
1491 return g_io_thread_application_locale.Get();
1492 return g_browser_process->GetApplicationLocale();
1495 std::string ChromeContentBrowserClient::GetAcceptLangs(
1496 content::BrowserContext* context) {
1497 Profile* profile = Profile::FromBrowserContext(context);
1498 return profile->GetPrefs()->GetString(prefs::kAcceptLanguages);
1501 const gfx::ImageSkia* ChromeContentBrowserClient::GetDefaultFavicon() {
1502 ResourceBundle& rb = ResourceBundle::GetSharedInstance();
1503 return rb.GetNativeImageNamed(IDR_DEFAULT_FAVICON).ToImageSkia();
1506 bool ChromeContentBrowserClient::AllowAppCache(
1507 const GURL& manifest_url,
1508 const GURL& first_party,
1509 content::ResourceContext* context) {
1510 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1511 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1512 return io_data->GetCookieSettings()->
1513 IsSettingCookieAllowed(manifest_url, first_party);
1516 bool ChromeContentBrowserClient::AllowServiceWorker(
1517 const GURL& scope,
1518 const GURL& first_party_url,
1519 content::ResourceContext* context) {
1520 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1521 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1522 return io_data->GetCookieSettings()->
1523 IsSettingCookieAllowed(scope, first_party_url);
1526 bool ChromeContentBrowserClient::AllowGetCookie(
1527 const GURL& url,
1528 const GURL& first_party,
1529 const net::CookieList& cookie_list,
1530 content::ResourceContext* context,
1531 int render_process_id,
1532 int render_frame_id) {
1533 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1534 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1535 bool allow = io_data->GetCookieSettings()->
1536 IsReadingCookieAllowed(url, first_party);
1538 BrowserThread::PostTask(
1539 BrowserThread::UI, FROM_HERE,
1540 base::Bind(&TabSpecificContentSettings::CookiesRead, render_process_id,
1541 render_frame_id, url, first_party, cookie_list, !allow, true));
1542 return allow;
1545 bool ChromeContentBrowserClient::AllowSetCookie(
1546 const GURL& url,
1547 const GURL& first_party,
1548 const std::string& cookie_line,
1549 content::ResourceContext* context,
1550 int render_process_id,
1551 int render_frame_id,
1552 net::CookieOptions* options) {
1553 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1554 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1555 CookieSettings* cookie_settings = io_data->GetCookieSettings();
1556 bool allow = cookie_settings->IsSettingCookieAllowed(url, first_party);
1558 if (prerender_tracker_) {
1559 prerender_tracker_->OnCookieChangedForURL(
1560 render_process_id,
1561 context->GetRequestContext()->cookie_store()->GetCookieMonster(),
1562 url);
1565 BrowserThread::PostTask(
1566 BrowserThread::UI, FROM_HERE,
1567 base::Bind(&TabSpecificContentSettings::CookieChanged, render_process_id,
1568 render_frame_id, url, first_party, cookie_line, *options,
1569 !allow));
1570 return allow;
1573 bool ChromeContentBrowserClient::AllowSaveLocalState(
1574 content::ResourceContext* context) {
1575 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1576 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1577 CookieSettings* cookie_settings = io_data->GetCookieSettings();
1578 ContentSetting setting = cookie_settings->GetDefaultCookieSetting(NULL);
1580 // TODO(bauerb): Should we also disallow local state if the default is BLOCK?
1581 // Could we even support per-origin settings?
1582 return setting != CONTENT_SETTING_SESSION_ONLY;
1585 bool ChromeContentBrowserClient::AllowWorkerDatabase(
1586 const GURL& url,
1587 const base::string16& name,
1588 const base::string16& display_name,
1589 unsigned long estimated_size,
1590 content::ResourceContext* context,
1591 const std::vector<std::pair<int, int> >& render_frames) {
1592 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1593 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1594 CookieSettings* cookie_settings = io_data->GetCookieSettings();
1595 bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1597 // Record access to database for potential display in UI.
1598 std::vector<std::pair<int, int> >::const_iterator i;
1599 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1600 BrowserThread::PostTask(
1601 BrowserThread::UI, FROM_HERE,
1602 base::Bind(&TabSpecificContentSettings::WebDatabaseAccessed,
1603 i->first, i->second, url, name, display_name, !allow));
1606 return allow;
1609 void ChromeContentBrowserClient::AllowWorkerFileSystem(
1610 const GURL& url,
1611 content::ResourceContext* context,
1612 const std::vector<std::pair<int, int> >& render_frames,
1613 base::Callback<void(bool)> callback) {
1614 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1615 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1616 CookieSettings* cookie_settings = io_data->GetCookieSettings();
1617 bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1619 #if defined(ENABLE_EXTENSIONS)
1620 GuestPermissionRequestHelper(url, render_frames, callback, allow);
1621 #else
1622 FileSystemAccessed(url, render_frames, callback, allow);
1623 #endif
1626 #if defined(ENABLE_EXTENSIONS)
1627 void ChromeContentBrowserClient::GuestPermissionRequestHelper(
1628 const GURL& url,
1629 const std::vector<std::pair<int, int> >& render_frames,
1630 base::Callback<void(bool)> callback,
1631 bool allow) {
1632 DCHECK(BrowserThread:: CurrentlyOn(BrowserThread::IO));
1633 std::vector<std::pair<int, int> >::const_iterator i;
1634 std::map<int, int> process_map;
1635 std::map<int, int>::const_iterator it;
1636 bool has_web_view_guest = false;
1637 // Record access to file system for potential display in UI.
1638 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1639 if (process_map.find(i->first) != process_map.end())
1640 continue;
1642 process_map.insert(std::pair<int, int>(i->first, i->second));
1644 if (extensions::WebViewRendererState::GetInstance()->IsGuest(i->first))
1645 has_web_view_guest = true;
1647 if (!has_web_view_guest) {
1648 FileSystemAccessed(url, render_frames, callback, allow);
1649 return;
1651 DCHECK_EQ(1U, process_map.size());
1652 it = process_map.begin();
1653 BrowserThread::PostTask(
1654 BrowserThread::UI,
1655 FROM_HERE,
1656 base::Bind(&ChromeContentBrowserClient::
1657 RequestFileSystemPermissionOnUIThread,
1658 it->first,
1659 it->second,
1660 url,
1661 allow,
1662 base::Bind(&ChromeContentBrowserClient::FileSystemAccessed,
1663 weak_factory_.GetWeakPtr(),
1664 url,
1665 render_frames,
1666 callback)));
1669 void ChromeContentBrowserClient::RequestFileSystemPermissionOnUIThread(
1670 int render_process_id,
1671 int render_frame_id,
1672 const GURL& url,
1673 bool allowed_by_default,
1674 const base::Callback<void(bool)>& callback) {
1675 DCHECK(BrowserThread:: CurrentlyOn(BrowserThread::UI));
1676 extensions::WebViewPermissionHelper* web_view_permission_helper =
1677 extensions::WebViewPermissionHelper::FromFrameID(
1678 render_process_id, render_frame_id);
1679 web_view_permission_helper->RequestFileSystemPermission(url,
1680 allowed_by_default,
1681 callback);
1683 #endif
1685 void ChromeContentBrowserClient::FileSystemAccessed(
1686 const GURL& url,
1687 const std::vector<std::pair<int, int> >& render_frames,
1688 base::Callback<void(bool)> callback,
1689 bool allow) {
1690 // Record access to file system for potential display in UI.
1691 std::vector<std::pair<int, int> >::const_iterator i;
1692 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1693 BrowserThread::PostTask(
1694 BrowserThread::UI,
1695 FROM_HERE,
1696 base::Bind(&TabSpecificContentSettings::FileSystemAccessed,
1697 i->first, i->second, url, !allow));
1699 callback.Run(allow);
1702 bool ChromeContentBrowserClient::AllowWorkerIndexedDB(
1703 const GURL& url,
1704 const base::string16& name,
1705 content::ResourceContext* context,
1706 const std::vector<std::pair<int, int> >& render_frames) {
1707 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1708 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1709 CookieSettings* cookie_settings = io_data->GetCookieSettings();
1710 bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1712 // Record access to IndexedDB for potential display in UI.
1713 std::vector<std::pair<int, int> >::const_iterator i;
1714 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1715 BrowserThread::PostTask(
1716 BrowserThread::UI, FROM_HERE,
1717 base::Bind(&TabSpecificContentSettings::IndexedDBAccessed,
1718 i->first, i->second, url, name, !allow));
1721 return allow;
1724 net::URLRequestContext*
1725 ChromeContentBrowserClient::OverrideRequestContextForURL(
1726 const GURL& url, content::ResourceContext* context) {
1727 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1728 #if defined(ENABLE_EXTENSIONS)
1729 if (url.SchemeIs(extensions::kExtensionScheme)) {
1730 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1731 return io_data->extensions_request_context();
1733 #endif
1735 return NULL;
1738 QuotaPermissionContext*
1739 ChromeContentBrowserClient::CreateQuotaPermissionContext() {
1740 return new ChromeQuotaPermissionContext();
1743 void ChromeContentBrowserClient::AllowCertificateError(
1744 int render_process_id,
1745 int render_frame_id,
1746 int cert_error,
1747 const net::SSLInfo& ssl_info,
1748 const GURL& request_url,
1749 ResourceType resource_type,
1750 bool overridable,
1751 bool strict_enforcement,
1752 bool expired_previous_decision,
1753 const base::Callback<void(bool)>& callback,
1754 content::CertificateRequestResultType* result) {
1755 if (resource_type != content::RESOURCE_TYPE_MAIN_FRAME) {
1756 // A sub-resource has a certificate error. The user doesn't really
1757 // have a context for making the right decision, so block the
1758 // request hard, without an info bar to allow showing the insecure
1759 // content.
1760 *result = content::CERTIFICATE_REQUEST_RESULT_TYPE_DENY;
1761 return;
1764 // If the tab is being prerendered, cancel the prerender and the request.
1765 content::RenderFrameHost* render_frame_host =
1766 content::RenderFrameHost::FromID(render_process_id, render_frame_id);
1767 WebContents* tab = WebContents::FromRenderFrameHost(render_frame_host);
1768 if (!tab) {
1769 NOTREACHED();
1770 return;
1773 prerender::PrerenderContents* prerender_contents =
1774 prerender::PrerenderContents::FromWebContents(tab);
1775 if (prerender_contents) {
1776 prerender_contents->Destroy(prerender::FINAL_STATUS_SSL_ERROR);
1777 *result = content::CERTIFICATE_REQUEST_RESULT_TYPE_CANCEL;
1778 return;
1781 // Otherwise, display an SSL blocking page. The interstitial page takes
1782 // ownership of ssl_blocking_page.
1783 int options_mask = 0;
1784 if (overridable)
1785 options_mask |= SSLBlockingPage::OVERRIDABLE;
1786 if (strict_enforcement)
1787 options_mask |= SSLBlockingPage::STRICT_ENFORCEMENT;
1788 if (expired_previous_decision)
1789 options_mask |= SSLBlockingPage::EXPIRED_BUT_PREVIOUSLY_ALLOWED;
1791 SSLErrorHandler::HandleSSLError(
1792 tab, cert_error, ssl_info, request_url, options_mask, callback);
1795 void ChromeContentBrowserClient::SelectClientCertificate(
1796 int render_process_id,
1797 int render_frame_id,
1798 net::SSLCertRequestInfo* cert_request_info,
1799 const base::Callback<void(net::X509Certificate*)>& callback) {
1800 content::RenderFrameHost* rfh = content::RenderFrameHost::FromID(
1801 render_process_id, render_frame_id);
1802 WebContents* tab = WebContents::FromRenderFrameHost(rfh);
1803 if (!tab) {
1804 // TODO(davidben): This makes the request hang, but returning no certificate
1805 // also breaks. It should abort the request. See https://crbug.com/417092
1806 return;
1809 prerender::PrerenderContents* prerender_contents =
1810 prerender::PrerenderContents::FromWebContents(tab);
1811 if (prerender_contents) {
1812 prerender_contents->Destroy(
1813 prerender::FINAL_STATUS_SSL_CLIENT_CERTIFICATE_REQUESTED);
1814 return;
1817 GURL requesting_url("https://" + cert_request_info->host_and_port.ToString());
1818 DCHECK(requesting_url.is_valid())
1819 << "Invalid URL string: https://"
1820 << cert_request_info->host_and_port.ToString();
1822 Profile* profile = Profile::FromBrowserContext(tab->GetBrowserContext());
1823 scoped_ptr<base::Value> filter =
1824 profile->GetHostContentSettingsMap()->GetWebsiteSetting(
1825 requesting_url,
1826 requesting_url,
1827 CONTENT_SETTINGS_TYPE_AUTO_SELECT_CERTIFICATE,
1828 std::string(),
1829 NULL);
1831 if (filter.get()) {
1832 // Try to automatically select a client certificate.
1833 if (filter->IsType(base::Value::TYPE_DICTIONARY)) {
1834 base::DictionaryValue* filter_dict =
1835 static_cast<base::DictionaryValue*>(filter.get());
1837 const std::vector<scoped_refptr<net::X509Certificate> >&
1838 all_client_certs = cert_request_info->client_certs;
1839 for (size_t i = 0; i < all_client_certs.size(); ++i) {
1840 if (CertMatchesFilter(*all_client_certs[i].get(), *filter_dict)) {
1841 // Use the first certificate that is matched by the filter.
1842 callback.Run(all_client_certs[i].get());
1843 return;
1846 } else {
1847 NOTREACHED();
1851 chrome::ShowSSLClientCertificateSelector(tab, cert_request_info, callback);
1854 void ChromeContentBrowserClient::AddCertificate(
1855 net::CertificateMimeType cert_type,
1856 const void* cert_data,
1857 size_t cert_size,
1858 int render_process_id,
1859 int render_frame_id) {
1860 chrome::SSLAddCertificate(cert_type, cert_data, cert_size,
1861 render_process_id, render_frame_id);
1864 content::MediaObserver* ChromeContentBrowserClient::GetMediaObserver() {
1865 return MediaCaptureDevicesDispatcher::GetInstance();
1868 content::PlatformNotificationService*
1869 ChromeContentBrowserClient::GetPlatformNotificationService() {
1870 #if defined(ENABLE_NOTIFICATIONS)
1871 return PlatformNotificationServiceImpl::GetInstance();
1872 #else
1873 NOTIMPLEMENTED();
1874 return NULL;
1875 #endif
1878 void ChromeContentBrowserClient::RequestPermission(
1879 content::PermissionType permission,
1880 content::WebContents* web_contents,
1881 int bridge_id,
1882 const GURL& requesting_frame,
1883 bool user_gesture,
1884 const base::Callback<void(bool)>& result_callback) {
1885 int render_process_id = web_contents->GetRenderProcessHost()->GetID();
1886 int render_view_id = web_contents->GetRenderViewHost()->GetRoutingID();
1887 Profile* profile =
1888 Profile::FromBrowserContext(web_contents->GetBrowserContext());
1890 const PermissionRequestID request_id(render_process_id,
1891 render_view_id,
1892 bridge_id,
1893 requesting_frame);
1895 switch (permission) {
1896 case content::PERMISSION_MIDI_SYSEX:
1897 MidiPermissionContextFactory::GetForProfile(profile)
1898 ->RequestPermission(web_contents,
1899 request_id,
1900 requesting_frame,
1901 user_gesture,
1902 result_callback);
1903 break;
1904 case content::PERMISSION_NOTIFICATIONS:
1905 #if defined(ENABLE_NOTIFICATIONS)
1906 DesktopNotificationServiceFactory::GetForProfile(profile)
1907 ->RequestNotificationPermission(web_contents,
1908 request_id,
1909 requesting_frame,
1910 user_gesture,
1911 result_callback);
1912 #else
1913 NOTIMPLEMENTED();
1914 #endif
1915 break;
1916 case content::PERMISSION_GEOLOCATION:
1917 GeolocationPermissionContextFactory::GetForProfile(profile)
1918 ->RequestPermission(web_contents,
1919 request_id,
1920 requesting_frame.GetOrigin(),
1921 user_gesture,
1922 result_callback);
1923 break;
1924 case content::PERMISSION_PROTECTED_MEDIA:
1925 #if defined(OS_ANDROID)
1926 ProtectedMediaIdentifierPermissionContextFactory::GetForProfile(profile)
1927 ->RequestPermission(web_contents,
1928 request_id,
1929 requesting_frame.GetOrigin(),
1930 user_gesture,
1931 result_callback);
1932 #else
1933 NOTIMPLEMENTED();
1934 #endif
1935 break;
1936 case content::PERMISSION_PUSH_MESSAGING:
1937 gcm::PushMessagingPermissionContextFactory::GetForProfile(profile)
1938 ->RequestPermission(web_contents,
1939 request_id,
1940 requesting_frame.GetOrigin(),
1941 user_gesture,
1942 result_callback);
1943 break;
1944 case content::PERMISSION_NUM:
1945 NOTREACHED() << "Invalid RequestPermission for " << permission;
1946 break;
1950 content::PermissionStatus ChromeContentBrowserClient::GetPermissionStatus(
1951 content::PermissionType permission,
1952 content::BrowserContext* browser_context,
1953 const GURL& requesting_origin,
1954 const GURL& embedding_origin) {
1955 DCHECK(browser_context);
1956 Profile* profile = Profile::FromBrowserContext(browser_context);
1958 PermissionContextBase* context = nullptr;
1959 switch (permission) {
1960 case content::PERMISSION_MIDI_SYSEX:
1961 context = MidiPermissionContextFactory::GetForProfile(profile);
1962 break;
1963 case content::PERMISSION_NOTIFICATIONS:
1964 #if defined(ENABLE_NOTIFICATIONS)
1965 context = DesktopNotificationServiceFactory::GetForProfile(profile);
1966 #else
1967 NOTIMPLEMENTED();
1968 #endif
1969 break;
1970 case content::PERMISSION_GEOLOCATION:
1971 context = GeolocationPermissionContextFactory::GetForProfile(profile);
1972 break;
1973 case content::PERMISSION_PROTECTED_MEDIA:
1974 NOTIMPLEMENTED();
1975 break;
1976 case content::PERMISSION_PUSH_MESSAGING:
1977 context = gcm::PushMessagingPermissionContextFactory::GetForProfile(
1978 profile);
1979 break;
1980 case content::PERMISSION_NUM:
1981 NOTREACHED() << "Invalid RequestPermission for " << permission;
1982 break;
1985 ContentSetting result = context
1986 ? context->GetPermissionStatus(requesting_origin.GetOrigin(),
1987 embedding_origin.GetOrigin())
1988 : CONTENT_SETTING_DEFAULT;
1990 return ContentSettingToPermissionStatus(result);
1993 void ChromeContentBrowserClient::CancelPermissionRequest(
1994 content::PermissionType permission,
1995 content::WebContents* web_contents,
1996 int bridge_id,
1997 const GURL& requesting_frame) {
1998 int render_process_id = web_contents->GetRenderProcessHost()->GetID();
1999 int render_view_id = web_contents->GetRenderViewHost()->GetRoutingID();
2001 const PermissionRequestID request_id(render_process_id,
2002 render_view_id,
2003 bridge_id,
2004 requesting_frame);
2005 Profile* profile =
2006 Profile::FromBrowserContext(web_contents->GetBrowserContext());
2007 switch (permission) {
2008 case content::PERMISSION_MIDI_SYSEX:
2009 MidiPermissionContextFactory::GetForProfile(profile)
2010 ->CancelPermissionRequest(web_contents, request_id);
2011 break;
2012 case content::PERMISSION_NOTIFICATIONS:
2013 #if defined(ENABLE_NOTIFICATIONS)
2014 DesktopNotificationServiceFactory::GetForProfile(profile)
2015 ->CancelPermissionRequest(web_contents, request_id);
2016 #else
2017 NOTIMPLEMENTED();
2018 #endif
2019 break;
2020 case content::PERMISSION_GEOLOCATION:
2021 GeolocationPermissionContextFactory::GetForProfile(profile)
2022 ->CancelPermissionRequest(web_contents, request_id);
2023 break;
2024 case content::PERMISSION_PROTECTED_MEDIA:
2025 #if defined(OS_ANDROID)
2026 ProtectedMediaIdentifierPermissionContextFactory::GetForProfile(profile)
2027 ->CancelPermissionRequest(web_contents, request_id);
2028 #else
2029 NOTIMPLEMENTED();
2030 #endif
2031 break;
2032 case content::PERMISSION_PUSH_MESSAGING:
2033 NOTIMPLEMENTED() << "CancelPermission not implemented for " << permission;
2034 break;
2035 case content::PERMISSION_NUM:
2036 NOTREACHED() << "Invalid CancelPermission for " << permission;
2037 break;
2041 // Helper method to translate from Permissions to ContentSettings
2042 static ContentSettingsType PermissionToContentSetting(
2043 content::PermissionType permission) {
2044 switch (permission) {
2045 case content::PERMISSION_MIDI_SYSEX:
2046 return CONTENT_SETTINGS_TYPE_MIDI_SYSEX;
2047 case content::PERMISSION_PUSH_MESSAGING:
2048 return CONTENT_SETTINGS_TYPE_PUSH_MESSAGING;
2049 case content::PERMISSION_NOTIFICATIONS:
2050 return CONTENT_SETTINGS_TYPE_NOTIFICATIONS;
2051 case content::PERMISSION_GEOLOCATION:
2052 return CONTENT_SETTINGS_TYPE_GEOLOCATION;
2053 #if defined(OS_ANDROID) || defined(OS_CHROMEOS)
2054 case content::PERMISSION_PROTECTED_MEDIA:
2055 return CONTENT_SETTINGS_TYPE_PROTECTED_MEDIA_IDENTIFIER;
2056 #endif
2057 default:
2058 NOTREACHED() << "Unknown content setting for permission " << permission;
2059 return CONTENT_SETTINGS_TYPE_DEFAULT;
2063 void ChromeContentBrowserClient::RegisterPermissionUsage(
2064 content::PermissionType permission,
2065 content::WebContents* web_contents,
2066 const GURL& frame_url,
2067 const GURL& main_frame_url) {
2068 Profile::FromBrowserContext(web_contents->GetBrowserContext())
2069 ->GetHostContentSettingsMap()
2070 ->UpdateLastUsage(
2071 frame_url, main_frame_url, PermissionToContentSetting(permission));
2074 bool ChromeContentBrowserClient::CanCreateWindow(
2075 const GURL& opener_url,
2076 const GURL& opener_top_level_frame_url,
2077 const GURL& source_origin,
2078 WindowContainerType container_type,
2079 const GURL& target_url,
2080 const content::Referrer& referrer,
2081 WindowOpenDisposition disposition,
2082 const WebWindowFeatures& features,
2083 bool user_gesture,
2084 bool opener_suppressed,
2085 content::ResourceContext* context,
2086 int render_process_id,
2087 int opener_id,
2088 bool* no_javascript_access) {
2089 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
2091 *no_javascript_access = false;
2093 // If the opener is trying to create a background window but doesn't have
2094 // the appropriate permission, fail the attempt.
2095 if (container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {
2096 #if defined(ENABLE_EXTENSIONS)
2097 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
2098 InfoMap* map = io_data->GetExtensionInfoMap();
2099 if (!map->SecurityOriginHasAPIPermission(
2100 source_origin,
2101 render_process_id,
2102 APIPermission::kBackground)) {
2103 return false;
2106 // Note: this use of GetExtensionOrAppByURL is safe but imperfect. It may
2107 // return a recently installed Extension even if this CanCreateWindow call
2108 // was made by an old copy of the page in a normal web process. That's ok,
2109 // because the permission check above would have caused an early return
2110 // already. We must use the full URL to find hosted apps, though, and not
2111 // just the origin.
2112 const Extension* extension =
2113 map->extensions().GetExtensionOrAppByURL(opener_url);
2114 if (extension && !extensions::BackgroundInfo::AllowJSAccess(extension))
2115 *no_javascript_access = true;
2116 #endif
2118 return true;
2121 #if defined(ENABLE_EXTENSIONS)
2122 if (extensions::WebViewRendererState::GetInstance()->IsGuest(
2123 render_process_id))
2124 return true;
2125 #endif
2127 HostContentSettingsMap* content_settings =
2128 ProfileIOData::FromResourceContext(context)->GetHostContentSettingsMap();
2129 BlockedWindowParams blocked_params(target_url,
2130 referrer,
2131 disposition,
2132 features,
2133 user_gesture,
2134 opener_suppressed,
2135 render_process_id,
2136 opener_id);
2138 if (!user_gesture &&
2139 !base::CommandLine::ForCurrentProcess()->HasSwitch(
2140 switches::kDisablePopupBlocking)) {
2141 if (content_settings->GetContentSetting(opener_top_level_frame_url,
2142 opener_top_level_frame_url,
2143 CONTENT_SETTINGS_TYPE_POPUPS,
2144 std::string()) !=
2145 CONTENT_SETTING_ALLOW) {
2146 BrowserThread::PostTask(BrowserThread::UI,
2147 FROM_HERE,
2148 base::Bind(&HandleBlockedPopupOnUIThread,
2149 blocked_params));
2150 return false;
2154 #if defined(OS_ANDROID)
2155 if (SingleTabModeTabHelper::IsRegistered(render_process_id, opener_id)) {
2156 BrowserThread::PostTask(BrowserThread::UI,
2157 FROM_HERE,
2158 base::Bind(&HandleSingleTabModeBlockOnUIThread,
2159 blocked_params));
2160 return false;
2162 #endif
2164 return true;
2167 void ChromeContentBrowserClient::ResourceDispatcherHostCreated() {
2168 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
2169 prerender_tracker_ = g_browser_process->prerender_tracker();
2170 return g_browser_process->ResourceDispatcherHostCreated();
2173 content::SpeechRecognitionManagerDelegate*
2174 ChromeContentBrowserClient::CreateSpeechRecognitionManagerDelegate() {
2175 return new speech::ChromeSpeechRecognitionManagerDelegate();
2178 net::NetLog* ChromeContentBrowserClient::GetNetLog() {
2179 return g_browser_process->net_log();
2182 AccessTokenStore* ChromeContentBrowserClient::CreateAccessTokenStore() {
2183 return new ChromeAccessTokenStore();
2186 bool ChromeContentBrowserClient::IsFastShutdownPossible() {
2187 return true;
2190 void ChromeContentBrowserClient::OverrideWebkitPrefs(
2191 RenderViewHost* rvh, const GURL& url, WebPreferences* web_prefs) {
2192 Profile* profile = Profile::FromBrowserContext(
2193 rvh->GetProcess()->GetBrowserContext());
2194 PrefService* prefs = profile->GetPrefs();
2196 // Fill per-script font preferences. These are not registered on Android
2197 // - http://crbug.com/308033.
2198 #if !defined(OS_ANDROID)
2199 FontFamilyCache::FillFontFamilyMap(profile,
2200 prefs::kWebKitStandardFontFamilyMap,
2201 &web_prefs->standard_font_family_map);
2202 FontFamilyCache::FillFontFamilyMap(profile,
2203 prefs::kWebKitFixedFontFamilyMap,
2204 &web_prefs->fixed_font_family_map);
2205 FontFamilyCache::FillFontFamilyMap(profile,
2206 prefs::kWebKitSerifFontFamilyMap,
2207 &web_prefs->serif_font_family_map);
2208 FontFamilyCache::FillFontFamilyMap(profile,
2209 prefs::kWebKitSansSerifFontFamilyMap,
2210 &web_prefs->sans_serif_font_family_map);
2211 FontFamilyCache::FillFontFamilyMap(profile,
2212 prefs::kWebKitCursiveFontFamilyMap,
2213 &web_prefs->cursive_font_family_map);
2214 FontFamilyCache::FillFontFamilyMap(profile,
2215 prefs::kWebKitFantasyFontFamilyMap,
2216 &web_prefs->fantasy_font_family_map);
2217 FontFamilyCache::FillFontFamilyMap(profile,
2218 prefs::kWebKitPictographFontFamilyMap,
2219 &web_prefs->pictograph_font_family_map);
2220 #endif
2222 web_prefs->default_font_size =
2223 prefs->GetInteger(prefs::kWebKitDefaultFontSize);
2224 web_prefs->default_fixed_font_size =
2225 prefs->GetInteger(prefs::kWebKitDefaultFixedFontSize);
2226 web_prefs->minimum_font_size =
2227 prefs->GetInteger(prefs::kWebKitMinimumFontSize);
2228 web_prefs->minimum_logical_font_size =
2229 prefs->GetInteger(prefs::kWebKitMinimumLogicalFontSize);
2231 web_prefs->default_encoding = prefs->GetString(prefs::kDefaultCharset);
2233 web_prefs->javascript_can_open_windows_automatically =
2234 prefs->GetBoolean(prefs::kWebKitJavascriptCanOpenWindowsAutomatically);
2235 web_prefs->dom_paste_enabled =
2236 prefs->GetBoolean(prefs::kWebKitDomPasteEnabled);
2237 web_prefs->shrinks_standalone_images_to_fit =
2238 prefs->GetBoolean(prefs::kWebKitShrinksStandaloneImagesToFit);
2239 web_prefs->tabs_to_links = prefs->GetBoolean(prefs::kWebkitTabsToLinks);
2241 if (!prefs->GetBoolean(prefs::kWebKitJavascriptEnabled))
2242 web_prefs->javascript_enabled = false;
2243 if (!prefs->GetBoolean(prefs::kWebKitWebSecurityEnabled))
2244 web_prefs->web_security_enabled = false;
2245 if (!prefs->GetBoolean(prefs::kWebKitPluginsEnabled))
2246 web_prefs->plugins_enabled = false;
2247 if (!prefs->GetBoolean(prefs::kWebKitJavaEnabled))
2248 web_prefs->java_enabled = false;
2249 web_prefs->loads_images_automatically =
2250 prefs->GetBoolean(prefs::kWebKitLoadsImagesAutomatically);
2252 if (prefs->GetBoolean(prefs::kDisable3DAPIs))
2253 web_prefs->experimental_webgl_enabled = false;
2255 web_prefs->allow_displaying_insecure_content =
2256 prefs->GetBoolean(prefs::kWebKitAllowDisplayingInsecureContent);
2257 web_prefs->allow_running_insecure_content =
2258 prefs->GetBoolean(prefs::kWebKitAllowRunningInsecureContent);
2259 #if defined(OS_ANDROID)
2260 web_prefs->font_scale_factor =
2261 static_cast<float>(prefs->GetDouble(prefs::kWebKitFontScaleFactor));
2262 web_prefs->device_scale_adjustment = GetDeviceScaleAdjustment();
2263 web_prefs->force_enable_zoom =
2264 prefs->GetBoolean(prefs::kWebKitForceEnableZoom);
2265 #endif
2267 #if defined(OS_ANDROID)
2268 web_prefs->password_echo_enabled =
2269 prefs->GetBoolean(prefs::kWebKitPasswordEchoEnabled);
2270 #else
2271 web_prefs->password_echo_enabled = browser_defaults::kPasswordEchoEnabled;
2272 #endif
2274 web_prefs->asynchronous_spell_checking_enabled = true;
2275 web_prefs->unified_textchecker_enabled = true;
2277 web_prefs->uses_universal_detector =
2278 prefs->GetBoolean(prefs::kWebKitUsesUniversalDetector);
2279 web_prefs->text_areas_are_resizable =
2280 prefs->GetBoolean(prefs::kWebKitTextAreasAreResizable);
2281 web_prefs->hyperlink_auditing_enabled =
2282 prefs->GetBoolean(prefs::kEnableHyperlinkAuditing);
2284 // Make sure we will set the default_encoding with canonical encoding name.
2285 web_prefs->default_encoding =
2286 CharacterEncoding::GetCanonicalEncodingNameByAliasName(
2287 web_prefs->default_encoding);
2288 if (web_prefs->default_encoding.empty()) {
2289 prefs->ClearPref(prefs::kDefaultCharset);
2290 web_prefs->default_encoding = prefs->GetString(prefs::kDefaultCharset);
2292 DCHECK(!web_prefs->default_encoding.empty());
2294 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2295 switches::kEnablePotentiallyAnnoyingSecurityFeatures)) {
2296 web_prefs->strict_mixed_content_checking = true;
2297 web_prefs->strict_powerful_feature_restrictions = true;
2300 for (size_t i = 0; i < extra_parts_.size(); ++i)
2301 extra_parts_[i]->OverrideWebkitPrefs(rvh, url, web_prefs);
2304 void ChromeContentBrowserClient::BrowserURLHandlerCreated(
2305 BrowserURLHandler* handler) {
2306 for (size_t i = 0; i < extra_parts_.size(); ++i)
2307 extra_parts_[i]->BrowserURLHandlerCreated(handler);
2309 // about: handler. Must come before chrome: handler, since it will
2310 // rewrite about: urls to chrome: URLs and then expect chrome: to
2311 // actually handle them.
2312 handler->AddHandlerPair(&WillHandleBrowserAboutURL,
2313 BrowserURLHandler::null_handler());
2315 #if defined(OS_ANDROID)
2316 // Handler to rewrite chrome://newtab on Android.
2317 handler->AddHandlerPair(&chrome::android::HandleAndroidNewTabURL,
2318 BrowserURLHandler::null_handler());
2319 #else
2320 // Handler to rewrite chrome://newtab for InstantExtended.
2321 handler->AddHandlerPair(&chrome::HandleNewTabURLRewrite,
2322 &chrome::HandleNewTabURLReverseRewrite);
2323 #endif
2325 // chrome: & friends.
2326 handler->AddHandlerPair(&HandleWebUI, &HandleWebUIReverse);
2329 void ChromeContentBrowserClient::ClearCache(RenderViewHost* rvh) {
2330 Profile* profile = Profile::FromBrowserContext(
2331 rvh->GetSiteInstance()->GetProcess()->GetBrowserContext());
2332 BrowsingDataRemover* remover =
2333 BrowsingDataRemover::CreateForUnboundedRange(profile);
2334 remover->Remove(BrowsingDataRemover::REMOVE_CACHE,
2335 BrowsingDataHelper::UNPROTECTED_WEB);
2336 // BrowsingDataRemover takes care of deleting itself when done.
2339 void ChromeContentBrowserClient::ClearCookies(RenderViewHost* rvh) {
2340 Profile* profile = Profile::FromBrowserContext(
2341 rvh->GetSiteInstance()->GetProcess()->GetBrowserContext());
2342 BrowsingDataRemover* remover =
2343 BrowsingDataRemover::CreateForUnboundedRange(profile);
2344 int remove_mask = BrowsingDataRemover::REMOVE_SITE_DATA;
2345 remover->Remove(remove_mask, BrowsingDataHelper::UNPROTECTED_WEB);
2346 // BrowsingDataRemover takes care of deleting itself when done.
2349 base::FilePath ChromeContentBrowserClient::GetDefaultDownloadDirectory() {
2350 return DownloadPrefs::GetDefaultDownloadDirectory();
2353 std::string ChromeContentBrowserClient::GetDefaultDownloadName() {
2354 return l10n_util::GetStringUTF8(IDS_DEFAULT_DOWNLOAD_FILENAME);
2357 void ChromeContentBrowserClient::DidCreatePpapiPlugin(
2358 content::BrowserPpapiHost* browser_host) {
2359 #if defined(ENABLE_PLUGINS)
2360 ChromeContentBrowserClientPluginsPart::DidCreatePpapiPlugin(browser_host);
2361 #endif
2364 content::BrowserPpapiHost*
2365 ChromeContentBrowserClient::GetExternalBrowserPpapiHost(
2366 int plugin_process_id) {
2367 #if !defined(DISABLE_NACL)
2368 content::BrowserChildProcessHostIterator iter(PROCESS_TYPE_NACL_LOADER);
2369 while (!iter.Done()) {
2370 nacl::NaClProcessHost* host = static_cast<nacl::NaClProcessHost*>(
2371 iter.GetDelegate());
2372 if (host->process() &&
2373 host->process()->GetData().id == plugin_process_id) {
2374 // Found the plugin.
2375 return host->browser_ppapi_host();
2377 ++iter;
2379 #endif
2380 return NULL;
2383 bool ChromeContentBrowserClient::AllowPepperSocketAPI(
2384 content::BrowserContext* browser_context,
2385 const GURL& url,
2386 bool private_api,
2387 const content::SocketPermissionRequest* params) {
2388 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
2389 return ChromeContentBrowserClientPluginsPart::AllowPepperSocketAPI(
2390 browser_context, url, private_api, params, allowed_socket_origins_);
2391 #else
2392 return false;
2393 #endif
2396 ui::SelectFilePolicy* ChromeContentBrowserClient::CreateSelectFilePolicy(
2397 WebContents* web_contents) {
2398 return new ChromeSelectFilePolicy(web_contents);
2401 void ChromeContentBrowserClient::GetAdditionalAllowedSchemesForFileSystem(
2402 std::vector<std::string>* additional_allowed_schemes) {
2403 ContentBrowserClient::GetAdditionalAllowedSchemesForFileSystem(
2404 additional_allowed_schemes);
2405 additional_allowed_schemes->push_back(content::kChromeDevToolsScheme);
2406 additional_allowed_schemes->push_back(content::kChromeUIScheme);
2407 for (size_t i = 0; i < extra_parts_.size(); ++i) {
2408 extra_parts_[i]->GetAdditionalAllowedSchemesForFileSystem(
2409 additional_allowed_schemes);
2413 void ChromeContentBrowserClient::GetURLRequestAutoMountHandlers(
2414 std::vector<storage::URLRequestAutoMountHandler>* handlers) {
2415 for (size_t i = 0; i < extra_parts_.size(); ++i)
2416 extra_parts_[i]->GetURLRequestAutoMountHandlers(handlers);
2419 void ChromeContentBrowserClient::GetAdditionalFileSystemBackends(
2420 content::BrowserContext* browser_context,
2421 const base::FilePath& storage_partition_path,
2422 ScopedVector<storage::FileSystemBackend>* additional_backends) {
2423 #if defined(OS_CHROMEOS)
2424 storage::ExternalMountPoints* external_mount_points =
2425 content::BrowserContext::GetMountPoints(browser_context);
2426 DCHECK(external_mount_points);
2427 chromeos::FileSystemBackend* backend = new chromeos::FileSystemBackend(
2428 new drive::FileSystemBackendDelegate,
2429 new chromeos::file_system_provider::BackendDelegate,
2430 new chromeos::MTPFileSystemBackendDelegate(storage_partition_path),
2431 browser_context->GetSpecialStoragePolicy(),
2432 external_mount_points,
2433 storage::ExternalMountPoints::GetSystemInstance());
2434 backend->AddSystemMountPoints();
2435 DCHECK(backend->CanHandleType(storage::kFileSystemTypeExternal));
2436 additional_backends->push_back(backend);
2437 #endif
2439 for (size_t i = 0; i < extra_parts_.size(); ++i) {
2440 extra_parts_[i]->GetAdditionalFileSystemBackends(
2441 browser_context, storage_partition_path, additional_backends);
2445 #if defined(OS_POSIX) && !defined(OS_MACOSX)
2446 void ChromeContentBrowserClient::GetAdditionalMappedFilesForChildProcess(
2447 const base::CommandLine& command_line,
2448 int child_process_id,
2449 FileDescriptorInfo* mappings) {
2450 #if defined(OS_ANDROID)
2451 base::FilePath data_path;
2452 PathService::Get(ui::DIR_RESOURCE_PAKS_ANDROID, &data_path);
2453 DCHECK(!data_path.empty());
2455 int flags = base::File::FLAG_OPEN | base::File::FLAG_READ;
2456 base::FilePath chrome_resources_pak =
2457 data_path.AppendASCII("chrome_100_percent.pak");
2458 base::File file(chrome_resources_pak, flags);
2459 DCHECK(file.IsValid());
2460 mappings->Transfer(kAndroidChrome100PercentPakDescriptor,
2461 base::ScopedFD(file.TakePlatformFile()));
2463 const std::string locale = GetApplicationLocale();
2464 base::FilePath locale_pak = ResourceBundle::GetSharedInstance().
2465 GetLocaleFilePath(locale, false);
2466 file.Initialize(locale_pak, flags);
2467 DCHECK(file.IsValid());
2468 mappings->Transfer(kAndroidLocalePakDescriptor,
2469 base::ScopedFD(file.TakePlatformFile()));
2471 base::FilePath resources_pack_path;
2472 PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
2473 file.Initialize(resources_pack_path, flags);
2474 DCHECK(file.IsValid());
2475 mappings->Transfer(kAndroidUIResourcesPakDescriptor,
2476 base::ScopedFD(file.TakePlatformFile()));
2478 if (breakpad::IsCrashReporterEnabled()) {
2479 file = breakpad::CrashDumpManager::GetInstance()->CreateMinidumpFile(
2480 child_process_id);
2481 if (file.IsValid()) {
2482 mappings->Transfer(kAndroidMinidumpDescriptor,
2483 base::ScopedFD(file.TakePlatformFile()));
2484 } else {
2485 LOG(ERROR) << "Failed to create file for minidump, crash reporting will "
2486 "be disabled for this process.";
2490 base::FilePath app_data_path;
2491 PathService::Get(base::DIR_ANDROID_APP_DATA, &app_data_path);
2492 DCHECK(!app_data_path.empty());
2494 flags = base::File::FLAG_OPEN | base::File::FLAG_READ;
2495 base::FilePath icudata_path =
2496 app_data_path.AppendASCII(base::i18n::kIcuDataFileName);
2497 base::File icudata_file(icudata_path, flags);
2498 DCHECK(icudata_file.IsValid());
2499 mappings->Transfer(kAndroidICUDataDescriptor,
2500 base::ScopedFD(icudata_file.TakePlatformFile()));
2502 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
2503 base::FilePath v8_data_path;
2504 PathService::Get(base::DIR_ANDROID_APP_DATA, &v8_data_path);
2505 DCHECK(!v8_data_path.empty());
2507 int file_flags = base::File::FLAG_OPEN | base::File::FLAG_READ;
2508 base::FilePath v8_natives_data_path =
2509 v8_data_path.AppendASCII(gin::IsolateHolder::kNativesFileName);
2510 base::FilePath v8_snapshot_data_path =
2511 v8_data_path.AppendASCII(gin::IsolateHolder::kSnapshotFileName);
2512 base::File v8_natives_data_file(v8_natives_data_path, file_flags);
2513 base::File v8_snapshot_data_file(v8_snapshot_data_path, file_flags);
2514 DCHECK(v8_natives_data_file.IsValid());
2515 DCHECK(v8_snapshot_data_file.IsValid());
2516 mappings->Transfer(kV8NativesDataDescriptor,
2517 base::ScopedFD(v8_natives_data_file.TakePlatformFile()));
2518 mappings->Transfer(kV8SnapshotDataDescriptor,
2519 base::ScopedFD(v8_snapshot_data_file.TakePlatformFile()));
2520 #endif // V8_USE_EXTERNAL_STARTUP_DATA
2522 #else
2523 int crash_signal_fd = GetCrashSignalFD(command_line);
2524 if (crash_signal_fd >= 0) {
2525 mappings->Share(kCrashDumpSignal, crash_signal_fd);
2527 #endif // defined(OS_ANDROID)
2529 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
2531 #if defined(OS_WIN)
2532 const wchar_t* ChromeContentBrowserClient::GetResourceDllName() {
2533 return chrome::kBrowserResourcesDll;
2536 void ChromeContentBrowserClient::PreSpawnRenderer(
2537 sandbox::TargetPolicy* policy,
2538 bool* success) {
2539 // This code is duplicated in nacl_exe_win_64.cc.
2540 // Allow the server side of a pipe restricted to the "chrome.nacl."
2541 // namespace so that it cannot impersonate other system or other chrome
2542 // service pipes.
2543 sandbox::ResultCode result = policy->AddRule(
2544 sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
2545 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
2546 L"\\\\.\\pipe\\chrome.nacl.*");
2547 if (result != sandbox::SBOX_ALL_OK) {
2548 *success = false;
2549 return;
2552 // Renderers need to send named pipe handles and shared memory
2553 // segment handles to NaCl loader processes.
2554 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
2555 sandbox::TargetPolicy::HANDLES_DUP_ANY,
2556 L"File");
2557 if (result != sandbox::SBOX_ALL_OK) {
2558 *success = false;
2559 return;
2562 #endif
2564 bool ChromeContentBrowserClient::CheckMediaAccessPermission(
2565 content::BrowserContext* browser_context,
2566 const GURL& security_origin,
2567 content::MediaStreamType type) {
2568 return MediaCaptureDevicesDispatcher::GetInstance()
2569 ->CheckMediaAccessPermission(
2570 browser_context, security_origin, type);
2573 content::DevToolsManagerDelegate*
2574 ChromeContentBrowserClient::GetDevToolsManagerDelegate() {
2575 #if defined(OS_ANDROID)
2576 return new DevToolsManagerDelegateAndroid();
2577 #else
2578 return new ChromeDevToolsManagerDelegate();
2579 #endif
2582 bool ChromeContentBrowserClient::IsPluginAllowedToCallRequestOSFileHandle(
2583 content::BrowserContext* browser_context,
2584 const GURL& url) {
2585 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
2586 return ChromeContentBrowserClientPluginsPart::
2587 IsPluginAllowedToCallRequestOSFileHandle(browser_context, url,
2588 allowed_file_handle_origins_);
2589 #else
2590 return false;
2591 #endif
2594 bool ChromeContentBrowserClient::IsPluginAllowedToUseDevChannelAPIs(
2595 content::BrowserContext* browser_context,
2596 const GURL& url) {
2597 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
2598 return ChromeContentBrowserClientPluginsPart::
2599 IsPluginAllowedToUseDevChannelAPIs(browser_context, url,
2600 allowed_dev_channel_origins_);
2601 #else
2602 return false;
2603 #endif
2606 net::CookieStore*
2607 ChromeContentBrowserClient::OverrideCookieStoreForRenderProcess(
2608 int render_process_id) {
2609 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
2610 if (!prerender_tracker_)
2611 return NULL;
2612 return prerender_tracker_->GetPrerenderCookieStoreForRenderProcess(
2613 render_process_id).get();
2616 #if defined(ENABLE_WEBRTC)
2617 void ChromeContentBrowserClient::MaybeCopyDisableWebRtcEncryptionSwitch(
2618 base::CommandLine* to_command_line,
2619 const base::CommandLine& from_command_line,
2620 VersionInfo::Channel channel) {
2621 #if defined(OS_ANDROID)
2622 const VersionInfo::Channel kMaxDisableEncryptionChannel =
2623 VersionInfo::CHANNEL_BETA;
2624 #else
2625 const VersionInfo::Channel kMaxDisableEncryptionChannel =
2626 VersionInfo::CHANNEL_DEV;
2627 #endif
2628 if (channel <= kMaxDisableEncryptionChannel) {
2629 static const char* const kWebRtcDevSwitchNames[] = {
2630 switches::kDisableWebRtcEncryption,
2632 to_command_line->CopySwitchesFrom(from_command_line,
2633 kWebRtcDevSwitchNames,
2634 arraysize(kWebRtcDevSwitchNames));
2637 #endif // defined(ENABLE_WEBRTC)
2639 } // namespace chrome