Add ENABLE_MEDIA_ROUTER define to builds other than Android and iOS.
[chromium-blink-merge.git] / chrome / browser / profiles / profile_io_data.cc
blob8457344dfe9036313e06de4c6e95ecebdc19a02c
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/profiler/scoped_tracker.h"
20 #include "base/stl_util.h"
21 #include "base/strings/string_number_conversions.h"
22 #include "base/strings/string_util.h"
23 #include "base/strings/stringprintf.h"
24 #include "base/thread_task_runner_handle.h"
25 #include "base/threading/sequenced_worker_pool.h"
26 #include "chrome/browser/browser_process.h"
27 #include "chrome/browser/chrome_notification_types.h"
28 #include "chrome/browser/content_settings/cookie_settings.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/about_protocol_handler.h"
38 #include "chrome/browser/net/chrome_fraudulent_certificate_reporter.h"
39 #include "chrome/browser/net/chrome_http_user_agent_settings.h"
40 #include "chrome/browser/net/chrome_net_log.h"
41 #include "chrome/browser/net/chrome_network_delegate.h"
42 #include "chrome/browser/net/chrome_url_request_context_getter.h"
43 #include "chrome/browser/net/cookie_store_util.h"
44 #include "chrome/browser/net/proxy_service_factory.h"
45 #include "chrome/browser/net/resource_prefetch_predictor_observer.h"
46 #include "chrome/browser/predictors/resource_prefetch_predictor.h"
47 #include "chrome/browser/predictors/resource_prefetch_predictor_factory.h"
48 #include "chrome/browser/profiles/profile.h"
49 #include "chrome/browser/profiles/profile_manager.h"
50 #include "chrome/browser/signin/signin_names_io_thread.h"
51 #include "chrome/browser/ui/search/new_tab_page_interceptor_service.h"
52 #include "chrome/browser/ui/search/new_tab_page_interceptor_service_factory.h"
53 #include "chrome/common/chrome_paths.h"
54 #include "chrome/common/chrome_switches.h"
55 #include "chrome/common/pref_names.h"
56 #include "chrome/common/url_constants.h"
57 #include "components/content_settings/core/browser/content_settings_provider.h"
58 #include "components/content_settings/core/browser/host_content_settings_map.h"
59 #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_io_data.h"
60 #include "components/dom_distiller/core/url_constants.h"
61 #include "components/startup_metric_utils/startup_metric_utils.h"
62 #include "components/sync_driver/pref_names.h"
63 #include "components/url_fixer/url_fixer.h"
64 #include "content/public/browser/browser_thread.h"
65 #include "content/public/browser/host_zoom_map.h"
66 #include "content/public/browser/notification_service.h"
67 #include "content/public/browser/resource_context.h"
68 #include "net/base/keygen_handler.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/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_file_job.h"
84 #include "net/url_request/url_request_intercepting_job_factory.h"
85 #include "net/url_request/url_request_interceptor.h"
86 #include "net/url_request/url_request_job_factory_impl.h"
88 #if defined(ENABLE_CONFIGURATION_POLICY)
89 #include "chrome/browser/policy/cloud/policy_header_service_factory.h"
90 #include "chrome/browser/policy/policy_helpers.h"
91 #include "components/policy/core/browser/url_blacklist_manager.h"
92 #include "components/policy/core/common/cloud/policy_header_io_helper.h"
93 #include "components/policy/core/common/cloud/policy_header_service.h"
94 #include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
95 #endif
97 #if defined(ENABLE_EXTENSIONS)
98 #include "chrome/browser/extensions/extension_resource_protocols.h"
99 #include "extensions/browser/extension_protocols.h"
100 #include "extensions/browser/extension_system.h"
101 #include "extensions/browser/info_map.h"
102 #include "extensions/common/constants.h"
103 #endif
105 #if defined(ENABLE_SUPERVISED_USERS)
106 #include "chrome/browser/supervised_user/supervised_user_service.h"
107 #include "chrome/browser/supervised_user/supervised_user_service_factory.h"
108 #include "chrome/browser/supervised_user/supervised_user_url_filter.h"
109 #endif
111 #if defined(OS_ANDROID)
112 #include "content/public/browser/android/content_protocol_handler.h"
113 #endif // defined(OS_ANDROID)
115 #if defined(OS_CHROMEOS)
116 #include "chrome/browser/chromeos/fileapi/external_file_protocol_handler.h"
117 #include "chrome/browser/chromeos/login/startup_utils.h"
118 #include "chrome/browser/chromeos/net/cert_verify_proc_chromeos.h"
119 #include "chrome/browser/chromeos/net/client_cert_filter_chromeos.h"
120 #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
121 #include "chrome/browser/chromeos/policy/policy_cert_service.h"
122 #include "chrome/browser/chromeos/policy/policy_cert_service_factory.h"
123 #include "chrome/browser/chromeos/policy/policy_cert_verifier.h"
124 #include "chrome/browser/chromeos/profiles/profile_helper.h"
125 #include "chrome/browser/chromeos/settings/cros_settings.h"
126 #include "chrome/browser/net/nss_context.h"
127 #include "chromeos/dbus/dbus_thread_manager.h"
128 #include "chromeos/settings/cros_settings_names.h"
129 #include "chromeos/tpm/tpm_token_info_getter.h"
130 #include "components/user_manager/user.h"
131 #include "components/user_manager/user_manager.h"
132 #include "crypto/nss_util.h"
133 #include "crypto/nss_util_internal.h"
134 #include "net/cert/cert_verifier.h"
135 #include "net/cert/multi_threaded_cert_verifier.h"
136 #include "net/ssl/client_cert_store_chromeos.h"
137 #endif // defined(OS_CHROMEOS)
139 #if defined(USE_NSS)
140 #include "chrome/browser/ui/crypto_module_delegate_nss.h"
141 #include "net/ssl/client_cert_store_nss.h"
142 #endif
144 #if defined(OS_WIN)
145 #include "net/ssl/client_cert_store_win.h"
146 #endif
148 #if defined(OS_MACOSX)
149 #include "net/ssl/client_cert_store_mac.h"
150 #endif
152 using content::BrowserContext;
153 using content::BrowserThread;
154 using content::ResourceContext;
156 namespace {
158 #if defined(DEBUG_DEVTOOLS)
159 bool IsSupportedDevToolsURL(const GURL& url, base::FilePath* path) {
160 std::string bundled_path_prefix(chrome::kChromeUIDevToolsBundledPath);
161 bundled_path_prefix = "/" + bundled_path_prefix + "/";
163 if (!url.SchemeIs(content::kChromeDevToolsScheme) ||
164 url.host() != chrome::kChromeUIDevToolsHost ||
165 !StartsWithASCII(url.path(), bundled_path_prefix, false)) {
166 return false;
169 if (!url.is_valid()) {
170 NOTREACHED();
171 return false;
174 // Remove Query and Ref from URL.
175 GURL stripped_url;
176 GURL::Replacements replacements;
177 replacements.ClearQuery();
178 replacements.ClearRef();
179 stripped_url = url.ReplaceComponents(replacements);
181 std::string relative_path;
182 const std::string& spec = stripped_url.possibly_invalid_spec();
183 const url::Parsed& parsed = stripped_url.parsed_for_possibly_invalid_spec();
184 int offset = parsed.CountCharactersBefore(url::Parsed::PATH, false);
185 if (offset < static_cast<int>(spec.size()))
186 relative_path.assign(spec.substr(offset + bundled_path_prefix.length()));
188 // Check that |relative_path| is not an absolute path (otherwise
189 // AppendASCII() will DCHECK). The awkward use of StringType is because on
190 // some systems FilePath expects a std::string, but on others a std::wstring.
191 base::FilePath p(
192 base::FilePath::StringType(relative_path.begin(), relative_path.end()));
193 if (p.IsAbsolute())
194 return false;
196 base::FilePath inspector_dir;
197 if (!PathService::Get(chrome::DIR_INSPECTOR, &inspector_dir))
198 return false;
200 if (inspector_dir.empty())
201 return false;
203 *path = inspector_dir.AppendASCII(relative_path);
204 return true;
207 class DebugDevToolsInterceptor : public net::URLRequestInterceptor {
208 public:
209 // net::URLRequestInterceptor implementation.
210 net::URLRequestJob* MaybeInterceptRequest(
211 net::URLRequest* request,
212 net::NetworkDelegate* network_delegate) const override {
213 base::FilePath path;
214 if (IsSupportedDevToolsURL(request->url(), &path))
215 return new net::URLRequestFileJob(
216 request, network_delegate, path,
217 content::BrowserThread::GetBlockingPool()->
218 GetTaskRunnerWithShutdownBehavior(
219 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN));
221 return NULL;
224 #endif // defined(DEBUG_DEVTOOLS)
226 #if defined(OS_CHROMEOS)
227 // The following four functions are responsible for initializing NSS for each
228 // profile on ChromeOS, which has a separate NSS database and TPM slot
229 // per-profile.
231 // Initialization basically follows these steps:
232 // 1) Get some info from user_manager::UserManager about the User for this
233 // profile.
234 // 2) Tell nss_util to initialize the software slot for this profile.
235 // 3) Wait for the TPM module to be loaded by nss_util if it isn't already.
236 // 4) Ask CryptohomeClient which TPM slot id corresponds to this profile.
237 // 5) Tell nss_util to use that slot id on the TPM module.
239 // Some of these steps must happen on the UI thread, others must happen on the
240 // IO thread:
241 // UI thread IO Thread
243 // ProfileIOData::InitializeOnUIThread
244 // |
245 // ProfileHelper::Get()->GetUserByProfile()
246 // \---------------------------------------v
247 // StartNSSInitOnIOThread
248 // |
249 // crypto::InitializeNSSForChromeOSUser
250 // |
251 // crypto::IsTPMTokenReady
252 // |
253 // StartTPMSlotInitializationOnIOThread
254 // v---------------------------------------/
255 // GetTPMInfoForUserOnUIThread
256 // |
257 // chromeos::TPMTokenInfoGetter::Start
258 // |
259 // DidGetTPMInfoForUserOnUIThread
260 // \---------------------------------------v
261 // crypto::InitializeTPMForChromeOSUser
263 void DidGetTPMInfoForUserOnUIThread(
264 scoped_ptr<chromeos::TPMTokenInfoGetter> getter,
265 const std::string& username_hash,
266 const chromeos::TPMTokenInfo& info) {
267 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
268 if (info.tpm_is_enabled && info.token_slot_id != -1) {
269 DVLOG(1) << "Got TPM slot for " << username_hash << ": "
270 << info.token_slot_id;
271 BrowserThread::PostTask(
272 BrowserThread::IO,
273 FROM_HERE,
274 base::Bind(&crypto::InitializeTPMForChromeOSUser,
275 username_hash, info.token_slot_id));
276 } else {
277 NOTREACHED() << "TPMTokenInfoGetter reported invalid token.";
281 void GetTPMInfoForUserOnUIThread(const std::string& username,
282 const std::string& username_hash) {
283 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
284 DVLOG(1) << "Getting TPM info from cryptohome for "
285 << " " << username << " " << username_hash;
286 scoped_ptr<chromeos::TPMTokenInfoGetter> scoped_token_info_getter =
287 chromeos::TPMTokenInfoGetter::CreateForUserToken(
288 username,
289 chromeos::DBusThreadManager::Get()->GetCryptohomeClient(),
290 base::ThreadTaskRunnerHandle::Get());
291 chromeos::TPMTokenInfoGetter* token_info_getter =
292 scoped_token_info_getter.get();
294 // Bind |token_info_getter| to the callback to ensure it does not go away
295 // before TPM token info is fetched.
296 // TODO(tbarzic, pneubeck): Handle this in a nicer way when this logic is
297 // moved to a separate profile service.
298 token_info_getter->Start(
299 base::Bind(&DidGetTPMInfoForUserOnUIThread,
300 base::Passed(&scoped_token_info_getter),
301 username_hash));
304 void StartTPMSlotInitializationOnIOThread(const std::string& username,
305 const std::string& username_hash) {
306 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
308 BrowserThread::PostTask(
309 BrowserThread::UI,
310 FROM_HERE,
311 base::Bind(&GetTPMInfoForUserOnUIThread, username, username_hash));
314 void StartNSSInitOnIOThread(const std::string& username,
315 const std::string& username_hash,
316 const base::FilePath& path) {
317 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
318 DVLOG(1) << "Starting NSS init for " << username
319 << " hash:" << username_hash;
321 // Make sure NSS is initialized for the user.
322 crypto::InitializeNSSForChromeOSUser(username_hash, path);
324 // Check if it's OK to initialize TPM for the user before continuing. This
325 // may not be the case if the TPM slot initialization was previously
326 // requested for the same user.
327 if (!crypto::ShouldInitializeTPMForChromeOSUser(username_hash))
328 return;
330 crypto::WillInitializeTPMForChromeOSUser(username_hash);
332 if (crypto::IsTPMTokenEnabledForNSS()) {
333 if (crypto::IsTPMTokenReady(base::Bind(
334 &StartTPMSlotInitializationOnIOThread, username, username_hash))) {
335 StartTPMSlotInitializationOnIOThread(username, username_hash);
336 } else {
337 DVLOG(1) << "Waiting for tpm ready ...";
339 } else {
340 crypto::InitializePrivateSoftwareSlotForChromeOSUser(username_hash);
343 #endif // defined(OS_CHROMEOS)
345 #if defined(USE_NSS)
346 void InitializeAndPassKeygenHandler(
347 scoped_ptr<net::KeygenHandler> keygen_handler,
348 const base::Callback<void(scoped_ptr<net::KeygenHandler>)>& callback,
349 scoped_ptr<ChromeNSSCryptoModuleDelegate> delegate) {
350 if (delegate)
351 keygen_handler->set_crypto_module_delegate(delegate.Pass());
352 callback.Run(keygen_handler.Pass());
354 #endif // defined(USE_NSS)
356 void InvalidateContextGettersOnIO(
357 scoped_ptr<ProfileIOData::ChromeURLRequestContextGetterVector> getters) {
358 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
359 ProfileIOData::ChromeURLRequestContextGetterVector::iterator iter;
360 for (iter = getters->begin(); iter != getters->end(); ++iter)
361 (*iter)->Invalidate();
364 } // namespace
366 void ProfileIOData::InitializeOnUIThread(Profile* profile) {
367 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
368 PrefService* pref_service = profile->GetPrefs();
369 PrefService* local_state_pref_service = g_browser_process->local_state();
371 scoped_ptr<ProfileParams> params(new ProfileParams);
372 params->path = profile->GetPath();
374 params->io_thread = g_browser_process->io_thread();
376 params->cookie_settings = CookieSettings::Factory::GetForProfile(profile);
377 params->host_content_settings_map = profile->GetHostContentSettingsMap();
378 params->ssl_config_service = profile->GetSSLConfigService();
379 params->cookie_monster_delegate =
380 chrome_browser_net::CreateCookieDelegate(profile);
381 #if defined(ENABLE_EXTENSIONS)
382 params->extension_info_map =
383 extensions::ExtensionSystem::Get(profile)->info_map();
384 #endif
386 if (predictors::ResourcePrefetchPredictor* predictor =
387 predictors::ResourcePrefetchPredictorFactory::GetForProfile(
388 profile)) {
389 resource_prefetch_predictor_observer_.reset(
390 new chrome_browser_net::ResourcePrefetchPredictorObserver(predictor));
393 ProtocolHandlerRegistry* protocol_handler_registry =
394 ProtocolHandlerRegistryFactory::GetForBrowserContext(profile);
395 DCHECK(protocol_handler_registry);
397 // The profile instance is only available here in the InitializeOnUIThread
398 // method, so we create the url job factory here, then save it for
399 // later delivery to the job factory in Init().
400 params->protocol_handler_interceptor =
401 protocol_handler_registry->CreateJobInterceptorFactory();
403 NewTabPageInterceptorService* new_tab_interceptor_service =
404 NewTabPageInterceptorServiceFactory::GetForProfile(profile);
405 if (new_tab_interceptor_service) {
406 params->new_tab_page_interceptor =
407 new_tab_interceptor_service->CreateInterceptor();
410 params->proxy_config_service
411 .reset(ProxyServiceFactory::CreateProxyConfigService(
412 profile->GetProxyConfigTracker()));
413 #if defined(ENABLE_SUPERVISED_USERS)
414 SupervisedUserService* supervised_user_service =
415 SupervisedUserServiceFactory::GetForProfile(profile);
416 params->supervised_user_url_filter =
417 supervised_user_service->GetURLFilterForIOThread();
418 #endif
419 #if defined(OS_CHROMEOS)
420 user_manager::UserManager* user_manager = user_manager::UserManager::Get();
421 if (user_manager) {
422 const user_manager::User* user =
423 chromeos::ProfileHelper::Get()->GetUserByProfile(profile);
424 // No need to initialize NSS for users with empty username hash:
425 // Getters for a user's NSS slots always return NULL slot if the user's
426 // username hash is empty, even when the NSS is not initialized for the
427 // user.
428 if (user && !user->username_hash().empty()) {
429 params->username_hash = user->username_hash();
430 DCHECK(!params->username_hash.empty());
431 BrowserThread::PostTask(BrowserThread::IO,
432 FROM_HERE,
433 base::Bind(&StartNSSInitOnIOThread,
434 user->email(),
435 user->username_hash(),
436 profile->GetPath()));
438 // Use the device-wide system key slot only if the user is of the same
439 // domain as the device is registered to.
440 policy::BrowserPolicyConnectorChromeOS* connector =
441 g_browser_process->platform_part()
442 ->browser_policy_connector_chromeos();
443 params->use_system_key_slot =
444 connector->GetUserAffiliation(user->email()) ==
445 policy::USER_AFFILIATION_MANAGED;
448 #endif
450 params->profile = profile;
451 profile_params_.reset(params.release());
453 ChromeNetworkDelegate::InitializePrefsOnUIThread(
454 &enable_referrers_,
455 &enable_do_not_track_,
456 &force_safesearch_,
457 &force_google_safesearch_,
458 &force_youtube_safety_mode_,
459 pref_service);
461 scoped_refptr<base::MessageLoopProxy> io_message_loop_proxy =
462 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
464 chrome_http_user_agent_settings_.reset(
465 new ChromeHttpUserAgentSettings(pref_service));
467 // These members are used only for one click sign in, which is not enabled
468 // in incognito mode. So no need to initialize them.
469 if (!IsOffTheRecord()) {
470 signin_names_.reset(new SigninNamesOnIOThread());
472 google_services_user_account_id_.Init(
473 prefs::kGoogleServicesUserAccountId, pref_service);
474 google_services_user_account_id_.MoveToThread(io_message_loop_proxy);
476 sync_disabled_.Init(sync_driver::prefs::kSyncManaged, pref_service);
477 sync_disabled_.MoveToThread(io_message_loop_proxy);
479 signin_allowed_.Init(prefs::kSigninAllowed, pref_service);
480 signin_allowed_.MoveToThread(io_message_loop_proxy);
483 quick_check_enabled_.Init(prefs::kQuickCheckEnabled,
484 local_state_pref_service);
485 quick_check_enabled_.MoveToThread(io_message_loop_proxy);
487 media_device_id_salt_ = new MediaDeviceIDSalt(pref_service, IsOffTheRecord());
489 network_prediction_options_.Init(prefs::kNetworkPredictionOptions,
490 pref_service);
492 network_prediction_options_.MoveToThread(io_message_loop_proxy);
494 #if defined(OS_CHROMEOS)
495 scoped_ptr<policy::PolicyCertVerifier> verifier =
496 policy::PolicyCertServiceFactory::CreateForProfile(profile);
497 policy_cert_verifier_ = verifier.get();
498 cert_verifier_ = verifier.Pass();
499 #endif
500 // The URLBlacklistManager has to be created on the UI thread to register
501 // observers of |pref_service|, and it also has to clean up on
502 // ShutdownOnUIThread to release these observers on the right thread.
503 // Don't pass it in |profile_params_| to make sure it is correctly cleaned up,
504 // in particular when this ProfileIOData isn't |initialized_| during deletion.
505 #if defined(ENABLE_CONFIGURATION_POLICY)
506 policy::URLBlacklist::SegmentURLCallback callback =
507 static_cast<policy::URLBlacklist::SegmentURLCallback>(
508 url_fixer::SegmentURL);
509 base::SequencedWorkerPool* pool = BrowserThread::GetBlockingPool();
510 scoped_refptr<base::SequencedTaskRunner> background_task_runner =
511 pool->GetSequencedTaskRunner(pool->GetSequenceToken());
512 url_blacklist_manager_.reset(
513 new policy::URLBlacklistManager(
514 pref_service,
515 background_task_runner,
516 io_message_loop_proxy,
517 callback,
518 base::Bind(policy::OverrideBlacklistForURL)));
520 if (!IsOffTheRecord()) {
521 // Add policy headers for non-incognito requests.
522 policy::PolicyHeaderService* policy_header_service =
523 policy::PolicyHeaderServiceFactory::GetForBrowserContext(profile);
524 if (policy_header_service) {
525 policy_header_helper_ = policy_header_service->CreatePolicyHeaderIOHelper(
526 io_message_loop_proxy);
529 #endif
531 incognito_availibility_pref_.Init(
532 prefs::kIncognitoModeAvailability, pref_service);
533 incognito_availibility_pref_.MoveToThread(io_message_loop_proxy);
535 initialized_on_UI_thread_ = true;
537 // We need to make sure that content initializes its own data structures that
538 // are associated with each ResourceContext because we might post this
539 // object to the IO thread after this function.
540 BrowserContext::EnsureResourceContextInitialized(profile);
543 ProfileIOData::MediaRequestContext::MediaRequestContext() {
546 void ProfileIOData::MediaRequestContext::SetHttpTransactionFactory(
547 scoped_ptr<net::HttpTransactionFactory> http_factory) {
548 http_factory_ = http_factory.Pass();
549 set_http_transaction_factory(http_factory_.get());
552 ProfileIOData::MediaRequestContext::~MediaRequestContext() {
553 AssertNoURLRequests();
556 ProfileIOData::AppRequestContext::AppRequestContext() {
559 void ProfileIOData::AppRequestContext::SetCookieStore(
560 net::CookieStore* cookie_store) {
561 cookie_store_ = cookie_store;
562 set_cookie_store(cookie_store);
565 void ProfileIOData::AppRequestContext::SetHttpTransactionFactory(
566 scoped_ptr<net::HttpTransactionFactory> http_factory) {
567 http_factory_ = http_factory.Pass();
568 set_http_transaction_factory(http_factory_.get());
571 void ProfileIOData::AppRequestContext::SetJobFactory(
572 scoped_ptr<net::URLRequestJobFactory> job_factory) {
573 job_factory_ = job_factory.Pass();
574 set_job_factory(job_factory_.get());
577 ProfileIOData::AppRequestContext::~AppRequestContext() {
578 AssertNoURLRequests();
581 ProfileIOData::ProfileParams::ProfileParams()
582 : io_thread(NULL),
583 #if defined(OS_CHROMEOS)
584 use_system_key_slot(false),
585 #endif
586 profile(NULL) {
589 ProfileIOData::ProfileParams::~ProfileParams() {}
591 ProfileIOData::ProfileIOData(Profile::ProfileType profile_type)
592 : initialized_(false),
593 #if defined(OS_CHROMEOS)
594 policy_cert_verifier_(NULL),
595 use_system_key_slot_(false),
596 #endif
597 resource_context_(new ResourceContext(this)),
598 initialized_on_UI_thread_(false),
599 profile_type_(profile_type) {
600 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
603 ProfileIOData::~ProfileIOData() {
604 if (BrowserThread::IsMessageLoopValid(BrowserThread::IO))
605 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
607 // Pull the contents of the request context maps onto the stack for sanity
608 // checking of values in a minidump. http://crbug.com/260425
609 size_t num_app_contexts = app_request_context_map_.size();
610 size_t num_media_contexts = isolated_media_request_context_map_.size();
611 size_t current_context = 0;
612 static const size_t kMaxCachedContexts = 20;
613 net::URLRequestContext* app_context_cache[kMaxCachedContexts] = {0};
614 void* app_context_vtable_cache[kMaxCachedContexts] = {0};
615 net::URLRequestContext* media_context_cache[kMaxCachedContexts] = {0};
616 void* media_context_vtable_cache[kMaxCachedContexts] = {0};
617 void* tmp_vtable = NULL;
618 base::debug::Alias(&num_app_contexts);
619 base::debug::Alias(&num_media_contexts);
620 base::debug::Alias(&current_context);
621 base::debug::Alias(app_context_cache);
622 base::debug::Alias(app_context_vtable_cache);
623 base::debug::Alias(media_context_cache);
624 base::debug::Alias(media_context_vtable_cache);
625 base::debug::Alias(&tmp_vtable);
627 current_context = 0;
628 for (URLRequestContextMap::const_iterator it =
629 app_request_context_map_.begin();
630 current_context < kMaxCachedContexts &&
631 it != app_request_context_map_.end();
632 ++it, ++current_context) {
633 app_context_cache[current_context] = it->second;
634 memcpy(&app_context_vtable_cache[current_context],
635 static_cast<void*>(it->second), sizeof(void*));
638 current_context = 0;
639 for (URLRequestContextMap::const_iterator it =
640 isolated_media_request_context_map_.begin();
641 current_context < kMaxCachedContexts &&
642 it != isolated_media_request_context_map_.end();
643 ++it, ++current_context) {
644 media_context_cache[current_context] = it->second;
645 memcpy(&media_context_vtable_cache[current_context],
646 static_cast<void*>(it->second), sizeof(void*));
649 // TODO(ajwong): These AssertNoURLRequests() calls are unnecessary since they
650 // are already done in the URLRequestContext destructor.
651 if (main_request_context_)
652 main_request_context_->AssertNoURLRequests();
653 if (extensions_request_context_)
654 extensions_request_context_->AssertNoURLRequests();
656 current_context = 0;
657 for (URLRequestContextMap::iterator it = app_request_context_map_.begin();
658 it != app_request_context_map_.end(); ++it) {
659 if (current_context < kMaxCachedContexts) {
660 CHECK_EQ(app_context_cache[current_context], it->second);
661 memcpy(&tmp_vtable, static_cast<void*>(it->second), sizeof(void*));
662 CHECK_EQ(app_context_vtable_cache[current_context], tmp_vtable);
664 it->second->AssertNoURLRequests();
665 delete it->second;
666 current_context++;
669 current_context = 0;
670 for (URLRequestContextMap::iterator it =
671 isolated_media_request_context_map_.begin();
672 it != isolated_media_request_context_map_.end(); ++it) {
673 if (current_context < kMaxCachedContexts) {
674 CHECK_EQ(media_context_cache[current_context], it->second);
675 memcpy(&tmp_vtable, static_cast<void*>(it->second), sizeof(void*));
676 CHECK_EQ(media_context_vtable_cache[current_context], tmp_vtable);
678 it->second->AssertNoURLRequests();
679 delete it->second;
680 current_context++;
684 // static
685 ProfileIOData* ProfileIOData::FromResourceContext(
686 content::ResourceContext* rc) {
687 return (static_cast<ResourceContext*>(rc))->io_data_;
690 // static
691 bool ProfileIOData::IsHandledProtocol(const std::string& scheme) {
692 DCHECK_EQ(scheme, base::StringToLowerASCII(scheme));
693 static const char* const kProtocolList[] = {
694 url::kFileScheme,
695 content::kChromeDevToolsScheme,
696 dom_distiller::kDomDistillerScheme,
697 #if defined(ENABLE_EXTENSIONS)
698 extensions::kExtensionScheme,
699 extensions::kExtensionResourceScheme,
700 #endif
701 content::kChromeUIScheme,
702 url::kDataScheme,
703 #if defined(OS_CHROMEOS)
704 content::kExternalFileScheme,
705 #endif // defined(OS_CHROMEOS)
706 url::kAboutScheme,
707 #if !defined(DISABLE_FTP_SUPPORT)
708 url::kFtpScheme,
709 #endif // !defined(DISABLE_FTP_SUPPORT)
710 url::kBlobScheme,
711 url::kFileSystemScheme,
712 chrome::kChromeSearchScheme,
714 for (size_t i = 0; i < arraysize(kProtocolList); ++i) {
715 if (scheme == kProtocolList[i])
716 return true;
718 return net::URLRequest::IsHandledProtocol(scheme);
721 // static
722 bool ProfileIOData::IsHandledURL(const GURL& url) {
723 if (!url.is_valid()) {
724 // We handle error cases.
725 return true;
728 return IsHandledProtocol(url.scheme());
731 // static
732 void ProfileIOData::InstallProtocolHandlers(
733 net::URLRequestJobFactoryImpl* job_factory,
734 content::ProtocolHandlerMap* protocol_handlers) {
735 for (content::ProtocolHandlerMap::iterator it =
736 protocol_handlers->begin();
737 it != protocol_handlers->end();
738 ++it) {
739 bool set_protocol = job_factory->SetProtocolHandler(
740 it->first, it->second.release());
741 DCHECK(set_protocol);
743 protocol_handlers->clear();
746 content::ResourceContext* ProfileIOData::GetResourceContext() const {
747 return resource_context_.get();
750 net::URLRequestContext* ProfileIOData::GetMainRequestContext() const {
751 DCHECK(initialized_);
752 return main_request_context_.get();
755 net::URLRequestContext* ProfileIOData::GetMediaRequestContext() const {
756 DCHECK(initialized_);
757 net::URLRequestContext* context = AcquireMediaRequestContext();
758 DCHECK(context);
759 return context;
762 net::URLRequestContext* ProfileIOData::GetExtensionsRequestContext() const {
763 DCHECK(initialized_);
764 return extensions_request_context_.get();
767 net::URLRequestContext* ProfileIOData::GetIsolatedAppRequestContext(
768 net::URLRequestContext* main_context,
769 const StoragePartitionDescriptor& partition_descriptor,
770 scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
771 protocol_handler_interceptor,
772 content::ProtocolHandlerMap* protocol_handlers,
773 content::URLRequestInterceptorScopedVector request_interceptors) const {
774 DCHECK(initialized_);
775 net::URLRequestContext* context = NULL;
776 if (ContainsKey(app_request_context_map_, partition_descriptor)) {
777 context = app_request_context_map_[partition_descriptor];
778 } else {
779 context =
780 AcquireIsolatedAppRequestContext(main_context,
781 partition_descriptor,
782 protocol_handler_interceptor.Pass(),
783 protocol_handlers,
784 request_interceptors.Pass());
785 app_request_context_map_[partition_descriptor] = context;
787 DCHECK(context);
788 return context;
791 net::URLRequestContext* ProfileIOData::GetIsolatedMediaRequestContext(
792 net::URLRequestContext* app_context,
793 const StoragePartitionDescriptor& partition_descriptor) const {
794 DCHECK(initialized_);
795 net::URLRequestContext* context = NULL;
796 if (ContainsKey(isolated_media_request_context_map_, partition_descriptor)) {
797 context = isolated_media_request_context_map_[partition_descriptor];
798 } else {
799 context = AcquireIsolatedMediaRequestContext(app_context,
800 partition_descriptor);
801 isolated_media_request_context_map_[partition_descriptor] = context;
803 DCHECK(context);
804 return context;
807 extensions::InfoMap* ProfileIOData::GetExtensionInfoMap() const {
808 DCHECK(initialized_) << "ExtensionSystem not initialized";
809 #if defined(ENABLE_EXTENSIONS)
810 return extension_info_map_.get();
811 #else
812 return NULL;
813 #endif
816 CookieSettings* ProfileIOData::GetCookieSettings() const {
817 // Allow either Init() or SetCookieSettingsForTesting() to initialize.
818 DCHECK(initialized_ || cookie_settings_.get());
819 return cookie_settings_.get();
822 HostContentSettingsMap* ProfileIOData::GetHostContentSettingsMap() const {
823 DCHECK(initialized_);
824 return host_content_settings_map_.get();
827 ResourceContext::SaltCallback ProfileIOData::GetMediaDeviceIDSalt() const {
828 return base::Bind(&MediaDeviceIDSalt::GetSalt, media_device_id_salt_);
831 bool ProfileIOData::IsOffTheRecord() const {
832 return profile_type() == Profile::INCOGNITO_PROFILE
833 || profile_type() == Profile::GUEST_PROFILE;
836 void ProfileIOData::InitializeMetricsEnabledStateOnUIThread() {
837 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
838 #if defined(OS_CHROMEOS)
839 // Just fetch the value from ChromeOS' settings while we're on the UI thread.
840 // TODO(stevet): For now, this value is only set on profile initialization.
841 // We will want to do something similar to the PrefMember method below in the
842 // future to more accurately capture this state.
843 chromeos::CrosSettings::Get()->GetBoolean(chromeos::kStatsReportingPref,
844 &enable_metrics_);
845 #elif defined(OS_ANDROID)
846 // TODO(dwkang): rename or unify the pref for UMA once we have conclusion
847 // in crbugs.com/246495.
848 // Android has it's own preferences for metrics / crash uploading.
849 enable_metrics_.Init(prefs::kCrashReportingEnabled,
850 g_browser_process->local_state());
851 enable_metrics_.MoveToThread(
852 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
853 #else
854 // Prep the PrefMember and send it to the IO thread, since this value will be
855 // read from there.
856 enable_metrics_.Init(prefs::kMetricsReportingEnabled,
857 g_browser_process->local_state());
858 enable_metrics_.MoveToThread(
859 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
860 #endif // defined(OS_CHROMEOS)
863 bool ProfileIOData::GetMetricsEnabledStateOnIOThread() const {
864 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
865 #if defined(OS_CHROMEOS)
866 return enable_metrics_;
867 #else
868 return enable_metrics_.GetValue();
869 #endif // defined(OS_CHROMEOS)
872 bool ProfileIOData::IsDataReductionProxyEnabled() const {
873 return data_reduction_proxy_io_data()->IsEnabled();
876 void ProfileIOData::set_data_reduction_proxy_io_data(
877 scoped_ptr<data_reduction_proxy::DataReductionProxyIOData>
878 data_reduction_proxy_io_data) const {
879 data_reduction_proxy_io_data_ = data_reduction_proxy_io_data.Pass();
882 base::WeakPtr<net::HttpServerProperties>
883 ProfileIOData::http_server_properties() const {
884 return http_server_properties_->GetWeakPtr();
887 void ProfileIOData::set_http_server_properties(
888 scoped_ptr<net::HttpServerProperties> http_server_properties) const {
889 http_server_properties_ = http_server_properties.Pass();
892 ProfileIOData::ResourceContext::ResourceContext(ProfileIOData* io_data)
893 : io_data_(io_data),
894 host_resolver_(NULL),
895 request_context_(NULL) {
896 DCHECK(io_data);
899 ProfileIOData::ResourceContext::~ResourceContext() {}
901 net::HostResolver* ProfileIOData::ResourceContext::GetHostResolver() {
902 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
903 DCHECK(io_data_->initialized_);
904 return host_resolver_;
907 net::URLRequestContext* ProfileIOData::ResourceContext::GetRequestContext() {
908 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
909 DCHECK(io_data_->initialized_);
910 return request_context_;
913 scoped_ptr<net::ClientCertStore>
914 ProfileIOData::ResourceContext::CreateClientCertStore() {
915 if (!io_data_->client_cert_store_factory_.is_null())
916 return io_data_->client_cert_store_factory_.Run();
917 #if defined(OS_CHROMEOS)
918 return scoped_ptr<net::ClientCertStore>(new net::ClientCertStoreChromeOS(
919 make_scoped_ptr(new chromeos::ClientCertFilterChromeOS(
920 io_data_->use_system_key_slot(), io_data_->username_hash())),
921 base::Bind(&CreateCryptoModuleBlockingPasswordDelegate,
922 chrome::kCryptoModulePasswordClientAuth)));
923 #elif defined(USE_NSS)
924 return scoped_ptr<net::ClientCertStore>(new net::ClientCertStoreNSS(
925 base::Bind(&CreateCryptoModuleBlockingPasswordDelegate,
926 chrome::kCryptoModulePasswordClientAuth)));
927 #elif defined(OS_WIN)
928 return scoped_ptr<net::ClientCertStore>(new net::ClientCertStoreWin());
929 #elif defined(OS_MACOSX)
930 return scoped_ptr<net::ClientCertStore>(new net::ClientCertStoreMac());
931 #elif defined(USE_OPENSSL)
932 // OpenSSL does not use the ClientCertStore infrastructure. On Android client
933 // cert matching is done by the OS as part of the call to show the cert
934 // selection dialog.
935 return scoped_ptr<net::ClientCertStore>();
936 #else
937 #error Unknown platform.
938 #endif
941 void ProfileIOData::ResourceContext::CreateKeygenHandler(
942 uint32 key_size_in_bits,
943 const std::string& challenge_string,
944 const GURL& url,
945 const base::Callback<void(scoped_ptr<net::KeygenHandler>)>& callback) {
946 DCHECK(!callback.is_null());
947 #if defined(USE_NSS)
948 scoped_ptr<net::KeygenHandler> keygen_handler(
949 new net::KeygenHandler(key_size_in_bits, challenge_string, url));
951 base::Callback<void(scoped_ptr<ChromeNSSCryptoModuleDelegate>)>
952 got_delegate_callback = base::Bind(&InitializeAndPassKeygenHandler,
953 base::Passed(&keygen_handler),
954 callback);
956 ChromeNSSCryptoModuleDelegate::CreateForResourceContext(
957 chrome::kCryptoModulePasswordKeygen,
958 net::HostPortPair::FromURL(url),
959 this,
960 got_delegate_callback);
961 #else
962 callback.Run(make_scoped_ptr(
963 new net::KeygenHandler(key_size_in_bits, challenge_string, url)));
964 #endif
967 ResourceContext::SaltCallback
968 ProfileIOData::ResourceContext::GetMediaDeviceIDSalt() {
969 return io_data_->GetMediaDeviceIDSalt();
972 // static
973 std::string ProfileIOData::GetSSLSessionCacheShard() {
974 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
975 // The SSL session cache is partitioned by setting a string. This returns a
976 // unique string to partition the SSL session cache. Each time we create a
977 // new profile, we'll get a fresh SSL session cache which is separate from
978 // the other profiles.
979 static unsigned ssl_session_cache_instance = 0;
980 return base::StringPrintf("profile/%u", ssl_session_cache_instance++);
983 void ProfileIOData::Init(
984 content::ProtocolHandlerMap* protocol_handlers,
985 content::URLRequestInterceptorScopedVector request_interceptors) const {
986 // TODO(vadimt): Remove ScopedTracker below once crbug.com/436671 is fixed.
987 tracked_objects::ScopedTracker tracking_profile(
988 FROM_HERE_WITH_EXPLICIT_FUNCTION("436671 ProfileIOData::Init"));
990 // The basic logic is implemented here. The specific initialization
991 // is done in InitializeInternal(), implemented by subtypes. Static helper
992 // functions have been provided to assist in common operations.
993 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
994 DCHECK(!initialized_);
996 startup_metric_utils::ScopedSlowStartupUMA
997 scoped_timer("Startup.SlowStartupProfileIODataInit");
999 // TODO(jhawkins): Remove once crbug.com/102004 is fixed.
1000 CHECK(initialized_on_UI_thread_);
1002 // TODO(jhawkins): Return to DCHECK once crbug.com/102004 is fixed.
1003 CHECK(profile_params_.get());
1005 IOThread* const io_thread = profile_params_->io_thread;
1006 IOThread::Globals* const io_thread_globals = io_thread->globals();
1007 const base::CommandLine& command_line =
1008 *base::CommandLine::ForCurrentProcess();
1010 // TODO(vadimt): Remove ScopedTracker below once crbug.com/436671 is fixed.
1011 tracked_objects::ScopedTracker tracking_profile1(
1012 FROM_HERE_WITH_EXPLICIT_FUNCTION("436671 ProfileIOData::Init1"));
1014 // Create the common request contexts.
1015 main_request_context_.reset(new net::URLRequestContext());
1016 extensions_request_context_.reset(new net::URLRequestContext());
1018 // TODO(vadimt): Remove ScopedTracker below once crbug.com/436671 is fixed.
1019 tracked_objects::ScopedTracker tracking_profile2(
1020 FROM_HERE_WITH_EXPLICIT_FUNCTION("436671 ProfileIOData::Init2"));
1022 scoped_ptr<ChromeNetworkDelegate> network_delegate(
1023 new ChromeNetworkDelegate(
1024 #if defined(ENABLE_EXTENSIONS)
1025 io_thread_globals->extension_event_router_forwarder.get(),
1026 #else
1027 NULL,
1028 #endif
1029 &enable_referrers_));
1030 #if defined(ENABLE_EXTENSIONS)
1031 network_delegate->set_extension_info_map(
1032 profile_params_->extension_info_map.get());
1033 #endif
1034 #if defined(ENABLE_CONFIGURATION_POLICY)
1035 network_delegate->set_url_blacklist_manager(url_blacklist_manager_.get());
1036 #endif
1037 network_delegate->set_profile(profile_params_->profile);
1038 network_delegate->set_profile_path(profile_params_->path);
1039 network_delegate->set_cookie_settings(profile_params_->cookie_settings.get());
1040 network_delegate->set_enable_do_not_track(&enable_do_not_track_);
1041 network_delegate->set_force_safe_search(&force_safesearch_);
1042 network_delegate->set_force_google_safe_search(&force_google_safesearch_);
1043 network_delegate->set_force_youtube_safety_mode(&force_youtube_safety_mode_);
1044 fraudulent_certificate_reporter_.reset(
1045 new chrome_browser_net::ChromeFraudulentCertificateReporter(
1046 main_request_context_.get()));
1048 // TODO(vadimt): Remove ScopedTracker below once crbug.com/436671 is fixed.
1049 tracked_objects::ScopedTracker tracking_profile3(
1050 FROM_HERE_WITH_EXPLICIT_FUNCTION("436671 ProfileIOData::Init3"));
1052 // NOTE: Proxy service uses the default io thread network delegate, not the
1053 // delegate just created.
1054 proxy_service_.reset(
1055 ProxyServiceFactory::CreateProxyService(
1056 io_thread->net_log(),
1057 io_thread_globals->proxy_script_fetcher_context.get(),
1058 io_thread_globals->system_network_delegate.get(),
1059 profile_params_->proxy_config_service.release(),
1060 command_line,
1061 quick_check_enabled_.GetValue()));
1062 transport_security_state_.reset(new net::TransportSecurityState());
1063 transport_security_persister_.reset(
1064 new net::TransportSecurityPersister(
1065 transport_security_state_.get(),
1066 profile_params_->path,
1067 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE),
1068 IsOffTheRecord()));
1070 // TODO(vadimt): Remove ScopedTracker below once crbug.com/436671 is fixed.
1071 tracked_objects::ScopedTracker tracking_profile4(
1072 FROM_HERE_WITH_EXPLICIT_FUNCTION("436671 ProfileIOData::Init4"));
1074 // Take ownership over these parameters.
1075 cookie_settings_ = profile_params_->cookie_settings;
1076 host_content_settings_map_ = profile_params_->host_content_settings_map;
1077 #if defined(ENABLE_EXTENSIONS)
1078 extension_info_map_ = profile_params_->extension_info_map;
1079 #endif
1081 resource_context_->host_resolver_ = io_thread_globals->host_resolver.get();
1082 resource_context_->request_context_ = main_request_context_.get();
1084 if (profile_params_->resource_prefetch_predictor_observer_) {
1085 resource_prefetch_predictor_observer_.reset(
1086 profile_params_->resource_prefetch_predictor_observer_.release());
1089 #if defined(ENABLE_SUPERVISED_USERS)
1090 supervised_user_url_filter_ = profile_params_->supervised_user_url_filter;
1091 #endif
1093 #if defined(OS_CHROMEOS)
1094 username_hash_ = profile_params_->username_hash;
1095 use_system_key_slot_ = profile_params_->use_system_key_slot;
1096 if (use_system_key_slot_)
1097 EnableNSSSystemKeySlotForResourceContext(resource_context_.get());
1099 crypto::ScopedPK11Slot public_slot =
1100 crypto::GetPublicSlotForChromeOSUser(username_hash_);
1101 // The private slot won't be ready by this point. It shouldn't be necessary
1102 // for cert trust purposes anyway.
1103 scoped_refptr<net::CertVerifyProc> verify_proc(
1104 new chromeos::CertVerifyProcChromeOS(public_slot.Pass()));
1105 if (policy_cert_verifier_) {
1106 DCHECK_EQ(policy_cert_verifier_, cert_verifier_.get());
1107 policy_cert_verifier_->InitializeOnIOThread(verify_proc);
1108 } else {
1109 cert_verifier_.reset(new net::MultiThreadedCertVerifier(verify_proc.get()));
1111 main_request_context_->set_cert_verifier(cert_verifier_.get());
1112 #else
1113 main_request_context_->set_cert_verifier(
1114 io_thread_globals->cert_verifier.get());
1115 #endif
1117 // TODO(vadimt): Remove ScopedTracker below once crbug.com/436671 is fixed.
1118 tracked_objects::ScopedTracker tracking_profile5(
1119 FROM_HERE_WITH_EXPLICIT_FUNCTION("436671 ProfileIOData::Init5"));
1121 // Install the New Tab Page Interceptor.
1122 if (profile_params_->new_tab_page_interceptor.get()) {
1123 request_interceptors.push_back(
1124 profile_params_->new_tab_page_interceptor.release());
1127 InitializeInternal(
1128 network_delegate.Pass(), profile_params_.get(),
1129 protocol_handlers, request_interceptors.Pass());
1131 profile_params_.reset();
1132 initialized_ = true;
1135 void ProfileIOData::ApplyProfileParamsToContext(
1136 net::URLRequestContext* context) const {
1137 context->set_http_user_agent_settings(
1138 chrome_http_user_agent_settings_.get());
1139 context->set_ssl_config_service(profile_params_->ssl_config_service.get());
1142 scoped_ptr<net::URLRequestJobFactory> ProfileIOData::SetUpJobFactoryDefaults(
1143 scoped_ptr<net::URLRequestJobFactoryImpl> job_factory,
1144 content::URLRequestInterceptorScopedVector request_interceptors,
1145 scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
1146 protocol_handler_interceptor,
1147 net::NetworkDelegate* network_delegate,
1148 net::FtpTransactionFactory* ftp_transaction_factory) const {
1149 // NOTE(willchan): Keep these protocol handlers in sync with
1150 // ProfileIOData::IsHandledProtocol().
1151 bool set_protocol = job_factory->SetProtocolHandler(
1152 url::kFileScheme,
1153 new net::FileProtocolHandler(
1154 content::BrowserThread::GetBlockingPool()->
1155 GetTaskRunnerWithShutdownBehavior(
1156 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)));
1157 DCHECK(set_protocol);
1159 #if defined(ENABLE_EXTENSIONS)
1160 DCHECK(extension_info_map_.get());
1161 // Check only for incognito (and not Chrome OS guest mode GUEST_PROFILE).
1162 bool is_incognito = profile_type() == Profile::INCOGNITO_PROFILE;
1163 set_protocol = job_factory->SetProtocolHandler(
1164 extensions::kExtensionScheme,
1165 extensions::CreateExtensionProtocolHandler(is_incognito,
1166 extension_info_map_.get()));
1167 DCHECK(set_protocol);
1168 set_protocol = job_factory->SetProtocolHandler(
1169 extensions::kExtensionResourceScheme,
1170 CreateExtensionResourceProtocolHandler());
1171 DCHECK(set_protocol);
1172 #endif
1173 set_protocol = job_factory->SetProtocolHandler(
1174 url::kDataScheme, new net::DataProtocolHandler());
1175 DCHECK(set_protocol);
1176 #if defined(OS_CHROMEOS)
1177 if (profile_params_) {
1178 set_protocol = job_factory->SetProtocolHandler(
1179 content::kExternalFileScheme,
1180 new chromeos::ExternalFileProtocolHandler(profile_params_->profile));
1181 DCHECK(set_protocol);
1183 #endif // defined(OS_CHROMEOS)
1184 #if defined(OS_ANDROID)
1185 set_protocol = job_factory->SetProtocolHandler(
1186 url::kContentScheme,
1187 content::ContentProtocolHandler::Create(
1188 content::BrowserThread::GetBlockingPool()->
1189 GetTaskRunnerWithShutdownBehavior(
1190 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)));
1191 #endif
1193 job_factory->SetProtocolHandler(
1194 url::kAboutScheme, new chrome_browser_net::AboutProtocolHandler());
1195 #if !defined(DISABLE_FTP_SUPPORT)
1196 DCHECK(ftp_transaction_factory);
1197 job_factory->SetProtocolHandler(
1198 url::kFtpScheme,
1199 new net::FtpProtocolHandler(ftp_transaction_factory));
1200 #endif // !defined(DISABLE_FTP_SUPPORT)
1202 #if defined(DEBUG_DEVTOOLS)
1203 request_interceptors.push_back(new DebugDevToolsInterceptor);
1204 #endif
1206 // Set up interceptors in the reverse order.
1207 scoped_ptr<net::URLRequestJobFactory> top_job_factory = job_factory.Pass();
1208 for (content::URLRequestInterceptorScopedVector::reverse_iterator i =
1209 request_interceptors.rbegin();
1210 i != request_interceptors.rend();
1211 ++i) {
1212 top_job_factory.reset(new net::URLRequestInterceptingJobFactory(
1213 top_job_factory.Pass(), make_scoped_ptr(*i)));
1215 request_interceptors.weak_clear();
1217 if (protocol_handler_interceptor) {
1218 protocol_handler_interceptor->Chain(top_job_factory.Pass());
1219 return protocol_handler_interceptor.Pass();
1220 } else {
1221 return top_job_factory.Pass();
1225 void ProfileIOData::ShutdownOnUIThread(
1226 scoped_ptr<ChromeURLRequestContextGetterVector> context_getters) {
1227 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1229 if (signin_names_)
1230 signin_names_->ReleaseResourcesOnUIThread();
1232 google_services_user_account_id_.Destroy();
1233 enable_referrers_.Destroy();
1234 enable_do_not_track_.Destroy();
1235 force_safesearch_.Destroy();
1236 force_google_safesearch_.Destroy();
1237 force_youtube_safety_mode_.Destroy();
1238 #if !defined(OS_CHROMEOS)
1239 enable_metrics_.Destroy();
1240 #endif
1241 safe_browsing_enabled_.Destroy();
1242 sync_disabled_.Destroy();
1243 signin_allowed_.Destroy();
1244 network_prediction_options_.Destroy();
1245 quick_check_enabled_.Destroy();
1246 if (media_device_id_salt_.get())
1247 media_device_id_salt_->ShutdownOnUIThread();
1248 session_startup_pref_.Destroy();
1249 #if defined(ENABLE_CONFIGURATION_POLICY)
1250 if (url_blacklist_manager_)
1251 url_blacklist_manager_->ShutdownOnUIThread();
1252 #endif
1253 if (chrome_http_user_agent_settings_)
1254 chrome_http_user_agent_settings_->CleanupOnUIThread();
1255 incognito_availibility_pref_.Destroy();
1257 if (!context_getters->empty()) {
1258 if (BrowserThread::IsMessageLoopValid(BrowserThread::IO)) {
1259 BrowserThread::PostTask(
1260 BrowserThread::IO, FROM_HERE,
1261 base::Bind(&InvalidateContextGettersOnIO,
1262 base::Passed(&context_getters)));
1266 bool posted = BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, this);
1267 if (!posted)
1268 delete this;
1271 void ProfileIOData::set_channel_id_service(
1272 net::ChannelIDService* channel_id_service) const {
1273 channel_id_service_.reset(channel_id_service);
1276 void ProfileIOData::DestroyResourceContext() {
1277 resource_context_.reset();
1280 scoped_ptr<net::HttpCache> ProfileIOData::CreateMainHttpFactory(
1281 const ProfileParams* profile_params,
1282 net::HttpCache::BackendFactory* main_backend) const {
1283 net::HttpNetworkSession::Params params;
1284 net::URLRequestContext* context = main_request_context();
1286 IOThread* const io_thread = profile_params->io_thread;
1288 io_thread->InitializeNetworkSessionParams(&params);
1290 params.host_resolver = context->host_resolver();
1291 params.cert_verifier = context->cert_verifier();
1292 params.channel_id_service = context->channel_id_service();
1293 params.transport_security_state = context->transport_security_state();
1294 params.cert_transparency_verifier = context->cert_transparency_verifier();
1295 params.proxy_service = context->proxy_service();
1296 params.ssl_session_cache_shard = GetSSLSessionCacheShard();
1297 params.ssl_config_service = context->ssl_config_service();
1298 params.http_auth_handler_factory = context->http_auth_handler_factory();
1299 params.network_delegate = context->network_delegate();
1300 params.http_server_properties = context->http_server_properties();
1301 params.net_log = context->net_log();
1302 if (data_reduction_proxy_io_data_.get())
1303 params.proxy_delegate = data_reduction_proxy_io_data_->proxy_delegate();
1305 network_controller_.reset(new DevToolsNetworkController());
1307 net::HttpNetworkSession* session = new net::HttpNetworkSession(params);
1308 return scoped_ptr<net::HttpCache>(new net::HttpCache(
1309 new DevToolsNetworkTransactionFactory(network_controller_.get(), session),
1310 context->net_log(), main_backend));
1313 scoped_ptr<net::HttpCache> ProfileIOData::CreateHttpFactory(
1314 net::HttpNetworkSession* shared_session,
1315 net::HttpCache::BackendFactory* backend) const {
1316 return scoped_ptr<net::HttpCache>(new net::HttpCache(
1317 new DevToolsNetworkTransactionFactory(
1318 network_controller_.get(), shared_session),
1319 shared_session->net_log(), backend));
1322 void ProfileIOData::SetCookieSettingsForTesting(
1323 CookieSettings* cookie_settings) {
1324 DCHECK(!cookie_settings_.get());
1325 cookie_settings_ = cookie_settings;
1328 void ProfileIOData::set_signin_names_for_testing(
1329 SigninNamesOnIOThread* signin_names) {
1330 signin_names_.reset(signin_names);