We started redesigning GpuMemoryBuffer interface to handle multiple buffers [0].
[chromium-blink-merge.git] / net / spdy / spdy_session_pool.cc
blobb5496b98c88ee756d576153df3e5ab4ad6d641b6
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"
17 namespace net {
19 namespace {
21 enum SpdySessionGetTypes {
22 CREATED_NEW = 0,
23 FOUND_EXISTING = 1,
24 FOUND_EXISTING_FROM_IP_POOL = 2,
25 IMPORTED_FROM_SOCKET = 3,
26 SPDY_SESSION_GET_MAX = 4
29 } // namespace
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 session_max_recv_window_size,
41 size_t stream_max_recv_window_size,
42 size_t initial_max_concurrent_streams,
43 size_t max_concurrent_streams_limit,
44 SpdySessionPool::TimeFunc time_func,
45 const std::string& trusted_spdy_proxy)
46 : http_server_properties_(http_server_properties),
47 transport_security_state_(transport_security_state),
48 ssl_config_service_(ssl_config_service),
49 resolver_(resolver),
50 verify_domain_authentication_(true),
51 enable_sending_initial_data_(true),
52 force_single_domain_(force_single_domain),
53 enable_compression_(enable_compression),
54 enable_ping_based_connection_checking_(
55 enable_ping_based_connection_checking),
56 // TODO(akalin): Force callers to have a valid value of
57 // |default_protocol_|.
58 default_protocol_((default_protocol == kProtoUnknown) ? kProtoSPDY31
59 : default_protocol),
60 session_max_recv_window_size_(session_max_recv_window_size),
61 stream_max_recv_window_size_(stream_max_recv_window_size),
62 initial_max_concurrent_streams_(initial_max_concurrent_streams),
63 max_concurrent_streams_limit_(max_concurrent_streams_limit),
64 time_func_(time_func),
65 trusted_spdy_proxy_(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() {
75 CloseAllSessions();
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,
94 bool is_secure) {
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(new SpdySession(
102 key, http_server_properties_, transport_security_state_,
103 verify_domain_authentication_, enable_sending_initial_data_,
104 enable_compression_, enable_ping_based_connection_checking_,
105 default_protocol_, session_max_recv_window_size_,
106 stream_max_recv_window_size_, initial_max_concurrent_streams_,
107 max_concurrent_streams_limit_, time_func_, trusted_spdy_proxy_,
108 net_log.net_log()));
110 new_session->InitializeWithSocket(
111 connection.Pass(), this, is_secure, certificate_error_code);
113 base::WeakPtr<SpdySession> available_session = new_session->GetWeakPtr();
114 sessions_.insert(new_session.release());
115 MapKeyToAvailableSession(key, available_session);
117 net_log.AddEvent(
118 NetLog::TYPE_HTTP2_SESSION_POOL_IMPORTED_SESSION_FROM_SOCKET,
119 available_session->net_log().source().ToEventParametersCallback());
121 // Look up the IP address for this session so that we can match
122 // future sessions (potentially to different domains) which can
123 // potentially be pooled with this one. Because GetPeerAddress()
124 // reports the proxy's address instead of the origin server, check
125 // to see if this is a direct connection.
126 if (key.proxy_server().is_direct()) {
127 IPEndPoint address;
128 if (available_session->GetPeerAddress(&address) == OK)
129 aliases_[address] = key;
132 return available_session;
135 base::WeakPtr<SpdySession> SpdySessionPool::FindAvailableSession(
136 const SpdySessionKey& key,
137 const BoundNetLog& net_log) {
138 AvailableSessionMap::iterator it = LookupAvailableSessionByKey(key);
139 if (it != available_sessions_.end()) {
140 UMA_HISTOGRAM_ENUMERATION(
141 "Net.SpdySessionGet", FOUND_EXISTING, SPDY_SESSION_GET_MAX);
142 net_log.AddEvent(
143 NetLog::TYPE_HTTP2_SESSION_POOL_FOUND_EXISTING_SESSION,
144 it->second->net_log().source().ToEventParametersCallback());
145 return it->second;
148 // Look up the key's from the resolver's cache.
149 net::HostResolver::RequestInfo resolve_info(key.host_port_pair());
150 AddressList addresses;
151 int rv = resolver_->ResolveFromCache(resolve_info, &addresses, net_log);
152 DCHECK_NE(rv, ERR_IO_PENDING);
153 if (rv != OK)
154 return base::WeakPtr<SpdySession>();
156 // Check if we have a session through a domain alias.
157 for (AddressList::const_iterator address_it = addresses.begin();
158 address_it != addresses.end();
159 ++address_it) {
160 AliasMap::const_iterator alias_it = aliases_.find(*address_it);
161 if (alias_it == aliases_.end())
162 continue;
164 // We found an alias.
165 const SpdySessionKey& alias_key = alias_it->second;
167 // We can reuse this session only if the proxy and privacy
168 // settings match.
169 if (!(alias_key.proxy_server() == key.proxy_server()) ||
170 !(alias_key.privacy_mode() == key.privacy_mode()))
171 continue;
173 AvailableSessionMap::iterator available_session_it =
174 LookupAvailableSessionByKey(alias_key);
175 if (available_session_it == available_sessions_.end()) {
176 NOTREACHED(); // It shouldn't be in the aliases table if we can't get it!
177 continue;
180 const base::WeakPtr<SpdySession>& available_session =
181 available_session_it->second;
182 DCHECK(ContainsKey(sessions_, available_session.get()));
183 // If the session is a secure one, we need to verify that the
184 // server is authenticated to serve traffic for |host_port_proxy_pair| too.
185 if (!available_session->VerifyDomainAuthentication(
186 key.host_port_pair().host())) {
187 UMA_HISTOGRAM_ENUMERATION("Net.SpdyIPPoolDomainMatch", 0, 2);
188 continue;
191 UMA_HISTOGRAM_ENUMERATION("Net.SpdyIPPoolDomainMatch", 1, 2);
192 UMA_HISTOGRAM_ENUMERATION("Net.SpdySessionGet",
193 FOUND_EXISTING_FROM_IP_POOL,
194 SPDY_SESSION_GET_MAX);
195 net_log.AddEvent(
196 NetLog::TYPE_HTTP2_SESSION_POOL_FOUND_EXISTING_SESSION_FROM_IP_POOL,
197 available_session->net_log().source().ToEventParametersCallback());
198 // Add this session to the map so that we can find it next time.
199 MapKeyToAvailableSession(key, available_session);
200 available_session->AddPooledAlias(key);
201 return available_session;
204 return base::WeakPtr<SpdySession>();
207 void SpdySessionPool::MakeSessionUnavailable(
208 const base::WeakPtr<SpdySession>& available_session) {
209 UnmapKey(available_session->spdy_session_key());
210 RemoveAliases(available_session->spdy_session_key());
211 const std::set<SpdySessionKey>& aliases = available_session->pooled_aliases();
212 for (std::set<SpdySessionKey>::const_iterator it = aliases.begin();
213 it != aliases.end(); ++it) {
214 UnmapKey(*it);
215 RemoveAliases(*it);
217 DCHECK(!IsSessionAvailable(available_session));
220 void SpdySessionPool::RemoveUnavailableSession(
221 const base::WeakPtr<SpdySession>& unavailable_session) {
222 DCHECK(!IsSessionAvailable(unavailable_session));
224 unavailable_session->net_log().AddEvent(
225 NetLog::TYPE_HTTP2_SESSION_POOL_REMOVE_SESSION,
226 unavailable_session->net_log().source().ToEventParametersCallback());
228 SessionSet::iterator it = sessions_.find(unavailable_session.get());
229 CHECK(it != sessions_.end());
230 scoped_ptr<SpdySession> owned_session(*it);
231 sessions_.erase(it);
234 // Make a copy of |sessions_| in the Close* functions below to avoid
235 // reentrancy problems. Since arbitrary functions get called by close
236 // handlers, it doesn't suffice to simply increment the iterator
237 // before closing.
239 void SpdySessionPool::CloseCurrentSessions(net::Error error) {
240 CloseCurrentSessionsHelper(error, "Closing current sessions.",
241 false /* idle_only */);
244 void SpdySessionPool::CloseCurrentIdleSessions() {
245 CloseCurrentSessionsHelper(ERR_ABORTED, "Closing idle sessions.",
246 true /* idle_only */);
249 void SpdySessionPool::CloseAllSessions() {
250 while (!available_sessions_.empty()) {
251 CloseCurrentSessionsHelper(ERR_ABORTED, "Closing all sessions.",
252 false /* idle_only */);
256 base::Value* SpdySessionPool::SpdySessionPoolInfoToValue() const {
257 base::ListValue* list = new base::ListValue();
259 for (AvailableSessionMap::const_iterator it = available_sessions_.begin();
260 it != available_sessions_.end(); ++it) {
261 // Only add the session if the key in the map matches the main
262 // host_port_proxy_pair (not an alias).
263 const SpdySessionKey& key = it->first;
264 const SpdySessionKey& session_key = it->second->spdy_session_key();
265 if (key.Equals(session_key))
266 list->Append(it->second->GetInfoAsValue());
268 return list;
271 void SpdySessionPool::OnIPAddressChanged() {
272 WeakSessionList current_sessions = GetCurrentSessions();
273 for (WeakSessionList::const_iterator it = current_sessions.begin();
274 it != current_sessions.end(); ++it) {
275 if (!*it)
276 continue;
278 // For OSs that terminate TCP connections upon relevant network changes,
279 // attempt to preserve active streams by marking all sessions as going
280 // away, rather than explicitly closing them. Streams may still fail due
281 // to a generated TCP reset.
282 #if defined(OS_ANDROID) || defined(OS_WIN) || defined(OS_IOS)
283 (*it)->MakeUnavailable();
284 (*it)->StartGoingAway(kLastStreamId, ERR_NETWORK_CHANGED);
285 (*it)->MaybeFinishGoingAway();
286 #else
287 (*it)->CloseSessionOnError(ERR_NETWORK_CHANGED,
288 "Closing current sessions.");
289 DCHECK((*it)->IsDraining());
290 #endif // defined(OS_ANDROID) || defined(OS_WIN) || defined(OS_IOS)
291 DCHECK(!IsSessionAvailable(*it));
293 http_server_properties_->ClearAllSpdySettings();
296 void SpdySessionPool::OnSSLConfigChanged() {
297 CloseCurrentSessions(ERR_NETWORK_CHANGED);
300 void SpdySessionPool::OnCertAdded(const X509Certificate* cert) {
301 CloseCurrentSessions(ERR_CERT_DATABASE_CHANGED);
304 void SpdySessionPool::OnCACertChanged(const X509Certificate* cert) {
305 // Per wtc, we actually only need to CloseCurrentSessions when trust is
306 // reduced. CloseCurrentSessions now because OnCACertChanged does not
307 // tell us this.
308 // See comments in ClientSocketPoolManager::OnCACertChanged.
309 CloseCurrentSessions(ERR_CERT_DATABASE_CHANGED);
312 bool SpdySessionPool::IsSessionAvailable(
313 const base::WeakPtr<SpdySession>& session) const {
314 for (AvailableSessionMap::const_iterator it = available_sessions_.begin();
315 it != available_sessions_.end(); ++it) {
316 if (it->second.get() == session.get())
317 return true;
319 return false;
322 const SpdySessionKey& SpdySessionPool::NormalizeListKey(
323 const SpdySessionKey& key) const {
324 if (!force_single_domain_)
325 return key;
327 static SpdySessionKey* single_domain_key = NULL;
328 if (!single_domain_key) {
329 HostPortPair single_domain = HostPortPair("singledomain.com", 80);
330 single_domain_key = new SpdySessionKey(single_domain,
331 ProxyServer::Direct(),
332 PRIVACY_MODE_DISABLED);
334 return *single_domain_key;
337 void SpdySessionPool::MapKeyToAvailableSession(
338 const SpdySessionKey& key,
339 const base::WeakPtr<SpdySession>& session) {
340 DCHECK(ContainsKey(sessions_, session.get()));
341 const SpdySessionKey& normalized_key = NormalizeListKey(key);
342 std::pair<AvailableSessionMap::iterator, bool> result =
343 available_sessions_.insert(std::make_pair(normalized_key, session));
344 CHECK(result.second);
347 SpdySessionPool::AvailableSessionMap::iterator
348 SpdySessionPool::LookupAvailableSessionByKey(
349 const SpdySessionKey& key) {
350 const SpdySessionKey& normalized_key = NormalizeListKey(key);
351 return available_sessions_.find(normalized_key);
354 void SpdySessionPool::UnmapKey(const SpdySessionKey& key) {
355 AvailableSessionMap::iterator it = LookupAvailableSessionByKey(key);
356 CHECK(it != available_sessions_.end());
357 available_sessions_.erase(it);
360 void SpdySessionPool::RemoveAliases(const SpdySessionKey& key) {
361 // Walk the aliases map, find references to this pair.
362 // TODO(mbelshe): Figure out if this is too expensive.
363 for (AliasMap::iterator it = aliases_.begin(); it != aliases_.end(); ) {
364 if (it->second.Equals(key)) {
365 AliasMap::iterator old_it = it;
366 ++it;
367 aliases_.erase(old_it);
368 } else {
369 ++it;
374 SpdySessionPool::WeakSessionList SpdySessionPool::GetCurrentSessions() const {
375 WeakSessionList current_sessions;
376 for (SessionSet::const_iterator it = sessions_.begin();
377 it != sessions_.end(); ++it) {
378 current_sessions.push_back((*it)->GetWeakPtr());
380 return current_sessions;
383 void SpdySessionPool::CloseCurrentSessionsHelper(
384 Error error,
385 const std::string& description,
386 bool idle_only) {
387 WeakSessionList current_sessions = GetCurrentSessions();
388 for (WeakSessionList::const_iterator it = current_sessions.begin();
389 it != current_sessions.end(); ++it) {
390 if (!*it)
391 continue;
393 if (idle_only && (*it)->is_active())
394 continue;
396 (*it)->CloseSessionOnError(error, description);
397 DCHECK(!IsSessionAvailable(*it));
401 } // namespace net