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