Fire an error if a pref used in the UI is missing once all prefs are fetched.
[chromium-blink-merge.git] / chrome / browser / profiles / profile_impl_io_data.cc
blobd64039e917f40b2aa221595083b4c581f0e6d2d4
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_impl_io_data.h"
7 #include <set>
9 #include "base/bind.h"
10 #include "base/command_line.h"
11 #include "base/logging.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/metrics/field_trial.h"
14 #include "base/prefs/json_pref_store.h"
15 #include "base/prefs/pref_filter.h"
16 #include "base/prefs/pref_member.h"
17 #include "base/prefs/pref_service.h"
18 #include "base/profiler/scoped_tracker.h"
19 #include "base/sequenced_task_runner.h"
20 #include "base/stl_util.h"
21 #include "base/strings/string_util.h"
22 #include "base/threading/sequenced_worker_pool.h"
23 #include "base/threading/worker_pool.h"
24 #include "chrome/browser/browser_process.h"
25 #include "chrome/browser/chrome_notification_types.h"
26 #include "chrome/browser/chromeos/profiles/profile_helper.h"
27 #include "chrome/browser/custom_handlers/protocol_handler_registry.h"
28 #include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h"
29 #include "chrome/browser/io_thread.h"
30 #include "chrome/browser/net/chrome_net_log.h"
31 #include "chrome/browser/net/chrome_network_delegate.h"
32 #include "chrome/browser/net/connect_interceptor.h"
33 #include "chrome/browser/net/cookie_store_util.h"
34 #include "chrome/browser/net/http_server_properties_manager_factory.h"
35 #include "chrome/browser/net/predictor.h"
36 #include "chrome/browser/net/quota_policy_channel_id_store.h"
37 #include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_io_data.h"
38 #include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings.h"
39 #include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings_factory.h"
40 #include "chrome/browser/profiles/profile.h"
41 #include "chrome/common/chrome_constants.h"
42 #include "chrome/common/chrome_switches.h"
43 #include "chrome/common/pref_names.h"
44 #include "chrome/common/url_constants.h"
45 #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_io_data.h"
46 #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_settings.h"
47 #include "components/domain_reliability/monitor.h"
48 #include "content/public/browser/browser_thread.h"
49 #include "content/public/browser/cookie_store_factory.h"
50 #include "content/public/browser/notification_service.h"
51 #include "content/public/browser/resource_context.h"
52 #include "content/public/browser/storage_partition.h"
53 #include "extensions/browser/extension_protocols.h"
54 #include "extensions/common/constants.h"
55 #include "net/base/cache_type.h"
56 #include "net/base/sdch_manager.h"
57 #include "net/ftp/ftp_network_layer.h"
58 #include "net/http/http_cache.h"
59 #include "net/http/http_server_properties_manager.h"
60 #include "net/sdch/sdch_owner.h"
61 #include "net/ssl/channel_id_service.h"
62 #include "net/url_request/url_request_intercepting_job_factory.h"
63 #include "net/url_request/url_request_job_factory_impl.h"
64 #include "storage/browser/quota/special_storage_policy.h"
66 namespace {
68 net::BackendType ChooseCacheBackendType() {
69 #if defined(OS_ANDROID)
70 return net::CACHE_BACKEND_SIMPLE;
71 #else
72 const base::CommandLine& command_line =
73 *base::CommandLine::ForCurrentProcess();
74 if (command_line.HasSwitch(switches::kUseSimpleCacheBackend)) {
75 const std::string opt_value =
76 command_line.GetSwitchValueASCII(switches::kUseSimpleCacheBackend);
77 if (LowerCaseEqualsASCII(opt_value, "off"))
78 return net::CACHE_BACKEND_BLOCKFILE;
79 if (opt_value.empty() || LowerCaseEqualsASCII(opt_value, "on"))
80 return net::CACHE_BACKEND_SIMPLE;
82 const std::string experiment_name =
83 base::FieldTrialList::FindFullName("SimpleCacheTrial");
84 if (experiment_name == "ExperimentYes" ||
85 experiment_name == "ExperimentYes2") {
86 return net::CACHE_BACKEND_SIMPLE;
88 return net::CACHE_BACKEND_BLOCKFILE;
89 #endif
92 bool ShouldUseSdchPersistence() {
93 const std::string group =
94 base::FieldTrialList::FindFullName("SdchPersistence");
95 const base::CommandLine* command_line =
96 base::CommandLine::ForCurrentProcess();
97 if (command_line->HasSwitch(switches::kEnableSdchPersistence)) {
98 return true;
100 if (command_line->HasSwitch(switches::kDisableSdchPersistence)) {
101 return false;
103 return group == "Enabled";
106 } // namespace
108 using content::BrowserThread;
110 ProfileImplIOData::Handle::Handle(Profile* profile)
111 : io_data_(new ProfileImplIOData),
112 profile_(profile),
113 initialized_(false) {
114 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
115 DCHECK(profile);
118 ProfileImplIOData::Handle::~Handle() {
119 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
120 if (io_data_->predictor_ != NULL) {
121 // io_data_->predictor_ might be NULL if Init() was never called
122 // (i.e. we shut down before ProfileImpl::DoFinalInit() got called).
123 bool save_prefs = true;
124 #if defined(OS_CHROMEOS)
125 save_prefs = !chromeos::ProfileHelper::IsSigninProfile(profile_);
126 #endif
127 if (save_prefs)
128 io_data_->predictor_->SaveStateForNextStartupAndTrim();
129 io_data_->predictor_->ShutdownOnUIThread();
132 if (io_data_->http_server_properties_manager_)
133 io_data_->http_server_properties_manager_->ShutdownOnPrefThread();
135 io_data_->data_reduction_proxy_io_data()->ShutdownOnUIThread();
136 io_data_->ShutdownOnUIThread(GetAllContextGetters().Pass());
139 void ProfileImplIOData::Handle::Init(
140 const base::FilePath& cookie_path,
141 const base::FilePath& channel_id_path,
142 const base::FilePath& cache_path,
143 int cache_max_size,
144 const base::FilePath& media_cache_path,
145 int media_cache_max_size,
146 const base::FilePath& extensions_cookie_path,
147 const base::FilePath& profile_path,
148 const base::FilePath& infinite_cache_path,
149 chrome_browser_net::Predictor* predictor,
150 content::CookieStoreConfig::SessionCookieMode session_cookie_mode,
151 storage::SpecialStoragePolicy* special_storage_policy,
152 scoped_ptr<domain_reliability::DomainReliabilityMonitor>
153 domain_reliability_monitor) {
154 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
155 DCHECK(!io_data_->lazy_params_);
156 DCHECK(predictor);
158 LazyParams* lazy_params = new LazyParams();
160 lazy_params->cookie_path = cookie_path;
161 lazy_params->channel_id_path = channel_id_path;
162 lazy_params->cache_path = cache_path;
163 lazy_params->cache_max_size = cache_max_size;
164 lazy_params->media_cache_path = media_cache_path;
165 lazy_params->media_cache_max_size = media_cache_max_size;
166 lazy_params->extensions_cookie_path = extensions_cookie_path;
167 lazy_params->infinite_cache_path = infinite_cache_path;
168 lazy_params->session_cookie_mode = session_cookie_mode;
169 lazy_params->special_storage_policy = special_storage_policy;
171 io_data_->lazy_params_.reset(lazy_params);
173 // Keep track of profile path and cache sizes separately so we can use them
174 // on demand when creating storage isolated URLRequestContextGetters.
175 io_data_->profile_path_ = profile_path;
176 io_data_->app_cache_max_size_ = cache_max_size;
177 io_data_->app_media_cache_max_size_ = media_cache_max_size;
179 io_data_->predictor_.reset(predictor);
180 io_data_->domain_reliability_monitor_ = domain_reliability_monitor.Pass();
182 io_data_->InitializeMetricsEnabledStateOnUIThread();
183 if (io_data_->domain_reliability_monitor_)
184 io_data_->domain_reliability_monitor_->MoveToNetworkThread();
186 // TODO(tbansal): Move this to IO thread once the data reduction proxy
187 // params are unified into a single object.
188 bool enable_quic_for_data_reduction_proxy =
189 IOThread::ShouldEnableQuicForDataReductionProxy();
191 io_data_->set_data_reduction_proxy_io_data(
192 CreateDataReductionProxyChromeIOData(
193 g_browser_process->io_thread()->net_log(), profile_->GetPrefs(),
194 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO),
195 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI),
196 enable_quic_for_data_reduction_proxy)
197 .Pass());
199 DataReductionProxyChromeSettingsFactory::GetForBrowserContext(profile_)->
200 InitDataReductionProxySettings(
201 io_data_->data_reduction_proxy_io_data(), profile_->GetPrefs(),
202 profile_->GetRequestContext(),
203 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI));
206 content::ResourceContext*
207 ProfileImplIOData::Handle::GetResourceContext() const {
208 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
209 LazyInitialize();
210 return GetResourceContextNoInit();
213 content::ResourceContext*
214 ProfileImplIOData::Handle::GetResourceContextNoInit() const {
215 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
216 // Don't call LazyInitialize here, since the resource context is created at
217 // the beginning of initalization and is used by some members while they're
218 // being initialized (i.e. AppCacheService).
219 return io_data_->GetResourceContext();
222 scoped_refptr<ChromeURLRequestContextGetter>
223 ProfileImplIOData::Handle::CreateMainRequestContextGetter(
224 content::ProtocolHandlerMap* protocol_handlers,
225 content::URLRequestInterceptorScopedVector request_interceptors,
226 PrefService* local_state,
227 IOThread* io_thread) const {
228 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
229 LazyInitialize();
230 DCHECK(!main_request_context_getter_.get());
231 main_request_context_getter_ = ChromeURLRequestContextGetter::Create(
232 profile_, io_data_, protocol_handlers, request_interceptors.Pass());
234 io_data_->predictor_
235 ->InitNetworkPredictor(profile_->GetPrefs(),
236 local_state,
237 io_thread,
238 main_request_context_getter_.get(),
239 io_data_);
241 content::NotificationService::current()->Notify(
242 chrome::NOTIFICATION_PROFILE_URL_REQUEST_CONTEXT_GETTER_INITIALIZED,
243 content::Source<Profile>(profile_),
244 content::NotificationService::NoDetails());
245 return main_request_context_getter_;
248 scoped_refptr<ChromeURLRequestContextGetter>
249 ProfileImplIOData::Handle::GetMediaRequestContextGetter() const {
250 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
251 LazyInitialize();
252 if (!media_request_context_getter_.get()) {
253 media_request_context_getter_ =
254 ChromeURLRequestContextGetter::CreateForMedia(profile_, io_data_);
256 return media_request_context_getter_;
259 scoped_refptr<ChromeURLRequestContextGetter>
260 ProfileImplIOData::Handle::GetExtensionsRequestContextGetter() const {
261 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
262 LazyInitialize();
263 if (!extensions_request_context_getter_.get()) {
264 extensions_request_context_getter_ =
265 ChromeURLRequestContextGetter::CreateForExtensions(profile_, io_data_);
267 return extensions_request_context_getter_;
270 scoped_refptr<ChromeURLRequestContextGetter>
271 ProfileImplIOData::Handle::CreateIsolatedAppRequestContextGetter(
272 const base::FilePath& partition_path,
273 bool in_memory,
274 content::ProtocolHandlerMap* protocol_handlers,
275 content::URLRequestInterceptorScopedVector request_interceptors) const {
276 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
277 // Check that the partition_path is not the same as the base profile path. We
278 // expect isolated partition, which will never go to the default profile path.
279 CHECK(partition_path != profile_->GetPath());
280 LazyInitialize();
282 // Keep a map of request context getters, one per requested storage partition.
283 StoragePartitionDescriptor descriptor(partition_path, in_memory);
284 ChromeURLRequestContextGetterMap::iterator iter =
285 app_request_context_getter_map_.find(descriptor);
286 if (iter != app_request_context_getter_map_.end())
287 return iter->second;
289 scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
290 protocol_handler_interceptor(
291 ProtocolHandlerRegistryFactory::GetForBrowserContext(profile_)->
292 CreateJobInterceptorFactory());
293 ChromeURLRequestContextGetter* context =
294 ChromeURLRequestContextGetter::CreateForIsolatedApp(
295 profile_,
296 io_data_,
297 descriptor,
298 protocol_handler_interceptor.Pass(),
299 protocol_handlers,
300 request_interceptors.Pass());
301 app_request_context_getter_map_[descriptor] = context;
303 return context;
306 scoped_refptr<ChromeURLRequestContextGetter>
307 ProfileImplIOData::Handle::GetIsolatedMediaRequestContextGetter(
308 const base::FilePath& partition_path,
309 bool in_memory) const {
310 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
311 // We must have a non-default path, or this will act like the default media
312 // context.
313 CHECK(partition_path != profile_->GetPath());
314 LazyInitialize();
316 // Keep a map of request context getters, one per requested storage partition.
317 StoragePartitionDescriptor descriptor(partition_path, in_memory);
318 ChromeURLRequestContextGetterMap::iterator iter =
319 isolated_media_request_context_getter_map_.find(descriptor);
320 if (iter != isolated_media_request_context_getter_map_.end())
321 return iter->second;
323 // Get the app context as the starting point for the media context, so that
324 // it uses the app's cookie store.
325 ChromeURLRequestContextGetterMap::const_iterator app_iter =
326 app_request_context_getter_map_.find(descriptor);
327 DCHECK(app_iter != app_request_context_getter_map_.end());
328 ChromeURLRequestContextGetter* app_context = app_iter->second.get();
329 ChromeURLRequestContextGetter* context =
330 ChromeURLRequestContextGetter::CreateForIsolatedMedia(
331 profile_, app_context, io_data_, descriptor);
332 isolated_media_request_context_getter_map_[descriptor] = context;
334 return context;
337 DevToolsNetworkController*
338 ProfileImplIOData::Handle::GetDevToolsNetworkController() const {
339 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
340 return io_data_->network_controller();
343 void ProfileImplIOData::Handle::ClearNetworkingHistorySince(
344 base::Time time,
345 const base::Closure& completion) {
346 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
347 LazyInitialize();
349 BrowserThread::PostTask(
350 BrowserThread::IO, FROM_HERE,
351 base::Bind(
352 &ProfileImplIOData::ClearNetworkingHistorySinceOnIOThread,
353 base::Unretained(io_data_),
354 time,
355 completion));
358 void ProfileImplIOData::Handle::LazyInitialize() const {
359 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
360 if (initialized_)
361 return;
363 // Set initialized_ to true at the beginning in case any of the objects
364 // below try to get the ResourceContext pointer.
365 initialized_ = true;
366 PrefService* pref_service = profile_->GetPrefs();
367 io_data_->http_server_properties_manager_ =
368 chrome_browser_net::HttpServerPropertiesManagerFactory::CreateManager(
369 pref_service);
370 io_data_->set_http_server_properties(
371 scoped_ptr<net::HttpServerProperties>(
372 io_data_->http_server_properties_manager_));
373 io_data_->session_startup_pref()->Init(
374 prefs::kRestoreOnStartup, pref_service);
375 io_data_->session_startup_pref()->MoveToThread(
376 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
377 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
378 io_data_->safe_browsing_enabled()->Init(prefs::kSafeBrowsingEnabled,
379 pref_service);
380 io_data_->safe_browsing_enabled()->MoveToThread(
381 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
382 #endif
383 io_data_->InitializeOnUIThread(profile_);
386 scoped_ptr<ProfileIOData::ChromeURLRequestContextGetterVector>
387 ProfileImplIOData::Handle::GetAllContextGetters() {
388 ChromeURLRequestContextGetterMap::iterator iter;
389 scoped_ptr<ChromeURLRequestContextGetterVector> context_getters(
390 new ChromeURLRequestContextGetterVector());
392 iter = isolated_media_request_context_getter_map_.begin();
393 for (; iter != isolated_media_request_context_getter_map_.end(); ++iter)
394 context_getters->push_back(iter->second);
396 iter = app_request_context_getter_map_.begin();
397 for (; iter != app_request_context_getter_map_.end(); ++iter)
398 context_getters->push_back(iter->second);
400 if (extensions_request_context_getter_.get())
401 context_getters->push_back(extensions_request_context_getter_);
403 if (media_request_context_getter_.get())
404 context_getters->push_back(media_request_context_getter_);
406 if (main_request_context_getter_.get())
407 context_getters->push_back(main_request_context_getter_);
409 return context_getters.Pass();
412 ProfileImplIOData::LazyParams::LazyParams()
413 : cache_max_size(0),
414 media_cache_max_size(0),
415 session_cookie_mode(
416 content::CookieStoreConfig::EPHEMERAL_SESSION_COOKIES) {}
418 ProfileImplIOData::LazyParams::~LazyParams() {}
420 ProfileImplIOData::ProfileImplIOData()
421 : ProfileIOData(Profile::REGULAR_PROFILE),
422 http_server_properties_manager_(NULL),
423 app_cache_max_size_(0),
424 app_media_cache_max_size_(0) {
427 ProfileImplIOData::~ProfileImplIOData() {
428 DestroyResourceContext();
430 if (media_request_context_)
431 media_request_context_->AssertNoURLRequests();
434 void ProfileImplIOData::InitializeInternal(
435 scoped_ptr<ChromeNetworkDelegate> chrome_network_delegate,
436 ProfileParams* profile_params,
437 content::ProtocolHandlerMap* protocol_handlers,
438 content::URLRequestInterceptorScopedVector request_interceptors) const {
439 // TODO(vadimt): Remove ScopedTracker below once crbug.com/436671 is fixed.
440 tracked_objects::ScopedTracker tracking_profile(
441 FROM_HERE_WITH_EXPLICIT_FUNCTION(
442 "436671 ProfileImplIOData::InitializeInternal"));
444 // Set up a persistent store for use by the network stack on the IO thread.
445 base::FilePath network_json_store_filepath(
446 profile_path_.Append(chrome::kNetworkPersistentStateFilename));
447 network_json_store_ = new JsonPrefStore(
448 network_json_store_filepath,
449 JsonPrefStore::GetTaskRunnerForFile(network_json_store_filepath,
450 BrowserThread::GetBlockingPool()),
451 scoped_ptr<PrefFilter>());
452 network_json_store_->ReadPrefsAsync(nullptr);
454 net::URLRequestContext* main_context = main_request_context();
456 IOThread* const io_thread = profile_params->io_thread;
457 IOThread::Globals* const io_thread_globals = io_thread->globals();
459 chrome_network_delegate->set_predictor(predictor_.get());
461 if (domain_reliability_monitor_) {
462 // TODO(vadimt): Remove ScopedTracker below once crbug.com/436671 is fixed.
463 tracked_objects::ScopedTracker tracking_profile1(
464 FROM_HERE_WITH_EXPLICIT_FUNCTION(
465 "436671 ProfileImplIOData::InitializeInternal1"));
467 domain_reliability::DomainReliabilityMonitor* monitor =
468 domain_reliability_monitor_.get();
469 monitor->InitURLRequestContext(main_context);
470 monitor->AddBakedInConfigs();
471 monitor->SetDiscardUploads(!GetMetricsEnabledStateOnIOThread());
472 chrome_network_delegate->set_domain_reliability_monitor(monitor);
475 // TODO(vadimt): Remove ScopedTracker below once crbug.com/436671 is fixed.
476 tracked_objects::ScopedTracker tracking_profile2(
477 FROM_HERE_WITH_EXPLICIT_FUNCTION(
478 "436671 ProfileImplIOData::InitializeInternal2"));
480 ApplyProfileParamsToContext(main_context);
482 if (http_server_properties_manager_)
483 http_server_properties_manager_->InitializeOnNetworkThread();
485 main_context->set_transport_security_state(transport_security_state());
487 main_context->set_net_log(io_thread->net_log());
489 network_delegate_ = data_reduction_proxy_io_data()->CreateNetworkDelegate(
490 chrome_network_delegate.Pass(), true).Pass();
492 main_context->set_network_delegate(network_delegate_.get());
494 main_context->set_http_server_properties(http_server_properties());
496 main_context->set_host_resolver(
497 io_thread_globals->host_resolver.get());
498 main_context->set_cert_transparency_verifier(
499 io_thread_globals->cert_transparency_verifier.get());
500 main_context->set_http_auth_handler_factory(
501 io_thread_globals->http_auth_handler_factory.get());
503 main_context->set_fraudulent_certificate_reporter(
504 fraudulent_certificate_reporter());
506 main_context->set_throttler_manager(
507 io_thread_globals->throttler_manager.get());
509 main_context->set_proxy_service(proxy_service());
511 scoped_refptr<net::CookieStore> cookie_store = NULL;
512 net::ChannelIDService* channel_id_service = NULL;
514 // TODO(vadimt): Remove ScopedTracker below once crbug.com/436671 is fixed.
515 tracked_objects::ScopedTracker tracking_profile5(
516 FROM_HERE_WITH_EXPLICIT_FUNCTION(
517 "436671 ProfileImplIOData::InitializeInternal5"));
519 // setup cookie store
520 if (!cookie_store.get()) {
521 DCHECK(!lazy_params_->cookie_path.empty());
523 content::CookieStoreConfig cookie_config(
524 lazy_params_->cookie_path,
525 lazy_params_->session_cookie_mode,
526 lazy_params_->special_storage_policy.get(),
527 profile_params->cookie_monster_delegate.get());
528 cookie_config.crypto_delegate =
529 chrome_browser_net::GetCookieCryptoDelegate();
530 cookie_store = content::CreateCookieStore(cookie_config);
533 main_context->set_cookie_store(cookie_store.get());
535 // TODO(vadimt): Remove ScopedTracker below once crbug.com/436671 is fixed.
536 tracked_objects::ScopedTracker tracking_profile6(
537 FROM_HERE_WITH_EXPLICIT_FUNCTION(
538 "436671 ProfileImplIOData::InitializeInternal6"));
540 // Setup server bound cert service.
541 if (!channel_id_service) {
542 DCHECK(!lazy_params_->channel_id_path.empty());
544 scoped_refptr<QuotaPolicyChannelIDStore> channel_id_db =
545 new QuotaPolicyChannelIDStore(
546 lazy_params_->channel_id_path,
547 BrowserThread::GetBlockingPool()->GetSequencedTaskRunner(
548 BrowserThread::GetBlockingPool()->GetSequenceToken()),
549 lazy_params_->special_storage_policy.get());
550 channel_id_service = new net::ChannelIDService(
551 new net::DefaultChannelIDStore(channel_id_db.get()),
552 base::WorkerPool::GetTaskRunner(true));
555 set_channel_id_service(channel_id_service);
556 main_context->set_channel_id_service(channel_id_service);
558 // TODO(vadimt): Remove ScopedTracker below once crbug.com/436671 is fixed.
559 tracked_objects::ScopedTracker tracking_profile7(
560 FROM_HERE_WITH_EXPLICIT_FUNCTION(
561 "436671 ProfileImplIOData::InitializeInternal7"));
563 net::HttpCache::DefaultBackend* main_backend =
564 new net::HttpCache::DefaultBackend(
565 net::DISK_CACHE,
566 ChooseCacheBackendType(),
567 lazy_params_->cache_path,
568 lazy_params_->cache_max_size,
569 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::CACHE));
570 scoped_ptr<net::HttpCache> main_cache = CreateMainHttpFactory(
571 profile_params, main_backend);
573 // TODO(vadimt): Remove ScopedTracker below once crbug.com/436671 is fixed.
574 tracked_objects::ScopedTracker tracking_profile71(
575 FROM_HERE_WITH_EXPLICIT_FUNCTION(
576 "436671 ProfileImplIOData::InitializeInternal71"));
578 main_cache->InitializeInfiniteCache(lazy_params_->infinite_cache_path);
580 main_http_factory_.reset(main_cache.release());
581 main_context->set_http_transaction_factory(main_http_factory_.get());
583 #if !defined(DISABLE_FTP_SUPPORT)
584 ftp_factory_.reset(
585 new net::FtpNetworkLayer(io_thread_globals->host_resolver.get()));
586 #endif // !defined(DISABLE_FTP_SUPPORT)
588 // TODO(vadimt): Remove ScopedTracker below once crbug.com/436671 is fixed.
589 tracked_objects::ScopedTracker tracking_profile8(
590 FROM_HERE_WITH_EXPLICIT_FUNCTION(
591 "436671 ProfileImplIOData::InitializeInternal8"));
593 scoped_ptr<net::URLRequestJobFactoryImpl> main_job_factory(
594 new net::URLRequestJobFactoryImpl());
595 InstallProtocolHandlers(main_job_factory.get(), protocol_handlers);
597 // The data reduction proxy interceptor should be as close to the network
598 // as possible.
599 request_interceptors.insert(
600 request_interceptors.begin(),
601 data_reduction_proxy_io_data()->CreateInterceptor().release());
602 main_job_factory_ = SetUpJobFactoryDefaults(
603 main_job_factory.Pass(),
604 request_interceptors.Pass(),
605 profile_params->protocol_handler_interceptor.Pass(),
606 main_context->network_delegate(),
607 ftp_factory_.get());
608 main_context->set_job_factory(main_job_factory_.get());
610 // TODO(vadimt): Remove ScopedTracker below once crbug.com/436671 is fixed.
611 tracked_objects::ScopedTracker tracking_profile9(
612 FROM_HERE_WITH_EXPLICIT_FUNCTION(
613 "436671 ProfileImplIOData::InitializeInternal9"));
615 #if defined(ENABLE_EXTENSIONS)
616 InitializeExtensionsRequestContext(profile_params);
617 #endif
619 // Setup SDCH for this profile.
620 sdch_manager_.reset(new net::SdchManager);
621 sdch_policy_.reset(new net::SdchOwner(sdch_manager_.get(), main_context));
622 main_context->set_sdch_manager(sdch_manager_.get());
623 if (ShouldUseSdchPersistence()) {
624 sdch_policy_->EnablePersistentStorage(network_json_store_.get());
627 // Create a media request context based on the main context, but using a
628 // media cache. It shares the same job factory as the main context.
629 StoragePartitionDescriptor details(profile_path_, false);
630 media_request_context_.reset(InitializeMediaRequestContext(main_context,
631 details));
633 lazy_params_.reset();
636 void ProfileImplIOData::
637 InitializeExtensionsRequestContext(ProfileParams* profile_params) const {
638 net::URLRequestContext* extensions_context = extensions_request_context();
639 IOThread* const io_thread = profile_params->io_thread;
640 IOThread::Globals* const io_thread_globals = io_thread->globals();
641 ApplyProfileParamsToContext(extensions_context);
643 extensions_context->set_transport_security_state(transport_security_state());
645 extensions_context->set_net_log(io_thread->net_log());
647 extensions_context->set_throttler_manager(
648 io_thread_globals->throttler_manager.get());
650 content::CookieStoreConfig cookie_config(
651 lazy_params_->extensions_cookie_path,
652 lazy_params_->session_cookie_mode,
653 NULL, NULL);
654 cookie_config.crypto_delegate =
655 chrome_browser_net::GetCookieCryptoDelegate();
656 net::CookieStore* extensions_cookie_store =
657 content::CreateCookieStore(cookie_config);
658 // Enable cookies for devtools and extension URLs.
659 const char* const schemes[] = {
660 content::kChromeDevToolsScheme,
661 extensions::kExtensionScheme
663 extensions_cookie_store->GetCookieMonster()->SetCookieableSchemes(
664 schemes, arraysize(schemes));
665 extensions_context->set_cookie_store(extensions_cookie_store);
667 scoped_ptr<net::URLRequestJobFactoryImpl> extensions_job_factory(
668 new net::URLRequestJobFactoryImpl());
669 // TODO(shalev): The extensions_job_factory has a NULL NetworkDelegate.
670 // Without a network_delegate, this protocol handler will never
671 // handle file: requests, but as a side effect it makes
672 // job_factory::IsHandledProtocol return true, which prevents attempts to
673 // handle the protocol externally. We pass NULL in to
674 // SetUpJobFactory() to get this effect.
675 extensions_job_factory_ = SetUpJobFactoryDefaults(
676 extensions_job_factory.Pass(),
677 content::URLRequestInterceptorScopedVector(),
678 scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>(),
679 NULL,
680 ftp_factory_.get());
681 extensions_context->set_job_factory(extensions_job_factory_.get());
684 net::URLRequestContext* ProfileImplIOData::InitializeAppRequestContext(
685 net::URLRequestContext* main_context,
686 const StoragePartitionDescriptor& partition_descriptor,
687 scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
688 protocol_handler_interceptor,
689 content::ProtocolHandlerMap* protocol_handlers,
690 content::URLRequestInterceptorScopedVector request_interceptors) const {
691 // Copy most state from the main context.
692 AppRequestContext* context = new AppRequestContext();
693 context->CopyFrom(main_context);
695 base::FilePath cookie_path = partition_descriptor.path.Append(
696 chrome::kCookieFilename);
697 base::FilePath cache_path =
698 partition_descriptor.path.Append(chrome::kCacheDirname);
700 // Use a separate HTTP disk cache for isolated apps.
701 net::HttpCache::BackendFactory* app_backend = NULL;
702 if (partition_descriptor.in_memory) {
703 app_backend = net::HttpCache::DefaultBackend::InMemory(0);
704 } else {
705 app_backend = new net::HttpCache::DefaultBackend(
706 net::DISK_CACHE,
707 ChooseCacheBackendType(),
708 cache_path,
709 app_cache_max_size_,
710 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::CACHE));
712 net::HttpNetworkSession* main_network_session =
713 main_http_factory_->GetSession();
714 scoped_ptr<net::HttpCache> app_http_cache =
715 CreateHttpFactory(main_network_session, app_backend);
717 scoped_refptr<net::CookieStore> cookie_store = NULL;
718 if (partition_descriptor.in_memory) {
719 cookie_store = content::CreateCookieStore(content::CookieStoreConfig());
722 // Use an app-specific cookie store.
723 if (!cookie_store.get()) {
724 DCHECK(!cookie_path.empty());
726 // TODO(creis): We should have a cookie delegate for notifying the cookie
727 // extensions API, but we need to update it to understand isolated apps
728 // first.
729 content::CookieStoreConfig cookie_config(
730 cookie_path,
731 content::CookieStoreConfig::EPHEMERAL_SESSION_COOKIES,
732 NULL, NULL);
733 cookie_config.crypto_delegate =
734 chrome_browser_net::GetCookieCryptoDelegate();
735 cookie_store = content::CreateCookieStore(cookie_config);
738 // Transfer ownership of the cookies and cache to AppRequestContext.
739 context->SetCookieStore(cookie_store.get());
740 context->SetHttpTransactionFactory(app_http_cache.Pass());
742 scoped_ptr<net::URLRequestJobFactoryImpl> job_factory(
743 new net::URLRequestJobFactoryImpl());
744 InstallProtocolHandlers(job_factory.get(), protocol_handlers);
745 // The data reduction proxy interceptor should be as close to the network
746 // as possible.
747 request_interceptors.insert(
748 request_interceptors.begin(),
749 data_reduction_proxy_io_data()->CreateInterceptor().release());
750 scoped_ptr<net::URLRequestJobFactory> top_job_factory(
751 SetUpJobFactoryDefaults(job_factory.Pass(),
752 request_interceptors.Pass(),
753 protocol_handler_interceptor.Pass(),
754 main_context->network_delegate(),
755 ftp_factory_.get()));
756 context->SetJobFactory(top_job_factory.Pass());
758 return context;
761 net::URLRequestContext*
762 ProfileImplIOData::InitializeMediaRequestContext(
763 net::URLRequestContext* original_context,
764 const StoragePartitionDescriptor& partition_descriptor) const {
765 // Copy most state from the original context.
766 MediaRequestContext* context = new MediaRequestContext();
767 context->CopyFrom(original_context);
769 // For in-memory context, return immediately after creating the new
770 // context before attaching a separate cache. It is important to return
771 // a new context rather than just reusing |original_context| because
772 // the caller expects to take ownership of the pointer.
773 if (partition_descriptor.in_memory)
774 return context;
776 using content::StoragePartition;
777 base::FilePath cache_path;
778 int cache_max_size = app_media_cache_max_size_;
779 if (partition_descriptor.path == profile_path_) {
780 // lazy_params_ is only valid for the default media context creation.
781 cache_path = lazy_params_->media_cache_path;
782 cache_max_size = lazy_params_->media_cache_max_size;
783 } else {
784 cache_path = partition_descriptor.path.Append(chrome::kMediaCacheDirname);
787 // Use a separate HTTP disk cache for isolated apps.
788 net::HttpCache::BackendFactory* media_backend =
789 new net::HttpCache::DefaultBackend(
790 net::MEDIA_CACHE,
791 ChooseCacheBackendType(),
792 cache_path,
793 cache_max_size,
794 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::CACHE));
795 net::HttpNetworkSession* main_network_session =
796 main_http_factory_->GetSession();
797 scoped_ptr<net::HttpCache> media_http_cache =
798 CreateHttpFactory(main_network_session, media_backend);
800 // Transfer ownership of the cache to MediaRequestContext.
801 context->SetHttpTransactionFactory(media_http_cache.Pass());
803 // Note that we do not create a new URLRequestJobFactory because
804 // the media context should behave exactly like its parent context
805 // in all respects except for cache behavior on media subresources.
806 // The CopyFrom() step above means that our media context will use
807 // the same URLRequestJobFactory instance that our parent context does.
809 return context;
812 net::URLRequestContext*
813 ProfileImplIOData::AcquireMediaRequestContext() const {
814 DCHECK(media_request_context_);
815 return media_request_context_.get();
818 net::URLRequestContext* ProfileImplIOData::AcquireIsolatedAppRequestContext(
819 net::URLRequestContext* main_context,
820 const StoragePartitionDescriptor& partition_descriptor,
821 scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
822 protocol_handler_interceptor,
823 content::ProtocolHandlerMap* protocol_handlers,
824 content::URLRequestInterceptorScopedVector request_interceptors) const {
825 // We create per-app contexts on demand, unlike the others above.
826 net::URLRequestContext* app_request_context =
827 InitializeAppRequestContext(main_context,
828 partition_descriptor,
829 protocol_handler_interceptor.Pass(),
830 protocol_handlers,
831 request_interceptors.Pass());
832 DCHECK(app_request_context);
833 return app_request_context;
836 net::URLRequestContext*
837 ProfileImplIOData::AcquireIsolatedMediaRequestContext(
838 net::URLRequestContext* app_context,
839 const StoragePartitionDescriptor& partition_descriptor) const {
840 // We create per-app media contexts on demand, unlike the others above.
841 net::URLRequestContext* media_request_context =
842 InitializeMediaRequestContext(app_context, partition_descriptor);
843 DCHECK(media_request_context);
844 return media_request_context;
847 void ProfileImplIOData::ClearNetworkingHistorySinceOnIOThread(
848 base::Time time,
849 const base::Closure& completion) {
850 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
851 DCHECK(initialized());
853 DCHECK(transport_security_state());
854 // Completes synchronously.
855 transport_security_state()->DeleteAllDynamicDataSince(time);
856 DCHECK(http_server_properties_manager_);
857 http_server_properties_manager_->Clear(completion);