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.
5 #include "net/spdy/spdy_session_pool.h"
7 #include "base/logging.h"
8 #include "base/metrics/histogram.h"
9 #include "base/profiler/scoped_tracker.h"
10 #include "base/values.h"
11 #include "net/base/address_list.h"
12 #include "net/http/http_network_session.h"
13 #include "net/http/http_server_properties.h"
14 #include "net/spdy/spdy_session.h"
21 enum SpdySessionGetTypes
{
24 FOUND_EXISTING_FROM_IP_POOL
= 2,
25 IMPORTED_FROM_SOCKET
= 3,
26 SPDY_SESSION_GET_MAX
= 4
31 SpdySessionPool::SpdySessionPool(
32 HostResolver
* resolver
,
33 SSLConfigService
* ssl_config_service
,
34 const base::WeakPtr
<HttpServerProperties
>& http_server_properties
,
35 TransportSecurityState
* transport_security_state
,
36 bool enable_compression
,
37 bool enable_ping_based_connection_checking
,
38 NextProto default_protocol
,
39 size_t session_max_recv_window_size
,
40 size_t stream_max_recv_window_size
,
41 size_t initial_max_concurrent_streams
,
42 size_t max_concurrent_streams_limit
,
43 SpdySessionPool::TimeFunc time_func
,
44 const std::string
& trusted_spdy_proxy
)
45 : http_server_properties_(http_server_properties
),
46 transport_security_state_(transport_security_state
),
47 ssl_config_service_(ssl_config_service
),
49 verify_domain_authentication_(true),
50 enable_sending_initial_data_(true),
51 enable_compression_(enable_compression
),
52 enable_ping_based_connection_checking_(
53 enable_ping_based_connection_checking
),
54 // TODO(akalin): Force callers to have a valid value of
55 // |default_protocol_|.
56 default_protocol_((default_protocol
== kProtoUnknown
) ? kProtoSPDY31
58 session_max_recv_window_size_(session_max_recv_window_size
),
59 stream_max_recv_window_size_(stream_max_recv_window_size
),
60 initial_max_concurrent_streams_(initial_max_concurrent_streams
),
61 max_concurrent_streams_limit_(max_concurrent_streams_limit
),
62 time_func_(time_func
),
63 trusted_spdy_proxy_(HostPortPair::FromString(trusted_spdy_proxy
)) {
64 DCHECK(default_protocol_
>= kProtoSPDYMinimumVersion
&&
65 default_protocol_
<= kProtoSPDYMaximumVersion
);
66 NetworkChangeNotifier::AddIPAddressObserver(this);
67 if (ssl_config_service_
.get())
68 ssl_config_service_
->AddObserver(this);
69 CertDatabase::GetInstance()->AddObserver(this);
72 SpdySessionPool::~SpdySessionPool() {
75 while (!sessions_
.empty()) {
76 // Destroy sessions to enforce that lifetime is scoped to SpdySessionPool.
77 // Write callbacks queued upon session drain are not invoked.
78 RemoveUnavailableSession((*sessions_
.begin())->GetWeakPtr());
81 if (ssl_config_service_
.get())
82 ssl_config_service_
->RemoveObserver(this);
83 NetworkChangeNotifier::RemoveIPAddressObserver(this);
84 CertDatabase::GetInstance()->RemoveObserver(this);
87 base::WeakPtr
<SpdySession
> SpdySessionPool::CreateAvailableSessionFromSocket(
88 const SpdySessionKey
& key
,
89 scoped_ptr
<ClientSocketHandle
> connection
,
90 const BoundNetLog
& net_log
,
91 int certificate_error_code
,
93 DCHECK_GE(default_protocol_
, kProtoSPDYMinimumVersion
);
94 DCHECK_LE(default_protocol_
, kProtoSPDYMaximumVersion
);
96 UMA_HISTOGRAM_ENUMERATION(
97 "Net.SpdySessionGet", IMPORTED_FROM_SOCKET
, SPDY_SESSION_GET_MAX
);
99 scoped_ptr
<SpdySession
> new_session(new SpdySession(
100 key
, http_server_properties_
, transport_security_state_
,
101 verify_domain_authentication_
, enable_sending_initial_data_
,
102 enable_compression_
, enable_ping_based_connection_checking_
,
103 default_protocol_
, session_max_recv_window_size_
,
104 stream_max_recv_window_size_
, initial_max_concurrent_streams_
,
105 max_concurrent_streams_limit_
, time_func_
, trusted_spdy_proxy_
,
108 new_session
->InitializeWithSocket(
109 connection
.Pass(), this, is_secure
, certificate_error_code
);
111 base::WeakPtr
<SpdySession
> available_session
= new_session
->GetWeakPtr();
112 sessions_
.insert(new_session
.release());
113 MapKeyToAvailableSession(key
, available_session
);
116 NetLog::TYPE_HTTP2_SESSION_POOL_IMPORTED_SESSION_FROM_SOCKET
,
117 available_session
->net_log().source().ToEventParametersCallback());
119 // Look up the IP address for this session so that we can match
120 // future sessions (potentially to different domains) which can
121 // potentially be pooled with this one. Because GetPeerAddress()
122 // reports the proxy's address instead of the origin server, check
123 // to see if this is a direct connection.
124 if (key
.proxy_server().is_direct()) {
126 if (available_session
->GetPeerAddress(&address
) == OK
)
127 aliases_
[address
] = key
;
130 return available_session
;
133 base::WeakPtr
<SpdySession
> SpdySessionPool::FindAvailableSession(
134 const SpdySessionKey
& key
,
135 const BoundNetLog
& net_log
) {
136 AvailableSessionMap::iterator it
= LookupAvailableSessionByKey(key
);
137 if (it
!= available_sessions_
.end()) {
138 UMA_HISTOGRAM_ENUMERATION(
139 "Net.SpdySessionGet", FOUND_EXISTING
, SPDY_SESSION_GET_MAX
);
141 NetLog::TYPE_HTTP2_SESSION_POOL_FOUND_EXISTING_SESSION
,
142 it
->second
->net_log().source().ToEventParametersCallback());
146 // Look up the key's from the resolver's cache.
147 net::HostResolver::RequestInfo
resolve_info(key
.host_port_pair());
148 AddressList addresses
;
149 int rv
= resolver_
->ResolveFromCache(resolve_info
, &addresses
, net_log
);
150 DCHECK_NE(rv
, ERR_IO_PENDING
);
152 return base::WeakPtr
<SpdySession
>();
154 // Check if we have a session through a domain alias.
155 for (AddressList::const_iterator address_it
= addresses
.begin();
156 address_it
!= addresses
.end();
158 AliasMap::const_iterator alias_it
= aliases_
.find(*address_it
);
159 if (alias_it
== aliases_
.end())
162 // We found an alias.
163 const SpdySessionKey
& alias_key
= alias_it
->second
;
165 // We can reuse this session only if the proxy and privacy
167 if (!(alias_key
.proxy_server() == key
.proxy_server()) ||
168 !(alias_key
.privacy_mode() == key
.privacy_mode()))
171 AvailableSessionMap::iterator available_session_it
=
172 LookupAvailableSessionByKey(alias_key
);
173 if (available_session_it
== available_sessions_
.end()) {
174 NOTREACHED(); // It shouldn't be in the aliases table if we can't get it!
178 const base::WeakPtr
<SpdySession
>& available_session
=
179 available_session_it
->second
;
180 DCHECK(ContainsKey(sessions_
, available_session
.get()));
181 // If the session is a secure one, we need to verify that the
182 // server is authenticated to serve traffic for |host_port_proxy_pair| too.
183 if (!available_session
->VerifyDomainAuthentication(
184 key
.host_port_pair().host())) {
185 UMA_HISTOGRAM_ENUMERATION("Net.SpdyIPPoolDomainMatch", 0, 2);
189 UMA_HISTOGRAM_ENUMERATION("Net.SpdyIPPoolDomainMatch", 1, 2);
190 UMA_HISTOGRAM_ENUMERATION("Net.SpdySessionGet",
191 FOUND_EXISTING_FROM_IP_POOL
,
192 SPDY_SESSION_GET_MAX
);
194 NetLog::TYPE_HTTP2_SESSION_POOL_FOUND_EXISTING_SESSION_FROM_IP_POOL
,
195 available_session
->net_log().source().ToEventParametersCallback());
196 // Add this session to the map so that we can find it next time.
197 MapKeyToAvailableSession(key
, available_session
);
198 available_session
->AddPooledAlias(key
);
199 return available_session
;
202 return base::WeakPtr
<SpdySession
>();
205 void SpdySessionPool::MakeSessionUnavailable(
206 const base::WeakPtr
<SpdySession
>& available_session
) {
207 UnmapKey(available_session
->spdy_session_key());
208 RemoveAliases(available_session
->spdy_session_key());
209 const std::set
<SpdySessionKey
>& aliases
= available_session
->pooled_aliases();
210 for (std::set
<SpdySessionKey
>::const_iterator it
= aliases
.begin();
211 it
!= aliases
.end(); ++it
) {
215 DCHECK(!IsSessionAvailable(available_session
));
218 void SpdySessionPool::RemoveUnavailableSession(
219 const base::WeakPtr
<SpdySession
>& unavailable_session
) {
220 DCHECK(!IsSessionAvailable(unavailable_session
));
222 unavailable_session
->net_log().AddEvent(
223 NetLog::TYPE_HTTP2_SESSION_POOL_REMOVE_SESSION
,
224 unavailable_session
->net_log().source().ToEventParametersCallback());
226 SessionSet::iterator it
= sessions_
.find(unavailable_session
.get());
227 CHECK(it
!= sessions_
.end());
228 scoped_ptr
<SpdySession
> owned_session(*it
);
232 // Make a copy of |sessions_| in the Close* functions below to avoid
233 // reentrancy problems. Since arbitrary functions get called by close
234 // handlers, it doesn't suffice to simply increment the iterator
237 void SpdySessionPool::CloseCurrentSessions(net::Error error
) {
238 CloseCurrentSessionsHelper(error
, "Closing current sessions.",
239 false /* idle_only */);
242 void SpdySessionPool::CloseCurrentIdleSessions() {
243 CloseCurrentSessionsHelper(ERR_ABORTED
, "Closing idle sessions.",
244 true /* idle_only */);
247 void SpdySessionPool::CloseAllSessions() {
248 while (!available_sessions_
.empty()) {
249 CloseCurrentSessionsHelper(ERR_ABORTED
, "Closing all sessions.",
250 false /* idle_only */);
254 base::Value
* SpdySessionPool::SpdySessionPoolInfoToValue() const {
255 base::ListValue
* list
= new base::ListValue();
257 for (AvailableSessionMap::const_iterator it
= available_sessions_
.begin();
258 it
!= available_sessions_
.end(); ++it
) {
259 // Only add the session if the key in the map matches the main
260 // host_port_proxy_pair (not an alias).
261 const SpdySessionKey
& key
= it
->first
;
262 const SpdySessionKey
& session_key
= it
->second
->spdy_session_key();
263 if (key
.Equals(session_key
))
264 list
->Append(it
->second
->GetInfoAsValue());
269 void SpdySessionPool::OnIPAddressChanged() {
270 WeakSessionList current_sessions
= GetCurrentSessions();
271 for (WeakSessionList::const_iterator it
= current_sessions
.begin();
272 it
!= current_sessions
.end(); ++it
) {
276 // For OSs that terminate TCP connections upon relevant network changes,
277 // attempt to preserve active streams by marking all sessions as going
278 // away, rather than explicitly closing them. Streams may still fail due
279 // to a generated TCP reset.
280 #if defined(OS_ANDROID) || defined(OS_WIN) || defined(OS_IOS)
281 (*it
)->MakeUnavailable();
282 (*it
)->StartGoingAway(kLastStreamId
, ERR_NETWORK_CHANGED
);
283 (*it
)->MaybeFinishGoingAway();
285 (*it
)->CloseSessionOnError(ERR_NETWORK_CHANGED
,
286 "Closing current sessions.");
287 DCHECK((*it
)->IsDraining());
288 #endif // defined(OS_ANDROID) || defined(OS_WIN) || defined(OS_IOS)
289 DCHECK(!IsSessionAvailable(*it
));
291 http_server_properties_
->ClearAllSpdySettings();
294 void SpdySessionPool::OnSSLConfigChanged() {
295 CloseCurrentSessions(ERR_NETWORK_CHANGED
);
298 void SpdySessionPool::OnCertAdded(const X509Certificate
* cert
) {
299 CloseCurrentSessions(ERR_CERT_DATABASE_CHANGED
);
302 void SpdySessionPool::OnCACertChanged(const X509Certificate
* cert
) {
303 // Per wtc, we actually only need to CloseCurrentSessions when trust is
304 // reduced. CloseCurrentSessions now because OnCACertChanged does not
306 // See comments in ClientSocketPoolManager::OnCACertChanged.
307 CloseCurrentSessions(ERR_CERT_DATABASE_CHANGED
);
310 bool SpdySessionPool::IsSessionAvailable(
311 const base::WeakPtr
<SpdySession
>& session
) const {
312 for (AvailableSessionMap::const_iterator it
= available_sessions_
.begin();
313 it
!= available_sessions_
.end(); ++it
) {
314 if (it
->second
.get() == session
.get())
320 void SpdySessionPool::MapKeyToAvailableSession(
321 const SpdySessionKey
& key
,
322 const base::WeakPtr
<SpdySession
>& session
) {
323 DCHECK(ContainsKey(sessions_
, session
.get()));
324 std::pair
<AvailableSessionMap::iterator
, bool> result
=
325 available_sessions_
.insert(std::make_pair(key
, session
));
326 CHECK(result
.second
);
329 SpdySessionPool::AvailableSessionMap::iterator
330 SpdySessionPool::LookupAvailableSessionByKey(
331 const SpdySessionKey
& key
) {
332 return available_sessions_
.find(key
);
335 void SpdySessionPool::UnmapKey(const SpdySessionKey
& key
) {
336 AvailableSessionMap::iterator it
= LookupAvailableSessionByKey(key
);
337 CHECK(it
!= available_sessions_
.end());
338 available_sessions_
.erase(it
);
341 void SpdySessionPool::RemoveAliases(const SpdySessionKey
& key
) {
342 // Walk the aliases map, find references to this pair.
343 // TODO(mbelshe): Figure out if this is too expensive.
344 for (AliasMap::iterator it
= aliases_
.begin(); it
!= aliases_
.end(); ) {
345 if (it
->second
.Equals(key
)) {
346 AliasMap::iterator old_it
= it
;
348 aliases_
.erase(old_it
);
355 SpdySessionPool::WeakSessionList
SpdySessionPool::GetCurrentSessions() const {
356 WeakSessionList current_sessions
;
357 for (SessionSet::const_iterator it
= sessions_
.begin();
358 it
!= sessions_
.end(); ++it
) {
359 current_sessions
.push_back((*it
)->GetWeakPtr());
361 return current_sessions
;
364 void SpdySessionPool::CloseCurrentSessionsHelper(
366 const std::string
& description
,
368 WeakSessionList current_sessions
= GetCurrentSessions();
369 for (WeakSessionList::const_iterator it
= current_sessions
.begin();
370 it
!= current_sessions
.end(); ++it
) {
374 if (idle_only
&& (*it
)->is_active())
377 (*it
)->CloseSessionOnError(error
, description
);
378 DCHECK(!IsSessionAvailable(*it
));