Home | History | Annotate | Download | only in browser
      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 "chrome/browser/net/ssl_config_service_manager.h"
     18 #include "content/public/browser/browser_thread.h"
     19 #include "content/public/browser/browser_thread_delegate.h"
     20 #include "net/base/network_change_notifier.h"
     21 #include "net/http/http_network_session.h"
     22 #include "net/socket/next_proto.h"
     23 
     24 class ChromeNetLog;
     25 class CommandLine;
     26 class PrefProxyConfigTracker;
     27 class PrefService;
     28 class PrefRegistrySimple;
     29 class SystemURLRequestContextGetter;
     30 
     31 namespace chrome_browser_net {
     32 class DnsProbeService;
     33 class HttpPipeliningCompatibilityClient;
     34 class LoadTimeStats;
     35 }
     36 
     37 namespace extensions {
     38 class EventRouterForwarder;
     39 }
     40 
     41 namespace net {
     42 class CertVerifier;
     43 class CookieStore;
     44 class CTVerifier;
     45 class FtpTransactionFactory;
     46 class HostMappingRules;
     47 class HostResolver;
     48 class HttpAuthHandlerFactory;
     49 class HttpServerProperties;
     50 class HttpTransactionFactory;
     51 class HttpUserAgentSettings;
     52 class NetworkDelegate;
     53 class NetworkTimeNotifier;
     54 class ServerBoundCertService;
     55 class ProxyConfigService;
     56 class ProxyService;
     57 class SdchManager;
     58 class SSLConfigService;
     59 class TransportSecurityState;
     60 class URLRequestContext;
     61 class URLRequestContextGetter;
     62 class URLRequestJobFactory;
     63 class URLRequestThrottlerManager;
     64 class URLSecurityManager;
     65 }  // namespace net
     66 
     67 namespace policy {
     68 class PolicyService;
     69 }  // namespace policy
     70 
     71 // Contains state associated with, initialized and cleaned up on, and
     72 // primarily used on, the IO thread.
     73 //
     74 // If you are looking to interact with the IO thread (e.g. post tasks
     75 // to it or check if it is the current thread), see
     76 // content::BrowserThread.
     77 class IOThread : public content::BrowserThreadDelegate {
     78  public:
     79   struct Globals {
     80     template <typename T>
     81     class Optional {
     82      public:
     83       Optional() : set_(false) {}
     84 
     85       void set(T value) {
     86         set_ = true;
     87         value_ = value;
     88       }
     89       void CopyToIfSet(T* value) {
     90         if (set_) {
     91           *value = value_;
     92         }
     93       }
     94 
     95      private:
     96       bool set_;
     97       T value_;
     98     };
     99 
    100     class SystemRequestContextLeakChecker {
    101      public:
    102       explicit SystemRequestContextLeakChecker(Globals* globals);
    103       ~SystemRequestContextLeakChecker();
    104 
    105      private:
    106       Globals* const globals_;
    107     };
    108 
    109     Globals();
    110     ~Globals();
    111 
    112     // The "system" NetworkDelegate, used for Profile-agnostic network events.
    113     scoped_ptr<net::NetworkDelegate> system_network_delegate;
    114     scoped_ptr<net::HostResolver> host_resolver;
    115     scoped_ptr<net::CertVerifier> cert_verifier;
    116     // The ServerBoundCertService must outlive the HttpTransactionFactory.
    117     scoped_ptr<net::ServerBoundCertService> system_server_bound_cert_service;
    118     // This TransportSecurityState doesn't load or save any state. It's only
    119     // used to enforce pinning for system requests and will only use built-in
    120     // pins.
    121     scoped_ptr<net::TransportSecurityState> transport_security_state;
    122     scoped_ptr<net::CTVerifier> cert_transparency_verifier;
    123     scoped_refptr<net::SSLConfigService> ssl_config_service;
    124     scoped_ptr<net::HttpAuthHandlerFactory> http_auth_handler_factory;
    125     scoped_ptr<net::HttpServerProperties> http_server_properties;
    126     scoped_ptr<net::ProxyService> proxy_script_fetcher_proxy_service;
    127     scoped_ptr<net::HttpTransactionFactory>
    128         proxy_script_fetcher_http_transaction_factory;
    129     scoped_ptr<net::FtpTransactionFactory>
    130         proxy_script_fetcher_ftp_transaction_factory;
    131     scoped_ptr<net::URLRequestJobFactory>
    132         proxy_script_fetcher_url_request_job_factory;
    133     scoped_ptr<net::URLRequestThrottlerManager> throttler_manager;
    134     scoped_ptr<net::URLSecurityManager> url_security_manager;
    135     // TODO(willchan): Remove proxy script fetcher context since it's not
    136     // necessary now that I got rid of refcounting URLRequestContexts.
    137     //
    138     // The first URLRequestContext is |system_url_request_context|. We introduce
    139     // |proxy_script_fetcher_context| for the second context. It has a direct
    140     // ProxyService, since we always directly connect to fetch the PAC script.
    141     scoped_ptr<net::URLRequestContext> proxy_script_fetcher_context;
    142     scoped_ptr<net::ProxyService> system_proxy_service;
    143     scoped_ptr<net::HttpTransactionFactory> system_http_transaction_factory;
    144     scoped_ptr<net::URLRequestContext> system_request_context;
    145     SystemRequestContextLeakChecker system_request_context_leak_checker;
    146     // |system_cookie_store| and |system_server_bound_cert_service| are shared
    147     // between |proxy_script_fetcher_context| and |system_request_context|.
    148     scoped_refptr<net::CookieStore> system_cookie_store;
    149     scoped_refptr<extensions::EventRouterForwarder>
    150         extension_event_router_forwarder;
    151     scoped_ptr<chrome_browser_net::HttpPipeliningCompatibilityClient>
    152         http_pipelining_compatibility_client;
    153     scoped_ptr<chrome_browser_net::LoadTimeStats> load_time_stats;
    154     scoped_ptr<net::HostMappingRules> host_mapping_rules;
    155     scoped_ptr<net::HttpUserAgentSettings> http_user_agent_settings;
    156     bool ignore_certificate_errors;
    157     bool http_pipelining_enabled;
    158     uint16 testing_fixed_http_port;
    159     uint16 testing_fixed_https_port;
    160     Optional<size_t> initial_max_spdy_concurrent_streams;
    161     Optional<size_t> max_spdy_concurrent_streams_limit;
    162     Optional<bool> force_spdy_single_domain;
    163     Optional<bool> enable_spdy_ip_pooling;
    164     Optional<bool> enable_spdy_compression;
    165     Optional<bool> enable_spdy_ping_based_connection_checking;
    166     Optional<net::NextProto> spdy_default_protocol;
    167     Optional<string> trusted_spdy_proxy;
    168     Optional<bool> enable_quic;
    169     Optional<bool> enable_quic_https;
    170     Optional<size_t> quic_max_packet_length;
    171     Optional<net::HostPortPair> origin_to_force_quic_on;
    172     bool enable_user_alternate_protocol_ports;
    173     // NetErrorTabHelper uses |dns_probe_service| to send DNS probes when a
    174     // main frame load fails with a DNS error in order to provide more useful
    175     // information to the renderer so it can show a more specific error page.
    176     scoped_ptr<chrome_browser_net::DnsProbeService> dns_probe_service;
    177     scoped_ptr<net::NetworkTimeNotifier> network_time_notifier;
    178   };
    179 
    180   // |net_log| must either outlive the IOThread or be NULL.
    181   IOThread(PrefService* local_state,
    182            policy::PolicyService* policy_service,
    183            ChromeNetLog* net_log,
    184            extensions::EventRouterForwarder* extension_event_router_forwarder);
    185 
    186   virtual ~IOThread();
    187 
    188   static void RegisterPrefs(PrefRegistrySimple* registry);
    189 
    190   // Can only be called on the IO thread.
    191   Globals* globals();
    192 
    193   // Allows overriding Globals in tests where IOThread::Init() and
    194   // IOThread::CleanUp() are not called.  This allows for injecting mocks into
    195   // IOThread global objects.
    196   void SetGlobalsForTesting(Globals* globals);
    197 
    198   ChromeNetLog* net_log();
    199 
    200   // Handles changing to On The Record mode, discarding confidential data.
    201   void ChangedToOnTheRecord();
    202 
    203   // Returns a getter for the URLRequestContext.  Only called on the UI thread.
    204   net::URLRequestContextGetter* system_url_request_context_getter();
    205 
    206   // Clears the host cache.  Intended to be used to prevent exposing recently
    207   // visited sites on about:net-internals/#dns and about:dns pages.  Must be
    208   // called on the IO thread.
    209   void ClearHostCache();
    210 
    211   void InitializeNetworkSessionParams(net::HttpNetworkSession::Params* params);
    212 
    213  private:
    214   // Provide SystemURLRequestContextGetter with access to
    215   // InitSystemRequestContext().
    216   friend class SystemURLRequestContextGetter;
    217 
    218   // BrowserThreadDelegate implementation, runs on the IO thread.
    219   // This handles initialization and destruction of state that must
    220   // live on the IO thread.
    221   virtual void Init() OVERRIDE;
    222   virtual void InitAsync() OVERRIDE;
    223   virtual void CleanUp() OVERRIDE;
    224 
    225   void InitializeNetworkOptions(const CommandLine& parsed_command_line);
    226 
    227   // Enable SPDY with the given mode, which may contain the following:
    228   //
    229   //   "off"                      : Disables SPDY support entirely.
    230   //   "ssl"                      : Forces SPDY for all HTTPS requests.
    231   //   "no-ssl"                   : Forces SPDY for all HTTP requests.
    232   //   "no-ping"                  : Disables SPDY ping connection testing.
    233   //   "exclude=<host>"           : Disables SPDY support for the host <host>.
    234   //   "no-compress"              : Disables SPDY header compression.
    235   //   "no-alt-protocols          : Disables alternate protocol support.
    236   //   "force-alt-protocols       : Forces an alternate protocol of SPDY/3
    237   //                                on port 443.
    238   //   "single-domain"            : Forces all spdy traffic to a single domain.
    239   //   "init-max-streams=<limit>" : Specifies the maximum number of concurrent
    240   //                                streams for a SPDY session, unless the
    241   //                                specifies a different value via SETTINGS.
    242   void EnableSpdy(const std::string& mode);
    243 
    244   // Global state must be initialized on the IO thread, then this
    245   // method must be invoked on the UI thread.
    246   void InitSystemRequestContext();
    247 
    248   // Lazy initialization of system request context for
    249   // SystemURLRequestContextGetter. To be called on IO thread only
    250   // after global state has been initialized on the IO thread, and
    251   // SystemRequestContext state has been initialized on the UI thread.
    252   void InitSystemRequestContextOnIOThread();
    253 
    254   net::HttpAuthHandlerFactory* CreateDefaultAuthHandlerFactory(
    255       net::HostResolver* resolver);
    256 
    257   // Returns an SSLConfigService instance.
    258   net::SSLConfigService* GetSSLConfigService();
    259 
    260   void ChangedToOnTheRecordOnIOThread();
    261 
    262   void UpdateDnsClientEnabled();
    263 
    264   // Configures QUIC options based on the flags in |command_line| as
    265   // well as the QUIC field trial group.
    266   void ConfigureQuic(const CommandLine& command_line);
    267 
    268   // Returns true if QUIC should be enabled, either as a result
    269   // of a field trial or a command line flag.
    270   bool ShouldEnableQuic(const CommandLine& command_line,
    271                         base::StringPiece quic_trial_group);
    272 
    273   // Returns true if HTTPS over QUIC should be enabled, either as a result
    274   // of a field trial or a command line flag.
    275   bool ShouldEnableQuicHttps(const CommandLine& command_line,
    276                              base::StringPiece quic_trial_group);
    277 
    278   // Returns the maximum length for QUIC packets, based on any flags in
    279   // |command_line| or the field trial.  Returns 0 if there is an error
    280   // parsing any of the options, or if the default value should be used.
    281   size_t GetQuicMaxPacketLength(const CommandLine& command_line,
    282                                 base::StringPiece quic_trial_group);
    283 
    284   // The NetLog is owned by the browser process, to allow logging from other
    285   // threads during shutdown, but is used most frequently on the IOThread.
    286   ChromeNetLog* net_log_;
    287 
    288   // The extensions::EventRouterForwarder allows for sending events to
    289   // extensions from the IOThread.
    290   extensions::EventRouterForwarder* extension_event_router_forwarder_;
    291 
    292   // These member variables are basically global, but their lifetimes are tied
    293   // to the IOThread.  IOThread owns them all, despite not using scoped_ptr.
    294   // This is because the destructor of IOThread runs on the wrong thread.  All
    295   // member variables should be deleted in CleanUp().
    296 
    297   // These member variables are initialized in Init() and do not change for the
    298   // lifetime of the IO thread.
    299 
    300   Globals* globals_;
    301 
    302   // Observer that logs network changes to the ChromeNetLog.
    303   class LoggingNetworkChangeObserver;
    304   scoped_ptr<LoggingNetworkChangeObserver> network_change_observer_;
    305 
    306   BooleanPrefMember system_enable_referrers_;
    307 
    308   BooleanPrefMember dns_client_enabled_;
    309 
    310   // Store HTTP Auth-related policies in this thread.
    311   std::string auth_schemes_;
    312   bool negotiate_disable_cname_lookup_;
    313   bool negotiate_enable_port_;
    314   std::string auth_server_whitelist_;
    315   std::string auth_delegate_whitelist_;
    316   std::string gssapi_library_name_;
    317   std::vector<GURL> spdyproxy_auth_origins_;
    318 
    319   // This is an instance of the default SSLConfigServiceManager for the current
    320   // platform and it gets SSL preferences from local_state object.
    321   scoped_ptr<SSLConfigServiceManager> ssl_config_service_manager_;
    322 
    323   // These member variables are initialized by a task posted to the IO thread,
    324   // which gets posted by calling certain member functions of IOThread.
    325   scoped_ptr<net::ProxyConfigService> system_proxy_config_service_;
    326 
    327   scoped_ptr<PrefProxyConfigTracker> pref_proxy_config_tracker_;
    328 
    329   scoped_refptr<net::URLRequestContextGetter>
    330       system_url_request_context_getter_;
    331 
    332   net::SdchManager* sdch_manager_;
    333 
    334   // True if SPDY is disabled by policy.
    335   bool is_spdy_disabled_by_policy_;
    336 
    337   base::WeakPtrFactory<IOThread> weak_factory_;
    338 
    339   DISALLOW_COPY_AND_ASSIGN(IOThread);
    340 };
    341 
    342 #endif  // CHROME_BROWSER_IO_THREAD_H_
    343