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 "content/public/browser/browser_thread.h"
54 #include "content/public/browser/host_zoom_map.h"
55 #include "content/public/browser/notification_service.h"
56 #include "content/public/browser/resource_context.h"
57 #include "extensions/browser/extension_system.h"
58 #include "extensions/browser/info_map.h"
59 #include "extensions/common/constants.h"
60 #include "net/base/keygen_handler.h"
61 #include "net/cookies/canonical_cookie.h"
62 #include "net/http/http_transaction_factory.h"
63 #include "net/http/http_util.h"
64 #include "net/http/transport_security_persister.h"
65 #include "net/proxy/proxy_config_service_fixed.h"
66 #include "net/proxy/proxy_script_fetcher_impl.h"
67 #include "net/proxy/proxy_service.h"
68 #include "net/ssl/client_cert_store.h"
69 #include "net/ssl/server_bound_cert_service.h"
70 #include "net/url_request/data_protocol_handler.h"
71 #include "net/url_request/file_protocol_handler.h"
72 #include "net/url_request/ftp_protocol_handler.h"
73 #include "net/url_request/protocol_intercept_job_factory.h"
74 #include "net/url_request/url_request.h"
75 #include "net/url_request/url_request_file_job.h"
76 #include "net/url_request/url_request_job_factory_impl.h"
78 #if defined(ENABLE_CONFIGURATION_POLICY)
79 #include "chrome/browser/policy/cloud/policy_header_service_factory.h"
80 #include "chrome/browser/policy/policy_helpers.h"
81 #include "components/policy/core/browser/url_blacklist_manager.h"
82 #include "components/policy/core/common/cloud/policy_header_io_helper.h"
83 #include "components/policy/core/common/cloud/policy_header_service.h"
84 #include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
87 #if defined(ENABLE_MANAGED_USERS)
88 #include "chrome/browser/managed_mode/managed_mode_url_filter.h"
89 #include "chrome/browser/managed_mode/managed_user_service.h"
90 #include "chrome/browser/managed_mode/managed_user_service_factory.h"
93 #if defined(OS_CHROMEOS)
94 #include "chrome/browser/chromeos/drive/drive_protocol_handler.h"
95 #include "chrome/browser/chromeos/login/user.h"
96 #include "chrome/browser/chromeos/login/user_manager.h"
97 #include "chrome/browser/chromeos/net/cert_verify_proc_chromeos.h"
98 #include "chrome/browser/chromeos/policy/policy_cert_service.h"
99 #include "chrome/browser/chromeos/policy/policy_cert_service_factory.h"
100 #include "chrome/browser/chromeos/policy/policy_cert_verifier.h"
101 #include "chrome/browser/chromeos/settings/cros_settings.h"
102 #include "chromeos/dbus/cryptohome_client.h"
103 #include "chromeos/dbus/dbus_thread_manager.h"
104 #include "chromeos/settings/cros_settings_names.h"
105 #include "crypto/nss_util.h"
106 #include "crypto/nss_util_internal.h"
107 #include "net/cert/multi_threaded_cert_verifier.h"
108 #include "net/ssl/client_cert_store_chromeos.h"
109 #endif // defined(OS_CHROMEOS)
112 #include "chrome/browser/ui/crypto_module_delegate_nss.h"
113 #include "net/ssl/client_cert_store_nss.h"
117 #include "net/ssl/client_cert_store_win.h"
120 #if defined(OS_MACOSX)
121 #include "net/ssl/client_cert_store_mac.h"
124 using content::BrowserContext;
125 using content::BrowserThread;
126 using content::ResourceContext;
130 #if defined(DEBUG_DEVTOOLS)
131 bool IsSupportedDevToolsURL(const GURL& url, base::FilePath* path) {
132 std::string bundled_path_prefix(chrome::kChromeUIDevToolsBundledPath);
133 bundled_path_prefix = "/" + bundled_path_prefix + "/";
135 if (!url.SchemeIs(content::kChromeDevToolsScheme) ||
136 url.host() != chrome::kChromeUIDevToolsHost ||
137 !StartsWithASCII(url.path(), bundled_path_prefix, false)) {
141 if (!url.is_valid()) {
146 // Remove Query and Ref from URL.
148 GURL::Replacements replacements;
149 replacements.ClearQuery();
150 replacements.ClearRef();
151 stripped_url = url.ReplaceComponents(replacements);
153 std::string relative_path;
154 const std::string& spec = stripped_url.possibly_invalid_spec();
155 const url_parse::Parsed& parsed =
156 stripped_url.parsed_for_possibly_invalid_spec();
157 int offset = parsed.CountCharactersBefore(url_parse::Parsed::PATH, false);
158 if (offset < static_cast<int>(spec.size()))
159 relative_path.assign(spec.substr(offset + bundled_path_prefix.length()));
161 // Check that |relative_path| is not an absolute path (otherwise
162 // AppendASCII() will DCHECK). The awkward use of StringType is because on
163 // some systems FilePath expects a std::string, but on others a std::wstring.
165 base::FilePath::StringType(relative_path.begin(), relative_path.end()));
169 base::FilePath inspector_dir;
170 if (!PathService::Get(chrome::DIR_INSPECTOR, &inspector_dir))
173 if (inspector_dir.empty())
176 *path = inspector_dir.AppendASCII(relative_path);
180 class DebugDevToolsInterceptor
181 : public net::URLRequestJobFactory::ProtocolHandler {
183 DebugDevToolsInterceptor() {}
184 virtual ~DebugDevToolsInterceptor() {}
186 virtual net::URLRequestJob* MaybeCreateJob(
187 net::URLRequest* request,
188 net::NetworkDelegate* network_delegate) const OVERRIDE {
190 if (IsSupportedDevToolsURL(request->url(), &path))
191 return new net::URLRequestFileJob(
192 request, network_delegate, path,
193 content::BrowserThread::GetBlockingPool()->
194 GetTaskRunnerWithShutdownBehavior(
195 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN));
200 #endif // defined(DEBUG_DEVTOOLS)
202 #if defined(OS_CHROMEOS)
203 // The following four functions are responsible for initializing NSS for each
204 // profile on ChromeOS, which has a separate NSS database and TPM slot
207 // Initialization basically follows these steps:
208 // 1) Get some info from chromeos::UserManager about the User for this profile.
209 // 2) Tell nss_util to initialize the software slot for this profile.
210 // 3) Wait for the TPM module to be loaded by nss_util if it isn't already.
211 // 4) Ask CryptohomeClient which TPM slot id corresponds to this profile.
212 // 5) Tell nss_util to use that slot id on the TPM module.
214 // Some of these steps must happen on the UI thread, others must happen on the
216 // UI thread IO Thread
218 // ProfileIOData::InitializeOnUIThread
220 // chromeos::UserManager::GetUserByProfile
221 // \---------------------------------------v
222 // StartNSSInitOnIOThread
224 // crypto::InitializeNSSForChromeOSUser
226 // crypto::IsTPMTokenReady
228 // StartTPMSlotInitializationOnIOThread
229 // v---------------------------------------/
230 // GetTPMInfoForUserOnUIThread
232 // CryptohomeClient::Pkcs11GetTpmTokenInfoForUser
234 // DidGetTPMInfoForUserOnUIThread
235 // \---------------------------------------v
236 // crypto::InitializeTPMForChromeOSUser
238 void DidGetTPMInfoForUserOnUIThread(const std::string& username_hash,
239 chromeos::DBusMethodCallStatus call_status,
240 const std::string& label,
241 const std::string& user_pin,
243 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
244 if (call_status == chromeos::DBUS_METHOD_CALL_FAILURE) {
245 NOTREACHED() << "dbus error getting TPM info for " << username_hash;
248 DVLOG(1) << "Got TPM slot for " << username_hash << ": " << slot_id;
249 BrowserThread::PostTask(
253 &crypto::InitializeTPMForChromeOSUser, username_hash, slot_id));
256 void GetTPMInfoForUserOnUIThread(const std::string& username,
257 const std::string& username_hash) {
258 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
259 DVLOG(1) << "Getting TPM info from cryptohome for "
260 << " " << username << " " << username_hash;
261 chromeos::DBusThreadManager::Get()
262 ->GetCryptohomeClient()
263 ->Pkcs11GetTpmTokenInfoForUser(
265 base::Bind(&DidGetTPMInfoForUserOnUIThread, username_hash));
268 void StartTPMSlotInitializationOnIOThread(const std::string& username,
269 const std::string& username_hash) {
270 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
272 BrowserThread::PostTask(
275 base::Bind(&GetTPMInfoForUserOnUIThread, username, username_hash));
278 void StartNSSInitOnIOThread(const std::string& username,
279 const std::string& username_hash,
280 const base::FilePath& path,
281 bool is_primary_user) {
282 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
283 DVLOG(1) << "Starting NSS init for " << username
284 << " hash:" << username_hash
285 << " is_primary_user:" << is_primary_user;
287 if (!crypto::InitializeNSSForChromeOSUser(
288 username, username_hash, is_primary_user, path)) {
289 // If the user already exists in nss_util's map, it is already initialized
290 // or in the process of being initialized. In either case, there's no need
295 if (crypto::IsTPMTokenEnabledForNSS()) {
296 if (crypto::IsTPMTokenReady(base::Bind(
297 &StartTPMSlotInitializationOnIOThread, username, username_hash))) {
298 StartTPMSlotInitializationOnIOThread(username, username_hash);
300 DVLOG(1) << "Waiting for tpm ready ...";
303 crypto::InitializePrivateSoftwareSlotForChromeOSUser(username_hash);
306 #endif // defined(OS_CHROMEOS)
310 void ProfileIOData::InitializeOnUIThread(Profile* profile) {
311 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
312 PrefService* pref_service = profile->GetPrefs();
313 PrefService* local_state_pref_service = g_browser_process->local_state();
315 scoped_ptr<ProfileParams> params(new ProfileParams);
316 params->path = profile->GetPath();
318 params->io_thread = g_browser_process->io_thread();
320 params->cookie_settings = CookieSettings::Factory::GetForProfile(profile);
321 params->host_content_settings_map = profile->GetHostContentSettingsMap();
322 params->ssl_config_service = profile->GetSSLConfigService();
323 params->cookie_monster_delegate =
324 chrome_browser_net::CreateCookieDelegate(profile);
325 params->extension_info_map =
326 extensions::ExtensionSystem::Get(profile)->info_map();
328 ProtocolHandlerRegistry* protocol_handler_registry =
329 ProtocolHandlerRegistryFactory::GetForProfile(profile);
330 DCHECK(protocol_handler_registry);
332 // The profile instance is only available here in the InitializeOnUIThread
333 // method, so we create the url job factory here, then save it for
334 // later delivery to the job factory in Init().
335 params->protocol_handler_interceptor =
336 protocol_handler_registry->CreateJobInterceptorFactory();
338 params->proxy_config_service
339 .reset(ProxyServiceFactory::CreateProxyConfigService(
340 profile->GetProxyConfigTracker()));
341 #if defined(ENABLE_MANAGED_USERS)
342 ManagedUserService* managed_user_service =
343 ManagedUserServiceFactory::GetForProfile(profile);
344 params->managed_mode_url_filter =
345 managed_user_service->GetURLFilterForIOThread();
347 #if defined(OS_CHROMEOS)
348 chromeos::UserManager* user_manager = chromeos::UserManager::Get();
350 chromeos::User* user = user_manager->GetUserByProfile(profile);
352 params->username_hash = user->username_hash();
353 bool is_primary_user = (user_manager->GetPrimaryUser() == user);
354 BrowserThread::PostTask(BrowserThread::IO,
356 base::Bind(&StartNSSInitOnIOThread,
358 user->username_hash(),
363 if (params->username_hash.empty())
364 LOG(WARNING) << "no username_hash";
367 params->profile = profile;
368 profile_params_.reset(params.release());
370 ChromeNetworkDelegate::InitializePrefsOnUIThread(
372 &enable_do_not_track_,
376 scoped_refptr<base::MessageLoopProxy> io_message_loop_proxy =
377 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
378 #if defined(ENABLE_PRINTING)
379 printing_enabled_.Init(prefs::kPrintingEnabled, pref_service);
380 printing_enabled_.MoveToThread(io_message_loop_proxy);
383 chrome_http_user_agent_settings_.reset(
384 new ChromeHttpUserAgentSettings(pref_service));
386 // These members are used only for one click sign in, which is not enabled
387 // in incognito mode. So no need to initialize them.
388 if (!is_incognito()) {
389 signin_names_.reset(new SigninNamesOnIOThread());
391 google_services_user_account_id_.Init(
392 prefs::kGoogleServicesUserAccountId, pref_service);
393 google_services_user_account_id_.MoveToThread(io_message_loop_proxy);
395 google_services_username_.Init(
396 prefs::kGoogleServicesUsername, pref_service);
397 google_services_username_.MoveToThread(io_message_loop_proxy);
399 google_services_username_pattern_.Init(
400 prefs::kGoogleServicesUsernamePattern, local_state_pref_service);
401 google_services_username_pattern_.MoveToThread(io_message_loop_proxy);
403 reverse_autologin_enabled_.Init(
404 prefs::kReverseAutologinEnabled, pref_service);
405 reverse_autologin_enabled_.MoveToThread(io_message_loop_proxy);
407 one_click_signin_rejected_email_list_.Init(
408 prefs::kReverseAutologinRejectedEmailList, pref_service);
409 one_click_signin_rejected_email_list_.MoveToThread(io_message_loop_proxy);
411 sync_disabled_.Init(prefs::kSyncManaged, pref_service);
412 sync_disabled_.MoveToThread(io_message_loop_proxy);
414 signin_allowed_.Init(prefs::kSigninAllowed, pref_service);
415 signin_allowed_.MoveToThread(io_message_loop_proxy);
418 quick_check_enabled_.Init(prefs::kQuickCheckEnabled,
419 local_state_pref_service);
420 quick_check_enabled_.MoveToThread(io_message_loop_proxy);
422 media_device_id_salt_ = new MediaDeviceIDSalt(pref_service, is_incognito());
424 network_prediction_enabled_.Init(prefs::kNetworkPredictionEnabled,
426 network_prediction_enabled_.MoveToThread(io_message_loop_proxy);
428 #if defined(OS_CHROMEOS)
429 cert_verifier_ = policy::PolicyCertServiceFactory::CreateForProfile(profile);
431 // The URLBlacklistManager has to be created on the UI thread to register
432 // observers of |pref_service|, and it also has to clean up on
433 // ShutdownOnUIThread to release these observers on the right thread.
434 // Don't pass it in |profile_params_| to make sure it is correctly cleaned up,
435 // in particular when this ProfileIOData isn't |initialized_| during deletion.
436 #if defined(ENABLE_CONFIGURATION_POLICY)
437 policy::URLBlacklist::SegmentURLCallback callback =
438 static_cast<policy::URLBlacklist::SegmentURLCallback>(
439 URLFixerUpper::SegmentURL);
440 base::SequencedWorkerPool* pool = BrowserThread::GetBlockingPool();
441 scoped_refptr<base::SequencedTaskRunner> background_task_runner =
442 pool->GetSequencedTaskRunner(pool->GetSequenceToken());
443 url_blacklist_manager_.reset(
444 new policy::URLBlacklistManager(pref_service,
445 background_task_runner,
446 io_message_loop_proxy,
448 policy::SkipBlacklistForURL));
450 if (!is_incognito()) {
451 // Add policy headers for non-incognito requests.
452 policy::PolicyHeaderService* policy_header_service =
453 policy::PolicyHeaderServiceFactory::GetForBrowserContext(profile);
454 if (policy_header_service) {
455 policy_header_helper_ = policy_header_service->CreatePolicyHeaderIOHelper(
456 io_message_loop_proxy);
461 initialized_on_UI_thread_ = true;
463 // We need to make sure that content initializes its own data structures that
464 // are associated with each ResourceContext because we might post this
465 // object to the IO thread after this function.
466 BrowserContext::EnsureResourceContextInitialized(profile);
469 ProfileIOData::MediaRequestContext::MediaRequestContext() {
472 void ProfileIOData::MediaRequestContext::SetHttpTransactionFactory(
473 scoped_ptr<net::HttpTransactionFactory> http_factory) {
474 http_factory_ = http_factory.Pass();
475 set_http_transaction_factory(http_factory_.get());
478 ProfileIOData::MediaRequestContext::~MediaRequestContext() {}
480 ProfileIOData::AppRequestContext::AppRequestContext() {
483 void ProfileIOData::AppRequestContext::SetCookieStore(
484 net::CookieStore* cookie_store) {
485 cookie_store_ = cookie_store;
486 set_cookie_store(cookie_store);
489 void ProfileIOData::AppRequestContext::SetHttpTransactionFactory(
490 scoped_ptr<net::HttpTransactionFactory> http_factory) {
491 http_factory_ = http_factory.Pass();
492 set_http_transaction_factory(http_factory_.get());
495 void ProfileIOData::AppRequestContext::SetJobFactory(
496 scoped_ptr<net::URLRequestJobFactory> job_factory) {
497 job_factory_ = job_factory.Pass();
498 set_job_factory(job_factory_.get());
501 ProfileIOData::AppRequestContext::~AppRequestContext() {}
503 ProfileIOData::ProfileParams::ProfileParams()
508 ProfileIOData::ProfileParams::~ProfileParams() {}
510 ProfileIOData::ProfileIOData(bool is_incognito)
511 : initialized_(false),
512 resource_context_(new ResourceContext(this)),
513 initialized_on_UI_thread_(false),
514 is_incognito_(is_incognito) {
515 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
518 ProfileIOData::~ProfileIOData() {
519 if (BrowserThread::IsMessageLoopValid(BrowserThread::IO))
520 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
522 // Pull the contents of the request context maps onto the stack for sanity
523 // checking of values in a minidump. http://crbug.com/260425
524 size_t num_app_contexts = app_request_context_map_.size();
525 size_t num_media_contexts = isolated_media_request_context_map_.size();
526 size_t current_context = 0;
527 static const size_t kMaxCachedContexts = 20;
528 ChromeURLRequestContext* app_context_cache[kMaxCachedContexts] = {0};
529 void* app_context_vtable_cache[kMaxCachedContexts] = {0};
530 ChromeURLRequestContext* media_context_cache[kMaxCachedContexts] = {0};
531 void* media_context_vtable_cache[kMaxCachedContexts] = {0};
532 void* tmp_vtable = NULL;
533 base::debug::Alias(&num_app_contexts);
534 base::debug::Alias(&num_media_contexts);
535 base::debug::Alias(¤t_context);
536 base::debug::Alias(app_context_cache);
537 base::debug::Alias(app_context_vtable_cache);
538 base::debug::Alias(media_context_cache);
539 base::debug::Alias(media_context_vtable_cache);
540 base::debug::Alias(&tmp_vtable);
543 for (URLRequestContextMap::const_iterator it =
544 app_request_context_map_.begin();
545 current_context < kMaxCachedContexts &&
546 it != app_request_context_map_.end();
547 ++it, ++current_context) {
548 app_context_cache[current_context] = it->second;
549 memcpy(&app_context_vtable_cache[current_context],
550 static_cast<void*>(it->second), sizeof(void*));
554 for (URLRequestContextMap::const_iterator it =
555 isolated_media_request_context_map_.begin();
556 current_context < kMaxCachedContexts &&
557 it != isolated_media_request_context_map_.end();
558 ++it, ++current_context) {
559 media_context_cache[current_context] = it->second;
560 memcpy(&media_context_vtable_cache[current_context],
561 static_cast<void*>(it->second), sizeof(void*));
564 // TODO(ajwong): These AssertNoURLRequests() calls are unnecessary since they
565 // are already done in the URLRequestContext destructor.
566 if (main_request_context_)
567 main_request_context_->AssertNoURLRequests();
568 if (extensions_request_context_)
569 extensions_request_context_->AssertNoURLRequests();
572 for (URLRequestContextMap::iterator it = app_request_context_map_.begin();
573 it != app_request_context_map_.end(); ++it) {
574 if (current_context < kMaxCachedContexts) {
575 CHECK_EQ(app_context_cache[current_context], it->second);
576 memcpy(&tmp_vtable, static_cast<void*>(it->second), sizeof(void*));
577 CHECK_EQ(app_context_vtable_cache[current_context], tmp_vtable);
579 it->second->AssertNoURLRequests();
585 for (URLRequestContextMap::iterator it =
586 isolated_media_request_context_map_.begin();
587 it != isolated_media_request_context_map_.end(); ++it) {
588 if (current_context < kMaxCachedContexts) {
589 CHECK_EQ(media_context_cache[current_context], it->second);
590 memcpy(&tmp_vtable, static_cast<void*>(it->second), sizeof(void*));
591 CHECK_EQ(media_context_vtable_cache[current_context], tmp_vtable);
593 it->second->AssertNoURLRequests();
600 ProfileIOData* ProfileIOData::FromResourceContext(
601 content::ResourceContext* rc) {
602 return (static_cast<ResourceContext*>(rc))->io_data_;
606 bool ProfileIOData::IsHandledProtocol(const std::string& scheme) {
607 DCHECK_EQ(scheme, StringToLowerASCII(scheme));
608 static const char* const kProtocolList[] = {
609 content::kFileScheme,
610 content::kChromeDevToolsScheme,
611 chrome::kDomDistillerScheme,
612 extensions::kExtensionScheme,
613 extensions::kExtensionResourceScheme,
614 content::kChromeUIScheme,
615 content::kDataScheme,
616 #if defined(OS_CHROMEOS)
617 chrome::kDriveScheme,
618 #endif // defined(OS_CHROMEOS)
619 chrome::kAboutScheme,
620 #if !defined(DISABLE_FTP_SUPPORT)
622 #endif // !defined(DISABLE_FTP_SUPPORT)
624 content::kFileSystemScheme,
625 chrome::kChromeSearchScheme,
627 for (size_t i = 0; i < arraysize(kProtocolList); ++i) {
628 if (scheme == kProtocolList[i])
631 return net::URLRequest::IsHandledProtocol(scheme);
635 bool ProfileIOData::IsHandledURL(const GURL& url) {
636 if (!url.is_valid()) {
637 // We handle error cases.
641 return IsHandledProtocol(url.scheme());
645 void ProfileIOData::InstallProtocolHandlers(
646 net::URLRequestJobFactoryImpl* job_factory,
647 content::ProtocolHandlerMap* protocol_handlers) {
648 for (content::ProtocolHandlerMap::iterator it =
649 protocol_handlers->begin();
650 it != protocol_handlers->end();
652 bool set_protocol = job_factory->SetProtocolHandler(
653 it->first, it->second.release());
654 DCHECK(set_protocol);
656 protocol_handlers->clear();
659 content::ResourceContext* ProfileIOData::GetResourceContext() const {
660 return resource_context_.get();
663 ChromeURLRequestContext* ProfileIOData::GetMainRequestContext() const {
664 DCHECK(initialized_);
665 return main_request_context_.get();
668 ChromeURLRequestContext* ProfileIOData::GetMediaRequestContext() const {
669 DCHECK(initialized_);
670 ChromeURLRequestContext* context = AcquireMediaRequestContext();
675 ChromeURLRequestContext* ProfileIOData::GetExtensionsRequestContext() const {
676 DCHECK(initialized_);
677 return extensions_request_context_.get();
680 ChromeURLRequestContext* ProfileIOData::GetIsolatedAppRequestContext(
681 ChromeURLRequestContext* main_context,
682 const StoragePartitionDescriptor& partition_descriptor,
683 scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
684 protocol_handler_interceptor,
685 content::ProtocolHandlerMap* protocol_handlers) const {
686 DCHECK(initialized_);
687 ChromeURLRequestContext* context = NULL;
688 if (ContainsKey(app_request_context_map_, partition_descriptor)) {
689 context = app_request_context_map_[partition_descriptor];
691 context = AcquireIsolatedAppRequestContext(
692 main_context, partition_descriptor, protocol_handler_interceptor.Pass(),
694 app_request_context_map_[partition_descriptor] = context;
700 ChromeURLRequestContext* ProfileIOData::GetIsolatedMediaRequestContext(
701 ChromeURLRequestContext* app_context,
702 const StoragePartitionDescriptor& partition_descriptor) const {
703 DCHECK(initialized_);
704 ChromeURLRequestContext* context = NULL;
705 if (ContainsKey(isolated_media_request_context_map_, partition_descriptor)) {
706 context = isolated_media_request_context_map_[partition_descriptor];
708 context = AcquireIsolatedMediaRequestContext(app_context,
709 partition_descriptor);
710 isolated_media_request_context_map_[partition_descriptor] = context;
716 extensions::InfoMap* ProfileIOData::GetExtensionInfoMap() const {
717 DCHECK(initialized_) << "ExtensionSystem not initialized";
718 return extension_info_map_.get();
721 CookieSettings* ProfileIOData::GetCookieSettings() const {
722 // Allow either Init() or SetCookieSettingsForTesting() to initialize.
723 DCHECK(initialized_ || cookie_settings_.get());
724 return cookie_settings_.get();
727 HostContentSettingsMap* ProfileIOData::GetHostContentSettingsMap() const {
728 DCHECK(initialized_);
729 return host_content_settings_map_.get();
732 ResourceContext::SaltCallback ProfileIOData::GetMediaDeviceIDSalt() const {
733 return base::Bind(&MediaDeviceIDSalt::GetSalt, media_device_id_salt_);
736 void ProfileIOData::InitializeMetricsEnabledStateOnUIThread() {
737 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
738 #if defined(OS_CHROMEOS)
739 // Just fetch the value from ChromeOS' settings while we're on the UI thread.
740 // TODO(stevet): For now, this value is only set on profile initialization.
741 // We will want to do something similar to the PrefMember method below in the
742 // future to more accurately capture this state.
743 chromeos::CrosSettings::Get()->GetBoolean(chromeos::kStatsReportingPref,
745 #elif defined(OS_ANDROID)
746 // TODO(dwkang): rename or unify the pref for UMA once we have conclusion
747 // in crbugs.com/246495.
748 // Android has it's own preferences for metrics / crash uploading.
749 enable_metrics_.Init(prefs::kCrashReportingEnabled,
750 g_browser_process->local_state());
751 enable_metrics_.MoveToThread(
752 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
754 // Prep the PrefMember and send it to the IO thread, since this value will be
756 enable_metrics_.Init(prefs::kMetricsReportingEnabled,
757 g_browser_process->local_state());
758 enable_metrics_.MoveToThread(
759 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
760 #endif // defined(OS_CHROMEOS)
763 bool ProfileIOData::GetMetricsEnabledStateOnIOThread() const {
764 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
765 #if defined(OS_CHROMEOS)
766 return enable_metrics_;
768 return enable_metrics_.GetValue();
769 #endif // defined(OS_CHROMEOS)
772 base::WeakPtr<net::HttpServerProperties>
773 ProfileIOData::http_server_properties() const {
774 return http_server_properties_->GetWeakPtr();
777 void ProfileIOData::set_http_server_properties(
778 scoped_ptr<net::HttpServerProperties> http_server_properties) const {
779 http_server_properties_ = http_server_properties.Pass();
782 ProfileIOData::ResourceContext::ResourceContext(ProfileIOData* io_data)
784 host_resolver_(NULL),
785 request_context_(NULL) {
789 ProfileIOData::ResourceContext::~ResourceContext() {}
791 net::HostResolver* ProfileIOData::ResourceContext::GetHostResolver() {
792 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
793 DCHECK(io_data_->initialized_);
794 return host_resolver_;
797 net::URLRequestContext* ProfileIOData::ResourceContext::GetRequestContext() {
798 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
799 DCHECK(io_data_->initialized_);
800 return request_context_;
803 scoped_ptr<net::ClientCertStore>
804 ProfileIOData::ResourceContext::CreateClientCertStore() {
805 if (!io_data_->client_cert_store_factory_.is_null())
806 return io_data_->client_cert_store_factory_.Run();
807 #if defined(OS_CHROMEOS)
808 return scoped_ptr<net::ClientCertStore>(new net::ClientCertStoreChromeOS(
809 io_data_->username_hash(),
810 base::Bind(&CreateCryptoModuleBlockingPasswordDelegate,
811 chrome::kCryptoModulePasswordClientAuth)));
812 #elif defined(USE_NSS)
813 return scoped_ptr<net::ClientCertStore>(new net::ClientCertStoreNSS(
814 base::Bind(&CreateCryptoModuleBlockingPasswordDelegate,
815 chrome::kCryptoModulePasswordClientAuth)));
816 #elif defined(OS_WIN)
817 return scoped_ptr<net::ClientCertStore>(new net::ClientCertStoreWin());
818 #elif defined(OS_MACOSX)
819 return scoped_ptr<net::ClientCertStore>(new net::ClientCertStoreMac());
820 #elif defined(USE_OPENSSL)
821 // OpenSSL does not use the ClientCertStore infrastructure. On Android client
822 // cert matching is done by the OS as part of the call to show the cert
824 return scoped_ptr<net::ClientCertStore>();
826 #error Unknown platform.
830 void ProfileIOData::ResourceContext::CreateKeygenHandler(
831 uint32 key_size_in_bits,
832 const std::string& challenge_string,
834 const base::Callback<void(scoped_ptr<net::KeygenHandler>)>& callback) {
835 DCHECK(!callback.is_null());
837 scoped_ptr<net::KeygenHandler> keygen_handler(
838 new net::KeygenHandler(key_size_in_bits, challenge_string, url));
840 scoped_ptr<ChromeNSSCryptoModuleDelegate> delegate(
841 new ChromeNSSCryptoModuleDelegate(chrome::kCryptoModulePasswordKeygen,
842 net::HostPortPair::FromURL(url)));
843 ChromeNSSCryptoModuleDelegate* delegate_ptr = delegate.get();
844 keygen_handler->set_crypto_module_delegate(
845 delegate.PassAs<crypto::NSSCryptoModuleDelegate>());
847 base::Closure bound_callback =
848 base::Bind(callback, base::Passed(&keygen_handler));
849 if (delegate_ptr->InitializeSlot(this, bound_callback)) {
850 // Initialization complete, run the callback synchronously.
851 bound_callback.Run();
854 // Otherwise, the InitializeSlot will run the callback asynchronously.
856 callback.Run(make_scoped_ptr(
857 new net::KeygenHandler(key_size_in_bits, challenge_string, url)));
861 bool ProfileIOData::ResourceContext::AllowMicAccess(const GURL& origin) {
862 return AllowContentAccess(origin, CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC);
865 bool ProfileIOData::ResourceContext::AllowCameraAccess(const GURL& origin) {
866 return AllowContentAccess(origin, CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA);
869 bool ProfileIOData::ResourceContext::AllowContentAccess(
870 const GURL& origin, ContentSettingsType type) {
871 HostContentSettingsMap* content_settings =
872 io_data_->GetHostContentSettingsMap();
873 ContentSetting setting = content_settings->GetContentSetting(
874 origin, origin, type, NO_RESOURCE_IDENTIFIER);
875 return setting == CONTENT_SETTING_ALLOW;
878 ResourceContext::SaltCallback
879 ProfileIOData::ResourceContext::GetMediaDeviceIDSalt() {
880 return io_data_->GetMediaDeviceIDSalt();
884 std::string ProfileIOData::GetSSLSessionCacheShard() {
885 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
886 // The SSL session cache is partitioned by setting a string. This returns a
887 // unique string to partition the SSL session cache. Each time we create a
888 // new profile, we'll get a fresh SSL session cache which is separate from
889 // the other profiles.
890 static unsigned ssl_session_cache_instance = 0;
891 return base::StringPrintf("profile/%u", ssl_session_cache_instance++);
894 void ProfileIOData::Init(content::ProtocolHandlerMap* protocol_handlers) const {
895 // The basic logic is implemented here. The specific initialization
896 // is done in InitializeInternal(), implemented by subtypes. Static helper
897 // functions have been provided to assist in common operations.
898 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
899 DCHECK(!initialized_);
901 startup_metric_utils::ScopedSlowStartupUMA
902 scoped_timer("Startup.SlowStartupProfileIODataInit");
904 // TODO(jhawkins): Remove once crbug.com/102004 is fixed.
905 CHECK(initialized_on_UI_thread_);
907 // TODO(jhawkins): Return to DCHECK once crbug.com/102004 is fixed.
908 CHECK(profile_params_.get());
910 IOThread* const io_thread = profile_params_->io_thread;
911 IOThread::Globals* const io_thread_globals = io_thread->globals();
912 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
914 // Create the common request contexts.
915 main_request_context_.reset(new ChromeURLRequestContext());
916 extensions_request_context_.reset(new ChromeURLRequestContext());
918 ChromeNetworkDelegate* network_delegate =
919 new ChromeNetworkDelegate(
920 io_thread_globals->extension_event_router_forwarder.get(),
922 if (command_line.HasSwitch(switches::kEnableClientHints))
923 network_delegate->SetEnableClientHints();
924 network_delegate->set_extension_info_map(
925 profile_params_->extension_info_map.get());
926 #if defined(ENABLE_CONFIGURATION_POLICY)
927 network_delegate->set_url_blacklist_manager(url_blacklist_manager_.get());
929 network_delegate->set_profile(profile_params_->profile);
930 network_delegate->set_profile_path(profile_params_->path);
931 network_delegate->set_cookie_settings(profile_params_->cookie_settings.get());
932 network_delegate->set_enable_do_not_track(&enable_do_not_track_);
933 network_delegate->set_force_google_safe_search(&force_safesearch_);
934 network_delegate_.reset(network_delegate);
936 fraudulent_certificate_reporter_.reset(
937 new chrome_browser_net::ChromeFraudulentCertificateReporter(
938 main_request_context_.get()));
940 // NOTE: Proxy service uses the default io thread network delegate, not the
941 // delegate just created.
942 proxy_service_.reset(
943 ProxyServiceFactory::CreateProxyService(
944 io_thread->net_log(),
945 io_thread_globals->proxy_script_fetcher_context.get(),
946 io_thread_globals->system_network_delegate.get(),
947 profile_params_->proxy_config_service.release(),
949 quick_check_enabled_.GetValue()));
951 transport_security_state_.reset(new net::TransportSecurityState());
952 transport_security_persister_.reset(
953 new net::TransportSecurityPersister(
954 transport_security_state_.get(),
955 profile_params_->path,
956 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE),
959 // Take ownership over these parameters.
960 cookie_settings_ = profile_params_->cookie_settings;
961 host_content_settings_map_ = profile_params_->host_content_settings_map;
962 extension_info_map_ = profile_params_->extension_info_map;
964 resource_context_->host_resolver_ = io_thread_globals->host_resolver.get();
965 resource_context_->request_context_ = main_request_context_.get();
967 #if defined(ENABLE_MANAGED_USERS)
968 managed_mode_url_filter_ = profile_params_->managed_mode_url_filter;
971 #if defined(OS_CHROMEOS)
972 username_hash_ = profile_params_->username_hash;
973 scoped_refptr<net::CertVerifyProc> verify_proc;
974 if (chromeos::UserManager::IsMultipleProfilesAllowed()) {
975 crypto::ScopedPK11Slot public_slot =
976 crypto::GetPublicSlotForChromeOSUser(username_hash_);
977 // The private slot won't be ready by this point. It shouldn't be necessary
978 // for cert trust purposes anyway.
979 verify_proc = new chromeos::CertVerifyProcChromeOS(public_slot.Pass());
981 verify_proc = net::CertVerifyProc::CreateDefault();
983 if (cert_verifier_) {
984 cert_verifier_->InitializeOnIOThread(verify_proc);
985 main_request_context_->set_cert_verifier(cert_verifier_.get());
987 main_request_context_->set_cert_verifier(
988 new net::MultiThreadedCertVerifier(verify_proc.get()));
991 main_request_context_->set_cert_verifier(
992 io_thread_globals->cert_verifier.get());
995 InitializeInternal(profile_params_.get(), protocol_handlers);
997 profile_params_.reset();
1001 void ProfileIOData::ApplyProfileParamsToContext(
1002 ChromeURLRequestContext* context) const {
1003 context->set_http_user_agent_settings(
1004 chrome_http_user_agent_settings_.get());
1005 context->set_ssl_config_service(profile_params_->ssl_config_service.get());
1008 scoped_ptr<net::URLRequestJobFactory> ProfileIOData::SetUpJobFactoryDefaults(
1009 scoped_ptr<net::URLRequestJobFactoryImpl> job_factory,
1010 scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
1011 protocol_handler_interceptor,
1012 net::NetworkDelegate* network_delegate,
1013 net::FtpTransactionFactory* ftp_transaction_factory) const {
1014 // NOTE(willchan): Keep these protocol handlers in sync with
1015 // ProfileIOData::IsHandledProtocol().
1016 bool set_protocol = job_factory->SetProtocolHandler(
1017 content::kFileScheme,
1018 new net::FileProtocolHandler(
1019 content::BrowserThread::GetBlockingPool()->
1020 GetTaskRunnerWithShutdownBehavior(
1021 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)));
1022 DCHECK(set_protocol);
1024 DCHECK(extension_info_map_.get());
1025 set_protocol = job_factory->SetProtocolHandler(
1026 extensions::kExtensionScheme,
1027 CreateExtensionProtocolHandler(is_incognito(),
1028 extension_info_map_.get()));
1029 DCHECK(set_protocol);
1030 set_protocol = job_factory->SetProtocolHandler(
1031 extensions::kExtensionResourceScheme,
1032 CreateExtensionResourceProtocolHandler());
1033 DCHECK(set_protocol);
1034 set_protocol = job_factory->SetProtocolHandler(
1035 content::kDataScheme, new net::DataProtocolHandler());
1036 DCHECK(set_protocol);
1037 #if defined(OS_CHROMEOS)
1038 if (!is_incognito() && profile_params_) {
1039 set_protocol = job_factory->SetProtocolHandler(
1040 chrome::kDriveScheme,
1041 new drive::DriveProtocolHandler(profile_params_->profile));
1042 DCHECK(set_protocol);
1044 #endif // defined(OS_CHROMEOS)
1046 job_factory->SetProtocolHandler(
1047 chrome::kAboutScheme,
1048 new chrome_browser_net::AboutProtocolHandler());
1049 #if !defined(DISABLE_FTP_SUPPORT)
1050 DCHECK(ftp_transaction_factory);
1051 job_factory->SetProtocolHandler(
1052 content::kFtpScheme,
1053 new net::FtpProtocolHandler(ftp_transaction_factory));
1054 #endif // !defined(DISABLE_FTP_SUPPORT)
1056 scoped_ptr<net::URLRequestJobFactory> top_job_factory =
1057 job_factory.PassAs<net::URLRequestJobFactory>();
1058 #if defined(DEBUG_DEVTOOLS)
1059 top_job_factory.reset(new net::ProtocolInterceptJobFactory(
1060 top_job_factory.Pass(),
1061 scoped_ptr<net::URLRequestJobFactory::ProtocolHandler>(
1062 new DebugDevToolsInterceptor)));
1065 if (protocol_handler_interceptor) {
1066 protocol_handler_interceptor->Chain(top_job_factory.Pass());
1067 return protocol_handler_interceptor.PassAs<net::URLRequestJobFactory>();
1069 return top_job_factory.Pass();
1073 void ProfileIOData::ShutdownOnUIThread() {
1074 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1077 signin_names_->ReleaseResourcesOnUIThread();
1079 google_services_user_account_id_.Destroy();
1080 google_services_username_.Destroy();
1081 google_services_username_pattern_.Destroy();
1082 reverse_autologin_enabled_.Destroy();
1083 one_click_signin_rejected_email_list_.Destroy();
1084 enable_referrers_.Destroy();
1085 enable_do_not_track_.Destroy();
1086 force_safesearch_.Destroy();
1087 #if !defined(OS_CHROMEOS)
1088 enable_metrics_.Destroy();
1090 safe_browsing_enabled_.Destroy();
1091 printing_enabled_.Destroy();
1092 sync_disabled_.Destroy();
1093 signin_allowed_.Destroy();
1094 network_prediction_enabled_.Destroy();
1095 quick_check_enabled_.Destroy();
1096 if (media_device_id_salt_)
1097 media_device_id_salt_->ShutdownOnUIThread();
1098 session_startup_pref_.Destroy();
1099 #if defined(ENABLE_CONFIGURATION_POLICY)
1100 if (url_blacklist_manager_)
1101 url_blacklist_manager_->ShutdownOnUIThread();
1103 if (chrome_http_user_agent_settings_)
1104 chrome_http_user_agent_settings_->CleanupOnUIThread();
1105 bool posted = BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, this);
1110 void ProfileIOData::set_server_bound_cert_service(
1111 net::ServerBoundCertService* server_bound_cert_service) const {
1112 server_bound_cert_service_.reset(server_bound_cert_service);
1115 void ProfileIOData::DestroyResourceContext() {
1116 resource_context_.reset();
1119 void ProfileIOData::PopulateNetworkSessionParams(
1120 const ProfileParams* profile_params,
1121 net::HttpNetworkSession::Params* params) const {
1123 ChromeURLRequestContext* context = main_request_context();
1125 IOThread* const io_thread = profile_params->io_thread;
1127 io_thread->InitializeNetworkSessionParams(params);
1129 params->host_resolver = context->host_resolver();
1130 params->cert_verifier = context->cert_verifier();
1131 params->server_bound_cert_service = context->server_bound_cert_service();
1132 params->transport_security_state = context->transport_security_state();
1133 params->cert_transparency_verifier = context->cert_transparency_verifier();
1134 params->proxy_service = context->proxy_service();
1135 params->ssl_session_cache_shard = GetSSLSessionCacheShard();
1136 params->ssl_config_service = context->ssl_config_service();
1137 params->http_auth_handler_factory = context->http_auth_handler_factory();
1138 params->network_delegate = network_delegate();
1139 params->http_server_properties = context->http_server_properties();
1140 params->net_log = context->net_log();
1143 void ProfileIOData::SetCookieSettingsForTesting(
1144 CookieSettings* cookie_settings) {
1145 DCHECK(!cookie_settings_.get());
1146 cookie_settings_ = cookie_settings;
1149 void ProfileIOData::set_signin_names_for_testing(
1150 SigninNamesOnIOThread* signin_names) {
1151 signin_names_.reset(signin_names);