[sql] Remove _HAS_EXCEPTIONS=0 from build info.
[chromium-blink-merge.git] / chrome / browser / profiles / profile_io_data.cc
blobb8db2b3dba581c82a5f3ca06bfe3b16911fee276
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/about_protocol_handler.h"
37 #include "chrome/browser/net/chrome_http_user_agent_settings.h"
38 #include "chrome/browser/net/chrome_net_log.h"
39 #include "chrome/browser/net/chrome_network_delegate.h"
40 #include "chrome/browser/net/chrome_url_request_context_getter.h"
41 #include "chrome/browser/net/cookie_store_util.h"
42 #include "chrome/browser/net/proxy_service_factory.h"
43 #include "chrome/browser/net/resource_prefetch_predictor_observer.h"
44 #include "chrome/browser/predictors/resource_prefetch_predictor.h"
45 #include "chrome/browser/predictors/resource_prefetch_predictor_factory.h"
46 #include "chrome/browser/profiles/profile.h"
47 #include "chrome/browser/profiles/profile_manager.h"
48 #include "chrome/browser/ssl/chrome_fraudulent_certificate_reporter.h"
49 #include "chrome/browser/ui/search/new_tab_page_interceptor_service.h"
50 #include "chrome/browser/ui/search/new_tab_page_interceptor_service_factory.h"
51 #include "chrome/common/chrome_paths.h"
52 #include "chrome/common/chrome_switches.h"
53 #include "chrome/common/pref_names.h"
54 #include "chrome/common/url_constants.h"
55 #include "components/content_settings/core/browser/content_settings_provider.h"
56 #include "components/content_settings/core/browser/cookie_settings.h"
57 #include "components/content_settings/core/browser/host_content_settings_map.h"
58 #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_io_data.h"
59 #include "components/dom_distiller/core/url_constants.h"
60 #include "components/sync_driver/pref_names.h"
61 #include "components/url_fixer/url_fixer.h"
62 #include "content/public/browser/browser_thread.h"
63 #include "content/public/browser/host_zoom_map.h"
64 #include "content/public/browser/notification_service.h"
65 #include "content/public/browser/resource_context.h"
66 #include "net/base/keygen_handler.h"
67 #include "net/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_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_cookie_monster_delegate.h"
99 #include "chrome/browser/extensions/extension_resource_protocols.h"
100 #include "extensions/browser/extension_protocols.h"
101 #include "extensions/browser/extension_system.h"
102 #include "extensions/browser/extension_throttle_manager.h"
103 #include "extensions/browser/info_map.h"
104 #include "extensions/common/constants.h"
105 #endif
107 #if defined(ENABLE_SUPERVISED_USERS)
108 #include "chrome/browser/supervised_user/supervised_user_service.h"
109 #include "chrome/browser/supervised_user/supervised_user_service_factory.h"
110 #include "chrome/browser/supervised_user/supervised_user_url_filter.h"
111 #endif
113 #if defined(OS_ANDROID)
114 #include "content/public/browser/android/content_protocol_handler.h"
115 #endif // defined(OS_ANDROID)
117 #if defined(OS_CHROMEOS)
118 #include "chrome/browser/chromeos/fileapi/external_file_protocol_handler.h"
119 #include "chrome/browser/chromeos/login/startup_utils.h"
120 #include "chrome/browser/chromeos/net/cert_verify_proc_chromeos.h"
121 #include "chrome/browser/chromeos/net/client_cert_filter_chromeos.h"
122 #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
123 #include "chrome/browser/chromeos/policy/policy_cert_service.h"
124 #include "chrome/browser/chromeos/policy/policy_cert_service_factory.h"
125 #include "chrome/browser/chromeos/policy/policy_cert_verifier.h"
126 #include "chrome/browser/chromeos/profiles/profile_helper.h"
127 #include "chrome/browser/chromeos/settings/cros_settings.h"
128 #include "chrome/browser/net/nss_context.h"
129 #include "chromeos/dbus/dbus_thread_manager.h"
130 #include "chromeos/settings/cros_settings_names.h"
131 #include "chromeos/tpm/tpm_token_info_getter.h"
132 #include "components/user_manager/user.h"
133 #include "components/user_manager/user_manager.h"
134 #include "crypto/nss_util.h"
135 #include "crypto/nss_util_internal.h"
136 #include "net/cert/cert_verifier.h"
137 #include "net/cert/multi_threaded_cert_verifier.h"
138 #include "net/ssl/client_cert_store_chromeos.h"
139 #endif // defined(OS_CHROMEOS)
141 #if defined(USE_NSS_CERTS)
142 #include "chrome/browser/ui/crypto_module_delegate_nss.h"
143 #include "net/ssl/client_cert_store_nss.h"
144 #endif
146 #if defined(OS_WIN)
147 #include "net/ssl/client_cert_store_win.h"
148 #endif
150 #if defined(OS_MACOSX)
151 #include "net/ssl/client_cert_store_mac.h"
152 #endif
154 using content::BrowserContext;
155 using content::BrowserThread;
156 using content::ResourceContext;
158 namespace {
160 net::CertVerifier* g_cert_verifier_for_testing = nullptr;
162 #if defined(DEBUG_DEVTOOLS)
163 bool IsSupportedDevToolsURL(const GURL& url, base::FilePath* path) {
164 std::string bundled_path_prefix(chrome::kChromeUIDevToolsBundledPath);
165 bundled_path_prefix = "/" + bundled_path_prefix + "/";
167 if (!url.SchemeIs(content::kChromeDevToolsScheme) ||
168 url.host() != chrome::kChromeUIDevToolsHost ||
169 !base::StartsWith(url.path(), bundled_path_prefix,
170 base::CompareCase::INSENSITIVE_ASCII)) {
171 return false;
174 if (!url.is_valid()) {
175 NOTREACHED();
176 return false;
179 // Remove Query and Ref from URL.
180 GURL stripped_url;
181 GURL::Replacements replacements;
182 replacements.ClearQuery();
183 replacements.ClearRef();
184 stripped_url = url.ReplaceComponents(replacements);
186 std::string relative_path;
187 const std::string& spec = stripped_url.possibly_invalid_spec();
188 const url::Parsed& parsed = stripped_url.parsed_for_possibly_invalid_spec();
189 int offset = parsed.CountCharactersBefore(url::Parsed::PATH, false);
190 if (offset < static_cast<int>(spec.size()))
191 relative_path.assign(spec.substr(offset + bundled_path_prefix.length()));
193 // Check that |relative_path| is not an absolute path (otherwise
194 // AppendASCII() will DCHECK). The awkward use of StringType is because on
195 // some systems FilePath expects a std::string, but on others a std::wstring.
196 base::FilePath p(
197 base::FilePath::StringType(relative_path.begin(), relative_path.end()));
198 if (p.IsAbsolute())
199 return false;
201 base::FilePath inspector_dir;
202 if (!PathService::Get(chrome::DIR_INSPECTOR, &inspector_dir))
203 return false;
205 if (inspector_dir.empty())
206 return false;
208 *path = inspector_dir.AppendASCII(relative_path);
209 return true;
212 class DebugDevToolsInterceptor : public net::URLRequestInterceptor {
213 public:
214 // net::URLRequestInterceptor implementation.
215 net::URLRequestJob* MaybeInterceptRequest(
216 net::URLRequest* request,
217 net::NetworkDelegate* network_delegate) const override {
218 base::FilePath path;
219 if (IsSupportedDevToolsURL(request->url(), &path))
220 return new net::URLRequestFileJob(
221 request, network_delegate, path,
222 content::BrowserThread::GetBlockingPool()->
223 GetTaskRunnerWithShutdownBehavior(
224 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN));
226 return NULL;
229 #endif // defined(DEBUG_DEVTOOLS)
231 #if defined(OS_CHROMEOS)
232 // The following four functions are responsible for initializing NSS for each
233 // profile on ChromeOS, which has a separate NSS database and TPM slot
234 // per-profile.
236 // Initialization basically follows these steps:
237 // 1) Get some info from user_manager::UserManager about the User for this
238 // profile.
239 // 2) Tell nss_util to initialize the software slot for this profile.
240 // 3) Wait for the TPM module to be loaded by nss_util if it isn't already.
241 // 4) Ask CryptohomeClient which TPM slot id corresponds to this profile.
242 // 5) Tell nss_util to use that slot id on the TPM module.
244 // Some of these steps must happen on the UI thread, others must happen on the
245 // IO thread:
246 // UI thread IO Thread
248 // ProfileIOData::InitializeOnUIThread
249 // |
250 // ProfileHelper::Get()->GetUserByProfile()
251 // \---------------------------------------v
252 // StartNSSInitOnIOThread
253 // |
254 // crypto::InitializeNSSForChromeOSUser
255 // |
256 // crypto::IsTPMTokenReady
257 // |
258 // StartTPMSlotInitializationOnIOThread
259 // v---------------------------------------/
260 // GetTPMInfoForUserOnUIThread
261 // |
262 // chromeos::TPMTokenInfoGetter::Start
263 // |
264 // DidGetTPMInfoForUserOnUIThread
265 // \---------------------------------------v
266 // crypto::InitializeTPMForChromeOSUser
268 void DidGetTPMInfoForUserOnUIThread(
269 scoped_ptr<chromeos::TPMTokenInfoGetter> getter,
270 const std::string& username_hash,
271 const chromeos::TPMTokenInfo& info) {
272 DCHECK_CURRENTLY_ON(BrowserThread::UI);
273 if (info.tpm_is_enabled && info.token_slot_id != -1) {
274 DVLOG(1) << "Got TPM slot for " << username_hash << ": "
275 << info.token_slot_id;
276 BrowserThread::PostTask(
277 BrowserThread::IO,
278 FROM_HERE,
279 base::Bind(&crypto::InitializeTPMForChromeOSUser,
280 username_hash, info.token_slot_id));
281 } else {
282 NOTREACHED() << "TPMTokenInfoGetter reported invalid token.";
286 void GetTPMInfoForUserOnUIThread(const std::string& username,
287 const std::string& username_hash) {
288 DCHECK_CURRENTLY_ON(BrowserThread::UI);
289 DVLOG(1) << "Getting TPM info from cryptohome for "
290 << " " << username << " " << username_hash;
291 scoped_ptr<chromeos::TPMTokenInfoGetter> scoped_token_info_getter =
292 chromeos::TPMTokenInfoGetter::CreateForUserToken(
293 username,
294 chromeos::DBusThreadManager::Get()->GetCryptohomeClient(),
295 base::ThreadTaskRunnerHandle::Get());
296 chromeos::TPMTokenInfoGetter* token_info_getter =
297 scoped_token_info_getter.get();
299 // Bind |token_info_getter| to the callback to ensure it does not go away
300 // before TPM token info is fetched.
301 // TODO(tbarzic, pneubeck): Handle this in a nicer way when this logic is
302 // moved to a separate profile service.
303 token_info_getter->Start(
304 base::Bind(&DidGetTPMInfoForUserOnUIThread,
305 base::Passed(&scoped_token_info_getter),
306 username_hash));
309 void StartTPMSlotInitializationOnIOThread(const std::string& username,
310 const std::string& username_hash) {
311 DCHECK_CURRENTLY_ON(BrowserThread::IO);
313 BrowserThread::PostTask(
314 BrowserThread::UI,
315 FROM_HERE,
316 base::Bind(&GetTPMInfoForUserOnUIThread, username, username_hash));
319 void StartNSSInitOnIOThread(const std::string& username,
320 const std::string& username_hash,
321 const base::FilePath& path) {
322 DCHECK_CURRENTLY_ON(BrowserThread::IO);
323 DVLOG(1) << "Starting NSS init for " << username
324 << " hash:" << username_hash;
326 // Make sure NSS is initialized for the user.
327 crypto::InitializeNSSForChromeOSUser(username_hash, path);
329 // Check if it's OK to initialize TPM for the user before continuing. This
330 // may not be the case if the TPM slot initialization was previously
331 // requested for the same user.
332 if (!crypto::ShouldInitializeTPMForChromeOSUser(username_hash))
333 return;
335 crypto::WillInitializeTPMForChromeOSUser(username_hash);
337 if (crypto::IsTPMTokenEnabledForNSS()) {
338 if (crypto::IsTPMTokenReady(base::Bind(
339 &StartTPMSlotInitializationOnIOThread, username, username_hash))) {
340 StartTPMSlotInitializationOnIOThread(username, username_hash);
341 } else {
342 DVLOG(1) << "Waiting for tpm ready ...";
344 } else {
345 crypto::InitializePrivateSoftwareSlotForChromeOSUser(username_hash);
348 #endif // defined(OS_CHROMEOS)
350 #if defined(USE_NSS_CERTS)
351 void InitializeAndPassKeygenHandler(
352 scoped_ptr<net::KeygenHandler> keygen_handler,
353 const base::Callback<void(scoped_ptr<net::KeygenHandler>)>& callback,
354 scoped_ptr<ChromeNSSCryptoModuleDelegate> delegate) {
355 if (delegate)
356 keygen_handler->set_crypto_module_delegate(delegate.Pass());
357 callback.Run(keygen_handler.Pass());
359 #endif // defined(USE_NSS_CERTS)
361 // For safe shutdown, must be called before the ProfileIOData is destroyed.
362 void NotifyContextGettersOfShutdownOnIO(
363 scoped_ptr<ProfileIOData::ChromeURLRequestContextGetterVector> getters) {
364 DCHECK_CURRENTLY_ON(BrowserThread::IO);
365 ProfileIOData::ChromeURLRequestContextGetterVector::iterator iter;
366 for (auto& chrome_context_getter : *getters)
367 chrome_context_getter->NotifyContextShuttingDown();
370 } // namespace
372 void ProfileIOData::InitializeOnUIThread(Profile* profile) {
373 DCHECK_CURRENTLY_ON(BrowserThread::UI);
374 PrefService* pref_service = profile->GetPrefs();
375 PrefService* local_state_pref_service = g_browser_process->local_state();
377 scoped_ptr<ProfileParams> params(new ProfileParams);
378 params->path = profile->GetPath();
380 params->io_thread = g_browser_process->io_thread();
382 params->cookie_settings = CookieSettingsFactory::GetForProfile(profile);
383 params->host_content_settings_map = profile->GetHostContentSettingsMap();
384 params->ssl_config_service = profile->GetSSLConfigService();
386 scoped_refptr<net::CookieMonsterDelegate> next_cookie_monster_delegate;
387 #if defined(ENABLE_EXTENSIONS)
388 params->extension_info_map =
389 extensions::ExtensionSystem::Get(profile)->info_map();
390 next_cookie_monster_delegate = new ExtensionCookieMonsterDelegate(profile);
391 #endif
392 params->cookie_monster_delegate =
393 chrome_browser_net::CreateCookieDelegate(next_cookie_monster_delegate);
395 if (predictors::ResourcePrefetchPredictor* predictor =
396 predictors::ResourcePrefetchPredictorFactory::GetForProfile(
397 profile)) {
398 resource_prefetch_predictor_observer_.reset(
399 new chrome_browser_net::ResourcePrefetchPredictorObserver(predictor));
402 ProtocolHandlerRegistry* protocol_handler_registry =
403 ProtocolHandlerRegistryFactory::GetForBrowserContext(profile);
404 DCHECK(protocol_handler_registry);
406 // The profile instance is only available here in the InitializeOnUIThread
407 // method, so we create the url job factory here, then save it for
408 // later delivery to the job factory in Init().
409 params->protocol_handler_interceptor =
410 protocol_handler_registry->CreateJobInterceptorFactory();
412 NewTabPageInterceptorService* new_tab_interceptor_service =
413 NewTabPageInterceptorServiceFactory::GetForProfile(profile);
414 if (new_tab_interceptor_service) {
415 params->new_tab_page_interceptor =
416 new_tab_interceptor_service->CreateInterceptor();
419 params->proxy_config_service
420 .reset(ProxyServiceFactory::CreateProxyConfigService(
421 profile->GetProxyConfigTracker()));
422 #if defined(ENABLE_SUPERVISED_USERS)
423 SupervisedUserService* supervised_user_service =
424 SupervisedUserServiceFactory::GetForProfile(profile);
425 params->supervised_user_url_filter =
426 supervised_user_service->GetURLFilterForIOThread();
427 #endif
428 #if defined(OS_CHROMEOS)
429 user_manager::UserManager* user_manager = user_manager::UserManager::Get();
430 if (user_manager) {
431 const user_manager::User* user =
432 chromeos::ProfileHelper::Get()->GetUserByProfile(profile);
433 // No need to initialize NSS for users with empty username hash:
434 // Getters for a user's NSS slots always return NULL slot if the user's
435 // username hash is empty, even when the NSS is not initialized for the
436 // user.
437 if (user && !user->username_hash().empty()) {
438 params->username_hash = user->username_hash();
439 DCHECK(!params->username_hash.empty());
440 BrowserThread::PostTask(BrowserThread::IO,
441 FROM_HERE,
442 base::Bind(&StartNSSInitOnIOThread,
443 user->email(),
444 user->username_hash(),
445 profile->GetPath()));
447 // Use the device-wide system key slot only if the user is of the same
448 // domain as the device is registered to.
449 policy::BrowserPolicyConnectorChromeOS* connector =
450 g_browser_process->platform_part()
451 ->browser_policy_connector_chromeos();
452 params->use_system_key_slot =
453 connector->GetUserAffiliation(user->email()) ==
454 policy::USER_AFFILIATION_MANAGED;
457 #endif
459 params->profile = profile;
460 profile_params_.reset(params.release());
462 ChromeNetworkDelegate::InitializePrefsOnUIThread(
463 &enable_referrers_,
464 &enable_do_not_track_,
465 &force_google_safesearch_,
466 &force_youtube_safety_mode_,
467 pref_service);
469 scoped_refptr<base::SingleThreadTaskRunner> io_task_runner =
470 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
472 chrome_http_user_agent_settings_.reset(
473 new ChromeHttpUserAgentSettings(pref_service));
475 // These members are used only for sign in, which is not enabled
476 // in incognito mode. So no need to initialize them.
477 if (!IsOffTheRecord()) {
478 google_services_user_account_id_.Init(
479 prefs::kGoogleServicesUserAccountId, pref_service);
480 google_services_user_account_id_.MoveToThread(io_task_runner);
482 sync_disabled_.Init(sync_driver::prefs::kSyncManaged, pref_service);
483 sync_disabled_.MoveToThread(io_task_runner);
485 signin_allowed_.Init(prefs::kSigninAllowed, pref_service);
486 signin_allowed_.MoveToThread(io_task_runner);
489 quick_check_enabled_.Init(prefs::kQuickCheckEnabled,
490 local_state_pref_service);
491 quick_check_enabled_.MoveToThread(io_task_runner);
493 media_device_id_salt_ = new MediaDeviceIDSalt(pref_service, IsOffTheRecord());
495 network_prediction_options_.Init(prefs::kNetworkPredictionOptions,
496 pref_service);
498 network_prediction_options_.MoveToThread(io_task_runner);
500 #if defined(OS_CHROMEOS)
501 scoped_ptr<policy::PolicyCertVerifier> verifier =
502 policy::PolicyCertServiceFactory::CreateForProfile(profile);
503 policy_cert_verifier_ = verifier.get();
504 cert_verifier_ = verifier.Pass();
505 #endif
506 // The URLBlacklistManager has to be created on the UI thread to register
507 // observers of |pref_service|, and it also has to clean up on
508 // ShutdownOnUIThread to release these observers on the right thread.
509 // Don't pass it in |profile_params_| to make sure it is correctly cleaned up,
510 // in particular when this ProfileIOData isn't |initialized_| during deletion.
511 #if defined(ENABLE_CONFIGURATION_POLICY)
512 policy::URLBlacklist::SegmentURLCallback callback =
513 static_cast<policy::URLBlacklist::SegmentURLCallback>(
514 url_fixer::SegmentURL);
515 base::SequencedWorkerPool* pool = BrowserThread::GetBlockingPool();
516 scoped_refptr<base::SequencedTaskRunner> background_task_runner =
517 pool->GetSequencedTaskRunner(pool->GetSequenceToken());
518 url_blacklist_manager_.reset(new policy::URLBlacklistManager(
519 pref_service, background_task_runner, io_task_runner, callback,
520 base::Bind(policy::OverrideBlacklistForURL)));
522 if (!IsOffTheRecord()) {
523 // Add policy headers for non-incognito requests.
524 policy::PolicyHeaderService* policy_header_service =
525 policy::PolicyHeaderServiceFactory::GetForBrowserContext(profile);
526 if (policy_header_service) {
527 policy_header_helper_ =
528 policy_header_service->CreatePolicyHeaderIOHelper(io_task_runner);
531 #endif
533 incognito_availibility_pref_.Init(
534 prefs::kIncognitoModeAvailability, pref_service);
535 incognito_availibility_pref_.MoveToThread(io_task_runner);
537 initialized_on_UI_thread_ = true;
539 // We need to make sure that content initializes its own data structures that
540 // are associated with each ResourceContext because we might post this
541 // object to the IO thread after this function.
542 BrowserContext::EnsureResourceContextInitialized(profile);
545 ProfileIOData::MediaRequestContext::MediaRequestContext() {
548 void ProfileIOData::MediaRequestContext::SetHttpTransactionFactory(
549 scoped_ptr<net::HttpTransactionFactory> http_factory) {
550 http_factory_ = http_factory.Pass();
551 set_http_transaction_factory(http_factory_.get());
554 ProfileIOData::MediaRequestContext::~MediaRequestContext() {
555 AssertNoURLRequests();
558 ProfileIOData::AppRequestContext::AppRequestContext() {
561 void ProfileIOData::AppRequestContext::SetCookieStore(
562 net::CookieStore* cookie_store) {
563 cookie_store_ = cookie_store;
564 set_cookie_store(cookie_store);
567 void ProfileIOData::AppRequestContext::SetHttpTransactionFactory(
568 scoped_ptr<net::HttpTransactionFactory> http_factory) {
569 http_factory_ = http_factory.Pass();
570 set_http_transaction_factory(http_factory_.get());
573 void ProfileIOData::AppRequestContext::SetJobFactory(
574 scoped_ptr<net::URLRequestJobFactory> job_factory) {
575 job_factory_ = job_factory.Pass();
576 set_job_factory(job_factory_.get());
579 ProfileIOData::AppRequestContext::~AppRequestContext() {
580 AssertNoURLRequests();
583 ProfileIOData::ProfileParams::ProfileParams()
584 : io_thread(NULL),
585 #if defined(OS_CHROMEOS)
586 use_system_key_slot(false),
587 #endif
588 profile(NULL) {
591 ProfileIOData::ProfileParams::~ProfileParams() {}
593 ProfileIOData::ProfileIOData(Profile::ProfileType profile_type)
594 : initialized_(false),
595 #if defined(OS_CHROMEOS)
596 policy_cert_verifier_(NULL),
597 use_system_key_slot_(false),
598 #endif
599 resource_context_(new ResourceContext(this)),
600 initialized_on_UI_thread_(false),
601 profile_type_(profile_type) {
602 DCHECK_CURRENTLY_ON(BrowserThread::UI);
605 ProfileIOData::~ProfileIOData() {
606 if (BrowserThread::IsMessageLoopValid(BrowserThread::IO))
607 DCHECK_CURRENTLY_ON(BrowserThread::IO);
609 // Pull the contents of the request context maps onto the stack for sanity
610 // checking of values in a minidump. http://crbug.com/260425
611 size_t num_app_contexts = app_request_context_map_.size();
612 size_t num_media_contexts = isolated_media_request_context_map_.size();
613 size_t current_context = 0;
614 static const size_t kMaxCachedContexts = 20;
615 net::URLRequestContext* app_context_cache[kMaxCachedContexts] = {0};
616 void* app_context_vtable_cache[kMaxCachedContexts] = {0};
617 net::URLRequestContext* media_context_cache[kMaxCachedContexts] = {0};
618 void* media_context_vtable_cache[kMaxCachedContexts] = {0};
619 void* tmp_vtable = NULL;
620 base::debug::Alias(&num_app_contexts);
621 base::debug::Alias(&num_media_contexts);
622 base::debug::Alias(&current_context);
623 base::debug::Alias(app_context_cache);
624 base::debug::Alias(app_context_vtable_cache);
625 base::debug::Alias(media_context_cache);
626 base::debug::Alias(media_context_vtable_cache);
627 base::debug::Alias(&tmp_vtable);
629 current_context = 0;
630 for (URLRequestContextMap::const_iterator it =
631 app_request_context_map_.begin();
632 current_context < kMaxCachedContexts &&
633 it != app_request_context_map_.end();
634 ++it, ++current_context) {
635 app_context_cache[current_context] = it->second;
636 memcpy(&app_context_vtable_cache[current_context],
637 static_cast<void*>(it->second), sizeof(void*));
640 current_context = 0;
641 for (URLRequestContextMap::const_iterator it =
642 isolated_media_request_context_map_.begin();
643 current_context < kMaxCachedContexts &&
644 it != isolated_media_request_context_map_.end();
645 ++it, ++current_context) {
646 media_context_cache[current_context] = it->second;
647 memcpy(&media_context_vtable_cache[current_context],
648 static_cast<void*>(it->second), sizeof(void*));
651 // Destroy certificate_report_sender_ before main_request_context_,
652 // since the former has a reference to the latter.
653 if (transport_security_state_)
654 transport_security_state_->SetReportSender(nullptr);
655 certificate_report_sender_.reset();
657 // TODO(ajwong): These AssertNoURLRequests() calls are unnecessary since they
658 // are already done in the URLRequestContext destructor.
659 if (main_request_context_)
660 main_request_context_->AssertNoURLRequests();
661 if (extensions_request_context_)
662 extensions_request_context_->AssertNoURLRequests();
664 current_context = 0;
665 for (URLRequestContextMap::iterator it = app_request_context_map_.begin();
666 it != app_request_context_map_.end(); ++it) {
667 if (current_context < kMaxCachedContexts) {
668 CHECK_EQ(app_context_cache[current_context], it->second);
669 memcpy(&tmp_vtable, static_cast<void*>(it->second), sizeof(void*));
670 CHECK_EQ(app_context_vtable_cache[current_context], tmp_vtable);
672 it->second->AssertNoURLRequests();
673 delete it->second;
674 current_context++;
677 current_context = 0;
678 for (URLRequestContextMap::iterator it =
679 isolated_media_request_context_map_.begin();
680 it != isolated_media_request_context_map_.end(); ++it) {
681 if (current_context < kMaxCachedContexts) {
682 CHECK_EQ(media_context_cache[current_context], it->second);
683 memcpy(&tmp_vtable, static_cast<void*>(it->second), sizeof(void*));
684 CHECK_EQ(media_context_vtable_cache[current_context], tmp_vtable);
686 it->second->AssertNoURLRequests();
687 delete it->second;
688 current_context++;
692 // static
693 ProfileIOData* ProfileIOData::FromResourceContext(
694 content::ResourceContext* rc) {
695 return (static_cast<ResourceContext*>(rc))->io_data_;
698 // static
699 bool ProfileIOData::IsHandledProtocol(const std::string& scheme) {
700 DCHECK_EQ(scheme, base::StringToLowerASCII(scheme));
701 static const char* const kProtocolList[] = {
702 url::kFileScheme,
703 content::kChromeDevToolsScheme,
704 dom_distiller::kDomDistillerScheme,
705 #if defined(ENABLE_EXTENSIONS)
706 extensions::kExtensionScheme,
707 extensions::kExtensionResourceScheme,
708 #endif
709 content::kChromeUIScheme,
710 url::kDataScheme,
711 #if defined(OS_CHROMEOS)
712 content::kExternalFileScheme,
713 #endif // defined(OS_CHROMEOS)
714 url::kAboutScheme,
715 #if !defined(DISABLE_FTP_SUPPORT)
716 url::kFtpScheme,
717 #endif // !defined(DISABLE_FTP_SUPPORT)
718 url::kBlobScheme,
719 url::kFileSystemScheme,
720 chrome::kChromeSearchScheme,
722 for (size_t i = 0; i < arraysize(kProtocolList); ++i) {
723 if (scheme == kProtocolList[i])
724 return true;
726 return net::URLRequest::IsHandledProtocol(scheme);
729 // static
730 bool ProfileIOData::IsHandledURL(const GURL& url) {
731 if (!url.is_valid()) {
732 // We handle error cases.
733 return true;
736 return IsHandledProtocol(url.scheme());
739 // static
740 void ProfileIOData::InstallProtocolHandlers(
741 net::URLRequestJobFactoryImpl* job_factory,
742 content::ProtocolHandlerMap* protocol_handlers) {
743 for (content::ProtocolHandlerMap::iterator it =
744 protocol_handlers->begin();
745 it != protocol_handlers->end();
746 ++it) {
747 bool set_protocol = job_factory->SetProtocolHandler(
748 it->first, it->second.release());
749 DCHECK(set_protocol);
751 protocol_handlers->clear();
754 // static
755 void ProfileIOData::SetCertVerifierForTesting(
756 net::CertVerifier* cert_verifier) {
757 g_cert_verifier_for_testing = cert_verifier;
760 content::ResourceContext* ProfileIOData::GetResourceContext() const {
761 return resource_context_.get();
764 net::URLRequestContext* ProfileIOData::GetMainRequestContext() const {
765 DCHECK(initialized_);
766 return main_request_context_.get();
769 net::URLRequestContext* ProfileIOData::GetMediaRequestContext() const {
770 DCHECK(initialized_);
771 net::URLRequestContext* context = AcquireMediaRequestContext();
772 DCHECK(context);
773 return context;
776 net::URLRequestContext* ProfileIOData::GetExtensionsRequestContext() const {
777 DCHECK(initialized_);
778 return extensions_request_context_.get();
781 net::URLRequestContext* ProfileIOData::GetIsolatedAppRequestContext(
782 net::URLRequestContext* main_context,
783 const StoragePartitionDescriptor& partition_descriptor,
784 scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
785 protocol_handler_interceptor,
786 content::ProtocolHandlerMap* protocol_handlers,
787 content::URLRequestInterceptorScopedVector request_interceptors) const {
788 DCHECK(initialized_);
789 net::URLRequestContext* context = NULL;
790 if (ContainsKey(app_request_context_map_, partition_descriptor)) {
791 context = app_request_context_map_[partition_descriptor];
792 } else {
793 context =
794 AcquireIsolatedAppRequestContext(main_context,
795 partition_descriptor,
796 protocol_handler_interceptor.Pass(),
797 protocol_handlers,
798 request_interceptors.Pass());
799 app_request_context_map_[partition_descriptor] = context;
801 DCHECK(context);
802 return context;
805 net::URLRequestContext* ProfileIOData::GetIsolatedMediaRequestContext(
806 net::URLRequestContext* app_context,
807 const StoragePartitionDescriptor& partition_descriptor) const {
808 DCHECK(initialized_);
809 net::URLRequestContext* context = NULL;
810 if (ContainsKey(isolated_media_request_context_map_, partition_descriptor)) {
811 context = isolated_media_request_context_map_[partition_descriptor];
812 } else {
813 context = AcquireIsolatedMediaRequestContext(app_context,
814 partition_descriptor);
815 isolated_media_request_context_map_[partition_descriptor] = context;
817 DCHECK(context);
818 return context;
821 extensions::InfoMap* ProfileIOData::GetExtensionInfoMap() const {
822 DCHECK(initialized_) << "ExtensionSystem not initialized";
823 #if defined(ENABLE_EXTENSIONS)
824 return extension_info_map_.get();
825 #else
826 return nullptr;
827 #endif
830 extensions::ExtensionThrottleManager*
831 ProfileIOData::GetExtensionThrottleManager() const {
832 DCHECK(initialized_) << "ExtensionSystem not initialized";
833 #if defined(ENABLE_EXTENSIONS)
834 return extension_throttle_manager_.get();
835 #else
836 return nullptr;
837 #endif
840 content_settings::CookieSettings* ProfileIOData::GetCookieSettings() const {
841 // Allow either Init() or SetCookieSettingsForTesting() to initialize.
842 DCHECK(initialized_ || cookie_settings_.get());
843 return cookie_settings_.get();
846 HostContentSettingsMap* ProfileIOData::GetHostContentSettingsMap() const {
847 DCHECK(initialized_);
848 return host_content_settings_map_.get();
851 ResourceContext::SaltCallback ProfileIOData::GetMediaDeviceIDSalt() const {
852 return base::Bind(&MediaDeviceIDSalt::GetSalt, media_device_id_salt_);
855 bool ProfileIOData::IsOffTheRecord() const {
856 return profile_type() == Profile::INCOGNITO_PROFILE
857 || profile_type() == Profile::GUEST_PROFILE;
860 void ProfileIOData::InitializeMetricsEnabledStateOnUIThread() {
861 DCHECK_CURRENTLY_ON(BrowserThread::UI);
862 #if defined(OS_CHROMEOS)
863 // Just fetch the value from ChromeOS' settings while we're on the UI thread.
864 // TODO(stevet): For now, this value is only set on profile initialization.
865 // We will want to do something similar to the PrefMember method below in the
866 // future to more accurately capture this state.
867 chromeos::CrosSettings::Get()->GetBoolean(chromeos::kStatsReportingPref,
868 &enable_metrics_);
869 #elif defined(OS_ANDROID)
870 // TODO(dwkang): rename or unify the pref for UMA once we have conclusion
871 // in crbugs.com/246495.
872 // Android has it's own preferences for metrics / crash uploading.
873 enable_metrics_.Init(prefs::kCrashReportingEnabled,
874 g_browser_process->local_state());
875 enable_metrics_.MoveToThread(
876 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
877 #else
878 // Prep the PrefMember and send it to the IO thread, since this value will be
879 // read from there.
880 enable_metrics_.Init(prefs::kMetricsReportingEnabled,
881 g_browser_process->local_state());
882 enable_metrics_.MoveToThread(
883 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
884 #endif // defined(OS_CHROMEOS)
887 bool ProfileIOData::GetMetricsEnabledStateOnIOThread() const {
888 DCHECK_CURRENTLY_ON(BrowserThread::IO);
889 #if defined(OS_CHROMEOS)
890 return enable_metrics_;
891 #else
892 return enable_metrics_.GetValue();
893 #endif // defined(OS_CHROMEOS)
896 bool ProfileIOData::IsDataReductionProxyEnabled() const {
897 return data_reduction_proxy_io_data() &&
898 data_reduction_proxy_io_data()->IsEnabled();
901 void ProfileIOData::set_data_reduction_proxy_io_data(
902 scoped_ptr<data_reduction_proxy::DataReductionProxyIOData>
903 data_reduction_proxy_io_data) const {
904 data_reduction_proxy_io_data_ = data_reduction_proxy_io_data.Pass();
907 base::WeakPtr<net::HttpServerProperties>
908 ProfileIOData::http_server_properties() const {
909 return http_server_properties_->GetWeakPtr();
912 void ProfileIOData::set_http_server_properties(
913 scoped_ptr<net::HttpServerProperties> http_server_properties) const {
914 http_server_properties_ = http_server_properties.Pass();
917 ProfileIOData::ResourceContext::ResourceContext(ProfileIOData* io_data)
918 : io_data_(io_data),
919 host_resolver_(NULL),
920 request_context_(NULL) {
921 DCHECK(io_data);
924 ProfileIOData::ResourceContext::~ResourceContext() {}
926 net::HostResolver* ProfileIOData::ResourceContext::GetHostResolver() {
927 DCHECK_CURRENTLY_ON(BrowserThread::IO);
928 DCHECK(io_data_->initialized_);
929 return host_resolver_;
932 net::URLRequestContext* ProfileIOData::ResourceContext::GetRequestContext() {
933 DCHECK_CURRENTLY_ON(BrowserThread::IO);
934 DCHECK(io_data_->initialized_);
935 return request_context_;
938 scoped_ptr<net::ClientCertStore>
939 ProfileIOData::ResourceContext::CreateClientCertStore() {
940 if (!io_data_->client_cert_store_factory_.is_null())
941 return io_data_->client_cert_store_factory_.Run();
942 #if defined(OS_CHROMEOS)
943 return scoped_ptr<net::ClientCertStore>(new net::ClientCertStoreChromeOS(
944 make_scoped_ptr(new chromeos::ClientCertFilterChromeOS(
945 io_data_->use_system_key_slot(), io_data_->username_hash())),
946 base::Bind(&CreateCryptoModuleBlockingPasswordDelegate,
947 chrome::kCryptoModulePasswordClientAuth)));
948 #elif defined(USE_NSS_CERTS)
949 return scoped_ptr<net::ClientCertStore>(new net::ClientCertStoreNSS(
950 base::Bind(&CreateCryptoModuleBlockingPasswordDelegate,
951 chrome::kCryptoModulePasswordClientAuth)));
952 #elif defined(OS_WIN)
953 return scoped_ptr<net::ClientCertStore>(new net::ClientCertStoreWin());
954 #elif defined(OS_MACOSX)
955 return scoped_ptr<net::ClientCertStore>(new net::ClientCertStoreMac());
956 #elif defined(USE_OPENSSL)
957 // OpenSSL does not use the ClientCertStore infrastructure. On Android client
958 // cert matching is done by the OS as part of the call to show the cert
959 // selection dialog.
960 return scoped_ptr<net::ClientCertStore>();
961 #else
962 #error Unknown platform.
963 #endif
966 void ProfileIOData::ResourceContext::CreateKeygenHandler(
967 uint32 key_size_in_bits,
968 const std::string& challenge_string,
969 const GURL& url,
970 const base::Callback<void(scoped_ptr<net::KeygenHandler>)>& callback) {
971 DCHECK(!callback.is_null());
972 #if defined(USE_NSS_CERTS)
973 scoped_ptr<net::KeygenHandler> keygen_handler(
974 new net::KeygenHandler(key_size_in_bits, challenge_string, url));
976 base::Callback<void(scoped_ptr<ChromeNSSCryptoModuleDelegate>)>
977 got_delegate_callback = base::Bind(&InitializeAndPassKeygenHandler,
978 base::Passed(&keygen_handler),
979 callback);
981 ChromeNSSCryptoModuleDelegate::CreateForResourceContext(
982 chrome::kCryptoModulePasswordKeygen,
983 net::HostPortPair::FromURL(url),
984 this,
985 got_delegate_callback);
986 #else
987 callback.Run(make_scoped_ptr(
988 new net::KeygenHandler(key_size_in_bits, challenge_string, url)));
989 #endif
992 ResourceContext::SaltCallback
993 ProfileIOData::ResourceContext::GetMediaDeviceIDSalt() {
994 return io_data_->GetMediaDeviceIDSalt();
997 // static
998 std::string ProfileIOData::GetSSLSessionCacheShard() {
999 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1000 // The SSL session cache is partitioned by setting a string. This returns a
1001 // unique string to partition the SSL session cache. Each time we create a
1002 // new profile, we'll get a fresh SSL session cache which is separate from
1003 // the other profiles.
1004 static unsigned ssl_session_cache_instance = 0;
1005 return base::StringPrintf("profile/%u", ssl_session_cache_instance++);
1008 void ProfileIOData::Init(
1009 content::ProtocolHandlerMap* protocol_handlers,
1010 content::URLRequestInterceptorScopedVector request_interceptors) const {
1011 // The basic logic is implemented here. The specific initialization
1012 // is done in InitializeInternal(), implemented by subtypes. Static helper
1013 // functions have been provided to assist in common operations.
1014 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1015 DCHECK(!initialized_);
1017 // TODO(jhawkins): Remove once crbug.com/102004 is fixed.
1018 CHECK(initialized_on_UI_thread_);
1020 // TODO(jhawkins): Return to DCHECK once crbug.com/102004 is fixed.
1021 CHECK(profile_params_.get());
1023 IOThread* const io_thread = profile_params_->io_thread;
1024 IOThread::Globals* const io_thread_globals = io_thread->globals();
1025 const base::CommandLine& command_line =
1026 *base::CommandLine::ForCurrentProcess();
1028 // Create the common request contexts.
1029 main_request_context_.reset(new net::URLRequestContext());
1030 extensions_request_context_.reset(new net::URLRequestContext());
1032 scoped_ptr<ChromeNetworkDelegate> network_delegate(
1033 new ChromeNetworkDelegate(
1034 #if defined(ENABLE_EXTENSIONS)
1035 io_thread_globals->extension_event_router_forwarder.get(),
1036 #else
1037 NULL,
1038 #endif
1039 &enable_referrers_));
1040 #if defined(ENABLE_EXTENSIONS)
1041 network_delegate->set_extension_info_map(
1042 profile_params_->extension_info_map.get());
1043 if (!command_line.HasSwitch(switches::kDisableExtensionsHttpThrottling)) {
1044 extension_throttle_manager_.reset(
1045 new extensions::ExtensionThrottleManager());
1047 #endif
1049 #if defined(ENABLE_CONFIGURATION_POLICY)
1050 network_delegate->set_url_blacklist_manager(url_blacklist_manager_.get());
1051 #endif
1052 network_delegate->set_profile(profile_params_->profile);
1053 network_delegate->set_profile_path(profile_params_->path);
1054 network_delegate->set_cookie_settings(profile_params_->cookie_settings.get());
1055 network_delegate->set_enable_do_not_track(&enable_do_not_track_);
1056 network_delegate->set_force_google_safe_search(&force_google_safesearch_);
1057 network_delegate->set_force_youtube_safety_mode(&force_youtube_safety_mode_);
1058 fraudulent_certificate_reporter_.reset(
1059 new ChromeFraudulentCertificateReporter(main_request_context_.get()));
1061 // NOTE: Proxy service uses the default io thread network delegate, not the
1062 // delegate just created.
1063 proxy_service_.reset(
1064 ProxyServiceFactory::CreateProxyService(
1065 io_thread->net_log(),
1066 io_thread_globals->proxy_script_fetcher_context.get(),
1067 io_thread_globals->system_network_delegate.get(),
1068 profile_params_->proxy_config_service.release(),
1069 command_line,
1070 quick_check_enabled_.GetValue()));
1071 transport_security_state_.reset(new net::TransportSecurityState());
1072 base::SequencedWorkerPool* pool = BrowserThread::GetBlockingPool();
1073 transport_security_persister_.reset(
1074 new net::TransportSecurityPersister(
1075 transport_security_state_.get(),
1076 profile_params_->path,
1077 pool->GetSequencedTaskRunnerWithShutdownBehavior(
1078 pool->GetSequenceToken(),
1079 base::SequencedWorkerPool::BLOCK_SHUTDOWN),
1080 IsOffTheRecord()));
1082 certificate_report_sender_.reset(new net::CertificateReportSender(
1083 main_request_context_.get(),
1084 net::CertificateReportSender::DO_NOT_SEND_COOKIES));
1085 transport_security_state_->SetReportSender(certificate_report_sender_.get());
1087 // Take ownership over these parameters.
1088 cookie_settings_ = profile_params_->cookie_settings;
1089 host_content_settings_map_ = profile_params_->host_content_settings_map;
1090 #if defined(ENABLE_EXTENSIONS)
1091 extension_info_map_ = profile_params_->extension_info_map;
1092 #endif
1094 resource_context_->host_resolver_ = io_thread_globals->host_resolver.get();
1095 resource_context_->request_context_ = main_request_context_.get();
1097 if (profile_params_->resource_prefetch_predictor_observer_) {
1098 resource_prefetch_predictor_observer_.reset(
1099 profile_params_->resource_prefetch_predictor_observer_.release());
1102 #if defined(ENABLE_SUPERVISED_USERS)
1103 supervised_user_url_filter_ = profile_params_->supervised_user_url_filter;
1104 #endif
1106 #if defined(OS_CHROMEOS)
1107 username_hash_ = profile_params_->username_hash;
1108 use_system_key_slot_ = profile_params_->use_system_key_slot;
1109 if (use_system_key_slot_)
1110 EnableNSSSystemKeySlotForResourceContext(resource_context_.get());
1111 #endif
1113 if (g_cert_verifier_for_testing) {
1114 main_request_context_->set_cert_verifier(g_cert_verifier_for_testing);
1115 } else {
1116 #if defined(OS_CHROMEOS)
1117 crypto::ScopedPK11Slot public_slot =
1118 crypto::GetPublicSlotForChromeOSUser(username_hash_);
1119 // The private slot won't be ready by this point. It shouldn't be necessary
1120 // for cert trust purposes anyway.
1121 scoped_refptr<net::CertVerifyProc> verify_proc(
1122 new chromeos::CertVerifyProcChromeOS(public_slot.Pass()));
1123 if (policy_cert_verifier_) {
1124 DCHECK_EQ(policy_cert_verifier_, cert_verifier_.get());
1125 policy_cert_verifier_->InitializeOnIOThread(verify_proc);
1126 } else {
1127 cert_verifier_.reset(
1128 new net::MultiThreadedCertVerifier(verify_proc.get()));
1130 main_request_context_->set_cert_verifier(cert_verifier_.get());
1131 #else
1132 main_request_context_->set_cert_verifier(
1133 io_thread_globals->cert_verifier.get());
1134 #endif
1137 // Install the New Tab Page Interceptor.
1138 if (profile_params_->new_tab_page_interceptor.get()) {
1139 request_interceptors.push_back(
1140 profile_params_->new_tab_page_interceptor.release());
1143 InitializeInternal(
1144 network_delegate.Pass(), profile_params_.get(),
1145 protocol_handlers, request_interceptors.Pass());
1147 profile_params_.reset();
1148 initialized_ = true;
1151 void ProfileIOData::ApplyProfileParamsToContext(
1152 net::URLRequestContext* context) const {
1153 context->set_http_user_agent_settings(
1154 chrome_http_user_agent_settings_.get());
1155 context->set_ssl_config_service(profile_params_->ssl_config_service.get());
1158 scoped_ptr<net::URLRequestJobFactory> ProfileIOData::SetUpJobFactoryDefaults(
1159 scoped_ptr<net::URLRequestJobFactoryImpl> job_factory,
1160 content::URLRequestInterceptorScopedVector request_interceptors,
1161 scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
1162 protocol_handler_interceptor,
1163 net::NetworkDelegate* network_delegate,
1164 net::FtpTransactionFactory* ftp_transaction_factory) const {
1165 // NOTE(willchan): Keep these protocol handlers in sync with
1166 // ProfileIOData::IsHandledProtocol().
1167 bool set_protocol = job_factory->SetProtocolHandler(
1168 url::kFileScheme,
1169 new net::FileProtocolHandler(
1170 content::BrowserThread::GetBlockingPool()->
1171 GetTaskRunnerWithShutdownBehavior(
1172 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)));
1173 DCHECK(set_protocol);
1175 #if defined(ENABLE_EXTENSIONS)
1176 DCHECK(extension_info_map_.get());
1177 // Check only for incognito (and not Chrome OS guest mode GUEST_PROFILE).
1178 bool is_incognito = profile_type() == Profile::INCOGNITO_PROFILE;
1179 set_protocol = job_factory->SetProtocolHandler(
1180 extensions::kExtensionScheme,
1181 extensions::CreateExtensionProtocolHandler(is_incognito,
1182 extension_info_map_.get()));
1183 DCHECK(set_protocol);
1184 set_protocol = job_factory->SetProtocolHandler(
1185 extensions::kExtensionResourceScheme,
1186 CreateExtensionResourceProtocolHandler());
1187 DCHECK(set_protocol);
1188 #endif
1189 set_protocol = job_factory->SetProtocolHandler(
1190 url::kDataScheme, new net::DataProtocolHandler());
1191 DCHECK(set_protocol);
1192 #if defined(OS_CHROMEOS)
1193 if (profile_params_) {
1194 set_protocol = job_factory->SetProtocolHandler(
1195 content::kExternalFileScheme,
1196 new chromeos::ExternalFileProtocolHandler(profile_params_->profile));
1197 DCHECK(set_protocol);
1199 #endif // defined(OS_CHROMEOS)
1200 #if defined(OS_ANDROID)
1201 set_protocol = job_factory->SetProtocolHandler(
1202 url::kContentScheme,
1203 content::ContentProtocolHandler::Create(
1204 content::BrowserThread::GetBlockingPool()->
1205 GetTaskRunnerWithShutdownBehavior(
1206 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)));
1207 #endif
1209 job_factory->SetProtocolHandler(
1210 url::kAboutScheme, new chrome_browser_net::AboutProtocolHandler());
1211 #if !defined(DISABLE_FTP_SUPPORT)
1212 DCHECK(ftp_transaction_factory);
1213 job_factory->SetProtocolHandler(
1214 url::kFtpScheme,
1215 new net::FtpProtocolHandler(ftp_transaction_factory));
1216 #endif // !defined(DISABLE_FTP_SUPPORT)
1218 #if defined(DEBUG_DEVTOOLS)
1219 request_interceptors.push_back(new DebugDevToolsInterceptor);
1220 #endif
1222 // Set up interceptors in the reverse order.
1223 scoped_ptr<net::URLRequestJobFactory> top_job_factory = job_factory.Pass();
1224 for (content::URLRequestInterceptorScopedVector::reverse_iterator i =
1225 request_interceptors.rbegin();
1226 i != request_interceptors.rend();
1227 ++i) {
1228 top_job_factory.reset(new net::URLRequestInterceptingJobFactory(
1229 top_job_factory.Pass(), make_scoped_ptr(*i)));
1231 request_interceptors.weak_clear();
1233 if (protocol_handler_interceptor) {
1234 protocol_handler_interceptor->Chain(top_job_factory.Pass());
1235 return protocol_handler_interceptor.Pass();
1236 } else {
1237 return top_job_factory.Pass();
1241 void ProfileIOData::ShutdownOnUIThread(
1242 scoped_ptr<ChromeURLRequestContextGetterVector> context_getters) {
1243 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1245 google_services_user_account_id_.Destroy();
1246 enable_referrers_.Destroy();
1247 enable_do_not_track_.Destroy();
1248 force_google_safesearch_.Destroy();
1249 force_youtube_safety_mode_.Destroy();
1250 #if !defined(OS_CHROMEOS)
1251 enable_metrics_.Destroy();
1252 #endif
1253 safe_browsing_enabled_.Destroy();
1254 sync_disabled_.Destroy();
1255 signin_allowed_.Destroy();
1256 network_prediction_options_.Destroy();
1257 quick_check_enabled_.Destroy();
1258 if (media_device_id_salt_.get())
1259 media_device_id_salt_->ShutdownOnUIThread();
1260 session_startup_pref_.Destroy();
1261 #if defined(ENABLE_CONFIGURATION_POLICY)
1262 if (url_blacklist_manager_)
1263 url_blacklist_manager_->ShutdownOnUIThread();
1264 #endif
1265 if (chrome_http_user_agent_settings_)
1266 chrome_http_user_agent_settings_->CleanupOnUIThread();
1267 incognito_availibility_pref_.Destroy();
1269 if (!context_getters->empty()) {
1270 if (BrowserThread::IsMessageLoopValid(BrowserThread::IO)) {
1271 BrowserThread::PostTask(
1272 BrowserThread::IO, FROM_HERE,
1273 base::Bind(&NotifyContextGettersOfShutdownOnIO,
1274 base::Passed(&context_getters)));
1278 bool posted = BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, this);
1279 if (!posted)
1280 delete this;
1283 void ProfileIOData::set_channel_id_service(
1284 net::ChannelIDService* channel_id_service) const {
1285 channel_id_service_.reset(channel_id_service);
1288 void ProfileIOData::DestroyResourceContext() {
1289 resource_context_.reset();
1292 scoped_ptr<net::HttpCache> ProfileIOData::CreateMainHttpFactory(
1293 const ProfileParams* profile_params,
1294 net::HttpCache::BackendFactory* main_backend) const {
1295 net::HttpNetworkSession::Params params;
1296 net::URLRequestContext* context = main_request_context();
1298 IOThread* const io_thread = profile_params->io_thread;
1300 io_thread->InitializeNetworkSessionParams(&params);
1302 params.host_resolver = context->host_resolver();
1303 params.cert_verifier = context->cert_verifier();
1304 params.channel_id_service = context->channel_id_service();
1305 params.transport_security_state = context->transport_security_state();
1306 params.cert_transparency_verifier = context->cert_transparency_verifier();
1307 params.proxy_service = context->proxy_service();
1308 params.ssl_session_cache_shard = GetSSLSessionCacheShard();
1309 params.ssl_config_service = context->ssl_config_service();
1310 params.http_auth_handler_factory = context->http_auth_handler_factory();
1311 params.network_delegate = context->network_delegate();
1312 params.http_server_properties = context->http_server_properties();
1313 params.net_log = context->net_log();
1314 if (data_reduction_proxy_io_data_.get())
1315 params.proxy_delegate = data_reduction_proxy_io_data_->proxy_delegate();
1317 network_controller_.reset(new DevToolsNetworkController());
1319 net::HttpNetworkSession* session = new net::HttpNetworkSession(params);
1320 return scoped_ptr<net::HttpCache>(new net::HttpCache(
1321 new DevToolsNetworkTransactionFactory(network_controller_.get(), session),
1322 context->net_log(), main_backend));
1325 scoped_ptr<net::HttpCache> ProfileIOData::CreateHttpFactory(
1326 net::HttpNetworkSession* shared_session,
1327 net::HttpCache::BackendFactory* backend) const {
1328 return scoped_ptr<net::HttpCache>(new net::HttpCache(
1329 new DevToolsNetworkTransactionFactory(
1330 network_controller_.get(), shared_session),
1331 shared_session->net_log(), backend));
1334 void ProfileIOData::SetCookieSettingsForTesting(
1335 content_settings::CookieSettings* cookie_settings) {
1336 DCHECK(!cookie_settings_.get());
1337 cookie_settings_ = cookie_settings;