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