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