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