ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / chrome / browser / io_thread.cc
blob309e6273e204d5e980bd4b4136a4bf8a6cbe84c1
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/metrics/user_metrics.h"
18 #include "base/prefs/pref_registry_simple.h"
19 #include "base/prefs/pref_service.h"
20 #include "base/profiler/scoped_tracker.h"
21 #include "base/stl_util.h"
22 #include "base/strings/string_number_conversions.h"
23 #include "base/strings/string_piece.h"
24 #include "base/strings/string_split.h"
25 #include "base/strings/string_util.h"
26 #include "base/threading/sequenced_worker_pool.h"
27 #include "base/threading/thread.h"
28 #include "base/threading/worker_pool.h"
29 #include "base/time/time.h"
30 #include "base/trace_event/trace_event.h"
31 #include "build/build_config.h"
32 #include "chrome/browser/browser_process.h"
33 #include "chrome/browser/net/async_dns_field_trial.h"
34 #include "chrome/browser/net/chrome_net_log.h"
35 #include "chrome/browser/net/chrome_network_delegate.h"
36 #include "chrome/browser/net/connect_interceptor.h"
37 #include "chrome/browser/net/dns_probe_service.h"
38 #include "chrome/browser/net/pref_proxy_config_tracker.h"
39 #include "chrome/browser/net/proxy_service_factory.h"
40 #include "chrome/common/chrome_content_client.h"
41 #include "chrome/common/chrome_switches.h"
42 #include "chrome/common/chrome_version_info.h"
43 #include "chrome/common/pref_names.h"
44 #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_prefs.h"
45 #include "components/data_reduction_proxy/core/common/data_reduction_proxy_params.h"
46 #include "components/policy/core/common/policy_service.h"
47 #include "components/variations/variations_associated_data.h"
48 #include "content/public/browser/browser_thread.h"
49 #include "content/public/browser/cookie_store_factory.h"
50 #include "net/base/host_mapping_rules.h"
51 #include "net/base/net_util.h"
52 #include "net/cert/cert_policy_enforcer.h"
53 #include "net/cert/cert_verifier.h"
54 #include "net/cert/cert_verify_proc.h"
55 #include "net/cert/ct_known_logs.h"
56 #include "net/cert/ct_known_logs_static.h"
57 #include "net/cert/ct_log_verifier.h"
58 #include "net/cert/ct_verifier.h"
59 #include "net/cert/multi_log_ct_verifier.h"
60 #include "net/cert/multi_threaded_cert_verifier.h"
61 #include "net/cookies/cookie_store.h"
62 #include "net/dns/host_cache.h"
63 #include "net/dns/host_resolver.h"
64 #include "net/dns/mapped_host_resolver.h"
65 #include "net/ftp/ftp_network_layer.h"
66 #include "net/http/http_auth_filter.h"
67 #include "net/http/http_auth_handler_factory.h"
68 #include "net/http/http_network_layer.h"
69 #include "net/http/http_server_properties_impl.h"
70 #include "net/proxy/proxy_config_service.h"
71 #include "net/proxy/proxy_script_fetcher_impl.h"
72 #include "net/proxy/proxy_service.h"
73 #include "net/quic/crypto/crypto_protocol.h"
74 #include "net/quic/quic_protocol.h"
75 #include "net/quic/quic_utils.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_ANDROID)
104 #include "base/android/build_info.h"
105 #endif
107 #if defined(OS_CHROMEOS)
108 #include "chrome/browser/chromeos/net/cert_verify_proc_chromeos.h"
109 #include "chromeos/network/host_resolver_impl_chromeos.h"
110 #endif
112 using content::BrowserThread;
114 class SafeBrowsingURLRequestContext;
116 // The IOThread object must outlive any tasks posted to the IO thread before the
117 // Quit task, so base::Bind() calls are not refcounted.
119 namespace {
121 const char kTCPFastOpenFieldTrialName[] = "TCPFastOpen";
122 const char kTCPFastOpenHttpsEnabledGroupName[] = "HttpsEnabled";
124 const char kQuicFieldTrialName[] = "QUIC";
125 const char kQuicFieldTrialEnabledGroupName[] = "Enabled";
126 const char kQuicFieldTrialHttpsEnabledGroupName[] = "HttpsEnabled";
128 // The SPDY trial composes two different trial plus control groups:
129 // * A "holdback" group with SPDY disabled, and corresponding control
130 // (SPDY/3.1). The primary purpose of the holdback group is to encourage site
131 // operators to do feature detection rather than UA-sniffing. As such, this
132 // trial runs continuously.
133 // * A SPDY/4 experiment, for SPDY/4 (aka HTTP/2) vs SPDY/3.1 comparisons and
134 // eventual SPDY/4 deployment.
135 const char kSpdyFieldTrialName[] = "SPDY";
136 const char kSpdyFieldTrialHoldbackGroupNamePrefix[] = "SpdyDisabled";
137 const char kSpdyFieldTrialSpdy31GroupNamePrefix[] = "Spdy31Enabled";
138 const char kSpdyFieldTrialSpdy4GroupNamePrefix[] = "Spdy4Enabled";
140 // Field trial for Cache-Control: stale-while-revalidate directive.
141 const char kStaleWhileRevalidateFieldTrialName[] = "StaleWhileRevalidate";
143 #if defined(OS_MACOSX) && !defined(OS_IOS)
144 void ObserveKeychainEvents() {
145 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
146 net::CertDatabase::GetInstance()->SetMessageLoopForKeychainEvents();
148 #endif
150 // Used for the "system" URLRequestContext.
151 class SystemURLRequestContext : public net::URLRequestContext {
152 public:
153 SystemURLRequestContext() {
154 #if defined(USE_NSS) || defined(OS_IOS)
155 net::SetURLRequestContextForNSSHttpIO(this);
156 #endif
159 private:
160 ~SystemURLRequestContext() override {
161 AssertNoURLRequests();
162 #if defined(USE_NSS) || defined(OS_IOS)
163 net::SetURLRequestContextForNSSHttpIO(NULL);
164 #endif
168 scoped_ptr<net::HostResolver> CreateGlobalHostResolver(net::NetLog* net_log) {
169 TRACE_EVENT0("startup", "IOThread::CreateGlobalHostResolver");
170 const base::CommandLine& command_line =
171 *base::CommandLine::ForCurrentProcess();
173 net::HostResolver::Options options;
175 // Use the retry attempts override from the command-line, if any.
176 if (command_line.HasSwitch(switches::kHostResolverRetryAttempts)) {
177 std::string s =
178 command_line.GetSwitchValueASCII(switches::kHostResolverRetryAttempts);
179 // Parse the switch (it should be a non-negative integer).
180 int n;
181 if (base::StringToInt(s, &n) && n >= 0) {
182 options.max_retry_attempts = static_cast<size_t>(n);
183 } else {
184 LOG(ERROR) << "Invalid switch for host resolver retry attempts: " << s;
188 scoped_ptr<net::HostResolver> global_host_resolver;
189 #if defined OS_CHROMEOS
190 global_host_resolver =
191 chromeos::HostResolverImplChromeOS::CreateSystemResolver(options,
192 net_log);
193 #else
194 global_host_resolver =
195 net::HostResolver::CreateSystemResolver(options, net_log);
196 #endif
198 // Determine if we should disable IPv6 support.
199 if (command_line.HasSwitch(switches::kEnableIPv6)) {
200 // Disable IPv6 probing.
201 global_host_resolver->SetDefaultAddressFamily(
202 net::ADDRESS_FAMILY_UNSPECIFIED);
203 } else if (command_line.HasSwitch(switches::kDisableIPv6)) {
204 global_host_resolver->SetDefaultAddressFamily(net::ADDRESS_FAMILY_IPV4);
207 // If hostname remappings were specified on the command-line, layer these
208 // rules on top of the real host resolver. This allows forwarding all requests
209 // through a designated test server.
210 if (!command_line.HasSwitch(switches::kHostResolverRules))
211 return global_host_resolver.Pass();
213 scoped_ptr<net::MappedHostResolver> remapped_resolver(
214 new net::MappedHostResolver(global_host_resolver.Pass()));
215 remapped_resolver->SetRulesFromString(
216 command_line.GetSwitchValueASCII(switches::kHostResolverRules));
217 return remapped_resolver.Pass();
220 // TODO(willchan): Remove proxy script fetcher context since it's not necessary
221 // now that I got rid of refcounting URLRequestContexts.
222 // See IOThread::Globals for details.
223 net::URLRequestContext*
224 ConstructProxyScriptFetcherContext(IOThread::Globals* globals,
225 net::NetLog* net_log) {
226 net::URLRequestContext* context = new net::URLRequestContext;
227 context->set_net_log(net_log);
228 context->set_host_resolver(globals->host_resolver.get());
229 context->set_cert_verifier(globals->cert_verifier.get());
230 context->set_transport_security_state(
231 globals->transport_security_state.get());
232 context->set_cert_transparency_verifier(
233 globals->cert_transparency_verifier.get());
234 context->set_http_auth_handler_factory(
235 globals->http_auth_handler_factory.get());
236 context->set_proxy_service(globals->proxy_script_fetcher_proxy_service.get());
237 context->set_http_transaction_factory(
238 globals->proxy_script_fetcher_http_transaction_factory.get());
239 context->set_job_factory(
240 globals->proxy_script_fetcher_url_request_job_factory.get());
241 context->set_cookie_store(globals->system_cookie_store.get());
242 context->set_channel_id_service(
243 globals->system_channel_id_service.get());
244 context->set_network_delegate(globals->system_network_delegate.get());
245 context->set_http_user_agent_settings(
246 globals->http_user_agent_settings.get());
247 // TODO(rtenneti): We should probably use HttpServerPropertiesManager for the
248 // system URLRequestContext too. There's no reason this should be tied to a
249 // profile.
250 return context;
253 net::URLRequestContext*
254 ConstructSystemRequestContext(IOThread::Globals* globals,
255 net::NetLog* net_log) {
256 net::URLRequestContext* context = new SystemURLRequestContext;
257 context->set_net_log(net_log);
258 context->set_host_resolver(globals->host_resolver.get());
259 context->set_cert_verifier(globals->cert_verifier.get());
260 context->set_transport_security_state(
261 globals->transport_security_state.get());
262 context->set_cert_transparency_verifier(
263 globals->cert_transparency_verifier.get());
264 context->set_http_auth_handler_factory(
265 globals->http_auth_handler_factory.get());
266 context->set_proxy_service(globals->system_proxy_service.get());
267 context->set_http_transaction_factory(
268 globals->system_http_transaction_factory.get());
269 context->set_job_factory(globals->system_url_request_job_factory.get());
270 context->set_cookie_store(globals->system_cookie_store.get());
271 context->set_channel_id_service(
272 globals->system_channel_id_service.get());
273 context->set_throttler_manager(globals->throttler_manager.get());
274 context->set_network_delegate(globals->system_network_delegate.get());
275 context->set_http_user_agent_settings(
276 globals->http_user_agent_settings.get());
277 return context;
280 int GetSwitchValueAsInt(const base::CommandLine& command_line,
281 const std::string& switch_name) {
282 int value;
283 if (!base::StringToInt(command_line.GetSwitchValueASCII(switch_name),
284 &value)) {
285 return 0;
287 return value;
290 // Returns the value associated with |key| in |params| or "" if the
291 // key is not present in the map.
292 const std::string& GetVariationParam(
293 const std::map<std::string, std::string>& params,
294 const std::string& key) {
295 std::map<std::string, std::string>::const_iterator it = params.find(key);
296 if (it == params.end())
297 return base::EmptyString();
299 return it->second;
302 // Return true if stale-while-revalidate support should be enabled.
303 bool IsStaleWhileRevalidateEnabled(const base::CommandLine& command_line) {
304 if (command_line.HasSwitch(switches::kEnableStaleWhileRevalidate))
305 return true;
306 const std::string group_name =
307 base::FieldTrialList::FindFullName(kStaleWhileRevalidateFieldTrialName);
308 return group_name == "Enabled";
311 bool IsCertificateTransparencyRequiredForEV(
312 const base::CommandLine& command_line) {
313 const std::string group_name =
314 base::FieldTrialList::FindFullName("CTRequiredForEVTrial");
316 if (command_line.HasSwitch(switches::kRequireCTForEV))
317 return true;
319 return group_name == "RequirementEnforced";
322 } // namespace
324 class IOThread::LoggingNetworkChangeObserver
325 : public net::NetworkChangeNotifier::IPAddressObserver,
326 public net::NetworkChangeNotifier::ConnectionTypeObserver,
327 public net::NetworkChangeNotifier::NetworkChangeObserver {
328 public:
329 // |net_log| must remain valid throughout our lifetime.
330 explicit LoggingNetworkChangeObserver(net::NetLog* net_log)
331 : net_log_(net_log) {
332 net::NetworkChangeNotifier::AddIPAddressObserver(this);
333 net::NetworkChangeNotifier::AddConnectionTypeObserver(this);
334 net::NetworkChangeNotifier::AddNetworkChangeObserver(this);
337 ~LoggingNetworkChangeObserver() override {
338 net::NetworkChangeNotifier::RemoveIPAddressObserver(this);
339 net::NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
340 net::NetworkChangeNotifier::RemoveNetworkChangeObserver(this);
343 // NetworkChangeNotifier::IPAddressObserver implementation.
344 void OnIPAddressChanged() override {
345 VLOG(1) << "Observed a change to the network IP addresses";
347 net_log_->AddGlobalEntry(net::NetLog::TYPE_NETWORK_IP_ADDRESSES_CHANGED);
350 // NetworkChangeNotifier::ConnectionTypeObserver implementation.
351 void OnConnectionTypeChanged(
352 net::NetworkChangeNotifier::ConnectionType type) override {
353 std::string type_as_string =
354 net::NetworkChangeNotifier::ConnectionTypeToString(type);
356 VLOG(1) << "Observed a change to network connectivity state "
357 << type_as_string;
359 net_log_->AddGlobalEntry(
360 net::NetLog::TYPE_NETWORK_CONNECTIVITY_CHANGED,
361 net::NetLog::StringCallback("new_connection_type", &type_as_string));
364 // NetworkChangeNotifier::NetworkChangeObserver implementation.
365 void OnNetworkChanged(
366 net::NetworkChangeNotifier::ConnectionType type) override {
367 std::string type_as_string =
368 net::NetworkChangeNotifier::ConnectionTypeToString(type);
370 VLOG(1) << "Observed a network change to state " << type_as_string;
372 net_log_->AddGlobalEntry(
373 net::NetLog::TYPE_NETWORK_CHANGED,
374 net::NetLog::StringCallback("new_connection_type", &type_as_string));
377 private:
378 net::NetLog* net_log_;
379 DISALLOW_COPY_AND_ASSIGN(LoggingNetworkChangeObserver);
382 class SystemURLRequestContextGetter : public net::URLRequestContextGetter {
383 public:
384 explicit SystemURLRequestContextGetter(IOThread* io_thread);
386 // Implementation for net::UrlRequestContextGetter.
387 net::URLRequestContext* GetURLRequestContext() override;
388 scoped_refptr<base::SingleThreadTaskRunner> GetNetworkTaskRunner()
389 const override;
391 protected:
392 ~SystemURLRequestContextGetter() override;
394 private:
395 IOThread* const io_thread_; // Weak pointer, owned by BrowserProcess.
396 scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_;
398 base::debug::LeakTracker<SystemURLRequestContextGetter> leak_tracker_;
401 SystemURLRequestContextGetter::SystemURLRequestContextGetter(
402 IOThread* io_thread)
403 : io_thread_(io_thread),
404 network_task_runner_(
405 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)) {
408 SystemURLRequestContextGetter::~SystemURLRequestContextGetter() {}
410 net::URLRequestContext* SystemURLRequestContextGetter::GetURLRequestContext() {
411 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
412 DCHECK(io_thread_->globals()->system_request_context.get());
414 return io_thread_->globals()->system_request_context.get();
417 scoped_refptr<base::SingleThreadTaskRunner>
418 SystemURLRequestContextGetter::GetNetworkTaskRunner() const {
419 return network_task_runner_;
422 IOThread::Globals::
423 SystemRequestContextLeakChecker::SystemRequestContextLeakChecker(
424 Globals* globals)
425 : globals_(globals) {
426 DCHECK(globals_);
429 IOThread::Globals::
430 SystemRequestContextLeakChecker::~SystemRequestContextLeakChecker() {
431 if (globals_->system_request_context.get())
432 globals_->system_request_context->AssertNoURLRequests();
435 IOThread::Globals::Globals()
436 : system_request_context_leak_checker(this),
437 enable_ssl_connect_job_waiting(false),
438 ignore_certificate_errors(false),
439 use_stale_while_revalidate(false),
440 testing_fixed_http_port(0),
441 testing_fixed_https_port(0),
442 enable_user_alternate_protocol_ports(false) {
445 IOThread::Globals::~Globals() {}
447 // |local_state| is passed in explicitly in order to (1) reduce implicit
448 // dependencies and (2) make IOThread more flexible for testing.
449 IOThread::IOThread(
450 PrefService* local_state,
451 policy::PolicyService* policy_service,
452 ChromeNetLog* net_log,
453 extensions::EventRouterForwarder* extension_event_router_forwarder)
454 : net_log_(net_log),
455 #if defined(ENABLE_EXTENSIONS)
456 extension_event_router_forwarder_(extension_event_router_forwarder),
457 #endif
458 globals_(NULL),
459 is_spdy_disabled_by_policy_(false),
460 creation_time_(base::TimeTicks::Now()),
461 weak_factory_(this) {
462 auth_schemes_ = local_state->GetString(prefs::kAuthSchemes);
463 negotiate_disable_cname_lookup_ = local_state->GetBoolean(
464 prefs::kDisableAuthNegotiateCnameLookup);
465 negotiate_enable_port_ = local_state->GetBoolean(
466 prefs::kEnableAuthNegotiatePort);
467 auth_server_whitelist_ = local_state->GetString(prefs::kAuthServerWhitelist);
468 auth_delegate_whitelist_ = local_state->GetString(
469 prefs::kAuthNegotiateDelegateWhitelist);
470 gssapi_library_name_ = local_state->GetString(prefs::kGSSAPILibraryName);
471 pref_proxy_config_tracker_.reset(
472 ProxyServiceFactory::CreatePrefProxyConfigTrackerOfLocalState(
473 local_state));
474 ChromeNetworkDelegate::InitializePrefsOnUIThread(
475 &system_enable_referrers_,
476 NULL,
477 NULL,
478 NULL,
479 NULL,
480 local_state);
481 ssl_config_service_manager_.reset(
482 SSLConfigServiceManager::CreateDefaultManager(local_state));
484 base::Value* dns_client_enabled_default = new base::FundamentalValue(
485 chrome_browser_net::ConfigureAsyncDnsFieldTrial());
486 local_state->SetDefaultPrefValue(prefs::kBuiltInDnsClientEnabled,
487 dns_client_enabled_default);
488 chrome_browser_net::LogAsyncDnsPrefSource(
489 local_state->FindPreference(prefs::kBuiltInDnsClientEnabled));
491 dns_client_enabled_.Init(prefs::kBuiltInDnsClientEnabled,
492 local_state,
493 base::Bind(&IOThread::UpdateDnsClientEnabled,
494 base::Unretained(this)));
495 dns_client_enabled_.MoveToThread(
496 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
498 quick_check_enabled_.Init(prefs::kQuickCheckEnabled,
499 local_state);
500 quick_check_enabled_.MoveToThread(
501 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
503 #if defined(ENABLE_CONFIGURATION_POLICY)
504 is_spdy_disabled_by_policy_ = policy_service->GetPolicies(
505 policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME, std::string())).Get(
506 policy::key::kDisableSpdy) != NULL;
507 #endif // ENABLE_CONFIGURATION_POLICY
509 BrowserThread::SetDelegate(BrowserThread::IO, this);
512 IOThread::~IOThread() {
513 // This isn't needed for production code, but in tests, IOThread may
514 // be multiply constructed.
515 BrowserThread::SetDelegate(BrowserThread::IO, NULL);
517 pref_proxy_config_tracker_->DetachFromPrefService();
518 DCHECK(!globals_);
521 IOThread::Globals* IOThread::globals() {
522 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
523 return globals_;
526 void IOThread::SetGlobalsForTesting(Globals* globals) {
527 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
528 DCHECK(!globals || !globals_);
529 globals_ = globals;
532 ChromeNetLog* IOThread::net_log() {
533 return net_log_;
536 void IOThread::ChangedToOnTheRecord() {
537 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
538 BrowserThread::PostTask(
539 BrowserThread::IO,
540 FROM_HERE,
541 base::Bind(&IOThread::ChangedToOnTheRecordOnIOThread,
542 base::Unretained(this)));
545 net::URLRequestContextGetter* IOThread::system_url_request_context_getter() {
546 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
547 if (!system_url_request_context_getter_.get()) {
548 InitSystemRequestContext();
550 return system_url_request_context_getter_.get();
553 void IOThread::Init() {
554 // Prefer to use InitAsync unless you need initialization to block
555 // the UI thread
558 void IOThread::InitAsync() {
559 TRACE_EVENT0("startup", "IOThread::InitAsync");
560 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
562 #if defined(USE_NSS) || defined(OS_IOS)
563 net::SetMessageLoopForNSSHttpIO();
564 #endif
566 const base::CommandLine& command_line =
567 *base::CommandLine::ForCurrentProcess();
569 DCHECK(!globals_);
570 globals_ = new Globals;
572 // Add an observer that will emit network change events to the ChromeNetLog.
573 // Assuming NetworkChangeNotifier dispatches in FIFO order, we should be
574 // logging the network change before other IO thread consumers respond to it.
575 network_change_observer_.reset(
576 new LoggingNetworkChangeObserver(net_log_));
578 // Setup the HistogramWatcher to run on the IO thread.
579 net::NetworkChangeNotifier::InitHistogramWatcher();
581 #if defined(ENABLE_EXTENSIONS)
582 globals_->extension_event_router_forwarder =
583 extension_event_router_forwarder_;
584 #endif
586 scoped_ptr<ChromeNetworkDelegate> chrome_network_delegate(
587 new ChromeNetworkDelegate(extension_event_router_forwarder(),
588 &system_enable_referrers_));
590 #if defined(ENABLE_EXTENSIONS)
591 if (command_line.HasSwitch(switches::kDisableExtensionsHttpThrottling))
592 chrome_network_delegate->NeverThrottleRequests();
593 #endif
595 globals_->system_network_delegate = chrome_network_delegate.Pass();
596 globals_->host_resolver = CreateGlobalHostResolver(net_log_);
597 UpdateDnsClientEnabled();
598 #if defined(OS_CHROMEOS)
599 // Creates a CertVerifyProc that doesn't allow any profile-provided certs.
600 globals_->cert_verifier.reset(new net::MultiThreadedCertVerifier(
601 new chromeos::CertVerifyProcChromeOS()));
602 #else
603 globals_->cert_verifier.reset(new net::MultiThreadedCertVerifier(
604 net::CertVerifyProc::CreateDefault()));
605 #endif
607 globals_->transport_security_state.reset(new net::TransportSecurityState());
609 net::MultiLogCTVerifier* ct_verifier = new net::MultiLogCTVerifier();
610 globals_->cert_transparency_verifier.reset(ct_verifier);
612 // Add built-in logs
613 ct_verifier->AddLogs(net::ct::CreateLogVerifiersForKnownLogs());
615 // Add logs from command line
616 if (command_line.HasSwitch(switches::kCertificateTransparencyLog)) {
617 std::string switch_value = command_line.GetSwitchValueASCII(
618 switches::kCertificateTransparencyLog);
619 std::vector<std::string> logs;
620 base::SplitString(switch_value, ',', &logs);
621 for (std::vector<std::string>::iterator it = logs.begin(); it != logs.end();
622 ++it) {
623 const std::string& curr_log = *it;
624 size_t delim_pos = curr_log.find(":");
625 CHECK(delim_pos != std::string::npos)
626 << "CT log description not provided (switch format"
627 " is 'description:base64_key')";
628 std::string log_description(curr_log.substr(0, delim_pos));
629 std::string ct_public_key_data;
630 CHECK(base::Base64Decode(curr_log.substr(delim_pos + 1),
631 &ct_public_key_data))
632 << "Unable to decode CT public key.";
633 scoped_ptr<net::CTLogVerifier> external_log_verifier(
634 net::CTLogVerifier::Create(ct_public_key_data, log_description));
635 CHECK(external_log_verifier) << "Unable to parse CT public key.";
636 VLOG(1) << "Adding log with description " << log_description;
637 ct_verifier->AddLog(external_log_verifier.Pass());
641 net::CertPolicyEnforcer* policy_enforcer = NULL;
642 policy_enforcer = new net::CertPolicyEnforcer(
643 IsCertificateTransparencyRequiredForEV(command_line));
644 globals_->cert_policy_enforcer.reset(policy_enforcer);
646 globals_->ssl_config_service = GetSSLConfigService();
648 globals_->http_auth_handler_factory.reset(CreateDefaultAuthHandlerFactory(
649 globals_->host_resolver.get()));
650 globals_->http_server_properties.reset(new net::HttpServerPropertiesImpl());
651 // For the ProxyScriptFetcher, we use a direct ProxyService.
652 globals_->proxy_script_fetcher_proxy_service.reset(
653 net::ProxyService::CreateDirectWithNetLog(net_log_));
654 // In-memory cookie store.
655 globals_->system_cookie_store =
656 content::CreateCookieStore(content::CookieStoreConfig());
657 // In-memory channel ID store.
658 globals_->system_channel_id_service.reset(
659 new net::ChannelIDService(
660 new net::DefaultChannelIDStore(NULL),
661 base::WorkerPool::GetTaskRunner(true)));
662 globals_->dns_probe_service.reset(new chrome_browser_net::DnsProbeService());
663 globals_->host_mapping_rules.reset(new net::HostMappingRules());
664 globals_->http_user_agent_settings.reset(
665 new net::StaticHttpUserAgentSettings(std::string(), GetUserAgent()));
666 if (command_line.HasSwitch(switches::kHostRules)) {
667 TRACE_EVENT_BEGIN0("startup", "IOThread::InitAsync:SetRulesFromString");
668 globals_->host_mapping_rules->SetRulesFromString(
669 command_line.GetSwitchValueASCII(switches::kHostRules));
670 TRACE_EVENT_END0("startup", "IOThread::InitAsync:SetRulesFromString");
672 if (command_line.HasSwitch(switches::kEnableSSLConnectJobWaiting))
673 globals_->enable_ssl_connect_job_waiting = true;
674 if (command_line.HasSwitch(switches::kIgnoreCertificateErrors))
675 globals_->ignore_certificate_errors = true;
676 globals_->use_stale_while_revalidate =
677 IsStaleWhileRevalidateEnabled(command_line);
678 if (command_line.HasSwitch(switches::kTestingFixedHttpPort)) {
679 globals_->testing_fixed_http_port =
680 GetSwitchValueAsInt(command_line, switches::kTestingFixedHttpPort);
682 if (command_line.HasSwitch(switches::kTestingFixedHttpsPort)) {
683 globals_->testing_fixed_https_port =
684 GetSwitchValueAsInt(command_line, switches::kTestingFixedHttpsPort);
686 ConfigureQuic(command_line);
687 if (command_line.HasSwitch(
688 switches::kEnableUserAlternateProtocolPorts)) {
689 globals_->enable_user_alternate_protocol_ports = true;
691 InitializeNetworkOptions(command_line);
693 net::HttpNetworkSession::Params session_params;
694 InitializeNetworkSessionParams(&session_params);
695 session_params.net_log = net_log_;
696 session_params.proxy_service =
697 globals_->proxy_script_fetcher_proxy_service.get();
699 TRACE_EVENT_BEGIN0("startup", "IOThread::InitAsync:HttpNetworkSession");
700 scoped_refptr<net::HttpNetworkSession> network_session(
701 new net::HttpNetworkSession(session_params));
702 globals_->proxy_script_fetcher_http_transaction_factory
703 .reset(new net::HttpNetworkLayer(network_session.get()));
704 TRACE_EVENT_END0("startup", "IOThread::InitAsync:HttpNetworkSession");
705 scoped_ptr<net::URLRequestJobFactoryImpl> job_factory(
706 new net::URLRequestJobFactoryImpl());
707 job_factory->SetProtocolHandler(url::kDataScheme,
708 new net::DataProtocolHandler());
709 job_factory->SetProtocolHandler(
710 url::kFileScheme,
711 new net::FileProtocolHandler(
712 content::BrowserThread::GetBlockingPool()->
713 GetTaskRunnerWithShutdownBehavior(
714 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)));
715 #if !defined(DISABLE_FTP_SUPPORT)
716 globals_->proxy_script_fetcher_ftp_transaction_factory.reset(
717 new net::FtpNetworkLayer(globals_->host_resolver.get()));
718 job_factory->SetProtocolHandler(
719 url::kFtpScheme,
720 new net::FtpProtocolHandler(
721 globals_->proxy_script_fetcher_ftp_transaction_factory.get()));
722 #endif
723 globals_->proxy_script_fetcher_url_request_job_factory = job_factory.Pass();
725 globals_->throttler_manager.reset(new net::URLRequestThrottlerManager());
726 globals_->throttler_manager->set_net_log(net_log_);
727 // Always done in production, disabled only for unit tests.
728 globals_->throttler_manager->set_enable_thread_checks(true);
730 globals_->proxy_script_fetcher_context.reset(
731 ConstructProxyScriptFetcherContext(globals_, net_log_));
733 #if defined(OS_MACOSX) && !defined(OS_IOS)
734 // Start observing Keychain events. This needs to be done on the UI thread,
735 // as Keychain services requires a CFRunLoop.
736 BrowserThread::PostTask(BrowserThread::UI,
737 FROM_HERE,
738 base::Bind(&ObserveKeychainEvents));
739 #endif
741 // InitSystemRequestContext turns right around and posts a task back
742 // to the IO thread, so we can't let it run until we know the IO
743 // thread has started.
745 // Note that since we are at BrowserThread::Init time, the UI thread
746 // is blocked waiting for the thread to start. Therefore, posting
747 // this task to the main thread's message loop here is guaranteed to
748 // get it onto the message loop while the IOThread object still
749 // exists. However, the message might not be processed on the UI
750 // thread until after IOThread is gone, so use a weak pointer.
751 BrowserThread::PostTask(BrowserThread::UI,
752 FROM_HERE,
753 base::Bind(&IOThread::InitSystemRequestContext,
754 weak_factory_.GetWeakPtr()));
757 void IOThread::CleanUp() {
758 base::debug::LeakTracker<SafeBrowsingURLRequestContext>::CheckForLeaks();
760 #if defined(USE_NSS) || defined(OS_IOS)
761 net::ShutdownNSSHttpIO();
762 #endif
764 system_url_request_context_getter_ = NULL;
766 // Release objects that the net::URLRequestContext could have been pointing
767 // to.
769 // Shutdown the HistogramWatcher on the IO thread.
770 net::NetworkChangeNotifier::ShutdownHistogramWatcher();
772 // This must be reset before the ChromeNetLog is destroyed.
773 network_change_observer_.reset();
775 system_proxy_config_service_.reset();
777 delete globals_;
778 globals_ = NULL;
780 base::debug::LeakTracker<SystemURLRequestContextGetter>::CheckForLeaks();
783 void IOThread::InitializeNetworkOptions(const base::CommandLine& command_line) {
784 // Only handle use-spdy command line flags if "spdy.disabled" preference is
785 // not disabled via policy.
786 if (is_spdy_disabled_by_policy_) {
787 base::FieldTrial* trial = base::FieldTrialList::Find(kSpdyFieldTrialName);
788 if (trial)
789 trial->Disable();
790 } else {
791 if (command_line.HasSwitch(switches::kTrustedSpdyProxy)) {
792 globals_->trusted_spdy_proxy.set(
793 command_line.GetSwitchValueASCII(switches::kTrustedSpdyProxy));
795 if (command_line.HasSwitch(switches::kIgnoreUrlFetcherCertRequests))
796 net::URLFetcher::SetIgnoreCertificateRequests(true);
798 if (command_line.HasSwitch(switches::kUseSpdy)) {
799 std::string spdy_mode =
800 command_line.GetSwitchValueASCII(switches::kUseSpdy);
801 EnableSpdy(spdy_mode);
802 } else if (command_line.HasSwitch(switches::kEnableSpdy4)) {
803 globals_->next_protos = net::NextProtosSpdy4Http2();
804 globals_->use_alternate_protocols.set(true);
805 } else if (command_line.HasSwitch(switches::kEnableNpnHttpOnly)) {
806 globals_->next_protos = net::NextProtosHttpOnly();
807 globals_->use_alternate_protocols.set(false);
808 } else {
809 // No SPDY command-line flags have been specified. Examine trial groups.
810 ConfigureSpdyFromTrial(
811 base::FieldTrialList::FindFullName(kSpdyFieldTrialName), globals_);
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 base::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(base::StringPiece spdy_trial_group,
836 Globals* globals) {
837 if (spdy_trial_group.starts_with(kSpdyFieldTrialHoldbackGroupNamePrefix)) {
838 // TODO(jgraettinger): Use net::NextProtosHttpOnly() instead?
839 net::HttpStreamFactory::set_spdy_enabled(false);
840 } else if (spdy_trial_group.starts_with(
841 kSpdyFieldTrialSpdy31GroupNamePrefix)) {
842 globals->next_protos = net::NextProtosSpdy31();
843 globals->use_alternate_protocols.set(true);
844 } else if (spdy_trial_group.starts_with(
845 kSpdyFieldTrialSpdy4GroupNamePrefix)) {
846 globals->next_protos = net::NextProtosSpdy4Http2();
847 globals->use_alternate_protocols.set(true);
848 } else {
849 // By default, enable HTTP/2.
850 globals->next_protos = net::NextProtosSpdy4Http2();
851 globals->use_alternate_protocols.set(true);
855 void IOThread::EnableSpdy(const std::string& mode) {
856 static const char kOff[] = "off";
857 static const char kSSL[] = "ssl";
858 static const char kDisableSSL[] = "no-ssl";
859 static const char kDisablePing[] = "no-ping";
860 static const char kExclude[] = "exclude"; // Hosts to exclude
861 static const char kDisableCompression[] = "no-compress";
862 static const char kDisableAltProtocols[] = "no-alt-protocols";
863 static const char kForceAltProtocols[] = "force-alt-protocols";
864 static const char kSingleDomain[] = "single-domain";
866 static const char kInitialMaxConcurrentStreams[] = "init-max-streams";
868 std::vector<std::string> spdy_options;
869 base::SplitString(mode, ',', &spdy_options);
871 for (std::vector<std::string>::iterator it = spdy_options.begin();
872 it != spdy_options.end(); ++it) {
873 const std::string& element = *it;
874 std::vector<std::string> name_value;
875 base::SplitString(element, '=', &name_value);
876 const std::string& option =
877 name_value.size() > 0 ? name_value[0] : std::string();
878 const std::string value =
879 name_value.size() > 1 ? name_value[1] : std::string();
881 if (option == kOff) {
882 net::HttpStreamFactory::set_spdy_enabled(false);
883 } else if (option == kDisableSSL) {
884 globals_->spdy_default_protocol.set(net::kProtoSPDY31);
885 globals_->force_spdy_over_ssl.set(false);
886 globals_->force_spdy_always.set(true);
887 } else if (option == kSSL) {
888 globals_->spdy_default_protocol.set(net::kProtoSPDY31);
889 globals_->force_spdy_over_ssl.set(true);
890 globals_->force_spdy_always.set(true);
891 } else if (option == kDisablePing) {
892 globals_->enable_spdy_ping_based_connection_checking.set(false);
893 } else if (option == kExclude) {
894 globals_->forced_spdy_exclusions.insert(
895 net::HostPortPair::FromURL(GURL(value)));
896 } else if (option == kDisableCompression) {
897 globals_->enable_spdy_compression.set(false);
898 } else if (option == kDisableAltProtocols) {
899 globals_->use_alternate_protocols.set(false);
900 } else if (option == kForceAltProtocols) {
901 net::AlternateProtocolInfo pair(443, net::NPN_SPDY_3, 1);
902 base::RecordAction(base::UserMetricsAction("Net.ForceAlternateProtocol"));
903 net::HttpServerPropertiesImpl::ForceAlternateProtocol(pair);
904 } else if (option == kSingleDomain) {
905 DVLOG(1) << "FORCING SINGLE DOMAIN";
906 globals_->force_spdy_single_domain.set(true);
907 } else if (option == kInitialMaxConcurrentStreams) {
908 int streams;
909 if (base::StringToInt(value, &streams))
910 globals_->initial_max_spdy_concurrent_streams.set(streams);
911 } else if (option.empty() && it == spdy_options.begin()) {
912 continue;
913 } else {
914 LOG(DFATAL) << "Unrecognized spdy option: " << option;
919 // static
920 void IOThread::RegisterPrefs(PrefRegistrySimple* registry) {
921 registry->RegisterStringPref(prefs::kAuthSchemes,
922 "basic,digest,ntlm,negotiate,"
923 "spdyproxy");
924 registry->RegisterBooleanPref(prefs::kDisableAuthNegotiateCnameLookup, false);
925 registry->RegisterBooleanPref(prefs::kEnableAuthNegotiatePort, false);
926 registry->RegisterStringPref(prefs::kAuthServerWhitelist, std::string());
927 registry->RegisterStringPref(prefs::kAuthNegotiateDelegateWhitelist,
928 std::string());
929 registry->RegisterStringPref(prefs::kGSSAPILibraryName, std::string());
930 registry->RegisterStringPref(
931 data_reduction_proxy::prefs::kDataReductionProxy, std::string());
932 registry->RegisterBooleanPref(prefs::kEnableReferrers, true);
933 data_reduction_proxy::RegisterPrefs(registry);
934 registry->RegisterBooleanPref(prefs::kBuiltInDnsClientEnabled, true);
935 registry->RegisterBooleanPref(prefs::kQuickCheckEnabled, true);
938 net::HttpAuthHandlerFactory* IOThread::CreateDefaultAuthHandlerFactory(
939 net::HostResolver* resolver) {
940 net::HttpAuthFilterWhitelist* auth_filter_default_credentials = NULL;
941 if (!auth_server_whitelist_.empty()) {
942 auth_filter_default_credentials =
943 new net::HttpAuthFilterWhitelist(auth_server_whitelist_);
945 net::HttpAuthFilterWhitelist* auth_filter_delegate = NULL;
946 if (!auth_delegate_whitelist_.empty()) {
947 auth_filter_delegate =
948 new net::HttpAuthFilterWhitelist(auth_delegate_whitelist_);
950 globals_->url_security_manager.reset(
951 net::URLSecurityManager::Create(auth_filter_default_credentials,
952 auth_filter_delegate));
953 std::vector<std::string> supported_schemes;
954 base::SplitString(auth_schemes_, ',', &supported_schemes);
956 scoped_ptr<net::HttpAuthHandlerRegistryFactory> registry_factory(
957 net::HttpAuthHandlerRegistryFactory::Create(
958 supported_schemes, globals_->url_security_manager.get(),
959 resolver, gssapi_library_name_, negotiate_disable_cname_lookup_,
960 negotiate_enable_port_));
961 return registry_factory.release();
964 void IOThread::ClearHostCache() {
965 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
967 net::HostCache* host_cache = globals_->host_resolver->GetHostCache();
968 if (host_cache)
969 host_cache->clear();
972 void IOThread::InitializeNetworkSessionParams(
973 net::HttpNetworkSession::Params* params) {
974 InitializeNetworkSessionParamsFromGlobals(*globals_, params);
977 // static
978 void IOThread::InitializeNetworkSessionParamsFromGlobals(
979 const IOThread::Globals& globals,
980 net::HttpNetworkSession::Params* params) {
981 params->host_resolver = globals.host_resolver.get();
982 params->cert_verifier = globals.cert_verifier.get();
983 params->cert_policy_enforcer = globals.cert_policy_enforcer.get();
984 params->channel_id_service = globals.system_channel_id_service.get();
985 params->transport_security_state = globals.transport_security_state.get();
986 params->ssl_config_service = globals.ssl_config_service.get();
987 params->http_auth_handler_factory = globals.http_auth_handler_factory.get();
988 params->http_server_properties =
989 globals.http_server_properties->GetWeakPtr();
990 params->network_delegate = globals.system_network_delegate.get();
991 params->host_mapping_rules = globals.host_mapping_rules.get();
992 params->enable_ssl_connect_job_waiting =
993 globals.enable_ssl_connect_job_waiting;
994 params->ignore_certificate_errors = globals.ignore_certificate_errors;
995 params->use_stale_while_revalidate = globals.use_stale_while_revalidate;
996 params->testing_fixed_http_port = globals.testing_fixed_http_port;
997 params->testing_fixed_https_port = globals.testing_fixed_https_port;
998 globals.enable_tcp_fast_open_for_ssl.CopyToIfSet(
999 &params->enable_tcp_fast_open_for_ssl);
1001 globals.initial_max_spdy_concurrent_streams.CopyToIfSet(
1002 &params->spdy_initial_max_concurrent_streams);
1003 globals.force_spdy_single_domain.CopyToIfSet(
1004 &params->force_spdy_single_domain);
1005 globals.enable_spdy_compression.CopyToIfSet(
1006 &params->enable_spdy_compression);
1007 globals.enable_spdy_ping_based_connection_checking.CopyToIfSet(
1008 &params->enable_spdy_ping_based_connection_checking);
1009 globals.spdy_default_protocol.CopyToIfSet(
1010 &params->spdy_default_protocol);
1011 params->next_protos = globals.next_protos;
1012 globals.trusted_spdy_proxy.CopyToIfSet(&params->trusted_spdy_proxy);
1013 globals.force_spdy_over_ssl.CopyToIfSet(&params->force_spdy_over_ssl);
1014 globals.force_spdy_always.CopyToIfSet(&params->force_spdy_always);
1015 params->forced_spdy_exclusions = globals.forced_spdy_exclusions;
1016 globals.use_alternate_protocols.CopyToIfSet(
1017 &params->use_alternate_protocols);
1018 globals.alternate_protocol_probability_threshold.CopyToIfSet(
1019 &params->alternate_protocol_probability_threshold);
1021 globals.enable_quic.CopyToIfSet(&params->enable_quic);
1022 globals.enable_quic_for_proxies.CopyToIfSet(&params->enable_quic_for_proxies);
1023 globals.quic_always_require_handshake_confirmation.CopyToIfSet(
1024 &params->quic_always_require_handshake_confirmation);
1025 globals.quic_disable_connection_pooling.CopyToIfSet(
1026 &params->quic_disable_connection_pooling);
1027 globals.quic_load_server_info_timeout_ms.CopyToIfSet(
1028 &params->quic_load_server_info_timeout_ms);
1029 globals.quic_load_server_info_timeout_srtt_multiplier.CopyToIfSet(
1030 &params->quic_load_server_info_timeout_srtt_multiplier);
1031 globals.quic_enable_truncated_connection_ids.CopyToIfSet(
1032 &params->quic_enable_truncated_connection_ids);
1033 globals.quic_enable_connection_racing.CopyToIfSet(
1034 &params->quic_enable_connection_racing);
1035 globals.quic_enable_non_blocking_io.CopyToIfSet(
1036 &params->quic_enable_non_blocking_io);
1037 globals.quic_disable_disk_cache.CopyToIfSet(
1038 &params->quic_disable_disk_cache);
1039 globals.quic_socket_receive_buffer_size.CopyToIfSet(
1040 &params->quic_socket_receive_buffer_size);
1041 globals.enable_quic_port_selection.CopyToIfSet(
1042 &params->enable_quic_port_selection);
1043 globals.quic_max_packet_length.CopyToIfSet(&params->quic_max_packet_length);
1044 globals.quic_user_agent_id.CopyToIfSet(&params->quic_user_agent_id);
1045 globals.quic_supported_versions.CopyToIfSet(
1046 &params->quic_supported_versions);
1047 params->quic_connection_options = globals.quic_connection_options;
1049 globals.origin_to_force_quic_on.CopyToIfSet(
1050 &params->origin_to_force_quic_on);
1051 params->enable_user_alternate_protocol_ports =
1052 globals.enable_user_alternate_protocol_ports;
1055 base::TimeTicks IOThread::creation_time() const {
1056 return creation_time_;
1059 net::SSLConfigService* IOThread::GetSSLConfigService() {
1060 return ssl_config_service_manager_->Get();
1063 void IOThread::ChangedToOnTheRecordOnIOThread() {
1064 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1066 // Clear the host cache to avoid showing entries from the OTR session
1067 // in about:net-internals.
1068 ClearHostCache();
1071 void IOThread::InitSystemRequestContext() {
1072 if (system_url_request_context_getter_.get())
1073 return;
1074 // If we're in unit_tests, IOThread may not be run.
1075 if (!BrowserThread::IsMessageLoopValid(BrowserThread::IO))
1076 return;
1077 system_proxy_config_service_.reset(
1078 ProxyServiceFactory::CreateProxyConfigService(
1079 pref_proxy_config_tracker_.get()));
1080 system_url_request_context_getter_ =
1081 new SystemURLRequestContextGetter(this);
1082 // Safe to post an unretained this pointer, since IOThread is
1083 // guaranteed to outlive the IO BrowserThread.
1084 BrowserThread::PostTask(
1085 BrowserThread::IO,
1086 FROM_HERE,
1087 base::Bind(&IOThread::InitSystemRequestContextOnIOThread,
1088 base::Unretained(this)));
1091 void IOThread::InitSystemRequestContextOnIOThread() {
1092 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1093 DCHECK(!globals_->system_proxy_service.get());
1094 DCHECK(system_proxy_config_service_.get());
1096 const base::CommandLine& command_line =
1097 *base::CommandLine::ForCurrentProcess();
1098 globals_->system_proxy_service.reset(
1099 ProxyServiceFactory::CreateProxyService(
1100 net_log_,
1101 globals_->proxy_script_fetcher_context.get(),
1102 globals_->system_network_delegate.get(),
1103 system_proxy_config_service_.release(),
1104 command_line,
1105 quick_check_enabled_.GetValue()));
1107 net::HttpNetworkSession::Params system_params;
1108 InitializeNetworkSessionParams(&system_params);
1109 system_params.net_log = net_log_;
1110 system_params.proxy_service = globals_->system_proxy_service.get();
1112 globals_->system_http_transaction_factory.reset(
1113 new net::HttpNetworkLayer(
1114 new net::HttpNetworkSession(system_params)));
1115 globals_->system_url_request_job_factory.reset(
1116 new net::URLRequestJobFactoryImpl());
1117 globals_->system_request_context.reset(
1118 ConstructSystemRequestContext(globals_, net_log_));
1119 globals_->system_request_context->set_ssl_config_service(
1120 globals_->ssl_config_service.get());
1121 globals_->system_request_context->set_http_server_properties(
1122 globals_->http_server_properties->GetWeakPtr());
1125 void IOThread::UpdateDnsClientEnabled() {
1126 globals()->host_resolver->SetDnsClientEnabled(*dns_client_enabled_);
1129 void IOThread::ConfigureQuic(const base::CommandLine& command_line) {
1130 // Always fetch the field trial group to ensure it is reported correctly.
1131 // The command line flags will be associated with a group that is reported
1132 // so long as trial is actually queried.
1133 std::string group =
1134 base::FieldTrialList::FindFullName(kQuicFieldTrialName);
1135 VariationParameters params;
1136 if (!variations::GetVariationParams(kQuicFieldTrialName, &params)) {
1137 params.clear();
1140 ConfigureQuicGlobals(command_line, group, params, globals_);
1143 // static
1144 void IOThread::ConfigureQuicGlobals(
1145 const base::CommandLine& command_line,
1146 base::StringPiece quic_trial_group,
1147 const VariationParameters& quic_trial_params,
1148 IOThread::Globals* globals) {
1149 bool enable_quic = ShouldEnableQuic(command_line, quic_trial_group);
1150 globals->enable_quic.set(enable_quic);
1151 bool enable_quic_for_proxies = ShouldEnableQuicForProxies(command_line,
1152 quic_trial_group);
1153 globals->enable_quic_for_proxies.set(enable_quic_for_proxies);
1154 if (enable_quic) {
1155 globals->quic_always_require_handshake_confirmation.set(
1156 ShouldQuicAlwaysRequireHandshakeConfirmation(quic_trial_params));
1157 globals->quic_disable_connection_pooling.set(
1158 ShouldQuicDisableConnectionPooling(quic_trial_params));
1159 int load_server_info_timeout_ms =
1160 GetQuicLoadServerInfoTimeout(quic_trial_params);
1161 if (load_server_info_timeout_ms != 0) {
1162 globals->quic_load_server_info_timeout_ms.set(
1163 load_server_info_timeout_ms);
1165 globals->quic_enable_truncated_connection_ids.set(
1166 ShouldQuicEnableTruncatedConnectionIds(quic_trial_params));
1167 globals->quic_enable_connection_racing.set(
1168 ShouldQuicEnableConnectionRacing(quic_trial_params));
1169 int receive_buffer_size = GetQuicSocketReceiveBufferSize(quic_trial_params);
1170 if (receive_buffer_size != 0) {
1171 globals->quic_socket_receive_buffer_size.set(receive_buffer_size);
1173 float load_server_info_timeout_srtt_multiplier =
1174 GetQuicLoadServerInfoTimeoutSrttMultiplier(quic_trial_params);
1175 if (load_server_info_timeout_srtt_multiplier != 0) {
1176 globals->quic_load_server_info_timeout_srtt_multiplier.set(
1177 load_server_info_timeout_srtt_multiplier);
1179 globals->quic_enable_truncated_connection_ids.set(
1180 ShouldQuicEnableTruncatedConnectionIds(quic_trial_params));
1181 globals->quic_enable_connection_racing.set(
1182 ShouldQuicEnableConnectionRacing(quic_trial_params));
1183 globals->quic_enable_non_blocking_io.set(
1184 ShouldQuicEnableNonBlockingIO(quic_trial_params));
1185 globals->quic_disable_disk_cache.set(
1186 ShouldQuicDisableDiskCache(quic_trial_params));
1187 globals->enable_quic_port_selection.set(
1188 ShouldEnableQuicPortSelection(command_line));
1189 globals->quic_connection_options =
1190 GetQuicConnectionOptions(command_line, quic_trial_params);
1191 if (ShouldEnableQuicPacing(command_line, quic_trial_params)) {
1192 globals->quic_connection_options.push_back(net::kPACE);
1196 size_t max_packet_length = GetQuicMaxPacketLength(command_line,
1197 quic_trial_params);
1198 if (max_packet_length != 0) {
1199 globals->quic_max_packet_length.set(max_packet_length);
1202 std::string quic_user_agent_id =
1203 chrome::VersionInfo::GetVersionStringModifier();
1204 if (!quic_user_agent_id.empty())
1205 quic_user_agent_id.push_back(' ');
1206 chrome::VersionInfo version_info;
1207 quic_user_agent_id.append(version_info.ProductNameAndVersionForUserAgent());
1208 globals->quic_user_agent_id.set(quic_user_agent_id);
1210 net::QuicVersion version = GetQuicVersion(command_line, quic_trial_params);
1211 if (version != net::QUIC_VERSION_UNSUPPORTED) {
1212 net::QuicVersionVector supported_versions;
1213 supported_versions.push_back(version);
1214 globals->quic_supported_versions.set(supported_versions);
1217 double threshold =
1218 GetAlternateProtocolProbabilityThreshold(command_line, quic_trial_params);
1219 if (threshold >=0 && threshold <= 1) {
1220 globals->alternate_protocol_probability_threshold.set(threshold);
1221 globals->http_server_properties->SetAlternateProtocolProbabilityThreshold(
1222 threshold);
1225 if (command_line.HasSwitch(switches::kOriginToForceQuicOn)) {
1226 net::HostPortPair quic_origin =
1227 net::HostPortPair::FromString(
1228 command_line.GetSwitchValueASCII(switches::kOriginToForceQuicOn));
1229 if (!quic_origin.IsEmpty()) {
1230 globals->origin_to_force_quic_on.set(quic_origin);
1235 bool IOThread::ShouldEnableQuic(const base::CommandLine& command_line,
1236 base::StringPiece quic_trial_group) {
1237 if (command_line.HasSwitch(switches::kDisableQuic))
1238 return false;
1240 if (command_line.HasSwitch(switches::kEnableQuic))
1241 return true;
1243 return quic_trial_group.starts_with(kQuicFieldTrialEnabledGroupName) ||
1244 quic_trial_group.starts_with(kQuicFieldTrialHttpsEnabledGroupName);
1247 // static
1248 bool IOThread::ShouldEnableQuicForProxies(const base::CommandLine& command_line,
1249 base::StringPiece quic_trial_group) {
1250 return ShouldEnableQuic(command_line, quic_trial_group) ||
1251 ShouldEnableQuicForDataReductionProxy();
1254 // static
1255 bool IOThread::ShouldEnableQuicForDataReductionProxy() {
1256 const base::CommandLine& command_line =
1257 *base::CommandLine::ForCurrentProcess();
1259 if (command_line.HasSwitch(switches::kDisableQuic))
1260 return false;
1262 return data_reduction_proxy::DataReductionProxyParams::
1263 IsIncludedInQuicFieldTrial();
1266 bool IOThread::ShouldEnableQuicPortSelection(
1267 const base::CommandLine& command_line) {
1268 if (command_line.HasSwitch(switches::kDisableQuicPortSelection))
1269 return false;
1271 if (command_line.HasSwitch(switches::kEnableQuicPortSelection))
1272 return true;
1274 return false; // Default to disabling port selection on all channels.
1277 bool IOThread::ShouldEnableQuicPacing(
1278 const base::CommandLine& command_line,
1279 const VariationParameters& quic_trial_params) {
1280 if (command_line.HasSwitch(switches::kEnableQuicPacing))
1281 return true;
1283 if (command_line.HasSwitch(switches::kDisableQuicPacing))
1284 return false;
1286 return LowerCaseEqualsASCII(
1287 GetVariationParam(quic_trial_params, "enable_pacing"),
1288 "true");
1291 net::QuicTagVector IOThread::GetQuicConnectionOptions(
1292 const base::CommandLine& command_line,
1293 const VariationParameters& quic_trial_params) {
1294 if (command_line.HasSwitch(switches::kQuicConnectionOptions)) {
1295 return net::QuicUtils::ParseQuicConnectionOptions(
1296 command_line.GetSwitchValueASCII(switches::kQuicConnectionOptions));
1299 VariationParameters::const_iterator it =
1300 quic_trial_params.find("connection_options");
1301 if (it == quic_trial_params.end()) {
1302 return net::QuicTagVector();
1305 return net::QuicUtils::ParseQuicConnectionOptions(it->second);
1308 // static
1309 double IOThread::GetAlternateProtocolProbabilityThreshold(
1310 const base::CommandLine& command_line,
1311 const VariationParameters& quic_trial_params) {
1312 double value;
1313 if (command_line.HasSwitch(
1314 switches::kAlternateProtocolProbabilityThreshold)) {
1315 if (base::StringToDouble(
1316 command_line.GetSwitchValueASCII(
1317 switches::kAlternateProtocolProbabilityThreshold),
1318 &value)) {
1319 return value;
1322 if (command_line.HasSwitch(switches::kEnableQuic)) {
1323 return 0;
1325 if (base::StringToDouble(
1326 GetVariationParam(quic_trial_params,
1327 "alternate_protocol_probability_threshold"),
1328 &value)) {
1329 return value;
1331 return -1;
1334 // static
1335 bool IOThread::ShouldQuicAlwaysRequireHandshakeConfirmation(
1336 const VariationParameters& quic_trial_params) {
1337 return LowerCaseEqualsASCII(
1338 GetVariationParam(quic_trial_params,
1339 "always_require_handshake_confirmation"),
1340 "true");
1343 // static
1344 bool IOThread::ShouldQuicDisableConnectionPooling(
1345 const VariationParameters& quic_trial_params) {
1346 return LowerCaseEqualsASCII(
1347 GetVariationParam(quic_trial_params, "disable_connection_pooling"),
1348 "true");
1351 // static
1352 int IOThread::GetQuicLoadServerInfoTimeout(
1353 const VariationParameters& quic_trial_params) {
1354 int value;
1355 if (base::StringToInt(GetVariationParam(quic_trial_params,
1356 "load_server_info_timeout"),
1357 &value)) {
1358 return value;
1360 return 0;
1363 // static
1364 float IOThread::GetQuicLoadServerInfoTimeoutSrttMultiplier(
1365 const VariationParameters& quic_trial_params) {
1366 double value;
1367 if (base::StringToDouble(GetVariationParam(quic_trial_params,
1368 "load_server_info_time_to_srtt"),
1369 &value)) {
1370 return (float)value;
1372 return 0.0f;
1375 // static
1376 bool IOThread::ShouldQuicEnableTruncatedConnectionIds(
1377 const VariationParameters& quic_trial_params) {
1378 return LowerCaseEqualsASCII(
1379 GetVariationParam(quic_trial_params, "enable_truncated_connection_ids"),
1380 "true");
1383 // static
1384 bool IOThread::ShouldQuicEnableConnectionRacing(
1385 const VariationParameters& quic_trial_params) {
1386 return LowerCaseEqualsASCII(
1387 GetVariationParam(quic_trial_params, "enable_connection_racing"),
1388 "true");
1391 // static
1392 bool IOThread::ShouldQuicEnableNonBlockingIO(
1393 const VariationParameters& quic_trial_params) {
1394 return LowerCaseEqualsASCII(
1395 GetVariationParam(quic_trial_params, "enable_non_blocking_io"),
1396 "true");
1399 // static
1400 bool IOThread::ShouldQuicDisableDiskCache(
1401 const VariationParameters& quic_trial_params) {
1402 return LowerCaseEqualsASCII(
1403 GetVariationParam(quic_trial_params, "disable_disk_cache"), "true");
1406 // static
1407 int IOThread::GetQuicSocketReceiveBufferSize(
1408 const VariationParameters& quic_trial_params) {
1409 int value;
1410 if (base::StringToInt(GetVariationParam(quic_trial_params,
1411 "receive_buffer_size"),
1412 &value)) {
1413 return value;
1415 return 0;
1418 // static
1419 size_t IOThread::GetQuicMaxPacketLength(
1420 const base::CommandLine& command_line,
1421 const VariationParameters& quic_trial_params) {
1422 if (command_line.HasSwitch(switches::kQuicMaxPacketLength)) {
1423 unsigned value;
1424 if (!base::StringToUint(
1425 command_line.GetSwitchValueASCII(switches::kQuicMaxPacketLength),
1426 &value)) {
1427 return 0;
1429 return value;
1432 unsigned value;
1433 if (base::StringToUint(GetVariationParam(quic_trial_params,
1434 "max_packet_length"),
1435 &value)) {
1436 return value;
1438 return 0;
1441 // static
1442 net::QuicVersion IOThread::GetQuicVersion(
1443 const base::CommandLine& command_line,
1444 const VariationParameters& quic_trial_params) {
1445 if (command_line.HasSwitch(switches::kQuicVersion)) {
1446 return ParseQuicVersion(
1447 command_line.GetSwitchValueASCII(switches::kQuicVersion));
1450 return ParseQuicVersion(GetVariationParam(quic_trial_params, "quic_version"));
1453 // static
1454 net::QuicVersion IOThread::ParseQuicVersion(const std::string& quic_version) {
1455 net::QuicVersionVector supported_versions = net::QuicSupportedVersions();
1456 for (size_t i = 0; i < supported_versions.size(); ++i) {
1457 net::QuicVersion version = supported_versions[i];
1458 if (net::QuicVersionToString(version) == quic_version) {
1459 return version;
1463 return net::QUIC_VERSION_UNSUPPORTED;