profile_impl_io_data.cc revision 58537e28ecd584eab876aee8be7156509866d23a
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
51namespace {
52
53net::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
74using content::BrowserThread;
75
76ProfileImplIOData::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
84ProfileImplIOData::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
98void 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
141content::ResourceContext*
142    ProfileImplIOData::Handle::GetResourceContext() const {
143  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
144  LazyInitialize();
145  return GetResourceContextNoInit();
146}
147
148content::ResourceContext*
149ProfileImplIOData::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
157scoped_refptr<ChromeURLRequestContextGetter>
158ProfileImplIOData::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
181scoped_refptr<ChromeURLRequestContextGetter>
182ProfileImplIOData::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
193scoped_refptr<ChromeURLRequestContextGetter>
194ProfileImplIOData::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
205scoped_refptr<ChromeURLRequestContextGetter>
206ProfileImplIOData::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
237scoped_refptr<ChromeURLRequestContextGetter>
238ProfileImplIOData::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
268void 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
283void 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
309ProfileImplIOData::LazyParams::LazyParams()
310    : cache_max_size(0),
311      media_cache_max_size(0),
312      restore_old_session_cookies(false) {}
313
314ProfileImplIOData::LazyParams::~LazyParams() {}
315
316ProfileImplIOData::ProfileImplIOData()
317    : ProfileIOData(false),
318      http_server_properties_manager_(NULL),
319      app_cache_max_size_(0),
320      app_media_cache_max_size_(0) {}
321ProfileImplIOData::~ProfileImplIOData() {
322  DestroyResourceContext();
323
324  if (media_request_context_)
325    media_request_context_->AssertNoURLRequests();
326}
327
328void ProfileImplIOData::InitializeInternal(
329    ProfileParams* profile_params,
330    content::ProtocolHandlerMap* protocol_handlers) const {
331  ChromeURLRequestContext* main_context = main_request_context();
332
333  IOThread* const io_thread = profile_params->io_thread;
334  IOThread::Globals* const io_thread_globals = io_thread->globals();
335  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
336  bool record_mode = command_line.HasSwitch(switches::kRecordMode) &&
337                     chrome::kRecordModeEnabled;
338  bool playback_mode = command_line.HasSwitch(switches::kPlaybackMode);
339
340  network_delegate()->set_predictor(predictor_.get());
341
342  // Initialize context members.
343
344  ApplyProfileParamsToContext(main_context);
345
346  if (http_server_properties_manager_)
347    http_server_properties_manager_->InitializeOnIOThread();
348
349  main_context->set_transport_security_state(transport_security_state());
350
351  main_context->set_net_log(io_thread->net_log());
352
353  main_context->set_network_delegate(network_delegate());
354
355  main_context->set_http_server_properties(http_server_properties());
356
357  main_context->set_host_resolver(
358      io_thread_globals->host_resolver.get());
359  main_context->set_http_auth_handler_factory(
360      io_thread_globals->http_auth_handler_factory.get());
361
362  main_context->set_fraudulent_certificate_reporter(
363      fraudulent_certificate_reporter());
364
365  main_context->set_throttler_manager(
366      io_thread_globals->throttler_manager.get());
367
368  main_context->set_proxy_service(proxy_service());
369
370  scoped_refptr<net::CookieStore> cookie_store = NULL;
371  net::ServerBoundCertService* server_bound_cert_service = NULL;
372  if (record_mode || playback_mode) {
373    // Don't use existing cookies and use an in-memory store.
374    cookie_store = new net::CookieMonster(
375        NULL, profile_params->cookie_monster_delegate.get());
376    // Don't use existing server-bound certs and use an in-memory store.
377    server_bound_cert_service = new net::ServerBoundCertService(
378        new net::DefaultServerBoundCertStore(NULL),
379        base::WorkerPool::GetTaskRunner(true));
380  }
381
382  // setup cookie store
383  if (!cookie_store.get()) {
384    DCHECK(!lazy_params_->cookie_path.empty());
385
386    cookie_store = content::CreatePersistentCookieStore(
387        lazy_params_->cookie_path,
388        lazy_params_->restore_old_session_cookies,
389        lazy_params_->special_storage_policy.get(),
390        profile_params->cookie_monster_delegate.get());
391    cookie_store->GetCookieMonster()->SetPersistSessionCookies(true);
392  }
393
394  main_context->set_cookie_store(cookie_store.get());
395
396  // Setup server bound cert service.
397  if (!server_bound_cert_service) {
398    DCHECK(!lazy_params_->server_bound_cert_path.empty());
399
400    scoped_refptr<SQLiteServerBoundCertStore> server_bound_cert_db =
401        new SQLiteServerBoundCertStore(
402            lazy_params_->server_bound_cert_path,
403            lazy_params_->special_storage_policy.get());
404    server_bound_cert_service = new net::ServerBoundCertService(
405        new net::DefaultServerBoundCertStore(server_bound_cert_db.get()),
406        base::WorkerPool::GetTaskRunner(true));
407  }
408
409  set_server_bound_cert_service(server_bound_cert_service);
410  main_context->set_server_bound_cert_service(server_bound_cert_service);
411
412  net::HttpCache::DefaultBackend* main_backend =
413      new net::HttpCache::DefaultBackend(
414          net::DISK_CACHE,
415          ChooseCacheBackendType(),
416          lazy_params_->cache_path,
417          lazy_params_->cache_max_size,
418          BrowserThread::GetMessageLoopProxyForThread(BrowserThread::CACHE)
419              .get());
420  net::HttpNetworkSession::Params network_session_params;
421  PopulateNetworkSessionParams(profile_params, &network_session_params);
422  net::HttpCache* main_cache = new net::HttpCache(
423      network_session_params, main_backend);
424  main_cache->InitializeInfiniteCache(lazy_params_->infinite_cache_path);
425
426#if defined(OS_ANDROID)
427  ChromeDataReductionProxyAndroid::Init(main_cache->GetSession());
428#endif
429
430  if (record_mode || playback_mode) {
431    main_cache->set_mode(
432        record_mode ? net::HttpCache::RECORD : net::HttpCache::PLAYBACK);
433  }
434
435  main_http_factory_.reset(main_cache);
436  main_context->set_http_transaction_factory(main_cache);
437
438#if !defined(DISABLE_FTP_SUPPORT)
439  ftp_factory_.reset(
440      new net::FtpNetworkLayer(io_thread_globals->host_resolver.get()));
441#endif  // !defined(DISABLE_FTP_SUPPORT)
442
443  scoped_ptr<net::URLRequestJobFactoryImpl> main_job_factory(
444      new net::URLRequestJobFactoryImpl());
445  InstallProtocolHandlers(main_job_factory.get(), protocol_handlers);
446  main_job_factory_ = SetUpJobFactoryDefaults(
447      main_job_factory.Pass(),
448      profile_params->protocol_handler_interceptor.Pass(),
449      network_delegate(),
450      ftp_factory_.get());
451  main_context->set_job_factory(main_job_factory_.get());
452
453#if defined(ENABLE_EXTENSIONS)
454  InitializeExtensionsRequestContext(profile_params);
455#endif
456
457  // Create a media request context based on the main context, but using a
458  // media cache.  It shares the same job factory as the main context.
459  StoragePartitionDescriptor details(profile_path_, false);
460  media_request_context_.reset(InitializeMediaRequestContext(main_context,
461                                                             details));
462
463  lazy_params_.reset();
464}
465
466void ProfileImplIOData::
467    InitializeExtensionsRequestContext(ProfileParams* profile_params) const {
468  ChromeURLRequestContext* extensions_context = extensions_request_context();
469  IOThread* const io_thread = profile_params->io_thread;
470  IOThread::Globals* const io_thread_globals = io_thread->globals();
471  ApplyProfileParamsToContext(extensions_context);
472
473  extensions_context->set_transport_security_state(transport_security_state());
474
475  extensions_context->set_net_log(io_thread->net_log());
476
477  extensions_context->set_throttler_manager(
478      io_thread_globals->throttler_manager.get());
479
480  net::CookieStore* extensions_cookie_store =
481      content::CreatePersistentCookieStore(
482          lazy_params_->extensions_cookie_path,
483          lazy_params_->restore_old_session_cookies,
484          NULL,
485          NULL);
486  // Enable cookies for devtools and extension URLs.
487  const char* schemes[] = {chrome::kChromeDevToolsScheme,
488                           extensions::kExtensionScheme};
489  extensions_cookie_store->GetCookieMonster()->SetCookieableSchemes(schemes, 2);
490  extensions_context->set_cookie_store(extensions_cookie_store);
491
492  scoped_ptr<net::URLRequestJobFactoryImpl> extensions_job_factory(
493      new net::URLRequestJobFactoryImpl());
494  // TODO(shalev): The extensions_job_factory has a NULL NetworkDelegate.
495  // Without a network_delegate, this protocol handler will never
496  // handle file: requests, but as a side effect it makes
497  // job_factory::IsHandledProtocol return true, which prevents attempts to
498  // handle the protocol externally. We pass NULL in to
499  // SetUpJobFactory() to get this effect.
500  extensions_job_factory_ = SetUpJobFactoryDefaults(
501      extensions_job_factory.Pass(),
502      scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>(),
503      NULL,
504      ftp_factory_.get());
505  extensions_context->set_job_factory(extensions_job_factory_.get());
506}
507
508ChromeURLRequestContext*
509ProfileImplIOData::InitializeAppRequestContext(
510    ChromeURLRequestContext* main_context,
511    const StoragePartitionDescriptor& partition_descriptor,
512    scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
513        protocol_handler_interceptor,
514    content::ProtocolHandlerMap* protocol_handlers) const {
515  // Copy most state from the main context.
516  AppRequestContext* context = new AppRequestContext(load_time_stats());
517  context->CopyFrom(main_context);
518
519  base::FilePath cookie_path = partition_descriptor.path.Append(
520      chrome::kCookieFilename);
521  base::FilePath cache_path =
522      partition_descriptor.path.Append(chrome::kCacheDirname);
523
524  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
525  bool record_mode = command_line.HasSwitch(switches::kRecordMode) &&
526                     chrome::kRecordModeEnabled;
527  bool playback_mode = command_line.HasSwitch(switches::kPlaybackMode);
528
529  // Use a separate HTTP disk cache for isolated apps.
530  net::HttpCache::BackendFactory* app_backend = NULL;
531  if (partition_descriptor.in_memory) {
532    app_backend = net::HttpCache::DefaultBackend::InMemory(0);
533  } else {
534    app_backend = new net::HttpCache::DefaultBackend(
535        net::DISK_CACHE,
536        ChooseCacheBackendType(),
537        cache_path,
538        app_cache_max_size_,
539        BrowserThread::GetMessageLoopProxyForThread(BrowserThread::CACHE)
540            .get());
541  }
542  net::HttpNetworkSession* main_network_session =
543      main_http_factory_->GetSession();
544  net::HttpCache* app_http_cache =
545      new net::HttpCache(main_network_session, app_backend);
546
547  scoped_refptr<net::CookieStore> cookie_store = NULL;
548  if (partition_descriptor.in_memory) {
549    cookie_store = new net::CookieMonster(NULL, NULL);
550  } else if (record_mode || playback_mode) {
551    // Don't use existing cookies and use an in-memory store.
552    // TODO(creis): We should have a cookie delegate for notifying the cookie
553    // extensions API, but we need to update it to understand isolated apps
554    // first.
555    cookie_store = new net::CookieMonster(NULL, NULL);
556    app_http_cache->set_mode(
557        record_mode ? net::HttpCache::RECORD : net::HttpCache::PLAYBACK);
558  }
559
560  // Use an app-specific cookie store.
561  if (!cookie_store.get()) {
562    DCHECK(!cookie_path.empty());
563
564    // TODO(creis): We should have a cookie delegate for notifying the cookie
565    // extensions API, but we need to update it to understand isolated apps
566    // first.
567    cookie_store = content::CreatePersistentCookieStore(
568        cookie_path,
569        false,
570        NULL,
571        NULL);
572  }
573
574  // Transfer ownership of the cookies and cache to AppRequestContext.
575  context->SetCookieStore(cookie_store.get());
576  context->SetHttpTransactionFactory(
577      scoped_ptr<net::HttpTransactionFactory>(app_http_cache));
578
579  scoped_ptr<net::URLRequestJobFactoryImpl> job_factory(
580      new net::URLRequestJobFactoryImpl());
581  InstallProtocolHandlers(job_factory.get(), protocol_handlers);
582  scoped_ptr<net::URLRequestJobFactory> top_job_factory;
583  // Overwrite the job factory that we inherit from the main context so
584  // that we can later provide our own handlers for storage related protocols.
585  // Install all the usual protocol handlers unless we are in a browser plugin
586  // guest process, in which case only web-safe schemes are allowed.
587  if (!partition_descriptor.in_memory) {
588    top_job_factory = SetUpJobFactoryDefaults(
589        job_factory.Pass(), protocol_handler_interceptor.Pass(),
590        network_delegate(),
591        ftp_factory_.get());
592  } else {
593    top_job_factory = job_factory.PassAs<net::URLRequestJobFactory>();
594  }
595  context->SetJobFactory(top_job_factory.Pass());
596
597  return context;
598}
599
600ChromeURLRequestContext*
601ProfileImplIOData::InitializeMediaRequestContext(
602    ChromeURLRequestContext* original_context,
603    const StoragePartitionDescriptor& partition_descriptor) const {
604  // Copy most state from the original context.
605  MediaRequestContext* context = new MediaRequestContext(load_time_stats());
606  context->CopyFrom(original_context);
607
608  // For in-memory context, return immediately after creating the new
609  // context before attaching a separate cache. It is important to return
610  // a new context rather than just reusing |original_context| because
611  // the caller expects to take ownership of the pointer.
612  if (partition_descriptor.in_memory)
613    return context;
614
615  using content::StoragePartition;
616  base::FilePath cache_path;
617  int cache_max_size = app_media_cache_max_size_;
618  if (partition_descriptor.path == profile_path_) {
619    // lazy_params_ is only valid for the default media context creation.
620    cache_path = lazy_params_->media_cache_path;
621    cache_max_size = lazy_params_->media_cache_max_size;
622  } else {
623    cache_path = partition_descriptor.path.Append(chrome::kMediaCacheDirname);
624  }
625
626  // Use a separate HTTP disk cache for isolated apps.
627  net::HttpCache::BackendFactory* media_backend =
628      new net::HttpCache::DefaultBackend(
629          net::MEDIA_CACHE,
630          ChooseCacheBackendType(),
631          cache_path,
632          cache_max_size,
633          BrowserThread::GetMessageLoopProxyForThread(BrowserThread::CACHE)
634              .get());
635  net::HttpNetworkSession* main_network_session =
636      main_http_factory_->GetSession();
637  scoped_ptr<net::HttpTransactionFactory> media_http_cache(
638      new net::HttpCache(main_network_session, media_backend));
639
640  // Transfer ownership of the cache to MediaRequestContext.
641  context->SetHttpTransactionFactory(media_http_cache.Pass());
642
643  // Note that we do not create a new URLRequestJobFactory because
644  // the media context should behave exactly like its parent context
645  // in all respects except for cache behavior on media subresources.
646  // The CopyFrom() step above means that our media context will use
647  // the same URLRequestJobFactory instance that our parent context does.
648
649  return context;
650}
651
652ChromeURLRequestContext*
653ProfileImplIOData::AcquireMediaRequestContext() const {
654  DCHECK(media_request_context_);
655  return media_request_context_.get();
656}
657
658ChromeURLRequestContext*
659ProfileImplIOData::AcquireIsolatedAppRequestContext(
660    ChromeURLRequestContext* main_context,
661    const StoragePartitionDescriptor& partition_descriptor,
662    scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
663        protocol_handler_interceptor,
664    content::ProtocolHandlerMap* protocol_handlers) const {
665  // We create per-app contexts on demand, unlike the others above.
666  ChromeURLRequestContext* app_request_context =
667      InitializeAppRequestContext(main_context, partition_descriptor,
668                                  protocol_handler_interceptor.Pass(),
669                                  protocol_handlers);
670  DCHECK(app_request_context);
671  return app_request_context;
672}
673
674ChromeURLRequestContext*
675ProfileImplIOData::AcquireIsolatedMediaRequestContext(
676    ChromeURLRequestContext* app_context,
677    const StoragePartitionDescriptor& partition_descriptor) const {
678  // We create per-app media contexts on demand, unlike the others above.
679  ChromeURLRequestContext* media_request_context =
680      InitializeMediaRequestContext(app_context, partition_descriptor);
681  DCHECK(media_request_context);
682  return media_request_context;
683}
684
685chrome_browser_net::LoadTimeStats* ProfileImplIOData::GetLoadTimeStats(
686    IOThread::Globals* io_thread_globals) const {
687  return io_thread_globals->load_time_stats.get();
688}
689
690void ProfileImplIOData::ClearNetworkingHistorySinceOnIOThread(
691    base::Time time,
692    const base::Closure& completion) {
693  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
694  DCHECK(initialized());
695
696  DCHECK(transport_security_state());
697  // Completes synchronously.
698  transport_security_state()->DeleteAllDynamicDataSince(time);
699  DCHECK(http_server_properties_manager_);
700  http_server_properties_manager_->Clear(completion);
701}
702