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