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