Roll src/third_party/skia 57a48a7:de7665a
[chromium-blink-merge.git] / net / spdy / spdy_session_pool.cc
blob8f0de903c6854ac4bf79218d0eec67067ac709b1
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 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),
48 resolver_(resolver),
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_|.
57 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),
64 trusted_spdy_proxy_(
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() {
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(
102 new SpdySession(key,
103 http_server_properties_,
104 transport_security_state_,
105 verify_domain_authentication_,
106 enable_sending_initial_data_,
107 enable_compression_,
108 enable_ping_based_connection_checking_,
109 default_protocol_,
110 stream_initial_recv_window_size_,
111 initial_max_concurrent_streams_,
112 max_concurrent_streams_limit_,
113 time_func_,
114 trusted_spdy_proxy_,
115 net_log.net_log()));
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);
124 net_log.AddEvent(
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()) {
134 IPEndPoint address;
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);
149 net_log.AddEvent(
150 NetLog::TYPE_HTTP2_SESSION_POOL_FOUND_EXISTING_SESSION,
151 it->second->net_log().source().ToEventParametersCallback());
152 return it->second;
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);
160 if (rv != OK)
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();
166 ++address_it) {
167 AliasMap::const_iterator alias_it = aliases_.find(*address_it);
168 if (alias_it == aliases_.end())
169 continue;
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
175 // settings match.
176 if (!(alias_key.proxy_server() == key.proxy_server()) ||
177 !(alias_key.privacy_mode() == key.privacy_mode()))
178 continue;
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!
184 continue;
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);
195 continue;
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);
202 net_log.AddEvent(
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) {
221 UnmapKey(*it);
222 RemoveAliases(*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);
238 sessions_.erase(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
244 // before closing.
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());
275 return list;
278 void SpdySessionPool::OnIPAddressChanged() {
279 WeakSessionList current_sessions = GetCurrentSessions();
280 for (WeakSessionList::const_iterator it = current_sessions.begin();
281 it != current_sessions.end(); ++it) {
282 if (!*it)
283 continue;
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();
293 #else
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
314 // tell us this.
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())
324 return true;
326 return false;
329 const SpdySessionKey& SpdySessionPool::NormalizeListKey(
330 const SpdySessionKey& key) const {
331 if (!force_single_domain_)
332 return key;
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;
373 ++it;
374 aliases_.erase(old_it);
375 } else {
376 ++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(
391 Error error,
392 const std::string& description,
393 bool idle_only) {
394 WeakSessionList current_sessions = GetCurrentSessions();
395 for (WeakSessionList::const_iterator it = current_sessions.begin();
396 it != current_sessions.end(); ++it) {
397 if (!*it)
398 continue;
400 if (idle_only && (*it)->is_active())
401 continue;
403 (*it)->CloseSessionOnError(error, description);
404 DCHECK(!IsSessionAvailable(*it));
408 } // namespace net