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/profiles/profile_io_data.h"
9 #include "base/basictypes.h"
10 #include "base/bind.h"
11 #include "base/bind_helpers.h"
12 #include "base/callback.h"
13 #include "base/command_line.h"
14 #include "base/compiler_specific.h"
15 #include "base/debug/alias.h"
16 #include "base/logging.h"
17 #include "base/path_service.h"
18 #include "base/prefs/pref_service.h"
19 #include "base/stl_util.h"
20 #include "base/strings/string_number_conversions.h"
21 #include "base/strings/string_util.h"
22 #include "base/strings/stringprintf.h"
23 #include "base/threading/sequenced_worker_pool.h"
24 #include "chrome/browser/browser_process.h"
25 #include "chrome/browser/chrome_notification_types.h"
26 #include "chrome/browser/content_settings/content_settings_provider.h"
27 #include "chrome/browser/content_settings/cookie_settings.h"
28 #include "chrome/browser/content_settings/host_content_settings_map.h"
29 #include "chrome/browser/custom_handlers/protocol_handler_registry.h"
30 #include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h"
31 #include "chrome/browser/download/download_service.h"
32 #include "chrome/browser/download/download_service_factory.h"
33 #include "chrome/browser/extensions/extension_protocols.h"
34 #include "chrome/browser/extensions/extension_resource_protocols.h"
35 #include "chrome/browser/io_thread.h"
36 #include "chrome/browser/media/media_device_id_salt.h"
37 #include "chrome/browser/net/about_protocol_handler.h"
38 #include "chrome/browser/net/chrome_fraudulent_certificate_reporter.h"
39 #include "chrome/browser/net/chrome_http_user_agent_settings.h"
40 #include "chrome/browser/net/chrome_net_log.h"
41 #include "chrome/browser/net/chrome_network_delegate.h"
42 #include "chrome/browser/net/cookie_store_util.h"
43 #include "chrome/browser/net/proxy_service_factory.h"
44 #include "chrome/browser/profiles/profile.h"
45 #include "chrome/browser/profiles/profile_manager.h"
46 #include "chrome/browser/signin/signin_names_io_thread.h"
47 #include "chrome/common/chrome_paths.h"
48 #include "chrome/common/chrome_switches.h"
49 #include "chrome/common/net/url_fixer_upper.h"
50 #include "chrome/common/pref_names.h"
51 #include "chrome/common/url_constants.h"
52 #include "components/startup_metric_utils/startup_metric_utils.h"
53 #include "components/sync_driver/pref_names.h"
54 #include "content/public/browser/browser_thread.h"
55 #include "content/public/browser/host_zoom_map.h"
56 #include "content/public/browser/notification_service.h"
57 #include "content/public/browser/resource_context.h"
58 #include "extensions/browser/extension_system.h"
59 #include "extensions/browser/info_map.h"
60 #include "extensions/common/constants.h"
61 #include "net/base/keygen_handler.h"
62 #include "net/cookies/canonical_cookie.h"
63 #include "net/http/http_transaction_factory.h"
64 #include "net/http/http_util.h"
65 #include "net/http/transport_security_persister.h"
66 #include "net/proxy/proxy_config_service_fixed.h"
67 #include "net/proxy/proxy_script_fetcher_impl.h"
68 #include "net/proxy/proxy_service.h"
69 #include "net/ssl/client_cert_store.h"
70 #include "net/ssl/server_bound_cert_service.h"
71 #include "net/url_request/data_protocol_handler.h"
72 #include "net/url_request/file_protocol_handler.h"
73 #include "net/url_request/ftp_protocol_handler.h"
74 #include "net/url_request/protocol_intercept_job_factory.h"
75 #include "net/url_request/url_request.h"
76 #include "net/url_request/url_request_file_job.h"
77 #include "net/url_request/url_request_job_factory_impl.h"
79 #if defined(ENABLE_CONFIGURATION_POLICY)
80 #include "chrome/browser/policy/cloud/policy_header_service_factory.h"
81 #include "chrome/browser/policy/policy_helpers.h"
82 #include "components/policy/core/browser/url_blacklist_manager.h"
83 #include "components/policy/core/common/cloud/policy_header_io_helper.h"
84 #include "components/policy/core/common/cloud/policy_header_service.h"
85 #include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
88 #if defined(ENABLE_MANAGED_USERS)
89 #include "chrome/browser/managed_mode/managed_mode_url_filter.h"
90 #include "chrome/browser/managed_mode/managed_user_service.h"
91 #include "chrome/browser/managed_mode/managed_user_service_factory.h"
94 #if defined(OS_CHROMEOS)
95 #include "chrome/browser/chromeos/drive/drive_protocol_handler.h"
96 #include "chrome/browser/chromeos/login/startup_utils.h"
97 #include "chrome/browser/chromeos/login/user.h"
98 #include "chrome/browser/chromeos/login/user_manager.h"
99 #include "chrome/browser/chromeos/net/cert_verify_proc_chromeos.h"
100 #include "chrome/browser/chromeos/policy/policy_cert_service.h"
101 #include "chrome/browser/chromeos/policy/policy_cert_service_factory.h"
102 #include "chrome/browser/chromeos/policy/policy_cert_verifier.h"
103 #include "chrome/browser/chromeos/settings/cros_settings.h"
104 #include "chromeos/dbus/cryptohome_client.h"
105 #include "chromeos/dbus/dbus_thread_manager.h"
106 #include "chromeos/settings/cros_settings_names.h"
107 #include "crypto/nss_util.h"
108 #include "crypto/nss_util_internal.h"
109 #include "net/cert/multi_threaded_cert_verifier.h"
110 #include "net/ssl/client_cert_store_chromeos.h"
111 #endif // defined(OS_CHROMEOS)
114 #include "chrome/browser/ui/crypto_module_delegate_nss.h"
115 #include "net/ssl/client_cert_store_nss.h"
119 #include "net/ssl/client_cert_store_win.h"
122 #if defined(OS_MACOSX)
123 #include "net/ssl/client_cert_store_mac.h"
126 using content::BrowserContext;
127 using content::BrowserThread;
128 using content::ResourceContext;
132 #if defined(DEBUG_DEVTOOLS)
133 bool IsSupportedDevToolsURL(const GURL& url, base::FilePath* path) {
134 std::string bundled_path_prefix(chrome::kChromeUIDevToolsBundledPath);
135 bundled_path_prefix = "/" + bundled_path_prefix + "/";
137 if (!url.SchemeIs(content::kChromeDevToolsScheme) ||
138 url.host() != chrome::kChromeUIDevToolsHost ||
139 !StartsWithASCII(url.path(), bundled_path_prefix, false)) {
143 if (!url.is_valid()) {
148 // Remove Query and Ref from URL.
150 GURL::Replacements replacements;
151 replacements.ClearQuery();
152 replacements.ClearRef();
153 stripped_url = url.ReplaceComponents(replacements);
155 std::string relative_path;
156 const std::string& spec = stripped_url.possibly_invalid_spec();
157 const url_parse::Parsed& parsed =
158 stripped_url.parsed_for_possibly_invalid_spec();
159 int offset = parsed.CountCharactersBefore(url_parse::Parsed::PATH, false);
160 if (offset < static_cast<int>(spec.size()))
161 relative_path.assign(spec.substr(offset + bundled_path_prefix.length()));
163 // Check that |relative_path| is not an absolute path (otherwise
164 // AppendASCII() will DCHECK). The awkward use of StringType is because on
165 // some systems FilePath expects a std::string, but on others a std::wstring.
167 base::FilePath::StringType(relative_path.begin(), relative_path.end()));
171 base::FilePath inspector_dir;
172 if (!PathService::Get(chrome::DIR_INSPECTOR, &inspector_dir))
175 if (inspector_dir.empty())
178 *path = inspector_dir.AppendASCII(relative_path);
182 class DebugDevToolsInterceptor
183 : public net::URLRequestJobFactory::ProtocolHandler {
185 DebugDevToolsInterceptor() {}
186 virtual ~DebugDevToolsInterceptor() {}
188 virtual net::URLRequestJob* MaybeCreateJob(
189 net::URLRequest* request,
190 net::NetworkDelegate* network_delegate) const OVERRIDE {
192 if (IsSupportedDevToolsURL(request->url(), &path))
193 return new net::URLRequestFileJob(
194 request, network_delegate, path,
195 content::BrowserThread::GetBlockingPool()->
196 GetTaskRunnerWithShutdownBehavior(
197 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN));
202 #endif // defined(DEBUG_DEVTOOLS)
204 #if defined(OS_CHROMEOS)
205 // The following four functions are responsible for initializing NSS for each
206 // profile on ChromeOS, which has a separate NSS database and TPM slot
209 // Initialization basically follows these steps:
210 // 1) Get some info from chromeos::UserManager about the User for this profile.
211 // 2) Tell nss_util to initialize the software slot for this profile.
212 // 3) Wait for the TPM module to be loaded by nss_util if it isn't already.
213 // 4) Ask CryptohomeClient which TPM slot id corresponds to this profile.
214 // 5) Tell nss_util to use that slot id on the TPM module.
216 // Some of these steps must happen on the UI thread, others must happen on the
218 // UI thread IO Thread
220 // ProfileIOData::InitializeOnUIThread
222 // chromeos::UserManager::GetUserByProfile
223 // \---------------------------------------v
224 // StartNSSInitOnIOThread
226 // crypto::InitializeNSSForChromeOSUser
228 // crypto::IsTPMTokenReady
230 // StartTPMSlotInitializationOnIOThread
231 // v---------------------------------------/
232 // GetTPMInfoForUserOnUIThread
234 // CryptohomeClient::Pkcs11GetTpmTokenInfoForUser
236 // DidGetTPMInfoForUserOnUIThread
237 // \---------------------------------------v
238 // crypto::InitializeTPMForChromeOSUser
240 void DidGetTPMInfoForUserOnUIThread(const std::string& username_hash,
241 chromeos::DBusMethodCallStatus call_status,
242 const std::string& label,
243 const std::string& user_pin,
245 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
246 if (call_status == chromeos::DBUS_METHOD_CALL_FAILURE) {
247 NOTREACHED() << "dbus error getting TPM info for " << username_hash;
250 DVLOG(1) << "Got TPM slot for " << username_hash << ": " << slot_id;
251 BrowserThread::PostTask(
255 &crypto::InitializeTPMForChromeOSUser, username_hash, slot_id));
258 void GetTPMInfoForUserOnUIThread(const std::string& username,
259 const std::string& username_hash) {
260 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
261 DVLOG(1) << "Getting TPM info from cryptohome for "
262 << " " << username << " " << username_hash;
263 chromeos::DBusThreadManager::Get()
264 ->GetCryptohomeClient()
265 ->Pkcs11GetTpmTokenInfoForUser(
267 base::Bind(&DidGetTPMInfoForUserOnUIThread, username_hash));
270 void StartTPMSlotInitializationOnIOThread(const std::string& username,
271 const std::string& username_hash) {
272 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
274 BrowserThread::PostTask(
277 base::Bind(&GetTPMInfoForUserOnUIThread, username, username_hash));
280 void StartNSSInitOnIOThread(const std::string& username,
281 const std::string& username_hash,
282 const base::FilePath& path,
283 bool is_primary_user) {
284 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
285 DVLOG(1) << "Starting NSS init for " << username
286 << " hash:" << username_hash
287 << " is_primary_user:" << is_primary_user;
289 if (!crypto::InitializeNSSForChromeOSUser(
290 username, username_hash, is_primary_user, path)) {
291 // If the user already exists in nss_util's map, it is already initialized
292 // or in the process of being initialized. In either case, there's no need
297 if (crypto::IsTPMTokenEnabledForNSS()) {
298 if (crypto::IsTPMTokenReady(base::Bind(
299 &StartTPMSlotInitializationOnIOThread, username, username_hash))) {
300 StartTPMSlotInitializationOnIOThread(username, username_hash);
302 DVLOG(1) << "Waiting for tpm ready ...";
305 crypto::InitializePrivateSoftwareSlotForChromeOSUser(username_hash);
308 #endif // defined(OS_CHROMEOS)
312 void ProfileIOData::InitializeOnUIThread(Profile* profile) {
313 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
314 PrefService* pref_service = profile->GetPrefs();
315 PrefService* local_state_pref_service = g_browser_process->local_state();
317 scoped_ptr<ProfileParams> params(new ProfileParams);
318 params->path = profile->GetPath();
320 params->io_thread = g_browser_process->io_thread();
322 params->cookie_settings = CookieSettings::Factory::GetForProfile(profile);
323 params->host_content_settings_map = profile->GetHostContentSettingsMap();
324 params->ssl_config_service = profile->GetSSLConfigService();
325 params->cookie_monster_delegate =
326 chrome_browser_net::CreateCookieDelegate(profile);
327 params->extension_info_map =
328 extensions::ExtensionSystem::Get(profile)->info_map();
330 ProtocolHandlerRegistry* protocol_handler_registry =
331 ProtocolHandlerRegistryFactory::GetForProfile(profile);
332 DCHECK(protocol_handler_registry);
334 // The profile instance is only available here in the InitializeOnUIThread
335 // method, so we create the url job factory here, then save it for
336 // later delivery to the job factory in Init().
337 params->protocol_handler_interceptor =
338 protocol_handler_registry->CreateJobInterceptorFactory();
340 params->proxy_config_service
341 .reset(ProxyServiceFactory::CreateProxyConfigService(
342 profile->GetProxyConfigTracker()));
343 #if defined(ENABLE_MANAGED_USERS)
344 ManagedUserService* managed_user_service =
345 ManagedUserServiceFactory::GetForProfile(profile);
346 params->managed_mode_url_filter =
347 managed_user_service->GetURLFilterForIOThread();
349 #if defined(OS_CHROMEOS)
350 chromeos::UserManager* user_manager = chromeos::UserManager::Get();
352 chromeos::User* user = user_manager->GetUserByProfile(profile);
354 params->username_hash = user->username_hash();
355 bool is_primary_user = (user_manager->GetPrimaryUser() == user);
356 BrowserThread::PostTask(BrowserThread::IO,
358 base::Bind(&StartNSSInitOnIOThread,
360 user->username_hash(),
365 if (params->username_hash.empty())
366 LOG(WARNING) << "no username_hash";
369 params->profile = profile;
370 profile_params_.reset(params.release());
372 ChromeNetworkDelegate::InitializePrefsOnUIThread(
374 &enable_do_not_track_,
378 scoped_refptr<base::MessageLoopProxy> io_message_loop_proxy =
379 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
380 #if defined(ENABLE_PRINTING)
381 printing_enabled_.Init(prefs::kPrintingEnabled, pref_service);
382 printing_enabled_.MoveToThread(io_message_loop_proxy);
385 chrome_http_user_agent_settings_.reset(
386 new ChromeHttpUserAgentSettings(pref_service));
388 // These members are used only for one click sign in, which is not enabled
389 // in incognito mode. So no need to initialize them.
390 if (!IsOffTheRecord()) {
391 signin_names_.reset(new SigninNamesOnIOThread());
393 google_services_user_account_id_.Init(
394 prefs::kGoogleServicesUserAccountId, pref_service);
395 google_services_user_account_id_.MoveToThread(io_message_loop_proxy);
397 google_services_username_.Init(
398 prefs::kGoogleServicesUsername, pref_service);
399 google_services_username_.MoveToThread(io_message_loop_proxy);
401 google_services_username_pattern_.Init(
402 prefs::kGoogleServicesUsernamePattern, local_state_pref_service);
403 google_services_username_pattern_.MoveToThread(io_message_loop_proxy);
405 reverse_autologin_enabled_.Init(
406 prefs::kReverseAutologinEnabled, pref_service);
407 reverse_autologin_enabled_.MoveToThread(io_message_loop_proxy);
409 one_click_signin_rejected_email_list_.Init(
410 prefs::kReverseAutologinRejectedEmailList, pref_service);
411 one_click_signin_rejected_email_list_.MoveToThread(io_message_loop_proxy);
413 sync_disabled_.Init(sync_driver::prefs::kSyncManaged, pref_service);
414 sync_disabled_.MoveToThread(io_message_loop_proxy);
416 signin_allowed_.Init(prefs::kSigninAllowed, pref_service);
417 signin_allowed_.MoveToThread(io_message_loop_proxy);
420 quick_check_enabled_.Init(prefs::kQuickCheckEnabled,
421 local_state_pref_service);
422 quick_check_enabled_.MoveToThread(io_message_loop_proxy);
424 media_device_id_salt_ = new MediaDeviceIDSalt(pref_service, IsOffTheRecord());
426 network_prediction_enabled_.Init(prefs::kNetworkPredictionEnabled,
428 network_prediction_enabled_.MoveToThread(io_message_loop_proxy);
430 #if defined(OS_CHROMEOS)
431 cert_verifier_ = policy::PolicyCertServiceFactory::CreateForProfile(profile);
433 // The URLBlacklistManager has to be created on the UI thread to register
434 // observers of |pref_service|, and it also has to clean up on
435 // ShutdownOnUIThread to release these observers on the right thread.
436 // Don't pass it in |profile_params_| to make sure it is correctly cleaned up,
437 // in particular when this ProfileIOData isn't |initialized_| during deletion.
438 #if defined(ENABLE_CONFIGURATION_POLICY)
439 policy::URLBlacklist::SegmentURLCallback callback =
440 static_cast<policy::URLBlacklist::SegmentURLCallback>(
441 URLFixerUpper::SegmentURL);
442 base::SequencedWorkerPool* pool = BrowserThread::GetBlockingPool();
443 scoped_refptr<base::SequencedTaskRunner> background_task_runner =
444 pool->GetSequencedTaskRunner(pool->GetSequenceToken());
445 url_blacklist_manager_.reset(
446 new policy::URLBlacklistManager(
448 background_task_runner,
449 io_message_loop_proxy,
451 base::Bind(policy::OverrideBlacklistForURL)));
453 if (!IsOffTheRecord()) {
454 // Add policy headers for non-incognito requests.
455 policy::PolicyHeaderService* policy_header_service =
456 policy::PolicyHeaderServiceFactory::GetForBrowserContext(profile);
457 if (policy_header_service) {
458 policy_header_helper_ = policy_header_service->CreatePolicyHeaderIOHelper(
459 io_message_loop_proxy);
464 initialized_on_UI_thread_ = true;
466 // We need to make sure that content initializes its own data structures that
467 // are associated with each ResourceContext because we might post this
468 // object to the IO thread after this function.
469 BrowserContext::EnsureResourceContextInitialized(profile);
472 ProfileIOData::MediaRequestContext::MediaRequestContext() {
475 void ProfileIOData::MediaRequestContext::SetHttpTransactionFactory(
476 scoped_ptr<net::HttpTransactionFactory> http_factory) {
477 http_factory_ = http_factory.Pass();
478 set_http_transaction_factory(http_factory_.get());
481 ProfileIOData::MediaRequestContext::~MediaRequestContext() {}
483 ProfileIOData::AppRequestContext::AppRequestContext() {
486 void ProfileIOData::AppRequestContext::SetCookieStore(
487 net::CookieStore* cookie_store) {
488 cookie_store_ = cookie_store;
489 set_cookie_store(cookie_store);
492 void ProfileIOData::AppRequestContext::SetHttpTransactionFactory(
493 scoped_ptr<net::HttpTransactionFactory> http_factory) {
494 http_factory_ = http_factory.Pass();
495 set_http_transaction_factory(http_factory_.get());
498 void ProfileIOData::AppRequestContext::SetJobFactory(
499 scoped_ptr<net::URLRequestJobFactory> job_factory) {
500 job_factory_ = job_factory.Pass();
501 set_job_factory(job_factory_.get());
504 ProfileIOData::AppRequestContext::~AppRequestContext() {}
506 ProfileIOData::ProfileParams::ProfileParams()
511 ProfileIOData::ProfileParams::~ProfileParams() {}
513 ProfileIOData::ProfileIOData(Profile::ProfileType profile_type)
514 : initialized_(false),
515 resource_context_(new ResourceContext(this)),
516 initialized_on_UI_thread_(false),
517 profile_type_(profile_type) {
518 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
521 ProfileIOData::~ProfileIOData() {
522 if (BrowserThread::IsMessageLoopValid(BrowserThread::IO))
523 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
525 // Pull the contents of the request context maps onto the stack for sanity
526 // checking of values in a minidump. http://crbug.com/260425
527 size_t num_app_contexts = app_request_context_map_.size();
528 size_t num_media_contexts = isolated_media_request_context_map_.size();
529 size_t current_context = 0;
530 static const size_t kMaxCachedContexts = 20;
531 ChromeURLRequestContext* app_context_cache[kMaxCachedContexts] = {0};
532 void* app_context_vtable_cache[kMaxCachedContexts] = {0};
533 ChromeURLRequestContext* media_context_cache[kMaxCachedContexts] = {0};
534 void* media_context_vtable_cache[kMaxCachedContexts] = {0};
535 void* tmp_vtable = NULL;
536 base::debug::Alias(&num_app_contexts);
537 base::debug::Alias(&num_media_contexts);
538 base::debug::Alias(¤t_context);
539 base::debug::Alias(app_context_cache);
540 base::debug::Alias(app_context_vtable_cache);
541 base::debug::Alias(media_context_cache);
542 base::debug::Alias(media_context_vtable_cache);
543 base::debug::Alias(&tmp_vtable);
546 for (URLRequestContextMap::const_iterator it =
547 app_request_context_map_.begin();
548 current_context < kMaxCachedContexts &&
549 it != app_request_context_map_.end();
550 ++it, ++current_context) {
551 app_context_cache[current_context] = it->second;
552 memcpy(&app_context_vtable_cache[current_context],
553 static_cast<void*>(it->second), sizeof(void*));
557 for (URLRequestContextMap::const_iterator it =
558 isolated_media_request_context_map_.begin();
559 current_context < kMaxCachedContexts &&
560 it != isolated_media_request_context_map_.end();
561 ++it, ++current_context) {
562 media_context_cache[current_context] = it->second;
563 memcpy(&media_context_vtable_cache[current_context],
564 static_cast<void*>(it->second), sizeof(void*));
567 // TODO(ajwong): These AssertNoURLRequests() calls are unnecessary since they
568 // are already done in the URLRequestContext destructor.
569 if (main_request_context_)
570 main_request_context_->AssertNoURLRequests();
571 if (extensions_request_context_)
572 extensions_request_context_->AssertNoURLRequests();
575 for (URLRequestContextMap::iterator it = app_request_context_map_.begin();
576 it != app_request_context_map_.end(); ++it) {
577 if (current_context < kMaxCachedContexts) {
578 CHECK_EQ(app_context_cache[current_context], it->second);
579 memcpy(&tmp_vtable, static_cast<void*>(it->second), sizeof(void*));
580 CHECK_EQ(app_context_vtable_cache[current_context], tmp_vtable);
582 it->second->AssertNoURLRequests();
588 for (URLRequestContextMap::iterator it =
589 isolated_media_request_context_map_.begin();
590 it != isolated_media_request_context_map_.end(); ++it) {
591 if (current_context < kMaxCachedContexts) {
592 CHECK_EQ(media_context_cache[current_context], it->second);
593 memcpy(&tmp_vtable, static_cast<void*>(it->second), sizeof(void*));
594 CHECK_EQ(media_context_vtable_cache[current_context], tmp_vtable);
596 it->second->AssertNoURLRequests();
603 ProfileIOData* ProfileIOData::FromResourceContext(
604 content::ResourceContext* rc) {
605 return (static_cast<ResourceContext*>(rc))->io_data_;
609 bool ProfileIOData::IsHandledProtocol(const std::string& scheme) {
610 DCHECK_EQ(scheme, StringToLowerASCII(scheme));
611 static const char* const kProtocolList[] = {
612 content::kFileScheme,
613 content::kChromeDevToolsScheme,
614 chrome::kDomDistillerScheme,
615 extensions::kExtensionScheme,
616 extensions::kExtensionResourceScheme,
617 content::kChromeUIScheme,
618 content::kDataScheme,
619 #if defined(OS_CHROMEOS)
620 chrome::kDriveScheme,
621 #endif // defined(OS_CHROMEOS)
622 content::kAboutScheme,
623 #if !defined(DISABLE_FTP_SUPPORT)
625 #endif // !defined(DISABLE_FTP_SUPPORT)
626 content::kBlobScheme,
627 content::kFileSystemScheme,
628 chrome::kChromeSearchScheme,
630 for (size_t i = 0; i < arraysize(kProtocolList); ++i) {
631 if (scheme == kProtocolList[i])
634 return net::URLRequest::IsHandledProtocol(scheme);
638 bool ProfileIOData::IsHandledURL(const GURL& url) {
639 if (!url.is_valid()) {
640 // We handle error cases.
644 return IsHandledProtocol(url.scheme());
648 void ProfileIOData::InstallProtocolHandlers(
649 net::URLRequestJobFactoryImpl* job_factory,
650 content::ProtocolHandlerMap* protocol_handlers) {
651 for (content::ProtocolHandlerMap::iterator it =
652 protocol_handlers->begin();
653 it != protocol_handlers->end();
655 bool set_protocol = job_factory->SetProtocolHandler(
656 it->first, it->second.release());
657 DCHECK(set_protocol);
659 protocol_handlers->clear();
662 content::ResourceContext* ProfileIOData::GetResourceContext() const {
663 return resource_context_.get();
666 ChromeURLRequestContext* ProfileIOData::GetMainRequestContext() const {
667 DCHECK(initialized_);
668 return main_request_context_.get();
671 ChromeURLRequestContext* ProfileIOData::GetMediaRequestContext() const {
672 DCHECK(initialized_);
673 ChromeURLRequestContext* context = AcquireMediaRequestContext();
678 ChromeURLRequestContext* ProfileIOData::GetExtensionsRequestContext() const {
679 DCHECK(initialized_);
680 return extensions_request_context_.get();
683 ChromeURLRequestContext* ProfileIOData::GetIsolatedAppRequestContext(
684 ChromeURLRequestContext* main_context,
685 const StoragePartitionDescriptor& partition_descriptor,
686 scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
687 protocol_handler_interceptor,
688 content::ProtocolHandlerMap* protocol_handlers,
689 content::ProtocolHandlerScopedVector protocol_interceptors) const {
690 DCHECK(initialized_);
691 ChromeURLRequestContext* context = NULL;
692 if (ContainsKey(app_request_context_map_, partition_descriptor)) {
693 context = app_request_context_map_[partition_descriptor];
696 AcquireIsolatedAppRequestContext(main_context,
697 partition_descriptor,
698 protocol_handler_interceptor.Pass(),
700 protocol_interceptors.Pass());
701 app_request_context_map_[partition_descriptor] = context;
707 ChromeURLRequestContext* ProfileIOData::GetIsolatedMediaRequestContext(
708 ChromeURLRequestContext* app_context,
709 const StoragePartitionDescriptor& partition_descriptor) const {
710 DCHECK(initialized_);
711 ChromeURLRequestContext* context = NULL;
712 if (ContainsKey(isolated_media_request_context_map_, partition_descriptor)) {
713 context = isolated_media_request_context_map_[partition_descriptor];
715 context = AcquireIsolatedMediaRequestContext(app_context,
716 partition_descriptor);
717 isolated_media_request_context_map_[partition_descriptor] = context;
723 extensions::InfoMap* ProfileIOData::GetExtensionInfoMap() const {
724 DCHECK(initialized_) << "ExtensionSystem not initialized";
725 return extension_info_map_.get();
728 CookieSettings* ProfileIOData::GetCookieSettings() const {
729 // Allow either Init() or SetCookieSettingsForTesting() to initialize.
730 DCHECK(initialized_ || cookie_settings_.get());
731 return cookie_settings_.get();
734 HostContentSettingsMap* ProfileIOData::GetHostContentSettingsMap() const {
735 DCHECK(initialized_);
736 return host_content_settings_map_.get();
739 ResourceContext::SaltCallback ProfileIOData::GetMediaDeviceIDSalt() const {
740 return base::Bind(&MediaDeviceIDSalt::GetSalt, media_device_id_salt_);
743 bool ProfileIOData::IsOffTheRecord() const {
744 return profile_type() == Profile::INCOGNITO_PROFILE
745 || profile_type() == Profile::GUEST_PROFILE;
748 void ProfileIOData::InitializeMetricsEnabledStateOnUIThread() {
749 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
750 #if defined(OS_CHROMEOS)
751 // Just fetch the value from ChromeOS' settings while we're on the UI thread.
752 // TODO(stevet): For now, this value is only set on profile initialization.
753 // We will want to do something similar to the PrefMember method below in the
754 // future to more accurately capture this state.
755 chromeos::CrosSettings::Get()->GetBoolean(chromeos::kStatsReportingPref,
757 #elif defined(OS_ANDROID)
758 // TODO(dwkang): rename or unify the pref for UMA once we have conclusion
759 // in crbugs.com/246495.
760 // Android has it's own preferences for metrics / crash uploading.
761 enable_metrics_.Init(prefs::kCrashReportingEnabled,
762 g_browser_process->local_state());
763 enable_metrics_.MoveToThread(
764 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
766 // Prep the PrefMember and send it to the IO thread, since this value will be
768 enable_metrics_.Init(prefs::kMetricsReportingEnabled,
769 g_browser_process->local_state());
770 enable_metrics_.MoveToThread(
771 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
772 #endif // defined(OS_CHROMEOS)
775 bool ProfileIOData::GetMetricsEnabledStateOnIOThread() const {
776 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
777 #if defined(OS_CHROMEOS)
778 return enable_metrics_;
780 return enable_metrics_.GetValue();
781 #endif // defined(OS_CHROMEOS)
784 base::WeakPtr<net::HttpServerProperties>
785 ProfileIOData::http_server_properties() const {
786 return http_server_properties_->GetWeakPtr();
789 void ProfileIOData::set_http_server_properties(
790 scoped_ptr<net::HttpServerProperties> http_server_properties) const {
791 http_server_properties_ = http_server_properties.Pass();
794 ProfileIOData::ResourceContext::ResourceContext(ProfileIOData* io_data)
796 host_resolver_(NULL),
797 request_context_(NULL) {
801 ProfileIOData::ResourceContext::~ResourceContext() {}
803 net::HostResolver* ProfileIOData::ResourceContext::GetHostResolver() {
804 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
805 DCHECK(io_data_->initialized_);
806 return host_resolver_;
809 net::URLRequestContext* ProfileIOData::ResourceContext::GetRequestContext() {
810 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
811 DCHECK(io_data_->initialized_);
812 return request_context_;
815 scoped_ptr<net::ClientCertStore>
816 ProfileIOData::ResourceContext::CreateClientCertStore() {
817 if (!io_data_->client_cert_store_factory_.is_null())
818 return io_data_->client_cert_store_factory_.Run();
819 #if defined(OS_CHROMEOS)
820 return scoped_ptr<net::ClientCertStore>(new net::ClientCertStoreChromeOS(
821 io_data_->username_hash(),
822 base::Bind(&CreateCryptoModuleBlockingPasswordDelegate,
823 chrome::kCryptoModulePasswordClientAuth)));
824 #elif defined(USE_NSS)
825 return scoped_ptr<net::ClientCertStore>(new net::ClientCertStoreNSS(
826 base::Bind(&CreateCryptoModuleBlockingPasswordDelegate,
827 chrome::kCryptoModulePasswordClientAuth)));
828 #elif defined(OS_WIN)
829 return scoped_ptr<net::ClientCertStore>(new net::ClientCertStoreWin());
830 #elif defined(OS_MACOSX)
831 return scoped_ptr<net::ClientCertStore>(new net::ClientCertStoreMac());
832 #elif defined(USE_OPENSSL)
833 // OpenSSL does not use the ClientCertStore infrastructure. On Android client
834 // cert matching is done by the OS as part of the call to show the cert
836 return scoped_ptr<net::ClientCertStore>();
838 #error Unknown platform.
842 void ProfileIOData::ResourceContext::CreateKeygenHandler(
843 uint32 key_size_in_bits,
844 const std::string& challenge_string,
846 const base::Callback<void(scoped_ptr<net::KeygenHandler>)>& callback) {
847 DCHECK(!callback.is_null());
849 scoped_ptr<net::KeygenHandler> keygen_handler(
850 new net::KeygenHandler(key_size_in_bits, challenge_string, url));
852 scoped_ptr<ChromeNSSCryptoModuleDelegate> delegate(
853 new ChromeNSSCryptoModuleDelegate(chrome::kCryptoModulePasswordKeygen,
854 net::HostPortPair::FromURL(url)));
855 ChromeNSSCryptoModuleDelegate* delegate_ptr = delegate.get();
856 keygen_handler->set_crypto_module_delegate(
857 delegate.PassAs<crypto::NSSCryptoModuleDelegate>());
859 base::Closure bound_callback =
860 base::Bind(callback, base::Passed(&keygen_handler));
861 if (delegate_ptr->InitializeSlot(this, bound_callback)) {
862 // Initialization complete, run the callback synchronously.
863 bound_callback.Run();
866 // Otherwise, the InitializeSlot will run the callback asynchronously.
868 callback.Run(make_scoped_ptr(
869 new net::KeygenHandler(key_size_in_bits, challenge_string, url)));
873 bool ProfileIOData::ResourceContext::AllowMicAccess(const GURL& origin) {
874 return AllowContentAccess(origin, CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC);
877 bool ProfileIOData::ResourceContext::AllowCameraAccess(const GURL& origin) {
878 return AllowContentAccess(origin, CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA);
881 bool ProfileIOData::ResourceContext::AllowContentAccess(
882 const GURL& origin, ContentSettingsType type) {
883 HostContentSettingsMap* content_settings =
884 io_data_->GetHostContentSettingsMap();
885 ContentSetting setting = content_settings->GetContentSetting(
886 origin, origin, type, NO_RESOURCE_IDENTIFIER);
887 return setting == CONTENT_SETTING_ALLOW;
890 ResourceContext::SaltCallback
891 ProfileIOData::ResourceContext::GetMediaDeviceIDSalt() {
892 return io_data_->GetMediaDeviceIDSalt();
896 std::string ProfileIOData::GetSSLSessionCacheShard() {
897 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
898 // The SSL session cache is partitioned by setting a string. This returns a
899 // unique string to partition the SSL session cache. Each time we create a
900 // new profile, we'll get a fresh SSL session cache which is separate from
901 // the other profiles.
902 static unsigned ssl_session_cache_instance = 0;
903 return base::StringPrintf("profile/%u", ssl_session_cache_instance++);
906 void ProfileIOData::Init(
907 content::ProtocolHandlerMap* protocol_handlers,
908 content::ProtocolHandlerScopedVector protocol_interceptors) const {
909 // The basic logic is implemented here. The specific initialization
910 // is done in InitializeInternal(), implemented by subtypes. Static helper
911 // functions have been provided to assist in common operations.
912 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
913 DCHECK(!initialized_);
915 startup_metric_utils::ScopedSlowStartupUMA
916 scoped_timer("Startup.SlowStartupProfileIODataInit");
918 // TODO(jhawkins): Remove once crbug.com/102004 is fixed.
919 CHECK(initialized_on_UI_thread_);
921 // TODO(jhawkins): Return to DCHECK once crbug.com/102004 is fixed.
922 CHECK(profile_params_.get());
924 IOThread* const io_thread = profile_params_->io_thread;
925 IOThread::Globals* const io_thread_globals = io_thread->globals();
926 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
928 // Create the common request contexts.
929 main_request_context_.reset(new ChromeURLRequestContext());
930 extensions_request_context_.reset(new ChromeURLRequestContext());
932 ChromeNetworkDelegate* network_delegate =
933 new ChromeNetworkDelegate(
934 io_thread_globals->extension_event_router_forwarder.get(),
936 if (command_line.HasSwitch(switches::kEnableClientHints))
937 network_delegate->SetEnableClientHints();
938 network_delegate->set_extension_info_map(
939 profile_params_->extension_info_map.get());
940 #if defined(ENABLE_CONFIGURATION_POLICY)
941 network_delegate->set_url_blacklist_manager(url_blacklist_manager_.get());
943 network_delegate->set_profile(profile_params_->profile);
944 network_delegate->set_profile_path(profile_params_->path);
945 network_delegate->set_cookie_settings(profile_params_->cookie_settings.get());
946 network_delegate->set_enable_do_not_track(&enable_do_not_track_);
947 network_delegate->set_force_google_safe_search(&force_safesearch_);
948 network_delegate_.reset(network_delegate);
950 fraudulent_certificate_reporter_.reset(
951 new chrome_browser_net::ChromeFraudulentCertificateReporter(
952 main_request_context_.get()));
954 // NOTE: Proxy service uses the default io thread network delegate, not the
955 // delegate just created.
956 proxy_service_.reset(
957 ProxyServiceFactory::CreateProxyService(
958 io_thread->net_log(),
959 io_thread_globals->proxy_script_fetcher_context.get(),
960 io_thread_globals->system_network_delegate.get(),
961 profile_params_->proxy_config_service.release(),
963 quick_check_enabled_.GetValue()));
965 transport_security_state_.reset(new net::TransportSecurityState());
966 transport_security_persister_.reset(
967 new net::TransportSecurityPersister(
968 transport_security_state_.get(),
969 profile_params_->path,
970 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE),
973 // Take ownership over these parameters.
974 cookie_settings_ = profile_params_->cookie_settings;
975 host_content_settings_map_ = profile_params_->host_content_settings_map;
976 extension_info_map_ = profile_params_->extension_info_map;
978 resource_context_->host_resolver_ = io_thread_globals->host_resolver.get();
979 resource_context_->request_context_ = main_request_context_.get();
981 #if defined(ENABLE_MANAGED_USERS)
982 managed_mode_url_filter_ = profile_params_->managed_mode_url_filter;
985 #if defined(OS_CHROMEOS)
986 username_hash_ = profile_params_->username_hash;
987 scoped_refptr<net::CertVerifyProc> verify_proc;
988 if (chromeos::UserManager::IsMultipleProfilesAllowed()) {
989 crypto::ScopedPK11Slot public_slot =
990 crypto::GetPublicSlotForChromeOSUser(username_hash_);
991 // The private slot won't be ready by this point. It shouldn't be necessary
992 // for cert trust purposes anyway.
993 verify_proc = new chromeos::CertVerifyProcChromeOS(public_slot.Pass());
995 verify_proc = net::CertVerifyProc::CreateDefault();
997 if (cert_verifier_) {
998 cert_verifier_->InitializeOnIOThread(verify_proc);
999 main_request_context_->set_cert_verifier(cert_verifier_.get());
1001 main_request_context_->set_cert_verifier(
1002 new net::MultiThreadedCertVerifier(verify_proc.get()));
1005 main_request_context_->set_cert_verifier(
1006 io_thread_globals->cert_verifier.get());
1010 profile_params_.get(), protocol_handlers, protocol_interceptors.Pass());
1012 profile_params_.reset();
1013 initialized_ = true;
1016 void ProfileIOData::ApplyProfileParamsToContext(
1017 ChromeURLRequestContext* context) const {
1018 context->set_http_user_agent_settings(
1019 chrome_http_user_agent_settings_.get());
1020 context->set_ssl_config_service(profile_params_->ssl_config_service.get());
1023 scoped_ptr<net::URLRequestJobFactory> ProfileIOData::SetUpJobFactoryDefaults(
1024 scoped_ptr<net::URLRequestJobFactoryImpl> job_factory,
1025 content::ProtocolHandlerScopedVector protocol_interceptors,
1026 scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
1027 protocol_handler_interceptor,
1028 net::NetworkDelegate* network_delegate,
1029 net::FtpTransactionFactory* ftp_transaction_factory) const {
1030 // NOTE(willchan): Keep these protocol handlers in sync with
1031 // ProfileIOData::IsHandledProtocol().
1032 bool set_protocol = job_factory->SetProtocolHandler(
1033 content::kFileScheme,
1034 new net::FileProtocolHandler(
1035 content::BrowserThread::GetBlockingPool()->
1036 GetTaskRunnerWithShutdownBehavior(
1037 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)));
1038 DCHECK(set_protocol);
1040 DCHECK(extension_info_map_.get());
1041 set_protocol = job_factory->SetProtocolHandler(
1042 extensions::kExtensionScheme,
1043 CreateExtensionProtocolHandler(profile_type(),
1044 extension_info_map_.get()));
1045 DCHECK(set_protocol);
1046 set_protocol = job_factory->SetProtocolHandler(
1047 extensions::kExtensionResourceScheme,
1048 CreateExtensionResourceProtocolHandler());
1049 DCHECK(set_protocol);
1050 set_protocol = job_factory->SetProtocolHandler(
1051 content::kDataScheme, new net::DataProtocolHandler());
1052 DCHECK(set_protocol);
1053 #if defined(OS_CHROMEOS)
1054 if (!IsOffTheRecord() && profile_params_) {
1055 set_protocol = job_factory->SetProtocolHandler(
1056 chrome::kDriveScheme,
1057 new drive::DriveProtocolHandler(profile_params_->profile));
1058 DCHECK(set_protocol);
1060 #endif // defined(OS_CHROMEOS)
1062 job_factory->SetProtocolHandler(
1063 content::kAboutScheme, new chrome_browser_net::AboutProtocolHandler());
1064 #if !defined(DISABLE_FTP_SUPPORT)
1065 DCHECK(ftp_transaction_factory);
1066 job_factory->SetProtocolHandler(
1067 content::kFtpScheme,
1068 new net::FtpProtocolHandler(ftp_transaction_factory));
1069 #endif // !defined(DISABLE_FTP_SUPPORT)
1071 #if defined(DEBUG_DEVTOOLS)
1072 protocol_interceptors.push_back(new DebugDevToolsInterceptor);
1075 // Set up interceptors in the reverse order.
1076 scoped_ptr<net::URLRequestJobFactory> top_job_factory =
1077 job_factory.PassAs<net::URLRequestJobFactory>();
1078 for (content::ProtocolHandlerScopedVector::reverse_iterator i =
1079 protocol_interceptors.rbegin();
1080 i != protocol_interceptors.rend();
1082 top_job_factory.reset(new net::ProtocolInterceptJobFactory(
1083 top_job_factory.Pass(), make_scoped_ptr(*i)));
1085 protocol_interceptors.weak_clear();
1087 if (protocol_handler_interceptor) {
1088 protocol_handler_interceptor->Chain(top_job_factory.Pass());
1089 return protocol_handler_interceptor.PassAs<net::URLRequestJobFactory>();
1091 return top_job_factory.Pass();
1095 void ProfileIOData::ShutdownOnUIThread() {
1096 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1099 signin_names_->ReleaseResourcesOnUIThread();
1101 google_services_user_account_id_.Destroy();
1102 google_services_username_.Destroy();
1103 google_services_username_pattern_.Destroy();
1104 reverse_autologin_enabled_.Destroy();
1105 one_click_signin_rejected_email_list_.Destroy();
1106 enable_referrers_.Destroy();
1107 enable_do_not_track_.Destroy();
1108 force_safesearch_.Destroy();
1109 #if !defined(OS_CHROMEOS)
1110 enable_metrics_.Destroy();
1112 safe_browsing_enabled_.Destroy();
1113 printing_enabled_.Destroy();
1114 sync_disabled_.Destroy();
1115 signin_allowed_.Destroy();
1116 network_prediction_enabled_.Destroy();
1117 quick_check_enabled_.Destroy();
1118 if (media_device_id_salt_)
1119 media_device_id_salt_->ShutdownOnUIThread();
1120 session_startup_pref_.Destroy();
1121 #if defined(ENABLE_CONFIGURATION_POLICY)
1122 if (url_blacklist_manager_)
1123 url_blacklist_manager_->ShutdownOnUIThread();
1125 if (chrome_http_user_agent_settings_)
1126 chrome_http_user_agent_settings_->CleanupOnUIThread();
1127 bool posted = BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, this);
1132 void ProfileIOData::set_server_bound_cert_service(
1133 net::ServerBoundCertService* server_bound_cert_service) const {
1134 server_bound_cert_service_.reset(server_bound_cert_service);
1137 void ProfileIOData::DestroyResourceContext() {
1138 resource_context_.reset();
1141 void ProfileIOData::PopulateNetworkSessionParams(
1142 const ProfileParams* profile_params,
1143 net::HttpNetworkSession::Params* params) const {
1145 ChromeURLRequestContext* context = main_request_context();
1147 IOThread* const io_thread = profile_params->io_thread;
1149 io_thread->InitializeNetworkSessionParams(params);
1151 params->host_resolver = context->host_resolver();
1152 params->cert_verifier = context->cert_verifier();
1153 params->server_bound_cert_service = context->server_bound_cert_service();
1154 params->transport_security_state = context->transport_security_state();
1155 params->cert_transparency_verifier = context->cert_transparency_verifier();
1156 params->proxy_service = context->proxy_service();
1157 params->ssl_session_cache_shard = GetSSLSessionCacheShard();
1158 params->ssl_config_service = context->ssl_config_service();
1159 params->http_auth_handler_factory = context->http_auth_handler_factory();
1160 params->network_delegate = network_delegate();
1161 params->http_server_properties = context->http_server_properties();
1162 params->net_log = context->net_log();
1165 void ProfileIOData::SetCookieSettingsForTesting(
1166 CookieSettings* cookie_settings) {
1167 DCHECK(!cookie_settings_.get());
1168 cookie_settings_ = cookie_settings;
1171 void ProfileIOData::set_signin_names_for_testing(
1172 SigninNamesOnIOThread* signin_names) {
1173 signin_names_.reset(signin_names);