Upstream version 11.39.250.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / io_thread.h
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.
4
5 #ifndef CHROME_BROWSER_IO_THREAD_H_
6 #define CHROME_BROWSER_IO_THREAD_H_
7
8 #include <string>
9 #include <vector>
10
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"
26
27 class ChromeNetLog;
28 class PrefProxyConfigTracker;
29 class PrefService;
30 class PrefRegistrySimple;
31 class SystemURLRequestContextGetter;
32
33 namespace base {
34 class CommandLine;
35 }
36
37 namespace chrome_browser_net {
38 class DnsProbeService;
39 }
40
41 namespace data_reduction_proxy {
42 class DataReductionProxyAuthRequestHandler;
43 class DataReductionProxyDelegate;
44 class DataReductionProxyParams;
45 }
46
47 namespace extensions {
48 class EventRouterForwarder;
49 }
50
51 namespace net {
52 class CertVerifier;
53 class ChannelIDService;
54 class CookieStore;
55 class CTVerifier;
56 class FtpTransactionFactory;
57 class HostMappingRules;
58 class HostResolver;
59 class HttpAuthHandlerFactory;
60 class HttpServerProperties;
61 class HttpTransactionFactory;
62 class HttpUserAgentSettings;
63 class NetworkDelegate;
64 class ProxyConfigService;
65 class ProxyService;
66 class SSLConfigService;
67 class TransportSecurityState;
68 class URLRequestContext;
69 class URLRequestContextGetter;
70 class URLRequestJobFactory;
71 class URLRequestThrottlerManager;
72 class URLSecurityManager;
73 }  // namespace net
74
75 namespace policy {
76 class PolicyService;
77 }  // namespace policy
78
79 namespace test {
80 class IOThreadPeer;
81 }  // namespace test
82
83 // Contains state associated with, initialized and cleaned up on, and
84 // primarily used on, the IO thread.
85 //
86 // If you are looking to interact with the IO thread (e.g. post tasks
87 // to it or check if it is the current thread), see
88 // content::BrowserThread.
89 class IOThread : public content::BrowserThreadDelegate {
90  public:
91   struct Globals {
92     template <typename T>
93     class Optional {
94      public:
95       Optional() : set_(false) {}
96
97       void set(T value) {
98         set_ = true;
99         value_ = value;
100       }
101       void CopyToIfSet(T* value) const {
102         if (set_) {
103           *value = value_;
104         }
105       }
106
107      private:
108       bool set_;
109       T value_;
110     };
111
112     class SystemRequestContextLeakChecker {
113      public:
114       explicit SystemRequestContextLeakChecker(Globals* globals);
115       ~SystemRequestContextLeakChecker();
116
117      private:
118       Globals* const globals_;
119     };
120
121     Globals();
122     ~Globals();
123
124     // The "system" NetworkDelegate, used for Profile-agnostic network events.
125     scoped_ptr<net::NetworkDelegate> system_network_delegate;
126     scoped_ptr<net::HostResolver> host_resolver;
127     scoped_ptr<net::CertVerifier> cert_verifier;
128     // The ChannelIDService must outlive the HttpTransactionFactory.
129     scoped_ptr<net::ChannelIDService> system_channel_id_service;
130     // This TransportSecurityState doesn't load or save any state. It's only
131     // used to enforce pinning for system requests and will only use built-in
132     // pins.
133     scoped_ptr<net::TransportSecurityState> transport_security_state;
134     scoped_ptr<net::CTVerifier> cert_transparency_verifier;
135     scoped_refptr<net::SSLConfigService> ssl_config_service;
136     scoped_ptr<net::HttpAuthHandlerFactory> http_auth_handler_factory;
137     scoped_ptr<net::HttpServerProperties> http_server_properties;
138     scoped_ptr<net::ProxyService> proxy_script_fetcher_proxy_service;
139     scoped_ptr<net::HttpTransactionFactory>
140         proxy_script_fetcher_http_transaction_factory;
141     scoped_ptr<net::FtpTransactionFactory>
142         proxy_script_fetcher_ftp_transaction_factory;
143     scoped_ptr<net::URLRequestJobFactory>
144         proxy_script_fetcher_url_request_job_factory;
145     scoped_ptr<net::URLRequestThrottlerManager> throttler_manager;
146     scoped_ptr<net::URLSecurityManager> url_security_manager;
147     // TODO(willchan): Remove proxy script fetcher context since it's not
148     // necessary now that I got rid of refcounting URLRequestContexts.
149     //
150     // The first URLRequestContext is |system_url_request_context|. We introduce
151     // |proxy_script_fetcher_context| for the second context. It has a direct
152     // ProxyService, since we always directly connect to fetch the PAC script.
153     scoped_ptr<net::URLRequestContext> proxy_script_fetcher_context;
154     scoped_ptr<net::ProxyService> system_proxy_service;
155     scoped_ptr<net::HttpTransactionFactory> system_http_transaction_factory;
156     scoped_ptr<net::URLRequestJobFactory> system_url_request_job_factory;
157     scoped_ptr<net::URLRequestContext> system_request_context;
158     SystemRequestContextLeakChecker system_request_context_leak_checker;
159     // |system_cookie_store| and |system_channel_id_service| are shared
160     // between |proxy_script_fetcher_context| and |system_request_context|.
161     scoped_refptr<net::CookieStore> system_cookie_store;
162 #if defined(ENABLE_EXTENSIONS)
163     scoped_refptr<extensions::EventRouterForwarder>
164         extension_event_router_forwarder;
165 #endif
166     scoped_ptr<net::HostMappingRules> host_mapping_rules;
167     scoped_ptr<net::HttpUserAgentSettings> http_user_agent_settings;
168     bool enable_ssl_connect_job_waiting;
169     bool ignore_certificate_errors;
170     uint16 testing_fixed_http_port;
171     uint16 testing_fixed_https_port;
172     Optional<bool> enable_tcp_fast_open_for_ssl;
173
174     Optional<size_t> initial_max_spdy_concurrent_streams;
175     Optional<bool> force_spdy_single_domain;
176     Optional<bool> enable_spdy_compression;
177     Optional<bool> enable_spdy_ping_based_connection_checking;
178     Optional<net::NextProto> spdy_default_protocol;
179     net::NextProtoVector next_protos;
180     Optional<string> trusted_spdy_proxy;
181     Optional<bool> force_spdy_over_ssl;
182     Optional<bool> force_spdy_always;
183     std::set<net::HostPortPair> forced_spdy_exclusions;
184     Optional<bool> use_alternate_protocols;
185     Optional<double> alternate_protocol_probability_threshold;
186     Optional<bool> enable_websocket_over_spdy;
187
188     Optional<bool> enable_quic;
189     Optional<bool> enable_quic_time_based_loss_detection;
190     Optional<bool> enable_quic_port_selection;
191     Optional<bool> quic_always_require_handshake_confirmation;
192     Optional<bool> quic_disable_connection_pooling;
193     Optional<size_t> quic_max_packet_length;
194     net::QuicTagVector quic_connection_options;
195     Optional<std::string> quic_user_agent_id;
196     Optional<net::QuicVersionVector> quic_supported_versions;
197     Optional<net::HostPortPair> origin_to_force_quic_on;
198     bool enable_user_alternate_protocol_ports;
199     // NetErrorTabHelper uses |dns_probe_service| to send DNS probes when a
200     // main frame load fails with a DNS error in order to provide more useful
201     // information to the renderer so it can show a more specific error page.
202     scoped_ptr<chrome_browser_net::DnsProbeService> dns_probe_service;
203     scoped_ptr<data_reduction_proxy::DataReductionProxyParams>
204         data_reduction_proxy_params;
205     scoped_ptr<data_reduction_proxy::DataReductionProxyAuthRequestHandler>
206         data_reduction_proxy_auth_request_handler;
207     scoped_ptr<data_reduction_proxy::DataReductionProxyDelegate>
208         data_reduction_proxy_delegate;
209   };
210
211   // |net_log| must either outlive the IOThread or be NULL.
212   IOThread(PrefService* local_state,
213            policy::PolicyService* policy_service,
214            ChromeNetLog* net_log,
215            extensions::EventRouterForwarder* extension_event_router_forwarder);
216
217   virtual ~IOThread();
218
219   static void RegisterPrefs(PrefRegistrySimple* registry);
220
221   // Can only be called on the IO thread.
222   Globals* globals();
223
224   // Allows overriding Globals in tests where IOThread::Init() and
225   // IOThread::CleanUp() are not called.  This allows for injecting mocks into
226   // IOThread global objects.
227   void SetGlobalsForTesting(Globals* globals);
228
229   ChromeNetLog* net_log();
230
231   // Handles changing to On The Record mode, discarding confidential data.
232   void ChangedToOnTheRecord();
233
234   // Returns a getter for the URLRequestContext.  Only called on the UI thread.
235   net::URLRequestContextGetter* system_url_request_context_getter();
236
237   // Clears the host cache.  Intended to be used to prevent exposing recently
238   // visited sites on about:net-internals/#dns and about:dns pages.  Must be
239   // called on the IO thread.
240   void ClearHostCache();
241
242   void InitializeNetworkSessionParams(net::HttpNetworkSession::Params* params);
243
244   base::TimeTicks creation_time() const;
245
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;
249
250   // Provide SystemURLRequestContextGetter with access to
251   // InitSystemRequestContext().
252   friend class SystemURLRequestContextGetter;
253
254   friend class test::IOThreadPeer;
255
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   virtual void Init() OVERRIDE;
260   virtual void InitAsync() OVERRIDE;
261   virtual void CleanUp() OVERRIDE;
262
263   // Initializes |params| based on the settings in |globals|.
264   static void InitializeNetworkSessionParamsFromGlobals(
265       const Globals& globals,
266       net::HttpNetworkSession::Params* params);
267
268   void InitializeNetworkOptions(const base::CommandLine& parsed_command_line);
269
270   // Sets up TCP FastOpen if enabled via field trials or via the command line.
271   void ConfigureTCPFastOpen(const base::CommandLine& command_line);
272
273   // Enable SPDY with the given mode, which may contain the following:
274   //
275   //   "off"                      : Disables SPDY support entirely.
276   //   "ssl"                      : Forces SPDY for all HTTPS requests.
277   //   "no-ssl"                   : Forces SPDY for all HTTP requests.
278   //   "no-ping"                  : Disables SPDY ping connection testing.
279   //   "exclude=<host>"           : Disables SPDY support for the host <host>.
280   //   "no-compress"              : Disables SPDY header compression.
281   //   "no-alt-protocols          : Disables alternate protocol support.
282   //   "force-alt-protocols       : Forces an alternate protocol of SPDY/3
283   //                                on port 443.
284   //   "single-domain"            : Forces all spdy traffic to a single domain.
285   //   "init-max-streams=<limit>" : Specifies the maximum number of concurrent
286   //                                streams for a SPDY session, unless the
287   //                                specifies a different value via SETTINGS.
288   void EnableSpdy(const std::string& mode);
289
290   // Configures available SPDY protocol versions from the given trial.
291   // Used only if no command-line configuration was present.
292   static void ConfigureSpdyFromTrial(base::StringPiece spdy_trial_group,
293                                      Globals* globals);
294
295   // Global state must be initialized on the IO thread, then this
296   // method must be invoked on the UI thread.
297   void InitSystemRequestContext();
298
299   // Lazy initialization of system request context for
300   // SystemURLRequestContextGetter. To be called on IO thread only
301   // after global state has been initialized on the IO thread, and
302   // SystemRequestContext state has been initialized on the UI thread.
303   void InitSystemRequestContextOnIOThread();
304
305   net::HttpAuthHandlerFactory* CreateDefaultAuthHandlerFactory(
306       net::HostResolver* resolver);
307
308   // Returns an SSLConfigService instance.
309   net::SSLConfigService* GetSSLConfigService();
310
311   void ChangedToOnTheRecordOnIOThread();
312
313   void UpdateDnsClientEnabled();
314
315   // Configures QUIC options based on the flags in |command_line| as
316   // well as the QUIC field trial group.
317   void ConfigureQuic(const base::CommandLine& command_line);
318
319   // Set up data reduction proxy related objects on IO thread globals.
320   void SetupDataReductionProxy(ChromeNetworkDelegate* network_delegate);
321
322   extensions::EventRouterForwarder* extension_event_router_forwarder() {
323 #if defined(ENABLE_EXTENSIONS)
324     return extension_event_router_forwarder_;
325 #else
326     return NULL;
327 #endif
328   }
329   // Configures QUIC options in |globals| based on the flags in |command_line|
330   // as well as the QUIC field trial group and parameters.
331   static void ConfigureQuicGlobals(
332       const base::CommandLine& command_line,
333       base::StringPiece quic_trial_group,
334       const VariationParameters& quic_trial_params,
335       Globals* globals);
336
337   // Returns true if QUIC should be enabled, either as a result
338   // of a field trial or a command line flag.
339   static bool ShouldEnableQuic(
340       const base::CommandLine& command_line,
341       base::StringPiece quic_trial_group);
342
343   // Returns true if the selection of the ephemeral port in bind() should be
344   // performed by Chromium, and false if the OS should select the port.  The OS
345   // option is used to prevent Windows from posting a security security warning
346   // dialog.
347   static bool ShouldEnableQuicPortSelection(
348       const base::CommandLine& command_line);
349
350   // Returns true if QUIC packet pacing should be negotiated during the
351   // QUIC handshake.
352   static bool ShouldEnableQuicPacing(
353       const base::CommandLine& command_line,
354       base::StringPiece quic_trial_group,
355       const VariationParameters& quic_trial_params);
356
357   // Returns true if QUIC time-base loss detection should be negotiated during
358   // the QUIC handshake.
359   static bool ShouldEnableQuicTimeBasedLossDetection(
360       const base::CommandLine& command_line,
361       base::StringPiece quic_trial_group,
362       const VariationParameters& quic_trial_params);
363
364   // Returns true if QUIC should always require handshake confirmation during
365   // the QUIC handshake.
366   static bool ShouldQuicAlwaysRequireHandshakeConfirmation(
367       const VariationParameters& quic_trial_params);
368
369   // Returns true if QUIC should disable connection pooling.
370   static bool ShouldQuicDisableConnectionPooling(
371       const VariationParameters& quic_trial_params);
372
373   // Returns the maximum length for QUIC packets, based on any flags in
374   // |command_line| or the field trial.  Returns 0 if there is an error
375   // parsing any of the options, or if the default value should be used.
376   static size_t GetQuicMaxPacketLength(
377       const base::CommandLine& command_line,
378       base::StringPiece quic_trial_group,
379       const VariationParameters& quic_trial_params);
380
381   // Returns the QUIC versions specified by any flags in |command_line|
382   // or |quic_trial_params|.
383   static net::QuicVersion GetQuicVersion(
384       const base::CommandLine& command_line,
385       const VariationParameters& quic_trial_params);
386
387   // Returns the QUIC version specified by |quic_version| or
388   // QUIC_VERSION_UNSUPPORTED if |quic_version| is invalid.
389   static net::QuicVersion ParseQuicVersion(const std::string& quic_version);
390
391   // Returns the QUIC connection options specified by any flags in
392   // |command_line| or |quic_trial_params|.
393   static net::QuicTagVector GetQuicConnectionOptions(
394       const base::CommandLine& command_line,
395       const VariationParameters& quic_trial_params);
396
397   // Returns the list of QUIC tags represented by the comma separated
398   // string in |connection_options|.
399   static net::QuicTagVector ParseQuicConnectionOptions(
400       const std::string& connection_options);
401
402   // Returns the alternate protocol probability threshold specified by
403   // any flags in |command_line| or |quic_trial_params|.
404   static double GetAlternateProtocolProbabilityThreshold(
405       const base::CommandLine& command_line,
406       const VariationParameters& quic_trial_params);
407
408   // The NetLog is owned by the browser process, to allow logging from other
409   // threads during shutdown, but is used most frequently on the IOThread.
410   ChromeNetLog* net_log_;
411
412 #if defined(ENABLE_EXTENSIONS)
413   // The extensions::EventRouterForwarder allows for sending events to
414   // extensions from the IOThread.
415   extensions::EventRouterForwarder* extension_event_router_forwarder_;
416 #endif
417
418   // These member variables are basically global, but their lifetimes are tied
419   // to the IOThread.  IOThread owns them all, despite not using scoped_ptr.
420   // This is because the destructor of IOThread runs on the wrong thread.  All
421   // member variables should be deleted in CleanUp().
422
423   // These member variables are initialized in Init() and do not change for the
424   // lifetime of the IO thread.
425
426   Globals* globals_;
427
428   // Observer that logs network changes to the ChromeNetLog.
429   class LoggingNetworkChangeObserver;
430   scoped_ptr<LoggingNetworkChangeObserver> network_change_observer_;
431
432   BooleanPrefMember system_enable_referrers_;
433
434   BooleanPrefMember dns_client_enabled_;
435
436   BooleanPrefMember quick_check_enabled_;
437
438   // Store HTTP Auth-related policies in this thread.
439   std::string auth_schemes_;
440   bool negotiate_disable_cname_lookup_;
441   bool negotiate_enable_port_;
442   std::string auth_server_whitelist_;
443   std::string auth_delegate_whitelist_;
444   std::string gssapi_library_name_;
445
446   // This is an instance of the default SSLConfigServiceManager for the current
447   // platform and it gets SSL preferences from local_state object.
448   scoped_ptr<SSLConfigServiceManager> ssl_config_service_manager_;
449
450   // These member variables are initialized by a task posted to the IO thread,
451   // which gets posted by calling certain member functions of IOThread.
452   scoped_ptr<net::ProxyConfigService> system_proxy_config_service_;
453
454   scoped_ptr<PrefProxyConfigTracker> pref_proxy_config_tracker_;
455
456   scoped_refptr<net::URLRequestContextGetter>
457       system_url_request_context_getter_;
458
459   // True if SPDY is disabled by policy.
460   bool is_spdy_disabled_by_policy_;
461
462   const base::TimeTicks creation_time_;
463
464   base::WeakPtrFactory<IOThread> weak_factory_;
465
466   DISALLOW_COPY_AND_ASSIGN(IOThread);
467 };
468
469 #endif  // CHROME_BROWSER_IO_THREAD_H_