Using pre-existing constants instead of hard-coding
[chromium-blink-merge.git] / net / spdy / spdy_session_pool.cc
blob4747f0595039e57a99203dece4302d321d9d2104
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 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),
45 resolver_(resolver),
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_|.
54 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),
61 trusted_spdy_proxy_(
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() {
72 CloseAllSessions();
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,
85 bool is_secure) {
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(
93 new SpdySession(key,
94 http_server_properties_,
95 verify_domain_authentication_,
96 enable_sending_initial_data_,
97 enable_compression_,
98 enable_ping_based_connection_checking_,
99 default_protocol_,
100 stream_initial_recv_window_size_,
101 initial_max_concurrent_streams_,
102 max_concurrent_streams_limit_,
103 time_func_,
104 trusted_spdy_proxy_,
105 net_log.net_log()));
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);
114 net_log.AddEvent(
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()) {
124 IPEndPoint address;
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);
139 net_log.AddEvent(
140 NetLog::TYPE_SPDY_SESSION_POOL_FOUND_EXISTING_SESSION,
141 it->second->net_log().source().ToEventParametersCallback());
142 return it->second;
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);
150 if (rv != OK)
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();
156 ++address_it) {
157 AliasMap::const_iterator alias_it = aliases_.find(*address_it);
158 if (alias_it == aliases_.end())
159 continue;
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
165 // settings match.
166 if (!(alias_key.proxy_server() == key.proxy_server()) ||
167 !(alias_key.privacy_mode() == key.privacy_mode()))
168 continue;
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!
174 continue;
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);
185 continue;
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);
192 net_log.AddEvent(
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) {
211 UnmapKey(*it);
212 RemoveAliases(*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);
228 sessions_.erase(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
234 // before closing.
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());
265 return list;
268 void SpdySessionPool::OnIPAddressChanged() {
269 WeakSessionList current_sessions = GetCurrentSessions();
270 for (WeakSessionList::const_iterator it = current_sessions.begin();
271 it != current_sessions.end(); ++it) {
272 if (!*it)
273 continue;
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();
280 #else
281 (*it)->CloseSessionOnError(ERR_NETWORK_CHANGED,
282 "Closing current sessions.");
283 DCHECK(!*it);
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
301 // tell us this.
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())
311 return true;
313 return false;
316 const SpdySessionKey& SpdySessionPool::NormalizeListKey(
317 const SpdySessionKey& key) const {
318 if (!force_single_domain_)
319 return key;
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;
360 ++it;
361 aliases_.erase(old_it);
362 } else {
363 ++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(
378 Error error,
379 const std::string& description,
380 bool idle_only) {
381 WeakSessionList current_sessions = GetCurrentSessions();
382 for (WeakSessionList::const_iterator it = current_sessions.begin();
383 it != current_sessions.end(); ++it) {
384 if (!*it)
385 continue;
387 if (idle_only && (*it)->is_active())
388 continue;
390 (*it)->CloseSessionOnError(error, description);
391 DCHECK(!IsSessionAvailable(*it));
392 DCHECK(!*it);
396 } // namespace net