profile_io_data.cc revision 5c02ac1a9c1b504631c0a3d2b6e737b5d738bae1
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_resource_protocols.h"
34#include "chrome/browser/io_thread.h"
35#include "chrome/browser/media/media_device_id_salt.h"
36#include "chrome/browser/net/about_protocol_handler.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/cookie_store_util.h"
42#include "chrome/browser/net/proxy_service_factory.h"
43#include "chrome/browser/profiles/profile.h"
44#include "chrome/browser/profiles/profile_manager.h"
45#include "chrome/browser/signin/signin_names_io_thread.h"
46#include "chrome/common/chrome_paths.h"
47#include "chrome/common/chrome_switches.h"
48#include "chrome/common/net/url_fixer_upper.h"
49#include "chrome/common/pref_names.h"
50#include "chrome/common/url_constants.h"
51#include "components/startup_metric_utils/startup_metric_utils.h"
52#include "components/sync_driver/pref_names.h"
53#include "content/public/browser/browser_thread.h"
54#include "content/public/browser/host_zoom_map.h"
55#include "content/public/browser/notification_service.h"
56#include "content/public/browser/resource_context.h"
57#include "extensions/browser/extension_protocols.h"
58#include "extensions/browser/extension_system.h"
59#include "extensions/browser/info_map.h"
60#include "extensions/common/constants.h"
61#include "net/base/keygen_handler.h"
62#include "net/cookies/canonical_cookie.h"
63#include "net/http/http_transaction_factory.h"
64#include "net/http/http_util.h"
65#include "net/http/transport_security_persister.h"
66#include "net/proxy/proxy_config_service_fixed.h"
67#include "net/proxy/proxy_script_fetcher_impl.h"
68#include "net/proxy/proxy_service.h"
69#include "net/ssl/client_cert_store.h"
70#include "net/ssl/server_bound_cert_service.h"
71#include "net/url_request/data_protocol_handler.h"
72#include "net/url_request/file_protocol_handler.h"
73#include "net/url_request/ftp_protocol_handler.h"
74#include "net/url_request/protocol_intercept_job_factory.h"
75#include "net/url_request/url_request.h"
76#include "net/url_request/url_request_file_job.h"
77#include "net/url_request/url_request_job_factory_impl.h"
78
79#if defined(ENABLE_CONFIGURATION_POLICY)
80#include "chrome/browser/policy/cloud/policy_header_service_factory.h"
81#include "chrome/browser/policy/policy_helpers.h"
82#include "components/policy/core/browser/url_blacklist_manager.h"
83#include "components/policy/core/common/cloud/policy_header_io_helper.h"
84#include "components/policy/core/common/cloud/policy_header_service.h"
85#include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
86#endif
87
88#if defined(ENABLE_MANAGED_USERS)
89#include "chrome/browser/managed_mode/managed_mode_url_filter.h"
90#include "chrome/browser/managed_mode/managed_user_service.h"
91#include "chrome/browser/managed_mode/managed_user_service_factory.h"
92#endif
93
94#if defined(OS_CHROMEOS)
95#include "chrome/browser/chromeos/drive/drive_protocol_handler.h"
96#include "chrome/browser/chromeos/login/startup_utils.h"
97#include "chrome/browser/chromeos/login/user.h"
98#include "chrome/browser/chromeos/login/user_manager.h"
99#include "chrome/browser/chromeos/net/cert_verify_proc_chromeos.h"
100#include "chrome/browser/chromeos/policy/policy_cert_service.h"
101#include "chrome/browser/chromeos/policy/policy_cert_service_factory.h"
102#include "chrome/browser/chromeos/policy/policy_cert_verifier.h"
103#include "chrome/browser/chromeos/settings/cros_settings.h"
104#include "chromeos/dbus/cryptohome_client.h"
105#include "chromeos/dbus/dbus_thread_manager.h"
106#include "chromeos/settings/cros_settings_names.h"
107#include "crypto/nss_util.h"
108#include "crypto/nss_util_internal.h"
109#include "net/cert/multi_threaded_cert_verifier.h"
110#include "net/ssl/client_cert_store_chromeos.h"
111#endif  // defined(OS_CHROMEOS)
112
113#if defined(USE_NSS)
114#include "chrome/browser/ui/crypto_module_delegate_nss.h"
115#include "net/ssl/client_cert_store_nss.h"
116#endif
117
118#if defined(OS_WIN)
119#include "net/ssl/client_cert_store_win.h"
120#endif
121
122#if defined(OS_MACOSX)
123#include "net/ssl/client_cert_store_mac.h"
124#endif
125
126using content::BrowserContext;
127using content::BrowserThread;
128using content::ResourceContext;
129
130namespace {
131
132#if defined(DEBUG_DEVTOOLS)
133bool IsSupportedDevToolsURL(const GURL& url, base::FilePath* path) {
134  std::string bundled_path_prefix(chrome::kChromeUIDevToolsBundledPath);
135  bundled_path_prefix = "/" + bundled_path_prefix + "/";
136
137  if (!url.SchemeIs(content::kChromeDevToolsScheme) ||
138      url.host() != chrome::kChromeUIDevToolsHost ||
139      !StartsWithASCII(url.path(), bundled_path_prefix, false)) {
140    return false;
141  }
142
143  if (!url.is_valid()) {
144    NOTREACHED();
145    return false;
146  }
147
148  // Remove Query and Ref from URL.
149  GURL stripped_url;
150  GURL::Replacements replacements;
151  replacements.ClearQuery();
152  replacements.ClearRef();
153  stripped_url = url.ReplaceComponents(replacements);
154
155  std::string relative_path;
156  const std::string& spec = stripped_url.possibly_invalid_spec();
157  const url::Parsed& parsed = stripped_url.parsed_for_possibly_invalid_spec();
158  int offset = parsed.CountCharactersBefore(url::Parsed::PATH, false);
159  if (offset < static_cast<int>(spec.size()))
160    relative_path.assign(spec.substr(offset + bundled_path_prefix.length()));
161
162  // Check that |relative_path| is not an absolute path (otherwise
163  // AppendASCII() will DCHECK).  The awkward use of StringType is because on
164  // some systems FilePath expects a std::string, but on others a std::wstring.
165  base::FilePath p(
166      base::FilePath::StringType(relative_path.begin(), relative_path.end()));
167  if (p.IsAbsolute())
168    return false;
169
170  base::FilePath inspector_dir;
171  if (!PathService::Get(chrome::DIR_INSPECTOR, &inspector_dir))
172    return false;
173
174  if (inspector_dir.empty())
175    return false;
176
177  *path = inspector_dir.AppendASCII(relative_path);
178  return true;
179}
180
181class DebugDevToolsInterceptor
182    : public net::URLRequestJobFactory::ProtocolHandler {
183 public:
184  DebugDevToolsInterceptor() {}
185  virtual ~DebugDevToolsInterceptor() {}
186
187  virtual net::URLRequestJob* MaybeCreateJob(
188      net::URLRequest* request,
189      net::NetworkDelegate* network_delegate) const OVERRIDE {
190    base::FilePath path;
191    if (IsSupportedDevToolsURL(request->url(), &path))
192      return new net::URLRequestFileJob(
193          request, network_delegate, path,
194          content::BrowserThread::GetBlockingPool()->
195              GetTaskRunnerWithShutdownBehavior(
196                  base::SequencedWorkerPool::SKIP_ON_SHUTDOWN));
197
198    return NULL;
199  }
200};
201#endif  // defined(DEBUG_DEVTOOLS)
202
203#if defined(OS_CHROMEOS)
204// The following four functions are responsible for initializing NSS for each
205// profile on ChromeOS, which has a separate NSS database and TPM slot
206// per-profile.
207//
208// Initialization basically follows these steps:
209// 1) Get some info from chromeos::UserManager about the User for this profile.
210// 2) Tell nss_util to initialize the software slot for this profile.
211// 3) Wait for the TPM module to be loaded by nss_util if it isn't already.
212// 4) Ask CryptohomeClient which TPM slot id corresponds to this profile.
213// 5) Tell nss_util to use that slot id on the TPM module.
214//
215// Some of these steps must happen on the UI thread, others must happen on the
216// IO thread:
217//               UI thread                              IO Thread
218//
219//  ProfileIOData::InitializeOnUIThread
220//                   |
221// chromeos::UserManager::GetUserByProfile
222//                   \---------------------------------------v
223//                                                 StartNSSInitOnIOThread
224//                                                           |
225//                                          crypto::InitializeNSSForChromeOSUser
226//                                                           |
227//                                                crypto::IsTPMTokenReady
228//                                                           |
229//                                          StartTPMSlotInitializationOnIOThread
230//                   v---------------------------------------/
231//     GetTPMInfoForUserOnUIThread
232//                   |
233// CryptohomeClient::Pkcs11GetTpmTokenInfoForUser
234//                   |
235//     DidGetTPMInfoForUserOnUIThread
236//                   \---------------------------------------v
237//                                          crypto::InitializeTPMForChromeOSUser
238
239void DidGetTPMInfoForUserOnUIThread(const std::string& username_hash,
240                                    chromeos::DBusMethodCallStatus call_status,
241                                    const std::string& label,
242                                    const std::string& user_pin,
243                                    int slot_id) {
244  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
245  if (call_status == chromeos::DBUS_METHOD_CALL_FAILURE) {
246    NOTREACHED() << "dbus error getting TPM info for " << username_hash;
247    return;
248  }
249  DVLOG(1) << "Got TPM slot for " << username_hash << ": " << slot_id;
250  BrowserThread::PostTask(
251      BrowserThread::IO,
252      FROM_HERE,
253      base::Bind(
254          &crypto::InitializeTPMForChromeOSUser, username_hash, slot_id));
255}
256
257void GetTPMInfoForUserOnUIThread(const std::string& username,
258                                 const std::string& username_hash) {
259  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
260  DVLOG(1) << "Getting TPM info from cryptohome for "
261           << " " << username << " " << username_hash;
262  chromeos::DBusThreadManager::Get()
263      ->GetCryptohomeClient()
264      ->Pkcs11GetTpmTokenInfoForUser(
265            username,
266            base::Bind(&DidGetTPMInfoForUserOnUIThread, username_hash));
267}
268
269void StartTPMSlotInitializationOnIOThread(const std::string& username,
270                                          const std::string& username_hash) {
271  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
272
273  BrowserThread::PostTask(
274      BrowserThread::UI,
275      FROM_HERE,
276      base::Bind(&GetTPMInfoForUserOnUIThread, username, username_hash));
277}
278
279void StartNSSInitOnIOThread(const std::string& username,
280                            const std::string& username_hash,
281                            const base::FilePath& path,
282                            bool is_primary_user) {
283  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
284  DVLOG(1) << "Starting NSS init for " << username
285           << "  hash:" << username_hash
286           << "  is_primary_user:" << is_primary_user;
287
288  if (!crypto::InitializeNSSForChromeOSUser(
289           username, username_hash, is_primary_user, path)) {
290    // If the user already exists in nss_util's map, it is already initialized
291    // or in the process of being initialized. In either case, there's no need
292    // to do anything.
293    return;
294  }
295
296  if (crypto::IsTPMTokenEnabledForNSS()) {
297    if (crypto::IsTPMTokenReady(base::Bind(
298            &StartTPMSlotInitializationOnIOThread, username, username_hash))) {
299      StartTPMSlotInitializationOnIOThread(username, username_hash);
300    } else {
301      DVLOG(1) << "Waiting for tpm ready ...";
302    }
303  } else {
304    crypto::InitializePrivateSoftwareSlotForChromeOSUser(username_hash);
305  }
306}
307#endif  // defined(OS_CHROMEOS)
308
309}  // namespace
310
311void ProfileIOData::InitializeOnUIThread(Profile* profile) {
312  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
313  PrefService* pref_service = profile->GetPrefs();
314  PrefService* local_state_pref_service = g_browser_process->local_state();
315
316  scoped_ptr<ProfileParams> params(new ProfileParams);
317  params->path = profile->GetPath();
318
319  params->io_thread = g_browser_process->io_thread();
320
321  params->cookie_settings = CookieSettings::Factory::GetForProfile(profile);
322  params->host_content_settings_map = profile->GetHostContentSettingsMap();
323  params->ssl_config_service = profile->GetSSLConfigService();
324  params->cookie_monster_delegate =
325      chrome_browser_net::CreateCookieDelegate(profile);
326  params->extension_info_map =
327      extensions::ExtensionSystem::Get(profile)->info_map();
328
329  ProtocolHandlerRegistry* protocol_handler_registry =
330      ProtocolHandlerRegistryFactory::GetForProfile(profile);
331  DCHECK(protocol_handler_registry);
332
333  // The profile instance is only available here in the InitializeOnUIThread
334  // method, so we create the url job factory here, then save it for
335  // later delivery to the job factory in Init().
336  params->protocol_handler_interceptor =
337      protocol_handler_registry->CreateJobInterceptorFactory();
338
339  params->proxy_config_service
340      .reset(ProxyServiceFactory::CreateProxyConfigService(
341           profile->GetProxyConfigTracker()));
342#if defined(ENABLE_MANAGED_USERS)
343  ManagedUserService* managed_user_service =
344      ManagedUserServiceFactory::GetForProfile(profile);
345  params->managed_mode_url_filter =
346      managed_user_service->GetURLFilterForIOThread();
347#endif
348#if defined(OS_CHROMEOS)
349  chromeos::UserManager* user_manager = chromeos::UserManager::Get();
350  if (user_manager) {
351    chromeos::User* user = user_manager->GetUserByProfile(profile);
352    if (user) {
353      params->username_hash = user->username_hash();
354      bool is_primary_user = (user_manager->GetPrimaryUser() == user);
355      BrowserThread::PostTask(BrowserThread::IO,
356                              FROM_HERE,
357                              base::Bind(&StartNSSInitOnIOThread,
358                                         user->email(),
359                                         user->username_hash(),
360                                         profile->GetPath(),
361                                         is_primary_user));
362    }
363  }
364  if (params->username_hash.empty())
365    LOG(WARNING) << "no username_hash";
366#endif
367
368  params->profile = profile;
369  profile_params_.reset(params.release());
370
371  ChromeNetworkDelegate::InitializePrefsOnUIThread(
372      &enable_referrers_,
373      &enable_do_not_track_,
374      &force_safesearch_,
375      pref_service);
376
377  scoped_refptr<base::MessageLoopProxy> io_message_loop_proxy =
378      BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
379#if defined(ENABLE_PRINTING)
380  printing_enabled_.Init(prefs::kPrintingEnabled, pref_service);
381  printing_enabled_.MoveToThread(io_message_loop_proxy);
382#endif
383
384  chrome_http_user_agent_settings_.reset(
385      new ChromeHttpUserAgentSettings(pref_service));
386
387  // These members are used only for one click sign in, which is not enabled
388  // in incognito mode.  So no need to initialize them.
389  if (!IsOffTheRecord()) {
390    signin_names_.reset(new SigninNamesOnIOThread());
391
392    google_services_user_account_id_.Init(
393        prefs::kGoogleServicesUserAccountId, pref_service);
394    google_services_user_account_id_.MoveToThread(io_message_loop_proxy);
395
396    google_services_username_.Init(
397        prefs::kGoogleServicesUsername, pref_service);
398    google_services_username_.MoveToThread(io_message_loop_proxy);
399
400    google_services_username_pattern_.Init(
401        prefs::kGoogleServicesUsernamePattern, local_state_pref_service);
402    google_services_username_pattern_.MoveToThread(io_message_loop_proxy);
403
404    reverse_autologin_enabled_.Init(
405        prefs::kReverseAutologinEnabled, pref_service);
406    reverse_autologin_enabled_.MoveToThread(io_message_loop_proxy);
407
408    one_click_signin_rejected_email_list_.Init(
409        prefs::kReverseAutologinRejectedEmailList, pref_service);
410    one_click_signin_rejected_email_list_.MoveToThread(io_message_loop_proxy);
411
412    sync_disabled_.Init(sync_driver::prefs::kSyncManaged, pref_service);
413    sync_disabled_.MoveToThread(io_message_loop_proxy);
414
415    signin_allowed_.Init(prefs::kSigninAllowed, pref_service);
416    signin_allowed_.MoveToThread(io_message_loop_proxy);
417  }
418
419  quick_check_enabled_.Init(prefs::kQuickCheckEnabled,
420                            local_state_pref_service);
421  quick_check_enabled_.MoveToThread(io_message_loop_proxy);
422
423  media_device_id_salt_ = new MediaDeviceIDSalt(pref_service, IsOffTheRecord());
424
425  network_prediction_enabled_.Init(prefs::kNetworkPredictionEnabled,
426                                   pref_service);
427  network_prediction_enabled_.MoveToThread(io_message_loop_proxy);
428
429#if defined(OS_CHROMEOS)
430  cert_verifier_ = policy::PolicyCertServiceFactory::CreateForProfile(profile);
431#endif
432  // The URLBlacklistManager has to be created on the UI thread to register
433  // observers of |pref_service|, and it also has to clean up on
434  // ShutdownOnUIThread to release these observers on the right thread.
435  // Don't pass it in |profile_params_| to make sure it is correctly cleaned up,
436  // in particular when this ProfileIOData isn't |initialized_| during deletion.
437#if defined(ENABLE_CONFIGURATION_POLICY)
438  policy::URLBlacklist::SegmentURLCallback callback =
439      static_cast<policy::URLBlacklist::SegmentURLCallback>(
440          URLFixerUpper::SegmentURL);
441  base::SequencedWorkerPool* pool = BrowserThread::GetBlockingPool();
442  scoped_refptr<base::SequencedTaskRunner> background_task_runner =
443      pool->GetSequencedTaskRunner(pool->GetSequenceToken());
444  url_blacklist_manager_.reset(
445      new policy::URLBlacklistManager(
446          pref_service,
447          background_task_runner,
448          io_message_loop_proxy,
449          callback,
450          base::Bind(policy::OverrideBlacklistForURL)));
451
452  if (!IsOffTheRecord()) {
453    // Add policy headers for non-incognito requests.
454    policy::PolicyHeaderService* policy_header_service =
455        policy::PolicyHeaderServiceFactory::GetForBrowserContext(profile);
456    if (policy_header_service) {
457      policy_header_helper_ = policy_header_service->CreatePolicyHeaderIOHelper(
458          io_message_loop_proxy);
459    }
460  }
461#endif
462
463  incognito_availibility_pref_.Init(
464      prefs::kIncognitoModeAvailability, pref_service);
465  incognito_availibility_pref_.MoveToThread(io_message_loop_proxy);
466
467  initialized_on_UI_thread_ = true;
468
469  // We need to make sure that content initializes its own data structures that
470  // are associated with each ResourceContext because we might post this
471  // object to the IO thread after this function.
472  BrowserContext::EnsureResourceContextInitialized(profile);
473}
474
475ProfileIOData::MediaRequestContext::MediaRequestContext() {
476}
477
478void ProfileIOData::MediaRequestContext::SetHttpTransactionFactory(
479    scoped_ptr<net::HttpTransactionFactory> http_factory) {
480  http_factory_ = http_factory.Pass();
481  set_http_transaction_factory(http_factory_.get());
482}
483
484ProfileIOData::MediaRequestContext::~MediaRequestContext() {}
485
486ProfileIOData::AppRequestContext::AppRequestContext() {
487}
488
489void ProfileIOData::AppRequestContext::SetCookieStore(
490    net::CookieStore* cookie_store) {
491  cookie_store_ = cookie_store;
492  set_cookie_store(cookie_store);
493}
494
495void ProfileIOData::AppRequestContext::SetHttpTransactionFactory(
496    scoped_ptr<net::HttpTransactionFactory> http_factory) {
497  http_factory_ = http_factory.Pass();
498  set_http_transaction_factory(http_factory_.get());
499}
500
501void ProfileIOData::AppRequestContext::SetJobFactory(
502    scoped_ptr<net::URLRequestJobFactory> job_factory) {
503  job_factory_ = job_factory.Pass();
504  set_job_factory(job_factory_.get());
505}
506
507ProfileIOData::AppRequestContext::~AppRequestContext() {}
508
509ProfileIOData::ProfileParams::ProfileParams()
510    : io_thread(NULL),
511      profile(NULL) {
512}
513
514ProfileIOData::ProfileParams::~ProfileParams() {}
515
516ProfileIOData::ProfileIOData(Profile::ProfileType profile_type)
517    : initialized_(false),
518      resource_context_(new ResourceContext(this)),
519      initialized_on_UI_thread_(false),
520      profile_type_(profile_type) {
521  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
522}
523
524ProfileIOData::~ProfileIOData() {
525  if (BrowserThread::IsMessageLoopValid(BrowserThread::IO))
526    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
527
528  // Pull the contents of the request context maps onto the stack for sanity
529  // checking of values in a minidump. http://crbug.com/260425
530  size_t num_app_contexts = app_request_context_map_.size();
531  size_t num_media_contexts = isolated_media_request_context_map_.size();
532  size_t current_context = 0;
533  static const size_t kMaxCachedContexts = 20;
534  ChromeURLRequestContext* app_context_cache[kMaxCachedContexts] = {0};
535  void* app_context_vtable_cache[kMaxCachedContexts] = {0};
536  ChromeURLRequestContext* media_context_cache[kMaxCachedContexts] = {0};
537  void* media_context_vtable_cache[kMaxCachedContexts] = {0};
538  void* tmp_vtable = NULL;
539  base::debug::Alias(&num_app_contexts);
540  base::debug::Alias(&num_media_contexts);
541  base::debug::Alias(&current_context);
542  base::debug::Alias(app_context_cache);
543  base::debug::Alias(app_context_vtable_cache);
544  base::debug::Alias(media_context_cache);
545  base::debug::Alias(media_context_vtable_cache);
546  base::debug::Alias(&tmp_vtable);
547
548  current_context = 0;
549  for (URLRequestContextMap::const_iterator it =
550           app_request_context_map_.begin();
551       current_context < kMaxCachedContexts &&
552           it != app_request_context_map_.end();
553       ++it, ++current_context) {
554    app_context_cache[current_context] = it->second;
555    memcpy(&app_context_vtable_cache[current_context],
556           static_cast<void*>(it->second), sizeof(void*));
557  }
558
559  current_context = 0;
560  for (URLRequestContextMap::const_iterator it =
561           isolated_media_request_context_map_.begin();
562       current_context < kMaxCachedContexts &&
563           it != isolated_media_request_context_map_.end();
564       ++it, ++current_context) {
565    media_context_cache[current_context] = it->second;
566    memcpy(&media_context_vtable_cache[current_context],
567           static_cast<void*>(it->second), sizeof(void*));
568  }
569
570  // TODO(ajwong): These AssertNoURLRequests() calls are unnecessary since they
571  // are already done in the URLRequestContext destructor.
572  if (main_request_context_)
573    main_request_context_->AssertNoURLRequests();
574  if (extensions_request_context_)
575    extensions_request_context_->AssertNoURLRequests();
576
577  current_context = 0;
578  for (URLRequestContextMap::iterator it = app_request_context_map_.begin();
579       it != app_request_context_map_.end(); ++it) {
580    if (current_context < kMaxCachedContexts) {
581      CHECK_EQ(app_context_cache[current_context], it->second);
582      memcpy(&tmp_vtable, static_cast<void*>(it->second), sizeof(void*));
583      CHECK_EQ(app_context_vtable_cache[current_context], tmp_vtable);
584    }
585    it->second->AssertNoURLRequests();
586    delete it->second;
587    current_context++;
588  }
589
590  current_context = 0;
591  for (URLRequestContextMap::iterator it =
592           isolated_media_request_context_map_.begin();
593       it != isolated_media_request_context_map_.end(); ++it) {
594    if (current_context < kMaxCachedContexts) {
595      CHECK_EQ(media_context_cache[current_context], it->second);
596      memcpy(&tmp_vtable, static_cast<void*>(it->second), sizeof(void*));
597      CHECK_EQ(media_context_vtable_cache[current_context], tmp_vtable);
598    }
599    it->second->AssertNoURLRequests();
600    delete it->second;
601    current_context++;
602  }
603}
604
605// static
606ProfileIOData* ProfileIOData::FromResourceContext(
607    content::ResourceContext* rc) {
608  return (static_cast<ResourceContext*>(rc))->io_data_;
609}
610
611// static
612bool ProfileIOData::IsHandledProtocol(const std::string& scheme) {
613  DCHECK_EQ(scheme, StringToLowerASCII(scheme));
614  static const char* const kProtocolList[] = {
615    content::kFileScheme,
616    content::kChromeDevToolsScheme,
617    chrome::kDomDistillerScheme,
618    extensions::kExtensionScheme,
619    extensions::kExtensionResourceScheme,
620    content::kChromeUIScheme,
621    content::kDataScheme,
622#if defined(OS_CHROMEOS)
623    chrome::kDriveScheme,
624#endif  // defined(OS_CHROMEOS)
625    content::kAboutScheme,
626#if !defined(DISABLE_FTP_SUPPORT)
627    content::kFtpScheme,
628#endif  // !defined(DISABLE_FTP_SUPPORT)
629    content::kBlobScheme,
630    content::kFileSystemScheme,
631    chrome::kChromeSearchScheme,
632  };
633  for (size_t i = 0; i < arraysize(kProtocolList); ++i) {
634    if (scheme == kProtocolList[i])
635      return true;
636  }
637  return net::URLRequest::IsHandledProtocol(scheme);
638}
639
640// static
641bool ProfileIOData::IsHandledURL(const GURL& url) {
642  if (!url.is_valid()) {
643    // We handle error cases.
644    return true;
645  }
646
647  return IsHandledProtocol(url.scheme());
648}
649
650// static
651void ProfileIOData::InstallProtocolHandlers(
652    net::URLRequestJobFactoryImpl* job_factory,
653    content::ProtocolHandlerMap* protocol_handlers) {
654  for (content::ProtocolHandlerMap::iterator it =
655           protocol_handlers->begin();
656       it != protocol_handlers->end();
657       ++it) {
658    bool set_protocol = job_factory->SetProtocolHandler(
659        it->first, it->second.release());
660    DCHECK(set_protocol);
661  }
662  protocol_handlers->clear();
663}
664
665content::ResourceContext* ProfileIOData::GetResourceContext() const {
666  return resource_context_.get();
667}
668
669ChromeURLRequestContext* ProfileIOData::GetMainRequestContext() const {
670  DCHECK(initialized_);
671  return main_request_context_.get();
672}
673
674ChromeURLRequestContext* ProfileIOData::GetMediaRequestContext() const {
675  DCHECK(initialized_);
676  ChromeURLRequestContext* context = AcquireMediaRequestContext();
677  DCHECK(context);
678  return context;
679}
680
681ChromeURLRequestContext* ProfileIOData::GetExtensionsRequestContext() const {
682  DCHECK(initialized_);
683  return extensions_request_context_.get();
684}
685
686ChromeURLRequestContext* ProfileIOData::GetIsolatedAppRequestContext(
687    ChromeURLRequestContext* main_context,
688    const StoragePartitionDescriptor& partition_descriptor,
689    scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
690        protocol_handler_interceptor,
691    content::ProtocolHandlerMap* protocol_handlers,
692    content::ProtocolHandlerScopedVector protocol_interceptors) const {
693  DCHECK(initialized_);
694  ChromeURLRequestContext* context = NULL;
695  if (ContainsKey(app_request_context_map_, partition_descriptor)) {
696    context = app_request_context_map_[partition_descriptor];
697  } else {
698    context =
699        AcquireIsolatedAppRequestContext(main_context,
700                                         partition_descriptor,
701                                         protocol_handler_interceptor.Pass(),
702                                         protocol_handlers,
703                                         protocol_interceptors.Pass());
704    app_request_context_map_[partition_descriptor] = context;
705  }
706  DCHECK(context);
707  return context;
708}
709
710ChromeURLRequestContext* ProfileIOData::GetIsolatedMediaRequestContext(
711    ChromeURLRequestContext* app_context,
712    const StoragePartitionDescriptor& partition_descriptor) const {
713  DCHECK(initialized_);
714  ChromeURLRequestContext* context = NULL;
715  if (ContainsKey(isolated_media_request_context_map_, partition_descriptor)) {
716    context = isolated_media_request_context_map_[partition_descriptor];
717  } else {
718    context = AcquireIsolatedMediaRequestContext(app_context,
719                                                 partition_descriptor);
720    isolated_media_request_context_map_[partition_descriptor] = context;
721  }
722  DCHECK(context);
723  return context;
724}
725
726extensions::InfoMap* ProfileIOData::GetExtensionInfoMap() const {
727  DCHECK(initialized_) << "ExtensionSystem not initialized";
728  return extension_info_map_.get();
729}
730
731CookieSettings* ProfileIOData::GetCookieSettings() const {
732  // Allow either Init() or SetCookieSettingsForTesting() to initialize.
733  DCHECK(initialized_ || cookie_settings_.get());
734  return cookie_settings_.get();
735}
736
737HostContentSettingsMap* ProfileIOData::GetHostContentSettingsMap() const {
738  DCHECK(initialized_);
739  return host_content_settings_map_.get();
740}
741
742ResourceContext::SaltCallback ProfileIOData::GetMediaDeviceIDSalt() const {
743  return base::Bind(&MediaDeviceIDSalt::GetSalt, media_device_id_salt_);
744}
745
746bool ProfileIOData::IsOffTheRecord() const {
747  return profile_type() == Profile::INCOGNITO_PROFILE
748      || profile_type() == Profile::GUEST_PROFILE;
749}
750
751void ProfileIOData::InitializeMetricsEnabledStateOnUIThread() {
752  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
753#if defined(OS_CHROMEOS)
754  // Just fetch the value from ChromeOS' settings while we're on the UI thread.
755  // TODO(stevet): For now, this value is only set on profile initialization.
756  // We will want to do something similar to the PrefMember method below in the
757  // future to more accurately capture this state.
758  chromeos::CrosSettings::Get()->GetBoolean(chromeos::kStatsReportingPref,
759                                            &enable_metrics_);
760#elif defined(OS_ANDROID)
761  // TODO(dwkang): rename or unify the pref for UMA once we have conclusion
762  // in crbugs.com/246495.
763  // Android has it's own preferences for metrics / crash uploading.
764  enable_metrics_.Init(prefs::kCrashReportingEnabled,
765                       g_browser_process->local_state());
766  enable_metrics_.MoveToThread(
767      BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
768#else
769  // Prep the PrefMember and send it to the IO thread, since this value will be
770  // read from there.
771  enable_metrics_.Init(prefs::kMetricsReportingEnabled,
772                       g_browser_process->local_state());
773  enable_metrics_.MoveToThread(
774      BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
775#endif  // defined(OS_CHROMEOS)
776}
777
778bool ProfileIOData::GetMetricsEnabledStateOnIOThread() const {
779  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
780#if defined(OS_CHROMEOS)
781  return enable_metrics_;
782#else
783  return enable_metrics_.GetValue();
784#endif  // defined(OS_CHROMEOS)
785}
786
787base::WeakPtr<net::HttpServerProperties>
788ProfileIOData::http_server_properties() const {
789  return http_server_properties_->GetWeakPtr();
790}
791
792void ProfileIOData::set_http_server_properties(
793    scoped_ptr<net::HttpServerProperties> http_server_properties) const {
794  http_server_properties_ = http_server_properties.Pass();
795}
796
797ProfileIOData::ResourceContext::ResourceContext(ProfileIOData* io_data)
798    : io_data_(io_data),
799      host_resolver_(NULL),
800      request_context_(NULL) {
801  DCHECK(io_data);
802}
803
804ProfileIOData::ResourceContext::~ResourceContext() {}
805
806net::HostResolver* ProfileIOData::ResourceContext::GetHostResolver()  {
807  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
808  DCHECK(io_data_->initialized_);
809  return host_resolver_;
810}
811
812net::URLRequestContext* ProfileIOData::ResourceContext::GetRequestContext()  {
813  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
814  DCHECK(io_data_->initialized_);
815  return request_context_;
816}
817
818scoped_ptr<net::ClientCertStore>
819ProfileIOData::ResourceContext::CreateClientCertStore() {
820  if (!io_data_->client_cert_store_factory_.is_null())
821    return io_data_->client_cert_store_factory_.Run();
822#if defined(OS_CHROMEOS)
823  return scoped_ptr<net::ClientCertStore>(new net::ClientCertStoreChromeOS(
824      io_data_->username_hash(),
825      base::Bind(&CreateCryptoModuleBlockingPasswordDelegate,
826                 chrome::kCryptoModulePasswordClientAuth)));
827#elif defined(USE_NSS)
828  return scoped_ptr<net::ClientCertStore>(new net::ClientCertStoreNSS(
829      base::Bind(&CreateCryptoModuleBlockingPasswordDelegate,
830                 chrome::kCryptoModulePasswordClientAuth)));
831#elif defined(OS_WIN)
832  return scoped_ptr<net::ClientCertStore>(new net::ClientCertStoreWin());
833#elif defined(OS_MACOSX)
834  return scoped_ptr<net::ClientCertStore>(new net::ClientCertStoreMac());
835#elif defined(USE_OPENSSL)
836  // OpenSSL does not use the ClientCertStore infrastructure. On Android client
837  // cert matching is done by the OS as part of the call to show the cert
838  // selection dialog.
839  return scoped_ptr<net::ClientCertStore>();
840#else
841#error Unknown platform.
842#endif
843}
844
845void ProfileIOData::ResourceContext::CreateKeygenHandler(
846    uint32 key_size_in_bits,
847    const std::string& challenge_string,
848    const GURL& url,
849    const base::Callback<void(scoped_ptr<net::KeygenHandler>)>& callback) {
850  DCHECK(!callback.is_null());
851#if defined(USE_NSS)
852  scoped_ptr<net::KeygenHandler> keygen_handler(
853      new net::KeygenHandler(key_size_in_bits, challenge_string, url));
854
855  scoped_ptr<ChromeNSSCryptoModuleDelegate> delegate(
856      new ChromeNSSCryptoModuleDelegate(chrome::kCryptoModulePasswordKeygen,
857                                        net::HostPortPair::FromURL(url)));
858  ChromeNSSCryptoModuleDelegate* delegate_ptr = delegate.get();
859  keygen_handler->set_crypto_module_delegate(
860      delegate.PassAs<crypto::NSSCryptoModuleDelegate>());
861
862  base::Closure bound_callback =
863      base::Bind(callback, base::Passed(&keygen_handler));
864  if (delegate_ptr->InitializeSlot(this, bound_callback)) {
865    // Initialization complete, run the callback synchronously.
866    bound_callback.Run();
867    return;
868  }
869  // Otherwise, the InitializeSlot will run the callback asynchronously.
870#else
871  callback.Run(make_scoped_ptr(
872      new net::KeygenHandler(key_size_in_bits, challenge_string, url)));
873#endif
874}
875
876bool ProfileIOData::ResourceContext::AllowMicAccess(const GURL& origin) {
877  return AllowContentAccess(origin, CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC);
878}
879
880bool ProfileIOData::ResourceContext::AllowCameraAccess(const GURL& origin) {
881  return AllowContentAccess(origin, CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA);
882}
883
884bool ProfileIOData::ResourceContext::AllowContentAccess(
885    const GURL& origin, ContentSettingsType type) {
886  HostContentSettingsMap* content_settings =
887      io_data_->GetHostContentSettingsMap();
888  ContentSetting setting = content_settings->GetContentSetting(
889      origin, origin, type, NO_RESOURCE_IDENTIFIER);
890  return setting == CONTENT_SETTING_ALLOW;
891}
892
893ResourceContext::SaltCallback
894ProfileIOData::ResourceContext::GetMediaDeviceIDSalt() {
895  return io_data_->GetMediaDeviceIDSalt();
896}
897
898// static
899std::string ProfileIOData::GetSSLSessionCacheShard() {
900  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
901  // The SSL session cache is partitioned by setting a string. This returns a
902  // unique string to partition the SSL session cache. Each time we create a
903  // new profile, we'll get a fresh SSL session cache which is separate from
904  // the other profiles.
905  static unsigned ssl_session_cache_instance = 0;
906  return base::StringPrintf("profile/%u", ssl_session_cache_instance++);
907}
908
909void ProfileIOData::Init(
910    content::ProtocolHandlerMap* protocol_handlers,
911    content::ProtocolHandlerScopedVector protocol_interceptors) const {
912  // The basic logic is implemented here. The specific initialization
913  // is done in InitializeInternal(), implemented by subtypes. Static helper
914  // functions have been provided to assist in common operations.
915  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
916  DCHECK(!initialized_);
917
918  startup_metric_utils::ScopedSlowStartupUMA
919      scoped_timer("Startup.SlowStartupProfileIODataInit");
920
921  // TODO(jhawkins): Remove once crbug.com/102004 is fixed.
922  CHECK(initialized_on_UI_thread_);
923
924  // TODO(jhawkins): Return to DCHECK once crbug.com/102004 is fixed.
925  CHECK(profile_params_.get());
926
927  IOThread* const io_thread = profile_params_->io_thread;
928  IOThread::Globals* const io_thread_globals = io_thread->globals();
929  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
930
931  // Create the common request contexts.
932  main_request_context_.reset(new ChromeURLRequestContext());
933  extensions_request_context_.reset(new ChromeURLRequestContext());
934
935  ChromeNetworkDelegate* network_delegate =
936      new ChromeNetworkDelegate(
937          io_thread_globals->extension_event_router_forwarder.get(),
938          &enable_referrers_);
939  if (command_line.HasSwitch(switches::kEnableClientHints))
940    network_delegate->SetEnableClientHints();
941  network_delegate->set_extension_info_map(
942      profile_params_->extension_info_map.get());
943#if defined(ENABLE_CONFIGURATION_POLICY)
944  network_delegate->set_url_blacklist_manager(url_blacklist_manager_.get());
945#endif
946  network_delegate->set_profile(profile_params_->profile);
947  network_delegate->set_profile_path(profile_params_->path);
948  network_delegate->set_cookie_settings(profile_params_->cookie_settings.get());
949  network_delegate->set_enable_do_not_track(&enable_do_not_track_);
950  network_delegate->set_force_google_safe_search(&force_safesearch_);
951  network_delegate_.reset(network_delegate);
952
953  fraudulent_certificate_reporter_.reset(
954      new chrome_browser_net::ChromeFraudulentCertificateReporter(
955          main_request_context_.get()));
956
957  // NOTE: Proxy service uses the default io thread network delegate, not the
958  // delegate just created.
959  proxy_service_.reset(
960      ProxyServiceFactory::CreateProxyService(
961          io_thread->net_log(),
962          io_thread_globals->proxy_script_fetcher_context.get(),
963          io_thread_globals->system_network_delegate.get(),
964          profile_params_->proxy_config_service.release(),
965          command_line,
966          quick_check_enabled_.GetValue()));
967
968  transport_security_state_.reset(new net::TransportSecurityState());
969  transport_security_persister_.reset(
970      new net::TransportSecurityPersister(
971          transport_security_state_.get(),
972          profile_params_->path,
973          BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE),
974          IsOffTheRecord()));
975
976  // Take ownership over these parameters.
977  cookie_settings_ = profile_params_->cookie_settings;
978  host_content_settings_map_ = profile_params_->host_content_settings_map;
979  extension_info_map_ = profile_params_->extension_info_map;
980
981  resource_context_->host_resolver_ = io_thread_globals->host_resolver.get();
982  resource_context_->request_context_ = main_request_context_.get();
983
984#if defined(ENABLE_MANAGED_USERS)
985  managed_mode_url_filter_ = profile_params_->managed_mode_url_filter;
986#endif
987
988#if defined(OS_CHROMEOS)
989  username_hash_ = profile_params_->username_hash;
990  scoped_refptr<net::CertVerifyProc> verify_proc;
991  if (chromeos::UserManager::IsMultipleProfilesAllowed()) {
992    crypto::ScopedPK11Slot public_slot =
993        crypto::GetPublicSlotForChromeOSUser(username_hash_);
994    // The private slot won't be ready by this point. It shouldn't be necessary
995    // for cert trust purposes anyway.
996    verify_proc = new chromeos::CertVerifyProcChromeOS(public_slot.Pass());
997  } else {
998    verify_proc = net::CertVerifyProc::CreateDefault();
999  }
1000  if (cert_verifier_) {
1001    cert_verifier_->InitializeOnIOThread(verify_proc);
1002    main_request_context_->set_cert_verifier(cert_verifier_.get());
1003  } else {
1004    main_request_context_->set_cert_verifier(
1005        new net::MultiThreadedCertVerifier(verify_proc.get()));
1006  }
1007#else
1008  main_request_context_->set_cert_verifier(
1009      io_thread_globals->cert_verifier.get());
1010#endif
1011
1012  InitializeInternal(
1013      profile_params_.get(), protocol_handlers, protocol_interceptors.Pass());
1014
1015  profile_params_.reset();
1016  initialized_ = true;
1017}
1018
1019void ProfileIOData::ApplyProfileParamsToContext(
1020    ChromeURLRequestContext* context) const {
1021  context->set_http_user_agent_settings(
1022      chrome_http_user_agent_settings_.get());
1023  context->set_ssl_config_service(profile_params_->ssl_config_service.get());
1024}
1025
1026scoped_ptr<net::URLRequestJobFactory> ProfileIOData::SetUpJobFactoryDefaults(
1027    scoped_ptr<net::URLRequestJobFactoryImpl> job_factory,
1028    content::ProtocolHandlerScopedVector protocol_interceptors,
1029    scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
1030        protocol_handler_interceptor,
1031    net::NetworkDelegate* network_delegate,
1032    net::FtpTransactionFactory* ftp_transaction_factory) const {
1033  // NOTE(willchan): Keep these protocol handlers in sync with
1034  // ProfileIOData::IsHandledProtocol().
1035  bool set_protocol = job_factory->SetProtocolHandler(
1036      content::kFileScheme,
1037      new net::FileProtocolHandler(
1038          content::BrowserThread::GetBlockingPool()->
1039              GetTaskRunnerWithShutdownBehavior(
1040                  base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)));
1041  DCHECK(set_protocol);
1042
1043  DCHECK(extension_info_map_.get());
1044  // Check only for incognito (and not Chrome OS guest mode GUEST_PROFILE).
1045  bool is_incognito = profile_type() == Profile::INCOGNITO_PROFILE;
1046  set_protocol = job_factory->SetProtocolHandler(
1047      extensions::kExtensionScheme,
1048      extensions::CreateExtensionProtocolHandler(is_incognito,
1049                                                 extension_info_map_.get()));
1050  DCHECK(set_protocol);
1051  set_protocol = job_factory->SetProtocolHandler(
1052      extensions::kExtensionResourceScheme,
1053      CreateExtensionResourceProtocolHandler());
1054  DCHECK(set_protocol);
1055  set_protocol = job_factory->SetProtocolHandler(
1056      content::kDataScheme, new net::DataProtocolHandler());
1057  DCHECK(set_protocol);
1058#if defined(OS_CHROMEOS)
1059  if (!IsOffTheRecord() && profile_params_) {
1060    set_protocol = job_factory->SetProtocolHandler(
1061        chrome::kDriveScheme,
1062        new drive::DriveProtocolHandler(profile_params_->profile));
1063    DCHECK(set_protocol);
1064  }
1065#endif  // defined(OS_CHROMEOS)
1066
1067  job_factory->SetProtocolHandler(
1068      content::kAboutScheme, new chrome_browser_net::AboutProtocolHandler());
1069#if !defined(DISABLE_FTP_SUPPORT)
1070  DCHECK(ftp_transaction_factory);
1071  job_factory->SetProtocolHandler(
1072      content::kFtpScheme,
1073      new net::FtpProtocolHandler(ftp_transaction_factory));
1074#endif  // !defined(DISABLE_FTP_SUPPORT)
1075
1076#if defined(DEBUG_DEVTOOLS)
1077  protocol_interceptors.push_back(new DebugDevToolsInterceptor);
1078#endif
1079
1080  // Set up interceptors in the reverse order.
1081  scoped_ptr<net::URLRequestJobFactory> top_job_factory =
1082      job_factory.PassAs<net::URLRequestJobFactory>();
1083  for (content::ProtocolHandlerScopedVector::reverse_iterator i =
1084           protocol_interceptors.rbegin();
1085       i != protocol_interceptors.rend();
1086       ++i) {
1087    top_job_factory.reset(new net::ProtocolInterceptJobFactory(
1088        top_job_factory.Pass(), make_scoped_ptr(*i)));
1089  }
1090  protocol_interceptors.weak_clear();
1091
1092  if (protocol_handler_interceptor) {
1093    protocol_handler_interceptor->Chain(top_job_factory.Pass());
1094    return protocol_handler_interceptor.PassAs<net::URLRequestJobFactory>();
1095  } else {
1096    return top_job_factory.Pass();
1097  }
1098}
1099
1100void ProfileIOData::ShutdownOnUIThread() {
1101  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1102
1103  if (signin_names_)
1104    signin_names_->ReleaseResourcesOnUIThread();
1105
1106  google_services_user_account_id_.Destroy();
1107  google_services_username_.Destroy();
1108  google_services_username_pattern_.Destroy();
1109  reverse_autologin_enabled_.Destroy();
1110  one_click_signin_rejected_email_list_.Destroy();
1111  enable_referrers_.Destroy();
1112  enable_do_not_track_.Destroy();
1113  force_safesearch_.Destroy();
1114#if !defined(OS_CHROMEOS)
1115  enable_metrics_.Destroy();
1116#endif
1117  safe_browsing_enabled_.Destroy();
1118  printing_enabled_.Destroy();
1119  sync_disabled_.Destroy();
1120  signin_allowed_.Destroy();
1121  network_prediction_enabled_.Destroy();
1122  quick_check_enabled_.Destroy();
1123  if (media_device_id_salt_)
1124    media_device_id_salt_->ShutdownOnUIThread();
1125  session_startup_pref_.Destroy();
1126#if defined(ENABLE_CONFIGURATION_POLICY)
1127  if (url_blacklist_manager_)
1128    url_blacklist_manager_->ShutdownOnUIThread();
1129#endif
1130  if (chrome_http_user_agent_settings_)
1131    chrome_http_user_agent_settings_->CleanupOnUIThread();
1132  incognito_availibility_pref_.Destroy();
1133  bool posted = BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, this);
1134  if (!posted)
1135    delete this;
1136}
1137
1138void ProfileIOData::set_server_bound_cert_service(
1139    net::ServerBoundCertService* server_bound_cert_service) const {
1140  server_bound_cert_service_.reset(server_bound_cert_service);
1141}
1142
1143void ProfileIOData::DestroyResourceContext() {
1144  resource_context_.reset();
1145}
1146
1147void ProfileIOData::PopulateNetworkSessionParams(
1148    const ProfileParams* profile_params,
1149    net::HttpNetworkSession::Params* params) const {
1150
1151  ChromeURLRequestContext* context = main_request_context();
1152
1153  IOThread* const io_thread = profile_params->io_thread;
1154
1155  io_thread->InitializeNetworkSessionParams(params);
1156
1157  params->host_resolver = context->host_resolver();
1158  params->cert_verifier = context->cert_verifier();
1159  params->server_bound_cert_service = context->server_bound_cert_service();
1160  params->transport_security_state = context->transport_security_state();
1161  params->cert_transparency_verifier = context->cert_transparency_verifier();
1162  params->proxy_service = context->proxy_service();
1163  params->ssl_session_cache_shard = GetSSLSessionCacheShard();
1164  params->ssl_config_service = context->ssl_config_service();
1165  params->http_auth_handler_factory = context->http_auth_handler_factory();
1166  params->network_delegate = network_delegate();
1167  params->http_server_properties = context->http_server_properties();
1168  params->net_log = context->net_log();
1169}
1170
1171void ProfileIOData::SetCookieSettingsForTesting(
1172    CookieSettings* cookie_settings) {
1173  DCHECK(!cookie_settings_.get());
1174  cookie_settings_ = cookie_settings;
1175}
1176
1177void ProfileIOData::set_signin_names_for_testing(
1178    SigninNamesOnIOThread* signin_names) {
1179  signin_names_.reset(signin_names);
1180}
1181