Adding instrumentation to locate the source of jankiness
[chromium-blink-merge.git] / chrome / browser / io_thread.cc
blobf6ae5163946e5d0e8b5eca5d5224624de62b0fd0
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/debug/trace_event.h"
16 #include "base/logging.h"
17 #include "base/metrics/field_trial.h"
18 #include "base/prefs/pref_registry_simple.h"
19 #include "base/prefs/pref_service.h"
20 #include "base/stl_util.h"
21 #include "base/strings/string_number_conversions.h"
22 #include "base/strings/string_split.h"
23 #include "base/strings/string_util.h"
24 #include "base/threading/sequenced_worker_pool.h"
25 #include "base/threading/thread.h"
26 #include "base/threading/worker_pool.h"
27 #include "base/time/time.h"
28 #include "build/build_config.h"
29 #include "chrome/browser/browser_process.h"
30 #include "chrome/browser/net/async_dns_field_trial.h"
31 #include "chrome/browser/net/chrome_net_log.h"
32 #include "chrome/browser/net/chrome_network_delegate.h"
33 #include "chrome/browser/net/connect_interceptor.h"
34 #include "chrome/browser/net/dns_probe_service.h"
35 #include "chrome/browser/net/pref_proxy_config_tracker.h"
36 #include "chrome/browser/net/proxy_service_factory.h"
37 #include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings.h"
38 #include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings_factory.h"
39 #include "chrome/common/chrome_content_client.h"
40 #include "chrome/common/chrome_switches.h"
41 #include "chrome/common/chrome_version_info.h"
42 #include "chrome/common/pref_names.h"
43 #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_auth_request_handler.h"
44 #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_delegate.h"
45 #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_params.h"
46 #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_prefs.h"
47 #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_protocol.h"
48 #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_settings.h"
49 #include "components/policy/core/common/policy_service.h"
50 #include "components/variations/variations_associated_data.h"
51 #include "content/public/browser/browser_thread.h"
52 #include "content/public/browser/cookie_store_factory.h"
53 #include "net/base/host_mapping_rules.h"
54 #include "net/base/net_util.h"
55 #include "net/cert/cert_verifier.h"
56 #include "net/cert/cert_verify_proc.h"
57 #include "net/cert/ct_known_logs.h"
58 #include "net/cert/ct_log_verifier.h"
59 #include "net/cert/ct_verifier.h"
60 #include "net/cert/multi_log_ct_verifier.h"
61 #include "net/cert/multi_threaded_cert_verifier.h"
62 #include "net/cookies/cookie_store.h"
63 #include "net/dns/host_cache.h"
64 #include "net/dns/host_resolver.h"
65 #include "net/dns/mapped_host_resolver.h"
66 #include "net/ftp/ftp_network_layer.h"
67 #include "net/http/http_auth_filter.h"
68 #include "net/http/http_auth_handler_factory.h"
69 #include "net/http/http_network_layer.h"
70 #include "net/http/http_server_properties_impl.h"
71 #include "net/proxy/proxy_config_service.h"
72 #include "net/proxy/proxy_script_fetcher_impl.h"
73 #include "net/proxy/proxy_service.h"
74 #include "net/quic/crypto/crypto_protocol.h"
75 #include "net/quic/quic_protocol.h"
76 #include "net/socket/tcp_client_socket.h"
77 #include "net/spdy/spdy_session.h"
78 #include "net/ssl/channel_id_service.h"
79 #include "net/ssl/default_channel_id_store.h"
80 #include "net/url_request/data_protocol_handler.h"
81 #include "net/url_request/file_protocol_handler.h"
82 #include "net/url_request/ftp_protocol_handler.h"
83 #include "net/url_request/static_http_user_agent_settings.h"
84 #include "net/url_request/url_fetcher.h"
85 #include "net/url_request/url_request_context.h"
86 #include "net/url_request/url_request_context_getter.h"
87 #include "net/url_request/url_request_job_factory_impl.h"
88 #include "net/url_request/url_request_throttler_manager.h"
89 #include "url/url_constants.h"
91 #if defined(ENABLE_CONFIGURATION_POLICY)
92 #include "policy/policy_constants.h"
93 #endif
95 #if defined(ENABLE_EXTENSIONS)
96 #include "chrome/browser/extensions/event_router_forwarder.h"
97 #endif
99 #if defined(USE_NSS) || defined(OS_IOS)
100 #include "net/ocsp/nss_ocsp.h"
101 #endif
103 #if defined(OS_CHROMEOS)
104 #include "chrome/browser/chromeos/net/cert_verify_proc_chromeos.h"
105 #include "chromeos/network/host_resolver_impl_chromeos.h"
106 #endif
108 using content::BrowserThread;
110 class SafeBrowsingURLRequestContext;
112 // The IOThread object must outlive any tasks posted to the IO thread before the
113 // Quit task, so base::Bind() calls are not refcounted.
115 namespace {
117 const char kTCPFastOpenFieldTrialName[] = "TCPFastOpen";
118 const char kTCPFastOpenHttpsEnabledGroupName[] = "HttpsEnabled";
120 const char kQuicFieldTrialName[] = "QUIC";
121 const char kQuicFieldTrialEnabledGroupName[] = "Enabled";
122 const char kQuicFieldTrialHttpsEnabledGroupName[] = "HttpsEnabled";
123 const char kQuicFieldTrialPacketLengthSuffix[] = "BytePackets";
124 const char kQuicFieldTrialPacingSuffix[] = "WithPacing";
126 // The SPDY trial composes two different trial plus control groups:
127 // * A "holdback" group with SPDY disabled, and corresponding control
128 // (SPDY/3.1). The primary purpose of the holdback group is to encourage site
129 // operators to do feature detection rather than UA-sniffing. As such, this
130 // trial runs continuously.
131 // * A SPDY/4 experiment, for SPDY/4 (aka HTTP/2) vs SPDY/3.1 comparisons and
132 // eventual SPDY/4 deployment.
133 const char kSpdyFieldTrialName[] = "SPDY";
134 const char kSpdyFieldTrialHoldbackGroupName[] = "SpdyDisabled";
135 const char kSpdyFieldTrialHoldbackControlGroupName[] = "Control";
136 const char kSpdyFieldTrialSpdy4GroupName[] = "Spdy4Enabled";
137 const char kSpdyFieldTrialSpdy4ControlGroupName[] = "Spdy4Control";
139 // Field trial for Cache-Control: stale-while-revalidate directive.
140 const char kStaleWhileRevalidateFieldTrialName[] = "StaleWhileRevalidate";
142 #if defined(OS_MACOSX) && !defined(OS_IOS)
143 void ObserveKeychainEvents() {
144 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
145 net::CertDatabase::GetInstance()->SetMessageLoopForKeychainEvents();
147 #endif
149 // Used for the "system" URLRequestContext.
150 class SystemURLRequestContext : public net::URLRequestContext {
151 public:
152 SystemURLRequestContext() {
153 #if defined(USE_NSS) || defined(OS_IOS)
154 net::SetURLRequestContextForNSSHttpIO(this);
155 #endif
158 private:
159 virtual ~SystemURLRequestContext() {
160 AssertNoURLRequests();
161 #if defined(USE_NSS) || defined(OS_IOS)
162 net::SetURLRequestContextForNSSHttpIO(NULL);
163 #endif
167 scoped_ptr<net::HostResolver> CreateGlobalHostResolver(net::NetLog* net_log) {
168 TRACE_EVENT0("startup", "IOThread::CreateGlobalHostResolver");
169 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
171 net::HostResolver::Options options;
173 // Use the concurrency override from the command-line, if any.
174 if (command_line.HasSwitch(switches::kHostResolverParallelism)) {
175 std::string s =
176 command_line.GetSwitchValueASCII(switches::kHostResolverParallelism);
178 // Parse the switch (it should be a positive integer formatted as decimal).
179 int n;
180 if (base::StringToInt(s, &n) && n > 0) {
181 options.max_concurrent_resolves = static_cast<size_t>(n);
182 } else {
183 LOG(ERROR) << "Invalid switch for host resolver parallelism: " << s;
187 // Use the retry attempts override from the command-line, if any.
188 if (command_line.HasSwitch(switches::kHostResolverRetryAttempts)) {
189 std::string s =
190 command_line.GetSwitchValueASCII(switches::kHostResolverRetryAttempts);
191 // Parse the switch (it should be a non-negative integer).
192 int n;
193 if (base::StringToInt(s, &n) && n >= 0) {
194 options.max_retry_attempts = static_cast<size_t>(n);
195 } else {
196 LOG(ERROR) << "Invalid switch for host resolver retry attempts: " << s;
200 scoped_ptr<net::HostResolver> global_host_resolver;
201 #if defined OS_CHROMEOS
202 global_host_resolver =
203 chromeos::HostResolverImplChromeOS::CreateSystemResolver(options,
204 net_log);
205 #else
206 global_host_resolver =
207 net::HostResolver::CreateSystemResolver(options, net_log);
208 #endif
210 // Determine if we should disable IPv6 support.
211 if (command_line.HasSwitch(switches::kEnableIPv6)) {
212 // Disable IPv6 probing.
213 global_host_resolver->SetDefaultAddressFamily(
214 net::ADDRESS_FAMILY_UNSPECIFIED);
215 } else if (command_line.HasSwitch(switches::kDisableIPv6)) {
216 global_host_resolver->SetDefaultAddressFamily(net::ADDRESS_FAMILY_IPV4);
219 // If hostname remappings were specified on the command-line, layer these
220 // rules on top of the real host resolver. This allows forwarding all requests
221 // through a designated test server.
222 if (!command_line.HasSwitch(switches::kHostResolverRules))
223 return global_host_resolver.Pass();
225 scoped_ptr<net::MappedHostResolver> remapped_resolver(
226 new net::MappedHostResolver(global_host_resolver.Pass()));
227 remapped_resolver->SetRulesFromString(
228 command_line.GetSwitchValueASCII(switches::kHostResolverRules));
229 return remapped_resolver.Pass();
232 // TODO(willchan): Remove proxy script fetcher context since it's not necessary
233 // now that I got rid of refcounting URLRequestContexts.
234 // See IOThread::Globals for details.
235 net::URLRequestContext*
236 ConstructProxyScriptFetcherContext(IOThread::Globals* globals,
237 net::NetLog* net_log) {
238 net::URLRequestContext* context = new net::URLRequestContext;
239 context->set_net_log(net_log);
240 context->set_host_resolver(globals->host_resolver.get());
241 context->set_cert_verifier(globals->cert_verifier.get());
242 context->set_transport_security_state(
243 globals->transport_security_state.get());
244 context->set_cert_transparency_verifier(
245 globals->cert_transparency_verifier.get());
246 context->set_http_auth_handler_factory(
247 globals->http_auth_handler_factory.get());
248 context->set_proxy_service(globals->proxy_script_fetcher_proxy_service.get());
249 context->set_http_transaction_factory(
250 globals->proxy_script_fetcher_http_transaction_factory.get());
251 context->set_job_factory(
252 globals->proxy_script_fetcher_url_request_job_factory.get());
253 context->set_cookie_store(globals->system_cookie_store.get());
254 context->set_channel_id_service(
255 globals->system_channel_id_service.get());
256 context->set_network_delegate(globals->system_network_delegate.get());
257 context->set_http_user_agent_settings(
258 globals->http_user_agent_settings.get());
259 // TODO(rtenneti): We should probably use HttpServerPropertiesManager for the
260 // system URLRequestContext too. There's no reason this should be tied to a
261 // profile.
262 return context;
265 net::URLRequestContext*
266 ConstructSystemRequestContext(IOThread::Globals* globals,
267 net::NetLog* net_log) {
268 net::URLRequestContext* context = new SystemURLRequestContext;
269 context->set_net_log(net_log);
270 context->set_host_resolver(globals->host_resolver.get());
271 context->set_cert_verifier(globals->cert_verifier.get());
272 context->set_transport_security_state(
273 globals->transport_security_state.get());
274 context->set_cert_transparency_verifier(
275 globals->cert_transparency_verifier.get());
276 context->set_http_auth_handler_factory(
277 globals->http_auth_handler_factory.get());
278 context->set_proxy_service(globals->system_proxy_service.get());
279 context->set_http_transaction_factory(
280 globals->system_http_transaction_factory.get());
281 context->set_job_factory(globals->system_url_request_job_factory.get());
282 context->set_cookie_store(globals->system_cookie_store.get());
283 context->set_channel_id_service(
284 globals->system_channel_id_service.get());
285 context->set_throttler_manager(globals->throttler_manager.get());
286 context->set_network_delegate(globals->system_network_delegate.get());
287 context->set_http_user_agent_settings(
288 globals->http_user_agent_settings.get());
289 return context;
292 int GetSwitchValueAsInt(const CommandLine& command_line,
293 const std::string& switch_name) {
294 int value;
295 if (!base::StringToInt(command_line.GetSwitchValueASCII(switch_name),
296 &value)) {
297 return 0;
299 return value;
302 // Returns the value associated with |key| in |params| or "" if the
303 // key is not present in the map.
304 const std::string& GetVariationParam(
305 const std::map<std::string, std::string>& params,
306 const std::string& key) {
307 std::map<std::string, std::string>::const_iterator it = params.find(key);
308 if (it == params.end())
309 return base::EmptyString();
311 return it->second;
314 } // namespace
316 class IOThread::LoggingNetworkChangeObserver
317 : public net::NetworkChangeNotifier::IPAddressObserver,
318 public net::NetworkChangeNotifier::ConnectionTypeObserver,
319 public net::NetworkChangeNotifier::NetworkChangeObserver {
320 public:
321 // |net_log| must remain valid throughout our lifetime.
322 explicit LoggingNetworkChangeObserver(net::NetLog* net_log)
323 : net_log_(net_log) {
324 net::NetworkChangeNotifier::AddIPAddressObserver(this);
325 net::NetworkChangeNotifier::AddConnectionTypeObserver(this);
326 net::NetworkChangeNotifier::AddNetworkChangeObserver(this);
329 virtual ~LoggingNetworkChangeObserver() {
330 net::NetworkChangeNotifier::RemoveIPAddressObserver(this);
331 net::NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
332 net::NetworkChangeNotifier::RemoveNetworkChangeObserver(this);
335 // NetworkChangeNotifier::IPAddressObserver implementation.
336 virtual void OnIPAddressChanged() override {
337 VLOG(1) << "Observed a change to the network IP addresses";
339 net_log_->AddGlobalEntry(net::NetLog::TYPE_NETWORK_IP_ADDRESSES_CHANGED);
342 // NetworkChangeNotifier::ConnectionTypeObserver implementation.
343 virtual void OnConnectionTypeChanged(
344 net::NetworkChangeNotifier::ConnectionType type) override {
345 std::string type_as_string =
346 net::NetworkChangeNotifier::ConnectionTypeToString(type);
348 VLOG(1) << "Observed a change to network connectivity state "
349 << type_as_string;
351 net_log_->AddGlobalEntry(
352 net::NetLog::TYPE_NETWORK_CONNECTIVITY_CHANGED,
353 net::NetLog::StringCallback("new_connection_type", &type_as_string));
356 // NetworkChangeNotifier::NetworkChangeObserver implementation.
357 virtual void OnNetworkChanged(
358 net::NetworkChangeNotifier::ConnectionType type) override {
359 std::string type_as_string =
360 net::NetworkChangeNotifier::ConnectionTypeToString(type);
362 VLOG(1) << "Observed a network change to state " << type_as_string;
364 net_log_->AddGlobalEntry(
365 net::NetLog::TYPE_NETWORK_CHANGED,
366 net::NetLog::StringCallback("new_connection_type", &type_as_string));
369 private:
370 net::NetLog* net_log_;
371 DISALLOW_COPY_AND_ASSIGN(LoggingNetworkChangeObserver);
374 class SystemURLRequestContextGetter : public net::URLRequestContextGetter {
375 public:
376 explicit SystemURLRequestContextGetter(IOThread* io_thread);
378 // Implementation for net::UrlRequestContextGetter.
379 virtual net::URLRequestContext* GetURLRequestContext() override;
380 virtual scoped_refptr<base::SingleThreadTaskRunner>
381 GetNetworkTaskRunner() const override;
383 protected:
384 virtual ~SystemURLRequestContextGetter();
386 private:
387 IOThread* const io_thread_; // Weak pointer, owned by BrowserProcess.
388 scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_;
390 base::debug::LeakTracker<SystemURLRequestContextGetter> leak_tracker_;
393 SystemURLRequestContextGetter::SystemURLRequestContextGetter(
394 IOThread* io_thread)
395 : io_thread_(io_thread),
396 network_task_runner_(
397 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)) {
400 SystemURLRequestContextGetter::~SystemURLRequestContextGetter() {}
402 net::URLRequestContext* SystemURLRequestContextGetter::GetURLRequestContext() {
403 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
404 DCHECK(io_thread_->globals()->system_request_context.get());
406 return io_thread_->globals()->system_request_context.get();
409 scoped_refptr<base::SingleThreadTaskRunner>
410 SystemURLRequestContextGetter::GetNetworkTaskRunner() const {
411 return network_task_runner_;
414 IOThread::Globals::
415 SystemRequestContextLeakChecker::SystemRequestContextLeakChecker(
416 Globals* globals)
417 : globals_(globals) {
418 DCHECK(globals_);
421 IOThread::Globals::
422 SystemRequestContextLeakChecker::~SystemRequestContextLeakChecker() {
423 if (globals_->system_request_context.get())
424 globals_->system_request_context->AssertNoURLRequests();
427 IOThread::Globals::Globals()
428 : system_request_context_leak_checker(this),
429 enable_ssl_connect_job_waiting(false),
430 ignore_certificate_errors(false),
431 use_stale_while_revalidate(false),
432 testing_fixed_http_port(0),
433 testing_fixed_https_port(0),
434 enable_user_alternate_protocol_ports(false) {
437 IOThread::Globals::~Globals() {}
439 // |local_state| is passed in explicitly in order to (1) reduce implicit
440 // dependencies and (2) make IOThread more flexible for testing.
441 IOThread::IOThread(
442 PrefService* local_state,
443 policy::PolicyService* policy_service,
444 ChromeNetLog* net_log,
445 extensions::EventRouterForwarder* extension_event_router_forwarder)
446 : net_log_(net_log),
447 #if defined(ENABLE_EXTENSIONS)
448 extension_event_router_forwarder_(extension_event_router_forwarder),
449 #endif
450 globals_(NULL),
451 is_spdy_disabled_by_policy_(false),
452 creation_time_(base::TimeTicks::Now()),
453 weak_factory_(this) {
454 auth_schemes_ = local_state->GetString(prefs::kAuthSchemes);
455 negotiate_disable_cname_lookup_ = local_state->GetBoolean(
456 prefs::kDisableAuthNegotiateCnameLookup);
457 negotiate_enable_port_ = local_state->GetBoolean(
458 prefs::kEnableAuthNegotiatePort);
459 auth_server_whitelist_ = local_state->GetString(prefs::kAuthServerWhitelist);
460 auth_delegate_whitelist_ = local_state->GetString(
461 prefs::kAuthNegotiateDelegateWhitelist);
462 gssapi_library_name_ = local_state->GetString(prefs::kGSSAPILibraryName);
463 pref_proxy_config_tracker_.reset(
464 ProxyServiceFactory::CreatePrefProxyConfigTrackerOfLocalState(
465 local_state));
466 ChromeNetworkDelegate::InitializePrefsOnUIThread(
467 &system_enable_referrers_,
468 NULL,
469 NULL,
470 local_state);
471 ssl_config_service_manager_.reset(
472 SSLConfigServiceManager::CreateDefaultManager(local_state));
474 base::Value* dns_client_enabled_default = new base::FundamentalValue(
475 chrome_browser_net::ConfigureAsyncDnsFieldTrial());
476 local_state->SetDefaultPrefValue(prefs::kBuiltInDnsClientEnabled,
477 dns_client_enabled_default);
479 dns_client_enabled_.Init(prefs::kBuiltInDnsClientEnabled,
480 local_state,
481 base::Bind(&IOThread::UpdateDnsClientEnabled,
482 base::Unretained(this)));
483 dns_client_enabled_.MoveToThread(
484 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
486 quick_check_enabled_.Init(prefs::kQuickCheckEnabled,
487 local_state);
488 quick_check_enabled_.MoveToThread(
489 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
491 #if defined(ENABLE_CONFIGURATION_POLICY)
492 is_spdy_disabled_by_policy_ = policy_service->GetPolicies(
493 policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME, std::string())).Get(
494 policy::key::kDisableSpdy) != NULL;
495 #endif // ENABLE_CONFIGURATION_POLICY
497 BrowserThread::SetDelegate(BrowserThread::IO, this);
500 IOThread::~IOThread() {
501 // This isn't needed for production code, but in tests, IOThread may
502 // be multiply constructed.
503 BrowserThread::SetDelegate(BrowserThread::IO, NULL);
505 pref_proxy_config_tracker_->DetachFromPrefService();
506 DCHECK(!globals_);
509 IOThread::Globals* IOThread::globals() {
510 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
511 return globals_;
514 void IOThread::SetGlobalsForTesting(Globals* globals) {
515 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
516 DCHECK(!globals || !globals_);
517 globals_ = globals;
520 ChromeNetLog* IOThread::net_log() {
521 return net_log_;
524 void IOThread::ChangedToOnTheRecord() {
525 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
526 BrowserThread::PostTask(
527 BrowserThread::IO,
528 FROM_HERE,
529 base::Bind(&IOThread::ChangedToOnTheRecordOnIOThread,
530 base::Unretained(this)));
533 net::URLRequestContextGetter* IOThread::system_url_request_context_getter() {
534 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
535 if (!system_url_request_context_getter_.get()) {
536 InitSystemRequestContext();
538 return system_url_request_context_getter_.get();
541 void IOThread::Init() {
542 // Prefer to use InitAsync unless you need initialization to block
543 // the UI thread
546 void IOThread::InitAsync() {
547 TRACE_EVENT0("startup", "IOThread::InitAsync");
548 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
550 #if defined(USE_NSS) || defined(OS_IOS)
551 net::SetMessageLoopForNSSHttpIO();
552 #endif
554 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
556 DCHECK(!globals_);
557 globals_ = new Globals;
559 // Add an observer that will emit network change events to the ChromeNetLog.
560 // Assuming NetworkChangeNotifier dispatches in FIFO order, we should be
561 // logging the network change before other IO thread consumers respond to it.
562 network_change_observer_.reset(
563 new LoggingNetworkChangeObserver(net_log_));
565 // Setup the HistogramWatcher to run on the IO thread.
566 net::NetworkChangeNotifier::InitHistogramWatcher();
568 #if defined(ENABLE_EXTENSIONS)
569 globals_->extension_event_router_forwarder =
570 extension_event_router_forwarder_;
571 #endif
573 ChromeNetworkDelegate* network_delegate =
574 new ChromeNetworkDelegate(extension_event_router_forwarder(),
575 &system_enable_referrers_);
577 if (command_line.HasSwitch(switches::kEnableClientHints))
578 network_delegate->SetEnableClientHints();
580 #if defined(ENABLE_EXTENSIONS)
581 if (command_line.HasSwitch(switches::kDisableExtensionsHttpThrottling))
582 network_delegate->NeverThrottleRequests();
583 #endif
585 globals_->system_network_delegate.reset(network_delegate);
586 globals_->host_resolver = CreateGlobalHostResolver(net_log_);
587 UpdateDnsClientEnabled();
588 #if defined(OS_CHROMEOS)
589 // Creates a CertVerifyProc that doesn't allow any profile-provided certs.
590 globals_->cert_verifier.reset(new net::MultiThreadedCertVerifier(
591 new chromeos::CertVerifyProcChromeOS()));
592 #else
593 globals_->cert_verifier.reset(new net::MultiThreadedCertVerifier(
594 net::CertVerifyProc::CreateDefault()));
595 #endif
597 globals_->transport_security_state.reset(new net::TransportSecurityState());
599 net::MultiLogCTVerifier* ct_verifier = new net::MultiLogCTVerifier();
600 globals_->cert_transparency_verifier.reset(ct_verifier);
602 // Add built-in logs
603 ct_verifier->AddLogs(net::ct::CreateLogVerifiersForKnownLogs());
605 // Add logs from command line
606 if (command_line.HasSwitch(switches::kCertificateTransparencyLog)) {
607 std::string switch_value = command_line.GetSwitchValueASCII(
608 switches::kCertificateTransparencyLog);
609 std::vector<std::string> logs;
610 base::SplitString(switch_value, ',', &logs);
611 for (std::vector<std::string>::iterator it = logs.begin(); it != logs.end();
612 ++it) {
613 const std::string& curr_log = *it;
614 size_t delim_pos = curr_log.find(":");
615 CHECK(delim_pos != std::string::npos)
616 << "CT log description not provided (switch format"
617 " is 'description:base64_key')";
618 std::string log_description(curr_log.substr(0, delim_pos));
619 std::string ct_public_key_data;
620 CHECK(base::Base64Decode(curr_log.substr(delim_pos + 1),
621 &ct_public_key_data))
622 << "Unable to decode CT public key.";
623 scoped_ptr<net::CTLogVerifier> external_log_verifier(
624 net::CTLogVerifier::Create(ct_public_key_data, log_description));
625 CHECK(external_log_verifier) << "Unable to parse CT public key.";
626 VLOG(1) << "Adding log with description " << log_description;
627 ct_verifier->AddLog(external_log_verifier.Pass());
631 globals_->ssl_config_service = GetSSLConfigService();
633 SetupDataReductionProxy(network_delegate);
635 globals_->http_auth_handler_factory.reset(CreateDefaultAuthHandlerFactory(
636 globals_->host_resolver.get()));
637 globals_->http_server_properties.reset(new net::HttpServerPropertiesImpl());
638 // For the ProxyScriptFetcher, we use a direct ProxyService.
639 globals_->proxy_script_fetcher_proxy_service.reset(
640 net::ProxyService::CreateDirectWithNetLog(net_log_));
641 // In-memory cookie store.
642 globals_->system_cookie_store =
643 content::CreateCookieStore(content::CookieStoreConfig());
644 // In-memory channel ID store.
645 globals_->system_channel_id_service.reset(
646 new net::ChannelIDService(
647 new net::DefaultChannelIDStore(NULL),
648 base::WorkerPool::GetTaskRunner(true)));
649 globals_->dns_probe_service.reset(new chrome_browser_net::DnsProbeService());
650 globals_->host_mapping_rules.reset(new net::HostMappingRules());
651 globals_->http_user_agent_settings.reset(
652 new net::StaticHttpUserAgentSettings(std::string(), GetUserAgent()));
653 if (command_line.HasSwitch(switches::kHostRules)) {
654 TRACE_EVENT_BEGIN0("startup", "IOThread::InitAsync:SetRulesFromString");
655 globals_->host_mapping_rules->SetRulesFromString(
656 command_line.GetSwitchValueASCII(switches::kHostRules));
657 TRACE_EVENT_END0("startup", "IOThread::InitAsync:SetRulesFromString");
659 if (command_line.HasSwitch(switches::kEnableSSLConnectJobWaiting))
660 globals_->enable_ssl_connect_job_waiting = true;
661 if (command_line.HasSwitch(switches::kIgnoreCertificateErrors))
662 globals_->ignore_certificate_errors = true;
663 if (command_line.HasSwitch(switches::kEnableStaleWhileRevalidate))
664 globals_->use_stale_while_revalidate = true;
665 if (base::FieldTrialList::FindFullName(kStaleWhileRevalidateFieldTrialName) ==
666 "Enabled")
667 globals_->use_stale_while_revalidate = true;
668 if (command_line.HasSwitch(switches::kTestingFixedHttpPort)) {
669 globals_->testing_fixed_http_port =
670 GetSwitchValueAsInt(command_line, switches::kTestingFixedHttpPort);
672 if (command_line.HasSwitch(switches::kTestingFixedHttpsPort)) {
673 globals_->testing_fixed_https_port =
674 GetSwitchValueAsInt(command_line, switches::kTestingFixedHttpsPort);
676 ConfigureQuic(command_line);
677 if (command_line.HasSwitch(
678 switches::kEnableUserAlternateProtocolPorts)) {
679 globals_->enable_user_alternate_protocol_ports = true;
681 InitializeNetworkOptions(command_line);
683 net::HttpNetworkSession::Params session_params;
684 InitializeNetworkSessionParams(&session_params);
685 session_params.net_log = net_log_;
686 session_params.proxy_service =
687 globals_->proxy_script_fetcher_proxy_service.get();
689 TRACE_EVENT_BEGIN0("startup", "IOThread::InitAsync:HttpNetworkSession");
690 scoped_refptr<net::HttpNetworkSession> network_session(
691 new net::HttpNetworkSession(session_params));
692 globals_->proxy_script_fetcher_http_transaction_factory
693 .reset(new net::HttpNetworkLayer(network_session.get()));
694 TRACE_EVENT_END0("startup", "IOThread::InitAsync:HttpNetworkSession");
695 scoped_ptr<net::URLRequestJobFactoryImpl> job_factory(
696 new net::URLRequestJobFactoryImpl());
697 job_factory->SetProtocolHandler(url::kDataScheme,
698 new net::DataProtocolHandler());
699 job_factory->SetProtocolHandler(
700 url::kFileScheme,
701 new net::FileProtocolHandler(
702 content::BrowserThread::GetBlockingPool()->
703 GetTaskRunnerWithShutdownBehavior(
704 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)));
705 #if !defined(DISABLE_FTP_SUPPORT)
706 globals_->proxy_script_fetcher_ftp_transaction_factory.reset(
707 new net::FtpNetworkLayer(globals_->host_resolver.get()));
708 job_factory->SetProtocolHandler(
709 url::kFtpScheme,
710 new net::FtpProtocolHandler(
711 globals_->proxy_script_fetcher_ftp_transaction_factory.get()));
712 #endif
713 globals_->proxy_script_fetcher_url_request_job_factory = job_factory.Pass();
715 globals_->throttler_manager.reset(new net::URLRequestThrottlerManager());
716 globals_->throttler_manager->set_net_log(net_log_);
717 // Always done in production, disabled only for unit tests.
718 globals_->throttler_manager->set_enable_thread_checks(true);
720 globals_->proxy_script_fetcher_context.reset(
721 ConstructProxyScriptFetcherContext(globals_, net_log_));
723 #if defined(OS_MACOSX) && !defined(OS_IOS)
724 // Start observing Keychain events. This needs to be done on the UI thread,
725 // as Keychain services requires a CFRunLoop.
726 BrowserThread::PostTask(BrowserThread::UI,
727 FROM_HERE,
728 base::Bind(&ObserveKeychainEvents));
729 #endif
731 // InitSystemRequestContext turns right around and posts a task back
732 // to the IO thread, so we can't let it run until we know the IO
733 // thread has started.
735 // Note that since we are at BrowserThread::Init time, the UI thread
736 // is blocked waiting for the thread to start. Therefore, posting
737 // this task to the main thread's message loop here is guaranteed to
738 // get it onto the message loop while the IOThread object still
739 // exists. However, the message might not be processed on the UI
740 // thread until after IOThread is gone, so use a weak pointer.
741 BrowserThread::PostTask(BrowserThread::UI,
742 FROM_HERE,
743 base::Bind(&IOThread::InitSystemRequestContext,
744 weak_factory_.GetWeakPtr()));
747 void IOThread::CleanUp() {
748 base::debug::LeakTracker<SafeBrowsingURLRequestContext>::CheckForLeaks();
750 #if defined(USE_NSS) || defined(OS_IOS)
751 net::ShutdownNSSHttpIO();
752 #endif
754 system_url_request_context_getter_ = NULL;
756 // Release objects that the net::URLRequestContext could have been pointing
757 // to.
759 // Shutdown the HistogramWatcher on the IO thread.
760 net::NetworkChangeNotifier::ShutdownHistogramWatcher();
762 // This must be reset before the ChromeNetLog is destroyed.
763 network_change_observer_.reset();
765 system_proxy_config_service_.reset();
767 delete globals_;
768 globals_ = NULL;
770 base::debug::LeakTracker<SystemURLRequestContextGetter>::CheckForLeaks();
773 void IOThread::InitializeNetworkOptions(const CommandLine& command_line) {
774 // Only handle use-spdy command line flags if "spdy.disabled" preference is
775 // not disabled via policy.
776 if (is_spdy_disabled_by_policy_) {
777 base::FieldTrial* trial = base::FieldTrialList::Find(kSpdyFieldTrialName);
778 if (trial)
779 trial->Disable();
780 } else {
781 if (command_line.HasSwitch(switches::kTrustedSpdyProxy)) {
782 globals_->trusted_spdy_proxy.set(
783 command_line.GetSwitchValueASCII(switches::kTrustedSpdyProxy));
785 if (command_line.HasSwitch(switches::kIgnoreUrlFetcherCertRequests))
786 net::URLFetcher::SetIgnoreCertificateRequests(true);
788 if (command_line.HasSwitch(switches::kUseSpdy)) {
789 std::string spdy_mode =
790 command_line.GetSwitchValueASCII(switches::kUseSpdy);
791 EnableSpdy(spdy_mode);
792 } else if (command_line.HasSwitch(switches::kEnableSpdy4)) {
793 globals_->next_protos = net::NextProtosSpdy4Http2();
794 globals_->use_alternate_protocols.set(true);
795 } else if (command_line.HasSwitch(switches::kDisableSpdy31)) {
796 globals_->next_protos = net::NextProtosSpdy3();
797 globals_->use_alternate_protocols.set(true);
798 } else if (command_line.HasSwitch(switches::kEnableNpnHttpOnly)) {
799 globals_->next_protos = net::NextProtosHttpOnly();
800 globals_->use_alternate_protocols.set(false);
801 } else if (command_line.HasSwitch(switches::kEnableWebSocketOverSpdy)) {
802 // Use the current SPDY default (SPDY/3.1).
803 globals_->next_protos = net::NextProtosSpdy31();
804 globals_->use_alternate_protocols.set(true);
805 } else {
806 // No SPDY command-line flags have been specified. Examine trial groups.
807 ConfigureSpdyFromTrial(
808 base::FieldTrialList::FindFullName(kSpdyFieldTrialName), globals_);
811 if (command_line.HasSwitch(switches::kEnableWebSocketOverSpdy))
812 globals_->enable_websocket_over_spdy.set(true);
815 ConfigureTCPFastOpen(command_line);
817 // TODO(rch): Make the client socket factory a per-network session
818 // instance, constructed from a NetworkSession::Params, to allow us
819 // to move this option to IOThread::Globals &
820 // HttpNetworkSession::Params.
823 void IOThread::ConfigureTCPFastOpen(const CommandLine& command_line) {
824 const std::string trial_group =
825 base::FieldTrialList::FindFullName(kTCPFastOpenFieldTrialName);
826 if (trial_group == kTCPFastOpenHttpsEnabledGroupName)
827 globals_->enable_tcp_fast_open_for_ssl.set(true);
828 bool always_enable_if_supported =
829 command_line.HasSwitch(switches::kEnableTcpFastOpen);
830 // Check for OS support of TCP FastOpen, and turn it on for all connections
831 // if indicated by user.
832 net::CheckSupportAndMaybeEnableTCPFastOpen(always_enable_if_supported);
835 void IOThread::ConfigureSpdyFromTrial(const std::string& spdy_trial_group,
836 Globals* globals) {
837 if (spdy_trial_group == kSpdyFieldTrialHoldbackGroupName) {
838 // TODO(jgraettinger): Use net::NextProtosHttpOnly() instead?
839 net::HttpStreamFactory::set_spdy_enabled(false);
840 } else if (spdy_trial_group == kSpdyFieldTrialHoldbackControlGroupName) {
841 // Use the current SPDY default (SPDY/3.1).
842 globals->next_protos = net::NextProtosSpdy31();
843 globals->use_alternate_protocols.set(true);
844 } else if (spdy_trial_group == kSpdyFieldTrialSpdy4GroupName) {
845 globals->next_protos = net::NextProtosSpdy4Http2();
846 globals->use_alternate_protocols.set(true);
847 } else if (spdy_trial_group == kSpdyFieldTrialSpdy4ControlGroupName) {
848 // This control group is pinned at SPDY/3.1.
849 globals->next_protos = net::NextProtosSpdy31();
850 globals->use_alternate_protocols.set(true);
851 } else {
852 // Use the current SPDY default (SPDY/3.1).
853 globals->next_protos = net::NextProtosSpdy31();
854 globals->use_alternate_protocols.set(true);
858 void IOThread::EnableSpdy(const std::string& mode) {
859 static const char kOff[] = "off";
860 static const char kSSL[] = "ssl";
861 static const char kDisableSSL[] = "no-ssl";
862 static const char kDisablePing[] = "no-ping";
863 static const char kExclude[] = "exclude"; // Hosts to exclude
864 static const char kDisableCompression[] = "no-compress";
865 static const char kDisableAltProtocols[] = "no-alt-protocols";
866 static const char kForceAltProtocols[] = "force-alt-protocols";
867 static const char kSingleDomain[] = "single-domain";
869 static const char kInitialMaxConcurrentStreams[] = "init-max-streams";
871 std::vector<std::string> spdy_options;
872 base::SplitString(mode, ',', &spdy_options);
874 for (std::vector<std::string>::iterator it = spdy_options.begin();
875 it != spdy_options.end(); ++it) {
876 const std::string& element = *it;
877 std::vector<std::string> name_value;
878 base::SplitString(element, '=', &name_value);
879 const std::string& option =
880 name_value.size() > 0 ? name_value[0] : std::string();
881 const std::string value =
882 name_value.size() > 1 ? name_value[1] : std::string();
884 if (option == kOff) {
885 net::HttpStreamFactory::set_spdy_enabled(false);
886 } else if (option == kDisableSSL) {
887 globals_->spdy_default_protocol.set(net::kProtoSPDY3);
888 globals_->force_spdy_over_ssl.set(false);
889 globals_->force_spdy_always.set(true);
890 } else if (option == kSSL) {
891 globals_->spdy_default_protocol.set(net::kProtoSPDY3);
892 globals_->force_spdy_over_ssl.set(true);
893 globals_->force_spdy_always.set(true);
894 } else if (option == kDisablePing) {
895 globals_->enable_spdy_ping_based_connection_checking.set(false);
896 } else if (option == kExclude) {
897 globals_->forced_spdy_exclusions.insert(
898 net::HostPortPair::FromURL(GURL(value)));
899 } else if (option == kDisableCompression) {
900 globals_->enable_spdy_compression.set(false);
901 } else if (option == kDisableAltProtocols) {
902 globals_->use_alternate_protocols.set(false);
903 } else if (option == kForceAltProtocols) {
904 net::AlternateProtocolInfo pair(443, net::NPN_SPDY_3, 1);
905 net::HttpServerPropertiesImpl::ForceAlternateProtocol(pair);
906 } else if (option == kSingleDomain) {
907 DVLOG(1) << "FORCING SINGLE DOMAIN";
908 globals_->force_spdy_single_domain.set(true);
909 } else if (option == kInitialMaxConcurrentStreams) {
910 int streams;
911 if (base::StringToInt(value, &streams))
912 globals_->initial_max_spdy_concurrent_streams.set(streams);
913 } else if (option.empty() && it == spdy_options.begin()) {
914 continue;
915 } else {
916 LOG(DFATAL) << "Unrecognized spdy option: " << option;
921 // static
922 void IOThread::RegisterPrefs(PrefRegistrySimple* registry) {
923 registry->RegisterStringPref(prefs::kAuthSchemes,
924 "basic,digest,ntlm,negotiate,"
925 "spdyproxy");
926 registry->RegisterBooleanPref(prefs::kDisableAuthNegotiateCnameLookup, false);
927 registry->RegisterBooleanPref(prefs::kEnableAuthNegotiatePort, false);
928 registry->RegisterStringPref(prefs::kAuthServerWhitelist, std::string());
929 registry->RegisterStringPref(prefs::kAuthNegotiateDelegateWhitelist,
930 std::string());
931 registry->RegisterStringPref(prefs::kGSSAPILibraryName, std::string());
932 registry->RegisterStringPref(
933 data_reduction_proxy::prefs::kDataReductionProxy, std::string());
934 registry->RegisterBooleanPref(prefs::kEnableReferrers, true);
935 data_reduction_proxy::RegisterPrefs(registry);
936 registry->RegisterBooleanPref(prefs::kBuiltInDnsClientEnabled, true);
937 registry->RegisterBooleanPref(prefs::kQuickCheckEnabled, true);
940 net::HttpAuthHandlerFactory* IOThread::CreateDefaultAuthHandlerFactory(
941 net::HostResolver* resolver) {
942 net::HttpAuthFilterWhitelist* auth_filter_default_credentials = NULL;
943 if (!auth_server_whitelist_.empty()) {
944 auth_filter_default_credentials =
945 new net::HttpAuthFilterWhitelist(auth_server_whitelist_);
947 net::HttpAuthFilterWhitelist* auth_filter_delegate = NULL;
948 if (!auth_delegate_whitelist_.empty()) {
949 auth_filter_delegate =
950 new net::HttpAuthFilterWhitelist(auth_delegate_whitelist_);
952 globals_->url_security_manager.reset(
953 net::URLSecurityManager::Create(auth_filter_default_credentials,
954 auth_filter_delegate));
955 std::vector<std::string> supported_schemes;
956 base::SplitString(auth_schemes_, ',', &supported_schemes);
958 scoped_ptr<net::HttpAuthHandlerRegistryFactory> registry_factory(
959 net::HttpAuthHandlerRegistryFactory::Create(
960 supported_schemes, globals_->url_security_manager.get(),
961 resolver, gssapi_library_name_, negotiate_disable_cname_lookup_,
962 negotiate_enable_port_));
963 return registry_factory.release();
966 void IOThread::ClearHostCache() {
967 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
969 net::HostCache* host_cache = globals_->host_resolver->GetHostCache();
970 if (host_cache)
971 host_cache->clear();
974 void IOThread::InitializeNetworkSessionParams(
975 net::HttpNetworkSession::Params* params) {
976 InitializeNetworkSessionParamsFromGlobals(*globals_, params);
979 // static
980 void IOThread::InitializeNetworkSessionParamsFromGlobals(
981 const IOThread::Globals& globals,
982 net::HttpNetworkSession::Params* params) {
983 params->host_resolver = globals.host_resolver.get();
984 params->cert_verifier = globals.cert_verifier.get();
985 params->channel_id_service = globals.system_channel_id_service.get();
986 params->transport_security_state = globals.transport_security_state.get();
987 params->ssl_config_service = globals.ssl_config_service.get();
988 params->http_auth_handler_factory = globals.http_auth_handler_factory.get();
989 params->http_server_properties =
990 globals.http_server_properties->GetWeakPtr();
991 params->network_delegate = globals.system_network_delegate.get();
992 params->host_mapping_rules = globals.host_mapping_rules.get();
993 params->enable_ssl_connect_job_waiting =
994 globals.enable_ssl_connect_job_waiting;
995 params->ignore_certificate_errors = globals.ignore_certificate_errors;
996 params->use_stale_while_revalidate = globals.use_stale_while_revalidate;
997 params->testing_fixed_http_port = globals.testing_fixed_http_port;
998 params->testing_fixed_https_port = globals.testing_fixed_https_port;
999 globals.enable_tcp_fast_open_for_ssl.CopyToIfSet(
1000 &params->enable_tcp_fast_open_for_ssl);
1002 globals.initial_max_spdy_concurrent_streams.CopyToIfSet(
1003 &params->spdy_initial_max_concurrent_streams);
1004 globals.force_spdy_single_domain.CopyToIfSet(
1005 &params->force_spdy_single_domain);
1006 globals.enable_spdy_compression.CopyToIfSet(
1007 &params->enable_spdy_compression);
1008 globals.enable_spdy_ping_based_connection_checking.CopyToIfSet(
1009 &params->enable_spdy_ping_based_connection_checking);
1010 globals.spdy_default_protocol.CopyToIfSet(
1011 &params->spdy_default_protocol);
1012 params->next_protos = globals.next_protos;
1013 globals.trusted_spdy_proxy.CopyToIfSet(&params->trusted_spdy_proxy);
1014 globals.force_spdy_over_ssl.CopyToIfSet(&params->force_spdy_over_ssl);
1015 globals.force_spdy_always.CopyToIfSet(&params->force_spdy_always);
1016 params->forced_spdy_exclusions = globals.forced_spdy_exclusions;
1017 globals.use_alternate_protocols.CopyToIfSet(
1018 &params->use_alternate_protocols);
1019 globals.alternate_protocol_probability_threshold.CopyToIfSet(
1020 &params->alternate_protocol_probability_threshold);
1021 globals.enable_websocket_over_spdy.CopyToIfSet(
1022 &params->enable_websocket_over_spdy);
1024 globals.enable_quic.CopyToIfSet(&params->enable_quic);
1025 globals.quic_always_require_handshake_confirmation.CopyToIfSet(
1026 &params->quic_always_require_handshake_confirmation);
1027 globals.quic_disable_connection_pooling.CopyToIfSet(
1028 &params->quic_disable_connection_pooling);
1029 globals.enable_quic_port_selection.CopyToIfSet(
1030 &params->enable_quic_port_selection);
1031 globals.quic_max_packet_length.CopyToIfSet(&params->quic_max_packet_length);
1032 globals.quic_user_agent_id.CopyToIfSet(&params->quic_user_agent_id);
1033 globals.quic_supported_versions.CopyToIfSet(
1034 &params->quic_supported_versions);
1035 params->quic_connection_options = globals.quic_connection_options;
1037 globals.origin_to_force_quic_on.CopyToIfSet(
1038 &params->origin_to_force_quic_on);
1039 params->enable_user_alternate_protocol_ports =
1040 globals.enable_user_alternate_protocol_ports;
1041 params->proxy_delegate = globals.data_reduction_proxy_delegate.get();
1044 base::TimeTicks IOThread::creation_time() const {
1045 return creation_time_;
1048 net::SSLConfigService* IOThread::GetSSLConfigService() {
1049 return ssl_config_service_manager_->Get();
1052 void IOThread::ChangedToOnTheRecordOnIOThread() {
1053 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1055 // Clear the host cache to avoid showing entries from the OTR session
1056 // in about:net-internals.
1057 ClearHostCache();
1060 void IOThread::InitSystemRequestContext() {
1061 if (system_url_request_context_getter_.get())
1062 return;
1063 // If we're in unit_tests, IOThread may not be run.
1064 if (!BrowserThread::IsMessageLoopValid(BrowserThread::IO))
1065 return;
1066 system_proxy_config_service_.reset(
1067 ProxyServiceFactory::CreateProxyConfigService(
1068 pref_proxy_config_tracker_.get()));
1069 system_url_request_context_getter_ =
1070 new SystemURLRequestContextGetter(this);
1071 // Safe to post an unretained this pointer, since IOThread is
1072 // guaranteed to outlive the IO BrowserThread.
1073 BrowserThread::PostTask(
1074 BrowserThread::IO,
1075 FROM_HERE,
1076 base::Bind(&IOThread::InitSystemRequestContextOnIOThread,
1077 base::Unretained(this)));
1080 void IOThread::InitSystemRequestContextOnIOThread() {
1081 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1082 DCHECK(!globals_->system_proxy_service.get());
1083 DCHECK(system_proxy_config_service_.get());
1085 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
1086 globals_->system_proxy_service.reset(
1087 ProxyServiceFactory::CreateProxyService(
1088 net_log_,
1089 globals_->proxy_script_fetcher_context.get(),
1090 globals_->system_network_delegate.get(),
1091 system_proxy_config_service_.release(),
1092 command_line,
1093 quick_check_enabled_.GetValue()));
1094 DCHECK(globals_->data_reduction_proxy_params);
1096 net::HttpNetworkSession::Params system_params;
1097 InitializeNetworkSessionParams(&system_params);
1098 system_params.net_log = net_log_;
1099 system_params.proxy_service = globals_->system_proxy_service.get();
1101 globals_->system_http_transaction_factory.reset(
1102 new net::HttpNetworkLayer(
1103 new net::HttpNetworkSession(system_params)));
1104 globals_->system_url_request_job_factory.reset(
1105 new net::URLRequestJobFactoryImpl());
1106 globals_->system_request_context.reset(
1107 ConstructSystemRequestContext(globals_, net_log_));
1108 globals_->system_request_context->set_ssl_config_service(
1109 globals_->ssl_config_service.get());
1110 globals_->system_request_context->set_http_server_properties(
1111 globals_->http_server_properties->GetWeakPtr());
1114 void IOThread::UpdateDnsClientEnabled() {
1115 globals()->host_resolver->SetDnsClientEnabled(*dns_client_enabled_);
1118 void IOThread::ConfigureQuic(const CommandLine& command_line) {
1119 // Always fetch the field trial group to ensure it is reported correctly.
1120 // The command line flags will be associated with a group that is reported
1121 // so long as trial is actually queried.
1122 std::string group =
1123 base::FieldTrialList::FindFullName(kQuicFieldTrialName);
1124 VariationParameters params;
1125 if (!variations::GetVariationParams(kQuicFieldTrialName, &params)) {
1126 params.clear();
1129 ConfigureQuicGlobals(command_line, group, params, globals_);
1132 void IOThread::SetupDataReductionProxy(
1133 ChromeNetworkDelegate* network_delegate) {
1134 // TODO(kundaji): Move flags initialization to DataReductionProxyParams and
1135 // merge with flag initialization in
1136 // data_reduction_proxy_chrome_settings_factory.cc.
1137 int flags = data_reduction_proxy::DataReductionProxyParams::kAllowed |
1138 data_reduction_proxy::DataReductionProxyParams::kFallbackAllowed |
1139 data_reduction_proxy::DataReductionProxyParams::kAlternativeAllowed;
1140 if (data_reduction_proxy::DataReductionProxyParams::
1141 IsIncludedInPromoFieldTrial()) {
1142 flags |= data_reduction_proxy::DataReductionProxyParams::kPromoAllowed;
1144 if (data_reduction_proxy::DataReductionProxyParams::
1145 IsIncludedInHoldbackFieldTrial()) {
1146 flags |= data_reduction_proxy::DataReductionProxyParams::kHoldback;
1148 globals_->data_reduction_proxy_params.reset(
1149 new data_reduction_proxy::DataReductionProxyParams(flags));
1150 globals_->data_reduction_proxy_auth_request_handler.reset(
1151 new data_reduction_proxy::DataReductionProxyAuthRequestHandler(
1152 DataReductionProxyChromeSettings::GetClient(),
1153 globals_->data_reduction_proxy_params.get(),
1154 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)));
1155 globals_->data_reduction_proxy_delegate.reset(
1156 new data_reduction_proxy::DataReductionProxyDelegate(
1157 globals_->data_reduction_proxy_auth_request_handler.get()));
1158 // This is the same as in ProfileImplIOData except that we do not collect
1159 // usage stats.
1160 network_delegate->set_data_reduction_proxy_params(
1161 globals_->data_reduction_proxy_params.get());
1162 network_delegate->set_data_reduction_proxy_auth_request_handler(
1163 globals_->data_reduction_proxy_auth_request_handler.get());
1164 network_delegate->set_on_resolve_proxy_handler(
1165 base::Bind(data_reduction_proxy::OnResolveProxyHandler));
1168 // static
1169 void IOThread::ConfigureQuicGlobals(
1170 const base::CommandLine& command_line,
1171 base::StringPiece quic_trial_group,
1172 const VariationParameters& quic_trial_params,
1173 IOThread::Globals* globals) {
1174 bool enable_quic = ShouldEnableQuic(command_line, quic_trial_group);
1175 globals->enable_quic.set(enable_quic);
1176 if (enable_quic) {
1177 globals->quic_always_require_handshake_confirmation.set(
1178 ShouldQuicAlwaysRequireHandshakeConfirmation(quic_trial_params));
1179 globals->quic_disable_connection_pooling.set(
1180 ShouldQuicDisableConnectionPooling(quic_trial_params));
1181 globals->enable_quic_port_selection.set(
1182 ShouldEnableQuicPortSelection(command_line));
1183 globals->quic_connection_options =
1184 GetQuicConnectionOptions(command_line, quic_trial_params);
1185 if (ShouldEnableQuicPacing(command_line, quic_trial_group,
1186 quic_trial_params)) {
1187 globals->quic_connection_options.push_back(net::kPACE);
1191 size_t max_packet_length = GetQuicMaxPacketLength(command_line,
1192 quic_trial_group,
1193 quic_trial_params);
1194 if (max_packet_length != 0) {
1195 globals->quic_max_packet_length.set(max_packet_length);
1198 std::string quic_user_agent_id =
1199 chrome::VersionInfo::GetVersionStringModifier();
1200 if (!quic_user_agent_id.empty())
1201 quic_user_agent_id.push_back(' ');
1202 chrome::VersionInfo version_info;
1203 quic_user_agent_id.append(version_info.ProductNameAndVersionForUserAgent());
1204 globals->quic_user_agent_id.set(quic_user_agent_id);
1206 net::QuicVersion version = GetQuicVersion(command_line, quic_trial_params);
1207 if (version != net::QUIC_VERSION_UNSUPPORTED) {
1208 net::QuicVersionVector supported_versions;
1209 supported_versions.push_back(version);
1210 globals->quic_supported_versions.set(supported_versions);
1213 double threshold =
1214 GetAlternateProtocolProbabilityThreshold(command_line, quic_trial_params);
1215 if (threshold >=0 && threshold <= 1) {
1216 globals->alternate_protocol_probability_threshold.set(threshold);
1217 globals->http_server_properties->SetAlternateProtocolProbabilityThreshold(
1218 threshold);
1221 if (command_line.HasSwitch(switches::kOriginToForceQuicOn)) {
1222 net::HostPortPair quic_origin =
1223 net::HostPortPair::FromString(
1224 command_line.GetSwitchValueASCII(switches::kOriginToForceQuicOn));
1225 if (!quic_origin.IsEmpty()) {
1226 globals->origin_to_force_quic_on.set(quic_origin);
1231 bool IOThread::ShouldEnableQuic(const CommandLine& command_line,
1232 base::StringPiece quic_trial_group) {
1233 if (command_line.HasSwitch(switches::kDisableQuic))
1234 return false;
1236 if (command_line.HasSwitch(switches::kEnableQuic))
1237 return true;
1239 return quic_trial_group.starts_with(kQuicFieldTrialEnabledGroupName) ||
1240 quic_trial_group.starts_with(kQuicFieldTrialHttpsEnabledGroupName);
1243 bool IOThread::ShouldEnableQuicPortSelection(
1244 const CommandLine& command_line) {
1245 if (command_line.HasSwitch(switches::kDisableQuicPortSelection))
1246 return false;
1248 if (command_line.HasSwitch(switches::kEnableQuicPortSelection))
1249 return true;
1251 return false; // Default to disabling port selection on all channels.
1254 bool IOThread::ShouldEnableQuicPacing(
1255 const CommandLine& command_line,
1256 base::StringPiece quic_trial_group,
1257 const VariationParameters& quic_trial_params) {
1258 if (command_line.HasSwitch(switches::kEnableQuicPacing))
1259 return true;
1261 if (command_line.HasSwitch(switches::kDisableQuicPacing))
1262 return false;
1264 if (LowerCaseEqualsASCII(
1265 GetVariationParam(quic_trial_params, "enable_pacing"),
1266 "true"))
1267 return true;
1269 return quic_trial_group.ends_with(kQuicFieldTrialPacingSuffix);
1272 net::QuicTagVector IOThread::GetQuicConnectionOptions(
1273 const CommandLine& command_line,
1274 const VariationParameters& quic_trial_params) {
1275 if (command_line.HasSwitch(switches::kQuicConnectionOptions)) {
1276 return ParseQuicConnectionOptions(
1277 command_line.GetSwitchValueASCII(switches::kQuicConnectionOptions));
1280 VariationParameters::const_iterator it =
1281 quic_trial_params.find("connection_options");
1282 if (it == quic_trial_params.end()) {
1283 // TODO(rch): remove support for deprecated congestion_options.
1284 it = quic_trial_params.find("congestion_options");
1285 if (it == quic_trial_params.end())
1286 return net::QuicTagVector();
1289 return ParseQuicConnectionOptions(it->second);
1292 // static
1293 net::QuicTagVector IOThread::ParseQuicConnectionOptions(
1294 const std::string& connection_options) {
1295 net::QuicTagVector options;
1296 std::vector<std::string> tokens;
1297 base::SplitString(connection_options, ',', &tokens);
1298 // Tokens are expected to be no more than 4 characters long, but we
1299 // handle overflow gracefully.
1300 for (std::vector<std::string>::iterator token = tokens.begin();
1301 token != tokens.end(); ++token) {
1302 uint32 option = 0;
1303 for (size_t i = token->length() ; i > 0; --i) {
1304 option <<= 8;
1305 option |= static_cast<unsigned char>((*token)[i - 1]);
1307 options.push_back(static_cast<net::QuicTag>(option));
1309 return options;
1312 // static
1313 double IOThread::GetAlternateProtocolProbabilityThreshold(
1314 const base::CommandLine& command_line,
1315 const VariationParameters& quic_trial_params) {
1316 double value;
1317 if (command_line.HasSwitch(
1318 switches::kAlternateProtocolProbabilityThreshold)) {
1319 if (base::StringToDouble(
1320 command_line.GetSwitchValueASCII(
1321 switches::kAlternateProtocolProbabilityThreshold),
1322 &value)) {
1323 return value;
1326 if (command_line.HasSwitch(switches::kEnableQuic)) {
1327 return 0;
1329 if (base::StringToDouble(
1330 GetVariationParam(quic_trial_params,
1331 "alternate_protocol_probability_threshold"),
1332 &value)) {
1333 return value;
1335 return -1;
1338 // static
1339 bool IOThread::ShouldQuicAlwaysRequireHandshakeConfirmation(
1340 const VariationParameters& quic_trial_params) {
1341 return LowerCaseEqualsASCII(
1342 GetVariationParam(quic_trial_params,
1343 "always_require_handshake_confirmation"),
1344 "true");
1347 // static
1348 bool IOThread::ShouldQuicDisableConnectionPooling(
1349 const VariationParameters& quic_trial_params) {
1350 return LowerCaseEqualsASCII(
1351 GetVariationParam(quic_trial_params, "disable_connection_pooling"),
1352 "true");
1355 // static
1356 size_t IOThread::GetQuicMaxPacketLength(
1357 const CommandLine& command_line,
1358 base::StringPiece quic_trial_group,
1359 const VariationParameters& quic_trial_params) {
1360 if (command_line.HasSwitch(switches::kQuicMaxPacketLength)) {
1361 unsigned value;
1362 if (!base::StringToUint(
1363 command_line.GetSwitchValueASCII(switches::kQuicMaxPacketLength),
1364 &value)) {
1365 return 0;
1367 return value;
1370 unsigned value;
1371 if (base::StringToUint(GetVariationParam(quic_trial_params,
1372 "max_packet_length"),
1373 &value)) {
1374 return value;
1377 // Format of the packet length group names is:
1378 // (Https)?Enabled<length>BytePackets.
1379 base::StringPiece length_str(quic_trial_group);
1380 if (length_str.starts_with(kQuicFieldTrialEnabledGroupName)) {
1381 length_str.remove_prefix(strlen(kQuicFieldTrialEnabledGroupName));
1382 } else if (length_str.starts_with(kQuicFieldTrialHttpsEnabledGroupName)) {
1383 length_str.remove_prefix(strlen(kQuicFieldTrialHttpsEnabledGroupName));
1384 } else {
1385 return 0;
1387 if (!length_str.ends_with(kQuicFieldTrialPacketLengthSuffix)) {
1388 return 0;
1390 length_str.remove_suffix(strlen(kQuicFieldTrialPacketLengthSuffix));
1391 if (!base::StringToUint(length_str, &value)) {
1392 return 0;
1394 return value;
1397 // static
1398 net::QuicVersion IOThread::GetQuicVersion(
1399 const CommandLine& command_line,
1400 const VariationParameters& quic_trial_params) {
1401 if (command_line.HasSwitch(switches::kQuicVersion)) {
1402 return ParseQuicVersion(
1403 command_line.GetSwitchValueASCII(switches::kQuicVersion));
1406 return ParseQuicVersion(GetVariationParam(quic_trial_params, "quic_version"));
1409 // static
1410 net::QuicVersion IOThread::ParseQuicVersion(const std::string& quic_version) {
1411 net::QuicVersionVector supported_versions = net::QuicSupportedVersions();
1412 for (size_t i = 0; i < supported_versions.size(); ++i) {
1413 net::QuicVersion version = supported_versions[i];
1414 if (net::QuicVersionToString(version) == quic_version) {
1415 return version;
1419 return net::QUIC_VERSION_UNSUPPORTED;