Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / net / spdy / spdy_session_pool.cc
blobeef0f9bfc4897a2ab8dedf1d2501b2f58f5f873c
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_macros.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 enable_compression,
37 bool enable_ping_based_connection_checking,
38 NextProto default_protocol,
39 size_t session_max_recv_window_size,
40 size_t stream_max_recv_window_size,
41 size_t initial_max_concurrent_streams,
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 enable_compression_(enable_compression),
51 enable_ping_based_connection_checking_(
52 enable_ping_based_connection_checking),
53 // TODO(akalin): Force callers to have a valid value of
54 // |default_protocol_|.
55 default_protocol_((default_protocol == kProtoUnknown) ? kProtoSPDY31
56 : default_protocol),
57 session_max_recv_window_size_(session_max_recv_window_size),
58 stream_max_recv_window_size_(stream_max_recv_window_size),
59 initial_max_concurrent_streams_(initial_max_concurrent_streams),
60 time_func_(time_func),
61 trusted_spdy_proxy_(HostPortPair::FromString(trusted_spdy_proxy)) {
62 DCHECK(default_protocol_ >= kProtoSPDYMinimumVersion &&
63 default_protocol_ <= kProtoSPDYMaximumVersion);
64 NetworkChangeNotifier::AddIPAddressObserver(this);
65 if (ssl_config_service_.get())
66 ssl_config_service_->AddObserver(this);
67 CertDatabase::GetInstance()->AddObserver(this);
70 SpdySessionPool::~SpdySessionPool() {
71 CloseAllSessions();
73 while (!sessions_.empty()) {
74 // Destroy sessions to enforce that lifetime is scoped to SpdySessionPool.
75 // Write callbacks queued upon session drain are not invoked.
76 RemoveUnavailableSession((*sessions_.begin())->GetWeakPtr());
79 if (ssl_config_service_.get())
80 ssl_config_service_->RemoveObserver(this);
81 NetworkChangeNotifier::RemoveIPAddressObserver(this);
82 CertDatabase::GetInstance()->RemoveObserver(this);
85 base::WeakPtr<SpdySession> SpdySessionPool::CreateAvailableSessionFromSocket(
86 const SpdySessionKey& key,
87 scoped_ptr<ClientSocketHandle> connection,
88 const BoundNetLog& net_log,
89 int certificate_error_code,
90 bool is_secure) {
91 DCHECK_GE(default_protocol_, kProtoSPDYMinimumVersion);
92 DCHECK_LE(default_protocol_, kProtoSPDYMaximumVersion);
94 UMA_HISTOGRAM_ENUMERATION(
95 "Net.SpdySessionGet", IMPORTED_FROM_SOCKET, SPDY_SESSION_GET_MAX);
97 scoped_ptr<SpdySession> new_session(new SpdySession(
98 key, http_server_properties_, transport_security_state_,
99 verify_domain_authentication_, enable_sending_initial_data_,
100 enable_compression_, enable_ping_based_connection_checking_,
101 default_protocol_, session_max_recv_window_size_,
102 stream_max_recv_window_size_, initial_max_concurrent_streams_, time_func_,
103 trusted_spdy_proxy_, net_log.net_log()));
105 new_session->InitializeWithSocket(
106 connection.Pass(), this, is_secure, certificate_error_code);
108 base::WeakPtr<SpdySession> available_session = new_session->GetWeakPtr();
109 sessions_.insert(new_session.release());
110 MapKeyToAvailableSession(key, available_session);
112 net_log.AddEvent(
113 NetLog::TYPE_HTTP2_SESSION_POOL_IMPORTED_SESSION_FROM_SOCKET,
114 available_session->net_log().source().ToEventParametersCallback());
116 // Look up the IP address for this session so that we can match
117 // future sessions (potentially to different domains) which can
118 // potentially be pooled with this one. Because GetPeerAddress()
119 // reports the proxy's address instead of the origin server, check
120 // to see if this is a direct connection.
121 if (key.proxy_server().is_direct()) {
122 IPEndPoint address;
123 if (available_session->GetPeerAddress(&address) == OK)
124 aliases_[address] = key;
127 return available_session;
130 base::WeakPtr<SpdySession> SpdySessionPool::FindAvailableSession(
131 const SpdySessionKey& key,
132 const BoundNetLog& net_log) {
133 AvailableSessionMap::iterator it = LookupAvailableSessionByKey(key);
134 if (it != available_sessions_.end()) {
135 UMA_HISTOGRAM_ENUMERATION(
136 "Net.SpdySessionGet", FOUND_EXISTING, SPDY_SESSION_GET_MAX);
137 net_log.AddEvent(
138 NetLog::TYPE_HTTP2_SESSION_POOL_FOUND_EXISTING_SESSION,
139 it->second->net_log().source().ToEventParametersCallback());
140 return it->second;
143 // Look up the key's from the resolver's cache.
144 HostResolver::RequestInfo resolve_info(key.host_port_pair());
145 AddressList addresses;
146 int rv = resolver_->ResolveFromCache(resolve_info, &addresses, net_log);
147 DCHECK_NE(rv, ERR_IO_PENDING);
148 if (rv != OK)
149 return base::WeakPtr<SpdySession>();
151 // Check if we have a session through a domain alias.
152 for (AddressList::const_iterator address_it = addresses.begin();
153 address_it != addresses.end();
154 ++address_it) {
155 AliasMap::const_iterator alias_it = aliases_.find(*address_it);
156 if (alias_it == aliases_.end())
157 continue;
159 // We found an alias.
160 const SpdySessionKey& alias_key = alias_it->second;
162 // We can reuse this session only if the proxy and privacy
163 // settings match.
164 if (!(alias_key.proxy_server() == key.proxy_server()) ||
165 !(alias_key.privacy_mode() == key.privacy_mode()))
166 continue;
168 AvailableSessionMap::iterator available_session_it =
169 LookupAvailableSessionByKey(alias_key);
170 if (available_session_it == available_sessions_.end()) {
171 NOTREACHED(); // It shouldn't be in the aliases table if we can't get it!
172 continue;
175 const base::WeakPtr<SpdySession>& available_session =
176 available_session_it->second;
177 DCHECK(ContainsKey(sessions_, available_session.get()));
178 // If the session is a secure one, we need to verify that the
179 // server is authenticated to serve traffic for |host_port_proxy_pair| too.
180 if (!available_session->VerifyDomainAuthentication(
181 key.host_port_pair().host())) {
182 UMA_HISTOGRAM_ENUMERATION("Net.SpdyIPPoolDomainMatch", 0, 2);
183 continue;
186 UMA_HISTOGRAM_ENUMERATION("Net.SpdyIPPoolDomainMatch", 1, 2);
187 UMA_HISTOGRAM_ENUMERATION("Net.SpdySessionGet",
188 FOUND_EXISTING_FROM_IP_POOL,
189 SPDY_SESSION_GET_MAX);
190 net_log.AddEvent(
191 NetLog::TYPE_HTTP2_SESSION_POOL_FOUND_EXISTING_SESSION_FROM_IP_POOL,
192 available_session->net_log().source().ToEventParametersCallback());
193 // Add this session to the map so that we can find it next time.
194 MapKeyToAvailableSession(key, available_session);
195 available_session->AddPooledAlias(key);
196 return available_session;
199 return base::WeakPtr<SpdySession>();
202 void SpdySessionPool::MakeSessionUnavailable(
203 const base::WeakPtr<SpdySession>& available_session) {
204 UnmapKey(available_session->spdy_session_key());
205 RemoveAliases(available_session->spdy_session_key());
206 const std::set<SpdySessionKey>& aliases = available_session->pooled_aliases();
207 for (std::set<SpdySessionKey>::const_iterator it = aliases.begin();
208 it != aliases.end(); ++it) {
209 UnmapKey(*it);
210 RemoveAliases(*it);
212 DCHECK(!IsSessionAvailable(available_session));
215 void SpdySessionPool::RemoveUnavailableSession(
216 const base::WeakPtr<SpdySession>& unavailable_session) {
217 DCHECK(!IsSessionAvailable(unavailable_session));
219 unavailable_session->net_log().AddEvent(
220 NetLog::TYPE_HTTP2_SESSION_POOL_REMOVE_SESSION,
221 unavailable_session->net_log().source().ToEventParametersCallback());
223 SessionSet::iterator it = sessions_.find(unavailable_session.get());
224 CHECK(it != sessions_.end());
225 scoped_ptr<SpdySession> owned_session(*it);
226 sessions_.erase(it);
229 // Make a copy of |sessions_| in the Close* functions below to avoid
230 // reentrancy problems. Since arbitrary functions get called by close
231 // handlers, it doesn't suffice to simply increment the iterator
232 // before closing.
234 void SpdySessionPool::CloseCurrentSessions(Error error) {
235 CloseCurrentSessionsHelper(error, "Closing current sessions.",
236 false /* idle_only */);
239 void SpdySessionPool::CloseCurrentIdleSessions() {
240 CloseCurrentSessionsHelper(ERR_ABORTED, "Closing idle sessions.",
241 true /* idle_only */);
244 void SpdySessionPool::CloseAllSessions() {
245 while (!available_sessions_.empty()) {
246 CloseCurrentSessionsHelper(ERR_ABORTED, "Closing all sessions.",
247 false /* idle_only */);
251 scoped_ptr<base::Value> SpdySessionPool::SpdySessionPoolInfoToValue() const {
252 scoped_ptr<base::ListValue> list(new base::ListValue());
254 for (AvailableSessionMap::const_iterator it = available_sessions_.begin();
255 it != available_sessions_.end(); ++it) {
256 // Only add the session if the key in the map matches the main
257 // host_port_proxy_pair (not an alias).
258 const SpdySessionKey& key = it->first;
259 const SpdySessionKey& session_key = it->second->spdy_session_key();
260 if (key.Equals(session_key))
261 list->Append(it->second->GetInfoAsValue());
263 return list.Pass();
266 void SpdySessionPool::OnIPAddressChanged() {
267 WeakSessionList current_sessions = GetCurrentSessions();
268 for (WeakSessionList::const_iterator it = current_sessions.begin();
269 it != current_sessions.end(); ++it) {
270 if (!*it)
271 continue;
273 // For OSs that terminate TCP connections upon relevant network changes,
274 // attempt to preserve active streams by marking all sessions as going
275 // away, rather than explicitly closing them. Streams may still fail due
276 // to a generated TCP reset.
277 #if defined(OS_ANDROID) || defined(OS_WIN) || defined(OS_IOS)
278 (*it)->MakeUnavailable();
279 (*it)->StartGoingAway(kLastStreamId, ERR_NETWORK_CHANGED);
280 (*it)->MaybeFinishGoingAway();
281 #else
282 (*it)->CloseSessionOnError(ERR_NETWORK_CHANGED,
283 "Closing current sessions.");
284 DCHECK((*it)->IsDraining());
285 #endif // defined(OS_ANDROID) || defined(OS_WIN) || defined(OS_IOS)
286 DCHECK(!IsSessionAvailable(*it));
288 http_server_properties_->ClearAllSpdySettings();
291 void SpdySessionPool::OnSSLConfigChanged() {
292 CloseCurrentSessions(ERR_NETWORK_CHANGED);
295 void SpdySessionPool::OnCertAdded(const X509Certificate* cert) {
296 CloseCurrentSessions(ERR_CERT_DATABASE_CHANGED);
299 void SpdySessionPool::OnCACertChanged(const X509Certificate* cert) {
300 // Per wtc, we actually only need to CloseCurrentSessions when trust is
301 // reduced. CloseCurrentSessions now because OnCACertChanged does not
302 // tell us this.
303 // See comments in ClientSocketPoolManager::OnCACertChanged.
304 CloseCurrentSessions(ERR_CERT_DATABASE_CHANGED);
307 bool SpdySessionPool::IsSessionAvailable(
308 const base::WeakPtr<SpdySession>& session) const {
309 for (AvailableSessionMap::const_iterator it = available_sessions_.begin();
310 it != available_sessions_.end(); ++it) {
311 if (it->second.get() == session.get())
312 return true;
314 return false;
317 void SpdySessionPool::MapKeyToAvailableSession(
318 const SpdySessionKey& key,
319 const base::WeakPtr<SpdySession>& session) {
320 DCHECK(ContainsKey(sessions_, session.get()));
321 std::pair<AvailableSessionMap::iterator, bool> result =
322 available_sessions_.insert(std::make_pair(key, session));
323 CHECK(result.second);
326 SpdySessionPool::AvailableSessionMap::iterator
327 SpdySessionPool::LookupAvailableSessionByKey(
328 const SpdySessionKey& key) {
329 return available_sessions_.find(key);
332 void SpdySessionPool::UnmapKey(const SpdySessionKey& key) {
333 AvailableSessionMap::iterator it = LookupAvailableSessionByKey(key);
334 CHECK(it != available_sessions_.end());
335 available_sessions_.erase(it);
338 void SpdySessionPool::RemoveAliases(const SpdySessionKey& key) {
339 // Walk the aliases map, find references to this pair.
340 // TODO(mbelshe): Figure out if this is too expensive.
341 for (AliasMap::iterator it = aliases_.begin(); it != aliases_.end(); ) {
342 if (it->second.Equals(key)) {
343 AliasMap::iterator old_it = it;
344 ++it;
345 aliases_.erase(old_it);
346 } else {
347 ++it;
352 SpdySessionPool::WeakSessionList SpdySessionPool::GetCurrentSessions() const {
353 WeakSessionList current_sessions;
354 for (SessionSet::const_iterator it = sessions_.begin();
355 it != sessions_.end(); ++it) {
356 current_sessions.push_back((*it)->GetWeakPtr());
358 return current_sessions;
361 void SpdySessionPool::CloseCurrentSessionsHelper(
362 Error error,
363 const std::string& description,
364 bool idle_only) {
365 WeakSessionList current_sessions = GetCurrentSessions();
366 for (WeakSessionList::const_iterator it = current_sessions.begin();
367 it != current_sessions.end(); ++it) {
368 if (!*it)
369 continue;
371 if (idle_only && (*it)->is_active())
372 continue;
374 (*it)->CloseSessionOnError(error, description);
375 DCHECK(!IsSessionAvailable(*it));
379 } // namespace net