profile_io_data.cc revision 3551c9c881056c480085172ff9840cab31610854
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_io_data.h"
6
7#include <string>
8
9#include "base/basictypes.h"
10#include "base/bind.h"
11#include "base/bind_helpers.h"
12#include "base/command_line.h"
13#include "base/compiler_specific.h"
14#include "base/debug/alias.h"
15#include "base/logging.h"
16#include "base/path_service.h"
17#include "base/prefs/pref_service.h"
18#include "base/stl_util.h"
19#include "base/strings/string_number_conversions.h"
20#include "base/strings/string_util.h"
21#include "base/strings/stringprintf.h"
22#include "base/threading/sequenced_worker_pool.h"
23#include "chrome/browser/browser_process.h"
24#include "chrome/browser/chrome_notification_types.h"
25#include "chrome/browser/content_settings/content_settings_provider.h"
26#include "chrome/browser/content_settings/cookie_settings.h"
27#include "chrome/browser/content_settings/host_content_settings_map.h"
28#include "chrome/browser/custom_handlers/protocol_handler_registry.h"
29#include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h"
30#include "chrome/browser/download/download_service.h"
31#include "chrome/browser/download/download_service_factory.h"
32#include "chrome/browser/extensions/extension_info_map.h"
33#include "chrome/browser/extensions/extension_protocols.h"
34#include "chrome/browser/extensions/extension_resource_protocols.h"
35#include "chrome/browser/extensions/extension_system.h"
36#include "chrome/browser/io_thread.h"
37#include "chrome/browser/net/about_protocol_handler.h"
38#include "chrome/browser/net/chrome_cookie_notification_details.h"
39#include "chrome/browser/net/chrome_fraudulent_certificate_reporter.h"
40#include "chrome/browser/net/chrome_http_user_agent_settings.h"
41#include "chrome/browser/net/chrome_net_log.h"
42#include "chrome/browser/net/chrome_network_delegate.h"
43#include "chrome/browser/net/evicted_domain_cookie_counter.h"
44#include "chrome/browser/net/load_time_stats.h"
45#include "chrome/browser/net/proxy_service_factory.h"
46#include "chrome/browser/net/resource_prefetch_predictor_observer.h"
47#include "chrome/browser/net/transport_security_persister.h"
48#include "chrome/browser/notifications/desktop_notification_service_factory.h"
49#include "chrome/browser/policy/url_blacklist_manager.h"
50#include "chrome/browser/predictors/resource_prefetch_predictor.h"
51#include "chrome/browser/predictors/resource_prefetch_predictor_factory.h"
52#include "chrome/browser/profiles/profile.h"
53#include "chrome/browser/profiles/profile_manager.h"
54#include "chrome/browser/signin/signin_names_io_thread.h"
55#include "chrome/common/chrome_paths.h"
56#include "chrome/common/chrome_switches.h"
57#include "chrome/common/pref_names.h"
58#include "chrome/common/startup_metric_utils.h"
59#include "chrome/common/url_constants.h"
60#include "content/public/browser/browser_thread.h"
61#include "content/public/browser/host_zoom_map.h"
62#include "content/public/browser/notification_service.h"
63#include "content/public/browser/resource_context.h"
64#include "extensions/common/constants.h"
65#include "net/cert/cert_verifier.h"
66#include "net/cookies/canonical_cookie.h"
67#include "net/cookies/cookie_monster.h"
68#include "net/http/http_transaction_factory.h"
69#include "net/http/http_util.h"
70#include "net/proxy/proxy_config_service_fixed.h"
71#include "net/proxy/proxy_script_fetcher_impl.h"
72#include "net/proxy/proxy_service.h"
73#include "net/ssl/server_bound_cert_service.h"
74#include "net/url_request/data_protocol_handler.h"
75#include "net/url_request/file_protocol_handler.h"
76#include "net/url_request/ftp_protocol_handler.h"
77#include "net/url_request/protocol_intercept_job_factory.h"
78#include "net/url_request/url_request.h"
79#include "net/url_request/url_request_file_job.h"
80#include "net/url_request/url_request_job_factory_impl.h"
81
82#if defined(ENABLE_MANAGED_USERS)
83#include "chrome/browser/managed_mode/managed_mode_url_filter.h"
84#include "chrome/browser/managed_mode/managed_user_service.h"
85#include "chrome/browser/managed_mode/managed_user_service_factory.h"
86#endif
87
88#if defined(OS_CHROMEOS)
89#include "chrome/browser/chromeos/drive/drive_protocol_handler.h"
90#include "chrome/browser/chromeos/policy/policy_cert_verifier.h"
91#include "chrome/browser/chromeos/settings/cros_settings.h"
92#include "chrome/browser/chromeos/settings/cros_settings_names.h"
93#include "chrome/browser/policy/browser_policy_connector.h"
94#endif  // defined(OS_CHROMEOS)
95
96using content::BrowserContext;
97using content::BrowserThread;
98using content::ResourceContext;
99
100namespace {
101
102// ----------------------------------------------------------------------------
103// CookieMonster::Delegate implementation
104// ----------------------------------------------------------------------------
105class ChromeCookieMonsterDelegate : public net::CookieMonster::Delegate {
106 public:
107  explicit ChromeCookieMonsterDelegate(
108      const base::Callback<Profile*(void)>& profile_getter)
109      : profile_getter_(profile_getter) {
110    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
111  }
112
113  // net::CookieMonster::Delegate implementation.
114  virtual void OnCookieChanged(
115      const net::CanonicalCookie& cookie,
116      bool removed,
117      net::CookieMonster::Delegate::ChangeCause cause) OVERRIDE {
118    BrowserThread::PostTask(
119        BrowserThread::UI, FROM_HERE,
120        base::Bind(&ChromeCookieMonsterDelegate::OnCookieChangedAsyncHelper,
121                   this, cookie, removed, cause));
122  }
123
124 private:
125  virtual ~ChromeCookieMonsterDelegate() {}
126
127  void OnCookieChangedAsyncHelper(
128      const net::CanonicalCookie& cookie,
129      bool removed,
130      net::CookieMonster::Delegate::ChangeCause cause) {
131    Profile* profile = profile_getter_.Run();
132    if (profile) {
133      ChromeCookieDetails cookie_details(&cookie, removed, cause);
134      content::NotificationService::current()->Notify(
135          chrome::NOTIFICATION_COOKIE_CHANGED,
136          content::Source<Profile>(profile),
137          content::Details<ChromeCookieDetails>(&cookie_details));
138    }
139  }
140
141  const base::Callback<Profile*(void)> profile_getter_;
142};
143
144Profile* GetProfileOnUI(ProfileManager* profile_manager, Profile* profile) {
145  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
146  DCHECK(profile);
147  if (profile_manager->IsValidProfile(profile))
148    return profile;
149  return NULL;
150}
151
152#if defined(DEBUG_DEVTOOLS)
153bool IsSupportedDevToolsURL(const GURL& url, base::FilePath* path) {
154  std::string bundled_path_prefix(chrome::kChromeUIDevToolsBundledPath);
155  bundled_path_prefix = "/" + bundled_path_prefix + "/";
156
157  if (!url.SchemeIs(chrome::kChromeDevToolsScheme) ||
158      url.host() != chrome::kChromeUIDevToolsHost ||
159      !StartsWithASCII(url.path(), bundled_path_prefix, false)) {
160    return false;
161  }
162
163  if (!url.is_valid()) {
164    NOTREACHED();
165    return false;
166  }
167
168  // Remove Query and Ref from URL.
169  GURL stripped_url;
170  GURL::Replacements replacements;
171  replacements.ClearQuery();
172  replacements.ClearRef();
173  stripped_url = url.ReplaceComponents(replacements);
174
175  std::string relative_path;
176  const std::string& spec = stripped_url.possibly_invalid_spec();
177  const url_parse::Parsed& parsed =
178      stripped_url.parsed_for_possibly_invalid_spec();
179  int offset = parsed.CountCharactersBefore(url_parse::Parsed::PATH, false);
180  if (offset < static_cast<int>(spec.size()))
181    relative_path.assign(spec.substr(offset + bundled_path_prefix.length()));
182
183  // Check that |relative_path| is not an absolute path (otherwise
184  // AppendASCII() will DCHECK).  The awkward use of StringType is because on
185  // some systems FilePath expects a std::string, but on others a std::wstring.
186  base::FilePath p(
187      base::FilePath::StringType(relative_path.begin(), relative_path.end()));
188  if (p.IsAbsolute())
189    return false;
190
191  base::FilePath inspector_dir;
192  if (!PathService::Get(chrome::DIR_INSPECTOR, &inspector_dir))
193    return false;
194
195  if (inspector_dir.empty())
196    return false;
197
198  *path = inspector_dir.AppendASCII(relative_path);
199  return true;
200}
201
202class DebugDevToolsInterceptor
203    : public net::URLRequestJobFactory::ProtocolHandler {
204 public:
205  DebugDevToolsInterceptor() {}
206  virtual ~DebugDevToolsInterceptor() {}
207
208  virtual net::URLRequestJob* MaybeCreateJob(
209      net::URLRequest* request,
210      net::NetworkDelegate* network_delegate) const OVERRIDE {
211    base::FilePath path;
212    if (IsSupportedDevToolsURL(request->url(), &path))
213      return new net::URLRequestFileJob(
214          request, network_delegate, path,
215          content::BrowserThread::GetBlockingPool()->
216              GetTaskRunnerWithShutdownBehavior(
217                  base::SequencedWorkerPool::SKIP_ON_SHUTDOWN));
218
219    return NULL;
220  }
221};
222#endif  // defined(DEBUG_DEVTOOLS)
223
224}  // namespace
225
226void ProfileIOData::InitializeOnUIThread(Profile* profile) {
227  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
228  PrefService* pref_service = profile->GetPrefs();
229  PrefService* local_state_pref_service = g_browser_process->local_state();
230
231  scoped_ptr<ProfileParams> params(new ProfileParams);
232  params->path = profile->GetPath();
233
234  params->io_thread = g_browser_process->io_thread();
235
236  params->cookie_settings = CookieSettings::Factory::GetForProfile(profile);
237  params->host_content_settings_map = profile->GetHostContentSettingsMap();
238  params->ssl_config_service = profile->GetSSLConfigService();
239  base::Callback<Profile*(void)> profile_getter =
240      base::Bind(&GetProfileOnUI, g_browser_process->profile_manager(),
241                 profile);
242  params->cookie_monster_delegate =
243      new chrome_browser_net::EvictedDomainCookieCounter(
244          new ChromeCookieMonsterDelegate(profile_getter));
245  params->extension_info_map =
246      extensions::ExtensionSystem::Get(profile)->info_map();
247
248  if (predictors::ResourcePrefetchPredictor* predictor =
249          predictors::ResourcePrefetchPredictorFactory::GetForProfile(
250              profile)) {
251    resource_prefetch_predictor_observer_.reset(
252        new chrome_browser_net::ResourcePrefetchPredictorObserver(predictor));
253  }
254
255#if defined(ENABLE_NOTIFICATIONS)
256  params->notification_service =
257      DesktopNotificationServiceFactory::GetForProfile(profile);
258#endif
259
260  ProtocolHandlerRegistry* protocol_handler_registry =
261      ProtocolHandlerRegistryFactory::GetForProfile(profile);
262  DCHECK(protocol_handler_registry);
263
264  // The profile instance is only available here in the InitializeOnUIThread
265  // method, so we create the url job factory here, then save it for
266  // later delivery to the job factory in Init().
267  params->protocol_handler_interceptor =
268      protocol_handler_registry->CreateJobInterceptorFactory();
269
270  params->proxy_config_service
271      .reset(ProxyServiceFactory::CreateProxyConfigService(
272           profile->GetProxyConfigTracker()));
273#if defined(ENABLE_MANAGED_USERS)
274  ManagedUserService* managed_user_service =
275      ManagedUserServiceFactory::GetForProfile(profile);
276  params->managed_mode_url_filter =
277      managed_user_service->GetURLFilterForIOThread();
278#endif
279#if defined(OS_CHROMEOS)
280  policy::BrowserPolicyConnector* connector =
281      g_browser_process->browser_policy_connector();
282  params->trust_anchor_provider = connector->GetCertTrustAnchorProvider();
283#endif
284
285  params->profile = profile;
286  profile_params_.reset(params.release());
287
288  ChromeNetworkDelegate::InitializePrefsOnUIThread(
289      &enable_referrers_,
290      &enable_do_not_track_,
291      &force_safesearch_,
292      pref_service);
293
294  scoped_refptr<base::MessageLoopProxy> io_message_loop_proxy =
295      BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
296#if defined(ENABLE_PRINTING)
297  printing_enabled_.Init(prefs::kPrintingEnabled, pref_service);
298  printing_enabled_.MoveToThread(io_message_loop_proxy);
299#endif
300  chrome_http_user_agent_settings_.reset(
301      new ChromeHttpUserAgentSettings(pref_service));
302
303  // These members are used only for one click sign in, which is not enabled
304  // in incognito mode.  So no need to initialize them.
305  if (!is_incognito()) {
306    signin_names_.reset(new SigninNamesOnIOThread());
307
308    google_services_username_.Init(
309        prefs::kGoogleServicesUsername, pref_service);
310    google_services_username_.MoveToThread(io_message_loop_proxy);
311
312    google_services_username_pattern_.Init(
313        prefs::kGoogleServicesUsernamePattern, local_state_pref_service);
314    google_services_username_pattern_.MoveToThread(io_message_loop_proxy);
315
316    reverse_autologin_enabled_.Init(
317        prefs::kReverseAutologinEnabled, pref_service);
318    reverse_autologin_enabled_.MoveToThread(io_message_loop_proxy);
319
320    one_click_signin_rejected_email_list_.Init(
321        prefs::kReverseAutologinRejectedEmailList, pref_service);
322    one_click_signin_rejected_email_list_.MoveToThread(io_message_loop_proxy);
323
324    sync_disabled_.Init(prefs::kSyncManaged, pref_service);
325    sync_disabled_.MoveToThread(io_message_loop_proxy);
326
327    signin_allowed_.Init(prefs::kSigninAllowed, pref_service);
328    signin_allowed_.MoveToThread(io_message_loop_proxy);
329  }
330
331  // The URLBlacklistManager has to be created on the UI thread to register
332  // observers of |pref_service|, and it also has to clean up on
333  // ShutdownOnUIThread to release these observers on the right thread.
334  // Don't pass it in |profile_params_| to make sure it is correctly cleaned up,
335  // in particular when this ProfileIOData isn't |initialized_| during deletion.
336#if defined(ENABLE_CONFIGURATION_POLICY)
337  url_blacklist_manager_.reset(new policy::URLBlacklistManager(pref_service));
338#endif
339
340  initialized_on_UI_thread_ = true;
341
342  // We need to make sure that content initializes its own data structures that
343  // are associated with each ResourceContext because we might post this
344  // object to the IO thread after this function.
345  BrowserContext::EnsureResourceContextInitialized(profile);
346}
347
348ProfileIOData::MediaRequestContext::MediaRequestContext(
349    chrome_browser_net::LoadTimeStats* load_time_stats)
350    : ChromeURLRequestContext(ChromeURLRequestContext::CONTEXT_TYPE_MEDIA,
351                              load_time_stats) {
352}
353
354void ProfileIOData::MediaRequestContext::SetHttpTransactionFactory(
355    scoped_ptr<net::HttpTransactionFactory> http_factory) {
356  http_factory_ = http_factory.Pass();
357  set_http_transaction_factory(http_factory_.get());
358}
359
360ProfileIOData::MediaRequestContext::~MediaRequestContext() {}
361
362ProfileIOData::AppRequestContext::AppRequestContext(
363    chrome_browser_net::LoadTimeStats* load_time_stats)
364    : ChromeURLRequestContext(ChromeURLRequestContext::CONTEXT_TYPE_APP,
365                              load_time_stats) {
366}
367
368void ProfileIOData::AppRequestContext::SetCookieStore(
369    net::CookieStore* cookie_store) {
370  cookie_store_ = cookie_store;
371  set_cookie_store(cookie_store);
372}
373
374void ProfileIOData::AppRequestContext::SetHttpTransactionFactory(
375    scoped_ptr<net::HttpTransactionFactory> http_factory) {
376  http_factory_ = http_factory.Pass();
377  set_http_transaction_factory(http_factory_.get());
378}
379
380void ProfileIOData::AppRequestContext::SetJobFactory(
381    scoped_ptr<net::URLRequestJobFactory> job_factory) {
382  job_factory_ = job_factory.Pass();
383  set_job_factory(job_factory_.get());
384}
385
386ProfileIOData::AppRequestContext::~AppRequestContext() {}
387
388ProfileIOData::ProfileParams::ProfileParams()
389    : io_thread(NULL),
390#if defined(ENABLE_NOTIFICATIONS)
391      notification_service(NULL),
392#endif
393#if defined(OS_CHROMEOS)
394      trust_anchor_provider(NULL),
395#endif
396      profile(NULL) {
397}
398
399ProfileIOData::ProfileParams::~ProfileParams() {}
400
401ProfileIOData::ProfileIOData(bool is_incognito)
402    : initialized_(false),
403#if defined(ENABLE_NOTIFICATIONS)
404      notification_service_(NULL),
405#endif
406      resource_context_(new ResourceContext(this)),
407      load_time_stats_(NULL),
408      initialized_on_UI_thread_(false),
409      is_incognito_(is_incognito) {
410  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
411}
412
413ProfileIOData::~ProfileIOData() {
414  if (BrowserThread::IsMessageLoopValid(BrowserThread::IO))
415    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
416
417  // Pull the contents of the request context maps onto the stack for sanity
418  // checking of values in a minidump. http://crbug.com/260425
419  size_t num_app_contexts = app_request_context_map_.size();
420  size_t num_media_contexts = isolated_media_request_context_map_.size();
421  size_t current_context = 0;
422  static const size_t kMaxCachedContexts = 20;
423  ChromeURLRequestContext* app_context_cache[kMaxCachedContexts] = {0};
424  void* app_context_vtable_cache[kMaxCachedContexts] = {0};
425  ChromeURLRequestContext* media_context_cache[kMaxCachedContexts] = {0};
426  void* media_context_vtable_cache[kMaxCachedContexts] = {0};
427  void* tmp_vtable = NULL;
428  base::debug::Alias(&num_app_contexts);
429  base::debug::Alias(&num_media_contexts);
430  base::debug::Alias(&current_context);
431  base::debug::Alias(app_context_cache);
432  base::debug::Alias(app_context_vtable_cache);
433  base::debug::Alias(media_context_cache);
434  base::debug::Alias(media_context_vtable_cache);
435  base::debug::Alias(&tmp_vtable);
436
437  current_context = 0;
438  for (URLRequestContextMap::const_iterator it =
439           app_request_context_map_.begin();
440       current_context < kMaxCachedContexts &&
441           it != app_request_context_map_.end();
442       ++it, ++current_context) {
443    app_context_cache[current_context] = it->second;
444    memcpy(&app_context_vtable_cache[current_context],
445           static_cast<void*>(it->second), sizeof(void*));
446  }
447
448  current_context = 0;
449  for (URLRequestContextMap::const_iterator it =
450           isolated_media_request_context_map_.begin();
451       current_context < kMaxCachedContexts &&
452           it != isolated_media_request_context_map_.end();
453       ++it, ++current_context) {
454    media_context_cache[current_context] = it->second;
455    memcpy(&media_context_vtable_cache[current_context],
456           static_cast<void*>(it->second), sizeof(void*));
457  }
458
459  // TODO(ajwong): These AssertNoURLRequests() calls are unnecessary since they
460  // are already done in the URLRequestContext destructor.
461  if (main_request_context_)
462    main_request_context_->AssertNoURLRequests();
463  if (extensions_request_context_)
464    extensions_request_context_->AssertNoURLRequests();
465
466  current_context = 0;
467  for (URLRequestContextMap::iterator it = app_request_context_map_.begin();
468       it != app_request_context_map_.end(); ++it) {
469    if (current_context < kMaxCachedContexts) {
470      CHECK_EQ(app_context_cache[current_context], it->second);
471      memcpy(&tmp_vtable, static_cast<void*>(it->second), sizeof(void*));
472      CHECK_EQ(app_context_vtable_cache[current_context], tmp_vtable);
473    }
474    it->second->AssertNoURLRequests();
475    delete it->second;
476    current_context++;
477  }
478
479  current_context = 0;
480  for (URLRequestContextMap::iterator it =
481           isolated_media_request_context_map_.begin();
482       it != isolated_media_request_context_map_.end(); ++it) {
483    if (current_context < kMaxCachedContexts) {
484      CHECK_EQ(media_context_cache[current_context], it->second);
485      memcpy(&tmp_vtable, static_cast<void*>(it->second), sizeof(void*));
486      CHECK_EQ(media_context_vtable_cache[current_context], tmp_vtable);
487    }
488    it->second->AssertNoURLRequests();
489    delete it->second;
490    current_context++;
491  }
492}
493
494// static
495ProfileIOData* ProfileIOData::FromResourceContext(
496    content::ResourceContext* rc) {
497  return (static_cast<ResourceContext*>(rc))->io_data_;
498}
499
500// static
501bool ProfileIOData::IsHandledProtocol(const std::string& scheme) {
502  DCHECK_EQ(scheme, StringToLowerASCII(scheme));
503  static const char* const kProtocolList[] = {
504    chrome::kFileScheme,
505    chrome::kChromeDevToolsScheme,
506    extensions::kExtensionScheme,
507    chrome::kExtensionResourceScheme,
508    chrome::kChromeUIScheme,
509    chrome::kDataScheme,
510#if defined(OS_CHROMEOS)
511    chrome::kDriveScheme,
512#endif  // defined(OS_CHROMEOS)
513    chrome::kAboutScheme,
514#if !defined(DISABLE_FTP_SUPPORT)
515    chrome::kFtpScheme,
516#endif  // !defined(DISABLE_FTP_SUPPORT)
517    chrome::kBlobScheme,
518    chrome::kFileSystemScheme,
519    chrome::kChromeSearchScheme,
520  };
521  for (size_t i = 0; i < arraysize(kProtocolList); ++i) {
522    if (scheme == kProtocolList[i])
523      return true;
524  }
525  return net::URLRequest::IsHandledProtocol(scheme);
526}
527
528// static
529bool ProfileIOData::IsHandledURL(const GURL& url) {
530  if (!url.is_valid()) {
531    // We handle error cases.
532    return true;
533  }
534
535  return IsHandledProtocol(url.scheme());
536}
537
538// static
539void ProfileIOData::InstallProtocolHandlers(
540    net::URLRequestJobFactoryImpl* job_factory,
541    content::ProtocolHandlerMap* protocol_handlers) {
542  for (content::ProtocolHandlerMap::iterator it =
543           protocol_handlers->begin();
544       it != protocol_handlers->end();
545       ++it) {
546    bool set_protocol = job_factory->SetProtocolHandler(
547        it->first, it->second.release());
548    DCHECK(set_protocol);
549  }
550  protocol_handlers->clear();
551}
552
553content::ResourceContext* ProfileIOData::GetResourceContext() const {
554  return resource_context_.get();
555}
556
557ChromeURLRequestContext* ProfileIOData::GetMainRequestContext() const {
558  DCHECK(initialized_);
559  return main_request_context_.get();
560}
561
562ChromeURLRequestContext* ProfileIOData::GetMediaRequestContext() const {
563  DCHECK(initialized_);
564  ChromeURLRequestContext* context = AcquireMediaRequestContext();
565  DCHECK(context);
566  return context;
567}
568
569ChromeURLRequestContext* ProfileIOData::GetExtensionsRequestContext() const {
570  DCHECK(initialized_);
571  return extensions_request_context_.get();
572}
573
574ChromeURLRequestContext* ProfileIOData::GetIsolatedAppRequestContext(
575    ChromeURLRequestContext* main_context,
576    const StoragePartitionDescriptor& partition_descriptor,
577    scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
578        protocol_handler_interceptor,
579    content::ProtocolHandlerMap* protocol_handlers) const {
580  DCHECK(initialized_);
581  ChromeURLRequestContext* context = NULL;
582  if (ContainsKey(app_request_context_map_, partition_descriptor)) {
583    context = app_request_context_map_[partition_descriptor];
584  } else {
585    context = AcquireIsolatedAppRequestContext(
586        main_context, partition_descriptor, protocol_handler_interceptor.Pass(),
587        protocol_handlers);
588    app_request_context_map_[partition_descriptor] = context;
589  }
590  DCHECK(context);
591  return context;
592}
593
594ChromeURLRequestContext* ProfileIOData::GetIsolatedMediaRequestContext(
595    ChromeURLRequestContext* app_context,
596    const StoragePartitionDescriptor& partition_descriptor) const {
597  DCHECK(initialized_);
598  ChromeURLRequestContext* context = NULL;
599  if (ContainsKey(isolated_media_request_context_map_, partition_descriptor)) {
600    context = isolated_media_request_context_map_[partition_descriptor];
601  } else {
602    context = AcquireIsolatedMediaRequestContext(app_context,
603                                                 partition_descriptor);
604    isolated_media_request_context_map_[partition_descriptor] = context;
605  }
606  DCHECK(context);
607  return context;
608}
609
610ExtensionInfoMap* ProfileIOData::GetExtensionInfoMap() const {
611  DCHECK(initialized_) << "ExtensionSystem not initialized";
612  return extension_info_map_.get();
613}
614
615CookieSettings* ProfileIOData::GetCookieSettings() const {
616  // Allow either Init() or SetCookieSettingsForTesting() to initialize.
617  DCHECK(initialized_ || cookie_settings_.get());
618  return cookie_settings_.get();
619}
620
621HostContentSettingsMap* ProfileIOData::GetHostContentSettingsMap() const {
622  DCHECK(initialized_);
623  return host_content_settings_map_.get();
624}
625
626#if defined(ENABLE_NOTIFICATIONS)
627DesktopNotificationService* ProfileIOData::GetNotificationService() const {
628  DCHECK(initialized_);
629  return notification_service_;
630}
631#endif
632
633void ProfileIOData::InitializeMetricsEnabledStateOnUIThread() {
634  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
635#if defined(OS_CHROMEOS)
636  // Just fetch the value from ChromeOS' settings while we're on the UI thread.
637  // TODO(stevet): For now, this value is only set on profile initialization.
638  // We will want to do something similar to the PrefMember method below in the
639  // future to more accurately capture this state.
640  chromeos::CrosSettings::Get()->GetBoolean(chromeos::kStatsReportingPref,
641                                            &enable_metrics_);
642#elif defined(OS_ANDROID)
643  // TODO(dwkang): rename or unify the pref for UMA once we have conclusion
644  // in crbugs.com/246495.
645  // Android has it's own preferences for metrics / crash uploading.
646  enable_metrics_.Init(prefs::kCrashReportingEnabled,
647                       g_browser_process->local_state());
648  enable_metrics_.MoveToThread(
649      BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
650#else
651  // Prep the PrefMember and send it to the IO thread, since this value will be
652  // read from there.
653  enable_metrics_.Init(prefs::kMetricsReportingEnabled,
654                       g_browser_process->local_state());
655  enable_metrics_.MoveToThread(
656      BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
657#endif  // defined(OS_CHROMEOS)
658}
659
660bool ProfileIOData::GetMetricsEnabledStateOnIOThread() const {
661  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
662#if defined(OS_CHROMEOS)
663  return enable_metrics_;
664#else
665  return enable_metrics_.GetValue();
666#endif  // defined(OS_CHROMEOS)
667}
668
669base::WeakPtr<net::HttpServerProperties>
670ProfileIOData::http_server_properties() const {
671  return http_server_properties_->GetWeakPtr();
672}
673
674void ProfileIOData::set_http_server_properties(
675    scoped_ptr<net::HttpServerProperties> http_server_properties) const {
676  http_server_properties_ = http_server_properties.Pass();
677}
678
679ProfileIOData::ResourceContext::ResourceContext(ProfileIOData* io_data)
680    : io_data_(io_data),
681      host_resolver_(NULL),
682      request_context_(NULL) {
683  DCHECK(io_data);
684}
685
686ProfileIOData::ResourceContext::~ResourceContext() {}
687
688net::HostResolver* ProfileIOData::ResourceContext::GetHostResolver()  {
689  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
690  DCHECK(io_data_->initialized_);
691  return host_resolver_;
692}
693
694net::URLRequestContext* ProfileIOData::ResourceContext::GetRequestContext()  {
695  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
696  DCHECK(io_data_->initialized_);
697  return request_context_;
698}
699
700bool ProfileIOData::ResourceContext::AllowMicAccess(const GURL& origin) {
701  return AllowContentAccess(origin, CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC);
702}
703
704bool ProfileIOData::ResourceContext::AllowCameraAccess(const GURL& origin) {
705  return AllowContentAccess(origin, CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA);
706}
707
708bool ProfileIOData::ResourceContext::AllowContentAccess(
709    const GURL& origin, ContentSettingsType type) {
710  HostContentSettingsMap* content_settings =
711      io_data_->GetHostContentSettingsMap();
712  ContentSetting setting = content_settings->GetContentSetting(
713      origin, origin, type, NO_RESOURCE_IDENTIFIER);
714  return setting == CONTENT_SETTING_ALLOW;
715}
716
717// static
718std::string ProfileIOData::GetSSLSessionCacheShard() {
719  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
720  // The SSL session cache is partitioned by setting a string. This returns a
721  // unique string to partition the SSL session cache. Each time we create a
722  // new profile, we'll get a fresh SSL session cache which is separate from
723  // the other profiles.
724  static unsigned ssl_session_cache_instance = 0;
725  return base::StringPrintf("profile/%u", ssl_session_cache_instance++);
726}
727
728void ProfileIOData::Init(content::ProtocolHandlerMap* protocol_handlers) const {
729  // The basic logic is implemented here. The specific initialization
730  // is done in InitializeInternal(), implemented by subtypes. Static helper
731  // functions have been provided to assist in common operations.
732  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
733  DCHECK(!initialized_);
734
735  startup_metric_utils::ScopedSlowStartupUMA
736      scoped_timer("Startup.SlowStartupProfileIODataInit");
737
738  // TODO(jhawkins): Remove once crbug.com/102004 is fixed.
739  CHECK(initialized_on_UI_thread_);
740
741  // TODO(jhawkins): Return to DCHECK once crbug.com/102004 is fixed.
742  CHECK(profile_params_.get());
743
744  IOThread* const io_thread = profile_params_->io_thread;
745  IOThread::Globals* const io_thread_globals = io_thread->globals();
746  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
747  load_time_stats_ = GetLoadTimeStats(io_thread_globals);
748
749  // Create the common request contexts.
750  main_request_context_.reset(
751      new ChromeURLRequestContext(ChromeURLRequestContext::CONTEXT_TYPE_MAIN,
752                                  load_time_stats_));
753  extensions_request_context_.reset(
754      new ChromeURLRequestContext(
755          ChromeURLRequestContext::CONTEXT_TYPE_EXTENSIONS,
756          load_time_stats_));
757
758  ChromeNetworkDelegate* network_delegate =
759      new ChromeNetworkDelegate(
760          io_thread_globals->extension_event_router_forwarder.get(),
761          &enable_referrers_);
762  network_delegate->set_extension_info_map(
763      profile_params_->extension_info_map.get());
764  network_delegate->set_url_blacklist_manager(url_blacklist_manager_.get());
765  network_delegate->set_profile(profile_params_->profile);
766  network_delegate->set_cookie_settings(profile_params_->cookie_settings.get());
767  network_delegate->set_enable_do_not_track(&enable_do_not_track_);
768  network_delegate->set_force_google_safe_search(&force_safesearch_);
769  network_delegate->set_load_time_stats(load_time_stats_);
770  network_delegate_.reset(network_delegate);
771
772  fraudulent_certificate_reporter_.reset(
773      new chrome_browser_net::ChromeFraudulentCertificateReporter(
774          main_request_context_.get()));
775
776  // NOTE: Proxy service uses the default io thread network delegate, not the
777  // delegate just created.
778  proxy_service_.reset(
779      ProxyServiceFactory::CreateProxyService(
780          io_thread->net_log(),
781          io_thread_globals->proxy_script_fetcher_context.get(),
782          io_thread_globals->system_network_delegate.get(),
783          profile_params_->proxy_config_service.release(),
784          command_line));
785
786  transport_security_state_.reset(new net::TransportSecurityState());
787  transport_security_persister_.reset(
788      new TransportSecurityPersister(transport_security_state_.get(),
789                                     profile_params_->path,
790                                     is_incognito()));
791
792  // Take ownership over these parameters.
793  cookie_settings_ = profile_params_->cookie_settings;
794  host_content_settings_map_ = profile_params_->host_content_settings_map;
795#if defined(ENABLE_NOTIFICATIONS)
796  notification_service_ = profile_params_->notification_service;
797#endif
798  extension_info_map_ = profile_params_->extension_info_map;
799
800  resource_context_->host_resolver_ = io_thread_globals->host_resolver.get();
801  resource_context_->request_context_ = main_request_context_.get();
802
803  if (profile_params_->resource_prefetch_predictor_observer_) {
804    resource_prefetch_predictor_observer_.reset(
805        profile_params_->resource_prefetch_predictor_observer_.release());
806  }
807
808#if defined(ENABLE_MANAGED_USERS)
809  managed_mode_url_filter_ = profile_params_->managed_mode_url_filter;
810#endif
811
812#if defined(OS_CHROMEOS)
813  cert_verifier_.reset(new policy::PolicyCertVerifier(
814      profile_params_->profile, profile_params_->trust_anchor_provider));
815  main_request_context_->set_cert_verifier(cert_verifier_.get());
816#else
817  main_request_context_->set_cert_verifier(
818      io_thread_globals->cert_verifier.get());
819#endif
820
821  InitializeInternal(profile_params_.get(), protocol_handlers);
822
823  profile_params_.reset();
824  initialized_ = true;
825}
826
827void ProfileIOData::ApplyProfileParamsToContext(
828    ChromeURLRequestContext* context) const {
829  context->set_http_user_agent_settings(
830      chrome_http_user_agent_settings_.get());
831  context->set_ssl_config_service(profile_params_->ssl_config_service.get());
832}
833
834scoped_ptr<net::URLRequestJobFactory> ProfileIOData::SetUpJobFactoryDefaults(
835    scoped_ptr<net::URLRequestJobFactoryImpl> job_factory,
836    scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
837        protocol_handler_interceptor,
838    net::NetworkDelegate* network_delegate,
839    net::FtpTransactionFactory* ftp_transaction_factory) const {
840  // NOTE(willchan): Keep these protocol handlers in sync with
841  // ProfileIOData::IsHandledProtocol().
842  bool set_protocol = job_factory->SetProtocolHandler(
843      chrome::kFileScheme,
844      new net::FileProtocolHandler(
845          content::BrowserThread::GetBlockingPool()->
846              GetTaskRunnerWithShutdownBehavior(
847                  base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)));
848  DCHECK(set_protocol);
849
850  DCHECK(extension_info_map_.get());
851  set_protocol = job_factory->SetProtocolHandler(
852      extensions::kExtensionScheme,
853      CreateExtensionProtocolHandler(is_incognito(),
854                                     extension_info_map_.get()));
855  DCHECK(set_protocol);
856  set_protocol = job_factory->SetProtocolHandler(
857      chrome::kExtensionResourceScheme,
858      CreateExtensionResourceProtocolHandler());
859  DCHECK(set_protocol);
860  set_protocol = job_factory->SetProtocolHandler(
861      chrome::kDataScheme, new net::DataProtocolHandler());
862  DCHECK(set_protocol);
863#if defined(OS_CHROMEOS)
864  if (!is_incognito() && profile_params_) {
865    set_protocol = job_factory->SetProtocolHandler(
866        chrome::kDriveScheme,
867        new drive::DriveProtocolHandler(profile_params_->profile));
868    DCHECK(set_protocol);
869  }
870#endif  // defined(OS_CHROMEOS)
871
872  job_factory->SetProtocolHandler(
873      chrome::kAboutScheme,
874      new chrome_browser_net::AboutProtocolHandler());
875#if !defined(DISABLE_FTP_SUPPORT)
876  DCHECK(ftp_transaction_factory);
877  job_factory->SetProtocolHandler(
878      chrome::kFtpScheme,
879      new net::FtpProtocolHandler(ftp_transaction_factory));
880#endif  // !defined(DISABLE_FTP_SUPPORT)
881
882  scoped_ptr<net::URLRequestJobFactory> top_job_factory =
883      job_factory.PassAs<net::URLRequestJobFactory>();
884#if defined(DEBUG_DEVTOOLS)
885  top_job_factory.reset(new net::ProtocolInterceptJobFactory(
886      top_job_factory.Pass(),
887      scoped_ptr<net::URLRequestJobFactory::ProtocolHandler>(
888          new DebugDevToolsInterceptor)));
889#endif
890
891  if (protocol_handler_interceptor) {
892    protocol_handler_interceptor->Chain(top_job_factory.Pass());
893    return protocol_handler_interceptor.PassAs<net::URLRequestJobFactory>();
894  } else {
895    return top_job_factory.Pass();
896  }
897}
898
899void ProfileIOData::ShutdownOnUIThread() {
900  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
901
902  if (signin_names_)
903    signin_names_->ReleaseResourcesOnUIThread();
904
905  google_services_username_.Destroy();
906  google_services_username_pattern_.Destroy();
907  reverse_autologin_enabled_.Destroy();
908  one_click_signin_rejected_email_list_.Destroy();
909  enable_referrers_.Destroy();
910  enable_do_not_track_.Destroy();
911  force_safesearch_.Destroy();
912#if !defined(OS_CHROMEOS)
913  enable_metrics_.Destroy();
914#endif
915  safe_browsing_enabled_.Destroy();
916  printing_enabled_.Destroy();
917  sync_disabled_.Destroy();
918  signin_allowed_.Destroy();
919  session_startup_pref_.Destroy();
920#if defined(ENABLE_CONFIGURATION_POLICY)
921  if (url_blacklist_manager_)
922    url_blacklist_manager_->ShutdownOnUIThread();
923#endif
924  if (chrome_http_user_agent_settings_)
925    chrome_http_user_agent_settings_->CleanupOnUIThread();
926  bool posted = BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, this);
927  if (!posted)
928    delete this;
929}
930
931void ProfileIOData::set_server_bound_cert_service(
932    net::ServerBoundCertService* server_bound_cert_service) const {
933  server_bound_cert_service_.reset(server_bound_cert_service);
934}
935
936void ProfileIOData::DestroyResourceContext() {
937  resource_context_.reset();
938}
939
940void ProfileIOData::PopulateNetworkSessionParams(
941    const ProfileParams* profile_params,
942    net::HttpNetworkSession::Params* params) const {
943
944  ChromeURLRequestContext* context = main_request_context();
945
946  IOThread* const io_thread = profile_params->io_thread;
947
948  io_thread->InitializeNetworkSessionParams(params);
949
950  params->host_resolver = context->host_resolver();
951  params->cert_verifier = context->cert_verifier();
952  params->server_bound_cert_service = context->server_bound_cert_service();
953  params->transport_security_state = context->transport_security_state();
954  params->proxy_service = context->proxy_service();
955  params->ssl_session_cache_shard = GetSSLSessionCacheShard();
956  params->ssl_config_service = context->ssl_config_service();
957  params->http_auth_handler_factory = context->http_auth_handler_factory();
958  params->network_delegate = network_delegate();
959  params->http_server_properties = context->http_server_properties();
960  params->net_log = context->net_log();
961}
962
963void ProfileIOData::SetCookieSettingsForTesting(
964    CookieSettings* cookie_settings) {
965  DCHECK(!cookie_settings_.get());
966  cookie_settings_ = cookie_settings;
967}
968
969void ProfileIOData::set_signin_names_for_testing(
970    SigninNamesOnIOThread* signin_names) {
971  signin_names_.reset(signin_names);
972}
973