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