spdy_session_pool.cc 30 KB

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