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