ExtensionSyncService cleanup: process uninstalls in one step
[chromium-blink-merge.git] / chrome / browser / io_thread.cc
blob43eb98bc37d1adc677b525b7ddc2698acf059258
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.
5 #include "chrome/browser/io_thread.h"
7 #include <vector>
9 #include "base/base64.h"
10 #include "base/bind.h"
11 #include "base/bind_helpers.h"
12 #include "base/command_line.h"
13 #include "base/compiler_specific.h"
14 #include "base/debug/leak_tracker.h"
15 #include "base/logging.h"
16 #include "base/metrics/field_trial.h"
17 #include "base/prefs/pref_registry_simple.h"
18 #include "base/prefs/pref_service.h"
19 #include "base/profiler/scoped_tracker.h"
20 #include "base/stl_util.h"
21 #include "base/strings/string_number_conversions.h"
22 #include "base/strings/string_piece.h"
23 #include "base/strings/string_split.h"
24 #include "base/strings/string_util.h"
25 #include "base/threading/sequenced_worker_pool.h"
26 #include "base/threading/thread.h"
27 #include "base/threading/worker_pool.h"
28 #include "base/time/time.h"
29 #include "base/trace_event/trace_event.h"
30 #include "build/build_config.h"
31 #include "chrome/browser/browser_process.h"
32 #include "chrome/browser/net/async_dns_field_trial.h"
33 #include "chrome/browser/net/chrome_net_log.h"
34 #include "chrome/browser/net/chrome_network_delegate.h"
35 #include "chrome/browser/net/connect_interceptor.h"
36 #include "chrome/browser/net/dns_probe_service.h"
37 #include "chrome/browser/net/pref_proxy_config_tracker.h"
38 #include "chrome/browser/net/proxy_service_factory.h"
39 #include "chrome/common/chrome_content_client.h"
40 #include "chrome/common/chrome_switches.h"
41 #include "chrome/common/chrome_version_info.h"
42 #include "chrome/common/pref_names.h"
43 #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_prefs.h"
44 #include "components/data_reduction_proxy/core/common/data_reduction_proxy_params.h"
45 #include "components/policy/core/common/policy_service.h"
46 #include "components/variations/variations_associated_data.h"
47 #include "content/public/browser/browser_thread.h"
48 #include "content/public/browser/cookie_store_factory.h"
49 #include "content/public/common/user_agent.h"
50 #include "net/base/host_mapping_rules.h"
51 #include "net/base/net_util.h"
52 #include "net/base/network_quality_estimator.h"
53 #include "net/base/sdch_manager.h"
54 #include "net/cert/cert_policy_enforcer.h"
55 #include "net/cert/cert_verifier.h"
56 #include "net/cert/cert_verify_proc.h"
57 #include "net/cert/ct_known_logs.h"
58 #include "net/cert/ct_known_logs_static.h"
59 #include "net/cert/ct_log_verifier.h"
60 #include "net/cert/ct_verifier.h"
61 #include "net/cert/multi_log_ct_verifier.h"
62 #include "net/cert/multi_threaded_cert_verifier.h"
63 #include "net/cookies/cookie_store.h"
64 #include "net/dns/host_cache.h"
65 #include "net/dns/host_resolver.h"
66 #include "net/dns/mapped_host_resolver.h"
67 #include "net/ftp/ftp_network_layer.h"
68 #include "net/http/http_auth_filter.h"
69 #include "net/http/http_auth_handler_factory.h"
70 #include "net/http/http_network_layer.h"
71 #include "net/http/http_server_properties_impl.h"
72 #include "net/proxy/proxy_config_service.h"
73 #include "net/proxy/proxy_script_fetcher_impl.h"
74 #include "net/proxy/proxy_service.h"
75 #include "net/quic/crypto/crypto_protocol.h"
76 #include "net/quic/quic_protocol.h"
77 #include "net/quic/quic_utils.h"
78 #include "net/socket/tcp_client_socket.h"
79 #include "net/spdy/spdy_session.h"
80 #include "net/ssl/channel_id_service.h"
81 #include "net/ssl/default_channel_id_store.h"
82 #include "net/url_request/data_protocol_handler.h"
83 #include "net/url_request/file_protocol_handler.h"
84 #include "net/url_request/ftp_protocol_handler.h"
85 #include "net/url_request/static_http_user_agent_settings.h"
86 #include "net/url_request/url_fetcher.h"
87 #include "net/url_request/url_request_context.h"
88 #include "net/url_request/url_request_context_getter.h"
89 #include "net/url_request/url_request_job_factory_impl.h"
90 #include "url/url_constants.h"
92 #if defined(ENABLE_CONFIGURATION_POLICY)
93 #include "policy/policy_constants.h"
94 #endif
96 #if defined(ENABLE_EXTENSIONS)
97 #include "chrome/browser/extensions/event_router_forwarder.h"
98 #endif
100 #if defined(USE_NSS_CERTS) || defined(OS_IOS)
101 #include "net/cert_net/nss_ocsp.h"
102 #endif
104 #if defined(OS_ANDROID)
105 #include "base/android/build_info.h"
106 #endif
108 #if defined(OS_CHROMEOS)
109 #include "chrome/browser/chromeos/net/cert_verify_proc_chromeos.h"
110 #include "chromeos/network/host_resolver_impl_chromeos.h"
111 #endif
113 using content::BrowserThread;
115 class SafeBrowsingURLRequestContext;
117 // The IOThread object must outlive any tasks posted to the IO thread before the
118 // Quit task, so base::Bind() calls are not refcounted.
120 namespace {
122 const char kTCPFastOpenFieldTrialName[] = "TCPFastOpen";
123 const char kTCPFastOpenHttpsEnabledGroupName[] = "HttpsEnabled";
125 const char kQuicFieldTrialName[] = "QUIC";
126 const char kQuicFieldTrialEnabledGroupName[] = "Enabled";
127 const char kQuicFieldTrialHttpsEnabledGroupName[] = "HttpsEnabled";
129 // The SPDY trial composes two different trial plus control groups:
130 // * A "holdback" group with SPDY disabled, and corresponding control
131 // (SPDY/3.1). The primary purpose of the holdback group is to encourage site
132 // operators to do feature detection rather than UA-sniffing. As such, this
133 // trial runs continuously.
134 // * A SPDY/4 experiment, for SPDY/4 (aka HTTP/2) vs SPDY/3.1 comparisons and
135 // eventual SPDY/4 deployment.
136 const char kSpdyFieldTrialName[] = "SPDY";
137 const char kSpdyFieldTrialHoldbackGroupNamePrefix[] = "SpdyDisabled";
138 const char kSpdyFieldTrialSpdy31GroupNamePrefix[] = "Spdy31Enabled";
139 const char kSpdyFieldTrialSpdy4GroupNamePrefix[] = "Spdy4Enabled";
140 const char kSpdyFieldTrialParametrizedPrefix[] = "Parametrized";
142 // Field trial for network quality estimator. Seeds RTT and downstream
143 // throughput observations with values that correspond to the connection type
144 // determined by the operating system.
145 const char kNetworkQualityEstimatorFieldTrialName[] = "NetworkQualityEstimator";
147 #if defined(OS_MACOSX) && !defined(OS_IOS)
148 void ObserveKeychainEvents() {
149 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
150 net::CertDatabase::GetInstance()->SetMessageLoopForKeychainEvents();
152 #endif
154 // Used for the "system" URLRequestContext.
155 class SystemURLRequestContext : public net::URLRequestContext {
156 public:
157 SystemURLRequestContext() {
158 #if defined(USE_NSS_CERTS) || defined(OS_IOS)
159 net::SetURLRequestContextForNSSHttpIO(this);
160 #endif
163 private:
164 ~SystemURLRequestContext() override {
165 AssertNoURLRequests();
166 #if defined(USE_NSS_CERTS) || defined(OS_IOS)
167 net::SetURLRequestContextForNSSHttpIO(NULL);
168 #endif
172 scoped_ptr<net::HostResolver> CreateGlobalHostResolver(net::NetLog* net_log) {
173 TRACE_EVENT0("startup", "IOThread::CreateGlobalHostResolver");
174 const base::CommandLine& command_line =
175 *base::CommandLine::ForCurrentProcess();
177 net::HostResolver::Options options;
179 // Use the retry attempts override from the command-line, if any.
180 if (command_line.HasSwitch(switches::kHostResolverRetryAttempts)) {
181 std::string s =
182 command_line.GetSwitchValueASCII(switches::kHostResolverRetryAttempts);
183 // Parse the switch (it should be a non-negative integer).
184 int n;
185 if (base::StringToInt(s, &n) && n >= 0) {
186 options.max_retry_attempts = static_cast<size_t>(n);
187 } else {
188 LOG(ERROR) << "Invalid switch for host resolver retry attempts: " << s;
192 scoped_ptr<net::HostResolver> global_host_resolver;
193 #if defined OS_CHROMEOS
194 global_host_resolver =
195 chromeos::HostResolverImplChromeOS::CreateSystemResolver(options,
196 net_log);
197 #else
198 global_host_resolver =
199 net::HostResolver::CreateSystemResolver(options, net_log);
200 #endif
202 // If hostname remappings were specified on the command-line, layer these
203 // rules on top of the real host resolver. This allows forwarding all requests
204 // through a designated test server.
205 if (!command_line.HasSwitch(switches::kHostResolverRules))
206 return global_host_resolver.Pass();
208 scoped_ptr<net::MappedHostResolver> remapped_resolver(
209 new net::MappedHostResolver(global_host_resolver.Pass()));
210 remapped_resolver->SetRulesFromString(
211 command_line.GetSwitchValueASCII(switches::kHostResolverRules));
212 return remapped_resolver.Pass();
215 // TODO(willchan): Remove proxy script fetcher context since it's not necessary
216 // now that I got rid of refcounting URLRequestContexts.
217 // See IOThread::Globals for details.
218 net::URLRequestContext*
219 ConstructProxyScriptFetcherContext(IOThread::Globals* globals,
220 net::NetLog* net_log) {
221 net::URLRequestContext* context = new net::URLRequestContext;
222 context->set_net_log(net_log);
223 context->set_host_resolver(globals->host_resolver.get());
224 context->set_cert_verifier(globals->cert_verifier.get());
225 context->set_transport_security_state(
226 globals->transport_security_state.get());
227 context->set_cert_transparency_verifier(
228 globals->cert_transparency_verifier.get());
229 context->set_http_auth_handler_factory(
230 globals->http_auth_handler_factory.get());
231 context->set_proxy_service(globals->proxy_script_fetcher_proxy_service.get());
232 context->set_http_transaction_factory(
233 globals->proxy_script_fetcher_http_transaction_factory.get());
234 context->set_job_factory(
235 globals->proxy_script_fetcher_url_request_job_factory.get());
236 context->set_cookie_store(globals->system_cookie_store.get());
237 context->set_channel_id_service(
238 globals->system_channel_id_service.get());
239 context->set_network_delegate(globals->system_network_delegate.get());
240 context->set_http_user_agent_settings(
241 globals->http_user_agent_settings.get());
242 // TODO(rtenneti): We should probably use HttpServerPropertiesManager for the
243 // system URLRequestContext too. There's no reason this should be tied to a
244 // profile.
245 return context;
248 net::URLRequestContext*
249 ConstructSystemRequestContext(IOThread::Globals* globals,
250 net::NetLog* net_log) {
251 net::URLRequestContext* context = new SystemURLRequestContext;
252 context->set_net_log(net_log);
253 context->set_host_resolver(globals->host_resolver.get());
254 context->set_cert_verifier(globals->cert_verifier.get());
255 context->set_transport_security_state(
256 globals->transport_security_state.get());
257 context->set_cert_transparency_verifier(
258 globals->cert_transparency_verifier.get());
259 context->set_http_auth_handler_factory(
260 globals->http_auth_handler_factory.get());
261 context->set_proxy_service(globals->system_proxy_service.get());
262 context->set_http_transaction_factory(
263 globals->system_http_transaction_factory.get());
264 context->set_job_factory(globals->system_url_request_job_factory.get());
265 context->set_cookie_store(globals->system_cookie_store.get());
266 context->set_channel_id_service(
267 globals->system_channel_id_service.get());
268 context->set_network_delegate(globals->system_network_delegate.get());
269 context->set_http_user_agent_settings(
270 globals->http_user_agent_settings.get());
271 context->set_network_quality_estimator(
272 globals->network_quality_estimator.get());
273 return context;
276 int GetSwitchValueAsInt(const base::CommandLine& command_line,
277 const std::string& switch_name) {
278 int value;
279 if (!base::StringToInt(command_line.GetSwitchValueASCII(switch_name),
280 &value)) {
281 return 0;
283 return value;
286 // Returns the value associated with |key| in |params| or "" if the
287 // key is not present in the map.
288 const std::string& GetVariationParam(
289 const std::map<std::string, std::string>& params,
290 const std::string& key) {
291 std::map<std::string, std::string>::const_iterator it = params.find(key);
292 if (it == params.end())
293 return base::EmptyString();
295 return it->second;
298 // Parse kUseSpdy command line flag options, which may contain the following:
300 // "off" : Disables SPDY support entirely.
301 // "no-ping" : Disables SPDY ping connection testing.
302 // "exclude=<host>" : Disables SPDY support for the host <host>.
303 // "no-compress" : Disables SPDY header compression.
304 // "no-alt-protocols : Disables alternate protocol support.
305 // "init-max-streams=<limit>" : Specifies the maximum number of concurrent
306 // streams for a SPDY session, unless the
307 // specifies a different value via SETTINGS.
308 void ConfigureSpdyGlobalsFromUseSpdyArgument(const std::string& mode,
309 IOThread::Globals* globals) {
310 static const char kOff[] = "off";
311 static const char kDisablePing[] = "no-ping";
312 static const char kExclude[] = "exclude"; // Hosts to exclude
313 static const char kDisableCompression[] = "no-compress";
314 static const char kDisableAltProtocols[] = "no-alt-protocols";
315 static const char kInitialMaxConcurrentStreams[] = "init-max-streams";
317 std::vector<std::string> spdy_options;
318 base::SplitString(mode, ',', &spdy_options);
320 for (const std::string& element : spdy_options) {
321 std::vector<std::string> name_value;
322 base::SplitString(element, '=', &name_value);
323 const std::string& option =
324 name_value.size() > 0 ? name_value[0] : std::string();
325 const std::string value =
326 name_value.size() > 1 ? name_value[1] : std::string();
328 if (option == kOff) {
329 net::HttpStreamFactory::set_spdy_enabled(false);
330 continue;
332 if (option == kDisablePing) {
333 globals->enable_spdy_ping_based_connection_checking.set(false);
334 continue;
336 if (option == kExclude) {
337 globals->forced_spdy_exclusions.insert(
338 net::HostPortPair::FromURL(GURL(value)));
339 continue;
341 if (option == kDisableCompression) {
342 globals->enable_spdy_compression.set(false);
343 continue;
345 if (option == kDisableAltProtocols) {
346 globals->use_alternate_protocols.set(false);
347 continue;
349 if (option == kInitialMaxConcurrentStreams) {
350 int streams;
351 if (base::StringToInt(value, &streams)) {
352 globals->initial_max_spdy_concurrent_streams.set(streams);
353 continue;
356 LOG(DFATAL) << "Unrecognized spdy option: " << option;
360 } // namespace
362 class IOThread::LoggingNetworkChangeObserver
363 : public net::NetworkChangeNotifier::IPAddressObserver,
364 public net::NetworkChangeNotifier::ConnectionTypeObserver,
365 public net::NetworkChangeNotifier::NetworkChangeObserver {
366 public:
367 // |net_log| must remain valid throughout our lifetime.
368 explicit LoggingNetworkChangeObserver(net::NetLog* net_log)
369 : net_log_(net_log) {
370 net::NetworkChangeNotifier::AddIPAddressObserver(this);
371 net::NetworkChangeNotifier::AddConnectionTypeObserver(this);
372 net::NetworkChangeNotifier::AddNetworkChangeObserver(this);
375 ~LoggingNetworkChangeObserver() override {
376 net::NetworkChangeNotifier::RemoveIPAddressObserver(this);
377 net::NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
378 net::NetworkChangeNotifier::RemoveNetworkChangeObserver(this);
381 // NetworkChangeNotifier::IPAddressObserver implementation.
382 void OnIPAddressChanged() override {
383 VLOG(1) << "Observed a change to the network IP addresses";
385 net_log_->AddGlobalEntry(net::NetLog::TYPE_NETWORK_IP_ADDRESSES_CHANGED);
388 // NetworkChangeNotifier::ConnectionTypeObserver implementation.
389 void OnConnectionTypeChanged(
390 net::NetworkChangeNotifier::ConnectionType type) override {
391 std::string type_as_string =
392 net::NetworkChangeNotifier::ConnectionTypeToString(type);
394 VLOG(1) << "Observed a change to network connectivity state "
395 << type_as_string;
397 net_log_->AddGlobalEntry(
398 net::NetLog::TYPE_NETWORK_CONNECTIVITY_CHANGED,
399 net::NetLog::StringCallback("new_connection_type", &type_as_string));
402 // NetworkChangeNotifier::NetworkChangeObserver implementation.
403 void OnNetworkChanged(
404 net::NetworkChangeNotifier::ConnectionType type) override {
405 std::string type_as_string =
406 net::NetworkChangeNotifier::ConnectionTypeToString(type);
408 VLOG(1) << "Observed a network change to state " << type_as_string;
410 net_log_->AddGlobalEntry(
411 net::NetLog::TYPE_NETWORK_CHANGED,
412 net::NetLog::StringCallback("new_connection_type", &type_as_string));
415 private:
416 net::NetLog* net_log_;
417 DISALLOW_COPY_AND_ASSIGN(LoggingNetworkChangeObserver);
420 class SystemURLRequestContextGetter : public net::URLRequestContextGetter {
421 public:
422 explicit SystemURLRequestContextGetter(IOThread* io_thread);
424 // Implementation for net::UrlRequestContextGetter.
425 net::URLRequestContext* GetURLRequestContext() override;
426 scoped_refptr<base::SingleThreadTaskRunner> GetNetworkTaskRunner()
427 const override;
429 protected:
430 ~SystemURLRequestContextGetter() override;
432 private:
433 IOThread* const io_thread_; // Weak pointer, owned by BrowserProcess.
434 scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_;
436 base::debug::LeakTracker<SystemURLRequestContextGetter> leak_tracker_;
439 SystemURLRequestContextGetter::SystemURLRequestContextGetter(
440 IOThread* io_thread)
441 : io_thread_(io_thread),
442 network_task_runner_(
443 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)) {
446 SystemURLRequestContextGetter::~SystemURLRequestContextGetter() {}
448 net::URLRequestContext* SystemURLRequestContextGetter::GetURLRequestContext() {
449 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
450 DCHECK(io_thread_->globals()->system_request_context.get());
452 return io_thread_->globals()->system_request_context.get();
455 scoped_refptr<base::SingleThreadTaskRunner>
456 SystemURLRequestContextGetter::GetNetworkTaskRunner() const {
457 return network_task_runner_;
460 IOThread::Globals::
461 SystemRequestContextLeakChecker::SystemRequestContextLeakChecker(
462 Globals* globals)
463 : globals_(globals) {
464 DCHECK(globals_);
467 IOThread::Globals::
468 SystemRequestContextLeakChecker::~SystemRequestContextLeakChecker() {
469 if (globals_->system_request_context.get())
470 globals_->system_request_context->AssertNoURLRequests();
473 IOThread::Globals::Globals()
474 : system_request_context_leak_checker(this),
475 ignore_certificate_errors(false),
476 testing_fixed_http_port(0),
477 testing_fixed_https_port(0),
478 enable_user_alternate_protocol_ports(false) {
481 IOThread::Globals::~Globals() {}
483 // |local_state| is passed in explicitly in order to (1) reduce implicit
484 // dependencies and (2) make IOThread more flexible for testing.
485 IOThread::IOThread(
486 PrefService* local_state,
487 policy::PolicyService* policy_service,
488 ChromeNetLog* net_log,
489 extensions::EventRouterForwarder* extension_event_router_forwarder)
490 : net_log_(net_log),
491 #if defined(ENABLE_EXTENSIONS)
492 extension_event_router_forwarder_(extension_event_router_forwarder),
493 #endif
494 globals_(NULL),
495 is_spdy_disabled_by_policy_(false),
496 is_quic_allowed_by_policy_(true),
497 creation_time_(base::TimeTicks::Now()),
498 weak_factory_(this) {
499 auth_schemes_ = local_state->GetString(prefs::kAuthSchemes);
500 negotiate_disable_cname_lookup_ = local_state->GetBoolean(
501 prefs::kDisableAuthNegotiateCnameLookup);
502 negotiate_enable_port_ = local_state->GetBoolean(
503 prefs::kEnableAuthNegotiatePort);
504 auth_server_whitelist_ = local_state->GetString(prefs::kAuthServerWhitelist);
505 auth_delegate_whitelist_ = local_state->GetString(
506 prefs::kAuthNegotiateDelegateWhitelist);
507 gssapi_library_name_ = local_state->GetString(prefs::kGSSAPILibraryName);
508 auth_android_negotiate_account_type_ =
509 local_state->GetString(prefs::kAuthAndroidNegotiateAccountType);
510 pref_proxy_config_tracker_.reset(
511 ProxyServiceFactory::CreatePrefProxyConfigTrackerOfLocalState(
512 local_state));
513 ChromeNetworkDelegate::InitializePrefsOnUIThread(
514 &system_enable_referrers_,
515 NULL,
516 NULL,
517 NULL,
518 local_state);
519 ssl_config_service_manager_.reset(
520 SSLConfigServiceManager::CreateDefaultManager(local_state));
522 base::Value* dns_client_enabled_default = new base::FundamentalValue(
523 chrome_browser_net::ConfigureAsyncDnsFieldTrial());
524 local_state->SetDefaultPrefValue(prefs::kBuiltInDnsClientEnabled,
525 dns_client_enabled_default);
526 chrome_browser_net::LogAsyncDnsPrefSource(
527 local_state->FindPreference(prefs::kBuiltInDnsClientEnabled));
529 dns_client_enabled_.Init(prefs::kBuiltInDnsClientEnabled,
530 local_state,
531 base::Bind(&IOThread::UpdateDnsClientEnabled,
532 base::Unretained(this)));
533 dns_client_enabled_.MoveToThread(
534 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
536 quick_check_enabled_.Init(prefs::kQuickCheckEnabled,
537 local_state);
538 quick_check_enabled_.MoveToThread(
539 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
541 #if defined(ENABLE_CONFIGURATION_POLICY)
542 is_spdy_disabled_by_policy_ = policy_service->GetPolicies(
543 policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME, std::string())).Get(
544 policy::key::kDisableSpdy) != NULL;
546 const base::Value* value = policy_service->GetPolicies(
547 policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME,
548 std::string())).GetValue(policy::key::kQuicAllowed);
549 if (value)
550 value->GetAsBoolean(&is_quic_allowed_by_policy_);
551 #endif // ENABLE_CONFIGURATION_POLICY
553 BrowserThread::SetDelegate(BrowserThread::IO, this);
556 IOThread::~IOThread() {
557 // This isn't needed for production code, but in tests, IOThread may
558 // be multiply constructed.
559 BrowserThread::SetDelegate(BrowserThread::IO, NULL);
561 pref_proxy_config_tracker_->DetachFromPrefService();
562 DCHECK(!globals_);
565 IOThread::Globals* IOThread::globals() {
566 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
567 return globals_;
570 void IOThread::SetGlobalsForTesting(Globals* globals) {
571 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
572 DCHECK(!globals || !globals_);
573 globals_ = globals;
576 ChromeNetLog* IOThread::net_log() {
577 return net_log_;
580 void IOThread::ChangedToOnTheRecord() {
581 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
582 BrowserThread::PostTask(
583 BrowserThread::IO,
584 FROM_HERE,
585 base::Bind(&IOThread::ChangedToOnTheRecordOnIOThread,
586 base::Unretained(this)));
589 net::URLRequestContextGetter* IOThread::system_url_request_context_getter() {
590 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
591 if (!system_url_request_context_getter_.get()) {
592 InitSystemRequestContext();
594 return system_url_request_context_getter_.get();
597 void IOThread::Init() {
598 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
599 // is fixed.
600 tracked_objects::ScopedTracker tracking_profile1(
601 FROM_HERE_WITH_EXPLICIT_FUNCTION("466432 IOThread::InitAsync::Start"));
602 TRACE_EVENT0("startup", "IOThread::InitAsync");
603 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
605 #if defined(USE_NSS_CERTS) || defined(OS_IOS)
606 net::SetMessageLoopForNSSHttpIO();
607 #endif
609 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
610 // is fixed.
611 tracked_objects::ScopedTracker tracking_profile2(
612 FROM_HERE_WITH_EXPLICIT_FUNCTION(
613 "466432 IOThread::InitAsync::CommandLineForCurrentProcess"));
614 const base::CommandLine& command_line =
615 *base::CommandLine::ForCurrentProcess();
617 DCHECK(!globals_);
618 globals_ = new Globals;
620 // Add an observer that will emit network change events to the ChromeNetLog.
621 // Assuming NetworkChangeNotifier dispatches in FIFO order, we should be
622 // logging the network change before other IO thread consumers respond to it.
623 network_change_observer_.reset(
624 new LoggingNetworkChangeObserver(net_log_));
626 // Setup the HistogramWatcher to run on the IO thread.
627 net::NetworkChangeNotifier::InitHistogramWatcher();
629 #if defined(ENABLE_EXTENSIONS)
630 globals_->extension_event_router_forwarder =
631 extension_event_router_forwarder_;
632 #endif
634 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
635 // is fixed.
636 tracked_objects::ScopedTracker tracking_profile3(
637 FROM_HERE_WITH_EXPLICIT_FUNCTION(
638 "466432 IOThread::InitAsync::ChromeNetworkDelegate"));
639 scoped_ptr<ChromeNetworkDelegate> chrome_network_delegate(
640 new ChromeNetworkDelegate(extension_event_router_forwarder(),
641 &system_enable_referrers_));
643 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
644 // is fixed.
645 tracked_objects::ScopedTracker tracking_profile4(
646 FROM_HERE_WITH_EXPLICIT_FUNCTION(
647 "466432 IOThread::InitAsync::CreateGlobalHostResolver"));
648 globals_->system_network_delegate = chrome_network_delegate.Pass();
649 globals_->host_resolver = CreateGlobalHostResolver(net_log_);
651 std::map<std::string, std::string> network_quality_estimator_params;
652 variations::GetVariationParams(kNetworkQualityEstimatorFieldTrialName,
653 &network_quality_estimator_params);
654 globals_->network_quality_estimator.reset(
655 new net::NetworkQualityEstimator(network_quality_estimator_params));
657 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
658 // is fixed.
659 tracked_objects::ScopedTracker tracking_profile5(
660 FROM_HERE_WITH_EXPLICIT_FUNCTION(
661 "466432 IOThread::InitAsync::UpdateDnsClientEnabled::Start"));
662 UpdateDnsClientEnabled();
663 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
664 // is fixed.
665 tracked_objects::ScopedTracker tracking_profile6(
666 FROM_HERE_WITH_EXPLICIT_FUNCTION(
667 "466432 IOThread::InitAsync::UpdateDnsClientEnabled::End"));
668 #if defined(OS_CHROMEOS)
669 // Creates a CertVerifyProc that doesn't allow any profile-provided certs.
670 globals_->cert_verifier.reset(new net::MultiThreadedCertVerifier(
671 new chromeos::CertVerifyProcChromeOS()));
672 #else
673 globals_->cert_verifier.reset(new net::MultiThreadedCertVerifier(
674 net::CertVerifyProc::CreateDefault()));
675 #endif
677 globals_->transport_security_state.reset(new net::TransportSecurityState());
679 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
680 // is fixed.
681 tracked_objects::ScopedTracker tracking_profile8(
682 FROM_HERE_WITH_EXPLICIT_FUNCTION(
683 "466432 IOThread::InitAsync::CreateLogVerifiers::Start"));
684 std::vector<scoped_refptr<net::CTLogVerifier>> ct_logs(
685 net::ct::CreateLogVerifiersForKnownLogs());
687 // Add logs from command line
688 if (command_line.HasSwitch(switches::kCertificateTransparencyLog)) {
689 std::string switch_value = command_line.GetSwitchValueASCII(
690 switches::kCertificateTransparencyLog);
691 std::vector<std::string> logs;
692 base::SplitString(switch_value, ',', &logs);
693 for (std::vector<std::string>::iterator it = logs.begin(); it != logs.end();
694 ++it) {
695 const std::string& curr_log = *it;
696 std::vector<std::string> log_metadata;
697 base::SplitString(curr_log, ':', &log_metadata);
698 CHECK_GE(log_metadata.size(), 3u)
699 << "CT log metadata missing: Switch format is "
700 << "'description:base64_key:url_without_schema'.";
701 std::string log_description(log_metadata[0]);
702 std::string log_url(std::string("https://") + log_metadata[2]);
703 std::string ct_public_key_data;
704 CHECK(base::Base64Decode(log_metadata[1], &ct_public_key_data))
705 << "Unable to decode CT public key.";
706 scoped_refptr<net::CTLogVerifier> external_log_verifier(
707 net::CTLogVerifier::Create(ct_public_key_data, log_description,
708 log_url));
709 CHECK(external_log_verifier) << "Unable to parse CT public key.";
710 VLOG(1) << "Adding log with description " << log_description;
711 ct_logs.push_back(external_log_verifier);
715 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
716 // is fixed.
717 tracked_objects::ScopedTracker tracking_profile9(
718 FROM_HERE_WITH_EXPLICIT_FUNCTION(
719 "466432 IOThread::InitAsync::CreateLogVerifiers::End"));
720 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
721 // is fixed.
722 tracked_objects::ScopedTracker tracking_profile7(
723 FROM_HERE_WITH_EXPLICIT_FUNCTION(
724 "466432 IOThread::InitAsync::CreateMultiLogVerifier"));
725 net::MultiLogCTVerifier* ct_verifier = new net::MultiLogCTVerifier();
726 globals_->cert_transparency_verifier.reset(ct_verifier);
727 // Add built-in logs
728 ct_verifier->AddLogs(ct_logs);
730 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
731 // is fixed.
732 tracked_objects::ScopedTracker tracking_profile10(
733 FROM_HERE_WITH_EXPLICIT_FUNCTION(
734 "466432 IOThread::InitAsync::CertPolicyEnforcer"));
735 net::CertPolicyEnforcer* policy_enforcer = new net::CertPolicyEnforcer;
736 globals_->cert_policy_enforcer.reset(policy_enforcer);
738 globals_->ssl_config_service = GetSSLConfigService();
740 globals_->http_auth_handler_factory.reset(CreateDefaultAuthHandlerFactory(
741 globals_->host_resolver.get()));
742 globals_->http_server_properties.reset(new net::HttpServerPropertiesImpl());
743 // For the ProxyScriptFetcher, we use a direct ProxyService.
744 globals_->proxy_script_fetcher_proxy_service.reset(
745 net::ProxyService::CreateDirectWithNetLog(net_log_));
746 // In-memory cookie store.
747 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
748 // is fixed.
749 tracked_objects::ScopedTracker tracking_profile11(
750 FROM_HERE_WITH_EXPLICIT_FUNCTION(
751 "466432 IOThread::InitAsync::CreateCookieStore::Start"));
752 globals_->system_cookie_store =
753 content::CreateCookieStore(content::CookieStoreConfig());
754 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
755 // is fixed.
756 tracked_objects::ScopedTracker tracking_profile12(
757 FROM_HERE_WITH_EXPLICIT_FUNCTION(
758 "466432 IOThread::InitAsync::CreateCookieStore::End"));
759 // In-memory channel ID store.
760 globals_->system_channel_id_service.reset(
761 new net::ChannelIDService(
762 new net::DefaultChannelIDStore(NULL),
763 base::WorkerPool::GetTaskRunner(true)));
764 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
765 // is fixed.
766 tracked_objects::ScopedTracker tracking_profile12_1(
767 FROM_HERE_WITH_EXPLICIT_FUNCTION(
768 "466432 IOThread::InitAsync::CreateDnsProbeService"));
769 globals_->dns_probe_service.reset(new chrome_browser_net::DnsProbeService());
770 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
771 // is fixed.
772 tracked_objects::ScopedTracker tracking_profile12_2(
773 FROM_HERE_WITH_EXPLICIT_FUNCTION(
774 "466432 IOThread::InitAsync::CreateHostMappingRules"));
775 globals_->host_mapping_rules.reset(new net::HostMappingRules());
776 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
777 // is fixed.
778 tracked_objects::ScopedTracker tracking_profile12_3(
779 FROM_HERE_WITH_EXPLICIT_FUNCTION(
780 "466432 IOThread::InitAsync::CreateHTTPUserAgentSettings"));
781 globals_->http_user_agent_settings.reset(
782 new net::StaticHttpUserAgentSettings(std::string(), GetUserAgent()));
783 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
784 // is fixed.
785 tracked_objects::ScopedTracker tracking_profile12_4(
786 FROM_HERE_WITH_EXPLICIT_FUNCTION(
787 "466432 IOThread::InitAsync::CommandLineConfiguration"));
788 if (command_line.HasSwitch(switches::kHostRules)) {
789 TRACE_EVENT_BEGIN0("startup", "IOThread::InitAsync:SetRulesFromString");
790 globals_->host_mapping_rules->SetRulesFromString(
791 command_line.GetSwitchValueASCII(switches::kHostRules));
792 TRACE_EVENT_END0("startup", "IOThread::InitAsync:SetRulesFromString");
794 if (command_line.HasSwitch(switches::kIgnoreCertificateErrors))
795 globals_->ignore_certificate_errors = true;
796 if (command_line.HasSwitch(switches::kTestingFixedHttpPort)) {
797 globals_->testing_fixed_http_port =
798 GetSwitchValueAsInt(command_line, switches::kTestingFixedHttpPort);
800 if (command_line.HasSwitch(switches::kTestingFixedHttpsPort)) {
801 globals_->testing_fixed_https_port =
802 GetSwitchValueAsInt(command_line, switches::kTestingFixedHttpsPort);
804 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
805 // is fixed.
806 tracked_objects::ScopedTracker tracking_profile12_5(
807 FROM_HERE_WITH_EXPLICIT_FUNCTION(
808 "466432 IOThread::InitAsync::QuicConfiguration"));
809 ConfigureQuic(command_line);
810 if (command_line.HasSwitch(
811 switches::kEnableUserAlternateProtocolPorts)) {
812 globals_->enable_user_alternate_protocol_ports = true;
814 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
815 // is fixed.
816 tracked_objects::ScopedTracker tracking_profile13(
817 FROM_HERE_WITH_EXPLICIT_FUNCTION(
818 "466432 IOThread::InitAsync::InitializeNetworkOptions"));
819 InitializeNetworkOptions(command_line);
821 net::HttpNetworkSession::Params session_params;
822 InitializeNetworkSessionParams(&session_params);
823 session_params.net_log = net_log_;
824 session_params.proxy_service =
825 globals_->proxy_script_fetcher_proxy_service.get();
827 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
828 // is fixed.
829 tracked_objects::ScopedTracker tracking_profile14(
830 FROM_HERE_WITH_EXPLICIT_FUNCTION(
831 "466432 IOThread::InitAsync::HttpNetorkSession::Start"));
832 TRACE_EVENT_BEGIN0("startup", "IOThread::InitAsync:HttpNetworkSession");
833 scoped_refptr<net::HttpNetworkSession> network_session(
834 new net::HttpNetworkSession(session_params));
835 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
836 // is fixed.
837 tracked_objects::ScopedTracker tracking_profile15(
838 FROM_HERE_WITH_EXPLICIT_FUNCTION(
839 "466432 IOThread::InitAsync::HttpNetorkSession::End"));
840 globals_->proxy_script_fetcher_http_transaction_factory
841 .reset(new net::HttpNetworkLayer(network_session.get()));
842 TRACE_EVENT_END0("startup", "IOThread::InitAsync:HttpNetworkSession");
843 scoped_ptr<net::URLRequestJobFactoryImpl> job_factory(
844 new net::URLRequestJobFactoryImpl());
846 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
847 // is fixed.
848 tracked_objects::ScopedTracker tracking_profile16(
849 FROM_HERE_WITH_EXPLICIT_FUNCTION(
850 "466432 IOThread::InitAsync::SetProtocolHandler"));
851 job_factory->SetProtocolHandler(url::kDataScheme,
852 new net::DataProtocolHandler());
853 job_factory->SetProtocolHandler(
854 url::kFileScheme,
855 new net::FileProtocolHandler(
856 content::BrowserThread::GetBlockingPool()->
857 GetTaskRunnerWithShutdownBehavior(
858 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)));
859 #if !defined(DISABLE_FTP_SUPPORT)
860 globals_->proxy_script_fetcher_ftp_transaction_factory.reset(
861 new net::FtpNetworkLayer(globals_->host_resolver.get()));
862 job_factory->SetProtocolHandler(
863 url::kFtpScheme,
864 new net::FtpProtocolHandler(
865 globals_->proxy_script_fetcher_ftp_transaction_factory.get()));
866 #endif
867 globals_->proxy_script_fetcher_url_request_job_factory = job_factory.Pass();
869 globals_->proxy_script_fetcher_context.reset(
870 ConstructProxyScriptFetcherContext(globals_, net_log_));
872 #if defined(OS_MACOSX) && !defined(OS_IOS)
873 // Start observing Keychain events. This needs to be done on the UI thread,
874 // as Keychain services requires a CFRunLoop.
875 BrowserThread::PostTask(BrowserThread::UI,
876 FROM_HERE,
877 base::Bind(&ObserveKeychainEvents));
878 #endif
880 // InitSystemRequestContext turns right around and posts a task back
881 // to the IO thread, so we can't let it run until we know the IO
882 // thread has started.
884 // Note that since we are at BrowserThread::Init time, the UI thread
885 // is blocked waiting for the thread to start. Therefore, posting
886 // this task to the main thread's message loop here is guaranteed to
887 // get it onto the message loop while the IOThread object still
888 // exists. However, the message might not be processed on the UI
889 // thread until after IOThread is gone, so use a weak pointer.
890 BrowserThread::PostTask(BrowserThread::UI,
891 FROM_HERE,
892 base::Bind(&IOThread::InitSystemRequestContext,
893 weak_factory_.GetWeakPtr()));
896 void IOThread::CleanUp() {
897 base::debug::LeakTracker<SafeBrowsingURLRequestContext>::CheckForLeaks();
899 #if defined(USE_NSS_CERTS) || defined(OS_IOS)
900 net::ShutdownNSSHttpIO();
901 #endif
903 system_url_request_context_getter_ = NULL;
905 // Release objects that the net::URLRequestContext could have been pointing
906 // to.
908 // Shutdown the HistogramWatcher on the IO thread.
909 net::NetworkChangeNotifier::ShutdownHistogramWatcher();
911 // This must be reset before the ChromeNetLog is destroyed.
912 network_change_observer_.reset();
914 system_proxy_config_service_.reset();
916 delete globals_;
917 globals_ = NULL;
919 base::debug::LeakTracker<SystemURLRequestContextGetter>::CheckForLeaks();
922 void IOThread::InitializeNetworkOptions(const base::CommandLine& command_line) {
923 // Only handle use-spdy command line flags if "spdy.disabled" preference is
924 // not disabled via policy.
925 if (is_spdy_disabled_by_policy_) {
926 base::FieldTrial* trial = base::FieldTrialList::Find(kSpdyFieldTrialName);
927 if (trial)
928 trial->Disable();
929 } else {
930 std::string group = base::FieldTrialList::FindFullName(kSpdyFieldTrialName);
931 VariationParameters params;
932 if (!variations::GetVariationParams(kSpdyFieldTrialName, &params)) {
933 params.clear();
935 ConfigureSpdyGlobals(command_line, group, params, globals_);
938 ConfigureTCPFastOpen(command_line);
940 // TODO(rch): Make the client socket factory a per-network session
941 // instance, constructed from a NetworkSession::Params, to allow us
942 // to move this option to IOThread::Globals &
943 // HttpNetworkSession::Params.
946 void IOThread::ConfigureTCPFastOpen(const base::CommandLine& command_line) {
947 const std::string trial_group =
948 base::FieldTrialList::FindFullName(kTCPFastOpenFieldTrialName);
949 if (trial_group == kTCPFastOpenHttpsEnabledGroupName)
950 globals_->enable_tcp_fast_open_for_ssl.set(true);
951 bool always_enable_if_supported =
952 command_line.HasSwitch(switches::kEnableTcpFastOpen);
953 // Check for OS support of TCP FastOpen, and turn it on for all connections
954 // if indicated by user.
955 net::CheckSupportAndMaybeEnableTCPFastOpen(always_enable_if_supported);
958 // static
959 void IOThread::ConfigureSpdyGlobals(
960 const base::CommandLine& command_line,
961 base::StringPiece spdy_trial_group,
962 const VariationParameters& spdy_trial_params,
963 IOThread::Globals* globals) {
964 if (command_line.HasSwitch(switches::kTrustedSpdyProxy)) {
965 globals->trusted_spdy_proxy.set(
966 command_line.GetSwitchValueASCII(switches::kTrustedSpdyProxy));
968 if (command_line.HasSwitch(switches::kIgnoreUrlFetcherCertRequests))
969 net::URLFetcher::SetIgnoreCertificateRequests(true);
971 if (command_line.HasSwitch(switches::kUseSpdy)) {
972 std::string spdy_mode =
973 command_line.GetSwitchValueASCII(switches::kUseSpdy);
974 ConfigureSpdyGlobalsFromUseSpdyArgument(spdy_mode, globals);
975 return;
978 globals->next_protos.clear();
979 globals->next_protos.push_back(net::kProtoHTTP11);
980 bool enable_quic = false;
981 globals->enable_quic.CopyToIfSet(&enable_quic);
982 if (enable_quic) {
983 globals->next_protos.push_back(net::kProtoQUIC1SPDY3);
986 // No SPDY command-line flags have been specified. Examine trial groups.
987 if (spdy_trial_group.starts_with(kSpdyFieldTrialHoldbackGroupNamePrefix)) {
988 net::HttpStreamFactory::set_spdy_enabled(false);
989 return;
991 if (spdy_trial_group.starts_with(kSpdyFieldTrialSpdy31GroupNamePrefix)) {
992 globals->next_protos.push_back(net::kProtoSPDY31);
993 globals->use_alternate_protocols.set(true);
994 return;
996 if (spdy_trial_group.starts_with(kSpdyFieldTrialSpdy4GroupNamePrefix)) {
997 globals->next_protos.push_back(net::kProtoSPDY31);
998 globals->next_protos.push_back(net::kProtoHTTP2_14);
999 globals->next_protos.push_back(net::kProtoHTTP2);
1000 globals->use_alternate_protocols.set(true);
1001 return;
1003 if (spdy_trial_group.starts_with(kSpdyFieldTrialParametrizedPrefix)) {
1004 bool spdy_enabled = false;
1005 if (base::LowerCaseEqualsASCII(
1006 GetVariationParam(spdy_trial_params, "enable_spdy31"), "true")) {
1007 globals->next_protos.push_back(net::kProtoSPDY31);
1008 spdy_enabled = true;
1010 if (base::LowerCaseEqualsASCII(
1011 GetVariationParam(spdy_trial_params, "enable_http2_14"), "true")) {
1012 globals->next_protos.push_back(net::kProtoHTTP2_14);
1013 spdy_enabled = true;
1015 if (base::LowerCaseEqualsASCII(
1016 GetVariationParam(spdy_trial_params, "enable_http2"), "true")) {
1017 globals->next_protos.push_back(net::kProtoHTTP2);
1018 spdy_enabled = true;
1020 // TODO(bnc): HttpStreamFactory::spdy_enabled_ is redundant with
1021 // globals->next_protos, can it be eliminated?
1022 net::HttpStreamFactory::set_spdy_enabled(spdy_enabled);
1023 globals->use_alternate_protocols.set(true);
1024 return;
1027 // By default, enable HTTP/2.
1028 globals->next_protos.push_back(net::kProtoSPDY31);
1029 globals->next_protos.push_back(net::kProtoHTTP2_14);
1030 globals->next_protos.push_back(net::kProtoHTTP2);
1031 globals->use_alternate_protocols.set(true);
1034 // static
1035 void IOThread::RegisterPrefs(PrefRegistrySimple* registry) {
1036 registry->RegisterStringPref(prefs::kAuthSchemes,
1037 "basic,digest,ntlm,negotiate");
1038 registry->RegisterBooleanPref(prefs::kDisableAuthNegotiateCnameLookup, false);
1039 registry->RegisterBooleanPref(prefs::kEnableAuthNegotiatePort, false);
1040 registry->RegisterStringPref(prefs::kAuthServerWhitelist, std::string());
1041 registry->RegisterStringPref(prefs::kAuthNegotiateDelegateWhitelist,
1042 std::string());
1043 registry->RegisterStringPref(prefs::kGSSAPILibraryName, std::string());
1044 registry->RegisterStringPref(prefs::kAuthAndroidNegotiateAccountType,
1045 std::string());
1046 registry->RegisterStringPref(
1047 data_reduction_proxy::prefs::kDataReductionProxy, std::string());
1048 registry->RegisterBooleanPref(prefs::kEnableReferrers, true);
1049 data_reduction_proxy::RegisterPrefs(registry);
1050 registry->RegisterBooleanPref(prefs::kBuiltInDnsClientEnabled, true);
1051 registry->RegisterBooleanPref(prefs::kQuickCheckEnabled, true);
1054 net::HttpAuthHandlerFactory* IOThread::CreateDefaultAuthHandlerFactory(
1055 net::HostResolver* resolver) {
1056 net::HttpAuthFilterWhitelist* auth_filter_default_credentials = NULL;
1057 if (!auth_server_whitelist_.empty()) {
1058 auth_filter_default_credentials =
1059 new net::HttpAuthFilterWhitelist(auth_server_whitelist_);
1061 net::HttpAuthFilterWhitelist* auth_filter_delegate = NULL;
1062 if (!auth_delegate_whitelist_.empty()) {
1063 auth_filter_delegate =
1064 new net::HttpAuthFilterWhitelist(auth_delegate_whitelist_);
1066 globals_->url_security_manager.reset(
1067 net::URLSecurityManager::Create(auth_filter_default_credentials,
1068 auth_filter_delegate));
1069 std::vector<std::string> supported_schemes;
1070 base::SplitString(auth_schemes_, ',', &supported_schemes);
1072 scoped_ptr<net::HttpAuthHandlerRegistryFactory> registry_factory(
1073 net::HttpAuthHandlerRegistryFactory::Create(
1074 supported_schemes, globals_->url_security_manager.get(), resolver,
1075 gssapi_library_name_, auth_android_negotiate_account_type_,
1076 negotiate_disable_cname_lookup_, negotiate_enable_port_));
1077 return registry_factory.release();
1080 void IOThread::ClearHostCache() {
1081 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1083 net::HostCache* host_cache = globals_->host_resolver->GetHostCache();
1084 if (host_cache)
1085 host_cache->clear();
1088 void IOThread::InitializeNetworkSessionParams(
1089 net::HttpNetworkSession::Params* params) {
1090 InitializeNetworkSessionParamsFromGlobals(*globals_, params);
1093 // static
1094 void IOThread::InitializeNetworkSessionParamsFromGlobals(
1095 const IOThread::Globals& globals,
1096 net::HttpNetworkSession::Params* params) {
1097 params->host_resolver = globals.host_resolver.get();
1098 params->cert_verifier = globals.cert_verifier.get();
1099 params->cert_policy_enforcer = globals.cert_policy_enforcer.get();
1100 params->channel_id_service = globals.system_channel_id_service.get();
1101 params->transport_security_state = globals.transport_security_state.get();
1102 params->ssl_config_service = globals.ssl_config_service.get();
1103 params->http_auth_handler_factory = globals.http_auth_handler_factory.get();
1104 params->http_server_properties =
1105 globals.http_server_properties->GetWeakPtr();
1106 params->network_delegate = globals.system_network_delegate.get();
1107 params->host_mapping_rules = globals.host_mapping_rules.get();
1108 params->ignore_certificate_errors = globals.ignore_certificate_errors;
1109 params->testing_fixed_http_port = globals.testing_fixed_http_port;
1110 params->testing_fixed_https_port = globals.testing_fixed_https_port;
1111 globals.enable_tcp_fast_open_for_ssl.CopyToIfSet(
1112 &params->enable_tcp_fast_open_for_ssl);
1114 globals.initial_max_spdy_concurrent_streams.CopyToIfSet(
1115 &params->spdy_initial_max_concurrent_streams);
1116 globals.enable_spdy_compression.CopyToIfSet(
1117 &params->enable_spdy_compression);
1118 globals.enable_spdy_ping_based_connection_checking.CopyToIfSet(
1119 &params->enable_spdy_ping_based_connection_checking);
1120 globals.spdy_default_protocol.CopyToIfSet(
1121 &params->spdy_default_protocol);
1122 params->next_protos = globals.next_protos;
1123 globals.trusted_spdy_proxy.CopyToIfSet(&params->trusted_spdy_proxy);
1124 params->forced_spdy_exclusions = globals.forced_spdy_exclusions;
1125 globals.use_alternate_protocols.CopyToIfSet(
1126 &params->use_alternate_protocols);
1127 globals.alternative_service_probability_threshold.CopyToIfSet(
1128 &params->alternative_service_probability_threshold);
1130 globals.enable_quic.CopyToIfSet(&params->enable_quic);
1131 globals.disable_insecure_quic.CopyToIfSet(&params->disable_insecure_quic);
1132 globals.enable_quic_for_proxies.CopyToIfSet(&params->enable_quic_for_proxies);
1133 globals.quic_always_require_handshake_confirmation.CopyToIfSet(
1134 &params->quic_always_require_handshake_confirmation);
1135 globals.quic_disable_connection_pooling.CopyToIfSet(
1136 &params->quic_disable_connection_pooling);
1137 globals.quic_load_server_info_timeout_srtt_multiplier.CopyToIfSet(
1138 &params->quic_load_server_info_timeout_srtt_multiplier);
1139 globals.quic_enable_connection_racing.CopyToIfSet(
1140 &params->quic_enable_connection_racing);
1141 globals.quic_enable_non_blocking_io.CopyToIfSet(
1142 &params->quic_enable_non_blocking_io);
1143 globals.quic_prefer_aes.CopyToIfSet(&params->quic_prefer_aes);
1144 globals.quic_disable_disk_cache.CopyToIfSet(
1145 &params->quic_disable_disk_cache);
1146 globals.quic_max_number_of_lossy_connections.CopyToIfSet(
1147 &params->quic_max_number_of_lossy_connections);
1148 globals.quic_packet_loss_threshold.CopyToIfSet(
1149 &params->quic_packet_loss_threshold);
1150 globals.quic_socket_receive_buffer_size.CopyToIfSet(
1151 &params->quic_socket_receive_buffer_size);
1152 globals.enable_quic_port_selection.CopyToIfSet(
1153 &params->enable_quic_port_selection);
1154 globals.quic_max_packet_length.CopyToIfSet(&params->quic_max_packet_length);
1155 globals.quic_user_agent_id.CopyToIfSet(&params->quic_user_agent_id);
1156 globals.quic_supported_versions.CopyToIfSet(
1157 &params->quic_supported_versions);
1158 params->quic_connection_options = globals.quic_connection_options;
1160 globals.origin_to_force_quic_on.CopyToIfSet(
1161 &params->origin_to_force_quic_on);
1162 params->enable_user_alternate_protocol_ports =
1163 globals.enable_user_alternate_protocol_ports;
1166 base::TimeTicks IOThread::creation_time() const {
1167 return creation_time_;
1170 net::SSLConfigService* IOThread::GetSSLConfigService() {
1171 return ssl_config_service_manager_->Get();
1174 void IOThread::ChangedToOnTheRecordOnIOThread() {
1175 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1177 // Clear the host cache to avoid showing entries from the OTR session
1178 // in about:net-internals.
1179 ClearHostCache();
1182 void IOThread::InitSystemRequestContext() {
1183 if (system_url_request_context_getter_.get())
1184 return;
1185 // If we're in unit_tests, IOThread may not be run.
1186 if (!BrowserThread::IsMessageLoopValid(BrowserThread::IO))
1187 return;
1188 system_proxy_config_service_.reset(
1189 ProxyServiceFactory::CreateProxyConfigService(
1190 pref_proxy_config_tracker_.get()));
1191 system_url_request_context_getter_ =
1192 new SystemURLRequestContextGetter(this);
1193 // Safe to post an unretained this pointer, since IOThread is
1194 // guaranteed to outlive the IO BrowserThread.
1195 BrowserThread::PostTask(
1196 BrowserThread::IO,
1197 FROM_HERE,
1198 base::Bind(&IOThread::InitSystemRequestContextOnIOThread,
1199 base::Unretained(this)));
1202 void IOThread::InitSystemRequestContextOnIOThread() {
1203 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1204 DCHECK(!globals_->system_proxy_service.get());
1205 DCHECK(system_proxy_config_service_.get());
1207 const base::CommandLine& command_line =
1208 *base::CommandLine::ForCurrentProcess();
1209 globals_->system_proxy_service.reset(
1210 ProxyServiceFactory::CreateProxyService(
1211 net_log_,
1212 globals_->proxy_script_fetcher_context.get(),
1213 globals_->system_network_delegate.get(),
1214 system_proxy_config_service_.release(),
1215 command_line,
1216 quick_check_enabled_.GetValue()));
1218 net::HttpNetworkSession::Params system_params;
1219 InitializeNetworkSessionParams(&system_params);
1220 system_params.net_log = net_log_;
1221 system_params.proxy_service = globals_->system_proxy_service.get();
1223 globals_->system_http_transaction_factory.reset(
1224 new net::HttpNetworkLayer(
1225 new net::HttpNetworkSession(system_params)));
1226 globals_->system_url_request_job_factory.reset(
1227 new net::URLRequestJobFactoryImpl());
1228 globals_->system_request_context.reset(
1229 ConstructSystemRequestContext(globals_, net_log_));
1230 globals_->system_request_context->set_ssl_config_service(
1231 globals_->ssl_config_service.get());
1232 globals_->system_request_context->set_http_server_properties(
1233 globals_->http_server_properties->GetWeakPtr());
1236 void IOThread::UpdateDnsClientEnabled() {
1237 globals()->host_resolver->SetDnsClientEnabled(*dns_client_enabled_);
1240 void IOThread::ConfigureQuic(const base::CommandLine& command_line) {
1241 // Always fetch the field trial group to ensure it is reported correctly.
1242 // The command line flags will be associated with a group that is reported
1243 // so long as trial is actually queried.
1244 std::string group =
1245 base::FieldTrialList::FindFullName(kQuicFieldTrialName);
1246 VariationParameters params;
1247 if (!variations::GetVariationParams(kQuicFieldTrialName, &params)) {
1248 params.clear();
1251 ConfigureQuicGlobals(command_line, group, params, is_quic_allowed_by_policy_,
1252 globals_);
1255 // static
1256 void IOThread::ConfigureQuicGlobals(
1257 const base::CommandLine& command_line,
1258 base::StringPiece quic_trial_group,
1259 const VariationParameters& quic_trial_params,
1260 bool quic_allowed_by_policy,
1261 IOThread::Globals* globals) {
1262 bool enable_quic = ShouldEnableQuic(command_line, quic_trial_group,
1263 quic_allowed_by_policy);
1264 globals->enable_quic.set(enable_quic);
1265 bool enable_quic_for_proxies = ShouldEnableQuicForProxies(
1266 command_line, quic_trial_group, quic_allowed_by_policy);
1267 globals->enable_quic_for_proxies.set(enable_quic_for_proxies);
1268 if (enable_quic) {
1269 globals->disable_insecure_quic.set(
1270 ShouldDisableInsecureQuic(quic_trial_params));
1271 globals->quic_always_require_handshake_confirmation.set(
1272 ShouldQuicAlwaysRequireHandshakeConfirmation(quic_trial_params));
1273 globals->quic_disable_connection_pooling.set(
1274 ShouldQuicDisableConnectionPooling(quic_trial_params));
1275 int receive_buffer_size = GetQuicSocketReceiveBufferSize(quic_trial_params);
1276 if (receive_buffer_size != 0) {
1277 globals->quic_socket_receive_buffer_size.set(receive_buffer_size);
1279 float load_server_info_timeout_srtt_multiplier =
1280 GetQuicLoadServerInfoTimeoutSrttMultiplier(quic_trial_params);
1281 if (load_server_info_timeout_srtt_multiplier != 0) {
1282 globals->quic_load_server_info_timeout_srtt_multiplier.set(
1283 load_server_info_timeout_srtt_multiplier);
1285 globals->quic_enable_connection_racing.set(
1286 ShouldQuicEnableConnectionRacing(quic_trial_params));
1287 globals->quic_enable_non_blocking_io.set(
1288 ShouldQuicEnableNonBlockingIO(quic_trial_params));
1289 globals->quic_disable_disk_cache.set(
1290 ShouldQuicDisableDiskCache(quic_trial_params));
1291 globals->quic_prefer_aes.set(
1292 ShouldQuicPreferAes(quic_trial_params));
1293 int max_number_of_lossy_connections = GetQuicMaxNumberOfLossyConnections(
1294 quic_trial_params);
1295 if (max_number_of_lossy_connections != 0) {
1296 globals->quic_max_number_of_lossy_connections.set(
1297 max_number_of_lossy_connections);
1299 float packet_loss_threshold = GetQuicPacketLossThreshold(quic_trial_params);
1300 if (packet_loss_threshold != 0)
1301 globals->quic_packet_loss_threshold.set(packet_loss_threshold);
1302 globals->enable_quic_port_selection.set(
1303 ShouldEnableQuicPortSelection(command_line));
1304 globals->quic_connection_options =
1305 GetQuicConnectionOptions(command_line, quic_trial_params);
1308 size_t max_packet_length = GetQuicMaxPacketLength(command_line,
1309 quic_trial_params);
1310 if (max_packet_length != 0) {
1311 globals->quic_max_packet_length.set(max_packet_length);
1314 std::string quic_user_agent_id =
1315 chrome::VersionInfo::GetVersionStringModifier();
1316 if (!quic_user_agent_id.empty())
1317 quic_user_agent_id.push_back(' ');
1318 chrome::VersionInfo version_info;
1319 quic_user_agent_id.append(version_info.ProductNameAndVersionForUserAgent());
1320 quic_user_agent_id.push_back(' ');
1321 quic_user_agent_id.append(content::BuildOSCpuInfo());
1322 globals->quic_user_agent_id.set(quic_user_agent_id);
1324 net::QuicVersion version = GetQuicVersion(command_line, quic_trial_params);
1325 if (version != net::QUIC_VERSION_UNSUPPORTED) {
1326 net::QuicVersionVector supported_versions;
1327 supported_versions.push_back(version);
1328 globals->quic_supported_versions.set(supported_versions);
1331 double threshold = GetAlternativeProtocolProbabilityThreshold(
1332 command_line, quic_trial_params);
1333 if (threshold >=0 && threshold <= 1) {
1334 globals->alternative_service_probability_threshold.set(threshold);
1335 globals->http_server_properties->SetAlternativeServiceProbabilityThreshold(
1336 threshold);
1339 if (command_line.HasSwitch(switches::kOriginToForceQuicOn)) {
1340 net::HostPortPair quic_origin =
1341 net::HostPortPair::FromString(
1342 command_line.GetSwitchValueASCII(switches::kOriginToForceQuicOn));
1343 if (!quic_origin.IsEmpty()) {
1344 globals->origin_to_force_quic_on.set(quic_origin);
1349 bool IOThread::ShouldEnableQuic(const base::CommandLine& command_line,
1350 base::StringPiece quic_trial_group,
1351 bool quic_allowed_by_policy) {
1352 if (command_line.HasSwitch(switches::kDisableQuic) || !quic_allowed_by_policy)
1353 return false;
1355 if (command_line.HasSwitch(switches::kEnableQuic))
1356 return true;
1358 return quic_trial_group.starts_with(kQuicFieldTrialEnabledGroupName) ||
1359 quic_trial_group.starts_with(kQuicFieldTrialHttpsEnabledGroupName);
1362 // static
1363 bool IOThread::ShouldEnableQuicForProxies(const base::CommandLine& command_line,
1364 base::StringPiece quic_trial_group,
1365 bool quic_allowed_by_policy) {
1366 return ShouldEnableQuic(
1367 command_line, quic_trial_group, quic_allowed_by_policy) ||
1368 ShouldEnableQuicForDataReductionProxy();
1371 // static
1372 bool IOThread::ShouldEnableQuicForDataReductionProxy() {
1373 const base::CommandLine& command_line =
1374 *base::CommandLine::ForCurrentProcess();
1376 if (command_line.HasSwitch(switches::kDisableQuic))
1377 return false;
1379 return data_reduction_proxy::params::IsIncludedInQuicFieldTrial();
1382 // static
1383 bool IOThread::ShouldDisableInsecureQuic(
1384 const VariationParameters& quic_trial_params) {
1385 return base::LowerCaseEqualsASCII(
1386 GetVariationParam(quic_trial_params, "disable_insecure_quic"),
1387 "true");
1390 bool IOThread::ShouldEnableQuicPortSelection(
1391 const base::CommandLine& command_line) {
1392 if (command_line.HasSwitch(switches::kDisableQuicPortSelection))
1393 return false;
1395 if (command_line.HasSwitch(switches::kEnableQuicPortSelection))
1396 return true;
1398 return false; // Default to disabling port selection on all channels.
1401 net::QuicTagVector IOThread::GetQuicConnectionOptions(
1402 const base::CommandLine& command_line,
1403 const VariationParameters& quic_trial_params) {
1404 if (command_line.HasSwitch(switches::kQuicConnectionOptions)) {
1405 return net::QuicUtils::ParseQuicConnectionOptions(
1406 command_line.GetSwitchValueASCII(switches::kQuicConnectionOptions));
1409 VariationParameters::const_iterator it =
1410 quic_trial_params.find("connection_options");
1411 if (it == quic_trial_params.end()) {
1412 return net::QuicTagVector();
1415 return net::QuicUtils::ParseQuicConnectionOptions(it->second);
1418 // static
1419 double IOThread::GetAlternativeProtocolProbabilityThreshold(
1420 const base::CommandLine& command_line,
1421 const VariationParameters& quic_trial_params) {
1422 double value;
1423 if (command_line.HasSwitch(
1424 switches::kAlternativeServiceProbabilityThreshold)) {
1425 if (base::StringToDouble(
1426 command_line.GetSwitchValueASCII(
1427 switches::kAlternativeServiceProbabilityThreshold),
1428 &value)) {
1429 return value;
1432 if (command_line.HasSwitch(switches::kEnableQuic)) {
1433 return 0;
1435 // TODO(bnc): Remove when new parameter name rolls out and server
1436 // configuration is changed.
1437 if (base::StringToDouble(
1438 GetVariationParam(quic_trial_params,
1439 "alternate_protocol_probability_threshold"),
1440 &value)) {
1441 return value;
1443 if (base::StringToDouble(
1444 GetVariationParam(quic_trial_params,
1445 "alternative_service_probability_threshold"),
1446 &value)) {
1447 return value;
1449 return -1;
1452 // static
1453 bool IOThread::ShouldQuicAlwaysRequireHandshakeConfirmation(
1454 const VariationParameters& quic_trial_params) {
1455 return base::LowerCaseEqualsASCII(
1456 GetVariationParam(quic_trial_params,
1457 "always_require_handshake_confirmation"),
1458 "true");
1461 // static
1462 bool IOThread::ShouldQuicDisableConnectionPooling(
1463 const VariationParameters& quic_trial_params) {
1464 return base::LowerCaseEqualsASCII(
1465 GetVariationParam(quic_trial_params, "disable_connection_pooling"),
1466 "true");
1469 // static
1470 float IOThread::GetQuicLoadServerInfoTimeoutSrttMultiplier(
1471 const VariationParameters& quic_trial_params) {
1472 double value;
1473 if (base::StringToDouble(GetVariationParam(quic_trial_params,
1474 "load_server_info_time_to_srtt"),
1475 &value)) {
1476 return (float)value;
1478 return 0.0f;
1481 // static
1482 bool IOThread::ShouldQuicEnableConnectionRacing(
1483 const VariationParameters& quic_trial_params) {
1484 return base::LowerCaseEqualsASCII(
1485 GetVariationParam(quic_trial_params, "enable_connection_racing"),
1486 "true");
1489 // static
1490 bool IOThread::ShouldQuicEnableNonBlockingIO(
1491 const VariationParameters& quic_trial_params) {
1492 return base::LowerCaseEqualsASCII(
1493 GetVariationParam(quic_trial_params, "enable_non_blocking_io"),
1494 "true");
1497 // static
1498 bool IOThread::ShouldQuicDisableDiskCache(
1499 const VariationParameters& quic_trial_params) {
1500 return base::LowerCaseEqualsASCII(
1501 GetVariationParam(quic_trial_params, "disable_disk_cache"), "true");
1504 // static
1505 bool IOThread::ShouldQuicPreferAes(
1506 const VariationParameters& quic_trial_params) {
1507 return base::LowerCaseEqualsASCII(
1508 GetVariationParam(quic_trial_params, "prefer_aes"), "true");
1511 // static
1512 int IOThread::GetQuicMaxNumberOfLossyConnections(
1513 const VariationParameters& quic_trial_params) {
1514 int value;
1515 if (base::StringToInt(GetVariationParam(quic_trial_params,
1516 "max_number_of_lossy_connections"),
1517 &value)) {
1518 return value;
1520 return 0;
1523 // static
1524 float IOThread::GetQuicPacketLossThreshold(
1525 const VariationParameters& quic_trial_params) {
1526 double value;
1527 if (base::StringToDouble(GetVariationParam(quic_trial_params,
1528 "packet_loss_threshold"),
1529 &value)) {
1530 return (float)value;
1532 return 0.0f;
1535 // static
1536 int IOThread::GetQuicSocketReceiveBufferSize(
1537 const VariationParameters& quic_trial_params) {
1538 int value;
1539 if (base::StringToInt(GetVariationParam(quic_trial_params,
1540 "receive_buffer_size"),
1541 &value)) {
1542 return value;
1544 return 0;
1547 // static
1548 size_t IOThread::GetQuicMaxPacketLength(
1549 const base::CommandLine& command_line,
1550 const VariationParameters& quic_trial_params) {
1551 if (command_line.HasSwitch(switches::kQuicMaxPacketLength)) {
1552 unsigned value;
1553 if (!base::StringToUint(
1554 command_line.GetSwitchValueASCII(switches::kQuicMaxPacketLength),
1555 &value)) {
1556 return 0;
1558 return value;
1561 unsigned value;
1562 if (base::StringToUint(GetVariationParam(quic_trial_params,
1563 "max_packet_length"),
1564 &value)) {
1565 return value;
1567 return 0;
1570 // static
1571 net::QuicVersion IOThread::GetQuicVersion(
1572 const base::CommandLine& command_line,
1573 const VariationParameters& quic_trial_params) {
1574 if (command_line.HasSwitch(switches::kQuicVersion)) {
1575 return ParseQuicVersion(
1576 command_line.GetSwitchValueASCII(switches::kQuicVersion));
1579 return ParseQuicVersion(GetVariationParam(quic_trial_params, "quic_version"));
1582 // static
1583 net::QuicVersion IOThread::ParseQuicVersion(const std::string& quic_version) {
1584 net::QuicVersionVector supported_versions = net::QuicSupportedVersions();
1585 for (size_t i = 0; i < supported_versions.size(); ++i) {
1586 net::QuicVersion version = supported_versions[i];
1587 if (net::QuicVersionToString(version) == quic_version) {
1588 return version;
1592 return net::QUIC_VERSION_UNSUPPORTED;