SupervisedUserSyncService cleanup: Implement SigninManagerBase::Observer
[chromium-blink-merge.git] / chrome / browser / chrome_content_browser_client.cc
blobf3d767f5790f955d8df52b54a1ce038bf0a7c366
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/net/spdyproxy/data_reduction_proxy_chrome_settings.h"
46 #include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings_factory.h"
47 #include "chrome/browser/notifications/desktop_notification_service.h"
48 #include "chrome/browser/notifications/desktop_notification_service_factory.h"
49 #include "chrome/browser/notifications/platform_notification_service_impl.h"
50 #include "chrome/browser/platform_util.h"
51 #include "chrome/browser/prerender/prerender_final_status.h"
52 #include "chrome/browser/prerender/prerender_manager.h"
53 #include "chrome/browser/prerender/prerender_manager_factory.h"
54 #include "chrome/browser/prerender/prerender_message_filter.h"
55 #include "chrome/browser/printing/printing_message_filter.h"
56 #include "chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.h"
57 #include "chrome/browser/profiles/profile.h"
58 #include "chrome/browser/profiles/profile_io_data.h"
59 #include "chrome/browser/push_messaging/push_messaging_permission_context.h"
60 #include "chrome/browser/push_messaging/push_messaging_permission_context_factory.h"
61 #include "chrome/browser/renderer_host/chrome_render_message_filter.h"
62 #include "chrome/browser/renderer_host/pepper/chrome_browser_pepper_host_factory.h"
63 #include "chrome/browser/search/instant_service.h"
64 #include "chrome/browser/search/instant_service_factory.h"
65 #include "chrome/browser/search/search.h"
66 #include "chrome/browser/search_engines/search_provider_install_state_message_filter.h"
67 #include "chrome/browser/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/tracing/chrome_tracing_delegate.h"
77 #include "chrome/browser/ui/blocked_content/blocked_window_params.h"
78 #include "chrome/browser/ui/blocked_content/popup_blocker_tab_helper.h"
79 #include "chrome/browser/ui/chrome_select_file_policy.h"
80 #include "chrome/browser/ui/sync/sync_promo_ui.h"
81 #include "chrome/browser/ui/tab_contents/chrome_web_contents_view_delegate.h"
82 #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
83 #include "chrome/common/chrome_constants.h"
84 #include "chrome/common/chrome_paths.h"
85 #include "chrome/common/chrome_switches.h"
86 #include "chrome/common/env_vars.h"
87 #include "chrome/common/logging_chrome.h"
88 #include "chrome/common/pepper_permission_util.h"
89 #include "chrome/common/pref_names.h"
90 #include "chrome/common/render_messages.h"
91 #include "chrome/common/url_constants.h"
92 #include "chrome/grit/generated_resources.h"
93 #include "chrome/installer/util/google_update_settings.h"
94 #include "chromeos/chromeos_constants.h"
95 #include "components/cdm/browser/cdm_message_filter_android.h"
96 #include "components/cloud_devices/common/cloud_devices_switches.h"
97 #include "components/content_settings/core/browser/content_settings_provider.h"
98 #include "components/content_settings/core/browser/content_settings_utils.h"
99 #include "components/content_settings/core/browser/host_content_settings_map.h"
100 #include "components/content_settings/core/common/content_settings.h"
101 #include "components/content_settings/core/common/permission_request_id.h"
102 #include "components/data_reduction_proxy/content/browser/data_reduction_proxy_message_filter.h"
103 #include "components/dom_distiller/core/url_constants.h"
104 #include "components/google/core/browser/google_util.h"
105 #include "components/metrics/client_info.h"
106 #include "components/pref_registry/pref_registry_syncable.h"
107 #include "components/rappor/rappor_utils.h"
108 #include "components/signin/core/common/profile_management_switches.h"
109 #include "components/translate/core/common/translate_switches.h"
110 #include "components/url_fixer/url_fixer.h"
111 #include "content/public/browser/browser_child_process_host.h"
112 #include "content/public/browser/browser_main_parts.h"
113 #include "content/public/browser/browser_ppapi_host.h"
114 #include "content/public/browser/browser_thread.h"
115 #include "content/public/browser/browser_url_handler.h"
116 #include "content/public/browser/child_process_data.h"
117 #include "content/public/browser/child_process_security_policy.h"
118 #include "content/public/browser/client_certificate_delegate.h"
119 #include "content/public/browser/permission_type.h"
120 #include "content/public/browser/render_frame_host.h"
121 #include "content/public/browser/render_process_host.h"
122 #include "content/public/browser/render_view_host.h"
123 #include "content/public/browser/resource_context.h"
124 #include "content/public/browser/site_instance.h"
125 #include "content/public/browser/web_contents.h"
126 #include "content/public/common/child_process_host.h"
127 #include "content/public/common/content_descriptors.h"
128 #include "content/public/common/url_utils.h"
129 #include "content/public/common/web_preferences.h"
130 #include "gin/public/isolate_holder.h"
131 #include "net/base/mime_util.h"
132 #include "net/cookies/canonical_cookie.h"
133 #include "net/cookies/cookie_options.h"
134 #include "net/ssl/ssl_cert_request_info.h"
135 #include "ppapi/host/ppapi_host.h"
136 #include "storage/browser/fileapi/external_mount_points.h"
137 #include "ui/base/l10n/l10n_util.h"
138 #include "ui/base/resource/resource_bundle.h"
139 #include "ui/resources/grit/ui_resources.h"
141 #if defined(OS_WIN)
142 #include "base/win/windows_version.h"
143 #include "chrome/browser/chrome_browser_main_win.h"
144 #include "sandbox/win/src/sandbox_policy.h"
145 #elif defined(OS_MACOSX)
146 #include "chrome/browser/chrome_browser_main_mac.h"
147 #include "chrome/browser/spellchecker/spellcheck_message_filter_mac.h"
148 #elif defined(OS_CHROMEOS)
149 #include "chrome/browser/chromeos/chrome_browser_main_chromeos.h"
150 #include "chrome/browser/chromeos/drive/fileapi/file_system_backend_delegate.h"
151 #include "chrome/browser/chromeos/file_manager/app_id.h"
152 #include "chrome/browser/chromeos/file_system_provider/fileapi/backend_delegate.h"
153 #include "chrome/browser/chromeos/fileapi/file_system_backend.h"
154 #include "chrome/browser/chromeos/fileapi/mtp_file_system_backend_delegate.h"
155 #include "chrome/browser/chromeos/login/startup_utils.h"
156 #include "chrome/browser/chromeos/system/input_device_settings.h"
157 #include "chromeos/chromeos_switches.h"
158 #include "components/user_manager/user_manager.h"
159 #elif defined(OS_LINUX)
160 #include "chrome/browser/chrome_browser_main_linux.h"
161 #elif defined(OS_ANDROID)
162 #include "chrome/browser/android/new_tab_page_url_handler.h"
163 #include "chrome/browser/android/service_tab_launcher.h"
164 #include "chrome/browser/android/webapps/single_tab_mode_tab_helper.h"
165 #include "chrome/browser/chrome_browser_main_android.h"
166 #include "chrome/common/descriptors_android.h"
167 #include "components/crash/browser/crash_dump_manager_android.h"
168 #elif defined(OS_POSIX)
169 #include "chrome/browser/chrome_browser_main_posix.h"
170 #endif
172 #if defined(OS_ANDROID) || defined(OS_CHROMEOS)
173 #include "chrome/browser/media/protected_media_identifier_permission_context.h"
174 #include "chrome/browser/media/protected_media_identifier_permission_context_factory.h"
175 #endif
177 #if defined(OS_POSIX) && !defined(OS_MACOSX)
178 #include "base/debug/leak_annotations.h"
179 #include "components/crash/app/breakpad_linux.h"
180 #include "components/crash/browser/crash_handler_host_linux.h"
181 #endif
183 #if defined(OS_ANDROID)
184 #include "ui/base/ui_base_paths.h"
185 #include "ui/gfx/android/device_display_info.h"
186 #endif
188 #if defined(OS_ANDROID)
189 #include "chrome/browser/android/dev_tools_manager_delegate_android.h"
190 #else
191 #include "chrome/browser/devtools/chrome_devtools_manager_delegate.h"
192 #endif
194 #if defined(TOOLKIT_VIEWS)
195 #include "chrome/browser/ui/views/chrome_browser_main_extra_parts_views.h"
196 #endif
198 #if defined(USE_ASH)
199 #include "chrome/browser/ui/views/ash/chrome_browser_main_extra_parts_ash.h"
200 #endif
202 #if defined(USE_AURA)
203 #include "chrome/browser/ui/aura/chrome_browser_main_extra_parts_aura.h"
204 #endif
206 #if defined(USE_X11)
207 #include "chrome/browser/chrome_browser_main_extra_parts_x11.h"
208 #endif
210 #if defined(ENABLE_CAPTIVE_PORTAL_DETECTION)
211 #include "chrome/browser/captive_portal/captive_portal_tab_helper.h"
212 #endif
214 #if !defined(DISABLE_NACL)
215 #include "components/nacl/browser/nacl_browser.h"
216 #include "components/nacl/browser/nacl_host_message_filter.h"
217 #include "components/nacl/browser/nacl_process_host.h"
218 #include "components/nacl/common/nacl_process_type.h"
219 #include "components/nacl/common/nacl_switches.h"
220 #endif
222 #if defined(ENABLE_EXTENSIONS)
223 #include "chrome/browser/accessibility/animation_policy_prefs.h"
224 #include "chrome/browser/extensions/chrome_content_browser_client_extensions_part.h"
225 #include "chrome/browser/extensions/extension_util.h"
226 #include "chrome/browser/media/cast_transport_host_filter.h"
227 #include "chrome/browser/speech/extension_api/tts_engine_extension_api.h"
228 #include "extensions/browser/extension_registry.h"
229 #include "extensions/browser/guest_view/guest_view_base.h"
230 #include "extensions/browser/guest_view/guest_view_manager.h"
231 #include "extensions/browser/guest_view/web_view/web_view_guest.h"
232 #include "extensions/browser/guest_view/web_view/web_view_permission_helper.h"
233 #include "extensions/browser/guest_view/web_view/web_view_renderer_state.h"
234 #include "extensions/common/constants.h"
235 #include "extensions/common/extension.h"
236 #include "extensions/common/extension_set.h"
237 #include "extensions/common/manifest_handlers/background_info.h"
238 #include "extensions/common/manifest_handlers/shared_module_info.h"
239 #include "extensions/common/permissions/permissions_data.h"
240 #include "extensions/common/permissions/socket_permission.h"
241 #include "extensions/common/switches.h"
242 #endif
244 #if defined(ENABLE_PLUGINS)
245 #include "chrome/browser/plugins/chrome_content_browser_client_plugins_part.h"
246 #endif
248 #if defined(ENABLE_SPELLCHECK)
249 #include "chrome/browser/spellchecker/spellcheck_message_filter.h"
250 #endif
252 #if defined(ENABLE_WEBRTC)
253 #include "chrome/browser/media/webrtc_logging_handler_host.h"
254 #endif
256 using base::FileDescriptor;
257 using blink::WebWindowFeatures;
258 using content::AccessTokenStore;
259 using content::BrowserThread;
260 using content::BrowserURLHandler;
261 using content::ChildProcessSecurityPolicy;
262 using content::QuotaPermissionContext;
263 using content::RenderFrameHost;
264 using content::RenderViewHost;
265 using content::ResourceType;
266 using content::SiteInstance;
267 using content::WebContents;
268 using content::WebPreferences;
269 using message_center::NotifierId;
271 #if defined(OS_POSIX)
272 using content::FileDescriptorInfo;
273 #endif
275 #if defined(ENABLE_EXTENSIONS)
276 using extensions::APIPermission;
277 using extensions::ChromeContentBrowserClientExtensionsPart;
278 using extensions::Extension;
279 using extensions::InfoMap;
280 using extensions::Manifest;
281 #endif
283 #if defined(ENABLE_PLUGINS)
284 using plugins::ChromeContentBrowserClientPluginsPart;
285 #endif
287 namespace {
289 // Cached version of the locale so we can return the locale on the I/O
290 // thread.
291 base::LazyInstance<std::string> g_io_thread_application_locale;
293 #if defined(ENABLE_PLUGINS)
294 // TODO(teravest): Add renderer-side API-specific checking for these APIs so
295 // that blanket permission isn't granted to all dev channel APIs for these.
296 // http://crbug.com/386743
297 const char* const kPredefinedAllowedDevChannelOrigins[] = {
298 "6EAED1924DB611B6EEF2A664BD077BE7EAD33B8F", // see crbug.com/383937
299 "4EB74897CB187C7633357C2FE832E0AD6A44883A" // see crbug.com/383937
302 const char* const kPredefinedAllowedFileHandleOrigins[] = {
303 "6EAED1924DB611B6EEF2A664BD077BE7EAD33B8F", // see crbug.com/234789
304 "4EB74897CB187C7633357C2FE832E0AD6A44883A" // see crbug.com/234789
307 const char* const kPredefinedAllowedSocketOrigins[] = {
308 "okddffdblfhhnmhodogpojmfkjmhinfp", // Test SSH Client
309 "pnhechapfaindjhompbnflcldabbghjo", // HTerm App (SSH Client)
310 "bglhmjfplikpjnfoegeomebmfnkjomhe", // see crbug.com/122126
311 "gbchcmhmhahfdphkhkmpfmihenigjmpp", // Chrome Remote Desktop
312 "kgngmbheleoaphbjbaiobfdepmghbfah", // Pre-release Chrome Remote Desktop
313 "odkaodonbgfohohmklejpjiejmcipmib", // Dogfood Chrome Remote Desktop
314 "ojoimpklfciegopdfgeenehpalipignm", // Chromoting canary
315 "cbkkbcmdlboombapidmoeolnmdacpkch", // see crbug.com/129089
316 "hhnbmknkdabfoieppbbljkhkfjcmcbjh", // see crbug.com/134099
317 "mablfbjkhmhkmefkjjacnbaikjkipphg", // see crbug.com/134099
318 "pdeelgamlgannhelgoegilelnnojegoh", // see crbug.com/134099
319 "cabapfdbkniadpollkckdnedaanlciaj", // see crbug.com/134099
320 "mapljbgnjledlpdmlchihnmeclmefbba", // see crbug.com/134099
321 "ghbfeebgmiidnnmeobbbaiamklmpbpii", // see crbug.com/134099
322 "jdfhpkjeckflbbleddjlpimecpbjdeep", // see crbug.com/142514
323 "iabmpiboiopbgfabjmgeedhcmjenhbla", // see crbug.com/165080
324 "B7CF8A292249681AF81771650BA4CEEAF19A4560", // see crbug.com/165080
325 "7525AF4F66763A70A883C4700529F647B470E4D2", // see crbug.com/238084
326 "0B549507088E1564D672F7942EB87CA4DAD73972", // see crbug.com/238084
327 "864288364E239573E777D3E0E36864E590E95C74" // see crbug.com/238084
329 #endif
331 // Returns a copy of the given url with its host set to given host and path set
332 // to given path. Other parts of the url will be the same.
333 GURL ReplaceURLHostAndPath(const GURL& url,
334 const std::string& host,
335 const std::string& path) {
336 url::Replacements<char> replacements;
337 replacements.SetHost(host.c_str(), url::Component(0, host.length()));
338 replacements.SetPath(path.c_str(), url::Component(0, path.length()));
339 return url.ReplaceComponents(replacements);
342 // Maps "foo://bar/baz/" to "foo://chrome/bar/baz/".
343 GURL AddUberHost(const GURL& url) {
344 const std::string uber_host = chrome::kChromeUIUberHost;
345 const std::string new_path = url.host() + url.path();
347 return ReplaceURLHostAndPath(url, uber_host, new_path);
350 // If url->host() is "chrome" and url->path() has characters other than the
351 // first slash, changes the url from "foo://chrome/bar/" to "foo://bar/" and
352 // returns true. Otherwise returns false.
353 bool RemoveUberHost(GURL* url) {
354 if (url->host() != chrome::kChromeUIUberHost)
355 return false;
357 if (url->path().empty() || url->path() == "/")
358 return false;
360 const std::string old_path = url->path();
362 const std::string::size_type separator = old_path.find('/', 1);
363 std::string new_host;
364 std::string new_path;
365 if (separator == std::string::npos) {
366 new_host = old_path.substr(1);
367 } else {
368 new_host = old_path.substr(1, separator - 1);
369 new_path = old_path.substr(separator);
372 // Do not allow URLs with paths empty before the first slash since we can't
373 // have an empty host. (e.g "foo://chrome//")
374 if (new_host.empty())
375 return false;
377 *url = ReplaceURLHostAndPath(*url, new_host, new_path);
379 DCHECK(url->is_valid());
381 return true;
384 // Handles rewriting Web UI URLs.
385 bool HandleWebUI(GURL* url, content::BrowserContext* browser_context) {
386 // Do not handle special URLs such as "about:foo"
387 if (!url->host().empty()) {
388 const GURL chrome_url = AddUberHost(*url);
390 // Handle valid "chrome://chrome/foo" URLs so the reverse handler will
391 // be called.
392 if (ChromeWebUIControllerFactory::GetInstance()->UseWebUIForURL(
393 browser_context, chrome_url))
394 return true;
397 if (!ChromeWebUIControllerFactory::GetInstance()->UseWebUIForURL(
398 browser_context, *url))
399 return false;
401 #if defined(OS_CHROMEOS)
402 // Special case : in ChromeOS in Guest mode bookmarks and history are
403 // disabled for security reasons. New tab page explains the reasons, so
404 // we redirect user to new tab page.
405 if (user_manager::UserManager::Get()->IsLoggedInAsGuest()) {
406 if (url->SchemeIs(content::kChromeUIScheme) &&
407 (url->DomainIs(chrome::kChromeUIBookmarksHost) ||
408 url->DomainIs(chrome::kChromeUIHistoryHost))) {
409 // Rewrite with new tab URL
410 *url = GURL(chrome::kChromeUINewTabURL);
413 #endif
415 return true;
418 // Reverse URL handler for Web UI. Maps "chrome://chrome/foo/" to
419 // "chrome://foo/".
420 bool HandleWebUIReverse(GURL* url, content::BrowserContext* browser_context) {
421 if (!url->is_valid() || !url->SchemeIs(content::kChromeUIScheme))
422 return false;
424 return RemoveUberHost(url);
427 bool CertMatchesFilter(const net::X509Certificate& cert,
428 const base::DictionaryValue& filter) {
429 // TODO(markusheintz): This is the minimal required filter implementation.
430 // Implement a better matcher.
432 // An empty filter matches any client certificate since no requirements are
433 // specified at all.
434 if (filter.empty())
435 return true;
437 std::string common_name;
438 if (filter.GetString("ISSUER.CN", &common_name) &&
439 (cert.issuer().common_name == common_name)) {
440 return true;
442 return false;
445 #if defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_MACOSX)
446 breakpad::CrashHandlerHostLinux* CreateCrashHandlerHost(
447 const std::string& process_type) {
448 base::FilePath dumps_path;
449 PathService::Get(chrome::DIR_CRASH_DUMPS, &dumps_path);
451 ANNOTATE_SCOPED_MEMORY_LEAK;
452 bool upload = (getenv(env_vars::kHeadless) == NULL);
453 breakpad::CrashHandlerHostLinux* crash_handler =
454 new breakpad::CrashHandlerHostLinux(process_type, dumps_path, upload);
455 crash_handler->StartUploaderThread();
456 return crash_handler;
460 int GetCrashSignalFD(const base::CommandLine& command_line) {
461 // Extensions have the same process type as renderers.
462 if (command_line.HasSwitch(extensions::switches::kExtensionProcess)) {
463 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
464 if (!crash_handler)
465 crash_handler = CreateCrashHandlerHost("extension");
466 return crash_handler->GetDeathSignalSocket();
469 std::string process_type =
470 command_line.GetSwitchValueASCII(switches::kProcessType);
472 if (process_type == switches::kRendererProcess) {
473 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
474 if (!crash_handler)
475 crash_handler = CreateCrashHandlerHost(process_type);
476 return crash_handler->GetDeathSignalSocket();
479 if (process_type == switches::kPluginProcess) {
480 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
481 if (!crash_handler)
482 crash_handler = CreateCrashHandlerHost(process_type);
483 return crash_handler->GetDeathSignalSocket();
486 if (process_type == switches::kPpapiPluginProcess) {
487 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
488 if (!crash_handler)
489 crash_handler = CreateCrashHandlerHost(process_type);
490 return crash_handler->GetDeathSignalSocket();
493 if (process_type == switches::kGpuProcess) {
494 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
495 if (!crash_handler)
496 crash_handler = CreateCrashHandlerHost(process_type);
497 return crash_handler->GetDeathSignalSocket();
500 return -1;
502 #endif // defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_MACOSX)
504 void SetApplicationLocaleOnIOThread(const std::string& locale) {
505 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
506 g_io_thread_application_locale.Get() = locale;
509 void HandleBlockedPopupOnUIThread(const BlockedWindowParams& params) {
510 // TODO(jochen): This code path should use RenderFrameHosts. See
511 // http://crbug.com/431769 for details.
512 RenderViewHost* render_view_host =
513 RenderViewHost::FromID(params.render_process_id(), params.opener_id());
514 if (!render_view_host)
515 return;
516 WebContents* tab = WebContents::FromRenderViewHost(render_view_host);
517 // The tab might already have navigated away.
518 if (!tab || tab->GetRenderViewHost() != render_view_host)
519 return;
521 prerender::PrerenderContents* prerender_contents =
522 prerender::PrerenderContents::FromWebContents(tab);
523 if (prerender_contents) {
524 prerender_contents->Destroy(prerender::FINAL_STATUS_CREATE_NEW_WINDOW);
525 return;
528 PopupBlockerTabHelper* popup_helper =
529 PopupBlockerTabHelper::FromWebContents(tab);
530 if (!popup_helper)
531 return;
532 popup_helper->AddBlockedPopup(params);
535 #if defined(OS_ANDROID)
537 void HandleSingleTabModeBlockOnUIThread(const BlockedWindowParams& params) {
538 WebContents* web_contents =
539 tab_util::GetWebContentsByID(params.render_process_id(),
540 params.opener_id());
541 if (!web_contents)
542 return;
544 SingleTabModeTabHelper::FromWebContents(web_contents)->HandleOpenUrl(params);
547 float GetDeviceScaleAdjustment() {
548 static const float kMinFSM = 1.05f;
549 static const int kWidthForMinFSM = 320;
550 static const float kMaxFSM = 1.3f;
551 static const int kWidthForMaxFSM = 800;
553 gfx::DeviceDisplayInfo info;
554 int minWidth = info.GetSmallestDIPWidth();
556 if (minWidth <= kWidthForMinFSM)
557 return kMinFSM;
558 if (minWidth >= kWidthForMaxFSM)
559 return kMaxFSM;
561 // The font scale multiplier varies linearly between kMinFSM and kMaxFSM.
562 float ratio = static_cast<float>(minWidth - kWidthForMinFSM) /
563 (kWidthForMaxFSM - kWidthForMinFSM);
564 return ratio * (kMaxFSM - kMinFSM) + kMinFSM;
567 #endif // defined(OS_ANDROID)
569 #if defined(ENABLE_EXTENSIONS)
570 // By default, JavaScript and images are enabled in guest content.
571 void GetGuestViewDefaultContentSettingRules(
572 bool incognito,
573 RendererContentSettingRules* rules) {
574 rules->image_rules.push_back(
575 ContentSettingPatternSource(ContentSettingsPattern::Wildcard(),
576 ContentSettingsPattern::Wildcard(),
577 CONTENT_SETTING_ALLOW,
578 std::string(),
579 incognito));
581 rules->script_rules.push_back(
582 ContentSettingPatternSource(ContentSettingsPattern::Wildcard(),
583 ContentSettingsPattern::Wildcard(),
584 CONTENT_SETTING_ALLOW,
585 std::string(),
586 incognito));
588 #endif // defined(ENALBE_EXTENSIONS)
590 content::PermissionStatus
591 ContentSettingToPermissionStatus(ContentSetting setting) {
592 switch (setting) {
593 case CONTENT_SETTING_ALLOW:
594 case CONTENT_SETTING_SESSION_ONLY:
595 return content::PERMISSION_STATUS_GRANTED;
596 case CONTENT_SETTING_BLOCK:
597 return content::PERMISSION_STATUS_DENIED;
598 case CONTENT_SETTING_ASK:
599 return content::PERMISSION_STATUS_ASK;
600 case CONTENT_SETTING_DETECT_IMPORTANT_CONTENT:
601 case CONTENT_SETTING_DEFAULT:
602 case CONTENT_SETTING_NUM_SETTINGS:
603 break;
605 NOTREACHED();
606 return content::PERMISSION_STATUS_DENIED;
609 PermissionContextBase* GetPermissionContext(Profile* profile,
610 content::PermissionType permission) {
611 switch (permission) {
612 case content::PERMISSION_MIDI_SYSEX:
613 return MidiPermissionContextFactory::GetForProfile(profile);
614 case content::PERMISSION_NOTIFICATIONS:
615 #if defined(ENABLE_NOTIFICATIONS)
616 return DesktopNotificationServiceFactory::GetForProfile(profile);
617 #else
618 NOTIMPLEMENTED();
619 break;
620 #endif
621 case content::PERMISSION_GEOLOCATION:
622 return GeolocationPermissionContextFactory::GetForProfile(profile);
623 case content::PERMISSION_PROTECTED_MEDIA_IDENTIFIER:
624 #if defined(OS_ANDROID) || defined(OS_CHROMEOS)
625 return ProtectedMediaIdentifierPermissionContextFactory::GetForProfile(
626 profile);
627 #else
628 NOTIMPLEMENTED();
629 break;
630 #endif
631 case content::PERMISSION_PUSH_MESSAGING:
632 return PushMessagingPermissionContextFactory::GetForProfile(profile);
633 case content::PERMISSION_NUM:
634 NOTREACHED() << "Invalid RequestPermission for " << permission;
635 break;
637 return nullptr;
640 // Helper method to translate from Permissions to ContentSettings
641 ContentSettingsType PermissionToContentSetting(
642 content::PermissionType permission) {
643 switch (permission) {
644 case content::PERMISSION_MIDI_SYSEX:
645 return CONTENT_SETTINGS_TYPE_MIDI_SYSEX;
646 case content::PERMISSION_PUSH_MESSAGING:
647 return CONTENT_SETTINGS_TYPE_PUSH_MESSAGING;
648 case content::PERMISSION_NOTIFICATIONS:
649 return CONTENT_SETTINGS_TYPE_NOTIFICATIONS;
650 case content::PERMISSION_GEOLOCATION:
651 return CONTENT_SETTINGS_TYPE_GEOLOCATION;
652 #if defined(OS_ANDROID) || defined(OS_CHROMEOS)
653 case content::PERMISSION_PROTECTED_MEDIA_IDENTIFIER:
654 return CONTENT_SETTINGS_TYPE_PROTECTED_MEDIA_IDENTIFIER;
655 #endif
656 default:
657 NOTREACHED() << "Unknown content setting for permission " << permission;
658 return CONTENT_SETTINGS_TYPE_DEFAULT;
662 void OnRequestPermission(
663 const base::Callback<void(content::PermissionStatus)>& callback,
664 ContentSetting content_setting) {
665 callback.Run(ContentSettingToPermissionStatus(content_setting));
668 } // namespace
670 namespace chrome {
672 ChromeContentBrowserClient::ChromeContentBrowserClient()
674 #if defined(OS_POSIX) && !defined(OS_MACOSX)
675 v8_natives_fd_(-1),
676 v8_snapshot_fd_(-1),
677 #endif // OS_POSIX && !OS_MACOSX
678 weak_factory_(this) {
679 #if defined(ENABLE_PLUGINS)
680 for (size_t i = 0; i < arraysize(kPredefinedAllowedDevChannelOrigins); ++i)
681 allowed_dev_channel_origins_.insert(kPredefinedAllowedDevChannelOrigins[i]);
682 for (size_t i = 0; i < arraysize(kPredefinedAllowedFileHandleOrigins); ++i)
683 allowed_file_handle_origins_.insert(kPredefinedAllowedFileHandleOrigins[i]);
684 for (size_t i = 0; i < arraysize(kPredefinedAllowedSocketOrigins); ++i)
685 allowed_socket_origins_.insert(kPredefinedAllowedSocketOrigins[i]);
687 extra_parts_.push_back(new ChromeContentBrowserClientPluginsPart);
688 #endif
690 #if !defined(OS_ANDROID)
691 TtsExtensionEngine* tts_extension_engine = TtsExtensionEngine::GetInstance();
692 TtsController::GetInstance()->SetTtsEngineDelegate(tts_extension_engine);
693 #endif
695 #if defined(ENABLE_EXTENSIONS)
696 extra_parts_.push_back(new ChromeContentBrowserClientExtensionsPart);
697 #endif
700 ChromeContentBrowserClient::~ChromeContentBrowserClient() {
701 for (int i = static_cast<int>(extra_parts_.size()) - 1; i >= 0; --i)
702 delete extra_parts_[i];
703 extra_parts_.clear();
706 // static
707 void ChromeContentBrowserClient::RegisterProfilePrefs(
708 user_prefs::PrefRegistrySyncable* registry) {
709 registry->RegisterBooleanPref(
710 prefs::kDisable3DAPIs,
711 false,
712 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
713 registry->RegisterBooleanPref(
714 prefs::kEnableHyperlinkAuditing,
715 true,
716 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
717 registry->RegisterListPref(
718 prefs::kEnableDeprecatedWebPlatformFeatures,
719 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
722 // static
723 void ChromeContentBrowserClient::SetApplicationLocale(
724 const std::string& locale) {
725 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
727 // This object is guaranteed to outlive all threads so we don't have to
728 // worry about the lack of refcounting and can just post as Unretained.
730 // The common case is that this function is called early in Chrome startup
731 // before any threads are created (it will also be called later if the user
732 // changes the pref). In this case, there will be no threads created and
733 // posting will fail. When there are no threads, we can just set the string
734 // without worrying about threadsafety.
735 if (!BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
736 base::Bind(&SetApplicationLocaleOnIOThread, locale))) {
737 g_io_thread_application_locale.Get() = locale;
741 content::BrowserMainParts* ChromeContentBrowserClient::CreateBrowserMainParts(
742 const content::MainFunctionParams& parameters) {
743 ChromeBrowserMainParts* main_parts;
744 // Construct the Main browser parts based on the OS type.
745 #if defined(OS_WIN)
746 main_parts = new ChromeBrowserMainPartsWin(parameters);
747 #elif defined(OS_MACOSX)
748 main_parts = new ChromeBrowserMainPartsMac(parameters);
749 #elif defined(OS_CHROMEOS)
750 main_parts = new chromeos::ChromeBrowserMainPartsChromeos(parameters);
751 #elif defined(OS_LINUX)
752 main_parts = new ChromeBrowserMainPartsLinux(parameters);
753 #elif defined(OS_ANDROID)
754 main_parts = new ChromeBrowserMainPartsAndroid(parameters);
755 #elif defined(OS_POSIX)
756 main_parts = new ChromeBrowserMainPartsPosix(parameters);
757 #else
758 NOTREACHED();
759 main_parts = new ChromeBrowserMainParts(parameters);
760 #endif
762 chrome::AddProfilesExtraParts(main_parts);
764 // Construct additional browser parts. Stages are called in the order in
765 // which they are added.
766 #if defined(TOOLKIT_VIEWS)
767 main_parts->AddParts(new ChromeBrowserMainExtraPartsViews());
768 #endif
770 // TODO(oshima): Athena on chrome currently requires USE_ASH to build.
771 // We should reduce the dependency as much as possible.
772 #if defined(USE_ASH)
773 main_parts->AddParts(new ChromeBrowserMainExtraPartsAsh());
774 #endif
776 #if defined(USE_AURA)
777 main_parts->AddParts(new ChromeBrowserMainExtraPartsAura());
778 #endif
780 #if defined(USE_X11)
781 main_parts->AddParts(new ChromeBrowserMainExtraPartsX11());
782 #endif
784 chrome::AddMetricsExtraParts(main_parts);
786 return main_parts;
789 std::string ChromeContentBrowserClient::GetStoragePartitionIdForSite(
790 content::BrowserContext* browser_context,
791 const GURL& site) {
792 std::string partition_id;
794 // The partition ID for webview guest processes is the string value of its
795 // SiteInstance URL - "chrome-guest://app_id/persist?partition".
796 if (site.SchemeIs(content::kGuestScheme)) {
797 partition_id = site.spec();
798 } else if (site.GetOrigin().spec() == kChromeUIChromeSigninURL) {
799 // Chrome signin page has an embedded iframe of extension and web content,
800 // thus it must be isolated from other webUI pages.
801 partition_id = site.GetOrigin().spec();
804 DCHECK(IsValidStoragePartitionId(browser_context, partition_id));
805 return partition_id;
808 bool ChromeContentBrowserClient::IsValidStoragePartitionId(
809 content::BrowserContext* browser_context,
810 const std::string& partition_id) {
811 // The default ID is empty and is always valid.
812 if (partition_id.empty())
813 return true;
815 return GURL(partition_id).is_valid();
818 void ChromeContentBrowserClient::GetStoragePartitionConfigForSite(
819 content::BrowserContext* browser_context,
820 const GURL& site,
821 bool can_be_default,
822 std::string* partition_domain,
823 std::string* partition_name,
824 bool* in_memory) {
825 // Default to the browser-wide storage partition and override based on |site|
826 // below.
827 partition_domain->clear();
828 partition_name->clear();
829 *in_memory = false;
831 bool success = false;
832 #if defined(ENABLE_EXTENSIONS)
833 success = extensions::WebViewGuest::GetGuestPartitionConfigForSite(
834 site, partition_domain, partition_name, in_memory);
836 if (!success && site.SchemeIs(extensions::kExtensionScheme)) {
837 // If |can_be_default| is false, the caller is stating that the |site|
838 // should be parsed as if it had isolated storage. In particular it is
839 // important to NOT check ExtensionService for the is_storage_isolated()
840 // attribute because this code path is run during Extension uninstall
841 // to do cleanup after the Extension has already been unloaded from the
842 // ExtensionService.
843 bool is_isolated = !can_be_default;
844 if (can_be_default) {
845 if (extensions::util::SiteHasIsolatedStorage(site, browser_context))
846 is_isolated = true;
849 if (is_isolated) {
850 CHECK(site.has_host());
851 // For extensions with isolated storage, the the host of the |site| is
852 // the |partition_domain|. The |in_memory| and |partition_name| are only
853 // used in guest schemes so they are cleared here.
854 *partition_domain = site.host();
855 *in_memory = false;
856 partition_name->clear();
858 success = true;
860 #endif
862 if (!success && (site.GetOrigin().spec() == kChromeUIChromeSigninURL)) {
863 // Chrome signin page has an embedded iframe of extension and web content,
864 // thus it must be isolated from other webUI pages.
865 *partition_domain = chrome::kChromeUIChromeSigninHost;
868 // Assert that if |can_be_default| is false, the code above must have found a
869 // non-default partition. If this fails, the caller has a serious logic
870 // error about which StoragePartition they expect to be in and it is not
871 // safe to continue.
872 CHECK(can_be_default || !partition_domain->empty());
875 content::WebContentsViewDelegate*
876 ChromeContentBrowserClient::GetWebContentsViewDelegate(
877 content::WebContents* web_contents) {
878 return chrome::CreateWebContentsViewDelegate(web_contents);
881 void ChromeContentBrowserClient::RenderProcessWillLaunch(
882 content::RenderProcessHost* host) {
883 int id = host->GetID();
884 Profile* profile = Profile::FromBrowserContext(host->GetBrowserContext());
885 net::URLRequestContextGetter* context =
886 profile->GetRequestContextForRenderProcess(id);
888 host->AddFilter(new ChromeRenderMessageFilter(id, profile));
889 #if defined(ENABLE_EXTENSIONS)
890 host->AddFilter(new cast::CastTransportHostFilter);
891 #endif
892 #if defined(ENABLE_PRINTING)
893 host->AddFilter(new printing::PrintingMessageFilter(id, profile));
894 #endif
895 host->AddFilter(new SearchProviderInstallStateMessageFilter(id, profile));
896 #if defined(ENABLE_SPELLCHECK)
897 host->AddFilter(new SpellCheckMessageFilter(id));
898 #endif
899 #if defined(OS_MACOSX)
900 host->AddFilter(new SpellCheckMessageFilterMac(id));
901 #endif
902 host->AddFilter(new ChromeNetBenchmarkingMessageFilter(profile, context));
903 host->AddFilter(new prerender::PrerenderMessageFilter(id, profile));
904 host->AddFilter(new TtsMessageFilter(id, host->GetBrowserContext()));
905 #if defined(ENABLE_WEBRTC)
906 WebRtcLoggingHandlerHost* webrtc_logging_handler_host =
907 new WebRtcLoggingHandlerHost(profile);
908 host->SetWebRtcLogMessageCallback(base::Bind(
909 &WebRtcLoggingHandlerHost::LogMessage, webrtc_logging_handler_host));
910 host->AddFilter(webrtc_logging_handler_host);
911 host->SetUserData(host, new base::UserDataAdapter<WebRtcLoggingHandlerHost>(
912 webrtc_logging_handler_host));
913 #endif
914 #if !defined(DISABLE_NACL)
915 host->AddFilter(new nacl::NaClHostMessageFilter(
916 id, profile->IsOffTheRecord(),
917 profile->GetPath(),
918 context));
919 #endif
920 #if defined(OS_ANDROID)
921 host->AddFilter(new cdm::CdmMessageFilterAndroid());
922 #endif
923 DataReductionProxyChromeSettings* data_reduction_proxy_settings =
924 DataReductionProxyChromeSettingsFactory::GetForBrowserContext(profile);
925 host->AddFilter(new data_reduction_proxy::DataReductionProxyMessageFilter(
926 data_reduction_proxy_settings));
928 host->Send(new ChromeViewMsg_SetIsIncognitoProcess(
929 profile->IsOffTheRecord()));
931 for (size_t i = 0; i < extra_parts_.size(); ++i)
932 extra_parts_[i]->RenderProcessWillLaunch(host);
934 RendererContentSettingRules rules;
935 if (host->IsIsolatedGuest()) {
936 #if defined(ENABLE_EXTENSIONS)
937 GetGuestViewDefaultContentSettingRules(profile->IsOffTheRecord(), &rules);
938 #else
939 NOTREACHED();
940 #endif
941 } else {
942 GetRendererContentSettingRules(
943 profile->GetHostContentSettingsMap(), &rules);
945 host->Send(new ChromeViewMsg_SetContentSettingRules(rules));
948 GURL ChromeContentBrowserClient::GetEffectiveURL(
949 content::BrowserContext* browser_context, const GURL& url) {
950 Profile* profile = Profile::FromBrowserContext(browser_context);
951 if (!profile)
952 return url;
954 // If the input |url| should be assigned to the Instant renderer, make its
955 // effective URL distinct from other URLs on the search provider's domain.
956 if (chrome::ShouldAssignURLToInstantRenderer(url, profile))
957 return chrome::GetEffectiveURLForInstant(url, profile);
959 #if defined(ENABLE_EXTENSIONS)
960 return ChromeContentBrowserClientExtensionsPart::GetEffectiveURL(
961 profile, url);
962 #else
963 return url;
964 #endif
967 bool ChromeContentBrowserClient::ShouldUseProcessPerSite(
968 content::BrowserContext* browser_context, const GURL& effective_url) {
969 // Non-extension, non-Instant URLs should generally use
970 // process-per-site-instance. Because we expect to use the effective URL,
971 // URLs for hosted apps (apart from bookmark apps) should have an extension
972 // scheme by now.
974 Profile* profile = Profile::FromBrowserContext(browser_context);
975 if (!profile)
976 return false;
978 if (chrome::ShouldUseProcessPerSiteForInstantURL(effective_url, profile))
979 return true;
981 #if defined(ENABLE_EXTENSIONS)
982 return ChromeContentBrowserClientExtensionsPart::ShouldUseProcessPerSite(
983 profile, effective_url);
984 #else
985 return false;
986 #endif
989 // These are treated as WebUI schemes but do not get WebUI bindings. Also,
990 // view-source is allowed for these schemes.
991 void ChromeContentBrowserClient::GetAdditionalWebUISchemes(
992 std::vector<std::string>* additional_schemes) {
993 additional_schemes->push_back(chrome::kChromeSearchScheme);
994 additional_schemes->push_back(dom_distiller::kDomDistillerScheme);
997 void ChromeContentBrowserClient::GetAdditionalWebUIHostsToIgnoreParititionCheck(
998 std::vector<std::string>* hosts) {
999 hosts->push_back(chrome::kChromeUIExtensionIconHost);
1000 hosts->push_back(chrome::kChromeUIFaviconHost);
1001 hosts->push_back(chrome::kChromeUIThemeHost);
1002 hosts->push_back(chrome::kChromeUIThumbnailHost);
1003 hosts->push_back(chrome::kChromeUIThumbnailHost2);
1004 hosts->push_back(chrome::kChromeUIThumbnailListHost);
1007 net::URLRequestContextGetter*
1008 ChromeContentBrowserClient::CreateRequestContext(
1009 content::BrowserContext* browser_context,
1010 content::ProtocolHandlerMap* protocol_handlers,
1011 content::URLRequestInterceptorScopedVector request_interceptors) {
1012 Profile* profile = Profile::FromBrowserContext(browser_context);
1013 return profile->CreateRequestContext(protocol_handlers,
1014 request_interceptors.Pass());
1017 net::URLRequestContextGetter*
1018 ChromeContentBrowserClient::CreateRequestContextForStoragePartition(
1019 content::BrowserContext* browser_context,
1020 const base::FilePath& partition_path,
1021 bool in_memory,
1022 content::ProtocolHandlerMap* protocol_handlers,
1023 content::URLRequestInterceptorScopedVector request_interceptors) {
1024 Profile* profile = Profile::FromBrowserContext(browser_context);
1025 return profile->CreateRequestContextForStoragePartition(
1026 partition_path,
1027 in_memory,
1028 protocol_handlers,
1029 request_interceptors.Pass());
1032 bool ChromeContentBrowserClient::IsHandledURL(const GURL& url) {
1033 return ProfileIOData::IsHandledURL(url);
1036 bool ChromeContentBrowserClient::CanCommitURL(
1037 content::RenderProcessHost* process_host,
1038 const GURL& url) {
1039 #if defined(ENABLE_EXTENSIONS)
1040 return ChromeContentBrowserClientExtensionsPart::CanCommitURL(
1041 process_host, url);
1042 #else
1043 return true;
1044 #endif
1047 bool ChromeContentBrowserClient::ShouldAllowOpenURL(
1048 content::SiteInstance* site_instance, const GURL& url) {
1049 GURL from_url = site_instance->GetSiteURL();
1051 #if defined(ENABLE_EXTENSIONS)
1052 bool result;
1053 if (ChromeContentBrowserClientExtensionsPart::ShouldAllowOpenURL(
1054 site_instance, from_url, url, &result))
1055 return result;
1056 #endif
1058 // Do not allow chrome://chrome-signin navigate to other chrome:// URLs, since
1059 // the signin page may host untrusted web content.
1060 if (from_url.GetOrigin().spec() == chrome::kChromeUIChromeSigninURL &&
1061 url.SchemeIs(content::kChromeUIScheme) &&
1062 url.host() != chrome::kChromeUIChromeSigninHost) {
1063 VLOG(1) << "Blocked navigation to " << url.spec() << " from "
1064 << chrome::kChromeUIChromeSigninURL;
1065 return false;
1068 return true;
1071 bool ChromeContentBrowserClient::IsSuitableHost(
1072 content::RenderProcessHost* process_host,
1073 const GURL& site_url) {
1074 Profile* profile =
1075 Profile::FromBrowserContext(process_host->GetBrowserContext());
1076 // This may be NULL during tests. In that case, just assume any site can
1077 // share any host.
1078 if (!profile)
1079 return true;
1081 // Instant URLs should only be in the instant process and instant process
1082 // should only have Instant URLs.
1083 InstantService* instant_service =
1084 InstantServiceFactory::GetForProfile(profile);
1085 if (instant_service) {
1086 bool is_instant_process = instant_service->IsInstantProcess(
1087 process_host->GetID());
1088 bool should_be_in_instant_process =
1089 chrome::ShouldAssignURLToInstantRenderer(site_url, profile);
1090 if (is_instant_process || should_be_in_instant_process)
1091 return is_instant_process && should_be_in_instant_process;
1094 #if defined(ENABLE_EXTENSIONS)
1095 return ChromeContentBrowserClientExtensionsPart::IsSuitableHost(
1096 profile, process_host, site_url);
1097 #else
1098 return true;
1099 #endif
1102 bool ChromeContentBrowserClient::MayReuseHost(
1103 content::RenderProcessHost* process_host) {
1104 // If there is currently a prerender in progress for the host provided,
1105 // it may not be shared. We require prerenders to be by themselves in a
1106 // separate process so that we can monitor their resource usage.
1107 Profile* profile = Profile::FromBrowserContext(
1108 process_host->GetBrowserContext());
1109 prerender::PrerenderManager* prerender_manager =
1110 prerender::PrerenderManagerFactory::GetForProfile(profile);
1111 if (prerender_manager &&
1112 !prerender_manager->MayReuseProcessHost(process_host)) {
1113 return false;
1116 return true;
1119 bool ChromeContentBrowserClient::ShouldTryToUseExistingProcessHost(
1120 content::BrowserContext* browser_context, const GURL& url) {
1121 // It has to be a valid URL for us to check for an extension.
1122 if (!url.is_valid())
1123 return false;
1125 #if defined(ENABLE_EXTENSIONS)
1126 Profile* profile = Profile::FromBrowserContext(browser_context);
1127 return ChromeContentBrowserClientExtensionsPart::
1128 ShouldTryToUseExistingProcessHost(
1129 profile, url);
1130 #else
1131 return false;
1132 #endif
1135 void ChromeContentBrowserClient::SiteInstanceGotProcess(
1136 SiteInstance* site_instance) {
1137 CHECK(site_instance->HasProcess());
1139 Profile* profile = Profile::FromBrowserContext(
1140 site_instance->GetBrowserContext());
1141 if (!profile)
1142 return;
1144 // Remember the ID of the Instant process to signal the renderer process
1145 // on startup in |AppendExtraCommandLineSwitches| below.
1146 if (chrome::ShouldAssignURLToInstantRenderer(
1147 site_instance->GetSiteURL(), profile)) {
1148 InstantService* instant_service =
1149 InstantServiceFactory::GetForProfile(profile);
1150 if (instant_service)
1151 instant_service->AddInstantProcess(site_instance->GetProcess()->GetID());
1154 for (size_t i = 0; i < extra_parts_.size(); ++i)
1155 extra_parts_[i]->SiteInstanceGotProcess(site_instance);
1158 void ChromeContentBrowserClient::SiteInstanceDeleting(
1159 SiteInstance* site_instance) {
1160 if (!site_instance->HasProcess())
1161 return;
1163 for (size_t i = 0; i < extra_parts_.size(); ++i)
1164 extra_parts_[i]->SiteInstanceDeleting(site_instance);
1167 bool ChromeContentBrowserClient::ShouldSwapBrowsingInstancesForNavigation(
1168 SiteInstance* site_instance,
1169 const GURL& current_url,
1170 const GURL& new_url) {
1171 #if defined(ENABLE_EXTENSIONS)
1172 return ChromeContentBrowserClientExtensionsPart::
1173 ShouldSwapBrowsingInstancesForNavigation(
1174 site_instance, current_url, new_url);
1175 #else
1176 return false;
1177 #endif
1180 bool ChromeContentBrowserClient::ShouldSwapProcessesForRedirect(
1181 content::ResourceContext* resource_context, const GURL& current_url,
1182 const GURL& new_url) {
1183 #if defined(ENABLE_EXTENSIONS)
1184 return ChromeContentBrowserClientExtensionsPart::
1185 ShouldSwapProcessesForRedirect(resource_context, current_url, new_url);
1186 #else
1187 return false;
1188 #endif
1191 bool ChromeContentBrowserClient::ShouldAssignSiteForURL(const GURL& url) {
1192 return !url.SchemeIs(chrome::kChromeNativeScheme);
1195 std::string ChromeContentBrowserClient::GetCanonicalEncodingNameByAliasName(
1196 const std::string& alias_name) {
1197 return CharacterEncoding::GetCanonicalEncodingNameByAliasName(alias_name);
1200 namespace {
1202 bool IsAutoReloadEnabled() {
1203 // Fetch the field trial, even though we don't use it. Calling FindFullName()
1204 // causes the field-trial mechanism to report which group we're in, which
1205 // might reflect a hard disable or hard enable via flag, both of which have
1206 // their own field trial groups. This lets us know what percentage of users
1207 // manually enable or disable auto-reload.
1208 std::string group = base::FieldTrialList::FindFullName(
1209 "AutoReloadExperiment");
1210 const base::CommandLine& browser_command_line =
1211 *base::CommandLine::ForCurrentProcess();
1212 if (browser_command_line.HasSwitch(switches::kEnableOfflineAutoReload))
1213 return true;
1214 if (browser_command_line.HasSwitch(switches::kDisableOfflineAutoReload))
1215 return false;
1216 return true;
1219 bool IsAutoReloadVisibleOnlyEnabled() {
1220 // See the block comment in IsAutoReloadEnabled().
1221 std::string group = base::FieldTrialList::FindFullName(
1222 "AutoReloadVisibleOnlyExperiment");
1223 const base::CommandLine& browser_command_line =
1224 *base::CommandLine::ForCurrentProcess();
1225 if (browser_command_line.HasSwitch(
1226 switches::kEnableOfflineAutoReloadVisibleOnly)) {
1227 return true;
1229 if (browser_command_line.HasSwitch(
1230 switches::kDisableOfflineAutoReloadVisibleOnly)) {
1231 return false;
1233 return true;
1236 } // namespace
1238 void ChromeContentBrowserClient::AppendExtraCommandLineSwitches(
1239 base::CommandLine* command_line,
1240 int child_process_id) {
1241 #if defined(OS_POSIX) && !defined(OS_MACOSX)
1242 if (breakpad::IsCrashReporterEnabled()) {
1243 scoped_ptr<metrics::ClientInfo> client_info =
1244 GoogleUpdateSettings::LoadMetricsClientInfo();
1245 command_line->AppendSwitchASCII(switches::kEnableCrashReporter,
1246 client_info ? client_info->client_id
1247 : std::string());
1249 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
1251 if (logging::DialogsAreSuppressed())
1252 command_line->AppendSwitch(switches::kNoErrorDialogs);
1254 std::string process_type =
1255 command_line->GetSwitchValueASCII(switches::kProcessType);
1256 const base::CommandLine& browser_command_line =
1257 *base::CommandLine::ForCurrentProcess();
1259 static const char* const kCommonSwitchNames[] = {
1260 switches::kUserAgent,
1261 switches::kUserDataDir, // Make logs go to the right file.
1263 command_line->CopySwitchesFrom(browser_command_line, kCommonSwitchNames,
1264 arraysize(kCommonSwitchNames));
1266 #if defined(ENABLE_IPC_FUZZER)
1267 static const char* const kIpcFuzzerSwitches[] = {
1268 switches::kIpcDumpDirectory,
1269 switches::kIpcFuzzerTestcase,
1271 command_line->CopySwitchesFrom(browser_command_line, kIpcFuzzerSwitches,
1272 arraysize(kIpcFuzzerSwitches));
1273 #endif
1275 #if defined(OS_CHROMEOS)
1276 // On Chrome OS need to pass primary user homedir (in multi-profiles session).
1277 base::FilePath homedir;
1278 PathService::Get(base::DIR_HOME, &homedir);
1279 command_line->AppendSwitchASCII(chromeos::switches::kHomedir,
1280 homedir.value().c_str());
1281 #endif
1283 if (process_type == switches::kRendererProcess) {
1284 content::RenderProcessHost* process =
1285 content::RenderProcessHost::FromID(child_process_id);
1286 Profile* profile =
1287 process ? Profile::FromBrowserContext(process->GetBrowserContext())
1288 : NULL;
1289 for (size_t i = 0; i < extra_parts_.size(); ++i) {
1290 extra_parts_[i]->AppendExtraRendererCommandLineSwitches(
1291 command_line, process, profile);
1294 #if defined(OS_CHROMEOS)
1295 const std::string& login_profile =
1296 browser_command_line.GetSwitchValueASCII(
1297 chromeos::switches::kLoginProfile);
1298 if (!login_profile.empty())
1299 command_line->AppendSwitchASCII(
1300 chromeos::switches::kLoginProfile, login_profile);
1301 #endif
1303 #if defined(ENABLE_WEBRTC)
1304 MaybeCopyDisableWebRtcEncryptionSwitch(command_line,
1305 browser_command_line,
1306 VersionInfo::GetChannel());
1307 #endif
1309 if (process) {
1310 PrefService* prefs = profile->GetPrefs();
1311 // Currently this pref is only registered if applied via a policy.
1312 if (prefs->HasPrefPath(prefs::kDisable3DAPIs) &&
1313 prefs->GetBoolean(prefs::kDisable3DAPIs)) {
1314 // Turn this policy into a command line switch.
1315 command_line->AppendSwitch(switches::kDisable3DAPIs);
1318 const base::ListValue* switches =
1319 prefs->GetList(prefs::kEnableDeprecatedWebPlatformFeatures);
1320 if (switches) {
1321 // Enable any deprecated features that have been re-enabled by policy.
1322 for (base::ListValue::const_iterator it = switches->begin();
1323 it != switches->end(); ++it) {
1324 std::string switch_to_enable;
1325 if ((*it)->GetAsString(&switch_to_enable))
1326 command_line->AppendSwitch(switch_to_enable);
1330 // Disable client-side phishing detection in the renderer if it is
1331 // disabled in the Profile preferences or the browser process.
1332 if (!prefs->GetBoolean(prefs::kSafeBrowsingEnabled) ||
1333 !g_browser_process->safe_browsing_detection_service()) {
1334 command_line->AppendSwitch(
1335 switches::kDisableClientSidePhishingDetection);
1338 if (prefs->GetBoolean(prefs::kPrintPreviewDisabled))
1339 command_line->AppendSwitch(switches::kDisablePrintPreview);
1341 InstantService* instant_service =
1342 InstantServiceFactory::GetForProfile(profile);
1343 if (instant_service &&
1344 instant_service->IsInstantProcess(process->GetID()))
1345 command_line->AppendSwitch(switches::kInstantProcess);
1348 if (IsAutoReloadEnabled())
1349 command_line->AppendSwitch(switches::kEnableOfflineAutoReload);
1350 if (IsAutoReloadVisibleOnlyEnabled()) {
1351 command_line->AppendSwitch(
1352 switches::kEnableOfflineAutoReloadVisibleOnly);
1356 // Enable showing a saved copy if this session is in the field trial
1357 // or the user explicitly enabled it. Note that as far as the
1358 // renderer is concerned, the feature is enabled if-and-only-if
1359 // one of the kEnableShowSavedCopy* switches is on the command
1360 // line; the yes/no/default behavior is only at the browser
1361 // command line level.
1363 // Command line switches override
1364 const std::string& show_saved_copy_value =
1365 browser_command_line.GetSwitchValueASCII(switches::kShowSavedCopy);
1366 if (show_saved_copy_value == switches::kEnableShowSavedCopyPrimary ||
1367 show_saved_copy_value == switches::kEnableShowSavedCopySecondary ||
1368 show_saved_copy_value == switches::kDisableShowSavedCopy) {
1369 command_line->AppendSwitchASCII(switches::kShowSavedCopy,
1370 show_saved_copy_value);
1371 } else {
1372 std::string group =
1373 base::FieldTrialList::FindFullName("LoadStaleCacheExperiment");
1375 if (group == "Primary") {
1376 command_line->AppendSwitchASCII(
1377 switches::kShowSavedCopy, switches::kEnableShowSavedCopyPrimary);
1378 } else if (group == "Secondary") {
1379 command_line->AppendSwitchASCII(
1380 switches::kShowSavedCopy,
1381 switches::kEnableShowSavedCopySecondary);
1386 // Please keep this in alphabetical order.
1387 static const char* const kSwitchNames[] = {
1388 autofill::switches::kDisableFillOnAccountSelect,
1389 autofill::switches::kDisablePasswordGeneration,
1390 autofill::switches::kEnableFillOnAccountSelect,
1391 autofill::switches::kEnableFillOnAccountSelectNoHighlighting,
1392 autofill::switches::kEnablePasswordGeneration,
1393 autofill::switches::kEnablePasswordSaveOnInPageNavigation,
1394 autofill::switches::kEnableSingleClickAutofill,
1395 autofill::switches::kIgnoreAutocompleteOffForAutofill,
1396 autofill::switches::kLocalHeuristicsOnlyForPasswordGeneration,
1397 autofill::switches::kRespectAutocompleteOffForAutofill,
1398 #if defined(ENABLE_EXTENSIONS)
1399 extensions::switches::kAllowHTTPBackgroundPage,
1400 extensions::switches::kAllowLegacyExtensionManifests,
1401 extensions::switches::kEnableSurfaceWorker,
1402 extensions::switches::kEnableAppWindowControls,
1403 extensions::switches::kEnableEmbeddedExtensionOptions,
1404 extensions::switches::kEnableExperimentalExtensionApis,
1405 extensions::switches::kExtensionsOnChromeURLs,
1406 extensions::switches::kWhitelistedExtensionID,
1407 #endif
1408 switches::kAllowInsecureLocalhost,
1409 switches::kAppsCheckoutURL,
1410 switches::kAppsGalleryURL,
1411 switches::kCloudPrintURL,
1412 switches::kCloudPrintXmppEndpoint,
1413 switches::kDisableBundledPpapiFlash,
1414 switches::kDisableCastStreamingHWEncoding,
1415 switches::kDisableJavaScriptHarmonyShipping,
1416 switches::kDisableNewBookmarkApps,
1417 switches::kDisableOutOfProcessPdf,
1418 switches::kEnableBenchmarking,
1419 switches::kEnableNaCl,
1420 #if !defined(DISABLE_NACL)
1421 switches::kEnableNaClDebug,
1422 switches::kEnableNaClNonSfiMode,
1423 #endif
1424 switches::kEnableNetBenchmarking,
1425 switches::kEnableNewBookmarkApps,
1426 switches::kEnableOutOfProcessPdf,
1427 switches::kEnablePluginPlaceholderShadowDom,
1428 switches::kJavaScriptHarmony,
1429 switches::kMessageLoopHistogrammer,
1430 switches::kPpapiFlashArgs,
1431 switches::kPpapiFlashPath,
1432 switches::kPpapiFlashVersion,
1433 switches::kProfilingAtStart,
1434 switches::kProfilingFile,
1435 switches::kProfilingFlush,
1436 translate::switches::kTranslateSecurityOrigin,
1439 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1440 arraysize(kSwitchNames));
1441 } else if (process_type == switches::kUtilityProcess) {
1442 #if defined(ENABLE_EXTENSIONS)
1443 static const char* const kSwitchNames[] = {
1444 extensions::switches::kAllowHTTPBackgroundPage,
1445 extensions::switches::kEnableExperimentalExtensionApis,
1446 extensions::switches::kExtensionsOnChromeURLs,
1447 extensions::switches::kWhitelistedExtensionID,
1450 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1451 arraysize(kSwitchNames));
1452 #endif
1453 } else if (process_type == switches::kPluginProcess) {
1454 #if defined(OS_CHROMEOS)
1455 static const char* const kSwitchNames[] = {
1456 chromeos::switches::kLoginProfile,
1459 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1460 arraysize(kSwitchNames));
1461 #endif
1462 } else if (process_type == switches::kZygoteProcess) {
1463 static const char* const kSwitchNames[] = {
1464 // Load (in-process) Pepper plugins in-process in the zygote pre-sandbox.
1465 switches::kDisableBundledPpapiFlash,
1466 #if !defined(DISABLE_NACL)
1467 switches::kEnableNaClDebug,
1468 switches::kEnableNaClNonSfiMode,
1469 switches::kNaClDangerousNoSandboxNonSfi,
1470 switches::kUseNaClHelperNonSfi,
1471 #endif
1472 switches::kPpapiFlashPath,
1473 switches::kPpapiFlashVersion,
1476 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1477 arraysize(kSwitchNames));
1478 } else if (process_type == switches::kGpuProcess) {
1479 // If --ignore-gpu-blacklist is passed in, don't send in crash reports
1480 // because GPU is expected to be unreliable.
1481 if (browser_command_line.HasSwitch(switches::kIgnoreGpuBlacklist) &&
1482 !command_line->HasSwitch(switches::kDisableBreakpad))
1483 command_line->AppendSwitch(switches::kDisableBreakpad);
1486 // The command line switch kEnableBenchmarking needs to be specified along
1487 // with the kEnableStatsTable switch to ensure that the stats table global
1488 // is initialized correctly.
1489 if (command_line->HasSwitch(switches::kEnableBenchmarking))
1490 DCHECK(command_line->HasSwitch(switches::kEnableStatsTable));
1493 std::string ChromeContentBrowserClient::GetApplicationLocale() {
1494 if (BrowserThread::CurrentlyOn(BrowserThread::IO))
1495 return g_io_thread_application_locale.Get();
1496 return g_browser_process->GetApplicationLocale();
1499 std::string ChromeContentBrowserClient::GetAcceptLangs(
1500 content::BrowserContext* context) {
1501 Profile* profile = Profile::FromBrowserContext(context);
1502 return profile->GetPrefs()->GetString(prefs::kAcceptLanguages);
1505 const gfx::ImageSkia* ChromeContentBrowserClient::GetDefaultFavicon() {
1506 ResourceBundle& rb = ResourceBundle::GetSharedInstance();
1507 return rb.GetNativeImageNamed(IDR_DEFAULT_FAVICON).ToImageSkia();
1510 bool ChromeContentBrowserClient::AllowAppCache(
1511 const GURL& manifest_url,
1512 const GURL& first_party,
1513 content::ResourceContext* context) {
1514 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1515 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1516 return io_data->GetCookieSettings()->
1517 IsSettingCookieAllowed(manifest_url, first_party);
1520 bool ChromeContentBrowserClient::AllowServiceWorker(
1521 const GURL& scope,
1522 const GURL& first_party_url,
1523 content::ResourceContext* context) {
1524 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1525 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1526 return io_data->GetCookieSettings()->
1527 IsSettingCookieAllowed(scope, first_party_url);
1530 bool ChromeContentBrowserClient::AllowGetCookie(
1531 const GURL& url,
1532 const GURL& first_party,
1533 const net::CookieList& cookie_list,
1534 content::ResourceContext* context,
1535 int render_process_id,
1536 int render_frame_id) {
1537 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1538 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1539 bool allow = io_data->GetCookieSettings()->
1540 IsReadingCookieAllowed(url, first_party);
1542 BrowserThread::PostTask(
1543 BrowserThread::UI, FROM_HERE,
1544 base::Bind(&TabSpecificContentSettings::CookiesRead, render_process_id,
1545 render_frame_id, url, first_party, cookie_list, !allow));
1546 return allow;
1549 bool ChromeContentBrowserClient::AllowSetCookie(
1550 const GURL& url,
1551 const GURL& first_party,
1552 const std::string& cookie_line,
1553 content::ResourceContext* context,
1554 int render_process_id,
1555 int render_frame_id,
1556 net::CookieOptions* options) {
1557 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1558 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1559 CookieSettings* cookie_settings = io_data->GetCookieSettings();
1560 bool allow = cookie_settings->IsSettingCookieAllowed(url, first_party);
1562 BrowserThread::PostTask(
1563 BrowserThread::UI, FROM_HERE,
1564 base::Bind(&TabSpecificContentSettings::CookieChanged, render_process_id,
1565 render_frame_id, url, first_party, cookie_line, *options,
1566 !allow));
1567 return allow;
1570 bool ChromeContentBrowserClient::AllowSaveLocalState(
1571 content::ResourceContext* context) {
1572 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1573 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1574 CookieSettings* cookie_settings = io_data->GetCookieSettings();
1575 ContentSetting setting = cookie_settings->GetDefaultCookieSetting(NULL);
1577 // TODO(bauerb): Should we also disallow local state if the default is BLOCK?
1578 // Could we even support per-origin settings?
1579 return setting != CONTENT_SETTING_SESSION_ONLY;
1582 bool ChromeContentBrowserClient::AllowWorkerDatabase(
1583 const GURL& url,
1584 const base::string16& name,
1585 const base::string16& display_name,
1586 unsigned long estimated_size,
1587 content::ResourceContext* context,
1588 const std::vector<std::pair<int, int> >& render_frames) {
1589 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1590 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1591 CookieSettings* cookie_settings = io_data->GetCookieSettings();
1592 bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1594 // Record access to database for potential display in UI.
1595 std::vector<std::pair<int, int> >::const_iterator i;
1596 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1597 BrowserThread::PostTask(
1598 BrowserThread::UI, FROM_HERE,
1599 base::Bind(&TabSpecificContentSettings::WebDatabaseAccessed,
1600 i->first, i->second, url, name, display_name, !allow));
1603 return allow;
1606 void ChromeContentBrowserClient::AllowWorkerFileSystem(
1607 const GURL& url,
1608 content::ResourceContext* context,
1609 const std::vector<std::pair<int, int> >& render_frames,
1610 base::Callback<void(bool)> callback) {
1611 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1612 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1613 CookieSettings* cookie_settings = io_data->GetCookieSettings();
1614 bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1616 #if defined(ENABLE_EXTENSIONS)
1617 GuestPermissionRequestHelper(url, render_frames, callback, allow);
1618 #else
1619 FileSystemAccessed(url, render_frames, callback, allow);
1620 #endif
1623 #if defined(ENABLE_EXTENSIONS)
1624 void ChromeContentBrowserClient::GuestPermissionRequestHelper(
1625 const GURL& url,
1626 const std::vector<std::pair<int, int> >& render_frames,
1627 base::Callback<void(bool)> callback,
1628 bool allow) {
1629 DCHECK(BrowserThread:: CurrentlyOn(BrowserThread::IO));
1630 std::vector<std::pair<int, int> >::const_iterator i;
1631 std::map<int, int> process_map;
1632 std::map<int, int>::const_iterator it;
1633 bool has_web_view_guest = false;
1634 // Record access to file system for potential display in UI.
1635 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1636 if (process_map.find(i->first) != process_map.end())
1637 continue;
1639 process_map.insert(std::pair<int, int>(i->first, i->second));
1641 if (extensions::WebViewRendererState::GetInstance()->IsGuest(i->first))
1642 has_web_view_guest = true;
1644 if (!has_web_view_guest) {
1645 FileSystemAccessed(url, render_frames, callback, allow);
1646 return;
1648 DCHECK_EQ(1U, process_map.size());
1649 it = process_map.begin();
1650 BrowserThread::PostTask(
1651 BrowserThread::UI,
1652 FROM_HERE,
1653 base::Bind(&ChromeContentBrowserClient::
1654 RequestFileSystemPermissionOnUIThread,
1655 it->first,
1656 it->second,
1657 url,
1658 allow,
1659 base::Bind(&ChromeContentBrowserClient::FileSystemAccessed,
1660 weak_factory_.GetWeakPtr(),
1661 url,
1662 render_frames,
1663 callback)));
1666 void ChromeContentBrowserClient::RequestFileSystemPermissionOnUIThread(
1667 int render_process_id,
1668 int render_frame_id,
1669 const GURL& url,
1670 bool allowed_by_default,
1671 const base::Callback<void(bool)>& callback) {
1672 DCHECK(BrowserThread:: CurrentlyOn(BrowserThread::UI));
1673 extensions::WebViewPermissionHelper* web_view_permission_helper =
1674 extensions::WebViewPermissionHelper::FromFrameID(
1675 render_process_id, render_frame_id);
1676 web_view_permission_helper->RequestFileSystemPermission(url,
1677 allowed_by_default,
1678 callback);
1680 #endif
1682 void ChromeContentBrowserClient::FileSystemAccessed(
1683 const GURL& url,
1684 const std::vector<std::pair<int, int> >& render_frames,
1685 base::Callback<void(bool)> callback,
1686 bool allow) {
1687 // Record access to file system for potential display in UI.
1688 std::vector<std::pair<int, int> >::const_iterator i;
1689 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1690 BrowserThread::PostTask(
1691 BrowserThread::UI,
1692 FROM_HERE,
1693 base::Bind(&TabSpecificContentSettings::FileSystemAccessed,
1694 i->first, i->second, url, !allow));
1696 callback.Run(allow);
1699 bool ChromeContentBrowserClient::AllowWorkerIndexedDB(
1700 const GURL& url,
1701 const base::string16& name,
1702 content::ResourceContext* context,
1703 const std::vector<std::pair<int, int> >& render_frames) {
1704 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1705 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1706 CookieSettings* cookie_settings = io_data->GetCookieSettings();
1707 bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1709 // Record access to IndexedDB for potential display in UI.
1710 std::vector<std::pair<int, int> >::const_iterator i;
1711 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1712 BrowserThread::PostTask(
1713 BrowserThread::UI, FROM_HERE,
1714 base::Bind(&TabSpecificContentSettings::IndexedDBAccessed,
1715 i->first, i->second, url, name, !allow));
1718 return allow;
1721 net::URLRequestContext*
1722 ChromeContentBrowserClient::OverrideRequestContextForURL(
1723 const GURL& url, content::ResourceContext* context) {
1724 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1725 #if defined(ENABLE_EXTENSIONS)
1726 if (url.SchemeIs(extensions::kExtensionScheme)) {
1727 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1728 return io_data->extensions_request_context();
1730 #endif
1732 return NULL;
1735 QuotaPermissionContext*
1736 ChromeContentBrowserClient::CreateQuotaPermissionContext() {
1737 return new ChromeQuotaPermissionContext();
1740 void ChromeContentBrowserClient::AllowCertificateError(
1741 int render_process_id,
1742 int render_frame_id,
1743 int cert_error,
1744 const net::SSLInfo& ssl_info,
1745 const GURL& request_url,
1746 ResourceType resource_type,
1747 bool overridable,
1748 bool strict_enforcement,
1749 bool expired_previous_decision,
1750 const base::Callback<void(bool)>& callback,
1751 content::CertificateRequestResultType* result) {
1752 if (resource_type != content::RESOURCE_TYPE_MAIN_FRAME) {
1753 // A sub-resource has a certificate error. The user doesn't really
1754 // have a context for making the right decision, so block the
1755 // request hard, without an info bar to allow showing the insecure
1756 // content.
1757 *result = content::CERTIFICATE_REQUEST_RESULT_TYPE_DENY;
1758 return;
1761 // If the tab is being prerendered, cancel the prerender and the request.
1762 content::RenderFrameHost* render_frame_host =
1763 content::RenderFrameHost::FromID(render_process_id, render_frame_id);
1764 WebContents* tab = WebContents::FromRenderFrameHost(render_frame_host);
1765 if (!tab) {
1766 NOTREACHED();
1767 return;
1770 prerender::PrerenderContents* prerender_contents =
1771 prerender::PrerenderContents::FromWebContents(tab);
1772 if (prerender_contents) {
1773 prerender_contents->Destroy(prerender::FINAL_STATUS_SSL_ERROR);
1774 *result = content::CERTIFICATE_REQUEST_RESULT_TYPE_CANCEL;
1775 return;
1778 // Otherwise, display an SSL blocking page. The interstitial page takes
1779 // ownership of ssl_blocking_page.
1780 int options_mask = 0;
1781 if (overridable)
1782 options_mask |= SSLBlockingPage::OVERRIDABLE;
1783 if (strict_enforcement)
1784 options_mask |= SSLBlockingPage::STRICT_ENFORCEMENT;
1785 if (expired_previous_decision)
1786 options_mask |= SSLBlockingPage::EXPIRED_BUT_PREVIOUSLY_ALLOWED;
1788 SSLErrorHandler::HandleSSLError(
1789 tab, cert_error, ssl_info, request_url, options_mask, callback);
1792 void ChromeContentBrowserClient::SelectClientCertificate(
1793 content::WebContents* web_contents,
1794 net::SSLCertRequestInfo* cert_request_info,
1795 scoped_ptr<content::ClientCertificateDelegate> delegate) {
1796 prerender::PrerenderContents* prerender_contents =
1797 prerender::PrerenderContents::FromWebContents(web_contents);
1798 if (prerender_contents) {
1799 prerender_contents->Destroy(
1800 prerender::FINAL_STATUS_SSL_CLIENT_CERTIFICATE_REQUESTED);
1801 return;
1804 GURL requesting_url("https://" + cert_request_info->host_and_port.ToString());
1805 DCHECK(requesting_url.is_valid())
1806 << "Invalid URL string: https://"
1807 << cert_request_info->host_and_port.ToString();
1809 Profile* profile =
1810 Profile::FromBrowserContext(web_contents->GetBrowserContext());
1811 scoped_ptr<base::Value> filter =
1812 profile->GetHostContentSettingsMap()->GetWebsiteSetting(
1813 requesting_url,
1814 requesting_url,
1815 CONTENT_SETTINGS_TYPE_AUTO_SELECT_CERTIFICATE,
1816 std::string(),
1817 NULL);
1819 if (filter.get()) {
1820 // Try to automatically select a client certificate.
1821 if (filter->IsType(base::Value::TYPE_DICTIONARY)) {
1822 base::DictionaryValue* filter_dict =
1823 static_cast<base::DictionaryValue*>(filter.get());
1825 const std::vector<scoped_refptr<net::X509Certificate> >&
1826 all_client_certs = cert_request_info->client_certs;
1827 for (size_t i = 0; i < all_client_certs.size(); ++i) {
1828 if (CertMatchesFilter(*all_client_certs[i].get(), *filter_dict)) {
1829 // Use the first certificate that is matched by the filter.
1830 delegate->ContinueWithCertificate(all_client_certs[i].get());
1831 return;
1834 } else {
1835 NOTREACHED();
1839 chrome::ShowSSLClientCertificateSelector(web_contents, cert_request_info,
1840 delegate.Pass());
1843 void ChromeContentBrowserClient::AddCertificate(
1844 net::CertificateMimeType cert_type,
1845 const void* cert_data,
1846 size_t cert_size,
1847 int render_process_id,
1848 int render_frame_id) {
1849 chrome::SSLAddCertificate(cert_type, cert_data, cert_size,
1850 render_process_id, render_frame_id);
1853 content::MediaObserver* ChromeContentBrowserClient::GetMediaObserver() {
1854 return MediaCaptureDevicesDispatcher::GetInstance();
1857 content::PlatformNotificationService*
1858 ChromeContentBrowserClient::GetPlatformNotificationService() {
1859 #if defined(ENABLE_NOTIFICATIONS)
1860 return PlatformNotificationServiceImpl::GetInstance();
1861 #else
1862 NOTIMPLEMENTED();
1863 return NULL;
1864 #endif
1867 void ChromeContentBrowserClient::RequestPermission(
1868 content::PermissionType permission,
1869 content::WebContents* web_contents,
1870 int bridge_id,
1871 const GURL& requesting_frame,
1872 bool user_gesture,
1873 const base::Callback<void(content::PermissionStatus)>& result_callback) {
1874 int render_process_id = web_contents->GetRenderProcessHost()->GetID();
1875 int render_view_id = web_contents->GetRenderViewHost()->GetRoutingID();
1876 const PermissionRequestID request_id(render_process_id,
1877 render_view_id,
1878 bridge_id,
1879 requesting_frame);
1880 Profile* profile =
1881 Profile::FromBrowserContext(web_contents->GetBrowserContext());
1882 PermissionContextBase* context = GetPermissionContext(profile, permission);
1884 if (!context)
1885 return;
1887 context->RequestPermission(web_contents, request_id, requesting_frame,
1888 user_gesture,
1889 base::Bind(&OnRequestPermission, result_callback));
1892 content::PermissionStatus ChromeContentBrowserClient::GetPermissionStatus(
1893 content::PermissionType permission,
1894 content::BrowserContext* browser_context,
1895 const GURL& requesting_origin,
1896 const GURL& embedding_origin) {
1897 DCHECK(browser_context);
1898 Profile* profile = Profile::FromBrowserContext(browser_context);
1899 PermissionContextBase* context = GetPermissionContext(profile, permission);
1901 if (!context)
1902 return content::PERMISSION_STATUS_ASK;
1904 return ContentSettingToPermissionStatus(
1905 context->GetPermissionStatus(requesting_origin.GetOrigin(),
1906 embedding_origin.GetOrigin()));
1909 void ChromeContentBrowserClient::ResetPermission(
1910 content::PermissionType permission,
1911 content::BrowserContext* browser_context,
1912 const GURL& requesting_origin,
1913 const GURL& embedding_origin) {
1914 DCHECK(browser_context);
1915 Profile* profile = Profile::FromBrowserContext(browser_context);
1916 PermissionContextBase* context = GetPermissionContext(profile, permission);
1918 if (!context)
1919 return;
1921 context->ResetPermission(requesting_origin.GetOrigin(),
1922 embedding_origin.GetOrigin());
1925 void ChromeContentBrowserClient::CancelPermissionRequest(
1926 content::PermissionType permission,
1927 content::WebContents* web_contents,
1928 int bridge_id,
1929 const GURL& requesting_frame) {
1930 int render_process_id = web_contents->GetRenderProcessHost()->GetID();
1931 int render_view_id = web_contents->GetRenderViewHost()->GetRoutingID();
1932 const PermissionRequestID request_id(render_process_id,
1933 render_view_id,
1934 bridge_id,
1935 requesting_frame);
1936 Profile* profile =
1937 Profile::FromBrowserContext(web_contents->GetBrowserContext());
1938 PermissionContextBase* context = GetPermissionContext(profile, permission);
1939 if (!context)
1940 return;
1941 context->CancelPermissionRequest(web_contents, request_id);
1944 void ChromeContentBrowserClient::RegisterPermissionUsage(
1945 content::PermissionType permission,
1946 content::WebContents* web_contents,
1947 const GURL& frame_url,
1948 const GURL& main_frame_url) {
1949 Profile::FromBrowserContext(web_contents->GetBrowserContext())
1950 ->GetHostContentSettingsMap()
1951 ->UpdateLastUsage(
1952 frame_url, main_frame_url, PermissionToContentSetting(permission));
1955 bool ChromeContentBrowserClient::CanCreateWindow(
1956 const GURL& opener_url,
1957 const GURL& opener_top_level_frame_url,
1958 const GURL& source_origin,
1959 WindowContainerType container_type,
1960 const GURL& target_url,
1961 const content::Referrer& referrer,
1962 WindowOpenDisposition disposition,
1963 const WebWindowFeatures& features,
1964 bool user_gesture,
1965 bool opener_suppressed,
1966 content::ResourceContext* context,
1967 int render_process_id,
1968 int opener_id,
1969 bool* no_javascript_access) {
1970 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1972 *no_javascript_access = false;
1974 // If the opener is trying to create a background window but doesn't have
1975 // the appropriate permission, fail the attempt.
1976 if (container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {
1977 #if defined(ENABLE_EXTENSIONS)
1978 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1979 InfoMap* map = io_data->GetExtensionInfoMap();
1980 if (!map->SecurityOriginHasAPIPermission(
1981 source_origin,
1982 render_process_id,
1983 APIPermission::kBackground)) {
1984 return false;
1987 // Note: this use of GetExtensionOrAppByURL is safe but imperfect. It may
1988 // return a recently installed Extension even if this CanCreateWindow call
1989 // was made by an old copy of the page in a normal web process. That's ok,
1990 // because the permission check above would have caused an early return
1991 // already. We must use the full URL to find hosted apps, though, and not
1992 // just the origin.
1993 const Extension* extension =
1994 map->extensions().GetExtensionOrAppByURL(opener_url);
1995 if (extension && !extensions::BackgroundInfo::AllowJSAccess(extension))
1996 *no_javascript_access = true;
1997 #endif
1999 return true;
2002 #if defined(ENABLE_EXTENSIONS)
2003 if (extensions::WebViewRendererState::GetInstance()->IsGuest(
2004 render_process_id))
2005 return true;
2006 #endif
2008 HostContentSettingsMap* content_settings =
2009 ProfileIOData::FromResourceContext(context)->GetHostContentSettingsMap();
2010 BlockedWindowParams blocked_params(target_url,
2011 referrer,
2012 disposition,
2013 features,
2014 user_gesture,
2015 opener_suppressed,
2016 render_process_id,
2017 opener_id);
2019 if (!user_gesture &&
2020 !base::CommandLine::ForCurrentProcess()->HasSwitch(
2021 switches::kDisablePopupBlocking)) {
2022 if (content_settings->GetContentSetting(opener_top_level_frame_url,
2023 opener_top_level_frame_url,
2024 CONTENT_SETTINGS_TYPE_POPUPS,
2025 std::string()) !=
2026 CONTENT_SETTING_ALLOW) {
2027 BrowserThread::PostTask(BrowserThread::UI,
2028 FROM_HERE,
2029 base::Bind(&HandleBlockedPopupOnUIThread,
2030 blocked_params));
2031 return false;
2035 #if defined(OS_ANDROID)
2036 if (SingleTabModeTabHelper::IsRegistered(render_process_id, opener_id)) {
2037 BrowserThread::PostTask(BrowserThread::UI,
2038 FROM_HERE,
2039 base::Bind(&HandleSingleTabModeBlockOnUIThread,
2040 blocked_params));
2041 return false;
2043 #endif
2045 return true;
2048 void ChromeContentBrowserClient::ResourceDispatcherHostCreated() {
2049 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
2050 return g_browser_process->ResourceDispatcherHostCreated();
2053 content::SpeechRecognitionManagerDelegate*
2054 ChromeContentBrowserClient::CreateSpeechRecognitionManagerDelegate() {
2055 return new speech::ChromeSpeechRecognitionManagerDelegate();
2058 net::NetLog* ChromeContentBrowserClient::GetNetLog() {
2059 return g_browser_process->net_log();
2062 AccessTokenStore* ChromeContentBrowserClient::CreateAccessTokenStore() {
2063 return new ChromeAccessTokenStore();
2066 bool ChromeContentBrowserClient::IsFastShutdownPossible() {
2067 return true;
2070 void ChromeContentBrowserClient::OverrideWebkitPrefs(
2071 RenderViewHost* rvh, WebPreferences* web_prefs) {
2072 Profile* profile = Profile::FromBrowserContext(
2073 rvh->GetProcess()->GetBrowserContext());
2074 PrefService* prefs = profile->GetPrefs();
2076 // Fill per-script font preferences. These are not registered on Android
2077 // - http://crbug.com/308033.
2078 #if !defined(OS_ANDROID)
2079 FontFamilyCache::FillFontFamilyMap(profile,
2080 prefs::kWebKitStandardFontFamilyMap,
2081 &web_prefs->standard_font_family_map);
2082 FontFamilyCache::FillFontFamilyMap(profile,
2083 prefs::kWebKitFixedFontFamilyMap,
2084 &web_prefs->fixed_font_family_map);
2085 FontFamilyCache::FillFontFamilyMap(profile,
2086 prefs::kWebKitSerifFontFamilyMap,
2087 &web_prefs->serif_font_family_map);
2088 FontFamilyCache::FillFontFamilyMap(profile,
2089 prefs::kWebKitSansSerifFontFamilyMap,
2090 &web_prefs->sans_serif_font_family_map);
2091 FontFamilyCache::FillFontFamilyMap(profile,
2092 prefs::kWebKitCursiveFontFamilyMap,
2093 &web_prefs->cursive_font_family_map);
2094 FontFamilyCache::FillFontFamilyMap(profile,
2095 prefs::kWebKitFantasyFontFamilyMap,
2096 &web_prefs->fantasy_font_family_map);
2097 FontFamilyCache::FillFontFamilyMap(profile,
2098 prefs::kWebKitPictographFontFamilyMap,
2099 &web_prefs->pictograph_font_family_map);
2100 #endif
2102 web_prefs->default_font_size =
2103 prefs->GetInteger(prefs::kWebKitDefaultFontSize);
2104 web_prefs->default_fixed_font_size =
2105 prefs->GetInteger(prefs::kWebKitDefaultFixedFontSize);
2106 web_prefs->minimum_font_size =
2107 prefs->GetInteger(prefs::kWebKitMinimumFontSize);
2108 web_prefs->minimum_logical_font_size =
2109 prefs->GetInteger(prefs::kWebKitMinimumLogicalFontSize);
2111 web_prefs->default_encoding = prefs->GetString(prefs::kDefaultCharset);
2113 web_prefs->javascript_can_open_windows_automatically =
2114 prefs->GetBoolean(prefs::kWebKitJavascriptCanOpenWindowsAutomatically);
2115 web_prefs->dom_paste_enabled =
2116 prefs->GetBoolean(prefs::kWebKitDomPasteEnabled);
2117 web_prefs->shrinks_standalone_images_to_fit =
2118 prefs->GetBoolean(prefs::kWebKitShrinksStandaloneImagesToFit);
2119 web_prefs->tabs_to_links = prefs->GetBoolean(prefs::kWebkitTabsToLinks);
2121 if (!prefs->GetBoolean(prefs::kWebKitJavascriptEnabled))
2122 web_prefs->javascript_enabled = false;
2123 if (!prefs->GetBoolean(prefs::kWebKitWebSecurityEnabled))
2124 web_prefs->web_security_enabled = false;
2125 if (!prefs->GetBoolean(prefs::kWebKitPluginsEnabled))
2126 web_prefs->plugins_enabled = false;
2127 if (!prefs->GetBoolean(prefs::kWebKitJavaEnabled))
2128 web_prefs->java_enabled = false;
2129 web_prefs->loads_images_automatically =
2130 prefs->GetBoolean(prefs::kWebKitLoadsImagesAutomatically);
2132 if (prefs->GetBoolean(prefs::kDisable3DAPIs))
2133 web_prefs->experimental_webgl_enabled = false;
2135 web_prefs->allow_displaying_insecure_content =
2136 prefs->GetBoolean(prefs::kWebKitAllowDisplayingInsecureContent);
2137 web_prefs->allow_running_insecure_content =
2138 prefs->GetBoolean(prefs::kWebKitAllowRunningInsecureContent);
2139 #if defined(OS_ANDROID)
2140 web_prefs->font_scale_factor =
2141 static_cast<float>(prefs->GetDouble(prefs::kWebKitFontScaleFactor));
2142 web_prefs->device_scale_adjustment = GetDeviceScaleAdjustment();
2143 web_prefs->force_enable_zoom =
2144 prefs->GetBoolean(prefs::kWebKitForceEnableZoom);
2145 #endif
2147 #if defined(OS_ANDROID)
2148 web_prefs->password_echo_enabled =
2149 prefs->GetBoolean(prefs::kWebKitPasswordEchoEnabled);
2150 #else
2151 web_prefs->password_echo_enabled = browser_defaults::kPasswordEchoEnabled;
2152 #endif
2154 web_prefs->asynchronous_spell_checking_enabled = true;
2155 web_prefs->unified_textchecker_enabled = true;
2157 web_prefs->uses_universal_detector =
2158 prefs->GetBoolean(prefs::kWebKitUsesUniversalDetector);
2159 web_prefs->text_areas_are_resizable =
2160 prefs->GetBoolean(prefs::kWebKitTextAreasAreResizable);
2161 web_prefs->hyperlink_auditing_enabled =
2162 prefs->GetBoolean(prefs::kEnableHyperlinkAuditing);
2164 #if defined(ENABLE_EXTENSIONS)
2165 std::string image_animation_policy =
2166 prefs->GetString(prefs::kAnimationPolicy);
2167 if (image_animation_policy == kAnimationPolicyOnce)
2168 web_prefs->animation_policy =
2169 content::IMAGE_ANIMATION_POLICY_ANIMATION_ONCE;
2170 else if (image_animation_policy == kAnimationPolicyNone)
2171 web_prefs->animation_policy = content::IMAGE_ANIMATION_POLICY_NO_ANIMATION;
2172 else
2173 web_prefs->animation_policy = content::IMAGE_ANIMATION_POLICY_ALLOWED;
2174 #endif
2176 // Make sure we will set the default_encoding with canonical encoding name.
2177 web_prefs->default_encoding =
2178 CharacterEncoding::GetCanonicalEncodingNameByAliasName(
2179 web_prefs->default_encoding);
2180 if (web_prefs->default_encoding.empty()) {
2181 prefs->ClearPref(prefs::kDefaultCharset);
2182 web_prefs->default_encoding = prefs->GetString(prefs::kDefaultCharset);
2184 DCHECK(!web_prefs->default_encoding.empty());
2186 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2187 switches::kEnablePotentiallyAnnoyingSecurityFeatures)) {
2188 web_prefs->disable_reading_from_canvas = true;
2189 web_prefs->strict_mixed_content_checking = true;
2190 web_prefs->strict_powerful_feature_restrictions = true;
2193 for (size_t i = 0; i < extra_parts_.size(); ++i)
2194 extra_parts_[i]->OverrideWebkitPrefs(rvh, web_prefs);
2197 void ChromeContentBrowserClient::BrowserURLHandlerCreated(
2198 BrowserURLHandler* handler) {
2199 for (size_t i = 0; i < extra_parts_.size(); ++i)
2200 extra_parts_[i]->BrowserURLHandlerCreated(handler);
2202 // about: handler. Must come before chrome: handler, since it will
2203 // rewrite about: urls to chrome: URLs and then expect chrome: to
2204 // actually handle them. Also relies on a preliminary fixup phase.
2205 handler->SetFixupHandler(&FixupBrowserAboutURL);
2206 handler->AddHandlerPair(&WillHandleBrowserAboutURL,
2207 BrowserURLHandler::null_handler());
2209 #if defined(OS_ANDROID)
2210 // Handler to rewrite chrome://newtab on Android.
2211 handler->AddHandlerPair(&chrome::android::HandleAndroidNativePageURL,
2212 BrowserURLHandler::null_handler());
2213 #else
2214 // Handler to rewrite chrome://newtab for InstantExtended.
2215 handler->AddHandlerPair(&chrome::HandleNewTabURLRewrite,
2216 &chrome::HandleNewTabURLReverseRewrite);
2217 #endif
2219 // chrome: & friends.
2220 handler->AddHandlerPair(&HandleWebUI, &HandleWebUIReverse);
2223 void ChromeContentBrowserClient::ClearCache(RenderViewHost* rvh) {
2224 Profile* profile = Profile::FromBrowserContext(
2225 rvh->GetSiteInstance()->GetProcess()->GetBrowserContext());
2226 BrowsingDataRemover* remover =
2227 BrowsingDataRemover::CreateForUnboundedRange(profile);
2228 remover->Remove(BrowsingDataRemover::REMOVE_CACHE,
2229 BrowsingDataHelper::UNPROTECTED_WEB);
2230 // BrowsingDataRemover takes care of deleting itself when done.
2233 void ChromeContentBrowserClient::ClearCookies(RenderViewHost* rvh) {
2234 Profile* profile = Profile::FromBrowserContext(
2235 rvh->GetSiteInstance()->GetProcess()->GetBrowserContext());
2236 BrowsingDataRemover* remover =
2237 BrowsingDataRemover::CreateForUnboundedRange(profile);
2238 int remove_mask = BrowsingDataRemover::REMOVE_SITE_DATA;
2239 remover->Remove(remove_mask, BrowsingDataHelper::UNPROTECTED_WEB);
2240 // BrowsingDataRemover takes care of deleting itself when done.
2243 base::FilePath ChromeContentBrowserClient::GetDefaultDownloadDirectory() {
2244 return DownloadPrefs::GetDefaultDownloadDirectory();
2247 std::string ChromeContentBrowserClient::GetDefaultDownloadName() {
2248 return l10n_util::GetStringUTF8(IDS_DEFAULT_DOWNLOAD_FILENAME);
2251 void ChromeContentBrowserClient::DidCreatePpapiPlugin(
2252 content::BrowserPpapiHost* browser_host) {
2253 #if defined(ENABLE_PLUGINS)
2254 ChromeContentBrowserClientPluginsPart::DidCreatePpapiPlugin(browser_host);
2255 #endif
2258 content::BrowserPpapiHost*
2259 ChromeContentBrowserClient::GetExternalBrowserPpapiHost(
2260 int plugin_process_id) {
2261 #if !defined(DISABLE_NACL)
2262 content::BrowserChildProcessHostIterator iter(PROCESS_TYPE_NACL_LOADER);
2263 while (!iter.Done()) {
2264 nacl::NaClProcessHost* host = static_cast<nacl::NaClProcessHost*>(
2265 iter.GetDelegate());
2266 if (host->process() &&
2267 host->process()->GetData().id == plugin_process_id) {
2268 // Found the plugin.
2269 return host->browser_ppapi_host();
2271 ++iter;
2273 #endif
2274 return NULL;
2277 bool ChromeContentBrowserClient::AllowPepperSocketAPI(
2278 content::BrowserContext* browser_context,
2279 const GURL& url,
2280 bool private_api,
2281 const content::SocketPermissionRequest* params) {
2282 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
2283 return ChromeContentBrowserClientPluginsPart::AllowPepperSocketAPI(
2284 browser_context, url, private_api, params, allowed_socket_origins_);
2285 #else
2286 return false;
2287 #endif
2290 ui::SelectFilePolicy* ChromeContentBrowserClient::CreateSelectFilePolicy(
2291 WebContents* web_contents) {
2292 return new ChromeSelectFilePolicy(web_contents);
2295 void ChromeContentBrowserClient::GetAdditionalAllowedSchemesForFileSystem(
2296 std::vector<std::string>* additional_allowed_schemes) {
2297 ContentBrowserClient::GetAdditionalAllowedSchemesForFileSystem(
2298 additional_allowed_schemes);
2299 additional_allowed_schemes->push_back(content::kChromeDevToolsScheme);
2300 additional_allowed_schemes->push_back(content::kChromeUIScheme);
2301 for (size_t i = 0; i < extra_parts_.size(); ++i) {
2302 extra_parts_[i]->GetAdditionalAllowedSchemesForFileSystem(
2303 additional_allowed_schemes);
2307 void ChromeContentBrowserClient::GetURLRequestAutoMountHandlers(
2308 std::vector<storage::URLRequestAutoMountHandler>* handlers) {
2309 for (size_t i = 0; i < extra_parts_.size(); ++i)
2310 extra_parts_[i]->GetURLRequestAutoMountHandlers(handlers);
2313 void ChromeContentBrowserClient::GetAdditionalFileSystemBackends(
2314 content::BrowserContext* browser_context,
2315 const base::FilePath& storage_partition_path,
2316 ScopedVector<storage::FileSystemBackend>* additional_backends) {
2317 #if defined(OS_CHROMEOS)
2318 storage::ExternalMountPoints* external_mount_points =
2319 content::BrowserContext::GetMountPoints(browser_context);
2320 DCHECK(external_mount_points);
2321 chromeos::FileSystemBackend* backend = new chromeos::FileSystemBackend(
2322 new drive::FileSystemBackendDelegate,
2323 new chromeos::file_system_provider::BackendDelegate,
2324 new chromeos::MTPFileSystemBackendDelegate(storage_partition_path),
2325 browser_context->GetSpecialStoragePolicy(),
2326 external_mount_points,
2327 storage::ExternalMountPoints::GetSystemInstance());
2328 backend->AddSystemMountPoints();
2329 DCHECK(backend->CanHandleType(storage::kFileSystemTypeExternal));
2330 additional_backends->push_back(backend);
2331 #endif
2333 for (size_t i = 0; i < extra_parts_.size(); ++i) {
2334 extra_parts_[i]->GetAdditionalFileSystemBackends(
2335 browser_context, storage_partition_path, additional_backends);
2339 #if defined(OS_POSIX) && !defined(OS_MACOSX)
2340 void ChromeContentBrowserClient::GetAdditionalMappedFilesForChildProcess(
2341 const base::CommandLine& command_line,
2342 int child_process_id,
2343 FileDescriptorInfo* mappings) {
2344 #if defined(V8_USE_EXTERNAL_STARTUP_DATA)
2345 if (v8_snapshot_fd_.get() == -1 && v8_natives_fd_.get() == -1) {
2346 base::FilePath v8_data_path;
2347 PathService::Get(gin::IsolateHolder::kV8SnapshotBasePathKey, &v8_data_path);
2348 DCHECK(!v8_data_path.empty());
2350 int file_flags = base::File::FLAG_OPEN | base::File::FLAG_READ;
2351 base::FilePath v8_natives_data_path =
2352 v8_data_path.AppendASCII(gin::IsolateHolder::kNativesFileName);
2353 base::FilePath v8_snapshot_data_path =
2354 v8_data_path.AppendASCII(gin::IsolateHolder::kSnapshotFileName);
2355 base::File v8_natives_data_file(v8_natives_data_path, file_flags);
2356 base::File v8_snapshot_data_file(v8_snapshot_data_path, file_flags);
2357 DCHECK(v8_natives_data_file.IsValid());
2358 DCHECK(v8_snapshot_data_file.IsValid());
2359 v8_natives_fd_.reset(v8_natives_data_file.TakePlatformFile());
2360 v8_snapshot_fd_.reset(v8_snapshot_data_file.TakePlatformFile());
2362 mappings->Share(kV8NativesDataDescriptor, v8_natives_fd_.get());
2363 mappings->Share(kV8SnapshotDataDescriptor, v8_snapshot_fd_.get());
2364 #endif // V8_USE_EXTERNAL_STARTUP_DATA
2366 #if defined(OS_ANDROID)
2367 base::FilePath data_path;
2368 PathService::Get(ui::DIR_RESOURCE_PAKS_ANDROID, &data_path);
2369 DCHECK(!data_path.empty());
2371 int flags = base::File::FLAG_OPEN | base::File::FLAG_READ;
2372 base::FilePath chrome_resources_pak =
2373 data_path.AppendASCII("chrome_100_percent.pak");
2374 base::File file(chrome_resources_pak, flags);
2375 DCHECK(file.IsValid());
2376 mappings->Transfer(kAndroidChrome100PercentPakDescriptor,
2377 base::ScopedFD(file.TakePlatformFile()));
2379 const std::string locale = GetApplicationLocale();
2380 base::FilePath locale_pak = ResourceBundle::GetSharedInstance().
2381 GetLocaleFilePath(locale, false);
2382 file.Initialize(locale_pak, flags);
2383 DCHECK(file.IsValid());
2384 mappings->Transfer(kAndroidLocalePakDescriptor,
2385 base::ScopedFD(file.TakePlatformFile()));
2387 base::FilePath resources_pack_path;
2388 PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
2389 file.Initialize(resources_pack_path, flags);
2390 DCHECK(file.IsValid());
2391 mappings->Transfer(kAndroidUIResourcesPakDescriptor,
2392 base::ScopedFD(file.TakePlatformFile()));
2394 if (breakpad::IsCrashReporterEnabled()) {
2395 file = breakpad::CrashDumpManager::GetInstance()->CreateMinidumpFile(
2396 child_process_id);
2397 if (file.IsValid()) {
2398 mappings->Transfer(kAndroidMinidumpDescriptor,
2399 base::ScopedFD(file.TakePlatformFile()));
2400 } else {
2401 LOG(ERROR) << "Failed to create file for minidump, crash reporting will "
2402 "be disabled for this process.";
2406 base::FilePath app_data_path;
2407 PathService::Get(base::DIR_ANDROID_APP_DATA, &app_data_path);
2408 DCHECK(!app_data_path.empty());
2410 flags = base::File::FLAG_OPEN | base::File::FLAG_READ;
2411 base::FilePath icudata_path =
2412 app_data_path.AppendASCII(base::i18n::kIcuDataFileName);
2413 base::File icudata_file(icudata_path, flags);
2414 DCHECK(icudata_file.IsValid());
2415 mappings->Transfer(kAndroidICUDataDescriptor,
2416 base::ScopedFD(icudata_file.TakePlatformFile()));
2417 #else
2418 int crash_signal_fd = GetCrashSignalFD(command_line);
2419 if (crash_signal_fd >= 0) {
2420 mappings->Share(kCrashDumpSignal, crash_signal_fd);
2422 #endif // defined(OS_ANDROID)
2424 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
2426 #if defined(OS_WIN)
2427 const wchar_t* ChromeContentBrowserClient::GetResourceDllName() {
2428 return chrome::kBrowserResourcesDll;
2431 void ChromeContentBrowserClient::PreSpawnRenderer(
2432 sandbox::TargetPolicy* policy,
2433 bool* success) {
2434 // This code is duplicated in nacl_exe_win_64.cc.
2435 // Allow the server side of a pipe restricted to the "chrome.nacl."
2436 // namespace so that it cannot impersonate other system or other chrome
2437 // service pipes.
2438 sandbox::ResultCode result = policy->AddRule(
2439 sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
2440 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
2441 L"\\\\.\\pipe\\chrome.nacl.*");
2442 if (result != sandbox::SBOX_ALL_OK) {
2443 *success = false;
2444 return;
2447 // Renderers need to send named pipe handles and shared memory
2448 // segment handles to NaCl loader processes.
2449 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
2450 sandbox::TargetPolicy::HANDLES_DUP_ANY,
2451 L"File");
2452 if (result != sandbox::SBOX_ALL_OK) {
2453 *success = false;
2454 return;
2457 #endif
2459 bool ChromeContentBrowserClient::CheckMediaAccessPermission(
2460 content::BrowserContext* browser_context,
2461 const GURL& security_origin,
2462 content::MediaStreamType type) {
2463 return MediaCaptureDevicesDispatcher::GetInstance()
2464 ->CheckMediaAccessPermission(
2465 browser_context, security_origin, type);
2468 void ChromeContentBrowserClient::OpenURL(
2469 content::BrowserContext* browser_context,
2470 const content::OpenURLParams& params,
2471 const base::Callback<void(content::WebContents*)>& callback) {
2472 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2474 #if !defined(OS_ANDROID) && !defined(OS_IOS)
2475 NavigateParams nav_params(Profile::FromBrowserContext(browser_context),
2476 params.url,
2477 params.transition);
2478 FillNavigateParamsFromOpenURLParams(&nav_params, params);
2479 nav_params.user_gesture = params.user_gesture;
2481 Navigate(&nav_params);
2482 callback.Run(nav_params.target_contents);
2483 #elif defined(OS_ANDROID)
2484 chrome::android::ServiceTabLauncher::GetInstance()->LaunchTab(
2485 browser_context, params, callback);
2486 #else
2487 NOTIMPLEMENTED();
2488 #endif
2491 void ChromeContentBrowserClient::RecordURLMetric(const std::string& metric,
2492 const GURL& url) {
2493 if (url.is_valid()) {
2494 rappor::SampleDomainAndRegistryFromGURL(g_browser_process->rappor_service(),
2495 metric, url);
2499 content::DevToolsManagerDelegate*
2500 ChromeContentBrowserClient::GetDevToolsManagerDelegate() {
2501 #if defined(OS_ANDROID)
2502 return new DevToolsManagerDelegateAndroid();
2503 #else
2504 return new ChromeDevToolsManagerDelegate();
2505 #endif
2508 content::TracingDelegate* ChromeContentBrowserClient::GetTracingDelegate() {
2509 #if !defined(OS_ANDROID)
2510 return new ChromeTracingDelegate();
2511 #else
2512 return nullptr;
2513 #endif
2516 bool ChromeContentBrowserClient::IsPluginAllowedToCallRequestOSFileHandle(
2517 content::BrowserContext* browser_context,
2518 const GURL& url) {
2519 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
2520 return ChromeContentBrowserClientPluginsPart::
2521 IsPluginAllowedToCallRequestOSFileHandle(browser_context, url,
2522 allowed_file_handle_origins_);
2523 #else
2524 return false;
2525 #endif
2528 bool ChromeContentBrowserClient::IsPluginAllowedToUseDevChannelAPIs(
2529 content::BrowserContext* browser_context,
2530 const GURL& url) {
2531 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
2532 return ChromeContentBrowserClientPluginsPart::
2533 IsPluginAllowedToUseDevChannelAPIs(browser_context, url,
2534 allowed_dev_channel_origins_);
2535 #else
2536 return false;
2537 #endif
2540 void ChromeContentBrowserClient::OverridePageVisibilityState(
2541 RenderFrameHost* render_frame_host,
2542 blink::WebPageVisibilityState* visibility_state) {
2543 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
2545 WebContents* web_contents =
2546 WebContents::FromRenderFrameHost(render_frame_host);
2547 DCHECK(web_contents);
2549 Profile* profile =
2550 Profile::FromBrowserContext(web_contents->GetBrowserContext());
2551 prerender::PrerenderManager* prerender_manager =
2552 prerender::PrerenderManagerFactory::GetForProfile(profile);
2553 if (prerender_manager &&
2554 prerender_manager->IsWebContentsPrerendering(web_contents, nullptr)) {
2555 *visibility_state = blink::WebPageVisibilityStatePrerender;
2559 #if defined(ENABLE_WEBRTC)
2560 void ChromeContentBrowserClient::MaybeCopyDisableWebRtcEncryptionSwitch(
2561 base::CommandLine* to_command_line,
2562 const base::CommandLine& from_command_line,
2563 VersionInfo::Channel channel) {
2564 #if defined(OS_ANDROID)
2565 const VersionInfo::Channel kMaxDisableEncryptionChannel =
2566 VersionInfo::CHANNEL_BETA;
2567 #else
2568 const VersionInfo::Channel kMaxDisableEncryptionChannel =
2569 VersionInfo::CHANNEL_DEV;
2570 #endif
2571 if (channel <= kMaxDisableEncryptionChannel) {
2572 static const char* const kWebRtcDevSwitchNames[] = {
2573 switches::kDisableWebRtcEncryption,
2575 to_command_line->CopySwitchesFrom(from_command_line,
2576 kWebRtcDevSwitchNames,
2577 arraysize(kWebRtcDevSwitchNames));
2580 #endif // defined(ENABLE_WEBRTC)
2582 } // namespace chrome