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