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_ip_pooling,
36 bool enable_compression,
37 bool enable_ping_based_connection_checking,
38 NextProto default_protocol,
39 size_t stream_initial_recv_window_size,
40 size_t initial_max_concurrent_streams,
41 size_t max_concurrent_streams_limit,
42 SpdySessionPool::TimeFunc time_func,
43 const std::string& trusted_spdy_proxy)
44 : http_server_properties_(http_server_properties),
45 ssl_config_service_(ssl_config_service),
47 verify_domain_authentication_(true),
48 enable_sending_initial_data_(true),
49 force_single_domain_(force_single_domain),
50 enable_ip_pooling_(enable_ip_pooling),
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_|.
57 (default_protocol == kProtoUnknown) ?
58 kProtoSPDY3 : default_protocol),
59 stream_initial_recv_window_size_(stream_initial_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),
64 HostPortPair::FromString(trusted_spdy_proxy)) {
65 DCHECK(default_protocol_ >= kProtoSPDYMinimumVersion &&
66 default_protocol_ <= kProtoSPDYMaximumVersion);
67 NetworkChangeNotifier::AddIPAddressObserver(this);
68 if (ssl_config_service_.get())
69 ssl_config_service_->AddObserver(this);
70 CertDatabase::GetInstance()->AddObserver(this);
73 SpdySessionPool::~SpdySessionPool() {
76 if (ssl_config_service_.get())
77 ssl_config_service_->RemoveObserver(this);
78 NetworkChangeNotifier::RemoveIPAddressObserver(this);
79 CertDatabase::GetInstance()->RemoveObserver(this);
82 net::Error SpdySessionPool::CreateAvailableSessionFromSocket(
83 const SpdySessionKey& key,
84 scoped_ptr<ClientSocketHandle> connection,
85 const BoundNetLog& net_log,
86 int certificate_error_code,
87 base::WeakPtr<SpdySession>* available_session,
89 DCHECK_GE(default_protocol_, kProtoSPDYMinimumVersion);
90 DCHECK_LE(default_protocol_, kProtoSPDYMaximumVersion);
92 UMA_HISTOGRAM_ENUMERATION(
93 "Net.SpdySessionGet", IMPORTED_FROM_SOCKET, SPDY_SESSION_GET_MAX);
95 scoped_ptr<SpdySession> new_session(
97 http_server_properties_,
98 verify_domain_authentication_,
99 enable_sending_initial_data_,
101 enable_ping_based_connection_checking_,
103 stream_initial_recv_window_size_,
104 initial_max_concurrent_streams_,
105 max_concurrent_streams_limit_,
110 Error error = new_session->InitializeWithSocket(
111 connection.Pass(), this, is_secure, certificate_error_code);
112 DCHECK_NE(error, ERR_IO_PENDING);
115 available_session->reset();
119 *available_session = new_session->GetWeakPtr();
120 sessions_.insert(new_session.release());
121 MapKeyToAvailableSession(key, *available_session);
124 NetLog::TYPE_SPDY_SESSION_POOL_IMPORTED_SESSION_FROM_SOCKET,
125 (*available_session)->net_log().source().ToEventParametersCallback());
127 // Look up the IP address for this session so that we can match
128 // future sessions (potentially to different domains) which can
129 // potentially be pooled with this one. Because GetPeerAddress()
130 // reports the proxy's address instead of the origin server, check
131 // to see if this is a direct connection.
132 if (enable_ip_pooling_ && key.proxy_server().is_direct()) {
134 if ((*available_session)->GetPeerAddress(&address) == OK)
135 aliases_[address] = key;
141 base::WeakPtr<SpdySession> SpdySessionPool::FindAvailableSession(
142 const SpdySessionKey& key,
143 const BoundNetLog& net_log) {
144 AvailableSessionMap::iterator it = LookupAvailableSessionByKey(key);
145 if (it != available_sessions_.end()) {
146 UMA_HISTOGRAM_ENUMERATION(
147 "Net.SpdySessionGet", FOUND_EXISTING, SPDY_SESSION_GET_MAX);
149 NetLog::TYPE_SPDY_SESSION_POOL_FOUND_EXISTING_SESSION,
150 it->second->net_log().source().ToEventParametersCallback());
154 if (!enable_ip_pooling_)
155 return base::WeakPtr<SpdySession>();
157 // Look up the key's from the resolver's cache.
158 net::HostResolver::RequestInfo resolve_info(key.host_port_pair());
159 AddressList addresses;
160 int rv = resolver_->ResolveFromCache(resolve_info, &addresses, net_log);
161 DCHECK_NE(rv, ERR_IO_PENDING);
163 return base::WeakPtr<SpdySession>();
165 // Check if we have a session through a domain alias.
166 for (AddressList::const_iterator address_it = addresses.begin();
167 address_it != addresses.end();
169 AliasMap::const_iterator alias_it = aliases_.find(*address_it);
170 if (alias_it == aliases_.end())
173 // We found an alias.
174 const SpdySessionKey& alias_key = alias_it->second;
176 // We can reuse this session only if the proxy and privacy
178 if (!(alias_key.proxy_server() == key.proxy_server()) ||
179 !(alias_key.privacy_mode() == key.privacy_mode()))
182 AvailableSessionMap::iterator available_session_it =
183 LookupAvailableSessionByKey(alias_key);
184 if (available_session_it == available_sessions_.end()) {
185 NOTREACHED(); // It shouldn't be in the aliases table if we can't get it!
189 const base::WeakPtr<SpdySession>& available_session =
190 available_session_it->second;
191 DCHECK(ContainsKey(sessions_, available_session.get()));
192 // If the session is a secure one, we need to verify that the
193 // server is authenticated to serve traffic for |host_port_proxy_pair| too.
194 if (!available_session->VerifyDomainAuthentication(
195 key.host_port_pair().host())) {
196 UMA_HISTOGRAM_ENUMERATION("Net.SpdyIPPoolDomainMatch", 0, 2);
200 UMA_HISTOGRAM_ENUMERATION("Net.SpdyIPPoolDomainMatch", 1, 2);
201 UMA_HISTOGRAM_ENUMERATION("Net.SpdySessionGet",
202 FOUND_EXISTING_FROM_IP_POOL,
203 SPDY_SESSION_GET_MAX);
205 NetLog::TYPE_SPDY_SESSION_POOL_FOUND_EXISTING_SESSION_FROM_IP_POOL,
206 available_session->net_log().source().ToEventParametersCallback());
207 // Add this session to the map so that we can find it next time.
208 MapKeyToAvailableSession(key, available_session);
209 available_session->AddPooledAlias(key);
210 return available_session;
213 return base::WeakPtr<SpdySession>();
216 void SpdySessionPool::MakeSessionUnavailable(
217 const base::WeakPtr<SpdySession>& available_session) {
218 UnmapKey(available_session->spdy_session_key());
219 RemoveAliases(available_session->spdy_session_key());
220 const std::set<SpdySessionKey>& aliases = available_session->pooled_aliases();
221 for (std::set<SpdySessionKey>::const_iterator it = aliases.begin();
222 it != aliases.end(); ++it) {
226 DCHECK(!IsSessionAvailable(available_session));
229 void SpdySessionPool::RemoveUnavailableSession(
230 const base::WeakPtr<SpdySession>& unavailable_session) {
231 DCHECK(!IsSessionAvailable(unavailable_session));
233 unavailable_session->net_log().AddEvent(
234 NetLog::TYPE_SPDY_SESSION_POOL_REMOVE_SESSION,
235 unavailable_session->net_log().source().ToEventParametersCallback());
237 SessionSet::iterator it = sessions_.find(unavailable_session.get());
238 CHECK(it != sessions_.end());
239 scoped_ptr<SpdySession> owned_session(*it);
243 // Make a copy of |sessions_| in the Close* functions below to avoid
244 // reentrancy problems. Since arbitrary functions get called by close
245 // handlers, it doesn't suffice to simply increment the iterator
248 void SpdySessionPool::CloseCurrentSessions(net::Error error) {
249 CloseCurrentSessionsHelper(error, "Closing current sessions.",
250 false /* idle_only */);
253 void SpdySessionPool::CloseCurrentIdleSessions() {
254 CloseCurrentSessionsHelper(ERR_ABORTED, "Closing idle sessions.",
255 true /* idle_only */);
258 void SpdySessionPool::CloseAllSessions() {
259 while (!sessions_.empty()) {
260 CloseCurrentSessionsHelper(ERR_ABORTED, "Closing all sessions.",
261 false /* idle_only */);
265 base::Value* SpdySessionPool::SpdySessionPoolInfoToValue() const {
266 base::ListValue* list = new base::ListValue();
268 for (AvailableSessionMap::const_iterator it = available_sessions_.begin();
269 it != available_sessions_.end(); ++it) {
270 // Only add the session if the key in the map matches the main
271 // host_port_proxy_pair (not an alias).
272 const SpdySessionKey& key = it->first;
273 const SpdySessionKey& session_key = it->second->spdy_session_key();
274 if (key.Equals(session_key))
275 list->Append(it->second->GetInfoAsValue());
280 void SpdySessionPool::OnIPAddressChanged() {
281 WeakSessionList current_sessions = GetCurrentSessions();
282 for (WeakSessionList::const_iterator it = current_sessions.begin();
283 it != current_sessions.end(); ++it) {
287 // For OSs that terminate TCP connections upon relevant network changes
288 // there is no need to explicitly close SpdySessions, instead simply mark
289 // the sessions as deprecated so they aren't reused.
290 #if defined(OS_ANDROID) || defined(OS_WIN) || defined(OS_IOS)
291 (*it)->MakeUnavailable();
293 (*it)->CloseSessionOnError(ERR_NETWORK_CHANGED,
294 "Closing current sessions.");
296 #endif // defined(OS_ANDROID) || defined(OS_WIN) || defined(OS_IOS)
297 DCHECK(!IsSessionAvailable(*it));
299 http_server_properties_->ClearAllSpdySettings();
302 void SpdySessionPool::OnSSLConfigChanged() {
303 CloseCurrentSessions(ERR_NETWORK_CHANGED);
306 void SpdySessionPool::OnCertAdded(const X509Certificate* cert) {
307 CloseCurrentSessions(ERR_CERT_DATABASE_CHANGED);
310 void SpdySessionPool::OnCACertChanged(const X509Certificate* cert) {
311 // Per wtc, we actually only need to CloseCurrentSessions when trust is
312 // reduced. CloseCurrentSessions now because OnCACertChanged does not
314 // See comments in ClientSocketPoolManager::OnCACertChanged.
315 CloseCurrentSessions(ERR_CERT_DATABASE_CHANGED);
318 bool SpdySessionPool::IsSessionAvailable(
319 const base::WeakPtr<SpdySession>& session) const {
320 for (AvailableSessionMap::const_iterator it = available_sessions_.begin();
321 it != available_sessions_.end(); ++it) {
322 if (it->second.get() == session.get())
328 const SpdySessionKey& SpdySessionPool::NormalizeListKey(
329 const SpdySessionKey& key) const {
330 if (!force_single_domain_)
333 static SpdySessionKey* single_domain_key = NULL;
334 if (!single_domain_key) {
335 HostPortPair single_domain = HostPortPair("singledomain.com", 80);
336 single_domain_key = new SpdySessionKey(single_domain,
337 ProxyServer::Direct(),
338 kPrivacyModeDisabled);
340 return *single_domain_key;
343 void SpdySessionPool::MapKeyToAvailableSession(
344 const SpdySessionKey& key,
345 const base::WeakPtr<SpdySession>& session) {
346 DCHECK(ContainsKey(sessions_, session.get()));
347 const SpdySessionKey& normalized_key = NormalizeListKey(key);
348 std::pair<AvailableSessionMap::iterator, bool> result =
349 available_sessions_.insert(std::make_pair(normalized_key, session));
350 CHECK(result.second);
353 SpdySessionPool::AvailableSessionMap::iterator
354 SpdySessionPool::LookupAvailableSessionByKey(
355 const SpdySessionKey& key) {
356 const SpdySessionKey& normalized_key = NormalizeListKey(key);
357 return available_sessions_.find(normalized_key);
360 void SpdySessionPool::UnmapKey(const SpdySessionKey& key) {
361 AvailableSessionMap::iterator it = LookupAvailableSessionByKey(key);
362 CHECK(it != available_sessions_.end());
363 available_sessions_.erase(it);
366 void SpdySessionPool::RemoveAliases(const SpdySessionKey& key) {
367 // Walk the aliases map, find references to this pair.
368 // TODO(mbelshe): Figure out if this is too expensive.
369 for (AliasMap::iterator it = aliases_.begin(); it != aliases_.end(); ) {
370 if (it->second.Equals(key)) {
371 AliasMap::iterator old_it = it;
373 aliases_.erase(old_it);
380 SpdySessionPool::WeakSessionList SpdySessionPool::GetCurrentSessions() const {
381 WeakSessionList current_sessions;
382 for (SessionSet::const_iterator it = sessions_.begin();
383 it != sessions_.end(); ++it) {
384 current_sessions.push_back((*it)->GetWeakPtr());
386 return current_sessions;
389 void SpdySessionPool::CloseCurrentSessionsHelper(
391 const std::string& description,
393 WeakSessionList current_sessions = GetCurrentSessions();
394 for (WeakSessionList::const_iterator it = current_sessions.begin();
395 it != current_sessions.end(); ++it) {
399 if (idle_only && (*it)->is_active())
402 (*it)->CloseSessionOnError(error, description);
403 DCHECK(!IsSessionAvailable(*it));