Remove aura enum from DesktopMediaID to fix desktop mirroring audio (CrOS).
[chromium-blink-merge.git] / chrome / browser / io_thread.cc
blobf5d30e33c119380c722346919143ffdbb04a3a25
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/channel_info.h"
40 #include "chrome/common/chrome_content_client.h"
41 #include "chrome/common/chrome_switches.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 "components/version_info/version_info.h"
48 #include "content/public/browser/browser_thread.h"
49 #include "content/public/browser/cookie_store_factory.h"
50 #include "content/public/common/user_agent.h"
51 #include "net/base/host_mapping_rules.h"
52 #include "net/base/net_util.h"
53 #include "net/base/network_quality_estimator.h"
54 #include "net/base/sdch_manager.h"
55 #include "net/cert/cert_policy_enforcer.h"
56 #include "net/cert/cert_verifier.h"
57 #include "net/cert/cert_verify_proc.h"
58 #include "net/cert/ct_known_logs.h"
59 #include "net/cert/ct_known_logs_static.h"
60 #include "net/cert/ct_log_verifier.h"
61 #include "net/cert/ct_verifier.h"
62 #include "net/cert/multi_log_ct_verifier.h"
63 #include "net/cert/multi_threaded_cert_verifier.h"
64 #include "net/cookies/cookie_store.h"
65 #include "net/dns/host_cache.h"
66 #include "net/dns/host_resolver.h"
67 #include "net/dns/mapped_host_resolver.h"
68 #include "net/ftp/ftp_network_layer.h"
69 #include "net/http/http_auth_filter.h"
70 #include "net/http/http_auth_handler_factory.h"
71 #include "net/http/http_network_layer.h"
72 #include "net/http/http_server_properties_impl.h"
73 #include "net/proxy/proxy_config_service.h"
74 #include "net/proxy/proxy_script_fetcher_impl.h"
75 #include "net/proxy/proxy_service.h"
76 #include "net/quic/crypto/crypto_protocol.h"
77 #include "net/quic/quic_protocol.h"
78 #include "net/quic/quic_utils.h"
79 #include "net/socket/tcp_client_socket.h"
80 #include "net/spdy/spdy_session.h"
81 #include "net/ssl/channel_id_service.h"
82 #include "net/ssl/default_channel_id_store.h"
83 #include "net/url_request/data_protocol_handler.h"
84 #include "net/url_request/file_protocol_handler.h"
85 #include "net/url_request/ftp_protocol_handler.h"
86 #include "net/url_request/static_http_user_agent_settings.h"
87 #include "net/url_request/url_fetcher.h"
88 #include "net/url_request/url_request_backoff_manager.h"
89 #include "net/url_request/url_request_context.h"
90 #include "net/url_request/url_request_context_getter.h"
91 #include "net/url_request/url_request_job_factory_impl.h"
92 #include "url/url_constants.h"
94 #if defined(ENABLE_CONFIGURATION_POLICY)
95 #include "policy/policy_constants.h"
96 #endif
98 #if defined(ENABLE_EXTENSIONS)
99 #include "chrome/browser/extensions/event_router_forwarder.h"
100 #endif
102 #if defined(USE_NSS_CERTS) || defined(OS_IOS)
103 #include "net/cert_net/nss_ocsp.h"
104 #endif
106 #if defined(OS_ANDROID)
107 #include "base/android/build_info.h"
108 #endif
110 #if defined(OS_CHROMEOS)
111 #include "chrome/browser/chromeos/net/cert_verify_proc_chromeos.h"
112 #include "chromeos/network/host_resolver_impl_chromeos.h"
113 #endif
115 using content::BrowserThread;
117 class SafeBrowsingURLRequestContext;
119 // The IOThread object must outlive any tasks posted to the IO thread before the
120 // Quit task, so base::Bind() calls are not refcounted.
122 namespace {
124 const char kTCPFastOpenFieldTrialName[] = "TCPFastOpen";
125 const char kTCPFastOpenHttpsEnabledGroupName[] = "HttpsEnabled";
127 const char kQuicFieldTrialName[] = "QUIC";
128 const char kQuicFieldTrialEnabledGroupName[] = "Enabled";
129 const char kQuicFieldTrialHttpsEnabledGroupName[] = "HttpsEnabled";
131 // The SPDY trial composes two different trial plus control groups:
132 // * A "holdback" group with SPDY disabled, and corresponding control
133 // (SPDY/3.1). The primary purpose of the holdback group is to encourage site
134 // operators to do feature detection rather than UA-sniffing. As such, this
135 // trial runs continuously.
136 // * A SPDY/4 experiment, for SPDY/4 (aka HTTP/2) vs SPDY/3.1 comparisons and
137 // eventual SPDY/4 deployment.
138 const char kSpdyFieldTrialName[] = "SPDY";
139 const char kSpdyFieldTrialHoldbackGroupNamePrefix[] = "SpdyDisabled";
140 const char kSpdyFieldTrialSpdy31GroupNamePrefix[] = "Spdy31Enabled";
141 const char kSpdyFieldTrialSpdy4GroupNamePrefix[] = "Spdy4Enabled";
142 const char kSpdyFieldTrialParametrizedPrefix[] = "Parametrized";
144 // Field trial for network quality estimator. Seeds RTT and downstream
145 // throughput observations with values that correspond to the connection type
146 // determined by the operating system.
147 const char kNetworkQualityEstimatorFieldTrialName[] = "NetworkQualityEstimator";
149 #if defined(OS_MACOSX) && !defined(OS_IOS)
150 void ObserveKeychainEvents() {
151 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
152 net::CertDatabase::GetInstance()->SetMessageLoopForKeychainEvents();
154 #endif
156 // Used for the "system" URLRequestContext.
157 class SystemURLRequestContext : public net::URLRequestContext {
158 public:
159 SystemURLRequestContext() {
160 #if defined(USE_NSS_CERTS) || defined(OS_IOS)
161 net::SetURLRequestContextForNSSHttpIO(this);
162 #endif
165 private:
166 ~SystemURLRequestContext() override {
167 AssertNoURLRequests();
168 #if defined(USE_NSS_CERTS) || defined(OS_IOS)
169 net::SetURLRequestContextForNSSHttpIO(NULL);
170 #endif
174 scoped_ptr<net::HostResolver> CreateGlobalHostResolver(net::NetLog* net_log) {
175 TRACE_EVENT0("startup", "IOThread::CreateGlobalHostResolver");
176 const base::CommandLine& command_line =
177 *base::CommandLine::ForCurrentProcess();
179 net::HostResolver::Options options;
181 // Use the retry attempts override from the command-line, if any.
182 if (command_line.HasSwitch(switches::kHostResolverRetryAttempts)) {
183 std::string s =
184 command_line.GetSwitchValueASCII(switches::kHostResolverRetryAttempts);
185 // Parse the switch (it should be a non-negative integer).
186 int n;
187 if (base::StringToInt(s, &n) && n >= 0) {
188 options.max_retry_attempts = static_cast<size_t>(n);
189 } else {
190 LOG(ERROR) << "Invalid switch for host resolver retry attempts: " << s;
194 scoped_ptr<net::HostResolver> global_host_resolver;
195 #if defined OS_CHROMEOS
196 global_host_resolver =
197 chromeos::HostResolverImplChromeOS::CreateSystemResolver(options,
198 net_log);
199 #else
200 global_host_resolver =
201 net::HostResolver::CreateSystemResolver(options, net_log);
202 #endif
204 // If hostname remappings were specified on the command-line, layer these
205 // rules on top of the real host resolver. This allows forwarding all requests
206 // through a designated test server.
207 if (!command_line.HasSwitch(switches::kHostResolverRules))
208 return global_host_resolver.Pass();
210 scoped_ptr<net::MappedHostResolver> remapped_resolver(
211 new net::MappedHostResolver(global_host_resolver.Pass()));
212 remapped_resolver->SetRulesFromString(
213 command_line.GetSwitchValueASCII(switches::kHostResolverRules));
214 return remapped_resolver.Pass();
217 // TODO(willchan): Remove proxy script fetcher context since it's not necessary
218 // now that I got rid of refcounting URLRequestContexts.
219 // See IOThread::Globals for details.
220 net::URLRequestContext*
221 ConstructProxyScriptFetcherContext(IOThread::Globals* globals,
222 net::NetLog* net_log) {
223 net::URLRequestContext* context = new net::URLRequestContext;
224 context->set_net_log(net_log);
225 context->set_host_resolver(globals->host_resolver.get());
226 context->set_cert_verifier(globals->cert_verifier.get());
227 context->set_transport_security_state(
228 globals->transport_security_state.get());
229 context->set_cert_transparency_verifier(
230 globals->cert_transparency_verifier.get());
231 context->set_http_auth_handler_factory(
232 globals->http_auth_handler_factory.get());
233 context->set_proxy_service(globals->proxy_script_fetcher_proxy_service.get());
234 context->set_http_transaction_factory(
235 globals->proxy_script_fetcher_http_transaction_factory.get());
236 context->set_job_factory(
237 globals->proxy_script_fetcher_url_request_job_factory.get());
238 context->set_cookie_store(globals->system_cookie_store.get());
239 context->set_channel_id_service(
240 globals->system_channel_id_service.get());
241 context->set_network_delegate(globals->system_network_delegate.get());
242 context->set_http_user_agent_settings(
243 globals->http_user_agent_settings.get());
244 // TODO(rtenneti): We should probably use HttpServerPropertiesManager for the
245 // system URLRequestContext too. There's no reason this should be tied to a
246 // profile.
247 return context;
250 net::URLRequestContext*
251 ConstructSystemRequestContext(IOThread::Globals* globals,
252 net::NetLog* net_log) {
253 net::URLRequestContext* context = new SystemURLRequestContext;
254 context->set_net_log(net_log);
255 context->set_host_resolver(globals->host_resolver.get());
256 context->set_cert_verifier(globals->cert_verifier.get());
257 context->set_transport_security_state(
258 globals->transport_security_state.get());
259 context->set_cert_transparency_verifier(
260 globals->cert_transparency_verifier.get());
261 context->set_http_auth_handler_factory(
262 globals->http_auth_handler_factory.get());
263 context->set_proxy_service(globals->system_proxy_service.get());
264 context->set_http_transaction_factory(
265 globals->system_http_transaction_factory.get());
266 context->set_job_factory(globals->system_url_request_job_factory.get());
267 context->set_cookie_store(globals->system_cookie_store.get());
268 context->set_channel_id_service(
269 globals->system_channel_id_service.get());
270 context->set_network_delegate(globals->system_network_delegate.get());
271 context->set_http_user_agent_settings(
272 globals->http_user_agent_settings.get());
273 context->set_network_quality_estimator(
274 globals->network_quality_estimator.get());
275 context->set_backoff_manager(globals->url_request_backoff_manager.get());
276 return context;
279 int GetSwitchValueAsInt(const base::CommandLine& command_line,
280 const std::string& switch_name) {
281 int value;
282 if (!base::StringToInt(command_line.GetSwitchValueASCII(switch_name),
283 &value)) {
284 return 0;
286 return value;
289 // Returns the value associated with |key| in |params| or "" if the
290 // key is not present in the map.
291 const std::string& GetVariationParam(
292 const std::map<std::string, std::string>& params,
293 const std::string& key) {
294 std::map<std::string, std::string>::const_iterator it = params.find(key);
295 if (it == params.end())
296 return base::EmptyString();
298 return it->second;
301 // Parse kUseSpdy command line flag options, which may contain the following:
303 // "off" : Disables SPDY support entirely.
304 // "no-ping" : Disables SPDY ping connection testing.
305 // "exclude=<host>" : Disables SPDY support for the host <host>.
306 // "no-compress" : Disables SPDY header compression.
307 // "no-alt-protocols : Disables alternate protocol support.
308 // "init-max-streams=<limit>" : Specifies the maximum number of concurrent
309 // streams for a SPDY session, unless the
310 // specifies a different value via SETTINGS.
311 void ConfigureSpdyGlobalsFromUseSpdyArgument(const std::string& mode,
312 IOThread::Globals* globals) {
313 static const char kOff[] = "off";
314 static const char kDisablePing[] = "no-ping";
315 static const char kExclude[] = "exclude"; // Hosts to exclude
316 static const char kDisableCompression[] = "no-compress";
317 static const char kDisableAltProtocols[] = "no-alt-protocols";
318 static const char kInitialMaxConcurrentStreams[] = "init-max-streams";
320 for (const base::StringPiece& element : base::SplitStringPiece(
321 mode, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) {
322 std::vector<base::StringPiece> name_value = base::SplitStringPiece(
323 element, "=", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
324 const base::StringPiece option =
325 name_value.size() > 0 ? name_value[0] : base::StringPiece();
326 const base::StringPiece value =
327 name_value.size() > 1 ? name_value[1] : base::StringPiece();
329 if (option == kOff) {
330 net::HttpStreamFactory::set_spdy_enabled(false);
331 continue;
333 if (option == kDisablePing) {
334 globals->enable_spdy_ping_based_connection_checking.set(false);
335 continue;
337 if (option == kExclude) {
338 globals->forced_spdy_exclusions.insert(
339 net::HostPortPair::FromURL(GURL(value.as_string())));
340 continue;
342 if (option == kDisableCompression) {
343 globals->enable_spdy_compression.set(false);
344 continue;
346 if (option == kDisableAltProtocols) {
347 globals->use_alternate_protocols.set(false);
348 continue;
350 if (option == kInitialMaxConcurrentStreams) {
351 int streams;
352 if (base::StringToInt(value, &streams)) {
353 globals->initial_max_spdy_concurrent_streams.set(streams);
354 continue;
357 LOG(DFATAL) << "Unrecognized spdy option: " << option.as_string();
361 } // namespace
363 class IOThread::LoggingNetworkChangeObserver
364 : public net::NetworkChangeNotifier::IPAddressObserver,
365 public net::NetworkChangeNotifier::ConnectionTypeObserver,
366 public net::NetworkChangeNotifier::NetworkChangeObserver {
367 public:
368 // |net_log| must remain valid throughout our lifetime.
369 explicit LoggingNetworkChangeObserver(net::NetLog* net_log)
370 : net_log_(net_log) {
371 net::NetworkChangeNotifier::AddIPAddressObserver(this);
372 net::NetworkChangeNotifier::AddConnectionTypeObserver(this);
373 net::NetworkChangeNotifier::AddNetworkChangeObserver(this);
376 ~LoggingNetworkChangeObserver() override {
377 net::NetworkChangeNotifier::RemoveIPAddressObserver(this);
378 net::NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
379 net::NetworkChangeNotifier::RemoveNetworkChangeObserver(this);
382 // NetworkChangeNotifier::IPAddressObserver implementation.
383 void OnIPAddressChanged() override {
384 VLOG(1) << "Observed a change to the network IP addresses";
386 net_log_->AddGlobalEntry(net::NetLog::TYPE_NETWORK_IP_ADDRESSES_CHANGED);
389 // NetworkChangeNotifier::ConnectionTypeObserver implementation.
390 void OnConnectionTypeChanged(
391 net::NetworkChangeNotifier::ConnectionType type) override {
392 std::string type_as_string =
393 net::NetworkChangeNotifier::ConnectionTypeToString(type);
395 VLOG(1) << "Observed a change to network connectivity state "
396 << type_as_string;
398 net_log_->AddGlobalEntry(
399 net::NetLog::TYPE_NETWORK_CONNECTIVITY_CHANGED,
400 net::NetLog::StringCallback("new_connection_type", &type_as_string));
403 // NetworkChangeNotifier::NetworkChangeObserver implementation.
404 void OnNetworkChanged(
405 net::NetworkChangeNotifier::ConnectionType type) override {
406 std::string type_as_string =
407 net::NetworkChangeNotifier::ConnectionTypeToString(type);
409 VLOG(1) << "Observed a network change to state " << type_as_string;
411 net_log_->AddGlobalEntry(
412 net::NetLog::TYPE_NETWORK_CHANGED,
413 net::NetLog::StringCallback("new_connection_type", &type_as_string));
416 private:
417 net::NetLog* net_log_;
418 DISALLOW_COPY_AND_ASSIGN(LoggingNetworkChangeObserver);
421 class SystemURLRequestContextGetter : public net::URLRequestContextGetter {
422 public:
423 explicit SystemURLRequestContextGetter(IOThread* io_thread);
425 // Implementation for net::UrlRequestContextGetter.
426 net::URLRequestContext* GetURLRequestContext() override;
427 scoped_refptr<base::SingleThreadTaskRunner> GetNetworkTaskRunner()
428 const override;
430 protected:
431 ~SystemURLRequestContextGetter() override;
433 private:
434 IOThread* const io_thread_; // Weak pointer, owned by BrowserProcess.
435 scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_;
437 base::debug::LeakTracker<SystemURLRequestContextGetter> leak_tracker_;
440 SystemURLRequestContextGetter::SystemURLRequestContextGetter(
441 IOThread* io_thread)
442 : io_thread_(io_thread),
443 network_task_runner_(
444 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)) {
447 SystemURLRequestContextGetter::~SystemURLRequestContextGetter() {}
449 net::URLRequestContext* SystemURLRequestContextGetter::GetURLRequestContext() {
450 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
451 DCHECK(io_thread_->globals()->system_request_context.get());
453 return io_thread_->globals()->system_request_context.get();
456 scoped_refptr<base::SingleThreadTaskRunner>
457 SystemURLRequestContextGetter::GetNetworkTaskRunner() const {
458 return network_task_runner_;
461 IOThread::Globals::
462 SystemRequestContextLeakChecker::SystemRequestContextLeakChecker(
463 Globals* globals)
464 : globals_(globals) {
465 DCHECK(globals_);
468 IOThread::Globals::
469 SystemRequestContextLeakChecker::~SystemRequestContextLeakChecker() {
470 if (globals_->system_request_context.get())
471 globals_->system_request_context->AssertNoURLRequests();
474 IOThread::Globals::Globals()
475 : system_request_context_leak_checker(this),
476 ignore_certificate_errors(false),
477 testing_fixed_http_port(0),
478 testing_fixed_https_port(0),
479 enable_user_alternate_protocol_ports(false) {
482 IOThread::Globals::~Globals() {}
484 // |local_state| is passed in explicitly in order to (1) reduce implicit
485 // dependencies and (2) make IOThread more flexible for testing.
486 IOThread::IOThread(
487 PrefService* local_state,
488 policy::PolicyService* policy_service,
489 ChromeNetLog* net_log,
490 extensions::EventRouterForwarder* extension_event_router_forwarder)
491 : net_log_(net_log),
492 #if defined(ENABLE_EXTENSIONS)
493 extension_event_router_forwarder_(extension_event_router_forwarder),
494 #endif
495 globals_(NULL),
496 is_spdy_disabled_by_policy_(false),
497 is_quic_allowed_by_policy_(true),
498 creation_time_(base::TimeTicks::Now()),
499 weak_factory_(this) {
500 auth_schemes_ = local_state->GetString(prefs::kAuthSchemes);
501 negotiate_disable_cname_lookup_ = local_state->GetBoolean(
502 prefs::kDisableAuthNegotiateCnameLookup);
503 negotiate_enable_port_ = local_state->GetBoolean(
504 prefs::kEnableAuthNegotiatePort);
505 auth_server_whitelist_ = local_state->GetString(prefs::kAuthServerWhitelist);
506 auth_delegate_whitelist_ = local_state->GetString(
507 prefs::kAuthNegotiateDelegateWhitelist);
508 gssapi_library_name_ = local_state->GetString(prefs::kGSSAPILibraryName);
509 auth_android_negotiate_account_type_ =
510 local_state->GetString(prefs::kAuthAndroidNegotiateAccountType);
511 pref_proxy_config_tracker_.reset(
512 ProxyServiceFactory::CreatePrefProxyConfigTrackerOfLocalState(
513 local_state));
514 ChromeNetworkDelegate::InitializePrefsOnUIThread(
515 &system_enable_referrers_,
516 NULL,
517 NULL,
518 NULL,
519 local_state);
520 ssl_config_service_manager_.reset(
521 SSLConfigServiceManager::CreateDefaultManager(local_state));
523 base::Value* dns_client_enabled_default = new base::FundamentalValue(
524 chrome_browser_net::ConfigureAsyncDnsFieldTrial());
525 local_state->SetDefaultPrefValue(prefs::kBuiltInDnsClientEnabled,
526 dns_client_enabled_default);
527 chrome_browser_net::LogAsyncDnsPrefSource(
528 local_state->FindPreference(prefs::kBuiltInDnsClientEnabled));
530 dns_client_enabled_.Init(prefs::kBuiltInDnsClientEnabled,
531 local_state,
532 base::Bind(&IOThread::UpdateDnsClientEnabled,
533 base::Unretained(this)));
534 dns_client_enabled_.MoveToThread(
535 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
537 quick_check_enabled_.Init(prefs::kQuickCheckEnabled,
538 local_state);
539 quick_check_enabled_.MoveToThread(
540 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
542 #if defined(ENABLE_CONFIGURATION_POLICY)
543 is_spdy_disabled_by_policy_ = policy_service->GetPolicies(
544 policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME, std::string())).Get(
545 policy::key::kDisableSpdy) != NULL;
547 const base::Value* value = policy_service->GetPolicies(
548 policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME,
549 std::string())).GetValue(policy::key::kQuicAllowed);
550 if (value)
551 value->GetAsBoolean(&is_quic_allowed_by_policy_);
552 #endif // ENABLE_CONFIGURATION_POLICY
554 BrowserThread::SetDelegate(BrowserThread::IO, this);
557 IOThread::~IOThread() {
558 // This isn't needed for production code, but in tests, IOThread may
559 // be multiply constructed.
560 BrowserThread::SetDelegate(BrowserThread::IO, NULL);
562 pref_proxy_config_tracker_->DetachFromPrefService();
563 DCHECK(!globals_);
566 IOThread::Globals* IOThread::globals() {
567 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
568 return globals_;
571 void IOThread::SetGlobalsForTesting(Globals* globals) {
572 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
573 DCHECK(!globals || !globals_);
574 globals_ = globals;
577 ChromeNetLog* IOThread::net_log() {
578 return net_log_;
581 void IOThread::ChangedToOnTheRecord() {
582 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
583 BrowserThread::PostTask(
584 BrowserThread::IO,
585 FROM_HERE,
586 base::Bind(&IOThread::ChangedToOnTheRecordOnIOThread,
587 base::Unretained(this)));
590 net::URLRequestContextGetter* IOThread::system_url_request_context_getter() {
591 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
592 if (!system_url_request_context_getter_.get()) {
593 InitSystemRequestContext();
595 return system_url_request_context_getter_.get();
598 void IOThread::Init() {
599 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
600 // is fixed.
601 tracked_objects::ScopedTracker tracking_profile1(
602 FROM_HERE_WITH_EXPLICIT_FUNCTION("466432 IOThread::InitAsync::Start"));
603 TRACE_EVENT0("startup", "IOThread::InitAsync");
604 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
606 #if defined(USE_NSS_CERTS) || defined(OS_IOS)
607 net::SetMessageLoopForNSSHttpIO();
608 #endif
610 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
611 // is fixed.
612 tracked_objects::ScopedTracker tracking_profile2(
613 FROM_HERE_WITH_EXPLICIT_FUNCTION(
614 "466432 IOThread::InitAsync::CommandLineForCurrentProcess"));
615 const base::CommandLine& command_line =
616 *base::CommandLine::ForCurrentProcess();
618 DCHECK(!globals_);
619 globals_ = new Globals;
621 // Add an observer that will emit network change events to the ChromeNetLog.
622 // Assuming NetworkChangeNotifier dispatches in FIFO order, we should be
623 // logging the network change before other IO thread consumers respond to it.
624 network_change_observer_.reset(
625 new LoggingNetworkChangeObserver(net_log_));
627 // Setup the HistogramWatcher to run on the IO thread.
628 net::NetworkChangeNotifier::InitHistogramWatcher();
630 #if defined(ENABLE_EXTENSIONS)
631 globals_->extension_event_router_forwarder =
632 extension_event_router_forwarder_;
633 #endif
635 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
636 // is fixed.
637 tracked_objects::ScopedTracker tracking_profile3(
638 FROM_HERE_WITH_EXPLICIT_FUNCTION(
639 "466432 IOThread::InitAsync::ChromeNetworkDelegate"));
640 scoped_ptr<ChromeNetworkDelegate> chrome_network_delegate(
641 new ChromeNetworkDelegate(extension_event_router_forwarder(),
642 &system_enable_referrers_));
644 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
645 // is fixed.
646 tracked_objects::ScopedTracker tracking_profile4(
647 FROM_HERE_WITH_EXPLICIT_FUNCTION(
648 "466432 IOThread::InitAsync::CreateGlobalHostResolver"));
649 globals_->system_network_delegate = chrome_network_delegate.Pass();
650 globals_->host_resolver = CreateGlobalHostResolver(net_log_);
652 std::map<std::string, std::string> network_quality_estimator_params;
653 variations::GetVariationParams(kNetworkQualityEstimatorFieldTrialName,
654 &network_quality_estimator_params);
655 globals_->network_quality_estimator.reset(
656 new net::NetworkQualityEstimator(network_quality_estimator_params));
658 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
659 // is fixed.
660 tracked_objects::ScopedTracker tracking_profile5(
661 FROM_HERE_WITH_EXPLICIT_FUNCTION(
662 "466432 IOThread::InitAsync::UpdateDnsClientEnabled::Start"));
663 UpdateDnsClientEnabled();
664 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
665 // is fixed.
666 tracked_objects::ScopedTracker tracking_profile6(
667 FROM_HERE_WITH_EXPLICIT_FUNCTION(
668 "466432 IOThread::InitAsync::UpdateDnsClientEnabled::End"));
669 #if defined(OS_CHROMEOS)
670 // Creates a CertVerifyProc that doesn't allow any profile-provided certs.
671 globals_->cert_verifier.reset(new net::MultiThreadedCertVerifier(
672 new chromeos::CertVerifyProcChromeOS()));
673 #else
674 globals_->cert_verifier.reset(new net::MultiThreadedCertVerifier(
675 net::CertVerifyProc::CreateDefault()));
676 #endif
678 globals_->transport_security_state.reset(new net::TransportSecurityState());
680 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
681 // is fixed.
682 tracked_objects::ScopedTracker tracking_profile8(
683 FROM_HERE_WITH_EXPLICIT_FUNCTION(
684 "466432 IOThread::InitAsync::CreateLogVerifiers::Start"));
685 std::vector<scoped_refptr<net::CTLogVerifier>> ct_logs(
686 net::ct::CreateLogVerifiersForKnownLogs());
688 // Add logs from command line
689 if (command_line.HasSwitch(switches::kCertificateTransparencyLog)) {
690 std::string switch_value = command_line.GetSwitchValueASCII(
691 switches::kCertificateTransparencyLog);
692 for (const base::StringPiece& curr_log : base::SplitStringPiece(
693 switch_value, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) {
694 std::vector<std::string> log_metadata = base::SplitString(
695 curr_log, ":", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
696 CHECK_GE(log_metadata.size(), 3u)
697 << "CT log metadata missing: Switch format is "
698 << "'description:base64_key:url_without_schema'.";
699 std::string log_description(log_metadata[0]);
700 std::string log_url(std::string("https://") + log_metadata[2]);
701 std::string ct_public_key_data;
702 CHECK(base::Base64Decode(log_metadata[1], &ct_public_key_data))
703 << "Unable to decode CT public key.";
704 scoped_refptr<net::CTLogVerifier> external_log_verifier(
705 net::CTLogVerifier::Create(ct_public_key_data, log_description,
706 log_url));
707 CHECK(external_log_verifier) << "Unable to parse CT public key.";
708 VLOG(1) << "Adding log with description " << log_description;
709 ct_logs.push_back(external_log_verifier);
713 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
714 // is fixed.
715 tracked_objects::ScopedTracker tracking_profile9(
716 FROM_HERE_WITH_EXPLICIT_FUNCTION(
717 "466432 IOThread::InitAsync::CreateLogVerifiers::End"));
718 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
719 // is fixed.
720 tracked_objects::ScopedTracker tracking_profile7(
721 FROM_HERE_WITH_EXPLICIT_FUNCTION(
722 "466432 IOThread::InitAsync::CreateMultiLogVerifier"));
723 net::MultiLogCTVerifier* ct_verifier = new net::MultiLogCTVerifier();
724 globals_->cert_transparency_verifier.reset(ct_verifier);
725 // Add built-in logs
726 ct_verifier->AddLogs(ct_logs);
728 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
729 // is fixed.
730 tracked_objects::ScopedTracker tracking_profile10(
731 FROM_HERE_WITH_EXPLICIT_FUNCTION(
732 "466432 IOThread::InitAsync::CertPolicyEnforcer"));
733 net::CertPolicyEnforcer* policy_enforcer = new net::CertPolicyEnforcer;
734 globals_->cert_policy_enforcer.reset(policy_enforcer);
736 globals_->ssl_config_service = GetSSLConfigService();
738 globals_->http_auth_handler_factory.reset(CreateDefaultAuthHandlerFactory(
739 globals_->host_resolver.get()));
740 globals_->http_server_properties.reset(new net::HttpServerPropertiesImpl());
741 // For the ProxyScriptFetcher, we use a direct ProxyService.
742 globals_->proxy_script_fetcher_proxy_service.reset(
743 net::ProxyService::CreateDirectWithNetLog(net_log_));
744 // In-memory cookie store.
745 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
746 // is fixed.
747 tracked_objects::ScopedTracker tracking_profile11(
748 FROM_HERE_WITH_EXPLICIT_FUNCTION(
749 "466432 IOThread::InitAsync::CreateCookieStore::Start"));
750 globals_->system_cookie_store =
751 content::CreateCookieStore(content::CookieStoreConfig());
752 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
753 // is fixed.
754 tracked_objects::ScopedTracker tracking_profile12(
755 FROM_HERE_WITH_EXPLICIT_FUNCTION(
756 "466432 IOThread::InitAsync::CreateCookieStore::End"));
757 // In-memory channel ID store.
758 globals_->system_channel_id_service.reset(
759 new net::ChannelIDService(
760 new net::DefaultChannelIDStore(NULL),
761 base::WorkerPool::GetTaskRunner(true)));
762 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
763 // is fixed.
764 tracked_objects::ScopedTracker tracking_profile12_1(
765 FROM_HERE_WITH_EXPLICIT_FUNCTION(
766 "466432 IOThread::InitAsync::CreateDnsProbeService"));
767 globals_->dns_probe_service.reset(new chrome_browser_net::DnsProbeService());
768 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
769 // is fixed.
770 tracked_objects::ScopedTracker tracking_profile12_2(
771 FROM_HERE_WITH_EXPLICIT_FUNCTION(
772 "466432 IOThread::InitAsync::CreateHostMappingRules"));
773 globals_->host_mapping_rules.reset(new net::HostMappingRules());
774 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
775 // is fixed.
776 tracked_objects::ScopedTracker tracking_profile12_3(
777 FROM_HERE_WITH_EXPLICIT_FUNCTION(
778 "466432 IOThread::InitAsync::CreateHTTPUserAgentSettings"));
779 globals_->http_user_agent_settings.reset(
780 new net::StaticHttpUserAgentSettings(std::string(), GetUserAgent()));
781 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
782 // is fixed.
783 tracked_objects::ScopedTracker tracking_profile12_4(
784 FROM_HERE_WITH_EXPLICIT_FUNCTION(
785 "466432 IOThread::InitAsync::CommandLineConfiguration"));
786 if (command_line.HasSwitch(switches::kHostRules)) {
787 TRACE_EVENT_BEGIN0("startup", "IOThread::InitAsync:SetRulesFromString");
788 globals_->host_mapping_rules->SetRulesFromString(
789 command_line.GetSwitchValueASCII(switches::kHostRules));
790 TRACE_EVENT_END0("startup", "IOThread::InitAsync:SetRulesFromString");
792 if (command_line.HasSwitch(switches::kIgnoreCertificateErrors))
793 globals_->ignore_certificate_errors = true;
794 if (command_line.HasSwitch(switches::kTestingFixedHttpPort)) {
795 globals_->testing_fixed_http_port =
796 GetSwitchValueAsInt(command_line, switches::kTestingFixedHttpPort);
798 if (command_line.HasSwitch(switches::kTestingFixedHttpsPort)) {
799 globals_->testing_fixed_https_port =
800 GetSwitchValueAsInt(command_line, switches::kTestingFixedHttpsPort);
802 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
803 // is fixed.
804 tracked_objects::ScopedTracker tracking_profile12_5(
805 FROM_HERE_WITH_EXPLICIT_FUNCTION(
806 "466432 IOThread::InitAsync::QuicConfiguration"));
807 ConfigureQuic(command_line);
808 if (command_line.HasSwitch(
809 switches::kEnableUserAlternateProtocolPorts)) {
810 globals_->enable_user_alternate_protocol_ports = true;
812 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
813 // is fixed.
814 tracked_objects::ScopedTracker tracking_profile13(
815 FROM_HERE_WITH_EXPLICIT_FUNCTION(
816 "466432 IOThread::InitAsync::InitializeNetworkOptions"));
817 InitializeNetworkOptions(command_line);
819 net::HttpNetworkSession::Params session_params;
820 InitializeNetworkSessionParams(&session_params);
821 session_params.net_log = net_log_;
822 session_params.proxy_service =
823 globals_->proxy_script_fetcher_proxy_service.get();
825 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
826 // is fixed.
827 tracked_objects::ScopedTracker tracking_profile14(
828 FROM_HERE_WITH_EXPLICIT_FUNCTION(
829 "466432 IOThread::InitAsync::HttpNetorkSession::Start"));
830 TRACE_EVENT_BEGIN0("startup", "IOThread::InitAsync:HttpNetworkSession");
831 scoped_refptr<net::HttpNetworkSession> network_session(
832 new net::HttpNetworkSession(session_params));
833 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
834 // is fixed.
835 tracked_objects::ScopedTracker tracking_profile15(
836 FROM_HERE_WITH_EXPLICIT_FUNCTION(
837 "466432 IOThread::InitAsync::HttpNetorkSession::End"));
838 globals_->proxy_script_fetcher_http_transaction_factory
839 .reset(new net::HttpNetworkLayer(network_session.get()));
840 TRACE_EVENT_END0("startup", "IOThread::InitAsync:HttpNetworkSession");
841 scoped_ptr<net::URLRequestJobFactoryImpl> job_factory(
842 new net::URLRequestJobFactoryImpl());
844 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
845 // is fixed.
846 tracked_objects::ScopedTracker tracking_profile16(
847 FROM_HERE_WITH_EXPLICIT_FUNCTION(
848 "466432 IOThread::InitAsync::SetProtocolHandler"));
849 job_factory->SetProtocolHandler(url::kDataScheme,
850 new net::DataProtocolHandler());
851 job_factory->SetProtocolHandler(
852 url::kFileScheme,
853 new net::FileProtocolHandler(
854 content::BrowserThread::GetBlockingPool()->
855 GetTaskRunnerWithShutdownBehavior(
856 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)));
857 #if !defined(DISABLE_FTP_SUPPORT)
858 globals_->proxy_script_fetcher_ftp_transaction_factory.reset(
859 new net::FtpNetworkLayer(globals_->host_resolver.get()));
860 job_factory->SetProtocolHandler(
861 url::kFtpScheme,
862 new net::FtpProtocolHandler(
863 globals_->proxy_script_fetcher_ftp_transaction_factory.get()));
864 #endif
865 globals_->proxy_script_fetcher_url_request_job_factory = job_factory.Pass();
867 globals_->proxy_script_fetcher_context.reset(
868 ConstructProxyScriptFetcherContext(globals_, net_log_));
870 const version_info::Channel channel = chrome::GetChannel();
871 if (channel == version_info::Channel::UNKNOWN ||
872 channel == version_info::Channel::CANARY ||
873 channel == version_info::Channel::DEV) {
874 globals_->url_request_backoff_manager.reset(
875 new net::URLRequestBackoffManager());
878 #if defined(OS_MACOSX) && !defined(OS_IOS)
879 // Start observing Keychain events. This needs to be done on the UI thread,
880 // as Keychain services requires a CFRunLoop.
881 BrowserThread::PostTask(BrowserThread::UI,
882 FROM_HERE,
883 base::Bind(&ObserveKeychainEvents));
884 #endif
886 // InitSystemRequestContext turns right around and posts a task back
887 // to the IO thread, so we can't let it run until we know the IO
888 // thread has started.
890 // Note that since we are at BrowserThread::Init time, the UI thread
891 // is blocked waiting for the thread to start. Therefore, posting
892 // this task to the main thread's message loop here is guaranteed to
893 // get it onto the message loop while the IOThread object still
894 // exists. However, the message might not be processed on the UI
895 // thread until after IOThread is gone, so use a weak pointer.
896 BrowserThread::PostTask(BrowserThread::UI,
897 FROM_HERE,
898 base::Bind(&IOThread::InitSystemRequestContext,
899 weak_factory_.GetWeakPtr()));
902 void IOThread::CleanUp() {
903 base::debug::LeakTracker<SafeBrowsingURLRequestContext>::CheckForLeaks();
905 #if defined(USE_NSS_CERTS) || defined(OS_IOS)
906 net::ShutdownNSSHttpIO();
907 #endif
909 system_url_request_context_getter_ = NULL;
911 // Release objects that the net::URLRequestContext could have been pointing
912 // to.
914 // Shutdown the HistogramWatcher on the IO thread.
915 net::NetworkChangeNotifier::ShutdownHistogramWatcher();
917 // This must be reset before the ChromeNetLog is destroyed.
918 network_change_observer_.reset();
920 system_proxy_config_service_.reset();
922 delete globals_;
923 globals_ = NULL;
925 base::debug::LeakTracker<SystemURLRequestContextGetter>::CheckForLeaks();
928 void IOThread::InitializeNetworkOptions(const base::CommandLine& command_line) {
929 // Only handle use-spdy command line flags if "spdy.disabled" preference is
930 // not disabled via policy.
931 if (is_spdy_disabled_by_policy_) {
932 base::FieldTrial* trial = base::FieldTrialList::Find(kSpdyFieldTrialName);
933 if (trial)
934 trial->Disable();
935 } else {
936 std::string group = base::FieldTrialList::FindFullName(kSpdyFieldTrialName);
937 VariationParameters params;
938 if (!variations::GetVariationParams(kSpdyFieldTrialName, &params)) {
939 params.clear();
941 ConfigureSpdyGlobals(command_line, group, params, globals_);
944 ConfigureTCPFastOpen(command_line);
946 // TODO(rch): Make the client socket factory a per-network session
947 // instance, constructed from a NetworkSession::Params, to allow us
948 // to move this option to IOThread::Globals &
949 // HttpNetworkSession::Params.
952 void IOThread::ConfigureTCPFastOpen(const base::CommandLine& command_line) {
953 const std::string trial_group =
954 base::FieldTrialList::FindFullName(kTCPFastOpenFieldTrialName);
955 if (trial_group == kTCPFastOpenHttpsEnabledGroupName)
956 globals_->enable_tcp_fast_open_for_ssl.set(true);
957 bool always_enable_if_supported =
958 command_line.HasSwitch(switches::kEnableTcpFastOpen);
959 // Check for OS support of TCP FastOpen, and turn it on for all connections
960 // if indicated by user.
961 net::CheckSupportAndMaybeEnableTCPFastOpen(always_enable_if_supported);
964 // static
965 void IOThread::ConfigureSpdyGlobals(
966 const base::CommandLine& command_line,
967 base::StringPiece spdy_trial_group,
968 const VariationParameters& spdy_trial_params,
969 IOThread::Globals* globals) {
970 if (command_line.HasSwitch(switches::kTrustedSpdyProxy)) {
971 globals->trusted_spdy_proxy.set(
972 command_line.GetSwitchValueASCII(switches::kTrustedSpdyProxy));
974 if (command_line.HasSwitch(switches::kIgnoreUrlFetcherCertRequests))
975 net::URLFetcher::SetIgnoreCertificateRequests(true);
977 if (command_line.HasSwitch(switches::kUseSpdy)) {
978 std::string spdy_mode =
979 command_line.GetSwitchValueASCII(switches::kUseSpdy);
980 ConfigureSpdyGlobalsFromUseSpdyArgument(spdy_mode, globals);
981 return;
984 globals->next_protos.clear();
985 globals->next_protos.push_back(net::kProtoHTTP11);
986 bool enable_quic = false;
987 globals->enable_quic.CopyToIfSet(&enable_quic);
988 if (enable_quic) {
989 globals->next_protos.push_back(net::kProtoQUIC1SPDY3);
992 // No SPDY command-line flags have been specified. Examine trial groups.
993 if (spdy_trial_group.starts_with(kSpdyFieldTrialHoldbackGroupNamePrefix)) {
994 net::HttpStreamFactory::set_spdy_enabled(false);
995 return;
997 if (spdy_trial_group.starts_with(kSpdyFieldTrialSpdy31GroupNamePrefix)) {
998 globals->next_protos.push_back(net::kProtoSPDY31);
999 globals->use_alternate_protocols.set(true);
1000 return;
1002 if (spdy_trial_group.starts_with(kSpdyFieldTrialSpdy4GroupNamePrefix)) {
1003 globals->next_protos.push_back(net::kProtoSPDY31);
1004 globals->next_protos.push_back(net::kProtoHTTP2_14);
1005 globals->next_protos.push_back(net::kProtoHTTP2);
1006 globals->use_alternate_protocols.set(true);
1007 return;
1009 if (spdy_trial_group.starts_with(kSpdyFieldTrialParametrizedPrefix)) {
1010 bool spdy_enabled = false;
1011 if (base::LowerCaseEqualsASCII(
1012 GetVariationParam(spdy_trial_params, "enable_spdy31"), "true")) {
1013 globals->next_protos.push_back(net::kProtoSPDY31);
1014 spdy_enabled = true;
1016 if (base::LowerCaseEqualsASCII(
1017 GetVariationParam(spdy_trial_params, "enable_http2_14"), "true")) {
1018 globals->next_protos.push_back(net::kProtoHTTP2_14);
1019 spdy_enabled = true;
1021 if (base::LowerCaseEqualsASCII(
1022 GetVariationParam(spdy_trial_params, "enable_http2"), "true")) {
1023 globals->next_protos.push_back(net::kProtoHTTP2);
1024 spdy_enabled = true;
1026 // TODO(bnc): HttpStreamFactory::spdy_enabled_ is redundant with
1027 // globals->next_protos, can it be eliminated?
1028 net::HttpStreamFactory::set_spdy_enabled(spdy_enabled);
1029 globals->use_alternate_protocols.set(true);
1030 return;
1033 // By default, enable HTTP/2.
1034 globals->next_protos.push_back(net::kProtoSPDY31);
1035 globals->next_protos.push_back(net::kProtoHTTP2_14);
1036 globals->next_protos.push_back(net::kProtoHTTP2);
1037 globals->use_alternate_protocols.set(true);
1040 // static
1041 void IOThread::RegisterPrefs(PrefRegistrySimple* registry) {
1042 registry->RegisterStringPref(prefs::kAuthSchemes,
1043 "basic,digest,ntlm,negotiate");
1044 registry->RegisterBooleanPref(prefs::kDisableAuthNegotiateCnameLookup, false);
1045 registry->RegisterBooleanPref(prefs::kEnableAuthNegotiatePort, false);
1046 registry->RegisterStringPref(prefs::kAuthServerWhitelist, std::string());
1047 registry->RegisterStringPref(prefs::kAuthNegotiateDelegateWhitelist,
1048 std::string());
1049 registry->RegisterStringPref(prefs::kGSSAPILibraryName, std::string());
1050 registry->RegisterStringPref(prefs::kAuthAndroidNegotiateAccountType,
1051 std::string());
1052 registry->RegisterStringPref(
1053 data_reduction_proxy::prefs::kDataReductionProxy, std::string());
1054 registry->RegisterBooleanPref(prefs::kEnableReferrers, true);
1055 data_reduction_proxy::RegisterPrefs(registry);
1056 registry->RegisterBooleanPref(prefs::kBuiltInDnsClientEnabled, true);
1057 registry->RegisterBooleanPref(prefs::kQuickCheckEnabled, true);
1060 net::HttpAuthHandlerFactory* IOThread::CreateDefaultAuthHandlerFactory(
1061 net::HostResolver* resolver) {
1062 net::HttpAuthFilterWhitelist* auth_filter_default_credentials = NULL;
1063 if (!auth_server_whitelist_.empty()) {
1064 auth_filter_default_credentials =
1065 new net::HttpAuthFilterWhitelist(auth_server_whitelist_);
1067 net::HttpAuthFilterWhitelist* auth_filter_delegate = NULL;
1068 if (!auth_delegate_whitelist_.empty()) {
1069 auth_filter_delegate =
1070 new net::HttpAuthFilterWhitelist(auth_delegate_whitelist_);
1072 globals_->url_security_manager.reset(
1073 net::URLSecurityManager::Create(auth_filter_default_credentials,
1074 auth_filter_delegate));
1075 std::vector<std::string> supported_schemes;
1076 base::SplitString(auth_schemes_, ',', &supported_schemes);
1078 scoped_ptr<net::HttpAuthHandlerRegistryFactory> registry_factory(
1079 net::HttpAuthHandlerRegistryFactory::Create(
1080 supported_schemes, globals_->url_security_manager.get(), resolver,
1081 gssapi_library_name_, auth_android_negotiate_account_type_,
1082 negotiate_disable_cname_lookup_, negotiate_enable_port_));
1083 return registry_factory.release();
1086 void IOThread::ClearHostCache() {
1087 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1089 net::HostCache* host_cache = globals_->host_resolver->GetHostCache();
1090 if (host_cache)
1091 host_cache->clear();
1094 void IOThread::InitializeNetworkSessionParams(
1095 net::HttpNetworkSession::Params* params) {
1096 InitializeNetworkSessionParamsFromGlobals(*globals_, params);
1099 // static
1100 void IOThread::InitializeNetworkSessionParamsFromGlobals(
1101 const IOThread::Globals& globals,
1102 net::HttpNetworkSession::Params* params) {
1103 params->host_resolver = globals.host_resolver.get();
1104 params->cert_verifier = globals.cert_verifier.get();
1105 params->cert_policy_enforcer = globals.cert_policy_enforcer.get();
1106 params->channel_id_service = globals.system_channel_id_service.get();
1107 params->transport_security_state = globals.transport_security_state.get();
1108 params->ssl_config_service = globals.ssl_config_service.get();
1109 params->http_auth_handler_factory = globals.http_auth_handler_factory.get();
1110 params->http_server_properties =
1111 globals.http_server_properties->GetWeakPtr();
1112 params->network_delegate = globals.system_network_delegate.get();
1113 params->host_mapping_rules = globals.host_mapping_rules.get();
1114 params->ignore_certificate_errors = globals.ignore_certificate_errors;
1115 params->testing_fixed_http_port = globals.testing_fixed_http_port;
1116 params->testing_fixed_https_port = globals.testing_fixed_https_port;
1117 globals.enable_tcp_fast_open_for_ssl.CopyToIfSet(
1118 &params->enable_tcp_fast_open_for_ssl);
1120 globals.initial_max_spdy_concurrent_streams.CopyToIfSet(
1121 &params->spdy_initial_max_concurrent_streams);
1122 globals.enable_spdy_compression.CopyToIfSet(
1123 &params->enable_spdy_compression);
1124 globals.enable_spdy_ping_based_connection_checking.CopyToIfSet(
1125 &params->enable_spdy_ping_based_connection_checking);
1126 globals.spdy_default_protocol.CopyToIfSet(
1127 &params->spdy_default_protocol);
1128 params->next_protos = globals.next_protos;
1129 globals.trusted_spdy_proxy.CopyToIfSet(&params->trusted_spdy_proxy);
1130 params->forced_spdy_exclusions = globals.forced_spdy_exclusions;
1131 globals.use_alternate_protocols.CopyToIfSet(
1132 &params->use_alternate_protocols);
1133 globals.alternative_service_probability_threshold.CopyToIfSet(
1134 &params->alternative_service_probability_threshold);
1136 globals.enable_quic.CopyToIfSet(&params->enable_quic);
1137 globals.enable_insecure_quic.CopyToIfSet(&params->enable_insecure_quic);
1138 globals.enable_quic_for_proxies.CopyToIfSet(&params->enable_quic_for_proxies);
1139 globals.quic_always_require_handshake_confirmation.CopyToIfSet(
1140 &params->quic_always_require_handshake_confirmation);
1141 globals.quic_disable_connection_pooling.CopyToIfSet(
1142 &params->quic_disable_connection_pooling);
1143 globals.quic_load_server_info_timeout_srtt_multiplier.CopyToIfSet(
1144 &params->quic_load_server_info_timeout_srtt_multiplier);
1145 globals.quic_enable_connection_racing.CopyToIfSet(
1146 &params->quic_enable_connection_racing);
1147 globals.quic_enable_non_blocking_io.CopyToIfSet(
1148 &params->quic_enable_non_blocking_io);
1149 globals.quic_prefer_aes.CopyToIfSet(&params->quic_prefer_aes);
1150 globals.quic_disable_disk_cache.CopyToIfSet(
1151 &params->quic_disable_disk_cache);
1152 globals.quic_max_number_of_lossy_connections.CopyToIfSet(
1153 &params->quic_max_number_of_lossy_connections);
1154 globals.quic_packet_loss_threshold.CopyToIfSet(
1155 &params->quic_packet_loss_threshold);
1156 globals.quic_socket_receive_buffer_size.CopyToIfSet(
1157 &params->quic_socket_receive_buffer_size);
1158 globals.enable_quic_port_selection.CopyToIfSet(
1159 &params->enable_quic_port_selection);
1160 globals.quic_max_packet_length.CopyToIfSet(&params->quic_max_packet_length);
1161 globals.quic_user_agent_id.CopyToIfSet(&params->quic_user_agent_id);
1162 globals.quic_supported_versions.CopyToIfSet(
1163 &params->quic_supported_versions);
1164 params->quic_connection_options = globals.quic_connection_options;
1166 globals.origin_to_force_quic_on.CopyToIfSet(
1167 &params->origin_to_force_quic_on);
1168 params->enable_user_alternate_protocol_ports =
1169 globals.enable_user_alternate_protocol_ports;
1172 base::TimeTicks IOThread::creation_time() const {
1173 return creation_time_;
1176 net::SSLConfigService* IOThread::GetSSLConfigService() {
1177 return ssl_config_service_manager_->Get();
1180 void IOThread::ChangedToOnTheRecordOnIOThread() {
1181 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1183 // Clear the host cache to avoid showing entries from the OTR session
1184 // in about:net-internals.
1185 ClearHostCache();
1188 void IOThread::InitSystemRequestContext() {
1189 if (system_url_request_context_getter_.get())
1190 return;
1191 // If we're in unit_tests, IOThread may not be run.
1192 if (!BrowserThread::IsMessageLoopValid(BrowserThread::IO))
1193 return;
1194 system_proxy_config_service_.reset(
1195 ProxyServiceFactory::CreateProxyConfigService(
1196 pref_proxy_config_tracker_.get()));
1197 system_url_request_context_getter_ =
1198 new SystemURLRequestContextGetter(this);
1199 // Safe to post an unretained this pointer, since IOThread is
1200 // guaranteed to outlive the IO BrowserThread.
1201 BrowserThread::PostTask(
1202 BrowserThread::IO,
1203 FROM_HERE,
1204 base::Bind(&IOThread::InitSystemRequestContextOnIOThread,
1205 base::Unretained(this)));
1208 void IOThread::InitSystemRequestContextOnIOThread() {
1209 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1210 DCHECK(!globals_->system_proxy_service.get());
1211 DCHECK(system_proxy_config_service_.get());
1213 const base::CommandLine& command_line =
1214 *base::CommandLine::ForCurrentProcess();
1215 globals_->system_proxy_service.reset(
1216 ProxyServiceFactory::CreateProxyService(
1217 net_log_,
1218 globals_->proxy_script_fetcher_context.get(),
1219 globals_->system_network_delegate.get(),
1220 system_proxy_config_service_.release(),
1221 command_line,
1222 quick_check_enabled_.GetValue()));
1224 net::HttpNetworkSession::Params system_params;
1225 InitializeNetworkSessionParams(&system_params);
1226 system_params.net_log = net_log_;
1227 system_params.proxy_service = globals_->system_proxy_service.get();
1229 globals_->system_http_transaction_factory.reset(
1230 new net::HttpNetworkLayer(
1231 new net::HttpNetworkSession(system_params)));
1232 globals_->system_url_request_job_factory.reset(
1233 new net::URLRequestJobFactoryImpl());
1234 globals_->system_request_context.reset(
1235 ConstructSystemRequestContext(globals_, net_log_));
1236 globals_->system_request_context->set_ssl_config_service(
1237 globals_->ssl_config_service.get());
1238 globals_->system_request_context->set_http_server_properties(
1239 globals_->http_server_properties->GetWeakPtr());
1242 void IOThread::UpdateDnsClientEnabled() {
1243 globals()->host_resolver->SetDnsClientEnabled(*dns_client_enabled_);
1246 void IOThread::ConfigureQuic(const base::CommandLine& command_line) {
1247 // Always fetch the field trial group to ensure it is reported correctly.
1248 // The command line flags will be associated with a group that is reported
1249 // so long as trial is actually queried.
1250 std::string group =
1251 base::FieldTrialList::FindFullName(kQuicFieldTrialName);
1252 VariationParameters params;
1253 if (!variations::GetVariationParams(kQuicFieldTrialName, &params)) {
1254 params.clear();
1257 ConfigureQuicGlobals(command_line, group, params, is_quic_allowed_by_policy_,
1258 globals_);
1261 // static
1262 void IOThread::ConfigureQuicGlobals(
1263 const base::CommandLine& command_line,
1264 base::StringPiece quic_trial_group,
1265 const VariationParameters& quic_trial_params,
1266 bool quic_allowed_by_policy,
1267 IOThread::Globals* globals) {
1268 bool enable_quic = ShouldEnableQuic(command_line, quic_trial_group,
1269 quic_allowed_by_policy);
1270 globals->enable_quic.set(enable_quic);
1271 bool enable_quic_for_proxies = ShouldEnableQuicForProxies(
1272 command_line, quic_trial_group, quic_allowed_by_policy);
1273 globals->enable_quic_for_proxies.set(enable_quic_for_proxies);
1274 if (enable_quic) {
1275 globals->enable_insecure_quic.set(
1276 ShouldEnableInsecureQuic(command_line, quic_trial_params));
1277 globals->quic_always_require_handshake_confirmation.set(
1278 ShouldQuicAlwaysRequireHandshakeConfirmation(quic_trial_params));
1279 globals->quic_disable_connection_pooling.set(
1280 ShouldQuicDisableConnectionPooling(quic_trial_params));
1281 int receive_buffer_size = GetQuicSocketReceiveBufferSize(quic_trial_params);
1282 if (receive_buffer_size != 0) {
1283 globals->quic_socket_receive_buffer_size.set(receive_buffer_size);
1285 float load_server_info_timeout_srtt_multiplier =
1286 GetQuicLoadServerInfoTimeoutSrttMultiplier(quic_trial_params);
1287 if (load_server_info_timeout_srtt_multiplier != 0) {
1288 globals->quic_load_server_info_timeout_srtt_multiplier.set(
1289 load_server_info_timeout_srtt_multiplier);
1291 globals->quic_enable_connection_racing.set(
1292 ShouldQuicEnableConnectionRacing(quic_trial_params));
1293 globals->quic_enable_non_blocking_io.set(
1294 ShouldQuicEnableNonBlockingIO(quic_trial_params));
1295 globals->quic_disable_disk_cache.set(
1296 ShouldQuicDisableDiskCache(quic_trial_params));
1297 globals->quic_prefer_aes.set(
1298 ShouldQuicPreferAes(quic_trial_params));
1299 int max_number_of_lossy_connections = GetQuicMaxNumberOfLossyConnections(
1300 quic_trial_params);
1301 if (max_number_of_lossy_connections != 0) {
1302 globals->quic_max_number_of_lossy_connections.set(
1303 max_number_of_lossy_connections);
1305 float packet_loss_threshold = GetQuicPacketLossThreshold(quic_trial_params);
1306 if (packet_loss_threshold != 0)
1307 globals->quic_packet_loss_threshold.set(packet_loss_threshold);
1308 globals->enable_quic_port_selection.set(
1309 ShouldEnableQuicPortSelection(command_line));
1310 globals->quic_connection_options =
1311 GetQuicConnectionOptions(command_line, quic_trial_params);
1314 size_t max_packet_length = GetQuicMaxPacketLength(command_line,
1315 quic_trial_params);
1316 if (max_packet_length != 0) {
1317 globals->quic_max_packet_length.set(max_packet_length);
1320 std::string quic_user_agent_id = chrome::GetChannelString();
1321 if (!quic_user_agent_id.empty())
1322 quic_user_agent_id.push_back(' ');
1323 quic_user_agent_id.append(
1324 version_info::GetProductNameAndVersionForUserAgent());
1325 quic_user_agent_id.push_back(' ');
1326 quic_user_agent_id.append(content::BuildOSCpuInfo());
1327 globals->quic_user_agent_id.set(quic_user_agent_id);
1329 net::QuicVersion version = GetQuicVersion(command_line, quic_trial_params);
1330 if (version != net::QUIC_VERSION_UNSUPPORTED) {
1331 net::QuicVersionVector supported_versions;
1332 supported_versions.push_back(version);
1333 globals->quic_supported_versions.set(supported_versions);
1336 double threshold = GetAlternativeProtocolProbabilityThreshold(
1337 command_line, quic_trial_params);
1338 if (threshold >=0 && threshold <= 1) {
1339 globals->alternative_service_probability_threshold.set(threshold);
1340 globals->http_server_properties->SetAlternativeServiceProbabilityThreshold(
1341 threshold);
1344 if (command_line.HasSwitch(switches::kOriginToForceQuicOn)) {
1345 net::HostPortPair quic_origin =
1346 net::HostPortPair::FromString(
1347 command_line.GetSwitchValueASCII(switches::kOriginToForceQuicOn));
1348 if (!quic_origin.IsEmpty()) {
1349 globals->origin_to_force_quic_on.set(quic_origin);
1354 bool IOThread::ShouldEnableQuic(const base::CommandLine& command_line,
1355 base::StringPiece quic_trial_group,
1356 bool quic_allowed_by_policy) {
1357 if (command_line.HasSwitch(switches::kDisableQuic) || !quic_allowed_by_policy)
1358 return false;
1360 if (command_line.HasSwitch(switches::kEnableQuic))
1361 return true;
1363 return quic_trial_group.starts_with(kQuicFieldTrialEnabledGroupName) ||
1364 quic_trial_group.starts_with(kQuicFieldTrialHttpsEnabledGroupName);
1367 // static
1368 bool IOThread::ShouldEnableQuicForProxies(const base::CommandLine& command_line,
1369 base::StringPiece quic_trial_group,
1370 bool quic_allowed_by_policy) {
1371 return ShouldEnableQuic(
1372 command_line, quic_trial_group, quic_allowed_by_policy) ||
1373 ShouldEnableQuicForDataReductionProxy();
1376 // static
1377 bool IOThread::ShouldEnableQuicForDataReductionProxy() {
1378 const base::CommandLine& command_line =
1379 *base::CommandLine::ForCurrentProcess();
1381 if (command_line.HasSwitch(switches::kDisableQuic))
1382 return false;
1384 return data_reduction_proxy::params::IsIncludedInQuicFieldTrial();
1387 // static
1388 bool IOThread::ShouldEnableInsecureQuic(
1389 const base::CommandLine& command_line,
1390 const VariationParameters& quic_trial_params) {
1391 if (command_line.HasSwitch(switches::kEnableInsecureQuic))
1392 return true;
1394 return base::LowerCaseEqualsASCII(
1395 GetVariationParam(quic_trial_params, "enable_insecure_quic"),
1396 "true");
1399 bool IOThread::ShouldEnableQuicPortSelection(
1400 const base::CommandLine& command_line) {
1401 if (command_line.HasSwitch(switches::kDisableQuicPortSelection))
1402 return false;
1404 if (command_line.HasSwitch(switches::kEnableQuicPortSelection))
1405 return true;
1407 return false; // Default to disabling port selection on all channels.
1410 net::QuicTagVector IOThread::GetQuicConnectionOptions(
1411 const base::CommandLine& command_line,
1412 const VariationParameters& quic_trial_params) {
1413 if (command_line.HasSwitch(switches::kQuicConnectionOptions)) {
1414 return net::QuicUtils::ParseQuicConnectionOptions(
1415 command_line.GetSwitchValueASCII(switches::kQuicConnectionOptions));
1418 VariationParameters::const_iterator it =
1419 quic_trial_params.find("connection_options");
1420 if (it == quic_trial_params.end()) {
1421 return net::QuicTagVector();
1424 return net::QuicUtils::ParseQuicConnectionOptions(it->second);
1427 // static
1428 double IOThread::GetAlternativeProtocolProbabilityThreshold(
1429 const base::CommandLine& command_line,
1430 const VariationParameters& quic_trial_params) {
1431 double value;
1432 if (command_line.HasSwitch(
1433 switches::kAlternativeServiceProbabilityThreshold)) {
1434 if (base::StringToDouble(
1435 command_line.GetSwitchValueASCII(
1436 switches::kAlternativeServiceProbabilityThreshold),
1437 &value)) {
1438 return value;
1441 if (command_line.HasSwitch(switches::kEnableQuic)) {
1442 return 0;
1444 // TODO(bnc): Remove when new parameter name rolls out and server
1445 // configuration is changed.
1446 if (base::StringToDouble(
1447 GetVariationParam(quic_trial_params,
1448 "alternate_protocol_probability_threshold"),
1449 &value)) {
1450 return value;
1452 if (base::StringToDouble(
1453 GetVariationParam(quic_trial_params,
1454 "alternative_service_probability_threshold"),
1455 &value)) {
1456 return value;
1458 return -1;
1461 // static
1462 bool IOThread::ShouldQuicAlwaysRequireHandshakeConfirmation(
1463 const VariationParameters& quic_trial_params) {
1464 return base::LowerCaseEqualsASCII(
1465 GetVariationParam(quic_trial_params,
1466 "always_require_handshake_confirmation"),
1467 "true");
1470 // static
1471 bool IOThread::ShouldQuicDisableConnectionPooling(
1472 const VariationParameters& quic_trial_params) {
1473 return base::LowerCaseEqualsASCII(
1474 GetVariationParam(quic_trial_params, "disable_connection_pooling"),
1475 "true");
1478 // static
1479 float IOThread::GetQuicLoadServerInfoTimeoutSrttMultiplier(
1480 const VariationParameters& quic_trial_params) {
1481 double value;
1482 if (base::StringToDouble(GetVariationParam(quic_trial_params,
1483 "load_server_info_time_to_srtt"),
1484 &value)) {
1485 return (float)value;
1487 return 0.0f;
1490 // static
1491 bool IOThread::ShouldQuicEnableConnectionRacing(
1492 const VariationParameters& quic_trial_params) {
1493 return base::LowerCaseEqualsASCII(
1494 GetVariationParam(quic_trial_params, "enable_connection_racing"),
1495 "true");
1498 // static
1499 bool IOThread::ShouldQuicEnableNonBlockingIO(
1500 const VariationParameters& quic_trial_params) {
1501 return base::LowerCaseEqualsASCII(
1502 GetVariationParam(quic_trial_params, "enable_non_blocking_io"),
1503 "true");
1506 // static
1507 bool IOThread::ShouldQuicDisableDiskCache(
1508 const VariationParameters& quic_trial_params) {
1509 return base::LowerCaseEqualsASCII(
1510 GetVariationParam(quic_trial_params, "disable_disk_cache"), "true");
1513 // static
1514 bool IOThread::ShouldQuicPreferAes(
1515 const VariationParameters& quic_trial_params) {
1516 return base::LowerCaseEqualsASCII(
1517 GetVariationParam(quic_trial_params, "prefer_aes"), "true");
1520 // static
1521 int IOThread::GetQuicMaxNumberOfLossyConnections(
1522 const VariationParameters& quic_trial_params) {
1523 int value;
1524 if (base::StringToInt(GetVariationParam(quic_trial_params,
1525 "max_number_of_lossy_connections"),
1526 &value)) {
1527 return value;
1529 return 0;
1532 // static
1533 float IOThread::GetQuicPacketLossThreshold(
1534 const VariationParameters& quic_trial_params) {
1535 double value;
1536 if (base::StringToDouble(GetVariationParam(quic_trial_params,
1537 "packet_loss_threshold"),
1538 &value)) {
1539 return (float)value;
1541 return 0.0f;
1544 // static
1545 int IOThread::GetQuicSocketReceiveBufferSize(
1546 const VariationParameters& quic_trial_params) {
1547 int value;
1548 if (base::StringToInt(GetVariationParam(quic_trial_params,
1549 "receive_buffer_size"),
1550 &value)) {
1551 return value;
1553 return 0;
1556 // static
1557 size_t IOThread::GetQuicMaxPacketLength(
1558 const base::CommandLine& command_line,
1559 const VariationParameters& quic_trial_params) {
1560 if (command_line.HasSwitch(switches::kQuicMaxPacketLength)) {
1561 unsigned value;
1562 if (!base::StringToUint(
1563 command_line.GetSwitchValueASCII(switches::kQuicMaxPacketLength),
1564 &value)) {
1565 return 0;
1567 return value;
1570 unsigned value;
1571 if (base::StringToUint(GetVariationParam(quic_trial_params,
1572 "max_packet_length"),
1573 &value)) {
1574 return value;
1576 return 0;
1579 // static
1580 net::QuicVersion IOThread::GetQuicVersion(
1581 const base::CommandLine& command_line,
1582 const VariationParameters& quic_trial_params) {
1583 if (command_line.HasSwitch(switches::kQuicVersion)) {
1584 return ParseQuicVersion(
1585 command_line.GetSwitchValueASCII(switches::kQuicVersion));
1588 return ParseQuicVersion(GetVariationParam(quic_trial_params, "quic_version"));
1591 // static
1592 net::QuicVersion IOThread::ParseQuicVersion(const std::string& quic_version) {
1593 net::QuicVersionVector supported_versions = net::QuicSupportedVersions();
1594 for (size_t i = 0; i < supported_versions.size(); ++i) {
1595 net::QuicVersion version = supported_versions[i];
1596 if (net::QuicVersionToString(version) == quic_version) {
1597 return version;
1601 return net::QUIC_VERSION_UNSUPPORTED;