• 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 ProxyServer;
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 // Specifies the maximum concurrent streams server could send (via push).
83 const uint32_t kSpdyMaxConcurrentPushedStreams = 1000;
84 
85 // Self-contained structure with all the simple configuration options
86 // supported by the HttpNetworkSession.
87 struct NET_EXPORT HttpNetworkSessionParams {
88   HttpNetworkSessionParams();
89   HttpNetworkSessionParams(const HttpNetworkSessionParams& other);
90   ~HttpNetworkSessionParams();
91 
92   bool enable_server_push_cancellation = false;
93   HostMappingRules host_mapping_rules;
94   bool ignore_certificate_errors = false;
95   uint16_t testing_fixed_http_port = 0;
96   uint16_t testing_fixed_https_port = 0;
97   bool enable_user_alternate_protocol_ports = false;
98 
99   // Use SPDY ping frames to test for connection health after idle.
100   bool enable_spdy_ping_based_connection_checking = true;
101   bool enable_http2 = true;
102   size_t spdy_session_max_recv_window_size;
103   // Maximum number of capped frames that can be queued at any time.
104   int spdy_session_max_queued_capped_frames;
105   // Whether SPDY pools should mark sessions as going away upon relevant network
106   // changes (instead of closing them). Default value is OS specific.
107   // For OSs that terminate TCP connections upon relevant network changes,
108   // attempt to preserve active streams by marking all sessions as going
109   // away, rather than explicitly closing them. Streams may still fail due
110   // to a generated TCP reset.
111 #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_WIN) || BUILDFLAG(IS_IOS)
112   bool spdy_go_away_on_ip_change = true;
113 #else
114   bool spdy_go_away_on_ip_change = false;
115 #endif
116   // HTTP/2 connection settings.
117   // Unknown settings will still be sent to the server.
118   // Might contain unknown setting identifiers from a predefined set that
119   // servers are supposed to ignore, see
120   // https://tools.ietf.org/html/draft-bishop-httpbis-grease-00.
121   // The same setting will be sent on every connection to prevent the retry
122   // logic from hiding broken servers.
123   spdy::SettingsMap http2_settings;
124   // If true, a setting parameter with reserved identifier will be sent in every
125   // initial SETTINGS frame, see
126   // https://tools.ietf.org/html/draft-bishop-httpbis-grease-00.
127   // The setting identifier and value will be drawn independently for each
128   // connection to prevent tracking of the client.
129   bool enable_http2_settings_grease = false;
130   // If set, an HTTP/2 frame with a reserved frame type will be sent after
131   // every HTTP/2 SETTINGS frame and before every HTTP/2 DATA frame.
132   // https://tools.ietf.org/html/draft-bishop-httpbis-grease-00.
133   // The same frame will be sent out on all connections to prevent the retry
134   // logic from hiding broken servers.
135   absl::optional<SpdySessionPool::GreasedHttp2Frame> greased_http2_frame;
136   // If set, the HEADERS frame carrying a request without body will not have
137   // the END_STREAM flag set.  The stream will be closed by a subsequent empty
138   // DATA frame with END_STREAM.  Does not affect bidirectional or proxy
139   // streams.
140   // If unset, the HEADERS frame will have the END_STREAM flag set on.
141   // This is useful in conjunction with |greased_http2_frame| so that a frame
142   // of reserved type can be sent out even on requests without a body.
143   bool http2_end_stream_with_data_frame = false;
144   // Source of time for SPDY connections.
145   SpdySessionPool::TimeFunc time_func;
146   // Whether to enable HTTP/2 Alt-Svc entries.
147   bool enable_http2_alternative_service = false;
148 
149   // Enables 0-RTT support.
150   bool enable_early_data;
151 
152   // Enables QUIC support.
153   bool enable_quic = true;
154 
155   // If true, HTTPS URLs can be sent to QUIC proxies.
156   bool enable_quic_proxies_for_https_urls = false;
157 
158   // If non-empty, QUIC will only be spoken to hosts in this list.
159   base::flat_set<std::string> quic_host_allowlist;
160 
161   // If true, idle sockets won't be closed when memory pressure happens.
162   bool disable_idle_sockets_close_on_memory_pressure = false;
163 
164   bool key_auth_cache_server_entries_by_network_anonymization_key = false;
165 
166   // If true, enable sending PRIORITY_UPDATE frames until SETTINGS frame
167   // arrives.  After SETTINGS frame arrives, do not send PRIORITY_UPDATE
168   // frames any longer if SETTINGS_DEPRECATE_HTTP2_PRIORITIES is missing or
169   // has zero 0, but continue and also stop sending HTTP/2-style priority
170   // information in HEADERS frames and PRIORITY frames if it has value 1.
171   bool enable_priority_update = false;
172 
173   // If true, objects used by a HttpNetworkTransaction are asked not to perform
174   // disruptive work after there has been an IP address change (which usually
175   // means that the "default network" has possibly changed).
176   // This is currently used by HttpNetworkSessions that are bound to a specific
177   // network: for these, the underlying network does never change, even if the
178   // default network does (hence underlying objects should not drop their
179   // state).
180   bool ignore_ip_address_changes = false;
181 
182   // Whether to use the ALPN information in the DNS HTTPS record.
183   bool use_dns_https_svcb_alpn = false;
184 };
185 
186   // Structure with pointers to the dependencies of the HttpNetworkSession.
187   // These objects must all outlive the HttpNetworkSession.
188 struct NET_EXPORT HttpNetworkSessionContext {
189   HttpNetworkSessionContext();
190   HttpNetworkSessionContext(const HttpNetworkSessionContext& other);
191   ~HttpNetworkSessionContext();
192 
193   raw_ptr<ClientSocketFactory> client_socket_factory;
194   raw_ptr<HostResolver> host_resolver;
195   raw_ptr<CertVerifier> cert_verifier;
196   raw_ptr<TransportSecurityState> transport_security_state;
197   raw_ptr<CTPolicyEnforcer> ct_policy_enforcer;
198   raw_ptr<SCTAuditingDelegate> sct_auditing_delegate;
199   raw_ptr<ProxyResolutionService> proxy_resolution_service;
200   raw_ptr<ProxyDelegate> proxy_delegate;
201   raw_ptr<const HttpUserAgentSettings> http_user_agent_settings;
202   raw_ptr<SSLConfigService> ssl_config_service;
203   raw_ptr<HttpAuthHandlerFactory> http_auth_handler_factory;
204   raw_ptr<HttpServerProperties> http_server_properties;
205   raw_ptr<NetLog> net_log;
206   raw_ptr<SocketPerformanceWatcherFactory> socket_performance_watcher_factory;
207   raw_ptr<NetworkQualityEstimator> network_quality_estimator;
208   raw_ptr<QuicContext> quic_context;
209 #if BUILDFLAG(ENABLE_REPORTING)
210   raw_ptr<ReportingService> reporting_service;
211   raw_ptr<NetworkErrorLoggingService> network_error_logging_service;
212 #endif
213 
214     // Optional factory to use for creating QuicCryptoClientStreams.
215   raw_ptr<QuicCryptoClientStreamFactory> quic_crypto_client_stream_factory;
216 };
217 
218 // This class holds session objects used by HttpNetworkTransaction objects.
219 class NET_EXPORT HttpNetworkSession {
220  public:
221   enum SocketPoolType {
222     NORMAL_SOCKET_POOL,
223     WEBSOCKET_SOCKET_POOL,
224     NUM_SOCKET_POOL_TYPES
225   };
226 
227   HttpNetworkSession(const HttpNetworkSessionParams& params,
228                      const HttpNetworkSessionContext& context);
229   ~HttpNetworkSession();
230 
http_auth_cache()231   HttpAuthCache* http_auth_cache() { return &http_auth_cache_; }
ssl_client_context()232   SSLClientContext* ssl_client_context() { return &ssl_client_context_; }
233 
234   void StartResponseDrainer(std::unique_ptr<HttpResponseBodyDrainer> drainer);
235 
236   // Removes the drainer from the session.
237   void RemoveResponseDrainer(HttpResponseBodyDrainer* drainer);
238 
239   // Returns the socket pool of the given type for use with the specified
240   // ProxyServer. Use ProxyServer::Direct() to get the pool for use with direct
241   // connections.
242   ClientSocketPool* GetSocketPool(SocketPoolType pool_type,
243                                   const ProxyServer& proxy_server);
244 
cert_verifier()245   CertVerifier* cert_verifier() { return cert_verifier_; }
proxy_resolution_service()246   ProxyResolutionService* proxy_resolution_service() {
247     return proxy_resolution_service_;
248   }
ssl_config_service()249   SSLConfigService* ssl_config_service() { return ssl_config_service_; }
websocket_endpoint_lock_manager()250   WebSocketEndpointLockManager* websocket_endpoint_lock_manager() {
251     return &websocket_endpoint_lock_manager_;
252   }
spdy_session_pool()253   SpdySessionPool* spdy_session_pool() { return &spdy_session_pool_; }
quic_stream_factory()254   QuicStreamFactory* quic_stream_factory() { return &quic_stream_factory_; }
http_auth_handler_factory()255   HttpAuthHandlerFactory* http_auth_handler_factory() {
256     return http_auth_handler_factory_;
257   }
http_server_properties()258   HttpServerProperties* http_server_properties() {
259     return http_server_properties_;
260   }
http_stream_factory()261   HttpStreamFactory* http_stream_factory() {
262     return http_stream_factory_.get();
263   }
net_log()264   NetLog* net_log() {
265     return net_log_;
266   }
host_resolver()267   HostResolver* host_resolver() { return host_resolver_; }
268 #if BUILDFLAG(ENABLE_REPORTING)
reporting_service()269   ReportingService* reporting_service() const { return reporting_service_; }
network_error_logging_service()270   NetworkErrorLoggingService* network_error_logging_service() const {
271     return network_error_logging_service_;
272   }
273 #endif
274 
275   // Creates a Value summary of the state of the socket pools.
276   base::Value SocketPoolInfoToValue() const;
277 
278   // Creates a Value summary of the state of the SPDY sessions.
279   std::unique_ptr<base::Value> SpdySessionPoolInfoToValue() const;
280 
281   // Creates a Value summary of the state of the QUIC sessions and
282   // configuration.
283   base::Value QuicInfoToValue() const;
284 
285   void CloseAllConnections(int net_error, const char* net_log_reason_utf8);
286   void CloseIdleConnections(const char* net_log_reason_utf8);
287 
288   // Returns the original Params used to construct this session.
params()289   const HttpNetworkSessionParams& params() const { return params_; }
290   // Returns the original Context used to construct this session.
context()291   const HttpNetworkSessionContext& context() const { return context_; }
292 
293   void SetServerPushDelegate(std::unique_ptr<ServerPushDelegate> push_delegate);
294 
295   // Returns protocols to be used with ALPN.
GetAlpnProtos()296   const NextProtoVector& GetAlpnProtos() const { return next_protos_; }
297 
298   // Returns ALPS data to be sent to server for each NextProto.
299   // Data might be empty.
GetApplicationSettings()300   const SSLConfig::ApplicationSettings& GetApplicationSettings() const {
301     return application_settings_;
302   }
303 
304   // Evaluates if QUIC is enabled for new streams.
305   bool IsQuicEnabled() const;
306 
307   // Disable QUIC for new streams.
308   void DisableQuic();
309 
310   // Clear the SSL session cache.
311   void ClearSSLSessionCache();
312 
313   // Returns a CommonConnectJobParams that references the NetworkSession's
314   // components. If |for_websockets| is true, the Params'
315   // |websocket_endpoint_lock_manager| field will be populated. Otherwise, it
316   // will be nullptr.
317   CommonConnectJobParams CreateCommonConnectJobParams(
318       bool for_websockets = false);
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   std::unique_ptr<ServerPushDelegate> push_delegate_;
349   QuicStreamFactory quic_stream_factory_;
350   SpdySessionPool spdy_session_pool_;
351   std::unique_ptr<HttpStreamFactory> http_stream_factory_;
352   std::set<std::unique_ptr<HttpResponseBodyDrainer>, base::UniquePtrComparator>
353       response_drainers_;
354   NextProtoVector next_protos_;
355   SSLConfig::ApplicationSettings application_settings_;
356 
357   HttpNetworkSessionParams params_;
358   HttpNetworkSessionContext context_;
359 
360   std::unique_ptr<base::MemoryPressureListener> memory_pressure_listener_;
361 
362   THREAD_CHECKER(thread_checker_);
363 };
364 
365 }  // namespace net
366 
367 #endif  // NET_HTTP_HTTP_NETWORK_SESSION_H_
368