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