Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / chrome / browser / io_thread.cc
blobc0fb93609a2ea8970d26e127e152e4ed1d72809f
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 for (const base::StringPiece& element : base::SplitStringPiece(
318 mode, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) {
319 std::vector<base::StringPiece> name_value = base::SplitStringPiece(
320 element, "=", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
321 const base::StringPiece option =
322 name_value.size() > 0 ? name_value[0] : base::StringPiece();
323 const base::StringPiece value =
324 name_value.size() > 1 ? name_value[1] : base::StringPiece();
326 if (option == kOff) {
327 net::HttpStreamFactory::set_spdy_enabled(false);
328 continue;
330 if (option == kDisablePing) {
331 globals->enable_spdy_ping_based_connection_checking.set(false);
332 continue;
334 if (option == kExclude) {
335 globals->forced_spdy_exclusions.insert(
336 net::HostPortPair::FromURL(GURL(value.as_string())));
337 continue;
339 if (option == kDisableCompression) {
340 globals->enable_spdy_compression.set(false);
341 continue;
343 if (option == kDisableAltProtocols) {
344 globals->use_alternate_protocols.set(false);
345 continue;
347 if (option == kInitialMaxConcurrentStreams) {
348 int streams;
349 if (base::StringToInt(value, &streams)) {
350 globals->initial_max_spdy_concurrent_streams.set(streams);
351 continue;
354 LOG(DFATAL) << "Unrecognized spdy option: " << option.as_string();
358 } // namespace
360 class IOThread::LoggingNetworkChangeObserver
361 : public net::NetworkChangeNotifier::IPAddressObserver,
362 public net::NetworkChangeNotifier::ConnectionTypeObserver,
363 public net::NetworkChangeNotifier::NetworkChangeObserver {
364 public:
365 // |net_log| must remain valid throughout our lifetime.
366 explicit LoggingNetworkChangeObserver(net::NetLog* net_log)
367 : net_log_(net_log) {
368 net::NetworkChangeNotifier::AddIPAddressObserver(this);
369 net::NetworkChangeNotifier::AddConnectionTypeObserver(this);
370 net::NetworkChangeNotifier::AddNetworkChangeObserver(this);
373 ~LoggingNetworkChangeObserver() override {
374 net::NetworkChangeNotifier::RemoveIPAddressObserver(this);
375 net::NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
376 net::NetworkChangeNotifier::RemoveNetworkChangeObserver(this);
379 // NetworkChangeNotifier::IPAddressObserver implementation.
380 void OnIPAddressChanged() override {
381 VLOG(1) << "Observed a change to the network IP addresses";
383 net_log_->AddGlobalEntry(net::NetLog::TYPE_NETWORK_IP_ADDRESSES_CHANGED);
386 // NetworkChangeNotifier::ConnectionTypeObserver implementation.
387 void OnConnectionTypeChanged(
388 net::NetworkChangeNotifier::ConnectionType type) override {
389 std::string type_as_string =
390 net::NetworkChangeNotifier::ConnectionTypeToString(type);
392 VLOG(1) << "Observed a change to network connectivity state "
393 << type_as_string;
395 net_log_->AddGlobalEntry(
396 net::NetLog::TYPE_NETWORK_CONNECTIVITY_CHANGED,
397 net::NetLog::StringCallback("new_connection_type", &type_as_string));
400 // NetworkChangeNotifier::NetworkChangeObserver implementation.
401 void OnNetworkChanged(
402 net::NetworkChangeNotifier::ConnectionType type) override {
403 std::string type_as_string =
404 net::NetworkChangeNotifier::ConnectionTypeToString(type);
406 VLOG(1) << "Observed a network change to state " << type_as_string;
408 net_log_->AddGlobalEntry(
409 net::NetLog::TYPE_NETWORK_CHANGED,
410 net::NetLog::StringCallback("new_connection_type", &type_as_string));
413 private:
414 net::NetLog* net_log_;
415 DISALLOW_COPY_AND_ASSIGN(LoggingNetworkChangeObserver);
418 class SystemURLRequestContextGetter : public net::URLRequestContextGetter {
419 public:
420 explicit SystemURLRequestContextGetter(IOThread* io_thread);
422 // Implementation for net::UrlRequestContextGetter.
423 net::URLRequestContext* GetURLRequestContext() override;
424 scoped_refptr<base::SingleThreadTaskRunner> GetNetworkTaskRunner()
425 const override;
427 protected:
428 ~SystemURLRequestContextGetter() override;
430 private:
431 IOThread* const io_thread_; // Weak pointer, owned by BrowserProcess.
432 scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_;
434 base::debug::LeakTracker<SystemURLRequestContextGetter> leak_tracker_;
437 SystemURLRequestContextGetter::SystemURLRequestContextGetter(
438 IOThread* io_thread)
439 : io_thread_(io_thread),
440 network_task_runner_(
441 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)) {
444 SystemURLRequestContextGetter::~SystemURLRequestContextGetter() {}
446 net::URLRequestContext* SystemURLRequestContextGetter::GetURLRequestContext() {
447 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
448 DCHECK(io_thread_->globals()->system_request_context.get());
450 return io_thread_->globals()->system_request_context.get();
453 scoped_refptr<base::SingleThreadTaskRunner>
454 SystemURLRequestContextGetter::GetNetworkTaskRunner() const {
455 return network_task_runner_;
458 IOThread::Globals::
459 SystemRequestContextLeakChecker::SystemRequestContextLeakChecker(
460 Globals* globals)
461 : globals_(globals) {
462 DCHECK(globals_);
465 IOThread::Globals::
466 SystemRequestContextLeakChecker::~SystemRequestContextLeakChecker() {
467 if (globals_->system_request_context.get())
468 globals_->system_request_context->AssertNoURLRequests();
471 IOThread::Globals::Globals()
472 : system_request_context_leak_checker(this),
473 ignore_certificate_errors(false),
474 testing_fixed_http_port(0),
475 testing_fixed_https_port(0),
476 enable_user_alternate_protocol_ports(false) {
479 IOThread::Globals::~Globals() {}
481 // |local_state| is passed in explicitly in order to (1) reduce implicit
482 // dependencies and (2) make IOThread more flexible for testing.
483 IOThread::IOThread(
484 PrefService* local_state,
485 policy::PolicyService* policy_service,
486 ChromeNetLog* net_log,
487 extensions::EventRouterForwarder* extension_event_router_forwarder)
488 : net_log_(net_log),
489 #if defined(ENABLE_EXTENSIONS)
490 extension_event_router_forwarder_(extension_event_router_forwarder),
491 #endif
492 globals_(NULL),
493 is_spdy_disabled_by_policy_(false),
494 is_quic_allowed_by_policy_(true),
495 creation_time_(base::TimeTicks::Now()),
496 weak_factory_(this) {
497 auth_schemes_ = local_state->GetString(prefs::kAuthSchemes);
498 negotiate_disable_cname_lookup_ = local_state->GetBoolean(
499 prefs::kDisableAuthNegotiateCnameLookup);
500 negotiate_enable_port_ = local_state->GetBoolean(
501 prefs::kEnableAuthNegotiatePort);
502 auth_server_whitelist_ = local_state->GetString(prefs::kAuthServerWhitelist);
503 auth_delegate_whitelist_ = local_state->GetString(
504 prefs::kAuthNegotiateDelegateWhitelist);
505 gssapi_library_name_ = local_state->GetString(prefs::kGSSAPILibraryName);
506 auth_android_negotiate_account_type_ =
507 local_state->GetString(prefs::kAuthAndroidNegotiateAccountType);
508 pref_proxy_config_tracker_.reset(
509 ProxyServiceFactory::CreatePrefProxyConfigTrackerOfLocalState(
510 local_state));
511 ChromeNetworkDelegate::InitializePrefsOnUIThread(
512 &system_enable_referrers_,
513 NULL,
514 NULL,
515 NULL,
516 local_state);
517 ssl_config_service_manager_.reset(
518 SSLConfigServiceManager::CreateDefaultManager(local_state));
520 base::Value* dns_client_enabled_default = new base::FundamentalValue(
521 chrome_browser_net::ConfigureAsyncDnsFieldTrial());
522 local_state->SetDefaultPrefValue(prefs::kBuiltInDnsClientEnabled,
523 dns_client_enabled_default);
524 chrome_browser_net::LogAsyncDnsPrefSource(
525 local_state->FindPreference(prefs::kBuiltInDnsClientEnabled));
527 dns_client_enabled_.Init(prefs::kBuiltInDnsClientEnabled,
528 local_state,
529 base::Bind(&IOThread::UpdateDnsClientEnabled,
530 base::Unretained(this)));
531 dns_client_enabled_.MoveToThread(
532 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
534 quick_check_enabled_.Init(prefs::kQuickCheckEnabled,
535 local_state);
536 quick_check_enabled_.MoveToThread(
537 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
539 #if defined(ENABLE_CONFIGURATION_POLICY)
540 is_spdy_disabled_by_policy_ = policy_service->GetPolicies(
541 policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME, std::string())).Get(
542 policy::key::kDisableSpdy) != NULL;
544 const base::Value* value = policy_service->GetPolicies(
545 policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME,
546 std::string())).GetValue(policy::key::kQuicAllowed);
547 if (value)
548 value->GetAsBoolean(&is_quic_allowed_by_policy_);
549 #endif // ENABLE_CONFIGURATION_POLICY
551 BrowserThread::SetDelegate(BrowserThread::IO, this);
554 IOThread::~IOThread() {
555 // This isn't needed for production code, but in tests, IOThread may
556 // be multiply constructed.
557 BrowserThread::SetDelegate(BrowserThread::IO, NULL);
559 pref_proxy_config_tracker_->DetachFromPrefService();
560 DCHECK(!globals_);
563 IOThread::Globals* IOThread::globals() {
564 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
565 return globals_;
568 void IOThread::SetGlobalsForTesting(Globals* globals) {
569 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
570 DCHECK(!globals || !globals_);
571 globals_ = globals;
574 ChromeNetLog* IOThread::net_log() {
575 return net_log_;
578 void IOThread::ChangedToOnTheRecord() {
579 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
580 BrowserThread::PostTask(
581 BrowserThread::IO,
582 FROM_HERE,
583 base::Bind(&IOThread::ChangedToOnTheRecordOnIOThread,
584 base::Unretained(this)));
587 net::URLRequestContextGetter* IOThread::system_url_request_context_getter() {
588 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
589 if (!system_url_request_context_getter_.get()) {
590 InitSystemRequestContext();
592 return system_url_request_context_getter_.get();
595 void IOThread::Init() {
596 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
597 // is fixed.
598 tracked_objects::ScopedTracker tracking_profile1(
599 FROM_HERE_WITH_EXPLICIT_FUNCTION("466432 IOThread::InitAsync::Start"));
600 TRACE_EVENT0("startup", "IOThread::InitAsync");
601 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
603 #if defined(USE_NSS_CERTS) || defined(OS_IOS)
604 net::SetMessageLoopForNSSHttpIO();
605 #endif
607 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
608 // is fixed.
609 tracked_objects::ScopedTracker tracking_profile2(
610 FROM_HERE_WITH_EXPLICIT_FUNCTION(
611 "466432 IOThread::InitAsync::CommandLineForCurrentProcess"));
612 const base::CommandLine& command_line =
613 *base::CommandLine::ForCurrentProcess();
615 DCHECK(!globals_);
616 globals_ = new Globals;
618 // Add an observer that will emit network change events to the ChromeNetLog.
619 // Assuming NetworkChangeNotifier dispatches in FIFO order, we should be
620 // logging the network change before other IO thread consumers respond to it.
621 network_change_observer_.reset(
622 new LoggingNetworkChangeObserver(net_log_));
624 // Setup the HistogramWatcher to run on the IO thread.
625 net::NetworkChangeNotifier::InitHistogramWatcher();
627 #if defined(ENABLE_EXTENSIONS)
628 globals_->extension_event_router_forwarder =
629 extension_event_router_forwarder_;
630 #endif
632 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
633 // is fixed.
634 tracked_objects::ScopedTracker tracking_profile3(
635 FROM_HERE_WITH_EXPLICIT_FUNCTION(
636 "466432 IOThread::InitAsync::ChromeNetworkDelegate"));
637 scoped_ptr<ChromeNetworkDelegate> chrome_network_delegate(
638 new ChromeNetworkDelegate(extension_event_router_forwarder(),
639 &system_enable_referrers_));
641 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
642 // is fixed.
643 tracked_objects::ScopedTracker tracking_profile4(
644 FROM_HERE_WITH_EXPLICIT_FUNCTION(
645 "466432 IOThread::InitAsync::CreateGlobalHostResolver"));
646 globals_->system_network_delegate = chrome_network_delegate.Pass();
647 globals_->host_resolver = CreateGlobalHostResolver(net_log_);
649 std::map<std::string, std::string> network_quality_estimator_params;
650 variations::GetVariationParams(kNetworkQualityEstimatorFieldTrialName,
651 &network_quality_estimator_params);
652 globals_->network_quality_estimator.reset(
653 new net::NetworkQualityEstimator(network_quality_estimator_params));
655 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
656 // is fixed.
657 tracked_objects::ScopedTracker tracking_profile5(
658 FROM_HERE_WITH_EXPLICIT_FUNCTION(
659 "466432 IOThread::InitAsync::UpdateDnsClientEnabled::Start"));
660 UpdateDnsClientEnabled();
661 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
662 // is fixed.
663 tracked_objects::ScopedTracker tracking_profile6(
664 FROM_HERE_WITH_EXPLICIT_FUNCTION(
665 "466432 IOThread::InitAsync::UpdateDnsClientEnabled::End"));
666 #if defined(OS_CHROMEOS)
667 // Creates a CertVerifyProc that doesn't allow any profile-provided certs.
668 globals_->cert_verifier.reset(new net::MultiThreadedCertVerifier(
669 new chromeos::CertVerifyProcChromeOS()));
670 #else
671 globals_->cert_verifier.reset(new net::MultiThreadedCertVerifier(
672 net::CertVerifyProc::CreateDefault()));
673 #endif
675 globals_->transport_security_state.reset(new net::TransportSecurityState());
677 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
678 // is fixed.
679 tracked_objects::ScopedTracker tracking_profile8(
680 FROM_HERE_WITH_EXPLICIT_FUNCTION(
681 "466432 IOThread::InitAsync::CreateLogVerifiers::Start"));
682 std::vector<scoped_refptr<net::CTLogVerifier>> ct_logs(
683 net::ct::CreateLogVerifiersForKnownLogs());
685 // Add logs from command line
686 if (command_line.HasSwitch(switches::kCertificateTransparencyLog)) {
687 std::string switch_value = command_line.GetSwitchValueASCII(
688 switches::kCertificateTransparencyLog);
689 for (const base::StringPiece& curr_log : base::SplitStringPiece(
690 switch_value, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) {
691 std::vector<std::string> log_metadata = base::SplitString(
692 curr_log, ":", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
693 CHECK_GE(log_metadata.size(), 3u)
694 << "CT log metadata missing: Switch format is "
695 << "'description:base64_key:url_without_schema'.";
696 std::string log_description(log_metadata[0]);
697 std::string log_url(std::string("https://") + log_metadata[2]);
698 std::string ct_public_key_data;
699 CHECK(base::Base64Decode(log_metadata[1], &ct_public_key_data))
700 << "Unable to decode CT public key.";
701 scoped_refptr<net::CTLogVerifier> external_log_verifier(
702 net::CTLogVerifier::Create(ct_public_key_data, log_description,
703 log_url));
704 CHECK(external_log_verifier) << "Unable to parse CT public key.";
705 VLOG(1) << "Adding log with description " << log_description;
706 ct_logs.push_back(external_log_verifier);
710 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
711 // is fixed.
712 tracked_objects::ScopedTracker tracking_profile9(
713 FROM_HERE_WITH_EXPLICIT_FUNCTION(
714 "466432 IOThread::InitAsync::CreateLogVerifiers::End"));
715 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
716 // is fixed.
717 tracked_objects::ScopedTracker tracking_profile7(
718 FROM_HERE_WITH_EXPLICIT_FUNCTION(
719 "466432 IOThread::InitAsync::CreateMultiLogVerifier"));
720 net::MultiLogCTVerifier* ct_verifier = new net::MultiLogCTVerifier();
721 globals_->cert_transparency_verifier.reset(ct_verifier);
722 // Add built-in logs
723 ct_verifier->AddLogs(ct_logs);
725 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
726 // is fixed.
727 tracked_objects::ScopedTracker tracking_profile10(
728 FROM_HERE_WITH_EXPLICIT_FUNCTION(
729 "466432 IOThread::InitAsync::CertPolicyEnforcer"));
730 net::CertPolicyEnforcer* policy_enforcer = new net::CertPolicyEnforcer;
731 globals_->cert_policy_enforcer.reset(policy_enforcer);
733 globals_->ssl_config_service = GetSSLConfigService();
735 globals_->http_auth_handler_factory.reset(CreateDefaultAuthHandlerFactory(
736 globals_->host_resolver.get()));
737 globals_->http_server_properties.reset(new net::HttpServerPropertiesImpl());
738 // For the ProxyScriptFetcher, we use a direct ProxyService.
739 globals_->proxy_script_fetcher_proxy_service.reset(
740 net::ProxyService::CreateDirectWithNetLog(net_log_));
741 // In-memory cookie store.
742 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
743 // is fixed.
744 tracked_objects::ScopedTracker tracking_profile11(
745 FROM_HERE_WITH_EXPLICIT_FUNCTION(
746 "466432 IOThread::InitAsync::CreateCookieStore::Start"));
747 globals_->system_cookie_store =
748 content::CreateCookieStore(content::CookieStoreConfig());
749 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
750 // is fixed.
751 tracked_objects::ScopedTracker tracking_profile12(
752 FROM_HERE_WITH_EXPLICIT_FUNCTION(
753 "466432 IOThread::InitAsync::CreateCookieStore::End"));
754 // In-memory channel ID store.
755 globals_->system_channel_id_service.reset(
756 new net::ChannelIDService(
757 new net::DefaultChannelIDStore(NULL),
758 base::WorkerPool::GetTaskRunner(true)));
759 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
760 // is fixed.
761 tracked_objects::ScopedTracker tracking_profile12_1(
762 FROM_HERE_WITH_EXPLICIT_FUNCTION(
763 "466432 IOThread::InitAsync::CreateDnsProbeService"));
764 globals_->dns_probe_service.reset(new chrome_browser_net::DnsProbeService());
765 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
766 // is fixed.
767 tracked_objects::ScopedTracker tracking_profile12_2(
768 FROM_HERE_WITH_EXPLICIT_FUNCTION(
769 "466432 IOThread::InitAsync::CreateHostMappingRules"));
770 globals_->host_mapping_rules.reset(new net::HostMappingRules());
771 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
772 // is fixed.
773 tracked_objects::ScopedTracker tracking_profile12_3(
774 FROM_HERE_WITH_EXPLICIT_FUNCTION(
775 "466432 IOThread::InitAsync::CreateHTTPUserAgentSettings"));
776 globals_->http_user_agent_settings.reset(
777 new net::StaticHttpUserAgentSettings(std::string(), GetUserAgent()));
778 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
779 // is fixed.
780 tracked_objects::ScopedTracker tracking_profile12_4(
781 FROM_HERE_WITH_EXPLICIT_FUNCTION(
782 "466432 IOThread::InitAsync::CommandLineConfiguration"));
783 if (command_line.HasSwitch(switches::kHostRules)) {
784 TRACE_EVENT_BEGIN0("startup", "IOThread::InitAsync:SetRulesFromString");
785 globals_->host_mapping_rules->SetRulesFromString(
786 command_line.GetSwitchValueASCII(switches::kHostRules));
787 TRACE_EVENT_END0("startup", "IOThread::InitAsync:SetRulesFromString");
789 if (command_line.HasSwitch(switches::kIgnoreCertificateErrors))
790 globals_->ignore_certificate_errors = true;
791 if (command_line.HasSwitch(switches::kTestingFixedHttpPort)) {
792 globals_->testing_fixed_http_port =
793 GetSwitchValueAsInt(command_line, switches::kTestingFixedHttpPort);
795 if (command_line.HasSwitch(switches::kTestingFixedHttpsPort)) {
796 globals_->testing_fixed_https_port =
797 GetSwitchValueAsInt(command_line, switches::kTestingFixedHttpsPort);
799 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
800 // is fixed.
801 tracked_objects::ScopedTracker tracking_profile12_5(
802 FROM_HERE_WITH_EXPLICIT_FUNCTION(
803 "466432 IOThread::InitAsync::QuicConfiguration"));
804 ConfigureQuic(command_line);
805 if (command_line.HasSwitch(
806 switches::kEnableUserAlternateProtocolPorts)) {
807 globals_->enable_user_alternate_protocol_ports = true;
809 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
810 // is fixed.
811 tracked_objects::ScopedTracker tracking_profile13(
812 FROM_HERE_WITH_EXPLICIT_FUNCTION(
813 "466432 IOThread::InitAsync::InitializeNetworkOptions"));
814 InitializeNetworkOptions(command_line);
816 net::HttpNetworkSession::Params session_params;
817 InitializeNetworkSessionParams(&session_params);
818 session_params.net_log = net_log_;
819 session_params.proxy_service =
820 globals_->proxy_script_fetcher_proxy_service.get();
822 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
823 // is fixed.
824 tracked_objects::ScopedTracker tracking_profile14(
825 FROM_HERE_WITH_EXPLICIT_FUNCTION(
826 "466432 IOThread::InitAsync::HttpNetorkSession::Start"));
827 TRACE_EVENT_BEGIN0("startup", "IOThread::InitAsync:HttpNetworkSession");
828 scoped_refptr<net::HttpNetworkSession> network_session(
829 new net::HttpNetworkSession(session_params));
830 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
831 // is fixed.
832 tracked_objects::ScopedTracker tracking_profile15(
833 FROM_HERE_WITH_EXPLICIT_FUNCTION(
834 "466432 IOThread::InitAsync::HttpNetorkSession::End"));
835 globals_->proxy_script_fetcher_http_transaction_factory
836 .reset(new net::HttpNetworkLayer(network_session.get()));
837 TRACE_EVENT_END0("startup", "IOThread::InitAsync:HttpNetworkSession");
838 scoped_ptr<net::URLRequestJobFactoryImpl> job_factory(
839 new net::URLRequestJobFactoryImpl());
841 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
842 // is fixed.
843 tracked_objects::ScopedTracker tracking_profile16(
844 FROM_HERE_WITH_EXPLICIT_FUNCTION(
845 "466432 IOThread::InitAsync::SetProtocolHandler"));
846 job_factory->SetProtocolHandler(url::kDataScheme,
847 new net::DataProtocolHandler());
848 job_factory->SetProtocolHandler(
849 url::kFileScheme,
850 new net::FileProtocolHandler(
851 content::BrowserThread::GetBlockingPool()->
852 GetTaskRunnerWithShutdownBehavior(
853 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)));
854 #if !defined(DISABLE_FTP_SUPPORT)
855 globals_->proxy_script_fetcher_ftp_transaction_factory.reset(
856 new net::FtpNetworkLayer(globals_->host_resolver.get()));
857 job_factory->SetProtocolHandler(
858 url::kFtpScheme,
859 new net::FtpProtocolHandler(
860 globals_->proxy_script_fetcher_ftp_transaction_factory.get()));
861 #endif
862 globals_->proxy_script_fetcher_url_request_job_factory = job_factory.Pass();
864 globals_->proxy_script_fetcher_context.reset(
865 ConstructProxyScriptFetcherContext(globals_, net_log_));
867 #if defined(OS_MACOSX) && !defined(OS_IOS)
868 // Start observing Keychain events. This needs to be done on the UI thread,
869 // as Keychain services requires a CFRunLoop.
870 BrowserThread::PostTask(BrowserThread::UI,
871 FROM_HERE,
872 base::Bind(&ObserveKeychainEvents));
873 #endif
875 // InitSystemRequestContext turns right around and posts a task back
876 // to the IO thread, so we can't let it run until we know the IO
877 // thread has started.
879 // Note that since we are at BrowserThread::Init time, the UI thread
880 // is blocked waiting for the thread to start. Therefore, posting
881 // this task to the main thread's message loop here is guaranteed to
882 // get it onto the message loop while the IOThread object still
883 // exists. However, the message might not be processed on the UI
884 // thread until after IOThread is gone, so use a weak pointer.
885 BrowserThread::PostTask(BrowserThread::UI,
886 FROM_HERE,
887 base::Bind(&IOThread::InitSystemRequestContext,
888 weak_factory_.GetWeakPtr()));
891 void IOThread::CleanUp() {
892 base::debug::LeakTracker<SafeBrowsingURLRequestContext>::CheckForLeaks();
894 #if defined(USE_NSS_CERTS) || defined(OS_IOS)
895 net::ShutdownNSSHttpIO();
896 #endif
898 system_url_request_context_getter_ = NULL;
900 // Release objects that the net::URLRequestContext could have been pointing
901 // to.
903 // Shutdown the HistogramWatcher on the IO thread.
904 net::NetworkChangeNotifier::ShutdownHistogramWatcher();
906 // This must be reset before the ChromeNetLog is destroyed.
907 network_change_observer_.reset();
909 system_proxy_config_service_.reset();
911 delete globals_;
912 globals_ = NULL;
914 base::debug::LeakTracker<SystemURLRequestContextGetter>::CheckForLeaks();
917 void IOThread::InitializeNetworkOptions(const base::CommandLine& command_line) {
918 // Only handle use-spdy command line flags if "spdy.disabled" preference is
919 // not disabled via policy.
920 if (is_spdy_disabled_by_policy_) {
921 base::FieldTrial* trial = base::FieldTrialList::Find(kSpdyFieldTrialName);
922 if (trial)
923 trial->Disable();
924 } else {
925 std::string group = base::FieldTrialList::FindFullName(kSpdyFieldTrialName);
926 VariationParameters params;
927 if (!variations::GetVariationParams(kSpdyFieldTrialName, &params)) {
928 params.clear();
930 ConfigureSpdyGlobals(command_line, group, params, globals_);
933 ConfigureTCPFastOpen(command_line);
935 // TODO(rch): Make the client socket factory a per-network session
936 // instance, constructed from a NetworkSession::Params, to allow us
937 // to move this option to IOThread::Globals &
938 // HttpNetworkSession::Params.
941 void IOThread::ConfigureTCPFastOpen(const base::CommandLine& command_line) {
942 const std::string trial_group =
943 base::FieldTrialList::FindFullName(kTCPFastOpenFieldTrialName);
944 if (trial_group == kTCPFastOpenHttpsEnabledGroupName)
945 globals_->enable_tcp_fast_open_for_ssl.set(true);
946 bool always_enable_if_supported =
947 command_line.HasSwitch(switches::kEnableTcpFastOpen);
948 // Check for OS support of TCP FastOpen, and turn it on for all connections
949 // if indicated by user.
950 net::CheckSupportAndMaybeEnableTCPFastOpen(always_enable_if_supported);
953 // static
954 void IOThread::ConfigureSpdyGlobals(
955 const base::CommandLine& command_line,
956 base::StringPiece spdy_trial_group,
957 const VariationParameters& spdy_trial_params,
958 IOThread::Globals* globals) {
959 if (command_line.HasSwitch(switches::kTrustedSpdyProxy)) {
960 globals->trusted_spdy_proxy.set(
961 command_line.GetSwitchValueASCII(switches::kTrustedSpdyProxy));
963 if (command_line.HasSwitch(switches::kIgnoreUrlFetcherCertRequests))
964 net::URLFetcher::SetIgnoreCertificateRequests(true);
966 if (command_line.HasSwitch(switches::kUseSpdy)) {
967 std::string spdy_mode =
968 command_line.GetSwitchValueASCII(switches::kUseSpdy);
969 ConfigureSpdyGlobalsFromUseSpdyArgument(spdy_mode, globals);
970 return;
973 globals->next_protos.clear();
974 globals->next_protos.push_back(net::kProtoHTTP11);
975 bool enable_quic = false;
976 globals->enable_quic.CopyToIfSet(&enable_quic);
977 if (enable_quic) {
978 globals->next_protos.push_back(net::kProtoQUIC1SPDY3);
981 // No SPDY command-line flags have been specified. Examine trial groups.
982 if (spdy_trial_group.starts_with(kSpdyFieldTrialHoldbackGroupNamePrefix)) {
983 net::HttpStreamFactory::set_spdy_enabled(false);
984 return;
986 if (spdy_trial_group.starts_with(kSpdyFieldTrialSpdy31GroupNamePrefix)) {
987 globals->next_protos.push_back(net::kProtoSPDY31);
988 globals->use_alternate_protocols.set(true);
989 return;
991 if (spdy_trial_group.starts_with(kSpdyFieldTrialSpdy4GroupNamePrefix)) {
992 globals->next_protos.push_back(net::kProtoSPDY31);
993 globals->next_protos.push_back(net::kProtoHTTP2_14);
994 globals->next_protos.push_back(net::kProtoHTTP2);
995 globals->use_alternate_protocols.set(true);
996 return;
998 if (spdy_trial_group.starts_with(kSpdyFieldTrialParametrizedPrefix)) {
999 bool spdy_enabled = false;
1000 if (base::LowerCaseEqualsASCII(
1001 GetVariationParam(spdy_trial_params, "enable_spdy31"), "true")) {
1002 globals->next_protos.push_back(net::kProtoSPDY31);
1003 spdy_enabled = true;
1005 if (base::LowerCaseEqualsASCII(
1006 GetVariationParam(spdy_trial_params, "enable_http2_14"), "true")) {
1007 globals->next_protos.push_back(net::kProtoHTTP2_14);
1008 spdy_enabled = true;
1010 if (base::LowerCaseEqualsASCII(
1011 GetVariationParam(spdy_trial_params, "enable_http2"), "true")) {
1012 globals->next_protos.push_back(net::kProtoHTTP2);
1013 spdy_enabled = true;
1015 // TODO(bnc): HttpStreamFactory::spdy_enabled_ is redundant with
1016 // globals->next_protos, can it be eliminated?
1017 net::HttpStreamFactory::set_spdy_enabled(spdy_enabled);
1018 globals->use_alternate_protocols.set(true);
1019 return;
1022 // By default, enable HTTP/2.
1023 globals->next_protos.push_back(net::kProtoSPDY31);
1024 globals->next_protos.push_back(net::kProtoHTTP2_14);
1025 globals->next_protos.push_back(net::kProtoHTTP2);
1026 globals->use_alternate_protocols.set(true);
1029 // static
1030 void IOThread::RegisterPrefs(PrefRegistrySimple* registry) {
1031 registry->RegisterStringPref(prefs::kAuthSchemes,
1032 "basic,digest,ntlm,negotiate");
1033 registry->RegisterBooleanPref(prefs::kDisableAuthNegotiateCnameLookup, false);
1034 registry->RegisterBooleanPref(prefs::kEnableAuthNegotiatePort, false);
1035 registry->RegisterStringPref(prefs::kAuthServerWhitelist, std::string());
1036 registry->RegisterStringPref(prefs::kAuthNegotiateDelegateWhitelist,
1037 std::string());
1038 registry->RegisterStringPref(prefs::kGSSAPILibraryName, std::string());
1039 registry->RegisterStringPref(prefs::kAuthAndroidNegotiateAccountType,
1040 std::string());
1041 registry->RegisterStringPref(
1042 data_reduction_proxy::prefs::kDataReductionProxy, std::string());
1043 registry->RegisterBooleanPref(prefs::kEnableReferrers, true);
1044 data_reduction_proxy::RegisterPrefs(registry);
1045 registry->RegisterBooleanPref(prefs::kBuiltInDnsClientEnabled, true);
1046 registry->RegisterBooleanPref(prefs::kQuickCheckEnabled, true);
1049 net::HttpAuthHandlerFactory* IOThread::CreateDefaultAuthHandlerFactory(
1050 net::HostResolver* resolver) {
1051 net::HttpAuthFilterWhitelist* auth_filter_default_credentials = NULL;
1052 if (!auth_server_whitelist_.empty()) {
1053 auth_filter_default_credentials =
1054 new net::HttpAuthFilterWhitelist(auth_server_whitelist_);
1056 net::HttpAuthFilterWhitelist* auth_filter_delegate = NULL;
1057 if (!auth_delegate_whitelist_.empty()) {
1058 auth_filter_delegate =
1059 new net::HttpAuthFilterWhitelist(auth_delegate_whitelist_);
1061 globals_->url_security_manager.reset(
1062 net::URLSecurityManager::Create(auth_filter_default_credentials,
1063 auth_filter_delegate));
1064 std::vector<std::string> supported_schemes;
1065 base::SplitString(auth_schemes_, ',', &supported_schemes);
1067 scoped_ptr<net::HttpAuthHandlerRegistryFactory> registry_factory(
1068 net::HttpAuthHandlerRegistryFactory::Create(
1069 supported_schemes, globals_->url_security_manager.get(), resolver,
1070 gssapi_library_name_, auth_android_negotiate_account_type_,
1071 negotiate_disable_cname_lookup_, negotiate_enable_port_));
1072 return registry_factory.release();
1075 void IOThread::ClearHostCache() {
1076 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1078 net::HostCache* host_cache = globals_->host_resolver->GetHostCache();
1079 if (host_cache)
1080 host_cache->clear();
1083 void IOThread::InitializeNetworkSessionParams(
1084 net::HttpNetworkSession::Params* params) {
1085 InitializeNetworkSessionParamsFromGlobals(*globals_, params);
1088 // static
1089 void IOThread::InitializeNetworkSessionParamsFromGlobals(
1090 const IOThread::Globals& globals,
1091 net::HttpNetworkSession::Params* params) {
1092 params->host_resolver = globals.host_resolver.get();
1093 params->cert_verifier = globals.cert_verifier.get();
1094 params->cert_policy_enforcer = globals.cert_policy_enforcer.get();
1095 params->channel_id_service = globals.system_channel_id_service.get();
1096 params->transport_security_state = globals.transport_security_state.get();
1097 params->ssl_config_service = globals.ssl_config_service.get();
1098 params->http_auth_handler_factory = globals.http_auth_handler_factory.get();
1099 params->http_server_properties =
1100 globals.http_server_properties->GetWeakPtr();
1101 params->network_delegate = globals.system_network_delegate.get();
1102 params->host_mapping_rules = globals.host_mapping_rules.get();
1103 params->ignore_certificate_errors = globals.ignore_certificate_errors;
1104 params->testing_fixed_http_port = globals.testing_fixed_http_port;
1105 params->testing_fixed_https_port = globals.testing_fixed_https_port;
1106 globals.enable_tcp_fast_open_for_ssl.CopyToIfSet(
1107 &params->enable_tcp_fast_open_for_ssl);
1109 globals.initial_max_spdy_concurrent_streams.CopyToIfSet(
1110 &params->spdy_initial_max_concurrent_streams);
1111 globals.enable_spdy_compression.CopyToIfSet(
1112 &params->enable_spdy_compression);
1113 globals.enable_spdy_ping_based_connection_checking.CopyToIfSet(
1114 &params->enable_spdy_ping_based_connection_checking);
1115 globals.spdy_default_protocol.CopyToIfSet(
1116 &params->spdy_default_protocol);
1117 params->next_protos = globals.next_protos;
1118 globals.trusted_spdy_proxy.CopyToIfSet(&params->trusted_spdy_proxy);
1119 params->forced_spdy_exclusions = globals.forced_spdy_exclusions;
1120 globals.use_alternate_protocols.CopyToIfSet(
1121 &params->use_alternate_protocols);
1122 globals.alternative_service_probability_threshold.CopyToIfSet(
1123 &params->alternative_service_probability_threshold);
1125 globals.enable_quic.CopyToIfSet(&params->enable_quic);
1126 globals.disable_insecure_quic.CopyToIfSet(&params->disable_insecure_quic);
1127 globals.enable_quic_for_proxies.CopyToIfSet(&params->enable_quic_for_proxies);
1128 globals.quic_always_require_handshake_confirmation.CopyToIfSet(
1129 &params->quic_always_require_handshake_confirmation);
1130 globals.quic_disable_connection_pooling.CopyToIfSet(
1131 &params->quic_disable_connection_pooling);
1132 globals.quic_load_server_info_timeout_srtt_multiplier.CopyToIfSet(
1133 &params->quic_load_server_info_timeout_srtt_multiplier);
1134 globals.quic_enable_connection_racing.CopyToIfSet(
1135 &params->quic_enable_connection_racing);
1136 globals.quic_enable_non_blocking_io.CopyToIfSet(
1137 &params->quic_enable_non_blocking_io);
1138 globals.quic_prefer_aes.CopyToIfSet(&params->quic_prefer_aes);
1139 globals.quic_disable_disk_cache.CopyToIfSet(
1140 &params->quic_disable_disk_cache);
1141 globals.quic_max_number_of_lossy_connections.CopyToIfSet(
1142 &params->quic_max_number_of_lossy_connections);
1143 globals.quic_packet_loss_threshold.CopyToIfSet(
1144 &params->quic_packet_loss_threshold);
1145 globals.quic_socket_receive_buffer_size.CopyToIfSet(
1146 &params->quic_socket_receive_buffer_size);
1147 globals.enable_quic_port_selection.CopyToIfSet(
1148 &params->enable_quic_port_selection);
1149 globals.quic_max_packet_length.CopyToIfSet(&params->quic_max_packet_length);
1150 globals.quic_user_agent_id.CopyToIfSet(&params->quic_user_agent_id);
1151 globals.quic_supported_versions.CopyToIfSet(
1152 &params->quic_supported_versions);
1153 params->quic_connection_options = globals.quic_connection_options;
1155 globals.origin_to_force_quic_on.CopyToIfSet(
1156 &params->origin_to_force_quic_on);
1157 params->enable_user_alternate_protocol_ports =
1158 globals.enable_user_alternate_protocol_ports;
1161 base::TimeTicks IOThread::creation_time() const {
1162 return creation_time_;
1165 net::SSLConfigService* IOThread::GetSSLConfigService() {
1166 return ssl_config_service_manager_->Get();
1169 void IOThread::ChangedToOnTheRecordOnIOThread() {
1170 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1172 // Clear the host cache to avoid showing entries from the OTR session
1173 // in about:net-internals.
1174 ClearHostCache();
1177 void IOThread::InitSystemRequestContext() {
1178 if (system_url_request_context_getter_.get())
1179 return;
1180 // If we're in unit_tests, IOThread may not be run.
1181 if (!BrowserThread::IsMessageLoopValid(BrowserThread::IO))
1182 return;
1183 system_proxy_config_service_.reset(
1184 ProxyServiceFactory::CreateProxyConfigService(
1185 pref_proxy_config_tracker_.get()));
1186 system_url_request_context_getter_ =
1187 new SystemURLRequestContextGetter(this);
1188 // Safe to post an unretained this pointer, since IOThread is
1189 // guaranteed to outlive the IO BrowserThread.
1190 BrowserThread::PostTask(
1191 BrowserThread::IO,
1192 FROM_HERE,
1193 base::Bind(&IOThread::InitSystemRequestContextOnIOThread,
1194 base::Unretained(this)));
1197 void IOThread::InitSystemRequestContextOnIOThread() {
1198 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1199 DCHECK(!globals_->system_proxy_service.get());
1200 DCHECK(system_proxy_config_service_.get());
1202 const base::CommandLine& command_line =
1203 *base::CommandLine::ForCurrentProcess();
1204 globals_->system_proxy_service.reset(
1205 ProxyServiceFactory::CreateProxyService(
1206 net_log_,
1207 globals_->proxy_script_fetcher_context.get(),
1208 globals_->system_network_delegate.get(),
1209 system_proxy_config_service_.release(),
1210 command_line,
1211 quick_check_enabled_.GetValue()));
1213 net::HttpNetworkSession::Params system_params;
1214 InitializeNetworkSessionParams(&system_params);
1215 system_params.net_log = net_log_;
1216 system_params.proxy_service = globals_->system_proxy_service.get();
1218 globals_->system_http_transaction_factory.reset(
1219 new net::HttpNetworkLayer(
1220 new net::HttpNetworkSession(system_params)));
1221 globals_->system_url_request_job_factory.reset(
1222 new net::URLRequestJobFactoryImpl());
1223 globals_->system_request_context.reset(
1224 ConstructSystemRequestContext(globals_, net_log_));
1225 globals_->system_request_context->set_ssl_config_service(
1226 globals_->ssl_config_service.get());
1227 globals_->system_request_context->set_http_server_properties(
1228 globals_->http_server_properties->GetWeakPtr());
1231 void IOThread::UpdateDnsClientEnabled() {
1232 globals()->host_resolver->SetDnsClientEnabled(*dns_client_enabled_);
1235 void IOThread::ConfigureQuic(const base::CommandLine& command_line) {
1236 // Always fetch the field trial group to ensure it is reported correctly.
1237 // The command line flags will be associated with a group that is reported
1238 // so long as trial is actually queried.
1239 std::string group =
1240 base::FieldTrialList::FindFullName(kQuicFieldTrialName);
1241 VariationParameters params;
1242 if (!variations::GetVariationParams(kQuicFieldTrialName, &params)) {
1243 params.clear();
1246 ConfigureQuicGlobals(command_line, group, params, is_quic_allowed_by_policy_,
1247 globals_);
1250 // static
1251 void IOThread::ConfigureQuicGlobals(
1252 const base::CommandLine& command_line,
1253 base::StringPiece quic_trial_group,
1254 const VariationParameters& quic_trial_params,
1255 bool quic_allowed_by_policy,
1256 IOThread::Globals* globals) {
1257 bool enable_quic = ShouldEnableQuic(command_line, quic_trial_group,
1258 quic_allowed_by_policy);
1259 globals->enable_quic.set(enable_quic);
1260 bool enable_quic_for_proxies = ShouldEnableQuicForProxies(
1261 command_line, quic_trial_group, quic_allowed_by_policy);
1262 globals->enable_quic_for_proxies.set(enable_quic_for_proxies);
1263 if (enable_quic) {
1264 globals->disable_insecure_quic.set(
1265 ShouldDisableInsecureQuic(quic_trial_params));
1266 globals->quic_always_require_handshake_confirmation.set(
1267 ShouldQuicAlwaysRequireHandshakeConfirmation(quic_trial_params));
1268 globals->quic_disable_connection_pooling.set(
1269 ShouldQuicDisableConnectionPooling(quic_trial_params));
1270 int receive_buffer_size = GetQuicSocketReceiveBufferSize(quic_trial_params);
1271 if (receive_buffer_size != 0) {
1272 globals->quic_socket_receive_buffer_size.set(receive_buffer_size);
1274 float load_server_info_timeout_srtt_multiplier =
1275 GetQuicLoadServerInfoTimeoutSrttMultiplier(quic_trial_params);
1276 if (load_server_info_timeout_srtt_multiplier != 0) {
1277 globals->quic_load_server_info_timeout_srtt_multiplier.set(
1278 load_server_info_timeout_srtt_multiplier);
1280 globals->quic_enable_connection_racing.set(
1281 ShouldQuicEnableConnectionRacing(quic_trial_params));
1282 globals->quic_enable_non_blocking_io.set(
1283 ShouldQuicEnableNonBlockingIO(quic_trial_params));
1284 globals->quic_disable_disk_cache.set(
1285 ShouldQuicDisableDiskCache(quic_trial_params));
1286 globals->quic_prefer_aes.set(
1287 ShouldQuicPreferAes(quic_trial_params));
1288 int max_number_of_lossy_connections = GetQuicMaxNumberOfLossyConnections(
1289 quic_trial_params);
1290 if (max_number_of_lossy_connections != 0) {
1291 globals->quic_max_number_of_lossy_connections.set(
1292 max_number_of_lossy_connections);
1294 float packet_loss_threshold = GetQuicPacketLossThreshold(quic_trial_params);
1295 if (packet_loss_threshold != 0)
1296 globals->quic_packet_loss_threshold.set(packet_loss_threshold);
1297 globals->enable_quic_port_selection.set(
1298 ShouldEnableQuicPortSelection(command_line));
1299 globals->quic_connection_options =
1300 GetQuicConnectionOptions(command_line, quic_trial_params);
1303 size_t max_packet_length = GetQuicMaxPacketLength(command_line,
1304 quic_trial_params);
1305 if (max_packet_length != 0) {
1306 globals->quic_max_packet_length.set(max_packet_length);
1309 std::string quic_user_agent_id =
1310 chrome::VersionInfo::GetVersionStringModifier();
1311 if (!quic_user_agent_id.empty())
1312 quic_user_agent_id.push_back(' ');
1313 chrome::VersionInfo version_info;
1314 quic_user_agent_id.append(version_info.ProductNameAndVersionForUserAgent());
1315 quic_user_agent_id.push_back(' ');
1316 quic_user_agent_id.append(content::BuildOSCpuInfo());
1317 globals->quic_user_agent_id.set(quic_user_agent_id);
1319 net::QuicVersion version = GetQuicVersion(command_line, quic_trial_params);
1320 if (version != net::QUIC_VERSION_UNSUPPORTED) {
1321 net::QuicVersionVector supported_versions;
1322 supported_versions.push_back(version);
1323 globals->quic_supported_versions.set(supported_versions);
1326 double threshold = GetAlternativeProtocolProbabilityThreshold(
1327 command_line, quic_trial_params);
1328 if (threshold >=0 && threshold <= 1) {
1329 globals->alternative_service_probability_threshold.set(threshold);
1330 globals->http_server_properties->SetAlternativeServiceProbabilityThreshold(
1331 threshold);
1334 if (command_line.HasSwitch(switches::kOriginToForceQuicOn)) {
1335 net::HostPortPair quic_origin =
1336 net::HostPortPair::FromString(
1337 command_line.GetSwitchValueASCII(switches::kOriginToForceQuicOn));
1338 if (!quic_origin.IsEmpty()) {
1339 globals->origin_to_force_quic_on.set(quic_origin);
1344 bool IOThread::ShouldEnableQuic(const base::CommandLine& command_line,
1345 base::StringPiece quic_trial_group,
1346 bool quic_allowed_by_policy) {
1347 if (command_line.HasSwitch(switches::kDisableQuic) || !quic_allowed_by_policy)
1348 return false;
1350 if (command_line.HasSwitch(switches::kEnableQuic))
1351 return true;
1353 return quic_trial_group.starts_with(kQuicFieldTrialEnabledGroupName) ||
1354 quic_trial_group.starts_with(kQuicFieldTrialHttpsEnabledGroupName);
1357 // static
1358 bool IOThread::ShouldEnableQuicForProxies(const base::CommandLine& command_line,
1359 base::StringPiece quic_trial_group,
1360 bool quic_allowed_by_policy) {
1361 return ShouldEnableQuic(
1362 command_line, quic_trial_group, quic_allowed_by_policy) ||
1363 ShouldEnableQuicForDataReductionProxy();
1366 // static
1367 bool IOThread::ShouldEnableQuicForDataReductionProxy() {
1368 const base::CommandLine& command_line =
1369 *base::CommandLine::ForCurrentProcess();
1371 if (command_line.HasSwitch(switches::kDisableQuic))
1372 return false;
1374 return data_reduction_proxy::params::IsIncludedInQuicFieldTrial();
1377 // static
1378 bool IOThread::ShouldDisableInsecureQuic(
1379 const VariationParameters& quic_trial_params) {
1380 return base::LowerCaseEqualsASCII(
1381 GetVariationParam(quic_trial_params, "disable_insecure_quic"),
1382 "true");
1385 bool IOThread::ShouldEnableQuicPortSelection(
1386 const base::CommandLine& command_line) {
1387 if (command_line.HasSwitch(switches::kDisableQuicPortSelection))
1388 return false;
1390 if (command_line.HasSwitch(switches::kEnableQuicPortSelection))
1391 return true;
1393 return false; // Default to disabling port selection on all channels.
1396 net::QuicTagVector IOThread::GetQuicConnectionOptions(
1397 const base::CommandLine& command_line,
1398 const VariationParameters& quic_trial_params) {
1399 if (command_line.HasSwitch(switches::kQuicConnectionOptions)) {
1400 return net::QuicUtils::ParseQuicConnectionOptions(
1401 command_line.GetSwitchValueASCII(switches::kQuicConnectionOptions));
1404 VariationParameters::const_iterator it =
1405 quic_trial_params.find("connection_options");
1406 if (it == quic_trial_params.end()) {
1407 return net::QuicTagVector();
1410 return net::QuicUtils::ParseQuicConnectionOptions(it->second);
1413 // static
1414 double IOThread::GetAlternativeProtocolProbabilityThreshold(
1415 const base::CommandLine& command_line,
1416 const VariationParameters& quic_trial_params) {
1417 double value;
1418 if (command_line.HasSwitch(
1419 switches::kAlternativeServiceProbabilityThreshold)) {
1420 if (base::StringToDouble(
1421 command_line.GetSwitchValueASCII(
1422 switches::kAlternativeServiceProbabilityThreshold),
1423 &value)) {
1424 return value;
1427 if (command_line.HasSwitch(switches::kEnableQuic)) {
1428 return 0;
1430 // TODO(bnc): Remove when new parameter name rolls out and server
1431 // configuration is changed.
1432 if (base::StringToDouble(
1433 GetVariationParam(quic_trial_params,
1434 "alternate_protocol_probability_threshold"),
1435 &value)) {
1436 return value;
1438 if (base::StringToDouble(
1439 GetVariationParam(quic_trial_params,
1440 "alternative_service_probability_threshold"),
1441 &value)) {
1442 return value;
1444 return -1;
1447 // static
1448 bool IOThread::ShouldQuicAlwaysRequireHandshakeConfirmation(
1449 const VariationParameters& quic_trial_params) {
1450 return base::LowerCaseEqualsASCII(
1451 GetVariationParam(quic_trial_params,
1452 "always_require_handshake_confirmation"),
1453 "true");
1456 // static
1457 bool IOThread::ShouldQuicDisableConnectionPooling(
1458 const VariationParameters& quic_trial_params) {
1459 return base::LowerCaseEqualsASCII(
1460 GetVariationParam(quic_trial_params, "disable_connection_pooling"),
1461 "true");
1464 // static
1465 float IOThread::GetQuicLoadServerInfoTimeoutSrttMultiplier(
1466 const VariationParameters& quic_trial_params) {
1467 double value;
1468 if (base::StringToDouble(GetVariationParam(quic_trial_params,
1469 "load_server_info_time_to_srtt"),
1470 &value)) {
1471 return (float)value;
1473 return 0.0f;
1476 // static
1477 bool IOThread::ShouldQuicEnableConnectionRacing(
1478 const VariationParameters& quic_trial_params) {
1479 return base::LowerCaseEqualsASCII(
1480 GetVariationParam(quic_trial_params, "enable_connection_racing"),
1481 "true");
1484 // static
1485 bool IOThread::ShouldQuicEnableNonBlockingIO(
1486 const VariationParameters& quic_trial_params) {
1487 return base::LowerCaseEqualsASCII(
1488 GetVariationParam(quic_trial_params, "enable_non_blocking_io"),
1489 "true");
1492 // static
1493 bool IOThread::ShouldQuicDisableDiskCache(
1494 const VariationParameters& quic_trial_params) {
1495 return base::LowerCaseEqualsASCII(
1496 GetVariationParam(quic_trial_params, "disable_disk_cache"), "true");
1499 // static
1500 bool IOThread::ShouldQuicPreferAes(
1501 const VariationParameters& quic_trial_params) {
1502 return base::LowerCaseEqualsASCII(
1503 GetVariationParam(quic_trial_params, "prefer_aes"), "true");
1506 // static
1507 int IOThread::GetQuicMaxNumberOfLossyConnections(
1508 const VariationParameters& quic_trial_params) {
1509 int value;
1510 if (base::StringToInt(GetVariationParam(quic_trial_params,
1511 "max_number_of_lossy_connections"),
1512 &value)) {
1513 return value;
1515 return 0;
1518 // static
1519 float IOThread::GetQuicPacketLossThreshold(
1520 const VariationParameters& quic_trial_params) {
1521 double value;
1522 if (base::StringToDouble(GetVariationParam(quic_trial_params,
1523 "packet_loss_threshold"),
1524 &value)) {
1525 return (float)value;
1527 return 0.0f;
1530 // static
1531 int IOThread::GetQuicSocketReceiveBufferSize(
1532 const VariationParameters& quic_trial_params) {
1533 int value;
1534 if (base::StringToInt(GetVariationParam(quic_trial_params,
1535 "receive_buffer_size"),
1536 &value)) {
1537 return value;
1539 return 0;
1542 // static
1543 size_t IOThread::GetQuicMaxPacketLength(
1544 const base::CommandLine& command_line,
1545 const VariationParameters& quic_trial_params) {
1546 if (command_line.HasSwitch(switches::kQuicMaxPacketLength)) {
1547 unsigned value;
1548 if (!base::StringToUint(
1549 command_line.GetSwitchValueASCII(switches::kQuicMaxPacketLength),
1550 &value)) {
1551 return 0;
1553 return value;
1556 unsigned value;
1557 if (base::StringToUint(GetVariationParam(quic_trial_params,
1558 "max_packet_length"),
1559 &value)) {
1560 return value;
1562 return 0;
1565 // static
1566 net::QuicVersion IOThread::GetQuicVersion(
1567 const base::CommandLine& command_line,
1568 const VariationParameters& quic_trial_params) {
1569 if (command_line.HasSwitch(switches::kQuicVersion)) {
1570 return ParseQuicVersion(
1571 command_line.GetSwitchValueASCII(switches::kQuicVersion));
1574 return ParseQuicVersion(GetVariationParam(quic_trial_params, "quic_version"));
1577 // static
1578 net::QuicVersion IOThread::ParseQuicVersion(const std::string& quic_version) {
1579 net::QuicVersionVector supported_versions = net::QuicSupportedVersions();
1580 for (size_t i = 0; i < supported_versions.size(); ++i) {
1581 net::QuicVersion version = supported_versions[i];
1582 if (net::QuicVersionToString(version) == quic_version) {
1583 return version;
1587 return net::QUIC_VERSION_UNSUPPORTED;