Adding instrumentation to locate the source of jankiness
[chromium-blink-merge.git] / chrome / browser / chrome_content_browser_client.cc
blobf57d75c04f098c77d5fe3bdf545caba967341b31
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/chrome_content_browser_client.h"
7 #include <set>
8 #include <utility>
9 #include <vector>
11 #include "base/bind.h"
12 #include "base/command_line.h"
13 #include "base/files/scoped_file.h"
14 #include "base/lazy_instance.h"
15 #include "base/path_service.h"
16 #include "base/prefs/pref_service.h"
17 #include "base/prefs/scoped_user_pref_update.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "base/threading/sequenced_worker_pool.h"
21 #include "chrome/browser/browser_about_handler.h"
22 #include "chrome/browser/browser_process.h"
23 #include "chrome/browser/browser_shutdown.h"
24 #include "chrome/browser/browsing_data/browsing_data_helper.h"
25 #include "chrome/browser/browsing_data/browsing_data_remover.h"
26 #include "chrome/browser/character_encoding.h"
27 #include "chrome/browser/chrome_content_browser_client_parts.h"
28 #include "chrome/browser/chrome_net_benchmarking_message_filter.h"
29 #include "chrome/browser/chrome_quota_permission_context.h"
30 #include "chrome/browser/content_settings/content_settings_utils.h"
31 #include "chrome/browser/content_settings/cookie_settings.h"
32 #include "chrome/browser/content_settings/host_content_settings_map.h"
33 #include "chrome/browser/content_settings/tab_specific_content_settings.h"
34 #include "chrome/browser/defaults.h"
35 #include "chrome/browser/download/download_prefs.h"
36 #include "chrome/browser/font_family_cache.h"
37 #include "chrome/browser/geolocation/chrome_access_token_store.h"
38 #include "chrome/browser/geolocation/geolocation_permission_context.h"
39 #include "chrome/browser/geolocation/geolocation_permission_context_factory.h"
40 #include "chrome/browser/media/cast_transport_host_filter.h"
41 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
42 #include "chrome/browser/media/midi_permission_context.h"
43 #include "chrome/browser/media/midi_permission_context_factory.h"
44 #include "chrome/browser/metrics/chrome_browser_main_extra_parts_metrics.h"
45 #include "chrome/browser/nacl_host/nacl_browser_delegate_impl.h"
46 #include "chrome/browser/net/chrome_net_log.h"
47 #include "chrome/browser/notifications/desktop_notification_service.h"
48 #include "chrome/browser/notifications/desktop_notification_service_factory.h"
49 #include "chrome/browser/platform_util.h"
50 #include "chrome/browser/plugins/plugin_info_message_filter.h"
51 #include "chrome/browser/prerender/prerender_final_status.h"
52 #include "chrome/browser/prerender/prerender_manager.h"
53 #include "chrome/browser/prerender/prerender_manager_factory.h"
54 #include "chrome/browser/prerender/prerender_message_filter.h"
55 #include "chrome/browser/prerender/prerender_tracker.h"
56 #include "chrome/browser/printing/printing_message_filter.h"
57 #include "chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.h"
58 #include "chrome/browser/profiles/profile.h"
59 #include "chrome/browser/profiles/profile_io_data.h"
60 #include "chrome/browser/renderer_host/chrome_render_message_filter.h"
61 #include "chrome/browser/renderer_host/pepper/chrome_browser_pepper_host_factory.h"
62 #include "chrome/browser/search/instant_service.h"
63 #include "chrome/browser/search/instant_service_factory.h"
64 #include "chrome/browser/search/search.h"
65 #include "chrome/browser/search_engines/search_provider_install_state_message_filter.h"
66 #include "chrome/browser/signin/principals_message_filter.h"
67 #include "chrome/browser/speech/chrome_speech_recognition_manager_delegate.h"
68 #include "chrome/browser/speech/tts_controller.h"
69 #include "chrome/browser/speech/tts_message_filter.h"
70 #include "chrome/browser/ssl/ssl_add_certificate.h"
71 #include "chrome/browser/ssl/ssl_blocking_page.h"
72 #include "chrome/browser/ssl/ssl_client_certificate_selector.h"
73 #include "chrome/browser/tab_contents/tab_util.h"
74 #include "chrome/browser/ui/blocked_content/blocked_window_params.h"
75 #include "chrome/browser/ui/blocked_content/popup_blocker_tab_helper.h"
76 #include "chrome/browser/ui/chrome_select_file_policy.h"
77 #include "chrome/browser/ui/sync/sync_promo_ui.h"
78 #include "chrome/browser/ui/tab_contents/chrome_web_contents_view_delegate.h"
79 #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
80 #include "chrome/common/chrome_constants.h"
81 #include "chrome/common/chrome_paths.h"
82 #include "chrome/common/chrome_switches.h"
83 #include "chrome/common/env_vars.h"
84 #include "chrome/common/logging_chrome.h"
85 #include "chrome/common/pepper_permission_util.h"
86 #include "chrome/common/pref_names.h"
87 #include "chrome/common/render_messages.h"
88 #include "chrome/common/url_constants.h"
89 #include "chrome/grit/generated_resources.h"
90 #include "chrome/installer/util/google_update_settings.h"
91 #include "chromeos/chromeos_constants.h"
92 #include "components/cdm/browser/cdm_message_filter_android.h"
93 #include "components/cloud_devices/common/cloud_devices_switches.h"
94 #include "components/content_settings/core/browser/content_settings_provider.h"
95 #include "components/content_settings/core/common/content_settings.h"
96 #include "components/content_settings/core/common/permission_request_id.h"
97 #include "components/dom_distiller/core/url_constants.h"
98 #include "components/google/core/browser/google_util.h"
99 #include "components/metrics/client_info.h"
100 #include "components/pref_registry/pref_registry_syncable.h"
101 #include "components/signin/core/common/profile_management_switches.h"
102 #include "components/translate/core/common/translate_switches.h"
103 #include "content/public/browser/browser_child_process_host.h"
104 #include "content/public/browser/browser_main_parts.h"
105 #include "content/public/browser/browser_ppapi_host.h"
106 #include "content/public/browser/browser_thread.h"
107 #include "content/public/browser/browser_url_handler.h"
108 #include "content/public/browser/child_process_data.h"
109 #include "content/public/browser/child_process_security_policy.h"
110 #include "content/public/browser/desktop_notification_delegate.h"
111 #include "content/public/browser/render_frame_host.h"
112 #include "content/public/browser/render_process_host.h"
113 #include "content/public/browser/render_view_host.h"
114 #include "content/public/browser/resource_context.h"
115 #include "content/public/browser/site_instance.h"
116 #include "content/public/browser/web_contents.h"
117 #include "content/public/common/child_process_host.h"
118 #include "content/public/common/content_descriptors.h"
119 #include "content/public/common/show_desktop_notification_params.h"
120 #include "content/public/common/url_utils.h"
121 #include "content/public/common/web_preferences.h"
122 #include "net/base/mime_util.h"
123 #include "net/cookies/canonical_cookie.h"
124 #include "net/cookies/cookie_options.h"
125 #include "net/ssl/ssl_cert_request_info.h"
126 #include "ppapi/host/ppapi_host.h"
127 #include "ppapi/shared_impl/ppapi_switches.h"
128 #include "storage/browser/fileapi/external_mount_points.h"
129 #include "ui/base/l10n/l10n_util.h"
130 #include "ui/base/resource/resource_bundle.h"
131 #include "ui/resources/grit/ui_resources.h"
133 #if defined(OS_WIN)
134 #include "base/win/windows_version.h"
135 #include "chrome/browser/chrome_browser_main_win.h"
136 #include "sandbox/win/src/sandbox_policy.h"
137 #elif defined(OS_MACOSX)
138 #include "chrome/browser/chrome_browser_main_mac.h"
139 #include "chrome/browser/spellchecker/spellcheck_message_filter_mac.h"
140 #include "components/crash/app/breakpad_mac.h"
141 #elif defined(OS_CHROMEOS)
142 #include "chrome/browser/chromeos/chrome_browser_main_chromeos.h"
143 #include "chrome/browser/chromeos/drive/fileapi/file_system_backend_delegate.h"
144 #include "chrome/browser/chromeos/file_manager/app_id.h"
145 #include "chrome/browser/chromeos/file_system_provider/fileapi/backend_delegate.h"
146 #include "chrome/browser/chromeos/fileapi/file_system_backend.h"
147 #include "chrome/browser/chromeos/fileapi/mtp_file_system_backend_delegate.h"
148 #include "chrome/browser/chromeos/login/startup_utils.h"
149 #include "chrome/browser/chromeos/system/input_device_settings.h"
150 #include "chromeos/chromeos_switches.h"
151 #include "components/user_manager/user_manager.h"
152 #elif defined(OS_LINUX)
153 #include "chrome/browser/chrome_browser_main_linux.h"
154 #elif defined(OS_ANDROID)
155 #include "chrome/browser/android/new_tab_page_url_handler.h"
156 #include "chrome/browser/android/webapps/single_tab_mode_tab_helper.h"
157 #include "chrome/browser/chrome_browser_main_android.h"
158 #include "chrome/browser/media/protected_media_identifier_permission_context.h"
159 #include "chrome/browser/media/protected_media_identifier_permission_context_factory.h"
160 #include "chrome/common/descriptors_android.h"
161 #include "components/crash/browser/crash_dump_manager_android.h"
162 #elif defined(OS_POSIX)
163 #include "chrome/browser/chrome_browser_main_posix.h"
164 #endif
166 #if defined(OS_POSIX) && !defined(OS_MACOSX)
167 #include "base/debug/leak_annotations.h"
168 #include "components/crash/app/breakpad_linux.h"
169 #include "components/crash/browser/crash_handler_host_linux.h"
170 #endif
172 #if defined(OS_ANDROID)
173 #include "ui/base/ui_base_paths.h"
174 #include "ui/gfx/android/device_display_info.h"
175 #endif
177 #if defined(OS_ANDROID)
178 #include "chrome/browser/android/dev_tools_manager_delegate_android.h"
179 #else
180 #include "chrome/browser/devtools/chrome_devtools_manager_delegate.h"
181 #endif
183 #if !defined(OS_CHROMEOS)
184 #include "chrome/browser/signin/chrome_signin_client.h"
185 #include "chrome/browser/signin/chrome_signin_client_factory.h"
186 #include "chrome/browser/signin/signin_manager_factory.h"
187 #include "components/signin/core/browser/signin_manager.h"
188 #endif
190 #if defined(TOOLKIT_VIEWS)
191 #include "chrome/browser/ui/views/chrome_browser_main_extra_parts_views.h"
192 #endif
194 #if defined(USE_ATHENA)
195 #include "athena/content/public/web_contents_view_delegate_creator.h"
196 #include "chrome/browser/ui/views/athena/chrome_browser_main_extra_parts_athena.h"
197 #elif defined(USE_ASH)
198 #include "chrome/browser/ui/views/ash/chrome_browser_main_extra_parts_ash.h"
199 #endif
201 #if defined(USE_AURA)
202 #include "chrome/browser/ui/aura/chrome_browser_main_extra_parts_aura.h"
203 #endif
205 #if defined(USE_X11)
206 #include "chrome/browser/chrome_browser_main_extra_parts_x11.h"
207 #endif
209 #if defined(ENABLE_CAPTIVE_PORTAL_DETECTION)
210 #include "chrome/browser/captive_portal/captive_portal_tab_helper.h"
211 #endif
213 #if !defined(DISABLE_NACL)
214 #include "components/nacl/browser/nacl_browser.h"
215 #include "components/nacl/browser/nacl_host_message_filter.h"
216 #include "components/nacl/browser/nacl_process_host.h"
217 #include "components/nacl/common/nacl_process_type.h"
218 #include "components/nacl/common/nacl_switches.h"
219 #endif
221 #if defined(ENABLE_EXTENSIONS)
222 #include "chrome/browser/extensions/chrome_content_browser_client_extensions_part.h"
223 #include "chrome/browser/extensions/extension_service.h"
224 #include "chrome/browser/extensions/extension_util.h"
225 #include "chrome/browser/speech/extension_api/tts_engine_extension_api.h"
226 #include "extensions/browser/extension_system.h"
227 #include "extensions/browser/guest_view/guest_view_base.h"
228 #include "extensions/browser/guest_view/guest_view_manager.h"
229 #include "extensions/browser/guest_view/web_view/web_view_guest.h"
230 #include "extensions/browser/guest_view/web_view/web_view_permission_helper.h"
231 #include "extensions/browser/guest_view/web_view/web_view_renderer_state.h"
232 #include "extensions/common/constants.h"
233 #include "extensions/common/extension.h"
234 #include "extensions/common/extension_set.h"
235 #include "extensions/common/manifest_handlers/background_info.h"
236 #include "extensions/common/manifest_handlers/shared_module_info.h"
237 #include "extensions/common/permissions/permissions_data.h"
238 #include "extensions/common/permissions/socket_permission.h"
239 #include "extensions/common/switches.h"
240 #endif
242 #if defined(ENABLE_SPELLCHECK)
243 #include "chrome/browser/spellchecker/spellcheck_message_filter.h"
244 #endif
246 #if defined(ENABLE_WEBRTC)
247 #include "chrome/browser/media/webrtc_logging_handler_host.h"
248 #endif
250 using base::FileDescriptor;
251 using blink::WebWindowFeatures;
252 using content::AccessTokenStore;
253 using content::BrowserThread;
254 using content::BrowserURLHandler;
255 using content::ChildProcessSecurityPolicy;
256 using content::QuotaPermissionContext;
257 using content::RenderFrameHost;
258 using content::RenderViewHost;
259 using content::ResourceType;
260 using content::SiteInstance;
261 using content::WebContents;
262 using content::WebPreferences;
263 using message_center::NotifierId;
265 #if defined(OS_POSIX)
266 using content::FileDescriptorInfo;
267 #endif
269 #if defined(ENABLE_EXTENSIONS)
270 using extensions::APIPermission;
271 using extensions::ChromeContentBrowserClientExtensionsPart;
272 using extensions::Extension;
273 using extensions::InfoMap;
274 using extensions::Manifest;
275 #endif
277 namespace {
279 // Cached version of the locale so we can return the locale on the I/O
280 // thread.
281 base::LazyInstance<std::string> g_io_thread_application_locale;
283 #if defined(ENABLE_PLUGINS)
284 // TODO(teravest): Add renderer-side API-specific checking for these APIs so
285 // that blanket permission isn't granted to all dev channel APIs for these.
286 // http://crbug.com/386743
287 const char* const kPredefinedAllowedDevChannelOrigins[] = {
288 "6EAED1924DB611B6EEF2A664BD077BE7EAD33B8F", // see crbug.com/383937
289 "4EB74897CB187C7633357C2FE832E0AD6A44883A" // see crbug.com/383937
292 const char* const kPredefinedAllowedFileHandleOrigins[] = {
293 "6EAED1924DB611B6EEF2A664BD077BE7EAD33B8F", // see crbug.com/234789
294 "4EB74897CB187C7633357C2FE832E0AD6A44883A" // see crbug.com/234789
297 const char* const kPredefinedAllowedSocketOrigins[] = {
298 "okddffdblfhhnmhodogpojmfkjmhinfp", // Test SSH Client
299 "pnhechapfaindjhompbnflcldabbghjo", // HTerm App (SSH Client)
300 "bglhmjfplikpjnfoegeomebmfnkjomhe", // see crbug.com/122126
301 "gbchcmhmhahfdphkhkmpfmihenigjmpp", // Chrome Remote Desktop
302 "kgngmbheleoaphbjbaiobfdepmghbfah", // Pre-release Chrome Remote Desktop
303 "odkaodonbgfohohmklejpjiejmcipmib", // Dogfood Chrome Remote Desktop
304 "ojoimpklfciegopdfgeenehpalipignm", // Chromoting canary
305 "cbkkbcmdlboombapidmoeolnmdacpkch", // see crbug.com/129089
306 "hhnbmknkdabfoieppbbljkhkfjcmcbjh", // see crbug.com/134099
307 "mablfbjkhmhkmefkjjacnbaikjkipphg", // see crbug.com/134099
308 "pdeelgamlgannhelgoegilelnnojegoh", // see crbug.com/134099
309 "cabapfdbkniadpollkckdnedaanlciaj", // see crbug.com/134099
310 "mapljbgnjledlpdmlchihnmeclmefbba", // see crbug.com/134099
311 "ghbfeebgmiidnnmeobbbaiamklmpbpii", // see crbug.com/134099
312 "jdfhpkjeckflbbleddjlpimecpbjdeep", // see crbug.com/142514
313 "iabmpiboiopbgfabjmgeedhcmjenhbla", // see crbug.com/165080
314 "B7CF8A292249681AF81771650BA4CEEAF19A4560", // see crbug.com/165080
315 "7525AF4F66763A70A883C4700529F647B470E4D2", // see crbug.com/238084
316 "0B549507088E1564D672F7942EB87CA4DAD73972", // see crbug.com/238084
317 "864288364E239573E777D3E0E36864E590E95C74" // see crbug.com/238084
319 #endif
321 // Returns a copy of the given url with its host set to given host and path set
322 // to given path. Other parts of the url will be the same.
323 GURL ReplaceURLHostAndPath(const GURL& url,
324 const std::string& host,
325 const std::string& path) {
326 url::Replacements<char> replacements;
327 replacements.SetHost(host.c_str(), url::Component(0, host.length()));
328 replacements.SetPath(path.c_str(), url::Component(0, path.length()));
329 return url.ReplaceComponents(replacements);
332 // Maps "foo://bar/baz/" to "foo://chrome/bar/baz/".
333 GURL AddUberHost(const GURL& url) {
334 const std::string uber_host = chrome::kChromeUIUberHost;
335 const std::string new_path = url.host() + url.path();
337 return ReplaceURLHostAndPath(url, uber_host, new_path);
340 // If url->host() is "chrome" and url->path() has characters other than the
341 // first slash, changes the url from "foo://chrome/bar/" to "foo://bar/" and
342 // returns true. Otherwise returns false.
343 bool RemoveUberHost(GURL* url) {
344 if (url->host() != chrome::kChromeUIUberHost)
345 return false;
347 if (url->path().empty() || url->path() == "/")
348 return false;
350 const std::string old_path = url->path();
352 const std::string::size_type separator = old_path.find('/', 1);
353 std::string new_host;
354 std::string new_path;
355 if (separator == std::string::npos) {
356 new_host = old_path.substr(1);
357 } else {
358 new_host = old_path.substr(1, separator - 1);
359 new_path = old_path.substr(separator);
362 // Do not allow URLs with paths empty before the first slash since we can't
363 // have an empty host. (e.g "foo://chrome//")
364 if (new_host.empty())
365 return false;
367 *url = ReplaceURLHostAndPath(*url, new_host, new_path);
369 DCHECK(url->is_valid());
371 return true;
374 // Handles rewriting Web UI URLs.
375 bool HandleWebUI(GURL* url, content::BrowserContext* browser_context) {
376 // Do not handle special URLs such as "about:foo"
377 if (!url->host().empty()) {
378 const GURL chrome_url = AddUberHost(*url);
380 // Handle valid "chrome://chrome/foo" URLs so the reverse handler will
381 // be called.
382 if (ChromeWebUIControllerFactory::GetInstance()->UseWebUIForURL(
383 browser_context, chrome_url))
384 return true;
387 if (!ChromeWebUIControllerFactory::GetInstance()->UseWebUIForURL(
388 browser_context, *url))
389 return false;
391 #if defined(OS_CHROMEOS)
392 // Special case : in ChromeOS in Guest mode bookmarks and history are
393 // disabled for security reasons. New tab page explains the reasons, so
394 // we redirect user to new tab page.
395 if (user_manager::UserManager::Get()->IsLoggedInAsGuest()) {
396 if (url->SchemeIs(content::kChromeUIScheme) &&
397 (url->DomainIs(chrome::kChromeUIBookmarksHost) ||
398 url->DomainIs(chrome::kChromeUIHistoryHost))) {
399 // Rewrite with new tab URL
400 *url = GURL(chrome::kChromeUINewTabURL);
403 #endif
405 return true;
408 // Reverse URL handler for Web UI. Maps "chrome://chrome/foo/" to
409 // "chrome://foo/".
410 bool HandleWebUIReverse(GURL* url, content::BrowserContext* browser_context) {
411 if (!url->is_valid() || !url->SchemeIs(content::kChromeUIScheme))
412 return false;
414 return RemoveUberHost(url);
417 bool CertMatchesFilter(const net::X509Certificate& cert,
418 const base::DictionaryValue& filter) {
419 // TODO(markusheintz): This is the minimal required filter implementation.
420 // Implement a better matcher.
422 // An empty filter matches any client certificate since no requirements are
423 // specified at all.
424 if (filter.empty())
425 return true;
427 std::string common_name;
428 if (filter.GetString("ISSUER.CN", &common_name) &&
429 (cert.issuer().common_name == common_name)) {
430 return true;
432 return false;
435 #if defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_MACOSX)
436 breakpad::CrashHandlerHostLinux* CreateCrashHandlerHost(
437 const std::string& process_type) {
438 base::FilePath dumps_path;
439 PathService::Get(chrome::DIR_CRASH_DUMPS, &dumps_path);
441 ANNOTATE_SCOPED_MEMORY_LEAK;
442 bool upload = (getenv(env_vars::kHeadless) == NULL);
443 breakpad::CrashHandlerHostLinux* crash_handler =
444 new breakpad::CrashHandlerHostLinux(process_type, dumps_path, upload);
445 crash_handler->StartUploaderThread();
446 return crash_handler;
450 int GetCrashSignalFD(const CommandLine& command_line) {
451 // Extensions have the same process type as renderers.
452 if (command_line.HasSwitch(extensions::switches::kExtensionProcess)) {
453 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
454 if (!crash_handler)
455 crash_handler = CreateCrashHandlerHost("extension");
456 return crash_handler->GetDeathSignalSocket();
459 std::string process_type =
460 command_line.GetSwitchValueASCII(switches::kProcessType);
462 if (process_type == switches::kRendererProcess) {
463 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
464 if (!crash_handler)
465 crash_handler = CreateCrashHandlerHost(process_type);
466 return crash_handler->GetDeathSignalSocket();
469 if (process_type == switches::kPluginProcess) {
470 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
471 if (!crash_handler)
472 crash_handler = CreateCrashHandlerHost(process_type);
473 return crash_handler->GetDeathSignalSocket();
476 if (process_type == switches::kPpapiPluginProcess) {
477 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
478 if (!crash_handler)
479 crash_handler = CreateCrashHandlerHost(process_type);
480 return crash_handler->GetDeathSignalSocket();
483 if (process_type == switches::kGpuProcess) {
484 static breakpad::CrashHandlerHostLinux* crash_handler = NULL;
485 if (!crash_handler)
486 crash_handler = CreateCrashHandlerHost(process_type);
487 return crash_handler->GetDeathSignalSocket();
490 return -1;
492 #endif // defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_MACOSX)
494 #if !defined(OS_CHROMEOS)
495 GURL GetEffectiveURLForSignin(const GURL& url) {
496 CHECK(SigninManager::IsWebBasedSigninFlowURL(url));
498 GURL effective_url(SigninManager::kChromeSigninEffectiveSite);
499 // Copy the path because the argument to SetPathStr must outlive
500 // the Replacements object.
501 const std::string path_copy(url.path());
502 GURL::Replacements replacements;
503 replacements.SetPathStr(path_copy);
504 effective_url = effective_url.ReplaceComponents(replacements);
505 return effective_url;
507 #endif
509 void SetApplicationLocaleOnIOThread(const std::string& locale) {
510 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
511 g_io_thread_application_locale.Get() = locale;
514 void HandleBlockedPopupOnUIThread(const BlockedWindowParams& params) {
515 WebContents* tab = tab_util::GetWebContentsByID(params.render_process_id(),
516 params.opener_id());
517 if (!tab)
518 return;
520 prerender::PrerenderContents* prerender_contents =
521 prerender::PrerenderContents::FromWebContents(tab);
522 if (prerender_contents) {
523 prerender_contents->Destroy(prerender::FINAL_STATUS_CREATE_NEW_WINDOW);
524 return;
527 PopupBlockerTabHelper* popup_helper =
528 PopupBlockerTabHelper::FromWebContents(tab);
529 if (!popup_helper)
530 return;
531 popup_helper->AddBlockedPopup(params);
534 #if defined(OS_ANDROID)
536 void HandleSingleTabModeBlockOnUIThread(const BlockedWindowParams& params) {
537 WebContents* web_contents =
538 tab_util::GetWebContentsByID(params.render_process_id(),
539 params.opener_id());
540 if (!web_contents)
541 return;
543 SingleTabModeTabHelper::FromWebContents(web_contents)->HandleOpenUrl(params);
546 float GetDeviceScaleAdjustment() {
547 static const float kMinFSM = 1.05f;
548 static const int kWidthForMinFSM = 320;
549 static const float kMaxFSM = 1.3f;
550 static const int kWidthForMaxFSM = 800;
552 gfx::DeviceDisplayInfo info;
553 int minWidth = info.GetSmallestDIPWidth();
555 if (minWidth <= kWidthForMinFSM)
556 return kMinFSM;
557 if (minWidth >= kWidthForMaxFSM)
558 return kMaxFSM;
560 // The font scale multiplier varies linearly between kMinFSM and kMaxFSM.
561 float ratio = static_cast<float>(minWidth - kWidthForMinFSM) /
562 (kWidthForMaxFSM - kWidthForMinFSM);
563 return ratio * (kMaxFSM - kMinFSM) + kMinFSM;
566 #endif // defined(OS_ANDROID)
568 #if defined(ENABLE_EXTENSIONS)
569 // By default, JavaScript and images are enabled in guest content.
570 void GetGuestViewDefaultContentSettingRules(
571 bool incognito,
572 RendererContentSettingRules* rules) {
573 rules->image_rules.push_back(
574 ContentSettingPatternSource(ContentSettingsPattern::Wildcard(),
575 ContentSettingsPattern::Wildcard(),
576 CONTENT_SETTING_ALLOW,
577 std::string(),
578 incognito));
580 rules->script_rules.push_back(
581 ContentSettingPatternSource(ContentSettingsPattern::Wildcard(),
582 ContentSettingsPattern::Wildcard(),
583 CONTENT_SETTING_ALLOW,
584 std::string(),
585 incognito));
587 #endif // defined(ENALBE_EXTENSIONS)
589 } // namespace
591 namespace chrome {
593 ChromeContentBrowserClient::ChromeContentBrowserClient()
594 : prerender_tracker_(NULL),
595 weak_factory_(this) {
596 #if defined(ENABLE_PLUGINS)
597 for (size_t i = 0; i < arraysize(kPredefinedAllowedDevChannelOrigins); ++i)
598 allowed_dev_channel_origins_.insert(kPredefinedAllowedDevChannelOrigins[i]);
599 for (size_t i = 0; i < arraysize(kPredefinedAllowedFileHandleOrigins); ++i)
600 allowed_file_handle_origins_.insert(kPredefinedAllowedFileHandleOrigins[i]);
601 for (size_t i = 0; i < arraysize(kPredefinedAllowedSocketOrigins); ++i)
602 allowed_socket_origins_.insert(kPredefinedAllowedSocketOrigins[i]);
603 #endif
605 #if !defined(OS_ANDROID)
606 TtsExtensionEngine* tts_extension_engine = TtsExtensionEngine::GetInstance();
607 TtsController::GetInstance()->SetTtsEngineDelegate(tts_extension_engine);
608 #endif
610 #if defined(ENABLE_EXTENSIONS)
611 extra_parts_.push_back(new ChromeContentBrowserClientExtensionsPart);
612 #endif
615 ChromeContentBrowserClient::~ChromeContentBrowserClient() {
616 for (int i = static_cast<int>(extra_parts_.size()) - 1; i >= 0; --i)
617 delete extra_parts_[i];
618 extra_parts_.clear();
621 // static
622 void ChromeContentBrowserClient::RegisterProfilePrefs(
623 user_prefs::PrefRegistrySyncable* registry) {
624 registry->RegisterBooleanPref(
625 prefs::kDisable3DAPIs,
626 false,
627 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
628 registry->RegisterBooleanPref(
629 prefs::kEnableHyperlinkAuditing,
630 true,
631 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
632 registry->RegisterListPref(
633 prefs::kEnableDeprecatedWebPlatformFeatures,
634 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
637 // static
638 void ChromeContentBrowserClient::SetApplicationLocale(
639 const std::string& locale) {
640 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
642 // This object is guaranteed to outlive all threads so we don't have to
643 // worry about the lack of refcounting and can just post as Unretained.
645 // The common case is that this function is called early in Chrome startup
646 // before any threads are created (it will also be called later if the user
647 // changes the pref). In this case, there will be no threads created and
648 // posting will fail. When there are no threads, we can just set the string
649 // without worrying about threadsafety.
650 if (!BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
651 base::Bind(&SetApplicationLocaleOnIOThread, locale))) {
652 g_io_thread_application_locale.Get() = locale;
656 content::BrowserMainParts* ChromeContentBrowserClient::CreateBrowserMainParts(
657 const content::MainFunctionParams& parameters) {
658 ChromeBrowserMainParts* main_parts;
659 // Construct the Main browser parts based on the OS type.
660 #if defined(OS_WIN)
661 main_parts = new ChromeBrowserMainPartsWin(parameters);
662 #elif defined(OS_MACOSX)
663 main_parts = new ChromeBrowserMainPartsMac(parameters);
664 #elif defined(OS_CHROMEOS)
665 main_parts = new chromeos::ChromeBrowserMainPartsChromeos(parameters);
666 #elif defined(OS_LINUX)
667 main_parts = new ChromeBrowserMainPartsLinux(parameters);
668 #elif defined(OS_ANDROID)
669 main_parts = new ChromeBrowserMainPartsAndroid(parameters);
670 #elif defined(OS_POSIX)
671 main_parts = new ChromeBrowserMainPartsPosix(parameters);
672 #else
673 NOTREACHED();
674 main_parts = new ChromeBrowserMainParts(parameters);
675 #endif
677 chrome::AddProfilesExtraParts(main_parts);
679 // Construct additional browser parts. Stages are called in the order in
680 // which they are added.
681 #if defined(TOOLKIT_VIEWS)
682 main_parts->AddParts(new ChromeBrowserMainExtraPartsViews());
683 #endif
685 // TODO(oshima): Athena on chrome currently requires USE_ASH to build.
686 // We should reduce the dependency as much as possible.
687 #if defined(USE_ATHENA)
688 main_parts->AddParts(CreateChromeBrowserMainExtraPartsAthena());
689 #elif defined(USE_ASH)
690 main_parts->AddParts(new ChromeBrowserMainExtraPartsAsh());
691 #endif
693 #if defined(USE_AURA)
694 main_parts->AddParts(new ChromeBrowserMainExtraPartsAura());
695 #endif
697 #if defined(USE_X11)
698 main_parts->AddParts(new ChromeBrowserMainExtraPartsX11());
699 #endif
701 chrome::AddMetricsExtraParts(main_parts);
703 return main_parts;
706 std::string ChromeContentBrowserClient::GetStoragePartitionIdForSite(
707 content::BrowserContext* browser_context,
708 const GURL& site) {
709 std::string partition_id;
711 // The partition ID for webview guest processes is the string value of its
712 // SiteInstance URL - "chrome-guest://app_id/persist?partition".
713 if (site.SchemeIs(content::kGuestScheme)) {
714 partition_id = site.spec();
715 } else if (site.GetOrigin().spec() == kChromeUIChromeSigninURL) {
716 // Chrome signin page has an embedded iframe of extension and web content,
717 // thus it must be isolated from other webUI pages.
718 partition_id = site.GetOrigin().spec();
721 DCHECK(IsValidStoragePartitionId(browser_context, partition_id));
722 return partition_id;
725 bool ChromeContentBrowserClient::IsValidStoragePartitionId(
726 content::BrowserContext* browser_context,
727 const std::string& partition_id) {
728 // The default ID is empty and is always valid.
729 if (partition_id.empty())
730 return true;
732 return GURL(partition_id).is_valid();
735 void ChromeContentBrowserClient::GetStoragePartitionConfigForSite(
736 content::BrowserContext* browser_context,
737 const GURL& site,
738 bool can_be_default,
739 std::string* partition_domain,
740 std::string* partition_name,
741 bool* in_memory) {
742 // Default to the browser-wide storage partition and override based on |site|
743 // below.
744 partition_domain->clear();
745 partition_name->clear();
746 *in_memory = false;
748 bool success = false;
749 #if defined(ENABLE_EXTENSIONS)
750 success = extensions::WebViewGuest::GetGuestPartitionConfigForSite(
751 site, partition_domain, partition_name, in_memory);
753 if (!success && site.SchemeIs(extensions::kExtensionScheme)) {
754 // If |can_be_default| is false, the caller is stating that the |site|
755 // should be parsed as if it had isolated storage. In particular it is
756 // important to NOT check ExtensionService for the is_storage_isolated()
757 // attribute because this code path is run during Extension uninstall
758 // to do cleanup after the Extension has already been unloaded from the
759 // ExtensionService.
760 bool is_isolated = !can_be_default;
761 if (can_be_default) {
762 if (extensions::util::SiteHasIsolatedStorage(site, browser_context))
763 is_isolated = true;
766 if (is_isolated) {
767 CHECK(site.has_host());
768 // For extensions with isolated storage, the the host of the |site| is
769 // the |partition_domain|. The |in_memory| and |partition_name| are only
770 // used in guest schemes so they are cleared here.
771 *partition_domain = site.host();
772 *in_memory = false;
773 partition_name->clear();
775 success = true;
777 #endif
779 if (!success && (site.GetOrigin().spec() == kChromeUIChromeSigninURL)) {
780 // Chrome signin page has an embedded iframe of extension and web content,
781 // thus it must be isolated from other webUI pages.
782 *partition_domain = chrome::kChromeUIChromeSigninHost;
785 // Assert that if |can_be_default| is false, the code above must have found a
786 // non-default partition. If this fails, the caller has a serious logic
787 // error about which StoragePartition they expect to be in and it is not
788 // safe to continue.
789 CHECK(can_be_default || !partition_domain->empty());
792 content::WebContentsViewDelegate*
793 ChromeContentBrowserClient::GetWebContentsViewDelegate(
794 content::WebContents* web_contents) {
795 #if defined(USE_ATHENA)
796 return athena::CreateWebContentsViewDelegate(web_contents);
797 #else
798 return chrome::CreateWebContentsViewDelegate(web_contents);
799 #endif
802 void ChromeContentBrowserClient::RenderProcessWillLaunch(
803 content::RenderProcessHost* host) {
804 int id = host->GetID();
805 Profile* profile = Profile::FromBrowserContext(host->GetBrowserContext());
806 net::URLRequestContextGetter* context =
807 profile->GetRequestContextForRenderProcess(id);
809 host->AddFilter(new ChromeRenderMessageFilter(id, profile));
810 #if defined(ENABLE_PLUGINS)
811 host->AddFilter(new PluginInfoMessageFilter(id, profile));
812 #endif
813 host->AddFilter(new cast::CastTransportHostFilter);
814 #if defined(ENABLE_PRINTING)
815 host->AddFilter(new printing::PrintingMessageFilter(id, profile));
816 #endif
817 host->AddFilter(new SearchProviderInstallStateMessageFilter(id, profile));
818 #if defined(ENABLE_SPELLCHECK)
819 host->AddFilter(new SpellCheckMessageFilter(id));
820 #endif
821 #if defined(OS_MACOSX)
822 host->AddFilter(new SpellCheckMessageFilterMac(id));
823 #endif
824 host->AddFilter(new ChromeNetBenchmarkingMessageFilter(profile, context));
825 host->AddFilter(new prerender::PrerenderMessageFilter(id, profile));
826 host->AddFilter(new TtsMessageFilter(id, host->GetBrowserContext()));
827 #if defined(ENABLE_WEBRTC)
828 WebRtcLoggingHandlerHost* webrtc_logging_handler_host =
829 new WebRtcLoggingHandlerHost(profile);
830 host->SetWebRtcLogMessageCallback(base::Bind(
831 &WebRtcLoggingHandlerHost::LogMessage, webrtc_logging_handler_host));
832 host->AddFilter(webrtc_logging_handler_host);
833 host->SetUserData(host, new base::UserDataAdapter<WebRtcLoggingHandlerHost>(
834 webrtc_logging_handler_host));
835 #endif
836 #if !defined(DISABLE_NACL)
837 host->AddFilter(new nacl::NaClHostMessageFilter(
838 id, profile->IsOffTheRecord(),
839 profile->GetPath(),
840 context));
841 #endif
842 #if defined(OS_ANDROID)
843 host->AddFilter(new cdm::CdmMessageFilterAndroid());
844 #endif
845 if (switches::IsEnableAccountConsistency())
846 host->AddFilter(new PrincipalsMessageFilter(id));
848 host->Send(new ChromeViewMsg_SetIsIncognitoProcess(
849 profile->IsOffTheRecord()));
851 for (size_t i = 0; i < extra_parts_.size(); ++i)
852 extra_parts_[i]->RenderProcessWillLaunch(host);
854 RendererContentSettingRules rules;
855 if (host->IsIsolatedGuest()) {
856 #if defined(ENABLE_EXTENSIONS)
857 GetGuestViewDefaultContentSettingRules(profile->IsOffTheRecord(), &rules);
858 #else
859 NOTREACHED();
860 #endif
861 } else {
862 GetRendererContentSettingRules(
863 profile->GetHostContentSettingsMap(), &rules);
865 host->Send(new ChromeViewMsg_SetContentSettingRules(rules));
868 GURL ChromeContentBrowserClient::GetEffectiveURL(
869 content::BrowserContext* browser_context, const GURL& url) {
870 Profile* profile = Profile::FromBrowserContext(browser_context);
871 if (!profile)
872 return url;
874 // If the input |url| should be assigned to the Instant renderer, make its
875 // effective URL distinct from other URLs on the search provider's domain.
876 if (chrome::ShouldAssignURLToInstantRenderer(url, profile))
877 return chrome::GetEffectiveURLForInstant(url, profile);
879 #if !defined(OS_CHROMEOS)
880 // If the input |url| should be assigned to the Signin renderer, make its
881 // effective URL distinct from other URLs on the signin service's domain.
882 // Note that the signin renderer will be allowed to sign the user in to
883 // Chrome.
884 if (SigninManager::IsWebBasedSigninFlowURL(url))
885 return GetEffectiveURLForSignin(url);
886 #endif
888 #if defined(ENABLE_EXTENSIONS)
889 return ChromeContentBrowserClientExtensionsPart::GetEffectiveURL(
890 profile, url);
891 #else
892 return url;
893 #endif
896 bool ChromeContentBrowserClient::ShouldUseProcessPerSite(
897 content::BrowserContext* browser_context, const GURL& effective_url) {
898 // Non-extension, non-Instant URLs should generally use
899 // process-per-site-instance. Because we expect to use the effective URL,
900 // URLs for hosted apps (apart from bookmark apps) should have an extension
901 // scheme by now.
903 Profile* profile = Profile::FromBrowserContext(browser_context);
904 if (!profile)
905 return false;
907 if (chrome::ShouldUseProcessPerSiteForInstantURL(effective_url, profile))
908 return true;
910 #if !defined(OS_CHROMEOS)
911 if (SigninManager::IsWebBasedSigninFlowURL(effective_url))
912 return true;
913 #endif
915 #if defined(ENABLE_EXTENSIONS)
916 return ChromeContentBrowserClientExtensionsPart::ShouldUseProcessPerSite(
917 profile, effective_url);
918 #else
919 return false;
920 #endif
923 // These are treated as WebUI schemes but do not get WebUI bindings. Also,
924 // view-source is allowed for these schemes.
925 void ChromeContentBrowserClient::GetAdditionalWebUISchemes(
926 std::vector<std::string>* additional_schemes) {
927 additional_schemes->push_back(chrome::kChromeSearchScheme);
928 additional_schemes->push_back(dom_distiller::kDomDistillerScheme);
931 void ChromeContentBrowserClient::GetAdditionalWebUIHostsToIgnoreParititionCheck(
932 std::vector<std::string>* hosts) {
933 hosts->push_back(chrome::kChromeUIExtensionIconHost);
934 hosts->push_back(chrome::kChromeUIFaviconHost);
935 hosts->push_back(chrome::kChromeUIThemeHost);
936 hosts->push_back(chrome::kChromeUIThumbnailHost);
937 hosts->push_back(chrome::kChromeUIThumbnailHost2);
938 hosts->push_back(chrome::kChromeUIThumbnailListHost);
941 net::URLRequestContextGetter*
942 ChromeContentBrowserClient::CreateRequestContext(
943 content::BrowserContext* browser_context,
944 content::ProtocolHandlerMap* protocol_handlers,
945 content::URLRequestInterceptorScopedVector request_interceptors) {
946 Profile* profile = Profile::FromBrowserContext(browser_context);
947 return profile->CreateRequestContext(protocol_handlers,
948 request_interceptors.Pass());
951 net::URLRequestContextGetter*
952 ChromeContentBrowserClient::CreateRequestContextForStoragePartition(
953 content::BrowserContext* browser_context,
954 const base::FilePath& partition_path,
955 bool in_memory,
956 content::ProtocolHandlerMap* protocol_handlers,
957 content::URLRequestInterceptorScopedVector request_interceptors) {
958 Profile* profile = Profile::FromBrowserContext(browser_context);
959 return profile->CreateRequestContextForStoragePartition(
960 partition_path,
961 in_memory,
962 protocol_handlers,
963 request_interceptors.Pass());
966 bool ChromeContentBrowserClient::IsHandledURL(const GURL& url) {
967 return ProfileIOData::IsHandledURL(url);
970 bool ChromeContentBrowserClient::CanCommitURL(
971 content::RenderProcessHost* process_host,
972 const GURL& url) {
973 #if defined(ENABLE_EXTENSIONS)
974 return ChromeContentBrowserClientExtensionsPart::CanCommitURL(
975 process_host, url);
976 #else
977 return true;
978 #endif
981 bool ChromeContentBrowserClient::ShouldAllowOpenURL(
982 content::SiteInstance* site_instance, const GURL& url) {
983 GURL from_url = site_instance->GetSiteURL();
985 #if defined(ENABLE_EXTENSIONS)
986 bool result;
987 if (ChromeContentBrowserClientExtensionsPart::ShouldAllowOpenURL(
988 site_instance, from_url, url, &result))
989 return result;
990 #endif
992 // Do not allow chrome://chrome-signin navigate to other chrome:// URLs, since
993 // the signin page may host untrusted web content.
994 if (from_url.GetOrigin().spec() == chrome::kChromeUIChromeSigninURL &&
995 url.SchemeIs(content::kChromeUIScheme) &&
996 url.host() != chrome::kChromeUIChromeSigninHost) {
997 VLOG(1) << "Blocked navigation to " << url.spec() << " from "
998 << chrome::kChromeUIChromeSigninURL;
999 return false;
1002 return true;
1005 bool ChromeContentBrowserClient::IsSuitableHost(
1006 content::RenderProcessHost* process_host,
1007 const GURL& site_url) {
1008 Profile* profile =
1009 Profile::FromBrowserContext(process_host->GetBrowserContext());
1010 // This may be NULL during tests. In that case, just assume any site can
1011 // share any host.
1012 if (!profile)
1013 return true;
1015 // Instant URLs should only be in the instant process and instant process
1016 // should only have Instant URLs.
1017 InstantService* instant_service =
1018 InstantServiceFactory::GetForProfile(profile);
1019 if (instant_service) {
1020 bool is_instant_process = instant_service->IsInstantProcess(
1021 process_host->GetID());
1022 bool should_be_in_instant_process =
1023 chrome::ShouldAssignURLToInstantRenderer(site_url, profile);
1024 if (is_instant_process || should_be_in_instant_process)
1025 return is_instant_process && should_be_in_instant_process;
1028 #if !defined(OS_CHROMEOS)
1029 SigninClient* signin_client =
1030 ChromeSigninClientFactory::GetForProfile(profile);
1031 if (signin_client && signin_client->IsSigninProcess(process_host->GetID()))
1032 return SigninManager::IsWebBasedSigninFlowURL(site_url);
1033 #endif
1035 #if defined(ENABLE_EXTENSIONS)
1036 return ChromeContentBrowserClientExtensionsPart::IsSuitableHost(
1037 profile, process_host, site_url);
1038 #else
1039 return true;
1040 #endif
1043 bool ChromeContentBrowserClient::MayReuseHost(
1044 content::RenderProcessHost* process_host) {
1045 // If there is currently a prerender in progress for the host provided,
1046 // it may not be shared. We require prerenders to be by themselves in a
1047 // separate process, so that we can monitor their resource usage, and so that
1048 // we can track the cookies that they change.
1049 Profile* profile = Profile::FromBrowserContext(
1050 process_host->GetBrowserContext());
1051 prerender::PrerenderManager* prerender_manager =
1052 prerender::PrerenderManagerFactory::GetForProfile(profile);
1053 if (prerender_manager &&
1054 !prerender_manager->MayReuseProcessHost(process_host)) {
1055 return false;
1058 return true;
1061 bool ChromeContentBrowserClient::ShouldTryToUseExistingProcessHost(
1062 content::BrowserContext* browser_context, const GURL& url) {
1063 // It has to be a valid URL for us to check for an extension.
1064 if (!url.is_valid())
1065 return false;
1067 #if defined(ENABLE_EXTENSIONS)
1068 Profile* profile = Profile::FromBrowserContext(browser_context);
1069 return ChromeContentBrowserClientExtensionsPart::
1070 ShouldTryToUseExistingProcessHost(
1071 profile, url);
1072 #else
1073 return false;
1074 #endif
1077 void ChromeContentBrowserClient::SiteInstanceGotProcess(
1078 SiteInstance* site_instance) {
1079 CHECK(site_instance->HasProcess());
1081 Profile* profile = Profile::FromBrowserContext(
1082 site_instance->GetBrowserContext());
1083 if (!profile)
1084 return;
1086 // Remember the ID of the Instant process to signal the renderer process
1087 // on startup in |AppendExtraCommandLineSwitches| below.
1088 if (chrome::ShouldAssignURLToInstantRenderer(
1089 site_instance->GetSiteURL(), profile)) {
1090 InstantService* instant_service =
1091 InstantServiceFactory::GetForProfile(profile);
1092 if (instant_service)
1093 instant_service->AddInstantProcess(site_instance->GetProcess()->GetID());
1096 #if !defined(OS_CHROMEOS)
1097 // We only expect there to be one signin process as we use process-per-site
1098 // for signin URLs. The signin process will be cleared from SigninManager
1099 // when the renderer is destroyed.
1100 if (SigninManager::IsWebBasedSigninFlowURL(site_instance->GetSiteURL())) {
1101 SigninClient* signin_client =
1102 ChromeSigninClientFactory::GetForProfile(profile);
1103 if (signin_client)
1104 signin_client->SetSigninProcess(site_instance->GetProcess()->GetID());
1105 #if defined(ENABLE_EXTENSIONS)
1106 ChromeContentBrowserClientExtensionsPart::SetSigninProcess(site_instance);
1107 #endif
1109 #endif
1111 for (size_t i = 0; i < extra_parts_.size(); ++i)
1112 extra_parts_[i]->SiteInstanceGotProcess(site_instance);
1115 void ChromeContentBrowserClient::SiteInstanceDeleting(
1116 SiteInstance* site_instance) {
1117 if (!site_instance->HasProcess())
1118 return;
1120 for (size_t i = 0; i < extra_parts_.size(); ++i)
1121 extra_parts_[i]->SiteInstanceDeleting(site_instance);
1124 bool ChromeContentBrowserClient::ShouldSwapBrowsingInstancesForNavigation(
1125 SiteInstance* site_instance,
1126 const GURL& current_url,
1127 const GURL& new_url) {
1128 #if defined(ENABLE_EXTENSIONS)
1129 return ChromeContentBrowserClientExtensionsPart::
1130 ShouldSwapBrowsingInstancesForNavigation(
1131 site_instance, current_url, new_url);
1132 #else
1133 return false;
1134 #endif
1137 bool ChromeContentBrowserClient::ShouldSwapProcessesForRedirect(
1138 content::ResourceContext* resource_context, const GURL& current_url,
1139 const GURL& new_url) {
1140 #if defined(ENABLE_EXTENSIONS)
1141 return ChromeContentBrowserClientExtensionsPart::
1142 ShouldSwapProcessesForRedirect(resource_context, current_url, new_url);
1143 #else
1144 return false;
1145 #endif
1148 bool ChromeContentBrowserClient::ShouldAssignSiteForURL(const GURL& url) {
1149 return !url.SchemeIs(chrome::kChromeNativeScheme);
1152 std::string ChromeContentBrowserClient::GetCanonicalEncodingNameByAliasName(
1153 const std::string& alias_name) {
1154 return CharacterEncoding::GetCanonicalEncodingNameByAliasName(alias_name);
1157 namespace {
1159 bool IsAutoReloadEnabled() {
1160 // Fetch the field trial, even though we don't use it. Calling FindFullName()
1161 // causes the field-trial mechanism to report which group we're in, which
1162 // might reflect a hard disable or hard enable via flag, both of which have
1163 // their own field trial groups. This lets us know what percentage of users
1164 // manually enable or disable auto-reload.
1165 std::string group = base::FieldTrialList::FindFullName(
1166 "AutoReloadExperiment");
1167 const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
1168 if (browser_command_line.HasSwitch(switches::kEnableOfflineAutoReload))
1169 return true;
1170 if (browser_command_line.HasSwitch(switches::kDisableOfflineAutoReload))
1171 return false;
1172 return true;
1175 bool IsAutoReloadVisibleOnlyEnabled() {
1176 // See the block comment in IsAutoReloadEnabled().
1177 std::string group = base::FieldTrialList::FindFullName(
1178 "AutoReloadVisibleOnlyExperiment");
1179 const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
1180 if (browser_command_line.HasSwitch(
1181 switches::kEnableOfflineAutoReloadVisibleOnly)) {
1182 return true;
1184 if (browser_command_line.HasSwitch(
1185 switches::kDisableOfflineAutoReloadVisibleOnly)) {
1186 return false;
1188 return true;
1191 } // namespace
1193 void ChromeContentBrowserClient::AppendExtraCommandLineSwitches(
1194 CommandLine* command_line, int child_process_id) {
1195 #if defined(OS_POSIX)
1196 if (breakpad::IsCrashReporterEnabled()) {
1197 scoped_ptr<metrics::ClientInfo> client_info =
1198 GoogleUpdateSettings::LoadMetricsClientInfo();
1199 command_line->AppendSwitchASCII(switches::kEnableCrashReporter,
1200 client_info ? client_info->client_id
1201 : std::string());
1203 #endif // defined(OS_POSIX)
1205 if (logging::DialogsAreSuppressed())
1206 command_line->AppendSwitch(switches::kNoErrorDialogs);
1208 std::string process_type =
1209 command_line->GetSwitchValueASCII(switches::kProcessType);
1210 const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
1212 static const char* const kCommonSwitchNames[] = {
1213 switches::kUserAgent,
1214 switches::kUserDataDir, // Make logs go to the right file.
1216 command_line->CopySwitchesFrom(browser_command_line, kCommonSwitchNames,
1217 arraysize(kCommonSwitchNames));
1219 #if defined(ENABLE_IPC_FUZZER)
1220 static const char* const kIpcFuzzerSwitches[] = {
1221 switches::kIpcFuzzerTestcase,
1223 command_line->CopySwitchesFrom(browser_command_line, kIpcFuzzerSwitches,
1224 arraysize(kIpcFuzzerSwitches));
1225 #endif
1227 #if defined(OS_CHROMEOS)
1228 // On Chrome OS need to pass primary user homedir (in multi-profiles session).
1229 base::FilePath homedir;
1230 PathService::Get(base::DIR_HOME, &homedir);
1231 command_line->AppendSwitchASCII(chromeos::switches::kHomedir,
1232 homedir.value().c_str());
1233 #endif
1235 if (process_type == switches::kRendererProcess) {
1236 content::RenderProcessHost* process =
1237 content::RenderProcessHost::FromID(child_process_id);
1238 Profile* profile =
1239 process ? Profile::FromBrowserContext(process->GetBrowserContext())
1240 : NULL;
1241 for (size_t i = 0; i < extra_parts_.size(); ++i) {
1242 extra_parts_[i]->AppendExtraRendererCommandLineSwitches(
1243 command_line, process, profile);
1246 #if defined(OS_CHROMEOS)
1247 const std::string& login_profile =
1248 browser_command_line.GetSwitchValueASCII(
1249 chromeos::switches::kLoginProfile);
1250 if (!login_profile.empty())
1251 command_line->AppendSwitchASCII(
1252 chromeos::switches::kLoginProfile, login_profile);
1253 #endif
1255 #if defined(ENABLE_WEBRTC)
1256 MaybeCopyDisableWebRtcEncryptionSwitch(command_line,
1257 browser_command_line,
1258 VersionInfo::GetChannel());
1259 #endif
1261 if (process) {
1262 PrefService* prefs = profile->GetPrefs();
1263 // Currently this pref is only registered if applied via a policy.
1264 if (prefs->HasPrefPath(prefs::kDisable3DAPIs) &&
1265 prefs->GetBoolean(prefs::kDisable3DAPIs)) {
1266 // Turn this policy into a command line switch.
1267 command_line->AppendSwitch(switches::kDisable3DAPIs);
1270 const base::ListValue* switches =
1271 prefs->GetList(prefs::kEnableDeprecatedWebPlatformFeatures);
1272 if (switches) {
1273 // Enable any deprecated features that have been re-enabled by policy.
1274 for (base::ListValue::const_iterator it = switches->begin();
1275 it != switches->end(); ++it) {
1276 std::string switch_to_enable;
1277 if ((*it)->GetAsString(&switch_to_enable))
1278 command_line->AppendSwitch(switch_to_enable);
1282 // Disable client-side phishing detection in the renderer if it is
1283 // disabled in the Profile preferences or the browser process.
1284 if (!prefs->GetBoolean(prefs::kSafeBrowsingEnabled) ||
1285 !g_browser_process->safe_browsing_detection_service()) {
1286 command_line->AppendSwitch(
1287 switches::kDisableClientSidePhishingDetection);
1290 if (prefs->GetBoolean(prefs::kPrintPreviewDisabled))
1291 command_line->AppendSwitch(switches::kDisablePrintPreview);
1293 InstantService* instant_service =
1294 InstantServiceFactory::GetForProfile(profile);
1295 if (instant_service &&
1296 instant_service->IsInstantProcess(process->GetID()))
1297 command_line->AppendSwitch(switches::kInstantProcess);
1299 #if !defined(OS_CHROMEOS)
1300 SigninClient* signin_client =
1301 ChromeSigninClientFactory::GetForProfile(profile);
1302 if (signin_client && signin_client->IsSigninProcess(process->GetID()))
1303 command_line->AppendSwitch(switches::kSigninProcess);
1304 #endif
1307 if (IsAutoReloadEnabled())
1308 command_line->AppendSwitch(switches::kEnableOfflineAutoReload);
1309 if (IsAutoReloadVisibleOnlyEnabled()) {
1310 command_line->AppendSwitch(
1311 switches::kEnableOfflineAutoReloadVisibleOnly);
1315 // Enable load stale cache if this session is in the field trial or
1316 // the user explicitly enabled it. Note that as far as the renderer
1317 // is concerned, the feature is enabled if-and-only-if the
1318 // kEnableOfflineLoadStaleCache flag is on the command line;
1319 // the yes/no/default behavior is only at the browser command line
1320 // level.
1322 // Command line switches override
1323 if (browser_command_line.HasSwitch(
1324 switches::kEnableOfflineLoadStaleCache)) {
1325 command_line->AppendSwitch(switches::kEnableOfflineLoadStaleCache);
1326 } else if (!browser_command_line.HasSwitch(
1327 switches::kDisableOfflineLoadStaleCache)) {
1328 std::string group =
1329 base::FieldTrialList::FindFullName("LoadStaleCacheExperiment");
1331 if (group == "Enabled")
1332 command_line->AppendSwitch(switches::kEnableOfflineLoadStaleCache);
1336 // Please keep this in alphabetical order.
1337 static const char* const kSwitchNames[] = {
1338 autofill::switches::kDisableIgnoreAutocompleteOff,
1339 autofill::switches::kDisablePasswordGeneration,
1340 autofill::switches::kEnablePasswordGeneration,
1341 autofill::switches::kLocalHeuristicsOnlyForPasswordGeneration,
1342 #if defined(ENABLE_EXTENSIONS)
1343 extensions::switches::kAllowHTTPBackgroundPage,
1344 extensions::switches::kAllowLegacyExtensionManifests,
1345 extensions::switches::kEnableAppWindowControls,
1346 extensions::switches::kEnableEmbeddedExtensionOptions,
1347 extensions::switches::kEnableExperimentalExtensionApis,
1348 extensions::switches::kEnableScriptsRequireAction,
1349 extensions::switches::kExtensionsOnChromeURLs,
1350 extensions::switches::kWhitelistedExtensionID,
1351 #endif
1352 switches::kAppsCheckoutURL,
1353 switches::kAppsGalleryURL,
1354 switches::kCloudPrintURL,
1355 switches::kCloudPrintXmppEndpoint,
1356 switches::kDisableBundledPpapiFlash,
1357 switches::kEnableBenchmarking,
1358 switches::kEnableNaCl,
1359 #if !defined(DISABLE_NACL)
1360 switches::kEnableNaClDebug,
1361 switches::kEnableNaClNonSfiMode,
1362 #endif
1363 switches::kEnableNetBenchmarking,
1364 switches::kEnableShowModalDialog,
1365 switches::kEnableStreamlinedHostedApps,
1366 switches::kEnableWebBasedSignin,
1367 switches::kJavaScriptHarmony,
1368 switches::kMessageLoopHistogrammer,
1369 switches::kOutOfProcessPdf,
1370 switches::kPlaybackMode,
1371 switches::kPpapiFlashArgs,
1372 switches::kPpapiFlashPath,
1373 switches::kPpapiFlashVersion,
1374 switches::kProfilingAtStart,
1375 switches::kProfilingFile,
1376 switches::kProfilingFlush,
1377 switches::kRecordMode,
1378 translate::switches::kTranslateSecurityOrigin,
1381 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1382 arraysize(kSwitchNames));
1383 } else if (process_type == switches::kUtilityProcess) {
1384 #if defined(ENABLE_EXTENSIONS)
1385 static const char* const kSwitchNames[] = {
1386 extensions::switches::kAllowHTTPBackgroundPage,
1387 extensions::switches::kEnableExperimentalExtensionApis,
1388 extensions::switches::kExtensionsOnChromeURLs,
1389 extensions::switches::kWhitelistedExtensionID,
1392 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1393 arraysize(kSwitchNames));
1394 #endif
1395 } else if (process_type == switches::kPluginProcess) {
1396 #if defined(OS_CHROMEOS)
1397 static const char* const kSwitchNames[] = {
1398 chromeos::switches::kLoginProfile,
1401 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1402 arraysize(kSwitchNames));
1403 #endif
1404 } else if (process_type == switches::kZygoteProcess) {
1405 static const char* const kSwitchNames[] = {
1406 // Load (in-process) Pepper plugins in-process in the zygote pre-sandbox.
1407 switches::kDisableBundledPpapiFlash,
1408 #if !defined(DISABLE_NACL)
1409 switches::kEnableNaClNonSfiMode,
1410 switches::kNaClDangerousNoSandboxNonSfi,
1411 #endif
1412 switches::kPpapiFlashPath,
1413 switches::kPpapiFlashVersion,
1416 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1417 arraysize(kSwitchNames));
1418 } else if (process_type == switches::kGpuProcess) {
1419 // If --ignore-gpu-blacklist is passed in, don't send in crash reports
1420 // because GPU is expected to be unreliable.
1421 if (browser_command_line.HasSwitch(switches::kIgnoreGpuBlacklist) &&
1422 !command_line->HasSwitch(switches::kDisableBreakpad))
1423 command_line->AppendSwitch(switches::kDisableBreakpad);
1426 // The command line switch kEnableBenchmarking needs to be specified along
1427 // with the kEnableStatsTable switch to ensure that the stats table global
1428 // is initialized correctly.
1429 if (command_line->HasSwitch(switches::kEnableBenchmarking))
1430 DCHECK(command_line->HasSwitch(switches::kEnableStatsTable));
1433 std::string ChromeContentBrowserClient::GetApplicationLocale() {
1434 if (BrowserThread::CurrentlyOn(BrowserThread::IO))
1435 return g_io_thread_application_locale.Get();
1436 return g_browser_process->GetApplicationLocale();
1439 std::string ChromeContentBrowserClient::GetAcceptLangs(
1440 content::BrowserContext* context) {
1441 Profile* profile = Profile::FromBrowserContext(context);
1442 return profile->GetPrefs()->GetString(prefs::kAcceptLanguages);
1445 const gfx::ImageSkia* ChromeContentBrowserClient::GetDefaultFavicon() {
1446 ResourceBundle& rb = ResourceBundle::GetSharedInstance();
1447 return rb.GetNativeImageNamed(IDR_DEFAULT_FAVICON).ToImageSkia();
1450 bool ChromeContentBrowserClient::AllowAppCache(
1451 const GURL& manifest_url,
1452 const GURL& first_party,
1453 content::ResourceContext* context) {
1454 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1455 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1456 return io_data->GetCookieSettings()->
1457 IsSettingCookieAllowed(manifest_url, first_party);
1460 bool ChromeContentBrowserClient::AllowServiceWorker(
1461 const GURL& scope,
1462 const GURL& first_party_url,
1463 content::ResourceContext* context) {
1464 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1465 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1466 return io_data->GetCookieSettings()->
1467 IsSettingCookieAllowed(scope, first_party_url);
1470 bool ChromeContentBrowserClient::AllowGetCookie(
1471 const GURL& url,
1472 const GURL& first_party,
1473 const net::CookieList& cookie_list,
1474 content::ResourceContext* context,
1475 int render_process_id,
1476 int render_frame_id) {
1477 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1478 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1479 bool allow = io_data->GetCookieSettings()->
1480 IsReadingCookieAllowed(url, first_party);
1482 BrowserThread::PostTask(
1483 BrowserThread::UI, FROM_HERE,
1484 base::Bind(&TabSpecificContentSettings::CookiesRead, render_process_id,
1485 render_frame_id, url, first_party, cookie_list, !allow, true));
1486 return allow;
1489 bool ChromeContentBrowserClient::AllowSetCookie(
1490 const GURL& url,
1491 const GURL& first_party,
1492 const std::string& cookie_line,
1493 content::ResourceContext* context,
1494 int render_process_id,
1495 int render_frame_id,
1496 net::CookieOptions* options) {
1497 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1498 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1499 CookieSettings* cookie_settings = io_data->GetCookieSettings();
1500 bool allow = cookie_settings->IsSettingCookieAllowed(url, first_party);
1502 if (prerender_tracker_) {
1503 prerender_tracker_->OnCookieChangedForURL(
1504 render_process_id,
1505 context->GetRequestContext()->cookie_store()->GetCookieMonster(),
1506 url);
1509 BrowserThread::PostTask(
1510 BrowserThread::UI, FROM_HERE,
1511 base::Bind(&TabSpecificContentSettings::CookieChanged, render_process_id,
1512 render_frame_id, url, first_party, cookie_line, *options,
1513 !allow));
1514 return allow;
1517 bool ChromeContentBrowserClient::AllowSaveLocalState(
1518 content::ResourceContext* context) {
1519 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1520 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1521 CookieSettings* cookie_settings = io_data->GetCookieSettings();
1522 ContentSetting setting = cookie_settings->GetDefaultCookieSetting(NULL);
1524 // TODO(bauerb): Should we also disallow local state if the default is BLOCK?
1525 // Could we even support per-origin settings?
1526 return setting != CONTENT_SETTING_SESSION_ONLY;
1529 bool ChromeContentBrowserClient::AllowWorkerDatabase(
1530 const GURL& url,
1531 const base::string16& name,
1532 const base::string16& display_name,
1533 unsigned long estimated_size,
1534 content::ResourceContext* context,
1535 const std::vector<std::pair<int, int> >& render_frames) {
1536 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1537 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1538 CookieSettings* cookie_settings = io_data->GetCookieSettings();
1539 bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1541 // Record access to database for potential display in UI.
1542 std::vector<std::pair<int, int> >::const_iterator i;
1543 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1544 BrowserThread::PostTask(
1545 BrowserThread::UI, FROM_HERE,
1546 base::Bind(&TabSpecificContentSettings::WebDatabaseAccessed,
1547 i->first, i->second, url, name, display_name, !allow));
1550 return allow;
1553 void ChromeContentBrowserClient::AllowWorkerFileSystem(
1554 const GURL& url,
1555 content::ResourceContext* context,
1556 const std::vector<std::pair<int, int> >& render_frames,
1557 base::Callback<void(bool)> callback) {
1558 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1559 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1560 CookieSettings* cookie_settings = io_data->GetCookieSettings();
1561 bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1563 #if defined(ENABLE_EXTENSIONS)
1564 GuestPermissionRequestHelper(url, render_frames, callback, allow);
1565 #else
1566 FileSystemAccessed(url, render_frames, callback, allow);
1567 #endif
1570 #if defined(ENABLE_EXTENSIONS)
1571 void ChromeContentBrowserClient::GuestPermissionRequestHelper(
1572 const GURL& url,
1573 const std::vector<std::pair<int, int> >& render_frames,
1574 base::Callback<void(bool)> callback,
1575 bool allow) {
1576 DCHECK(BrowserThread:: CurrentlyOn(BrowserThread::IO));
1577 std::vector<std::pair<int, int> >::const_iterator i;
1578 std::map<int, int> process_map;
1579 std::map<int, int>::const_iterator it;
1580 bool has_web_view_guest = false;
1581 // Record access to file system for potential display in UI.
1582 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1583 if (process_map.find(i->first) != process_map.end())
1584 continue;
1586 process_map.insert(std::pair<int, int>(i->first, i->second));
1588 if (extensions::WebViewRendererState::GetInstance()->IsGuest(i->first))
1589 has_web_view_guest = true;
1591 if (!has_web_view_guest) {
1592 FileSystemAccessed(url, render_frames, callback, allow);
1593 return;
1595 DCHECK_EQ(1U, process_map.size());
1596 it = process_map.begin();
1597 BrowserThread::PostTask(
1598 BrowserThread::UI,
1599 FROM_HERE,
1600 base::Bind(&ChromeContentBrowserClient::
1601 RequestFileSystemPermissionOnUIThread,
1602 it->first,
1603 it->second,
1604 url,
1605 allow,
1606 base::Bind(&ChromeContentBrowserClient::FileSystemAccessed,
1607 weak_factory_.GetWeakPtr(),
1608 url,
1609 render_frames,
1610 callback)));
1613 void ChromeContentBrowserClient::RequestFileSystemPermissionOnUIThread(
1614 int render_process_id,
1615 int render_frame_id,
1616 const GURL& url,
1617 bool allowed_by_default,
1618 const base::Callback<void(bool)>& callback) {
1619 DCHECK(BrowserThread:: CurrentlyOn(BrowserThread::UI));
1620 extensions::WebViewPermissionHelper* web_view_permission_helper =
1621 extensions::WebViewPermissionHelper::FromFrameID(
1622 render_process_id, render_frame_id);
1623 web_view_permission_helper->RequestFileSystemPermission(url,
1624 allowed_by_default,
1625 callback);
1627 #endif
1629 void ChromeContentBrowserClient::FileSystemAccessed(
1630 const GURL& url,
1631 const std::vector<std::pair<int, int> >& render_frames,
1632 base::Callback<void(bool)> callback,
1633 bool allow) {
1634 // Record access to file system for potential display in UI.
1635 std::vector<std::pair<int, int> >::const_iterator i;
1636 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1637 BrowserThread::PostTask(
1638 BrowserThread::UI,
1639 FROM_HERE,
1640 base::Bind(&TabSpecificContentSettings::FileSystemAccessed,
1641 i->first, i->second, url, !allow));
1643 callback.Run(allow);
1646 bool ChromeContentBrowserClient::AllowWorkerIndexedDB(
1647 const GURL& url,
1648 const base::string16& name,
1649 content::ResourceContext* context,
1650 const std::vector<std::pair<int, int> >& render_frames) {
1651 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1652 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1653 CookieSettings* cookie_settings = io_data->GetCookieSettings();
1654 bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1656 // Record access to IndexedDB for potential display in UI.
1657 std::vector<std::pair<int, int> >::const_iterator i;
1658 for (i = render_frames.begin(); i != render_frames.end(); ++i) {
1659 BrowserThread::PostTask(
1660 BrowserThread::UI, FROM_HERE,
1661 base::Bind(&TabSpecificContentSettings::IndexedDBAccessed,
1662 i->first, i->second, url, name, !allow));
1665 return allow;
1668 net::URLRequestContext*
1669 ChromeContentBrowserClient::OverrideRequestContextForURL(
1670 const GURL& url, content::ResourceContext* context) {
1671 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1672 #if defined(ENABLE_EXTENSIONS)
1673 if (url.SchemeIs(extensions::kExtensionScheme)) {
1674 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1675 return io_data->extensions_request_context();
1677 #endif
1679 return NULL;
1682 QuotaPermissionContext*
1683 ChromeContentBrowserClient::CreateQuotaPermissionContext() {
1684 return new ChromeQuotaPermissionContext();
1687 void ChromeContentBrowserClient::AllowCertificateError(
1688 int render_process_id,
1689 int render_frame_id,
1690 int cert_error,
1691 const net::SSLInfo& ssl_info,
1692 const GURL& request_url,
1693 ResourceType resource_type,
1694 bool overridable,
1695 bool strict_enforcement,
1696 bool expired_previous_decision,
1697 const base::Callback<void(bool)>& callback,
1698 content::CertificateRequestResultType* result) {
1699 if (resource_type != content::RESOURCE_TYPE_MAIN_FRAME) {
1700 // A sub-resource has a certificate error. The user doesn't really
1701 // have a context for making the right decision, so block the
1702 // request hard, without an info bar to allow showing the insecure
1703 // content.
1704 *result = content::CERTIFICATE_REQUEST_RESULT_TYPE_DENY;
1705 return;
1708 // If the tab is being prerendered, cancel the prerender and the request.
1709 content::RenderFrameHost* render_frame_host =
1710 content::RenderFrameHost::FromID(render_process_id, render_frame_id);
1711 WebContents* tab = WebContents::FromRenderFrameHost(render_frame_host);
1712 if (!tab) {
1713 NOTREACHED();
1714 return;
1717 prerender::PrerenderContents* prerender_contents =
1718 prerender::PrerenderContents::FromWebContents(tab);
1719 if (prerender_contents) {
1720 prerender_contents->Destroy(prerender::FINAL_STATUS_SSL_ERROR);
1721 *result = content::CERTIFICATE_REQUEST_RESULT_TYPE_CANCEL;
1722 return;
1725 #if defined(ENABLE_CAPTIVE_PORTAL_DETECTION)
1726 CaptivePortalTabHelper* captive_portal_tab_helper =
1727 CaptivePortalTabHelper::FromWebContents(tab);
1728 if (captive_portal_tab_helper)
1729 captive_portal_tab_helper->OnSSLCertError(ssl_info);
1730 #endif
1732 // Otherwise, display an SSL blocking page. The interstitial page takes
1733 // ownership of ssl_blocking_page.
1734 int options_mask = 0;
1735 if (overridable)
1736 options_mask |= SSLBlockingPage::OVERRIDABLE;
1737 if (strict_enforcement)
1738 options_mask |= SSLBlockingPage::STRICT_ENFORCEMENT;
1739 if (expired_previous_decision)
1740 options_mask |= SSLBlockingPage::EXPIRED_BUT_PREVIOUSLY_ALLOWED;
1741 SSLBlockingPage* ssl_blocking_page = new SSLBlockingPage(
1742 tab, cert_error, ssl_info, request_url, options_mask, callback);
1743 ssl_blocking_page->Show();
1746 void ChromeContentBrowserClient::SelectClientCertificate(
1747 int render_process_id,
1748 int render_frame_id,
1749 net::SSLCertRequestInfo* cert_request_info,
1750 const base::Callback<void(net::X509Certificate*)>& callback) {
1751 content::RenderFrameHost* rfh = content::RenderFrameHost::FromID(
1752 render_process_id, render_frame_id);
1753 WebContents* tab = WebContents::FromRenderFrameHost(rfh);
1754 if (!tab) {
1755 // TODO(davidben): This makes the request hang, but returning no certificate
1756 // also breaks. It should abort the request. See https://crbug.com/417092
1757 return;
1760 prerender::PrerenderContents* prerender_contents =
1761 prerender::PrerenderContents::FromWebContents(tab);
1762 if (prerender_contents) {
1763 prerender_contents->Destroy(
1764 prerender::FINAL_STATUS_SSL_CLIENT_CERTIFICATE_REQUESTED);
1765 return;
1768 GURL requesting_url("https://" + cert_request_info->host_and_port.ToString());
1769 DCHECK(requesting_url.is_valid())
1770 << "Invalid URL string: https://"
1771 << cert_request_info->host_and_port.ToString();
1773 Profile* profile = Profile::FromBrowserContext(tab->GetBrowserContext());
1774 scoped_ptr<base::Value> filter =
1775 profile->GetHostContentSettingsMap()->GetWebsiteSetting(
1776 requesting_url,
1777 requesting_url,
1778 CONTENT_SETTINGS_TYPE_AUTO_SELECT_CERTIFICATE,
1779 std::string(),
1780 NULL);
1782 if (filter.get()) {
1783 // Try to automatically select a client certificate.
1784 if (filter->IsType(base::Value::TYPE_DICTIONARY)) {
1785 base::DictionaryValue* filter_dict =
1786 static_cast<base::DictionaryValue*>(filter.get());
1788 const std::vector<scoped_refptr<net::X509Certificate> >&
1789 all_client_certs = cert_request_info->client_certs;
1790 for (size_t i = 0; i < all_client_certs.size(); ++i) {
1791 if (CertMatchesFilter(*all_client_certs[i].get(), *filter_dict)) {
1792 // Use the first certificate that is matched by the filter.
1793 callback.Run(all_client_certs[i].get());
1794 return;
1797 } else {
1798 NOTREACHED();
1802 chrome::ShowSSLClientCertificateSelector(tab, cert_request_info, callback);
1805 void ChromeContentBrowserClient::AddCertificate(
1806 net::CertificateMimeType cert_type,
1807 const void* cert_data,
1808 size_t cert_size,
1809 int render_process_id,
1810 int render_frame_id) {
1811 chrome::SSLAddCertificate(cert_type, cert_data, cert_size,
1812 render_process_id, render_frame_id);
1815 content::MediaObserver* ChromeContentBrowserClient::GetMediaObserver() {
1816 return MediaCaptureDevicesDispatcher::GetInstance();
1819 void ChromeContentBrowserClient::RequestDesktopNotificationPermission(
1820 const GURL& source_origin,
1821 content::RenderFrameHost* render_frame_host,
1822 const base::Callback<void(blink::WebNotificationPermission)>& callback) {
1823 #if defined(ENABLE_NOTIFICATIONS)
1824 // Skip showing the infobar if the request comes from an extension, and that
1825 // extension has the 'notify' permission. (If the extension does not have the
1826 // permission, the user will still be prompted.)
1827 Profile* profile = Profile::FromBrowserContext(
1828 render_frame_host->GetSiteInstance()->GetBrowserContext());
1829 DesktopNotificationService* notification_service =
1830 DesktopNotificationServiceFactory::GetForProfile(profile);
1831 WebContents* web_contents = WebContents::FromRenderFrameHost(
1832 render_frame_host);
1833 int render_process_id = render_frame_host->GetProcess()->GetID();
1834 const PermissionRequestID request_id(render_process_id,
1835 web_contents->GetRoutingID(),
1836 -1 /* bridge id */,
1837 GURL());
1839 notification_service->RequestNotificationPermission(
1840 web_contents,
1841 request_id,
1842 source_origin,
1843 // TODO(peter): plumb user_gesture over IPC
1844 true,
1845 callback);
1847 #else
1848 NOTIMPLEMENTED();
1849 #endif
1852 blink::WebNotificationPermission
1853 ChromeContentBrowserClient::CheckDesktopNotificationPermission(
1854 const GURL& source_origin,
1855 content::ResourceContext* context,
1856 int render_process_id) {
1857 #if defined(ENABLE_NOTIFICATIONS)
1858 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1860 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1861 #if defined(ENABLE_EXTENSIONS)
1862 InfoMap* extension_info_map = io_data->GetExtensionInfoMap();
1864 // We want to see if there is an extension that hasn't been manually disabled
1865 // that has the notifications permission and applies to this security origin.
1866 // First, get the list of extensions with permission for the origin.
1867 extensions::ExtensionSet extensions;
1868 extension_info_map->GetExtensionsWithAPIPermissionForSecurityOrigin(
1869 source_origin,
1870 render_process_id,
1871 extensions::APIPermission::kNotifications,
1872 &extensions);
1873 for (extensions::ExtensionSet::const_iterator iter = extensions.begin();
1874 iter != extensions.end(); ++iter) {
1875 // Then, check to see if it's been disabled by the user.
1876 if (!extension_info_map->AreNotificationsDisabled((*iter)->id()))
1877 return blink::WebNotificationPermissionAllowed;
1879 #endif
1881 // No enabled extensions exist, so check the normal host content settings.
1882 HostContentSettingsMap* host_content_settings_map =
1883 io_data->GetHostContentSettingsMap();
1884 ContentSetting setting = host_content_settings_map->GetContentSetting(
1885 source_origin,
1886 source_origin,
1887 CONTENT_SETTINGS_TYPE_NOTIFICATIONS,
1888 NO_RESOURCE_IDENTIFIER);
1890 if (setting == CONTENT_SETTING_ALLOW)
1891 return blink::WebNotificationPermissionAllowed;
1892 if (setting == CONTENT_SETTING_BLOCK)
1893 return blink::WebNotificationPermissionDenied;
1894 return blink::WebNotificationPermissionDefault;
1895 #else
1896 return blink::WebNotificationPermissionAllowed;
1897 #endif
1900 void ChromeContentBrowserClient::ShowDesktopNotification(
1901 const content::ShowDesktopNotificationHostMsgParams& params,
1902 RenderFrameHost* render_frame_host,
1903 scoped_ptr<content::DesktopNotificationDelegate> delegate,
1904 base::Closure* cancel_callback) {
1905 #if defined(ENABLE_NOTIFICATIONS)
1906 content::RenderProcessHost* process = render_frame_host->GetProcess();
1907 Profile* profile = Profile::FromBrowserContext(process->GetBrowserContext());
1908 DesktopNotificationService* service =
1909 DesktopNotificationServiceFactory::GetForProfile(profile);
1910 service->ShowDesktopNotification(
1911 params, render_frame_host, delegate.Pass(), cancel_callback);
1913 profile->GetHostContentSettingsMap()->UpdateLastUsage(
1914 params.origin, params.origin, CONTENT_SETTINGS_TYPE_NOTIFICATIONS);
1915 #else
1916 NOTIMPLEMENTED();
1917 #endif
1920 void ChromeContentBrowserClient::RequestGeolocationPermission(
1921 content::WebContents* web_contents,
1922 int bridge_id,
1923 const GURL& requesting_frame,
1924 bool user_gesture,
1925 const base::Callback<void(bool)>& result_callback) {
1926 int render_process_id = web_contents->GetRenderProcessHost()->GetID();
1927 int render_view_id = web_contents->GetRenderViewHost()->GetRoutingID();
1929 const PermissionRequestID request_id(render_process_id,
1930 render_view_id,
1931 bridge_id,
1932 requesting_frame);
1933 GeolocationPermissionContextFactory::GetForProfile(
1934 Profile::FromBrowserContext(web_contents->GetBrowserContext()))->
1935 RequestPermission(web_contents, request_id,
1936 requesting_frame.GetOrigin(), user_gesture,
1937 result_callback);
1940 void ChromeContentBrowserClient::CancelGeolocationPermissionRequest(
1941 content::WebContents* web_contents,
1942 int bridge_id,
1943 const GURL& requesting_frame) {
1944 int render_process_id = web_contents->GetRenderProcessHost()->GetID();
1945 int render_view_id = web_contents->GetRenderViewHost()->GetRoutingID();
1947 const PermissionRequestID request_id(render_process_id,
1948 render_view_id,
1949 bridge_id,
1950 requesting_frame);
1951 GeolocationPermissionContextFactory::GetForProfile(
1952 Profile::FromBrowserContext(web_contents->GetBrowserContext()))->
1953 CancelPermissionRequest(web_contents, request_id);
1956 void ChromeContentBrowserClient::RequestMidiSysExPermission(
1957 content::WebContents* web_contents,
1958 int bridge_id,
1959 const GURL& requesting_frame,
1960 bool user_gesture,
1961 base::Callback<void(bool)> result_callback,
1962 base::Closure* cancel_callback) {
1963 MidiPermissionContext* context =
1964 MidiPermissionContextFactory::GetForProfile(
1965 Profile::FromBrowserContext(web_contents->GetBrowserContext()));
1966 int renderer_id = web_contents->GetRenderProcessHost()->GetID();
1967 int render_view_id = web_contents->GetRenderViewHost()->GetRoutingID();
1968 const PermissionRequestID id(renderer_id, render_view_id, bridge_id, GURL());
1970 context->RequestPermission(web_contents, id, requesting_frame,
1971 user_gesture, result_callback);
1974 void ChromeContentBrowserClient::DidUseGeolocationPermission(
1975 content::WebContents* web_contents,
1976 const GURL& frame_url,
1977 const GURL& main_frame_url) {
1978 Profile::FromBrowserContext(web_contents->GetBrowserContext())
1979 ->GetHostContentSettingsMap()
1980 ->UpdateLastUsage(
1981 frame_url, main_frame_url, CONTENT_SETTINGS_TYPE_GEOLOCATION);
1984 void ChromeContentBrowserClient::RequestProtectedMediaIdentifierPermission(
1985 content::WebContents* web_contents,
1986 const GURL& origin,
1987 base::Callback<void(bool)> result_callback,
1988 base::Closure* cancel_callback) {
1989 #if defined(OS_ANDROID)
1990 ProtectedMediaIdentifierPermissionContext* context =
1991 ProtectedMediaIdentifierPermissionContextFactory::GetForProfile(
1992 Profile::FromBrowserContext(web_contents->GetBrowserContext()));
1993 context->RequestProtectedMediaIdentifierPermission(web_contents,
1994 origin,
1995 result_callback,
1996 cancel_callback);
1997 #else
1998 NOTIMPLEMENTED();
1999 result_callback.Run(false);
2000 #endif // defined(OS_ANDROID)
2003 bool ChromeContentBrowserClient::CanCreateWindow(
2004 const GURL& opener_url,
2005 const GURL& opener_top_level_frame_url,
2006 const GURL& source_origin,
2007 WindowContainerType container_type,
2008 const GURL& target_url,
2009 const content::Referrer& referrer,
2010 WindowOpenDisposition disposition,
2011 const WebWindowFeatures& features,
2012 bool user_gesture,
2013 bool opener_suppressed,
2014 content::ResourceContext* context,
2015 int render_process_id,
2016 int opener_id,
2017 bool* no_javascript_access) {
2018 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
2020 *no_javascript_access = false;
2022 // If the opener is trying to create a background window but doesn't have
2023 // the appropriate permission, fail the attempt.
2024 if (container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {
2025 #if defined(ENABLE_EXTENSIONS)
2026 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
2027 InfoMap* map = io_data->GetExtensionInfoMap();
2028 if (!map->SecurityOriginHasAPIPermission(
2029 source_origin,
2030 render_process_id,
2031 APIPermission::kBackground)) {
2032 return false;
2035 // Note: this use of GetExtensionOrAppByURL is safe but imperfect. It may
2036 // return a recently installed Extension even if this CanCreateWindow call
2037 // was made by an old copy of the page in a normal web process. That's ok,
2038 // because the permission check above would have caused an early return
2039 // already. We must use the full URL to find hosted apps, though, and not
2040 // just the origin.
2041 const Extension* extension =
2042 map->extensions().GetExtensionOrAppByURL(opener_url);
2043 if (extension && !extensions::BackgroundInfo::AllowJSAccess(extension))
2044 *no_javascript_access = true;
2045 #endif
2047 return true;
2050 #if defined(ENABLE_EXTENSIONS)
2051 if (extensions::WebViewRendererState::GetInstance()->IsGuest(
2052 render_process_id))
2053 return true;
2054 #endif
2056 HostContentSettingsMap* content_settings =
2057 ProfileIOData::FromResourceContext(context)->GetHostContentSettingsMap();
2058 BlockedWindowParams blocked_params(target_url,
2059 referrer,
2060 disposition,
2061 features,
2062 user_gesture,
2063 opener_suppressed,
2064 render_process_id,
2065 opener_id);
2067 if (!user_gesture && !CommandLine::ForCurrentProcess()->HasSwitch(
2068 switches::kDisablePopupBlocking)) {
2069 if (content_settings->GetContentSetting(opener_top_level_frame_url,
2070 opener_top_level_frame_url,
2071 CONTENT_SETTINGS_TYPE_POPUPS,
2072 std::string()) !=
2073 CONTENT_SETTING_ALLOW) {
2074 BrowserThread::PostTask(BrowserThread::UI,
2075 FROM_HERE,
2076 base::Bind(&HandleBlockedPopupOnUIThread,
2077 blocked_params));
2078 return false;
2082 #if defined(OS_ANDROID)
2083 if (SingleTabModeTabHelper::IsRegistered(render_process_id, opener_id)) {
2084 BrowserThread::PostTask(BrowserThread::UI,
2085 FROM_HERE,
2086 base::Bind(&HandleSingleTabModeBlockOnUIThread,
2087 blocked_params));
2088 return false;
2090 #endif
2092 return true;
2095 void ChromeContentBrowserClient::ResourceDispatcherHostCreated() {
2096 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
2097 prerender_tracker_ = g_browser_process->prerender_tracker();
2098 return g_browser_process->ResourceDispatcherHostCreated();
2101 // TODO(tommi): Rename from Get to Create.
2102 content::SpeechRecognitionManagerDelegate*
2103 ChromeContentBrowserClient::GetSpeechRecognitionManagerDelegate() {
2104 return new speech::ChromeSpeechRecognitionManagerDelegate();
2107 net::NetLog* ChromeContentBrowserClient::GetNetLog() {
2108 return g_browser_process->net_log();
2111 AccessTokenStore* ChromeContentBrowserClient::CreateAccessTokenStore() {
2112 return new ChromeAccessTokenStore();
2115 bool ChromeContentBrowserClient::IsFastShutdownPossible() {
2116 return true;
2119 void ChromeContentBrowserClient::OverrideWebkitPrefs(
2120 RenderViewHost* rvh, const GURL& url, WebPreferences* web_prefs) {
2121 Profile* profile = Profile::FromBrowserContext(
2122 rvh->GetProcess()->GetBrowserContext());
2123 PrefService* prefs = profile->GetPrefs();
2125 // Fill per-script font preferences. These are not registered on Android
2126 // - http://crbug.com/308033.
2127 #if !defined(OS_ANDROID)
2128 FontFamilyCache::FillFontFamilyMap(profile,
2129 prefs::kWebKitStandardFontFamilyMap,
2130 &web_prefs->standard_font_family_map);
2131 FontFamilyCache::FillFontFamilyMap(profile,
2132 prefs::kWebKitFixedFontFamilyMap,
2133 &web_prefs->fixed_font_family_map);
2134 FontFamilyCache::FillFontFamilyMap(profile,
2135 prefs::kWebKitSerifFontFamilyMap,
2136 &web_prefs->serif_font_family_map);
2137 FontFamilyCache::FillFontFamilyMap(profile,
2138 prefs::kWebKitSansSerifFontFamilyMap,
2139 &web_prefs->sans_serif_font_family_map);
2140 FontFamilyCache::FillFontFamilyMap(profile,
2141 prefs::kWebKitCursiveFontFamilyMap,
2142 &web_prefs->cursive_font_family_map);
2143 FontFamilyCache::FillFontFamilyMap(profile,
2144 prefs::kWebKitFantasyFontFamilyMap,
2145 &web_prefs->fantasy_font_family_map);
2146 FontFamilyCache::FillFontFamilyMap(profile,
2147 prefs::kWebKitPictographFontFamilyMap,
2148 &web_prefs->pictograph_font_family_map);
2149 #endif
2151 web_prefs->default_font_size =
2152 prefs->GetInteger(prefs::kWebKitDefaultFontSize);
2153 web_prefs->default_fixed_font_size =
2154 prefs->GetInteger(prefs::kWebKitDefaultFixedFontSize);
2155 web_prefs->minimum_font_size =
2156 prefs->GetInteger(prefs::kWebKitMinimumFontSize);
2157 web_prefs->minimum_logical_font_size =
2158 prefs->GetInteger(prefs::kWebKitMinimumLogicalFontSize);
2160 web_prefs->default_encoding = prefs->GetString(prefs::kDefaultCharset);
2162 web_prefs->javascript_can_open_windows_automatically =
2163 prefs->GetBoolean(prefs::kWebKitJavascriptCanOpenWindowsAutomatically);
2164 web_prefs->dom_paste_enabled =
2165 prefs->GetBoolean(prefs::kWebKitDomPasteEnabled);
2166 web_prefs->shrinks_standalone_images_to_fit =
2167 prefs->GetBoolean(prefs::kWebKitShrinksStandaloneImagesToFit);
2168 web_prefs->tabs_to_links = prefs->GetBoolean(prefs::kWebkitTabsToLinks);
2170 if (!prefs->GetBoolean(prefs::kWebKitJavascriptEnabled))
2171 web_prefs->javascript_enabled = false;
2172 if (!prefs->GetBoolean(prefs::kWebKitWebSecurityEnabled))
2173 web_prefs->web_security_enabled = false;
2174 if (!prefs->GetBoolean(prefs::kWebKitPluginsEnabled))
2175 web_prefs->plugins_enabled = false;
2176 if (!prefs->GetBoolean(prefs::kWebKitJavaEnabled))
2177 web_prefs->java_enabled = false;
2178 web_prefs->loads_images_automatically =
2179 prefs->GetBoolean(prefs::kWebKitLoadsImagesAutomatically);
2181 if (prefs->GetBoolean(prefs::kDisable3DAPIs))
2182 web_prefs->experimental_webgl_enabled = false;
2184 web_prefs->allow_displaying_insecure_content =
2185 prefs->GetBoolean(prefs::kWebKitAllowDisplayingInsecureContent);
2186 web_prefs->allow_running_insecure_content =
2187 prefs->GetBoolean(prefs::kWebKitAllowRunningInsecureContent);
2188 #if defined(OS_ANDROID)
2189 web_prefs->font_scale_factor =
2190 static_cast<float>(prefs->GetDouble(prefs::kWebKitFontScaleFactor));
2191 web_prefs->device_scale_adjustment = GetDeviceScaleAdjustment();
2192 web_prefs->force_enable_zoom =
2193 prefs->GetBoolean(prefs::kWebKitForceEnableZoom);
2194 #endif
2196 #if defined(OS_ANDROID)
2197 web_prefs->password_echo_enabled =
2198 prefs->GetBoolean(prefs::kWebKitPasswordEchoEnabled);
2199 #else
2200 web_prefs->password_echo_enabled = browser_defaults::kPasswordEchoEnabled;
2201 #endif
2203 web_prefs->asynchronous_spell_checking_enabled = true;
2204 web_prefs->unified_textchecker_enabled = true;
2206 web_prefs->uses_universal_detector =
2207 prefs->GetBoolean(prefs::kWebKitUsesUniversalDetector);
2208 web_prefs->text_areas_are_resizable =
2209 prefs->GetBoolean(prefs::kWebKitTextAreasAreResizable);
2210 web_prefs->hyperlink_auditing_enabled =
2211 prefs->GetBoolean(prefs::kEnableHyperlinkAuditing);
2213 // Make sure we will set the default_encoding with canonical encoding name.
2214 web_prefs->default_encoding =
2215 CharacterEncoding::GetCanonicalEncodingNameByAliasName(
2216 web_prefs->default_encoding);
2217 if (web_prefs->default_encoding.empty()) {
2218 prefs->ClearPref(prefs::kDefaultCharset);
2219 web_prefs->default_encoding = prefs->GetString(prefs::kDefaultCharset);
2221 DCHECK(!web_prefs->default_encoding.empty());
2223 for (size_t i = 0; i < extra_parts_.size(); ++i)
2224 extra_parts_[i]->OverrideWebkitPrefs(rvh, url, web_prefs);
2227 void ChromeContentBrowserClient::BrowserURLHandlerCreated(
2228 BrowserURLHandler* handler) {
2229 for (size_t i = 0; i < extra_parts_.size(); ++i)
2230 extra_parts_[i]->BrowserURLHandlerCreated(handler);
2232 // about: handler. Must come before chrome: handler, since it will
2233 // rewrite about: urls to chrome: URLs and then expect chrome: to
2234 // actually handle them.
2235 handler->AddHandlerPair(&WillHandleBrowserAboutURL,
2236 BrowserURLHandler::null_handler());
2238 #if defined(OS_ANDROID)
2239 // Handler to rewrite chrome://newtab on Android.
2240 handler->AddHandlerPair(&chrome::android::HandleAndroidNewTabURL,
2241 BrowserURLHandler::null_handler());
2242 #else
2243 // Handler to rewrite chrome://newtab for InstantExtended.
2244 handler->AddHandlerPair(&chrome::HandleNewTabURLRewrite,
2245 &chrome::HandleNewTabURLReverseRewrite);
2246 #endif
2248 // chrome: & friends.
2249 handler->AddHandlerPair(&HandleWebUI, &HandleWebUIReverse);
2252 void ChromeContentBrowserClient::ClearCache(RenderViewHost* rvh) {
2253 Profile* profile = Profile::FromBrowserContext(
2254 rvh->GetSiteInstance()->GetProcess()->GetBrowserContext());
2255 BrowsingDataRemover* remover =
2256 BrowsingDataRemover::CreateForUnboundedRange(profile);
2257 remover->Remove(BrowsingDataRemover::REMOVE_CACHE,
2258 BrowsingDataHelper::UNPROTECTED_WEB);
2259 // BrowsingDataRemover takes care of deleting itself when done.
2262 void ChromeContentBrowserClient::ClearCookies(RenderViewHost* rvh) {
2263 Profile* profile = Profile::FromBrowserContext(
2264 rvh->GetSiteInstance()->GetProcess()->GetBrowserContext());
2265 BrowsingDataRemover* remover =
2266 BrowsingDataRemover::CreateForUnboundedRange(profile);
2267 int remove_mask = BrowsingDataRemover::REMOVE_SITE_DATA;
2268 remover->Remove(remove_mask, BrowsingDataHelper::UNPROTECTED_WEB);
2269 // BrowsingDataRemover takes care of deleting itself when done.
2272 base::FilePath ChromeContentBrowserClient::GetDefaultDownloadDirectory() {
2273 return DownloadPrefs::GetDefaultDownloadDirectory();
2276 std::string ChromeContentBrowserClient::GetDefaultDownloadName() {
2277 return l10n_util::GetStringUTF8(IDS_DEFAULT_DOWNLOAD_FILENAME);
2280 void ChromeContentBrowserClient::DidCreatePpapiPlugin(
2281 content::BrowserPpapiHost* browser_host) {
2282 #if defined(ENABLE_PLUGINS)
2283 browser_host->GetPpapiHost()->AddHostFactoryFilter(
2284 scoped_ptr<ppapi::host::HostFactory>(
2285 new ChromeBrowserPepperHostFactory(browser_host)));
2286 #endif
2289 content::BrowserPpapiHost*
2290 ChromeContentBrowserClient::GetExternalBrowserPpapiHost(
2291 int plugin_process_id) {
2292 #if !defined(DISABLE_NACL)
2293 content::BrowserChildProcessHostIterator iter(PROCESS_TYPE_NACL_LOADER);
2294 while (!iter.Done()) {
2295 nacl::NaClProcessHost* host = static_cast<nacl::NaClProcessHost*>(
2296 iter.GetDelegate());
2297 if (host->process() &&
2298 host->process()->GetData().id == plugin_process_id) {
2299 // Found the plugin.
2300 return host->browser_ppapi_host();
2302 ++iter;
2304 #endif
2305 return NULL;
2308 bool ChromeContentBrowserClient::AllowPepperSocketAPI(
2309 content::BrowserContext* browser_context,
2310 const GURL& url,
2311 bool private_api,
2312 const content::SocketPermissionRequest* params) {
2313 #if defined(ENABLE_EXTENSIONS)
2314 Profile* profile = Profile::FromBrowserContext(browser_context);
2315 const extensions::ExtensionSet* extension_set = NULL;
2316 if (profile) {
2317 const ExtensionService* ext_service =
2318 extensions::ExtensionSystem::Get(profile)->extension_service();
2319 if (ext_service) {
2320 extension_set = ext_service->extensions();
2324 if (private_api) {
2325 // Access to private socket APIs is controlled by the whitelist.
2326 if (IsExtensionOrSharedModuleWhitelisted(url, extension_set,
2327 allowed_socket_origins_)) {
2328 return true;
2330 } else {
2331 // Access to public socket APIs is controlled by extension permissions.
2332 if (url.is_valid() && url.SchemeIs(extensions::kExtensionScheme) &&
2333 extension_set) {
2334 const Extension* extension = extension_set->GetByID(url.host());
2335 if (extension) {
2336 const extensions::PermissionsData* permissions_data =
2337 extension->permissions_data();
2338 if (params) {
2339 extensions::SocketPermission::CheckParam check_params(
2340 params->type, params->host, params->port);
2341 if (permissions_data->CheckAPIPermissionWithParam(
2342 extensions::APIPermission::kSocket, &check_params)) {
2343 return true;
2345 } else if (permissions_data->HasAPIPermission(
2346 extensions::APIPermission::kSocket)) {
2347 return true;
2353 // Allow both public and private APIs if the command line says so.
2354 return IsHostAllowedByCommandLine(url, extension_set,
2355 switches::kAllowNaClSocketAPI);
2356 #else
2357 return false;
2358 #endif
2361 ui::SelectFilePolicy* ChromeContentBrowserClient::CreateSelectFilePolicy(
2362 WebContents* web_contents) {
2363 return new ChromeSelectFilePolicy(web_contents);
2366 void ChromeContentBrowserClient::GetAdditionalAllowedSchemesForFileSystem(
2367 std::vector<std::string>* additional_allowed_schemes) {
2368 ContentBrowserClient::GetAdditionalAllowedSchemesForFileSystem(
2369 additional_allowed_schemes);
2370 additional_allowed_schemes->push_back(content::kChromeDevToolsScheme);
2371 additional_allowed_schemes->push_back(content::kChromeUIScheme);
2372 for (size_t i = 0; i < extra_parts_.size(); ++i) {
2373 extra_parts_[i]->GetAdditionalAllowedSchemesForFileSystem(
2374 additional_allowed_schemes);
2378 void ChromeContentBrowserClient::GetURLRequestAutoMountHandlers(
2379 std::vector<storage::URLRequestAutoMountHandler>* handlers) {
2380 for (size_t i = 0; i < extra_parts_.size(); ++i)
2381 extra_parts_[i]->GetURLRequestAutoMountHandlers(handlers);
2384 void ChromeContentBrowserClient::GetAdditionalFileSystemBackends(
2385 content::BrowserContext* browser_context,
2386 const base::FilePath& storage_partition_path,
2387 ScopedVector<storage::FileSystemBackend>* additional_backends) {
2388 #if defined(OS_CHROMEOS)
2389 storage::ExternalMountPoints* external_mount_points =
2390 content::BrowserContext::GetMountPoints(browser_context);
2391 DCHECK(external_mount_points);
2392 chromeos::FileSystemBackend* backend = new chromeos::FileSystemBackend(
2393 new drive::FileSystemBackendDelegate,
2394 new chromeos::file_system_provider::BackendDelegate,
2395 new chromeos::MTPFileSystemBackendDelegate(storage_partition_path),
2396 browser_context->GetSpecialStoragePolicy(),
2397 external_mount_points,
2398 storage::ExternalMountPoints::GetSystemInstance());
2399 backend->AddSystemMountPoints();
2400 DCHECK(backend->CanHandleType(storage::kFileSystemTypeExternal));
2401 additional_backends->push_back(backend);
2402 #endif
2404 for (size_t i = 0; i < extra_parts_.size(); ++i) {
2405 extra_parts_[i]->GetAdditionalFileSystemBackends(
2406 browser_context, storage_partition_path, additional_backends);
2410 #if defined(OS_POSIX) && !defined(OS_MACOSX)
2411 void ChromeContentBrowserClient::GetAdditionalMappedFilesForChildProcess(
2412 const CommandLine& command_line,
2413 int child_process_id,
2414 FileDescriptorInfo* mappings) {
2415 #if defined(OS_ANDROID)
2416 base::FilePath data_path;
2417 PathService::Get(ui::DIR_RESOURCE_PAKS_ANDROID, &data_path);
2418 DCHECK(!data_path.empty());
2420 int flags = base::File::FLAG_OPEN | base::File::FLAG_READ;
2421 base::FilePath chrome_resources_pak =
2422 data_path.AppendASCII("chrome_100_percent.pak");
2423 base::File file(chrome_resources_pak, flags);
2424 DCHECK(file.IsValid());
2425 mappings->Transfer(kAndroidChrome100PercentPakDescriptor,
2426 base::ScopedFD(file.TakePlatformFile()));
2428 const std::string locale = GetApplicationLocale();
2429 base::FilePath locale_pak = ResourceBundle::GetSharedInstance().
2430 GetLocaleFilePath(locale, false);
2431 file.Initialize(locale_pak, flags);
2432 DCHECK(file.IsValid());
2433 mappings->Transfer(kAndroidLocalePakDescriptor,
2434 base::ScopedFD(file.TakePlatformFile()));
2436 base::FilePath resources_pack_path;
2437 PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
2438 file.Initialize(resources_pack_path, flags);
2439 DCHECK(file.IsValid());
2440 mappings->Transfer(kAndroidUIResourcesPakDescriptor,
2441 base::ScopedFD(file.TakePlatformFile()));
2443 if (breakpad::IsCrashReporterEnabled()) {
2444 file = breakpad::CrashDumpManager::GetInstance()->CreateMinidumpFile(
2445 child_process_id);
2446 if (file.IsValid()) {
2447 mappings->Transfer(kAndroidMinidumpDescriptor,
2448 base::ScopedFD(file.TakePlatformFile()));
2449 } else {
2450 LOG(ERROR) << "Failed to create file for minidump, crash reporting will "
2451 "be disabled for this process.";
2455 base::FilePath app_data_path;
2456 PathService::Get(base::DIR_ANDROID_APP_DATA, &app_data_path);
2457 DCHECK(!app_data_path.empty());
2459 flags = base::File::FLAG_OPEN | base::File::FLAG_READ;
2460 base::FilePath icudata_path =
2461 app_data_path.AppendASCII("icudtl.dat");
2462 base::File icudata_file(icudata_path, flags);
2463 DCHECK(icudata_file.IsValid());
2464 mappings->Transfer(kAndroidICUDataDescriptor,
2465 base::ScopedFD(icudata_file.TakePlatformFile()));
2467 #else
2468 int crash_signal_fd = GetCrashSignalFD(command_line);
2469 if (crash_signal_fd >= 0) {
2470 mappings->Share(kCrashDumpSignal, crash_signal_fd);
2472 #endif // defined(OS_ANDROID)
2474 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
2476 #if defined(OS_WIN)
2477 const wchar_t* ChromeContentBrowserClient::GetResourceDllName() {
2478 return chrome::kBrowserResourcesDll;
2481 void ChromeContentBrowserClient::PreSpawnRenderer(
2482 sandbox::TargetPolicy* policy,
2483 bool* success) {
2484 // This code is duplicated in nacl_exe_win_64.cc.
2485 // Allow the server side of a pipe restricted to the "chrome.nacl."
2486 // namespace so that it cannot impersonate other system or other chrome
2487 // service pipes.
2488 sandbox::ResultCode result = policy->AddRule(
2489 sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
2490 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
2491 L"\\\\.\\pipe\\chrome.nacl.*");
2492 if (result != sandbox::SBOX_ALL_OK) {
2493 *success = false;
2494 return;
2497 // Renderers need to send named pipe handles and shared memory
2498 // segment handles to NaCl loader processes.
2499 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
2500 sandbox::TargetPolicy::HANDLES_DUP_ANY,
2501 L"File");
2502 if (result != sandbox::SBOX_ALL_OK) {
2503 *success = false;
2504 return;
2507 #endif
2509 bool ChromeContentBrowserClient::CheckMediaAccessPermission(
2510 content::BrowserContext* browser_context,
2511 const GURL& security_origin,
2512 content::MediaStreamType type) {
2513 return MediaCaptureDevicesDispatcher::GetInstance()
2514 ->CheckMediaAccessPermission(
2515 browser_context, security_origin, type);
2518 content::DevToolsManagerDelegate*
2519 ChromeContentBrowserClient::GetDevToolsManagerDelegate() {
2520 #if defined(OS_ANDROID)
2521 return new DevToolsManagerDelegateAndroid();
2522 #else
2523 return new ChromeDevToolsManagerDelegate();
2524 #endif
2527 bool ChromeContentBrowserClient::IsPluginAllowedToCallRequestOSFileHandle(
2528 content::BrowserContext* browser_context,
2529 const GURL& url) {
2530 #if defined(ENABLE_EXTENSIONS)
2531 Profile* profile = Profile::FromBrowserContext(browser_context);
2532 const extensions::ExtensionSet* extension_set = NULL;
2533 if (profile) {
2534 const ExtensionService* ext_service =
2535 extensions::ExtensionSystem::Get(profile)->extension_service();
2536 if (ext_service) {
2537 extension_set = ext_service->extensions();
2540 return IsExtensionOrSharedModuleWhitelisted(url, extension_set,
2541 allowed_file_handle_origins_) ||
2542 IsHostAllowedByCommandLine(url, extension_set,
2543 switches::kAllowNaClFileHandleAPI);
2544 #else
2545 return false;
2546 #endif
2549 bool ChromeContentBrowserClient::IsPluginAllowedToUseDevChannelAPIs(
2550 content::BrowserContext* browser_context,
2551 const GURL& url) {
2552 #if defined(ENABLE_EXTENSIONS)
2553 // Allow access for tests.
2554 if (CommandLine::ForCurrentProcess()->HasSwitch(
2555 switches::kEnablePepperTesting)) {
2556 return true;
2559 Profile* profile = Profile::FromBrowserContext(browser_context);
2560 const extensions::ExtensionSet* extension_set = NULL;
2561 if (profile) {
2562 const ExtensionService* ext_service =
2563 extensions::ExtensionSystem::Get(profile)->extension_service();
2564 if (ext_service) {
2565 extension_set = ext_service->extensions();
2569 // Allow access for whitelisted applications.
2570 if (IsExtensionOrSharedModuleWhitelisted(url,
2571 extension_set,
2572 allowed_dev_channel_origins_)) {
2573 return true;
2576 chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
2577 // Allow dev channel APIs to be used on "Canary", "Dev", and "Unknown"
2578 // releases of Chrome. Permitting "Unknown" allows these APIs to be used on
2579 // Chromium builds as well.
2580 return channel <= chrome::VersionInfo::CHANNEL_DEV;
2581 #else
2582 return false;
2583 #endif
2586 net::CookieStore*
2587 ChromeContentBrowserClient::OverrideCookieStoreForRenderProcess(
2588 int render_process_id) {
2589 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
2590 if (!prerender_tracker_)
2591 return NULL;
2592 return prerender_tracker_->GetPrerenderCookieStoreForRenderProcess(
2593 render_process_id).get();
2596 #if defined(ENABLE_WEBRTC)
2597 void ChromeContentBrowserClient::MaybeCopyDisableWebRtcEncryptionSwitch(
2598 CommandLine* to_command_line,
2599 const CommandLine& from_command_line,
2600 VersionInfo::Channel channel) {
2601 #if defined(OS_ANDROID)
2602 const VersionInfo::Channel kMaxDisableEncryptionChannel =
2603 VersionInfo::CHANNEL_BETA;
2604 #else
2605 const VersionInfo::Channel kMaxDisableEncryptionChannel =
2606 VersionInfo::CHANNEL_DEV;
2607 #endif
2608 if (channel <= kMaxDisableEncryptionChannel) {
2609 static const char* const kWebRtcDevSwitchNames[] = {
2610 switches::kDisableWebRtcEncryption,
2612 to_command_line->CopySwitchesFrom(from_command_line,
2613 kWebRtcDevSwitchNames,
2614 arraysize(kWebRtcDevSwitchNames));
2617 #endif // defined(ENABLE_WEBRTC)
2619 } // namespace chrome