Upstream version 10.38.220.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / profiles / profile_impl_io_data.cc
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.
4
5 #include "chrome/browser/profiles/profile_impl_io_data.h"
6
7 #include "base/bind.h"
8 #include "base/command_line.h"
9 #include "base/logging.h"
10 #include "base/metrics/field_trial.h"
11 #include "base/prefs/pref_member.h"
12 #include "base/prefs/pref_service.h"
13 #include "base/sequenced_task_runner.h"
14 #include "base/stl_util.h"
15 #include "base/strings/string_util.h"
16 #include "base/threading/sequenced_worker_pool.h"
17 #include "base/threading/worker_pool.h"
18 #include "chrome/browser/chrome_notification_types.h"
19 #include "chrome/browser/chromeos/profiles/profile_helper.h"
20 #include "chrome/browser/custom_handlers/protocol_handler_registry.h"
21 #include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h"
22 #include "chrome/browser/io_thread.h"
23 #include "chrome/browser/net/chrome_net_log.h"
24 #include "chrome/browser/net/chrome_network_delegate.h"
25 #include "chrome/browser/net/connect_interceptor.h"
26 #include "chrome/browser/net/cookie_store_util.h"
27 #include "chrome/browser/net/http_server_properties_manager_factory.h"
28 #include "chrome/browser/net/predictor.h"
29 #include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_configurator.h"
30 #include "chrome/browser/net/sqlite_channel_id_store.h"
31 #include "chrome/browser/profiles/profile.h"
32 #include "chrome/common/chrome_constants.h"
33 #include "chrome/common/chrome_switches.h"
34 #include "chrome/common/pref_names.h"
35 #include "chrome/common/url_constants.h"
36 #include "components/domain_reliability/monitor.h"
37 #include "content/public/browser/browser_thread.h"
38 #include "content/public/browser/cookie_store_factory.h"
39 #include "content/public/browser/notification_service.h"
40 #include "content/public/browser/resource_context.h"
41 #include "content/public/browser/storage_partition.h"
42 #include "extensions/browser/extension_protocols.h"
43 #include "extensions/common/constants.h"
44 #include "net/base/cache_type.h"
45 #include "net/base/sdch_dictionary_fetcher.h"
46 #include "net/base/sdch_manager.h"
47 #include "net/ftp/ftp_network_layer.h"
48 #include "net/http/http_cache.h"
49 #include "net/http/http_server_properties_manager.h"
50 #include "net/ssl/channel_id_service.h"
51 #include "net/url_request/url_request_job_factory_impl.h"
52 #include "webkit/browser/quota/special_storage_policy.h"
53
54 #if defined(SPDY_PROXY_AUTH_ORIGIN)
55 #include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings.h"
56 #include "components/data_reduction_proxy/browser/data_reduction_proxy_auth_request_handler.h"
57 #include "components/data_reduction_proxy/browser/data_reduction_proxy_protocol.h"
58 #include "components/data_reduction_proxy/browser/data_reduction_proxy_usage_stats.h"
59 #include "components/data_reduction_proxy/common/data_reduction_proxy_pref_names.h"
60 #endif  // defined(SPDY_PROXY_AUTH_ORIGIN)
61
62 namespace {
63
64 net::BackendType ChooseCacheBackendType() {
65 #if defined(OS_ANDROID)
66   return net::CACHE_BACKEND_SIMPLE;
67 #else
68   const CommandLine& command_line = *CommandLine::ForCurrentProcess();
69   if (command_line.HasSwitch(switches::kUseSimpleCacheBackend)) {
70     const std::string opt_value =
71         command_line.GetSwitchValueASCII(switches::kUseSimpleCacheBackend);
72     if (LowerCaseEqualsASCII(opt_value, "off"))
73       return net::CACHE_BACKEND_BLOCKFILE;
74     if (opt_value == "" || LowerCaseEqualsASCII(opt_value, "on"))
75       return net::CACHE_BACKEND_SIMPLE;
76   }
77   const std::string experiment_name =
78       base::FieldTrialList::FindFullName("SimpleCacheTrial");
79   if (experiment_name == "ExperimentYes" ||
80       experiment_name == "ExperimentYes2") {
81     return net::CACHE_BACKEND_SIMPLE;
82   }
83   return net::CACHE_BACKEND_BLOCKFILE;
84 #endif
85 }
86
87 }  // namespace
88
89 using content::BrowserThread;
90 #if defined(SPDY_PROXY_AUTH_ORIGIN)
91 using data_reduction_proxy::DataReductionProxyParams;
92 #endif  // defined(SPDY_PROXY_AUTH_ORIGIN)
93
94 ProfileImplIOData::Handle::Handle(Profile* profile)
95     : io_data_(new ProfileImplIOData),
96       profile_(profile),
97       initialized_(false) {
98   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
99   DCHECK(profile);
100 }
101
102 ProfileImplIOData::Handle::~Handle() {
103   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
104   if (io_data_->predictor_ != NULL) {
105     // io_data_->predictor_ might be NULL if Init() was never called
106     // (i.e. we shut down before ProfileImpl::DoFinalInit() got called).
107     bool save_prefs = true;
108 #if defined(OS_CHROMEOS)
109     save_prefs = !chromeos::ProfileHelper::IsSigninProfile(profile_);
110 #endif
111     if (save_prefs)
112       io_data_->predictor_->SaveStateForNextStartupAndTrim();
113     io_data_->predictor_->ShutdownOnUIThread();
114   }
115
116   if (io_data_->http_server_properties_manager_)
117     io_data_->http_server_properties_manager_->ShutdownOnPrefThread();
118
119   io_data_->ShutdownOnUIThread(GetAllContextGetters().Pass());
120 }
121
122 void ProfileImplIOData::Handle::Init(
123       const base::FilePath& cookie_path,
124       const base::FilePath& channel_id_path,
125       const base::FilePath& cache_path,
126       int cache_max_size,
127       const base::FilePath& media_cache_path,
128       int media_cache_max_size,
129       const base::FilePath& extensions_cookie_path,
130       const base::FilePath& profile_path,
131       const base::FilePath& infinite_cache_path,
132       chrome_browser_net::Predictor* predictor,
133       content::CookieStoreConfig::SessionCookieMode session_cookie_mode,
134       quota::SpecialStoragePolicy* special_storage_policy,
135       scoped_ptr<domain_reliability::DomainReliabilityMonitor>
136           domain_reliability_monitor,
137       const base::Callback<void(bool)>& data_reduction_proxy_unavailable,
138       scoped_ptr<DataReductionProxyChromeConfigurator>
139           data_reduction_proxy_chrome_configurator,
140       scoped_ptr<data_reduction_proxy::DataReductionProxyParams>
141           data_reduction_proxy_params) {
142   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
143   DCHECK(!io_data_->lazy_params_);
144   DCHECK(predictor);
145
146   LazyParams* lazy_params = new LazyParams();
147
148   lazy_params->cookie_path = cookie_path;
149   lazy_params->channel_id_path = channel_id_path;
150   lazy_params->cache_path = cache_path;
151   lazy_params->cache_max_size = cache_max_size;
152   lazy_params->media_cache_path = media_cache_path;
153   lazy_params->media_cache_max_size = media_cache_max_size;
154   lazy_params->extensions_cookie_path = extensions_cookie_path;
155   lazy_params->infinite_cache_path = infinite_cache_path;
156   lazy_params->session_cookie_mode = session_cookie_mode;
157   lazy_params->special_storage_policy = special_storage_policy;
158
159   io_data_->lazy_params_.reset(lazy_params);
160
161   // Keep track of profile path and cache sizes separately so we can use them
162   // on demand when creating storage isolated URLRequestContextGetters.
163   io_data_->profile_path_ = profile_path;
164   io_data_->app_cache_max_size_ = cache_max_size;
165   io_data_->app_media_cache_max_size_ = media_cache_max_size;
166
167   io_data_->predictor_.reset(predictor);
168   io_data_->domain_reliability_monitor_ = domain_reliability_monitor.Pass();
169
170   io_data_->InitializeMetricsEnabledStateOnUIThread();
171
172 #if defined(SPDY_PROXY_AUTH_ORIGIN)
173   io_data_->data_reduction_proxy_unavailable_callback_ =
174       data_reduction_proxy_unavailable;
175   io_data_->data_reduction_proxy_chrome_configurator_ =
176       data_reduction_proxy_chrome_configurator.Pass();
177   io_data_->data_reduction_proxy_params_ =
178       data_reduction_proxy_params.Pass();
179 #endif  // defined(SPDY_PROXY_AUTH_ORIGIN)
180 }
181
182 content::ResourceContext*
183     ProfileImplIOData::Handle::GetResourceContext() const {
184   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
185   LazyInitialize();
186   return GetResourceContextNoInit();
187 }
188
189 content::ResourceContext*
190 ProfileImplIOData::Handle::GetResourceContextNoInit() const {
191   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
192   // Don't call LazyInitialize here, since the resource context is created at
193   // the beginning of initalization and is used by some members while they're
194   // being initialized (i.e. AppCacheService).
195   return io_data_->GetResourceContext();
196 }
197
198 scoped_refptr<ChromeURLRequestContextGetter>
199 ProfileImplIOData::Handle::CreateMainRequestContextGetter(
200     content::ProtocolHandlerMap* protocol_handlers,
201     content::URLRequestInterceptorScopedVector request_interceptors,
202     PrefService* local_state,
203     IOThread* io_thread) const {
204   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
205   LazyInitialize();
206   DCHECK(!main_request_context_getter_.get());
207   main_request_context_getter_ = ChromeURLRequestContextGetter::Create(
208       profile_, io_data_, protocol_handlers, request_interceptors.Pass());
209
210   io_data_->predictor_
211       ->InitNetworkPredictor(profile_->GetPrefs(),
212                              local_state,
213                              io_thread,
214                              main_request_context_getter_.get(),
215                              io_data_);
216
217   content::NotificationService::current()->Notify(
218       chrome::NOTIFICATION_PROFILE_URL_REQUEST_CONTEXT_GETTER_INITIALIZED,
219       content::Source<Profile>(profile_),
220       content::NotificationService::NoDetails());
221   return main_request_context_getter_;
222 }
223
224 scoped_refptr<ChromeURLRequestContextGetter>
225 ProfileImplIOData::Handle::GetMediaRequestContextGetter() const {
226   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
227   LazyInitialize();
228   if (!media_request_context_getter_.get()) {
229     media_request_context_getter_ =
230         ChromeURLRequestContextGetter::CreateForMedia(profile_, io_data_);
231   }
232   return media_request_context_getter_;
233 }
234
235 scoped_refptr<ChromeURLRequestContextGetter>
236 ProfileImplIOData::Handle::GetExtensionsRequestContextGetter() const {
237   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
238   LazyInitialize();
239   if (!extensions_request_context_getter_.get()) {
240     extensions_request_context_getter_ =
241         ChromeURLRequestContextGetter::CreateForExtensions(profile_, io_data_);
242   }
243   return extensions_request_context_getter_;
244 }
245
246 scoped_refptr<ChromeURLRequestContextGetter>
247 ProfileImplIOData::Handle::CreateIsolatedAppRequestContextGetter(
248     const base::FilePath& partition_path,
249     bool in_memory,
250     content::ProtocolHandlerMap* protocol_handlers,
251     content::URLRequestInterceptorScopedVector request_interceptors) const {
252   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
253   // Check that the partition_path is not the same as the base profile path. We
254   // expect isolated partition, which will never go to the default profile path.
255   CHECK(partition_path != profile_->GetPath());
256   LazyInitialize();
257
258   // Keep a map of request context getters, one per requested storage partition.
259   StoragePartitionDescriptor descriptor(partition_path, in_memory);
260   ChromeURLRequestContextGetterMap::iterator iter =
261       app_request_context_getter_map_.find(descriptor);
262   if (iter != app_request_context_getter_map_.end())
263     return iter->second;
264
265   scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
266       protocol_handler_interceptor(
267           ProtocolHandlerRegistryFactory::GetForBrowserContext(profile_)->
268               CreateJobInterceptorFactory());
269   ChromeURLRequestContextGetter* context =
270       ChromeURLRequestContextGetter::CreateForIsolatedApp(
271           profile_,
272           io_data_,
273           descriptor,
274           protocol_handler_interceptor.Pass(),
275           protocol_handlers,
276           request_interceptors.Pass());
277   app_request_context_getter_map_[descriptor] = context;
278
279   return context;
280 }
281
282 scoped_refptr<ChromeURLRequestContextGetter>
283 ProfileImplIOData::Handle::GetIsolatedMediaRequestContextGetter(
284     const base::FilePath& partition_path,
285     bool in_memory) const {
286   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
287   // We must have a non-default path, or this will act like the default media
288   // context.
289   CHECK(partition_path != profile_->GetPath());
290   LazyInitialize();
291
292   // Keep a map of request context getters, one per requested storage partition.
293   StoragePartitionDescriptor descriptor(partition_path, in_memory);
294   ChromeURLRequestContextGetterMap::iterator iter =
295       isolated_media_request_context_getter_map_.find(descriptor);
296   if (iter != isolated_media_request_context_getter_map_.end())
297     return iter->second;
298
299   // Get the app context as the starting point for the media context, so that
300   // it uses the app's cookie store.
301   ChromeURLRequestContextGetterMap::const_iterator app_iter =
302       app_request_context_getter_map_.find(descriptor);
303   DCHECK(app_iter != app_request_context_getter_map_.end());
304   ChromeURLRequestContextGetter* app_context = app_iter->second.get();
305   ChromeURLRequestContextGetter* context =
306       ChromeURLRequestContextGetter::CreateForIsolatedMedia(
307           profile_, app_context, io_data_, descriptor);
308   isolated_media_request_context_getter_map_[descriptor] = context;
309
310   return context;
311 }
312
313 DevToolsNetworkController*
314 ProfileImplIOData::Handle::GetDevToolsNetworkController() const {
315   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
316   return io_data_->network_controller();
317 }
318
319 void ProfileImplIOData::Handle::ClearNetworkingHistorySince(
320     base::Time time,
321     const base::Closure& completion) {
322   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
323   LazyInitialize();
324
325   BrowserThread::PostTask(
326       BrowserThread::IO, FROM_HERE,
327       base::Bind(
328           &ProfileImplIOData::ClearNetworkingHistorySinceOnIOThread,
329           base::Unretained(io_data_),
330           time,
331           completion));
332 }
333
334 void ProfileImplIOData::Handle::LazyInitialize() const {
335   if (initialized_)
336     return;
337
338   // Set initialized_ to true at the beginning in case any of the objects
339   // below try to get the ResourceContext pointer.
340   initialized_ = true;
341   PrefService* pref_service = profile_->GetPrefs();
342   io_data_->http_server_properties_manager_ =
343       chrome_browser_net::HttpServerPropertiesManagerFactory::CreateManager(
344           pref_service);
345   io_data_->set_http_server_properties(
346       scoped_ptr<net::HttpServerProperties>(
347           io_data_->http_server_properties_manager_));
348   io_data_->session_startup_pref()->Init(
349       prefs::kRestoreOnStartup, pref_service);
350   io_data_->session_startup_pref()->MoveToThread(
351       BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
352 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
353   io_data_->safe_browsing_enabled()->Init(prefs::kSafeBrowsingEnabled,
354       pref_service);
355   io_data_->safe_browsing_enabled()->MoveToThread(
356       BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
357 #endif
358 #if defined(SPDY_PROXY_AUTH_ORIGIN)
359   io_data_->data_reduction_proxy_enabled()->Init(
360       data_reduction_proxy::prefs::kDataReductionProxyEnabled, pref_service);
361   io_data_->data_reduction_proxy_enabled()->MoveToThread(
362       BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
363 #endif  // defined(SPDY_PROXY_AUTH_ORIGIN)
364   io_data_->InitializeOnUIThread(profile_);
365 }
366
367 scoped_ptr<ProfileIOData::ChromeURLRequestContextGetterVector>
368 ProfileImplIOData::Handle::GetAllContextGetters() {
369   ChromeURLRequestContextGetterMap::iterator iter;
370   scoped_ptr<ChromeURLRequestContextGetterVector> context_getters(
371       new ChromeURLRequestContextGetterVector());
372
373   iter = isolated_media_request_context_getter_map_.begin();
374   for (; iter != isolated_media_request_context_getter_map_.end(); ++iter)
375     context_getters->push_back(iter->second);
376
377   iter = app_request_context_getter_map_.begin();
378   for (; iter != app_request_context_getter_map_.end(); ++iter)
379     context_getters->push_back(iter->second);
380
381   if (extensions_request_context_getter_)
382     context_getters->push_back(extensions_request_context_getter_);
383
384   if (media_request_context_getter_)
385     context_getters->push_back(media_request_context_getter_);
386
387   if (main_request_context_getter_)
388     context_getters->push_back(main_request_context_getter_);
389
390   return context_getters.Pass();
391 }
392
393 ProfileImplIOData::LazyParams::LazyParams()
394     : cache_max_size(0),
395       media_cache_max_size(0),
396       session_cookie_mode(
397           content::CookieStoreConfig::EPHEMERAL_SESSION_COOKIES) {}
398
399 ProfileImplIOData::LazyParams::~LazyParams() {}
400
401 ProfileImplIOData::ProfileImplIOData()
402     : ProfileIOData(Profile::REGULAR_PROFILE),
403       http_server_properties_manager_(NULL),
404       app_cache_max_size_(0),
405       app_media_cache_max_size_(0) {
406 }
407
408 ProfileImplIOData::~ProfileImplIOData() {
409   if (initialized())
410     network_delegate()->set_domain_reliability_monitor(NULL);
411
412   DestroyResourceContext();
413
414   if (media_request_context_)
415     media_request_context_->AssertNoURLRequests();
416 }
417
418 void ProfileImplIOData::InitializeInternal(
419     ProfileParams* profile_params,
420     content::ProtocolHandlerMap* protocol_handlers,
421     content::URLRequestInterceptorScopedVector request_interceptors) const {
422   net::URLRequestContext* main_context = main_request_context();
423
424   IOThread* const io_thread = profile_params->io_thread;
425   IOThread::Globals* const io_thread_globals = io_thread->globals();
426
427 #if defined(SPDY_PROXY_AUTH_ORIGIN)
428   data_reduction_proxy_auth_request_handler_.reset(
429       new data_reduction_proxy::DataReductionProxyAuthRequestHandler(
430           DataReductionProxyChromeSettings::GetClient(),
431           data_reduction_proxy_params_.get(),
432           BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)));
433   data_reduction_proxy_usage_stats_.reset(
434       new data_reduction_proxy::DataReductionProxyUsageStats(
435           data_reduction_proxy_params_.get(),
436           BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI)));
437   data_reduction_proxy_usage_stats_->set_unavailable_callback(
438       data_reduction_proxy_unavailable_callback_);
439
440
441   network_delegate()->set_data_reduction_proxy_params(
442       data_reduction_proxy_params_.get());
443   network_delegate()->set_data_reduction_proxy_usage_stats(
444       data_reduction_proxy_usage_stats_.get());
445   network_delegate()->set_data_reduction_proxy_auth_request_handler(
446       data_reduction_proxy_auth_request_handler_.get());
447   network_delegate()->set_on_resolve_proxy_handler(
448       base::Bind(data_reduction_proxy::OnResolveProxyHandler));
449   network_delegate()->set_proxy_config_getter(
450       base::Bind(
451           &DataReductionProxyChromeConfigurator::GetProxyConfigOnIO,
452           base::Unretained(data_reduction_proxy_chrome_configurator_.get())));
453 #endif  // defined(SPDY_PROXY_AUTH_ORIGIN)
454
455   network_delegate()->set_predictor(predictor_.get());
456
457   // Initialize context members.
458
459   ApplyProfileParamsToContext(main_context);
460
461   if (http_server_properties_manager_)
462     http_server_properties_manager_->InitializeOnNetworkThread();
463
464   main_context->set_transport_security_state(transport_security_state());
465
466   main_context->set_net_log(io_thread->net_log());
467
468   main_context->set_network_delegate(network_delegate());
469
470   main_context->set_http_server_properties(http_server_properties());
471
472   main_context->set_host_resolver(
473       io_thread_globals->host_resolver.get());
474   main_context->set_cert_transparency_verifier(
475       io_thread_globals->cert_transparency_verifier.get());
476   main_context->set_http_auth_handler_factory(
477       io_thread_globals->http_auth_handler_factory.get());
478
479   main_context->set_fraudulent_certificate_reporter(
480       fraudulent_certificate_reporter());
481
482   main_context->set_throttler_manager(
483       io_thread_globals->throttler_manager.get());
484
485   main_context->set_proxy_service(proxy_service());
486
487   scoped_refptr<net::CookieStore> cookie_store = NULL;
488   net::ChannelIDService* channel_id_service = NULL;
489   if (chrome_browser_net::ShouldUseInMemoryCookiesAndCache()) {
490     // Don't use existing cookies and use an in-memory store.
491     using content::CookieStoreConfig;
492     cookie_store = content::CreateCookieStore(CookieStoreConfig(
493         base::FilePath(),
494         CookieStoreConfig::EPHEMERAL_SESSION_COOKIES,
495         NULL,
496         profile_params->cookie_monster_delegate.get()));
497     // Don't use existing channel ids and use an in-memory store.
498     channel_id_service = new net::ChannelIDService(
499         new net::DefaultChannelIDStore(NULL),
500         base::WorkerPool::GetTaskRunner(true));
501   }
502
503
504   // setup cookie store
505   if (!cookie_store.get()) {
506     DCHECK(!lazy_params_->cookie_path.empty());
507
508     content::CookieStoreConfig cookie_config(
509         lazy_params_->cookie_path,
510         lazy_params_->session_cookie_mode,
511         lazy_params_->special_storage_policy.get(),
512         profile_params->cookie_monster_delegate.get());
513     cookie_config.crypto_delegate =
514       chrome_browser_net::GetCookieCryptoDelegate();
515     cookie_store = content::CreateCookieStore(cookie_config);
516   }
517
518   main_context->set_cookie_store(cookie_store.get());
519
520   // Setup server bound cert service.
521   if (!channel_id_service) {
522     DCHECK(!lazy_params_->channel_id_path.empty());
523
524     scoped_refptr<SQLiteChannelIDStore> channel_id_db =
525         new SQLiteChannelIDStore(
526             lazy_params_->channel_id_path,
527             BrowserThread::GetBlockingPool()->GetSequencedTaskRunner(
528                 BrowserThread::GetBlockingPool()->GetSequenceToken()),
529             lazy_params_->special_storage_policy.get());
530     channel_id_service = new net::ChannelIDService(
531         new net::DefaultChannelIDStore(channel_id_db.get()),
532         base::WorkerPool::GetTaskRunner(true));
533   }
534
535   set_channel_id_service(channel_id_service);
536   main_context->set_channel_id_service(channel_id_service);
537
538   net::HttpCache::DefaultBackend* main_backend =
539       new net::HttpCache::DefaultBackend(
540           net::DISK_CACHE,
541           ChooseCacheBackendType(),
542           lazy_params_->cache_path,
543           lazy_params_->cache_max_size,
544           BrowserThread::GetMessageLoopProxyForThread(BrowserThread::CACHE)
545               .get());
546   scoped_ptr<net::HttpCache> main_cache = CreateMainHttpFactory(
547       profile_params, main_backend);
548   main_cache->InitializeInfiniteCache(lazy_params_->infinite_cache_path);
549
550   if (chrome_browser_net::ShouldUseInMemoryCookiesAndCache()) {
551     main_cache->set_mode(
552         chrome_browser_net::IsCookieRecordMode() ?
553         net::HttpCache::RECORD : net::HttpCache::PLAYBACK);
554   }
555
556   main_http_factory_.reset(main_cache.release());
557   main_context->set_http_transaction_factory(main_http_factory_.get());
558
559 #if !defined(DISABLE_FTP_SUPPORT)
560   ftp_factory_.reset(
561       new net::FtpNetworkLayer(io_thread_globals->host_resolver.get()));
562 #endif  // !defined(DISABLE_FTP_SUPPORT)
563
564   scoped_ptr<net::URLRequestJobFactoryImpl> main_job_factory(
565       new net::URLRequestJobFactoryImpl());
566   InstallProtocolHandlers(main_job_factory.get(), protocol_handlers);
567   main_job_factory_ = SetUpJobFactoryDefaults(
568       main_job_factory.Pass(),
569       request_interceptors.Pass(),
570       profile_params->protocol_handler_interceptor.Pass(),
571       network_delegate(),
572       ftp_factory_.get());
573   main_context->set_job_factory(main_job_factory_.get());
574
575 #if defined(ENABLE_EXTENSIONS)
576   InitializeExtensionsRequestContext(profile_params);
577 #endif
578
579   // Setup the SDCHManager for this profile.
580   sdch_manager_.reset(new net::SdchManager);
581   sdch_manager_->set_sdch_fetcher(
582       new net::SdchDictionaryFetcher(
583           sdch_manager_.get(),
584           // SdchDictionaryFetcher takes a reference to the Getter, and
585           // hence implicitly takes ownership.
586           new net::TrivialURLRequestContextGetter(
587               main_context,
588               content::BrowserThread::GetMessageLoopProxyForThread(
589                   content::BrowserThread::IO))));
590   main_context->set_sdch_manager(sdch_manager_.get());
591
592   // Create a media request context based on the main context, but using a
593   // media cache.  It shares the same job factory as the main context.
594   StoragePartitionDescriptor details(profile_path_, false);
595   media_request_context_.reset(InitializeMediaRequestContext(main_context,
596                                                              details));
597
598   if (domain_reliability_monitor_) {
599     domain_reliability_monitor_->Init(
600         main_context,
601         BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
602     domain_reliability_monitor_->AddBakedInConfigs();
603     network_delegate()->set_domain_reliability_monitor(
604         domain_reliability_monitor_.get());
605   }
606
607   lazy_params_.reset();
608 }
609
610 void ProfileImplIOData::
611     InitializeExtensionsRequestContext(ProfileParams* profile_params) const {
612   net::URLRequestContext* extensions_context = extensions_request_context();
613   IOThread* const io_thread = profile_params->io_thread;
614   IOThread::Globals* const io_thread_globals = io_thread->globals();
615   ApplyProfileParamsToContext(extensions_context);
616
617   extensions_context->set_transport_security_state(transport_security_state());
618
619   extensions_context->set_net_log(io_thread->net_log());
620
621   extensions_context->set_throttler_manager(
622       io_thread_globals->throttler_manager.get());
623
624   content::CookieStoreConfig cookie_config(
625       lazy_params_->extensions_cookie_path,
626       lazy_params_->session_cookie_mode,
627       NULL, NULL);
628   cookie_config.crypto_delegate =
629       chrome_browser_net::GetCookieCryptoDelegate();
630   net::CookieStore* extensions_cookie_store =
631       content::CreateCookieStore(cookie_config);
632   // Enable cookies for devtools and extension URLs.
633   const char* const schemes[] = {
634       content::kChromeDevToolsScheme,
635       extensions::kExtensionScheme
636   };
637   extensions_cookie_store->GetCookieMonster()->SetCookieableSchemes(
638       schemes, arraysize(schemes));
639   extensions_context->set_cookie_store(extensions_cookie_store);
640
641   scoped_ptr<net::URLRequestJobFactoryImpl> extensions_job_factory(
642       new net::URLRequestJobFactoryImpl());
643   // TODO(shalev): The extensions_job_factory has a NULL NetworkDelegate.
644   // Without a network_delegate, this protocol handler will never
645   // handle file: requests, but as a side effect it makes
646   // job_factory::IsHandledProtocol return true, which prevents attempts to
647   // handle the protocol externally. We pass NULL in to
648   // SetUpJobFactory() to get this effect.
649   extensions_job_factory_ = SetUpJobFactoryDefaults(
650       extensions_job_factory.Pass(),
651       content::URLRequestInterceptorScopedVector(),
652       scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>(),
653       NULL,
654       ftp_factory_.get());
655   extensions_context->set_job_factory(extensions_job_factory_.get());
656 }
657
658 net::URLRequestContext* ProfileImplIOData::InitializeAppRequestContext(
659     net::URLRequestContext* main_context,
660     const StoragePartitionDescriptor& partition_descriptor,
661     scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
662         protocol_handler_interceptor,
663     content::ProtocolHandlerMap* protocol_handlers,
664     content::URLRequestInterceptorScopedVector request_interceptors) const {
665   // Copy most state from the main context.
666   AppRequestContext* context = new AppRequestContext();
667   context->CopyFrom(main_context);
668
669   base::FilePath cookie_path = partition_descriptor.path.Append(
670       chrome::kCookieFilename);
671   base::FilePath cache_path =
672       partition_descriptor.path.Append(chrome::kCacheDirname);
673
674   // Use a separate HTTP disk cache for isolated apps.
675   net::HttpCache::BackendFactory* app_backend = NULL;
676   if (partition_descriptor.in_memory) {
677     app_backend = net::HttpCache::DefaultBackend::InMemory(0);
678   } else {
679     app_backend = new net::HttpCache::DefaultBackend(
680         net::DISK_CACHE,
681         ChooseCacheBackendType(),
682         cache_path,
683         app_cache_max_size_,
684         BrowserThread::GetMessageLoopProxyForThread(BrowserThread::CACHE)
685             .get());
686   }
687   net::HttpNetworkSession* main_network_session =
688       main_http_factory_->GetSession();
689   scoped_ptr<net::HttpCache> app_http_cache =
690       CreateHttpFactory(main_network_session, app_backend);
691
692   scoped_refptr<net::CookieStore> cookie_store = NULL;
693   if (partition_descriptor.in_memory) {
694     cookie_store = content::CreateCookieStore(content::CookieStoreConfig());
695   } else if (chrome_browser_net::ShouldUseInMemoryCookiesAndCache()) {
696     // Don't use existing cookies and use an in-memory store.
697     // TODO(creis): We should have a cookie delegate for notifying the cookie
698     // extensions API, but we need to update it to understand isolated apps
699     // first.
700     cookie_store = content::CreateCookieStore(content::CookieStoreConfig());
701     app_http_cache->set_mode(
702         chrome_browser_net::IsCookieRecordMode() ?
703         net::HttpCache::RECORD : net::HttpCache::PLAYBACK);
704   }
705
706   // Use an app-specific cookie store.
707   if (!cookie_store.get()) {
708     DCHECK(!cookie_path.empty());
709
710     // TODO(creis): We should have a cookie delegate for notifying the cookie
711     // extensions API, but we need to update it to understand isolated apps
712     // first.
713     content::CookieStoreConfig cookie_config(
714         cookie_path,
715         content::CookieStoreConfig::EPHEMERAL_SESSION_COOKIES,
716         NULL, NULL);
717     cookie_config.crypto_delegate =
718       chrome_browser_net::GetCookieCryptoDelegate();
719     cookie_store = content::CreateCookieStore(cookie_config);
720   }
721
722   // Transfer ownership of the cookies and cache to AppRequestContext.
723   context->SetCookieStore(cookie_store.get());
724   context->SetHttpTransactionFactory(
725       scoped_ptr<net::HttpTransactionFactory>(
726           app_http_cache.PassAs<net::HttpTransactionFactory>()));
727
728   scoped_ptr<net::URLRequestJobFactoryImpl> job_factory(
729       new net::URLRequestJobFactoryImpl());
730   InstallProtocolHandlers(job_factory.get(), protocol_handlers);
731   scoped_ptr<net::URLRequestJobFactory> top_job_factory(
732       SetUpJobFactoryDefaults(job_factory.Pass(),
733                               request_interceptors.Pass(),
734                               protocol_handler_interceptor.Pass(),
735                               network_delegate(),
736                               ftp_factory_.get()));
737   context->SetJobFactory(top_job_factory.Pass());
738
739   return context;
740 }
741
742 net::URLRequestContext*
743 ProfileImplIOData::InitializeMediaRequestContext(
744     net::URLRequestContext* original_context,
745     const StoragePartitionDescriptor& partition_descriptor) const {
746   // Copy most state from the original context.
747   MediaRequestContext* context = new MediaRequestContext();
748   context->CopyFrom(original_context);
749
750   // For in-memory context, return immediately after creating the new
751   // context before attaching a separate cache. It is important to return
752   // a new context rather than just reusing |original_context| because
753   // the caller expects to take ownership of the pointer.
754   if (partition_descriptor.in_memory)
755     return context;
756
757   using content::StoragePartition;
758   base::FilePath cache_path;
759   int cache_max_size = app_media_cache_max_size_;
760   if (partition_descriptor.path == profile_path_) {
761     // lazy_params_ is only valid for the default media context creation.
762     cache_path = lazy_params_->media_cache_path;
763     cache_max_size = lazy_params_->media_cache_max_size;
764   } else {
765     cache_path = partition_descriptor.path.Append(chrome::kMediaCacheDirname);
766   }
767
768   // Use a separate HTTP disk cache for isolated apps.
769   net::HttpCache::BackendFactory* media_backend =
770       new net::HttpCache::DefaultBackend(
771           net::MEDIA_CACHE,
772           ChooseCacheBackendType(),
773           cache_path,
774           cache_max_size,
775           BrowserThread::GetMessageLoopProxyForThread(BrowserThread::CACHE)
776               .get());
777   net::HttpNetworkSession* main_network_session =
778       main_http_factory_->GetSession();
779   scoped_ptr<net::HttpCache> media_http_cache =
780       CreateHttpFactory(main_network_session, media_backend);
781
782   // Transfer ownership of the cache to MediaRequestContext.
783   context->SetHttpTransactionFactory(
784       media_http_cache.PassAs<net::HttpTransactionFactory>());
785
786   // Note that we do not create a new URLRequestJobFactory because
787   // the media context should behave exactly like its parent context
788   // in all respects except for cache behavior on media subresources.
789   // The CopyFrom() step above means that our media context will use
790   // the same URLRequestJobFactory instance that our parent context does.
791
792   return context;
793 }
794
795 net::URLRequestContext*
796 ProfileImplIOData::AcquireMediaRequestContext() const {
797   DCHECK(media_request_context_);
798   return media_request_context_.get();
799 }
800
801 net::URLRequestContext* ProfileImplIOData::AcquireIsolatedAppRequestContext(
802     net::URLRequestContext* main_context,
803     const StoragePartitionDescriptor& partition_descriptor,
804     scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
805         protocol_handler_interceptor,
806     content::ProtocolHandlerMap* protocol_handlers,
807     content::URLRequestInterceptorScopedVector request_interceptors) const {
808   // We create per-app contexts on demand, unlike the others above.
809   net::URLRequestContext* app_request_context =
810       InitializeAppRequestContext(main_context,
811                                   partition_descriptor,
812                                   protocol_handler_interceptor.Pass(),
813                                   protocol_handlers,
814                                   request_interceptors.Pass());
815   DCHECK(app_request_context);
816   return app_request_context;
817 }
818
819 net::URLRequestContext*
820 ProfileImplIOData::AcquireIsolatedMediaRequestContext(
821     net::URLRequestContext* app_context,
822     const StoragePartitionDescriptor& partition_descriptor) const {
823   // We create per-app media contexts on demand, unlike the others above.
824   net::URLRequestContext* media_request_context =
825       InitializeMediaRequestContext(app_context, partition_descriptor);
826   DCHECK(media_request_context);
827   return media_request_context;
828 }
829
830 void ProfileImplIOData::ClearNetworkingHistorySinceOnIOThread(
831     base::Time time,
832     const base::Closure& completion) {
833   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
834   DCHECK(initialized());
835
836   DCHECK(transport_security_state());
837   // Completes synchronously.
838   transport_security_state()->DeleteAllDynamicDataSince(time);
839   DCHECK(http_server_properties_manager_);
840   http_server_properties_manager_->Clear(completion);
841 }