Updating trunk VERSION from 2139.0 to 2140.0
[chromium-blink-merge.git] / net / spdy / spdy_session_pool.cc
blobd8397855d94f2c1c0f07a7ce2857ed35dcd2818d
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"
16 namespace net {
18 namespace {
20 enum SpdySessionGetTypes {
21 CREATED_NEW = 0,
22 FOUND_EXISTING = 1,
23 FOUND_EXISTING_FROM_IP_POOL = 2,
24 IMPORTED_FROM_SOCKET = 3,
25 SPDY_SESSION_GET_MAX = 4
28 } // namespace
30 SpdySessionPool::SpdySessionPool(
31 HostResolver* resolver,
32 SSLConfigService* ssl_config_service,
33 const base::WeakPtr<HttpServerProperties>& http_server_properties,
34 TransportSecurityState* transport_security_state,
35 bool force_single_domain,
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 transport_security_state_(transport_security_state),
46 ssl_config_service_(ssl_config_service),
47 resolver_(resolver),
48 verify_domain_authentication_(true),
49 enable_sending_initial_data_(true),
50 force_single_domain_(force_single_domain),
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_(
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),
63 trusted_spdy_proxy_(
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() {
74 CloseAllSessions();
76 while (!sessions_.empty()) {
77 // Destroy sessions to enforce that lifetime is scoped to SpdySessionPool.
78 // Write callbacks queued upon session drain are not invoked.
79 RemoveUnavailableSession((*sessions_.begin())->GetWeakPtr());
82 if (ssl_config_service_.get())
83 ssl_config_service_->RemoveObserver(this);
84 NetworkChangeNotifier::RemoveIPAddressObserver(this);
85 CertDatabase::GetInstance()->RemoveObserver(this);
88 base::WeakPtr<SpdySession> SpdySessionPool::CreateAvailableSessionFromSocket(
89 const SpdySessionKey& key,
90 scoped_ptr<ClientSocketHandle> connection,
91 const BoundNetLog& net_log,
92 int certificate_error_code,
93 bool is_secure) {
94 DCHECK_GE(default_protocol_, kProtoSPDYMinimumVersion);
95 DCHECK_LE(default_protocol_, kProtoSPDYMaximumVersion);
97 UMA_HISTOGRAM_ENUMERATION(
98 "Net.SpdySessionGet", IMPORTED_FROM_SOCKET, SPDY_SESSION_GET_MAX);
100 scoped_ptr<SpdySession> new_session(
101 new SpdySession(key,
102 http_server_properties_,
103 transport_security_state_,
104 verify_domain_authentication_,
105 enable_sending_initial_data_,
106 enable_compression_,
107 enable_ping_based_connection_checking_,
108 default_protocol_,
109 stream_initial_recv_window_size_,
110 initial_max_concurrent_streams_,
111 max_concurrent_streams_limit_,
112 time_func_,
113 trusted_spdy_proxy_,
114 net_log.net_log()));
116 new_session->InitializeWithSocket(
117 connection.Pass(), this, is_secure, certificate_error_code);
119 base::WeakPtr<SpdySession> available_session = new_session->GetWeakPtr();
120 sessions_.insert(new_session.release());
121 MapKeyToAvailableSession(key, available_session);
123 net_log.AddEvent(
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 (key.proxy_server().is_direct()) {
133 IPEndPoint address;
134 if (available_session->GetPeerAddress(&address) == OK)
135 aliases_[address] = key;
138 return available_session;
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);
148 net_log.AddEvent(
149 NetLog::TYPE_SPDY_SESSION_POOL_FOUND_EXISTING_SESSION,
150 it->second->net_log().source().ToEventParametersCallback());
151 return it->second;
154 // Look up the key's from the resolver's cache.
155 net::HostResolver::RequestInfo resolve_info(key.host_port_pair());
156 AddressList addresses;
157 int rv = resolver_->ResolveFromCache(resolve_info, &addresses, net_log);
158 DCHECK_NE(rv, ERR_IO_PENDING);
159 if (rv != OK)
160 return base::WeakPtr<SpdySession>();
162 // Check if we have a session through a domain alias.
163 for (AddressList::const_iterator address_it = addresses.begin();
164 address_it != addresses.end();
165 ++address_it) {
166 AliasMap::const_iterator alias_it = aliases_.find(*address_it);
167 if (alias_it == aliases_.end())
168 continue;
170 // We found an alias.
171 const SpdySessionKey& alias_key = alias_it->second;
173 // We can reuse this session only if the proxy and privacy
174 // settings match.
175 if (!(alias_key.proxy_server() == key.proxy_server()) ||
176 !(alias_key.privacy_mode() == key.privacy_mode()))
177 continue;
179 AvailableSessionMap::iterator available_session_it =
180 LookupAvailableSessionByKey(alias_key);
181 if (available_session_it == available_sessions_.end()) {
182 NOTREACHED(); // It shouldn't be in the aliases table if we can't get it!
183 continue;
186 const base::WeakPtr<SpdySession>& available_session =
187 available_session_it->second;
188 DCHECK(ContainsKey(sessions_, available_session.get()));
189 // If the session is a secure one, we need to verify that the
190 // server is authenticated to serve traffic for |host_port_proxy_pair| too.
191 if (!available_session->VerifyDomainAuthentication(
192 key.host_port_pair().host())) {
193 UMA_HISTOGRAM_ENUMERATION("Net.SpdyIPPoolDomainMatch", 0, 2);
194 continue;
197 UMA_HISTOGRAM_ENUMERATION("Net.SpdyIPPoolDomainMatch", 1, 2);
198 UMA_HISTOGRAM_ENUMERATION("Net.SpdySessionGet",
199 FOUND_EXISTING_FROM_IP_POOL,
200 SPDY_SESSION_GET_MAX);
201 net_log.AddEvent(
202 NetLog::TYPE_SPDY_SESSION_POOL_FOUND_EXISTING_SESSION_FROM_IP_POOL,
203 available_session->net_log().source().ToEventParametersCallback());
204 // Add this session to the map so that we can find it next time.
205 MapKeyToAvailableSession(key, available_session);
206 available_session->AddPooledAlias(key);
207 return available_session;
210 return base::WeakPtr<SpdySession>();
213 void SpdySessionPool::MakeSessionUnavailable(
214 const base::WeakPtr<SpdySession>& available_session) {
215 UnmapKey(available_session->spdy_session_key());
216 RemoveAliases(available_session->spdy_session_key());
217 const std::set<SpdySessionKey>& aliases = available_session->pooled_aliases();
218 for (std::set<SpdySessionKey>::const_iterator it = aliases.begin();
219 it != aliases.end(); ++it) {
220 UnmapKey(*it);
221 RemoveAliases(*it);
223 DCHECK(!IsSessionAvailable(available_session));
226 void SpdySessionPool::RemoveUnavailableSession(
227 const base::WeakPtr<SpdySession>& unavailable_session) {
228 DCHECK(!IsSessionAvailable(unavailable_session));
230 unavailable_session->net_log().AddEvent(
231 NetLog::TYPE_SPDY_SESSION_POOL_REMOVE_SESSION,
232 unavailable_session->net_log().source().ToEventParametersCallback());
234 SessionSet::iterator it = sessions_.find(unavailable_session.get());
235 CHECK(it != sessions_.end());
236 scoped_ptr<SpdySession> owned_session(*it);
237 sessions_.erase(it);
240 // Make a copy of |sessions_| in the Close* functions below to avoid
241 // reentrancy problems. Since arbitrary functions get called by close
242 // handlers, it doesn't suffice to simply increment the iterator
243 // before closing.
245 void SpdySessionPool::CloseCurrentSessions(net::Error error) {
246 CloseCurrentSessionsHelper(error, "Closing current sessions.",
247 false /* idle_only */);
250 void SpdySessionPool::CloseCurrentIdleSessions() {
251 CloseCurrentSessionsHelper(ERR_ABORTED, "Closing idle sessions.",
252 true /* idle_only */);
255 void SpdySessionPool::CloseAllSessions() {
256 while (!available_sessions_.empty()) {
257 CloseCurrentSessionsHelper(ERR_ABORTED, "Closing all sessions.",
258 false /* idle_only */);
262 base::Value* SpdySessionPool::SpdySessionPoolInfoToValue() const {
263 base::ListValue* list = new base::ListValue();
265 for (AvailableSessionMap::const_iterator it = available_sessions_.begin();
266 it != available_sessions_.end(); ++it) {
267 // Only add the session if the key in the map matches the main
268 // host_port_proxy_pair (not an alias).
269 const SpdySessionKey& key = it->first;
270 const SpdySessionKey& session_key = it->second->spdy_session_key();
271 if (key.Equals(session_key))
272 list->Append(it->second->GetInfoAsValue());
274 return list;
277 void SpdySessionPool::OnIPAddressChanged() {
278 WeakSessionList current_sessions = GetCurrentSessions();
279 for (WeakSessionList::const_iterator it = current_sessions.begin();
280 it != current_sessions.end(); ++it) {
281 if (!*it)
282 continue;
284 // For OSs that terminate TCP connections upon relevant network changes,
285 // attempt to preserve active streams by marking all sessions as going
286 // away, rather than explicitly closing them. Streams may still fail due
287 // to a generated TCP reset.
288 #if defined(OS_ANDROID) || defined(OS_WIN) || defined(OS_IOS)
289 (*it)->MakeUnavailable();
290 (*it)->StartGoingAway(kLastStreamId, ERR_NETWORK_CHANGED);
291 (*it)->MaybeFinishGoingAway();
292 #else
293 (*it)->CloseSessionOnError(ERR_NETWORK_CHANGED,
294 "Closing current sessions.");
295 DCHECK((*it)->IsDraining());
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
313 // tell us this.
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())
323 return true;
325 return false;
328 const SpdySessionKey& SpdySessionPool::NormalizeListKey(
329 const SpdySessionKey& key) const {
330 if (!force_single_domain_)
331 return key;
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 PRIVACY_MODE_DISABLED);
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;
372 ++it;
373 aliases_.erase(old_it);
374 } else {
375 ++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(
390 Error error,
391 const std::string& description,
392 bool idle_only) {
393 WeakSessionList current_sessions = GetCurrentSessions();
394 for (WeakSessionList::const_iterator it = current_sessions.begin();
395 it != current_sessions.end(); ++it) {
396 if (!*it)
397 continue;
399 if (idle_only && (*it)->is_active())
400 continue;
402 (*it)->CloseSessionOnError(error, description);
403 DCHECK(!IsSessionAvailable(*it));
407 } // namespace net