• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 The Chromium Authors
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 NET_HTTP_HTTP_NETWORK_SESSION_H_
6 #define NET_HTTP_HTTP_NETWORK_SESSION_H_
7 
8 #include <stddef.h>
9 #include <stdint.h>
10 
11 #include <map>
12 #include <memory>
13 #include <set>
14 #include <string>
15 #include <unordered_set>
16 #include <vector>
17 
18 #include "base/containers/flat_set.h"
19 #include "base/containers/unique_ptr_adapters.h"
20 #include "base/functional/bind.h"
21 #include "base/memory/memory_pressure_monitor.h"
22 #include "base/memory/raw_ptr.h"
23 #include "base/memory/weak_ptr.h"
24 #include "base/threading/thread_checker.h"
25 #include "base/values.h"
26 #include "build/buildflag.h"
27 #include "net/base/host_mapping_rules.h"
28 #include "net/base/host_port_pair.h"
29 #include "net/base/net_export.h"
30 #include "net/http/http_auth_cache.h"
31 #include "net/http/http_stream_factory.h"
32 #include "net/net_buildflags.h"
33 #include "net/quic/quic_stream_factory.h"
34 #include "net/socket/connect_job.h"
35 #include "net/socket/next_proto.h"
36 #include "net/socket/websocket_endpoint_lock_manager.h"
37 #include "net/spdy/spdy_session_pool.h"
38 #include "net/ssl/ssl_client_session_cache.h"
39 #include "net/third_party/quiche/src/quiche/spdy/core/spdy_protocol.h"
40 #include "third_party/abseil-cpp/absl/types/optional.h"
41 
42 namespace base {
43 class Value;
44 }
45 
46 namespace net {
47 
48 class CTPolicyEnforcer;
49 class CertVerifier;
50 class ClientSocketFactory;
51 class ClientSocketPool;
52 class ClientSocketPoolManager;
53 class HostResolver;
54 class HttpAuthHandlerFactory;
55 class HttpNetworkSessionPeer;
56 class HttpResponseBodyDrainer;
57 class HttpServerProperties;
58 class HttpUserAgentSettings;
59 class NetLog;
60 #if BUILDFLAG(ENABLE_REPORTING)
61 class NetworkErrorLoggingService;
62 #endif
63 class NetworkQualityEstimator;
64 class ProxyDelegate;
65 class ProxyResolutionService;
66 class ProxyChain;
67 class QuicCryptoClientStreamFactory;
68 #if BUILDFLAG(ENABLE_REPORTING)
69 class ReportingService;
70 #endif
71 class SCTAuditingDelegate;
72 class SocketPerformanceWatcherFactory;
73 class SSLConfigService;
74 class TransportSecurityState;
75 
76 // Specifies the maximum HPACK dynamic table size the server is allowed to set.
77 const uint32_t kSpdyMaxHeaderTableSize = 64 * 1024;
78 
79 // The maximum size of header list that the server is allowed to send.
80 const uint32_t kSpdyMaxHeaderListSize = 256 * 1024;
81 
82 // Self-contained structure with all the simple configuration options
83 // supported by the HttpNetworkSession.
84 struct NET_EXPORT HttpNetworkSessionParams {
85   HttpNetworkSessionParams();
86   HttpNetworkSessionParams(const HttpNetworkSessionParams& other);
87   ~HttpNetworkSessionParams();
88 
89   HostMappingRules host_mapping_rules;
90   bool ignore_certificate_errors = false;
91   uint16_t testing_fixed_http_port = 0;
92   uint16_t testing_fixed_https_port = 0;
93   bool enable_user_alternate_protocol_ports = false;
94 
95   // Use SPDY ping frames to test for connection health after idle.
96   bool enable_spdy_ping_based_connection_checking = true;
97   bool enable_http2 = true;
98   size_t spdy_session_max_recv_window_size;
99   // Maximum number of capped frames that can be queued at any time.
100   int spdy_session_max_queued_capped_frames;
101   // Whether SPDY pools should mark sessions as going away upon relevant network
102   // changes (instead of closing them). Default value is OS specific.
103   // For OSs that terminate TCP connections upon relevant network changes,
104   // attempt to preserve active streams by marking all sessions as going
105   // away, rather than explicitly closing them. Streams may still fail due
106   // to a generated TCP reset.
107 #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_WIN) || BUILDFLAG(IS_IOS)
108   bool spdy_go_away_on_ip_change = true;
109 #else
110   bool spdy_go_away_on_ip_change = false;
111 #endif
112   // HTTP/2 connection settings.
113   // Unknown settings will still be sent to the server.
114   // Might contain unknown setting identifiers from a predefined set that
115   // servers are supposed to ignore, see
116   // https://tools.ietf.org/html/draft-bishop-httpbis-grease-00.
117   // The same setting will be sent on every connection to prevent the retry
118   // logic from hiding broken servers.
119   spdy::SettingsMap http2_settings;
120   // If true, a setting parameter with reserved identifier will be sent in every
121   // initial SETTINGS frame, see
122   // https://tools.ietf.org/html/draft-bishop-httpbis-grease-00.
123   // The setting identifier and value will be drawn independently for each
124   // connection to prevent tracking of the client.
125   bool enable_http2_settings_grease = false;
126   // If set, an HTTP/2 frame with a reserved frame type will be sent after
127   // every HTTP/2 SETTINGS frame and before every HTTP/2 DATA frame.
128   // https://tools.ietf.org/html/draft-bishop-httpbis-grease-00.
129   // The same frame will be sent out on all connections to prevent the retry
130   // logic from hiding broken servers.
131   absl::optional<SpdySessionPool::GreasedHttp2Frame> greased_http2_frame;
132   // If set, the HEADERS frame carrying a request without body will not have
133   // the END_STREAM flag set.  The stream will be closed by a subsequent empty
134   // DATA frame with END_STREAM.  Does not affect bidirectional or proxy
135   // streams.
136   // If unset, the HEADERS frame will have the END_STREAM flag set on.
137   // This is useful in conjunction with |greased_http2_frame| so that a frame
138   // of reserved type can be sent out even on requests without a body.
139   bool http2_end_stream_with_data_frame = false;
140   // Source of time for SPDY connections.
141   SpdySessionPool::TimeFunc time_func;
142   // Whether to enable HTTP/2 Alt-Svc entries.
143   bool enable_http2_alternative_service = false;
144 
145   // Enables 0-RTT support.
146   bool enable_early_data;
147 
148   // Enables QUIC support.
149   bool enable_quic = true;
150 
151   // If true, HTTPS URLs can be sent to QUIC proxies.
152   bool enable_quic_proxies_for_https_urls = false;
153 
154   // If non-empty, QUIC will only be spoken to hosts in this list.
155   base::flat_set<std::string> quic_host_allowlist;
156 
157   // If true, idle sockets won't be closed when memory pressure happens.
158   bool disable_idle_sockets_close_on_memory_pressure = false;
159 
160   bool key_auth_cache_server_entries_by_network_anonymization_key = false;
161 
162   // If true, enable sending PRIORITY_UPDATE frames until SETTINGS frame
163   // arrives.  After SETTINGS frame arrives, do not send PRIORITY_UPDATE
164   // frames any longer if SETTINGS_DEPRECATE_HTTP2_PRIORITIES is missing or
165   // has zero 0, but continue and also stop sending HTTP/2-style priority
166   // information in HEADERS frames and PRIORITY frames if it has value 1.
167   bool enable_priority_update = false;
168 
169   // If true, objects used by a HttpNetworkTransaction are asked not to perform
170   // disruptive work after there has been an IP address change (which usually
171   // means that the "default network" has possibly changed).
172   // This is currently used by HttpNetworkSessions that are bound to a specific
173   // network: for these, the underlying network does never change, even if the
174   // default network does (hence underlying objects should not drop their
175   // state).
176   bool ignore_ip_address_changes = false;
177 
178   // Whether to use the ALPN information in the DNS HTTPS record.
179   bool use_dns_https_svcb_alpn = false;
180 };
181 
182   // Structure with pointers to the dependencies of the HttpNetworkSession.
183   // These objects must all outlive the HttpNetworkSession.
184 struct NET_EXPORT HttpNetworkSessionContext {
185   HttpNetworkSessionContext();
186   HttpNetworkSessionContext(const HttpNetworkSessionContext& other);
187   ~HttpNetworkSessionContext();
188 
189   raw_ptr<ClientSocketFactory> client_socket_factory;
190   raw_ptr<HostResolver> host_resolver;
191   raw_ptr<CertVerifier> cert_verifier;
192   raw_ptr<TransportSecurityState> transport_security_state;
193   raw_ptr<CTPolicyEnforcer> ct_policy_enforcer;
194   raw_ptr<SCTAuditingDelegate> sct_auditing_delegate;
195   raw_ptr<ProxyResolutionService, DanglingUntriaged> proxy_resolution_service;
196   raw_ptr<ProxyDelegate> proxy_delegate;
197   raw_ptr<const HttpUserAgentSettings> http_user_agent_settings;
198   raw_ptr<SSLConfigService> ssl_config_service;
199   raw_ptr<HttpAuthHandlerFactory> http_auth_handler_factory;
200   raw_ptr<HttpServerProperties> http_server_properties;
201   raw_ptr<NetLog> net_log;
202   raw_ptr<SocketPerformanceWatcherFactory> socket_performance_watcher_factory;
203   raw_ptr<NetworkQualityEstimator> network_quality_estimator;
204   raw_ptr<QuicContext> quic_context;
205 #if BUILDFLAG(ENABLE_REPORTING)
206   raw_ptr<ReportingService> reporting_service;
207   raw_ptr<NetworkErrorLoggingService> network_error_logging_service;
208 #endif
209 
210     // Optional factory to use for creating QuicCryptoClientStreams.
211   raw_ptr<QuicCryptoClientStreamFactory> quic_crypto_client_stream_factory;
212 };
213 
214 // This class holds session objects used by HttpNetworkTransaction objects.
215 class NET_EXPORT HttpNetworkSession {
216  public:
217   enum SocketPoolType {
218     NORMAL_SOCKET_POOL,
219     WEBSOCKET_SOCKET_POOL,
220     NUM_SOCKET_POOL_TYPES
221   };
222 
223   HttpNetworkSession(const HttpNetworkSessionParams& params,
224                      const HttpNetworkSessionContext& context);
225   ~HttpNetworkSession();
226 
http_auth_cache()227   HttpAuthCache* http_auth_cache() { return &http_auth_cache_; }
ssl_client_context()228   SSLClientContext* ssl_client_context() { return &ssl_client_context_; }
229 
230   void StartResponseDrainer(std::unique_ptr<HttpResponseBodyDrainer> drainer);
231 
232   // Removes the drainer from the session.
233   void RemoveResponseDrainer(HttpResponseBodyDrainer* drainer);
234 
235   // Returns the socket pool of the given type for use with the specified
236   // ProxyChain. Use ProxyChain::Direct() to get the pool for use with direct
237   // connections.
238   ClientSocketPool* GetSocketPool(SocketPoolType pool_type,
239                                   const ProxyChain& proxy_chain);
240 
cert_verifier()241   CertVerifier* cert_verifier() { return cert_verifier_; }
proxy_resolution_service()242   ProxyResolutionService* proxy_resolution_service() {
243     return proxy_resolution_service_;
244   }
ssl_config_service()245   SSLConfigService* ssl_config_service() { return ssl_config_service_; }
websocket_endpoint_lock_manager()246   WebSocketEndpointLockManager* websocket_endpoint_lock_manager() {
247     return &websocket_endpoint_lock_manager_;
248   }
spdy_session_pool()249   SpdySessionPool* spdy_session_pool() { return &spdy_session_pool_; }
quic_stream_factory()250   QuicStreamFactory* quic_stream_factory() { return &quic_stream_factory_; }
http_auth_handler_factory()251   HttpAuthHandlerFactory* http_auth_handler_factory() {
252     return http_auth_handler_factory_;
253   }
http_server_properties()254   HttpServerProperties* http_server_properties() {
255     return http_server_properties_;
256   }
http_stream_factory()257   HttpStreamFactory* http_stream_factory() {
258     return http_stream_factory_.get();
259   }
net_log()260   NetLog* net_log() {
261     return net_log_;
262   }
host_resolver()263   HostResolver* host_resolver() { return host_resolver_; }
264 #if BUILDFLAG(ENABLE_REPORTING)
reporting_service()265   ReportingService* reporting_service() const { return reporting_service_; }
network_error_logging_service()266   NetworkErrorLoggingService* network_error_logging_service() const {
267     return network_error_logging_service_;
268   }
269 #endif
270 
271   // Creates a Value summary of the state of the socket pools.
272   base::Value SocketPoolInfoToValue() const;
273 
274   // Creates a Value summary of the state of the SPDY sessions.
275   std::unique_ptr<base::Value> SpdySessionPoolInfoToValue() const;
276 
277   // Creates a Value summary of the state of the QUIC sessions and
278   // configuration.
279   base::Value QuicInfoToValue() const;
280 
281   void CloseAllConnections(int net_error, const char* net_log_reason_utf8);
282   void CloseIdleConnections(const char* net_log_reason_utf8);
283 
284   // Returns the original Params used to construct this session.
params()285   const HttpNetworkSessionParams& params() const { return params_; }
286   // Returns the original Context used to construct this session.
context()287   const HttpNetworkSessionContext& context() const { return context_; }
288 
289   // Returns protocols to be used with ALPN.
GetAlpnProtos()290   const NextProtoVector& GetAlpnProtos() const { return next_protos_; }
291 
292   // Returns ALPS data to be sent to server for each NextProto.
293   // Data might be empty.
GetApplicationSettings()294   const SSLConfig::ApplicationSettings& GetApplicationSettings() const {
295     return application_settings_;
296   }
297 
298   // Evaluates if QUIC is enabled for new streams.
299   bool IsQuicEnabled() const;
300 
301   // Disable QUIC for new streams.
302   void DisableQuic();
303 
304   // Ignores certificate errors on new connection attempts.
305   void IgnoreCertificateErrorsForTesting();
306 
307   // Clear the SSL session cache.
308   void ClearSSLSessionCache();
309 
310   // Returns a CommonConnectJobParams that references the NetworkSession's
311   // components. If |for_websockets| is true, the Params'
312   // |websocket_endpoint_lock_manager| field will be populated. Otherwise, it
313   // will be nullptr.
314   CommonConnectJobParams CreateCommonConnectJobParams(
315       bool for_websockets = false);
316 
317  private:
318   friend class HttpNetworkSessionPeer;
319 
320   ClientSocketPoolManager* GetSocketPoolManager(SocketPoolType pool_type);
321 
322   // Flush sockets on low memory notifications callback.
323   void OnMemoryPressure(
324       base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level);
325 
326   const raw_ptr<NetLog> net_log_;
327   const raw_ptr<HttpServerProperties> http_server_properties_;
328   const raw_ptr<CertVerifier> cert_verifier_;
329   const raw_ptr<HttpAuthHandlerFactory> http_auth_handler_factory_;
330   const raw_ptr<HostResolver> host_resolver_;
331 
332 #if BUILDFLAG(ENABLE_REPORTING)
333   const raw_ptr<ReportingService> reporting_service_;
334   const raw_ptr<NetworkErrorLoggingService> network_error_logging_service_;
335 #endif
336   const raw_ptr<ProxyResolutionService, DanglingUntriaged>
337       proxy_resolution_service_;
338   const raw_ptr<SSLConfigService> ssl_config_service_;
339 
340   HttpAuthCache http_auth_cache_;
341   SSLClientSessionCache ssl_client_session_cache_;
342   SSLClientContext ssl_client_context_;
343   WebSocketEndpointLockManager websocket_endpoint_lock_manager_;
344   std::unique_ptr<ClientSocketPoolManager> normal_socket_pool_manager_;
345   std::unique_ptr<ClientSocketPoolManager> websocket_socket_pool_manager_;
346   QuicStreamFactory quic_stream_factory_;
347   SpdySessionPool spdy_session_pool_;
348   std::unique_ptr<HttpStreamFactory> http_stream_factory_;
349   std::set<std::unique_ptr<HttpResponseBodyDrainer>, base::UniquePtrComparator>
350       response_drainers_;
351   NextProtoVector next_protos_;
352   SSLConfig::ApplicationSettings application_settings_;
353 
354   HttpNetworkSessionParams params_;
355   HttpNetworkSessionContext context_;
356 
357   std::unique_ptr<base::MemoryPressureListener> memory_pressure_listener_;
358 
359   THREAD_CHECKER(thread_checker_);
360 };
361 
362 }  // namespace net
363 
364 #endif  // NET_HTTP_HTTP_NETWORK_SESSION_H_
365