SkBitmap::Config is deprecated, use SkColorType instead
[chromium-blink-merge.git] / chrome / browser / io_thread.cc
blob14e622e7bcfeab355c6c1d7b7007fd0d4bb307a7
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/extensions/event_router_forwarder.h"
31 #include "chrome/browser/net/async_dns_field_trial.h"
32 #include "chrome/browser/net/chrome_net_log.h"
33 #include "chrome/browser/net/chrome_network_delegate.h"
34 #include "chrome/browser/net/chrome_url_request_context.h"
35 #include "chrome/browser/net/connect_interceptor.h"
36 #include "chrome/browser/net/dns_probe_service.h"
37 #include "chrome/browser/net/pref_proxy_config_tracker.h"
38 #include "chrome/browser/net/proxy_service_factory.h"
39 #include "chrome/common/chrome_content_client.h"
40 #include "chrome/common/chrome_switches.h"
41 #include "chrome/common/chrome_version_info.h"
42 #include "chrome/common/pref_names.h"
43 #include "components/data_reduction_proxy/browser/data_reduction_proxy_prefs.h"
44 #include "components/policy/core/common/policy_service.h"
45 #include "components/variations/variations_associated_data.h"
46 #include "content/public/browser/browser_thread.h"
47 #include "content/public/browser/cookie_store_factory.h"
48 #include "net/base/host_mapping_rules.h"
49 #include "net/base/net_util.h"
50 #include "net/cert/cert_verifier.h"
51 #include "net/cert/cert_verify_proc.h"
52 #include "net/cert/ct_known_logs.h"
53 #include "net/cert/ct_verifier.h"
54 #include "net/cert/multi_threaded_cert_verifier.h"
55 #include "net/cookies/cookie_store.h"
56 #include "net/dns/host_cache.h"
57 #include "net/dns/host_resolver.h"
58 #include "net/dns/mapped_host_resolver.h"
59 #include "net/ftp/ftp_network_layer.h"
60 #include "net/http/http_auth_filter.h"
61 #include "net/http/http_auth_handler_factory.h"
62 #include "net/http/http_network_layer.h"
63 #include "net/http/http_server_properties_impl.h"
64 #include "net/proxy/proxy_config_service.h"
65 #include "net/proxy/proxy_script_fetcher_impl.h"
66 #include "net/proxy/proxy_service.h"
67 #include "net/quic/quic_protocol.h"
68 #include "net/socket/tcp_client_socket.h"
69 #include "net/spdy/spdy_session.h"
70 #include "net/ssl/default_server_bound_cert_store.h"
71 #include "net/ssl/server_bound_cert_service.h"
72 #include "net/url_request/data_protocol_handler.h"
73 #include "net/url_request/file_protocol_handler.h"
74 #include "net/url_request/ftp_protocol_handler.h"
75 #include "net/url_request/static_http_user_agent_settings.h"
76 #include "net/url_request/url_fetcher.h"
77 #include "net/url_request/url_request_job_factory_impl.h"
78 #include "net/url_request/url_request_throttler_manager.h"
79 #include "url/url_constants.h"
81 #if defined(ENABLE_CONFIGURATION_POLICY)
82 #include "policy/policy_constants.h"
83 #endif
85 #if !defined(USE_OPENSSL)
86 #include "net/cert/ct_log_verifier.h"
87 #include "net/cert/multi_log_ct_verifier.h"
88 #endif
90 #if defined(USE_NSS) || defined(OS_IOS)
91 #include "net/ocsp/nss_ocsp.h"
92 #endif
94 #if defined(OS_ANDROID) || defined(OS_IOS)
95 #include "components/data_reduction_proxy/browser/data_reduction_proxy_auth_request_handler.h"
96 #include "components/data_reduction_proxy/browser/data_reduction_proxy_params.h"
97 #include "components/data_reduction_proxy/browser/data_reduction_proxy_settings.h"
98 #endif
100 #if defined(OS_CHROMEOS)
101 #include "chrome/browser/chromeos/login/users/user_manager.h"
102 #include "chrome/browser/chromeos/net/cert_verify_proc_chromeos.h"
103 #include "chromeos/network/host_resolver_impl_chromeos.h"
104 #endif
106 using content::BrowserThread;
108 #if defined(OS_ANDROID) || defined(OS_IOS)
109 using data_reduction_proxy::DataReductionProxyAuthRequestHandler;
110 using data_reduction_proxy::DataReductionProxyParams;
111 using data_reduction_proxy::DataReductionProxyUsageStats;
112 using data_reduction_proxy::DataReductionProxySettings;
113 #endif
115 class SafeBrowsingURLRequestContext;
117 // The IOThread object must outlive any tasks posted to the IO thread before the
118 // Quit task, so base::Bind() calls are not refcounted.
120 namespace {
122 const char kQuicFieldTrialName[] = "QUIC";
123 const char kQuicFieldTrialEnabledGroupName[] = "Enabled";
124 const char kQuicFieldTrialHttpsEnabledGroupName[] = "HttpsEnabled";
125 const char kQuicFieldTrialPacketLengthSuffix[] = "BytePackets";
126 const char kQuicFieldTrialPacingSuffix[] = "WithPacing";
127 const char kQuicFieldTrialTimeBasedLossDetectionSuffix[] =
128 "WithTimeBasedLossDetection";
130 // The SPDY trial composes two different trial plus control groups:
131 // * A "holdback" group with SPDY disabled, and corresponding control
132 // (SPDY/3.1). The primary purpose of the holdback group is to encourage site
133 // operators to do feature detection rather than UA-sniffing. As such, this
134 // trial runs continuously.
135 // * A SPDY/4 experiment, for SPDY/4 (aka HTTP/2) vs SPDY/3.1 comparisons and
136 // eventual SPDY/4 deployment.
137 const char kSpdyFieldTrialName[] = "SPDY";
138 const char kSpdyFieldTrialHoldbackGroupName[] = "SpdyDisabled";
139 const char kSpdyFieldTrialHoldbackControlGroupName[] = "Control";
140 const char kSpdyFieldTrialSpdy4GroupName[] = "Spdy4Enabled";
141 const char kSpdyFieldTrialSpdy4ControlGroupName[] = "Spdy4Control";
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 virtual ~SystemURLRequestContext() {
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.PassAs<net::HostResolver>();
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.PassAs<net::HostResolver>();
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_server_bound_cert_service(
255 globals->system_server_bound_cert_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_server_bound_cert_service(
284 globals->system_server_bound_cert_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 ignore_certificate_errors(false),
430 testing_fixed_http_port(0),
431 testing_fixed_https_port(0),
432 enable_user_alternate_protocol_ports(false) {
435 IOThread::Globals::~Globals() {}
437 // |local_state| is passed in explicitly in order to (1) reduce implicit
438 // dependencies and (2) make IOThread more flexible for testing.
439 IOThread::IOThread(
440 PrefService* local_state,
441 policy::PolicyService* policy_service,
442 ChromeNetLog* net_log,
443 extensions::EventRouterForwarder* extension_event_router_forwarder)
444 : net_log_(net_log),
445 extension_event_router_forwarder_(extension_event_router_forwarder),
446 globals_(NULL),
447 is_spdy_disabled_by_policy_(false),
448 weak_factory_(this),
449 creation_time_(base::TimeTicks::Now()) {
450 auth_schemes_ = local_state->GetString(prefs::kAuthSchemes);
451 negotiate_disable_cname_lookup_ = local_state->GetBoolean(
452 prefs::kDisableAuthNegotiateCnameLookup);
453 negotiate_enable_port_ = local_state->GetBoolean(
454 prefs::kEnableAuthNegotiatePort);
455 auth_server_whitelist_ = local_state->GetString(prefs::kAuthServerWhitelist);
456 auth_delegate_whitelist_ = local_state->GetString(
457 prefs::kAuthNegotiateDelegateWhitelist);
458 gssapi_library_name_ = local_state->GetString(prefs::kGSSAPILibraryName);
459 pref_proxy_config_tracker_.reset(
460 ProxyServiceFactory::CreatePrefProxyConfigTrackerOfLocalState(
461 local_state));
462 ChromeNetworkDelegate::InitializePrefsOnUIThread(
463 &system_enable_referrers_,
464 NULL,
465 NULL,
466 local_state);
467 ssl_config_service_manager_.reset(
468 SSLConfigServiceManager::CreateDefaultManager(local_state));
470 base::Value* dns_client_enabled_default = new base::FundamentalValue(
471 chrome_browser_net::ConfigureAsyncDnsFieldTrial());
472 local_state->SetDefaultPrefValue(prefs::kBuiltInDnsClientEnabled,
473 dns_client_enabled_default);
475 dns_client_enabled_.Init(prefs::kBuiltInDnsClientEnabled,
476 local_state,
477 base::Bind(&IOThread::UpdateDnsClientEnabled,
478 base::Unretained(this)));
479 dns_client_enabled_.MoveToThread(
480 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
482 quick_check_enabled_.Init(prefs::kQuickCheckEnabled,
483 local_state);
484 quick_check_enabled_.MoveToThread(
485 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
487 #if defined(ENABLE_CONFIGURATION_POLICY)
488 is_spdy_disabled_by_policy_ = policy_service->GetPolicies(
489 policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME, std::string())).Get(
490 policy::key::kDisableSpdy) != NULL;
491 #endif // ENABLE_CONFIGURATION_POLICY
493 BrowserThread::SetDelegate(BrowserThread::IO, this);
496 IOThread::~IOThread() {
497 // This isn't needed for production code, but in tests, IOThread may
498 // be multiply constructed.
499 BrowserThread::SetDelegate(BrowserThread::IO, NULL);
501 pref_proxy_config_tracker_->DetachFromPrefService();
502 DCHECK(!globals_);
505 IOThread::Globals* IOThread::globals() {
506 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
507 return globals_;
510 void IOThread::SetGlobalsForTesting(Globals* globals) {
511 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
512 DCHECK(!globals || !globals_);
513 globals_ = globals;
516 ChromeNetLog* IOThread::net_log() {
517 return net_log_;
520 void IOThread::ChangedToOnTheRecord() {
521 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
522 BrowserThread::PostTask(
523 BrowserThread::IO,
524 FROM_HERE,
525 base::Bind(&IOThread::ChangedToOnTheRecordOnIOThread,
526 base::Unretained(this)));
529 net::URLRequestContextGetter* IOThread::system_url_request_context_getter() {
530 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
531 if (!system_url_request_context_getter_.get()) {
532 InitSystemRequestContext();
534 return system_url_request_context_getter_.get();
537 void IOThread::Init() {
538 // Prefer to use InitAsync unless you need initialization to block
539 // the UI thread
542 void IOThread::InitAsync() {
543 TRACE_EVENT0("startup", "IOThread::InitAsync");
544 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
546 #if defined(USE_NSS) || defined(OS_IOS)
547 net::SetMessageLoopForNSSHttpIO();
548 #endif
550 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
552 DCHECK(!globals_);
553 globals_ = new Globals;
555 // Add an observer that will emit network change events to the ChromeNetLog.
556 // Assuming NetworkChangeNotifier dispatches in FIFO order, we should be
557 // logging the network change before other IO thread consumers respond to it.
558 network_change_observer_.reset(
559 new LoggingNetworkChangeObserver(net_log_));
561 // Setup the HistogramWatcher to run on the IO thread.
562 net::NetworkChangeNotifier::InitHistogramWatcher();
564 globals_->extension_event_router_forwarder =
565 extension_event_router_forwarder_;
566 ChromeNetworkDelegate* network_delegate =
567 new ChromeNetworkDelegate(extension_event_router_forwarder_,
568 &system_enable_referrers_);
569 if (command_line.HasSwitch(switches::kEnableClientHints))
570 network_delegate->SetEnableClientHints();
571 if (command_line.HasSwitch(switches::kDisableExtensionsHttpThrottling))
572 network_delegate->NeverThrottleRequests();
573 globals_->system_network_delegate.reset(network_delegate);
574 globals_->host_resolver = CreateGlobalHostResolver(net_log_);
575 UpdateDnsClientEnabled();
576 #if defined(OS_CHROMEOS)
577 // Creates a CertVerifyProc that doesn't allow any profile-provided certs.
578 globals_->cert_verifier.reset(new net::MultiThreadedCertVerifier(
579 new chromeos::CertVerifyProcChromeOS()));
580 #else
581 globals_->cert_verifier.reset(new net::MultiThreadedCertVerifier(
582 net::CertVerifyProc::CreateDefault()));
583 #endif
585 globals_->transport_security_state.reset(new net::TransportSecurityState());
586 #if !defined(USE_OPENSSL)
587 // For now, Certificate Transparency is only implemented for platforms
588 // that use NSS.
589 net::MultiLogCTVerifier* ct_verifier = new net::MultiLogCTVerifier();
590 globals_->cert_transparency_verifier.reset(ct_verifier);
592 // Add built-in logs
593 ct_verifier->AddLogs(net::ct::CreateLogVerifiersForKnownLogs());
595 // Add logs from command line
596 if (command_line.HasSwitch(switches::kCertificateTransparencyLog)) {
597 std::string switch_value = command_line.GetSwitchValueASCII(
598 switches::kCertificateTransparencyLog);
599 std::vector<std::string> logs;
600 base::SplitString(switch_value, ',', &logs);
601 for (std::vector<std::string>::iterator it = logs.begin(); it != logs.end();
602 ++it) {
603 const std::string& curr_log = *it;
604 size_t delim_pos = curr_log.find(":");
605 CHECK(delim_pos != std::string::npos)
606 << "CT log description not provided (switch format"
607 " is 'description:base64_key')";
608 std::string log_description(curr_log.substr(0, delim_pos));
609 std::string ct_public_key_data;
610 CHECK(base::Base64Decode(curr_log.substr(delim_pos + 1),
611 &ct_public_key_data))
612 << "Unable to decode CT public key.";
613 scoped_ptr<net::CTLogVerifier> external_log_verifier(
614 net::CTLogVerifier::Create(ct_public_key_data, log_description));
615 CHECK(external_log_verifier) << "Unable to parse CT public key.";
616 VLOG(1) << "Adding log with description " << log_description;
617 ct_verifier->AddLog(external_log_verifier.Pass());
620 #else
621 if (command_line.HasSwitch(switches::kCertificateTransparencyLog)) {
622 LOG(DFATAL) << "Certificate Transparency is not yet supported in Chrome "
623 "builds using OpenSSL.";
625 #endif
626 globals_->ssl_config_service = GetSSLConfigService();
627 #if defined(OS_ANDROID) || defined(OS_IOS)
628 #if defined(SPDY_PROXY_AUTH_ORIGIN)
629 int drp_flags = DataReductionProxyParams::kFallbackAllowed;
630 if (DataReductionProxyParams::IsIncludedInFieldTrial())
631 drp_flags |= DataReductionProxyParams::kAllowed;
632 if (DataReductionProxyParams::IsIncludedInAlternativeFieldTrial())
633 drp_flags |= DataReductionProxyParams::kAlternativeAllowed;
634 if (DataReductionProxyParams::IsIncludedInPromoFieldTrial())
635 drp_flags |= DataReductionProxyParams::kPromoAllowed;
636 DataReductionProxyParams* proxy_params =
637 new DataReductionProxyParams(drp_flags);
638 globals_->data_reduction_proxy_params.reset(proxy_params);
639 globals_->data_reduction_proxy_auth_request_handler.reset(
640 new DataReductionProxyAuthRequestHandler(proxy_params));
641 DataReductionProxyUsageStats* proxy_usage_stats =
642 new DataReductionProxyUsageStats(proxy_params,
643 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI),
644 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
645 network_delegate->set_data_reduction_proxy_params(proxy_params);
646 globals_->data_reduction_proxy_usage_stats.reset(proxy_usage_stats);
647 network_delegate->set_data_reduction_proxy_usage_stats(proxy_usage_stats);
648 network_delegate->set_data_reduction_proxy_auth_request_handler(
649 globals_->data_reduction_proxy_auth_request_handler.get());
650 #endif // defined(SPDY_PROXY_AUTH_ORIGIN)
651 #endif // defined(OS_ANDROID) || defined(OS_IOS)
652 globals_->http_auth_handler_factory.reset(CreateDefaultAuthHandlerFactory(
653 globals_->host_resolver.get()));
654 globals_->http_server_properties.reset(new net::HttpServerPropertiesImpl());
655 // For the ProxyScriptFetcher, we use a direct ProxyService.
656 globals_->proxy_script_fetcher_proxy_service.reset(
657 net::ProxyService::CreateDirectWithNetLog(net_log_));
658 // In-memory cookie store.
659 globals_->system_cookie_store =
660 content::CreateCookieStore(content::CookieStoreConfig());
661 // In-memory server bound cert store.
662 globals_->system_server_bound_cert_service.reset(
663 new net::ServerBoundCertService(
664 new net::DefaultServerBoundCertStore(NULL),
665 base::WorkerPool::GetTaskRunner(true)));
666 globals_->dns_probe_service.reset(new chrome_browser_net::DnsProbeService());
667 globals_->host_mapping_rules.reset(new net::HostMappingRules());
668 globals_->http_user_agent_settings.reset(
669 new net::StaticHttpUserAgentSettings(std::string(), GetUserAgent()));
670 if (command_line.HasSwitch(switches::kHostRules)) {
671 TRACE_EVENT_BEGIN0("startup", "IOThread::InitAsync:SetRulesFromString");
672 globals_->host_mapping_rules->SetRulesFromString(
673 command_line.GetSwitchValueASCII(switches::kHostRules));
674 TRACE_EVENT_END0("startup", "IOThread::InitAsync:SetRulesFromString");
676 if (command_line.HasSwitch(switches::kIgnoreCertificateErrors))
677 globals_->ignore_certificate_errors = true;
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 =
724 job_factory.PassAs<net::URLRequestJobFactory>();
726 globals_->throttler_manager.reset(new net::URLRequestThrottlerManager());
727 globals_->throttler_manager->set_net_log(net_log_);
728 // Always done in production, disabled only for unit tests.
729 globals_->throttler_manager->set_enable_thread_checks(true);
731 globals_->proxy_script_fetcher_context.reset(
732 ConstructProxyScriptFetcherContext(globals_, net_log_));
734 #if defined(OS_MACOSX) && !defined(OS_IOS)
735 // Start observing Keychain events. This needs to be done on the UI thread,
736 // as Keychain services requires a CFRunLoop.
737 BrowserThread::PostTask(BrowserThread::UI,
738 FROM_HERE,
739 base::Bind(&ObserveKeychainEvents));
740 #endif
742 // InitSystemRequestContext turns right around and posts a task back
743 // to the IO thread, so we can't let it run until we know the IO
744 // thread has started.
746 // Note that since we are at BrowserThread::Init time, the UI thread
747 // is blocked waiting for the thread to start. Therefore, posting
748 // this task to the main thread's message loop here is guaranteed to
749 // get it onto the message loop while the IOThread object still
750 // exists. However, the message might not be processed on the UI
751 // thread until after IOThread is gone, so use a weak pointer.
752 BrowserThread::PostTask(BrowserThread::UI,
753 FROM_HERE,
754 base::Bind(&IOThread::InitSystemRequestContext,
755 weak_factory_.GetWeakPtr()));
758 void IOThread::CleanUp() {
759 base::debug::LeakTracker<SafeBrowsingURLRequestContext>::CheckForLeaks();
761 #if defined(USE_NSS) || defined(OS_IOS)
762 net::ShutdownNSSHttpIO();
763 #endif
765 system_url_request_context_getter_ = NULL;
767 // Release objects that the net::URLRequestContext could have been pointing
768 // to.
770 // Shutdown the HistogramWatcher on the IO thread.
771 net::NetworkChangeNotifier::ShutdownHistogramWatcher();
773 // This must be reset before the ChromeNetLog is destroyed.
774 network_change_observer_.reset();
776 system_proxy_config_service_.reset();
778 delete globals_;
779 globals_ = NULL;
781 base::debug::LeakTracker<SystemURLRequestContextGetter>::CheckForLeaks();
784 void IOThread::InitializeNetworkOptions(const CommandLine& command_line) {
785 // Only handle use-spdy command line flags if "spdy.disabled" preference is
786 // not disabled via policy.
787 if (is_spdy_disabled_by_policy_) {
788 base::FieldTrial* trial = base::FieldTrialList::Find(kSpdyFieldTrialName);
789 if (trial)
790 trial->Disable();
791 } else {
792 if (command_line.HasSwitch(switches::kTrustedSpdyProxy)) {
793 globals_->trusted_spdy_proxy.set(
794 command_line.GetSwitchValueASCII(switches::kTrustedSpdyProxy));
796 if (command_line.HasSwitch(switches::kIgnoreUrlFetcherCertRequests))
797 net::URLFetcher::SetIgnoreCertificateRequests(true);
799 if (command_line.HasSwitch(switches::kUseSpdy)) {
800 std::string spdy_mode =
801 command_line.GetSwitchValueASCII(switches::kUseSpdy);
802 EnableSpdy(spdy_mode);
803 } else if (command_line.HasSwitch(switches::kEnableSpdy4)) {
804 globals_->next_protos = net::NextProtosSpdy4Http2();
805 globals_->use_alternate_protocols.set(true);
806 } else if (command_line.HasSwitch(switches::kDisableSpdy31)) {
807 globals_->next_protos = net::NextProtosSpdy3();
808 globals_->use_alternate_protocols.set(true);
809 } else if (command_line.HasSwitch(switches::kEnableNpnHttpOnly)) {
810 globals_->next_protos = net::NextProtosHttpOnly();
811 globals_->use_alternate_protocols.set(false);
812 } else if (command_line.HasSwitch(switches::kEnableWebSocketOverSpdy)) {
813 // Use the current SPDY default (SPDY/3.1).
814 globals_->next_protos = net::NextProtosSpdy31();
815 globals_->use_alternate_protocols.set(true);
816 } else {
817 // No SPDY command-line flags have been specified. Examine trial groups.
818 ConfigureSpdyFromTrial(
819 base::FieldTrialList::FindFullName(kSpdyFieldTrialName), globals_);
822 if (command_line.HasSwitch(switches::kEnableWebSocketOverSpdy))
823 globals_->enable_websocket_over_spdy.set(true);
826 // TODO(rch): Make the client socket factory a per-network session
827 // instance, constructed from a NetworkSession::Params, to allow us
828 // to move this option to IOThread::Globals &
829 // HttpNetworkSession::Params.
830 if (command_line.HasSwitch(switches::kEnableTcpFastOpen))
831 net::SetTCPFastOpenEnabled(true);
834 void IOThread::ConfigureSpdyFromTrial(const std::string& spdy_trial_group,
835 Globals* globals) {
836 if (spdy_trial_group == kSpdyFieldTrialHoldbackGroupName) {
837 // TODO(jgraettinger): Use net::NextProtosHttpOnly() instead?
838 net::HttpStreamFactory::set_spdy_enabled(false);
839 } else if (spdy_trial_group == kSpdyFieldTrialHoldbackControlGroupName) {
840 // Use the current SPDY default (SPDY/3.1).
841 globals->next_protos = net::NextProtosSpdy31();
842 globals->use_alternate_protocols.set(true);
843 } else if (spdy_trial_group == kSpdyFieldTrialSpdy4GroupName) {
844 globals->next_protos = net::NextProtosSpdy4Http2();
845 globals->use_alternate_protocols.set(true);
846 } else if (spdy_trial_group == kSpdyFieldTrialSpdy4ControlGroupName) {
847 // This control group is pinned at SPDY/3.1.
848 globals->next_protos = net::NextProtosSpdy31();
849 globals->use_alternate_protocols.set(true);
850 } else {
851 // Use the current SPDY default (SPDY/3.1).
852 globals->next_protos = net::NextProtosSpdy31();
853 globals->use_alternate_protocols.set(true);
857 void IOThread::EnableSpdy(const std::string& mode) {
858 static const char kOff[] = "off";
859 static const char kSSL[] = "ssl";
860 static const char kDisableSSL[] = "no-ssl";
861 static const char kDisablePing[] = "no-ping";
862 static const char kExclude[] = "exclude"; // Hosts to exclude
863 static const char kDisableCompression[] = "no-compress";
864 static const char kDisableAltProtocols[] = "no-alt-protocols";
865 static const char kForceAltProtocols[] = "force-alt-protocols";
866 static const char kSingleDomain[] = "single-domain";
868 static const char kInitialMaxConcurrentStreams[] = "init-max-streams";
870 std::vector<std::string> spdy_options;
871 base::SplitString(mode, ',', &spdy_options);
873 for (std::vector<std::string>::iterator it = spdy_options.begin();
874 it != spdy_options.end(); ++it) {
875 const std::string& element = *it;
876 std::vector<std::string> name_value;
877 base::SplitString(element, '=', &name_value);
878 const std::string& option =
879 name_value.size() > 0 ? name_value[0] : std::string();
880 const std::string value =
881 name_value.size() > 1 ? name_value[1] : std::string();
883 if (option == kOff) {
884 net::HttpStreamFactory::set_spdy_enabled(false);
885 } else if (option == kDisableSSL) {
886 globals_->spdy_default_protocol.set(net::kProtoSPDY3);
887 globals_->force_spdy_over_ssl.set(false);
888 globals_->force_spdy_always.set(true);
889 } else if (option == kSSL) {
890 globals_->spdy_default_protocol.set(net::kProtoSPDY3);
891 globals_->force_spdy_over_ssl.set(true);
892 globals_->force_spdy_always.set(true);
893 } else if (option == kDisablePing) {
894 globals_->enable_spdy_ping_based_connection_checking.set(false);
895 } else if (option == kExclude) {
896 globals_->forced_spdy_exclusions.insert(
897 net::HostPortPair::FromURL(GURL(value)));
898 } else if (option == kDisableCompression) {
899 globals_->enable_spdy_compression.set(false);
900 } else if (option == kDisableAltProtocols) {
901 globals_->use_alternate_protocols.set(false);
902 } else if (option == kForceAltProtocols) {
903 net::AlternateProtocolInfo pair(443, net::NPN_SPDY_3, 1);
904 net::HttpServerPropertiesImpl::ForceAlternateProtocol(pair);
905 } else if (option == kSingleDomain) {
906 DVLOG(1) << "FORCING SINGLE DOMAIN";
907 globals_->force_spdy_single_domain.set(true);
908 } else if (option == kInitialMaxConcurrentStreams) {
909 int streams;
910 if (base::StringToInt(value, &streams))
911 globals_->initial_max_spdy_concurrent_streams.set(streams);
912 } else if (option.empty() && it == spdy_options.begin()) {
913 continue;
914 } else {
915 LOG(DFATAL) << "Unrecognized spdy option: " << option;
920 // static
921 void IOThread::RegisterPrefs(PrefRegistrySimple* registry) {
922 registry->RegisterStringPref(prefs::kAuthSchemes,
923 "basic,digest,ntlm,negotiate,"
924 "spdyproxy");
925 registry->RegisterBooleanPref(prefs::kDisableAuthNegotiateCnameLookup, false);
926 registry->RegisterBooleanPref(prefs::kEnableAuthNegotiatePort, false);
927 registry->RegisterStringPref(prefs::kAuthServerWhitelist, std::string());
928 registry->RegisterStringPref(prefs::kAuthNegotiateDelegateWhitelist,
929 std::string());
930 registry->RegisterStringPref(prefs::kGSSAPILibraryName, std::string());
931 registry->RegisterStringPref(
932 data_reduction_proxy::prefs::kDataReductionProxy, std::string());
933 registry->RegisterBooleanPref(prefs::kEnableReferrers, true);
934 data_reduction_proxy::RegisterPrefs(registry);
935 registry->RegisterBooleanPref(prefs::kBuiltInDnsClientEnabled, true);
936 registry->RegisterBooleanPref(prefs::kQuickCheckEnabled, true);
939 net::HttpAuthHandlerFactory* IOThread::CreateDefaultAuthHandlerFactory(
940 net::HostResolver* resolver) {
941 net::HttpAuthFilterWhitelist* auth_filter_default_credentials = NULL;
942 if (!auth_server_whitelist_.empty()) {
943 auth_filter_default_credentials =
944 new net::HttpAuthFilterWhitelist(auth_server_whitelist_);
946 net::HttpAuthFilterWhitelist* auth_filter_delegate = NULL;
947 if (!auth_delegate_whitelist_.empty()) {
948 auth_filter_delegate =
949 new net::HttpAuthFilterWhitelist(auth_delegate_whitelist_);
951 globals_->url_security_manager.reset(
952 net::URLSecurityManager::Create(auth_filter_default_credentials,
953 auth_filter_delegate));
954 std::vector<std::string> supported_schemes;
955 base::SplitString(auth_schemes_, ',', &supported_schemes);
957 scoped_ptr<net::HttpAuthHandlerRegistryFactory> registry_factory(
958 net::HttpAuthHandlerRegistryFactory::Create(
959 supported_schemes, globals_->url_security_manager.get(),
960 resolver, gssapi_library_name_, negotiate_disable_cname_lookup_,
961 negotiate_enable_port_));
962 return registry_factory.release();
965 void IOThread::ClearHostCache() {
966 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
968 net::HostCache* host_cache = globals_->host_resolver->GetHostCache();
969 if (host_cache)
970 host_cache->clear();
973 void IOThread::InitializeNetworkSessionParams(
974 net::HttpNetworkSession::Params* params) {
975 InitializeNetworkSessionParamsFromGlobals(*globals_, params);
978 // static
979 void IOThread::InitializeNetworkSessionParamsFromGlobals(
980 const IOThread::Globals& globals,
981 net::HttpNetworkSession::Params* params) {
982 params->host_resolver = globals.host_resolver.get();
983 params->cert_verifier = globals.cert_verifier.get();
984 params->server_bound_cert_service =
985 globals.system_server_bound_cert_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->ignore_certificate_errors = globals.ignore_certificate_errors;
994 params->testing_fixed_http_port = globals.testing_fixed_http_port;
995 params->testing_fixed_https_port = globals.testing_fixed_https_port;
997 globals.initial_max_spdy_concurrent_streams.CopyToIfSet(
998 &params->spdy_initial_max_concurrent_streams);
999 globals.force_spdy_single_domain.CopyToIfSet(
1000 &params->force_spdy_single_domain);
1001 globals.enable_spdy_compression.CopyToIfSet(
1002 &params->enable_spdy_compression);
1003 globals.enable_spdy_ping_based_connection_checking.CopyToIfSet(
1004 &params->enable_spdy_ping_based_connection_checking);
1005 globals.spdy_default_protocol.CopyToIfSet(
1006 &params->spdy_default_protocol);
1007 params->next_protos = globals.next_protos;
1008 globals.trusted_spdy_proxy.CopyToIfSet(&params->trusted_spdy_proxy);
1009 globals.force_spdy_over_ssl.CopyToIfSet(&params->force_spdy_over_ssl);
1010 globals.force_spdy_always.CopyToIfSet(&params->force_spdy_always);
1011 params->forced_spdy_exclusions = globals.forced_spdy_exclusions;
1012 globals.use_alternate_protocols.CopyToIfSet(
1013 &params->use_alternate_protocols);
1014 globals.alternate_protocol_probability_threshold.CopyToIfSet(
1015 &params->alternate_protocol_probability_threshold);
1016 globals.enable_websocket_over_spdy.CopyToIfSet(
1017 &params->enable_websocket_over_spdy);
1019 globals.enable_quic.CopyToIfSet(&params->enable_quic);
1020 globals.enable_quic_pacing.CopyToIfSet(
1021 &params->enable_quic_pacing);
1022 globals.enable_quic_time_based_loss_detection.CopyToIfSet(
1023 &params->enable_quic_time_based_loss_detection);
1024 globals.enable_quic_port_selection.CopyToIfSet(
1025 &params->enable_quic_port_selection);
1026 globals.quic_max_packet_length.CopyToIfSet(&params->quic_max_packet_length);
1027 globals.quic_user_agent_id.CopyToIfSet(&params->quic_user_agent_id);
1028 globals.quic_supported_versions.CopyToIfSet(
1029 &params->quic_supported_versions);
1030 params->quic_connection_options = globals.quic_connection_options;
1032 globals.origin_to_force_quic_on.CopyToIfSet(
1033 &params->origin_to_force_quic_on);
1034 params->enable_user_alternate_protocol_ports =
1035 globals.enable_user_alternate_protocol_ports;
1038 base::TimeTicks IOThread::creation_time() const {
1039 return creation_time_;
1042 net::SSLConfigService* IOThread::GetSSLConfigService() {
1043 return ssl_config_service_manager_->Get();
1046 void IOThread::ChangedToOnTheRecordOnIOThread() {
1047 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1049 // Clear the host cache to avoid showing entries from the OTR session
1050 // in about:net-internals.
1051 ClearHostCache();
1054 void IOThread::InitSystemRequestContext() {
1055 if (system_url_request_context_getter_.get())
1056 return;
1057 // If we're in unit_tests, IOThread may not be run.
1058 if (!BrowserThread::IsMessageLoopValid(BrowserThread::IO))
1059 return;
1060 system_proxy_config_service_.reset(
1061 ProxyServiceFactory::CreateProxyConfigService(
1062 pref_proxy_config_tracker_.get()));
1063 system_url_request_context_getter_ =
1064 new SystemURLRequestContextGetter(this);
1065 // Safe to post an unretained this pointer, since IOThread is
1066 // guaranteed to outlive the IO BrowserThread.
1067 BrowserThread::PostTask(
1068 BrowserThread::IO,
1069 FROM_HERE,
1070 base::Bind(&IOThread::InitSystemRequestContextOnIOThread,
1071 base::Unretained(this)));
1074 void IOThread::InitSystemRequestContextOnIOThread() {
1075 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1076 DCHECK(!globals_->system_proxy_service.get());
1077 DCHECK(system_proxy_config_service_.get());
1079 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
1080 globals_->system_proxy_service.reset(
1081 ProxyServiceFactory::CreateProxyService(
1082 net_log_,
1083 globals_->proxy_script_fetcher_context.get(),
1084 globals_->system_network_delegate.get(),
1085 system_proxy_config_service_.release(),
1086 command_line,
1087 quick_check_enabled_.GetValue()));
1089 net::HttpNetworkSession::Params system_params;
1090 InitializeNetworkSessionParams(&system_params);
1091 system_params.net_log = net_log_;
1092 system_params.proxy_service = globals_->system_proxy_service.get();
1094 globals_->system_http_transaction_factory.reset(
1095 new net::HttpNetworkLayer(
1096 new net::HttpNetworkSession(system_params)));
1097 globals_->system_url_request_job_factory.reset(
1098 new net::URLRequestJobFactoryImpl());
1099 globals_->system_request_context.reset(
1100 ConstructSystemRequestContext(globals_, net_log_));
1101 globals_->system_request_context->set_ssl_config_service(
1102 globals_->ssl_config_service);
1103 globals_->system_request_context->set_http_server_properties(
1104 globals_->http_server_properties->GetWeakPtr());
1107 void IOThread::UpdateDnsClientEnabled() {
1108 globals()->host_resolver->SetDnsClientEnabled(*dns_client_enabled_);
1111 void IOThread::ConfigureQuic(const CommandLine& command_line) {
1112 // Always fetch the field trial group to ensure it is reported correctly.
1113 // The command line flags will be associated with a group that is reported
1114 // so long as trial is actually queried.
1115 std::string group =
1116 base::FieldTrialList::FindFullName(kQuicFieldTrialName);
1117 VariationParameters params;
1118 if (!chrome_variations::GetVariationParams(kQuicFieldTrialName, &params)) {
1119 params.clear();
1122 ConfigureQuicGlobals(command_line, group, params, globals_);
1125 // static
1126 void IOThread::ConfigureQuicGlobals(
1127 const base::CommandLine& command_line,
1128 base::StringPiece quic_trial_group,
1129 const VariationParameters& quic_trial_params,
1130 IOThread::Globals* globals) {
1131 bool enable_quic = ShouldEnableQuic(command_line, quic_trial_group);
1132 globals->enable_quic.set(enable_quic);
1133 if (enable_quic) {
1134 globals->enable_quic_pacing.set(
1135 ShouldEnableQuicPacing(command_line, quic_trial_group,
1136 quic_trial_params));
1137 globals->enable_quic_time_based_loss_detection.set(
1138 ShouldEnableQuicTimeBasedLossDetection(command_line, quic_trial_group,
1139 quic_trial_params));
1140 globals->enable_quic_port_selection.set(
1141 ShouldEnableQuicPortSelection(command_line));
1142 globals->quic_connection_options =
1143 GetQuicConnectionOptions(command_line, quic_trial_params);
1146 size_t max_packet_length = GetQuicMaxPacketLength(command_line,
1147 quic_trial_group,
1148 quic_trial_params);
1149 if (max_packet_length != 0) {
1150 globals->quic_max_packet_length.set(max_packet_length);
1153 std::string quic_user_agent_id =
1154 chrome::VersionInfo::GetVersionStringModifier();
1155 quic_user_agent_id.append(1, ' ');
1156 chrome::VersionInfo version_info;
1157 quic_user_agent_id.append(version_info.ProductNameAndVersionForUserAgent());
1158 globals->quic_user_agent_id.set(quic_user_agent_id);
1160 net::QuicVersion version = GetQuicVersion(command_line, quic_trial_params);
1161 if (version != net::QUIC_VERSION_UNSUPPORTED) {
1162 net::QuicVersionVector supported_versions;
1163 supported_versions.push_back(version);
1164 globals->quic_supported_versions.set(supported_versions);
1167 double threshold =
1168 GetAlternateProtocolProbabilityThreshold(command_line, quic_trial_params);
1169 if (threshold >=0 && threshold <= 1) {
1170 globals->alternate_protocol_probability_threshold.set(threshold);
1171 globals->http_server_properties->SetAlternateProtocolProbabilityThreshold(
1172 threshold);
1175 if (command_line.HasSwitch(switches::kOriginToForceQuicOn)) {
1176 net::HostPortPair quic_origin =
1177 net::HostPortPair::FromString(
1178 command_line.GetSwitchValueASCII(switches::kOriginToForceQuicOn));
1179 if (!quic_origin.IsEmpty()) {
1180 globals->origin_to_force_quic_on.set(quic_origin);
1185 bool IOThread::ShouldEnableQuic(const CommandLine& command_line,
1186 base::StringPiece quic_trial_group) {
1187 if (command_line.HasSwitch(switches::kDisableQuic))
1188 return false;
1190 if (command_line.HasSwitch(switches::kEnableQuic))
1191 return true;
1193 return quic_trial_group.starts_with(kQuicFieldTrialEnabledGroupName) ||
1194 quic_trial_group.starts_with(kQuicFieldTrialHttpsEnabledGroupName);
1197 bool IOThread::ShouldEnableQuicPortSelection(
1198 const CommandLine& command_line) {
1199 if (command_line.HasSwitch(switches::kDisableQuicPortSelection))
1200 return false;
1202 if (command_line.HasSwitch(switches::kEnableQuicPortSelection))
1203 return true;
1205 return false; // Default to disabling port selection on all channels.
1208 bool IOThread::ShouldEnableQuicPacing(
1209 const CommandLine& command_line,
1210 base::StringPiece quic_trial_group,
1211 const VariationParameters& quic_trial_params) {
1212 if (command_line.HasSwitch(switches::kEnableQuicPacing))
1213 return true;
1215 if (command_line.HasSwitch(switches::kDisableQuicPacing))
1216 return false;
1218 if (LowerCaseEqualsASCII(
1219 GetVariationParam(quic_trial_params, "enable_pacing"),
1220 "true"))
1221 return true;
1223 return quic_trial_group.ends_with(kQuicFieldTrialPacingSuffix);
1226 net::QuicTagVector IOThread::GetQuicConnectionOptions(
1227 const CommandLine& command_line,
1228 const VariationParameters& quic_trial_params) {
1229 if (command_line.HasSwitch(switches::kQuicConnectionOptions)) {
1230 return ParseQuicConnectionOptions(
1231 command_line.GetSwitchValueASCII(switches::kQuicConnectionOptions));
1234 VariationParameters::const_iterator it =
1235 quic_trial_params.find("congestion_options");
1236 if (it == quic_trial_params.end())
1237 return net::QuicTagVector();
1239 return ParseQuicConnectionOptions(it->second);
1242 // static
1243 net::QuicTagVector IOThread::ParseQuicConnectionOptions(
1244 const std::string& connection_options) {
1245 net::QuicTagVector options;
1246 std::vector<std::string> tokens;
1247 base::SplitString(connection_options, ',', &tokens);
1248 // Tokens are expected to be no more than 4 characters long, but we
1249 // handle overflow gracefully.
1250 for (std::vector<std::string>::iterator token = tokens.begin();
1251 token != tokens.end(); ++token) {
1252 uint32 option = 0;
1253 for (size_t i = token->length() ; i > 0; --i) {
1254 option <<= 8;
1255 option |= static_cast<unsigned char>((*token)[i - 1]);
1257 options.push_back(static_cast<net::QuicTag>(option));
1259 return options;
1262 // static
1263 double IOThread::GetAlternateProtocolProbabilityThreshold(
1264 const base::CommandLine& command_line,
1265 const VariationParameters& quic_trial_params) {
1266 double value;
1267 if (command_line.HasSwitch(
1268 switches::kAlternateProtocolProbabilityThreshold)) {
1269 if (base::StringToDouble(
1270 command_line.GetSwitchValueASCII(
1271 switches::kAlternateProtocolProbabilityThreshold),
1272 &value)) {
1273 return value;
1276 if (base::StringToDouble(
1277 GetVariationParam(quic_trial_params,
1278 "alternate_protocol_probability_threshold"),
1279 &value)) {
1280 return value;
1282 return -1;
1285 // static
1286 bool IOThread::ShouldEnableQuicTimeBasedLossDetection(
1287 const CommandLine& command_line,
1288 base::StringPiece quic_trial_group,
1289 const VariationParameters& quic_trial_params) {
1290 if (command_line.HasSwitch(switches::kEnableQuicTimeBasedLossDetection))
1291 return true;
1293 if (command_line.HasSwitch(switches::kDisableQuicTimeBasedLossDetection))
1294 return false;
1296 if (LowerCaseEqualsASCII(
1297 GetVariationParam(quic_trial_params, "enable_time_based_loss_detection"),
1298 "true"))
1299 return true;
1301 return quic_trial_group.ends_with(
1302 kQuicFieldTrialTimeBasedLossDetectionSuffix);
1305 // static
1306 size_t IOThread::GetQuicMaxPacketLength(
1307 const CommandLine& command_line,
1308 base::StringPiece quic_trial_group,
1309 const VariationParameters& quic_trial_params) {
1310 if (command_line.HasSwitch(switches::kQuicMaxPacketLength)) {
1311 unsigned value;
1312 if (!base::StringToUint(
1313 command_line.GetSwitchValueASCII(switches::kQuicMaxPacketLength),
1314 &value)) {
1315 return 0;
1317 return value;
1320 unsigned value;
1321 if (base::StringToUint(GetVariationParam(quic_trial_params,
1322 "max_packet_length"),
1323 &value)) {
1324 return value;
1327 // Format of the packet length group names is:
1328 // (Https)?Enabled<length>BytePackets.
1329 base::StringPiece length_str(quic_trial_group);
1330 if (length_str.starts_with(kQuicFieldTrialEnabledGroupName)) {
1331 length_str.remove_prefix(strlen(kQuicFieldTrialEnabledGroupName));
1332 } else if (length_str.starts_with(kQuicFieldTrialHttpsEnabledGroupName)) {
1333 length_str.remove_prefix(strlen(kQuicFieldTrialHttpsEnabledGroupName));
1334 } else {
1335 return 0;
1337 if (!length_str.ends_with(kQuicFieldTrialPacketLengthSuffix)) {
1338 return 0;
1340 length_str.remove_suffix(strlen(kQuicFieldTrialPacketLengthSuffix));
1341 if (!base::StringToUint(length_str, &value)) {
1342 return 0;
1344 return value;
1347 // static
1348 net::QuicVersion IOThread::GetQuicVersion(
1349 const CommandLine& command_line,
1350 const VariationParameters& quic_trial_params) {
1351 if (command_line.HasSwitch(switches::kQuicVersion)) {
1352 return ParseQuicVersion(
1353 command_line.GetSwitchValueASCII(switches::kQuicVersion));
1356 return ParseQuicVersion(GetVariationParam(quic_trial_params, "quic_version"));
1359 // static
1360 net::QuicVersion IOThread::ParseQuicVersion(const std::string& quic_version) {
1361 net::QuicVersionVector supported_versions = net::QuicSupportedVersions();
1362 for (size_t i = 0; i < supported_versions.size(); ++i) {
1363 net::QuicVersion version = supported_versions[i];
1364 if (net::QuicVersionToString(version) == quic_version) {
1365 return version;
1369 return net::QUIC_VERSION_UNSUPPORTED;