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