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 force_single_domain
,
37 bool enable_compression
,
38 bool enable_ping_based_connection_checking
,
39 NextProto default_protocol
,
40 size_t stream_initial_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 force_single_domain_(force_single_domain
),
52 enable_compression_(enable_compression
),
53 enable_ping_based_connection_checking_(
54 enable_ping_based_connection_checking
),
55 // TODO(akalin): Force callers to have a valid value of
56 // |default_protocol_|.
58 (default_protocol
== kProtoUnknown
) ?
59 kProtoSPDY31
: default_protocol
),
60 stream_initial_recv_window_size_(stream_initial_recv_window_size
),
61 initial_max_concurrent_streams_(initial_max_concurrent_streams
),
62 max_concurrent_streams_limit_(max_concurrent_streams_limit
),
63 time_func_(time_func
),
65 HostPortPair::FromString(trusted_spdy_proxy
)) {
66 DCHECK(default_protocol_
>= kProtoSPDYMinimumVersion
&&
67 default_protocol_
<= kProtoSPDYMaximumVersion
);
68 NetworkChangeNotifier::AddIPAddressObserver(this);
69 if (ssl_config_service_
.get())
70 ssl_config_service_
->AddObserver(this);
71 CertDatabase::GetInstance()->AddObserver(this);
74 SpdySessionPool::~SpdySessionPool() {
77 while (!sessions_
.empty()) {
78 // Destroy sessions to enforce that lifetime is scoped to SpdySessionPool.
79 // Write callbacks queued upon session drain are not invoked.
80 RemoveUnavailableSession((*sessions_
.begin())->GetWeakPtr());
83 if (ssl_config_service_
.get())
84 ssl_config_service_
->RemoveObserver(this);
85 NetworkChangeNotifier::RemoveIPAddressObserver(this);
86 CertDatabase::GetInstance()->RemoveObserver(this);
89 base::WeakPtr
<SpdySession
> SpdySessionPool::CreateAvailableSessionFromSocket(
90 const SpdySessionKey
& key
,
91 scoped_ptr
<ClientSocketHandle
> connection
,
92 const BoundNetLog
& net_log
,
93 int certificate_error_code
,
95 DCHECK_GE(default_protocol_
, kProtoSPDYMinimumVersion
);
96 DCHECK_LE(default_protocol_
, kProtoSPDYMaximumVersion
);
98 UMA_HISTOGRAM_ENUMERATION(
99 "Net.SpdySessionGet", IMPORTED_FROM_SOCKET
, SPDY_SESSION_GET_MAX
);
101 scoped_ptr
<SpdySession
> new_session(
103 http_server_properties_
,
104 transport_security_state_
,
105 verify_domain_authentication_
,
106 enable_sending_initial_data_
,
108 enable_ping_based_connection_checking_
,
110 stream_initial_recv_window_size_
,
111 initial_max_concurrent_streams_
,
112 max_concurrent_streams_limit_
,
117 new_session
->InitializeWithSocket(
118 connection
.Pass(), this, is_secure
, certificate_error_code
);
120 base::WeakPtr
<SpdySession
> available_session
= new_session
->GetWeakPtr();
121 sessions_
.insert(new_session
.release());
122 MapKeyToAvailableSession(key
, available_session
);
125 NetLog::TYPE_HTTP2_SESSION_POOL_IMPORTED_SESSION_FROM_SOCKET
,
126 available_session
->net_log().source().ToEventParametersCallback());
128 // Look up the IP address for this session so that we can match
129 // future sessions (potentially to different domains) which can
130 // potentially be pooled with this one. Because GetPeerAddress()
131 // reports the proxy's address instead of the origin server, check
132 // to see if this is a direct connection.
133 if (key
.proxy_server().is_direct()) {
135 if (available_session
->GetPeerAddress(&address
) == OK
)
136 aliases_
[address
] = key
;
139 return available_session
;
142 base::WeakPtr
<SpdySession
> SpdySessionPool::FindAvailableSession(
143 const SpdySessionKey
& key
,
144 const BoundNetLog
& net_log
) {
145 AvailableSessionMap::iterator it
= LookupAvailableSessionByKey(key
);
146 if (it
!= available_sessions_
.end()) {
147 UMA_HISTOGRAM_ENUMERATION(
148 "Net.SpdySessionGet", FOUND_EXISTING
, SPDY_SESSION_GET_MAX
);
150 NetLog::TYPE_HTTP2_SESSION_POOL_FOUND_EXISTING_SESSION
,
151 it
->second
->net_log().source().ToEventParametersCallback());
155 // Look up the key's from the resolver's cache.
156 net::HostResolver::RequestInfo
resolve_info(key
.host_port_pair());
157 AddressList addresses
;
158 int rv
= resolver_
->ResolveFromCache(resolve_info
, &addresses
, net_log
);
159 DCHECK_NE(rv
, ERR_IO_PENDING
);
161 return base::WeakPtr
<SpdySession
>();
163 // Check if we have a session through a domain alias.
164 for (AddressList::const_iterator address_it
= addresses
.begin();
165 address_it
!= addresses
.end();
167 AliasMap::const_iterator alias_it
= aliases_
.find(*address_it
);
168 if (alias_it
== aliases_
.end())
171 // We found an alias.
172 const SpdySessionKey
& alias_key
= alias_it
->second
;
174 // We can reuse this session only if the proxy and privacy
176 if (!(alias_key
.proxy_server() == key
.proxy_server()) ||
177 !(alias_key
.privacy_mode() == key
.privacy_mode()))
180 AvailableSessionMap::iterator available_session_it
=
181 LookupAvailableSessionByKey(alias_key
);
182 if (available_session_it
== available_sessions_
.end()) {
183 NOTREACHED(); // It shouldn't be in the aliases table if we can't get it!
187 const base::WeakPtr
<SpdySession
>& available_session
=
188 available_session_it
->second
;
189 DCHECK(ContainsKey(sessions_
, available_session
.get()));
190 // If the session is a secure one, we need to verify that the
191 // server is authenticated to serve traffic for |host_port_proxy_pair| too.
192 if (!available_session
->VerifyDomainAuthentication(
193 key
.host_port_pair().host())) {
194 UMA_HISTOGRAM_ENUMERATION("Net.SpdyIPPoolDomainMatch", 0, 2);
198 UMA_HISTOGRAM_ENUMERATION("Net.SpdyIPPoolDomainMatch", 1, 2);
199 UMA_HISTOGRAM_ENUMERATION("Net.SpdySessionGet",
200 FOUND_EXISTING_FROM_IP_POOL
,
201 SPDY_SESSION_GET_MAX
);
203 NetLog::TYPE_HTTP2_SESSION_POOL_FOUND_EXISTING_SESSION_FROM_IP_POOL
,
204 available_session
->net_log().source().ToEventParametersCallback());
205 // Add this session to the map so that we can find it next time.
206 MapKeyToAvailableSession(key
, available_session
);
207 available_session
->AddPooledAlias(key
);
208 return available_session
;
211 return base::WeakPtr
<SpdySession
>();
214 void SpdySessionPool::MakeSessionUnavailable(
215 const base::WeakPtr
<SpdySession
>& available_session
) {
216 UnmapKey(available_session
->spdy_session_key());
217 RemoveAliases(available_session
->spdy_session_key());
218 const std::set
<SpdySessionKey
>& aliases
= available_session
->pooled_aliases();
219 for (std::set
<SpdySessionKey
>::const_iterator it
= aliases
.begin();
220 it
!= aliases
.end(); ++it
) {
224 DCHECK(!IsSessionAvailable(available_session
));
227 void SpdySessionPool::RemoveUnavailableSession(
228 const base::WeakPtr
<SpdySession
>& unavailable_session
) {
229 DCHECK(!IsSessionAvailable(unavailable_session
));
231 unavailable_session
->net_log().AddEvent(
232 NetLog::TYPE_HTTP2_SESSION_POOL_REMOVE_SESSION
,
233 unavailable_session
->net_log().source().ToEventParametersCallback());
235 SessionSet::iterator it
= sessions_
.find(unavailable_session
.get());
236 CHECK(it
!= sessions_
.end());
237 scoped_ptr
<SpdySession
> owned_session(*it
);
241 // Make a copy of |sessions_| in the Close* functions below to avoid
242 // reentrancy problems. Since arbitrary functions get called by close
243 // handlers, it doesn't suffice to simply increment the iterator
246 void SpdySessionPool::CloseCurrentSessions(net::Error error
) {
247 CloseCurrentSessionsHelper(error
, "Closing current sessions.",
248 false /* idle_only */);
251 void SpdySessionPool::CloseCurrentIdleSessions() {
252 CloseCurrentSessionsHelper(ERR_ABORTED
, "Closing idle sessions.",
253 true /* idle_only */);
256 void SpdySessionPool::CloseAllSessions() {
257 while (!available_sessions_
.empty()) {
258 CloseCurrentSessionsHelper(ERR_ABORTED
, "Closing all sessions.",
259 false /* idle_only */);
263 base::Value
* SpdySessionPool::SpdySessionPoolInfoToValue() const {
264 base::ListValue
* list
= new base::ListValue();
266 for (AvailableSessionMap::const_iterator it
= available_sessions_
.begin();
267 it
!= available_sessions_
.end(); ++it
) {
268 // Only add the session if the key in the map matches the main
269 // host_port_proxy_pair (not an alias).
270 const SpdySessionKey
& key
= it
->first
;
271 const SpdySessionKey
& session_key
= it
->second
->spdy_session_key();
272 if (key
.Equals(session_key
))
273 list
->Append(it
->second
->GetInfoAsValue());
278 void SpdySessionPool::OnIPAddressChanged() {
279 WeakSessionList current_sessions
= GetCurrentSessions();
280 for (WeakSessionList::const_iterator it
= current_sessions
.begin();
281 it
!= current_sessions
.end(); ++it
) {
285 // For OSs that terminate TCP connections upon relevant network changes,
286 // attempt to preserve active streams by marking all sessions as going
287 // away, rather than explicitly closing them. Streams may still fail due
288 // to a generated TCP reset.
289 #if defined(OS_ANDROID) || defined(OS_WIN) || defined(OS_IOS)
290 (*it
)->MakeUnavailable();
291 (*it
)->StartGoingAway(kLastStreamId
, ERR_NETWORK_CHANGED
);
292 (*it
)->MaybeFinishGoingAway();
294 (*it
)->CloseSessionOnError(ERR_NETWORK_CHANGED
,
295 "Closing current sessions.");
296 DCHECK((*it
)->IsDraining());
297 #endif // defined(OS_ANDROID) || defined(OS_WIN) || defined(OS_IOS)
298 DCHECK(!IsSessionAvailable(*it
));
300 http_server_properties_
->ClearAllSpdySettings();
303 void SpdySessionPool::OnSSLConfigChanged() {
304 CloseCurrentSessions(ERR_NETWORK_CHANGED
);
307 void SpdySessionPool::OnCertAdded(const X509Certificate
* cert
) {
308 CloseCurrentSessions(ERR_CERT_DATABASE_CHANGED
);
311 void SpdySessionPool::OnCACertChanged(const X509Certificate
* cert
) {
312 // Per wtc, we actually only need to CloseCurrentSessions when trust is
313 // reduced. CloseCurrentSessions now because OnCACertChanged does not
315 // See comments in ClientSocketPoolManager::OnCACertChanged.
316 CloseCurrentSessions(ERR_CERT_DATABASE_CHANGED
);
319 bool SpdySessionPool::IsSessionAvailable(
320 const base::WeakPtr
<SpdySession
>& session
) const {
321 for (AvailableSessionMap::const_iterator it
= available_sessions_
.begin();
322 it
!= available_sessions_
.end(); ++it
) {
323 if (it
->second
.get() == session
.get())
329 const SpdySessionKey
& SpdySessionPool::NormalizeListKey(
330 const SpdySessionKey
& key
) const {
331 if (!force_single_domain_
)
334 static SpdySessionKey
* single_domain_key
= NULL
;
335 if (!single_domain_key
) {
336 HostPortPair single_domain
= HostPortPair("singledomain.com", 80);
337 single_domain_key
= new SpdySessionKey(single_domain
,
338 ProxyServer::Direct(),
339 PRIVACY_MODE_DISABLED
);
341 return *single_domain_key
;
344 void SpdySessionPool::MapKeyToAvailableSession(
345 const SpdySessionKey
& key
,
346 const base::WeakPtr
<SpdySession
>& session
) {
347 DCHECK(ContainsKey(sessions_
, session
.get()));
348 const SpdySessionKey
& normalized_key
= NormalizeListKey(key
);
349 std::pair
<AvailableSessionMap::iterator
, bool> result
=
350 available_sessions_
.insert(std::make_pair(normalized_key
, session
));
351 CHECK(result
.second
);
354 SpdySessionPool::AvailableSessionMap::iterator
355 SpdySessionPool::LookupAvailableSessionByKey(
356 const SpdySessionKey
& key
) {
357 const SpdySessionKey
& normalized_key
= NormalizeListKey(key
);
358 return available_sessions_
.find(normalized_key
);
361 void SpdySessionPool::UnmapKey(const SpdySessionKey
& key
) {
362 AvailableSessionMap::iterator it
= LookupAvailableSessionByKey(key
);
363 CHECK(it
!= available_sessions_
.end());
364 available_sessions_
.erase(it
);
367 void SpdySessionPool::RemoveAliases(const SpdySessionKey
& key
) {
368 // Walk the aliases map, find references to this pair.
369 // TODO(mbelshe): Figure out if this is too expensive.
370 for (AliasMap::iterator it
= aliases_
.begin(); it
!= aliases_
.end(); ) {
371 if (it
->second
.Equals(key
)) {
372 AliasMap::iterator old_it
= it
;
374 aliases_
.erase(old_it
);
381 SpdySessionPool::WeakSessionList
SpdySessionPool::GetCurrentSessions() const {
382 WeakSessionList current_sessions
;
383 for (SessionSet::const_iterator it
= sessions_
.begin();
384 it
!= sessions_
.end(); ++it
) {
385 current_sessions
.push_back((*it
)->GetWeakPtr());
387 return current_sessions
;
390 void SpdySessionPool::CloseCurrentSessionsHelper(
392 const std::string
& description
,
394 WeakSessionList current_sessions
= GetCurrentSessions();
395 for (WeakSessionList::const_iterator it
= current_sessions
.begin();
396 it
!= current_sessions
.end(); ++it
) {
400 if (idle_only
&& (*it
)->is_active())
403 (*it
)->CloseSessionOnError(error
, description
);
404 DCHECK(!IsSessionAvailable(*it
));