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