Only grant permissions to new extensions from sync if they have the expected version
[chromium-blink-merge.git] / chrome / browser / profiles / profile_io_data.cc
blob85815a83678555b58e707254d3669bc3d0f6f954
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/custom_handlers/protocol_handler_registry.h"
29 #include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h"
30 #include "chrome/browser/devtools/devtools_network_controller.h"
31 #include "chrome/browser/devtools/devtools_network_transaction_factory.h"
32 #include "chrome/browser/download/download_service.h"
33 #include "chrome/browser/download/download_service_factory.h"
34 #include "chrome/browser/io_thread.h"
35 #include "chrome/browser/media/media_device_id_salt.h"
36 #include "chrome/browser/net/chrome_http_user_agent_settings.h"
37 #include "chrome/browser/net/chrome_net_log.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/sync_driver/pref_names.h"
60 #include "components/url_formatter/url_fixer.h"
61 #include "content/public/browser/browser_thread.h"
62 #include "content/public/browser/host_zoom_map.h"
63 #include "content/public/browser/notification_service.h"
64 #include "content/public/browser/resource_context.h"
65 #include "net/base/keygen_handler.h"
66 #include "net/base/network_quality_estimator.h"
67 #include "net/cert/cert_verifier.h"
68 #include "net/cookies/canonical_cookie.h"
69 #include "net/http/http_transaction_factory.h"
70 #include "net/http/http_util.h"
71 #include "net/http/transport_security_persister.h"
72 #include "net/proxy/proxy_config_service_fixed.h"
73 #include "net/proxy/proxy_script_fetcher_impl.h"
74 #include "net/proxy/proxy_service.h"
75 #include "net/ssl/channel_id_service.h"
76 #include "net/ssl/client_cert_store.h"
77 #include "net/url_request/certificate_report_sender.h"
78 #include "net/url_request/data_protocol_handler.h"
79 #include "net/url_request/file_protocol_handler.h"
80 #include "net/url_request/ftp_protocol_handler.h"
81 #include "net/url_request/url_request.h"
82 #include "net/url_request/url_request_context.h"
83 #include "net/url_request/url_request_context_builder.h"
84 #include "net/url_request/url_request_file_job.h"
85 #include "net/url_request/url_request_intercepting_job_factory.h"
86 #include "net/url_request/url_request_interceptor.h"
87 #include "net/url_request/url_request_job_factory_impl.h"
89 #if defined(ENABLE_CONFIGURATION_POLICY)
90 #include "chrome/browser/policy/cloud/policy_header_service_factory.h"
91 #include "chrome/browser/policy/policy_helpers.h"
92 #include "components/policy/core/browser/url_blacklist_manager.h"
93 #include "components/policy/core/common/cloud/policy_header_io_helper.h"
94 #include "components/policy/core/common/cloud/policy_header_service.h"
95 #include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
96 #endif
98 #if defined(ENABLE_EXTENSIONS)
99 #include "chrome/browser/extensions/extension_cookie_monster_delegate.h"
100 #include "chrome/browser/extensions/extension_resource_protocols.h"
101 #include "extensions/browser/extension_protocols.h"
102 #include "extensions/browser/extension_system.h"
103 #include "extensions/browser/extension_throttle_manager.h"
104 #include "extensions/browser/info_map.h"
105 #include "extensions/common/constants.h"
106 #endif
108 #if defined(ENABLE_SUPERVISED_USERS)
109 #include "chrome/browser/supervised_user/supervised_user_service.h"
110 #include "chrome/browser/supervised_user/supervised_user_service_factory.h"
111 #include "chrome/browser/supervised_user/supervised_user_url_filter.h"
112 #endif
114 #if defined(OS_ANDROID)
115 #include "content/public/browser/android/content_protocol_handler.h"
116 #endif // defined(OS_ANDROID)
118 #if defined(OS_CHROMEOS)
119 #include "chrome/browser/chromeos/certificate_provider/certificate_provider.h"
120 #include "chrome/browser/chromeos/certificate_provider/certificate_provider_service.h"
121 #include "chrome/browser/chromeos/certificate_provider/certificate_provider_service_factory.h"
122 #include "chrome/browser/chromeos/fileapi/external_file_protocol_handler.h"
123 #include "chrome/browser/chromeos/login/startup_utils.h"
124 #include "chrome/browser/chromeos/net/cert_verify_proc_chromeos.h"
125 #include "chrome/browser/chromeos/net/client_cert_filter_chromeos.h"
126 #include "chrome/browser/chromeos/net/client_cert_store_chromeos.h"
127 #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
128 #include "chrome/browser/chromeos/policy/policy_cert_service.h"
129 #include "chrome/browser/chromeos/policy/policy_cert_service_factory.h"
130 #include "chrome/browser/chromeos/policy/policy_cert_verifier.h"
131 #include "chrome/browser/chromeos/profiles/profile_helper.h"
132 #include "chrome/browser/chromeos/settings/cros_settings.h"
133 #include "chrome/browser/net/nss_context.h"
134 #include "chromeos/dbus/dbus_thread_manager.h"
135 #include "chromeos/settings/cros_settings_names.h"
136 #include "chromeos/tpm/tpm_token_info_getter.h"
137 #include "components/user_manager/user.h"
138 #include "components/user_manager/user_manager.h"
139 #include "crypto/nss_util.h"
140 #include "crypto/nss_util_internal.h"
141 #include "net/cert/cert_verifier.h"
142 #include "net/cert/multi_threaded_cert_verifier.h"
143 #endif // defined(OS_CHROMEOS)
145 #if defined(USE_NSS_CERTS)
146 #include "chrome/browser/ui/crypto_module_delegate_nss.h"
147 #include "net/ssl/client_cert_store_nss.h"
148 #endif
150 #if defined(OS_WIN)
151 #include "net/ssl/client_cert_store_win.h"
152 #endif
154 #if defined(OS_MACOSX)
155 #include "net/ssl/client_cert_store_mac.h"
156 #endif
158 using content::BrowserContext;
159 using content::BrowserThread;
160 using content::ResourceContext;
162 namespace {
164 net::CertVerifier* g_cert_verifier_for_testing = nullptr;
166 #if defined(DEBUG_DEVTOOLS)
167 bool IsSupportedDevToolsURL(const GURL& url, base::FilePath* path) {
168 std::string bundled_path_prefix(chrome::kChromeUIDevToolsBundledPath);
169 bundled_path_prefix = "/" + bundled_path_prefix + "/";
171 if (!url.SchemeIs(content::kChromeDevToolsScheme) ||
172 url.host() != chrome::kChromeUIDevToolsHost ||
173 !base::StartsWith(url.path(), bundled_path_prefix,
174 base::CompareCase::INSENSITIVE_ASCII)) {
175 return false;
178 if (!url.is_valid()) {
179 NOTREACHED();
180 return false;
183 // Remove Query and Ref from URL.
184 GURL stripped_url;
185 GURL::Replacements replacements;
186 replacements.ClearQuery();
187 replacements.ClearRef();
188 stripped_url = url.ReplaceComponents(replacements);
190 std::string relative_path;
191 const std::string& spec = stripped_url.possibly_invalid_spec();
192 const url::Parsed& parsed = stripped_url.parsed_for_possibly_invalid_spec();
193 int offset = parsed.CountCharactersBefore(url::Parsed::PATH, false);
194 if (offset < static_cast<int>(spec.size()))
195 relative_path.assign(spec.substr(offset + bundled_path_prefix.length()));
197 // Check that |relative_path| is not an absolute path (otherwise
198 // AppendASCII() will DCHECK). The awkward use of StringType is because on
199 // some systems FilePath expects a std::string, but on others a std::wstring.
200 base::FilePath p(
201 base::FilePath::StringType(relative_path.begin(), relative_path.end()));
202 if (p.IsAbsolute())
203 return false;
205 base::FilePath inspector_dir;
206 if (!PathService::Get(chrome::DIR_INSPECTOR, &inspector_dir))
207 return false;
209 if (inspector_dir.empty())
210 return false;
212 *path = inspector_dir.AppendASCII(relative_path);
213 return true;
216 class DebugDevToolsInterceptor : public net::URLRequestInterceptor {
217 public:
218 // net::URLRequestInterceptor implementation.
219 net::URLRequestJob* MaybeInterceptRequest(
220 net::URLRequest* request,
221 net::NetworkDelegate* network_delegate) const override {
222 base::FilePath path;
223 if (IsSupportedDevToolsURL(request->url(), &path))
224 return new net::URLRequestFileJob(
225 request, network_delegate, path,
226 content::BrowserThread::GetBlockingPool()->
227 GetTaskRunnerWithShutdownBehavior(
228 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN));
230 return NULL;
233 #endif // defined(DEBUG_DEVTOOLS)
235 #if defined(OS_CHROMEOS)
236 // The following four functions are responsible for initializing NSS for each
237 // profile on ChromeOS, which has a separate NSS database and TPM slot
238 // per-profile.
240 // Initialization basically follows these steps:
241 // 1) Get some info from user_manager::UserManager about the User for this
242 // profile.
243 // 2) Tell nss_util to initialize the software slot for this profile.
244 // 3) Wait for the TPM module to be loaded by nss_util if it isn't already.
245 // 4) Ask CryptohomeClient which TPM slot id corresponds to this profile.
246 // 5) Tell nss_util to use that slot id on the TPM module.
248 // Some of these steps must happen on the UI thread, others must happen on the
249 // IO thread:
250 // UI thread IO Thread
252 // ProfileIOData::InitializeOnUIThread
253 // |
254 // ProfileHelper::Get()->GetUserByProfile()
255 // \---------------------------------------v
256 // StartNSSInitOnIOThread
257 // |
258 // crypto::InitializeNSSForChromeOSUser
259 // |
260 // crypto::IsTPMTokenReady
261 // |
262 // StartTPMSlotInitializationOnIOThread
263 // v---------------------------------------/
264 // GetTPMInfoForUserOnUIThread
265 // |
266 // chromeos::TPMTokenInfoGetter::Start
267 // |
268 // DidGetTPMInfoForUserOnUIThread
269 // \---------------------------------------v
270 // crypto::InitializeTPMForChromeOSUser
272 void DidGetTPMInfoForUserOnUIThread(
273 scoped_ptr<chromeos::TPMTokenInfoGetter> getter,
274 const std::string& username_hash,
275 const chromeos::TPMTokenInfo& info) {
276 DCHECK_CURRENTLY_ON(BrowserThread::UI);
277 if (info.tpm_is_enabled && info.token_slot_id != -1) {
278 DVLOG(1) << "Got TPM slot for " << username_hash << ": "
279 << info.token_slot_id;
280 BrowserThread::PostTask(
281 BrowserThread::IO,
282 FROM_HERE,
283 base::Bind(&crypto::InitializeTPMForChromeOSUser,
284 username_hash, info.token_slot_id));
285 } else {
286 NOTREACHED() << "TPMTokenInfoGetter reported invalid token.";
290 void GetTPMInfoForUserOnUIThread(const std::string& username,
291 const std::string& username_hash) {
292 DCHECK_CURRENTLY_ON(BrowserThread::UI);
293 DVLOG(1) << "Getting TPM info from cryptohome for "
294 << " " << username << " " << username_hash;
295 scoped_ptr<chromeos::TPMTokenInfoGetter> scoped_token_info_getter =
296 chromeos::TPMTokenInfoGetter::CreateForUserToken(
297 username,
298 chromeos::DBusThreadManager::Get()->GetCryptohomeClient(),
299 base::ThreadTaskRunnerHandle::Get());
300 chromeos::TPMTokenInfoGetter* token_info_getter =
301 scoped_token_info_getter.get();
303 // Bind |token_info_getter| to the callback to ensure it does not go away
304 // before TPM token info is fetched.
305 // TODO(tbarzic, pneubeck): Handle this in a nicer way when this logic is
306 // moved to a separate profile service.
307 token_info_getter->Start(
308 base::Bind(&DidGetTPMInfoForUserOnUIThread,
309 base::Passed(&scoped_token_info_getter),
310 username_hash));
313 void StartTPMSlotInitializationOnIOThread(const std::string& username,
314 const std::string& username_hash) {
315 DCHECK_CURRENTLY_ON(BrowserThread::IO);
317 BrowserThread::PostTask(
318 BrowserThread::UI,
319 FROM_HERE,
320 base::Bind(&GetTPMInfoForUserOnUIThread, username, username_hash));
323 void StartNSSInitOnIOThread(const std::string& username,
324 const std::string& username_hash,
325 const base::FilePath& path) {
326 DCHECK_CURRENTLY_ON(BrowserThread::IO);
327 DVLOG(1) << "Starting NSS init for " << username
328 << " hash:" << username_hash;
330 // Make sure NSS is initialized for the user.
331 crypto::InitializeNSSForChromeOSUser(username_hash, path);
333 // Check if it's OK to initialize TPM for the user before continuing. This
334 // may not be the case if the TPM slot initialization was previously
335 // requested for the same user.
336 if (!crypto::ShouldInitializeTPMForChromeOSUser(username_hash))
337 return;
339 crypto::WillInitializeTPMForChromeOSUser(username_hash);
341 if (crypto::IsTPMTokenEnabledForNSS()) {
342 if (crypto::IsTPMTokenReady(base::Bind(
343 &StartTPMSlotInitializationOnIOThread, username, username_hash))) {
344 StartTPMSlotInitializationOnIOThread(username, username_hash);
345 } else {
346 DVLOG(1) << "Waiting for tpm ready ...";
348 } else {
349 crypto::InitializePrivateSoftwareSlotForChromeOSUser(username_hash);
352 #endif // defined(OS_CHROMEOS)
354 #if defined(USE_NSS_CERTS)
355 void InitializeAndPassKeygenHandler(
356 scoped_ptr<net::KeygenHandler> keygen_handler,
357 const base::Callback<void(scoped_ptr<net::KeygenHandler>)>& callback,
358 scoped_ptr<ChromeNSSCryptoModuleDelegate> delegate) {
359 if (delegate)
360 keygen_handler->set_crypto_module_delegate(delegate.Pass());
361 callback.Run(keygen_handler.Pass());
363 #endif // defined(USE_NSS_CERTS)
365 // For safe shutdown, must be called before the ProfileIOData is destroyed.
366 void NotifyContextGettersOfShutdownOnIO(
367 scoped_ptr<ProfileIOData::ChromeURLRequestContextGetterVector> getters) {
368 DCHECK_CURRENTLY_ON(BrowserThread::IO);
369 ProfileIOData::ChromeURLRequestContextGetterVector::iterator iter;
370 for (auto& chrome_context_getter : *getters)
371 chrome_context_getter->NotifyContextShuttingDown();
374 } // namespace
376 void ProfileIOData::InitializeOnUIThread(Profile* profile) {
377 DCHECK_CURRENTLY_ON(BrowserThread::UI);
378 PrefService* pref_service = profile->GetPrefs();
379 PrefService* local_state_pref_service = g_browser_process->local_state();
381 scoped_ptr<ProfileParams> params(new ProfileParams);
382 params->path = profile->GetPath();
384 params->io_thread = g_browser_process->io_thread();
386 params->cookie_settings = CookieSettingsFactory::GetForProfile(profile);
387 params->host_content_settings_map = profile->GetHostContentSettingsMap();
388 params->ssl_config_service = profile->GetSSLConfigService();
390 #if defined(ENABLE_EXTENSIONS)
391 params->extension_info_map =
392 extensions::ExtensionSystem::Get(profile)->info_map();
393 params->cookie_monster_delegate = new ExtensionCookieMonsterDelegate(profile);
394 #endif
396 if (predictors::ResourcePrefetchPredictor* predictor =
397 predictors::ResourcePrefetchPredictorFactory::GetForProfile(
398 profile)) {
399 resource_prefetch_predictor_observer_.reset(
400 new chrome_browser_net::ResourcePrefetchPredictorObserver(predictor));
403 ProtocolHandlerRegistry* protocol_handler_registry =
404 ProtocolHandlerRegistryFactory::GetForBrowserContext(profile);
405 DCHECK(protocol_handler_registry);
407 // The profile instance is only available here in the InitializeOnUIThread
408 // method, so we create the url job factory here, then save it for
409 // later delivery to the job factory in Init().
410 params->protocol_handler_interceptor =
411 protocol_handler_registry->CreateJobInterceptorFactory();
413 NewTabPageInterceptorService* new_tab_interceptor_service =
414 NewTabPageInterceptorServiceFactory::GetForProfile(profile);
415 if (new_tab_interceptor_service) {
416 params->new_tab_page_interceptor =
417 new_tab_interceptor_service->CreateInterceptor();
420 params->proxy_config_service
421 .reset(ProxyServiceFactory::CreateProxyConfigService(
422 profile->GetProxyConfigTracker()));
423 #if defined(ENABLE_SUPERVISED_USERS)
424 SupervisedUserService* supervised_user_service =
425 SupervisedUserServiceFactory::GetForProfile(profile);
426 params->supervised_user_url_filter =
427 supervised_user_service->GetURLFilterForIOThread();
428 #endif
429 #if defined(OS_CHROMEOS)
430 user_manager::UserManager* user_manager = user_manager::UserManager::Get();
431 if (user_manager) {
432 const user_manager::User* user =
433 chromeos::ProfileHelper::Get()->GetUserByProfile(profile);
434 // No need to initialize NSS for users with empty username hash:
435 // Getters for a user's NSS slots always return NULL slot if the user's
436 // username hash is empty, even when the NSS is not initialized for the
437 // user.
438 if (user && !user->username_hash().empty()) {
439 params->username_hash = user->username_hash();
440 DCHECK(!params->username_hash.empty());
441 BrowserThread::PostTask(BrowserThread::IO,
442 FROM_HERE,
443 base::Bind(&StartNSSInitOnIOThread,
444 user->email(),
445 user->username_hash(),
446 profile->GetPath()));
448 // Use the device-wide system key slot only if the user is of the same
449 // domain as the device is registered to.
450 policy::BrowserPolicyConnectorChromeOS* connector =
451 g_browser_process->platform_part()
452 ->browser_policy_connector_chromeos();
453 params->use_system_key_slot =
454 connector->GetUserAffiliation(user->email()) ==
455 policy::USER_AFFILIATION_MANAGED;
459 chromeos::CertificateProviderService* cert_provider_service =
460 chromeos::CertificateProviderServiceFactory::GetForBrowserContext(
461 profile);
462 if (cert_provider_service) {
463 params->certificate_provider =
464 cert_provider_service->CreateCertificateProvider();
466 #endif
468 params->profile = profile;
469 profile_params_.reset(params.release());
471 ChromeNetworkDelegate::InitializePrefsOnUIThread(
472 &enable_referrers_,
473 &enable_do_not_track_,
474 &force_google_safesearch_,
475 &force_youtube_safety_mode_,
476 pref_service);
478 scoped_refptr<base::SingleThreadTaskRunner> io_task_runner =
479 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
481 chrome_http_user_agent_settings_.reset(
482 new ChromeHttpUserAgentSettings(pref_service));
484 // These members are used only for sign in, which is not enabled
485 // in incognito mode. So no need to initialize them.
486 if (!IsOffTheRecord()) {
487 google_services_user_account_id_.Init(
488 prefs::kGoogleServicesUserAccountId, pref_service);
489 google_services_user_account_id_.MoveToThread(io_task_runner);
491 sync_disabled_.Init(sync_driver::prefs::kSyncManaged, pref_service);
492 sync_disabled_.MoveToThread(io_task_runner);
494 signin_allowed_.Init(prefs::kSigninAllowed, pref_service);
495 signin_allowed_.MoveToThread(io_task_runner);
498 quick_check_enabled_.Init(prefs::kQuickCheckEnabled,
499 local_state_pref_service);
500 quick_check_enabled_.MoveToThread(io_task_runner);
502 media_device_id_salt_ = new MediaDeviceIDSalt(pref_service, IsOffTheRecord());
504 network_prediction_options_.Init(prefs::kNetworkPredictionOptions,
505 pref_service);
507 network_prediction_options_.MoveToThread(io_task_runner);
509 #if defined(OS_CHROMEOS)
510 scoped_ptr<policy::PolicyCertVerifier> verifier =
511 policy::PolicyCertServiceFactory::CreateForProfile(profile);
512 policy_cert_verifier_ = verifier.get();
513 cert_verifier_ = verifier.Pass();
514 #endif
515 // The URLBlacklistManager has to be created on the UI thread to register
516 // observers of |pref_service|, and it also has to clean up on
517 // ShutdownOnUIThread to release these observers on the right thread.
518 // Don't pass it in |profile_params_| to make sure it is correctly cleaned up,
519 // in particular when this ProfileIOData isn't |initialized_| during deletion.
520 #if defined(ENABLE_CONFIGURATION_POLICY)
521 policy::URLBlacklist::SegmentURLCallback callback =
522 static_cast<policy::URLBlacklist::SegmentURLCallback>(
523 url_formatter::SegmentURL);
524 base::SequencedWorkerPool* pool = BrowserThread::GetBlockingPool();
525 scoped_refptr<base::SequencedTaskRunner> background_task_runner =
526 pool->GetSequencedTaskRunner(pool->GetSequenceToken());
527 url_blacklist_manager_.reset(new policy::URLBlacklistManager(
528 pref_service, background_task_runner, io_task_runner, callback,
529 base::Bind(policy::OverrideBlacklistForURL)));
531 if (!IsOffTheRecord()) {
532 // Add policy headers for non-incognito requests.
533 policy::PolicyHeaderService* policy_header_service =
534 policy::PolicyHeaderServiceFactory::GetForBrowserContext(profile);
535 if (policy_header_service) {
536 policy_header_helper_ =
537 policy_header_service->CreatePolicyHeaderIOHelper(io_task_runner);
540 #endif
542 incognito_availibility_pref_.Init(
543 prefs::kIncognitoModeAvailability, pref_service);
544 incognito_availibility_pref_.MoveToThread(io_task_runner);
546 initialized_on_UI_thread_ = true;
548 // We need to make sure that content initializes its own data structures that
549 // are associated with each ResourceContext because we might post this
550 // object to the IO thread after this function.
551 BrowserContext::EnsureResourceContextInitialized(profile);
554 ProfileIOData::MediaRequestContext::MediaRequestContext() {
557 void ProfileIOData::MediaRequestContext::SetHttpTransactionFactory(
558 scoped_ptr<net::HttpTransactionFactory> http_factory) {
559 http_factory_ = http_factory.Pass();
560 set_http_transaction_factory(http_factory_.get());
563 ProfileIOData::MediaRequestContext::~MediaRequestContext() {
564 AssertNoURLRequests();
567 ProfileIOData::AppRequestContext::AppRequestContext() {
570 void ProfileIOData::AppRequestContext::SetCookieStore(
571 net::CookieStore* cookie_store) {
572 cookie_store_ = cookie_store;
573 set_cookie_store(cookie_store);
576 void ProfileIOData::AppRequestContext::SetHttpTransactionFactory(
577 scoped_ptr<net::HttpTransactionFactory> http_factory) {
578 http_factory_ = http_factory.Pass();
579 set_http_transaction_factory(http_factory_.get());
582 void ProfileIOData::AppRequestContext::SetJobFactory(
583 scoped_ptr<net::URLRequestJobFactory> job_factory) {
584 job_factory_ = job_factory.Pass();
585 set_job_factory(job_factory_.get());
588 ProfileIOData::AppRequestContext::~AppRequestContext() {
589 AssertNoURLRequests();
592 ProfileIOData::ProfileParams::ProfileParams()
593 : io_thread(NULL),
594 #if defined(OS_CHROMEOS)
595 use_system_key_slot(false),
596 #endif
597 profile(NULL) {
600 ProfileIOData::ProfileParams::~ProfileParams() {}
602 ProfileIOData::ProfileIOData(Profile::ProfileType profile_type)
603 : initialized_(false),
604 #if defined(OS_CHROMEOS)
605 policy_cert_verifier_(NULL),
606 use_system_key_slot_(false),
607 #endif
608 resource_context_(new ResourceContext(this)),
609 initialized_on_UI_thread_(false),
610 profile_type_(profile_type) {
611 DCHECK_CURRENTLY_ON(BrowserThread::UI);
614 ProfileIOData::~ProfileIOData() {
615 if (BrowserThread::IsMessageLoopValid(BrowserThread::IO))
616 DCHECK_CURRENTLY_ON(BrowserThread::IO);
618 // Pull the contents of the request context maps onto the stack for sanity
619 // checking of values in a minidump. http://crbug.com/260425
620 size_t num_app_contexts = app_request_context_map_.size();
621 size_t num_media_contexts = isolated_media_request_context_map_.size();
622 size_t current_context = 0;
623 static const size_t kMaxCachedContexts = 20;
624 net::URLRequestContext* app_context_cache[kMaxCachedContexts] = {0};
625 void* app_context_vtable_cache[kMaxCachedContexts] = {0};
626 net::URLRequestContext* media_context_cache[kMaxCachedContexts] = {0};
627 void* media_context_vtable_cache[kMaxCachedContexts] = {0};
628 void* tmp_vtable = NULL;
629 base::debug::Alias(&num_app_contexts);
630 base::debug::Alias(&num_media_contexts);
631 base::debug::Alias(&current_context);
632 base::debug::Alias(app_context_cache);
633 base::debug::Alias(app_context_vtable_cache);
634 base::debug::Alias(media_context_cache);
635 base::debug::Alias(media_context_vtable_cache);
636 base::debug::Alias(&tmp_vtable);
638 current_context = 0;
639 for (URLRequestContextMap::const_iterator it =
640 app_request_context_map_.begin();
641 current_context < kMaxCachedContexts &&
642 it != app_request_context_map_.end();
643 ++it, ++current_context) {
644 app_context_cache[current_context] = it->second;
645 memcpy(&app_context_vtable_cache[current_context],
646 static_cast<void*>(it->second), sizeof(void*));
649 current_context = 0;
650 for (URLRequestContextMap::const_iterator it =
651 isolated_media_request_context_map_.begin();
652 current_context < kMaxCachedContexts &&
653 it != isolated_media_request_context_map_.end();
654 ++it, ++current_context) {
655 media_context_cache[current_context] = it->second;
656 memcpy(&media_context_vtable_cache[current_context],
657 static_cast<void*>(it->second), sizeof(void*));
660 // Destroy certificate_report_sender_ before main_request_context_,
661 // since the former has a reference to the latter.
662 if (transport_security_state_)
663 transport_security_state_->SetReportSender(nullptr);
664 certificate_report_sender_.reset();
666 // TODO(ajwong): These AssertNoURLRequests() calls are unnecessary since they
667 // are already done in the URLRequestContext destructor.
668 if (main_request_context_)
669 main_request_context_->AssertNoURLRequests();
670 if (extensions_request_context_)
671 extensions_request_context_->AssertNoURLRequests();
673 current_context = 0;
674 for (URLRequestContextMap::iterator it = app_request_context_map_.begin();
675 it != app_request_context_map_.end(); ++it) {
676 if (current_context < kMaxCachedContexts) {
677 CHECK_EQ(app_context_cache[current_context], it->second);
678 memcpy(&tmp_vtable, static_cast<void*>(it->second), sizeof(void*));
679 CHECK_EQ(app_context_vtable_cache[current_context], tmp_vtable);
681 it->second->AssertNoURLRequests();
682 delete it->second;
683 current_context++;
686 current_context = 0;
687 for (URLRequestContextMap::iterator it =
688 isolated_media_request_context_map_.begin();
689 it != isolated_media_request_context_map_.end(); ++it) {
690 if (current_context < kMaxCachedContexts) {
691 CHECK_EQ(media_context_cache[current_context], it->second);
692 memcpy(&tmp_vtable, static_cast<void*>(it->second), sizeof(void*));
693 CHECK_EQ(media_context_vtable_cache[current_context], tmp_vtable);
695 it->second->AssertNoURLRequests();
696 delete it->second;
697 current_context++;
701 // static
702 ProfileIOData* ProfileIOData::FromResourceContext(
703 content::ResourceContext* rc) {
704 return (static_cast<ResourceContext*>(rc))->io_data_;
707 // static
708 bool ProfileIOData::IsHandledProtocol(const std::string& scheme) {
709 DCHECK_EQ(scheme, base::ToLowerASCII(scheme));
710 static const char* const kProtocolList[] = {
711 url::kFileScheme,
712 content::kChromeDevToolsScheme,
713 dom_distiller::kDomDistillerScheme,
714 #if defined(ENABLE_EXTENSIONS)
715 extensions::kExtensionScheme,
716 extensions::kExtensionResourceScheme,
717 #endif
718 content::kChromeUIScheme,
719 url::kDataScheme,
720 #if defined(OS_CHROMEOS)
721 content::kExternalFileScheme,
722 #endif // defined(OS_CHROMEOS)
723 url::kAboutScheme,
724 #if !defined(DISABLE_FTP_SUPPORT)
725 url::kFtpScheme,
726 #endif // !defined(DISABLE_FTP_SUPPORT)
727 url::kBlobScheme,
728 url::kFileSystemScheme,
729 chrome::kChromeSearchScheme,
731 for (size_t i = 0; i < arraysize(kProtocolList); ++i) {
732 if (scheme == kProtocolList[i])
733 return true;
735 return net::URLRequest::IsHandledProtocol(scheme);
738 // static
739 bool ProfileIOData::IsHandledURL(const GURL& url) {
740 if (!url.is_valid()) {
741 // We handle error cases.
742 return true;
745 return IsHandledProtocol(url.scheme());
748 // static
749 void ProfileIOData::InstallProtocolHandlers(
750 net::URLRequestJobFactoryImpl* job_factory,
751 content::ProtocolHandlerMap* protocol_handlers) {
752 for (content::ProtocolHandlerMap::iterator it =
753 protocol_handlers->begin();
754 it != protocol_handlers->end();
755 ++it) {
756 bool set_protocol = job_factory->SetProtocolHandler(
757 it->first, make_scoped_ptr(it->second.release()));
758 DCHECK(set_protocol);
760 protocol_handlers->clear();
763 // static
764 void ProfileIOData::SetCertVerifierForTesting(
765 net::CertVerifier* cert_verifier) {
766 g_cert_verifier_for_testing = cert_verifier;
769 content::ResourceContext* ProfileIOData::GetResourceContext() const {
770 return resource_context_.get();
773 net::URLRequestContext* ProfileIOData::GetMainRequestContext() const {
774 DCHECK(initialized_);
775 return main_request_context_.get();
778 net::URLRequestContext* ProfileIOData::GetMediaRequestContext() const {
779 DCHECK(initialized_);
780 net::URLRequestContext* context = AcquireMediaRequestContext();
781 DCHECK(context);
782 return context;
785 net::URLRequestContext* ProfileIOData::GetExtensionsRequestContext() const {
786 DCHECK(initialized_);
787 return extensions_request_context_.get();
790 net::URLRequestContext* ProfileIOData::GetIsolatedAppRequestContext(
791 net::URLRequestContext* main_context,
792 const StoragePartitionDescriptor& partition_descriptor,
793 scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
794 protocol_handler_interceptor,
795 content::ProtocolHandlerMap* protocol_handlers,
796 content::URLRequestInterceptorScopedVector request_interceptors) const {
797 DCHECK(initialized_);
798 net::URLRequestContext* context = NULL;
799 if (ContainsKey(app_request_context_map_, partition_descriptor)) {
800 context = app_request_context_map_[partition_descriptor];
801 } else {
802 context =
803 AcquireIsolatedAppRequestContext(main_context,
804 partition_descriptor,
805 protocol_handler_interceptor.Pass(),
806 protocol_handlers,
807 request_interceptors.Pass());
808 app_request_context_map_[partition_descriptor] = context;
810 DCHECK(context);
811 return context;
814 net::URLRequestContext* ProfileIOData::GetIsolatedMediaRequestContext(
815 net::URLRequestContext* app_context,
816 const StoragePartitionDescriptor& partition_descriptor) const {
817 DCHECK(initialized_);
818 net::URLRequestContext* context = NULL;
819 if (ContainsKey(isolated_media_request_context_map_, partition_descriptor)) {
820 context = isolated_media_request_context_map_[partition_descriptor];
821 } else {
822 context = AcquireIsolatedMediaRequestContext(app_context,
823 partition_descriptor);
824 isolated_media_request_context_map_[partition_descriptor] = context;
826 DCHECK(context);
827 return context;
830 extensions::InfoMap* ProfileIOData::GetExtensionInfoMap() const {
831 DCHECK(initialized_) << "ExtensionSystem not initialized";
832 #if defined(ENABLE_EXTENSIONS)
833 return extension_info_map_.get();
834 #else
835 return nullptr;
836 #endif
839 extensions::ExtensionThrottleManager*
840 ProfileIOData::GetExtensionThrottleManager() const {
841 DCHECK(initialized_) << "ExtensionSystem not initialized";
842 #if defined(ENABLE_EXTENSIONS)
843 return extension_throttle_manager_.get();
844 #else
845 return nullptr;
846 #endif
849 content_settings::CookieSettings* ProfileIOData::GetCookieSettings() const {
850 // Allow either Init() or SetCookieSettingsForTesting() to initialize.
851 DCHECK(initialized_ || cookie_settings_.get());
852 return cookie_settings_.get();
855 HostContentSettingsMap* ProfileIOData::GetHostContentSettingsMap() const {
856 DCHECK(initialized_);
857 return host_content_settings_map_.get();
860 ResourceContext::SaltCallback ProfileIOData::GetMediaDeviceIDSalt() const {
861 return base::Bind(&MediaDeviceIDSalt::GetSalt, media_device_id_salt_);
864 bool ProfileIOData::IsOffTheRecord() const {
865 return profile_type() == Profile::INCOGNITO_PROFILE
866 || profile_type() == Profile::GUEST_PROFILE;
869 void ProfileIOData::InitializeMetricsEnabledStateOnUIThread() {
870 DCHECK_CURRENTLY_ON(BrowserThread::UI);
871 #if defined(OS_CHROMEOS)
872 // Just fetch the value from ChromeOS' settings while we're on the UI thread.
873 // TODO(stevet): For now, this value is only set on profile initialization.
874 // We will want to do something similar to the PrefMember method below in the
875 // future to more accurately capture this state.
876 chromeos::CrosSettings::Get()->GetBoolean(chromeos::kStatsReportingPref,
877 &enable_metrics_);
878 #elif defined(OS_ANDROID)
879 // TODO(dwkang): rename or unify the pref for UMA once we have conclusion
880 // in crbugs.com/246495.
881 // Android has it's own preferences for metrics / crash uploading.
882 enable_metrics_.Init(prefs::kCrashReportingEnabled,
883 g_browser_process->local_state());
884 enable_metrics_.MoveToThread(
885 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
886 #else
887 // Prep the PrefMember and send it to the IO thread, since this value will be
888 // read from there.
889 enable_metrics_.Init(prefs::kMetricsReportingEnabled,
890 g_browser_process->local_state());
891 enable_metrics_.MoveToThread(
892 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
893 #endif // defined(OS_CHROMEOS)
896 bool ProfileIOData::GetMetricsEnabledStateOnIOThread() const {
897 DCHECK_CURRENTLY_ON(BrowserThread::IO);
898 #if defined(OS_CHROMEOS)
899 return enable_metrics_;
900 #else
901 return enable_metrics_.GetValue();
902 #endif // defined(OS_CHROMEOS)
905 bool ProfileIOData::IsDataReductionProxyEnabled() const {
906 return data_reduction_proxy_io_data() &&
907 data_reduction_proxy_io_data()->IsEnabled();
910 void ProfileIOData::set_data_reduction_proxy_io_data(
911 scoped_ptr<data_reduction_proxy::DataReductionProxyIOData>
912 data_reduction_proxy_io_data) const {
913 data_reduction_proxy_io_data_ = data_reduction_proxy_io_data.Pass();
916 base::WeakPtr<net::HttpServerProperties>
917 ProfileIOData::http_server_properties() const {
918 return http_server_properties_->GetWeakPtr();
921 void ProfileIOData::set_http_server_properties(
922 scoped_ptr<net::HttpServerProperties> http_server_properties) const {
923 http_server_properties_ = http_server_properties.Pass();
926 ProfileIOData::ResourceContext::ResourceContext(ProfileIOData* io_data)
927 : io_data_(io_data),
928 host_resolver_(NULL),
929 request_context_(NULL) {
930 DCHECK(io_data);
933 ProfileIOData::ResourceContext::~ResourceContext() {}
935 net::HostResolver* ProfileIOData::ResourceContext::GetHostResolver() {
936 DCHECK_CURRENTLY_ON(BrowserThread::IO);
937 DCHECK(io_data_->initialized_);
938 return host_resolver_;
941 net::URLRequestContext* ProfileIOData::ResourceContext::GetRequestContext() {
942 DCHECK_CURRENTLY_ON(BrowserThread::IO);
943 DCHECK(io_data_->initialized_);
944 return request_context_;
947 scoped_ptr<net::ClientCertStore>
948 ProfileIOData::ResourceContext::CreateClientCertStore() {
949 if (!io_data_->client_cert_store_factory_.is_null())
950 return io_data_->client_cert_store_factory_.Run();
951 #if defined(OS_CHROMEOS)
952 return scoped_ptr<net::ClientCertStore>(new chromeos::ClientCertStoreChromeOS(
953 io_data_->certificate_provider_->Copy(),
954 make_scoped_ptr(new chromeos::ClientCertFilterChromeOS(
955 io_data_->use_system_key_slot(), io_data_->username_hash())),
956 base::Bind(&CreateCryptoModuleBlockingPasswordDelegate,
957 chrome::kCryptoModulePasswordClientAuth)));
958 #elif defined(USE_NSS_CERTS)
959 return scoped_ptr<net::ClientCertStore>(new net::ClientCertStoreNSS(
960 base::Bind(&CreateCryptoModuleBlockingPasswordDelegate,
961 chrome::kCryptoModulePasswordClientAuth)));
962 #elif defined(OS_WIN)
963 return scoped_ptr<net::ClientCertStore>(new net::ClientCertStoreWin());
964 #elif defined(OS_MACOSX)
965 return scoped_ptr<net::ClientCertStore>(new net::ClientCertStoreMac());
966 #elif defined(OS_ANDROID)
967 // Android does not use the ClientCertStore infrastructure. On Android client
968 // cert matching is done by the OS as part of the call to show the cert
969 // selection dialog.
970 return nullptr;
971 #else
972 #error Unknown platform.
973 #endif
976 void ProfileIOData::ResourceContext::CreateKeygenHandler(
977 uint32 key_size_in_bits,
978 const std::string& challenge_string,
979 const GURL& url,
980 const base::Callback<void(scoped_ptr<net::KeygenHandler>)>& callback) {
981 DCHECK(!callback.is_null());
982 #if defined(USE_NSS_CERTS)
983 scoped_ptr<net::KeygenHandler> keygen_handler(
984 new net::KeygenHandler(key_size_in_bits, challenge_string, url));
986 base::Callback<void(scoped_ptr<ChromeNSSCryptoModuleDelegate>)>
987 got_delegate_callback = base::Bind(&InitializeAndPassKeygenHandler,
988 base::Passed(&keygen_handler),
989 callback);
991 ChromeNSSCryptoModuleDelegate::CreateForResourceContext(
992 chrome::kCryptoModulePasswordKeygen,
993 net::HostPortPair::FromURL(url),
994 this,
995 got_delegate_callback);
996 #else
997 callback.Run(make_scoped_ptr(
998 new net::KeygenHandler(key_size_in_bits, challenge_string, url)));
999 #endif
1002 ResourceContext::SaltCallback
1003 ProfileIOData::ResourceContext::GetMediaDeviceIDSalt() {
1004 return io_data_->GetMediaDeviceIDSalt();
1007 // static
1008 std::string ProfileIOData::GetSSLSessionCacheShard() {
1009 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1010 // The SSL session cache is partitioned by setting a string. This returns a
1011 // unique string to partition the SSL session cache. Each time we create a
1012 // new profile, we'll get a fresh SSL session cache which is separate from
1013 // the other profiles.
1014 static unsigned ssl_session_cache_instance = 0;
1015 return base::StringPrintf("profile/%u", ssl_session_cache_instance++);
1018 void ProfileIOData::Init(
1019 content::ProtocolHandlerMap* protocol_handlers,
1020 content::URLRequestInterceptorScopedVector request_interceptors) const {
1021 // The basic logic is implemented here. The specific initialization
1022 // is done in InitializeInternal(), implemented by subtypes. Static helper
1023 // functions have been provided to assist in common operations.
1024 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1025 DCHECK(!initialized_);
1027 // TODO(jhawkins): Remove once crbug.com/102004 is fixed.
1028 CHECK(initialized_on_UI_thread_);
1030 // TODO(jhawkins): Return to DCHECK once crbug.com/102004 is fixed.
1031 CHECK(profile_params_.get());
1033 IOThread* const io_thread = profile_params_->io_thread;
1034 IOThread::Globals* const io_thread_globals = io_thread->globals();
1035 const base::CommandLine& command_line =
1036 *base::CommandLine::ForCurrentProcess();
1038 // Create the common request contexts.
1039 main_request_context_.reset(new net::URLRequestContext());
1040 extensions_request_context_.reset(new net::URLRequestContext());
1042 scoped_ptr<ChromeNetworkDelegate> network_delegate(
1043 new ChromeNetworkDelegate(
1044 #if defined(ENABLE_EXTENSIONS)
1045 io_thread_globals->extension_event_router_forwarder.get(),
1046 #else
1047 NULL,
1048 #endif
1049 &enable_referrers_));
1050 #if defined(ENABLE_EXTENSIONS)
1051 network_delegate->set_extension_info_map(
1052 profile_params_->extension_info_map.get());
1053 if (!command_line.HasSwitch(switches::kDisableExtensionsHttpThrottling)) {
1054 extension_throttle_manager_.reset(
1055 new extensions::ExtensionThrottleManager());
1057 #endif
1059 #if defined(ENABLE_CONFIGURATION_POLICY)
1060 network_delegate->set_url_blacklist_manager(url_blacklist_manager_.get());
1061 #endif
1062 network_delegate->set_profile(profile_params_->profile);
1063 network_delegate->set_profile_path(profile_params_->path);
1064 network_delegate->set_cookie_settings(profile_params_->cookie_settings.get());
1065 network_delegate->set_enable_do_not_track(&enable_do_not_track_);
1066 network_delegate->set_force_google_safe_search(&force_google_safesearch_);
1067 network_delegate->set_force_youtube_safety_mode(&force_youtube_safety_mode_);
1069 // NOTE: Proxy service uses the default io thread network delegate, not the
1070 // delegate just created.
1071 proxy_service_.reset(
1072 ProxyServiceFactory::CreateProxyService(
1073 io_thread->net_log(),
1074 io_thread_globals->proxy_script_fetcher_context.get(),
1075 io_thread_globals->system_network_delegate.get(),
1076 profile_params_->proxy_config_service.release(),
1077 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 params.socket_performance_watcher_factory =
1318 io_thread->globals()->network_quality_estimator.get();
1319 if (data_reduction_proxy_io_data_.get())
1320 params.proxy_delegate = data_reduction_proxy_io_data_->proxy_delegate();
1322 net::HttpNetworkSession* session = new net::HttpNetworkSession(params);
1323 return scoped_ptr<net::HttpCache>(new net::HttpCache(
1324 new DevToolsNetworkTransactionFactory(
1325 network_controller_handle_.GetController(), session),
1326 context->net_log(), main_backend));
1329 scoped_ptr<net::HttpCache> ProfileIOData::CreateHttpFactory(
1330 net::HttpNetworkSession* shared_session,
1331 net::HttpCache::BackendFactory* backend) const {
1332 return scoped_ptr<net::HttpCache>(new net::HttpCache(
1333 new DevToolsNetworkTransactionFactory(
1334 network_controller_handle_.GetController(), shared_session),
1335 shared_session->net_log(), backend));
1338 void ProfileIOData::SetCookieSettingsForTesting(
1339 content_settings::CookieSettings* cookie_settings) {
1340 DCHECK(!cookie_settings_.get());
1341 cookie_settings_ = cookie_settings;