Disable view source for Developer Tools.
[chromium-blink-merge.git] / chrome / browser / profiles / profile_io_data.cc
blob6e00398f8c9c295b45af38a05a01f6373cf3cc84
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"
7 #include <string>
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/extensions/extension_system.h"
36 #include "chrome/browser/io_thread.h"
37 #include "chrome/browser/media/media_device_id_salt.h"
38 #include "chrome/browser/net/about_protocol_handler.h"
39 #include "chrome/browser/net/chrome_fraudulent_certificate_reporter.h"
40 #include "chrome/browser/net/chrome_http_user_agent_settings.h"
41 #include "chrome/browser/net/chrome_net_log.h"
42 #include "chrome/browser/net/chrome_network_delegate.h"
43 #include "chrome/browser/net/cookie_store_util.h"
44 #include "chrome/browser/net/proxy_service_factory.h"
45 #include "chrome/browser/profiles/profile.h"
46 #include "chrome/browser/profiles/profile_manager.h"
47 #include "chrome/browser/signin/signin_names_io_thread.h"
48 #include "chrome/common/chrome_paths.h"
49 #include "chrome/common/chrome_switches.h"
50 #include "chrome/common/net/url_fixer_upper.h"
51 #include "chrome/common/pref_names.h"
52 #include "chrome/common/url_constants.h"
53 #include "components/startup_metric_utils/startup_metric_utils.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/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"
85 #endif
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"
91 #endif
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/policy/policy_cert_service.h"
98 #include "chrome/browser/chromeos/policy/policy_cert_service_factory.h"
99 #include "chrome/browser/chromeos/policy/policy_cert_verifier.h"
100 #include "chrome/browser/chromeos/settings/cros_settings.h"
101 #include "chromeos/dbus/cryptohome_client.h"
102 #include "chromeos/dbus/dbus_thread_manager.h"
103 #include "chromeos/settings/cros_settings_names.h"
104 #include "crypto/nss_util.h"
105 #include "crypto/nss_util_internal.h"
106 #include "net/ssl/client_cert_store_chromeos.h"
107 #endif // defined(OS_CHROMEOS)
109 #if defined(USE_NSS)
110 #include "chrome/browser/ui/crypto_module_delegate_nss.h"
111 #include "net/ssl/client_cert_store_nss.h"
112 #endif
114 #if defined(OS_WIN)
115 #include "net/ssl/client_cert_store_win.h"
116 #endif
118 #if defined(OS_MACOSX)
119 #include "net/ssl/client_cert_store_mac.h"
120 #endif
122 using content::BrowserContext;
123 using content::BrowserThread;
124 using content::ResourceContext;
126 namespace {
128 #if defined(DEBUG_DEVTOOLS)
129 bool IsSupportedDevToolsURL(const GURL& url, base::FilePath* path) {
130 std::string bundled_path_prefix(chrome::kChromeUIDevToolsBundledPath);
131 bundled_path_prefix = "/" + bundled_path_prefix + "/";
133 if (!url.SchemeIs(chrome::kChromeDevToolsScheme) ||
134 url.host() != chrome::kChromeUIDevToolsHost ||
135 !StartsWithASCII(url.path(), bundled_path_prefix, false)) {
136 return false;
139 if (!url.is_valid()) {
140 NOTREACHED();
141 return false;
144 // Remove Query and Ref from URL.
145 GURL stripped_url;
146 GURL::Replacements replacements;
147 replacements.ClearQuery();
148 replacements.ClearRef();
149 stripped_url = url.ReplaceComponents(replacements);
151 std::string relative_path;
152 const std::string& spec = stripped_url.possibly_invalid_spec();
153 const url_parse::Parsed& parsed =
154 stripped_url.parsed_for_possibly_invalid_spec();
155 int offset = parsed.CountCharactersBefore(url_parse::Parsed::PATH, false);
156 if (offset < static_cast<int>(spec.size()))
157 relative_path.assign(spec.substr(offset + bundled_path_prefix.length()));
159 // Check that |relative_path| is not an absolute path (otherwise
160 // AppendASCII() will DCHECK). The awkward use of StringType is because on
161 // some systems FilePath expects a std::string, but on others a std::wstring.
162 base::FilePath p(
163 base::FilePath::StringType(relative_path.begin(), relative_path.end()));
164 if (p.IsAbsolute())
165 return false;
167 base::FilePath inspector_dir;
168 if (!PathService::Get(chrome::DIR_INSPECTOR, &inspector_dir))
169 return false;
171 if (inspector_dir.empty())
172 return false;
174 *path = inspector_dir.AppendASCII(relative_path);
175 return true;
178 class DebugDevToolsInterceptor
179 : public net::URLRequestJobFactory::ProtocolHandler {
180 public:
181 DebugDevToolsInterceptor() {}
182 virtual ~DebugDevToolsInterceptor() {}
184 virtual net::URLRequestJob* MaybeCreateJob(
185 net::URLRequest* request,
186 net::NetworkDelegate* network_delegate) const OVERRIDE {
187 base::FilePath path;
188 if (IsSupportedDevToolsURL(request->url(), &path))
189 return new net::URLRequestFileJob(
190 request, network_delegate, path,
191 content::BrowserThread::GetBlockingPool()->
192 GetTaskRunnerWithShutdownBehavior(
193 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN));
195 return NULL;
198 #endif // defined(DEBUG_DEVTOOLS)
200 #if defined(OS_CHROMEOS)
201 // The following four functions are responsible for initializing NSS for each
202 // profile on ChromeOS, which has a separate NSS database and TPM slot
203 // per-profile.
205 // Initialization basically follows these steps:
206 // 1) Get some info from chromeos::UserManager about the User for this profile.
207 // 2) Tell nss_util to initialize the software slot for this profile.
208 // 3) Wait for the TPM module to be loaded by nss_util if it isn't already.
209 // 4) Ask CryptohomeClient which TPM slot id corresponds to this profile.
210 // 5) Tell nss_util to use that slot id on the TPM module.
212 // Some of these steps must happen on the UI thread, others must happen on the
213 // IO thread:
214 // UI thread IO Thread
216 // ProfileIOData::InitializeOnUIThread
217 // |
218 // chromeos::UserManager::GetUserByProfile
219 // \---------------------------------------v
220 // StartNSSInitOnIOThread
221 // |
222 // crypto::InitializeNSSForChromeOSUser
223 // |
224 // crypto::IsTPMTokenReady
225 // |
226 // StartTPMSlotInitializationOnIOThread
227 // v---------------------------------------/
228 // GetTPMInfoForUserOnUIThread
229 // |
230 // CryptohomeClient::Pkcs11GetTpmTokenInfoForUser
231 // |
232 // DidGetTPMInfoForUserOnUIThread
233 // \---------------------------------------v
234 // crypto::InitializeTPMForChromeOSUser
236 void DidGetTPMInfoForUserOnUIThread(const std::string& username_hash,
237 chromeos::DBusMethodCallStatus call_status,
238 const std::string& label,
239 const std::string& user_pin,
240 int slot_id) {
241 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
242 if (call_status == chromeos::DBUS_METHOD_CALL_FAILURE) {
243 NOTREACHED() << "dbus error getting TPM info for " << username_hash;
244 return;
246 DVLOG(1) << "Got TPM slot for " << username_hash << ": " << slot_id;
247 BrowserThread::PostTask(
248 BrowserThread::IO,
249 FROM_HERE,
250 base::Bind(
251 &crypto::InitializeTPMForChromeOSUser, username_hash, slot_id));
254 void GetTPMInfoForUserOnUIThread(const std::string& username,
255 const std::string& username_hash) {
256 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
257 DVLOG(1) << "Getting TPM info from cryptohome for "
258 << " " << username << " " << username_hash;
259 chromeos::DBusThreadManager::Get()
260 ->GetCryptohomeClient()
261 ->Pkcs11GetTpmTokenInfoForUser(
262 username,
263 base::Bind(&DidGetTPMInfoForUserOnUIThread, username_hash));
266 void StartTPMSlotInitializationOnIOThread(const std::string& username,
267 const std::string& username_hash) {
268 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
270 BrowserThread::PostTask(
271 BrowserThread::UI,
272 FROM_HERE,
273 base::Bind(&GetTPMInfoForUserOnUIThread, username, username_hash));
276 void StartNSSInitOnIOThread(const std::string& username,
277 const std::string& username_hash,
278 const base::FilePath& path,
279 bool is_primary_user) {
280 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
281 DVLOG(1) << "Starting NSS init for " << username
282 << " hash:" << username_hash
283 << " is_primary_user:" << is_primary_user;
285 if (!crypto::InitializeNSSForChromeOSUser(
286 username, username_hash, is_primary_user, path)) {
287 // If the user already exists in nss_util's map, it is already initialized
288 // or in the process of being initialized. In either case, there's no need
289 // to do anything.
290 return;
293 if (crypto::IsTPMTokenEnabledForNSS()) {
294 if (crypto::IsTPMTokenReady(base::Bind(
295 &StartTPMSlotInitializationOnIOThread, username, username_hash))) {
296 StartTPMSlotInitializationOnIOThread(username, username_hash);
297 } else {
298 DVLOG(1) << "Waiting for tpm ready ...";
300 } else {
301 crypto::InitializePrivateSoftwareSlotForChromeOSUser(username_hash);
304 #endif // defined(OS_CHROMEOS)
306 } // namespace
308 void ProfileIOData::InitializeOnUIThread(Profile* profile) {
309 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
310 PrefService* pref_service = profile->GetPrefs();
311 PrefService* local_state_pref_service = g_browser_process->local_state();
313 scoped_ptr<ProfileParams> params(new ProfileParams);
314 params->path = profile->GetPath();
316 params->io_thread = g_browser_process->io_thread();
318 params->cookie_settings = CookieSettings::Factory::GetForProfile(profile);
319 params->host_content_settings_map = profile->GetHostContentSettingsMap();
320 params->ssl_config_service = profile->GetSSLConfigService();
321 params->cookie_monster_delegate =
322 chrome_browser_net::CreateCookieDelegate(profile);
323 params->extension_info_map =
324 extensions::ExtensionSystem::Get(profile)->info_map();
326 ProtocolHandlerRegistry* protocol_handler_registry =
327 ProtocolHandlerRegistryFactory::GetForProfile(profile);
328 DCHECK(protocol_handler_registry);
330 // The profile instance is only available here in the InitializeOnUIThread
331 // method, so we create the url job factory here, then save it for
332 // later delivery to the job factory in Init().
333 params->protocol_handler_interceptor =
334 protocol_handler_registry->CreateJobInterceptorFactory();
336 params->proxy_config_service
337 .reset(ProxyServiceFactory::CreateProxyConfigService(
338 profile->GetProxyConfigTracker()));
339 #if defined(ENABLE_MANAGED_USERS)
340 ManagedUserService* managed_user_service =
341 ManagedUserServiceFactory::GetForProfile(profile);
342 params->managed_mode_url_filter =
343 managed_user_service->GetURLFilterForIOThread();
344 #endif
345 #if defined(OS_CHROMEOS)
346 chromeos::UserManager* user_manager = chromeos::UserManager::Get();
347 if (user_manager) {
348 chromeos::User* user = user_manager->GetUserByProfile(profile);
349 if (user) {
350 params->username_hash = user->username_hash();
351 bool is_primary_user = (user_manager->GetPrimaryUser() == user);
352 BrowserThread::PostTask(BrowserThread::IO,
353 FROM_HERE,
354 base::Bind(&StartNSSInitOnIOThread,
355 user->email(),
356 user->username_hash(),
357 profile->GetPath(),
358 is_primary_user));
361 if (params->username_hash.empty())
362 LOG(WARNING) << "no username_hash";
363 #endif
365 params->profile = profile;
366 profile_params_.reset(params.release());
368 ChromeNetworkDelegate::InitializePrefsOnUIThread(
369 &enable_referrers_,
370 &enable_do_not_track_,
371 &force_safesearch_,
372 pref_service);
374 scoped_refptr<base::MessageLoopProxy> io_message_loop_proxy =
375 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
376 #if defined(ENABLE_PRINTING)
377 printing_enabled_.Init(prefs::kPrintingEnabled, pref_service);
378 printing_enabled_.MoveToThread(io_message_loop_proxy);
379 #endif
381 chrome_http_user_agent_settings_.reset(
382 new ChromeHttpUserAgentSettings(pref_service));
384 // These members are used only for one click sign in, which is not enabled
385 // in incognito mode. So no need to initialize them.
386 if (!is_incognito()) {
387 signin_names_.reset(new SigninNamesOnIOThread());
389 google_services_user_account_id_.Init(
390 prefs::kGoogleServicesUserAccountId, pref_service);
391 google_services_user_account_id_.MoveToThread(io_message_loop_proxy);
393 google_services_username_.Init(
394 prefs::kGoogleServicesUsername, pref_service);
395 google_services_username_.MoveToThread(io_message_loop_proxy);
397 google_services_username_pattern_.Init(
398 prefs::kGoogleServicesUsernamePattern, local_state_pref_service);
399 google_services_username_pattern_.MoveToThread(io_message_loop_proxy);
401 reverse_autologin_enabled_.Init(
402 prefs::kReverseAutologinEnabled, pref_service);
403 reverse_autologin_enabled_.MoveToThread(io_message_loop_proxy);
405 one_click_signin_rejected_email_list_.Init(
406 prefs::kReverseAutologinRejectedEmailList, pref_service);
407 one_click_signin_rejected_email_list_.MoveToThread(io_message_loop_proxy);
409 sync_disabled_.Init(prefs::kSyncManaged, pref_service);
410 sync_disabled_.MoveToThread(io_message_loop_proxy);
412 signin_allowed_.Init(prefs::kSigninAllowed, pref_service);
413 signin_allowed_.MoveToThread(io_message_loop_proxy);
416 quick_check_enabled_.Init(prefs::kQuickCheckEnabled,
417 local_state_pref_service);
418 quick_check_enabled_.MoveToThread(io_message_loop_proxy);
420 media_device_id_salt_.reset(new MediaDeviceIDSalt(pref_service,
421 is_incognito()));
423 #if defined(OS_CHROMEOS)
424 cert_verifier_ = policy::PolicyCertServiceFactory::CreateForProfile(profile);
425 #endif
426 // The URLBlacklistManager has to be created on the UI thread to register
427 // observers of |pref_service|, and it also has to clean up on
428 // ShutdownOnUIThread to release these observers on the right thread.
429 // Don't pass it in |profile_params_| to make sure it is correctly cleaned up,
430 // in particular when this ProfileIOData isn't |initialized_| during deletion.
431 #if defined(ENABLE_CONFIGURATION_POLICY)
432 policy::URLBlacklist::SegmentURLCallback callback =
433 static_cast<policy::URLBlacklist::SegmentURLCallback>(
434 URLFixerUpper::SegmentURL);
435 base::SequencedWorkerPool* pool = BrowserThread::GetBlockingPool();
436 scoped_refptr<base::SequencedTaskRunner> background_task_runner =
437 pool->GetSequencedTaskRunner(pool->GetSequenceToken());
438 url_blacklist_manager_.reset(
439 new policy::URLBlacklistManager(pref_service,
440 background_task_runner,
441 io_message_loop_proxy,
442 callback,
443 policy::SkipBlacklistForURL));
445 if (!is_incognito()) {
446 // Add policy headers for non-incognito requests.
447 policy::PolicyHeaderService* policy_header_service =
448 policy::PolicyHeaderServiceFactory::GetForBrowserContext(profile);
449 if (policy_header_service) {
450 policy_header_helper_ = policy_header_service->CreatePolicyHeaderIOHelper(
451 io_message_loop_proxy);
454 #endif
456 initialized_on_UI_thread_ = true;
458 // We need to make sure that content initializes its own data structures that
459 // are associated with each ResourceContext because we might post this
460 // object to the IO thread after this function.
461 BrowserContext::EnsureResourceContextInitialized(profile);
464 ProfileIOData::MediaRequestContext::MediaRequestContext() {
467 void ProfileIOData::MediaRequestContext::SetHttpTransactionFactory(
468 scoped_ptr<net::HttpTransactionFactory> http_factory) {
469 http_factory_ = http_factory.Pass();
470 set_http_transaction_factory(http_factory_.get());
473 ProfileIOData::MediaRequestContext::~MediaRequestContext() {}
475 ProfileIOData::AppRequestContext::AppRequestContext() {
478 void ProfileIOData::AppRequestContext::SetCookieStore(
479 net::CookieStore* cookie_store) {
480 cookie_store_ = cookie_store;
481 set_cookie_store(cookie_store);
484 void ProfileIOData::AppRequestContext::SetHttpTransactionFactory(
485 scoped_ptr<net::HttpTransactionFactory> http_factory) {
486 http_factory_ = http_factory.Pass();
487 set_http_transaction_factory(http_factory_.get());
490 void ProfileIOData::AppRequestContext::SetJobFactory(
491 scoped_ptr<net::URLRequestJobFactory> job_factory) {
492 job_factory_ = job_factory.Pass();
493 set_job_factory(job_factory_.get());
496 ProfileIOData::AppRequestContext::~AppRequestContext() {}
498 ProfileIOData::ProfileParams::ProfileParams()
499 : io_thread(NULL),
500 profile(NULL) {
503 ProfileIOData::ProfileParams::~ProfileParams() {}
505 ProfileIOData::ProfileIOData(bool is_incognito)
506 : initialized_(false),
507 resource_context_(new ResourceContext(this)),
508 initialized_on_UI_thread_(false),
509 is_incognito_(is_incognito) {
510 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
513 ProfileIOData::~ProfileIOData() {
514 if (BrowserThread::IsMessageLoopValid(BrowserThread::IO))
515 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
517 // Pull the contents of the request context maps onto the stack for sanity
518 // checking of values in a minidump. http://crbug.com/260425
519 size_t num_app_contexts = app_request_context_map_.size();
520 size_t num_media_contexts = isolated_media_request_context_map_.size();
521 size_t current_context = 0;
522 static const size_t kMaxCachedContexts = 20;
523 ChromeURLRequestContext* app_context_cache[kMaxCachedContexts] = {0};
524 void* app_context_vtable_cache[kMaxCachedContexts] = {0};
525 ChromeURLRequestContext* media_context_cache[kMaxCachedContexts] = {0};
526 void* media_context_vtable_cache[kMaxCachedContexts] = {0};
527 void* tmp_vtable = NULL;
528 base::debug::Alias(&num_app_contexts);
529 base::debug::Alias(&num_media_contexts);
530 base::debug::Alias(&current_context);
531 base::debug::Alias(app_context_cache);
532 base::debug::Alias(app_context_vtable_cache);
533 base::debug::Alias(media_context_cache);
534 base::debug::Alias(media_context_vtable_cache);
535 base::debug::Alias(&tmp_vtable);
537 current_context = 0;
538 for (URLRequestContextMap::const_iterator it =
539 app_request_context_map_.begin();
540 current_context < kMaxCachedContexts &&
541 it != app_request_context_map_.end();
542 ++it, ++current_context) {
543 app_context_cache[current_context] = it->second;
544 memcpy(&app_context_vtable_cache[current_context],
545 static_cast<void*>(it->second), sizeof(void*));
548 current_context = 0;
549 for (URLRequestContextMap::const_iterator it =
550 isolated_media_request_context_map_.begin();
551 current_context < kMaxCachedContexts &&
552 it != isolated_media_request_context_map_.end();
553 ++it, ++current_context) {
554 media_context_cache[current_context] = it->second;
555 memcpy(&media_context_vtable_cache[current_context],
556 static_cast<void*>(it->second), sizeof(void*));
559 // TODO(ajwong): These AssertNoURLRequests() calls are unnecessary since they
560 // are already done in the URLRequestContext destructor.
561 if (main_request_context_)
562 main_request_context_->AssertNoURLRequests();
563 if (extensions_request_context_)
564 extensions_request_context_->AssertNoURLRequests();
566 current_context = 0;
567 for (URLRequestContextMap::iterator it = app_request_context_map_.begin();
568 it != app_request_context_map_.end(); ++it) {
569 if (current_context < kMaxCachedContexts) {
570 CHECK_EQ(app_context_cache[current_context], it->second);
571 memcpy(&tmp_vtable, static_cast<void*>(it->second), sizeof(void*));
572 CHECK_EQ(app_context_vtable_cache[current_context], tmp_vtable);
574 it->second->AssertNoURLRequests();
575 delete it->second;
576 current_context++;
579 current_context = 0;
580 for (URLRequestContextMap::iterator it =
581 isolated_media_request_context_map_.begin();
582 it != isolated_media_request_context_map_.end(); ++it) {
583 if (current_context < kMaxCachedContexts) {
584 CHECK_EQ(media_context_cache[current_context], it->second);
585 memcpy(&tmp_vtable, static_cast<void*>(it->second), sizeof(void*));
586 CHECK_EQ(media_context_vtable_cache[current_context], tmp_vtable);
588 it->second->AssertNoURLRequests();
589 delete it->second;
590 current_context++;
594 // static
595 ProfileIOData* ProfileIOData::FromResourceContext(
596 content::ResourceContext* rc) {
597 return (static_cast<ResourceContext*>(rc))->io_data_;
600 // static
601 bool ProfileIOData::IsHandledProtocol(const std::string& scheme) {
602 DCHECK_EQ(scheme, StringToLowerASCII(scheme));
603 static const char* const kProtocolList[] = {
604 content::kFileScheme,
605 chrome::kChromeDevToolsScheme,
606 extensions::kExtensionScheme,
607 extensions::kExtensionResourceScheme,
608 chrome::kChromeUIScheme,
609 chrome::kDataScheme,
610 #if defined(OS_CHROMEOS)
611 chrome::kDriveScheme,
612 #endif // defined(OS_CHROMEOS)
613 chrome::kAboutScheme,
614 #if !defined(DISABLE_FTP_SUPPORT)
615 content::kFtpScheme,
616 #endif // !defined(DISABLE_FTP_SUPPORT)
617 chrome::kBlobScheme,
618 content::kFileSystemScheme,
619 chrome::kChromeSearchScheme,
621 for (size_t i = 0; i < arraysize(kProtocolList); ++i) {
622 if (scheme == kProtocolList[i])
623 return true;
625 return net::URLRequest::IsHandledProtocol(scheme);
628 // static
629 bool ProfileIOData::IsHandledURL(const GURL& url) {
630 if (!url.is_valid()) {
631 // We handle error cases.
632 return true;
635 return IsHandledProtocol(url.scheme());
638 // static
639 void ProfileIOData::InstallProtocolHandlers(
640 net::URLRequestJobFactoryImpl* job_factory,
641 content::ProtocolHandlerMap* protocol_handlers) {
642 for (content::ProtocolHandlerMap::iterator it =
643 protocol_handlers->begin();
644 it != protocol_handlers->end();
645 ++it) {
646 bool set_protocol = job_factory->SetProtocolHandler(
647 it->first, it->second.release());
648 DCHECK(set_protocol);
650 protocol_handlers->clear();
653 content::ResourceContext* ProfileIOData::GetResourceContext() const {
654 return resource_context_.get();
657 ChromeURLRequestContext* ProfileIOData::GetMainRequestContext() const {
658 DCHECK(initialized_);
659 return main_request_context_.get();
662 ChromeURLRequestContext* ProfileIOData::GetMediaRequestContext() const {
663 DCHECK(initialized_);
664 ChromeURLRequestContext* context = AcquireMediaRequestContext();
665 DCHECK(context);
666 return context;
669 ChromeURLRequestContext* ProfileIOData::GetExtensionsRequestContext() const {
670 DCHECK(initialized_);
671 return extensions_request_context_.get();
674 ChromeURLRequestContext* ProfileIOData::GetIsolatedAppRequestContext(
675 ChromeURLRequestContext* main_context,
676 const StoragePartitionDescriptor& partition_descriptor,
677 scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
678 protocol_handler_interceptor,
679 content::ProtocolHandlerMap* protocol_handlers) const {
680 DCHECK(initialized_);
681 ChromeURLRequestContext* context = NULL;
682 if (ContainsKey(app_request_context_map_, partition_descriptor)) {
683 context = app_request_context_map_[partition_descriptor];
684 } else {
685 context = AcquireIsolatedAppRequestContext(
686 main_context, partition_descriptor, protocol_handler_interceptor.Pass(),
687 protocol_handlers);
688 app_request_context_map_[partition_descriptor] = context;
690 DCHECK(context);
691 return context;
694 ChromeURLRequestContext* ProfileIOData::GetIsolatedMediaRequestContext(
695 ChromeURLRequestContext* app_context,
696 const StoragePartitionDescriptor& partition_descriptor) const {
697 DCHECK(initialized_);
698 ChromeURLRequestContext* context = NULL;
699 if (ContainsKey(isolated_media_request_context_map_, partition_descriptor)) {
700 context = isolated_media_request_context_map_[partition_descriptor];
701 } else {
702 context = AcquireIsolatedMediaRequestContext(app_context,
703 partition_descriptor);
704 isolated_media_request_context_map_[partition_descriptor] = context;
706 DCHECK(context);
707 return context;
710 extensions::InfoMap* ProfileIOData::GetExtensionInfoMap() const {
711 DCHECK(initialized_) << "ExtensionSystem not initialized";
712 return extension_info_map_.get();
715 CookieSettings* ProfileIOData::GetCookieSettings() const {
716 // Allow either Init() or SetCookieSettingsForTesting() to initialize.
717 DCHECK(initialized_ || cookie_settings_.get());
718 return cookie_settings_.get();
721 HostContentSettingsMap* ProfileIOData::GetHostContentSettingsMap() const {
722 DCHECK(initialized_);
723 return host_content_settings_map_.get();
726 std::string ProfileIOData::GetMediaDeviceIDSalt() const {
727 return media_device_id_salt_->GetSalt();
730 void ProfileIOData::InitializeMetricsEnabledStateOnUIThread() {
731 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
732 #if defined(OS_CHROMEOS)
733 // Just fetch the value from ChromeOS' settings while we're on the UI thread.
734 // TODO(stevet): For now, this value is only set on profile initialization.
735 // We will want to do something similar to the PrefMember method below in the
736 // future to more accurately capture this state.
737 chromeos::CrosSettings::Get()->GetBoolean(chromeos::kStatsReportingPref,
738 &enable_metrics_);
739 #elif defined(OS_ANDROID)
740 // TODO(dwkang): rename or unify the pref for UMA once we have conclusion
741 // in crbugs.com/246495.
742 // Android has it's own preferences for metrics / crash uploading.
743 enable_metrics_.Init(prefs::kCrashReportingEnabled,
744 g_browser_process->local_state());
745 enable_metrics_.MoveToThread(
746 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
747 #else
748 // Prep the PrefMember and send it to the IO thread, since this value will be
749 // read from there.
750 enable_metrics_.Init(prefs::kMetricsReportingEnabled,
751 g_browser_process->local_state());
752 enable_metrics_.MoveToThread(
753 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
754 #endif // defined(OS_CHROMEOS)
757 bool ProfileIOData::GetMetricsEnabledStateOnIOThread() const {
758 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
759 #if defined(OS_CHROMEOS)
760 return enable_metrics_;
761 #else
762 return enable_metrics_.GetValue();
763 #endif // defined(OS_CHROMEOS)
766 base::WeakPtr<net::HttpServerProperties>
767 ProfileIOData::http_server_properties() const {
768 return http_server_properties_->GetWeakPtr();
771 void ProfileIOData::set_http_server_properties(
772 scoped_ptr<net::HttpServerProperties> http_server_properties) const {
773 http_server_properties_ = http_server_properties.Pass();
776 ProfileIOData::ResourceContext::ResourceContext(ProfileIOData* io_data)
777 : io_data_(io_data),
778 host_resolver_(NULL),
779 request_context_(NULL) {
780 DCHECK(io_data);
783 ProfileIOData::ResourceContext::~ResourceContext() {}
785 net::HostResolver* ProfileIOData::ResourceContext::GetHostResolver() {
786 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
787 DCHECK(io_data_->initialized_);
788 return host_resolver_;
791 net::URLRequestContext* ProfileIOData::ResourceContext::GetRequestContext() {
792 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
793 DCHECK(io_data_->initialized_);
794 return request_context_;
797 scoped_ptr<net::ClientCertStore>
798 ProfileIOData::ResourceContext::CreateClientCertStore() {
799 if (!io_data_->client_cert_store_factory_.is_null())
800 return io_data_->client_cert_store_factory_.Run();
801 #if defined(OS_CHROMEOS)
802 return scoped_ptr<net::ClientCertStore>(new net::ClientCertStoreChromeOS(
803 io_data_->username_hash(),
804 base::Bind(&CreateCryptoModuleBlockingPasswordDelegate,
805 chrome::kCryptoModulePasswordClientAuth)));
806 #elif defined(USE_NSS)
807 return scoped_ptr<net::ClientCertStore>(new net::ClientCertStoreNSS(
808 base::Bind(&CreateCryptoModuleBlockingPasswordDelegate,
809 chrome::kCryptoModulePasswordClientAuth)));
810 #elif defined(OS_WIN)
811 return scoped_ptr<net::ClientCertStore>(new net::ClientCertStoreWin());
812 #elif defined(OS_MACOSX)
813 return scoped_ptr<net::ClientCertStore>(new net::ClientCertStoreMac());
814 #elif defined(USE_OPENSSL)
815 // OpenSSL does not use the ClientCertStore infrastructure. On Android client
816 // cert matching is done by the OS as part of the call to show the cert
817 // selection dialog.
818 return scoped_ptr<net::ClientCertStore>();
819 #else
820 #error Unknown platform.
821 #endif
824 void ProfileIOData::ResourceContext::CreateKeygenHandler(
825 uint32 key_size_in_bits,
826 const std::string& challenge_string,
827 const GURL& url,
828 const base::Callback<void(scoped_ptr<net::KeygenHandler>)>& callback) {
829 DCHECK(!callback.is_null());
830 #if defined(USE_NSS)
831 scoped_ptr<net::KeygenHandler> keygen_handler(
832 new net::KeygenHandler(key_size_in_bits, challenge_string, url));
834 scoped_ptr<ChromeNSSCryptoModuleDelegate> delegate(
835 new ChromeNSSCryptoModuleDelegate(chrome::kCryptoModulePasswordKeygen,
836 net::HostPortPair::FromURL(url)));
837 ChromeNSSCryptoModuleDelegate* delegate_ptr = delegate.get();
838 keygen_handler->set_crypto_module_delegate(
839 delegate.PassAs<crypto::NSSCryptoModuleDelegate>());
841 base::Closure bound_callback =
842 base::Bind(callback, base::Passed(&keygen_handler));
843 if (delegate_ptr->InitializeSlot(this, bound_callback)) {
844 // Initialization complete, run the callback synchronously.
845 bound_callback.Run();
846 return;
848 // Otherwise, the InitializeSlot will run the callback asynchronously.
849 #else
850 callback.Run(make_scoped_ptr(
851 new net::KeygenHandler(key_size_in_bits, challenge_string, url)));
852 #endif
855 bool ProfileIOData::ResourceContext::AllowMicAccess(const GURL& origin) {
856 return AllowContentAccess(origin, CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC);
859 bool ProfileIOData::ResourceContext::AllowCameraAccess(const GURL& origin) {
860 return AllowContentAccess(origin, CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA);
863 bool ProfileIOData::ResourceContext::AllowContentAccess(
864 const GURL& origin, ContentSettingsType type) {
865 HostContentSettingsMap* content_settings =
866 io_data_->GetHostContentSettingsMap();
867 ContentSetting setting = content_settings->GetContentSetting(
868 origin, origin, type, NO_RESOURCE_IDENTIFIER);
869 return setting == CONTENT_SETTING_ALLOW;
872 std::string ProfileIOData::ResourceContext::GetMediaDeviceIDSalt() {
873 return io_data_->GetMediaDeviceIDSalt();
876 // static
877 std::string ProfileIOData::GetSSLSessionCacheShard() {
878 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
879 // The SSL session cache is partitioned by setting a string. This returns a
880 // unique string to partition the SSL session cache. Each time we create a
881 // new profile, we'll get a fresh SSL session cache which is separate from
882 // the other profiles.
883 static unsigned ssl_session_cache_instance = 0;
884 return base::StringPrintf("profile/%u", ssl_session_cache_instance++);
887 void ProfileIOData::Init(content::ProtocolHandlerMap* protocol_handlers) const {
888 // The basic logic is implemented here. The specific initialization
889 // is done in InitializeInternal(), implemented by subtypes. Static helper
890 // functions have been provided to assist in common operations.
891 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
892 DCHECK(!initialized_);
894 startup_metric_utils::ScopedSlowStartupUMA
895 scoped_timer("Startup.SlowStartupProfileIODataInit");
897 // TODO(jhawkins): Remove once crbug.com/102004 is fixed.
898 CHECK(initialized_on_UI_thread_);
900 // TODO(jhawkins): Return to DCHECK once crbug.com/102004 is fixed.
901 CHECK(profile_params_.get());
903 IOThread* const io_thread = profile_params_->io_thread;
904 IOThread::Globals* const io_thread_globals = io_thread->globals();
905 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
907 // Create the common request contexts.
908 main_request_context_.reset(new ChromeURLRequestContext());
909 extensions_request_context_.reset(new ChromeURLRequestContext());
911 ChromeNetworkDelegate* network_delegate =
912 new ChromeNetworkDelegate(
913 io_thread_globals->extension_event_router_forwarder.get(),
914 &enable_referrers_);
915 if (command_line.HasSwitch(switches::kEnableClientHints))
916 network_delegate->SetEnableClientHints();
917 network_delegate->set_extension_info_map(
918 profile_params_->extension_info_map.get());
919 network_delegate->set_url_blacklist_manager(url_blacklist_manager_.get());
920 network_delegate->set_profile(profile_params_->profile);
921 network_delegate->set_profile_path(profile_params_->path);
922 network_delegate->set_cookie_settings(profile_params_->cookie_settings.get());
923 network_delegate->set_enable_do_not_track(&enable_do_not_track_);
924 network_delegate->set_force_google_safe_search(&force_safesearch_);
925 network_delegate_.reset(network_delegate);
927 fraudulent_certificate_reporter_.reset(
928 new chrome_browser_net::ChromeFraudulentCertificateReporter(
929 main_request_context_.get()));
931 // NOTE: Proxy service uses the default io thread network delegate, not the
932 // delegate just created.
933 proxy_service_.reset(
934 ProxyServiceFactory::CreateProxyService(
935 io_thread->net_log(),
936 io_thread_globals->proxy_script_fetcher_context.get(),
937 io_thread_globals->system_network_delegate.get(),
938 profile_params_->proxy_config_service.release(),
939 command_line,
940 quick_check_enabled_.GetValue()));
942 transport_security_state_.reset(new net::TransportSecurityState());
943 transport_security_persister_.reset(
944 new net::TransportSecurityPersister(
945 transport_security_state_.get(),
946 profile_params_->path,
947 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE),
948 is_incognito()));
950 // Take ownership over these parameters.
951 cookie_settings_ = profile_params_->cookie_settings;
952 host_content_settings_map_ = profile_params_->host_content_settings_map;
953 extension_info_map_ = profile_params_->extension_info_map;
955 resource_context_->host_resolver_ = io_thread_globals->host_resolver.get();
956 resource_context_->request_context_ = main_request_context_.get();
958 #if defined(ENABLE_MANAGED_USERS)
959 managed_mode_url_filter_ = profile_params_->managed_mode_url_filter;
960 #endif
962 #if defined(OS_CHROMEOS)
963 if (cert_verifier_) {
964 cert_verifier_->InitializeOnIOThread();
965 main_request_context_->set_cert_verifier(cert_verifier_.get());
966 } else {
967 main_request_context_->set_cert_verifier(
968 io_thread_globals->cert_verifier.get());
970 username_hash_ = profile_params_->username_hash;
971 #else
972 main_request_context_->set_cert_verifier(
973 io_thread_globals->cert_verifier.get());
974 #endif
976 InitializeInternal(profile_params_.get(), protocol_handlers);
978 profile_params_.reset();
979 initialized_ = true;
982 void ProfileIOData::ApplyProfileParamsToContext(
983 ChromeURLRequestContext* context) const {
984 context->set_http_user_agent_settings(
985 chrome_http_user_agent_settings_.get());
986 context->set_ssl_config_service(profile_params_->ssl_config_service.get());
989 scoped_ptr<net::URLRequestJobFactory> ProfileIOData::SetUpJobFactoryDefaults(
990 scoped_ptr<net::URLRequestJobFactoryImpl> job_factory,
991 scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
992 protocol_handler_interceptor,
993 net::NetworkDelegate* network_delegate,
994 net::FtpTransactionFactory* ftp_transaction_factory) const {
995 // NOTE(willchan): Keep these protocol handlers in sync with
996 // ProfileIOData::IsHandledProtocol().
997 bool set_protocol = job_factory->SetProtocolHandler(
998 content::kFileScheme,
999 new net::FileProtocolHandler(
1000 content::BrowserThread::GetBlockingPool()->
1001 GetTaskRunnerWithShutdownBehavior(
1002 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)));
1003 DCHECK(set_protocol);
1005 DCHECK(extension_info_map_.get());
1006 set_protocol = job_factory->SetProtocolHandler(
1007 extensions::kExtensionScheme,
1008 CreateExtensionProtocolHandler(is_incognito(),
1009 extension_info_map_.get()));
1010 DCHECK(set_protocol);
1011 set_protocol = job_factory->SetProtocolHandler(
1012 extensions::kExtensionResourceScheme,
1013 CreateExtensionResourceProtocolHandler());
1014 DCHECK(set_protocol);
1015 set_protocol = job_factory->SetProtocolHandler(
1016 chrome::kDataScheme, new net::DataProtocolHandler());
1017 DCHECK(set_protocol);
1018 #if defined(OS_CHROMEOS)
1019 if (!is_incognito() && profile_params_) {
1020 set_protocol = job_factory->SetProtocolHandler(
1021 chrome::kDriveScheme,
1022 new drive::DriveProtocolHandler(profile_params_->profile));
1023 DCHECK(set_protocol);
1025 #endif // defined(OS_CHROMEOS)
1027 job_factory->SetProtocolHandler(
1028 chrome::kAboutScheme,
1029 new chrome_browser_net::AboutProtocolHandler());
1030 #if !defined(DISABLE_FTP_SUPPORT)
1031 DCHECK(ftp_transaction_factory);
1032 job_factory->SetProtocolHandler(
1033 content::kFtpScheme,
1034 new net::FtpProtocolHandler(ftp_transaction_factory));
1035 #endif // !defined(DISABLE_FTP_SUPPORT)
1037 scoped_ptr<net::URLRequestJobFactory> top_job_factory =
1038 job_factory.PassAs<net::URLRequestJobFactory>();
1039 #if defined(DEBUG_DEVTOOLS)
1040 top_job_factory.reset(new net::ProtocolInterceptJobFactory(
1041 top_job_factory.Pass(),
1042 scoped_ptr<net::URLRequestJobFactory::ProtocolHandler>(
1043 new DebugDevToolsInterceptor)));
1044 #endif
1046 if (protocol_handler_interceptor) {
1047 protocol_handler_interceptor->Chain(top_job_factory.Pass());
1048 return protocol_handler_interceptor.PassAs<net::URLRequestJobFactory>();
1049 } else {
1050 return top_job_factory.Pass();
1054 void ProfileIOData::ShutdownOnUIThread() {
1055 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1057 if (signin_names_)
1058 signin_names_->ReleaseResourcesOnUIThread();
1060 google_services_user_account_id_.Destroy();
1061 google_services_username_.Destroy();
1062 google_services_username_pattern_.Destroy();
1063 reverse_autologin_enabled_.Destroy();
1064 one_click_signin_rejected_email_list_.Destroy();
1065 enable_referrers_.Destroy();
1066 enable_do_not_track_.Destroy();
1067 force_safesearch_.Destroy();
1068 #if !defined(OS_CHROMEOS)
1069 enable_metrics_.Destroy();
1070 #endif
1071 safe_browsing_enabled_.Destroy();
1072 printing_enabled_.Destroy();
1073 sync_disabled_.Destroy();
1074 signin_allowed_.Destroy();
1075 quick_check_enabled_.Destroy();
1076 if (media_device_id_salt_)
1077 media_device_id_salt_->ShutdownOnUIThread();
1078 session_startup_pref_.Destroy();
1079 #if defined(ENABLE_CONFIGURATION_POLICY)
1080 if (url_blacklist_manager_)
1081 url_blacklist_manager_->ShutdownOnUIThread();
1082 #endif
1083 if (chrome_http_user_agent_settings_)
1084 chrome_http_user_agent_settings_->CleanupOnUIThread();
1085 bool posted = BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, this);
1086 if (!posted)
1087 delete this;
1090 void ProfileIOData::set_server_bound_cert_service(
1091 net::ServerBoundCertService* server_bound_cert_service) const {
1092 server_bound_cert_service_.reset(server_bound_cert_service);
1095 void ProfileIOData::DestroyResourceContext() {
1096 resource_context_.reset();
1099 void ProfileIOData::PopulateNetworkSessionParams(
1100 const ProfileParams* profile_params,
1101 net::HttpNetworkSession::Params* params) const {
1103 ChromeURLRequestContext* context = main_request_context();
1105 IOThread* const io_thread = profile_params->io_thread;
1107 io_thread->InitializeNetworkSessionParams(params);
1109 params->host_resolver = context->host_resolver();
1110 params->cert_verifier = context->cert_verifier();
1111 params->server_bound_cert_service = context->server_bound_cert_service();
1112 params->transport_security_state = context->transport_security_state();
1113 params->cert_transparency_verifier = context->cert_transparency_verifier();
1114 params->proxy_service = context->proxy_service();
1115 params->ssl_session_cache_shard = GetSSLSessionCacheShard();
1116 params->ssl_config_service = context->ssl_config_service();
1117 params->http_auth_handler_factory = context->http_auth_handler_factory();
1118 params->network_delegate = network_delegate();
1119 params->http_server_properties = context->http_server_properties();
1120 params->net_log = context->net_log();
1123 void ProfileIOData::SetCookieSettingsForTesting(
1124 CookieSettings* cookie_settings) {
1125 DCHECK(!cookie_settings_.get());
1126 cookie_settings_ = cookie_settings;
1129 void ProfileIOData::set_signin_names_for_testing(
1130 SigninNamesOnIOThread* signin_names) {
1131 signin_names_.reset(signin_names);