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_resource_protocols.h"
34 #include "chrome/browser/io_thread.h"
35 #include "chrome/browser/media/media_device_id_salt.h"
36 #include "chrome/browser/net/about_protocol_handler.h"
37 #include "chrome/browser/net/chrome_fraudulent_certificate_reporter.h"
38 #include "chrome/browser/net/chrome_http_user_agent_settings.h"
39 #include "chrome/browser/net/chrome_net_log.h"
40 #include "chrome/browser/net/chrome_network_delegate.h"
41 #include "chrome/browser/net/cookie_store_util.h"
42 #include "chrome/browser/net/proxy_service_factory.h"
43 #include "chrome/browser/profiles/profile.h"
44 #include "chrome/browser/profiles/profile_manager.h"
45 #include "chrome/browser/signin/signin_names_io_thread.h"
46 #include "chrome/common/chrome_paths.h"
47 #include "chrome/common/chrome_switches.h"
48 #include "chrome/common/net/url_fixer_upper.h"
49 #include "chrome/common/pref_names.h"
50 #include "chrome/common/url_constants.h"
51 #include "components/startup_metric_utils/startup_metric_utils.h"
52 #include "components/sync_driver/pref_names.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_protocols.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::Parsed& parsed = stripped_url.parsed_for_possibly_invalid_spec();
158 int offset = parsed.CountCharactersBefore(url::Parsed::PATH, false);
159 if (offset < static_cast<int>(spec.size()))
160 relative_path.assign(spec.substr(offset + bundled_path_prefix.length()));
162 // Check that |relative_path| is not an absolute path (otherwise
163 // AppendASCII() will DCHECK). The awkward use of StringType is because on
164 // some systems FilePath expects a std::string, but on others a std::wstring.
166 base::FilePath::StringType(relative_path.begin(), relative_path.end()));
170 base::FilePath inspector_dir;
171 if (!PathService::Get(chrome::DIR_INSPECTOR, &inspector_dir))
174 if (inspector_dir.empty())
177 *path = inspector_dir.AppendASCII(relative_path);
181 class DebugDevToolsInterceptor
182 : public net::URLRequestJobFactory::ProtocolHandler {
184 DebugDevToolsInterceptor() {}
185 virtual ~DebugDevToolsInterceptor() {}
187 virtual net::URLRequestJob* MaybeCreateJob(
188 net::URLRequest* request,
189 net::NetworkDelegate* network_delegate) const OVERRIDE {
191 if (IsSupportedDevToolsURL(request->url(), &path))
192 return new net::URLRequestFileJob(
193 request, network_delegate, path,
194 content::BrowserThread::GetBlockingPool()->
195 GetTaskRunnerWithShutdownBehavior(
196 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN));
201 #endif // defined(DEBUG_DEVTOOLS)
203 #if defined(OS_CHROMEOS)
204 // The following four functions are responsible for initializing NSS for each
205 // profile on ChromeOS, which has a separate NSS database and TPM slot
208 // Initialization basically follows these steps:
209 // 1) Get some info from chromeos::UserManager about the User for this profile.
210 // 2) Tell nss_util to initialize the software slot for this profile.
211 // 3) Wait for the TPM module to be loaded by nss_util if it isn't already.
212 // 4) Ask CryptohomeClient which TPM slot id corresponds to this profile.
213 // 5) Tell nss_util to use that slot id on the TPM module.
215 // Some of these steps must happen on the UI thread, others must happen on the
217 // UI thread IO Thread
219 // ProfileIOData::InitializeOnUIThread
221 // chromeos::UserManager::GetUserByProfile
222 // \---------------------------------------v
223 // StartNSSInitOnIOThread
225 // crypto::InitializeNSSForChromeOSUser
227 // crypto::IsTPMTokenReady
229 // StartTPMSlotInitializationOnIOThread
230 // v---------------------------------------/
231 // GetTPMInfoForUserOnUIThread
233 // CryptohomeClient::Pkcs11GetTpmTokenInfoForUser
235 // DidGetTPMInfoForUserOnUIThread
236 // \---------------------------------------v
237 // crypto::InitializeTPMForChromeOSUser
239 void DidGetTPMInfoForUserOnUIThread(const std::string& username_hash,
240 chromeos::DBusMethodCallStatus call_status,
241 const std::string& label,
242 const std::string& user_pin,
244 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
245 if (call_status == chromeos::DBUS_METHOD_CALL_FAILURE) {
246 NOTREACHED() << "dbus error getting TPM info for " << username_hash;
249 DVLOG(1) << "Got TPM slot for " << username_hash << ": " << slot_id;
250 BrowserThread::PostTask(
254 &crypto::InitializeTPMForChromeOSUser, username_hash, slot_id));
257 void GetTPMInfoForUserOnUIThread(const std::string& username,
258 const std::string& username_hash) {
259 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
260 DVLOG(1) << "Getting TPM info from cryptohome for "
261 << " " << username << " " << username_hash;
262 chromeos::DBusThreadManager::Get()
263 ->GetCryptohomeClient()
264 ->Pkcs11GetTpmTokenInfoForUser(
266 base::Bind(&DidGetTPMInfoForUserOnUIThread, username_hash));
269 void StartTPMSlotInitializationOnIOThread(const std::string& username,
270 const std::string& username_hash) {
271 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
273 BrowserThread::PostTask(
276 base::Bind(&GetTPMInfoForUserOnUIThread, username, username_hash));
279 void StartNSSInitOnIOThread(const std::string& username,
280 const std::string& username_hash,
281 const base::FilePath& path,
282 bool is_primary_user) {
283 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
284 DVLOG(1) << "Starting NSS init for " << username
285 << " hash:" << username_hash
286 << " is_primary_user:" << is_primary_user;
288 if (!crypto::InitializeNSSForChromeOSUser(
289 username, username_hash, is_primary_user, path)) {
290 // If the user already exists in nss_util's map, it is already initialized
291 // or in the process of being initialized. In either case, there's no need
296 if (crypto::IsTPMTokenEnabledForNSS()) {
297 if (crypto::IsTPMTokenReady(base::Bind(
298 &StartTPMSlotInitializationOnIOThread, username, username_hash))) {
299 StartTPMSlotInitializationOnIOThread(username, username_hash);
301 DVLOG(1) << "Waiting for tpm ready ...";
304 crypto::InitializePrivateSoftwareSlotForChromeOSUser(username_hash);
307 #endif // defined(OS_CHROMEOS)
311 void ProfileIOData::InitializeOnUIThread(Profile* profile) {
312 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
313 PrefService* pref_service = profile->GetPrefs();
314 PrefService* local_state_pref_service = g_browser_process->local_state();
316 scoped_ptr<ProfileParams> params(new ProfileParams);
317 params->path = profile->GetPath();
319 params->io_thread = g_browser_process->io_thread();
321 params->cookie_settings = CookieSettings::Factory::GetForProfile(profile);
322 params->host_content_settings_map = profile->GetHostContentSettingsMap();
323 params->ssl_config_service = profile->GetSSLConfigService();
324 params->cookie_monster_delegate =
325 chrome_browser_net::CreateCookieDelegate(profile);
326 params->extension_info_map =
327 extensions::ExtensionSystem::Get(profile)->info_map();
329 ProtocolHandlerRegistry* protocol_handler_registry =
330 ProtocolHandlerRegistryFactory::GetForProfile(profile);
331 DCHECK(protocol_handler_registry);
333 // The profile instance is only available here in the InitializeOnUIThread
334 // method, so we create the url job factory here, then save it for
335 // later delivery to the job factory in Init().
336 params->protocol_handler_interceptor =
337 protocol_handler_registry->CreateJobInterceptorFactory();
339 params->proxy_config_service
340 .reset(ProxyServiceFactory::CreateProxyConfigService(
341 profile->GetProxyConfigTracker()));
342 #if defined(ENABLE_MANAGED_USERS)
343 ManagedUserService* managed_user_service =
344 ManagedUserServiceFactory::GetForProfile(profile);
345 params->managed_mode_url_filter =
346 managed_user_service->GetURLFilterForIOThread();
348 #if defined(OS_CHROMEOS)
349 chromeos::UserManager* user_manager = chromeos::UserManager::Get();
351 chromeos::User* user = user_manager->GetUserByProfile(profile);
353 params->username_hash = user->username_hash();
354 bool is_primary_user = (user_manager->GetPrimaryUser() == user);
355 BrowserThread::PostTask(BrowserThread::IO,
357 base::Bind(&StartNSSInitOnIOThread,
359 user->username_hash(),
364 if (params->username_hash.empty())
365 LOG(WARNING) << "no username_hash";
368 params->profile = profile;
369 profile_params_.reset(params.release());
371 ChromeNetworkDelegate::InitializePrefsOnUIThread(
373 &enable_do_not_track_,
377 scoped_refptr<base::MessageLoopProxy> io_message_loop_proxy =
378 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
379 #if defined(ENABLE_PRINTING)
380 printing_enabled_.Init(prefs::kPrintingEnabled, pref_service);
381 printing_enabled_.MoveToThread(io_message_loop_proxy);
384 chrome_http_user_agent_settings_.reset(
385 new ChromeHttpUserAgentSettings(pref_service));
387 // These members are used only for one click sign in, which is not enabled
388 // in incognito mode. So no need to initialize them.
389 if (!IsOffTheRecord()) {
390 signin_names_.reset(new SigninNamesOnIOThread());
392 google_services_user_account_id_.Init(
393 prefs::kGoogleServicesUserAccountId, pref_service);
394 google_services_user_account_id_.MoveToThread(io_message_loop_proxy);
396 google_services_username_.Init(
397 prefs::kGoogleServicesUsername, pref_service);
398 google_services_username_.MoveToThread(io_message_loop_proxy);
400 google_services_username_pattern_.Init(
401 prefs::kGoogleServicesUsernamePattern, local_state_pref_service);
402 google_services_username_pattern_.MoveToThread(io_message_loop_proxy);
404 reverse_autologin_enabled_.Init(
405 prefs::kReverseAutologinEnabled, pref_service);
406 reverse_autologin_enabled_.MoveToThread(io_message_loop_proxy);
408 one_click_signin_rejected_email_list_.Init(
409 prefs::kReverseAutologinRejectedEmailList, pref_service);
410 one_click_signin_rejected_email_list_.MoveToThread(io_message_loop_proxy);
412 sync_disabled_.Init(sync_driver::prefs::kSyncManaged, pref_service);
413 sync_disabled_.MoveToThread(io_message_loop_proxy);
415 signin_allowed_.Init(prefs::kSigninAllowed, pref_service);
416 signin_allowed_.MoveToThread(io_message_loop_proxy);
419 quick_check_enabled_.Init(prefs::kQuickCheckEnabled,
420 local_state_pref_service);
421 quick_check_enabled_.MoveToThread(io_message_loop_proxy);
423 media_device_id_salt_ = new MediaDeviceIDSalt(pref_service, IsOffTheRecord());
425 network_prediction_enabled_.Init(prefs::kNetworkPredictionEnabled,
427 network_prediction_enabled_.MoveToThread(io_message_loop_proxy);
429 #if defined(OS_CHROMEOS)
430 cert_verifier_ = policy::PolicyCertServiceFactory::CreateForProfile(profile);
432 // The URLBlacklistManager has to be created on the UI thread to register
433 // observers of |pref_service|, and it also has to clean up on
434 // ShutdownOnUIThread to release these observers on the right thread.
435 // Don't pass it in |profile_params_| to make sure it is correctly cleaned up,
436 // in particular when this ProfileIOData isn't |initialized_| during deletion.
437 #if defined(ENABLE_CONFIGURATION_POLICY)
438 policy::URLBlacklist::SegmentURLCallback callback =
439 static_cast<policy::URLBlacklist::SegmentURLCallback>(
440 URLFixerUpper::SegmentURL);
441 base::SequencedWorkerPool* pool = BrowserThread::GetBlockingPool();
442 scoped_refptr<base::SequencedTaskRunner> background_task_runner =
443 pool->GetSequencedTaskRunner(pool->GetSequenceToken());
444 url_blacklist_manager_.reset(
445 new policy::URLBlacklistManager(
447 background_task_runner,
448 io_message_loop_proxy,
450 base::Bind(policy::OverrideBlacklistForURL)));
452 if (!IsOffTheRecord()) {
453 // Add policy headers for non-incognito requests.
454 policy::PolicyHeaderService* policy_header_service =
455 policy::PolicyHeaderServiceFactory::GetForBrowserContext(profile);
456 if (policy_header_service) {
457 policy_header_helper_ = policy_header_service->CreatePolicyHeaderIOHelper(
458 io_message_loop_proxy);
463 incognito_availibility_pref_.Init(
464 prefs::kIncognitoModeAvailability, pref_service);
465 incognito_availibility_pref_.MoveToThread(io_message_loop_proxy);
467 initialized_on_UI_thread_ = true;
469 // We need to make sure that content initializes its own data structures that
470 // are associated with each ResourceContext because we might post this
471 // object to the IO thread after this function.
472 BrowserContext::EnsureResourceContextInitialized(profile);
475 ProfileIOData::MediaRequestContext::MediaRequestContext() {
478 void ProfileIOData::MediaRequestContext::SetHttpTransactionFactory(
479 scoped_ptr<net::HttpTransactionFactory> http_factory) {
480 http_factory_ = http_factory.Pass();
481 set_http_transaction_factory(http_factory_.get());
484 ProfileIOData::MediaRequestContext::~MediaRequestContext() {}
486 ProfileIOData::AppRequestContext::AppRequestContext() {
489 void ProfileIOData::AppRequestContext::SetCookieStore(
490 net::CookieStore* cookie_store) {
491 cookie_store_ = cookie_store;
492 set_cookie_store(cookie_store);
495 void ProfileIOData::AppRequestContext::SetHttpTransactionFactory(
496 scoped_ptr<net::HttpTransactionFactory> http_factory) {
497 http_factory_ = http_factory.Pass();
498 set_http_transaction_factory(http_factory_.get());
501 void ProfileIOData::AppRequestContext::SetJobFactory(
502 scoped_ptr<net::URLRequestJobFactory> job_factory) {
503 job_factory_ = job_factory.Pass();
504 set_job_factory(job_factory_.get());
507 ProfileIOData::AppRequestContext::~AppRequestContext() {}
509 ProfileIOData::ProfileParams::ProfileParams()
514 ProfileIOData::ProfileParams::~ProfileParams() {}
516 ProfileIOData::ProfileIOData(Profile::ProfileType profile_type)
517 : initialized_(false),
518 resource_context_(new ResourceContext(this)),
519 initialized_on_UI_thread_(false),
520 profile_type_(profile_type) {
521 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
524 ProfileIOData::~ProfileIOData() {
525 if (BrowserThread::IsMessageLoopValid(BrowserThread::IO))
526 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
528 // Pull the contents of the request context maps onto the stack for sanity
529 // checking of values in a minidump. http://crbug.com/260425
530 size_t num_app_contexts = app_request_context_map_.size();
531 size_t num_media_contexts = isolated_media_request_context_map_.size();
532 size_t current_context = 0;
533 static const size_t kMaxCachedContexts = 20;
534 ChromeURLRequestContext* app_context_cache[kMaxCachedContexts] = {0};
535 void* app_context_vtable_cache[kMaxCachedContexts] = {0};
536 ChromeURLRequestContext* media_context_cache[kMaxCachedContexts] = {0};
537 void* media_context_vtable_cache[kMaxCachedContexts] = {0};
538 void* tmp_vtable = NULL;
539 base::debug::Alias(&num_app_contexts);
540 base::debug::Alias(&num_media_contexts);
541 base::debug::Alias(¤t_context);
542 base::debug::Alias(app_context_cache);
543 base::debug::Alias(app_context_vtable_cache);
544 base::debug::Alias(media_context_cache);
545 base::debug::Alias(media_context_vtable_cache);
546 base::debug::Alias(&tmp_vtable);
549 for (URLRequestContextMap::const_iterator it =
550 app_request_context_map_.begin();
551 current_context < kMaxCachedContexts &&
552 it != app_request_context_map_.end();
553 ++it, ++current_context) {
554 app_context_cache[current_context] = it->second;
555 memcpy(&app_context_vtable_cache[current_context],
556 static_cast<void*>(it->second), sizeof(void*));
560 for (URLRequestContextMap::const_iterator it =
561 isolated_media_request_context_map_.begin();
562 current_context < kMaxCachedContexts &&
563 it != isolated_media_request_context_map_.end();
564 ++it, ++current_context) {
565 media_context_cache[current_context] = it->second;
566 memcpy(&media_context_vtable_cache[current_context],
567 static_cast<void*>(it->second), sizeof(void*));
570 // TODO(ajwong): These AssertNoURLRequests() calls are unnecessary since they
571 // are already done in the URLRequestContext destructor.
572 if (main_request_context_)
573 main_request_context_->AssertNoURLRequests();
574 if (extensions_request_context_)
575 extensions_request_context_->AssertNoURLRequests();
578 for (URLRequestContextMap::iterator it = app_request_context_map_.begin();
579 it != app_request_context_map_.end(); ++it) {
580 if (current_context < kMaxCachedContexts) {
581 CHECK_EQ(app_context_cache[current_context], it->second);
582 memcpy(&tmp_vtable, static_cast<void*>(it->second), sizeof(void*));
583 CHECK_EQ(app_context_vtable_cache[current_context], tmp_vtable);
585 it->second->AssertNoURLRequests();
591 for (URLRequestContextMap::iterator it =
592 isolated_media_request_context_map_.begin();
593 it != isolated_media_request_context_map_.end(); ++it) {
594 if (current_context < kMaxCachedContexts) {
595 CHECK_EQ(media_context_cache[current_context], it->second);
596 memcpy(&tmp_vtable, static_cast<void*>(it->second), sizeof(void*));
597 CHECK_EQ(media_context_vtable_cache[current_context], tmp_vtable);
599 it->second->AssertNoURLRequests();
606 ProfileIOData* ProfileIOData::FromResourceContext(
607 content::ResourceContext* rc) {
608 return (static_cast<ResourceContext*>(rc))->io_data_;
612 bool ProfileIOData::IsHandledProtocol(const std::string& scheme) {
613 DCHECK_EQ(scheme, StringToLowerASCII(scheme));
614 static const char* const kProtocolList[] = {
615 content::kFileScheme,
616 content::kChromeDevToolsScheme,
617 chrome::kDomDistillerScheme,
618 extensions::kExtensionScheme,
619 extensions::kExtensionResourceScheme,
620 content::kChromeUIScheme,
621 content::kDataScheme,
622 #if defined(OS_CHROMEOS)
623 chrome::kDriveScheme,
624 #endif // defined(OS_CHROMEOS)
625 content::kAboutScheme,
626 #if !defined(DISABLE_FTP_SUPPORT)
628 #endif // !defined(DISABLE_FTP_SUPPORT)
629 content::kBlobScheme,
630 content::kFileSystemScheme,
631 chrome::kChromeSearchScheme,
633 for (size_t i = 0; i < arraysize(kProtocolList); ++i) {
634 if (scheme == kProtocolList[i])
637 return net::URLRequest::IsHandledProtocol(scheme);
641 bool ProfileIOData::IsHandledURL(const GURL& url) {
642 if (!url.is_valid()) {
643 // We handle error cases.
647 return IsHandledProtocol(url.scheme());
651 void ProfileIOData::InstallProtocolHandlers(
652 net::URLRequestJobFactoryImpl* job_factory,
653 content::ProtocolHandlerMap* protocol_handlers) {
654 for (content::ProtocolHandlerMap::iterator it =
655 protocol_handlers->begin();
656 it != protocol_handlers->end();
658 bool set_protocol = job_factory->SetProtocolHandler(
659 it->first, it->second.release());
660 DCHECK(set_protocol);
662 protocol_handlers->clear();
665 content::ResourceContext* ProfileIOData::GetResourceContext() const {
666 return resource_context_.get();
669 ChromeURLRequestContext* ProfileIOData::GetMainRequestContext() const {
670 DCHECK(initialized_);
671 return main_request_context_.get();
674 ChromeURLRequestContext* ProfileIOData::GetMediaRequestContext() const {
675 DCHECK(initialized_);
676 ChromeURLRequestContext* context = AcquireMediaRequestContext();
681 ChromeURLRequestContext* ProfileIOData::GetExtensionsRequestContext() const {
682 DCHECK(initialized_);
683 return extensions_request_context_.get();
686 ChromeURLRequestContext* ProfileIOData::GetIsolatedAppRequestContext(
687 ChromeURLRequestContext* main_context,
688 const StoragePartitionDescriptor& partition_descriptor,
689 scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
690 protocol_handler_interceptor,
691 content::ProtocolHandlerMap* protocol_handlers,
692 content::ProtocolHandlerScopedVector protocol_interceptors) const {
693 DCHECK(initialized_);
694 ChromeURLRequestContext* context = NULL;
695 if (ContainsKey(app_request_context_map_, partition_descriptor)) {
696 context = app_request_context_map_[partition_descriptor];
699 AcquireIsolatedAppRequestContext(main_context,
700 partition_descriptor,
701 protocol_handler_interceptor.Pass(),
703 protocol_interceptors.Pass());
704 app_request_context_map_[partition_descriptor] = context;
710 ChromeURLRequestContext* ProfileIOData::GetIsolatedMediaRequestContext(
711 ChromeURLRequestContext* app_context,
712 const StoragePartitionDescriptor& partition_descriptor) const {
713 DCHECK(initialized_);
714 ChromeURLRequestContext* context = NULL;
715 if (ContainsKey(isolated_media_request_context_map_, partition_descriptor)) {
716 context = isolated_media_request_context_map_[partition_descriptor];
718 context = AcquireIsolatedMediaRequestContext(app_context,
719 partition_descriptor);
720 isolated_media_request_context_map_[partition_descriptor] = context;
726 extensions::InfoMap* ProfileIOData::GetExtensionInfoMap() const {
727 DCHECK(initialized_) << "ExtensionSystem not initialized";
728 return extension_info_map_.get();
731 CookieSettings* ProfileIOData::GetCookieSettings() const {
732 // Allow either Init() or SetCookieSettingsForTesting() to initialize.
733 DCHECK(initialized_ || cookie_settings_.get());
734 return cookie_settings_.get();
737 HostContentSettingsMap* ProfileIOData::GetHostContentSettingsMap() const {
738 DCHECK(initialized_);
739 return host_content_settings_map_.get();
742 ResourceContext::SaltCallback ProfileIOData::GetMediaDeviceIDSalt() const {
743 return base::Bind(&MediaDeviceIDSalt::GetSalt, media_device_id_salt_);
746 bool ProfileIOData::IsOffTheRecord() const {
747 return profile_type() == Profile::INCOGNITO_PROFILE
748 || profile_type() == Profile::GUEST_PROFILE;
751 void ProfileIOData::InitializeMetricsEnabledStateOnUIThread() {
752 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
753 #if defined(OS_CHROMEOS)
754 // Just fetch the value from ChromeOS' settings while we're on the UI thread.
755 // TODO(stevet): For now, this value is only set on profile initialization.
756 // We will want to do something similar to the PrefMember method below in the
757 // future to more accurately capture this state.
758 chromeos::CrosSettings::Get()->GetBoolean(chromeos::kStatsReportingPref,
760 #elif defined(OS_ANDROID)
761 // TODO(dwkang): rename or unify the pref for UMA once we have conclusion
762 // in crbugs.com/246495.
763 // Android has it's own preferences for metrics / crash uploading.
764 enable_metrics_.Init(prefs::kCrashReportingEnabled,
765 g_browser_process->local_state());
766 enable_metrics_.MoveToThread(
767 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
769 // Prep the PrefMember and send it to the IO thread, since this value will be
771 enable_metrics_.Init(prefs::kMetricsReportingEnabled,
772 g_browser_process->local_state());
773 enable_metrics_.MoveToThread(
774 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
775 #endif // defined(OS_CHROMEOS)
778 bool ProfileIOData::GetMetricsEnabledStateOnIOThread() const {
779 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
780 #if defined(OS_CHROMEOS)
781 return enable_metrics_;
783 return enable_metrics_.GetValue();
784 #endif // defined(OS_CHROMEOS)
787 base::WeakPtr<net::HttpServerProperties>
788 ProfileIOData::http_server_properties() const {
789 return http_server_properties_->GetWeakPtr();
792 void ProfileIOData::set_http_server_properties(
793 scoped_ptr<net::HttpServerProperties> http_server_properties) const {
794 http_server_properties_ = http_server_properties.Pass();
797 ProfileIOData::ResourceContext::ResourceContext(ProfileIOData* io_data)
799 host_resolver_(NULL),
800 request_context_(NULL) {
804 ProfileIOData::ResourceContext::~ResourceContext() {}
806 net::HostResolver* ProfileIOData::ResourceContext::GetHostResolver() {
807 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
808 DCHECK(io_data_->initialized_);
809 return host_resolver_;
812 net::URLRequestContext* ProfileIOData::ResourceContext::GetRequestContext() {
813 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
814 DCHECK(io_data_->initialized_);
815 return request_context_;
818 scoped_ptr<net::ClientCertStore>
819 ProfileIOData::ResourceContext::CreateClientCertStore() {
820 if (!io_data_->client_cert_store_factory_.is_null())
821 return io_data_->client_cert_store_factory_.Run();
822 #if defined(OS_CHROMEOS)
823 return scoped_ptr<net::ClientCertStore>(new net::ClientCertStoreChromeOS(
824 io_data_->username_hash(),
825 base::Bind(&CreateCryptoModuleBlockingPasswordDelegate,
826 chrome::kCryptoModulePasswordClientAuth)));
827 #elif defined(USE_NSS)
828 return scoped_ptr<net::ClientCertStore>(new net::ClientCertStoreNSS(
829 base::Bind(&CreateCryptoModuleBlockingPasswordDelegate,
830 chrome::kCryptoModulePasswordClientAuth)));
831 #elif defined(OS_WIN)
832 return scoped_ptr<net::ClientCertStore>(new net::ClientCertStoreWin());
833 #elif defined(OS_MACOSX)
834 return scoped_ptr<net::ClientCertStore>(new net::ClientCertStoreMac());
835 #elif defined(USE_OPENSSL)
836 // OpenSSL does not use the ClientCertStore infrastructure. On Android client
837 // cert matching is done by the OS as part of the call to show the cert
839 return scoped_ptr<net::ClientCertStore>();
841 #error Unknown platform.
845 void ProfileIOData::ResourceContext::CreateKeygenHandler(
846 uint32 key_size_in_bits,
847 const std::string& challenge_string,
849 const base::Callback<void(scoped_ptr<net::KeygenHandler>)>& callback) {
850 DCHECK(!callback.is_null());
852 scoped_ptr<net::KeygenHandler> keygen_handler(
853 new net::KeygenHandler(key_size_in_bits, challenge_string, url));
855 scoped_ptr<ChromeNSSCryptoModuleDelegate> delegate(
856 new ChromeNSSCryptoModuleDelegate(chrome::kCryptoModulePasswordKeygen,
857 net::HostPortPair::FromURL(url)));
858 ChromeNSSCryptoModuleDelegate* delegate_ptr = delegate.get();
859 keygen_handler->set_crypto_module_delegate(
860 delegate.PassAs<crypto::NSSCryptoModuleDelegate>());
862 base::Closure bound_callback =
863 base::Bind(callback, base::Passed(&keygen_handler));
864 if (delegate_ptr->InitializeSlot(this, bound_callback)) {
865 // Initialization complete, run the callback synchronously.
866 bound_callback.Run();
869 // Otherwise, the InitializeSlot will run the callback asynchronously.
871 callback.Run(make_scoped_ptr(
872 new net::KeygenHandler(key_size_in_bits, challenge_string, url)));
876 bool ProfileIOData::ResourceContext::AllowMicAccess(const GURL& origin) {
877 return AllowContentAccess(origin, CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC);
880 bool ProfileIOData::ResourceContext::AllowCameraAccess(const GURL& origin) {
881 return AllowContentAccess(origin, CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA);
884 bool ProfileIOData::ResourceContext::AllowContentAccess(
885 const GURL& origin, ContentSettingsType type) {
886 HostContentSettingsMap* content_settings =
887 io_data_->GetHostContentSettingsMap();
888 ContentSetting setting = content_settings->GetContentSetting(
889 origin, origin, type, NO_RESOURCE_IDENTIFIER);
890 return setting == CONTENT_SETTING_ALLOW;
893 ResourceContext::SaltCallback
894 ProfileIOData::ResourceContext::GetMediaDeviceIDSalt() {
895 return io_data_->GetMediaDeviceIDSalt();
899 std::string ProfileIOData::GetSSLSessionCacheShard() {
900 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
901 // The SSL session cache is partitioned by setting a string. This returns a
902 // unique string to partition the SSL session cache. Each time we create a
903 // new profile, we'll get a fresh SSL session cache which is separate from
904 // the other profiles.
905 static unsigned ssl_session_cache_instance = 0;
906 return base::StringPrintf("profile/%u", ssl_session_cache_instance++);
909 void ProfileIOData::Init(
910 content::ProtocolHandlerMap* protocol_handlers,
911 content::ProtocolHandlerScopedVector protocol_interceptors) const {
912 // The basic logic is implemented here. The specific initialization
913 // is done in InitializeInternal(), implemented by subtypes. Static helper
914 // functions have been provided to assist in common operations.
915 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
916 DCHECK(!initialized_);
918 startup_metric_utils::ScopedSlowStartupUMA
919 scoped_timer("Startup.SlowStartupProfileIODataInit");
921 // TODO(jhawkins): Remove once crbug.com/102004 is fixed.
922 CHECK(initialized_on_UI_thread_);
924 // TODO(jhawkins): Return to DCHECK once crbug.com/102004 is fixed.
925 CHECK(profile_params_.get());
927 IOThread* const io_thread = profile_params_->io_thread;
928 IOThread::Globals* const io_thread_globals = io_thread->globals();
929 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
931 // Create the common request contexts.
932 main_request_context_.reset(new ChromeURLRequestContext());
933 extensions_request_context_.reset(new ChromeURLRequestContext());
935 ChromeNetworkDelegate* network_delegate =
936 new ChromeNetworkDelegate(
937 io_thread_globals->extension_event_router_forwarder.get(),
939 if (command_line.HasSwitch(switches::kEnableClientHints))
940 network_delegate->SetEnableClientHints();
941 network_delegate->set_extension_info_map(
942 profile_params_->extension_info_map.get());
943 #if defined(ENABLE_CONFIGURATION_POLICY)
944 network_delegate->set_url_blacklist_manager(url_blacklist_manager_.get());
946 network_delegate->set_profile(profile_params_->profile);
947 network_delegate->set_profile_path(profile_params_->path);
948 network_delegate->set_cookie_settings(profile_params_->cookie_settings.get());
949 network_delegate->set_enable_do_not_track(&enable_do_not_track_);
950 network_delegate->set_force_google_safe_search(&force_safesearch_);
951 network_delegate_.reset(network_delegate);
953 fraudulent_certificate_reporter_.reset(
954 new chrome_browser_net::ChromeFraudulentCertificateReporter(
955 main_request_context_.get()));
957 // NOTE: Proxy service uses the default io thread network delegate, not the
958 // delegate just created.
959 proxy_service_.reset(
960 ProxyServiceFactory::CreateProxyService(
961 io_thread->net_log(),
962 io_thread_globals->proxy_script_fetcher_context.get(),
963 io_thread_globals->system_network_delegate.get(),
964 profile_params_->proxy_config_service.release(),
966 quick_check_enabled_.GetValue()));
968 transport_security_state_.reset(new net::TransportSecurityState());
969 transport_security_persister_.reset(
970 new net::TransportSecurityPersister(
971 transport_security_state_.get(),
972 profile_params_->path,
973 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE),
976 // Take ownership over these parameters.
977 cookie_settings_ = profile_params_->cookie_settings;
978 host_content_settings_map_ = profile_params_->host_content_settings_map;
979 extension_info_map_ = profile_params_->extension_info_map;
981 resource_context_->host_resolver_ = io_thread_globals->host_resolver.get();
982 resource_context_->request_context_ = main_request_context_.get();
984 #if defined(ENABLE_MANAGED_USERS)
985 managed_mode_url_filter_ = profile_params_->managed_mode_url_filter;
988 #if defined(OS_CHROMEOS)
989 username_hash_ = profile_params_->username_hash;
990 scoped_refptr<net::CertVerifyProc> verify_proc;
991 if (chromeos::UserManager::IsMultipleProfilesAllowed()) {
992 crypto::ScopedPK11Slot public_slot =
993 crypto::GetPublicSlotForChromeOSUser(username_hash_);
994 // The private slot won't be ready by this point. It shouldn't be necessary
995 // for cert trust purposes anyway.
996 verify_proc = new chromeos::CertVerifyProcChromeOS(public_slot.Pass());
998 verify_proc = net::CertVerifyProc::CreateDefault();
1000 if (cert_verifier_) {
1001 cert_verifier_->InitializeOnIOThread(verify_proc);
1002 main_request_context_->set_cert_verifier(cert_verifier_.get());
1004 main_request_context_->set_cert_verifier(
1005 new net::MultiThreadedCertVerifier(verify_proc.get()));
1008 main_request_context_->set_cert_verifier(
1009 io_thread_globals->cert_verifier.get());
1013 profile_params_.get(), protocol_handlers, protocol_interceptors.Pass());
1015 profile_params_.reset();
1016 initialized_ = true;
1019 void ProfileIOData::ApplyProfileParamsToContext(
1020 ChromeURLRequestContext* context) const {
1021 context->set_http_user_agent_settings(
1022 chrome_http_user_agent_settings_.get());
1023 context->set_ssl_config_service(profile_params_->ssl_config_service.get());
1026 scoped_ptr<net::URLRequestJobFactory> ProfileIOData::SetUpJobFactoryDefaults(
1027 scoped_ptr<net::URLRequestJobFactoryImpl> job_factory,
1028 content::ProtocolHandlerScopedVector protocol_interceptors,
1029 scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
1030 protocol_handler_interceptor,
1031 net::NetworkDelegate* network_delegate,
1032 net::FtpTransactionFactory* ftp_transaction_factory) const {
1033 // NOTE(willchan): Keep these protocol handlers in sync with
1034 // ProfileIOData::IsHandledProtocol().
1035 bool set_protocol = job_factory->SetProtocolHandler(
1036 content::kFileScheme,
1037 new net::FileProtocolHandler(
1038 content::BrowserThread::GetBlockingPool()->
1039 GetTaskRunnerWithShutdownBehavior(
1040 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)));
1041 DCHECK(set_protocol);
1043 DCHECK(extension_info_map_.get());
1044 // Check only for incognito (and not Chrome OS guest mode GUEST_PROFILE).
1045 bool is_incognito = profile_type() == Profile::INCOGNITO_PROFILE;
1046 set_protocol = job_factory->SetProtocolHandler(
1047 extensions::kExtensionScheme,
1048 extensions::CreateExtensionProtocolHandler(is_incognito,
1049 extension_info_map_.get()));
1050 DCHECK(set_protocol);
1051 set_protocol = job_factory->SetProtocolHandler(
1052 extensions::kExtensionResourceScheme,
1053 CreateExtensionResourceProtocolHandler());
1054 DCHECK(set_protocol);
1055 set_protocol = job_factory->SetProtocolHandler(
1056 content::kDataScheme, new net::DataProtocolHandler());
1057 DCHECK(set_protocol);
1058 #if defined(OS_CHROMEOS)
1059 if (!IsOffTheRecord() && profile_params_) {
1060 set_protocol = job_factory->SetProtocolHandler(
1061 chrome::kDriveScheme,
1062 new drive::DriveProtocolHandler(profile_params_->profile));
1063 DCHECK(set_protocol);
1065 #endif // defined(OS_CHROMEOS)
1067 job_factory->SetProtocolHandler(
1068 content::kAboutScheme, new chrome_browser_net::AboutProtocolHandler());
1069 #if !defined(DISABLE_FTP_SUPPORT)
1070 DCHECK(ftp_transaction_factory);
1071 job_factory->SetProtocolHandler(
1072 content::kFtpScheme,
1073 new net::FtpProtocolHandler(ftp_transaction_factory));
1074 #endif // !defined(DISABLE_FTP_SUPPORT)
1076 #if defined(DEBUG_DEVTOOLS)
1077 protocol_interceptors.push_back(new DebugDevToolsInterceptor);
1080 // Set up interceptors in the reverse order.
1081 scoped_ptr<net::URLRequestJobFactory> top_job_factory =
1082 job_factory.PassAs<net::URLRequestJobFactory>();
1083 for (content::ProtocolHandlerScopedVector::reverse_iterator i =
1084 protocol_interceptors.rbegin();
1085 i != protocol_interceptors.rend();
1087 top_job_factory.reset(new net::ProtocolInterceptJobFactory(
1088 top_job_factory.Pass(), make_scoped_ptr(*i)));
1090 protocol_interceptors.weak_clear();
1092 if (protocol_handler_interceptor) {
1093 protocol_handler_interceptor->Chain(top_job_factory.Pass());
1094 return protocol_handler_interceptor.PassAs<net::URLRequestJobFactory>();
1096 return top_job_factory.Pass();
1100 void ProfileIOData::ShutdownOnUIThread() {
1101 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1104 signin_names_->ReleaseResourcesOnUIThread();
1106 google_services_user_account_id_.Destroy();
1107 google_services_username_.Destroy();
1108 google_services_username_pattern_.Destroy();
1109 reverse_autologin_enabled_.Destroy();
1110 one_click_signin_rejected_email_list_.Destroy();
1111 enable_referrers_.Destroy();
1112 enable_do_not_track_.Destroy();
1113 force_safesearch_.Destroy();
1114 #if !defined(OS_CHROMEOS)
1115 enable_metrics_.Destroy();
1117 safe_browsing_enabled_.Destroy();
1118 printing_enabled_.Destroy();
1119 sync_disabled_.Destroy();
1120 signin_allowed_.Destroy();
1121 network_prediction_enabled_.Destroy();
1122 quick_check_enabled_.Destroy();
1123 if (media_device_id_salt_)
1124 media_device_id_salt_->ShutdownOnUIThread();
1125 session_startup_pref_.Destroy();
1126 #if defined(ENABLE_CONFIGURATION_POLICY)
1127 if (url_blacklist_manager_)
1128 url_blacklist_manager_->ShutdownOnUIThread();
1130 if (chrome_http_user_agent_settings_)
1131 chrome_http_user_agent_settings_->CleanupOnUIThread();
1132 incognito_availibility_pref_.Destroy();
1133 bool posted = BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, this);
1138 void ProfileIOData::set_server_bound_cert_service(
1139 net::ServerBoundCertService* server_bound_cert_service) const {
1140 server_bound_cert_service_.reset(server_bound_cert_service);
1143 void ProfileIOData::DestroyResourceContext() {
1144 resource_context_.reset();
1147 void ProfileIOData::PopulateNetworkSessionParams(
1148 const ProfileParams* profile_params,
1149 net::HttpNetworkSession::Params* params) const {
1151 ChromeURLRequestContext* context = main_request_context();
1153 IOThread* const io_thread = profile_params->io_thread;
1155 io_thread->InitializeNetworkSessionParams(params);
1157 params->host_resolver = context->host_resolver();
1158 params->cert_verifier = context->cert_verifier();
1159 params->server_bound_cert_service = context->server_bound_cert_service();
1160 params->transport_security_state = context->transport_security_state();
1161 params->cert_transparency_verifier = context->cert_transparency_verifier();
1162 params->proxy_service = context->proxy_service();
1163 params->ssl_session_cache_shard = GetSSLSessionCacheShard();
1164 params->ssl_config_service = context->ssl_config_service();
1165 params->http_auth_handler_factory = context->http_auth_handler_factory();
1166 params->network_delegate = network_delegate();
1167 params->http_server_properties = context->http_server_properties();
1168 params->net_log = context->net_log();
1171 void ProfileIOData::SetCookieSettingsForTesting(
1172 CookieSettings* cookie_settings) {
1173 DCHECK(!cookie_settings_.get());
1174 cookie_settings_ = cookie_settings;
1177 void ProfileIOData::set_signin_names_for_testing(
1178 SigninNamesOnIOThread* signin_names) {
1179 signin_names_.reset(signin_names);