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