Componentize HistoryURLProvider/ScoredHistoryMatch.
[chromium-blink-merge.git] / chrome / browser / chrome_content_browser_client.cc
blob6bc3356d6f16f517fdecba44e20a990208d14948
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/chrome_content_browser_client.h"
7 #include <set>
8 #include <utility>
9 #include <vector>
11 #include "base/bind.h"
12 #include "base/bind_helpers.h"
13 #include "base/command_line.h"
14 #include "base/files/scoped_file.h"
15 #include "base/i18n/icu_util.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/utf_string_conversions.h"
22 #include "base/thread_task_runner_handle.h"
23 #include "base/threading/sequenced_worker_pool.h"
24 #include "chrome/browser/after_startup_task_utils.h"
25 #include "chrome/browser/browser_about_handler.h"
26 #include "chrome/browser/browser_process.h"
27 #include "chrome/browser/browser_shutdown.h"
28 #include "chrome/browser/browsing_data/browsing_data_helper.h"
29 #include "chrome/browser/browsing_data/browsing_data_remover.h"
30 #include "chrome/browser/character_encoding.h"
31 #include "chrome/browser/chrome_content_browser_client_parts.h"
32 #include "chrome/browser/chrome_net_benchmarking_message_filter.h"
33 #include "chrome/browser/chrome_quota_permission_context.h"
34 #include "chrome/browser/content_settings/cookie_settings.h"
35 #include "chrome/browser/content_settings/tab_specific_content_settings.h"
36 #include "chrome/browser/defaults.h"
37 #include "chrome/browser/devtools/chrome_devtools_manager_delegate.h"
38 #include "chrome/browser/download/download_prefs.h"
39 #include "chrome/browser/font_family_cache.h"
40 #include "chrome/browser/geolocation/chrome_access_token_store.h"
41 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
42 #include "chrome/browser/metrics/chrome_browser_main_extra_parts_metrics.h"
43 #include "chrome/browser/nacl_host/nacl_browser_delegate_impl.h"
44 #include "chrome/browser/net/chrome_net_log.h"
45 #include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings.h"
46 #include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings_factory.h"
47 #include "chrome/browser/notifications/platform_notification_service_impl.h"
48 #include "chrome/browser/platform_util.h"
49 #include "chrome/browser/prerender/prerender_final_status.h"
50 #include "chrome/browser/prerender/prerender_manager.h"
51 #include "chrome/browser/prerender/prerender_manager_factory.h"
52 #include "chrome/browser/prerender/prerender_message_filter.h"
53 #include "chrome/browser/printing/printing_message_filter.h"
54 #include "chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.h"
55 #include "chrome/browser/profiles/profile.h"
56 #include "chrome/browser/profiles/profile_io_data.h"
57 #include "chrome/browser/renderer_host/chrome_render_message_filter.h"
58 #include "chrome/browser/renderer_host/pepper/chrome_browser_pepper_host_factory.h"
59 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
60 #include "chrome/browser/safe_browsing/ui_manager.h"
61 #include "chrome/browser/search/instant_service.h"
62 #include "chrome/browser/search/instant_service_factory.h"
63 #include "chrome/browser/search/search.h"
64 #include "chrome/browser/search_engines/search_provider_install_state_message_filter.h"
65 #include "chrome/browser/speech/chrome_speech_recognition_manager_delegate.h"
66 #include "chrome/browser/speech/tts_controller.h"
67 #include "chrome/browser/speech/tts_message_filter.h"
68 #include "chrome/browser/ssl/ssl_add_certificate.h"
69 #include "chrome/browser/ssl/ssl_blocking_page.h"
70 #include "chrome/browser/ssl/ssl_cert_reporter.h"
71 #include "chrome/browser/ssl/ssl_client_certificate_selector.h"
72 #include "chrome/browser/ssl/ssl_error_handler.h"
73 #include "chrome/browser/sync_file_system/local/sync_file_system_backend.h"
74 #include "chrome/browser/tab_contents/tab_util.h"
75 #include "chrome/browser/tracing/chrome_tracing_delegate.h"
76 #include "chrome/browser/ui/blocked_content/blocked_window_params.h"
77 #include "chrome/browser/ui/blocked_content/popup_blocker_tab_helper.h"
78 #include "chrome/browser/ui/chrome_select_file_policy.h"
79 #include "chrome/browser/ui/sync/sync_promo_ui.h"
80 #include "chrome/browser/ui/tab_contents/chrome_web_contents_view_delegate.h"
81 #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
82 #include "chrome/common/chrome_constants.h"
83 #include "chrome/common/chrome_paths.h"
84 #include "chrome/common/chrome_switches.h"
85 #include "chrome/common/env_vars.h"
86 #include "chrome/common/logging_chrome.h"
87 #include "chrome/common/pepper_permission_util.h"
88 #include "chrome/common/pref_names.h"
89 #include "chrome/common/render_messages.h"
90 #include "chrome/common/url_constants.h"
91 #include "chrome/grit/generated_resources.h"
92 #include "chrome/installer/util/google_update_settings.h"
93 #include "chromeos/chromeos_constants.h"
94 #include "components/cdm/browser/cdm_message_filter_android.h"
95 #include "components/cloud_devices/common/cloud_devices_switches.h"
96 #include "components/content_settings/core/browser/content_settings_utils.h"
97 #include "components/content_settings/core/browser/host_content_settings_map.h"
98 #include "components/content_settings/core/common/content_settings.h"
99 #include "components/data_reduction_proxy/content/browser/data_reduction_proxy_message_filter.h"
100 #include "components/dom_distiller/core/url_constants.h"
101 #include "components/google/core/browser/google_util.h"
102 #include "components/metrics/client_info.h"
103 #include "components/pref_registry/pref_registry_syncable.h"
104 #include "components/rappor/rappor_utils.h"
105 #include "components/signin/core/common/profile_management_switches.h"
106 #include "components/translate/core/common/translate_switches.h"
107 #include "components/url_fixer/url_fixer.h"
108 #include "content/public/browser/browser_child_process_host.h"
109 #include "content/public/browser/browser_main_parts.h"
110 #include "content/public/browser/browser_ppapi_host.h"
111 #include "content/public/browser/browser_thread.h"
112 #include "content/public/browser/browser_url_handler.h"
113 #include "content/public/browser/child_process_data.h"
114 #include "content/public/browser/child_process_security_policy.h"
115 #include "content/public/browser/client_certificate_delegate.h"
116 #include "content/public/browser/render_frame_host.h"
117 #include "content/public/browser/render_process_host.h"
118 #include "content/public/browser/render_view_host.h"
119 #include "content/public/browser/resource_context.h"
120 #include "content/public/browser/site_instance.h"
121 #include "content/public/browser/web_contents.h"
122 #include "content/public/common/child_process_host.h"
123 #include "content/public/common/content_descriptors.h"
124 #include "content/public/common/service_registry.h"
125 #include "content/public/common/url_utils.h"
126 #include "content/public/common/web_preferences.h"
127 #include "device/devices_app/devices_app.h"
128 #include "gin/v8_initializer.h"
129 #include "net/base/mime_util.h"
130 #include "net/cookies/canonical_cookie.h"
131 #include "net/cookies/cookie_options.h"
132 #include "net/ssl/ssl_cert_request_info.h"
133 #include "ppapi/host/ppapi_host.h"
134 #include "storage/browser/fileapi/external_mount_points.h"
135 #include "ui/base/l10n/l10n_util.h"
136 #include "ui/base/resource/resource_bundle.h"
137 #include "ui/resources/grit/ui_resources.h"
139 #if defined(OS_WIN)
140 #include "base/win/windows_version.h"
141 #include "chrome/browser/chrome_browser_main_win.h"
142 #include "sandbox/win/src/sandbox_policy.h"
143 #elif defined(OS_MACOSX)
144 #include "chrome/browser/chrome_browser_main_mac.h"
145 #include "chrome/browser/spellchecker/spellcheck_message_filter_mac.h"
146 #elif defined(OS_CHROMEOS)
147 #include "chrome/browser/chromeos/attestation/platform_verification_impl.h"
148 #include "chrome/browser/chromeos/chrome_browser_main_chromeos.h"
149 #include "chrome/browser/chromeos/drive/fileapi/file_system_backend_delegate.h"
150 #include "chrome/browser/chromeos/file_manager/app_id.h"
151 #include "chrome/browser/chromeos/file_system_provider/fileapi/backend_delegate.h"
152 #include "chrome/browser/chromeos/fileapi/file_system_backend.h"
153 #include "chrome/browser/chromeos/fileapi/mtp_file_system_backend_delegate.h"
154 #include "chrome/browser/chromeos/login/startup_utils.h"
155 #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
156 #include "chrome/browser/chromeos/system/input_device_settings.h"
157 #include "chromeos/chromeos_switches.h"
158 #include "components/user_manager/user_manager.h"
159 #elif defined(OS_LINUX)
160 #include "chrome/browser/chrome_browser_main_linux.h"
161 #elif defined(OS_ANDROID)
162 #include "chrome/browser/android/new_tab_page_url_handler.h"
163 #include "chrome/browser/android/webapps/single_tab_mode_tab_helper.h"
164 #include "chrome/browser/chrome_browser_main_android.h"
165 #include "chrome/common/descriptors_android.h"
166 #include "components/crash/browser/crash_dump_manager_android.h"
167 #include "components/service_tab_launcher/browser/android/service_tab_launcher.h"
168 #elif defined(OS_POSIX)
169 #include "chrome/browser/chrome_browser_main_posix.h"
170 #endif
172 #if defined(OS_POSIX) && !defined(OS_MACOSX)
173 #include "base/debug/leak_annotations.h"
174 #include "components/crash/app/breakpad_linux.h"
175 #include "components/crash/browser/crash_handler_host_linux.h"
176 #endif
178 #if defined(OS_ANDROID)
179 #include "ui/base/ui_base_paths.h"
180 #include "ui/gfx/android/device_display_info.h"
181 #endif
183 #if defined(TOOLKIT_VIEWS)
184 #include "chrome/browser/ui/views/chrome_browser_main_extra_parts_views.h"
185 #endif
187 #if defined(USE_ASH)
188 #include "chrome/browser/ui/views/ash/chrome_browser_main_extra_parts_ash.h"
189 #endif
191 #if defined(USE_AURA)
192 #include "chrome/browser/ui/aura/chrome_browser_main_extra_parts_aura.h"
193 #endif
195 #if defined(USE_X11)
196 #include "chrome/browser/chrome_browser_main_extra_parts_x11.h"
197 #endif
199 #if defined(ENABLE_CAPTIVE_PORTAL_DETECTION)
200 #include "chrome/browser/captive_portal/captive_portal_tab_helper.h"
201 #endif
203 #if !defined(DISABLE_NACL)
204 #include "components/nacl/browser/nacl_browser.h"
205 #include "components/nacl/browser/nacl_host_message_filter.h"
206 #include "components/nacl/browser/nacl_process_host.h"
207 #include "components/nacl/common/nacl_process_type.h"
208 #include "components/nacl/common/nacl_switches.h"
209 #endif
211 #if defined(ENABLE_EXTENSIONS)
212 #include "chrome/browser/accessibility/animation_policy_prefs.h"
213 #include "chrome/browser/extensions/chrome_content_browser_client_extensions_part.h"
214 #include "chrome/browser/extensions/extension_util.h"
215 #include "chrome/browser/media/cast_transport_host_filter.h"
216 #include "chrome/browser/speech/extension_api/tts_engine_extension_api.h"
217 #include "components/guest_view/browser/guest_view_base.h"
218 #include "components/guest_view/browser/guest_view_manager.h"
219 #include "extensions/browser/extension_registry.h"
220 #include "extensions/browser/guest_view/web_view/web_view_guest.h"
221 #include "extensions/browser/guest_view/web_view/web_view_permission_helper.h"
222 #include "extensions/browser/guest_view/web_view/web_view_renderer_state.h"
223 #include "extensions/common/constants.h"
224 #include "extensions/common/extension.h"
225 #include "extensions/common/extension_set.h"
226 #include "extensions/common/manifest_handlers/background_info.h"
227 #include "extensions/common/manifest_handlers/shared_module_info.h"
228 #include "extensions/common/permissions/permissions_data.h"
229 #include "extensions/common/permissions/socket_permission.h"
230 #include "extensions/common/switches.h"
231 #endif
233 #if defined(ENABLE_PLUGINS)
234 #include "chrome/browser/plugins/chrome_content_browser_client_plugins_part.h"
235 #endif
237 #if defined(ENABLE_SPELLCHECK)
238 #include "chrome/browser/spellchecker/spellcheck_message_filter.h"
239 #endif
241 #if defined(ENABLE_WEBRTC)
242 #include "chrome/browser/media/webrtc_logging_handler_host.h"
243 #endif
245 #if defined(ENABLE_MEDIA_ROUTER)
246 #include "chrome/browser/media/router/presentation_service_delegate_impl.h"
247 #endif
249 using base::FileDescriptor;
250 using blink::WebWindowFeatures;
251 using content::AccessTokenStore;
252 using content::BrowserThread;
253 using content::BrowserURLHandler;
254 using content::ChildProcessSecurityPolicy;
255 using content::QuotaPermissionContext;
256 using content::RenderFrameHost;
257 using content::RenderViewHost;
258 using content::ResourceType;
259 using content::SiteInstance;
260 using content::WebContents;
261 using content::WebPreferences;
262 using message_center::NotifierId;
264 #if defined(OS_POSIX)
265 using content::FileDescriptorInfo;
266 #endif
268 #if defined(ENABLE_EXTENSIONS)
269 using extensions::APIPermission;
270 using extensions::ChromeContentBrowserClientExtensionsPart;
271 using extensions::Extension;
272 using extensions::InfoMap;
273 using extensions::Manifest;
274 #endif
276 #if defined(ENABLE_PLUGINS)
277 using plugins::ChromeContentBrowserClientPluginsPart;
278 #endif
280 namespace {
282 // Cached version of the locale so we can return the locale on the I/O
283 // thread.
284 base::LazyInstance<std::string> g_io_thread_application_locale;
286 #if defined(ENABLE_PLUGINS)
287 // TODO(teravest): Add renderer-side API-specific checking for these APIs so
288 // that blanket permission isn't granted to all dev channel APIs for these.
289 // http://crbug.com/386743
290 const char* const kPredefinedAllowedDevChannelOrigins[] = {
291 "6EAED1924DB611B6EEF2A664BD077BE7EAD33B8F", // see crbug.com/383937
292 "4EB74897CB187C7633357C2FE832E0AD6A44883A" // see crbug.com/383937
295 const char* const kPredefinedAllowedFileHandleOrigins[] = {
296 "6EAED1924DB611B6EEF2A664BD077BE7EAD33B8F", // see crbug.com/234789
297 "4EB74897CB187C7633357C2FE832E0AD6A44883A" // see crbug.com/234789
300 const char* const kPredefinedAllowedSocketOrigins[] = {
301 "okddffdblfhhnmhodogpojmfkjmhinfp", // Test SSH Client
302 "pnhechapfaindjhompbnflcldabbghjo", // HTerm App (SSH Client)
303 "bglhmjfplikpjnfoegeomebmfnkjomhe", // see crbug.com/122126
304 "gbchcmhmhahfdphkhkmpfmihenigjmpp", // Chrome Remote Desktop
305 "kgngmbheleoaphbjbaiobfdepmghbfah", // Pre-release Chrome Remote Desktop
306 "odkaodonbgfohohmklejpjiejmcipmib", // Dogfood Chrome Remote Desktop
307 "ojoimpklfciegopdfgeenehpalipignm", // Chromoting canary
308 "cbkkbcmdlboombapidmoeolnmdacpkch", // see crbug.com/129089
309 "hhnbmknkdabfoieppbbljkhkfjcmcbjh", // see crbug.com/134099
310 "mablfbjkhmhkmefkjjacnbaikjkipphg", // see crbug.com/134099
311 "pdeelgamlgannhelgoegilelnnojegoh", // see crbug.com/134099
312 "cabapfdbkniadpollkckdnedaanlciaj", // see crbug.com/134099
313 "mapljbgnjledlpdmlchihnmeclmefbba", // see crbug.com/134099
314 "ghbfeebgmiidnnmeobbbaiamklmpbpii", // see crbug.com/134099
315 "jdfhpkjeckflbbleddjlpimecpbjdeep", // see crbug.com/142514
316 "iabmpiboiopbgfabjmgeedhcmjenhbla", // see crbug.com/165080
317 "B7CF8A292249681AF81771650BA4CEEAF19A4560", // see crbug.com/165080
318 "7525AF4F66763A70A883C4700529F647B470E4D2", // see crbug.com/238084
319 "0B549507088E1564D672F7942EB87CA4DAD73972", // see crbug.com/238084
320 "864288364E239573E777D3E0E36864E590E95C74" // see crbug.com/238084
322 #endif
324 // Returns a copy of the given url with its host set to given host and path set
325 // to given path. Other parts of the url will be the same.
326 GURL ReplaceURLHostAndPath(const GURL& url,
327 const std::string& host,
328 const std::string& path) {
329 url::Replacements<char> replacements;
330 replacements.SetHost(host.c_str(), url::Component(0, host.length()));
331 replacements.SetPath(path.c_str(), url::Component(0, path.length()));
332 return url.ReplaceComponents(replacements);
335 // Maps "foo://bar/baz/" to "foo://chrome/bar/baz/".
336 GURL AddUberHost(const GURL& url) {
337 const std::string uber_host = chrome::kChromeUIUberHost;
338 const std::string new_path = url.host() + url.path();
340 return ReplaceURLHostAndPath(url, uber_host, new_path);
343 // If url->host() is "chrome" and url->path() has characters other than the
344 // first slash, changes the url from "foo://chrome/bar/" to "foo://bar/" and
345 // returns true. Otherwise returns false.
346 bool RemoveUberHost(GURL* url) {
347 if (url->host() != chrome::kChromeUIUberHost)
348 return false;
350 if (url->path().empty() || url->path() == "/")
351 return false;
353 const std::string old_path = url->path();
355 const std::string::size_type separator = old_path.find('/', 1);
356 std::string new_host;
357 std::string new_path;
358 if (separator == std::string::npos) {
359 new_host = old_path.substr(1);
360 } else {
361 new_host = old_path.substr(1, separator - 1);
362 new_path = old_path.substr(separator);
365 // Do not allow URLs with paths empty before the first slash since we can't
366 // have an empty host. (e.g "foo://chrome//")
367 if (new_host.empty())
368 return false;
370 *url = ReplaceURLHostAndPath(*url, new_host, new_path);
372 DCHECK(url->is_valid());
374 return true;
377 // Handles rewriting Web UI URLs.
378 bool HandleWebUI(GURL* url, content::BrowserContext* browser_context) {
379 // Do not handle special URLs such as "about:foo"
380 if (!url->host().empty()) {
381 const GURL chrome_url = AddUberHost(*url);
383 // Handle valid "chrome://chrome/foo" URLs so the reverse handler will
384 // be called.
385 if (ChromeWebUIControllerFactory::GetInstance()->UseWebUIForURL(
386 browser_context, chrome_url))
387 return true;
390 if (!ChromeWebUIControllerFactory::GetInstance()->UseWebUIForURL(
391 browser_context, *url))
392 return false;
394 #if defined(OS_CHROMEOS)
395 // Special case : in ChromeOS in Guest mode bookmarks and history are
396 // disabled for security reasons. New tab page explains the reasons, so
397 // we redirect user to new tab page.
398 if (user_manager::UserManager::Get()->IsLoggedInAsGuest()) {
399 if (url->SchemeIs(content::kChromeUIScheme) &&
400 (url->DomainIs(chrome::kChromeUIBookmarksHost) ||
401 url->DomainIs(chrome::kChromeUIHistoryHost))) {
402 // Rewrite with new tab URL
403 *url = GURL(chrome::kChromeUINewTabURL);
406 #endif
408 return true;
411 // Reverse URL handler for Web UI. Maps "chrome://chrome/foo/" to
412 // "chrome://foo/".
413 bool HandleWebUIReverse(GURL* url, content::BrowserContext* browser_context) {
414 if (!url->is_valid() || !url->SchemeIs(content::kChromeUIScheme))
415 return false;
417 return RemoveUberHost(url);
420 bool CertMatchesFilter(const net::X509Certificate& cert,
421 const base::DictionaryValue& filter) {
422 // TODO(markusheintz): This is the minimal required filter implementation.
423 // Implement a better matcher.
425 // An empty filter matches any client certificate since no requirements are
426 // specified at all.
427 if (filter.empty())
428 return true;
430 std::string common_name;
431 if (filter.GetString("ISSUER.CN", &common_name) &&
432 (cert.issuer().common_name == common_name)) {
433 return true;
435 return false;
438 #if defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_MACOSX)
439 breakpad::CrashHandlerHostLinux* CreateCrashHandlerHost(
440 const std::string& process_type) {
441 base::FilePath dumps_path;
442 PathService::Get(chrome::DIR_CRASH_DUMPS, &dumps_path);
444 ANNOTATE_SCOPED_MEMORY_LEAK;
445 bool upload = (getenv(env_vars::kHeadless) == NULL);
446 breakpad::CrashHandlerHostLinux* crash_handler =
447 new breakpad::CrashHandlerHostLinux(process_type, dumps_path, upload);
448 crash_handler->StartUploaderThread();
449 return crash_handler;
453 int GetCrashSignalFD(const base::CommandLine& command_line) {
454 // Extensions have the same process type as renderers.
455 if (command_line.HasSwitch(extensions::switches::kExtensionProcess)) {
456 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
457 if (!crash_handler)
458 crash_handler = CreateCrashHandlerHost("extension");
459 return crash_handler->GetDeathSignalSocket();
462 std::string process_type =
463 command_line.GetSwitchValueASCII(switches::kProcessType);
465 if (process_type == switches::kRendererProcess) {
466 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
467 if (!crash_handler)
468 crash_handler = CreateCrashHandlerHost(process_type);
469 return crash_handler->GetDeathSignalSocket();
472 if (process_type == switches::kPluginProcess) {
473 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
474 if (!crash_handler)
475 crash_handler = CreateCrashHandlerHost(process_type);
476 return crash_handler->GetDeathSignalSocket();
479 if (process_type == switches::kPpapiPluginProcess) {
480 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
481 if (!crash_handler)
482 crash_handler = CreateCrashHandlerHost(process_type);
483 return crash_handler->GetDeathSignalSocket();
486 if (process_type == switches::kGpuProcess) {
487 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
488 if (!crash_handler)
489 crash_handler = CreateCrashHandlerHost(process_type);
490 return crash_handler->GetDeathSignalSocket();
493 return -1;
495 #endif // defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_MACOSX)
497 void SetApplicationLocaleOnIOThread(const std::string& locale) {
498 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
499 g_io_thread_application_locale.Get() = locale;
502 void HandleBlockedPopupOnUIThread(const BlockedWindowParams& params) {
503 RenderFrameHost* render_frame_host = RenderFrameHost::FromID(
504 params.render_process_id(), params.opener_render_frame_id());
505 if (!render_frame_host)
506 return;
507 WebContents* tab = WebContents::FromRenderFrameHost(render_frame_host);
508 // The tab might already have navigated away. We only need to do this check
509 // for main frames, since the RenderFrameHost for a subframe opener will have
510 // already been deleted if the main frame navigates away.
511 if (!tab ||
512 (!render_frame_host->GetParent() &&
513 tab->GetMainFrame() != render_frame_host))
514 return;
516 prerender::PrerenderContents* prerender_contents =
517 prerender::PrerenderContents::FromWebContents(tab);
518 if (prerender_contents) {
519 prerender_contents->Destroy(prerender::FINAL_STATUS_CREATE_NEW_WINDOW);
520 return;
523 PopupBlockerTabHelper* popup_helper =
524 PopupBlockerTabHelper::FromWebContents(tab);
525 if (!popup_helper)
526 return;
527 popup_helper->AddBlockedPopup(params);
530 // An implementation of the SSLCertReporter interface used by
531 // SSLErrorHandler. Uses the SafeBrowsing UI manager to send invalid
532 // certificate reports.
533 class SafeBrowsingSSLCertReporter : public SSLCertReporter {
534 public:
535 explicit SafeBrowsingSSLCertReporter(
536 const scoped_refptr<SafeBrowsingUIManager>& safe_browsing_ui_manager)
537 : safe_browsing_ui_manager_(safe_browsing_ui_manager) {}
538 ~SafeBrowsingSSLCertReporter() override {}
540 // SSLCertReporter implementation
541 void ReportInvalidCertificateChain(
542 const std::string& serialized_report) override {
543 if (safe_browsing_ui_manager_) {
544 safe_browsing_ui_manager_->ReportInvalidCertificateChain(
545 serialized_report, base::Bind(&base::DoNothing));
549 private:
550 const scoped_refptr<SafeBrowsingUIManager> safe_browsing_ui_manager_;
553 #if defined(OS_ANDROID)
555 void HandleSingleTabModeBlockOnUIThread(const BlockedWindowParams& params) {
556 WebContents* web_contents = tab_util::GetWebContentsByFrameID(
557 params.render_process_id(), params.opener_render_frame_id());
558 if (!web_contents)
559 return;
561 SingleTabModeTabHelper::FromWebContents(web_contents)->HandleOpenUrl(params);
564 float GetDeviceScaleAdjustment() {
565 static const float kMinFSM = 1.05f;
566 static const int kWidthForMinFSM = 320;
567 static const float kMaxFSM = 1.3f;
568 static const int kWidthForMaxFSM = 800;
570 gfx::DeviceDisplayInfo info;
571 int minWidth = info.GetSmallestDIPWidth();
573 if (minWidth <= kWidthForMinFSM)
574 return kMinFSM;
575 if (minWidth >= kWidthForMaxFSM)
576 return kMaxFSM;
578 // The font scale multiplier varies linearly between kMinFSM and kMaxFSM.
579 float ratio = static_cast<float>(minWidth - kWidthForMinFSM) /
580 (kWidthForMaxFSM - kWidthForMinFSM);
581 return ratio * (kMaxFSM - kMinFSM) + kMinFSM;
584 #endif // defined(OS_ANDROID)
586 #if defined(ENABLE_EXTENSIONS)
587 // By default, JavaScript and images are enabled in guest content.
588 void GetGuestViewDefaultContentSettingRules(
589 bool incognito,
590 RendererContentSettingRules* rules) {
591 rules->image_rules.push_back(
592 ContentSettingPatternSource(ContentSettingsPattern::Wildcard(),
593 ContentSettingsPattern::Wildcard(),
594 CONTENT_SETTING_ALLOW,
595 std::string(),
596 incognito));
598 rules->script_rules.push_back(
599 ContentSettingPatternSource(ContentSettingsPattern::Wildcard(),
600 ContentSettingsPattern::Wildcard(),
601 CONTENT_SETTING_ALLOW,
602 std::string(),
603 incognito));
605 #endif // defined(ENABLE_EXTENSIONS)
607 } // namespace
609 namespace chrome {
611 ChromeContentBrowserClient::ChromeContentBrowserClient()
613 #if defined(OS_POSIX) && !defined(OS_MACOSX)
614 v8_natives_fd_(-1),
615 v8_snapshot_fd_(-1),
616 #endif // OS_POSIX && !OS_MACOSX
617 weak_factory_(this) {
618 #if defined(ENABLE_PLUGINS)
619 for (size_t i = 0; i < arraysize(kPredefinedAllowedDevChannelOrigins); ++i)
620 allowed_dev_channel_origins_.insert(kPredefinedAllowedDevChannelOrigins[i]);
621 for (size_t i = 0; i < arraysize(kPredefinedAllowedFileHandleOrigins); ++i)
622 allowed_file_handle_origins_.insert(kPredefinedAllowedFileHandleOrigins[i]);
623 for (size_t i = 0; i < arraysize(kPredefinedAllowedSocketOrigins); ++i)
624 allowed_socket_origins_.insert(kPredefinedAllowedSocketOrigins[i]);
626 extra_parts_.push_back(new ChromeContentBrowserClientPluginsPart);
627 #endif
629 #if !defined(OS_ANDROID)
630 TtsExtensionEngine* tts_extension_engine = TtsExtensionEngine::GetInstance();
631 TtsController::GetInstance()->SetTtsEngineDelegate(tts_extension_engine);
632 #endif
634 #if defined(ENABLE_EXTENSIONS)
635 extra_parts_.push_back(new ChromeContentBrowserClientExtensionsPart);
636 #endif
639 ChromeContentBrowserClient::~ChromeContentBrowserClient() {
640 for (int i = static_cast<int>(extra_parts_.size()) - 1; i >= 0; --i)
641 delete extra_parts_[i];
642 extra_parts_.clear();
645 // static
646 void ChromeContentBrowserClient::RegisterProfilePrefs(
647 user_prefs::PrefRegistrySyncable* registry) {
648 registry->RegisterBooleanPref(prefs::kDisable3DAPIs, false);
649 registry->RegisterBooleanPref(prefs::kEnableHyperlinkAuditing, true);
650 registry->RegisterListPref(prefs::kEnableDeprecatedWebPlatformFeatures);
653 // static
654 void ChromeContentBrowserClient::SetApplicationLocale(
655 const std::string& locale) {
656 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
658 // This object is guaranteed to outlive all threads so we don't have to
659 // worry about the lack of refcounting and can just post as Unretained.
661 // The common case is that this function is called early in Chrome startup
662 // before any threads are created (it will also be called later if the user
663 // changes the pref). In this case, there will be no threads created and
664 // posting will fail. When there are no threads, we can just set the string
665 // without worrying about threadsafety.
666 if (!BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
667 base::Bind(&SetApplicationLocaleOnIOThread, locale))) {
668 g_io_thread_application_locale.Get() = locale;
672 content::BrowserMainParts* ChromeContentBrowserClient::CreateBrowserMainParts(
673 const content::MainFunctionParams& parameters) {
674 ChromeBrowserMainParts* main_parts;
675 // Construct the Main browser parts based on the OS type.
676 #if defined(OS_WIN)
677 main_parts = new ChromeBrowserMainPartsWin(parameters);
678 #elif defined(OS_MACOSX)
679 main_parts = new ChromeBrowserMainPartsMac(parameters);
680 #elif defined(OS_CHROMEOS)
681 main_parts = new chromeos::ChromeBrowserMainPartsChromeos(parameters);
682 #elif defined(OS_LINUX)
683 main_parts = new ChromeBrowserMainPartsLinux(parameters);
684 #elif defined(OS_ANDROID)
685 main_parts = new ChromeBrowserMainPartsAndroid(parameters);
686 #elif defined(OS_POSIX)
687 main_parts = new ChromeBrowserMainPartsPosix(parameters);
688 #else
689 NOTREACHED();
690 main_parts = new ChromeBrowserMainParts(parameters);
691 #endif
693 chrome::AddProfilesExtraParts(main_parts);
695 // Construct additional browser parts. Stages are called in the order in
696 // which they are added.
697 #if defined(TOOLKIT_VIEWS)
698 main_parts->AddParts(new ChromeBrowserMainExtraPartsViews());
699 #endif
701 // TODO(oshima): Athena on chrome currently requires USE_ASH to build.
702 // We should reduce the dependency as much as possible.
703 #if defined(USE_ASH)
704 main_parts->AddParts(new ChromeBrowserMainExtraPartsAsh());
705 #endif
707 #if defined(USE_AURA)
708 main_parts->AddParts(new ChromeBrowserMainExtraPartsAura());
709 #endif
711 #if defined(USE_X11)
712 main_parts->AddParts(new ChromeBrowserMainExtraPartsX11());
713 #endif
715 chrome::AddMetricsExtraParts(main_parts);
717 return main_parts;
720 void ChromeContentBrowserClient::PostAfterStartupTask(
721 const tracked_objects::Location& from_here,
722 const scoped_refptr<base::TaskRunner>& task_runner,
723 const base::Closure& task) {
724 AfterStartupTaskUtils::PostTask(from_here, task_runner, task);
727 std::string ChromeContentBrowserClient::GetStoragePartitionIdForSite(
728 content::BrowserContext* browser_context,
729 const GURL& site) {
730 std::string partition_id;
732 // The partition ID for webview guest processes is the string value of its
733 // SiteInstance URL - "chrome-guest://app_id/persist?partition".
734 if (site.SchemeIs(content::kGuestScheme)) {
735 partition_id = site.spec();
736 } else if (!switches::IsEnableWebviewBasedSignin() &&
737 site.GetOrigin().spec() == kChromeUIChromeSigninURL) {
738 // The non-webview Chrome signin page has an embedded iframe of extension
739 // and web content, thus it must be isolated from other webUI pages.
740 partition_id = site.GetOrigin().spec();
743 DCHECK(IsValidStoragePartitionId(browser_context, partition_id));
744 return partition_id;
747 bool ChromeContentBrowserClient::IsValidStoragePartitionId(
748 content::BrowserContext* browser_context,
749 const std::string& partition_id) {
750 // The default ID is empty and is always valid.
751 if (partition_id.empty())
752 return true;
754 return GURL(partition_id).is_valid();
757 void ChromeContentBrowserClient::GetStoragePartitionConfigForSite(
758 content::BrowserContext* browser_context,
759 const GURL& site,
760 bool can_be_default,
761 std::string* partition_domain,
762 std::string* partition_name,
763 bool* in_memory) {
764 // Default to the browser-wide storage partition and override based on |site|
765 // below.
766 partition_domain->clear();
767 partition_name->clear();
768 *in_memory = false;
770 bool success = false;
771 #if defined(ENABLE_EXTENSIONS)
772 success = extensions::WebViewGuest::GetGuestPartitionConfigForSite(
773 site, partition_domain, partition_name, in_memory);
775 if (!success && site.SchemeIs(extensions::kExtensionScheme)) {
776 // If |can_be_default| is false, the caller is stating that the |site|
777 // should be parsed as if it had isolated storage. In particular it is
778 // important to NOT check ExtensionService for the is_storage_isolated()
779 // attribute because this code path is run during Extension uninstall
780 // to do cleanup after the Extension has already been unloaded from the
781 // ExtensionService.
782 bool is_isolated = !can_be_default;
783 if (can_be_default) {
784 if (extensions::util::SiteHasIsolatedStorage(site, browser_context))
785 is_isolated = true;
788 if (is_isolated) {
789 CHECK(site.has_host());
790 // For extensions with isolated storage, the the host of the |site| is
791 // the |partition_domain|. The |in_memory| and |partition_name| are only
792 // used in guest schemes so they are cleared here.
793 *partition_domain = site.host();
794 *in_memory = false;
795 partition_name->clear();
797 success = true;
799 #endif
801 if (!success && (!switches::IsEnableWebviewBasedSignin() &&
802 site.GetOrigin().spec() == kChromeUIChromeSigninURL)) {
803 // The non-webview Chrome signin page has an embedded iframe of extension
804 // and web content, thus it must be isolated from other webUI pages.
805 *partition_domain = chrome::kChromeUIChromeSigninHost;
808 // Assert that if |can_be_default| is false, the code above must have found a
809 // non-default partition. If this fails, the caller has a serious logic
810 // error about which StoragePartition they expect to be in and it is not
811 // safe to continue.
812 CHECK(can_be_default || !partition_domain->empty());
815 content::WebContentsViewDelegate*
816 ChromeContentBrowserClient::GetWebContentsViewDelegate(
817 content::WebContents* web_contents) {
818 return chrome::CreateWebContentsViewDelegate(web_contents);
821 void ChromeContentBrowserClient::RenderProcessWillLaunch(
822 content::RenderProcessHost* host) {
823 int id = host->GetID();
824 Profile* profile = Profile::FromBrowserContext(host->GetBrowserContext());
825 net::URLRequestContextGetter* context =
826 profile->GetRequestContextForRenderProcess(id);
828 host->AddFilter(new ChromeRenderMessageFilter(id, profile));
829 #if defined(ENABLE_EXTENSIONS)
830 host->AddFilter(new cast::CastTransportHostFilter);
831 #endif
832 #if defined(ENABLE_PRINTING)
833 host->AddFilter(new printing::PrintingMessageFilter(id, profile));
834 #endif
835 host->AddFilter(new SearchProviderInstallStateMessageFilter(id, profile));
836 #if defined(ENABLE_SPELLCHECK)
837 host->AddFilter(new SpellCheckMessageFilter(id));
838 #endif
839 #if defined(OS_MACOSX)
840 host->AddFilter(new SpellCheckMessageFilterMac(id));
841 #endif
842 host->AddFilter(new ChromeNetBenchmarkingMessageFilter(profile, context));
843 host->AddFilter(new prerender::PrerenderMessageFilter(id, profile));
844 host->AddFilter(new TtsMessageFilter(host->GetBrowserContext()));
845 #if defined(ENABLE_WEBRTC)
846 WebRtcLoggingHandlerHost* webrtc_logging_handler_host =
847 new WebRtcLoggingHandlerHost(profile);
848 host->SetWebRtcLogMessageCallback(base::Bind(
849 &WebRtcLoggingHandlerHost::LogMessage, webrtc_logging_handler_host));
850 host->AddFilter(webrtc_logging_handler_host);
851 host->SetUserData(host, new base::UserDataAdapter<WebRtcLoggingHandlerHost>(
852 webrtc_logging_handler_host));
853 #endif
854 #if !defined(DISABLE_NACL)
855 host->AddFilter(new nacl::NaClHostMessageFilter(
856 id, profile->IsOffTheRecord(),
857 profile->GetPath(),
858 context));
859 #endif
860 #if defined(OS_ANDROID)
861 host->AddFilter(new cdm::CdmMessageFilterAndroid());
862 #endif
863 DataReductionProxyChromeSettings* data_reduction_proxy_settings =
864 DataReductionProxyChromeSettingsFactory::GetForBrowserContext(profile);
865 host->AddFilter(new data_reduction_proxy::DataReductionProxyMessageFilter(
866 data_reduction_proxy_settings));
868 host->Send(new ChromeViewMsg_SetIsIncognitoProcess(
869 profile->IsOffTheRecord()));
871 for (size_t i = 0; i < extra_parts_.size(); ++i)
872 extra_parts_[i]->RenderProcessWillLaunch(host);
874 RendererContentSettingRules rules;
875 if (host->IsForGuestsOnly()) {
876 #if defined(ENABLE_EXTENSIONS)
877 GetGuestViewDefaultContentSettingRules(profile->IsOffTheRecord(), &rules);
878 #else
879 NOTREACHED();
880 #endif
881 } else {
882 GetRendererContentSettingRules(
883 profile->GetHostContentSettingsMap(), &rules);
885 host->Send(new ChromeViewMsg_SetContentSettingRules(rules));
888 GURL ChromeContentBrowserClient::GetEffectiveURL(
889 content::BrowserContext* browser_context, const GURL& url) {
890 Profile* profile = Profile::FromBrowserContext(browser_context);
891 if (!profile)
892 return url;
894 // If the input |url| should be assigned to the Instant renderer, make its
895 // effective URL distinct from other URLs on the search provider's domain.
896 if (chrome::ShouldAssignURLToInstantRenderer(url, profile))
897 return chrome::GetEffectiveURLForInstant(url, profile);
899 #if defined(ENABLE_EXTENSIONS)
900 return ChromeContentBrowserClientExtensionsPart::GetEffectiveURL(
901 profile, url);
902 #else
903 return url;
904 #endif
907 bool ChromeContentBrowserClient::ShouldUseProcessPerSite(
908 content::BrowserContext* browser_context, const GURL& effective_url) {
909 // Non-extension, non-Instant URLs should generally use
910 // process-per-site-instance. Because we expect to use the effective URL,
911 // URLs for hosted apps (apart from bookmark apps) should have an extension
912 // scheme by now.
914 Profile* profile = Profile::FromBrowserContext(browser_context);
915 if (!profile)
916 return false;
918 if (chrome::ShouldUseProcessPerSiteForInstantURL(effective_url, profile))
919 return true;
921 #if defined(ENABLE_EXTENSIONS)
922 return ChromeContentBrowserClientExtensionsPart::ShouldUseProcessPerSite(
923 profile, effective_url);
924 #else
925 return false;
926 #endif
929 // These are treated as WebUI schemes but do not get WebUI bindings. Also,
930 // view-source is allowed for these schemes.
931 void ChromeContentBrowserClient::GetAdditionalWebUISchemes(
932 std::vector<std::string>* additional_schemes) {
933 additional_schemes->push_back(chrome::kChromeSearchScheme);
934 additional_schemes->push_back(dom_distiller::kDomDistillerScheme);
937 void ChromeContentBrowserClient::GetAdditionalWebUIHostsToIgnoreParititionCheck(
938 std::vector<std::string>* hosts) {
939 hosts->push_back(chrome::kChromeUIExtensionIconHost);
940 hosts->push_back(chrome::kChromeUIFaviconHost);
941 hosts->push_back(chrome::kChromeUIThemeHost);
942 hosts->push_back(chrome::kChromeUIThumbnailHost);
943 hosts->push_back(chrome::kChromeUIThumbnailHost2);
944 hosts->push_back(chrome::kChromeUIThumbnailListHost);
947 net::URLRequestContextGetter*
948 ChromeContentBrowserClient::CreateRequestContext(
949 content::BrowserContext* browser_context,
950 content::ProtocolHandlerMap* protocol_handlers,
951 content::URLRequestInterceptorScopedVector request_interceptors) {
952 Profile* profile = Profile::FromBrowserContext(browser_context);
953 return profile->CreateRequestContext(protocol_handlers,
954 request_interceptors.Pass());
957 net::URLRequestContextGetter*
958 ChromeContentBrowserClient::CreateRequestContextForStoragePartition(
959 content::BrowserContext* browser_context,
960 const base::FilePath& partition_path,
961 bool in_memory,
962 content::ProtocolHandlerMap* protocol_handlers,
963 content::URLRequestInterceptorScopedVector request_interceptors) {
964 Profile* profile = Profile::FromBrowserContext(browser_context);
965 return profile->CreateRequestContextForStoragePartition(
966 partition_path,
967 in_memory,
968 protocol_handlers,
969 request_interceptors.Pass());
972 bool ChromeContentBrowserClient::IsHandledURL(const GURL& url) {
973 return ProfileIOData::IsHandledURL(url);
976 bool ChromeContentBrowserClient::CanCommitURL(
977 content::RenderProcessHost* process_host,
978 const GURL& url) {
979 #if defined(ENABLE_EXTENSIONS)
980 return ChromeContentBrowserClientExtensionsPart::CanCommitURL(
981 process_host, url);
982 #else
983 return true;
984 #endif
987 bool ChromeContentBrowserClient::ShouldAllowOpenURL(
988 content::SiteInstance* site_instance, const GURL& url) {
989 GURL from_url = site_instance->GetSiteURL();
991 #if defined(ENABLE_EXTENSIONS)
992 bool result;
993 if (ChromeContentBrowserClientExtensionsPart::ShouldAllowOpenURL(
994 site_instance, from_url, url, &result))
995 return result;
996 #endif
998 // Do not allow chrome://chrome-signin navigate to other chrome:// URLs, since
999 // the signin page may host untrusted web content.
1000 if (from_url.GetOrigin().spec() == chrome::kChromeUIChromeSigninURL &&
1001 url.SchemeIs(content::kChromeUIScheme) &&
1002 url.host() != chrome::kChromeUIChromeSigninHost) {
1003 VLOG(1) << "Blocked navigation to " << url.spec() << " from "
1004 << chrome::kChromeUIChromeSigninURL;
1005 return false;
1008 return true;
1011 bool ChromeContentBrowserClient::IsSuitableHost(
1012 content::RenderProcessHost* process_host,
1013 const GURL& site_url) {
1014 Profile* profile =
1015 Profile::FromBrowserContext(process_host->GetBrowserContext());
1016 // This may be NULL during tests. In that case, just assume any site can
1017 // share any host.
1018 if (!profile)
1019 return true;
1021 // Instant URLs should only be in the instant process and instant process
1022 // should only have Instant URLs.
1023 InstantService* instant_service =
1024 InstantServiceFactory::GetForProfile(profile);
1025 if (instant_service) {
1026 bool is_instant_process = instant_service->IsInstantProcess(
1027 process_host->GetID());
1028 bool should_be_in_instant_process =
1029 chrome::ShouldAssignURLToInstantRenderer(site_url, profile);
1030 if (is_instant_process || should_be_in_instant_process)
1031 return is_instant_process && should_be_in_instant_process;
1034 #if defined(ENABLE_EXTENSIONS)
1035 return ChromeContentBrowserClientExtensionsPart::IsSuitableHost(
1036 profile, process_host, site_url);
1037 #else
1038 return true;
1039 #endif
1042 bool ChromeContentBrowserClient::MayReuseHost(
1043 content::RenderProcessHost* process_host) {
1044 // If there is currently a prerender in progress for the host provided,
1045 // it may not be shared. We require prerenders to be by themselves in a
1046 // separate process so that we can monitor their resource usage.
1047 Profile* profile = Profile::FromBrowserContext(
1048 process_host->GetBrowserContext());
1049 prerender::PrerenderManager* prerender_manager =
1050 prerender::PrerenderManagerFactory::GetForProfile(profile);
1051 if (prerender_manager &&
1052 !prerender_manager->MayReuseProcessHost(process_host)) {
1053 return false;
1056 return true;
1059 bool ChromeContentBrowserClient::ShouldTryToUseExistingProcessHost(
1060 content::BrowserContext* browser_context, const GURL& url) {
1061 // It has to be a valid URL for us to check for an extension.
1062 if (!url.is_valid())
1063 return false;
1065 #if defined(ENABLE_EXTENSIONS)
1066 Profile* profile = Profile::FromBrowserContext(browser_context);
1067 return ChromeContentBrowserClientExtensionsPart::
1068 ShouldTryToUseExistingProcessHost(
1069 profile, url);
1070 #else
1071 return false;
1072 #endif
1075 void ChromeContentBrowserClient::SiteInstanceGotProcess(
1076 SiteInstance* site_instance) {
1077 CHECK(site_instance->HasProcess());
1079 Profile* profile = Profile::FromBrowserContext(
1080 site_instance->GetBrowserContext());
1081 if (!profile)
1082 return;
1084 // Remember the ID of the Instant process to signal the renderer process
1085 // on startup in |AppendExtraCommandLineSwitches| below.
1086 if (chrome::ShouldAssignURLToInstantRenderer(
1087 site_instance->GetSiteURL(), profile)) {
1088 InstantService* instant_service =
1089 InstantServiceFactory::GetForProfile(profile);
1090 if (instant_service)
1091 instant_service->AddInstantProcess(site_instance->GetProcess()->GetID());
1094 for (size_t i = 0; i < extra_parts_.size(); ++i)
1095 extra_parts_[i]->SiteInstanceGotProcess(site_instance);
1098 void ChromeContentBrowserClient::SiteInstanceDeleting(
1099 SiteInstance* site_instance) {
1100 if (!site_instance->HasProcess())
1101 return;
1103 for (size_t i = 0; i < extra_parts_.size(); ++i)
1104 extra_parts_[i]->SiteInstanceDeleting(site_instance);
1107 bool ChromeContentBrowserClient::ShouldSwapBrowsingInstancesForNavigation(
1108 SiteInstance* site_instance,
1109 const GURL& current_url,
1110 const GURL& new_url) {
1111 #if defined(ENABLE_EXTENSIONS)
1112 return ChromeContentBrowserClientExtensionsPart::
1113 ShouldSwapBrowsingInstancesForNavigation(
1114 site_instance, current_url, new_url);
1115 #else
1116 return false;
1117 #endif
1120 bool ChromeContentBrowserClient::ShouldSwapProcessesForRedirect(
1121 content::ResourceContext* resource_context, const GURL& current_url,
1122 const GURL& new_url) {
1123 #if defined(ENABLE_EXTENSIONS)
1124 return ChromeContentBrowserClientExtensionsPart::
1125 ShouldSwapProcessesForRedirect(resource_context, current_url, new_url);
1126 #else
1127 return false;
1128 #endif
1131 bool ChromeContentBrowserClient::ShouldAssignSiteForURL(const GURL& url) {
1132 return !url.SchemeIs(chrome::kChromeNativeScheme);
1135 std::string ChromeContentBrowserClient::GetCanonicalEncodingNameByAliasName(
1136 const std::string& alias_name) {
1137 return CharacterEncoding::GetCanonicalEncodingNameByAliasName(alias_name);
1140 namespace {
1142 bool IsAutoReloadEnabled() {
1143 // Fetch the field trial, even though we don't use it. Calling FindFullName()
1144 // causes the field-trial mechanism to report which group we're in, which
1145 // might reflect a hard disable or hard enable via flag, both of which have
1146 // their own field trial groups. This lets us know what percentage of users
1147 // manually enable or disable auto-reload.
1148 std::string group = base::FieldTrialList::FindFullName(
1149 "AutoReloadExperiment");
1150 const base::CommandLine& browser_command_line =
1151 *base::CommandLine::ForCurrentProcess();
1152 if (browser_command_line.HasSwitch(switches::kEnableOfflineAutoReload))
1153 return true;
1154 if (browser_command_line.HasSwitch(switches::kDisableOfflineAutoReload))
1155 return false;
1156 return true;
1159 bool IsAutoReloadVisibleOnlyEnabled() {
1160 // See the block comment in IsAutoReloadEnabled().
1161 std::string group = base::FieldTrialList::FindFullName(
1162 "AutoReloadVisibleOnlyExperiment");
1163 const base::CommandLine& browser_command_line =
1164 *base::CommandLine::ForCurrentProcess();
1165 if (browser_command_line.HasSwitch(
1166 switches::kEnableOfflineAutoReloadVisibleOnly)) {
1167 return true;
1169 if (browser_command_line.HasSwitch(
1170 switches::kDisableOfflineAutoReloadVisibleOnly)) {
1171 return false;
1173 return true;
1176 } // namespace
1178 // When Chrome is updated on non-Windows platforms, the new files (like
1179 // V8 natives and snapshot) can have the same names as the previous
1180 // versions. Since the renderers for an existing Chrome browser process
1181 // are likely not compatible with the new files, the browser keeps hold
1182 // of the old files using an open fd. This fd is passed to subprocesses
1183 // like renderers. Here we add the flag to tell the subprocesses where
1184 // to find these file descriptors.
1185 void ChromeContentBrowserClient::AppendMappedFileCommandLineSwitches(
1186 base::CommandLine* command_line) {
1187 #if defined(OS_POSIX) && !defined(OS_MACOSX)
1188 #if defined(V8_USE_EXTERNAL_STARTUP_DATA)
1189 std::string process_type =
1190 command_line->GetSwitchValueASCII(switches::kProcessType);
1191 if (process_type != switches::kZygoteProcess) {
1192 // We want to pass the natives by fd because after an update the file may
1193 // be updated, but we want the newly launched renderers to get the old one,
1194 // opened by the browser when it started.
1195 DCHECK(natives_fd_exists());
1196 command_line->AppendSwitch(::switches::kV8NativesPassedByFD);
1197 if (snapshot_fd_exists())
1198 command_line->AppendSwitch(::switches::kV8SnapshotPassedByFD);
1200 #endif // V8_USE_EXTERNAL_STARTUP_DATA
1201 #endif // OS_POSIX && !OS_MACOSX
1204 void ChromeContentBrowserClient::AppendExtraCommandLineSwitches(
1205 base::CommandLine* command_line,
1206 int child_process_id) {
1207 #if defined(OS_MACOSX)
1208 scoped_ptr<metrics::ClientInfo> client_info =
1209 GoogleUpdateSettings::LoadMetricsClientInfo();
1210 if (client_info) {
1211 command_line->AppendSwitchASCII(switches::kMetricsClientID,
1212 client_info->client_id);
1214 #elif defined(OS_POSIX)
1215 if (breakpad::IsCrashReporterEnabled()) {
1216 scoped_ptr<metrics::ClientInfo> client_info =
1217 GoogleUpdateSettings::LoadMetricsClientInfo();
1218 command_line->AppendSwitchASCII(switches::kEnableCrashReporter,
1219 client_info ? client_info->client_id
1220 : std::string());
1222 #endif
1224 if (logging::DialogsAreSuppressed())
1225 command_line->AppendSwitch(switches::kNoErrorDialogs);
1227 std::string process_type =
1228 command_line->GetSwitchValueASCII(switches::kProcessType);
1229 const base::CommandLine& browser_command_line =
1230 *base::CommandLine::ForCurrentProcess();
1232 static const char* const kCommonSwitchNames[] = {
1233 switches::kUserAgent,
1234 switches::kUserDataDir, // Make logs go to the right file.
1236 command_line->CopySwitchesFrom(browser_command_line, kCommonSwitchNames,
1237 arraysize(kCommonSwitchNames));
1239 #if defined(ENABLE_IPC_FUZZER)
1240 static const char* const kIpcFuzzerSwitches[] = {
1241 switches::kIpcDumpDirectory,
1242 switches::kIpcFuzzerTestcase,
1244 command_line->CopySwitchesFrom(browser_command_line, kIpcFuzzerSwitches,
1245 arraysize(kIpcFuzzerSwitches));
1246 #endif
1248 #if defined(OS_CHROMEOS)
1249 static const char* const kChromeOSSwitches[] = {
1250 switches::kDisableDinosaurEasterEgg,
1252 command_line->CopySwitchesFrom(browser_command_line, kChromeOSSwitches,
1253 arraysize(kChromeOSSwitches));
1255 // On Chrome OS need to pass primary user homedir (in multi-profiles session).
1256 base::FilePath homedir;
1257 PathService::Get(base::DIR_HOME, &homedir);
1258 command_line->AppendSwitchASCII(chromeos::switches::kHomedir,
1259 homedir.value().c_str());
1260 #endif
1262 if (process_type == switches::kRendererProcess) {
1263 content::RenderProcessHost* process =
1264 content::RenderProcessHost::FromID(child_process_id);
1265 Profile* profile =
1266 process ? Profile::FromBrowserContext(process->GetBrowserContext())
1267 : NULL;
1268 for (size_t i = 0; i < extra_parts_.size(); ++i) {
1269 extra_parts_[i]->AppendExtraRendererCommandLineSwitches(
1270 command_line, process, profile);
1273 #if defined(OS_CHROMEOS)
1274 const std::string& login_profile =
1275 browser_command_line.GetSwitchValueASCII(
1276 chromeos::switches::kLoginProfile);
1277 if (!login_profile.empty())
1278 command_line->AppendSwitchASCII(
1279 chromeos::switches::kLoginProfile, login_profile);
1280 #endif
1282 #if defined(ENABLE_WEBRTC)
1283 MaybeCopyDisableWebRtcEncryptionSwitch(command_line,
1284 browser_command_line,
1285 VersionInfo::GetChannel());
1286 #endif
1288 if (process) {
1289 PrefService* prefs = profile->GetPrefs();
1290 // Currently this pref is only registered if applied via a policy.
1291 if (prefs->HasPrefPath(prefs::kDisable3DAPIs) &&
1292 prefs->GetBoolean(prefs::kDisable3DAPIs)) {
1293 // Turn this policy into a command line switch.
1294 command_line->AppendSwitch(switches::kDisable3DAPIs);
1297 const base::ListValue* switches =
1298 prefs->GetList(prefs::kEnableDeprecatedWebPlatformFeatures);
1299 if (switches) {
1300 // Enable any deprecated features that have been re-enabled by policy.
1301 for (base::ListValue::const_iterator it = switches->begin();
1302 it != switches->end(); ++it) {
1303 std::string switch_to_enable;
1304 if ((*it)->GetAsString(&switch_to_enable))
1305 command_line->AppendSwitch(switch_to_enable);
1309 // Disable client-side phishing detection in the renderer if it is
1310 // disabled in the Profile preferences or the browser process.
1311 if (!prefs->GetBoolean(prefs::kSafeBrowsingEnabled) ||
1312 !g_browser_process->safe_browsing_detection_service()) {
1313 command_line->AppendSwitch(
1314 switches::kDisableClientSidePhishingDetection);
1317 if (prefs->GetBoolean(prefs::kPrintPreviewDisabled))
1318 command_line->AppendSwitch(switches::kDisablePrintPreview);
1320 InstantService* instant_service =
1321 InstantServiceFactory::GetForProfile(profile);
1322 if (instant_service &&
1323 instant_service->IsInstantProcess(process->GetID()))
1324 command_line->AppendSwitch(switches::kInstantProcess);
1327 if (IsAutoReloadEnabled())
1328 command_line->AppendSwitch(switches::kEnableOfflineAutoReload);
1329 if (IsAutoReloadVisibleOnlyEnabled()) {
1330 command_line->AppendSwitch(
1331 switches::kEnableOfflineAutoReloadVisibleOnly);
1335 // Enable showing a saved copy if this session is in the field trial
1336 // or the user explicitly enabled it. Note that as far as the
1337 // renderer is concerned, the feature is enabled if-and-only-if
1338 // one of the kEnableShowSavedCopy* switches is on the command
1339 // line; the yes/no/default behavior is only at the browser
1340 // command line level.
1342 // Command line switches override
1343 const std::string& show_saved_copy_value =
1344 browser_command_line.GetSwitchValueASCII(switches::kShowSavedCopy);
1345 if (show_saved_copy_value == switches::kEnableShowSavedCopyPrimary ||
1346 show_saved_copy_value == switches::kEnableShowSavedCopySecondary ||
1347 show_saved_copy_value == switches::kDisableShowSavedCopy) {
1348 command_line->AppendSwitchASCII(switches::kShowSavedCopy,
1349 show_saved_copy_value);
1350 } else {
1351 std::string group =
1352 base::FieldTrialList::FindFullName("LoadStaleCacheExperiment");
1354 if (group == "Primary") {
1355 command_line->AppendSwitchASCII(
1356 switches::kShowSavedCopy, switches::kEnableShowSavedCopyPrimary);
1357 } else if (group == "Secondary") {
1358 command_line->AppendSwitchASCII(
1359 switches::kShowSavedCopy,
1360 switches::kEnableShowSavedCopySecondary);
1365 // Please keep this in alphabetical order.
1366 static const char* const kSwitchNames[] = {
1367 autofill::switches::kDisableFillOnAccountSelect,
1368 autofill::switches::kDisablePasswordGeneration,
1369 autofill::switches::kEnableAccessorySuggestionView,
1370 autofill::switches::kEnableFillOnAccountSelect,
1371 autofill::switches::kEnableFillOnAccountSelectNoHighlighting,
1372 autofill::switches::kEnablePasswordGeneration,
1373 autofill::switches::kEnableSingleClickAutofill,
1374 autofill::switches::kIgnoreAutocompleteOffForAutofill,
1375 autofill::switches::kLocalHeuristicsOnlyForPasswordGeneration,
1376 #if defined(ENABLE_EXTENSIONS)
1377 extensions::switches::kAllowHTTPBackgroundPage,
1378 extensions::switches::kAllowLegacyExtensionManifests,
1379 extensions::switches::kEnableSurfaceWorker,
1380 extensions::switches::kEnableAppWindowControls,
1381 extensions::switches::kEnableEmbeddedExtensionOptions,
1382 extensions::switches::kEnableExperimentalExtensionApis,
1383 extensions::switches::kExtensionsOnChromeURLs,
1384 extensions::switches::kWhitelistedExtensionID,
1385 #endif
1386 switches::kAllowInsecureLocalhost,
1387 switches::kAppsCheckoutURL,
1388 switches::kAppsGalleryURL,
1389 switches::kCloudPrintURL,
1390 switches::kCloudPrintXmppEndpoint,
1391 switches::kDisableBundledPpapiFlash,
1392 switches::kDisableCastStreamingHWEncoding,
1393 switches::kDisableJavaScriptHarmonyShipping,
1394 switches::kDisableNewBookmarkApps,
1395 switches::kEnableBenchmarking,
1396 switches::kEnableNaCl,
1397 #if !defined(DISABLE_NACL)
1398 switches::kEnableNaClDebug,
1399 switches::kEnableNaClNonSfiMode,
1400 switches::kEnablePNaClSubzero,
1401 #endif
1402 switches::kEnableNetBenchmarking,
1403 switches::kEnableNewBookmarkApps,
1404 switches::kEnablePluginPlaceholderShadowDom,
1405 switches::kJavaScriptHarmony,
1406 switches::kMessageLoopHistogrammer,
1407 switches::kPpapiFlashArgs,
1408 switches::kPpapiFlashPath,
1409 switches::kPpapiFlashVersion,
1410 switches::kProfilingAtStart,
1411 switches::kProfilingFile,
1412 switches::kProfilingFlush,
1413 switches::kUnsafelyTreatInsecureOriginAsSecure,
1414 translate::switches::kTranslateSecurityOrigin,
1417 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1418 arraysize(kSwitchNames));
1419 } else if (process_type == switches::kUtilityProcess) {
1420 #if defined(ENABLE_EXTENSIONS)
1421 static const char* const kSwitchNames[] = {
1422 extensions::switches::kAllowHTTPBackgroundPage,
1423 extensions::switches::kEnableExperimentalExtensionApis,
1424 extensions::switches::kExtensionsOnChromeURLs,
1425 extensions::switches::kWhitelistedExtensionID,
1428 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1429 arraysize(kSwitchNames));
1430 #endif
1431 } else if (process_type == switches::kPluginProcess) {
1432 #if defined(OS_CHROMEOS)
1433 static const char* const kSwitchNames[] = {
1434 chromeos::switches::kLoginProfile,
1437 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1438 arraysize(kSwitchNames));
1439 #endif
1440 } else if (process_type == switches::kZygoteProcess) {
1441 static const char* const kSwitchNames[] = {
1442 // Load (in-process) Pepper plugins in-process in the zygote pre-sandbox.
1443 switches::kDisableBundledPpapiFlash,
1444 #if !defined(DISABLE_NACL)
1445 switches::kEnableNaClDebug,
1446 switches::kEnableNaClNonSfiMode,
1447 switches::kEnablePNaClSubzero,
1448 switches::kNaClDangerousNoSandboxNonSfi,
1449 switches::kUseNaClHelperNonSfi,
1450 #endif
1451 switches::kPpapiFlashPath,
1452 switches::kPpapiFlashVersion,
1455 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1456 arraysize(kSwitchNames));
1457 } else if (process_type == switches::kGpuProcess) {
1458 // If --ignore-gpu-blacklist is passed in, don't send in crash reports
1459 // because GPU is expected to be unreliable.
1460 if (browser_command_line.HasSwitch(switches::kIgnoreGpuBlacklist) &&
1461 !command_line->HasSwitch(switches::kDisableBreakpad))
1462 command_line->AppendSwitch(switches::kDisableBreakpad);
1465 // The command line switch kEnableBenchmarking needs to be specified along
1466 // with the kEnableStatsTable switch to ensure that the stats table global
1467 // is initialized correctly.
1468 if (command_line->HasSwitch(switches::kEnableBenchmarking))
1469 DCHECK(command_line->HasSwitch(switches::kEnableStatsTable));
1472 std::string ChromeContentBrowserClient::GetApplicationLocale() {
1473 if (BrowserThread::CurrentlyOn(BrowserThread::IO))
1474 return g_io_thread_application_locale.Get();
1475 return g_browser_process->GetApplicationLocale();
1478 std::string ChromeContentBrowserClient::GetAcceptLangs(
1479 content::BrowserContext* context) {
1480 Profile* profile = Profile::FromBrowserContext(context);
1481 return profile->GetPrefs()->GetString(prefs::kAcceptLanguages);
1484 const gfx::ImageSkia* ChromeContentBrowserClient::GetDefaultFavicon() {
1485 ResourceBundle& rb = ResourceBundle::GetSharedInstance();
1486 return rb.GetNativeImageNamed(IDR_DEFAULT_FAVICON).ToImageSkia();
1489 bool ChromeContentBrowserClient::AllowAppCache(
1490 const GURL& manifest_url,
1491 const GURL& first_party,
1492 content::ResourceContext* context) {
1493 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1494 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1495 return io_data->GetCookieSettings()->
1496 IsSettingCookieAllowed(manifest_url, first_party);
1499 bool ChromeContentBrowserClient::AllowServiceWorker(
1500 const GURL& scope,
1501 const GURL& first_party_url,
1502 content::ResourceContext* context,
1503 int render_process_id,
1504 int render_frame_id) {
1505 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1506 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1507 bool allow = io_data->GetCookieSettings()->IsSettingCookieAllowed(
1508 scope, first_party_url);
1510 // Record access to database for potential display in UI.
1511 BrowserThread::PostTask(
1512 BrowserThread::UI, FROM_HERE,
1513 base::Bind(&TabSpecificContentSettings::ServiceWorkerAccessed,
1514 render_process_id, render_frame_id, scope, !allow));
1515 return allow;
1518 bool ChromeContentBrowserClient::AllowGetCookie(
1519 const GURL& url,
1520 const GURL& first_party,
1521 const net::CookieList& cookie_list,
1522 content::ResourceContext* context,
1523 int render_process_id,
1524 int render_frame_id) {
1525 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1526 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1527 bool allow = io_data->GetCookieSettings()->
1528 IsReadingCookieAllowed(url, first_party);
1530 BrowserThread::PostTask(
1531 BrowserThread::UI, FROM_HERE,
1532 base::Bind(&TabSpecificContentSettings::CookiesRead, render_process_id,
1533 render_frame_id, url, first_party, cookie_list, !allow));
1534 return allow;
1537 bool ChromeContentBrowserClient::AllowSetCookie(
1538 const GURL& url,
1539 const GURL& first_party,
1540 const std::string& cookie_line,
1541 content::ResourceContext* context,
1542 int render_process_id,
1543 int render_frame_id,
1544 net::CookieOptions* options) {
1545 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1546 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1547 CookieSettings* cookie_settings = io_data->GetCookieSettings();
1548 bool allow = cookie_settings->IsSettingCookieAllowed(url, first_party);
1550 BrowserThread::PostTask(
1551 BrowserThread::UI, FROM_HERE,
1552 base::Bind(&TabSpecificContentSettings::CookieChanged, render_process_id,
1553 render_frame_id, url, first_party, cookie_line, *options,
1554 !allow));
1555 return allow;
1558 bool ChromeContentBrowserClient::AllowSaveLocalState(
1559 content::ResourceContext* context) {
1560 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1561 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1562 CookieSettings* cookie_settings = io_data->GetCookieSettings();
1563 ContentSetting setting = cookie_settings->GetDefaultCookieSetting(NULL);
1565 // TODO(bauerb): Should we also disallow local state if the default is BLOCK?
1566 // Could we even support per-origin settings?
1567 return setting != CONTENT_SETTING_SESSION_ONLY;
1570 bool ChromeContentBrowserClient::AllowWorkerDatabase(
1571 const GURL& url,
1572 const base::string16& name,
1573 const base::string16& display_name,
1574 unsigned long estimated_size,
1575 content::ResourceContext* context,
1576 const std::vector<std::pair<int, int> >& render_frames) {
1577 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1578 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1579 CookieSettings* cookie_settings = io_data->GetCookieSettings();
1580 bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1582 // Record access to database for potential display in UI.
1583 std::vector<std::pair<int, int> >::const_iterator i;
1584 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1585 BrowserThread::PostTask(
1586 BrowserThread::UI, FROM_HERE,
1587 base::Bind(&TabSpecificContentSettings::WebDatabaseAccessed,
1588 i->first, i->second, url, name, display_name, !allow));
1591 return allow;
1594 void ChromeContentBrowserClient::AllowWorkerFileSystem(
1595 const GURL& url,
1596 content::ResourceContext* context,
1597 const std::vector<std::pair<int, int> >& render_frames,
1598 base::Callback<void(bool)> callback) {
1599 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1600 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1601 CookieSettings* cookie_settings = io_data->GetCookieSettings();
1602 bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1604 #if defined(ENABLE_EXTENSIONS)
1605 GuestPermissionRequestHelper(url, render_frames, callback, allow);
1606 #else
1607 FileSystemAccessed(url, render_frames, callback, allow);
1608 #endif
1611 #if defined(ENABLE_EXTENSIONS)
1612 void ChromeContentBrowserClient::GuestPermissionRequestHelper(
1613 const GURL& url,
1614 const std::vector<std::pair<int, int> >& render_frames,
1615 base::Callback<void(bool)> callback,
1616 bool allow) {
1617 DCHECK(BrowserThread:: CurrentlyOn(BrowserThread::IO));
1618 std::vector<std::pair<int, int> >::const_iterator i;
1619 std::map<int, int> process_map;
1620 std::map<int, int>::const_iterator it;
1621 bool has_web_view_guest = false;
1622 // Record access to file system for potential display in UI.
1623 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1624 if (process_map.find(i->first) != process_map.end())
1625 continue;
1627 process_map.insert(std::pair<int, int>(i->first, i->second));
1629 if (extensions::WebViewRendererState::GetInstance()->IsGuest(i->first))
1630 has_web_view_guest = true;
1632 if (!has_web_view_guest) {
1633 FileSystemAccessed(url, render_frames, callback, allow);
1634 return;
1636 DCHECK_EQ(1U, process_map.size());
1637 it = process_map.begin();
1638 BrowserThread::PostTask(
1639 BrowserThread::UI,
1640 FROM_HERE,
1641 base::Bind(&ChromeContentBrowserClient::
1642 RequestFileSystemPermissionOnUIThread,
1643 it->first,
1644 it->second,
1645 url,
1646 allow,
1647 base::Bind(&ChromeContentBrowserClient::FileSystemAccessed,
1648 weak_factory_.GetWeakPtr(),
1649 url,
1650 render_frames,
1651 callback)));
1654 void ChromeContentBrowserClient::RequestFileSystemPermissionOnUIThread(
1655 int render_process_id,
1656 int render_frame_id,
1657 const GURL& url,
1658 bool allowed_by_default,
1659 const base::Callback<void(bool)>& callback) {
1660 DCHECK(BrowserThread:: CurrentlyOn(BrowserThread::UI));
1661 extensions::WebViewPermissionHelper* web_view_permission_helper =
1662 extensions::WebViewPermissionHelper::FromFrameID(
1663 render_process_id, render_frame_id);
1664 web_view_permission_helper->RequestFileSystemPermission(url,
1665 allowed_by_default,
1666 callback);
1668 #endif
1670 void ChromeContentBrowserClient::FileSystemAccessed(
1671 const GURL& url,
1672 const std::vector<std::pair<int, int> >& render_frames,
1673 base::Callback<void(bool)> callback,
1674 bool allow) {
1675 // Record access to file system for potential display in UI.
1676 std::vector<std::pair<int, int> >::const_iterator i;
1677 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1678 BrowserThread::PostTask(
1679 BrowserThread::UI,
1680 FROM_HERE,
1681 base::Bind(&TabSpecificContentSettings::FileSystemAccessed,
1682 i->first, i->second, url, !allow));
1684 callback.Run(allow);
1687 bool ChromeContentBrowserClient::AllowWorkerIndexedDB(
1688 const GURL& url,
1689 const base::string16& name,
1690 content::ResourceContext* context,
1691 const std::vector<std::pair<int, int> >& render_frames) {
1692 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1693 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1694 CookieSettings* cookie_settings = io_data->GetCookieSettings();
1695 bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1697 // Record access to IndexedDB for potential display in UI.
1698 std::vector<std::pair<int, int> >::const_iterator i;
1699 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1700 BrowserThread::PostTask(
1701 BrowserThread::UI, FROM_HERE,
1702 base::Bind(&TabSpecificContentSettings::IndexedDBAccessed,
1703 i->first, i->second, url, name, !allow));
1706 return allow;
1709 net::URLRequestContext*
1710 ChromeContentBrowserClient::OverrideRequestContextForURL(
1711 const GURL& url, content::ResourceContext* context) {
1712 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1713 #if defined(ENABLE_EXTENSIONS)
1714 if (url.SchemeIs(extensions::kExtensionScheme)) {
1715 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1716 return io_data->extensions_request_context();
1718 #endif
1720 return NULL;
1723 QuotaPermissionContext*
1724 ChromeContentBrowserClient::CreateQuotaPermissionContext() {
1725 return new ChromeQuotaPermissionContext();
1728 void ChromeContentBrowserClient::AllowCertificateError(
1729 int render_process_id,
1730 int render_frame_id,
1731 int cert_error,
1732 const net::SSLInfo& ssl_info,
1733 const GURL& request_url,
1734 ResourceType resource_type,
1735 bool overridable,
1736 bool strict_enforcement,
1737 bool expired_previous_decision,
1738 const base::Callback<void(bool)>& callback,
1739 content::CertificateRequestResultType* result) {
1740 if (resource_type != content::RESOURCE_TYPE_MAIN_FRAME) {
1741 // A sub-resource has a certificate error. The user doesn't really
1742 // have a context for making the right decision, so block the
1743 // request hard, without an info bar to allow showing the insecure
1744 // content.
1745 *result = content::CERTIFICATE_REQUEST_RESULT_TYPE_DENY;
1746 return;
1749 // If the tab is being prerendered, cancel the prerender and the request.
1750 content::RenderFrameHost* render_frame_host =
1751 content::RenderFrameHost::FromID(render_process_id, render_frame_id);
1752 WebContents* tab = WebContents::FromRenderFrameHost(render_frame_host);
1753 if (!tab) {
1754 NOTREACHED();
1755 return;
1758 prerender::PrerenderContents* prerender_contents =
1759 prerender::PrerenderContents::FromWebContents(tab);
1760 if (prerender_contents) {
1761 prerender_contents->Destroy(prerender::FINAL_STATUS_SSL_ERROR);
1762 *result = content::CERTIFICATE_REQUEST_RESULT_TYPE_CANCEL;
1763 return;
1766 // Otherwise, display an SSL blocking page. The interstitial page takes
1767 // ownership of ssl_blocking_page.
1768 int options_mask = 0;
1769 if (overridable)
1770 options_mask |= SSLBlockingPage::OVERRIDABLE;
1771 if (strict_enforcement)
1772 options_mask |= SSLBlockingPage::STRICT_ENFORCEMENT;
1773 if (expired_previous_decision)
1774 options_mask |= SSLBlockingPage::EXPIRED_BUT_PREVIOUSLY_ALLOWED;
1776 SafeBrowsingService* safe_browsing_service =
1777 g_browser_process->safe_browsing_service();
1778 scoped_ptr<SafeBrowsingSSLCertReporter> cert_reporter(
1779 new SafeBrowsingSSLCertReporter(safe_browsing_service
1780 ? safe_browsing_service->ui_manager()
1781 : nullptr));
1782 SSLErrorHandler::HandleSSLError(tab, cert_error, ssl_info, request_url,
1783 options_mask, cert_reporter.Pass(), callback);
1786 void ChromeContentBrowserClient::SelectClientCertificate(
1787 content::WebContents* web_contents,
1788 net::SSLCertRequestInfo* cert_request_info,
1789 scoped_ptr<content::ClientCertificateDelegate> delegate) {
1790 prerender::PrerenderContents* prerender_contents =
1791 prerender::PrerenderContents::FromWebContents(web_contents);
1792 if (prerender_contents) {
1793 prerender_contents->Destroy(
1794 prerender::FINAL_STATUS_SSL_CLIENT_CERTIFICATE_REQUESTED);
1795 return;
1798 GURL requesting_url("https://" + cert_request_info->host_and_port.ToString());
1799 DCHECK(requesting_url.is_valid())
1800 << "Invalid URL string: https://"
1801 << cert_request_info->host_and_port.ToString();
1803 Profile* profile =
1804 Profile::FromBrowserContext(web_contents->GetBrowserContext());
1805 scoped_ptr<base::Value> filter =
1806 profile->GetHostContentSettingsMap()->GetWebsiteSetting(
1807 requesting_url,
1808 requesting_url,
1809 CONTENT_SETTINGS_TYPE_AUTO_SELECT_CERTIFICATE,
1810 std::string(),
1811 NULL);
1813 if (filter.get()) {
1814 // Try to automatically select a client certificate.
1815 if (filter->IsType(base::Value::TYPE_DICTIONARY)) {
1816 base::DictionaryValue* filter_dict =
1817 static_cast<base::DictionaryValue*>(filter.get());
1819 const std::vector<scoped_refptr<net::X509Certificate> >&
1820 all_client_certs = cert_request_info->client_certs;
1821 for (size_t i = 0; i < all_client_certs.size(); ++i) {
1822 if (CertMatchesFilter(*all_client_certs[i].get(), *filter_dict)) {
1823 // Use the first certificate that is matched by the filter.
1824 delegate->ContinueWithCertificate(all_client_certs[i].get());
1825 return;
1828 } else {
1829 NOTREACHED();
1833 chrome::ShowSSLClientCertificateSelector(web_contents, cert_request_info,
1834 delegate.Pass());
1837 void ChromeContentBrowserClient::AddCertificate(
1838 net::CertificateMimeType cert_type,
1839 const void* cert_data,
1840 size_t cert_size,
1841 int render_process_id,
1842 int render_frame_id) {
1843 chrome::SSLAddCertificate(cert_type, cert_data, cert_size,
1844 render_process_id, render_frame_id);
1847 content::MediaObserver* ChromeContentBrowserClient::GetMediaObserver() {
1848 return MediaCaptureDevicesDispatcher::GetInstance();
1851 content::PlatformNotificationService*
1852 ChromeContentBrowserClient::GetPlatformNotificationService() {
1853 #if defined(ENABLE_NOTIFICATIONS)
1854 return PlatformNotificationServiceImpl::GetInstance();
1855 #else
1856 NOTIMPLEMENTED();
1857 return NULL;
1858 #endif
1861 bool ChromeContentBrowserClient::CanCreateWindow(
1862 const GURL& opener_url,
1863 const GURL& opener_top_level_frame_url,
1864 const GURL& source_origin,
1865 WindowContainerType container_type,
1866 const GURL& target_url,
1867 const content::Referrer& referrer,
1868 WindowOpenDisposition disposition,
1869 const WebWindowFeatures& features,
1870 bool user_gesture,
1871 bool opener_suppressed,
1872 content::ResourceContext* context,
1873 int render_process_id,
1874 int opener_render_view_id,
1875 int opener_render_frame_id,
1876 bool* no_javascript_access) {
1877 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1879 *no_javascript_access = false;
1881 // If the opener is trying to create a background window but doesn't have
1882 // the appropriate permission, fail the attempt.
1883 if (container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {
1884 #if defined(ENABLE_EXTENSIONS)
1885 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1886 InfoMap* map = io_data->GetExtensionInfoMap();
1887 if (!map->SecurityOriginHasAPIPermission(
1888 source_origin,
1889 render_process_id,
1890 APIPermission::kBackground)) {
1891 return false;
1894 // Note: this use of GetExtensionOrAppByURL is safe but imperfect. It may
1895 // return a recently installed Extension even if this CanCreateWindow call
1896 // was made by an old copy of the page in a normal web process. That's ok,
1897 // because the permission check above would have caused an early return
1898 // already. We must use the full URL to find hosted apps, though, and not
1899 // just the origin.
1900 const Extension* extension =
1901 map->extensions().GetExtensionOrAppByURL(opener_url);
1902 if (extension && !extensions::BackgroundInfo::AllowJSAccess(extension))
1903 *no_javascript_access = true;
1904 #endif
1906 return true;
1909 #if defined(ENABLE_EXTENSIONS)
1910 if (extensions::WebViewRendererState::GetInstance()->IsGuest(
1911 render_process_id))
1912 return true;
1913 #endif
1915 HostContentSettingsMap* content_settings =
1916 ProfileIOData::FromResourceContext(context)->GetHostContentSettingsMap();
1917 BlockedWindowParams blocked_params(target_url,
1918 referrer,
1919 disposition,
1920 features,
1921 user_gesture,
1922 opener_suppressed,
1923 render_process_id,
1924 opener_render_frame_id);
1926 if (!user_gesture &&
1927 !base::CommandLine::ForCurrentProcess()->HasSwitch(
1928 switches::kDisablePopupBlocking)) {
1929 if (content_settings->GetContentSetting(opener_top_level_frame_url,
1930 opener_top_level_frame_url,
1931 CONTENT_SETTINGS_TYPE_POPUPS,
1932 std::string()) !=
1933 CONTENT_SETTING_ALLOW) {
1934 BrowserThread::PostTask(BrowserThread::UI,
1935 FROM_HERE,
1936 base::Bind(&HandleBlockedPopupOnUIThread,
1937 blocked_params));
1938 return false;
1942 #if defined(OS_ANDROID)
1943 if (SingleTabModeTabHelper::IsRegistered(render_process_id,
1944 opener_render_view_id)) {
1945 BrowserThread::PostTask(BrowserThread::UI,
1946 FROM_HERE,
1947 base::Bind(&HandleSingleTabModeBlockOnUIThread,
1948 blocked_params));
1949 return false;
1951 #endif
1953 return true;
1956 void ChromeContentBrowserClient::ResourceDispatcherHostCreated() {
1957 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1958 return g_browser_process->ResourceDispatcherHostCreated();
1961 content::SpeechRecognitionManagerDelegate*
1962 ChromeContentBrowserClient::CreateSpeechRecognitionManagerDelegate() {
1963 return new speech::ChromeSpeechRecognitionManagerDelegate();
1966 net::NetLog* ChromeContentBrowserClient::GetNetLog() {
1967 return g_browser_process->net_log();
1970 AccessTokenStore* ChromeContentBrowserClient::CreateAccessTokenStore() {
1971 return new ChromeAccessTokenStore();
1974 bool ChromeContentBrowserClient::IsFastShutdownPossible() {
1975 return true;
1978 void ChromeContentBrowserClient::OverrideWebkitPrefs(
1979 RenderViewHost* rvh, WebPreferences* web_prefs) {
1980 Profile* profile = Profile::FromBrowserContext(
1981 rvh->GetProcess()->GetBrowserContext());
1982 PrefService* prefs = profile->GetPrefs();
1984 // Fill per-script font preferences. These are not registered on Android
1985 // - http://crbug.com/308033.
1986 #if !defined(OS_ANDROID)
1987 FontFamilyCache::FillFontFamilyMap(profile,
1988 prefs::kWebKitStandardFontFamilyMap,
1989 &web_prefs->standard_font_family_map);
1990 FontFamilyCache::FillFontFamilyMap(profile,
1991 prefs::kWebKitFixedFontFamilyMap,
1992 &web_prefs->fixed_font_family_map);
1993 FontFamilyCache::FillFontFamilyMap(profile,
1994 prefs::kWebKitSerifFontFamilyMap,
1995 &web_prefs->serif_font_family_map);
1996 FontFamilyCache::FillFontFamilyMap(profile,
1997 prefs::kWebKitSansSerifFontFamilyMap,
1998 &web_prefs->sans_serif_font_family_map);
1999 FontFamilyCache::FillFontFamilyMap(profile,
2000 prefs::kWebKitCursiveFontFamilyMap,
2001 &web_prefs->cursive_font_family_map);
2002 FontFamilyCache::FillFontFamilyMap(profile,
2003 prefs::kWebKitFantasyFontFamilyMap,
2004 &web_prefs->fantasy_font_family_map);
2005 FontFamilyCache::FillFontFamilyMap(profile,
2006 prefs::kWebKitPictographFontFamilyMap,
2007 &web_prefs->pictograph_font_family_map);
2008 #endif
2010 web_prefs->default_font_size =
2011 prefs->GetInteger(prefs::kWebKitDefaultFontSize);
2012 web_prefs->default_fixed_font_size =
2013 prefs->GetInteger(prefs::kWebKitDefaultFixedFontSize);
2014 web_prefs->minimum_font_size =
2015 prefs->GetInteger(prefs::kWebKitMinimumFontSize);
2016 web_prefs->minimum_logical_font_size =
2017 prefs->GetInteger(prefs::kWebKitMinimumLogicalFontSize);
2019 web_prefs->default_encoding = prefs->GetString(prefs::kDefaultCharset);
2021 web_prefs->javascript_can_open_windows_automatically =
2022 prefs->GetBoolean(prefs::kWebKitJavascriptCanOpenWindowsAutomatically);
2023 web_prefs->dom_paste_enabled =
2024 prefs->GetBoolean(prefs::kWebKitDomPasteEnabled);
2025 web_prefs->tabs_to_links = prefs->GetBoolean(prefs::kWebkitTabsToLinks);
2027 if (!prefs->GetBoolean(prefs::kWebKitJavascriptEnabled))
2028 web_prefs->javascript_enabled = false;
2029 if (!prefs->GetBoolean(prefs::kWebKitWebSecurityEnabled))
2030 web_prefs->web_security_enabled = false;
2031 if (!prefs->GetBoolean(prefs::kWebKitPluginsEnabled))
2032 web_prefs->plugins_enabled = false;
2033 if (!prefs->GetBoolean(prefs::kWebKitJavaEnabled))
2034 web_prefs->java_enabled = false;
2035 web_prefs->loads_images_automatically =
2036 prefs->GetBoolean(prefs::kWebKitLoadsImagesAutomatically);
2038 if (prefs->GetBoolean(prefs::kDisable3DAPIs))
2039 web_prefs->experimental_webgl_enabled = false;
2041 web_prefs->allow_displaying_insecure_content =
2042 prefs->GetBoolean(prefs::kWebKitAllowDisplayingInsecureContent);
2043 web_prefs->allow_running_insecure_content =
2044 prefs->GetBoolean(prefs::kWebKitAllowRunningInsecureContent);
2045 #if defined(OS_ANDROID)
2046 web_prefs->font_scale_factor =
2047 static_cast<float>(prefs->GetDouble(prefs::kWebKitFontScaleFactor));
2048 web_prefs->device_scale_adjustment = GetDeviceScaleAdjustment();
2049 web_prefs->force_enable_zoom =
2050 prefs->GetBoolean(prefs::kWebKitForceEnableZoom);
2051 #endif
2053 #if defined(OS_ANDROID)
2054 web_prefs->password_echo_enabled =
2055 prefs->GetBoolean(prefs::kWebKitPasswordEchoEnabled);
2056 #else
2057 web_prefs->password_echo_enabled = browser_defaults::kPasswordEchoEnabled;
2058 #endif
2060 web_prefs->asynchronous_spell_checking_enabled = true;
2061 web_prefs->unified_textchecker_enabled = true;
2063 web_prefs->uses_universal_detector =
2064 prefs->GetBoolean(prefs::kWebKitUsesUniversalDetector);
2065 web_prefs->text_areas_are_resizable =
2066 prefs->GetBoolean(prefs::kWebKitTextAreasAreResizable);
2067 web_prefs->hyperlink_auditing_enabled =
2068 prefs->GetBoolean(prefs::kEnableHyperlinkAuditing);
2070 #if defined(ENABLE_EXTENSIONS)
2071 std::string image_animation_policy =
2072 prefs->GetString(prefs::kAnimationPolicy);
2073 if (image_animation_policy == kAnimationPolicyOnce)
2074 web_prefs->animation_policy =
2075 content::IMAGE_ANIMATION_POLICY_ANIMATION_ONCE;
2076 else if (image_animation_policy == kAnimationPolicyNone)
2077 web_prefs->animation_policy = content::IMAGE_ANIMATION_POLICY_NO_ANIMATION;
2078 else
2079 web_prefs->animation_policy = content::IMAGE_ANIMATION_POLICY_ALLOWED;
2080 #endif
2082 // Make sure we will set the default_encoding with canonical encoding name.
2083 web_prefs->default_encoding =
2084 CharacterEncoding::GetCanonicalEncodingNameByAliasName(
2085 web_prefs->default_encoding);
2086 if (web_prefs->default_encoding.empty()) {
2087 prefs->ClearPref(prefs::kDefaultCharset);
2088 web_prefs->default_encoding = prefs->GetString(prefs::kDefaultCharset);
2090 DCHECK(!web_prefs->default_encoding.empty());
2092 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2093 switches::kEnablePotentiallyAnnoyingSecurityFeatures)) {
2094 web_prefs->disable_reading_from_canvas = true;
2095 web_prefs->strict_mixed_content_checking = true;
2096 web_prefs->strict_powerful_feature_restrictions = true;
2099 for (size_t i = 0; i < extra_parts_.size(); ++i)
2100 extra_parts_[i]->OverrideWebkitPrefs(rvh, web_prefs);
2103 void ChromeContentBrowserClient::BrowserURLHandlerCreated(
2104 BrowserURLHandler* handler) {
2105 for (size_t i = 0; i < extra_parts_.size(); ++i)
2106 extra_parts_[i]->BrowserURLHandlerCreated(handler);
2108 // about: handler. Must come before chrome: handler, since it will
2109 // rewrite about: urls to chrome: URLs and then expect chrome: to
2110 // actually handle them. Also relies on a preliminary fixup phase.
2111 handler->SetFixupHandler(&FixupBrowserAboutURL);
2112 handler->AddHandlerPair(&WillHandleBrowserAboutURL,
2113 BrowserURLHandler::null_handler());
2115 #if defined(OS_ANDROID)
2116 // Handler to rewrite chrome://newtab on Android.
2117 handler->AddHandlerPair(&chrome::android::HandleAndroidNativePageURL,
2118 BrowserURLHandler::null_handler());
2119 #else
2120 // Handler to rewrite chrome://newtab for InstantExtended.
2121 handler->AddHandlerPair(&chrome::HandleNewTabURLRewrite,
2122 &chrome::HandleNewTabURLReverseRewrite);
2123 #endif
2125 // chrome: & friends.
2126 handler->AddHandlerPair(&HandleWebUI, &HandleWebUIReverse);
2129 void ChromeContentBrowserClient::ClearCache(RenderFrameHost* rfh) {
2130 Profile* profile = Profile::FromBrowserContext(
2131 rfh->GetSiteInstance()->GetProcess()->GetBrowserContext());
2132 BrowsingDataRemover* remover =
2133 BrowsingDataRemover::CreateForUnboundedRange(profile);
2134 remover->Remove(BrowsingDataRemover::REMOVE_CACHE,
2135 BrowsingDataHelper::UNPROTECTED_WEB);
2136 // BrowsingDataRemover takes care of deleting itself when done.
2139 void ChromeContentBrowserClient::ClearCookies(RenderFrameHost* rfh) {
2140 Profile* profile = Profile::FromBrowserContext(
2141 rfh->GetSiteInstance()->GetProcess()->GetBrowserContext());
2142 BrowsingDataRemover* remover =
2143 BrowsingDataRemover::CreateForUnboundedRange(profile);
2144 int remove_mask = BrowsingDataRemover::REMOVE_SITE_DATA;
2145 remover->Remove(remove_mask, BrowsingDataHelper::UNPROTECTED_WEB);
2146 // BrowsingDataRemover takes care of deleting itself when done.
2149 base::FilePath ChromeContentBrowserClient::GetDefaultDownloadDirectory() {
2150 return DownloadPrefs::GetDefaultDownloadDirectory();
2153 std::string ChromeContentBrowserClient::GetDefaultDownloadName() {
2154 return l10n_util::GetStringUTF8(IDS_DEFAULT_DOWNLOAD_FILENAME);
2157 void ChromeContentBrowserClient::DidCreatePpapiPlugin(
2158 content::BrowserPpapiHost* browser_host) {
2159 #if defined(ENABLE_PLUGINS)
2160 ChromeContentBrowserClientPluginsPart::DidCreatePpapiPlugin(browser_host);
2161 #endif
2164 content::BrowserPpapiHost*
2165 ChromeContentBrowserClient::GetExternalBrowserPpapiHost(
2166 int plugin_process_id) {
2167 #if !defined(DISABLE_NACL)
2168 content::BrowserChildProcessHostIterator iter(PROCESS_TYPE_NACL_LOADER);
2169 while (!iter.Done()) {
2170 nacl::NaClProcessHost* host = static_cast<nacl::NaClProcessHost*>(
2171 iter.GetDelegate());
2172 if (host->process() &&
2173 host->process()->GetData().id == plugin_process_id) {
2174 // Found the plugin.
2175 return host->browser_ppapi_host();
2177 ++iter;
2179 #endif
2180 return NULL;
2183 bool ChromeContentBrowserClient::AllowPepperSocketAPI(
2184 content::BrowserContext* browser_context,
2185 const GURL& url,
2186 bool private_api,
2187 const content::SocketPermissionRequest* params) {
2188 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
2189 return ChromeContentBrowserClientPluginsPart::AllowPepperSocketAPI(
2190 browser_context, url, private_api, params, allowed_socket_origins_);
2191 #else
2192 return false;
2193 #endif
2196 ui::SelectFilePolicy* ChromeContentBrowserClient::CreateSelectFilePolicy(
2197 WebContents* web_contents) {
2198 return new ChromeSelectFilePolicy(web_contents);
2201 void ChromeContentBrowserClient::GetAdditionalAllowedSchemesForFileSystem(
2202 std::vector<std::string>* additional_allowed_schemes) {
2203 ContentBrowserClient::GetAdditionalAllowedSchemesForFileSystem(
2204 additional_allowed_schemes);
2205 additional_allowed_schemes->push_back(content::kChromeDevToolsScheme);
2206 additional_allowed_schemes->push_back(content::kChromeUIScheme);
2207 for (size_t i = 0; i < extra_parts_.size(); ++i) {
2208 extra_parts_[i]->GetAdditionalAllowedSchemesForFileSystem(
2209 additional_allowed_schemes);
2213 void ChromeContentBrowserClient::GetURLRequestAutoMountHandlers(
2214 std::vector<storage::URLRequestAutoMountHandler>* handlers) {
2215 for (size_t i = 0; i < extra_parts_.size(); ++i)
2216 extra_parts_[i]->GetURLRequestAutoMountHandlers(handlers);
2219 void ChromeContentBrowserClient::GetAdditionalFileSystemBackends(
2220 content::BrowserContext* browser_context,
2221 const base::FilePath& storage_partition_path,
2222 ScopedVector<storage::FileSystemBackend>* additional_backends) {
2223 #if defined(OS_CHROMEOS)
2224 storage::ExternalMountPoints* external_mount_points =
2225 content::BrowserContext::GetMountPoints(browser_context);
2226 DCHECK(external_mount_points);
2227 chromeos::FileSystemBackend* backend = new chromeos::FileSystemBackend(
2228 new drive::FileSystemBackendDelegate,
2229 new chromeos::file_system_provider::BackendDelegate,
2230 new chromeos::MTPFileSystemBackendDelegate(storage_partition_path),
2231 external_mount_points,
2232 storage::ExternalMountPoints::GetSystemInstance());
2233 backend->AddSystemMountPoints();
2234 DCHECK(backend->CanHandleType(storage::kFileSystemTypeExternal));
2235 additional_backends->push_back(backend);
2236 #endif
2238 for (size_t i = 0; i < extra_parts_.size(); ++i) {
2239 extra_parts_[i]->GetAdditionalFileSystemBackends(
2240 browser_context, storage_partition_path, additional_backends);
2244 #if defined(OS_POSIX) && !defined(OS_MACOSX)
2245 void ChromeContentBrowserClient::GetAdditionalMappedFilesForChildProcess(
2246 const base::CommandLine& command_line,
2247 int child_process_id,
2248 FileDescriptorInfo* mappings) {
2249 #if defined(V8_USE_EXTERNAL_STARTUP_DATA)
2250 if (!natives_fd_exists()) {
2251 int v8_natives_fd = -1;
2252 int v8_snapshot_fd = -1;
2253 if (gin::V8Initializer::OpenV8FilesForChildProcesses(&v8_natives_fd,
2254 &v8_snapshot_fd)) {
2255 v8_natives_fd_.reset(v8_natives_fd);
2256 v8_snapshot_fd_.reset(v8_snapshot_fd);
2259 // V8 can't start up without the source of the natives, but it can
2260 // start up (slower) without the snapshot.
2261 DCHECK(natives_fd_exists());
2262 mappings->Share(kV8NativesDataDescriptor, v8_natives_fd_.get());
2263 if (snapshot_fd_exists())
2264 mappings->Share(kV8SnapshotDataDescriptor, v8_snapshot_fd_.get());
2265 #endif // V8_USE_EXTERNAL_STARTUP_DATA
2267 #if defined(OS_ANDROID)
2268 base::FilePath data_path;
2269 PathService::Get(ui::DIR_RESOURCE_PAKS_ANDROID, &data_path);
2270 DCHECK(!data_path.empty());
2272 int flags = base::File::FLAG_OPEN | base::File::FLAG_READ;
2273 base::FilePath chrome_resources_pak =
2274 data_path.AppendASCII("chrome_100_percent.pak");
2275 base::File file(chrome_resources_pak, flags);
2276 DCHECK(file.IsValid());
2277 mappings->Transfer(kAndroidChrome100PercentPakDescriptor,
2278 base::ScopedFD(file.TakePlatformFile()));
2280 const std::string locale = GetApplicationLocale();
2281 base::FilePath locale_pak = ResourceBundle::GetSharedInstance().
2282 GetLocaleFilePath(locale, false);
2283 file.Initialize(locale_pak, flags);
2284 DCHECK(file.IsValid());
2285 mappings->Transfer(kAndroidLocalePakDescriptor,
2286 base::ScopedFD(file.TakePlatformFile()));
2288 base::FilePath resources_pack_path;
2289 PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
2290 file.Initialize(resources_pack_path, flags);
2291 DCHECK(file.IsValid());
2292 mappings->Transfer(kAndroidUIResourcesPakDescriptor,
2293 base::ScopedFD(file.TakePlatformFile()));
2295 if (breakpad::IsCrashReporterEnabled()) {
2296 file = breakpad::CrashDumpManager::GetInstance()->CreateMinidumpFile(
2297 child_process_id);
2298 if (file.IsValid()) {
2299 mappings->Transfer(kAndroidMinidumpDescriptor,
2300 base::ScopedFD(file.TakePlatformFile()));
2301 } else {
2302 LOG(ERROR) << "Failed to create file for minidump, crash reporting will "
2303 "be disabled for this process.";
2307 base::FilePath app_data_path;
2308 PathService::Get(base::DIR_ANDROID_APP_DATA, &app_data_path);
2309 DCHECK(!app_data_path.empty());
2311 flags = base::File::FLAG_OPEN | base::File::FLAG_READ;
2312 base::FilePath icudata_path =
2313 app_data_path.AppendASCII(base::i18n::kIcuDataFileName);
2314 base::File icudata_file(icudata_path, flags);
2315 DCHECK(icudata_file.IsValid());
2316 mappings->Transfer(kAndroidICUDataDescriptor,
2317 base::ScopedFD(icudata_file.TakePlatformFile()));
2318 #else
2319 int crash_signal_fd = GetCrashSignalFD(command_line);
2320 if (crash_signal_fd >= 0) {
2321 mappings->Share(kCrashDumpSignal, crash_signal_fd);
2323 #endif // defined(OS_ANDROID)
2325 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
2327 #if defined(OS_WIN)
2328 const wchar_t* ChromeContentBrowserClient::GetResourceDllName() {
2329 return chrome::kBrowserResourcesDll;
2332 void ChromeContentBrowserClient::PreSpawnRenderer(
2333 sandbox::TargetPolicy* policy,
2334 bool* success) {
2335 // This code is duplicated in nacl_exe_win_64.cc.
2336 // Allow the server side of a pipe restricted to the "chrome.nacl."
2337 // namespace so that it cannot impersonate other system or other chrome
2338 // service pipes.
2339 sandbox::ResultCode result = policy->AddRule(
2340 sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
2341 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
2342 L"\\\\.\\pipe\\chrome.nacl.*");
2343 if (result != sandbox::SBOX_ALL_OK) {
2344 *success = false;
2345 return;
2348 // Renderers need to send named pipe handles and shared memory
2349 // segment handles to NaCl loader processes.
2350 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
2351 sandbox::TargetPolicy::HANDLES_DUP_ANY,
2352 L"File");
2353 if (result != sandbox::SBOX_ALL_OK) {
2354 *success = false;
2355 return;
2358 #endif
2360 void ChromeContentBrowserClient::OverrideRenderFrameMojoServices(
2361 content::ServiceRegistry* registry,
2362 content::RenderFrameHost* render_frame_host) {
2363 #if defined(OS_CHROMEOS)
2364 registry->AddService(
2365 base::Bind(&chromeos::attestation::PlatformVerificationImpl::Create,
2366 render_frame_host));
2367 #endif
2370 void ChromeContentBrowserClient::RegisterMojoApplications(
2371 StaticMojoApplicationMap* apps) {
2372 #if !defined(OS_ANDROID) && !defined(OS_IOS)
2373 apps->insert(std::make_pair(GURL(device::kDevicesMojoAppUrl),
2374 base::Bind(&device::DevicesApp::CreateDelegate,
2375 base::ThreadTaskRunnerHandle::Get())));
2376 #endif
2379 void ChromeContentBrowserClient::OpenURL(
2380 content::BrowserContext* browser_context,
2381 const content::OpenURLParams& params,
2382 const base::Callback<void(content::WebContents*)>& callback) {
2383 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2385 #if !defined(OS_ANDROID) && !defined(OS_IOS)
2386 NavigateParams nav_params(Profile::FromBrowserContext(browser_context),
2387 params.url,
2388 params.transition);
2389 FillNavigateParamsFromOpenURLParams(&nav_params, params);
2390 nav_params.user_gesture = params.user_gesture;
2392 Navigate(&nav_params);
2393 callback.Run(nav_params.target_contents);
2394 #elif defined(OS_ANDROID)
2395 service_tab_launcher::ServiceTabLauncher::GetInstance()->LaunchTab(
2396 browser_context, params, callback);
2397 #else
2398 NOTIMPLEMENTED();
2399 #endif
2402 content::PresentationServiceDelegate*
2403 ChromeContentBrowserClient::GetPresentationServiceDelegate(
2404 content::WebContents* web_contents) {
2405 #if defined(ENABLE_MEDIA_ROUTER)
2406 if (switches::MediaRouterEnabled()) {
2407 return media_router::PresentationServiceDelegateImpl::
2408 GetOrCreateForWebContents(web_contents);
2410 #endif
2411 return nullptr;
2414 void ChromeContentBrowserClient::RecordURLMetric(const std::string& metric,
2415 const GURL& url) {
2416 if (url.is_valid()) {
2417 rappor::SampleDomainAndRegistryFromGURL(g_browser_process->rappor_service(),
2418 metric, url);
2422 content::DevToolsManagerDelegate*
2423 ChromeContentBrowserClient::GetDevToolsManagerDelegate() {
2424 return new ChromeDevToolsManagerDelegate();
2427 content::TracingDelegate* ChromeContentBrowserClient::GetTracingDelegate() {
2428 #if !defined(OS_ANDROID)
2429 return new ChromeTracingDelegate();
2430 #else
2431 return nullptr;
2432 #endif
2435 bool ChromeContentBrowserClient::IsPluginAllowedToCallRequestOSFileHandle(
2436 content::BrowserContext* browser_context,
2437 const GURL& url) {
2438 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
2439 return ChromeContentBrowserClientPluginsPart::
2440 IsPluginAllowedToCallRequestOSFileHandle(browser_context, url,
2441 allowed_file_handle_origins_);
2442 #else
2443 return false;
2444 #endif
2447 bool ChromeContentBrowserClient::IsPluginAllowedToUseDevChannelAPIs(
2448 content::BrowserContext* browser_context,
2449 const GURL& url) {
2450 #if defined(ENABLE_PLUGINS) && defined(ENABLE_EXTENSIONS)
2451 return ChromeContentBrowserClientPluginsPart::
2452 IsPluginAllowedToUseDevChannelAPIs(browser_context, url,
2453 allowed_dev_channel_origins_);
2454 #else
2455 return false;
2456 #endif
2459 void ChromeContentBrowserClient::OverridePageVisibilityState(
2460 RenderFrameHost* render_frame_host,
2461 blink::WebPageVisibilityState* visibility_state) {
2462 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
2464 WebContents* web_contents =
2465 WebContents::FromRenderFrameHost(render_frame_host);
2466 DCHECK(web_contents);
2468 Profile* profile =
2469 Profile::FromBrowserContext(web_contents->GetBrowserContext());
2470 prerender::PrerenderManager* prerender_manager =
2471 prerender::PrerenderManagerFactory::GetForProfile(profile);
2472 if (prerender_manager &&
2473 prerender_manager->IsWebContentsPrerendering(web_contents, nullptr)) {
2474 *visibility_state = blink::WebPageVisibilityStatePrerender;
2478 #if defined(ENABLE_WEBRTC)
2479 void ChromeContentBrowserClient::MaybeCopyDisableWebRtcEncryptionSwitch(
2480 base::CommandLine* to_command_line,
2481 const base::CommandLine& from_command_line,
2482 VersionInfo::Channel channel) {
2483 #if defined(OS_ANDROID)
2484 const VersionInfo::Channel kMaxDisableEncryptionChannel =
2485 VersionInfo::CHANNEL_BETA;
2486 #else
2487 const VersionInfo::Channel kMaxDisableEncryptionChannel =
2488 VersionInfo::CHANNEL_DEV;
2489 #endif
2490 if (channel <= kMaxDisableEncryptionChannel) {
2491 static const char* const kWebRtcDevSwitchNames[] = {
2492 switches::kDisableWebRtcEncryption,
2494 to_command_line->CopySwitchesFrom(from_command_line,
2495 kWebRtcDevSwitchNames,
2496 arraysize(kWebRtcDevSwitchNames));
2499 #endif // defined(ENABLE_WEBRTC)
2501 } // namespace chrome