Add the NetworkQualityEstimator class that is notified
[chromium-blink-merge.git] / chrome / browser / io_thread.h
blob7396cb08f5aff0c9519d519f65d81e3a6d9ad016
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 #ifndef CHROME_BROWSER_IO_THREAD_H_
6 #define CHROME_BROWSER_IO_THREAD_H_
8 #include <string>
9 #include <vector>
11 #include "base/basictypes.h"
12 #include "base/compiler_specific.h"
13 #include "base/memory/ref_counted.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/memory/weak_ptr.h"
16 #include "base/prefs/pref_member.h"
17 #include "base/strings/string_piece.h"
18 #include "base/time/time.h"
19 #include "chrome/browser/net/chrome_network_delegate.h"
20 #include "chrome/browser/net/ssl_config_service_manager.h"
21 #include "content/public/browser/browser_thread.h"
22 #include "content/public/browser/browser_thread_delegate.h"
23 #include "net/base/network_change_notifier.h"
24 #include "net/http/http_network_session.h"
25 #include "net/socket/next_proto.h"
27 class ChromeNetLog;
28 class PrefProxyConfigTracker;
29 class PrefService;
30 class PrefRegistrySimple;
31 class SystemURLRequestContextGetter;
33 namespace base {
34 class CommandLine;
37 namespace chrome_browser_net {
38 class DnsProbeService;
41 namespace extensions {
42 class EventRouterForwarder;
45 namespace net {
46 class CertPolicyEnforcer;
47 class CertVerifier;
48 class ChannelIDService;
49 class CookieStore;
50 class CTVerifier;
51 class FtpTransactionFactory;
52 class HostMappingRules;
53 class HostResolver;
54 class HttpAuthHandlerFactory;
55 class HttpServerProperties;
56 class HttpTransactionFactory;
57 class HttpUserAgentSettings;
58 class NetworkDelegate;
59 class NetworkQualityEstimator;
60 class ProxyConfigService;
61 class ProxyService;
62 class SSLConfigService;
63 class TransportSecurityState;
64 class URLRequestContext;
65 class URLRequestContextGetter;
66 class URLRequestJobFactory;
67 class URLRequestThrottlerManager;
68 class URLSecurityManager;
69 } // namespace net
71 namespace policy {
72 class PolicyService;
73 } // namespace policy
75 namespace test {
76 class IOThreadPeer;
77 } // namespace test
79 // Contains state associated with, initialized and cleaned up on, and
80 // primarily used on, the IO thread.
82 // If you are looking to interact with the IO thread (e.g. post tasks
83 // to it or check if it is the current thread), see
84 // content::BrowserThread.
85 class IOThread : public content::BrowserThreadDelegate {
86 public:
87 struct Globals {
88 template <typename T>
89 class Optional {
90 public:
91 Optional() : set_(false) {}
93 void set(T value) {
94 set_ = true;
95 value_ = value;
97 void CopyToIfSet(T* value) const {
98 if (set_) {
99 *value = value_;
103 private:
104 bool set_;
105 T value_;
108 class SystemRequestContextLeakChecker {
109 public:
110 explicit SystemRequestContextLeakChecker(Globals* globals);
111 ~SystemRequestContextLeakChecker();
113 private:
114 Globals* const globals_;
117 Globals();
118 ~Globals();
120 // The "system" NetworkDelegate, used for Profile-agnostic network events.
121 scoped_ptr<net::NetworkDelegate> system_network_delegate;
122 scoped_ptr<net::HostResolver> host_resolver;
123 scoped_ptr<net::CertVerifier> cert_verifier;
124 // The ChannelIDService must outlive the HttpTransactionFactory.
125 scoped_ptr<net::ChannelIDService> system_channel_id_service;
126 // This TransportSecurityState doesn't load or save any state. It's only
127 // used to enforce pinning for system requests and will only use built-in
128 // pins.
129 scoped_ptr<net::TransportSecurityState> transport_security_state;
130 scoped_ptr<net::CTVerifier> cert_transparency_verifier;
131 scoped_ptr<net::CertPolicyEnforcer> cert_policy_enforcer;
132 scoped_refptr<net::SSLConfigService> ssl_config_service;
133 scoped_ptr<net::HttpAuthHandlerFactory> http_auth_handler_factory;
134 scoped_ptr<net::HttpServerProperties> http_server_properties;
135 scoped_ptr<net::ProxyService> proxy_script_fetcher_proxy_service;
136 scoped_ptr<net::HttpTransactionFactory>
137 proxy_script_fetcher_http_transaction_factory;
138 scoped_ptr<net::FtpTransactionFactory>
139 proxy_script_fetcher_ftp_transaction_factory;
140 scoped_ptr<net::URLRequestJobFactory>
141 proxy_script_fetcher_url_request_job_factory;
142 scoped_ptr<net::URLRequestThrottlerManager> throttler_manager;
143 scoped_ptr<net::URLSecurityManager> url_security_manager;
144 // TODO(willchan): Remove proxy script fetcher context since it's not
145 // necessary now that I got rid of refcounting URLRequestContexts.
147 // The first URLRequestContext is |system_url_request_context|. We introduce
148 // |proxy_script_fetcher_context| for the second context. It has a direct
149 // ProxyService, since we always directly connect to fetch the PAC script.
150 scoped_ptr<net::URLRequestContext> proxy_script_fetcher_context;
151 scoped_ptr<net::ProxyService> system_proxy_service;
152 scoped_ptr<net::HttpTransactionFactory> system_http_transaction_factory;
153 scoped_ptr<net::URLRequestJobFactory> system_url_request_job_factory;
154 scoped_ptr<net::URLRequestContext> system_request_context;
155 SystemRequestContextLeakChecker system_request_context_leak_checker;
156 // |system_cookie_store| and |system_channel_id_service| are shared
157 // between |proxy_script_fetcher_context| and |system_request_context|.
158 scoped_refptr<net::CookieStore> system_cookie_store;
159 #if defined(ENABLE_EXTENSIONS)
160 scoped_refptr<extensions::EventRouterForwarder>
161 extension_event_router_forwarder;
162 #endif
163 scoped_ptr<net::HostMappingRules> host_mapping_rules;
164 scoped_ptr<net::HttpUserAgentSettings> http_user_agent_settings;
165 scoped_ptr<net::NetworkQualityEstimator> network_quality_estimator;
166 bool ignore_certificate_errors;
167 bool use_stale_while_revalidate;
168 uint16 testing_fixed_http_port;
169 uint16 testing_fixed_https_port;
170 Optional<bool> enable_tcp_fast_open_for_ssl;
172 Optional<size_t> initial_max_spdy_concurrent_streams;
173 Optional<bool> enable_spdy_compression;
174 Optional<bool> enable_spdy_ping_based_connection_checking;
175 Optional<net::NextProto> spdy_default_protocol;
176 net::NextProtoVector next_protos;
177 Optional<std::string> trusted_spdy_proxy;
178 std::set<net::HostPortPair> forced_spdy_exclusions;
179 Optional<bool> use_alternate_protocols;
180 Optional<double> alternative_service_probability_threshold;
182 Optional<bool> enable_quic;
183 Optional<bool> disable_insecure_quic;
184 Optional<bool> enable_quic_for_proxies;
185 Optional<bool> enable_quic_port_selection;
186 Optional<bool> quic_always_require_handshake_confirmation;
187 Optional<bool> quic_disable_connection_pooling;
188 Optional<float> quic_load_server_info_timeout_srtt_multiplier;
189 Optional<bool> quic_enable_connection_racing;
190 Optional<bool> quic_enable_non_blocking_io;
191 Optional<bool> quic_disable_disk_cache;
192 Optional<int> quic_max_number_of_lossy_connections;
193 Optional<float> quic_packet_loss_threshold;
194 Optional<int> quic_socket_receive_buffer_size;
195 Optional<size_t> quic_max_packet_length;
196 net::QuicTagVector quic_connection_options;
197 Optional<std::string> quic_user_agent_id;
198 Optional<net::QuicVersionVector> quic_supported_versions;
199 Optional<net::HostPortPair> origin_to_force_quic_on;
200 bool enable_user_alternate_protocol_ports;
201 // NetErrorTabHelper uses |dns_probe_service| to send DNS probes when a
202 // main frame load fails with a DNS error in order to provide more useful
203 // information to the renderer so it can show a more specific error page.
204 scoped_ptr<chrome_browser_net::DnsProbeService> dns_probe_service;
207 // |net_log| must either outlive the IOThread or be NULL.
208 IOThread(PrefService* local_state,
209 policy::PolicyService* policy_service,
210 ChromeNetLog* net_log,
211 extensions::EventRouterForwarder* extension_event_router_forwarder);
213 ~IOThread() override;
215 static void RegisterPrefs(PrefRegistrySimple* registry);
217 // Can only be called on the IO thread.
218 Globals* globals();
220 // Allows overriding Globals in tests where IOThread::Init() and
221 // IOThread::CleanUp() are not called. This allows for injecting mocks into
222 // IOThread global objects.
223 void SetGlobalsForTesting(Globals* globals);
225 ChromeNetLog* net_log();
227 // Handles changing to On The Record mode, discarding confidential data.
228 void ChangedToOnTheRecord();
230 // Returns a getter for the URLRequestContext. Only called on the UI thread.
231 net::URLRequestContextGetter* system_url_request_context_getter();
233 // Clears the host cache. Intended to be used to prevent exposing recently
234 // visited sites on about:net-internals/#dns and about:dns pages. Must be
235 // called on the IO thread.
236 void ClearHostCache();
238 void InitializeNetworkSessionParams(net::HttpNetworkSession::Params* params);
240 base::TimeTicks creation_time() const;
242 // Returns true if QUIC should be enabled for data reduction proxy, either as
243 // a result of a field trial or a command line flag.
244 static bool ShouldEnableQuicForDataReductionProxy();
246 private:
247 // Map from name to value for all parameters associate with a field trial.
248 typedef std::map<std::string, std::string> VariationParameters;
250 // Provide SystemURLRequestContextGetter with access to
251 // InitSystemRequestContext().
252 friend class SystemURLRequestContextGetter;
254 friend class test::IOThreadPeer;
256 // BrowserThreadDelegate implementation, runs on the IO thread.
257 // This handles initialization and destruction of state that must
258 // live on the IO thread.
259 void Init() override;
260 void InitAsync() override;
261 void CleanUp() override;
263 // Initializes |params| based on the settings in |globals|.
264 static void InitializeNetworkSessionParamsFromGlobals(
265 const Globals& globals,
266 net::HttpNetworkSession::Params* params);
268 void InitializeNetworkOptions(const base::CommandLine& parsed_command_line);
270 // Sets up TCP FastOpen if enabled via field trials or via the command line.
271 void ConfigureTCPFastOpen(const base::CommandLine& command_line);
273 // Sets up SDCH based on field trials.
274 void ConfigureSdch();
276 // Configures available SPDY protocol versions in |globals| based on the flags
277 // in |command_lin| as well as SPDY field trial group and parameters. Must be
278 // called after ConfigureQuicGlobals.
279 static void ConfigureSpdyGlobals(const base::CommandLine& command_line,
280 base::StringPiece quic_trial_group,
281 const VariationParameters& quic_trial_params,
282 Globals* globals);
284 // Global state must be initialized on the IO thread, then this
285 // method must be invoked on the UI thread.
286 void InitSystemRequestContext();
288 // Lazy initialization of system request context for
289 // SystemURLRequestContextGetter. To be called on IO thread only
290 // after global state has been initialized on the IO thread, and
291 // SystemRequestContext state has been initialized on the UI thread.
292 void InitSystemRequestContextOnIOThread();
294 net::HttpAuthHandlerFactory* CreateDefaultAuthHandlerFactory(
295 net::HostResolver* resolver);
297 // Returns an SSLConfigService instance.
298 net::SSLConfigService* GetSSLConfigService();
300 void ChangedToOnTheRecordOnIOThread();
302 void UpdateDnsClientEnabled();
304 // Configures QUIC options based on the flags in |command_line| as
305 // well as the QUIC field trial group.
306 void ConfigureQuic(const base::CommandLine& command_line);
308 extensions::EventRouterForwarder* extension_event_router_forwarder() {
309 #if defined(ENABLE_EXTENSIONS)
310 return extension_event_router_forwarder_;
311 #else
312 return NULL;
313 #endif
315 // Configures QUIC options in |globals| based on the flags in |command_line|
316 // as well as the QUIC field trial group and parameters. Must be called
317 // before ConfigureSpdyGlobals.
318 static void ConfigureQuicGlobals(
319 const base::CommandLine& command_line,
320 base::StringPiece quic_trial_group,
321 const VariationParameters& quic_trial_params,
322 bool quic_allowed_by_policy,
323 Globals* globals);
325 // Returns true if QUIC should be enabled, either as a result
326 // of a field trial or a command line flag.
327 static bool ShouldEnableQuic(
328 const base::CommandLine& command_line,
329 base::StringPiece quic_trial_group,
330 bool quic_allowed_by_policy);
332 // Returns true if QUIC should be enabled for proxies, either as a result
333 // of a field trial or a command line flag.
334 static bool ShouldEnableQuicForProxies(
335 const base::CommandLine& command_line,
336 base::StringPiece quic_trial_group,
337 bool quic_allowed_by_policy);
339 // Returns true if QUIC should be disabled for http:// URLs, as a result
340 // of a field trial.
341 static bool ShouldDisableInsecureQuic(
342 const VariationParameters& quic_trial_params);
344 // Returns true if the selection of the ephemeral port in bind() should be
345 // performed by Chromium, and false if the OS should select the port. The OS
346 // option is used to prevent Windows from posting a security security warning
347 // dialog.
348 static bool ShouldEnableQuicPortSelection(
349 const base::CommandLine& command_line);
351 // Returns true if QUIC should always require handshake confirmation during
352 // the QUIC handshake.
353 static bool ShouldQuicAlwaysRequireHandshakeConfirmation(
354 const VariationParameters& quic_trial_params);
356 // Returns true if QUIC should disable connection pooling.
357 static bool ShouldQuicDisableConnectionPooling(
358 const VariationParameters& quic_trial_params);
360 // Returns the ratio of time to load QUIC sever information from disk cache to
361 // 'smoothed RTT' based on field trial. Returns 0 if there is an error parsing
362 // the field trial params, or if the default value should be used.
363 static float GetQuicLoadServerInfoTimeoutSrttMultiplier(
364 const VariationParameters& quic_trial_params);
366 // Returns true if QUIC's connection racing should be enabled.
367 static bool ShouldQuicEnableConnectionRacing(
368 const VariationParameters& quic_trial_params);
370 // Returns true if QUIC's should use non-blocking IO.
371 static bool ShouldQuicEnableNonBlockingIO(
372 const VariationParameters& quic_trial_params);
374 // Returns true if QUIC shouldn't load QUIC server information from the disk
375 // cache.
376 static bool ShouldQuicDisableDiskCache(
377 const VariationParameters& quic_trial_params);
379 // Returns the maximum number of QUIC connections with high packet loss in a
380 // row after which QUIC should be disabled. Returns 0 if the default value
381 // should be used.
382 static int GetQuicMaxNumberOfLossyConnections(
383 const VariationParameters& quic_trial_params);
385 // Returns the packet loss rate in fraction after which a QUIC connection is
386 // closed and is considered as a lossy connection. Returns 0 if the default
387 // value should be used.
388 static float GetQuicPacketLossThreshold(
389 const VariationParameters& quic_trial_params);
391 // Returns the size of the QUIC receive buffer to use, or 0 if
392 // the default should be used.
393 static int GetQuicSocketReceiveBufferSize(
394 const VariationParameters& quic_trial_params);
396 // Returns the maximum length for QUIC packets, based on any flags in
397 // |command_line| or the field trial. Returns 0 if there is an error
398 // parsing any of the options, or if the default value should be used.
399 static size_t GetQuicMaxPacketLength(
400 const base::CommandLine& command_line,
401 const VariationParameters& quic_trial_params);
403 // Returns the QUIC versions specified by any flags in |command_line|
404 // or |quic_trial_params|.
405 static net::QuicVersion GetQuicVersion(
406 const base::CommandLine& command_line,
407 const VariationParameters& quic_trial_params);
409 // Returns the QUIC version specified by |quic_version| or
410 // QUIC_VERSION_UNSUPPORTED if |quic_version| is invalid.
411 static net::QuicVersion ParseQuicVersion(const std::string& quic_version);
413 // Returns the QUIC connection options specified by any flags in
414 // |command_line| or |quic_trial_params|.
415 static net::QuicTagVector GetQuicConnectionOptions(
416 const base::CommandLine& command_line,
417 const VariationParameters& quic_trial_params);
419 // Returns the alternative service probability threshold specified by
420 // any flags in |command_line| or |quic_trial_params|.
421 static double GetAlternativeProtocolProbabilityThreshold(
422 const base::CommandLine& command_line,
423 const VariationParameters& quic_trial_params);
425 // The NetLog is owned by the browser process, to allow logging from other
426 // threads during shutdown, but is used most frequently on the IOThread.
427 ChromeNetLog* net_log_;
429 #if defined(ENABLE_EXTENSIONS)
430 // The extensions::EventRouterForwarder allows for sending events to
431 // extensions from the IOThread.
432 extensions::EventRouterForwarder* extension_event_router_forwarder_;
433 #endif
435 // These member variables are basically global, but their lifetimes are tied
436 // to the IOThread. IOThread owns them all, despite not using scoped_ptr.
437 // This is because the destructor of IOThread runs on the wrong thread. All
438 // member variables should be deleted in CleanUp().
440 // These member variables are initialized in Init() and do not change for the
441 // lifetime of the IO thread.
443 Globals* globals_;
445 // Observer that logs network changes to the ChromeNetLog.
446 class LoggingNetworkChangeObserver;
447 scoped_ptr<LoggingNetworkChangeObserver> network_change_observer_;
449 BooleanPrefMember system_enable_referrers_;
451 BooleanPrefMember dns_client_enabled_;
453 BooleanPrefMember quick_check_enabled_;
455 // Store HTTP Auth-related policies in this thread.
456 std::string auth_schemes_;
457 bool negotiate_disable_cname_lookup_;
458 bool negotiate_enable_port_;
459 std::string auth_server_whitelist_;
460 std::string auth_delegate_whitelist_;
461 std::string gssapi_library_name_;
463 // This is an instance of the default SSLConfigServiceManager for the current
464 // platform and it gets SSL preferences from local_state object.
465 scoped_ptr<SSLConfigServiceManager> ssl_config_service_manager_;
467 // These member variables are initialized by a task posted to the IO thread,
468 // which gets posted by calling certain member functions of IOThread.
469 scoped_ptr<net::ProxyConfigService> system_proxy_config_service_;
471 scoped_ptr<PrefProxyConfigTracker> pref_proxy_config_tracker_;
473 scoped_refptr<net::URLRequestContextGetter>
474 system_url_request_context_getter_;
476 // True if SPDY is disabled by policy.
477 bool is_spdy_disabled_by_policy_;
479 // True if QUIC is allowed by policy.
480 bool is_quic_allowed_by_policy_;
482 const base::TimeTicks creation_time_;
484 base::WeakPtrFactory<IOThread> weak_factory_;
486 DISALLOW_COPY_AND_ASSIGN(IOThread);
489 #endif // CHROME_BROWSER_IO_THREAD_H_