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