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