profile_io_data.cc revision ca12bfac764ba476d6cd062bf1dde12cc64c3f40
1// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "chrome/browser/profiles/profile_io_data.h"
6
7#include <string>
8
9#include "base/basictypes.h"
10#include "base/bind.h"
11#include "base/bind_helpers.h"
12#include "base/command_line.h"
13#include "base/compiler_specific.h"
14#include "base/debug/alias.h"
15#include "base/logging.h"
16#include "base/path_service.h"
17#include "base/prefs/pref_service.h"
18#include "base/stl_util.h"
19#include "base/strings/string_number_conversions.h"
20#include "base/strings/string_util.h"
21#include "base/strings/stringprintf.h"
22#include "chrome/browser/browser_process.h"
23#include "chrome/browser/chrome_notification_types.h"
24#include "chrome/browser/content_settings/cookie_settings.h"
25#include "chrome/browser/content_settings/host_content_settings_map.h"
26#include "chrome/browser/custom_handlers/protocol_handler_registry.h"
27#include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h"
28#include "chrome/browser/download/download_service.h"
29#include "chrome/browser/download/download_service_factory.h"
30#include "chrome/browser/extensions/extension_info_map.h"
31#include "chrome/browser/extensions/extension_protocols.h"
32#include "chrome/browser/extensions/extension_resource_protocols.h"
33#include "chrome/browser/extensions/extension_system.h"
34#include "chrome/browser/io_thread.h"
35#include "chrome/browser/net/about_protocol_handler.h"
36#include "chrome/browser/net/chrome_cookie_notification_details.h"
37#include "chrome/browser/net/chrome_fraudulent_certificate_reporter.h"
38#include "chrome/browser/net/chrome_http_user_agent_settings.h"
39#include "chrome/browser/net/chrome_net_log.h"
40#include "chrome/browser/net/chrome_network_delegate.h"
41#include "chrome/browser/net/evicted_domain_cookie_counter.h"
42#include "chrome/browser/net/load_time_stats.h"
43#include "chrome/browser/net/proxy_service_factory.h"
44#include "chrome/browser/net/resource_prefetch_predictor_observer.h"
45#include "chrome/browser/net/transport_security_persister.h"
46#include "chrome/browser/notifications/desktop_notification_service_factory.h"
47#include "chrome/browser/policy/url_blacklist_manager.h"
48#include "chrome/browser/predictors/resource_prefetch_predictor.h"
49#include "chrome/browser/predictors/resource_prefetch_predictor_factory.h"
50#include "chrome/browser/profiles/profile.h"
51#include "chrome/browser/profiles/profile_manager.h"
52#include "chrome/browser/signin/signin_names_io_thread.h"
53#include "chrome/common/chrome_paths.h"
54#include "chrome/common/chrome_switches.h"
55#include "chrome/common/pref_names.h"
56#include "chrome/common/startup_metric_utils.h"
57#include "chrome/common/url_constants.h"
58#include "content/public/browser/browser_thread.h"
59#include "content/public/browser/host_zoom_map.h"
60#include "content/public/browser/notification_service.h"
61#include "content/public/browser/resource_context.h"
62#include "extensions/common/constants.h"
63#include "net/cert/cert_verifier.h"
64#include "net/cookies/canonical_cookie.h"
65#include "net/cookies/cookie_monster.h"
66#include "net/http/http_transaction_factory.h"
67#include "net/http/http_util.h"
68#include "net/proxy/proxy_config_service_fixed.h"
69#include "net/proxy/proxy_script_fetcher_impl.h"
70#include "net/proxy/proxy_service.h"
71#include "net/ssl/server_bound_cert_service.h"
72#include "net/url_request/data_protocol_handler.h"
73#include "net/url_request/file_protocol_handler.h"
74#include "net/url_request/ftp_protocol_handler.h"
75#include "net/url_request/protocol_intercept_job_factory.h"
76#include "net/url_request/url_request.h"
77#include "net/url_request/url_request_file_job.h"
78#include "net/url_request/url_request_job_factory_impl.h"
79
80#if defined(ENABLE_MANAGED_USERS)
81#include "chrome/browser/managed_mode/managed_mode_url_filter.h"
82#include "chrome/browser/managed_mode/managed_user_service.h"
83#include "chrome/browser/managed_mode/managed_user_service_factory.h"
84#endif
85
86#if defined(OS_CHROMEOS)
87#include "chrome/browser/chromeos/drive/drive_protocol_handler.h"
88#include "chrome/browser/chromeos/policy/policy_cert_verifier.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  params->proxy_config_service
264      .reset(ProxyServiceFactory::CreateProxyConfigService(
265           profile->GetProxyConfigTracker()));
266#if defined(ENABLE_MANAGED_USERS)
267  ManagedUserService* managed_user_service =
268      ManagedUserServiceFactory::GetForProfile(profile);
269  params->managed_mode_url_filter =
270      managed_user_service->GetURLFilterForIOThread();
271#endif
272#if defined(OS_CHROMEOS)
273  policy::BrowserPolicyConnector* connector =
274      g_browser_process->browser_policy_connector();
275  params->trust_anchor_provider = connector->GetCertTrustAnchorProvider();
276#endif
277
278  params->profile = profile;
279  profile_params_.reset(params.release());
280
281  ChromeNetworkDelegate::InitializePrefsOnUIThread(
282      &enable_referrers_,
283      &enable_do_not_track_,
284      &force_safesearch_,
285      pref_service);
286
287  scoped_refptr<base::MessageLoopProxy> io_message_loop_proxy =
288      BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
289#if defined(ENABLE_PRINTING)
290  printing_enabled_.Init(prefs::kPrintingEnabled, pref_service);
291  printing_enabled_.MoveToThread(io_message_loop_proxy);
292#endif
293  chrome_http_user_agent_settings_.reset(
294      new ChromeHttpUserAgentSettings(pref_service));
295
296  // These members are used only for one click sign in, which is not enabled
297  // in incognito mode.  So no need to initialize them.
298  if (!is_incognito()) {
299    signin_names_.reset(new SigninNamesOnIOThread());
300
301    google_services_username_.Init(
302        prefs::kGoogleServicesUsername, pref_service);
303    google_services_username_.MoveToThread(io_message_loop_proxy);
304
305    google_services_username_pattern_.Init(
306        prefs::kGoogleServicesUsernamePattern, local_state_pref_service);
307    google_services_username_pattern_.MoveToThread(io_message_loop_proxy);
308
309    reverse_autologin_enabled_.Init(
310        prefs::kReverseAutologinEnabled, pref_service);
311    reverse_autologin_enabled_.MoveToThread(io_message_loop_proxy);
312
313    one_click_signin_rejected_email_list_.Init(
314        prefs::kReverseAutologinRejectedEmailList, pref_service);
315    one_click_signin_rejected_email_list_.MoveToThread(io_message_loop_proxy);
316
317    sync_disabled_.Init(prefs::kSyncManaged, pref_service);
318    sync_disabled_.MoveToThread(io_message_loop_proxy);
319
320    signin_allowed_.Init(prefs::kSigninAllowed, pref_service);
321    signin_allowed_.MoveToThread(io_message_loop_proxy);
322  }
323
324  // The URLBlacklistManager has to be created on the UI thread to register
325  // observers of |pref_service|, and it also has to clean up on
326  // ShutdownOnUIThread to release these observers on the right thread.
327  // Don't pass it in |profile_params_| to make sure it is correctly cleaned up,
328  // in particular when this ProfileIOData isn't |initialized_| during deletion.
329#if defined(ENABLE_CONFIGURATION_POLICY)
330  url_blacklist_manager_.reset(new policy::URLBlacklistManager(pref_service));
331#endif
332
333  initialized_on_UI_thread_ = true;
334
335  // We need to make sure that content initializes its own data structures that
336  // are associated with each ResourceContext because we might post this
337  // object to the IO thread after this function.
338  BrowserContext::EnsureResourceContextInitialized(profile);
339}
340
341ProfileIOData::MediaRequestContext::MediaRequestContext(
342    chrome_browser_net::LoadTimeStats* load_time_stats)
343    : ChromeURLRequestContext(ChromeURLRequestContext::CONTEXT_TYPE_MEDIA,
344                              load_time_stats) {
345}
346
347void ProfileIOData::MediaRequestContext::SetHttpTransactionFactory(
348    scoped_ptr<net::HttpTransactionFactory> http_factory) {
349  http_factory_ = http_factory.Pass();
350  set_http_transaction_factory(http_factory_.get());
351}
352
353ProfileIOData::MediaRequestContext::~MediaRequestContext() {}
354
355ProfileIOData::AppRequestContext::AppRequestContext(
356    chrome_browser_net::LoadTimeStats* load_time_stats)
357    : ChromeURLRequestContext(ChromeURLRequestContext::CONTEXT_TYPE_APP,
358                              load_time_stats) {
359}
360
361void ProfileIOData::AppRequestContext::SetCookieStore(
362    net::CookieStore* cookie_store) {
363  cookie_store_ = cookie_store;
364  set_cookie_store(cookie_store);
365}
366
367void ProfileIOData::AppRequestContext::SetHttpTransactionFactory(
368    scoped_ptr<net::HttpTransactionFactory> http_factory) {
369  http_factory_ = http_factory.Pass();
370  set_http_transaction_factory(http_factory_.get());
371}
372
373void ProfileIOData::AppRequestContext::SetJobFactory(
374    scoped_ptr<net::URLRequestJobFactory> job_factory) {
375  job_factory_ = job_factory.Pass();
376  set_job_factory(job_factory_.get());
377}
378
379ProfileIOData::AppRequestContext::~AppRequestContext() {}
380
381ProfileIOData::ProfileParams::ProfileParams()
382    : io_thread(NULL),
383#if defined(ENABLE_NOTIFICATIONS)
384      notification_service(NULL),
385#endif
386#if defined(OS_CHROMEOS)
387      trust_anchor_provider(NULL),
388#endif
389      profile(NULL) {
390}
391
392ProfileIOData::ProfileParams::~ProfileParams() {}
393
394ProfileIOData::ProfileIOData(bool is_incognito)
395    : initialized_(false),
396#if defined(ENABLE_NOTIFICATIONS)
397      notification_service_(NULL),
398#endif
399      resource_context_(new ResourceContext(this)),
400      load_time_stats_(NULL),
401      initialized_on_UI_thread_(false),
402      is_incognito_(is_incognito) {
403  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
404}
405
406ProfileIOData::~ProfileIOData() {
407  if (BrowserThread::IsMessageLoopValid(BrowserThread::IO))
408    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
409
410  // Pull the contents of the request context maps onto the stack for sanity
411  // checking of values in a minidump. http://crbug.com/260425
412  size_t num_app_contexts = app_request_context_map_.size();
413  size_t num_media_contexts = isolated_media_request_context_map_.size();
414  size_t current_context = 0;
415  static const size_t kMaxCachedContexts = 20;
416  ChromeURLRequestContext* app_context_cache[kMaxCachedContexts] = {0};
417  void* app_context_vtable_cache[kMaxCachedContexts] = {0};
418  ChromeURLRequestContext* media_context_cache[kMaxCachedContexts] = {0};
419  void* media_context_vtable_cache[kMaxCachedContexts] = {0};
420  void* tmp_vtable = NULL;
421  base::debug::Alias(&num_app_contexts);
422  base::debug::Alias(&num_media_contexts);
423  base::debug::Alias(&current_context);
424  base::debug::Alias(app_context_cache);
425  base::debug::Alias(app_context_vtable_cache);
426  base::debug::Alias(media_context_cache);
427  base::debug::Alias(media_context_vtable_cache);
428  base::debug::Alias(&tmp_vtable);
429
430  current_context = 0;
431  for (URLRequestContextMap::const_iterator it =
432           app_request_context_map_.begin();
433       current_context < kMaxCachedContexts &&
434           it != app_request_context_map_.end();
435       ++it, ++current_context) {
436    app_context_cache[current_context] = it->second;
437    memcpy(&app_context_vtable_cache[current_context],
438           static_cast<void*>(it->second), sizeof(void*));
439  }
440
441  current_context = 0;
442  for (URLRequestContextMap::const_iterator it =
443           isolated_media_request_context_map_.begin();
444       current_context < kMaxCachedContexts &&
445           it != isolated_media_request_context_map_.end();
446       ++it, ++current_context) {
447    media_context_cache[current_context] = it->second;
448    memcpy(&media_context_vtable_cache[current_context],
449           static_cast<void*>(it->second), sizeof(void*));
450  }
451
452  // TODO(ajwong): These AssertNoURLRequests() calls are unnecessary since they
453  // are already done in the URLRequestContext destructor.
454  if (main_request_context_)
455    main_request_context_->AssertNoURLRequests();
456  if (extensions_request_context_)
457    extensions_request_context_->AssertNoURLRequests();
458
459  current_context = 0;
460  for (URLRequestContextMap::iterator it = app_request_context_map_.begin();
461       it != app_request_context_map_.end(); ++it) {
462    if (current_context < kMaxCachedContexts) {
463      CHECK_EQ(app_context_cache[current_context], it->second);
464      memcpy(&tmp_vtable, static_cast<void*>(it->second), sizeof(void*));
465      CHECK_EQ(app_context_vtable_cache[current_context], tmp_vtable);
466    }
467    it->second->AssertNoURLRequests();
468    delete it->second;
469    current_context++;
470  }
471
472  current_context = 0;
473  for (URLRequestContextMap::iterator it =
474           isolated_media_request_context_map_.begin();
475       it != isolated_media_request_context_map_.end(); ++it) {
476    if (current_context < kMaxCachedContexts) {
477      CHECK_EQ(media_context_cache[current_context], it->second);
478      memcpy(&tmp_vtable, static_cast<void*>(it->second), sizeof(void*));
479      CHECK_EQ(media_context_vtable_cache[current_context], tmp_vtable);
480    }
481    it->second->AssertNoURLRequests();
482    delete it->second;
483    current_context++;
484  }
485}
486
487// static
488ProfileIOData* ProfileIOData::FromResourceContext(
489    content::ResourceContext* rc) {
490  return (static_cast<ResourceContext*>(rc))->io_data_;
491}
492
493// static
494bool ProfileIOData::IsHandledProtocol(const std::string& scheme) {
495  DCHECK_EQ(scheme, StringToLowerASCII(scheme));
496  static const char* const kProtocolList[] = {
497    chrome::kFileScheme,
498    chrome::kChromeDevToolsScheme,
499    extensions::kExtensionScheme,
500    chrome::kExtensionResourceScheme,
501    chrome::kChromeUIScheme,
502    chrome::kDataScheme,
503#if defined(OS_CHROMEOS)
504    chrome::kDriveScheme,
505#endif  // defined(OS_CHROMEOS)
506    chrome::kAboutScheme,
507#if !defined(DISABLE_FTP_SUPPORT)
508    chrome::kFtpScheme,
509#endif  // !defined(DISABLE_FTP_SUPPORT)
510    chrome::kBlobScheme,
511    chrome::kFileSystemScheme,
512    chrome::kChromeSearchScheme,
513  };
514  for (size_t i = 0; i < arraysize(kProtocolList); ++i) {
515    if (scheme == kProtocolList[i])
516      return true;
517  }
518  return net::URLRequest::IsHandledProtocol(scheme);
519}
520
521// static
522bool ProfileIOData::IsHandledURL(const GURL& url) {
523  if (!url.is_valid()) {
524    // We handle error cases.
525    return true;
526  }
527
528  return IsHandledProtocol(url.scheme());
529}
530
531// static
532void ProfileIOData::InstallProtocolHandlers(
533    net::URLRequestJobFactoryImpl* job_factory,
534    content::ProtocolHandlerMap* protocol_handlers) {
535  for (content::ProtocolHandlerMap::iterator it =
536           protocol_handlers->begin();
537       it != protocol_handlers->end();
538       ++it) {
539    bool set_protocol = job_factory->SetProtocolHandler(
540        it->first, it->second.release());
541    DCHECK(set_protocol);
542  }
543  protocol_handlers->clear();
544}
545
546content::ResourceContext* ProfileIOData::GetResourceContext() const {
547  return resource_context_.get();
548}
549
550ChromeURLRequestContext* ProfileIOData::GetMainRequestContext() const {
551  DCHECK(initialized_);
552  return main_request_context_.get();
553}
554
555ChromeURLRequestContext* ProfileIOData::GetMediaRequestContext() const {
556  DCHECK(initialized_);
557  ChromeURLRequestContext* context = AcquireMediaRequestContext();
558  DCHECK(context);
559  return context;
560}
561
562ChromeURLRequestContext* ProfileIOData::GetExtensionsRequestContext() const {
563  DCHECK(initialized_);
564  return extensions_request_context_.get();
565}
566
567ChromeURLRequestContext* ProfileIOData::GetIsolatedAppRequestContext(
568    ChromeURLRequestContext* main_context,
569    const StoragePartitionDescriptor& partition_descriptor,
570    scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
571        protocol_handler_interceptor,
572    content::ProtocolHandlerMap* protocol_handlers) const {
573  DCHECK(initialized_);
574  ChromeURLRequestContext* context = NULL;
575  if (ContainsKey(app_request_context_map_, partition_descriptor)) {
576    context = app_request_context_map_[partition_descriptor];
577  } else {
578    context = AcquireIsolatedAppRequestContext(
579        main_context, partition_descriptor, protocol_handler_interceptor.Pass(),
580        protocol_handlers);
581    app_request_context_map_[partition_descriptor] = context;
582  }
583  DCHECK(context);
584  return context;
585}
586
587ChromeURLRequestContext* ProfileIOData::GetIsolatedMediaRequestContext(
588    ChromeURLRequestContext* app_context,
589    const StoragePartitionDescriptor& partition_descriptor) const {
590  DCHECK(initialized_);
591  ChromeURLRequestContext* context = NULL;
592  if (ContainsKey(isolated_media_request_context_map_, partition_descriptor)) {
593    context = isolated_media_request_context_map_[partition_descriptor];
594  } else {
595    context = AcquireIsolatedMediaRequestContext(app_context,
596                                                 partition_descriptor);
597    isolated_media_request_context_map_[partition_descriptor] = context;
598  }
599  DCHECK(context);
600  return context;
601}
602
603ExtensionInfoMap* ProfileIOData::GetExtensionInfoMap() const {
604  DCHECK(initialized_) << "ExtensionSystem not initialized";
605  return extension_info_map_.get();
606}
607
608CookieSettings* ProfileIOData::GetCookieSettings() const {
609  // Allow either Init() or SetCookieSettingsForTesting() to initialize.
610  DCHECK(initialized_ || cookie_settings_.get());
611  return cookie_settings_.get();
612}
613
614#if defined(ENABLE_NOTIFICATIONS)
615DesktopNotificationService* ProfileIOData::GetNotificationService() const {
616  DCHECK(initialized_);
617  return notification_service_;
618}
619#endif
620
621void ProfileIOData::InitializeMetricsEnabledStateOnUIThread() {
622  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
623#if defined(OS_CHROMEOS)
624  // Just fetch the value from ChromeOS' settings while we're on the UI thread.
625  // TODO(stevet): For now, this value is only set on profile initialization.
626  // We will want to do something similar to the PrefMember method below in the
627  // future to more accurately capture this state.
628  chromeos::CrosSettings::Get()->GetBoolean(chromeos::kStatsReportingPref,
629                                            &enable_metrics_);
630#elif defined(OS_ANDROID)
631  // TODO(dwkang): rename or unify the pref for UMA once we have conclusion
632  // in crbugs.com/246495.
633  // Android has it's own preferences for metrics / crash uploading.
634  enable_metrics_.Init(prefs::kCrashReportingEnabled,
635                       g_browser_process->local_state());
636  enable_metrics_.MoveToThread(
637      BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
638#else
639  // Prep the PrefMember and send it to the IO thread, since this value will be
640  // read from there.
641  enable_metrics_.Init(prefs::kMetricsReportingEnabled,
642                       g_browser_process->local_state());
643  enable_metrics_.MoveToThread(
644      BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
645#endif  // defined(OS_CHROMEOS)
646}
647
648bool ProfileIOData::GetMetricsEnabledStateOnIOThread() const {
649  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
650#if defined(OS_CHROMEOS)
651  return enable_metrics_;
652#else
653  return enable_metrics_.GetValue();
654#endif  // defined(OS_CHROMEOS)
655}
656
657base::WeakPtr<net::HttpServerProperties>
658ProfileIOData::http_server_properties() const {
659  return http_server_properties_->GetWeakPtr();
660}
661
662void ProfileIOData::set_http_server_properties(
663    scoped_ptr<net::HttpServerProperties> http_server_properties) const {
664  http_server_properties_ = http_server_properties.Pass();
665}
666
667ProfileIOData::ResourceContext::ResourceContext(ProfileIOData* io_data)
668    : io_data_(io_data),
669      host_resolver_(NULL),
670      request_context_(NULL) {
671  DCHECK(io_data);
672}
673
674ProfileIOData::ResourceContext::~ResourceContext() {}
675
676net::HostResolver* ProfileIOData::ResourceContext::GetHostResolver()  {
677  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
678  DCHECK(io_data_->initialized_);
679  return host_resolver_;
680}
681
682net::URLRequestContext* ProfileIOData::ResourceContext::GetRequestContext()  {
683  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
684  DCHECK(io_data_->initialized_);
685  return request_context_;
686}
687
688// static
689std::string ProfileIOData::GetSSLSessionCacheShard() {
690  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
691  // The SSL session cache is partitioned by setting a string. This returns a
692  // unique string to partition the SSL session cache. Each time we create a
693  // new profile, we'll get a fresh SSL session cache which is separate from
694  // the other profiles.
695  static unsigned ssl_session_cache_instance = 0;
696  return base::StringPrintf("profile/%u", ssl_session_cache_instance++);
697}
698
699void ProfileIOData::Init(content::ProtocolHandlerMap* protocol_handlers) const {
700  // The basic logic is implemented here. The specific initialization
701  // is done in InitializeInternal(), implemented by subtypes. Static helper
702  // functions have been provided to assist in common operations.
703  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
704  DCHECK(!initialized_);
705
706  startup_metric_utils::ScopedSlowStartupUMA
707      scoped_timer("Startup.SlowStartupProfileIODataInit");
708
709  // TODO(jhawkins): Remove once crbug.com/102004 is fixed.
710  CHECK(initialized_on_UI_thread_);
711
712  // TODO(jhawkins): Return to DCHECK once crbug.com/102004 is fixed.
713  CHECK(profile_params_.get());
714
715  IOThread* const io_thread = profile_params_->io_thread;
716  IOThread::Globals* const io_thread_globals = io_thread->globals();
717  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
718  load_time_stats_ = GetLoadTimeStats(io_thread_globals);
719
720  // Create the common request contexts.
721  main_request_context_.reset(
722      new ChromeURLRequestContext(ChromeURLRequestContext::CONTEXT_TYPE_MAIN,
723                                  load_time_stats_));
724  extensions_request_context_.reset(
725      new ChromeURLRequestContext(
726          ChromeURLRequestContext::CONTEXT_TYPE_EXTENSIONS,
727          load_time_stats_));
728
729  ChromeNetworkDelegate* network_delegate =
730      new ChromeNetworkDelegate(
731          io_thread_globals->extension_event_router_forwarder.get(),
732          &enable_referrers_);
733  network_delegate->set_extension_info_map(
734      profile_params_->extension_info_map.get());
735  network_delegate->set_url_blacklist_manager(url_blacklist_manager_.get());
736  network_delegate->set_profile(profile_params_->profile);
737  network_delegate->set_cookie_settings(profile_params_->cookie_settings.get());
738  network_delegate->set_enable_do_not_track(&enable_do_not_track_);
739  network_delegate->set_force_google_safe_search(&force_safesearch_);
740  network_delegate->set_load_time_stats(load_time_stats_);
741  network_delegate_.reset(network_delegate);
742
743  fraudulent_certificate_reporter_.reset(
744      new chrome_browser_net::ChromeFraudulentCertificateReporter(
745          main_request_context_.get()));
746
747  // NOTE: Proxy service uses the default io thread network delegate, not the
748  // delegate just created.
749  proxy_service_.reset(
750      ProxyServiceFactory::CreateProxyService(
751          io_thread->net_log(),
752          io_thread_globals->proxy_script_fetcher_context.get(),
753          io_thread_globals->system_network_delegate.get(),
754          profile_params_->proxy_config_service.release(),
755          command_line));
756
757  transport_security_state_.reset(new net::TransportSecurityState());
758  transport_security_persister_.reset(
759      new TransportSecurityPersister(transport_security_state_.get(),
760                                     profile_params_->path,
761                                     is_incognito()));
762
763  // Take ownership over these parameters.
764  cookie_settings_ = profile_params_->cookie_settings;
765#if defined(ENABLE_NOTIFICATIONS)
766  notification_service_ = profile_params_->notification_service;
767#endif
768  extension_info_map_ = profile_params_->extension_info_map;
769
770  resource_context_->host_resolver_ = io_thread_globals->host_resolver.get();
771  resource_context_->request_context_ = main_request_context_.get();
772
773  if (profile_params_->resource_prefetch_predictor_observer_) {
774    resource_prefetch_predictor_observer_.reset(
775        profile_params_->resource_prefetch_predictor_observer_.release());
776  }
777
778#if defined(ENABLE_MANAGED_USERS)
779  managed_mode_url_filter_ = profile_params_->managed_mode_url_filter;
780#endif
781
782#if defined(OS_CHROMEOS)
783  cert_verifier_.reset(new policy::PolicyCertVerifier(
784      profile_params_->profile, profile_params_->trust_anchor_provider));
785  main_request_context_->set_cert_verifier(cert_verifier_.get());
786#else
787  main_request_context_->set_cert_verifier(
788      io_thread_globals->cert_verifier.get());
789#endif
790
791  InitializeInternal(profile_params_.get(), protocol_handlers);
792
793  profile_params_.reset();
794  initialized_ = true;
795}
796
797void ProfileIOData::ApplyProfileParamsToContext(
798    ChromeURLRequestContext* context) const {
799  context->set_http_user_agent_settings(
800      chrome_http_user_agent_settings_.get());
801  context->set_ssl_config_service(profile_params_->ssl_config_service.get());
802}
803
804scoped_ptr<net::URLRequestJobFactory> ProfileIOData::SetUpJobFactoryDefaults(
805    scoped_ptr<net::URLRequestJobFactoryImpl> job_factory,
806    scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
807        protocol_handler_interceptor,
808    net::NetworkDelegate* network_delegate,
809    net::FtpTransactionFactory* ftp_transaction_factory) const {
810  // NOTE(willchan): Keep these protocol handlers in sync with
811  // ProfileIOData::IsHandledProtocol().
812  bool set_protocol = job_factory->SetProtocolHandler(
813      chrome::kFileScheme, new net::FileProtocolHandler());
814  DCHECK(set_protocol);
815
816  DCHECK(extension_info_map_.get());
817  set_protocol = job_factory->SetProtocolHandler(
818      extensions::kExtensionScheme,
819      CreateExtensionProtocolHandler(is_incognito(),
820                                     extension_info_map_.get()));
821  DCHECK(set_protocol);
822  set_protocol = job_factory->SetProtocolHandler(
823      chrome::kExtensionResourceScheme,
824      CreateExtensionResourceProtocolHandler());
825  DCHECK(set_protocol);
826  set_protocol = job_factory->SetProtocolHandler(
827      chrome::kDataScheme, new net::DataProtocolHandler());
828  DCHECK(set_protocol);
829#if defined(OS_CHROMEOS)
830  if (!is_incognito() && profile_params_) {
831    set_protocol = job_factory->SetProtocolHandler(
832        chrome::kDriveScheme,
833        new drive::DriveProtocolHandler(profile_params_->profile));
834    DCHECK(set_protocol);
835  }
836#endif  // defined(OS_CHROMEOS)
837
838  job_factory->SetProtocolHandler(
839      chrome::kAboutScheme,
840      new chrome_browser_net::AboutProtocolHandler());
841#if !defined(DISABLE_FTP_SUPPORT)
842  DCHECK(ftp_transaction_factory);
843  job_factory->SetProtocolHandler(
844      chrome::kFtpScheme,
845      new net::FtpProtocolHandler(ftp_transaction_factory));
846#endif  // !defined(DISABLE_FTP_SUPPORT)
847
848  scoped_ptr<net::URLRequestJobFactory> top_job_factory =
849      job_factory.PassAs<net::URLRequestJobFactory>();
850#if defined(DEBUG_DEVTOOLS)
851  top_job_factory.reset(new net::ProtocolInterceptJobFactory(
852      top_job_factory.Pass(),
853      scoped_ptr<net::URLRequestJobFactory::ProtocolHandler>(
854          new DebugDevToolsInterceptor)));
855#endif
856
857  if (protocol_handler_interceptor) {
858    protocol_handler_interceptor->Chain(top_job_factory.Pass());
859    return protocol_handler_interceptor.PassAs<net::URLRequestJobFactory>();
860  } else {
861    return top_job_factory.Pass();
862  }
863}
864
865void ProfileIOData::ShutdownOnUIThread() {
866  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
867
868  if (signin_names_)
869    signin_names_->ReleaseResourcesOnUIThread();
870
871  google_services_username_.Destroy();
872  google_services_username_pattern_.Destroy();
873  reverse_autologin_enabled_.Destroy();
874  one_click_signin_rejected_email_list_.Destroy();
875  enable_referrers_.Destroy();
876  enable_do_not_track_.Destroy();
877  force_safesearch_.Destroy();
878#if !defined(OS_CHROMEOS)
879  enable_metrics_.Destroy();
880#endif
881  safe_browsing_enabled_.Destroy();
882  printing_enabled_.Destroy();
883  sync_disabled_.Destroy();
884  signin_allowed_.Destroy();
885  session_startup_pref_.Destroy();
886#if defined(ENABLE_CONFIGURATION_POLICY)
887  if (url_blacklist_manager_)
888    url_blacklist_manager_->ShutdownOnUIThread();
889#endif
890  if (chrome_http_user_agent_settings_)
891    chrome_http_user_agent_settings_->CleanupOnUIThread();
892  bool posted = BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, this);
893  if (!posted)
894    delete this;
895}
896
897void ProfileIOData::set_server_bound_cert_service(
898    net::ServerBoundCertService* server_bound_cert_service) const {
899  server_bound_cert_service_.reset(server_bound_cert_service);
900}
901
902void ProfileIOData::DestroyResourceContext() {
903  resource_context_.reset();
904}
905
906void ProfileIOData::PopulateNetworkSessionParams(
907    const ProfileParams* profile_params,
908    net::HttpNetworkSession::Params* params) const {
909
910  ChromeURLRequestContext* context = main_request_context();
911
912  IOThread* const io_thread = profile_params->io_thread;
913
914  io_thread->InitializeNetworkSessionParams(params);
915
916  params->host_resolver = context->host_resolver();
917  params->cert_verifier = context->cert_verifier();
918  params->server_bound_cert_service = context->server_bound_cert_service();
919  params->transport_security_state = context->transport_security_state();
920  params->proxy_service = context->proxy_service();
921  params->ssl_session_cache_shard = GetSSLSessionCacheShard();
922  params->ssl_config_service = context->ssl_config_service();
923  params->http_auth_handler_factory = context->http_auth_handler_factory();
924  params->network_delegate = network_delegate();
925  params->http_server_properties = context->http_server_properties();
926  params->net_log = context->net_log();
927}
928
929void ProfileIOData::SetCookieSettingsForTesting(
930    CookieSettings* cookie_settings) {
931  DCHECK(!cookie_settings_.get());
932  cookie_settings_ = cookie_settings;
933}
934
935void ProfileIOData::set_signin_names_for_testing(
936    SigninNamesOnIOThread* signin_names) {
937  signin_names_.reset(signin_names);
938}
939