Fix build break
[chromium-blink-merge.git] / chrome / browser / chrome_content_browser_client.cc
blobce0e4b665a21ad16a6428f7ecfa958188bd0e178
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/lazy_instance.h"
14 #include "base/path_service.h"
15 #include "base/prefs/pref_service.h"
16 #include "base/strings/string_tokenizer.h"
17 #include "base/utf_string_conversions.h"
18 #include "chrome/app/breakpad_mac.h"
19 #include "chrome/browser/app_mode/app_mode_utils.h"
20 #include "chrome/browser/browser_about_handler.h"
21 #include "chrome/browser/browser_process.h"
22 #include "chrome/browser/browsing_data/browsing_data_helper.h"
23 #include "chrome/browser/browsing_data/browsing_data_remover.h"
24 #include "chrome/browser/character_encoding.h"
25 #include "chrome/browser/chrome_net_benchmarking_message_filter.h"
26 #include "chrome/browser/chrome_quota_permission_context.h"
27 #include "chrome/browser/content_settings/content_settings_utils.h"
28 #include "chrome/browser/content_settings/cookie_settings.h"
29 #include "chrome/browser/content_settings/host_content_settings_map.h"
30 #include "chrome/browser/content_settings/tab_specific_content_settings.h"
31 #include "chrome/browser/defaults.h"
32 #include "chrome/browser/download/download_util.h"
33 #include "chrome/browser/extensions/activity_log.h"
34 #include "chrome/browser/extensions/api/web_request/web_request_api.h"
35 #include "chrome/browser/extensions/extension_host.h"
36 #include "chrome/browser/extensions/extension_info_map.h"
37 #include "chrome/browser/extensions/extension_process_manager.h"
38 #include "chrome/browser/extensions/extension_service.h"
39 #include "chrome/browser/extensions/extension_system.h"
40 #include "chrome/browser/extensions/extension_web_ui.h"
41 #include "chrome/browser/extensions/extension_webkit_preferences.h"
42 #include "chrome/browser/extensions/suggest_permission_util.h"
43 #include "chrome/browser/geolocation/chrome_access_token_store.h"
44 #include "chrome/browser/google/google_util.h"
45 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
46 #include "chrome/browser/metrics/chrome_browser_main_extra_parts_metrics.h"
47 #include "chrome/browser/nacl_host/nacl_process_host.h"
48 #include "chrome/browser/net/chrome_net_log.h"
49 #include "chrome/browser/notifications/desktop_notification_service.h"
50 #include "chrome/browser/notifications/desktop_notification_service_factory.h"
51 #include "chrome/browser/platform_util.h"
52 #include "chrome/browser/plugins/plugin_info_message_filter.h"
53 #include "chrome/browser/prefs/scoped_user_pref_update.h"
54 #include "chrome/browser/prerender/prerender_manager.h"
55 #include "chrome/browser/prerender/prerender_manager_factory.h"
56 #include "chrome/browser/prerender/prerender_message_filter.h"
57 #include "chrome/browser/prerender/prerender_tracker.h"
58 #include "chrome/browser/printing/printing_message_filter.h"
59 #include "chrome/browser/profiles/profile.h"
60 #include "chrome/browser/profiles/profile_io_data.h"
61 #include "chrome/browser/profiles/profile_manager.h"
62 #include "chrome/browser/renderer_host/chrome_render_message_filter.h"
63 #include "chrome/browser/renderer_host/pepper/chrome_browser_pepper_host_factory.h"
64 #include "chrome/browser/search/instant_service.h"
65 #include "chrome/browser/search/instant_service_factory.h"
66 #include "chrome/browser/search/search.h"
67 #include "chrome/browser/search_engines/search_provider_install_state_message_filter.h"
68 #include "chrome/browser/signin/signin_manager.h"
69 #include "chrome/browser/signin/signin_manager_factory.h"
70 #include "chrome/browser/speech/chrome_speech_recognition_manager_delegate.h"
71 #include "chrome/browser/spellchecker/spellcheck_message_filter.h"
72 #include "chrome/browser/ssl/ssl_add_certificate.h"
73 #include "chrome/browser/ssl/ssl_blocking_page.h"
74 #include "chrome/browser/ssl/ssl_tab_helper.h"
75 #include "chrome/browser/tab_contents/tab_util.h"
76 #include "chrome/browser/toolkit_extra_parts.h"
77 #include "chrome/browser/ui/chrome_select_file_policy.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/browser/ui/webui/sync_promo/sync_promo_ui.h"
81 #include "chrome/browser/user_style_sheet_watcher.h"
82 #include "chrome/browser/user_style_sheet_watcher_factory.h"
83 #include "chrome/common/child_process_logging.h"
84 #include "chrome/common/chrome_constants.h"
85 #include "chrome/common/chrome_paths.h"
86 #include "chrome/common/chrome_process_type.h"
87 #include "chrome/common/chrome_switches.h"
88 #include "chrome/common/extensions/background_info.h"
89 #include "chrome/common/extensions/extension.h"
90 #include "chrome/common/extensions/extension_process_policy.h"
91 #include "chrome/common/extensions/extension_set.h"
92 #include "chrome/common/extensions/manifest_handlers/app_isolation_info.h"
93 #include "chrome/common/extensions/permissions/socket_permission.h"
94 #include "chrome/common/logging_chrome.h"
95 #include "chrome/common/pref_names.h"
96 #include "chrome/common/render_messages.h"
97 #include "chrome/common/url_constants.h"
98 #include "components/user_prefs/pref_registry_syncable.h"
99 #include "content/public/browser/browser_child_process_host.h"
100 #include "content/public/browser/browser_main_parts.h"
101 #include "content/public/browser/browser_ppapi_host.h"
102 #include "content/public/browser/browser_url_handler.h"
103 #include "content/public/browser/child_process_data.h"
104 #include "content/public/browser/child_process_security_policy.h"
105 #include "content/public/browser/compositor_util.h"
106 #include "content/public/browser/render_process_host.h"
107 #include "content/public/browser/render_view_host.h"
108 #include "content/public/browser/resource_context.h"
109 #include "content/public/browser/site_instance.h"
110 #include "content/public/browser/web_contents.h"
111 #include "content/public/browser/web_contents_view.h"
112 #include "content/public/common/child_process_host.h"
113 #include "content/public/common/content_descriptors.h"
114 #include "extensions/browser/view_type_utils.h"
115 #include "extensions/common/constants.h"
116 #include "grit/generated_resources.h"
117 #include "grit/ui_resources.h"
118 #include "net/base/escape.h"
119 #include "net/base/mime_util.h"
120 #include "net/cookies/canonical_cookie.h"
121 #include "net/cookies/cookie_options.h"
122 #include "net/ssl/ssl_cert_request_info.h"
123 #include "ppapi/host/ppapi_host.h"
124 #include "ui/base/l10n/l10n_util.h"
125 #include "ui/base/resource/resource_bundle.h"
126 #include "webkit/glue/webpreferences.h"
127 #include "webkit/plugins/plugin_switches.h"
129 #if defined(OS_WIN)
130 #include "chrome/browser/chrome_browser_main_win.h"
131 #include "sandbox/win/src/sandbox_policy.h"
132 #elif defined(OS_MACOSX)
133 #include "chrome/browser/chrome_browser_main_mac.h"
134 #include "chrome/browser/spellchecker/spellcheck_message_filter_mac.h"
135 #elif defined(OS_CHROMEOS)
136 #include "chrome/browser/chromeos/chrome_browser_main_chromeos.h"
137 #include "chrome/browser/chromeos/login/user_manager.h"
138 #include "chromeos/chromeos_switches.h"
139 #elif defined(OS_LINUX)
140 #include "chrome/browser/chrome_browser_main_linux.h"
141 #elif defined(OS_ANDROID)
142 #include "chrome/browser/android/crash_dump_manager.h"
143 #include "chrome/browser/chrome_browser_main_android.h"
144 #include "chrome/common/descriptors_android.h"
145 #elif defined(OS_POSIX)
146 #include "chrome/browser/chrome_browser_main_posix.h"
147 #endif
149 #if defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_ANDROID)
150 #include "base/linux_util.h"
151 #include "chrome/browser/crash_handler_host_linux.h"
152 #endif
154 #if defined(ENABLE_CAPTIVE_PORTAL_DETECTION)
155 #include "chrome/browser/captive_portal/captive_portal_tab_helper.h"
156 #endif
158 #if defined(ENABLE_MESSAGE_CENTER)
159 #include "ui/message_center/message_center_util.h"
160 #endif
162 #if defined(OS_ANDROID)
163 #include "ui/base/ui_base_paths.h"
164 #endif
166 #if defined(USE_NSS)
167 #include "chrome/browser/ui/crypto_module_password_dialog.h"
168 #endif
170 using base::FileDescriptor;
171 using content::AccessTokenStore;
172 using content::BrowserChildProcessHostIterator;
173 using content::BrowserThread;
174 using content::BrowserURLHandler;
175 using content::ChildProcessSecurityPolicy;
176 using content::FileDescriptorInfo;
177 using content::QuotaPermissionContext;
178 using content::RenderViewHost;
179 using content::SiteInstance;
180 using content::WebContents;
181 using extensions::APIPermission;
182 using extensions::Extension;
183 using extensions::Manifest;
184 using webkit_glue::WebPreferences;
186 namespace {
188 // Cached version of the locale so we can return the locale on the I/O
189 // thread.
190 base::LazyInstance<std::string> g_io_thread_application_locale;
192 const char* kPredefinedAllowedSocketOrigins[] = {
193 "okddffdblfhhnmhodogpojmfkjmhinfp", // Test SSH Client
194 "pnhechapfaindjhompbnflcldabbghjo", // HTerm App (SSH Client)
195 "bglhmjfplikpjnfoegeomebmfnkjomhe", // see crbug.com/122126
196 "gbchcmhmhahfdphkhkmpfmihenigjmpp", // Chrome Remote Desktop
197 "kgngmbheleoaphbjbaiobfdepmghbfah", // Pre-release Chrome Remote Desktop
198 "odkaodonbgfohohmklejpjiejmcipmib", // Dogfood Chrome Remote Desktop
199 "ojoimpklfciegopdfgeenehpalipignm", // Chromoting canary
200 "cbkkbcmdlboombapidmoeolnmdacpkch", // see crbug.com/129089
201 "hhnbmknkdabfoieppbbljkhkfjcmcbjh", // see crbug.com/134099
202 "mablfbjkhmhkmefkjjacnbaikjkipphg", // see crbug.com/134099
203 "pdeelgamlgannhelgoegilelnnojegoh", // see crbug.com/134099
204 "cabapfdbkniadpollkckdnedaanlciaj", // see crbug.com/134099
205 "mapljbgnjledlpdmlchihnmeclmefbba", // see crbug.com/134099
206 "ghbfeebgmiidnnmeobbbaiamklmpbpii", // see crbug.com/134099
207 "jdfhpkjeckflbbleddjlpimecpbjdeep", // see crbug.com/142514
208 "iabmpiboiopbgfabjmgeedhcmjenhbla" // see crbug.com/165080
211 // Returns a copy of the given url with its host set to given host and path set
212 // to given path. Other parts of the url will be the same.
213 GURL ReplaceURLHostAndPath(const GURL& url,
214 const std::string& host,
215 const std::string& path) {
216 url_canon::Replacements<char> replacements;
217 replacements.SetHost(host.c_str(),
218 url_parse::Component(0, host.length()));
219 replacements.SetPath(path.c_str(),
220 url_parse::Component(0, path.length()));
221 return url.ReplaceComponents(replacements);
224 // Maps "foo://bar/baz/" to "foo://chrome/bar/baz/".
225 GURL AddUberHost(const GURL& url) {
226 const std::string uber_host = chrome::kChromeUIUberHost;
227 const std::string new_path = url.host() + url.path();
229 return ReplaceURLHostAndPath(url, uber_host, new_path);
232 // If url->host() is "chrome" and url->path() has characters other than the
233 // first slash, changes the url from "foo://chrome/bar/" to "foo://bar/" and
234 // returns true. Otherwise returns false.
235 bool RemoveUberHost(GURL* url) {
236 if (url->host() != chrome::kChromeUIUberHost)
237 return false;
239 if (url->path().empty() || url->path() == "/")
240 return false;
242 const std::string old_path = url->path();
244 const std::string::size_type separator = old_path.find('/', 1);
245 std::string new_host;
246 std::string new_path;
247 if (separator == std::string::npos) {
248 new_host = old_path.substr(1);
249 } else {
250 new_host = old_path.substr(1, separator - 1);
251 new_path = old_path.substr(separator);
254 *url = ReplaceURLHostAndPath(*url, new_host, new_path);
256 return true;
259 // Handles rewriting Web UI URLs.
260 bool HandleWebUI(GURL* url, content::BrowserContext* browser_context) {
261 // Do not handle special URLs such as "about:foo"
262 if (!url->host().empty()) {
263 const GURL chrome_url = AddUberHost(*url);
265 // Handle valid "chrome://chrome/foo" URLs so the reverse handler will
266 // be called.
267 if (ChromeWebUIControllerFactory::GetInstance()->UseWebUIForURL(
268 browser_context, chrome_url))
269 return true;
272 if (!ChromeWebUIControllerFactory::GetInstance()->UseWebUIForURL(
273 browser_context, *url))
274 return false;
276 #if defined(OS_CHROMEOS)
277 // Special case : in ChromeOS in Guest mode bookmarks and history are
278 // disabled for security reasons. New tab page explains the reasons, so
279 // we redirect user to new tab page.
280 if (chromeos::UserManager::Get()->IsLoggedInAsGuest()) {
281 if (url->SchemeIs(chrome::kChromeUIScheme) &&
282 (url->DomainIs(chrome::kChromeUIBookmarksHost) ||
283 url->DomainIs(chrome::kChromeUIHistoryHost))) {
284 // Rewrite with new tab URL
285 *url = GURL(chrome::kChromeUINewTabURL);
288 #endif
290 // Special case the new tab page. In older versions of Chrome, the new tab
291 // page was hosted at chrome-internal:<blah>. This might be in people's saved
292 // sessions or bookmarks, so we say any URL with that scheme triggers the new
293 // tab page.
294 if (url->SchemeIs(chrome::kChromeInternalScheme)) {
295 // Rewrite it with the proper new tab URL.
296 *url = GURL(chrome::kChromeUINewTabURL);
299 return true;
302 // Reverse URL handler for Web UI. Maps "chrome://chrome/foo/" to
303 // "chrome://foo/".
304 bool HandleWebUIReverse(GURL* url, content::BrowserContext* browser_context) {
305 if (!url->is_valid() || !url->SchemeIs(chrome::kChromeUIScheme))
306 return false;
308 return RemoveUberHost(url);
311 // Used by the GetPrivilegeRequiredByUrl() and GetProcessPrivilege() functions
312 // below. Extension, and isolated apps require different privileges to be
313 // granted to their RenderProcessHosts. This classification allows us to make
314 // sure URLs are served by hosts with the right set of privileges.
315 enum RenderProcessHostPrivilege {
316 PRIV_NORMAL,
317 PRIV_HOSTED,
318 PRIV_ISOLATED,
319 PRIV_EXTENSION,
322 RenderProcessHostPrivilege GetPrivilegeRequiredByUrl(
323 const GURL& url,
324 ExtensionService* service) {
325 // Default to a normal renderer cause it is lower privileged. This should only
326 // occur if the URL on a site instance is either malformed, or uninitialized.
327 // If it is malformed, then there is no need for better privileges anyways.
328 // If it is uninitialized, but eventually settles on being an a scheme other
329 // than normal webrenderer, the navigation logic will correct us out of band
330 // anyways.
331 if (!url.is_valid())
332 return PRIV_NORMAL;
334 if (url.SchemeIs(extensions::kExtensionScheme)) {
335 const Extension* extension =
336 service->extensions()->GetByID(url.host());
337 if (extension &&
338 extensions::AppIsolationInfo::HasIsolatedStorage(extension))
339 return PRIV_ISOLATED;
340 if (extension && extension->is_hosted_app())
341 return PRIV_HOSTED;
343 return PRIV_EXTENSION;
346 return PRIV_NORMAL;
349 RenderProcessHostPrivilege GetProcessPrivilege(
350 content::RenderProcessHost* process_host,
351 extensions::ProcessMap* process_map,
352 ExtensionService* service) {
353 std::set<std::string> extension_ids =
354 process_map->GetExtensionsInProcess(process_host->GetID());
355 if (extension_ids.empty())
356 return PRIV_NORMAL;
358 for (std::set<std::string>::iterator iter = extension_ids.begin();
359 iter != extension_ids.end(); ++iter) {
360 const Extension* extension = service->GetExtensionById(*iter, false);
361 if (extension &&
362 extensions::AppIsolationInfo::HasIsolatedStorage(extension))
363 return PRIV_ISOLATED;
364 if (extension && extension->is_hosted_app())
365 return PRIV_HOSTED;
368 return PRIV_EXTENSION;
371 bool CertMatchesFilter(const net::X509Certificate& cert,
372 const base::DictionaryValue& filter) {
373 // TODO(markusheintz): This is the minimal required filter implementation.
374 // Implement a better matcher.
376 // An empty filter matches any client certificate since no requirements are
377 // specified at all.
378 if (filter.empty())
379 return true;
381 std::string common_name;
382 if (filter.GetString("ISSUER.CN", &common_name) &&
383 (cert.issuer().common_name == common_name)) {
384 return true;
386 return false;
389 // Fills |map| with the per-script font prefs under path |map_name|.
390 void FillFontFamilyMap(const PrefService* prefs,
391 const char* map_name,
392 WebPreferences::ScriptFontFamilyMap* map) {
393 for (size_t i = 0; i < prefs::kWebKitScriptsForFontFamilyMapsLength; ++i) {
394 const char* script = prefs::kWebKitScriptsForFontFamilyMaps[i];
395 std::string pref_name = base::StringPrintf("%s.%s", map_name, script);
396 std::string font_family = prefs->GetString(pref_name.c_str());
397 if (!font_family.empty())
398 (*map)[script] = UTF8ToUTF16(font_family);
402 #if defined(OS_POSIX) && !defined(OS_MACOSX)
403 int GetCrashSignalFD(const CommandLine& command_line) {
404 if (command_line.HasSwitch(switches::kExtensionProcess)) {
405 ExtensionCrashHandlerHostLinux* crash_handler =
406 ExtensionCrashHandlerHostLinux::GetInstance();
407 return crash_handler->GetDeathSignalSocket();
410 std::string process_type =
411 command_line.GetSwitchValueASCII(switches::kProcessType);
413 if (process_type == switches::kRendererProcess)
414 return RendererCrashHandlerHostLinux::GetInstance()->GetDeathSignalSocket();
416 if (process_type == switches::kPluginProcess)
417 return PluginCrashHandlerHostLinux::GetInstance()->GetDeathSignalSocket();
419 if (process_type == switches::kPpapiPluginProcess)
420 return PpapiCrashHandlerHostLinux::GetInstance()->GetDeathSignalSocket();
422 if (process_type == switches::kGpuProcess)
423 return GpuCrashHandlerHostLinux::GetInstance()->GetDeathSignalSocket();
425 return -1;
427 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
429 // Transforms the input |url| into its "effective URL". The returned URL
430 // facilitates grouping process-per-site. The |url| is transformed, for
431 // example, from
433 // https://www.google.com/search?espv=1&q=tractors
435 // to the effective URL
437 // chrome-search://www.google.com/search?espv=1&q=tractors
439 // Notice the scheme change.
441 // If the input is already an effective URL then that same URL is returned.
442 GURL GetEffectiveURLForInstant(const GURL& url, Profile* profile) {
443 CHECK(chrome::ShouldAssignURLToInstantRenderer(url, profile))
444 << "Error granting Instant access.";
446 if (url.SchemeIs(chrome::kChromeSearchScheme))
447 return url;
449 GURL effective_url(url);
451 // Replace the scheme with "chrome-search:".
452 url_canon::Replacements<char> replacements;
453 std::string search_scheme(chrome::kChromeSearchScheme);
454 replacements.SetScheme(search_scheme.data(),
455 url_parse::Component(0, search_scheme.length()));
456 effective_url = effective_url.ReplaceComponents(replacements);
457 return effective_url;
460 GURL GetEffectiveURLForSignin(const GURL& url) {
461 CHECK(SigninManager::IsWebBasedSigninFlowURL(url));
463 GURL effective_url(SigninManager::kChromeSigninEffectiveSite);
464 // Copy the path because the argument to SetPathStr must outlive
465 // the Replacements object.
466 const std::string path_copy(url.path());
467 GURL::Replacements replacements;
468 replacements.SetPathStr(path_copy);
469 effective_url = effective_url.ReplaceComponents(replacements);
470 return effective_url;
473 void SetApplicationLocaleOnIOThread(const std::string& locale) {
474 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
475 g_io_thread_application_locale.Get() = locale;
478 } // namespace
480 namespace chrome {
482 ChromeContentBrowserClient::ChromeContentBrowserClient() {
483 for (size_t i = 0; i < arraysize(kPredefinedAllowedSocketOrigins); ++i)
484 allowed_socket_origins_.insert(kPredefinedAllowedSocketOrigins[i]);
487 ChromeContentBrowserClient::~ChromeContentBrowserClient() {
490 // static
491 void ChromeContentBrowserClient::RegisterUserPrefs(
492 PrefRegistrySyncable* registry) {
493 registry->RegisterBooleanPref(prefs::kDisable3DAPIs,
494 false,
495 PrefRegistrySyncable::UNSYNCABLE_PREF);
496 registry->RegisterBooleanPref(prefs::kEnableHyperlinkAuditing,
497 true,
498 PrefRegistrySyncable::UNSYNCABLE_PREF);
499 registry->RegisterBooleanPref(prefs::kEnableMemoryInfo,
500 false,
501 PrefRegistrySyncable::UNSYNCABLE_PREF);
504 // static
505 void ChromeContentBrowserClient::SetApplicationLocale(
506 const std::string& locale) {
507 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
509 // This object is guaranteed to outlive all threads so we don't have to
510 // worry about the lack of refcounting and can just post as Unretained.
512 // The common case is that this function is called early in Chrome startup
513 // before any threads are created (it will also be called later if the user
514 // changes the pref). In this case, there will be no threads created and
515 // posting will fail. When there are no threads, we can just set the string
516 // without worrying about threadsafety.
517 if (!BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
518 base::Bind(&SetApplicationLocaleOnIOThread, locale))) {
519 g_io_thread_application_locale.Get() = locale;
523 content::BrowserMainParts* ChromeContentBrowserClient::CreateBrowserMainParts(
524 const content::MainFunctionParams& parameters) {
525 ChromeBrowserMainParts* main_parts;
526 // Construct the Main browser parts based on the OS type.
527 #if defined(OS_WIN)
528 main_parts = new ChromeBrowserMainPartsWin(parameters);
529 #elif defined(OS_MACOSX)
530 main_parts = new ChromeBrowserMainPartsMac(parameters);
531 #elif defined(OS_CHROMEOS)
532 main_parts = new chromeos::ChromeBrowserMainPartsChromeos(parameters);
533 #elif defined(OS_LINUX)
534 main_parts = new ChromeBrowserMainPartsLinux(parameters);
535 #elif defined(OS_ANDROID)
536 main_parts = new ChromeBrowserMainPartsAndroid(parameters);
537 #elif defined(OS_POSIX)
538 main_parts = new ChromeBrowserMainPartsPosix(parameters);
539 #else
540 NOTREACHED();
541 main_parts = new ChromeBrowserMainParts(parameters);
542 #endif
544 // Construct additional browser parts. Stages are called in the order in
545 // which they are added.
546 #if defined(TOOLKIT_GTK)
547 chrome::AddGtkToolkitExtraParts(main_parts);
548 #endif
550 #if defined(TOOLKIT_VIEWS)
551 chrome::AddViewsToolkitExtraParts(main_parts);
552 #endif
554 #if defined(USE_ASH)
555 chrome::AddAshToolkitExtraParts(main_parts);
556 #endif
558 #if defined(USE_AURA)
559 chrome::AddAuraToolkitExtraParts(main_parts);
560 #endif
562 chrome::AddMetricsExtraParts(main_parts);
564 return main_parts;
567 std::string ChromeContentBrowserClient::GetStoragePartitionIdForSite(
568 content::BrowserContext* browser_context,
569 const GURL& site) {
570 std::string partition_id;
572 // The partition ID for webview guest processes is the string value of its
573 // SiteInstance URL - "chrome-guest://app_id/persist?partition".
574 if (site.SchemeIs(chrome::kGuestScheme))
575 partition_id = site.spec();
577 DCHECK(IsValidStoragePartitionId(browser_context, partition_id));
578 return partition_id;
581 bool ChromeContentBrowserClient::IsValidStoragePartitionId(
582 content::BrowserContext* browser_context,
583 const std::string& partition_id) {
584 // The default ID is empty and is always valid.
585 if (partition_id.empty())
586 return true;
588 return GURL(partition_id).is_valid();
591 void ChromeContentBrowserClient::GetStoragePartitionConfigForSite(
592 content::BrowserContext* browser_context,
593 const GURL& site,
594 bool can_be_default,
595 std::string* partition_domain,
596 std::string* partition_name,
597 bool* in_memory) {
598 // Default to the browser-wide storage partition and override based on |site|
599 // below.
600 partition_domain->clear();
601 partition_name->clear();
602 *in_memory = false;
604 // For the webview tag, we create special guest processes, which host the
605 // tag content separately from the main application that embeds the tag.
606 // A webview tag can specify both the partition name and whether the storage
607 // for that partition should be persisted. Each tag gets a SiteInstance with
608 // a specially formatted URL, based on the application it is hosted by and
609 // the partition requested by it. The format for that URL is:
610 // chrome-guest://partition_domain/persist?partition_name
611 if (site.SchemeIs(chrome::kGuestScheme)) {
612 // Since guest URLs are only used for packaged apps, there must be an app
613 // id in the URL.
614 CHECK(site.has_host());
615 *partition_domain = site.host();
616 // Since persistence is optional, the path must either be empty or the
617 // literal string.
618 *in_memory = (site.path() != "/persist");
619 // The partition name is user supplied value, which we have encoded when the
620 // URL was created, so it needs to be decoded.
621 *partition_name = net::UnescapeURLComponent(site.query(),
622 net::UnescapeRule::NORMAL);
623 } else if (site.SchemeIs(extensions::kExtensionScheme)) {
624 // If |can_be_default| is false, the caller is stating that the |site|
625 // should be parsed as if it had isolated storage. In particular it is
626 // important to NOT check ExtensionService for the is_storage_isolated()
627 // attribute because this code path is run during Extension uninstall
628 // to do cleanup after the Extension has already been unloaded from the
629 // ExtensionService.
630 bool is_isolated = !can_be_default;
631 if (can_be_default) {
632 const Extension* extension = NULL;
633 Profile* profile = Profile::FromBrowserContext(browser_context);
634 ExtensionService* extension_service =
635 extensions::ExtensionSystem::Get(profile)->extension_service();
636 if (extension_service) {
637 extension = extension_service->extensions()->
638 GetExtensionOrAppByURL(ExtensionURLInfo(site));
639 if (extension &&
640 extensions::AppIsolationInfo::HasIsolatedStorage(extension)) {
641 is_isolated = true;
646 if (is_isolated) {
647 CHECK(site.has_host());
648 // For extensions with isolated storage, the the host of the |site| is
649 // the |partition_domain|. The |in_memory| and |partition_name| are only
650 // used in guest schemes so they are cleared here.
651 *partition_domain = site.host();
652 *in_memory = false;
653 partition_name->clear();
657 // Assert that if |can_be_default| is false, the code above must have found a
658 // non-default partition. If this fails, the caller has a serious logic
659 // error about which StoragePartition they expect to be in and it is not
660 // safe to continue.
661 CHECK(can_be_default || !partition_domain->empty());
664 content::WebContentsViewDelegate*
665 ChromeContentBrowserClient::GetWebContentsViewDelegate(
666 content::WebContents* web_contents) {
667 return chrome::CreateWebContentsViewDelegate(web_contents);
670 // Check if the extension activity log is enabled for the profile.
671 static bool IsExtensionActivityLogEnabledForProfile(Profile* profile) {
672 extensions::ActivityLog* activity_log =
673 extensions::ActivityLog::GetInstance(profile);
674 return activity_log->IsLogEnabled();
677 void ChromeContentBrowserClient::GuestWebContentsCreated(
678 WebContents* guest_web_contents, WebContents* embedder_web_contents) {
679 Profile* profile = Profile::FromBrowserContext(
680 embedder_web_contents->GetBrowserContext());
681 ExtensionService* service =
682 extensions::ExtensionSystem::Get(profile)->extension_service();
683 if (!service)
684 return;
685 const GURL& url = embedder_web_contents->GetSiteInstance()->GetSiteURL();
686 const Extension* extension = service->extensions()->
687 GetExtensionOrAppByURL(ExtensionURLInfo(url));
688 if (!extension)
689 return;
690 std::vector<ExtensionMsg_Loaded_Params> extensions;
691 extensions.push_back(ExtensionMsg_Loaded_Params(extension));
692 guest_web_contents->Send(new ExtensionMsg_Loaded(extensions));
695 void ChromeContentBrowserClient::RenderProcessHostCreated(
696 content::RenderProcessHost* host) {
697 int id = host->GetID();
698 Profile* profile = Profile::FromBrowserContext(host->GetBrowserContext());
699 net::URLRequestContextGetter* context =
700 profile->GetRequestContextForRenderProcess(id);
702 host->GetChannel()->AddFilter(new ChromeRenderMessageFilter(
703 id, profile, context));
704 #if defined(ENABLE_PLUGINS)
705 host->GetChannel()->AddFilter(new PluginInfoMessageFilter(id, profile));
706 #endif
707 #if defined(ENABLE_PRINTING)
708 host->GetChannel()->AddFilter(new PrintingMessageFilter(id, profile));
709 #endif
710 host->GetChannel()->AddFilter(
711 new SearchProviderInstallStateMessageFilter(id, profile));
712 host->GetChannel()->AddFilter(new SpellCheckMessageFilter(id));
713 #if defined(OS_MACOSX)
714 host->GetChannel()->AddFilter(new SpellCheckMessageFilterMac(id));
715 #endif
716 host->GetChannel()->AddFilter(new ChromeNetBenchmarkingMessageFilter(
717 id, profile, context));
718 host->GetChannel()->AddFilter(
719 new prerender::PrerenderMessageFilter(id, profile));
721 host->Send(new ChromeViewMsg_SetIsIncognitoProcess(
722 profile->IsOffTheRecord()));
724 host->Send(new ChromeViewMsg_SetExtensionActivityLogEnabled(
725 IsExtensionActivityLogEnabledForProfile(profile)));
727 SendExtensionWebRequestStatusToHost(host);
729 RendererContentSettingRules rules;
730 GetRendererContentSettingRules(profile->GetHostContentSettingsMap(), &rules);
731 host->Send(new ChromeViewMsg_SetContentSettingRules(rules));
734 GURL ChromeContentBrowserClient::GetEffectiveURL(
735 content::BrowserContext* browser_context, const GURL& url) {
736 Profile* profile = Profile::FromBrowserContext(browser_context);
737 if (!profile)
738 return url;
740 // If the input |url| should be assigned to the Instant renderer, make its
741 // effective URL distinct from other URLs on the search provider's domain.
742 if (chrome::ShouldAssignURLToInstantRenderer(url, profile))
743 return GetEffectiveURLForInstant(url, profile);
745 // If the input |url| should be assigned to the Signin renderer, make its
746 // effective URL distinct from other URLs on the signin service's domain.
747 // Note that the signin renderer will be allowed to sign the user in to
748 // Chrome.
749 if (SigninManager::IsWebBasedSigninFlowURL(url))
750 return GetEffectiveURLForSignin(url);
752 // If the input |url| is part of an installed app, the effective URL is an
753 // extension URL with the ID of that extension as the host. This has the
754 // effect of grouping apps together in a common SiteInstance.
755 ExtensionService* extension_service =
756 extensions::ExtensionSystem::Get(profile)->extension_service();
757 if (!extension_service)
758 return url;
760 const Extension* extension = extension_service->extensions()->
761 GetHostedAppByURL(ExtensionURLInfo(url));
762 if (!extension)
763 return url;
765 // Bookmark apps do not use the hosted app process model, and should be
766 // treated as normal URLs.
767 if (extension->from_bookmark())
768 return url;
770 // If the URL is part of an extension's web extent, convert it to an
771 // extension URL.
772 return extension->GetResourceURL(url.path());
775 bool ChromeContentBrowserClient::ShouldUseProcessPerSite(
776 content::BrowserContext* browser_context, const GURL& effective_url) {
777 // Non-extension, non-Instant URLs should generally use
778 // process-per-site-instance. Because we expect to use the effective URL,
779 // URLs for hosted apps (apart from bookmark apps) should have an extension
780 // scheme by now.
782 Profile* profile = Profile::FromBrowserContext(browser_context);
783 if (!profile)
784 return false;
786 if (chrome::ShouldAssignURLToInstantRenderer(effective_url, profile))
787 return true;
789 if (SigninManager::IsWebBasedSigninFlowURL(effective_url))
790 return true;
792 if (!effective_url.SchemeIs(extensions::kExtensionScheme))
793 return false;
795 ExtensionService* extension_service =
796 extensions::ExtensionSystem::Get(profile)->extension_service();
797 if (!extension_service)
798 return false;
800 const Extension* extension = extension_service->extensions()->
801 GetExtensionOrAppByURL(ExtensionURLInfo(effective_url));
802 if (!extension)
803 return false;
805 // If the URL is part of a hosted app that does not have the background
806 // permission, or that does not allow JavaScript access to the background
807 // page, we want to give each instance its own process to improve
808 // responsiveness.
809 if (extension->GetType() == Manifest::TYPE_HOSTED_APP) {
810 if (!extension->HasAPIPermission(APIPermission::kBackground) ||
811 !extensions::BackgroundInfo::AllowJSAccess(extension)) {
812 return false;
816 // Hosted apps that have script access to their background page must use
817 // process per site, since all instances can make synchronous calls to the
818 // background window. Other extensions should use process per site as well.
819 return true;
822 // These are treated as WebUI schemes but do not get WebUI bindings.
823 std::vector<std::string>
824 ChromeContentBrowserClient::GetAdditionalWebUISchemes() {
825 std::vector<std::string> additional_schemes;
826 additional_schemes.push_back(chrome::kChromeSearchScheme);
827 return additional_schemes;
830 net::URLRequestContextGetter*
831 ChromeContentBrowserClient::CreateRequestContext(
832 content::BrowserContext* browser_context,
833 content::ProtocolHandlerMap* protocol_handlers) {
834 Profile* profile = Profile::FromBrowserContext(browser_context);
835 return profile->CreateRequestContext(protocol_handlers);
838 net::URLRequestContextGetter*
839 ChromeContentBrowserClient::CreateRequestContextForStoragePartition(
840 content::BrowserContext* browser_context,
841 const base::FilePath& partition_path,
842 bool in_memory,
843 content::ProtocolHandlerMap* protocol_handlers) {
844 Profile* profile = Profile::FromBrowserContext(browser_context);
845 return profile->CreateRequestContextForStoragePartition(
846 partition_path, in_memory, protocol_handlers);
849 bool ChromeContentBrowserClient::IsHandledURL(const GURL& url) {
850 return ProfileIOData::IsHandledURL(url);
853 bool ChromeContentBrowserClient::IsSuitableHost(
854 content::RenderProcessHost* process_host,
855 const GURL& site_url) {
856 Profile* profile =
857 Profile::FromBrowserContext(process_host->GetBrowserContext());
858 // This may be NULL during tests. In that case, just assume any site can
859 // share any host.
860 if (!profile)
861 return true;
863 // Instant URLs should only be in the instant process and instant process
864 // should only have Instant URLs.
865 InstantService* instant_service =
866 InstantServiceFactory::GetForProfile(profile);
867 if (instant_service) {
868 bool is_instant_process = instant_service->IsInstantProcess(
869 process_host->GetID());
870 bool should_be_in_instant_process =
871 chrome::ShouldAssignURLToInstantRenderer(site_url, profile);
872 if (is_instant_process || should_be_in_instant_process)
873 return is_instant_process && should_be_in_instant_process;
876 SigninManager* signin_manager = SigninManagerFactory::GetForProfile(profile);
877 if (signin_manager && signin_manager->IsSigninProcess(process_host->GetID()))
878 return SigninManager::IsWebBasedSigninFlowURL(site_url);
880 ExtensionService* service =
881 extensions::ExtensionSystem::Get(profile)->extension_service();
882 extensions::ProcessMap* process_map = service->process_map();
884 // Don't allow the Task Manager to share a process with anything else.
885 // Otherwise it can affect the renderers it is observing.
886 // Note: we could create another RenderProcessHostPrivilege bucket for
887 // this to allow multiple chrome://tasks instances to share, but that's
888 // a very unlikely case without serious consequences.
889 if (site_url.GetOrigin() == GURL(chrome::kChromeUITaskManagerURL).GetOrigin())
890 return false;
892 // These may be NULL during tests. In that case, just assume any site can
893 // share any host.
894 if (!service || !process_map)
895 return true;
897 // Otherwise, just make sure the process privilege matches the privilege
898 // required by the site.
899 RenderProcessHostPrivilege privilege_required =
900 GetPrivilegeRequiredByUrl(site_url, service);
901 return GetProcessPrivilege(process_host, process_map, service) ==
902 privilege_required;
905 // This function is trying to limit the amount of processes used by extensions
906 // with background pages. It uses a globally set percentage of processes to
907 // run such extensions and if the limit is exceeded, it returns true, to
908 // indicate to the content module to group extensions together.
909 bool ChromeContentBrowserClient::ShouldTryToUseExistingProcessHost(
910 content::BrowserContext* browser_context, const GURL& url) {
911 // It has to be a valid URL for us to check for an extension.
912 if (!url.is_valid())
913 return false;
915 Profile* profile = Profile::FromBrowserContext(browser_context);
916 ExtensionService* service = !profile ? NULL :
917 extensions::ExtensionSystem::Get(profile)->extension_service();
918 if (!service)
919 return false;
921 // We have to have a valid extension with background page to proceed.
922 const Extension* extension =
923 service->extensions()->GetExtensionOrAppByURL(ExtensionURLInfo(url));
924 if (!extension)
925 return false;
926 if (!extensions::BackgroundInfo::HasBackgroundPage(extension))
927 return false;
929 std::set<int> process_ids;
930 size_t max_process_count =
931 content::RenderProcessHost::GetMaxRendererProcessCount();
933 // Go through all profiles to ensure we have total count of extension
934 // processes containing background pages, otherwise one profile can
935 // starve the other.
936 std::vector<Profile*> profiles = g_browser_process->profile_manager()->
937 GetLoadedProfiles();
938 for (size_t i = 0; i < profiles.size(); ++i) {
939 ExtensionProcessManager* epm =
940 extensions::ExtensionSystem::Get(profiles[i])->process_manager();
941 for (ExtensionProcessManager::const_iterator iter =
942 epm->background_hosts().begin();
943 iter != epm->background_hosts().end(); ++iter) {
944 const extensions::ExtensionHost* host = *iter;
945 process_ids.insert(host->render_process_host()->GetID());
949 if (process_ids.size() >
950 (max_process_count * chrome::kMaxShareOfExtensionProcesses)) {
951 return true;
954 return false;
957 void ChromeContentBrowserClient::SiteInstanceGotProcess(
958 SiteInstance* site_instance) {
959 CHECK(site_instance->HasProcess());
961 Profile* profile = Profile::FromBrowserContext(
962 site_instance->GetBrowserContext());
963 if (!profile)
964 return;
966 // Remember the ID of the Instant process to signal the renderer process
967 // on startup in |AppendExtraCommandLineSwitches| below.
968 if (chrome::ShouldAssignURLToInstantRenderer(
969 site_instance->GetSiteURL(), profile)) {
970 InstantService* instant_service =
971 InstantServiceFactory::GetForProfile(profile);
972 if (instant_service)
973 instant_service->AddInstantProcess(site_instance->GetProcess()->GetID());
976 // We only expect there to be one signin process as we use process-per-site
977 // for signin URLs. The signin process will be cleared from SigninManager
978 // when the renderer is destroyed.
979 if (SigninManager::IsWebBasedSigninFlowURL(site_instance->GetSiteURL())) {
980 SigninManager* signin_manager =
981 SigninManagerFactory::GetForProfile(profile);
982 if (signin_manager)
983 signin_manager->SetSigninProcess(site_instance->GetProcess()->GetID());
986 ExtensionService* service =
987 extensions::ExtensionSystem::Get(profile)->extension_service();
988 if (!service)
989 return;
991 const Extension* extension =
992 service->extensions()->GetExtensionOrAppByURL(ExtensionURLInfo(
993 site_instance->GetSiteURL()));
994 if (!extension)
995 return;
997 service->process_map()->Insert(extension->id(),
998 site_instance->GetProcess()->GetID(),
999 site_instance->GetId());
1000 BrowserThread::PostTask(
1001 BrowserThread::IO, FROM_HERE,
1002 base::Bind(&ExtensionInfoMap::RegisterExtensionProcess,
1003 extensions::ExtensionSystem::Get(profile)->info_map(),
1004 extension->id(),
1005 site_instance->GetProcess()->GetID(),
1006 site_instance->GetId()));
1009 void ChromeContentBrowserClient::SiteInstanceDeleting(
1010 SiteInstance* site_instance) {
1011 if (!site_instance->HasProcess())
1012 return;
1014 Profile* profile = Profile::FromBrowserContext(
1015 site_instance->GetBrowserContext());
1016 ExtensionService* service =
1017 extensions::ExtensionSystem::Get(profile)->extension_service();
1018 if (!service)
1019 return;
1021 const Extension* extension =
1022 service->extensions()->GetExtensionOrAppByURL(
1023 ExtensionURLInfo(site_instance->GetSiteURL()));
1024 if (!extension)
1025 return;
1027 service->process_map()->Remove(extension->id(),
1028 site_instance->GetProcess()->GetID(),
1029 site_instance->GetId());
1030 BrowserThread::PostTask(
1031 BrowserThread::IO, FROM_HERE,
1032 base::Bind(&ExtensionInfoMap::UnregisterExtensionProcess,
1033 extensions::ExtensionSystem::Get(profile)->info_map(),
1034 extension->id(),
1035 site_instance->GetProcess()->GetID(),
1036 site_instance->GetId()));
1039 bool ChromeContentBrowserClient::ShouldSwapProcessesForNavigation(
1040 SiteInstance* site_instance,
1041 const GURL& current_url,
1042 const GURL& new_url) {
1043 if (current_url.is_empty()) {
1044 // Always choose a new process when navigating to extension URLs. The
1045 // process grouping logic will combine all of a given extension's pages
1046 // into the same process.
1047 if (new_url.SchemeIs(extensions::kExtensionScheme))
1048 return true;
1050 return false;
1053 // Also, we must switch if one is an extension and the other is not the exact
1054 // same extension.
1055 if (current_url.SchemeIs(extensions::kExtensionScheme) ||
1056 new_url.SchemeIs(extensions::kExtensionScheme)) {
1057 if (current_url.GetOrigin() != new_url.GetOrigin())
1058 return true;
1061 // The checks below only matter if we can retrieve which extensions are
1062 // installed.
1063 Profile* profile =
1064 Profile::FromBrowserContext(site_instance->GetBrowserContext());
1065 ExtensionService* service =
1066 extensions::ExtensionSystem::Get(profile)->extension_service();
1067 if (!service)
1068 return false;
1070 // We must swap if the URL is for an extension and we are not using an
1071 // extension process.
1072 const Extension* new_extension =
1073 service->extensions()->GetExtensionOrAppByURL(ExtensionURLInfo(new_url));
1074 // Ignore all hosted apps except the Chrome Web Store, since they do not
1075 // require their own BrowsingInstance (e.g., postMessage is ok).
1076 if (new_extension &&
1077 new_extension->is_hosted_app() &&
1078 new_extension->id() != extension_misc::kWebStoreAppId)
1079 new_extension = NULL;
1080 if (new_extension &&
1081 site_instance->HasProcess() &&
1082 !service->process_map()->Contains(new_extension->id(),
1083 site_instance->GetProcess()->GetID()))
1084 return true;
1086 return false;
1089 bool ChromeContentBrowserClient::ShouldSwapProcessesForRedirect(
1090 content::ResourceContext* resource_context, const GURL& current_url,
1091 const GURL& new_url) {
1092 ProfileIOData* io_data = ProfileIOData::FromResourceContext(resource_context);
1093 return extensions::CrossesExtensionProcessBoundary(
1094 io_data->GetExtensionInfoMap()->extensions(),
1095 ExtensionURLInfo(current_url), ExtensionURLInfo(new_url), false);
1098 std::string ChromeContentBrowserClient::GetCanonicalEncodingNameByAliasName(
1099 const std::string& alias_name) {
1100 return CharacterEncoding::GetCanonicalEncodingNameByAliasName(alias_name);
1103 void ChromeContentBrowserClient::AppendExtraCommandLineSwitches(
1104 CommandLine* command_line, int child_process_id) {
1105 #if defined(USE_LINUX_BREAKPAD)
1106 if (IsCrashReporterEnabled()) {
1107 command_line->AppendSwitchASCII(switches::kEnableCrashReporter,
1108 child_process_logging::GetClientId() + "," + base::GetLinuxDistro());
1110 #elif defined(OS_MACOSX)
1111 if (IsCrashReporterEnabled()) {
1112 command_line->AppendSwitchASCII(switches::kEnableCrashReporter,
1113 child_process_logging::GetClientId());
1115 #endif // OS_MACOSX
1117 if (logging::DialogsAreSuppressed())
1118 command_line->AppendSwitch(switches::kNoErrorDialogs);
1120 std::string process_type =
1121 command_line->GetSwitchValueASCII(switches::kProcessType);
1122 const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
1124 if (browser_command_line.HasSwitch(switches::kChromeFrame))
1125 command_line->AppendSwitch(switches::kChromeFrame);
1127 if (process_type == switches::kRendererProcess) {
1128 base::FilePath user_data_dir =
1129 browser_command_line.GetSwitchValuePath(switches::kUserDataDir);
1130 if (!user_data_dir.empty())
1131 command_line->AppendSwitchPath(switches::kUserDataDir, user_data_dir);
1132 #if defined(OS_CHROMEOS)
1133 const std::string& login_profile =
1134 browser_command_line.GetSwitchValueASCII(
1135 chromeos::switches::kLoginProfile);
1136 if (!login_profile.empty())
1137 command_line->AppendSwitchASCII(
1138 chromeos::switches::kLoginProfile, login_profile);
1139 #endif
1141 content::RenderProcessHost* process =
1142 content::RenderProcessHost::FromID(child_process_id);
1143 if (process) {
1144 Profile* profile = Profile::FromBrowserContext(
1145 process->GetBrowserContext());
1146 ExtensionService* extension_service =
1147 extensions::ExtensionSystem::Get(profile)->extension_service();
1148 if (extension_service) {
1149 extensions::ProcessMap* process_map = extension_service->process_map();
1150 if (process_map && process_map->Contains(process->GetID()))
1151 command_line->AppendSwitch(switches::kExtensionProcess);
1154 PrefService* prefs = profile->GetPrefs();
1155 // Currently this pref is only registered if applied via a policy.
1156 if (prefs->HasPrefPath(prefs::kDisable3DAPIs) &&
1157 prefs->GetBoolean(prefs::kDisable3DAPIs)) {
1158 // Turn this policy into a command line switch.
1159 command_line->AppendSwitch(switches::kDisable3DAPIs);
1162 // Disable client-side phishing detection in the renderer if it is
1163 // disabled in the Profile preferences or the browser process.
1164 if (!prefs->GetBoolean(prefs::kSafeBrowsingEnabled) ||
1165 !g_browser_process->safe_browsing_detection_service()) {
1166 command_line->AppendSwitch(
1167 switches::kDisableClientSidePhishingDetection);
1170 if (!prefs->GetBoolean(prefs::kPrintPreviewDisabled))
1171 command_line->AppendSwitch(switches::kRendererPrintPreview);
1173 InstantService* instant_service =
1174 InstantServiceFactory::GetForProfile(profile);
1175 if (instant_service &&
1176 instant_service->IsInstantProcess(process->GetID()))
1177 command_line->AppendSwitch(switches::kInstantProcess);
1179 SigninManager* signin_manager =
1180 SigninManagerFactory::GetForProfile(profile);
1181 if (signin_manager && signin_manager->IsSigninProcess(process->GetID()))
1182 command_line->AppendSwitch(switches::kSigninProcess);
1185 if (content::IsThreadedCompositingEnabled())
1186 command_line->AppendSwitch(switches::kEnableThreadedCompositing);
1188 #if defined(ENABLE_MESSAGE_CENTER)
1189 if (message_center::IsRichNotificationEnabled())
1190 command_line->AppendSwitch(switches::kDisableHTMLNotifications);
1191 #endif
1193 // Please keep this in alphabetical order.
1194 static const char* const kSwitchNames[] = {
1195 autofill::switches::kEnableExperimentalFormFilling,
1196 switches::kAllowRequestOSFileHandleAPI,
1197 switches::kAllowHTTPBackgroundPage,
1198 switches::kAllowLegacyExtensionManifests,
1199 switches::kAllowScriptingGallery,
1200 switches::kAppsCheckoutURL,
1201 switches::kAppsGalleryURL,
1202 switches::kCloudPrintServiceURL,
1203 switches::kDebugPrint,
1204 switches::kDisableBundledPpapiFlash,
1205 switches::kDisableExtensionsResourceWhitelist,
1206 switches::kDisableScriptedPrintThrottling,
1207 switches::kDumpHistogramsOnExit,
1208 switches::kEnableAdview,
1209 switches::kEnableAdviewSrcAttribute,
1210 switches::kEnableBenchmarking,
1211 switches::kEnableExperimentalExtensionApis,
1212 switches::kEnableIPCFuzzing,
1213 switches::kEnableInteractiveAutocomplete,
1214 switches::kEnableNaCl,
1215 switches::kEnableNetBenchmarking,
1216 switches::kEnablePasswordGeneration,
1217 switches::kEnablePnacl,
1218 switches::kEnableWatchdog,
1219 switches::kExtensionsOnChromeURLs,
1220 switches::kMemoryProfiling,
1221 switches::kMessageLoopHistogrammer,
1222 switches::kNoJsRandomness,
1223 switches::kPlaybackMode,
1224 switches::kPpapiFlashArgs,
1225 switches::kPpapiFlashInProcess,
1226 switches::kPpapiFlashPath,
1227 switches::kPpapiFlashVersion,
1228 switches::kProfilingAtStart,
1229 switches::kProfilingFile,
1230 switches::kProfilingFlush,
1231 switches::kRecordMode,
1232 switches::kSilentDumpOnDCHECK,
1233 switches::kSpdyProxyAuthOrigin,
1234 switches::kWhitelistedExtensionID,
1237 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1238 arraysize(kSwitchNames));
1239 } else if (process_type == switches::kUtilityProcess) {
1240 static const char* const kSwitchNames[] = {
1241 switches::kAllowHTTPBackgroundPage,
1242 switches::kEnableExperimentalExtensionApis,
1243 switches::kWhitelistedExtensionID,
1246 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1247 arraysize(kSwitchNames));
1248 } else if (process_type == switches::kPluginProcess) {
1249 static const char* const kSwitchNames[] = {
1250 #if defined(OS_CHROMEOS)
1251 chromeos::switches::kLoginProfile,
1252 #endif
1253 switches::kMemoryProfiling,
1254 switches::kSilentDumpOnDCHECK,
1255 switches::kUserDataDir,
1258 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1259 arraysize(kSwitchNames));
1260 } else if (process_type == switches::kZygoteProcess) {
1261 static const char* const kSwitchNames[] = {
1262 switches::kUserDataDir, // Make logs go to the right file.
1263 // Load (in-process) Pepper plugins in-process in the zygote pre-sandbox.
1264 switches::kDisableBundledPpapiFlash,
1265 switches::kPpapiFlashInProcess,
1266 switches::kPpapiFlashPath,
1267 switches::kPpapiFlashVersion,
1270 command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1271 arraysize(kSwitchNames));
1272 } else if (process_type == switches::kGpuProcess) {
1273 base::FilePath user_data_dir =
1274 browser_command_line.GetSwitchValuePath(switches::kUserDataDir);
1275 if (!user_data_dir.empty())
1276 command_line->AppendSwitchPath(switches::kUserDataDir, user_data_dir);
1277 // If --ignore-gpu-blacklist is passed in, don't send in crash reports
1278 // because GPU is expected to be unreliable.
1279 if (browser_command_line.HasSwitch(switches::kIgnoreGpuBlacklist) &&
1280 !command_line->HasSwitch(switches::kDisableBreakpad))
1281 command_line->AppendSwitch(switches::kDisableBreakpad);
1284 // The command line switch kEnableBenchmarking needs to be specified along
1285 // with the kEnableStatsTable switch to ensure that the stats table global
1286 // is initialized correctly.
1287 if (command_line->HasSwitch(switches::kEnableBenchmarking))
1288 DCHECK(command_line->HasSwitch(switches::kEnableStatsTable));
1291 std::string ChromeContentBrowserClient::GetApplicationLocale() {
1292 if (BrowserThread::CurrentlyOn(BrowserThread::IO))
1293 return g_io_thread_application_locale.Get();
1294 return g_browser_process->GetApplicationLocale();
1297 std::string ChromeContentBrowserClient::GetAcceptLangs(
1298 content::BrowserContext* context) {
1299 Profile* profile = Profile::FromBrowserContext(context);
1300 return profile->GetPrefs()->GetString(prefs::kAcceptLanguages);
1303 gfx::ImageSkia* ChromeContentBrowserClient::GetDefaultFavicon() {
1304 ResourceBundle& rb = ResourceBundle::GetSharedInstance();
1305 return rb.GetImageSkiaNamed(IDR_DEFAULT_FAVICON);
1308 bool ChromeContentBrowserClient::AllowAppCache(
1309 const GURL& manifest_url,
1310 const GURL& first_party,
1311 content::ResourceContext* context) {
1312 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1313 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1314 return io_data->GetCookieSettings()->
1315 IsSettingCookieAllowed(manifest_url, first_party);
1318 bool ChromeContentBrowserClient::AllowGetCookie(
1319 const GURL& url,
1320 const GURL& first_party,
1321 const net::CookieList& cookie_list,
1322 content::ResourceContext* context,
1323 int render_process_id,
1324 int render_view_id) {
1325 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1326 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1327 bool allow = io_data->GetCookieSettings()->
1328 IsReadingCookieAllowed(url, first_party);
1330 BrowserThread::PostTask(
1331 BrowserThread::UI, FROM_HERE,
1332 base::Bind(&TabSpecificContentSettings::CookiesRead, render_process_id,
1333 render_view_id, url, first_party, cookie_list, !allow));
1334 return allow;
1337 bool ChromeContentBrowserClient::AllowSetCookie(
1338 const GURL& url,
1339 const GURL& first_party,
1340 const std::string& cookie_line,
1341 content::ResourceContext* context,
1342 int render_process_id,
1343 int render_view_id,
1344 net::CookieOptions* options) {
1345 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1346 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1347 CookieSettings* cookie_settings = io_data->GetCookieSettings();
1348 bool allow = cookie_settings->IsSettingCookieAllowed(url, first_party);
1350 BrowserThread::PostTask(
1351 BrowserThread::UI, FROM_HERE,
1352 base::Bind(&TabSpecificContentSettings::CookieChanged, render_process_id,
1353 render_view_id, url, first_party, cookie_line, *options,
1354 !allow));
1355 return allow;
1358 bool ChromeContentBrowserClient::AllowSaveLocalState(
1359 content::ResourceContext* context) {
1360 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1361 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1362 CookieSettings* cookie_settings = io_data->GetCookieSettings();
1363 ContentSetting setting = cookie_settings->GetDefaultCookieSetting(NULL);
1365 // TODO(bauerb): Should we also disallow local state if the default is BLOCK?
1366 // Could we even support per-origin settings?
1367 return setting != CONTENT_SETTING_SESSION_ONLY;
1370 bool ChromeContentBrowserClient::AllowWorkerDatabase(
1371 const GURL& url,
1372 const string16& name,
1373 const string16& display_name,
1374 unsigned long estimated_size,
1375 content::ResourceContext* context,
1376 const std::vector<std::pair<int, int> >& render_views) {
1377 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1378 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1379 CookieSettings* cookie_settings = io_data->GetCookieSettings();
1380 bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1382 // Record access to database for potential display in UI.
1383 std::vector<std::pair<int, int> >::const_iterator i;
1384 for (i = render_views.begin(); i != render_views.end(); ++i) {
1385 BrowserThread::PostTask(
1386 BrowserThread::UI, FROM_HERE,
1387 base::Bind(&TabSpecificContentSettings::WebDatabaseAccessed,
1388 i->first, i->second, url, name, display_name, !allow));
1391 return allow;
1394 bool ChromeContentBrowserClient::AllowWorkerFileSystem(
1395 const GURL& url,
1396 content::ResourceContext* context,
1397 const std::vector<std::pair<int, int> >& render_views) {
1398 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1399 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1400 CookieSettings* cookie_settings = io_data->GetCookieSettings();
1401 bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1403 // Record access to file system for potential display in UI.
1404 std::vector<std::pair<int, int> >::const_iterator i;
1405 for (i = render_views.begin(); i != render_views.end(); ++i) {
1406 BrowserThread::PostTask(
1407 BrowserThread::UI, FROM_HERE,
1408 base::Bind(&TabSpecificContentSettings::FileSystemAccessed,
1409 i->first, i->second, url, !allow));
1412 return allow;
1415 bool ChromeContentBrowserClient::AllowWorkerIndexedDB(
1416 const GURL& url,
1417 const string16& name,
1418 content::ResourceContext* context,
1419 const std::vector<std::pair<int, int> >& render_views) {
1420 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1421 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1422 CookieSettings* cookie_settings = io_data->GetCookieSettings();
1423 bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1425 // Record access to IndexedDB for potential display in UI.
1426 std::vector<std::pair<int, int> >::const_iterator i;
1427 for (i = render_views.begin(); i != render_views.end(); ++i) {
1428 BrowserThread::PostTask(
1429 BrowserThread::UI, FROM_HERE,
1430 base::Bind(&TabSpecificContentSettings::IndexedDBAccessed,
1431 i->first, i->second, url, name, !allow));
1434 return allow;
1437 net::URLRequestContext*
1438 ChromeContentBrowserClient::OverrideRequestContextForURL(
1439 const GURL& url, content::ResourceContext* context) {
1440 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1441 if (url.SchemeIs(extensions::kExtensionScheme)) {
1442 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1443 return io_data->extensions_request_context();
1446 return NULL;
1449 QuotaPermissionContext*
1450 ChromeContentBrowserClient::CreateQuotaPermissionContext() {
1451 return new ChromeQuotaPermissionContext();
1454 void ChromeContentBrowserClient::AllowCertificateError(
1455 int render_process_id,
1456 int render_view_id,
1457 int cert_error,
1458 const net::SSLInfo& ssl_info,
1459 const GURL& request_url,
1460 ResourceType::Type resource_type,
1461 bool overridable,
1462 bool strict_enforcement,
1463 const base::Callback<void(bool)>& callback,
1464 bool* cancel_request) {
1465 if (resource_type != ResourceType::MAIN_FRAME) {
1466 // A sub-resource has a certificate error. The user doesn't really
1467 // have a context for making the right decision, so block the
1468 // request hard, without an info bar to allow showing the insecure
1469 // content.
1470 *cancel_request = true;
1471 return;
1474 // If the tab is being prerendered, cancel the prerender and the request.
1475 WebContents* tab = tab_util::GetWebContentsByID(
1476 render_process_id, render_view_id);
1477 if (!tab) {
1478 NOTREACHED();
1479 return;
1481 prerender::PrerenderManager* prerender_manager =
1482 prerender::PrerenderManagerFactory::GetForProfile(
1483 Profile::FromBrowserContext(tab->GetBrowserContext()));
1484 if (prerender_manager && prerender_manager->IsWebContentsPrerendering(tab,
1485 NULL)) {
1486 if (prerender_manager->prerender_tracker()->TryCancel(
1487 render_process_id, render_view_id,
1488 prerender::FINAL_STATUS_SSL_ERROR)) {
1489 *cancel_request = true;
1490 return;
1494 #if defined(ENABLE_CAPTIVE_PORTAL_DETECTION)
1495 captive_portal::CaptivePortalTabHelper* captive_portal_tab_helper =
1496 captive_portal::CaptivePortalTabHelper::FromWebContents(tab);
1497 if (captive_portal_tab_helper)
1498 captive_portal_tab_helper->OnSSLCertError(ssl_info);
1499 #endif
1501 // Otherwise, display an SSL blocking page.
1502 new SSLBlockingPage(tab, cert_error, ssl_info, request_url, overridable,
1503 strict_enforcement, callback);
1506 void ChromeContentBrowserClient::SelectClientCertificate(
1507 int render_process_id,
1508 int render_view_id,
1509 const net::HttpNetworkSession* network_session,
1510 net::SSLCertRequestInfo* cert_request_info,
1511 const base::Callback<void(net::X509Certificate*)>& callback) {
1512 WebContents* tab = tab_util::GetWebContentsByID(
1513 render_process_id, render_view_id);
1514 if (!tab) {
1515 NOTREACHED();
1516 return;
1519 GURL requesting_url("https://" + cert_request_info->host_and_port);
1520 DCHECK(requesting_url.is_valid()) << "Invalid URL string: https://"
1521 << cert_request_info->host_and_port;
1523 Profile* profile = Profile::FromBrowserContext(tab->GetBrowserContext());
1524 scoped_ptr<Value> filter(
1525 profile->GetHostContentSettingsMap()->GetWebsiteSetting(
1526 requesting_url,
1527 requesting_url,
1528 CONTENT_SETTINGS_TYPE_AUTO_SELECT_CERTIFICATE,
1529 std::string(), NULL));
1531 if (filter.get()) {
1532 // Try to automatically select a client certificate.
1533 if (filter->IsType(Value::TYPE_DICTIONARY)) {
1534 DictionaryValue* filter_dict =
1535 static_cast<DictionaryValue*>(filter.get());
1537 const std::vector<scoped_refptr<net::X509Certificate> >&
1538 all_client_certs = cert_request_info->client_certs;
1539 for (size_t i = 0; i < all_client_certs.size(); ++i) {
1540 if (CertMatchesFilter(*all_client_certs[i], *filter_dict)) {
1541 // Use the first certificate that is matched by the filter.
1542 callback.Run(all_client_certs[i]);
1543 return;
1546 } else {
1547 NOTREACHED();
1551 SSLTabHelper* ssl_tab_helper = SSLTabHelper::FromWebContents(tab);
1552 if (!ssl_tab_helper) {
1553 // If there is no SSLTabHelper for the given WebContents then we can't
1554 // show the user a dialog to select a client certificate. So we simply
1555 // proceed with no client certificate.
1556 callback.Run(NULL);
1557 return;
1559 ssl_tab_helper->ShowClientCertificateRequestDialog(
1560 network_session, cert_request_info, callback);
1563 void ChromeContentBrowserClient::AddCertificate(
1564 net::URLRequest* request,
1565 net::CertificateMimeType cert_type,
1566 const void* cert_data,
1567 size_t cert_size,
1568 int render_process_id,
1569 int render_view_id) {
1570 chrome::SSLAddCertificate(request, cert_type, cert_data, cert_size,
1571 render_process_id, render_view_id);
1574 content::MediaObserver* ChromeContentBrowserClient::GetMediaObserver() {
1575 return MediaCaptureDevicesDispatcher::GetInstance();
1578 void ChromeContentBrowserClient::RequestDesktopNotificationPermission(
1579 const GURL& source_origin,
1580 int callback_context,
1581 int render_process_id,
1582 int render_view_id) {
1583 #if defined(ENABLE_NOTIFICATIONS)
1584 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1585 WebContents* contents =
1586 tab_util::GetWebContentsByID(render_process_id, render_view_id);
1587 if (!contents) {
1588 NOTREACHED();
1589 return;
1592 // Skip showing the infobar if the request comes from an extension, and that
1593 // extension has the 'notify' permission. (If the extension does not have the
1594 // permission, the user will still be prompted.)
1595 Profile* profile = Profile::FromBrowserContext(contents->GetBrowserContext());
1596 ExtensionService* service =
1597 extensions::ExtensionSystem::Get(profile)->extension_service();
1598 const Extension* extension = !service ? NULL :
1599 service->extensions()->GetExtensionOrAppByURL(ExtensionURLInfo(
1600 source_origin));
1601 RenderViewHost* rvh =
1602 RenderViewHost::FromID(render_process_id, render_view_id);
1603 if (IsExtensionWithPermissionOrSuggestInConsole(
1604 APIPermission::kNotification, extension, rvh)) {
1605 if (rvh)
1606 rvh->DesktopNotificationPermissionRequestDone(callback_context);
1607 return;
1610 DesktopNotificationService* notifications =
1611 DesktopNotificationServiceFactory::GetForProfile(profile);
1612 notifications->RequestPermission(source_origin, render_process_id,
1613 render_view_id, callback_context, contents);
1614 #else
1615 NOTIMPLEMENTED();
1616 #endif
1619 WebKit::WebNotificationPresenter::Permission
1620 ChromeContentBrowserClient::CheckDesktopNotificationPermission(
1621 const GURL& source_origin,
1622 content::ResourceContext* context,
1623 int render_process_id) {
1624 #if defined(ENABLE_NOTIFICATIONS)
1625 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1626 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1627 if (io_data->GetExtensionInfoMap()->SecurityOriginHasAPIPermission(
1628 source_origin, render_process_id,
1629 APIPermission::kNotification))
1630 return WebKit::WebNotificationPresenter::PermissionAllowed;
1632 // Fall back to the regular notification preferences, which works on an
1633 // origin basis.
1634 return io_data->GetNotificationService() ?
1635 io_data->GetNotificationService()->HasPermission(source_origin) :
1636 WebKit::WebNotificationPresenter::PermissionNotAllowed;
1637 #else
1638 return WebKit::WebNotificationPresenter::PermissionAllowed;
1639 #endif
1642 void ChromeContentBrowserClient::ShowDesktopNotification(
1643 const content::ShowDesktopNotificationHostMsgParams& params,
1644 int render_process_id,
1645 int render_view_id,
1646 bool worker) {
1647 #if defined(ENABLE_NOTIFICATIONS)
1648 RenderViewHost* rvh = RenderViewHost::FromID(
1649 render_process_id, render_view_id);
1650 if (!rvh) {
1651 NOTREACHED();
1652 return;
1655 content::RenderProcessHost* process = rvh->GetProcess();
1656 Profile* profile = Profile::FromBrowserContext(process->GetBrowserContext());
1657 DesktopNotificationService* service =
1658 DesktopNotificationServiceFactory::GetForProfile(profile);
1659 service->ShowDesktopNotification(
1660 params, render_process_id, render_view_id,
1661 worker ? DesktopNotificationService::WorkerNotification :
1662 DesktopNotificationService::PageNotification);
1663 #else
1664 NOTIMPLEMENTED();
1665 #endif
1668 void ChromeContentBrowserClient::CancelDesktopNotification(
1669 int render_process_id,
1670 int render_view_id,
1671 int notification_id) {
1672 #if defined(ENABLE_NOTIFICATIONS)
1673 RenderViewHost* rvh = RenderViewHost::FromID(
1674 render_process_id, render_view_id);
1675 if (!rvh) {
1676 NOTREACHED();
1677 return;
1680 content::RenderProcessHost* process = rvh->GetProcess();
1681 Profile* profile = Profile::FromBrowserContext(process->GetBrowserContext());
1682 DesktopNotificationService* service =
1683 DesktopNotificationServiceFactory::GetForProfile(profile);
1684 service->CancelDesktopNotification(
1685 render_process_id, render_view_id, notification_id);
1686 #else
1687 NOTIMPLEMENTED();
1688 #endif
1691 bool ChromeContentBrowserClient::CanCreateWindow(
1692 const GURL& opener_url,
1693 const GURL& source_origin,
1694 WindowContainerType container_type,
1695 content::ResourceContext* context,
1696 int render_process_id,
1697 bool* no_javascript_access) {
1698 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1700 *no_javascript_access = false;
1702 // If the opener is trying to create a background window but doesn't have
1703 // the appropriate permission, fail the attempt.
1704 if (container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {
1705 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1706 ExtensionInfoMap* map = io_data->GetExtensionInfoMap();
1708 if (!map->SecurityOriginHasAPIPermission(
1709 source_origin,
1710 render_process_id,
1711 APIPermission::kBackground)) {
1712 return false;
1715 // Note: this use of GetExtensionOrAppByURL is safe but imperfect. It may
1716 // return a recently installed Extension even if this CanCreateWindow call
1717 // was made by an old copy of the page in a normal web process. That's ok,
1718 // because the permission check above would have caused an early return
1719 // already. We must use the full URL to find hosted apps, though, and not
1720 // just the origin.
1721 const Extension* extension = map->extensions().GetExtensionOrAppByURL(
1722 ExtensionURLInfo(opener_url));
1723 if (extension && !extensions::BackgroundInfo::AllowJSAccess(extension))
1724 *no_javascript_access = true;
1727 // No new browser window (popup or tab) in app mode.
1728 if (container_type == WINDOW_CONTAINER_TYPE_NORMAL &&
1729 chrome::IsRunningInForcedAppMode()) {
1730 return false;
1733 return true;
1736 std::string ChromeContentBrowserClient::GetWorkerProcessTitle(
1737 const GURL& url, content::ResourceContext* context) {
1738 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1739 // Check if it's an extension-created worker, in which case we want to use
1740 // the name of the extension.
1741 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1742 const Extension* extension =
1743 io_data->GetExtensionInfoMap()->extensions().GetByID(url.host());
1744 return extension ? extension->name() : std::string();
1747 void ChromeContentBrowserClient::ResourceDispatcherHostCreated() {
1748 return g_browser_process->ResourceDispatcherHostCreated();
1751 content::SpeechRecognitionManagerDelegate*
1752 ChromeContentBrowserClient::GetSpeechRecognitionManagerDelegate() {
1753 #if defined(ENABLE_INPUT_SPEECH)
1754 return new speech::ChromeSpeechRecognitionManagerDelegate();
1755 #else
1756 return NULL;
1757 #endif
1760 net::NetLog* ChromeContentBrowserClient::GetNetLog() {
1761 return g_browser_process->net_log();
1764 AccessTokenStore* ChromeContentBrowserClient::CreateAccessTokenStore() {
1765 return new ChromeAccessTokenStore();
1768 bool ChromeContentBrowserClient::IsFastShutdownPossible() {
1769 return true;
1772 void ChromeContentBrowserClient::OverrideWebkitPrefs(
1773 RenderViewHost* rvh, const GURL& url, WebPreferences* web_prefs) {
1774 Profile* profile = Profile::FromBrowserContext(
1775 rvh->GetProcess()->GetBrowserContext());
1776 PrefService* prefs = profile->GetPrefs();
1778 FillFontFamilyMap(prefs, prefs::kWebKitStandardFontFamilyMap,
1779 &web_prefs->standard_font_family_map);
1780 FillFontFamilyMap(prefs, prefs::kWebKitFixedFontFamilyMap,
1781 &web_prefs->fixed_font_family_map);
1782 FillFontFamilyMap(prefs, prefs::kWebKitSerifFontFamilyMap,
1783 &web_prefs->serif_font_family_map);
1784 FillFontFamilyMap(prefs, prefs::kWebKitSansSerifFontFamilyMap,
1785 &web_prefs->sans_serif_font_family_map);
1786 FillFontFamilyMap(prefs, prefs::kWebKitCursiveFontFamilyMap,
1787 &web_prefs->cursive_font_family_map);
1788 FillFontFamilyMap(prefs, prefs::kWebKitFantasyFontFamilyMap,
1789 &web_prefs->fantasy_font_family_map);
1790 FillFontFamilyMap(prefs, prefs::kWebKitPictographFontFamilyMap,
1791 &web_prefs->pictograph_font_family_map);
1793 web_prefs->default_font_size =
1794 prefs->GetInteger(prefs::kWebKitDefaultFontSize);
1795 web_prefs->default_fixed_font_size =
1796 prefs->GetInteger(prefs::kWebKitDefaultFixedFontSize);
1797 web_prefs->minimum_font_size =
1798 prefs->GetInteger(prefs::kWebKitMinimumFontSize);
1799 web_prefs->minimum_logical_font_size =
1800 prefs->GetInteger(prefs::kWebKitMinimumLogicalFontSize);
1802 web_prefs->default_encoding = prefs->GetString(prefs::kDefaultCharset);
1804 web_prefs->javascript_can_open_windows_automatically =
1805 prefs->GetBoolean(prefs::kWebKitJavascriptCanOpenWindowsAutomatically);
1806 web_prefs->dom_paste_enabled =
1807 prefs->GetBoolean(prefs::kWebKitDomPasteEnabled);
1808 web_prefs->shrinks_standalone_images_to_fit =
1809 prefs->GetBoolean(prefs::kWebKitShrinksStandaloneImagesToFit);
1810 const DictionaryValue* inspector_settings =
1811 prefs->GetDictionary(prefs::kWebKitInspectorSettings);
1812 if (inspector_settings) {
1813 for (DictionaryValue::Iterator iter(*inspector_settings); !iter.IsAtEnd();
1814 iter.Advance()) {
1815 std::string value;
1816 if (iter.value().GetAsString(&value)) {
1817 web_prefs->inspector_settings.push_back(
1818 std::make_pair(iter.key(), value));
1822 web_prefs->tabs_to_links = prefs->GetBoolean(prefs::kWebkitTabsToLinks);
1824 if (!prefs->GetBoolean(prefs::kWebKitJavascriptEnabled))
1825 web_prefs->javascript_enabled = false;
1826 if (!prefs->GetBoolean(prefs::kWebKitWebSecurityEnabled))
1827 web_prefs->web_security_enabled = false;
1828 if (!prefs->GetBoolean(prefs::kWebKitPluginsEnabled))
1829 web_prefs->plugins_enabled = false;
1830 if (!prefs->GetBoolean(prefs::kWebKitJavaEnabled))
1831 web_prefs->java_enabled = false;
1832 web_prefs->loads_images_automatically =
1833 prefs->GetBoolean(prefs::kWebKitLoadsImagesAutomatically);
1835 if (prefs->GetBoolean(prefs::kDisable3DAPIs))
1836 web_prefs->experimental_webgl_enabled = false;
1838 web_prefs->memory_info_enabled =
1839 prefs->GetBoolean(prefs::kEnableMemoryInfo);
1840 web_prefs->allow_displaying_insecure_content =
1841 prefs->GetBoolean(prefs::kWebKitAllowDisplayingInsecureContent);
1842 web_prefs->allow_running_insecure_content =
1843 prefs->GetBoolean(prefs::kWebKitAllowRunningInsecureContent);
1844 #if defined(OS_ANDROID)
1845 web_prefs->font_scale_factor =
1846 static_cast<float>(prefs->GetDouble(prefs::kWebKitFontScaleFactor));
1847 web_prefs->force_enable_zoom =
1848 prefs->GetBoolean(prefs::kWebKitForceEnableZoom);
1849 #if defined(GOOGLE_TV)
1850 web_prefs->user_gesture_required_for_media_playback = false;
1851 #endif
1852 #endif
1853 web_prefs->password_echo_enabled = browser_defaults::kPasswordEchoEnabled;
1855 // The user stylesheet watcher may not exist in a testing profile.
1856 UserStyleSheetWatcher* user_style_sheet_watcher =
1857 UserStyleSheetWatcherFactory::GetForProfile(profile);
1858 if (user_style_sheet_watcher) {
1859 web_prefs->user_style_sheet_enabled = true;
1860 web_prefs->user_style_sheet_location =
1861 user_style_sheet_watcher->user_style_sheet();
1862 } else {
1863 web_prefs->user_style_sheet_enabled = false;
1866 web_prefs->asynchronous_spell_checking_enabled = true;
1867 web_prefs->unified_textchecker_enabled = true;
1869 web_prefs->uses_universal_detector =
1870 prefs->GetBoolean(prefs::kWebKitUsesUniversalDetector);
1871 web_prefs->text_areas_are_resizable =
1872 prefs->GetBoolean(prefs::kWebKitTextAreasAreResizable);
1873 web_prefs->hyperlink_auditing_enabled =
1874 prefs->GetBoolean(prefs::kEnableHyperlinkAuditing);
1876 // Make sure we will set the default_encoding with canonical encoding name.
1877 web_prefs->default_encoding =
1878 CharacterEncoding::GetCanonicalEncodingNameByAliasName(
1879 web_prefs->default_encoding);
1880 if (web_prefs->default_encoding.empty()) {
1881 prefs->ClearPref(prefs::kDefaultCharset);
1882 web_prefs->default_encoding = prefs->GetString(prefs::kDefaultCharset);
1884 DCHECK(!web_prefs->default_encoding.empty());
1886 if (content::IsForceCompositingModeEnabled())
1887 web_prefs->force_compositing_mode = true;
1889 WebContents* web_contents = WebContents::FromRenderViewHost(rvh);
1890 extensions::ViewType view_type = extensions::GetViewType(web_contents);
1891 ExtensionService* service =
1892 extensions::ExtensionSystem::Get(profile)->extension_service();
1893 if (service) {
1894 const GURL& url = rvh->GetSiteInstance()->GetSiteURL();
1895 const Extension* extension = service->extensions()->GetByID(url.host());
1896 // Ensure that we are only granting extension preferences to URLs with
1897 // the correct scheme. Without this check, chrome-guest:// schemes used by
1898 // webview tags as well as hosts that happen to match the id of an
1899 // installed extension would get the wrong preferences.
1900 if (url.SchemeIs(extensions::kExtensionScheme)) {
1901 extension_webkit_preferences::SetPreferences(
1902 extension, view_type, web_prefs);
1906 if (view_type == extensions::VIEW_TYPE_NOTIFICATION) {
1907 web_prefs->allow_scripts_to_close_windows = true;
1908 } else if (view_type == extensions::VIEW_TYPE_BACKGROUND_CONTENTS) {
1909 // Disable all kinds of acceleration for background pages.
1910 // See http://crbug.com/96005 and http://crbug.com/96006
1911 web_prefs->force_compositing_mode = false;
1912 web_prefs->accelerated_compositing_enabled = false;
1915 #if defined(FILE_MANAGER_EXTENSION)
1916 // Override the default of suppressing HW compositing for WebUI pages for the
1917 // file manager, which is implemented using WebUI but wants HW acceleration
1918 // for video decode & render.
1919 if (url.spec() == chrome::kChromeUIFileManagerURL) {
1920 web_prefs->accelerated_compositing_enabled = true;
1921 web_prefs->accelerated_2d_canvas_enabled = true;
1923 #endif
1926 void ChromeContentBrowserClient::UpdateInspectorSetting(
1927 RenderViewHost* rvh, const std::string& key, const std::string& value) {
1928 content::BrowserContext* browser_context =
1929 rvh->GetProcess()->GetBrowserContext();
1930 DictionaryPrefUpdate update(
1931 Profile::FromBrowserContext(browser_context)->GetPrefs(),
1932 prefs::kWebKitInspectorSettings);
1933 DictionaryValue* inspector_settings = update.Get();
1934 inspector_settings->SetWithoutPathExpansion(key,
1935 Value::CreateStringValue(value));
1938 void ChromeContentBrowserClient::BrowserURLHandlerCreated(
1939 BrowserURLHandler* handler) {
1940 // Add the default URL handlers.
1941 handler->AddHandlerPair(&ExtensionWebUI::HandleChromeURLOverride,
1942 BrowserURLHandler::null_handler());
1943 handler->AddHandlerPair(BrowserURLHandler::null_handler(),
1944 &ExtensionWebUI::HandleChromeURLOverrideReverse);
1946 // about: handler. Must come before chrome: handler, since it will
1947 // rewrite about: urls to chrome: URLs and then expect chrome: to
1948 // actually handle them.
1949 handler->AddHandlerPair(&WillHandleBrowserAboutURL,
1950 BrowserURLHandler::null_handler());
1951 // chrome: & friends.
1952 handler->AddHandlerPair(&HandleWebUI, &HandleWebUIReverse);
1955 void ChromeContentBrowserClient::ClearCache(RenderViewHost* rvh) {
1956 Profile* profile = Profile::FromBrowserContext(
1957 rvh->GetSiteInstance()->GetProcess()->GetBrowserContext());
1958 BrowsingDataRemover* remover =
1959 BrowsingDataRemover::CreateForUnboundedRange(profile);
1960 remover->Remove(BrowsingDataRemover::REMOVE_CACHE,
1961 BrowsingDataHelper::UNPROTECTED_WEB);
1962 // BrowsingDataRemover takes care of deleting itself when done.
1965 void ChromeContentBrowserClient::ClearCookies(RenderViewHost* rvh) {
1966 Profile* profile = Profile::FromBrowserContext(
1967 rvh->GetSiteInstance()->GetProcess()->GetBrowserContext());
1968 BrowsingDataRemover* remover =
1969 BrowsingDataRemover::CreateForUnboundedRange(profile);
1970 int remove_mask = BrowsingDataRemover::REMOVE_SITE_DATA;
1971 remover->Remove(remove_mask, BrowsingDataHelper::UNPROTECTED_WEB);
1972 // BrowsingDataRemover takes care of deleting itself when done.
1975 base::FilePath ChromeContentBrowserClient::GetDefaultDownloadDirectory() {
1976 return download_util::GetDefaultDownloadDirectory();
1979 std::string ChromeContentBrowserClient::GetDefaultDownloadName() {
1980 return l10n_util::GetStringUTF8(IDS_DEFAULT_DOWNLOAD_FILENAME);
1983 void ChromeContentBrowserClient::DidCreatePpapiPlugin(
1984 content::BrowserPpapiHost* browser_host) {
1985 #if defined(ENABLE_PLUGINS)
1986 browser_host->GetPpapiHost()->AddHostFactoryFilter(
1987 scoped_ptr<ppapi::host::HostFactory>(
1988 new ChromeBrowserPepperHostFactory(browser_host)));
1989 #endif
1992 content::BrowserPpapiHost*
1993 ChromeContentBrowserClient::GetExternalBrowserPpapiHost(
1994 int plugin_process_id) {
1995 BrowserChildProcessHostIterator iter(PROCESS_TYPE_NACL_LOADER);
1996 while (!iter.Done()) {
1997 NaClProcessHost* host = static_cast<NaClProcessHost*>(iter.GetDelegate());
1998 if (host->process() &&
1999 host->process()->GetData().id == plugin_process_id) {
2000 // Found the plugin.
2001 return host->browser_ppapi_host();
2003 ++iter;
2005 return NULL;
2008 bool ChromeContentBrowserClient::SupportsBrowserPlugin(
2009 content::BrowserContext* browser_context, const GURL& site_url) {
2010 if (CommandLine::ForCurrentProcess()->HasSwitch(
2011 switches::kEnableBrowserPluginForAllViewTypes))
2012 return true;
2014 Profile* profile = Profile::FromBrowserContext(browser_context);
2015 ExtensionService* service =
2016 extensions::ExtensionSystem::Get(profile)->extension_service();
2017 if (!service)
2018 return false;
2020 const Extension* extension = service->extensions()->
2021 GetExtensionOrAppByURL(ExtensionURLInfo(site_url));
2022 if (!extension)
2023 return false;
2025 return extension->HasAPIPermission(APIPermission::kWebView);
2028 bool ChromeContentBrowserClient::AllowPepperSocketAPI(
2029 content::BrowserContext* browser_context,
2030 const GURL& url,
2031 const content::SocketPermissionRequest& params) {
2032 if (!url.is_valid())
2033 return false;
2035 std::string host = url.host();
2036 if (url.SchemeIs(extensions::kExtensionScheme) &&
2037 allowed_socket_origins_.count(host)) {
2038 return true;
2041 Profile* profile = Profile::FromBrowserContext(browser_context);
2042 const Extension* extension = NULL;
2043 ExtensionService* extension_service = !profile ? NULL :
2044 extensions::ExtensionSystem::Get(profile)->extension_service();
2045 if (extension_service) {
2046 extension = extension_service->extensions()->
2047 GetExtensionOrAppByURL(ExtensionURLInfo(url));
2050 // Need to check this now and not on construction because otherwise it won't
2051 // work with browser_tests.
2052 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
2053 std::string allowed_list =
2054 command_line.GetSwitchValueASCII(switches::kAllowNaClSocketAPI);
2055 if (allowed_list == "*") {
2056 // The wildcard allows socket API only for packaged and platform apps.
2057 return extension &&
2058 (extension->GetType() == Manifest::TYPE_LEGACY_PACKAGED_APP ||
2059 extension->GetType() == Manifest::TYPE_PLATFORM_APP);
2060 } else if (!allowed_list.empty()) {
2061 base::StringTokenizer t(allowed_list, ",");
2062 while (t.GetNext()) {
2063 if (t.token() == host)
2064 return true;
2068 if (!extension)
2069 return false;
2071 extensions::SocketPermission::CheckParam extension_params(
2072 params.type, params.host, params.port);
2073 if (extension->CheckAPIPermissionWithParam(APIPermission::kSocket,
2074 &extension_params))
2075 return true;
2077 return false;
2080 base::FilePath ChromeContentBrowserClient::GetHyphenDictionaryDirectory() {
2081 base::FilePath directory;
2082 PathService::Get(chrome::DIR_APP_DICTIONARIES, &directory);
2083 return directory.Append(FILE_PATH_LITERAL("Hyphen"));
2086 ui::SelectFilePolicy* ChromeContentBrowserClient::CreateSelectFilePolicy(
2087 WebContents* web_contents) {
2088 return new ChromeSelectFilePolicy(web_contents);
2091 void ChromeContentBrowserClient::GetAdditionalAllowedSchemesForFileSystem(
2092 std::vector<std::string>* additional_allowed_schemes) {
2093 ContentBrowserClient::GetAdditionalAllowedSchemesForFileSystem(
2094 additional_allowed_schemes);
2095 additional_allowed_schemes->push_back(kChromeUIScheme);
2096 additional_allowed_schemes->push_back(extensions::kExtensionScheme);
2099 #if defined(OS_POSIX) && !defined(OS_MACOSX)
2100 void ChromeContentBrowserClient::GetAdditionalMappedFilesForChildProcess(
2101 const CommandLine& command_line,
2102 int child_process_id,
2103 std::vector<FileDescriptorInfo>* mappings) {
2104 #if defined(OS_ANDROID)
2105 base::FilePath data_path;
2106 PathService::Get(ui::DIR_RESOURCE_PAKS_ANDROID, &data_path);
2107 DCHECK(!data_path.empty());
2109 int flags = base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ;
2110 base::FilePath chrome_pak = data_path.AppendASCII("chrome.pak");
2111 base::PlatformFile f =
2112 base::CreatePlatformFile(chrome_pak, flags, NULL, NULL);
2113 DCHECK(f != base::kInvalidPlatformFileValue);
2114 mappings->push_back(FileDescriptorInfo(kAndroidChromePakDescriptor,
2115 FileDescriptor(f, true)));
2117 base::FilePath chrome_resources_pak =
2118 data_path.AppendASCII("chrome_100_percent.pak");
2119 f = base::CreatePlatformFile(chrome_resources_pak, flags, NULL, NULL);
2120 DCHECK(f != base::kInvalidPlatformFileValue);
2121 mappings->push_back(FileDescriptorInfo(kAndroidChrome100PercentPakDescriptor,
2122 FileDescriptor(f, true)));
2124 const std::string locale = GetApplicationLocale();
2125 base::FilePath locale_pak = ResourceBundle::GetSharedInstance().
2126 GetLocaleFilePath(locale, false);
2127 f = base::CreatePlatformFile(locale_pak, flags, NULL, NULL);
2128 DCHECK(f != base::kInvalidPlatformFileValue);
2129 mappings->push_back(FileDescriptorInfo(kAndroidLocalePakDescriptor,
2130 FileDescriptor(f, true)));
2132 base::FilePath resources_pack_path;
2133 PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
2134 f = base::CreatePlatformFile(resources_pack_path, flags, NULL, NULL);
2135 DCHECK(f != base::kInvalidPlatformFileValue);
2136 mappings->push_back(FileDescriptorInfo(kAndroidUIResourcesPakDescriptor,
2137 FileDescriptor(f, true)));
2139 #if defined(USE_LINUX_BREAKPAD)
2140 if (IsCrashReporterEnabled()) {
2141 f = CrashDumpManager::GetInstance()->CreateMinidumpFile(child_process_id);
2142 if (f == base::kInvalidPlatformFileValue) {
2143 LOG(ERROR) << "Failed to create file for minidump, crash reporting will "
2144 "be disabled for this process.";
2145 } else {
2146 mappings->push_back(FileDescriptorInfo(kAndroidMinidumpDescriptor,
2147 FileDescriptor(f, true)));
2150 #endif // defined(USE_LINUX_BREAKPAD)
2152 #else
2153 int crash_signal_fd = GetCrashSignalFD(command_line);
2154 if (crash_signal_fd >= 0) {
2155 mappings->push_back(FileDescriptorInfo(kCrashDumpSignal,
2156 FileDescriptor(crash_signal_fd,
2157 false)));
2159 #endif // defined(OS_ANDROID)
2161 #endif // defined(OS_POSIX) && !defined(OS_MACOSX)
2163 #if defined(OS_WIN)
2164 const wchar_t* ChromeContentBrowserClient::GetResourceDllName() {
2165 return chrome::kBrowserResourcesDll;
2168 void ChromeContentBrowserClient::PreSpawnRenderer(
2169 sandbox::TargetPolicy* policy,
2170 bool* success) {
2171 // This code is duplicated in nacl_exe_win_64.cc.
2172 // Allow the server side of a pipe restricted to the "chrome.nacl."
2173 // namespace so that it cannot impersonate other system or other chrome
2174 // service pipes.
2175 sandbox::ResultCode result = policy->AddRule(
2176 sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
2177 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
2178 L"\\\\.\\pipe\\chrome.nacl.*");
2179 if (result != sandbox::SBOX_ALL_OK) {
2180 *success = false;
2181 return;
2184 // Renderers need to send named pipe handles and shared memory
2185 // segment handles to NaCl loader processes.
2186 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
2187 sandbox::TargetPolicy::HANDLES_DUP_ANY,
2188 L"File");
2189 if (result != sandbox::SBOX_ALL_OK) {
2190 *success = false;
2191 return;
2194 #endif
2196 #if defined(USE_NSS)
2197 crypto::CryptoModuleBlockingPasswordDelegate*
2198 ChromeContentBrowserClient::GetCryptoPasswordDelegate(
2199 const GURL& url) {
2200 return chrome::NewCryptoModuleBlockingDialogDelegate(
2201 chrome::kCryptoModulePasswordKeygen, url.host());
2203 #endif
2205 } // namespace chrome