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