BookmarkManager: Fix 'new folder text field size changes on clicking it' issue.
[chromium-blink-merge.git] / chrome / browser / profiles / profile_io_data.cc
blobc2a9f321ecc31d3d58ad94803432044c25d79a6a
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/thread_task_runner_handle.h"
24 #include "base/threading/sequenced_worker_pool.h"
25 #include "chrome/browser/browser_process.h"
26 #include "chrome/browser/chrome_notification_types.h"
27 #include "chrome/browser/content_settings/cookie_settings_factory.h"
28 #include "chrome/browser/content_settings/host_content_settings_map_factory.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/devtools/devtools_network_controller.h"
32 #include "chrome/browser/devtools/devtools_network_transaction_factory.h"
33 #include "chrome/browser/download/download_service.h"
34 #include "chrome/browser/download/download_service_factory.h"
35 #include "chrome/browser/io_thread.h"
36 #include "chrome/browser/media/media_device_id_salt.h"
37 #include "chrome/browser/net/chrome_http_user_agent_settings.h"
38 #include "chrome/browser/net/chrome_network_delegate.h"
39 #include "chrome/browser/net/chrome_url_request_context_getter.h"
40 #include "chrome/browser/net/cookie_store_util.h"
41 #include "chrome/browser/net/proxy_service_factory.h"
42 #include "chrome/browser/net/resource_prefetch_predictor_observer.h"
43 #include "chrome/browser/predictors/resource_prefetch_predictor.h"
44 #include "chrome/browser/predictors/resource_prefetch_predictor_factory.h"
45 #include "chrome/browser/profiles/profile.h"
46 #include "chrome/browser/profiles/profile_manager.h"
47 #include "chrome/browser/ui/search/new_tab_page_interceptor_service.h"
48 #include "chrome/browser/ui/search/new_tab_page_interceptor_service_factory.h"
49 #include "chrome/common/chrome_paths.h"
50 #include "chrome/common/chrome_switches.h"
51 #include "chrome/common/pref_names.h"
52 #include "chrome/common/url_constants.h"
53 #include "components/about_handler/about_protocol_handler.h"
54 #include "components/content_settings/core/browser/content_settings_provider.h"
55 #include "components/content_settings/core/browser/cookie_settings.h"
56 #include "components/content_settings/core/browser/host_content_settings_map.h"
57 #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_io_data.h"
58 #include "components/dom_distiller/core/url_constants.h"
59 #include "components/net_log/chrome_net_log.h"
60 #include "components/sync_driver/pref_names.h"
61 #include "components/url_formatter/url_fixer.h"
62 #include "content/public/browser/browser_thread.h"
63 #include "content/public/browser/host_zoom_map.h"
64 #include "content/public/browser/notification_service.h"
65 #include "content/public/browser/resource_context.h"
66 #include "net/base/keygen_handler.h"
67 #include "net/base/network_quality_estimator.h"
68 #include "net/cert/cert_verifier.h"
69 #include "net/cookies/canonical_cookie.h"
70 #include "net/http/http_transaction_factory.h"
71 #include "net/http/http_util.h"
72 #include "net/http/transport_security_persister.h"
73 #include "net/proxy/proxy_config_service_fixed.h"
74 #include "net/proxy/proxy_script_fetcher_impl.h"
75 #include "net/proxy/proxy_service.h"
76 #include "net/ssl/channel_id_service.h"
77 #include "net/ssl/client_cert_store.h"
78 #include "net/url_request/certificate_report_sender.h"
79 #include "net/url_request/data_protocol_handler.h"
80 #include "net/url_request/file_protocol_handler.h"
81 #include "net/url_request/ftp_protocol_handler.h"
82 #include "net/url_request/url_request.h"
83 #include "net/url_request/url_request_context.h"
84 #include "net/url_request/url_request_context_builder.h"
85 #include "net/url_request/url_request_file_job.h"
86 #include "net/url_request/url_request_intercepting_job_factory.h"
87 #include "net/url_request/url_request_interceptor.h"
88 #include "net/url_request/url_request_job_factory_impl.h"
90 #if defined(ENABLE_CONFIGURATION_POLICY)
91 #include "chrome/browser/policy/cloud/policy_header_service_factory.h"
92 #include "chrome/browser/policy/policy_helpers.h"
93 #include "components/policy/core/browser/url_blacklist_manager.h"
94 #include "components/policy/core/common/cloud/policy_header_io_helper.h"
95 #include "components/policy/core/common/cloud/policy_header_service.h"
96 #include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
97 #endif
99 #if defined(ENABLE_EXTENSIONS)
100 #include "chrome/browser/extensions/extension_cookie_monster_delegate.h"
101 #include "chrome/browser/extensions/extension_resource_protocols.h"
102 #include "extensions/browser/extension_protocols.h"
103 #include "extensions/browser/extension_system.h"
104 #include "extensions/browser/extension_throttle_manager.h"
105 #include "extensions/browser/info_map.h"
106 #include "extensions/common/constants.h"
107 #endif
109 #if defined(ENABLE_SUPERVISED_USERS)
110 #include "chrome/browser/supervised_user/supervised_user_service.h"
111 #include "chrome/browser/supervised_user/supervised_user_service_factory.h"
112 #include "chrome/browser/supervised_user/supervised_user_url_filter.h"
113 #endif
115 #if defined(OS_ANDROID)
116 #include "content/public/browser/android/content_protocol_handler.h"
117 #endif // defined(OS_ANDROID)
119 #if defined(OS_CHROMEOS)
120 #include "chrome/browser/chromeos/certificate_provider/certificate_provider.h"
121 #include "chrome/browser/chromeos/certificate_provider/certificate_provider_service.h"
122 #include "chrome/browser/chromeos/certificate_provider/certificate_provider_service_factory.h"
123 #include "chrome/browser/chromeos/fileapi/external_file_protocol_handler.h"
124 #include "chrome/browser/chromeos/login/startup_utils.h"
125 #include "chrome/browser/chromeos/net/cert_verify_proc_chromeos.h"
126 #include "chrome/browser/chromeos/net/client_cert_filter_chromeos.h"
127 #include "chrome/browser/chromeos/net/client_cert_store_chromeos.h"
128 #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
129 #include "chrome/browser/chromeos/policy/policy_cert_service.h"
130 #include "chrome/browser/chromeos/policy/policy_cert_service_factory.h"
131 #include "chrome/browser/chromeos/policy/policy_cert_verifier.h"
132 #include "chrome/browser/chromeos/profiles/profile_helper.h"
133 #include "chrome/browser/chromeos/settings/cros_settings.h"
134 #include "chrome/browser/net/nss_context.h"
135 #include "chromeos/dbus/dbus_thread_manager.h"
136 #include "chromeos/settings/cros_settings_names.h"
137 #include "chromeos/tpm/tpm_token_info_getter.h"
138 #include "components/user_manager/user.h"
139 #include "components/user_manager/user_manager.h"
140 #include "crypto/nss_util.h"
141 #include "crypto/nss_util_internal.h"
142 #include "net/cert/cert_verifier.h"
143 #include "net/cert/multi_threaded_cert_verifier.h"
144 #endif // defined(OS_CHROMEOS)
146 #if defined(USE_NSS_CERTS)
147 #include "chrome/browser/ui/crypto_module_delegate_nss.h"
148 #include "net/ssl/client_cert_store_nss.h"
149 #endif
151 #if defined(OS_WIN)
152 #include "net/ssl/client_cert_store_win.h"
153 #endif
155 #if defined(OS_MACOSX)
156 #include "net/ssl/client_cert_store_mac.h"
157 #endif
159 using content::BrowserContext;
160 using content::BrowserThread;
161 using content::ResourceContext;
163 namespace {
165 net::CertVerifier* g_cert_verifier_for_testing = nullptr;
167 #if defined(DEBUG_DEVTOOLS)
168 bool IsSupportedDevToolsURL(const GURL& url, base::FilePath* path) {
169 std::string bundled_path_prefix(chrome::kChromeUIDevToolsBundledPath);
170 bundled_path_prefix = "/" + bundled_path_prefix + "/";
172 if (!url.SchemeIs(content::kChromeDevToolsScheme) ||
173 url.host() != chrome::kChromeUIDevToolsHost ||
174 !base::StartsWith(url.path(), bundled_path_prefix,
175 base::CompareCase::INSENSITIVE_ASCII)) {
176 return false;
179 if (!url.is_valid()) {
180 NOTREACHED();
181 return false;
184 // Remove Query and Ref from URL.
185 GURL stripped_url;
186 GURL::Replacements replacements;
187 replacements.ClearQuery();
188 replacements.ClearRef();
189 stripped_url = url.ReplaceComponents(replacements);
191 std::string relative_path;
192 const std::string& spec = stripped_url.possibly_invalid_spec();
193 const url::Parsed& parsed = stripped_url.parsed_for_possibly_invalid_spec();
194 int offset = parsed.CountCharactersBefore(url::Parsed::PATH, false);
195 if (offset < static_cast<int>(spec.size()))
196 relative_path.assign(spec.substr(offset + bundled_path_prefix.length()));
198 // Check that |relative_path| is not an absolute path (otherwise
199 // AppendASCII() will DCHECK). The awkward use of StringType is because on
200 // some systems FilePath expects a std::string, but on others a std::wstring.
201 base::FilePath p(
202 base::FilePath::StringType(relative_path.begin(), relative_path.end()));
203 if (p.IsAbsolute())
204 return false;
206 base::FilePath inspector_dir;
207 if (!PathService::Get(chrome::DIR_INSPECTOR, &inspector_dir))
208 return false;
210 if (inspector_dir.empty())
211 return false;
213 *path = inspector_dir.AppendASCII(relative_path);
214 return true;
217 class DebugDevToolsInterceptor : public net::URLRequestInterceptor {
218 public:
219 // net::URLRequestInterceptor implementation.
220 net::URLRequestJob* MaybeInterceptRequest(
221 net::URLRequest* request,
222 net::NetworkDelegate* network_delegate) const override {
223 base::FilePath path;
224 if (IsSupportedDevToolsURL(request->url(), &path))
225 return new net::URLRequestFileJob(
226 request, network_delegate, path,
227 content::BrowserThread::GetBlockingPool()->
228 GetTaskRunnerWithShutdownBehavior(
229 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN));
231 return NULL;
234 #endif // defined(DEBUG_DEVTOOLS)
236 #if defined(OS_CHROMEOS)
237 // The following four functions are responsible for initializing NSS for each
238 // profile on ChromeOS, which has a separate NSS database and TPM slot
239 // per-profile.
241 // Initialization basically follows these steps:
242 // 1) Get some info from user_manager::UserManager about the User for this
243 // profile.
244 // 2) Tell nss_util to initialize the software slot for this profile.
245 // 3) Wait for the TPM module to be loaded by nss_util if it isn't already.
246 // 4) Ask CryptohomeClient which TPM slot id corresponds to this profile.
247 // 5) Tell nss_util to use that slot id on the TPM module.
249 // Some of these steps must happen on the UI thread, others must happen on the
250 // IO thread:
251 // UI thread IO Thread
253 // ProfileIOData::InitializeOnUIThread
254 // |
255 // ProfileHelper::Get()->GetUserByProfile()
256 // \---------------------------------------v
257 // StartNSSInitOnIOThread
258 // |
259 // crypto::InitializeNSSForChromeOSUser
260 // |
261 // crypto::IsTPMTokenReady
262 // |
263 // StartTPMSlotInitializationOnIOThread
264 // v---------------------------------------/
265 // GetTPMInfoForUserOnUIThread
266 // |
267 // chromeos::TPMTokenInfoGetter::Start
268 // |
269 // DidGetTPMInfoForUserOnUIThread
270 // \---------------------------------------v
271 // crypto::InitializeTPMForChromeOSUser
273 void DidGetTPMInfoForUserOnUIThread(
274 scoped_ptr<chromeos::TPMTokenInfoGetter> getter,
275 const std::string& username_hash,
276 const chromeos::TPMTokenInfo& info) {
277 DCHECK_CURRENTLY_ON(BrowserThread::UI);
278 if (info.tpm_is_enabled && info.token_slot_id != -1) {
279 DVLOG(1) << "Got TPM slot for " << username_hash << ": "
280 << info.token_slot_id;
281 BrowserThread::PostTask(
282 BrowserThread::IO,
283 FROM_HERE,
284 base::Bind(&crypto::InitializeTPMForChromeOSUser,
285 username_hash, info.token_slot_id));
286 } else {
287 NOTREACHED() << "TPMTokenInfoGetter reported invalid token.";
291 void GetTPMInfoForUserOnUIThread(const std::string& username,
292 const std::string& username_hash) {
293 DCHECK_CURRENTLY_ON(BrowserThread::UI);
294 DVLOG(1) << "Getting TPM info from cryptohome for "
295 << " " << username << " " << username_hash;
296 scoped_ptr<chromeos::TPMTokenInfoGetter> scoped_token_info_getter =
297 chromeos::TPMTokenInfoGetter::CreateForUserToken(
298 username,
299 chromeos::DBusThreadManager::Get()->GetCryptohomeClient(),
300 base::ThreadTaskRunnerHandle::Get());
301 chromeos::TPMTokenInfoGetter* token_info_getter =
302 scoped_token_info_getter.get();
304 // Bind |token_info_getter| to the callback to ensure it does not go away
305 // before TPM token info is fetched.
306 // TODO(tbarzic, pneubeck): Handle this in a nicer way when this logic is
307 // moved to a separate profile service.
308 token_info_getter->Start(
309 base::Bind(&DidGetTPMInfoForUserOnUIThread,
310 base::Passed(&scoped_token_info_getter),
311 username_hash));
314 void StartTPMSlotInitializationOnIOThread(const std::string& username,
315 const std::string& username_hash) {
316 DCHECK_CURRENTLY_ON(BrowserThread::IO);
318 BrowserThread::PostTask(
319 BrowserThread::UI,
320 FROM_HERE,
321 base::Bind(&GetTPMInfoForUserOnUIThread, username, username_hash));
324 void StartNSSInitOnIOThread(const std::string& username,
325 const std::string& username_hash,
326 const base::FilePath& path) {
327 DCHECK_CURRENTLY_ON(BrowserThread::IO);
328 DVLOG(1) << "Starting NSS init for " << username
329 << " hash:" << username_hash;
331 // Make sure NSS is initialized for the user.
332 crypto::InitializeNSSForChromeOSUser(username_hash, path);
334 // Check if it's OK to initialize TPM for the user before continuing. This
335 // may not be the case if the TPM slot initialization was previously
336 // requested for the same user.
337 if (!crypto::ShouldInitializeTPMForChromeOSUser(username_hash))
338 return;
340 crypto::WillInitializeTPMForChromeOSUser(username_hash);
342 if (crypto::IsTPMTokenEnabledForNSS()) {
343 if (crypto::IsTPMTokenReady(base::Bind(
344 &StartTPMSlotInitializationOnIOThread, username, username_hash))) {
345 StartTPMSlotInitializationOnIOThread(username, username_hash);
346 } else {
347 DVLOG(1) << "Waiting for tpm ready ...";
349 } else {
350 crypto::InitializePrivateSoftwareSlotForChromeOSUser(username_hash);
353 #endif // defined(OS_CHROMEOS)
355 #if defined(USE_NSS_CERTS)
356 void InitializeAndPassKeygenHandler(
357 scoped_ptr<net::KeygenHandler> keygen_handler,
358 const base::Callback<void(scoped_ptr<net::KeygenHandler>)>& callback,
359 scoped_ptr<ChromeNSSCryptoModuleDelegate> delegate) {
360 if (delegate)
361 keygen_handler->set_crypto_module_delegate(delegate.Pass());
362 callback.Run(keygen_handler.Pass());
364 #endif // defined(USE_NSS_CERTS)
366 // For safe shutdown, must be called before the ProfileIOData is destroyed.
367 void NotifyContextGettersOfShutdownOnIO(
368 scoped_ptr<ProfileIOData::ChromeURLRequestContextGetterVector> getters) {
369 DCHECK_CURRENTLY_ON(BrowserThread::IO);
370 ProfileIOData::ChromeURLRequestContextGetterVector::iterator iter;
371 for (auto& chrome_context_getter : *getters)
372 chrome_context_getter->NotifyContextShuttingDown();
375 } // namespace
377 void ProfileIOData::InitializeOnUIThread(Profile* profile) {
378 DCHECK_CURRENTLY_ON(BrowserThread::UI);
379 PrefService* pref_service = profile->GetPrefs();
380 PrefService* local_state_pref_service = g_browser_process->local_state();
382 scoped_ptr<ProfileParams> params(new ProfileParams);
383 params->path = profile->GetPath();
385 params->io_thread = g_browser_process->io_thread();
387 params->cookie_settings = CookieSettingsFactory::GetForProfile(profile);
388 params->host_content_settings_map =
389 HostContentSettingsMapFactory::GetForProfile(profile);
390 params->ssl_config_service = profile->GetSSLConfigService();
392 #if defined(ENABLE_EXTENSIONS)
393 params->extension_info_map =
394 extensions::ExtensionSystem::Get(profile)->info_map();
395 params->cookie_monster_delegate = new ExtensionCookieMonsterDelegate(profile);
396 #endif
398 if (predictors::ResourcePrefetchPredictor* predictor =
399 predictors::ResourcePrefetchPredictorFactory::GetForProfile(
400 profile)) {
401 resource_prefetch_predictor_observer_.reset(
402 new chrome_browser_net::ResourcePrefetchPredictorObserver(predictor));
405 ProtocolHandlerRegistry* protocol_handler_registry =
406 ProtocolHandlerRegistryFactory::GetForBrowserContext(profile);
407 DCHECK(protocol_handler_registry);
409 // The profile instance is only available here in the InitializeOnUIThread
410 // method, so we create the url job factory here, then save it for
411 // later delivery to the job factory in Init().
412 params->protocol_handler_interceptor =
413 protocol_handler_registry->CreateJobInterceptorFactory();
415 NewTabPageInterceptorService* new_tab_interceptor_service =
416 NewTabPageInterceptorServiceFactory::GetForProfile(profile);
417 if (new_tab_interceptor_service) {
418 params->new_tab_page_interceptor =
419 new_tab_interceptor_service->CreateInterceptor();
422 params->proxy_config_service
423 .reset(ProxyServiceFactory::CreateProxyConfigService(
424 profile->GetProxyConfigTracker()));
425 #if defined(ENABLE_SUPERVISED_USERS)
426 SupervisedUserService* supervised_user_service =
427 SupervisedUserServiceFactory::GetForProfile(profile);
428 params->supervised_user_url_filter =
429 supervised_user_service->GetURLFilterForIOThread();
430 #endif
431 #if defined(OS_CHROMEOS)
432 user_manager::UserManager* user_manager = user_manager::UserManager::Get();
433 if (user_manager) {
434 const user_manager::User* user =
435 chromeos::ProfileHelper::Get()->GetUserByProfile(profile);
436 // No need to initialize NSS for users with empty username hash:
437 // Getters for a user's NSS slots always return NULL slot if the user's
438 // username hash is empty, even when the NSS is not initialized for the
439 // user.
440 if (user && !user->username_hash().empty()) {
441 params->username_hash = user->username_hash();
442 DCHECK(!params->username_hash.empty());
443 BrowserThread::PostTask(BrowserThread::IO,
444 FROM_HERE,
445 base::Bind(&StartNSSInitOnIOThread,
446 user->email(),
447 user->username_hash(),
448 profile->GetPath()));
450 // Use the device-wide system key slot only if the user is of the same
451 // domain as the device is registered to.
452 policy::BrowserPolicyConnectorChromeOS* connector =
453 g_browser_process->platform_part()
454 ->browser_policy_connector_chromeos();
455 params->use_system_key_slot =
456 connector->GetUserAffiliation(user->email()) ==
457 policy::USER_AFFILIATION_MANAGED;
461 chromeos::CertificateProviderService* cert_provider_service =
462 chromeos::CertificateProviderServiceFactory::GetForBrowserContext(
463 profile);
464 if (cert_provider_service) {
465 params->certificate_provider =
466 cert_provider_service->CreateCertificateProvider();
468 #endif
470 params->profile = profile;
471 profile_params_.reset(params.release());
473 ChromeNetworkDelegate::InitializePrefsOnUIThread(
474 &enable_referrers_,
475 &enable_do_not_track_,
476 &force_google_safesearch_,
477 &force_youtube_safety_mode_,
478 pref_service);
480 scoped_refptr<base::SingleThreadTaskRunner> io_task_runner =
481 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
483 chrome_http_user_agent_settings_.reset(
484 new ChromeHttpUserAgentSettings(pref_service));
486 // These members are used only for sign in, which is not enabled
487 // in incognito mode. So no need to initialize them.
488 if (!IsOffTheRecord()) {
489 google_services_user_account_id_.Init(
490 prefs::kGoogleServicesUserAccountId, pref_service);
491 google_services_user_account_id_.MoveToThread(io_task_runner);
493 sync_disabled_.Init(sync_driver::prefs::kSyncManaged, pref_service);
494 sync_disabled_.MoveToThread(io_task_runner);
496 signin_allowed_.Init(prefs::kSigninAllowed, pref_service);
497 signin_allowed_.MoveToThread(io_task_runner);
500 quick_check_enabled_.Init(prefs::kQuickCheckEnabled,
501 local_state_pref_service);
502 quick_check_enabled_.MoveToThread(io_task_runner);
504 media_device_id_salt_ = new MediaDeviceIDSalt(pref_service, IsOffTheRecord());
506 network_prediction_options_.Init(prefs::kNetworkPredictionOptions,
507 pref_service);
509 network_prediction_options_.MoveToThread(io_task_runner);
511 #if defined(OS_CHROMEOS)
512 scoped_ptr<policy::PolicyCertVerifier> verifier =
513 policy::PolicyCertServiceFactory::CreateForProfile(profile);
514 policy_cert_verifier_ = verifier.get();
515 cert_verifier_ = verifier.Pass();
516 #endif
517 // The URLBlacklistManager has to be created on the UI thread to register
518 // observers of |pref_service|, and it also has to clean up on
519 // ShutdownOnUIThread to release these observers on the right thread.
520 // Don't pass it in |profile_params_| to make sure it is correctly cleaned up,
521 // in particular when this ProfileIOData isn't |initialized_| during deletion.
522 #if defined(ENABLE_CONFIGURATION_POLICY)
523 policy::URLBlacklist::SegmentURLCallback callback =
524 static_cast<policy::URLBlacklist::SegmentURLCallback>(
525 url_formatter::SegmentURL);
526 base::SequencedWorkerPool* pool = BrowserThread::GetBlockingPool();
527 scoped_refptr<base::SequencedTaskRunner> background_task_runner =
528 pool->GetSequencedTaskRunner(pool->GetSequenceToken());
529 url_blacklist_manager_.reset(new policy::URLBlacklistManager(
530 pref_service, background_task_runner, io_task_runner, callback,
531 base::Bind(policy::OverrideBlacklistForURL)));
533 if (!IsOffTheRecord()) {
534 // Add policy headers for non-incognito requests.
535 policy::PolicyHeaderService* policy_header_service =
536 policy::PolicyHeaderServiceFactory::GetForBrowserContext(profile);
537 if (policy_header_service) {
538 policy_header_helper_ =
539 policy_header_service->CreatePolicyHeaderIOHelper(io_task_runner);
542 #endif
544 incognito_availibility_pref_.Init(
545 prefs::kIncognitoModeAvailability, pref_service);
546 incognito_availibility_pref_.MoveToThread(io_task_runner);
548 initialized_on_UI_thread_ = true;
550 // We need to make sure that content initializes its own data structures that
551 // are associated with each ResourceContext because we might post this
552 // object to the IO thread after this function.
553 BrowserContext::EnsureResourceContextInitialized(profile);
556 ProfileIOData::MediaRequestContext::MediaRequestContext() {
559 void ProfileIOData::MediaRequestContext::SetHttpTransactionFactory(
560 scoped_ptr<net::HttpTransactionFactory> http_factory) {
561 http_factory_ = http_factory.Pass();
562 set_http_transaction_factory(http_factory_.get());
565 ProfileIOData::MediaRequestContext::~MediaRequestContext() {
566 AssertNoURLRequests();
569 ProfileIOData::AppRequestContext::AppRequestContext() {
572 void ProfileIOData::AppRequestContext::SetCookieStore(
573 net::CookieStore* cookie_store) {
574 cookie_store_ = cookie_store;
575 set_cookie_store(cookie_store);
578 void ProfileIOData::AppRequestContext::SetHttpTransactionFactory(
579 scoped_ptr<net::HttpTransactionFactory> http_factory) {
580 http_factory_ = http_factory.Pass();
581 set_http_transaction_factory(http_factory_.get());
584 void ProfileIOData::AppRequestContext::SetJobFactory(
585 scoped_ptr<net::URLRequestJobFactory> job_factory) {
586 job_factory_ = job_factory.Pass();
587 set_job_factory(job_factory_.get());
590 ProfileIOData::AppRequestContext::~AppRequestContext() {
591 AssertNoURLRequests();
594 ProfileIOData::ProfileParams::ProfileParams()
595 : io_thread(NULL),
596 #if defined(OS_CHROMEOS)
597 use_system_key_slot(false),
598 #endif
599 profile(NULL) {
602 ProfileIOData::ProfileParams::~ProfileParams() {}
604 ProfileIOData::ProfileIOData(Profile::ProfileType profile_type)
605 : initialized_(false),
606 #if defined(OS_CHROMEOS)
607 policy_cert_verifier_(NULL),
608 use_system_key_slot_(false),
609 #endif
610 resource_context_(new ResourceContext(this)),
611 initialized_on_UI_thread_(false),
612 profile_type_(profile_type) {
613 DCHECK_CURRENTLY_ON(BrowserThread::UI);
616 ProfileIOData::~ProfileIOData() {
617 if (BrowserThread::IsMessageLoopValid(BrowserThread::IO))
618 DCHECK_CURRENTLY_ON(BrowserThread::IO);
620 // Pull the contents of the request context maps onto the stack for sanity
621 // checking of values in a minidump. http://crbug.com/260425
622 size_t num_app_contexts = app_request_context_map_.size();
623 size_t num_media_contexts = isolated_media_request_context_map_.size();
624 size_t current_context = 0;
625 static const size_t kMaxCachedContexts = 20;
626 net::URLRequestContext* app_context_cache[kMaxCachedContexts] = {0};
627 void* app_context_vtable_cache[kMaxCachedContexts] = {0};
628 net::URLRequestContext* media_context_cache[kMaxCachedContexts] = {0};
629 void* media_context_vtable_cache[kMaxCachedContexts] = {0};
630 void* tmp_vtable = NULL;
631 base::debug::Alias(&num_app_contexts);
632 base::debug::Alias(&num_media_contexts);
633 base::debug::Alias(&current_context);
634 base::debug::Alias(app_context_cache);
635 base::debug::Alias(app_context_vtable_cache);
636 base::debug::Alias(media_context_cache);
637 base::debug::Alias(media_context_vtable_cache);
638 base::debug::Alias(&tmp_vtable);
640 current_context = 0;
641 for (URLRequestContextMap::const_iterator it =
642 app_request_context_map_.begin();
643 current_context < kMaxCachedContexts &&
644 it != app_request_context_map_.end();
645 ++it, ++current_context) {
646 app_context_cache[current_context] = it->second;
647 memcpy(&app_context_vtable_cache[current_context],
648 static_cast<void*>(it->second), sizeof(void*));
651 current_context = 0;
652 for (URLRequestContextMap::const_iterator it =
653 isolated_media_request_context_map_.begin();
654 current_context < kMaxCachedContexts &&
655 it != isolated_media_request_context_map_.end();
656 ++it, ++current_context) {
657 media_context_cache[current_context] = it->second;
658 memcpy(&media_context_vtable_cache[current_context],
659 static_cast<void*>(it->second), sizeof(void*));
662 // Destroy certificate_report_sender_ before main_request_context_,
663 // since the former has a reference to the latter.
664 if (transport_security_state_)
665 transport_security_state_->SetReportSender(nullptr);
666 certificate_report_sender_.reset();
668 // TODO(ajwong): These AssertNoURLRequests() calls are unnecessary since they
669 // are already done in the URLRequestContext destructor.
670 if (main_request_context_)
671 main_request_context_->AssertNoURLRequests();
672 if (extensions_request_context_)
673 extensions_request_context_->AssertNoURLRequests();
675 current_context = 0;
676 for (URLRequestContextMap::iterator it = app_request_context_map_.begin();
677 it != app_request_context_map_.end(); ++it) {
678 if (current_context < kMaxCachedContexts) {
679 CHECK_EQ(app_context_cache[current_context], it->second);
680 memcpy(&tmp_vtable, static_cast<void*>(it->second), sizeof(void*));
681 CHECK_EQ(app_context_vtable_cache[current_context], tmp_vtable);
683 it->second->AssertNoURLRequests();
684 delete it->second;
685 current_context++;
688 current_context = 0;
689 for (URLRequestContextMap::iterator it =
690 isolated_media_request_context_map_.begin();
691 it != isolated_media_request_context_map_.end(); ++it) {
692 if (current_context < kMaxCachedContexts) {
693 CHECK_EQ(media_context_cache[current_context], it->second);
694 memcpy(&tmp_vtable, static_cast<void*>(it->second), sizeof(void*));
695 CHECK_EQ(media_context_vtable_cache[current_context], tmp_vtable);
697 it->second->AssertNoURLRequests();
698 delete it->second;
699 current_context++;
703 // static
704 ProfileIOData* ProfileIOData::FromResourceContext(
705 content::ResourceContext* rc) {
706 return (static_cast<ResourceContext*>(rc))->io_data_;
709 // static
710 bool ProfileIOData::IsHandledProtocol(const std::string& scheme) {
711 DCHECK_EQ(scheme, base::ToLowerASCII(scheme));
712 static const char* const kProtocolList[] = {
713 url::kFileScheme,
714 content::kChromeDevToolsScheme,
715 dom_distiller::kDomDistillerScheme,
716 #if defined(ENABLE_EXTENSIONS)
717 extensions::kExtensionScheme,
718 extensions::kExtensionResourceScheme,
719 #endif
720 content::kChromeUIScheme,
721 url::kDataScheme,
722 #if defined(OS_CHROMEOS)
723 content::kExternalFileScheme,
724 #endif // defined(OS_CHROMEOS)
725 url::kAboutScheme,
726 #if !defined(DISABLE_FTP_SUPPORT)
727 url::kFtpScheme,
728 #endif // !defined(DISABLE_FTP_SUPPORT)
729 url::kBlobScheme,
730 url::kFileSystemScheme,
731 chrome::kChromeSearchScheme,
733 for (size_t i = 0; i < arraysize(kProtocolList); ++i) {
734 if (scheme == kProtocolList[i])
735 return true;
737 return net::URLRequest::IsHandledProtocol(scheme);
740 // static
741 bool ProfileIOData::IsHandledURL(const GURL& url) {
742 if (!url.is_valid()) {
743 // We handle error cases.
744 return true;
747 return IsHandledProtocol(url.scheme());
750 // static
751 void ProfileIOData::InstallProtocolHandlers(
752 net::URLRequestJobFactoryImpl* job_factory,
753 content::ProtocolHandlerMap* protocol_handlers) {
754 for (content::ProtocolHandlerMap::iterator it =
755 protocol_handlers->begin();
756 it != protocol_handlers->end();
757 ++it) {
758 bool set_protocol = job_factory->SetProtocolHandler(
759 it->first, make_scoped_ptr(it->second.release()));
760 DCHECK(set_protocol);
762 protocol_handlers->clear();
765 // static
766 void ProfileIOData::SetCertVerifierForTesting(
767 net::CertVerifier* cert_verifier) {
768 g_cert_verifier_for_testing = cert_verifier;
771 content::ResourceContext* ProfileIOData::GetResourceContext() const {
772 return resource_context_.get();
775 net::URLRequestContext* ProfileIOData::GetMainRequestContext() const {
776 DCHECK(initialized_);
777 return main_request_context_.get();
780 net::URLRequestContext* ProfileIOData::GetMediaRequestContext() const {
781 DCHECK(initialized_);
782 net::URLRequestContext* context = AcquireMediaRequestContext();
783 DCHECK(context);
784 return context;
787 net::URLRequestContext* ProfileIOData::GetExtensionsRequestContext() const {
788 DCHECK(initialized_);
789 return extensions_request_context_.get();
792 net::URLRequestContext* ProfileIOData::GetIsolatedAppRequestContext(
793 net::URLRequestContext* main_context,
794 const StoragePartitionDescriptor& partition_descriptor,
795 scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
796 protocol_handler_interceptor,
797 content::ProtocolHandlerMap* protocol_handlers,
798 content::URLRequestInterceptorScopedVector request_interceptors) const {
799 DCHECK(initialized_);
800 net::URLRequestContext* context = NULL;
801 if (ContainsKey(app_request_context_map_, partition_descriptor)) {
802 context = app_request_context_map_[partition_descriptor];
803 } else {
804 context =
805 AcquireIsolatedAppRequestContext(main_context,
806 partition_descriptor,
807 protocol_handler_interceptor.Pass(),
808 protocol_handlers,
809 request_interceptors.Pass());
810 app_request_context_map_[partition_descriptor] = context;
812 DCHECK(context);
813 return context;
816 net::URLRequestContext* ProfileIOData::GetIsolatedMediaRequestContext(
817 net::URLRequestContext* app_context,
818 const StoragePartitionDescriptor& partition_descriptor) const {
819 DCHECK(initialized_);
820 net::URLRequestContext* context = NULL;
821 if (ContainsKey(isolated_media_request_context_map_, partition_descriptor)) {
822 context = isolated_media_request_context_map_[partition_descriptor];
823 } else {
824 context = AcquireIsolatedMediaRequestContext(app_context,
825 partition_descriptor);
826 isolated_media_request_context_map_[partition_descriptor] = context;
828 DCHECK(context);
829 return context;
832 extensions::InfoMap* ProfileIOData::GetExtensionInfoMap() const {
833 DCHECK(initialized_) << "ExtensionSystem not initialized";
834 #if defined(ENABLE_EXTENSIONS)
835 return extension_info_map_.get();
836 #else
837 return nullptr;
838 #endif
841 extensions::ExtensionThrottleManager*
842 ProfileIOData::GetExtensionThrottleManager() const {
843 DCHECK(initialized_) << "ExtensionSystem not initialized";
844 #if defined(ENABLE_EXTENSIONS)
845 return extension_throttle_manager_.get();
846 #else
847 return nullptr;
848 #endif
851 content_settings::CookieSettings* ProfileIOData::GetCookieSettings() const {
852 // Allow either Init() or SetCookieSettingsForTesting() to initialize.
853 DCHECK(initialized_ || cookie_settings_.get());
854 return cookie_settings_.get();
857 HostContentSettingsMap* ProfileIOData::GetHostContentSettingsMap() const {
858 DCHECK(initialized_);
859 return host_content_settings_map_.get();
862 ResourceContext::SaltCallback ProfileIOData::GetMediaDeviceIDSalt() const {
863 return base::Bind(&MediaDeviceIDSalt::GetSalt, media_device_id_salt_);
866 bool ProfileIOData::IsOffTheRecord() const {
867 return profile_type() == Profile::INCOGNITO_PROFILE
868 || profile_type() == Profile::GUEST_PROFILE;
871 void ProfileIOData::InitializeMetricsEnabledStateOnUIThread() {
872 DCHECK_CURRENTLY_ON(BrowserThread::UI);
873 #if defined(OS_CHROMEOS)
874 // Just fetch the value from ChromeOS' settings while we're on the UI thread.
875 // TODO(stevet): For now, this value is only set on profile initialization.
876 // We will want to do something similar to the PrefMember method below in the
877 // future to more accurately capture this state.
878 chromeos::CrosSettings::Get()->GetBoolean(chromeos::kStatsReportingPref,
879 &enable_metrics_);
880 #elif defined(OS_ANDROID)
881 // TODO(dwkang): rename or unify the pref for UMA once we have conclusion
882 // in crbugs.com/246495.
883 // Android has it's own preferences for metrics / crash uploading.
884 enable_metrics_.Init(prefs::kCrashReportingEnabled,
885 g_browser_process->local_state());
886 enable_metrics_.MoveToThread(
887 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
888 #else
889 // Prep the PrefMember and send it to the IO thread, since this value will be
890 // read from there.
891 enable_metrics_.Init(prefs::kMetricsReportingEnabled,
892 g_browser_process->local_state());
893 enable_metrics_.MoveToThread(
894 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
895 #endif // defined(OS_CHROMEOS)
898 bool ProfileIOData::GetMetricsEnabledStateOnIOThread() const {
899 DCHECK_CURRENTLY_ON(BrowserThread::IO);
900 #if defined(OS_CHROMEOS)
901 return enable_metrics_;
902 #else
903 return enable_metrics_.GetValue();
904 #endif // defined(OS_CHROMEOS)
907 bool ProfileIOData::IsDataReductionProxyEnabled() const {
908 return data_reduction_proxy_io_data() &&
909 data_reduction_proxy_io_data()->IsEnabled();
912 void ProfileIOData::set_data_reduction_proxy_io_data(
913 scoped_ptr<data_reduction_proxy::DataReductionProxyIOData>
914 data_reduction_proxy_io_data) const {
915 data_reduction_proxy_io_data_ = data_reduction_proxy_io_data.Pass();
918 base::WeakPtr<net::HttpServerProperties>
919 ProfileIOData::http_server_properties() const {
920 return http_server_properties_->GetWeakPtr();
923 void ProfileIOData::set_http_server_properties(
924 scoped_ptr<net::HttpServerProperties> http_server_properties) const {
925 http_server_properties_ = http_server_properties.Pass();
928 ProfileIOData::ResourceContext::ResourceContext(ProfileIOData* io_data)
929 : io_data_(io_data),
930 host_resolver_(NULL),
931 request_context_(NULL) {
932 DCHECK(io_data);
935 ProfileIOData::ResourceContext::~ResourceContext() {}
937 net::HostResolver* ProfileIOData::ResourceContext::GetHostResolver() {
938 DCHECK_CURRENTLY_ON(BrowserThread::IO);
939 DCHECK(io_data_->initialized_);
940 return host_resolver_;
943 net::URLRequestContext* ProfileIOData::ResourceContext::GetRequestContext() {
944 DCHECK_CURRENTLY_ON(BrowserThread::IO);
945 DCHECK(io_data_->initialized_);
946 return request_context_;
949 scoped_ptr<net::ClientCertStore>
950 ProfileIOData::ResourceContext::CreateClientCertStore() {
951 if (!io_data_->client_cert_store_factory_.is_null())
952 return io_data_->client_cert_store_factory_.Run();
953 #if defined(OS_CHROMEOS)
954 return scoped_ptr<net::ClientCertStore>(new chromeos::ClientCertStoreChromeOS(
955 io_data_->certificate_provider_->Copy(),
956 make_scoped_ptr(new chromeos::ClientCertFilterChromeOS(
957 io_data_->use_system_key_slot(), io_data_->username_hash())),
958 base::Bind(&CreateCryptoModuleBlockingPasswordDelegate,
959 chrome::kCryptoModulePasswordClientAuth)));
960 #elif defined(USE_NSS_CERTS)
961 return scoped_ptr<net::ClientCertStore>(new net::ClientCertStoreNSS(
962 base::Bind(&CreateCryptoModuleBlockingPasswordDelegate,
963 chrome::kCryptoModulePasswordClientAuth)));
964 #elif defined(OS_WIN)
965 return scoped_ptr<net::ClientCertStore>(new net::ClientCertStoreWin());
966 #elif defined(OS_MACOSX)
967 return scoped_ptr<net::ClientCertStore>(new net::ClientCertStoreMac());
968 #elif defined(OS_ANDROID)
969 // Android does not use the ClientCertStore infrastructure. On Android client
970 // cert matching is done by the OS as part of the call to show the cert
971 // selection dialog.
972 return nullptr;
973 #else
974 #error Unknown platform.
975 #endif
978 void ProfileIOData::ResourceContext::CreateKeygenHandler(
979 uint32 key_size_in_bits,
980 const std::string& challenge_string,
981 const GURL& url,
982 const base::Callback<void(scoped_ptr<net::KeygenHandler>)>& callback) {
983 DCHECK(!callback.is_null());
984 #if defined(USE_NSS_CERTS)
985 scoped_ptr<net::KeygenHandler> keygen_handler(
986 new net::KeygenHandler(key_size_in_bits, challenge_string, url));
988 base::Callback<void(scoped_ptr<ChromeNSSCryptoModuleDelegate>)>
989 got_delegate_callback = base::Bind(&InitializeAndPassKeygenHandler,
990 base::Passed(&keygen_handler),
991 callback);
993 ChromeNSSCryptoModuleDelegate::CreateForResourceContext(
994 chrome::kCryptoModulePasswordKeygen,
995 net::HostPortPair::FromURL(url),
996 this,
997 got_delegate_callback);
998 #else
999 callback.Run(make_scoped_ptr(
1000 new net::KeygenHandler(key_size_in_bits, challenge_string, url)));
1001 #endif
1004 ResourceContext::SaltCallback
1005 ProfileIOData::ResourceContext::GetMediaDeviceIDSalt() {
1006 return io_data_->GetMediaDeviceIDSalt();
1009 // static
1010 std::string ProfileIOData::GetSSLSessionCacheShard() {
1011 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1012 // The SSL session cache is partitioned by setting a string. This returns a
1013 // unique string to partition the SSL session cache. Each time we create a
1014 // new profile, we'll get a fresh SSL session cache which is separate from
1015 // the other profiles.
1016 static unsigned ssl_session_cache_instance = 0;
1017 return base::StringPrintf("profile/%u", ssl_session_cache_instance++);
1020 void ProfileIOData::Init(
1021 content::ProtocolHandlerMap* protocol_handlers,
1022 content::URLRequestInterceptorScopedVector request_interceptors) const {
1023 // The basic logic is implemented here. The specific initialization
1024 // is done in InitializeInternal(), implemented by subtypes. Static helper
1025 // functions have been provided to assist in common operations.
1026 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1027 DCHECK(!initialized_);
1029 // TODO(jhawkins): Remove once crbug.com/102004 is fixed.
1030 CHECK(initialized_on_UI_thread_);
1032 // TODO(jhawkins): Return to DCHECK once crbug.com/102004 is fixed.
1033 CHECK(profile_params_.get());
1035 IOThread* const io_thread = profile_params_->io_thread;
1036 IOThread::Globals* const io_thread_globals = io_thread->globals();
1037 const base::CommandLine& command_line =
1038 *base::CommandLine::ForCurrentProcess();
1040 // Create the common request contexts.
1041 main_request_context_.reset(new net::URLRequestContext());
1042 extensions_request_context_.reset(new net::URLRequestContext());
1044 scoped_ptr<ChromeNetworkDelegate> network_delegate(
1045 new ChromeNetworkDelegate(
1046 #if defined(ENABLE_EXTENSIONS)
1047 io_thread_globals->extension_event_router_forwarder.get(),
1048 #else
1049 NULL,
1050 #endif
1051 &enable_referrers_));
1052 #if defined(ENABLE_EXTENSIONS)
1053 network_delegate->set_extension_info_map(
1054 profile_params_->extension_info_map.get());
1055 if (!command_line.HasSwitch(switches::kDisableExtensionsHttpThrottling)) {
1056 extension_throttle_manager_.reset(
1057 new extensions::ExtensionThrottleManager());
1059 #endif
1061 #if defined(ENABLE_CONFIGURATION_POLICY)
1062 network_delegate->set_url_blacklist_manager(url_blacklist_manager_.get());
1063 #endif
1064 network_delegate->set_profile(profile_params_->profile);
1065 network_delegate->set_profile_path(profile_params_->path);
1066 network_delegate->set_cookie_settings(profile_params_->cookie_settings.get());
1067 network_delegate->set_enable_do_not_track(&enable_do_not_track_);
1068 network_delegate->set_force_google_safe_search(&force_google_safesearch_);
1069 network_delegate->set_force_youtube_safety_mode(&force_youtube_safety_mode_);
1071 // NOTE: Proxy service uses the default io thread network delegate, not the
1072 // delegate just created.
1073 proxy_service_ = ProxyServiceFactory::CreateProxyService(
1074 io_thread->net_log(),
1075 io_thread_globals->proxy_script_fetcher_context.get(),
1076 io_thread_globals->system_network_delegate.get(),
1077 profile_params_->proxy_config_service.release(), command_line,
1078 quick_check_enabled_.GetValue());
1079 transport_security_state_.reset(new net::TransportSecurityState());
1080 base::SequencedWorkerPool* pool = BrowserThread::GetBlockingPool();
1081 transport_security_persister_.reset(
1082 new net::TransportSecurityPersister(
1083 transport_security_state_.get(),
1084 profile_params_->path,
1085 pool->GetSequencedTaskRunnerWithShutdownBehavior(
1086 pool->GetSequenceToken(),
1087 base::SequencedWorkerPool::BLOCK_SHUTDOWN),
1088 IsOffTheRecord()));
1090 certificate_report_sender_.reset(new net::CertificateReportSender(
1091 main_request_context_.get(),
1092 net::CertificateReportSender::DO_NOT_SEND_COOKIES));
1093 transport_security_state_->SetReportSender(certificate_report_sender_.get());
1095 // Take ownership over these parameters.
1096 cookie_settings_ = profile_params_->cookie_settings;
1097 host_content_settings_map_ = profile_params_->host_content_settings_map;
1098 #if defined(ENABLE_EXTENSIONS)
1099 extension_info_map_ = profile_params_->extension_info_map;
1100 #endif
1102 resource_context_->host_resolver_ = io_thread_globals->host_resolver.get();
1103 resource_context_->request_context_ = main_request_context_.get();
1105 if (profile_params_->resource_prefetch_predictor_observer_) {
1106 resource_prefetch_predictor_observer_.reset(
1107 profile_params_->resource_prefetch_predictor_observer_.release());
1110 #if defined(ENABLE_SUPERVISED_USERS)
1111 supervised_user_url_filter_ = profile_params_->supervised_user_url_filter;
1112 #endif
1114 #if defined(OS_CHROMEOS)
1115 username_hash_ = profile_params_->username_hash;
1116 use_system_key_slot_ = profile_params_->use_system_key_slot;
1117 if (use_system_key_slot_)
1118 EnableNSSSystemKeySlotForResourceContext(resource_context_.get());
1120 certificate_provider_ = profile_params_->certificate_provider.Pass();
1121 #endif
1123 if (g_cert_verifier_for_testing) {
1124 main_request_context_->set_cert_verifier(g_cert_verifier_for_testing);
1125 } else {
1126 #if defined(OS_CHROMEOS)
1127 crypto::ScopedPK11Slot public_slot =
1128 crypto::GetPublicSlotForChromeOSUser(username_hash_);
1129 // The private slot won't be ready by this point. It shouldn't be necessary
1130 // for cert trust purposes anyway.
1131 scoped_refptr<net::CertVerifyProc> verify_proc(
1132 new chromeos::CertVerifyProcChromeOS(public_slot.Pass()));
1133 if (policy_cert_verifier_) {
1134 DCHECK_EQ(policy_cert_verifier_, cert_verifier_.get());
1135 policy_cert_verifier_->InitializeOnIOThread(verify_proc);
1136 } else {
1137 cert_verifier_.reset(
1138 new net::MultiThreadedCertVerifier(verify_proc.get()));
1140 main_request_context_->set_cert_verifier(cert_verifier_.get());
1141 #else
1142 main_request_context_->set_cert_verifier(
1143 io_thread_globals->cert_verifier.get());
1144 #endif
1147 // Install the New Tab Page Interceptor.
1148 if (profile_params_->new_tab_page_interceptor.get()) {
1149 request_interceptors.push_back(
1150 profile_params_->new_tab_page_interceptor.release());
1153 InitializeInternal(
1154 network_delegate.Pass(), profile_params_.get(),
1155 protocol_handlers, request_interceptors.Pass());
1157 profile_params_.reset();
1158 initialized_ = true;
1161 void ProfileIOData::ApplyProfileParamsToContext(
1162 net::URLRequestContext* context) const {
1163 context->set_http_user_agent_settings(
1164 chrome_http_user_agent_settings_.get());
1165 context->set_ssl_config_service(profile_params_->ssl_config_service.get());
1168 scoped_ptr<net::URLRequestJobFactory> ProfileIOData::SetUpJobFactoryDefaults(
1169 scoped_ptr<net::URLRequestJobFactoryImpl> job_factory,
1170 content::URLRequestInterceptorScopedVector request_interceptors,
1171 scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
1172 protocol_handler_interceptor,
1173 net::NetworkDelegate* network_delegate,
1174 net::FtpTransactionFactory* ftp_transaction_factory) const {
1175 // NOTE(willchan): Keep these protocol handlers in sync with
1176 // ProfileIOData::IsHandledProtocol().
1177 bool set_protocol = job_factory->SetProtocolHandler(
1178 url::kFileScheme,
1179 make_scoped_ptr(new net::FileProtocolHandler(
1180 content::BrowserThread::GetBlockingPool()
1181 ->GetTaskRunnerWithShutdownBehavior(
1182 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN))));
1183 DCHECK(set_protocol);
1185 #if defined(ENABLE_EXTENSIONS)
1186 DCHECK(extension_info_map_.get());
1187 // Check only for incognito (and not Chrome OS guest mode GUEST_PROFILE).
1188 bool is_incognito = profile_type() == Profile::INCOGNITO_PROFILE;
1189 set_protocol = job_factory->SetProtocolHandler(
1190 extensions::kExtensionScheme,
1191 extensions::CreateExtensionProtocolHandler(is_incognito,
1192 extension_info_map_.get()));
1193 DCHECK(set_protocol);
1194 set_protocol = job_factory->SetProtocolHandler(
1195 extensions::kExtensionResourceScheme,
1196 CreateExtensionResourceProtocolHandler());
1197 DCHECK(set_protocol);
1198 #endif
1199 set_protocol = job_factory->SetProtocolHandler(
1200 url::kDataScheme, make_scoped_ptr(new net::DataProtocolHandler()));
1201 DCHECK(set_protocol);
1202 #if defined(OS_CHROMEOS)
1203 if (profile_params_) {
1204 set_protocol = job_factory->SetProtocolHandler(
1205 content::kExternalFileScheme,
1206 make_scoped_ptr(new chromeos::ExternalFileProtocolHandler(
1207 profile_params_->profile)));
1208 DCHECK(set_protocol);
1210 #endif // defined(OS_CHROMEOS)
1211 #if defined(OS_ANDROID)
1212 set_protocol = job_factory->SetProtocolHandler(
1213 url::kContentScheme,
1214 content::ContentProtocolHandler::Create(
1215 content::BrowserThread::GetBlockingPool()
1216 ->GetTaskRunnerWithShutdownBehavior(
1217 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)));
1218 #endif
1220 job_factory->SetProtocolHandler(
1221 url::kAboutScheme,
1222 make_scoped_ptr(new about_handler::AboutProtocolHandler()));
1223 #if !defined(DISABLE_FTP_SUPPORT)
1224 DCHECK(ftp_transaction_factory);
1225 job_factory->SetProtocolHandler(
1226 url::kFtpScheme,
1227 make_scoped_ptr(new net::FtpProtocolHandler(ftp_transaction_factory)));
1228 #endif // !defined(DISABLE_FTP_SUPPORT)
1230 #if defined(DEBUG_DEVTOOLS)
1231 request_interceptors.push_back(new DebugDevToolsInterceptor);
1232 #endif
1234 // Set up interceptors in the reverse order.
1235 scoped_ptr<net::URLRequestJobFactory> top_job_factory = job_factory.Pass();
1236 for (content::URLRequestInterceptorScopedVector::reverse_iterator i =
1237 request_interceptors.rbegin();
1238 i != request_interceptors.rend();
1239 ++i) {
1240 top_job_factory.reset(new net::URLRequestInterceptingJobFactory(
1241 top_job_factory.Pass(), make_scoped_ptr(*i)));
1243 request_interceptors.weak_clear();
1245 if (protocol_handler_interceptor) {
1246 protocol_handler_interceptor->Chain(top_job_factory.Pass());
1247 return protocol_handler_interceptor.Pass();
1248 } else {
1249 return top_job_factory.Pass();
1253 void ProfileIOData::ShutdownOnUIThread(
1254 scoped_ptr<ChromeURLRequestContextGetterVector> context_getters) {
1255 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1257 google_services_user_account_id_.Destroy();
1258 enable_referrers_.Destroy();
1259 enable_do_not_track_.Destroy();
1260 force_google_safesearch_.Destroy();
1261 force_youtube_safety_mode_.Destroy();
1262 #if !defined(OS_CHROMEOS)
1263 enable_metrics_.Destroy();
1264 #endif
1265 safe_browsing_enabled_.Destroy();
1266 sync_disabled_.Destroy();
1267 signin_allowed_.Destroy();
1268 network_prediction_options_.Destroy();
1269 quick_check_enabled_.Destroy();
1270 if (media_device_id_salt_.get())
1271 media_device_id_salt_->ShutdownOnUIThread();
1272 session_startup_pref_.Destroy();
1273 #if defined(ENABLE_CONFIGURATION_POLICY)
1274 if (url_blacklist_manager_)
1275 url_blacklist_manager_->ShutdownOnUIThread();
1276 #endif
1277 if (chrome_http_user_agent_settings_)
1278 chrome_http_user_agent_settings_->CleanupOnUIThread();
1279 incognito_availibility_pref_.Destroy();
1281 if (!context_getters->empty()) {
1282 if (BrowserThread::IsMessageLoopValid(BrowserThread::IO)) {
1283 BrowserThread::PostTask(
1284 BrowserThread::IO, FROM_HERE,
1285 base::Bind(&NotifyContextGettersOfShutdownOnIO,
1286 base::Passed(&context_getters)));
1290 bool posted = BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, this);
1291 if (!posted)
1292 delete this;
1295 void ProfileIOData::set_channel_id_service(
1296 net::ChannelIDService* channel_id_service) const {
1297 channel_id_service_.reset(channel_id_service);
1300 void ProfileIOData::DestroyResourceContext() {
1301 resource_context_.reset();
1304 scoped_ptr<net::HttpCache> ProfileIOData::CreateMainHttpFactory(
1305 const ProfileParams* profile_params,
1306 net::HttpCache::BackendFactory* main_backend) const {
1307 net::HttpNetworkSession::Params params;
1308 net::URLRequestContext* context = main_request_context();
1310 IOThread* const io_thread = profile_params->io_thread;
1312 io_thread->InitializeNetworkSessionParams(&params);
1313 net::URLRequestContextBuilder::SetHttpNetworkSessionComponents(context,
1314 &params);
1316 params.ssl_session_cache_shard = GetSSLSessionCacheShard();
1317 if (!IsOffTheRecord()) {
1318 params.socket_performance_watcher_factory =
1319 io_thread->globals()->network_quality_estimator.get();
1321 if (data_reduction_proxy_io_data_.get())
1322 params.proxy_delegate = data_reduction_proxy_io_data_->proxy_delegate();
1324 net::HttpNetworkSession* session = new net::HttpNetworkSession(params);
1325 return scoped_ptr<net::HttpCache>(new net::HttpCache(
1326 new DevToolsNetworkTransactionFactory(
1327 network_controller_handle_.GetController(), session),
1328 context->net_log(), main_backend));
1331 scoped_ptr<net::HttpCache> ProfileIOData::CreateHttpFactory(
1332 net::HttpNetworkSession* shared_session,
1333 net::HttpCache::BackendFactory* backend) const {
1334 return scoped_ptr<net::HttpCache>(new net::HttpCache(
1335 new DevToolsNetworkTransactionFactory(
1336 network_controller_handle_.GetController(), shared_session),
1337 shared_session->net_log(), backend));
1340 void ProfileIOData::SetCookieSettingsForTesting(
1341 content_settings::CookieSettings* cookie_settings) {
1342 DCHECK(!cookie_settings_.get());
1343 cookie_settings_ = cookie_settings;