• 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 <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/http2/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 HttpStreamPool;
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   std::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 non-empty, QUIC will only be spoken to hosts in this list.
152   base::flat_set<std::string> quic_host_allowlist;
153 
154   // If true, idle sockets won't be closed when memory pressure happens.
155   bool disable_idle_sockets_close_on_memory_pressure = false;
156 
157   bool key_auth_cache_server_entries_by_network_anonymization_key = false;
158 
159   // If true, enable sending PRIORITY_UPDATE frames until SETTINGS frame
160   // arrives.  After SETTINGS frame arrives, do not send PRIORITY_UPDATE
161   // frames any longer if SETTINGS_DEPRECATE_HTTP2_PRIORITIES is missing or
162   // has zero 0, but continue and also stop sending HTTP/2-style priority
163   // information in HEADERS frames and PRIORITY frames if it has value 1.
164   bool enable_priority_update = false;
165 
166   // If true, objects used by a HttpNetworkTransaction are asked not to perform
167   // disruptive work after there has been an IP address change (which usually
168   // means that the "default network" has possibly changed).
169   // This is currently used by HttpNetworkSessions that are bound to a specific
170   // network: for these, the underlying network does never change, even if the
171   // default network does (hence underlying objects should not drop their
172   // state).
173   bool ignore_ip_address_changes = false;
174 
175   // Whether to use the ALPN information in the DNS HTTPS record.
176   bool use_dns_https_svcb_alpn = false;
177 };
178 
179 // Structure with pointers to the dependencies of the HttpNetworkSession.
180 // These objects must all outlive the HttpNetworkSession.
181 struct NET_EXPORT HttpNetworkSessionContext {
182   HttpNetworkSessionContext();
183   HttpNetworkSessionContext(const HttpNetworkSessionContext& other);
184   ~HttpNetworkSessionContext();
185 
186   raw_ptr<ClientSocketFactory> client_socket_factory;
187   raw_ptr<HostResolver> host_resolver;
188   raw_ptr<CertVerifier> cert_verifier;
189   raw_ptr<TransportSecurityState> transport_security_state;
190   raw_ptr<SCTAuditingDelegate> sct_auditing_delegate;
191   raw_ptr<ProxyResolutionService> proxy_resolution_service;
192   raw_ptr<ProxyDelegate> proxy_delegate;
193   raw_ptr<const HttpUserAgentSettings> http_user_agent_settings;
194   raw_ptr<SSLConfigService> ssl_config_service;
195   raw_ptr<HttpAuthHandlerFactory> http_auth_handler_factory;
196   raw_ptr<HttpServerProperties> http_server_properties;
197   raw_ptr<NetLog> net_log;
198   raw_ptr<SocketPerformanceWatcherFactory> socket_performance_watcher_factory;
199   raw_ptr<NetworkQualityEstimator> network_quality_estimator;
200   raw_ptr<QuicContext> quic_context;
201 #if BUILDFLAG(ENABLE_REPORTING)
202   raw_ptr<ReportingService> reporting_service;
203   raw_ptr<NetworkErrorLoggingService> network_error_logging_service;
204 #endif
205 
206   // Optional factory to use for creating QuicCryptoClientStreams.
207   raw_ptr<QuicCryptoClientStreamFactory> quic_crypto_client_stream_factory;
208 };
209 
210 // This class holds session objects used by HttpNetworkTransaction objects.
211 class NET_EXPORT HttpNetworkSession {
212  public:
213   enum SocketPoolType {
214     NORMAL_SOCKET_POOL,
215     WEBSOCKET_SOCKET_POOL,
216     NUM_SOCKET_POOL_TYPES
217   };
218 
219   HttpNetworkSession(const HttpNetworkSessionParams& params,
220                      const HttpNetworkSessionContext& context);
221   ~HttpNetworkSession();
222 
http_auth_cache()223   HttpAuthCache* http_auth_cache() { return &http_auth_cache_; }
ssl_client_context()224   SSLClientContext* ssl_client_context() { return &ssl_client_context_; }
225 
226   void StartResponseDrainer(std::unique_ptr<HttpResponseBodyDrainer> drainer);
227 
228   // Removes the drainer from the session.
229   void RemoveResponseDrainer(HttpResponseBodyDrainer* drainer);
230 
231   // Returns the socket pool of the given type for use with the specified
232   // ProxyChain. Use ProxyChain::Direct() to get the pool for use with direct
233   // connections.
234   ClientSocketPool* GetSocketPool(SocketPoolType pool_type,
235                                   const ProxyChain& proxy_chain);
236 
cert_verifier()237   CertVerifier* cert_verifier() { return cert_verifier_; }
proxy_resolution_service()238   ProxyResolutionService* proxy_resolution_service() {
239     return proxy_resolution_service_;
240   }
ssl_config_service()241   SSLConfigService* ssl_config_service() { return ssl_config_service_; }
websocket_endpoint_lock_manager()242   WebSocketEndpointLockManager* websocket_endpoint_lock_manager() {
243     return &websocket_endpoint_lock_manager_;
244   }
spdy_session_pool()245   SpdySessionPool* spdy_session_pool() { return &spdy_session_pool_; }
quic_session_pool()246   QuicSessionPool* quic_session_pool() { return &quic_session_pool_; }
http_auth_handler_factory()247   HttpAuthHandlerFactory* http_auth_handler_factory() {
248     return http_auth_handler_factory_;
249   }
http_server_properties()250   HttpServerProperties* http_server_properties() {
251     return http_server_properties_;
252   }
http_stream_pool()253   HttpStreamPool* http_stream_pool() { return http_stream_pool_.get(); }
http_stream_factory()254   HttpStreamFactory* http_stream_factory() {
255     return http_stream_factory_.get();
256   }
net_log()257   NetLog* net_log() { return net_log_; }
host_resolver()258   HostResolver* host_resolver() { return host_resolver_; }
259 #if BUILDFLAG(ENABLE_REPORTING)
reporting_service()260   ReportingService* reporting_service() const { return reporting_service_; }
network_error_logging_service()261   NetworkErrorLoggingService* network_error_logging_service() const {
262     return network_error_logging_service_;
263   }
264 #endif
265 
266   // Creates a Value summary of the state of the socket pools.
267   base::Value SocketPoolInfoToValue() const;
268 
269   // Creates a Value summary of the state of the SPDY sessions.
270   std::unique_ptr<base::Value> SpdySessionPoolInfoToValue() const;
271 
272   // Creates a Value summary of the state of the QUIC sessions and
273   // configuration.
274   base::Value QuicInfoToValue() const;
275 
276   void CloseAllConnections(int net_error, const char* net_log_reason_utf8);
277   void CloseIdleConnections(const char* net_log_reason_utf8);
278 
279   // Returns the original Params used to construct this session.
params()280   const HttpNetworkSessionParams& params() const { return params_; }
281   // Returns the original Context used to construct this session.
context()282   const HttpNetworkSessionContext& context() const { return context_; }
283 
284   // Returns protocols to be used with ALPN.
GetAlpnProtos()285   const NextProtoVector& GetAlpnProtos() const { return next_protos_; }
286 
287   // Returns ALPS data to be sent to server for each NextProto.
288   // Data might be empty.
GetApplicationSettings()289   const SSLConfig::ApplicationSettings& GetApplicationSettings() const {
290     return application_settings_;
291   }
292 
293   // Evaluates if QUIC is enabled for new streams.
294   bool IsQuicEnabled() const;
295 
296   // Disable QUIC for new streams.
297   void DisableQuic();
298 
299   // Returns true when QUIC is forcibly used for `destination`.
300   bool ShouldForceQuic(const url::SchemeHostPort& destination,
301                        const ProxyInfo& proxy_info,
302                        bool is_websocket);
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   // Rewrite the port of `endpoint` when testing fixed port is specified.
318   void ApplyTestingFixedPort(url::SchemeHostPort& endpoint) const;
319 
320  private:
321   friend class HttpNetworkSessionPeer;
322 
323   ClientSocketPoolManager* GetSocketPoolManager(SocketPoolType pool_type);
324 
325   // Flush sockets on low memory notifications callback.
326   void OnMemoryPressure(
327       base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level);
328 
329   const raw_ptr<NetLog> net_log_;
330   const raw_ptr<HttpServerProperties> http_server_properties_;
331   const raw_ptr<CertVerifier> cert_verifier_;
332   const raw_ptr<HttpAuthHandlerFactory> http_auth_handler_factory_;
333   const raw_ptr<HostResolver> host_resolver_;
334 
335 #if BUILDFLAG(ENABLE_REPORTING)
336   const raw_ptr<ReportingService> reporting_service_;
337   const raw_ptr<NetworkErrorLoggingService> network_error_logging_service_;
338 #endif
339   const raw_ptr<ProxyResolutionService> proxy_resolution_service_;
340   const raw_ptr<SSLConfigService> ssl_config_service_;
341 
342   HttpAuthCache http_auth_cache_;
343   SSLClientSessionCache ssl_client_session_cache_;
344   SSLClientContext ssl_client_context_;
345   WebSocketEndpointLockManager websocket_endpoint_lock_manager_;
346   std::unique_ptr<ClientSocketPoolManager> normal_socket_pool_manager_;
347   std::unique_ptr<ClientSocketPoolManager> websocket_socket_pool_manager_;
348   QuicSessionPool quic_session_pool_;
349   // `http_stream_pool_` needs to outlive `spdy_session_pool_` because it owns
350   // SpdySessions, which own HttpStreamHandle and handles are owned by
351   // `http_stream_pool_`.
352   // `http_stream_pool_` needs to be destroyed before `quic_session_pool_`
353   // because an HttpStreamPool::QuicTask, which is owned by `http_stream_pool_`,
354   // may have a QuicSessionAttempt that must be destroyed before
355   // `quic_session_pool_`.
356   std::unique_ptr<HttpStreamPool> http_stream_pool_;
357   SpdySessionPool spdy_session_pool_;
358   std::unique_ptr<HttpStreamFactory> http_stream_factory_;
359   std::set<std::unique_ptr<HttpResponseBodyDrainer>, base::UniquePtrComparator>
360       response_drainers_;
361   NextProtoVector next_protos_;
362   SSLConfig::ApplicationSettings application_settings_;
363 
364   HttpNetworkSessionParams params_;
365   HttpNetworkSessionContext context_;
366 
367   std::unique_ptr<base::MemoryPressureListener> memory_pressure_listener_;
368 
369   THREAD_CHECKER(thread_checker_);
370 };
371 
372 }  // namespace net
373 
374 #endif  // NET_HTTP_HTTP_NETWORK_SESSION_H_
375