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/values.h"
10 #include "net/base/address_list.h"
11 #include "net/http/http_network_session.h"
12 #include "net/http/http_server_properties.h"
13 #include "net/spdy/spdy_session.h"
20 enum SpdySessionGetTypes
{
23 FOUND_EXISTING_FROM_IP_POOL
= 2,
24 IMPORTED_FROM_SOCKET
= 3,
25 SPDY_SESSION_GET_MAX
= 4
30 SpdySessionPool::SpdySessionPool(
31 HostResolver
* resolver
,
32 SSLConfigService
* ssl_config_service
,
33 const base::WeakPtr
<HttpServerProperties
>& http_server_properties
,
34 bool force_single_domain
,
35 bool enable_compression
,
36 bool enable_ping_based_connection_checking
,
37 NextProto default_protocol
,
38 size_t stream_initial_recv_window_size
,
39 size_t initial_max_concurrent_streams
,
40 size_t max_concurrent_streams_limit
,
41 SpdySessionPool::TimeFunc time_func
,
42 const std::string
& trusted_spdy_proxy
)
43 : http_server_properties_(http_server_properties
),
44 ssl_config_service_(ssl_config_service
),
46 verify_domain_authentication_(true),
47 enable_sending_initial_data_(true),
48 force_single_domain_(force_single_domain
),
49 enable_compression_(enable_compression
),
50 enable_ping_based_connection_checking_(
51 enable_ping_based_connection_checking
),
52 // TODO(akalin): Force callers to have a valid value of
53 // |default_protocol_|.
55 (default_protocol
== kProtoUnknown
) ?
56 kProtoSPDY3
: default_protocol
),
57 stream_initial_recv_window_size_(stream_initial_recv_window_size
),
58 initial_max_concurrent_streams_(initial_max_concurrent_streams
),
59 max_concurrent_streams_limit_(max_concurrent_streams_limit
),
60 time_func_(time_func
),
62 HostPortPair::FromString(trusted_spdy_proxy
)) {
63 DCHECK(default_protocol_
>= kProtoSPDYMinimumVersion
&&
64 default_protocol_
<= kProtoSPDYMaximumVersion
);
65 NetworkChangeNotifier::AddIPAddressObserver(this);
66 if (ssl_config_service_
.get())
67 ssl_config_service_
->AddObserver(this);
68 CertDatabase::GetInstance()->AddObserver(this);
71 SpdySessionPool::~SpdySessionPool() {
74 if (ssl_config_service_
.get())
75 ssl_config_service_
->RemoveObserver(this);
76 NetworkChangeNotifier::RemoveIPAddressObserver(this);
77 CertDatabase::GetInstance()->RemoveObserver(this);
80 base::WeakPtr
<SpdySession
> SpdySessionPool::CreateAvailableSessionFromSocket(
81 const SpdySessionKey
& key
,
82 scoped_ptr
<ClientSocketHandle
> connection
,
83 const BoundNetLog
& net_log
,
84 int certificate_error_code
,
86 DCHECK_GE(default_protocol_
, kProtoSPDYMinimumVersion
);
87 DCHECK_LE(default_protocol_
, kProtoSPDYMaximumVersion
);
89 UMA_HISTOGRAM_ENUMERATION(
90 "Net.SpdySessionGet", IMPORTED_FROM_SOCKET
, SPDY_SESSION_GET_MAX
);
92 scoped_ptr
<SpdySession
> new_session(
94 http_server_properties_
,
95 verify_domain_authentication_
,
96 enable_sending_initial_data_
,
98 enable_ping_based_connection_checking_
,
100 stream_initial_recv_window_size_
,
101 initial_max_concurrent_streams_
,
102 max_concurrent_streams_limit_
,
107 new_session
->InitializeWithSocket(
108 connection
.Pass(), this, is_secure
, certificate_error_code
);
110 base::WeakPtr
<SpdySession
> available_session
= new_session
->GetWeakPtr();
111 sessions_
.insert(new_session
.release());
112 MapKeyToAvailableSession(key
, available_session
);
115 NetLog::TYPE_SPDY_SESSION_POOL_IMPORTED_SESSION_FROM_SOCKET
,
116 available_session
->net_log().source().ToEventParametersCallback());
118 // Look up the IP address for this session so that we can match
119 // future sessions (potentially to different domains) which can
120 // potentially be pooled with this one. Because GetPeerAddress()
121 // reports the proxy's address instead of the origin server, check
122 // to see if this is a direct connection.
123 if (key
.proxy_server().is_direct()) {
125 if (available_session
->GetPeerAddress(&address
) == OK
)
126 aliases_
[address
] = key
;
129 return available_session
;
132 base::WeakPtr
<SpdySession
> SpdySessionPool::FindAvailableSession(
133 const SpdySessionKey
& key
,
134 const BoundNetLog
& net_log
) {
135 AvailableSessionMap::iterator it
= LookupAvailableSessionByKey(key
);
136 if (it
!= available_sessions_
.end()) {
137 UMA_HISTOGRAM_ENUMERATION(
138 "Net.SpdySessionGet", FOUND_EXISTING
, SPDY_SESSION_GET_MAX
);
140 NetLog::TYPE_SPDY_SESSION_POOL_FOUND_EXISTING_SESSION
,
141 it
->second
->net_log().source().ToEventParametersCallback());
145 // Look up the key's from the resolver's cache.
146 net::HostResolver::RequestInfo
resolve_info(key
.host_port_pair());
147 AddressList addresses
;
148 int rv
= resolver_
->ResolveFromCache(resolve_info
, &addresses
, net_log
);
149 DCHECK_NE(rv
, ERR_IO_PENDING
);
151 return base::WeakPtr
<SpdySession
>();
153 // Check if we have a session through a domain alias.
154 for (AddressList::const_iterator address_it
= addresses
.begin();
155 address_it
!= addresses
.end();
157 AliasMap::const_iterator alias_it
= aliases_
.find(*address_it
);
158 if (alias_it
== aliases_
.end())
161 // We found an alias.
162 const SpdySessionKey
& alias_key
= alias_it
->second
;
164 // We can reuse this session only if the proxy and privacy
166 if (!(alias_key
.proxy_server() == key
.proxy_server()) ||
167 !(alias_key
.privacy_mode() == key
.privacy_mode()))
170 AvailableSessionMap::iterator available_session_it
=
171 LookupAvailableSessionByKey(alias_key
);
172 if (available_session_it
== available_sessions_
.end()) {
173 NOTREACHED(); // It shouldn't be in the aliases table if we can't get it!
177 const base::WeakPtr
<SpdySession
>& available_session
=
178 available_session_it
->second
;
179 DCHECK(ContainsKey(sessions_
, available_session
.get()));
180 // If the session is a secure one, we need to verify that the
181 // server is authenticated to serve traffic for |host_port_proxy_pair| too.
182 if (!available_session
->VerifyDomainAuthentication(
183 key
.host_port_pair().host())) {
184 UMA_HISTOGRAM_ENUMERATION("Net.SpdyIPPoolDomainMatch", 0, 2);
188 UMA_HISTOGRAM_ENUMERATION("Net.SpdyIPPoolDomainMatch", 1, 2);
189 UMA_HISTOGRAM_ENUMERATION("Net.SpdySessionGet",
190 FOUND_EXISTING_FROM_IP_POOL
,
191 SPDY_SESSION_GET_MAX
);
193 NetLog::TYPE_SPDY_SESSION_POOL_FOUND_EXISTING_SESSION_FROM_IP_POOL
,
194 available_session
->net_log().source().ToEventParametersCallback());
195 // Add this session to the map so that we can find it next time.
196 MapKeyToAvailableSession(key
, available_session
);
197 available_session
->AddPooledAlias(key
);
198 return available_session
;
201 return base::WeakPtr
<SpdySession
>();
204 void SpdySessionPool::MakeSessionUnavailable(
205 const base::WeakPtr
<SpdySession
>& available_session
) {
206 UnmapKey(available_session
->spdy_session_key());
207 RemoveAliases(available_session
->spdy_session_key());
208 const std::set
<SpdySessionKey
>& aliases
= available_session
->pooled_aliases();
209 for (std::set
<SpdySessionKey
>::const_iterator it
= aliases
.begin();
210 it
!= aliases
.end(); ++it
) {
214 DCHECK(!IsSessionAvailable(available_session
));
217 void SpdySessionPool::RemoveUnavailableSession(
218 const base::WeakPtr
<SpdySession
>& unavailable_session
) {
219 DCHECK(!IsSessionAvailable(unavailable_session
));
221 unavailable_session
->net_log().AddEvent(
222 NetLog::TYPE_SPDY_SESSION_POOL_REMOVE_SESSION
,
223 unavailable_session
->net_log().source().ToEventParametersCallback());
225 SessionSet::iterator it
= sessions_
.find(unavailable_session
.get());
226 CHECK(it
!= sessions_
.end());
227 scoped_ptr
<SpdySession
> owned_session(*it
);
231 // Make a copy of |sessions_| in the Close* functions below to avoid
232 // reentrancy problems. Since arbitrary functions get called by close
233 // handlers, it doesn't suffice to simply increment the iterator
236 void SpdySessionPool::CloseCurrentSessions(net::Error error
) {
237 CloseCurrentSessionsHelper(error
, "Closing current sessions.",
238 false /* idle_only */);
241 void SpdySessionPool::CloseCurrentIdleSessions() {
242 CloseCurrentSessionsHelper(ERR_ABORTED
, "Closing idle sessions.",
243 true /* idle_only */);
246 void SpdySessionPool::CloseAllSessions() {
247 while (!sessions_
.empty()) {
248 CloseCurrentSessionsHelper(ERR_ABORTED
, "Closing all sessions.",
249 false /* idle_only */);
253 base::Value
* SpdySessionPool::SpdySessionPoolInfoToValue() const {
254 base::ListValue
* list
= new base::ListValue();
256 for (AvailableSessionMap::const_iterator it
= available_sessions_
.begin();
257 it
!= available_sessions_
.end(); ++it
) {
258 // Only add the session if the key in the map matches the main
259 // host_port_proxy_pair (not an alias).
260 const SpdySessionKey
& key
= it
->first
;
261 const SpdySessionKey
& session_key
= it
->second
->spdy_session_key();
262 if (key
.Equals(session_key
))
263 list
->Append(it
->second
->GetInfoAsValue());
268 void SpdySessionPool::OnIPAddressChanged() {
269 WeakSessionList current_sessions
= GetCurrentSessions();
270 for (WeakSessionList::const_iterator it
= current_sessions
.begin();
271 it
!= current_sessions
.end(); ++it
) {
275 // For OSs that terminate TCP connections upon relevant network changes
276 // there is no need to explicitly close SpdySessions, instead simply mark
277 // the sessions as deprecated so they aren't reused.
278 #if defined(OS_ANDROID) || defined(OS_WIN) || defined(OS_IOS)
279 (*it
)->MakeUnavailable();
281 (*it
)->CloseSessionOnError(ERR_NETWORK_CHANGED
,
282 "Closing current sessions.");
284 #endif // defined(OS_ANDROID) || defined(OS_WIN) || defined(OS_IOS)
285 DCHECK(!IsSessionAvailable(*it
));
287 http_server_properties_
->ClearAllSpdySettings();
290 void SpdySessionPool::OnSSLConfigChanged() {
291 CloseCurrentSessions(ERR_NETWORK_CHANGED
);
294 void SpdySessionPool::OnCertAdded(const X509Certificate
* cert
) {
295 CloseCurrentSessions(ERR_CERT_DATABASE_CHANGED
);
298 void SpdySessionPool::OnCACertChanged(const X509Certificate
* cert
) {
299 // Per wtc, we actually only need to CloseCurrentSessions when trust is
300 // reduced. CloseCurrentSessions now because OnCACertChanged does not
302 // See comments in ClientSocketPoolManager::OnCACertChanged.
303 CloseCurrentSessions(ERR_CERT_DATABASE_CHANGED
);
306 bool SpdySessionPool::IsSessionAvailable(
307 const base::WeakPtr
<SpdySession
>& session
) const {
308 for (AvailableSessionMap::const_iterator it
= available_sessions_
.begin();
309 it
!= available_sessions_
.end(); ++it
) {
310 if (it
->second
.get() == session
.get())
316 const SpdySessionKey
& SpdySessionPool::NormalizeListKey(
317 const SpdySessionKey
& key
) const {
318 if (!force_single_domain_
)
321 static SpdySessionKey
* single_domain_key
= NULL
;
322 if (!single_domain_key
) {
323 HostPortPair single_domain
= HostPortPair("singledomain.com", 80);
324 single_domain_key
= new SpdySessionKey(single_domain
,
325 ProxyServer::Direct(),
326 PRIVACY_MODE_DISABLED
);
328 return *single_domain_key
;
331 void SpdySessionPool::MapKeyToAvailableSession(
332 const SpdySessionKey
& key
,
333 const base::WeakPtr
<SpdySession
>& session
) {
334 DCHECK(ContainsKey(sessions_
, session
.get()));
335 const SpdySessionKey
& normalized_key
= NormalizeListKey(key
);
336 std::pair
<AvailableSessionMap::iterator
, bool> result
=
337 available_sessions_
.insert(std::make_pair(normalized_key
, session
));
338 CHECK(result
.second
);
341 SpdySessionPool::AvailableSessionMap::iterator
342 SpdySessionPool::LookupAvailableSessionByKey(
343 const SpdySessionKey
& key
) {
344 const SpdySessionKey
& normalized_key
= NormalizeListKey(key
);
345 return available_sessions_
.find(normalized_key
);
348 void SpdySessionPool::UnmapKey(const SpdySessionKey
& key
) {
349 AvailableSessionMap::iterator it
= LookupAvailableSessionByKey(key
);
350 CHECK(it
!= available_sessions_
.end());
351 available_sessions_
.erase(it
);
354 void SpdySessionPool::RemoveAliases(const SpdySessionKey
& key
) {
355 // Walk the aliases map, find references to this pair.
356 // TODO(mbelshe): Figure out if this is too expensive.
357 for (AliasMap::iterator it
= aliases_
.begin(); it
!= aliases_
.end(); ) {
358 if (it
->second
.Equals(key
)) {
359 AliasMap::iterator old_it
= it
;
361 aliases_
.erase(old_it
);
368 SpdySessionPool::WeakSessionList
SpdySessionPool::GetCurrentSessions() const {
369 WeakSessionList current_sessions
;
370 for (SessionSet::const_iterator it
= sessions_
.begin();
371 it
!= sessions_
.end(); ++it
) {
372 current_sessions
.push_back((*it
)->GetWeakPtr());
374 return current_sessions
;
377 void SpdySessionPool::CloseCurrentSessionsHelper(
379 const std::string
& description
,
381 WeakSessionList current_sessions
= GetCurrentSessions();
382 for (WeakSessionList::const_iterator it
= current_sessions
.begin();
383 it
!= current_sessions
.end(); ++it
) {
387 if (idle_only
&& (*it
)->is_active())
390 (*it
)->CloseSessionOnError(error
, description
);
391 DCHECK(!IsSessionAvailable(*it
));