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 #include "net/socket/client_socket_pool.h"
6
7 #include <memory>
8 #include <string_view>
9 #include <utility>
10 #include <vector>
11
12 #include "base/check_op.h"
13 #include "base/feature_list.h"
14 #include "base/functional/bind.h"
15 #include "base/strings/strcat.h"
16 #include "net/base/features.h"
17 #include "net/base/host_port_pair.h"
18 #include "net/base/proxy_chain.h"
19 #include "net/base/session_usage.h"
20 #include "net/dns/public/secure_dns_policy.h"
21 #include "net/http/http_proxy_connect_job.h"
22 #include "net/log/net_log_event_type.h"
23 #include "net/log/net_log_with_source.h"
24 #include "net/socket/connect_job.h"
25 #include "net/socket/connect_job_factory.h"
26 #include "net/socket/socks_connect_job.h"
27 #include "net/socket/ssl_connect_job.h"
28 #include "net/socket/stream_socket.h"
29 #include "net/spdy/spdy_session.h"
30 #include "net/spdy/spdy_session_pool.h"
31 #include "net/ssl/ssl_config.h"
32 #include "url/gurl.h"
33 #include "url/scheme_host_port.h"
34 #include "url/url_constants.h"
35
36 namespace net {
37
38 namespace {
39
40 // The maximum duration, in seconds, to keep used idle persistent sockets alive.
41 int64_t g_used_idle_socket_timeout_s = 300; // 5 minutes
42
43 // Invoked by the transport socket pool after host resolution is complete
44 // to allow the connection to be aborted, if a matching SPDY session can
45 // be found. Returns OnHostResolutionCallbackResult::kMayBeDeletedAsync if such
46 // a session is found, as it will post a task that may delete the calling
47 // ConnectJob. Also returns kMayBeDeletedAsync if there may already be such
48 // a task posted.
OnHostResolution(SpdySessionPool * spdy_session_pool,const SpdySessionKey & spdy_session_key,bool is_for_websockets,const HostPortPair & host_port_pair,const std::vector<HostResolverEndpointResult> & endpoint_results,const std::set<std::string> & aliases)49 OnHostResolutionCallbackResult OnHostResolution(
50 SpdySessionPool* spdy_session_pool,
51 const SpdySessionKey& spdy_session_key,
52 bool is_for_websockets,
53 const HostPortPair& host_port_pair,
54 const std::vector<HostResolverEndpointResult>& endpoint_results,
55 const std::set<std::string>& aliases) {
56 DCHECK(host_port_pair == spdy_session_key.host_port_pair());
57
58 // It is OK to dereference spdy_session_pool, because the
59 // ClientSocketPoolManager will be destroyed in the same callback that
60 // destroys the SpdySessionPool.
61 return spdy_session_pool->OnHostResolutionComplete(
62 spdy_session_key, is_for_websockets, endpoint_results, aliases);
63 }
64
GetPrivacyModeGroupIdPrefix(PrivacyMode privacy_mode)65 std::string_view GetPrivacyModeGroupIdPrefix(PrivacyMode privacy_mode) {
66 switch (privacy_mode) {
67 case PrivacyMode::PRIVACY_MODE_DISABLED:
68 return "";
69 case PrivacyMode::PRIVACY_MODE_ENABLED:
70 return "pm/";
71 case PrivacyMode::PRIVACY_MODE_ENABLED_WITHOUT_CLIENT_CERTS:
72 return "pmwocc/";
73 case PrivacyMode::PRIVACY_MODE_ENABLED_PARTITIONED_STATE_ALLOWED:
74 return "pmpsa/";
75 }
76 }
77
GetSecureDnsPolicyGroupIdPrefix(SecureDnsPolicy secure_dns_policy)78 std::string_view GetSecureDnsPolicyGroupIdPrefix(
79 SecureDnsPolicy secure_dns_policy) {
80 switch (secure_dns_policy) {
81 case SecureDnsPolicy::kAllow:
82 return "";
83 case SecureDnsPolicy::kDisable:
84 return "dsd/";
85 case SecureDnsPolicy::kBootstrap:
86 return "dns_bootstrap/";
87 }
88 }
89
90 } // namespace
91
SocketParams(const std::vector<SSLConfig::CertAndStatus> & allowed_bad_certs)92 ClientSocketPool::SocketParams::SocketParams(
93 const std::vector<SSLConfig::CertAndStatus>& allowed_bad_certs)
94 : allowed_bad_certs_(allowed_bad_certs) {}
95
96 ClientSocketPool::SocketParams::~SocketParams() = default;
97
98 scoped_refptr<ClientSocketPool::SocketParams>
CreateForHttpForTesting()99 ClientSocketPool::SocketParams::CreateForHttpForTesting() {
100 return base::MakeRefCounted<SocketParams>(
101 /*allowed_bad_certs=*/std::vector<SSLConfig::CertAndStatus>());
102 }
103
GroupId()104 ClientSocketPool::GroupId::GroupId()
105 : privacy_mode_(PrivacyMode::PRIVACY_MODE_DISABLED) {}
106
GroupId(url::SchemeHostPort destination,PrivacyMode privacy_mode,NetworkAnonymizationKey network_anonymization_key,SecureDnsPolicy secure_dns_policy,bool disable_cert_network_fetches)107 ClientSocketPool::GroupId::GroupId(
108 url::SchemeHostPort destination,
109 PrivacyMode privacy_mode,
110 NetworkAnonymizationKey network_anonymization_key,
111 SecureDnsPolicy secure_dns_policy,
112 bool disable_cert_network_fetches)
113 : destination_(std::move(destination)),
114 privacy_mode_(privacy_mode),
115 network_anonymization_key_(
116 NetworkAnonymizationKey::IsPartitioningEnabled()
117 ? std::move(network_anonymization_key)
118 : NetworkAnonymizationKey()),
119 secure_dns_policy_(secure_dns_policy),
120 disable_cert_network_fetches_(disable_cert_network_fetches) {
121 DCHECK(destination_.IsValid());
122
123 // ClientSocketPool only expected to be used for HTTP/HTTPS/WS/WSS cases, and
124 // "ws"/"wss" schemes should be converted to "http"/"https" equivalent first.
125 DCHECK(destination_.scheme() == url::kHttpScheme ||
126 destination_.scheme() == url::kHttpsScheme);
127 }
128
129 ClientSocketPool::GroupId::GroupId(const GroupId& group_id) = default;
130
131 ClientSocketPool::GroupId::~GroupId() = default;
132
133 ClientSocketPool::GroupId& ClientSocketPool::GroupId::operator=(
134 const GroupId& group_id) = default;
135
136 ClientSocketPool::GroupId& ClientSocketPool::GroupId::operator=(
137 GroupId&& group_id) = default;
138
ToString() const139 std::string ClientSocketPool::GroupId::ToString() const {
140 return base::StrCat(
141 {disable_cert_network_fetches_ ? "disable_cert_network_fetches/" : "",
142 GetSecureDnsPolicyGroupIdPrefix(secure_dns_policy_),
143 GetPrivacyModeGroupIdPrefix(privacy_mode_), destination_.Serialize(),
144 NetworkAnonymizationKey::IsPartitioningEnabled()
145 ? base::StrCat(
146 {" <", network_anonymization_key_.ToDebugString(), ">"})
147 : ""});
148 }
149
150 ClientSocketPool::~ClientSocketPool() = default;
151
152 // static
used_idle_socket_timeout()153 base::TimeDelta ClientSocketPool::used_idle_socket_timeout() {
154 return base::Seconds(g_used_idle_socket_timeout_s);
155 }
156
157 // static
set_used_idle_socket_timeout(base::TimeDelta timeout)158 void ClientSocketPool::set_used_idle_socket_timeout(base::TimeDelta timeout) {
159 DCHECK_GT(timeout.InSeconds(), 0);
160 g_used_idle_socket_timeout_s = timeout.InSeconds();
161 }
162
ClientSocketPool(bool is_for_websockets,const CommonConnectJobParams * common_connect_job_params,std::unique_ptr<ConnectJobFactory> connect_job_factory)163 ClientSocketPool::ClientSocketPool(
164 bool is_for_websockets,
165 const CommonConnectJobParams* common_connect_job_params,
166 std::unique_ptr<ConnectJobFactory> connect_job_factory)
167 : is_for_websockets_(is_for_websockets),
168 common_connect_job_params_(common_connect_job_params),
169 connect_job_factory_(std::move(connect_job_factory)) {}
170
NetLogTcpClientSocketPoolRequestedSocket(const NetLogWithSource & net_log,const GroupId & group_id)171 void ClientSocketPool::NetLogTcpClientSocketPoolRequestedSocket(
172 const NetLogWithSource& net_log,
173 const GroupId& group_id) {
174 // TODO(eroman): Split out the host and port parameters.
175 net_log.AddEvent(NetLogEventType::TCP_CLIENT_SOCKET_POOL_REQUESTED_SOCKET,
176 [&] { return NetLogGroupIdParams(group_id); });
177 }
178
NetLogGroupIdParams(const GroupId & group_id)179 base::Value::Dict ClientSocketPool::NetLogGroupIdParams(
180 const GroupId& group_id) {
181 return base::Value::Dict().Set("group_id", group_id.ToString());
182 }
183
CreateConnectJob(GroupId group_id,scoped_refptr<SocketParams> socket_params,const ProxyChain & proxy_chain,const std::optional<NetworkTrafficAnnotationTag> & proxy_annotation_tag,RequestPriority request_priority,SocketTag socket_tag,ConnectJob::Delegate * delegate)184 std::unique_ptr<ConnectJob> ClientSocketPool::CreateConnectJob(
185 GroupId group_id,
186 scoped_refptr<SocketParams> socket_params,
187 const ProxyChain& proxy_chain,
188 const std::optional<NetworkTrafficAnnotationTag>& proxy_annotation_tag,
189 RequestPriority request_priority,
190 SocketTag socket_tag,
191 ConnectJob::Delegate* delegate) {
192 bool using_ssl = GURL::SchemeIsCryptographic(group_id.destination().scheme());
193
194 // If applicable, set up a callback to handle checking for H2 IP pooling
195 // opportunities. We don't perform H2 IP pooling to or through proxy servers,
196 // so ignore those cases.
197 OnHostResolutionCallback resolution_callback;
198 if (using_ssl && proxy_chain.is_direct()) {
199 resolution_callback = base::BindRepeating(
200 &OnHostResolution, common_connect_job_params_->spdy_session_pool,
201 // TODO(crbug.com/1206799): Pass along as SchemeHostPort.
202 SpdySessionKey(HostPortPair::FromSchemeHostPort(group_id.destination()),
203 group_id.privacy_mode(), proxy_chain,
204 SessionUsage::kDestination, socket_tag,
205 group_id.network_anonymization_key(),
206 group_id.secure_dns_policy(),
207 group_id.disable_cert_network_fetches()),
208 is_for_websockets_);
209 }
210
211 // Force a CONNECT tunnel for websockets. If this is false, the connect job
212 // may still use a tunnel for other reasons.
213 bool force_tunnel = is_for_websockets_;
214
215 // Only offer HTTP/1.1 for WebSockets. Although RFC 8441 defines WebSockets
216 // over HTTP/2, a single WSS/HTTPS origin may support HTTP over HTTP/2
217 // without supporting WebSockets over HTTP/2. Offering HTTP/2 for a fresh
218 // connection would break such origins.
219 //
220 // However, still offer HTTP/1.1 rather than skipping ALPN entirely. While
221 // this will not change the application protocol (HTTP/1.1 is default), it
222 // provides hardening against cross-protocol attacks and allows for the False
223 // Start (RFC 7918) optimization.
224 ConnectJobFactory::AlpnMode alpn_mode =
225 is_for_websockets_ ? ConnectJobFactory::AlpnMode::kHttp11Only
226 : ConnectJobFactory::AlpnMode::kHttpAll;
227
228 return connect_job_factory_->CreateConnectJob(
229 group_id.destination(), proxy_chain, proxy_annotation_tag,
230 socket_params->allowed_bad_certs(), alpn_mode, force_tunnel,
231 group_id.privacy_mode(), resolution_callback, request_priority,
232 socket_tag, group_id.network_anonymization_key(),
233 group_id.secure_dns_policy(), group_id.disable_cert_network_fetches(),
234 common_connect_job_params_, delegate);
235 }
236
237 } // namespace net
238