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/spdy/spdy_session_pool.h"
6
7 #include <set>
8 #include <utility>
9
10 #include "base/check_op.h"
11 #include "base/containers/contains.h"
12 #include "base/functional/bind.h"
13 #include "base/metrics/histogram_macros.h"
14 #include "base/ranges/algorithm.h"
15 #include "base/trace_event/base_tracing.h"
16 #include "base/task/single_thread_task_runner.h"
17 #include "base/values.h"
18 #include "build/build_config.h"
19 #include "net/base/ip_endpoint.h"
20 #include "net/base/trace_constants.h"
21 #include "net/base/tracing.h"
22 #include "net/dns/host_resolver.h"
23 #include "net/dns/public/host_resolver_source.h"
24 #include "net/http/http_network_session.h"
25 #include "net/http/http_server_properties.h"
26 #include "net/http/http_stream_request.h"
27 #include "net/log/net_log_event_type.h"
28 #include "net/log/net_log_source.h"
29 #include "net/log/net_log_with_source.h"
30 #include "net/socket/client_socket_handle.h"
31 #include "net/spdy/spdy_session.h"
32 #include "net/third_party/quiche/src/quiche/spdy/core/hpack/hpack_constants.h"
33 #include "net/third_party/quiche/src/quiche/spdy/core/hpack/hpack_static_table.h"
34
35 namespace net {
36
37 namespace {
38
39 enum SpdySessionGetTypes {
40 CREATED_NEW = 0,
41 FOUND_EXISTING = 1,
42 FOUND_EXISTING_FROM_IP_POOL = 2,
43 IMPORTED_FROM_SOCKET = 3,
44 SPDY_SESSION_GET_MAX = 4
45 };
46
47 } // namespace
48
49 SpdySessionPool::SpdySessionRequest::Delegate::Delegate() = default;
50 SpdySessionPool::SpdySessionRequest::Delegate::~Delegate() = default;
51
SpdySessionRequest(const SpdySessionKey & key,bool enable_ip_based_pooling,bool is_websocket,bool is_blocking_request_for_session,Delegate * delegate,SpdySessionPool * spdy_session_pool)52 SpdySessionPool::SpdySessionRequest::SpdySessionRequest(
53 const SpdySessionKey& key,
54 bool enable_ip_based_pooling,
55 bool is_websocket,
56 bool is_blocking_request_for_session,
57 Delegate* delegate,
58 SpdySessionPool* spdy_session_pool)
59 : key_(key),
60 enable_ip_based_pooling_(enable_ip_based_pooling),
61 is_websocket_(is_websocket),
62 is_blocking_request_for_session_(is_blocking_request_for_session),
63 delegate_(delegate),
64 spdy_session_pool_(spdy_session_pool) {}
65
~SpdySessionRequest()66 SpdySessionPool::SpdySessionRequest::~SpdySessionRequest() {
67 if (spdy_session_pool_)
68 spdy_session_pool_->RemoveRequestForSpdySession(this);
69 }
70
OnRemovedFromPool()71 void SpdySessionPool::SpdySessionRequest::OnRemovedFromPool() {
72 DCHECK(spdy_session_pool_);
73 spdy_session_pool_ = nullptr;
74 }
75
SpdySessionPool(HostResolver * resolver,SSLClientContext * ssl_client_context,HttpServerProperties * http_server_properties,TransportSecurityState * transport_security_state,const quic::ParsedQuicVersionVector & quic_supported_versions,bool enable_ping_based_connection_checking,bool is_http2_enabled,bool is_quic_enabled,size_t session_max_recv_window_size,int session_max_queued_capped_frames,const spdy::SettingsMap & initial_settings,bool enable_http2_settings_grease,const absl::optional<GreasedHttp2Frame> & greased_http2_frame,bool http2_end_stream_with_data_frame,bool enable_priority_update,bool go_away_on_ip_change,SpdySessionPool::TimeFunc time_func,NetworkQualityEstimator * network_quality_estimator,bool cleanup_sessions_on_ip_address_changed)76 SpdySessionPool::SpdySessionPool(
77 HostResolver* resolver,
78 SSLClientContext* ssl_client_context,
79 HttpServerProperties* http_server_properties,
80 TransportSecurityState* transport_security_state,
81 const quic::ParsedQuicVersionVector& quic_supported_versions,
82 bool enable_ping_based_connection_checking,
83 bool is_http2_enabled,
84 bool is_quic_enabled,
85 size_t session_max_recv_window_size,
86 int session_max_queued_capped_frames,
87 const spdy::SettingsMap& initial_settings,
88 bool enable_http2_settings_grease,
89 const absl::optional<GreasedHttp2Frame>& greased_http2_frame,
90 bool http2_end_stream_with_data_frame,
91 bool enable_priority_update,
92 bool go_away_on_ip_change,
93 SpdySessionPool::TimeFunc time_func,
94 NetworkQualityEstimator* network_quality_estimator,
95 bool cleanup_sessions_on_ip_address_changed)
96 : http_server_properties_(http_server_properties),
97 transport_security_state_(transport_security_state),
98 ssl_client_context_(ssl_client_context),
99 resolver_(resolver),
100 quic_supported_versions_(quic_supported_versions),
101 enable_ping_based_connection_checking_(
102 enable_ping_based_connection_checking),
103 is_http2_enabled_(is_http2_enabled),
104 is_quic_enabled_(is_quic_enabled),
105 session_max_recv_window_size_(session_max_recv_window_size),
106 session_max_queued_capped_frames_(session_max_queued_capped_frames),
107 initial_settings_(initial_settings),
108 enable_http2_settings_grease_(enable_http2_settings_grease),
109 greased_http2_frame_(greased_http2_frame),
110 http2_end_stream_with_data_frame_(http2_end_stream_with_data_frame),
111 enable_priority_update_(enable_priority_update),
112 go_away_on_ip_change_(go_away_on_ip_change),
113 time_func_(time_func),
114 network_quality_estimator_(network_quality_estimator),
115 cleanup_sessions_on_ip_address_changed_(
116 cleanup_sessions_on_ip_address_changed) {
117 if (cleanup_sessions_on_ip_address_changed_)
118 NetworkChangeNotifier::AddIPAddressObserver(this);
119 if (ssl_client_context_)
120 ssl_client_context_->AddObserver(this);
121 }
122
~SpdySessionPool()123 SpdySessionPool::~SpdySessionPool() {
124 #if DCHECK_IS_ON()
125 for (const auto& request_info : spdy_session_request_map_) {
126 // The should be no pending SpdySessionRequests on destruction, though there
127 // may be callbacks waiting to be invoked, since they use weak pointers and
128 // there's no API to unregister them.
129 DCHECK(request_info.second.request_set.empty());
130 }
131 #endif // DCHECK_IS_ON()
132
133 // TODO(bnc): CloseAllSessions() is also called in HttpNetworkSession
134 // destructor, one of the two calls should be removed.
135 CloseAllSessions();
136
137 while (!sessions_.empty()) {
138 // Destroy sessions to enforce that lifetime is scoped to SpdySessionPool.
139 // Write callbacks queued upon session drain are not invoked.
140 RemoveUnavailableSession((*sessions_.begin())->GetWeakPtr());
141 }
142
143 if (ssl_client_context_)
144 ssl_client_context_->RemoveObserver(this);
145 if (cleanup_sessions_on_ip_address_changed_)
146 NetworkChangeNotifier::RemoveIPAddressObserver(this);
147 }
148
CreateAvailableSessionFromSocketHandle(const SpdySessionKey & key,std::unique_ptr<ClientSocketHandle> client_socket_handle,const NetLogWithSource & net_log,base::WeakPtr<SpdySession> * session)149 int SpdySessionPool::CreateAvailableSessionFromSocketHandle(
150 const SpdySessionKey& key,
151 std::unique_ptr<ClientSocketHandle> client_socket_handle,
152 const NetLogWithSource& net_log,
153 base::WeakPtr<SpdySession>* session) {
154 TRACE_EVENT0(NetTracingCategory(),
155 "SpdySessionPool::CreateAvailableSessionFromSocketHandle");
156
157 std::unique_ptr<SpdySession> new_session =
158 CreateSession(key, net_log.net_log());
159 std::set<std::string> dns_aliases =
160 client_socket_handle->socket()->GetDnsAliases();
161
162 new_session->InitializeWithSocketHandle(std::move(client_socket_handle),
163 this);
164 *session = InsertSession(key, std::move(new_session), net_log,
165 std::move(dns_aliases));
166
167 if (!(*session)->HasAcceptableTransportSecurity()) {
168 (*session)->CloseSessionOnError(ERR_HTTP2_INADEQUATE_TRANSPORT_SECURITY,
169 "");
170 return ERR_HTTP2_INADEQUATE_TRANSPORT_SECURITY;
171 }
172
173 int rv = (*session)->ParseAlps();
174 if (rv != OK) {
175 DCHECK_NE(ERR_IO_PENDING, rv);
176 // ParseAlps() already closed the connection on error.
177 return rv;
178 }
179
180 return OK;
181 }
182
CreateAvailableSessionFromSocket(const SpdySessionKey & key,std::unique_ptr<StreamSocket> socket_stream,const LoadTimingInfo::ConnectTiming & connect_timing,const NetLogWithSource & net_log)183 base::WeakPtr<SpdySession> SpdySessionPool::CreateAvailableSessionFromSocket(
184 const SpdySessionKey& key,
185 std::unique_ptr<StreamSocket> socket_stream,
186 const LoadTimingInfo::ConnectTiming& connect_timing,
187 const NetLogWithSource& net_log) {
188 TRACE_EVENT0(NetTracingCategory(),
189 "SpdySessionPool::CreateAvailableSessionFromSocket");
190
191 std::unique_ptr<SpdySession> new_session =
192 CreateSession(key, net_log.net_log());
193 std::set<std::string> dns_aliases = socket_stream->GetDnsAliases();
194
195 new_session->InitializeWithSocket(std::move(socket_stream), connect_timing,
196 this);
197
198 return InsertSession(key, std::move(new_session), net_log,
199 std::move(dns_aliases));
200 }
201
FindAvailableSession(const SpdySessionKey & key,bool enable_ip_based_pooling,bool is_websocket,const NetLogWithSource & net_log)202 base::WeakPtr<SpdySession> SpdySessionPool::FindAvailableSession(
203 const SpdySessionKey& key,
204 bool enable_ip_based_pooling,
205 bool is_websocket,
206 const NetLogWithSource& net_log) {
207 auto it = LookupAvailableSessionByKey(key);
208 if (it == available_sessions_.end() ||
209 (is_websocket && !it->second->support_websocket())) {
210 return base::WeakPtr<SpdySession>();
211 }
212
213 if (key == it->second->spdy_session_key()) {
214 UMA_HISTOGRAM_ENUMERATION("Net.SpdySessionGet", FOUND_EXISTING,
215 SPDY_SESSION_GET_MAX);
216 net_log.AddEventReferencingSource(
217 NetLogEventType::HTTP2_SESSION_POOL_FOUND_EXISTING_SESSION,
218 it->second->net_log().source());
219 return it->second;
220 }
221
222 if (enable_ip_based_pooling) {
223 UMA_HISTOGRAM_ENUMERATION("Net.SpdySessionGet", FOUND_EXISTING_FROM_IP_POOL,
224 SPDY_SESSION_GET_MAX);
225 net_log.AddEventReferencingSource(
226 NetLogEventType::HTTP2_SESSION_POOL_FOUND_EXISTING_SESSION_FROM_IP_POOL,
227 it->second->net_log().source());
228 return it->second;
229 }
230
231 return base::WeakPtr<SpdySession>();
232 }
233
HasAvailableSession(const SpdySessionKey & key,bool is_websocket) const234 bool SpdySessionPool::HasAvailableSession(const SpdySessionKey& key,
235 bool is_websocket) const {
236 const auto it = available_sessions_.find(key);
237 return it != available_sessions_.end() &&
238 (!is_websocket || it->second->support_websocket());
239 }
240
RequestSession(const SpdySessionKey & key,bool enable_ip_based_pooling,bool is_websocket,const NetLogWithSource & net_log,base::RepeatingClosure on_blocking_request_destroyed_callback,SpdySessionRequest::Delegate * delegate,std::unique_ptr<SpdySessionRequest> * spdy_session_request,bool * is_blocking_request_for_session)241 base::WeakPtr<SpdySession> SpdySessionPool::RequestSession(
242 const SpdySessionKey& key,
243 bool enable_ip_based_pooling,
244 bool is_websocket,
245 const NetLogWithSource& net_log,
246 base::RepeatingClosure on_blocking_request_destroyed_callback,
247 SpdySessionRequest::Delegate* delegate,
248 std::unique_ptr<SpdySessionRequest>* spdy_session_request,
249 bool* is_blocking_request_for_session) {
250 DCHECK(delegate);
251
252 base::WeakPtr<SpdySession> spdy_session =
253 FindAvailableSession(key, enable_ip_based_pooling, is_websocket, net_log);
254 if (spdy_session) {
255 // This value doesn't really matter, but best to always populate it, for
256 // consistency.
257 *is_blocking_request_for_session = true;
258 return spdy_session;
259 }
260
261 RequestInfoForKey* request_info = &spdy_session_request_map_[key];
262 *is_blocking_request_for_session = !request_info->has_blocking_request;
263 *spdy_session_request = std::make_unique<SpdySessionRequest>(
264 key, enable_ip_based_pooling, is_websocket,
265 *is_blocking_request_for_session, delegate, this);
266 request_info->request_set.insert(spdy_session_request->get());
267
268 if (*is_blocking_request_for_session) {
269 request_info->has_blocking_request = true;
270 } else if (on_blocking_request_destroyed_callback) {
271 request_info->deferred_callbacks.push_back(
272 on_blocking_request_destroyed_callback);
273 }
274 return nullptr;
275 }
276
OnHostResolutionComplete(const SpdySessionKey & key,bool is_websocket,const std::vector<HostResolverEndpointResult> & endpoint_results,const std::set<std::string> & aliases)277 OnHostResolutionCallbackResult SpdySessionPool::OnHostResolutionComplete(
278 const SpdySessionKey& key,
279 bool is_websocket,
280 const std::vector<HostResolverEndpointResult>& endpoint_results,
281 const std::set<std::string>& aliases) {
282 // If there are no pending requests for that alias, nothing to do.
283 if (spdy_session_request_map_.find(key) == spdy_session_request_map_.end())
284 return OnHostResolutionCallbackResult::kContinue;
285
286 // Check if there's already a matching session. If so, there may already
287 // be a pending task to inform consumers of the alias. In this case, do
288 // nothing, but inform the caller to wait for such a task to run.
289 auto existing_session_it = LookupAvailableSessionByKey(key);
290 if (existing_session_it != available_sessions_.end()) {
291 if (is_websocket && !existing_session_it->second->support_websocket()) {
292 // We don't look for aliased sessions because it would not be possible to
293 // add them to the available_sessions_ map. See https://crbug.com/1220771.
294 return OnHostResolutionCallbackResult::kContinue;
295 }
296
297 return OnHostResolutionCallbackResult::kMayBeDeletedAsync;
298 }
299
300 // TODO(crbug.com/1264933): Consider dealing with the other endpoints
301 // with protocol metadata.
302 const auto ip_endpoints =
303 HostResolver::GetNonProtocolEndpoints(endpoint_results);
304 for (const auto& address : ip_endpoints) {
305 auto range = aliases_.equal_range(address);
306 for (auto alias_it = range.first; alias_it != range.second; ++alias_it) {
307 // We found a potential alias.
308 const SpdySessionKey& alias_key = alias_it->second;
309
310 auto available_session_it = LookupAvailableSessionByKey(alias_key);
311 // It shouldn't be in the aliases table if it doesn't exist!
312 DCHECK(available_session_it != available_sessions_.end());
313
314 SpdySessionKey::CompareForAliasingResult compare_result =
315 alias_key.CompareForAliasing(key);
316 // Keys must be aliasable.
317 if (!compare_result.is_potentially_aliasable)
318 continue;
319
320 if (is_websocket && !available_session_it->second->support_websocket())
321 continue;
322
323 // Make copy of WeakPtr as call to UnmapKey() will delete original.
324 const base::WeakPtr<SpdySession> available_session =
325 available_session_it->second;
326
327 // Need to verify that the server is authenticated to serve traffic for
328 // |host_port_proxy_pair| too.
329 if (!available_session->VerifyDomainAuthentication(
330 key.host_port_pair().host())) {
331 UMA_HISTOGRAM_ENUMERATION("Net.SpdyIPPoolDomainMatch", 0, 2);
332 continue;
333 }
334
335 UMA_HISTOGRAM_ENUMERATION("Net.SpdyIPPoolDomainMatch", 1, 2);
336
337 bool adding_pooled_alias = true;
338
339 // If socket tags differ, see if session's socket tag can be changed.
340 if (!compare_result.is_socket_tag_match) {
341 SpdySessionKey old_key = available_session->spdy_session_key();
342 SpdySessionKey new_key(old_key.host_port_pair(), old_key.proxy_server(),
343 old_key.privacy_mode(),
344 old_key.is_proxy_session(), key.socket_tag(),
345 old_key.network_anonymization_key(),
346 old_key.secure_dns_policy());
347
348 // If there is already a session with |new_key|, skip this one.
349 // It will be found in |aliases_| in a future iteration.
350 if (available_sessions_.find(new_key) != available_sessions_.end())
351 continue;
352
353 if (!available_session->ChangeSocketTag(key.socket_tag()))
354 continue;
355
356 DCHECK(available_session->spdy_session_key() == new_key);
357
358 // If this isn't a pooled alias, but the actual session that needs to
359 // have its socket tag change, there's no need to add an alias.
360 if (new_key == key)
361 adding_pooled_alias = false;
362
363 // Remap main session key.
364 std::set<std::string> main_session_old_dns_aliases =
365 GetDnsAliasesForSessionKey(old_key);
366 UnmapKey(old_key);
367 MapKeyToAvailableSession(new_key, available_session,
368 std::move(main_session_old_dns_aliases));
369
370 // Remap alias. From this point on |alias_it| is invalid, so no more
371 // iterations of the loop should be allowed.
372 aliases_.insert(AliasMap::value_type(alias_it->first, new_key));
373 aliases_.erase(alias_it);
374
375 // Remap pooled session keys.
376 const auto& pooled_aliases = available_session->pooled_aliases();
377 for (auto it = pooled_aliases.begin(); it != pooled_aliases.end();) {
378 // Ignore aliases this loop is inserting.
379 if (it->socket_tag() == key.socket_tag()) {
380 ++it;
381 continue;
382 }
383
384 std::set<std::string> pooled_alias_old_dns_aliases =
385 GetDnsAliasesForSessionKey(*it);
386 UnmapKey(*it);
387 SpdySessionKey new_pool_alias_key = SpdySessionKey(
388 it->host_port_pair(), it->proxy_server(), it->privacy_mode(),
389 it->is_proxy_session(), key.socket_tag(),
390 it->network_anonymization_key(), it->secure_dns_policy());
391 MapKeyToAvailableSession(new_pool_alias_key, available_session,
392 std::move(pooled_alias_old_dns_aliases));
393 auto old_it = it;
394 ++it;
395 available_session->RemovePooledAlias(*old_it);
396 available_session->AddPooledAlias(new_pool_alias_key);
397
398 // If this is desired key, no need to add an alias for the desired key
399 // at the end of this method.
400 if (new_pool_alias_key == key)
401 adding_pooled_alias = false;
402 }
403 }
404
405 if (adding_pooled_alias) {
406 // Add this session to the map so that we can find it next time.
407 MapKeyToAvailableSession(key, available_session, aliases);
408 available_session->AddPooledAlias(key);
409 }
410
411 // Post task to inform pending requests for session for |key| that a
412 // matching session is now available.
413 base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
414 FROM_HERE, base::BindOnce(&SpdySessionPool::UpdatePendingRequests,
415 weak_ptr_factory_.GetWeakPtr(), key));
416
417 // Inform the caller that the Callback may be deleted if the consumer is
418 // switched over to the newly aliased session. It's not guaranteed to be
419 // deleted, as the session may be closed, or taken by yet another pending
420 // request with a different SocketTag before the the request can try and
421 // use the session.
422 return OnHostResolutionCallbackResult::kMayBeDeletedAsync;
423 }
424 }
425 return OnHostResolutionCallbackResult::kContinue;
426 }
427
MakeSessionUnavailable(const base::WeakPtr<SpdySession> & available_session)428 void SpdySessionPool::MakeSessionUnavailable(
429 const base::WeakPtr<SpdySession>& available_session) {
430 UnmapKey(available_session->spdy_session_key());
431 RemoveAliases(available_session->spdy_session_key());
432 const std::set<SpdySessionKey>& aliases = available_session->pooled_aliases();
433 for (const auto& alias : aliases) {
434 UnmapKey(alias);
435 RemoveAliases(alias);
436 }
437 DCHECK(!IsSessionAvailable(available_session));
438 }
439
RemoveUnavailableSession(const base::WeakPtr<SpdySession> & unavailable_session)440 void SpdySessionPool::RemoveUnavailableSession(
441 const base::WeakPtr<SpdySession>& unavailable_session) {
442 DCHECK(!IsSessionAvailable(unavailable_session));
443
444 unavailable_session->net_log().AddEvent(
445 NetLogEventType::HTTP2_SESSION_POOL_REMOVE_SESSION);
446
447 auto it = sessions_.find(unavailable_session.get());
448 CHECK(it != sessions_.end());
449 std::unique_ptr<SpdySession> owned_session(*it);
450 sessions_.erase(it);
451 }
452
453 // Make a copy of |sessions_| in the Close* functions below to avoid
454 // reentrancy problems. Since arbitrary functions get called by close
455 // handlers, it doesn't suffice to simply increment the iterator
456 // before closing.
457
CloseCurrentSessions(Error error)458 void SpdySessionPool::CloseCurrentSessions(Error error) {
459 CloseCurrentSessionsHelper(error, "Closing current sessions.",
460 false /* idle_only */);
461 }
462
CloseCurrentIdleSessions(const std::string & description)463 void SpdySessionPool::CloseCurrentIdleSessions(const std::string& description) {
464 CloseCurrentSessionsHelper(ERR_ABORTED, description, true /* idle_only */);
465 }
466
CloseAllSessions()467 void SpdySessionPool::CloseAllSessions() {
468 auto is_draining = [](const SpdySession* s) { return s->IsDraining(); };
469 // Repeat until every SpdySession owned by |this| is draining.
470 while (!base::ranges::all_of(sessions_, is_draining)) {
471 CloseCurrentSessionsHelper(ERR_ABORTED, "Closing all sessions.",
472 false /* idle_only */);
473 }
474 }
475
MakeCurrentSessionsGoingAway(Error error)476 void SpdySessionPool::MakeCurrentSessionsGoingAway(Error error) {
477 WeakSessionList current_sessions = GetCurrentSessions();
478 for (base::WeakPtr<SpdySession>& session : current_sessions) {
479 if (!session) {
480 continue;
481 }
482
483 session->MakeUnavailable();
484 session->StartGoingAway(kLastStreamId, error);
485 session->MaybeFinishGoingAway();
486 DCHECK(!IsSessionAvailable(session));
487 }
488 }
489
SpdySessionPoolInfoToValue() const490 std::unique_ptr<base::Value> SpdySessionPool::SpdySessionPoolInfoToValue()
491 const {
492 base::Value::List list;
493
494 for (const auto& available_session : available_sessions_) {
495 // Only add the session if the key in the map matches the main
496 // host_port_proxy_pair (not an alias).
497 const SpdySessionKey& key = available_session.first;
498 const SpdySessionKey& session_key =
499 available_session.second->spdy_session_key();
500 if (key == session_key)
501 list.Append(available_session.second->GetInfoAsValue());
502 }
503 return std::make_unique<base::Value>(std::move(list));
504 }
505
OnIPAddressChanged()506 void SpdySessionPool::OnIPAddressChanged() {
507 DCHECK(cleanup_sessions_on_ip_address_changed_);
508 if (go_away_on_ip_change_) {
509 MakeCurrentSessionsGoingAway(ERR_NETWORK_CHANGED);
510 } else {
511 CloseCurrentSessions(ERR_NETWORK_CHANGED);
512 }
513 }
514
OnSSLConfigChanged(SSLClientContext::SSLConfigChangeType change_type)515 void SpdySessionPool::OnSSLConfigChanged(
516 SSLClientContext::SSLConfigChangeType change_type) {
517 switch (change_type) {
518 case SSLClientContext::SSLConfigChangeType::kSSLConfigChanged:
519 MakeCurrentSessionsGoingAway(ERR_NETWORK_CHANGED);
520 break;
521 case SSLClientContext::SSLConfigChangeType::kCertDatabaseChanged:
522 MakeCurrentSessionsGoingAway(ERR_CERT_DATABASE_CHANGED);
523 break;
524 case SSLClientContext::SSLConfigChangeType::kCertVerifierChanged:
525 MakeCurrentSessionsGoingAway(ERR_CERT_VERIFIER_CHANGED);
526 break;
527 };
528 }
529
OnSSLConfigForServerChanged(const HostPortPair & server)530 void SpdySessionPool::OnSSLConfigForServerChanged(const HostPortPair& server) {
531 WeakSessionList current_sessions = GetCurrentSessions();
532 for (base::WeakPtr<SpdySession>& session : current_sessions) {
533 if (!session)
534 continue;
535
536 const ProxyServer& proxy_server =
537 session->spdy_session_key().proxy_server();
538 if (session->host_port_pair() == server ||
539 (proxy_server.is_http_like() && !proxy_server.is_http() &&
540 proxy_server.host_port_pair() == server)) {
541 session->MakeUnavailable();
542 // Note this call preserves active streams but fails any streams that are
543 // waiting on a stream ID.
544 // TODO(https://crbug.com/1213609): This is not ideal, but SpdySession
545 // does not have a state that supports this.
546 session->StartGoingAway(kLastStreamId, ERR_NETWORK_CHANGED);
547 session->MaybeFinishGoingAway();
548 DCHECK(!IsSessionAvailable(session));
549 }
550 }
551 }
552
GetDnsAliasesForSessionKey(const SpdySessionKey & key) const553 std::set<std::string> SpdySessionPool::GetDnsAliasesForSessionKey(
554 const SpdySessionKey& key) const {
555 auto it = dns_aliases_by_session_key_.find(key);
556 if (it == dns_aliases_by_session_key_.end())
557 return {};
558
559 return it->second;
560 }
561
RemoveRequestForSpdySession(SpdySessionRequest * request)562 void SpdySessionPool::RemoveRequestForSpdySession(SpdySessionRequest* request) {
563 DCHECK_EQ(this, request->spdy_session_pool());
564
565 auto iter = spdy_session_request_map_.find(request->key());
566 DCHECK(iter != spdy_session_request_map_.end());
567
568 // Resume all pending requests if it is the blocking request, which is either
569 // being canceled, or has completed.
570 if (request->is_blocking_request_for_session() &&
571 !iter->second.deferred_callbacks.empty()) {
572 base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
573 FROM_HERE,
574 base::BindOnce(&SpdySessionPool::UpdatePendingRequests,
575 weak_ptr_factory_.GetWeakPtr(), request->key()));
576 }
577
578 DCHECK(base::Contains(iter->second.request_set, request));
579 RemoveRequestInternal(iter, iter->second.request_set.find(request));
580 }
581
582 SpdySessionPool::RequestInfoForKey::RequestInfoForKey() = default;
583 SpdySessionPool::RequestInfoForKey::~RequestInfoForKey() = default;
584
IsSessionAvailable(const base::WeakPtr<SpdySession> & session) const585 bool SpdySessionPool::IsSessionAvailable(
586 const base::WeakPtr<SpdySession>& session) const {
587 for (const auto& available_session : available_sessions_) {
588 if (available_session.second.get() == session.get())
589 return true;
590 }
591 return false;
592 }
593
MapKeyToAvailableSession(const SpdySessionKey & key,const base::WeakPtr<SpdySession> & session,std::set<std::string> dns_aliases)594 void SpdySessionPool::MapKeyToAvailableSession(
595 const SpdySessionKey& key,
596 const base::WeakPtr<SpdySession>& session,
597 std::set<std::string> dns_aliases) {
598 DCHECK(base::Contains(sessions_, session.get()));
599 std::pair<AvailableSessionMap::iterator, bool> result =
600 available_sessions_.insert(std::make_pair(key, session));
601 CHECK(result.second);
602
603 dns_aliases_by_session_key_[key] = std::move(dns_aliases);
604 }
605
606 SpdySessionPool::AvailableSessionMap::iterator
LookupAvailableSessionByKey(const SpdySessionKey & key)607 SpdySessionPool::LookupAvailableSessionByKey(
608 const SpdySessionKey& key) {
609 return available_sessions_.find(key);
610 }
611
UnmapKey(const SpdySessionKey & key)612 void SpdySessionPool::UnmapKey(const SpdySessionKey& key) {
613 auto it = LookupAvailableSessionByKey(key);
614 CHECK(it != available_sessions_.end());
615 available_sessions_.erase(it);
616 dns_aliases_by_session_key_.erase(key);
617 }
618
RemoveAliases(const SpdySessionKey & key)619 void SpdySessionPool::RemoveAliases(const SpdySessionKey& key) {
620 // Walk the aliases map, find references to this pair.
621 // TODO(mbelshe): Figure out if this is too expensive.
622 for (auto it = aliases_.begin(); it != aliases_.end();) {
623 if (it->second == key) {
624 auto old_it = it;
625 ++it;
626 aliases_.erase(old_it);
627 } else {
628 ++it;
629 }
630 }
631 }
632
GetCurrentSessions() const633 SpdySessionPool::WeakSessionList SpdySessionPool::GetCurrentSessions() const {
634 WeakSessionList current_sessions;
635 for (auto* session : sessions_) {
636 current_sessions.push_back(session->GetWeakPtr());
637 }
638 return current_sessions;
639 }
640
CloseCurrentSessionsHelper(Error error,const std::string & description,bool idle_only)641 void SpdySessionPool::CloseCurrentSessionsHelper(Error error,
642 const std::string& description,
643 bool idle_only) {
644 WeakSessionList current_sessions = GetCurrentSessions();
645 for (base::WeakPtr<SpdySession>& session : current_sessions) {
646 if (!session)
647 continue;
648
649 if (idle_only && session->is_active())
650 continue;
651
652 if (session->IsDraining())
653 continue;
654
655 session->CloseSessionOnError(error, description);
656
657 DCHECK(!IsSessionAvailable(session));
658 DCHECK(!session || session->IsDraining());
659 }
660 }
661
CreateSession(const SpdySessionKey & key,NetLog * net_log)662 std::unique_ptr<SpdySession> SpdySessionPool::CreateSession(
663 const SpdySessionKey& key,
664 NetLog* net_log) {
665 UMA_HISTOGRAM_ENUMERATION("Net.SpdySessionGet", IMPORTED_FROM_SOCKET,
666 SPDY_SESSION_GET_MAX);
667
668 // If there's a pre-existing matching session, it has to be an alias. Remove
669 // the alias.
670 auto it = LookupAvailableSessionByKey(key);
671 if (it != available_sessions_.end()) {
672 DCHECK(key != it->second->spdy_session_key());
673
674 // Remove session from available sessions and from aliases, and remove
675 // key from the session's pooled alias set, so that a new session can be
676 // created with this |key|.
677 it->second->RemovePooledAlias(key);
678 UnmapKey(key);
679 RemoveAliases(key);
680 }
681
682 return std::make_unique<SpdySession>(
683 key, http_server_properties_, transport_security_state_,
684 ssl_client_context_ ? ssl_client_context_->ssl_config_service() : nullptr,
685 quic_supported_versions_, enable_sending_initial_data_,
686 enable_ping_based_connection_checking_, is_http2_enabled_,
687 is_quic_enabled_, session_max_recv_window_size_,
688 session_max_queued_capped_frames_, initial_settings_,
689 enable_http2_settings_grease_, greased_http2_frame_,
690 http2_end_stream_with_data_frame_, enable_priority_update_, time_func_,
691 push_delegate_, network_quality_estimator_, net_log);
692 }
693
InsertSession(const SpdySessionKey & key,std::unique_ptr<SpdySession> new_session,const NetLogWithSource & source_net_log,std::set<std::string> dns_aliases)694 base::WeakPtr<SpdySession> SpdySessionPool::InsertSession(
695 const SpdySessionKey& key,
696 std::unique_ptr<SpdySession> new_session,
697 const NetLogWithSource& source_net_log,
698 std::set<std::string> dns_aliases) {
699 base::WeakPtr<SpdySession> available_session = new_session->GetWeakPtr();
700 sessions_.insert(new_session.release());
701 MapKeyToAvailableSession(key, available_session, std::move(dns_aliases));
702
703 base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
704 FROM_HERE, base::BindOnce(&SpdySessionPool::UpdatePendingRequests,
705 weak_ptr_factory_.GetWeakPtr(), key));
706
707 source_net_log.AddEventReferencingSource(
708 NetLogEventType::HTTP2_SESSION_POOL_IMPORTED_SESSION_FROM_SOCKET,
709 available_session->net_log().source());
710
711 // Look up the IP address for this session so that we can match
712 // future sessions (potentially to different domains) which can
713 // potentially be pooled with this one. Because GetPeerAddress()
714 // reports the proxy's address instead of the origin server, check
715 // to see if this is a direct connection.
716 if (key.proxy_server().is_direct()) {
717 IPEndPoint address;
718 if (available_session->GetPeerAddress(&address) == OK)
719 aliases_.insert(AliasMap::value_type(address, key));
720 }
721
722 return available_session;
723 }
724
UpdatePendingRequests(const SpdySessionKey & key)725 void SpdySessionPool::UpdatePendingRequests(const SpdySessionKey& key) {
726 auto it = LookupAvailableSessionByKey(key);
727 if (it != available_sessions_.end()) {
728 base::WeakPtr<SpdySession> new_session = it->second->GetWeakPtr();
729 bool is_pooled = (key != new_session->spdy_session_key());
730 while (new_session && new_session->IsAvailable()) {
731 // Each iteration may empty out the RequestSet for |spdy_session_key| in
732 // |spdy_session_request_map_|. So each time, check for RequestSet and use
733 // the first one. Could just keep track if the last iteration removed the
734 // final request, but it's possible that responding to one request will
735 // result in cancelling another one.
736 //
737 // TODO(willchan): If it's important, switch RequestSet out for a FIFO
738 // queue (Order by priority first, then FIFO within same priority).
739 // Unclear that it matters here.
740 auto iter = spdy_session_request_map_.find(key);
741 if (iter == spdy_session_request_map_.end())
742 break;
743 RequestSet* request_set = &iter->second.request_set;
744 // Find a request that can use the socket, if any.
745 RequestSet::iterator request;
746 for (request = request_set->begin(); request != request_set->end();
747 ++request) {
748 // If the request is for use with websockets, and the session doesn't
749 // support websockets, skip over the request.
750 if ((*request)->is_websocket() && !new_session->support_websocket())
751 continue;
752 // Don't use IP pooled session if not allowed.
753 if (!(*request)->enable_ip_based_pooling() && is_pooled)
754 continue;
755 break;
756 }
757 if (request == request_set->end())
758 break;
759
760 SpdySessionRequest::Delegate* delegate = (*request)->delegate();
761 RemoveRequestInternal(iter, request);
762 delegate->OnSpdySessionAvailable(new_session);
763 }
764 }
765
766 auto iter = spdy_session_request_map_.find(key);
767 if (iter == spdy_session_request_map_.end())
768 return;
769 // Remove all pending requests, if there are any. As a result, if one of these
770 // callbacks triggers a new RequestSession() call,
771 // |is_blocking_request_for_session| will be true.
772 std::list<base::RepeatingClosure> deferred_requests =
773 std::move(iter->second.deferred_callbacks);
774
775 // Delete the RequestMap if there are no SpdySessionRequests, and no deferred
776 // requests.
777 if (iter->second.request_set.empty())
778 spdy_session_request_map_.erase(iter);
779
780 // Resume any deferred requests. This needs to be after the
781 // OnSpdySessionAvailable() calls, to prevent requests from calling into the
782 // socket pools in cases where that's not necessary.
783 for (auto callback : deferred_requests) {
784 callback.Run();
785 }
786 }
787
RemoveRequestInternal(SpdySessionRequestMap::iterator request_map_iterator,RequestSet::iterator request_set_iterator)788 void SpdySessionPool::RemoveRequestInternal(
789 SpdySessionRequestMap::iterator request_map_iterator,
790 RequestSet::iterator request_set_iterator) {
791 SpdySessionRequest* request = *request_set_iterator;
792 request_map_iterator->second.request_set.erase(request_set_iterator);
793 if (request->is_blocking_request_for_session()) {
794 DCHECK(request_map_iterator->second.has_blocking_request);
795 request_map_iterator->second.has_blocking_request = false;
796 }
797
798 // If both lists of requests are empty, can now remove the entry from the map.
799 if (request_map_iterator->second.request_set.empty() &&
800 request_map_iterator->second.deferred_callbacks.empty()) {
801 spdy_session_request_map_.erase(request_map_iterator);
802 }
803 request->OnRemovedFromPool();
804 }
805
806 } // namespace net
807