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