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