ExtensionSyncService cleanup: process uninstalls in one step
[chromium-blink-merge.git] / chrome / browser / chrome_content_browser_client.cc
blob163c614d30fd42ad0bd98a1ce08fb11b1077773b
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/chrome_content_browser_client.h"
7 #include <map>
8 #include <set>
9 #include <utility>
10 #include <vector>
12 #include "base/bind.h"
13 #include "base/bind_helpers.h"
14 #include "base/command_line.h"
15 #include "base/files/scoped_file.h"
16 #include "base/lazy_instance.h"
17 #include "base/path_service.h"
18 #include "base/prefs/pref_service.h"
19 #include "base/prefs/scoped_user_pref_update.h"
20 #include "base/strings/string_number_conversions.h"
21 #include "base/strings/string_util.h"
22 #include "base/strings/stringprintf.h"
23 #include "base/strings/utf_string_conversions.h"
24 #include "base/thread_task_runner_handle.h"
25 #include "base/threading/sequenced_worker_pool.h"
26 #include "chrome/browser/after_startup_task_utils.h"
27 #include "chrome/browser/browser_about_handler.h"
28 #include "chrome/browser/browser_process.h"
29 #include "chrome/browser/browser_shutdown.h"
30 #include "chrome/browser/browsing_data/browsing_data_helper.h"
31 #include "chrome/browser/browsing_data/browsing_data_remover.h"
32 #include "chrome/browser/character_encoding.h"
33 #include "chrome/browser/chrome_content_browser_client_parts.h"
34 #include "chrome/browser/chrome_net_benchmarking_message_filter.h"
35 #include "chrome/browser/chrome_quota_permission_context.h"
36 #include "chrome/browser/content_settings/cookie_settings_factory.h"
37 #include "chrome/browser/content_settings/tab_specific_content_settings.h"
38 #include "chrome/browser/defaults.h"
39 #include "chrome/browser/devtools/chrome_devtools_manager_delegate.h"
40 #include "chrome/browser/download/download_prefs.h"
41 #include "chrome/browser/font_family_cache.h"
42 #include "chrome/browser/geolocation/chrome_access_token_store.h"
43 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
44 #include "chrome/browser/metrics/chrome_browser_main_extra_parts_metrics.h"
45 #include "chrome/browser/nacl_host/nacl_browser_delegate_impl.h"
46 #include "chrome/browser/net/chrome_net_log.h"
47 #include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings.h"
48 #include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings_factory.h"
49 #include "chrome/browser/notifications/platform_notification_service_impl.h"
50 #include "chrome/browser/platform_util.h"
51 #include "chrome/browser/prerender/prerender_final_status.h"
52 #include "chrome/browser/prerender/prerender_manager.h"
53 #include "chrome/browser/prerender/prerender_manager_factory.h"
54 #include "chrome/browser/prerender/prerender_message_filter.h"
55 #include "chrome/browser/printing/printing_message_filter.h"
56 #include "chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.h"
57 #include "chrome/browser/profiles/profile.h"
58 #include "chrome/browser/profiles/profile_io_data.h"
59 #include "chrome/browser/renderer_host/chrome_render_message_filter.h"
60 #include "chrome/browser/renderer_host/pepper/chrome_browser_pepper_host_factory.h"
61 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
62 #include "chrome/browser/safe_browsing/ui_manager.h"
63 #include "chrome/browser/search/instant_service.h"
64 #include "chrome/browser/search/instant_service_factory.h"
65 #include "chrome/browser/search/search.h"
66 #include "chrome/browser/search_engines/search_provider_install_state_message_filter.h"
67 #include "chrome/browser/speech/chrome_speech_recognition_manager_delegate.h"
68 #include "chrome/browser/speech/tts_controller.h"
69 #include "chrome/browser/speech/tts_message_filter.h"
70 #include "chrome/browser/ssl/ssl_add_certificate.h"
71 #include "chrome/browser/ssl/ssl_blocking_page.h"
72 #include "chrome/browser/ssl/ssl_cert_reporter.h"
73 #include "chrome/browser/ssl/ssl_client_certificate_selector.h"
74 #include "chrome/browser/ssl/ssl_error_handler.h"
75 #include "chrome/browser/sync_file_system/local/sync_file_system_backend.h"
76 #include "chrome/browser/tab_contents/tab_util.h"
77 #include "chrome/browser/tracing/chrome_tracing_delegate.h"
78 #include "chrome/browser/ui/blocked_content/blocked_window_params.h"
79 #include "chrome/browser/ui/blocked_content/popup_blocker_tab_helper.h"
80 #include "chrome/browser/ui/chrome_select_file_policy.h"
81 #include "chrome/browser/ui/sync/sync_promo_ui.h"
82 #include "chrome/browser/ui/tab_contents/chrome_web_contents_view_delegate.h"
83 #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
84 #include "chrome/common/chrome_constants.h"
85 #include "chrome/common/chrome_paths.h"
86 #include "chrome/common/chrome_switches.h"
87 #include "chrome/common/chrome_version_info.h"
88 #include "chrome/common/env_vars.h"
89 #include "chrome/common/logging_chrome.h"
90 #include "chrome/common/pepper_permission_util.h"
91 #include "chrome/common/pref_names.h"
92 #include "chrome/common/render_messages.h"
93 #include "chrome/common/url_constants.h"
94 #include "chrome/grit/generated_resources.h"
95 #include "chrome/installer/util/google_update_settings.h"
96 #include "chromeos/chromeos_constants.h"
97 #include "components/cdm/browser/cdm_message_filter_android.h"
98 #include "components/cloud_devices/common/cloud_devices_switches.h"
99 #include "components/content_settings/core/browser/content_settings_utils.h"
100 #include "components/content_settings/core/browser/cookie_settings.h"
101 #include "components/content_settings/core/browser/host_content_settings_map.h"
102 #include "components/content_settings/core/common/content_settings.h"
103 #include "components/data_reduction_proxy/content/browser/data_reduction_proxy_message_filter.h"
104 #include "components/dom_distiller/core/url_constants.h"
105 #include "components/google/core/browser/google_util.h"
106 #include "components/metrics/client_info.h"
107 #include "components/pref_registry/pref_registry_syncable.h"
108 #include "components/rappor/rappor_utils.h"
109 #include "components/signin/core/common/profile_management_switches.h"
110 #include "components/translate/core/common/translate_switches.h"
111 #include "components/url_fixer/url_fixer.h"
112 #include "components/variations/variations_associated_data.h"
113 #include "content/public/browser/browser_child_process_host.h"
114 #include "content/public/browser/browser_main_parts.h"
115 #include "content/public/browser/browser_ppapi_host.h"
116 #include "content/public/browser/browser_thread.h"
117 #include "content/public/browser/browser_url_handler.h"
118 #include "content/public/browser/child_process_data.h"
119 #include "content/public/browser/child_process_security_policy.h"
120 #include "content/public/browser/client_certificate_delegate.h"
121 #include "content/public/browser/render_frame_host.h"
122 #include "content/public/browser/render_process_host.h"
123 #include "content/public/browser/render_view_host.h"
124 #include "content/public/browser/resource_context.h"
125 #include "content/public/browser/site_instance.h"
126 #include "content/public/browser/web_contents.h"
127 #include "content/public/common/child_process_host.h"
128 #include "content/public/common/content_descriptors.h"
129 #include "content/public/common/sandbox_type.h"
130 #include "content/public/common/service_registry.h"
131 #include "content/public/common/url_utils.h"
132 #include "content/public/common/web_preferences.h"
133 #include "device/devices_app/public/cpp/constants.h"
134 #include "device/devices_app/public/cpp/devices_app_factory.h"
135 #include "gin/v8_initializer.h"
136 #include "mojo/application/public/cpp/application_delegate.h"
137 #include "net/base/mime_util.h"
138 #include "net/cookies/canonical_cookie.h"
139 #include "net/cookies/cookie_options.h"
140 #include "net/ssl/ssl_cert_request_info.h"
141 #include "ppapi/host/ppapi_host.h"
142 #include "storage/browser/fileapi/external_mount_points.h"
143 #include "ui/base/l10n/l10n_util.h"
144 #include "ui/base/resource/resource_bundle.h"
145 #include "ui/resources/grit/ui_resources.h"
147 #if defined(OS_WIN)
148 #include "base/win/windows_version.h"
149 #include "chrome/browser/chrome_browser_main_win.h"
150 #include "sandbox/win/src/sandbox_policy.h"
151 #elif defined(OS_MACOSX)
152 #include "chrome/browser/chrome_browser_main_mac.h"
153 #include "chrome/browser/spellchecker/spellcheck_message_filter_mac.h"
154 #elif defined(OS_CHROMEOS)
155 #include "chrome/browser/chromeos/attestation/platform_verification_impl.h"
156 #include "chrome/browser/chromeos/chrome_browser_main_chromeos.h"
157 #include "chrome/browser/chromeos/drive/fileapi/file_system_backend_delegate.h"
158 #include "chrome/browser/chromeos/file_manager/app_id.h"
159 #include "chrome/browser/chromeos/file_system_provider/fileapi/backend_delegate.h"
160 #include "chrome/browser/chromeos/fileapi/file_system_backend.h"
161 #include "chrome/browser/chromeos/fileapi/mtp_file_system_backend_delegate.h"
162 #include "chrome/browser/chromeos/login/startup_utils.h"
163 #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
164 #include "chrome/browser/chromeos/system/input_device_settings.h"
165 #include "chromeos/chromeos_switches.h"
166 #include "components/user_manager/user_manager.h"
167 #elif defined(OS_LINUX)
168 #include "chrome/browser/chrome_browser_main_linux.h"
169 #elif defined(OS_ANDROID)
170 #include "chrome/browser/android/new_tab_page_url_handler.h"
171 #include "chrome/browser/android/webapps/single_tab_mode_tab_helper.h"
172 #include "chrome/browser/chrome_browser_main_android.h"
173 #include "chrome/common/descriptors_android.h"
174 #include "components/crash/browser/crash_dump_manager_android.h"
175 #include "components/service_tab_launcher/browser/android/service_tab_launcher.h"
176 #include "ui/base/resource/resource_bundle_android.h"
177 #elif defined(OS_POSIX)
178 #include "chrome/browser/chrome_browser_main_posix.h"
179 #endif
181 #if defined(OS_POSIX) && !defined(OS_MACOSX)
182 #include "base/debug/leak_annotations.h"
183 #include "components/crash/app/breakpad_linux.h"
184 #include "components/crash/browser/crash_handler_host_linux.h"
185 #endif
187 #if defined(OS_ANDROID)
188 #include "ui/base/ui_base_paths.h"
189 #include "ui/gfx/android/device_display_info.h"
190 #endif
192 #if defined(TOOLKIT_VIEWS)
193 #include "chrome/browser/ui/views/chrome_browser_main_extra_parts_views.h"
194 #endif
196 #if defined(USE_ASH)
197 #include "chrome/browser/ui/views/ash/chrome_browser_main_extra_parts_ash.h"
198 #endif
200 #if defined(USE_AURA)
201 #include "chrome/browser/ui/aura/chrome_browser_main_extra_parts_aura.h"
202 #endif
204 #if defined(USE_X11)
205 #include "chrome/browser/chrome_browser_main_extra_parts_x11.h"
206 #endif
208 #if defined(ENABLE_CAPTIVE_PORTAL_DETECTION)
209 #include "chrome/browser/captive_portal/captive_portal_tab_helper.h"
210 #endif
212 #if !defined(DISABLE_NACL)
213 #include "components/nacl/browser/nacl_browser.h"
214 #include "components/nacl/browser/nacl_host_message_filter.h"
215 #include "components/nacl/browser/nacl_process_host.h"
216 #include "components/nacl/common/nacl_process_type.h"
217 #include "components/nacl/common/nacl_switches.h"
218 #endif
220 #if defined(ENABLE_EXTENSIONS)
221 #include "chrome/browser/accessibility/animation_policy_prefs.h"
222 #include "chrome/browser/extensions/chrome_content_browser_client_extensions_part.h"
223 #include "chrome/browser/media/cast_transport_host_filter.h"
224 #include "chrome/browser/speech/extension_api/tts_engine_extension_api.h"
225 #include "components/guest_view/browser/guest_view_base.h"
226 #include "components/guest_view/browser/guest_view_manager.h"
227 #include "extensions/browser/extension_registry.h"
228 #include "extensions/browser/extension_util.h"
229 #include "extensions/browser/guest_view/web_view/web_view_guest.h"
230 #include "extensions/browser/guest_view/web_view/web_view_permission_helper.h"
231 #include "extensions/browser/guest_view/web_view/web_view_renderer_state.h"
232 #include "extensions/common/constants.h"
233 #include "extensions/common/extension.h"
234 #include "extensions/common/extension_set.h"
235 #include "extensions/common/manifest_handlers/background_info.h"
236 #include "extensions/common/manifest_handlers/shared_module_info.h"
237 #include "extensions/common/permissions/permissions_data.h"
238 #include "extensions/common/permissions/socket_permission.h"
239 #include "extensions/common/switches.h"
240 #endif
242 #if defined(ENABLE_PLUGINS)
243 #include "chrome/browser/plugins/chrome_content_browser_client_plugins_part.h"
244 #endif
246 #if defined(ENABLE_SPELLCHECK)
247 #include "chrome/browser/spellchecker/spellcheck_message_filter.h"
248 #endif
250 #if defined(ENABLE_WEBRTC)
251 #include "chrome/browser/media/webrtc_logging_handler_host.h"
252 #endif
254 #if defined(ENABLE_MEDIA_ROUTER)
255 #include "chrome/browser/media/router/presentation_service_delegate_impl.h"
256 #endif
258 using base::FileDescriptor;
259 using blink::WebWindowFeatures;
260 using content::AccessTokenStore;
261 using content::BrowserThread;
262 using content::BrowserURLHandler;
263 using content::ChildProcessSecurityPolicy;
264 using content::QuotaPermissionContext;
265 using content::RenderFrameHost;
266 using content::RenderViewHost;
267 using content::ResourceType;
268 using content::SiteInstance;
269 using content::WebContents;
270 using content::WebPreferences;
271 using message_center::NotifierId;
273 #if defined(OS_POSIX)
274 using content::FileDescriptorInfo;
275 #endif
277 #if defined(ENABLE_EXTENSIONS)
278 using extensions::APIPermission;
279 using extensions::ChromeContentBrowserClientExtensionsPart;
280 using extensions::Extension;
281 using extensions::InfoMap;
282 using extensions::Manifest;
283 #endif
285 #if defined(ENABLE_PLUGINS)
286 using plugins::ChromeContentBrowserClientPluginsPart;
287 #endif
289 namespace {
291 // Cached version of the locale so we can return the locale on the I/O
292 // thread.
293 base::LazyInstance<std::string> g_io_thread_application_locale;
295 #if defined(ENABLE_PLUGINS)
296 // TODO(teravest): Add renderer-side API-specific checking for these APIs so
297 // that blanket permission isn't granted to all dev channel APIs for these.
298 // http://crbug.com/386743
299 const char* const kPredefinedAllowedDevChannelOrigins[] = {
300 "6EAED1924DB611B6EEF2A664BD077BE7EAD33B8F", // see crbug.com/383937
301 "4EB74897CB187C7633357C2FE832E0AD6A44883A" // see crbug.com/383937
304 const char* const kPredefinedAllowedFileHandleOrigins[] = {
305 "6EAED1924DB611B6EEF2A664BD077BE7EAD33B8F", // see crbug.com/234789
306 "4EB74897CB187C7633357C2FE832E0AD6A44883A" // see crbug.com/234789
309 const char* const kPredefinedAllowedSocketOrigins[] = {
310 "okddffdblfhhnmhodogpojmfkjmhinfp", // Test SSH Client
311 "pnhechapfaindjhompbnflcldabbghjo", // HTerm App (SSH Client)
312 "bglhmjfplikpjnfoegeomebmfnkjomhe", // see crbug.com/122126
313 "gbchcmhmhahfdphkhkmpfmihenigjmpp", // Chrome Remote Desktop
314 "kgngmbheleoaphbjbaiobfdepmghbfah", // Pre-release Chrome Remote Desktop
315 "odkaodonbgfohohmklejpjiejmcipmib", // Dogfood Chrome Remote Desktop
316 "ojoimpklfciegopdfgeenehpalipignm", // Chromoting canary
317 "cbkkbcmdlboombapidmoeolnmdacpkch", // see crbug.com/129089
318 "hhnbmknkdabfoieppbbljkhkfjcmcbjh", // see crbug.com/134099
319 "mablfbjkhmhkmefkjjacnbaikjkipphg", // see crbug.com/134099
320 "pdeelgamlgannhelgoegilelnnojegoh", // see crbug.com/134099
321 "cabapfdbkniadpollkckdnedaanlciaj", // see crbug.com/134099
322 "mapljbgnjledlpdmlchihnmeclmefbba", // see crbug.com/134099
323 "ghbfeebgmiidnnmeobbbaiamklmpbpii", // see crbug.com/134099
324 "jdfhpkjeckflbbleddjlpimecpbjdeep", // see crbug.com/142514
325 "iabmpiboiopbgfabjmgeedhcmjenhbla", // see crbug.com/165080
326 "B7CF8A292249681AF81771650BA4CEEAF19A4560", // see crbug.com/165080
327 "7525AF4F66763A70A883C4700529F647B470E4D2", // see crbug.com/238084
328 "0B549507088E1564D672F7942EB87CA4DAD73972", // see crbug.com/238084
329 "864288364E239573E777D3E0E36864E590E95C74" // see crbug.com/238084
331 #endif
333 // Returns a copy of the given url with its host set to given host and path set
334 // to given path. Other parts of the url will be the same.
335 GURL ReplaceURLHostAndPath(const GURL& url,
336 const std::string& host,
337 const std::string& path) {
338 url::Replacements<char> replacements;
339 replacements.SetHost(host.c_str(), url::Component(0, host.length()));
340 replacements.SetPath(path.c_str(), url::Component(0, path.length()));
341 return url.ReplaceComponents(replacements);
344 // Maps "foo://bar/baz/" to "foo://chrome/bar/baz/".
345 GURL AddUberHost(const GURL& url) {
346 const std::string uber_host = chrome::kChromeUIUberHost;
347 const std::string new_path = url.host() + url.path();
349 return ReplaceURLHostAndPath(url, uber_host, new_path);
352 // If url->host() is "chrome" and url->path() has characters other than the
353 // first slash, changes the url from "foo://chrome/bar/" to "foo://bar/" and
354 // returns true. Otherwise returns false.
355 bool RemoveUberHost(GURL* url) {
356 if (url->host() != chrome::kChromeUIUberHost)
357 return false;
359 if (url->path().empty() || url->path() == "/")
360 return false;
362 const std::string old_path = url->path();
364 const std::string::size_type separator = old_path.find('/', 1);
365 std::string new_host;
366 std::string new_path;
367 if (separator == std::string::npos) {
368 new_host = old_path.substr(1);
369 } else {
370 new_host = old_path.substr(1, separator - 1);
371 new_path = old_path.substr(separator);
374 // Do not allow URLs with paths empty before the first slash since we can't
375 // have an empty host. (e.g "foo://chrome//")
376 if (new_host.empty())
377 return false;
379 *url = ReplaceURLHostAndPath(*url, new_host, new_path);
381 DCHECK(url->is_valid());
383 return true;
386 // Handles rewriting Web UI URLs.
387 bool HandleWebUI(GURL* url, content::BrowserContext* browser_context) {
388 // Do not handle special URLs such as "about:foo"
389 if (!url->host().empty()) {
390 const GURL chrome_url = AddUberHost(*url);
392 // Handle valid "chrome://chrome/foo" URLs so the reverse handler will
393 // be called.
394 if (ChromeWebUIControllerFactory::GetInstance()->UseWebUIForURL(
395 browser_context, chrome_url))
396 return true;
399 if (!ChromeWebUIControllerFactory::GetInstance()->UseWebUIForURL(
400 browser_context, *url))
401 return false;
403 #if defined(OS_CHROMEOS)
404 // Special case : in ChromeOS in Guest mode bookmarks and history are
405 // disabled for security reasons. New tab page explains the reasons, so
406 // we redirect user to new tab page.
407 if (user_manager::UserManager::Get()->IsLoggedInAsGuest()) {
408 if (url->SchemeIs(content::kChromeUIScheme) &&
409 (url->DomainIs(chrome::kChromeUIBookmarksHost) ||
410 url->DomainIs(chrome::kChromeUIHistoryHost))) {
411 // Rewrite with new tab URL
412 *url = GURL(chrome::kChromeUINewTabURL);
415 #endif
417 return true;
420 // Reverse URL handler for Web UI. Maps "chrome://chrome/foo/" to
421 // "chrome://foo/".
422 bool HandleWebUIReverse(GURL* url, content::BrowserContext* browser_context) {
423 if (!url->is_valid() || !url->SchemeIs(content::kChromeUIScheme))
424 return false;
426 return RemoveUberHost(url);
429 bool CertMatchesFilter(const net::X509Certificate& cert,
430 const base::DictionaryValue& filter) {
431 // TODO(markusheintz): This is the minimal required filter implementation.
432 // Implement a better matcher.
434 // An empty filter matches any client certificate since no requirements are
435 // specified at all.
436 if (filter.empty())
437 return true;
439 std::string common_name;
440 if (filter.GetString("ISSUER.CN", &common_name) &&
441 (cert.issuer().common_name == common_name)) {
442 return true;
444 return false;
447 #if defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_MACOSX)
448 breakpad::CrashHandlerHostLinux* CreateCrashHandlerHost(
449 const std::string& process_type) {
450 base::FilePath dumps_path;
451 PathService::Get(chrome::DIR_CRASH_DUMPS, &dumps_path);
453 ANNOTATE_SCOPED_MEMORY_LEAK;
454 bool upload = (getenv(env_vars::kHeadless) == NULL);
455 breakpad::CrashHandlerHostLinux* crash_handler =
456 new breakpad::CrashHandlerHostLinux(process_type, dumps_path, upload);
457 crash_handler->StartUploaderThread();
458 return crash_handler;
462 int GetCrashSignalFD(const base::CommandLine& command_line) {
463 // Extensions have the same process type as renderers.
464 if (command_line.HasSwitch(extensions::switches::kExtensionProcess)) {
465 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
466 if (!crash_handler)
467 crash_handler = CreateCrashHandlerHost("extension");
468 return crash_handler->GetDeathSignalSocket();
471 std::string process_type =
472 command_line.GetSwitchValueASCII(switches::kProcessType);
474 if (process_type == switches::kRendererProcess) {
475 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
476 if (!crash_handler)
477 crash_handler = CreateCrashHandlerHost(process_type);
478 return crash_handler->GetDeathSignalSocket();
481 if (process_type == switches::kPluginProcess) {
482 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
483 if (!crash_handler)
484 crash_handler = CreateCrashHandlerHost(process_type);
485 return crash_handler->GetDeathSignalSocket();
488 if (process_type == switches::kPpapiPluginProcess) {
489 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
490 if (!crash_handler)
491 crash_handler = CreateCrashHandlerHost(process_type);
492 return crash_handler->GetDeathSignalSocket();
495 if (process_type == switches::kGpuProcess) {
496 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
497 if (!crash_handler)
498 crash_handler = CreateCrashHandlerHost(process_type);
499 return crash_handler->GetDeathSignalSocket();
502 return -1;
504 #endif // defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_MACOSX)
506 void SetApplicationLocaleOnIOThread(const std::string& locale) {
507 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
508 g_io_thread_application_locale.Get() = locale;
511 void HandleBlockedPopupOnUIThread(const BlockedWindowParams& params) {
512 RenderFrameHost* render_frame_host = RenderFrameHost::FromID(
513 params.render_process_id(), params.opener_render_frame_id());
514 if (!render_frame_host)
515 return;
516 WebContents* tab = WebContents::FromRenderFrameHost(render_frame_host);
517 // The tab might already have navigated away. We only need to do this check
518 // for main frames, since the RenderFrameHost for a subframe opener will have
519 // already been deleted if the main frame navigates away.
520 if (!tab ||
521 (!render_frame_host->GetParent() &&
522 tab->GetMainFrame() != render_frame_host))
523 return;
525 prerender::PrerenderContents* prerender_contents =
526 prerender::PrerenderContents::FromWebContents(tab);
527 if (prerender_contents) {
528 prerender_contents->Destroy(prerender::FINAL_STATUS_CREATE_NEW_WINDOW);
529 return;
532 PopupBlockerTabHelper* popup_helper =
533 PopupBlockerTabHelper::FromWebContents(tab);
534 if (!popup_helper)
535 return;
536 popup_helper->AddBlockedPopup(params);
539 // An implementation of the SSLCertReporter interface used by
540 // SSLErrorHandler. Uses the SafeBrowsing UI manager to send invalid
541 // certificate reports.
542 class SafeBrowsingSSLCertReporter : public SSLCertReporter {
543 public:
544 explicit SafeBrowsingSSLCertReporter(
545 const scoped_refptr<SafeBrowsingUIManager>& safe_browsing_ui_manager)
546 : safe_browsing_ui_manager_(safe_browsing_ui_manager) {}
547 ~SafeBrowsingSSLCertReporter() override {}
549 // SSLCertReporter implementation
550 void ReportInvalidCertificateChain(
551 const std::string& serialized_report) override {
552 if (safe_browsing_ui_manager_) {
553 safe_browsing_ui_manager_->ReportInvalidCertificateChain(
554 serialized_report, base::Bind(&base::DoNothing));
558 private:
559 const scoped_refptr<SafeBrowsingUIManager> safe_browsing_ui_manager_;
562 #if defined(OS_ANDROID)
564 void HandleSingleTabModeBlockOnUIThread(const BlockedWindowParams& params) {
565 WebContents* web_contents = tab_util::GetWebContentsByFrameID(
566 params.render_process_id(), params.opener_render_frame_id());
567 if (!web_contents)
568 return;
570 SingleTabModeTabHelper::FromWebContents(web_contents)->HandleOpenUrl(params);
573 float GetDeviceScaleAdjustment() {
574 static const float kMinFSM = 1.05f;
575 static const int kWidthForMinFSM = 320;
576 static const float kMaxFSM = 1.3f;
577 static const int kWidthForMaxFSM = 800;
579 gfx::DeviceDisplayInfo info;
580 int minWidth = info.GetSmallestDIPWidth();
582 if (minWidth <= kWidthForMinFSM)
583 return kMinFSM;
584 if (minWidth >= kWidthForMaxFSM)
585 return kMaxFSM;
587 // The font scale multiplier varies linearly between kMinFSM and kMaxFSM.
588 float ratio = static_cast<float>(minWidth - kWidthForMinFSM) /
589 (kWidthForMaxFSM - kWidthForMinFSM);
590 return ratio * (kMaxFSM - kMinFSM) + kMinFSM;
593 #endif // defined(OS_ANDROID)
595 #if defined(ENABLE_EXTENSIONS)
596 // By default, JavaScript and images are enabled in guest content.
597 void GetGuestViewDefaultContentSettingRules(
598 bool incognito,
599 RendererContentSettingRules* rules) {
600 rules->image_rules.push_back(
601 ContentSettingPatternSource(ContentSettingsPattern::Wildcard(),
602 ContentSettingsPattern::Wildcard(),
603 CONTENT_SETTING_ALLOW,
604 std::string(),
605 incognito));
607 rules->script_rules.push_back(
608 ContentSettingPatternSource(ContentSettingsPattern::Wildcard(),
609 ContentSettingsPattern::Wildcard(),
610 CONTENT_SETTING_ALLOW,
611 std::string(),
612 incognito));
614 #endif // defined(ENABLE_EXTENSIONS)
616 } // namespace
618 namespace chrome {
620 ChromeContentBrowserClient::ChromeContentBrowserClient()
622 weak_factory_(this) {
623 #if defined(ENABLE_PLUGINS)
624 for (size_t i = 0; i < arraysize(kPredefinedAllowedDevChannelOrigins); ++i)
625 allowed_dev_channel_origins_.insert(kPredefinedAllowedDevChannelOrigins[i]);
626 for (size_t i = 0; i < arraysize(kPredefinedAllowedFileHandleOrigins); ++i)
627 allowed_file_handle_origins_.insert(kPredefinedAllowedFileHandleOrigins[i]);
628 for (size_t i = 0; i < arraysize(kPredefinedAllowedSocketOrigins); ++i)
629 allowed_socket_origins_.insert(kPredefinedAllowedSocketOrigins[i]);
631 extra_parts_.push_back(new ChromeContentBrowserClientPluginsPart);
632 #endif
634 #if !defined(OS_ANDROID)
635 TtsExtensionEngine* tts_extension_engine = TtsExtensionEngine::GetInstance();
636 TtsController::GetInstance()->SetTtsEngineDelegate(tts_extension_engine);
637 #endif
639 #if defined(ENABLE_EXTENSIONS)
640 extra_parts_.push_back(new ChromeContentBrowserClientExtensionsPart);
641 #endif
644 ChromeContentBrowserClient::~ChromeContentBrowserClient() {
645 for (int i = static_cast<int>(extra_parts_.size()) - 1; i >= 0; --i)
646 delete extra_parts_[i];
647 extra_parts_.clear();
650 // static
651 void ChromeContentBrowserClient::RegisterProfilePrefs(
652 user_prefs::PrefRegistrySyncable* registry) {
653 registry->RegisterBooleanPref(prefs::kDisable3DAPIs, false);
654 registry->RegisterBooleanPref(prefs::kEnableHyperlinkAuditing, true);
655 registry->RegisterListPref(prefs::kEnableDeprecatedWebPlatformFeatures);
658 // static
659 void ChromeContentBrowserClient::SetApplicationLocale(
660 const std::string& locale) {
661 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
663 // This object is guaranteed to outlive all threads so we don't have to
664 // worry about the lack of refcounting and can just post as Unretained.
666 // The common case is that this function is called early in Chrome startup
667 // before any threads are created (it will also be called later if the user
668 // changes the pref). In this case, there will be no threads created and
669 // posting will fail. When there are no threads, we can just set the string
670 // without worrying about threadsafety.
671 if (!BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
672 base::Bind(&SetApplicationLocaleOnIOThread, locale))) {
673 g_io_thread_application_locale.Get() = locale;
677 content::BrowserMainParts* ChromeContentBrowserClient::CreateBrowserMainParts(
678 const content::MainFunctionParams& parameters) {
679 ChromeBrowserMainParts* main_parts;
680 // Construct the Main browser parts based on the OS type.
681 #if defined(OS_WIN)
682 main_parts = new ChromeBrowserMainPartsWin(parameters);
683 #elif defined(OS_MACOSX)
684 main_parts = new ChromeBrowserMainPartsMac(parameters);
685 #elif defined(OS_CHROMEOS)
686 main_parts = new chromeos::ChromeBrowserMainPartsChromeos(parameters);
687 #elif defined(OS_LINUX)
688 main_parts = new ChromeBrowserMainPartsLinux(parameters);
689 #elif defined(OS_ANDROID)
690 main_parts = new ChromeBrowserMainPartsAndroid(parameters);
691 #elif defined(OS_POSIX)
692 main_parts = new ChromeBrowserMainPartsPosix(parameters);
693 #else
694 NOTREACHED();
695 main_parts = new ChromeBrowserMainParts(parameters);
696 #endif
698 chrome::AddProfilesExtraParts(main_parts);
700 // Construct additional browser parts. Stages are called in the order in
701 // which they are added.
702 #if defined(TOOLKIT_VIEWS)
703 main_parts->AddParts(new ChromeBrowserMainExtraPartsViews());
704 #endif
706 // TODO(oshima): Athena on chrome currently requires USE_ASH to build.
707 // We should reduce the dependency as much as possible.
708 #if defined(USE_ASH)
709 main_parts->AddParts(new ChromeBrowserMainExtraPartsAsh());
710 #endif
712 #if defined(USE_AURA)
713 main_parts->AddParts(new ChromeBrowserMainExtraPartsAura());
714 #endif
716 #if defined(USE_X11)
717 main_parts->AddParts(new ChromeBrowserMainExtraPartsX11());
718 #endif
720 chrome::AddMetricsExtraParts(main_parts);
722 return main_parts;
725 void ChromeContentBrowserClient::PostAfterStartupTask(
726 const tracked_objects::Location& from_here,
727 const scoped_refptr<base::TaskRunner>& task_runner,
728 const base::Closure& task) {
729 AfterStartupTaskUtils::PostTask(from_here, task_runner, task);
732 std::string ChromeContentBrowserClient::GetStoragePartitionIdForSite(
733 content::BrowserContext* browser_context,
734 const GURL& site) {
735 std::string partition_id;
737 // The partition ID for webview guest processes is the string value of its
738 // SiteInstance URL - "chrome-guest://app_id/persist?partition".
739 if (site.SchemeIs(content::kGuestScheme)) {
740 partition_id = site.spec();
741 } else if (!switches::IsEnableWebviewBasedSignin() &&
742 site.GetOrigin().spec() == kChromeUIChromeSigninURL) {
743 // The non-webview Chrome signin page has an embedded iframe of extension
744 // and web content, thus it must be isolated from other webUI pages.
745 partition_id = site.GetOrigin().spec();
748 DCHECK(IsValidStoragePartitionId(browser_context, partition_id));
749 return partition_id;
752 bool ChromeContentBrowserClient::IsValidStoragePartitionId(
753 content::BrowserContext* browser_context,
754 const std::string& partition_id) {
755 // The default ID is empty and is always valid.
756 if (partition_id.empty())
757 return true;
759 return GURL(partition_id).is_valid();
762 void ChromeContentBrowserClient::GetStoragePartitionConfigForSite(
763 content::BrowserContext* browser_context,
764 const GURL& site,
765 bool can_be_default,
766 std::string* partition_domain,
767 std::string* partition_name,
768 bool* in_memory) {
769 // Default to the browser-wide storage partition and override based on |site|
770 // below.
771 partition_domain->clear();
772 partition_name->clear();
773 *in_memory = false;
775 bool success = false;
776 #if defined(ENABLE_EXTENSIONS)
777 success = extensions::WebViewGuest::GetGuestPartitionConfigForSite(
778 site, partition_domain, partition_name, in_memory);
780 if (!success && site.SchemeIs(extensions::kExtensionScheme)) {
781 // If |can_be_default| is false, the caller is stating that the |site|
782 // should be parsed as if it had isolated storage. In particular it is
783 // important to NOT check ExtensionService for the is_storage_isolated()
784 // attribute because this code path is run during Extension uninstall
785 // to do cleanup after the Extension has already been unloaded from the
786 // ExtensionService.
787 bool is_isolated = !can_be_default;
788 if (can_be_default) {
789 if (extensions::util::SiteHasIsolatedStorage(site, browser_context))
790 is_isolated = true;
793 if (is_isolated) {
794 CHECK(site.has_host());
795 // For extensions with isolated storage, the the host of the |site| is
796 // the |partition_domain|. The |in_memory| and |partition_name| are only
797 // used in guest schemes so they are cleared here.
798 *partition_domain = site.host();
799 *in_memory = false;
800 partition_name->clear();
802 success = true;
804 #endif
806 if (!success && (!switches::IsEnableWebviewBasedSignin() &&
807 site.GetOrigin().spec() == kChromeUIChromeSigninURL)) {
808 // The non-webview Chrome signin page has an embedded iframe of extension
809 // and web content, thus it must be isolated from other webUI pages.
810 *partition_domain = chrome::kChromeUIChromeSigninHost;
813 // Assert that if |can_be_default| is false, the code above must have found a
814 // non-default partition. If this fails, the caller has a serious logic
815 // error about which StoragePartition they expect to be in and it is not
816 // safe to continue.
817 CHECK(can_be_default || !partition_domain->empty());
820 content::WebContentsViewDelegate*
821 ChromeContentBrowserClient::GetWebContentsViewDelegate(
822 content::WebContents* web_contents) {
823 return chrome::CreateWebContentsViewDelegate(web_contents);
826 void ChromeContentBrowserClient::RenderProcessWillLaunch(
827 content::RenderProcessHost* host) {
828 int id = host->GetID();
829 Profile* profile = Profile::FromBrowserContext(host->GetBrowserContext());
830 net::URLRequestContextGetter* context =
831 profile->GetRequestContextForRenderProcess(id);
833 host->AddFilter(new ChromeRenderMessageFilter(id, profile));
834 #if defined(ENABLE_EXTENSIONS)
835 host->AddFilter(new cast::CastTransportHostFilter);
836 #endif
837 #if defined(ENABLE_PRINTING)
838 host->AddFilter(new printing::PrintingMessageFilter(id, profile));
839 #endif
840 host->AddFilter(new SearchProviderInstallStateMessageFilter(id, profile));
841 #if defined(ENABLE_SPELLCHECK)
842 host->AddFilter(new SpellCheckMessageFilter(id));
843 #endif
844 #if defined(OS_MACOSX)
845 host->AddFilter(new SpellCheckMessageFilterMac(id));
846 #endif
847 host->AddFilter(new ChromeNetBenchmarkingMessageFilter(profile, context));
848 host->AddFilter(new prerender::PrerenderMessageFilter(id, profile));
849 host->AddFilter(new TtsMessageFilter(host->GetBrowserContext()));
850 #if defined(ENABLE_WEBRTC)
851 WebRtcLoggingHandlerHost* webrtc_logging_handler_host =
852 new WebRtcLoggingHandlerHost(profile);
853 host->SetWebRtcLogMessageCallback(base::Bind(
854 &WebRtcLoggingHandlerHost::LogMessage, webrtc_logging_handler_host));
855 host->AddFilter(webrtc_logging_handler_host);
856 host->SetUserData(host, new base::UserDataAdapter<WebRtcLoggingHandlerHost>(
857 webrtc_logging_handler_host));
858 #endif
859 #if !defined(DISABLE_NACL)
860 host->AddFilter(new nacl::NaClHostMessageFilter(
861 id, profile->IsOffTheRecord(),
862 profile->GetPath(),
863 context));
864 #endif
865 #if defined(OS_ANDROID)
866 host->AddFilter(new cdm::CdmMessageFilterAndroid());
867 #endif
868 DataReductionProxyChromeSettings* data_reduction_proxy_settings =
869 DataReductionProxyChromeSettingsFactory::GetForBrowserContext(profile);
870 host->AddFilter(new data_reduction_proxy::DataReductionProxyMessageFilter(
871 data_reduction_proxy_settings));
873 host->Send(new ChromeViewMsg_SetIsIncognitoProcess(
874 profile->IsOffTheRecord()));
876 for (size_t i = 0; i < extra_parts_.size(); ++i)
877 extra_parts_[i]->RenderProcessWillLaunch(host);
879 RendererContentSettingRules rules;
880 if (host->IsForGuestsOnly()) {
881 #if defined(ENABLE_EXTENSIONS)
882 GetGuestViewDefaultContentSettingRules(profile->IsOffTheRecord(), &rules);
883 #else
884 NOTREACHED();
885 #endif
886 } else {
887 GetRendererContentSettingRules(
888 profile->GetHostContentSettingsMap(), &rules);
890 host->Send(new ChromeViewMsg_SetContentSettingRules(rules));
893 GURL ChromeContentBrowserClient::GetEffectiveURL(
894 content::BrowserContext* browser_context, const GURL& url) {
895 Profile* profile = Profile::FromBrowserContext(browser_context);
896 if (!profile)
897 return url;
899 // If the input |url| should be assigned to the Instant renderer, make its
900 // effective URL distinct from other URLs on the search provider's domain.
901 if (chrome::ShouldAssignURLToInstantRenderer(url, profile))
902 return chrome::GetEffectiveURLForInstant(url, profile);
904 #if defined(ENABLE_EXTENSIONS)
905 return ChromeContentBrowserClientExtensionsPart::GetEffectiveURL(
906 profile, url);
907 #else
908 return url;
909 #endif
912 bool ChromeContentBrowserClient::ShouldUseProcessPerSite(
913 content::BrowserContext* browser_context, const GURL& effective_url) {
914 // Non-extension, non-Instant URLs should generally use
915 // process-per-site-instance. Because we expect to use the effective URL,
916 // URLs for hosted apps (apart from bookmark apps) should have an extension
917 // scheme by now.
919 Profile* profile = Profile::FromBrowserContext(browser_context);
920 if (!profile)
921 return false;
923 if (chrome::ShouldUseProcessPerSiteForInstantURL(effective_url, profile))
924 return true;
926 #if defined(ENABLE_EXTENSIONS)
927 return ChromeContentBrowserClientExtensionsPart::ShouldUseProcessPerSite(
928 profile, effective_url);
929 #else
930 return false;
931 #endif
934 // These are treated as WebUI schemes but do not get WebUI bindings. Also,
935 // view-source is allowed for these schemes.
936 void ChromeContentBrowserClient::GetAdditionalWebUISchemes(
937 std::vector<std::string>* additional_schemes) {
938 additional_schemes->push_back(chrome::kChromeSearchScheme);
939 additional_schemes->push_back(dom_distiller::kDomDistillerScheme);
942 void ChromeContentBrowserClient::GetAdditionalWebUIHostsToIgnoreParititionCheck(
943 std::vector<std::string>* hosts) {
944 hosts->push_back(chrome::kChromeUIExtensionIconHost);
945 hosts->push_back(chrome::kChromeUIFaviconHost);
946 hosts->push_back(chrome::kChromeUIThemeHost);
947 hosts->push_back(chrome::kChromeUIThumbnailHost);
948 hosts->push_back(chrome::kChromeUIThumbnailHost2);
949 hosts->push_back(chrome::kChromeUIThumbnailListHost);
952 net::URLRequestContextGetter*
953 ChromeContentBrowserClient::CreateRequestContext(
954 content::BrowserContext* browser_context,
955 content::ProtocolHandlerMap* protocol_handlers,
956 content::URLRequestInterceptorScopedVector request_interceptors) {
957 Profile* profile = Profile::FromBrowserContext(browser_context);
958 return profile->CreateRequestContext(protocol_handlers,
959 request_interceptors.Pass());
962 net::URLRequestContextGetter*
963 ChromeContentBrowserClient::CreateRequestContextForStoragePartition(
964 content::BrowserContext* browser_context,
965 const base::FilePath& partition_path,
966 bool in_memory,
967 content::ProtocolHandlerMap* protocol_handlers,
968 content::URLRequestInterceptorScopedVector request_interceptors) {
969 Profile* profile = Profile::FromBrowserContext(browser_context);
970 return profile->CreateRequestContextForStoragePartition(
971 partition_path,
972 in_memory,
973 protocol_handlers,
974 request_interceptors.Pass());
977 bool ChromeContentBrowserClient::IsHandledURL(const GURL& url) {
978 return ProfileIOData::IsHandledURL(url);
981 bool ChromeContentBrowserClient::CanCommitURL(
982 content::RenderProcessHost* process_host,
983 const GURL& url) {
984 #if defined(ENABLE_EXTENSIONS)
985 return ChromeContentBrowserClientExtensionsPart::CanCommitURL(
986 process_host, url);
987 #else
988 return true;
989 #endif
992 bool ChromeContentBrowserClient::ShouldAllowOpenURL(
993 content::SiteInstance* site_instance, const GURL& url) {
994 GURL from_url = site_instance->GetSiteURL();
996 #if defined(ENABLE_EXTENSIONS)
997 bool result;
998 if (ChromeContentBrowserClientExtensionsPart::ShouldAllowOpenURL(
999 site_instance, from_url, url, &result))
1000 return result;
1001 #endif
1003 // Do not allow chrome://chrome-signin navigate to other chrome:// URLs, since
1004 // the signin page may host untrusted web content.
1005 if (from_url.GetOrigin().spec() == chrome::kChromeUIChromeSigninURL &&
1006 url.SchemeIs(content::kChromeUIScheme) &&
1007 url.host() != chrome::kChromeUIChromeSigninHost) {
1008 VLOG(1) << "Blocked navigation to " << url.spec() << " from "
1009 << chrome::kChromeUIChromeSigninURL;
1010 return false;
1013 return true;
1016 bool ChromeContentBrowserClient::IsSuitableHost(
1017 content::RenderProcessHost* process_host,
1018 const GURL& site_url) {
1019 Profile* profile =
1020 Profile::FromBrowserContext(process_host->GetBrowserContext());
1021 // This may be NULL during tests. In that case, just assume any site can
1022 // share any host.
1023 if (!profile)
1024 return true;
1026 // Instant URLs should only be in the instant process and instant process
1027 // should only have Instant URLs.
1028 InstantService* instant_service =
1029 InstantServiceFactory::GetForProfile(profile);
1030 if (instant_service) {
1031 bool is_instant_process = instant_service->IsInstantProcess(
1032 process_host->GetID());
1033 bool should_be_in_instant_process =
1034 chrome::ShouldAssignURLToInstantRenderer(site_url, profile);
1035 if (is_instant_process || should_be_in_instant_process)
1036 return is_instant_process && should_be_in_instant_process;
1039 #if defined(ENABLE_EXTENSIONS)
1040 return ChromeContentBrowserClientExtensionsPart::IsSuitableHost(
1041 profile, process_host, site_url);
1042 #else
1043 return true;
1044 #endif
1047 bool ChromeContentBrowserClient::MayReuseHost(
1048 content::RenderProcessHost* process_host) {
1049 // If there is currently a prerender in progress for the host provided,
1050 // it may not be shared. We require prerenders to be by themselves in a
1051 // separate process so that we can monitor their resource usage.
1052 Profile* profile = Profile::FromBrowserContext(
1053 process_host->GetBrowserContext());
1054 prerender::PrerenderManager* prerender_manager =
1055 prerender::PrerenderManagerFactory::GetForProfile(profile);
1056 if (prerender_manager &&
1057 !prerender_manager->MayReuseProcessHost(process_host)) {
1058 return false;
1061 return true;
1064 bool ChromeContentBrowserClient::ShouldTryToUseExistingProcessHost(
1065 content::BrowserContext* browser_context, const GURL& url) {
1066 // It has to be a valid URL for us to check for an extension.
1067 if (!url.is_valid())
1068 return false;
1070 #if defined(ENABLE_EXTENSIONS)
1071 Profile* profile = Profile::FromBrowserContext(browser_context);
1072 return ChromeContentBrowserClientExtensionsPart::
1073 ShouldTryToUseExistingProcessHost(
1074 profile, url);
1075 #else
1076 return false;
1077 #endif
1080 void ChromeContentBrowserClient::SiteInstanceGotProcess(
1081 SiteInstance* site_instance) {
1082 CHECK(site_instance->HasProcess());
1084 Profile* profile = Profile::FromBrowserContext(
1085 site_instance->GetBrowserContext());
1086 if (!profile)
1087 return;
1089 // Remember the ID of the Instant process to signal the renderer process
1090 // on startup in |AppendExtraCommandLineSwitches| below.
1091 if (chrome::ShouldAssignURLToInstantRenderer(
1092 site_instance->GetSiteURL(), profile)) {
1093 InstantService* instant_service =
1094 InstantServiceFactory::GetForProfile(profile);
1095 if (instant_service)
1096 instant_service->AddInstantProcess(site_instance->GetProcess()->GetID());
1099 for (size_t i = 0; i < extra_parts_.size(); ++i)
1100 extra_parts_[i]->SiteInstanceGotProcess(site_instance);
1103 void ChromeContentBrowserClient::SiteInstanceDeleting(
1104 SiteInstance* site_instance) {
1105 if (!site_instance->HasProcess())
1106 return;
1108 for (size_t i = 0; i < extra_parts_.size(); ++i)
1109 extra_parts_[i]->SiteInstanceDeleting(site_instance);
1112 bool ChromeContentBrowserClient::ShouldSwapBrowsingInstancesForNavigation(
1113 SiteInstance* site_instance,
1114 const GURL& current_url,
1115 const GURL& new_url) {
1116 #if defined(ENABLE_EXTENSIONS)
1117 return ChromeContentBrowserClientExtensionsPart::
1118 ShouldSwapBrowsingInstancesForNavigation(
1119 site_instance, current_url, new_url);
1120 #else
1121 return false;
1122 #endif
1125 bool ChromeContentBrowserClient::ShouldSwapProcessesForRedirect(
1126 content::ResourceContext* resource_context, const GURL& current_url,
1127 const GURL& new_url) {
1128 #if defined(ENABLE_EXTENSIONS)
1129 return ChromeContentBrowserClientExtensionsPart::
1130 ShouldSwapProcessesForRedirect(resource_context, current_url, new_url);
1131 #else
1132 return false;
1133 #endif
1136 bool ChromeContentBrowserClient::ShouldAssignSiteForURL(const GURL& url) {
1137 return !url.SchemeIs(chrome::kChromeNativeScheme);
1140 std::string ChromeContentBrowserClient::GetCanonicalEncodingNameByAliasName(
1141 const std::string& alias_name) {
1142 return CharacterEncoding::GetCanonicalEncodingNameByAliasName(alias_name);
1145 namespace {
1147 bool IsAutoReloadEnabled() {
1148 // Fetch the field trial, even though we don't use it. Calling FindFullName()
1149 // causes the field-trial mechanism to report which group we're in, which
1150 // might reflect a hard disable or hard enable via flag, both of which have
1151 // their own field trial groups. This lets us know what percentage of users
1152 // manually enable or disable auto-reload.
1153 std::string group = base::FieldTrialList::FindFullName(
1154 "AutoReloadExperiment");
1155 const base::CommandLine& browser_command_line =
1156 *base::CommandLine::ForCurrentProcess();
1157 if (browser_command_line.HasSwitch(switches::kEnableOfflineAutoReload))
1158 return true;
1159 if (browser_command_line.HasSwitch(switches::kDisableOfflineAutoReload))
1160 return false;
1161 return true;
1164 bool IsAutoReloadVisibleOnlyEnabled() {
1165 // See the block comment in IsAutoReloadEnabled().
1166 std::string group = base::FieldTrialList::FindFullName(
1167 "AutoReloadVisibleOnlyExperiment");
1168 const base::CommandLine& browser_command_line =
1169 *base::CommandLine::ForCurrentProcess();
1170 if (browser_command_line.HasSwitch(
1171 switches::kEnableOfflineAutoReloadVisibleOnly)) {
1172 return true;
1174 if (browser_command_line.HasSwitch(
1175 switches::kDisableOfflineAutoReloadVisibleOnly)) {
1176 return false;
1178 return true;
1181 void MaybeAppendBlinkSettingsSwitchForFieldTrial(
1182 const base::CommandLine& browser_command_line,
1183 base::CommandLine* command_line) {
1184 // List of field trials that modify the blink-settings command line flag. No
1185 // two field trials in the list should specify the same keys, otherwise one
1186 // field trial may overwrite another. See Source/core/frame/Settings.in in
1187 // Blink for the list of valid keys.
1188 static const char* const kBlinkSettingsFieldTrials[] = {
1189 // Keys: backgroundHtmlParserOutstandingTokenLimit
1190 // backgroundHtmlParserPendingTokenLimit
1191 "BackgroundHtmlParserTokenLimits",
1193 // Keys: doHtmlPreloadScanning
1194 "HtmlPreloadScanning",
1196 // Keys: lowPriorityIframes
1197 "LowPriorityIFrames",
1200 std::vector<std::string> blink_settings;
1201 for (const char* field_trial_name : kBlinkSettingsFieldTrials) {
1202 // Each blink-settings field trial should include a forcing_flag group,
1203 // to make sure that clients that specify the blink-settings flag on the
1204 // command line are excluded from the experiment groups. To make
1205 // sure we assign clients that specify this flag to the forcing_flag
1206 // group, we must call GetVariationParams for each field trial first
1207 // (for example, before checking HasSwitch() and returning), since
1208 // GetVariationParams has the side-effect of assigning the client to
1209 // a field trial group.
1210 std::map<std::string, std::string> params;
1211 if (variations::GetVariationParams(field_trial_name, &params)) {
1212 for (const auto& param : params) {
1213 blink_settings.push_back(base::StringPrintf(
1214 "%s=%s", param.first.c_str(), param.second.c_str()));
1218 if (blink_settings.empty()) {
1219 return;
1222 if (browser_command_line.HasSwitch(switches::kBlinkSettings) ||
1223 command_line->HasSwitch(switches::kBlinkSettings)) {
1224 // The field trial is configured to force users that specify the
1225 // blink-settings flag into a group with no params, and we return
1226 // above if no params were specified, so it's an error if we reach
1227 // this point.
1228 LOG(WARNING) << "Received field trial params, "
1229 "but blink-settings switch already specified.";
1230 return;
1233 command_line->AppendSwitchASCII(switches::kBlinkSettings,
1234 base::JoinString(blink_settings, ","));
1237 } // namespace
1239 void ChromeContentBrowserClient::AppendExtraCommandLineSwitches(
1240 base::CommandLine* command_line,
1241 int child_process_id) {
1242 #if defined(OS_MACOSX)
1243 scoped_ptr<metrics::ClientInfo> client_info =
1244 GoogleUpdateSettings::LoadMetricsClientInfo();
1245 if (client_info) {
1246 command_line->AppendSwitchASCII(switches::kMetricsClientID,
1247 client_info->client_id);
1249 #elif defined(OS_POSIX)
1250 if (breakpad::IsCrashReporterEnabled()) {
1251 scoped_ptr<metrics::ClientInfo> client_info =
1252 GoogleUpdateSettings::LoadMetricsClientInfo();
1253 command_line->AppendSwitchASCII(switches::kEnableCrashReporter,
1254 client_info ? client_info->client_id
1255 : std::string());
1257 #endif
1259 if (logging::DialogsAreSuppressed())
1260 command_line->AppendSwitch(switches::kNoErrorDialogs);
1262 std::string process_type =
1263 command_line->GetSwitchValueASCII(switches::kProcessType);
1264 const base::CommandLine& browser_command_line =
1265 *base::CommandLine::ForCurrentProcess();
1267 static const char* const kCommonSwitchNames[] = {
1268 switches::kUserAgent,
1269 switches::kUserDataDir, // Make logs go to the right file.
1271 command_line->CopySwitchesFrom(browser_command_line, kCommonSwitchNames,
1272 arraysize(kCommonSwitchNames));
1274 #if defined(ENABLE_IPC_FUZZER)
1275 static const char* const kIpcFuzzerSwitches[] = {
1276 switches::kIpcDumpDirectory,
1277 switches::kIpcFuzzerTestcase,
1279 command_line->CopySwitchesFrom(browser_command_line, kIpcFuzzerSwitches,
1280 arraysize(kIpcFuzzerSwitches));
1281 #endif
1283 #if defined(OS_CHROMEOS)
1284 static const char* const kChromeOSSwitches[] = {
1285 switches::kDisableDinosaurEasterEgg,
1287 command_line->CopySwitchesFrom(browser_command_line, kChromeOSSwitches,
1288 arraysize(kChromeOSSwitches));
1290 // On Chrome OS need to pass primary user homedir (in multi-profiles session).
1291 base::FilePath homedir;
1292 PathService::Get(base::DIR_HOME, &homedir);
1293 command_line->AppendSwitchASCII(chromeos::switches::kHomedir,
1294 homedir.value().c_str());
1295 #endif
1297 if (process_type == switches::kRendererProcess) {
1298 content::RenderProcessHost* process =
1299 content::RenderProcessHost::FromID(child_process_id);
1300 Profile* profile =
1301 process ? Profile::FromBrowserContext(process->GetBrowserContext())
1302 : NULL;
1303 for (size_t i = 0; i < extra_parts_.size(); ++i) {
1304 extra_parts_[i]->AppendExtraRendererCommandLineSwitches(
1305 command_line, process, profile);
1308 #if defined(OS_CHROMEOS)
1309 const std::string& login_profile =
1310 browser_command_line.GetSwitchValueASCII(
1311 chromeos::switches::kLoginProfile);
1312 if (!login_profile.empty())
1313 command_line->AppendSwitchASCII(
1314 chromeos::switches::kLoginProfile, login_profile);
1315 #endif
1317 #if defined(ENABLE_WEBRTC)
1318 MaybeCopyDisableWebRtcEncryptionSwitch(command_line,
1319 browser_command_line,
1320 VersionInfo::GetChannel());
1321 #endif
1323 if (process) {
1324 PrefService* prefs = profile->GetPrefs();
1325 // Currently this pref is only registered if applied via a policy.
1326 if (prefs->HasPrefPath(prefs::kDisable3DAPIs) &&
1327 prefs->GetBoolean(prefs::kDisable3DAPIs)) {
1328 // Turn this policy into a command line switch.
1329 command_line->AppendSwitch(switches::kDisable3DAPIs);
1332 const base::ListValue* switches =
1333 prefs->GetList(prefs::kEnableDeprecatedWebPlatformFeatures);
1334 if (switches) {
1335 // Enable any deprecated features that have been re-enabled by policy.
1336 for (base::ListValue::const_iterator it = switches->begin();
1337 it != switches->end(); ++it) {
1338 std::string switch_to_enable;
1339 if ((*it)->GetAsString(&switch_to_enable))
1340 command_line->AppendSwitch(switch_to_enable);
1344 // Disable client-side phishing detection in the renderer if it is
1345 // disabled in the Profile preferences or the browser process.
1346 if (!prefs->GetBoolean(prefs::kSafeBrowsingEnabled) ||
1347 !g_browser_process->safe_browsing_detection_service()) {
1348 command_line->AppendSwitch(
1349 switches::kDisableClientSidePhishingDetection);
1352 if (prefs->GetBoolean(prefs::kPrintPreviewDisabled))
1353 command_line->AppendSwitch(switches::kDisablePrintPreview);
1355 InstantService* instant_service =
1356 InstantServiceFactory::GetForProfile(profile);
1357 if (instant_service &&
1358 instant_service->IsInstantProcess(process->GetID()))
1359 command_line->AppendSwitch(switches::kInstantProcess);
1362 if (IsAutoReloadEnabled())
1363 command_line->AppendSwitch(switches::kEnableOfflineAutoReload);
1364 if (IsAutoReloadVisibleOnlyEnabled()) {
1365 command_line->AppendSwitch(
1366 switches::kEnableOfflineAutoReloadVisibleOnly);
1370 // Enable showing a saved copy if this session is in the field trial
1371 // or the user explicitly enabled it. Note that as far as the
1372 // renderer is concerned, the feature is enabled if-and-only-if
1373 // one of the kEnableShowSavedCopy* switches is on the command
1374 // line; the yes/no/default behavior is only at the browser
1375 // command line level.
1377 // Command line switches override
1378 const std::string& show_saved_copy_value =
1379 browser_command_line.GetSwitchValueASCII(switches::kShowSavedCopy);
1380 if (show_saved_copy_value == switches::kEnableShowSavedCopyPrimary ||
1381 show_saved_copy_value == switches::kEnableShowSavedCopySecondary ||
1382 show_saved_copy_value == switches::kDisableShowSavedCopy) {
1383 command_line->AppendSwitchASCII(switches::kShowSavedCopy,
1384 show_saved_copy_value);
1385 } else {
1386 std::string group =
1387 base::FieldTrialList::FindFullName("LoadStaleCacheExperiment");
1389 if (group == "Primary") {
1390 command_line->AppendSwitchASCII(
1391 switches::kShowSavedCopy, switches::kEnableShowSavedCopyPrimary);
1392 } else if (group == "Secondary") {
1393 command_line->AppendSwitchASCII(
1394 switches::kShowSavedCopy,
1395 switches::kEnableShowSavedCopySecondary);
1400 MaybeAppendBlinkSettingsSwitchForFieldTrial(
1401 browser_command_line, command_line);
1403 // Please keep this in alphabetical order.
1404 static const char* const kSwitchNames[] = {
1405 autofill::switches::kDisableFillOnAccountSelect,
1406 autofill::switches::kDisablePasswordGeneration,
1407 autofill::switches::kEnableAccessorySuggestionView,
1408 autofill::switches::kEnableFillOnAccountSelect,
1409 autofill::switches::kEnableFillOnAccountSelectNoHighlighting,
1410 autofill::switches::kEnablePasswordGeneration,
1411 autofill::switches::kEnableSingleClickAutofill,
1412 autofill::switches::kEnableSuggestionsWithSubstringMatch,
1413 autofill::switches::kIgnoreAutocompleteOffForAutofill,
1414 autofill::switches::kLocalHeuristicsOnlyForPasswordGeneration,
1415 #if defined(ENABLE_EXTENSIONS)
1416 extensions::switches::kAllowHTTPBackgroundPage,
1417 extensions::switches::kAllowLegacyExtensionManifests,
1418 extensions::switches::kEnableSurfaceWorker,
1419 extensions::switches::kEnableAppWindowControls,
1420 extensions::switches::kEnableEmbeddedExtensionOptions,
1421 extensions::switches::kEnableExperimentalExtensionApis,
1422 extensions::switches::kExtensionsOnChromeURLs,
1423 extensions::switches::kWhitelistedExtensionID,
1424 #endif
1425 switches::kAllowInsecureLocalhost,
1426 switches::kAppsCheckoutURL,
1427 switches::kAppsGalleryURL,
1428 switches::kCloudPrintURL,
1429 switches::kCloudPrintXmppEndpoint,
1430 switches::kDisableBundledPpapiFlash,
1431 switches::kDisableCastStreamingHWEncoding,
1432 switches::kDisableJavaScriptHarmonyShipping,
1433 switches::kDisableNewBookmarkApps,
1434 switches::kEnableBenchmarking,
1435 switches::kEnableNaCl,
1436 #if !defined(DISABLE_NACL)
1437 switches::kEnableNaClDebug,
1438 switches::kEnableNaClNonSfiMode,
1439 switches::kEnablePNaClSubzero,
1440 #endif
1441 switches::kEnableNetBenchmarking,
1442 switches::kEnableNewBookmarkApps,
1443 switches::kEnablePluginPlaceholderShadowDom,
1444 switches::kJavaScriptHarmony,
1445 switches::kMessageLoopHistogrammer,
1446 switches::kPpapiFlashArgs,
1447 switches::kPpapiFlashPath,
1448 switches::kPpapiFlashVersion,
1449 switches::kProfilingAtStart,
1450 switches::kProfilingFile,
1451 switches::kProfilingFlush,
1452 switches::kUnsafelyTreatInsecureOriginAsSecure,
1453 translate::switches::kTranslateSecurityOrigin,
1456 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1457 arraysize(kSwitchNames));
1458 } else if (process_type == switches::kUtilityProcess) {
1459 #if defined(ENABLE_EXTENSIONS)
1460 static const char* const kSwitchNames[] = {
1461 extensions::switches::kAllowHTTPBackgroundPage,
1462 extensions::switches::kEnableExperimentalExtensionApis,
1463 extensions::switches::kExtensionsOnChromeURLs,
1464 extensions::switches::kWhitelistedExtensionID,
1467 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1468 arraysize(kSwitchNames));
1469 #endif
1470 } else if (process_type == switches::kPluginProcess) {
1471 #if defined(OS_CHROMEOS)
1472 static const char* const kSwitchNames[] = {
1473 chromeos::switches::kLoginProfile,
1476 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1477 arraysize(kSwitchNames));
1478 #endif
1479 } else if (process_type == switches::kZygoteProcess) {
1480 static const char* const kSwitchNames[] = {
1481 // Load (in-process) Pepper plugins in-process in the zygote pre-sandbox.
1482 switches::kDisableBundledPpapiFlash,
1483 #if !defined(DISABLE_NACL)
1484 switches::kEnableNaClDebug,
1485 switches::kEnableNaClNonSfiMode,
1486 switches::kEnablePNaClSubzero,
1487 switches::kNaClDangerousNoSandboxNonSfi,
1488 switches::kUseNaClHelperNonSfi,
1489 #endif
1490 switches::kPpapiFlashPath,
1491 switches::kPpapiFlashVersion,
1494 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1495 arraysize(kSwitchNames));
1496 } else if (process_type == switches::kGpuProcess) {
1497 // If --ignore-gpu-blacklist is passed in, don't send in crash reports
1498 // because GPU is expected to be unreliable.
1499 if (browser_command_line.HasSwitch(switches::kIgnoreGpuBlacklist) &&
1500 !command_line->HasSwitch(switches::kDisableBreakpad))
1501 command_line->AppendSwitch(switches::kDisableBreakpad);
1504 // The command line switch kEnableBenchmarking needs to be specified along
1505 // with the kEnableStatsTable switch to ensure that the stats table global
1506 // is initialized correctly.
1507 if (command_line->HasSwitch(switches::kEnableBenchmarking))
1508 DCHECK(command_line->HasSwitch(switches::kEnableStatsTable));
1511 std::string ChromeContentBrowserClient::GetApplicationLocale() {
1512 if (BrowserThread::CurrentlyOn(BrowserThread::IO))
1513 return g_io_thread_application_locale.Get();
1514 return g_browser_process->GetApplicationLocale();
1517 std::string ChromeContentBrowserClient::GetAcceptLangs(
1518 content::BrowserContext* context) {
1519 Profile* profile = Profile::FromBrowserContext(context);
1520 return profile->GetPrefs()->GetString(prefs::kAcceptLanguages);
1523 const gfx::ImageSkia* ChromeContentBrowserClient::GetDefaultFavicon() {
1524 ResourceBundle& rb = ResourceBundle::GetSharedInstance();
1525 return rb.GetNativeImageNamed(IDR_DEFAULT_FAVICON).ToImageSkia();
1528 bool ChromeContentBrowserClient::AllowAppCache(
1529 const GURL& manifest_url,
1530 const GURL& first_party,
1531 content::ResourceContext* context) {
1532 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1533 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1534 return io_data->GetCookieSettings()->
1535 IsSettingCookieAllowed(manifest_url, first_party);
1538 bool ChromeContentBrowserClient::AllowServiceWorker(
1539 const GURL& scope,
1540 const GURL& first_party_url,
1541 content::ResourceContext* context,
1542 int render_process_id,
1543 int render_frame_id) {
1544 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1545 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1546 bool allow = io_data->GetCookieSettings()->IsSettingCookieAllowed(
1547 scope, first_party_url);
1549 // Record access to database for potential display in UI.
1550 BrowserThread::PostTask(
1551 BrowserThread::UI, FROM_HERE,
1552 base::Bind(&TabSpecificContentSettings::ServiceWorkerAccessed,
1553 render_process_id, render_frame_id, scope, !allow));
1554 return allow;
1557 bool ChromeContentBrowserClient::AllowGetCookie(
1558 const GURL& url,
1559 const GURL& first_party,
1560 const net::CookieList& cookie_list,
1561 content::ResourceContext* context,
1562 int render_process_id,
1563 int render_frame_id) {
1564 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1565 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1566 bool allow = io_data->GetCookieSettings()->
1567 IsReadingCookieAllowed(url, first_party);
1569 BrowserThread::PostTask(
1570 BrowserThread::UI, FROM_HERE,
1571 base::Bind(&TabSpecificContentSettings::CookiesRead, render_process_id,
1572 render_frame_id, url, first_party, cookie_list, !allow));
1573 return allow;
1576 bool ChromeContentBrowserClient::AllowSetCookie(
1577 const GURL& url,
1578 const GURL& first_party,
1579 const std::string& cookie_line,
1580 content::ResourceContext* context,
1581 int render_process_id,
1582 int render_frame_id,
1583 net::CookieOptions* options) {
1584 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1585 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1586 content_settings::CookieSettings* cookie_settings =
1587 io_data->GetCookieSettings();
1588 bool allow = cookie_settings->IsSettingCookieAllowed(url, first_party);
1590 BrowserThread::PostTask(
1591 BrowserThread::UI, FROM_HERE,
1592 base::Bind(&TabSpecificContentSettings::CookieChanged, render_process_id,
1593 render_frame_id, url, first_party, cookie_line, *options,
1594 !allow));
1595 return allow;
1598 bool ChromeContentBrowserClient::AllowSaveLocalState(
1599 content::ResourceContext* context) {
1600 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1601 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1602 content_settings::CookieSettings* cookie_settings =
1603 io_data->GetCookieSettings();
1604 ContentSetting setting = cookie_settings->GetDefaultCookieSetting(NULL);
1606 // TODO(bauerb): Should we also disallow local state if the default is BLOCK?
1607 // Could we even support per-origin settings?
1608 return setting != CONTENT_SETTING_SESSION_ONLY;
1611 bool ChromeContentBrowserClient::AllowWorkerDatabase(
1612 const GURL& url,
1613 const base::string16& name,
1614 const base::string16& display_name,
1615 unsigned long estimated_size,
1616 content::ResourceContext* context,
1617 const std::vector<std::pair<int, int> >& render_frames) {
1618 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1619 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1620 content_settings::CookieSettings* cookie_settings =
1621 io_data->GetCookieSettings();
1622 bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1624 // Record access to database for potential display in UI.
1625 std::vector<std::pair<int, int> >::const_iterator i;
1626 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1627 BrowserThread::PostTask(
1628 BrowserThread::UI, FROM_HERE,
1629 base::Bind(&TabSpecificContentSettings::WebDatabaseAccessed,
1630 i->first, i->second, url, name, display_name, !allow));
1633 return allow;
1636 void ChromeContentBrowserClient::AllowWorkerFileSystem(
1637 const GURL& url,
1638 content::ResourceContext* context,
1639 const std::vector<std::pair<int, int> >& render_frames,
1640 base::Callback<void(bool)> callback) {
1641 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1642 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1643 content_settings::CookieSettings* cookie_settings =
1644 io_data->GetCookieSettings();
1645 bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1647 #if defined(ENABLE_EXTENSIONS)
1648 GuestPermissionRequestHelper(url, render_frames, callback, allow);
1649 #else
1650 FileSystemAccessed(url, render_frames, callback, allow);
1651 #endif
1654 #if defined(ENABLE_EXTENSIONS)
1655 void ChromeContentBrowserClient::GuestPermissionRequestHelper(
1656 const GURL& url,
1657 const std::vector<std::pair<int, int> >& render_frames,
1658 base::Callback<void(bool)> callback,
1659 bool allow) {
1660 DCHECK(BrowserThread:: CurrentlyOn(BrowserThread::IO));
1661 std::vector<std::pair<int, int> >::const_iterator i;
1662 std::map<int, int> process_map;
1663 std::map<int, int>::const_iterator it;
1664 bool has_web_view_guest = false;
1665 // Record access to file system for potential display in UI.
1666 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1667 if (process_map.find(i->first) != process_map.end())
1668 continue;
1670 process_map.insert(std::pair<int, int>(i->first, i->second));
1672 if (extensions::WebViewRendererState::GetInstance()->IsGuest(i->first))
1673 has_web_view_guest = true;
1675 if (!has_web_view_guest) {
1676 FileSystemAccessed(url, render_frames, callback, allow);
1677 return;
1679 DCHECK_EQ(1U, process_map.size());
1680 it = process_map.begin();
1681 BrowserThread::PostTask(
1682 BrowserThread::UI,
1683 FROM_HERE,
1684 base::Bind(&ChromeContentBrowserClient::
1685 RequestFileSystemPermissionOnUIThread,
1686 it->first,
1687 it->second,
1688 url,
1689 allow,
1690 base::Bind(&ChromeContentBrowserClient::FileSystemAccessed,
1691 weak_factory_.GetWeakPtr(),
1692 url,
1693 render_frames,
1694 callback)));
1697 void ChromeContentBrowserClient::RequestFileSystemPermissionOnUIThread(
1698 int render_process_id,
1699 int render_frame_id,
1700 const GURL& url,
1701 bool allowed_by_default,
1702 const base::Callback<void(bool)>& callback) {
1703 DCHECK(BrowserThread:: CurrentlyOn(BrowserThread::UI));
1704 extensions::WebViewPermissionHelper* web_view_permission_helper =
1705 extensions::WebViewPermissionHelper::FromFrameID(
1706 render_process_id, render_frame_id);
1707 web_view_permission_helper->RequestFileSystemPermission(url,
1708 allowed_by_default,
1709 callback);
1711 #endif
1713 void ChromeContentBrowserClient::FileSystemAccessed(
1714 const GURL& url,
1715 const std::vector<std::pair<int, int> >& render_frames,
1716 base::Callback<void(bool)> callback,
1717 bool allow) {
1718 // Record access to file system for potential display in UI.
1719 std::vector<std::pair<int, int> >::const_iterator i;
1720 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1721 BrowserThread::PostTask(
1722 BrowserThread::UI,
1723 FROM_HERE,
1724 base::Bind(&TabSpecificContentSettings::FileSystemAccessed,
1725 i->first, i->second, url, !allow));
1727 callback.Run(allow);
1730 bool ChromeContentBrowserClient::AllowWorkerIndexedDB(
1731 const GURL& url,
1732 const base::string16& name,
1733 content::ResourceContext* context,
1734 const std::vector<std::pair<int, int> >& render_frames) {
1735 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1736 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1737 content_settings::CookieSettings* cookie_settings =
1738 io_data->GetCookieSettings();
1739 bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1741 // Record access to IndexedDB for potential display in UI.
1742 std::vector<std::pair<int, int> >::const_iterator i;
1743 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1744 BrowserThread::PostTask(
1745 BrowserThread::UI, FROM_HERE,
1746 base::Bind(&TabSpecificContentSettings::IndexedDBAccessed,
1747 i->first, i->second, url, name, !allow));
1750 return allow;
1753 net::URLRequestContext*
1754 ChromeContentBrowserClient::OverrideRequestContextForURL(
1755 const GURL& url, content::ResourceContext* context) {
1756 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1757 #if defined(ENABLE_EXTENSIONS)
1758 if (url.SchemeIs(extensions::kExtensionScheme)) {
1759 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1760 return io_data->extensions_request_context();
1762 #endif
1764 return NULL;
1767 QuotaPermissionContext*
1768 ChromeContentBrowserClient::CreateQuotaPermissionContext() {
1769 return new ChromeQuotaPermissionContext();
1772 void ChromeContentBrowserClient::AllowCertificateError(
1773 int render_process_id,
1774 int render_frame_id,
1775 int cert_error,
1776 const net::SSLInfo& ssl_info,
1777 const GURL& request_url,
1778 ResourceType resource_type,
1779 bool overridable,
1780 bool strict_enforcement,
1781 bool expired_previous_decision,
1782 const base::Callback<void(bool)>& callback,
1783 content::CertificateRequestResultType* result) {
1784 if (resource_type != content::RESOURCE_TYPE_MAIN_FRAME) {
1785 // A sub-resource has a certificate error. The user doesn't really
1786 // have a context for making the right decision, so block the
1787 // request hard, without an info bar to allow showing the insecure
1788 // content.
1789 *result = content::CERTIFICATE_REQUEST_RESULT_TYPE_DENY;
1790 return;
1793 // If the tab is being prerendered, cancel the prerender and the request.
1794 content::RenderFrameHost* render_frame_host =
1795 content::RenderFrameHost::FromID(render_process_id, render_frame_id);
1796 WebContents* tab = WebContents::FromRenderFrameHost(render_frame_host);
1797 if (!tab) {
1798 NOTREACHED();
1799 return;
1802 prerender::PrerenderContents* prerender_contents =
1803 prerender::PrerenderContents::FromWebContents(tab);
1804 if (prerender_contents) {
1805 prerender_contents->Destroy(prerender::FINAL_STATUS_SSL_ERROR);
1806 *result = content::CERTIFICATE_REQUEST_RESULT_TYPE_CANCEL;
1807 return;
1810 // Otherwise, display an SSL blocking page. The interstitial page takes
1811 // ownership of ssl_blocking_page.
1812 int options_mask = 0;
1813 if (overridable)
1814 options_mask |= SSLBlockingPage::OVERRIDABLE;
1815 if (strict_enforcement)
1816 options_mask |= SSLBlockingPage::STRICT_ENFORCEMENT;
1817 if (expired_previous_decision)
1818 options_mask |= SSLBlockingPage::EXPIRED_BUT_PREVIOUSLY_ALLOWED;
1820 SafeBrowsingService* safe_browsing_service =
1821 g_browser_process->safe_browsing_service();
1822 scoped_ptr<SafeBrowsingSSLCertReporter> cert_reporter(
1823 new SafeBrowsingSSLCertReporter(safe_browsing_service
1824 ? safe_browsing_service->ui_manager()
1825 : nullptr));
1826 SSLErrorHandler::HandleSSLError(tab, cert_error, ssl_info, request_url,
1827 options_mask, cert_reporter.Pass(), callback);
1830 void ChromeContentBrowserClient::SelectClientCertificate(
1831 content::WebContents* web_contents,
1832 net::SSLCertRequestInfo* cert_request_info,
1833 scoped_ptr<content::ClientCertificateDelegate> delegate) {
1834 prerender::PrerenderContents* prerender_contents =
1835 prerender::PrerenderContents::FromWebContents(web_contents);
1836 if (prerender_contents) {
1837 prerender_contents->Destroy(
1838 prerender::FINAL_STATUS_SSL_CLIENT_CERTIFICATE_REQUESTED);
1839 return;
1842 GURL requesting_url("https://" + cert_request_info->host_and_port.ToString());
1843 DCHECK(requesting_url.is_valid())
1844 << "Invalid URL string: https://"
1845 << cert_request_info->host_and_port.ToString();
1847 Profile* profile =
1848 Profile::FromBrowserContext(web_contents->GetBrowserContext());
1849 scoped_ptr<base::Value> filter =
1850 profile->GetHostContentSettingsMap()->GetWebsiteSetting(
1851 requesting_url,
1852 requesting_url,
1853 CONTENT_SETTINGS_TYPE_AUTO_SELECT_CERTIFICATE,
1854 std::string(),
1855 NULL);
1857 if (filter.get()) {
1858 // Try to automatically select a client certificate.
1859 if (filter->IsType(base::Value::TYPE_DICTIONARY)) {
1860 base::DictionaryValue* filter_dict =
1861 static_cast<base::DictionaryValue*>(filter.get());
1863 const std::vector<scoped_refptr<net::X509Certificate> >&
1864 all_client_certs = cert_request_info->client_certs;
1865 for (size_t i = 0; i < all_client_certs.size(); ++i) {
1866 if (CertMatchesFilter(*all_client_certs[i].get(), *filter_dict)) {
1867 // Use the first certificate that is matched by the filter.
1868 delegate->ContinueWithCertificate(all_client_certs[i].get());
1869 return;
1872 } else {
1873 NOTREACHED();
1877 chrome::ShowSSLClientCertificateSelector(web_contents, cert_request_info,
1878 delegate.Pass());
1881 void ChromeContentBrowserClient::AddCertificate(
1882 net::CertificateMimeType cert_type,
1883 const void* cert_data,
1884 size_t cert_size,
1885 int render_process_id,
1886 int render_frame_id) {
1887 chrome::SSLAddCertificate(cert_type, cert_data, cert_size,
1888 render_process_id, render_frame_id);
1891 content::MediaObserver* ChromeContentBrowserClient::GetMediaObserver() {
1892 return MediaCaptureDevicesDispatcher::GetInstance();
1895 content::PlatformNotificationService*
1896 ChromeContentBrowserClient::GetPlatformNotificationService() {
1897 #if defined(ENABLE_NOTIFICATIONS)
1898 return PlatformNotificationServiceImpl::GetInstance();
1899 #else
1900 NOTIMPLEMENTED();
1901 return NULL;
1902 #endif
1905 bool ChromeContentBrowserClient::CanCreateWindow(
1906 const GURL& opener_url,
1907 const GURL& opener_top_level_frame_url,
1908 const GURL& source_origin,
1909 WindowContainerType container_type,
1910 const GURL& target_url,
1911 const content::Referrer& referrer,
1912 WindowOpenDisposition disposition,
1913 const WebWindowFeatures& features,
1914 bool user_gesture,
1915 bool opener_suppressed,
1916 content::ResourceContext* context,
1917 int render_process_id,
1918 int opener_render_view_id,
1919 int opener_render_frame_id,
1920 bool* no_javascript_access) {
1921 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1923 *no_javascript_access = false;
1925 // If the opener is trying to create a background window but doesn't have
1926 // the appropriate permission, fail the attempt.
1927 if (container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {
1928 #if defined(ENABLE_EXTENSIONS)
1929 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1930 InfoMap* map = io_data->GetExtensionInfoMap();
1931 if (!map->SecurityOriginHasAPIPermission(
1932 source_origin,
1933 render_process_id,
1934 APIPermission::kBackground)) {
1935 return false;
1938 // Note: this use of GetExtensionOrAppByURL is safe but imperfect. It may
1939 // return a recently installed Extension even if this CanCreateWindow call
1940 // was made by an old copy of the page in a normal web process. That's ok,
1941 // because the permission check above would have caused an early return
1942 // already. We must use the full URL to find hosted apps, though, and not
1943 // just the origin.
1944 const Extension* extension =
1945 map->extensions().GetExtensionOrAppByURL(opener_url);
1946 if (extension && !extensions::BackgroundInfo::AllowJSAccess(extension))
1947 *no_javascript_access = true;
1948 #endif
1950 return true;
1953 #if defined(ENABLE_EXTENSIONS)
1954 if (extensions::WebViewRendererState::GetInstance()->IsGuest(
1955 render_process_id))
1956 return true;
1957 #endif
1959 HostContentSettingsMap* content_settings =
1960 ProfileIOData::FromResourceContext(context)->GetHostContentSettingsMap();
1961 BlockedWindowParams blocked_params(target_url,
1962 referrer,
1963 disposition,
1964 features,
1965 user_gesture,
1966 opener_suppressed,
1967 render_process_id,
1968 opener_render_frame_id);
1970 if (!user_gesture &&
1971 !base::CommandLine::ForCurrentProcess()->HasSwitch(
1972 switches::kDisablePopupBlocking)) {
1973 if (content_settings->GetContentSetting(opener_top_level_frame_url,
1974 opener_top_level_frame_url,
1975 CONTENT_SETTINGS_TYPE_POPUPS,
1976 std::string()) !=
1977 CONTENT_SETTING_ALLOW) {
1978 BrowserThread::PostTask(BrowserThread::UI,
1979 FROM_HERE,
1980 base::Bind(&HandleBlockedPopupOnUIThread,
1981 blocked_params));
1982 return false;
1986 #if defined(OS_ANDROID)
1987 if (SingleTabModeTabHelper::IsRegistered(render_process_id,
1988 opener_render_view_id)) {
1989 BrowserThread::PostTask(BrowserThread::UI,
1990 FROM_HERE,
1991 base::Bind(&HandleSingleTabModeBlockOnUIThread,
1992 blocked_params));
1993 return false;
1995 #endif
1997 return true;
2000 void ChromeContentBrowserClient::ResourceDispatcherHostCreated() {
2001 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
2002 return g_browser_process->ResourceDispatcherHostCreated();
2005 content::SpeechRecognitionManagerDelegate*
2006 ChromeContentBrowserClient::CreateSpeechRecognitionManagerDelegate() {
2007 return new speech::ChromeSpeechRecognitionManagerDelegate();
2010 net::NetLog* ChromeContentBrowserClient::GetNetLog() {
2011 return g_browser_process->net_log();
2014 AccessTokenStore* ChromeContentBrowserClient::CreateAccessTokenStore() {
2015 return new ChromeAccessTokenStore();
2018 bool ChromeContentBrowserClient::IsFastShutdownPossible() {
2019 return true;
2022 void ChromeContentBrowserClient::OverrideWebkitPrefs(
2023 RenderViewHost* rvh, WebPreferences* web_prefs) {
2024 Profile* profile = Profile::FromBrowserContext(
2025 rvh->GetProcess()->GetBrowserContext());
2026 PrefService* prefs = profile->GetPrefs();
2028 // Fill per-script font preferences. These are not registered on Android
2029 // - http://crbug.com/308033.
2030 #if !defined(OS_ANDROID)
2031 FontFamilyCache::FillFontFamilyMap(profile,
2032 prefs::kWebKitStandardFontFamilyMap,
2033 &web_prefs->standard_font_family_map);
2034 FontFamilyCache::FillFontFamilyMap(profile,
2035 prefs::kWebKitFixedFontFamilyMap,
2036 &web_prefs->fixed_font_family_map);
2037 FontFamilyCache::FillFontFamilyMap(profile,
2038 prefs::kWebKitSerifFontFamilyMap,
2039 &web_prefs->serif_font_family_map);
2040 FontFamilyCache::FillFontFamilyMap(profile,
2041 prefs::kWebKitSansSerifFontFamilyMap,
2042 &web_prefs->sans_serif_font_family_map);
2043 FontFamilyCache::FillFontFamilyMap(profile,
2044 prefs::kWebKitCursiveFontFamilyMap,
2045 &web_prefs->cursive_font_family_map);
2046 FontFamilyCache::FillFontFamilyMap(profile,
2047 prefs::kWebKitFantasyFontFamilyMap,
2048 &web_prefs->fantasy_font_family_map);
2049 FontFamilyCache::FillFontFamilyMap(profile,
2050 prefs::kWebKitPictographFontFamilyMap,
2051 &web_prefs->pictograph_font_family_map);
2052 #endif
2054 web_prefs->default_font_size =
2055 prefs->GetInteger(prefs::kWebKitDefaultFontSize);
2056 web_prefs->default_fixed_font_size =
2057 prefs->GetInteger(prefs::kWebKitDefaultFixedFontSize);
2058 web_prefs->minimum_font_size =
2059 prefs->GetInteger(prefs::kWebKitMinimumFontSize);
2060 web_prefs->minimum_logical_font_size =
2061 prefs->GetInteger(prefs::kWebKitMinimumLogicalFontSize);
2063 web_prefs->default_encoding = prefs->GetString(prefs::kDefaultCharset);
2065 web_prefs->javascript_can_open_windows_automatically =
2066 prefs->GetBoolean(prefs::kWebKitJavascriptCanOpenWindowsAutomatically);
2067 web_prefs->dom_paste_enabled =
2068 prefs->GetBoolean(prefs::kWebKitDomPasteEnabled);
2069 web_prefs->tabs_to_links = prefs->GetBoolean(prefs::kWebkitTabsToLinks);
2071 if (!prefs->GetBoolean(prefs::kWebKitJavascriptEnabled))
2072 web_prefs->javascript_enabled = false;
2073 if (!prefs->GetBoolean(prefs::kWebKitWebSecurityEnabled))
2074 web_prefs->web_security_enabled = false;
2075 if (!prefs->GetBoolean(prefs::kWebKitPluginsEnabled))
2076 web_prefs->plugins_enabled = false;
2077 if (!prefs->GetBoolean(prefs::kWebKitJavaEnabled))
2078 web_prefs->java_enabled = false;
2079 web_prefs->loads_images_automatically =
2080 prefs->GetBoolean(prefs::kWebKitLoadsImagesAutomatically);
2082 if (prefs->GetBoolean(prefs::kDisable3DAPIs))
2083 web_prefs->experimental_webgl_enabled = false;
2085 web_prefs->allow_displaying_insecure_content =
2086 prefs->GetBoolean(prefs::kWebKitAllowDisplayingInsecureContent);
2087 web_prefs->allow_running_insecure_content =
2088 prefs->GetBoolean(prefs::kWebKitAllowRunningInsecureContent);
2089 #if defined(OS_ANDROID)
2090 web_prefs->font_scale_factor =
2091 static_cast<float>(prefs->GetDouble(prefs::kWebKitFontScaleFactor));
2092 web_prefs->device_scale_adjustment = GetDeviceScaleAdjustment();
2093 web_prefs->force_enable_zoom =
2094 prefs->GetBoolean(prefs::kWebKitForceEnableZoom);
2095 #endif
2097 #if defined(OS_ANDROID)
2098 web_prefs->password_echo_enabled =
2099 prefs->GetBoolean(prefs::kWebKitPasswordEchoEnabled);
2100 #else
2101 web_prefs->password_echo_enabled = browser_defaults::kPasswordEchoEnabled;
2102 #endif
2104 web_prefs->asynchronous_spell_checking_enabled = true;
2105 web_prefs->unified_textchecker_enabled = true;
2107 web_prefs->uses_universal_detector =
2108 prefs->GetBoolean(prefs::kWebKitUsesUniversalDetector);
2109 web_prefs->text_areas_are_resizable =
2110 prefs->GetBoolean(prefs::kWebKitTextAreasAreResizable);
2111 web_prefs->hyperlink_auditing_enabled =
2112 prefs->GetBoolean(prefs::kEnableHyperlinkAuditing);
2114 #if defined(ENABLE_EXTENSIONS)
2115 std::string image_animation_policy =
2116 prefs->GetString(prefs::kAnimationPolicy);
2117 if (image_animation_policy == kAnimationPolicyOnce)
2118 web_prefs->animation_policy =
2119 content::IMAGE_ANIMATION_POLICY_ANIMATION_ONCE;
2120 else if (image_animation_policy == kAnimationPolicyNone)
2121 web_prefs->animation_policy = content::IMAGE_ANIMATION_POLICY_NO_ANIMATION;
2122 else
2123 web_prefs->animation_policy = content::IMAGE_ANIMATION_POLICY_ALLOWED;
2124 #endif
2126 // Make sure we will set the default_encoding with canonical encoding name.
2127 web_prefs->default_encoding =
2128 CharacterEncoding::GetCanonicalEncodingNameByAliasName(
2129 web_prefs->default_encoding);
2130 if (web_prefs->default_encoding.empty()) {
2131 prefs->ClearPref(prefs::kDefaultCharset);
2132 web_prefs->default_encoding = prefs->GetString(prefs::kDefaultCharset);
2134 DCHECK(!web_prefs->default_encoding.empty());
2136 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2137 switches::kEnablePotentiallyAnnoyingSecurityFeatures)) {
2138 web_prefs->disable_reading_from_canvas = true;
2139 web_prefs->strict_mixed_content_checking = true;
2140 web_prefs->strict_powerful_feature_restrictions = true;
2143 for (size_t i = 0; i < extra_parts_.size(); ++i)
2144 extra_parts_[i]->OverrideWebkitPrefs(rvh, web_prefs);
2147 void ChromeContentBrowserClient::BrowserURLHandlerCreated(
2148 BrowserURLHandler* handler) {
2149 for (size_t i = 0; i < extra_parts_.size(); ++i)
2150 extra_parts_[i]->BrowserURLHandlerCreated(handler);
2152 // about: handler. Must come before chrome: handler, since it will
2153 // rewrite about: urls to chrome: URLs and then expect chrome: to
2154 // actually handle them. Also relies on a preliminary fixup phase.
2155 handler->SetFixupHandler(&FixupBrowserAboutURL);
2156 handler->AddHandlerPair(&WillHandleBrowserAboutURL,
2157 BrowserURLHandler::null_handler());
2159 #if defined(OS_ANDROID)
2160 // Handler to rewrite chrome://newtab on Android.
2161 handler->AddHandlerPair(&chrome::android::HandleAndroidNativePageURL,
2162 BrowserURLHandler::null_handler());
2163 #else
2164 // Handler to rewrite chrome://newtab for InstantExtended.
2165 handler->AddHandlerPair(&chrome::HandleNewTabURLRewrite,
2166 &chrome::HandleNewTabURLReverseRewrite);
2167 #endif
2169 // chrome: & friends.
2170 handler->AddHandlerPair(&HandleWebUI, &HandleWebUIReverse);
2173 void ChromeContentBrowserClient::ClearCache(RenderFrameHost* rfh) {
2174 Profile* profile = Profile::FromBrowserContext(
2175 rfh->GetSiteInstance()->GetProcess()->GetBrowserContext());
2176 BrowsingDataRemover* remover =
2177 BrowsingDataRemover::CreateForUnboundedRange(profile);
2178 remover->Remove(BrowsingDataRemover::REMOVE_CACHE,
2179 BrowsingDataHelper::UNPROTECTED_WEB);
2180 // BrowsingDataRemover takes care of deleting itself when done.
2183 void ChromeContentBrowserClient::ClearCookies(RenderFrameHost* rfh) {
2184 Profile* profile = Profile::FromBrowserContext(
2185 rfh->GetSiteInstance()->GetProcess()->GetBrowserContext());
2186 BrowsingDataRemover* remover =
2187 BrowsingDataRemover::CreateForUnboundedRange(profile);
2188 int remove_mask = BrowsingDataRemover::REMOVE_SITE_DATA;
2189 remover->Remove(remove_mask, BrowsingDataHelper::UNPROTECTED_WEB);
2190 // BrowsingDataRemover takes care of deleting itself when done.
2193 base::FilePath ChromeContentBrowserClient::GetDefaultDownloadDirectory() {
2194 return DownloadPrefs::GetDefaultDownloadDirectory();
2197 std::string ChromeContentBrowserClient::GetDefaultDownloadName() {
2198 return l10n_util::GetStringUTF8(IDS_DEFAULT_DOWNLOAD_FILENAME);
2201 void ChromeContentBrowserClient::DidCreatePpapiPlugin(
2202 content::BrowserPpapiHost* browser_host) {
2203 #if defined(ENABLE_PLUGINS)
2204 ChromeContentBrowserClientPluginsPart::DidCreatePpapiPlugin(browser_host);
2205 #endif
2208 content::BrowserPpapiHost*
2209 ChromeContentBrowserClient::GetExternalBrowserPpapiHost(
2210 int plugin_process_id) {
2211 #if !defined(DISABLE_NACL)
2212 content::BrowserChildProcessHostIterator iter(PROCESS_TYPE_NACL_LOADER);
2213 while (!iter.Done()) {
2214 nacl::NaClProcessHost* host = static_cast<nacl::NaClProcessHost*>(
2215 iter.GetDelegate());
2216 if (host->process() &&
2217 host->process()->GetData().id == plugin_process_id) {
2218 // Found the plugin.
2219 return host->browser_ppapi_host();
2221 ++iter;
2223 #endif
2224 return NULL;
2227 bool ChromeContentBrowserClient::AllowPepperSocketAPI(
2228 content::BrowserContext* browser_context,
2229 const GURL& url,
2230 bool private_api,
2231 const content::SocketPermissionRequest* params) {
2232 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
2233 return ChromeContentBrowserClientPluginsPart::AllowPepperSocketAPI(
2234 browser_context, url, private_api, params, allowed_socket_origins_);
2235 #else
2236 return false;
2237 #endif
2240 ui::SelectFilePolicy* ChromeContentBrowserClient::CreateSelectFilePolicy(
2241 WebContents* web_contents) {
2242 return new ChromeSelectFilePolicy(web_contents);
2245 void ChromeContentBrowserClient::GetAdditionalAllowedSchemesForFileSystem(
2246 std::vector<std::string>* additional_allowed_schemes) {
2247 ContentBrowserClient::GetAdditionalAllowedSchemesForFileSystem(
2248 additional_allowed_schemes);
2249 additional_allowed_schemes->push_back(content::kChromeDevToolsScheme);
2250 additional_allowed_schemes->push_back(content::kChromeUIScheme);
2251 for (size_t i = 0; i < extra_parts_.size(); ++i) {
2252 extra_parts_[i]->GetAdditionalAllowedSchemesForFileSystem(
2253 additional_allowed_schemes);
2257 void ChromeContentBrowserClient::GetURLRequestAutoMountHandlers(
2258 std::vector<storage::URLRequestAutoMountHandler>* handlers) {
2259 for (size_t i = 0; i < extra_parts_.size(); ++i)
2260 extra_parts_[i]->GetURLRequestAutoMountHandlers(handlers);
2263 void ChromeContentBrowserClient::GetAdditionalFileSystemBackends(
2264 content::BrowserContext* browser_context,
2265 const base::FilePath& storage_partition_path,
2266 ScopedVector<storage::FileSystemBackend>* additional_backends) {
2267 #if defined(OS_CHROMEOS)
2268 storage::ExternalMountPoints* external_mount_points =
2269 content::BrowserContext::GetMountPoints(browser_context);
2270 DCHECK(external_mount_points);
2271 chromeos::FileSystemBackend* backend = new chromeos::FileSystemBackend(
2272 new drive::FileSystemBackendDelegate,
2273 new chromeos::file_system_provider::BackendDelegate,
2274 new chromeos::MTPFileSystemBackendDelegate(storage_partition_path),
2275 external_mount_points,
2276 storage::ExternalMountPoints::GetSystemInstance());
2277 backend->AddSystemMountPoints();
2278 DCHECK(backend->CanHandleType(storage::kFileSystemTypeExternal));
2279 additional_backends->push_back(backend);
2280 #endif
2282 for (size_t i = 0; i < extra_parts_.size(); ++i) {
2283 extra_parts_[i]->GetAdditionalFileSystemBackends(
2284 browser_context, storage_partition_path, additional_backends);
2288 #if defined(OS_ANDROID)
2289 void ChromeContentBrowserClient::GetAdditionalMappedFilesForChildProcess(
2290 const base::CommandLine& command_line,
2291 int child_process_id,
2292 FileDescriptorInfo* mappings,
2293 std::map<int, base::MemoryMappedFile::Region>* regions) {
2294 int fd = ui::GetMainAndroidPackFd(
2295 &(*regions)[kAndroidUIResourcesPakDescriptor]);
2296 mappings->Share(kAndroidUIResourcesPakDescriptor, fd);
2298 fd = ui::GetCommonResourcesPackFd(
2299 &(*regions)[kAndroidChrome100PercentPakDescriptor]);
2300 mappings->Share(kAndroidChrome100PercentPakDescriptor, fd);
2302 fd = ui::GetLocalePackFd(&(*regions)[kAndroidLocalePakDescriptor]);
2303 mappings->Share(kAndroidLocalePakDescriptor, fd);
2305 if (breakpad::IsCrashReporterEnabled()) {
2306 base::File file =
2307 breakpad::CrashDumpManager::GetInstance()->CreateMinidumpFile(
2308 child_process_id);
2309 if (file.IsValid()) {
2310 mappings->Transfer(kAndroidMinidumpDescriptor,
2311 base::ScopedFD(file.TakePlatformFile()));
2312 } else {
2313 LOG(ERROR) << "Failed to create file for minidump, crash reporting will "
2314 "be disabled for this process.";
2318 base::FilePath app_data_path;
2319 PathService::Get(base::DIR_ANDROID_APP_DATA, &app_data_path);
2320 DCHECK(!app_data_path.empty());
2322 #elif defined(OS_POSIX) && !defined(OS_MACOSX)
2323 void ChromeContentBrowserClient::GetAdditionalMappedFilesForChildProcess(
2324 const base::CommandLine& command_line,
2325 int child_process_id,
2326 FileDescriptorInfo* mappings) {
2327 int crash_signal_fd = GetCrashSignalFD(command_line);
2328 if (crash_signal_fd >= 0) {
2329 mappings->Share(kCrashDumpSignal, crash_signal_fd);
2332 #endif // defined(OS_ANDROID)
2334 #if defined(OS_WIN)
2335 const wchar_t* ChromeContentBrowserClient::GetResourceDllName() {
2336 return chrome::kBrowserResourcesDll;
2339 base::string16 ChromeContentBrowserClient::GetAppContainerSidForSandboxType(
2340 int sandbox_type) const {
2341 base::string16 sid;
2343 #if defined(GOOGLE_CHROME_BUILD)
2344 const chrome::VersionInfo::Channel channel =
2345 chrome::VersionInfo::GetChannel();
2347 // It's possible to have a SxS installation running at the same time as a
2348 // non-SxS so isolate them from each other.
2349 if (channel == chrome::VersionInfo::CHANNEL_CANARY) {
2350 sid.assign(
2351 L"S-1-15-2-3251537155-1984446955-2931258699-841473695-1938553385-"
2352 L"924012150-");
2353 } else {
2354 sid.assign(
2355 L"S-1-15-2-3251537155-1984446955-2931258699-841473695-1938553385-"
2356 L"924012149-");
2358 #else
2359 sid.assign(
2360 L"S-1-15-2-3251537155-1984446955-2931258699-841473695-1938553385-"
2361 L"924012148-");
2362 #endif
2364 // TODO(wfh): Add support for more process types here. crbug.com/499523
2365 switch (sandbox_type) {
2366 case content::SANDBOX_TYPE_RENDERER:
2367 return sid + L"129201922";
2368 case content::SANDBOX_TYPE_UTILITY:
2369 return base::string16();
2370 case content::SANDBOX_TYPE_GPU:
2371 return base::string16();
2372 case content::SANDBOX_TYPE_PPAPI:
2373 return base::string16();
2374 #if !defined(DISABLE_NACL)
2375 case PROCESS_TYPE_NACL_LOADER:
2376 return base::string16();
2377 case PROCESS_TYPE_NACL_BROKER:
2378 return base::string16();
2379 #endif
2382 // Should never reach here.
2383 CHECK(0);
2384 return base::string16();
2387 void ChromeContentBrowserClient::PreSpawnRenderer(
2388 sandbox::TargetPolicy* policy,
2389 bool* success) {
2390 // This code is duplicated in nacl_exe_win_64.cc.
2391 // Allow the server side of a pipe restricted to the "chrome.nacl."
2392 // namespace so that it cannot impersonate other system or other chrome
2393 // service pipes.
2394 sandbox::ResultCode result = policy->AddRule(
2395 sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
2396 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
2397 L"\\\\.\\pipe\\chrome.nacl.*");
2398 if (result != sandbox::SBOX_ALL_OK) {
2399 *success = false;
2400 return;
2403 // Renderers need to send named pipe handles and shared memory
2404 // segment handles to NaCl loader processes.
2405 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
2406 sandbox::TargetPolicy::HANDLES_DUP_ANY,
2407 L"File");
2408 if (result != sandbox::SBOX_ALL_OK) {
2409 *success = false;
2410 return;
2413 #endif
2415 void ChromeContentBrowserClient::RegisterFrameMojoShellServices(
2416 content::ServiceRegistry* registry,
2417 content::RenderFrameHost* render_frame_host) {
2418 #if defined(OS_CHROMEOS)
2419 registry->AddService(
2420 base::Bind(&chromeos::attestation::PlatformVerificationImpl::Create,
2421 render_frame_host));
2422 #endif
2425 void ChromeContentBrowserClient::RegisterInProcessMojoApplications(
2426 StaticMojoApplicationMap* apps) {
2427 #if !defined(OS_ANDROID) && !defined(OS_IOS)
2428 apps->insert(std::make_pair(GURL(device::kDevicesMojoAppUrl),
2429 base::Bind(&device::DevicesAppFactory::CreateApp,
2430 base::ThreadTaskRunnerHandle::Get())));
2431 #endif
2434 void ChromeContentBrowserClient::OpenURL(
2435 content::BrowserContext* browser_context,
2436 const content::OpenURLParams& params,
2437 const base::Callback<void(content::WebContents*)>& callback) {
2438 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2440 #if !defined(OS_ANDROID) && !defined(OS_IOS)
2441 NavigateParams nav_params(Profile::FromBrowserContext(browser_context),
2442 params.url,
2443 params.transition);
2444 FillNavigateParamsFromOpenURLParams(&nav_params, params);
2445 nav_params.user_gesture = params.user_gesture;
2447 Navigate(&nav_params);
2448 callback.Run(nav_params.target_contents);
2449 #elif defined(OS_ANDROID)
2450 service_tab_launcher::ServiceTabLauncher::GetInstance()->LaunchTab(
2451 browser_context, params, callback);
2452 #else
2453 NOTIMPLEMENTED();
2454 #endif
2457 content::PresentationServiceDelegate*
2458 ChromeContentBrowserClient::GetPresentationServiceDelegate(
2459 content::WebContents* web_contents) {
2460 #if defined(ENABLE_MEDIA_ROUTER)
2461 if (switches::MediaRouterEnabled()) {
2462 return media_router::PresentationServiceDelegateImpl::
2463 GetOrCreateForWebContents(web_contents);
2465 #endif
2466 return nullptr;
2469 void ChromeContentBrowserClient::RecordURLMetric(const std::string& metric,
2470 const GURL& url) {
2471 if (url.is_valid()) {
2472 rappor::SampleDomainAndRegistryFromGURL(g_browser_process->rappor_service(),
2473 metric, url);
2477 content::DevToolsManagerDelegate*
2478 ChromeContentBrowserClient::GetDevToolsManagerDelegate() {
2479 return new ChromeDevToolsManagerDelegate();
2482 content::TracingDelegate* ChromeContentBrowserClient::GetTracingDelegate() {
2483 #if !defined(OS_ANDROID)
2484 return new ChromeTracingDelegate();
2485 #else
2486 return nullptr;
2487 #endif
2490 bool ChromeContentBrowserClient::IsPluginAllowedToCallRequestOSFileHandle(
2491 content::BrowserContext* browser_context,
2492 const GURL& url) {
2493 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
2494 return ChromeContentBrowserClientPluginsPart::
2495 IsPluginAllowedToCallRequestOSFileHandle(browser_context, url,
2496 allowed_file_handle_origins_);
2497 #else
2498 return false;
2499 #endif
2502 bool ChromeContentBrowserClient::IsPluginAllowedToUseDevChannelAPIs(
2503 content::BrowserContext* browser_context,
2504 const GURL& url) {
2505 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
2506 return ChromeContentBrowserClientPluginsPart::
2507 IsPluginAllowedToUseDevChannelAPIs(browser_context, url,
2508 allowed_dev_channel_origins_);
2509 #else
2510 return false;
2511 #endif
2514 void ChromeContentBrowserClient::OverridePageVisibilityState(
2515 RenderFrameHost* render_frame_host,
2516 blink::WebPageVisibilityState* visibility_state) {
2517 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
2519 WebContents* web_contents =
2520 WebContents::FromRenderFrameHost(render_frame_host);
2521 DCHECK(web_contents);
2523 Profile* profile =
2524 Profile::FromBrowserContext(web_contents->GetBrowserContext());
2525 prerender::PrerenderManager* prerender_manager =
2526 prerender::PrerenderManagerFactory::GetForProfile(profile);
2527 if (prerender_manager &&
2528 prerender_manager->IsWebContentsPrerendering(web_contents, nullptr)) {
2529 *visibility_state = blink::WebPageVisibilityStatePrerender;
2533 #if defined(ENABLE_WEBRTC)
2534 void ChromeContentBrowserClient::MaybeCopyDisableWebRtcEncryptionSwitch(
2535 base::CommandLine* to_command_line,
2536 const base::CommandLine& from_command_line,
2537 VersionInfo::Channel channel) {
2538 #if defined(OS_ANDROID)
2539 const VersionInfo::Channel kMaxDisableEncryptionChannel =
2540 VersionInfo::CHANNEL_BETA;
2541 #else
2542 const VersionInfo::Channel kMaxDisableEncryptionChannel =
2543 VersionInfo::CHANNEL_DEV;
2544 #endif
2545 if (channel <= kMaxDisableEncryptionChannel) {
2546 static const char* const kWebRtcDevSwitchNames[] = {
2547 switches::kDisableWebRtcEncryption,
2549 to_command_line->CopySwitchesFrom(from_command_line,
2550 kWebRtcDevSwitchNames,
2551 arraysize(kWebRtcDevSwitchNames));
2554 #endif // defined(ENABLE_WEBRTC)
2556 } // namespace chrome