Cast: Skip receiver log messages with time delta that can't be encoded.
[chromium-blink-merge.git] / net / spdy / spdy_session_pool.cc
blob093db1eb9e574812bd773829397e89e8a748a4e6
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 net::Error SpdySessionPool::CreateAvailableSessionFromSocket(
81 const SpdySessionKey& key,
82 scoped_ptr<ClientSocketHandle> connection,
83 const BoundNetLog& net_log,
84 int certificate_error_code,
85 base::WeakPtr<SpdySession>* available_session,
86 bool is_secure) {
87 DCHECK_GE(default_protocol_, kProtoSPDYMinimumVersion);
88 DCHECK_LE(default_protocol_, kProtoSPDYMaximumVersion);
90 UMA_HISTOGRAM_ENUMERATION(
91 "Net.SpdySessionGet", IMPORTED_FROM_SOCKET, SPDY_SESSION_GET_MAX);
93 scoped_ptr<SpdySession> new_session(
94 new SpdySession(key,
95 http_server_properties_,
96 verify_domain_authentication_,
97 enable_sending_initial_data_,
98 enable_compression_,
99 enable_ping_based_connection_checking_,
100 default_protocol_,
101 stream_initial_recv_window_size_,
102 initial_max_concurrent_streams_,
103 max_concurrent_streams_limit_,
104 time_func_,
105 trusted_spdy_proxy_,
106 net_log.net_log()));
108 Error error = new_session->InitializeWithSocket(
109 connection.Pass(), this, is_secure, certificate_error_code);
110 DCHECK_NE(error, ERR_IO_PENDING);
112 if (error != OK) {
113 available_session->reset();
114 return error;
117 *available_session = new_session->GetWeakPtr();
118 sessions_.insert(new_session.release());
119 MapKeyToAvailableSession(key, *available_session);
121 net_log.AddEvent(
122 NetLog::TYPE_SPDY_SESSION_POOL_IMPORTED_SESSION_FROM_SOCKET,
123 (*available_session)->net_log().source().ToEventParametersCallback());
125 // Look up the IP address for this session so that we can match
126 // future sessions (potentially to different domains) which can
127 // potentially be pooled with this one. Because GetPeerAddress()
128 // reports the proxy's address instead of the origin server, check
129 // to see if this is a direct connection.
130 if (key.proxy_server().is_direct()) {
131 IPEndPoint address;
132 if ((*available_session)->GetPeerAddress(&address) == OK)
133 aliases_[address] = key;
136 return error;
139 base::WeakPtr<SpdySession> SpdySessionPool::FindAvailableSession(
140 const SpdySessionKey& key,
141 const BoundNetLog& net_log) {
142 AvailableSessionMap::iterator it = LookupAvailableSessionByKey(key);
143 if (it != available_sessions_.end()) {
144 UMA_HISTOGRAM_ENUMERATION(
145 "Net.SpdySessionGet", FOUND_EXISTING, SPDY_SESSION_GET_MAX);
146 net_log.AddEvent(
147 NetLog::TYPE_SPDY_SESSION_POOL_FOUND_EXISTING_SESSION,
148 it->second->net_log().source().ToEventParametersCallback());
149 return it->second;
152 // Look up the key's from the resolver's cache.
153 net::HostResolver::RequestInfo resolve_info(key.host_port_pair());
154 AddressList addresses;
155 int rv = resolver_->ResolveFromCache(resolve_info, &addresses, net_log);
156 DCHECK_NE(rv, ERR_IO_PENDING);
157 if (rv != OK)
158 return base::WeakPtr<SpdySession>();
160 // Check if we have a session through a domain alias.
161 for (AddressList::const_iterator address_it = addresses.begin();
162 address_it != addresses.end();
163 ++address_it) {
164 AliasMap::const_iterator alias_it = aliases_.find(*address_it);
165 if (alias_it == aliases_.end())
166 continue;
168 // We found an alias.
169 const SpdySessionKey& alias_key = alias_it->second;
171 // We can reuse this session only if the proxy and privacy
172 // settings match.
173 if (!(alias_key.proxy_server() == key.proxy_server()) ||
174 !(alias_key.privacy_mode() == key.privacy_mode()))
175 continue;
177 AvailableSessionMap::iterator available_session_it =
178 LookupAvailableSessionByKey(alias_key);
179 if (available_session_it == available_sessions_.end()) {
180 NOTREACHED(); // It shouldn't be in the aliases table if we can't get it!
181 continue;
184 const base::WeakPtr<SpdySession>& available_session =
185 available_session_it->second;
186 DCHECK(ContainsKey(sessions_, available_session.get()));
187 // If the session is a secure one, we need to verify that the
188 // server is authenticated to serve traffic for |host_port_proxy_pair| too.
189 if (!available_session->VerifyDomainAuthentication(
190 key.host_port_pair().host())) {
191 UMA_HISTOGRAM_ENUMERATION("Net.SpdyIPPoolDomainMatch", 0, 2);
192 continue;
195 UMA_HISTOGRAM_ENUMERATION("Net.SpdyIPPoolDomainMatch", 1, 2);
196 UMA_HISTOGRAM_ENUMERATION("Net.SpdySessionGet",
197 FOUND_EXISTING_FROM_IP_POOL,
198 SPDY_SESSION_GET_MAX);
199 net_log.AddEvent(
200 NetLog::TYPE_SPDY_SESSION_POOL_FOUND_EXISTING_SESSION_FROM_IP_POOL,
201 available_session->net_log().source().ToEventParametersCallback());
202 // Add this session to the map so that we can find it next time.
203 MapKeyToAvailableSession(key, available_session);
204 available_session->AddPooledAlias(key);
205 return available_session;
208 return base::WeakPtr<SpdySession>();
211 void SpdySessionPool::MakeSessionUnavailable(
212 const base::WeakPtr<SpdySession>& available_session) {
213 UnmapKey(available_session->spdy_session_key());
214 RemoveAliases(available_session->spdy_session_key());
215 const std::set<SpdySessionKey>& aliases = available_session->pooled_aliases();
216 for (std::set<SpdySessionKey>::const_iterator it = aliases.begin();
217 it != aliases.end(); ++it) {
218 UnmapKey(*it);
219 RemoveAliases(*it);
221 DCHECK(!IsSessionAvailable(available_session));
224 void SpdySessionPool::RemoveUnavailableSession(
225 const base::WeakPtr<SpdySession>& unavailable_session) {
226 DCHECK(!IsSessionAvailable(unavailable_session));
228 unavailable_session->net_log().AddEvent(
229 NetLog::TYPE_SPDY_SESSION_POOL_REMOVE_SESSION,
230 unavailable_session->net_log().source().ToEventParametersCallback());
232 SessionSet::iterator it = sessions_.find(unavailable_session.get());
233 CHECK(it != sessions_.end());
234 scoped_ptr<SpdySession> owned_session(*it);
235 sessions_.erase(it);
238 // Make a copy of |sessions_| in the Close* functions below to avoid
239 // reentrancy problems. Since arbitrary functions get called by close
240 // handlers, it doesn't suffice to simply increment the iterator
241 // before closing.
243 void SpdySessionPool::CloseCurrentSessions(net::Error error) {
244 CloseCurrentSessionsHelper(error, "Closing current sessions.",
245 false /* idle_only */);
248 void SpdySessionPool::CloseCurrentIdleSessions() {
249 CloseCurrentSessionsHelper(ERR_ABORTED, "Closing idle sessions.",
250 true /* idle_only */);
253 void SpdySessionPool::CloseAllSessions() {
254 while (!sessions_.empty()) {
255 CloseCurrentSessionsHelper(ERR_ABORTED, "Closing all sessions.",
256 false /* idle_only */);
260 base::Value* SpdySessionPool::SpdySessionPoolInfoToValue() const {
261 base::ListValue* list = new base::ListValue();
263 for (AvailableSessionMap::const_iterator it = available_sessions_.begin();
264 it != available_sessions_.end(); ++it) {
265 // Only add the session if the key in the map matches the main
266 // host_port_proxy_pair (not an alias).
267 const SpdySessionKey& key = it->first;
268 const SpdySessionKey& session_key = it->second->spdy_session_key();
269 if (key.Equals(session_key))
270 list->Append(it->second->GetInfoAsValue());
272 return list;
275 void SpdySessionPool::OnIPAddressChanged() {
276 WeakSessionList current_sessions = GetCurrentSessions();
277 for (WeakSessionList::const_iterator it = current_sessions.begin();
278 it != current_sessions.end(); ++it) {
279 if (!*it)
280 continue;
282 // For OSs that terminate TCP connections upon relevant network changes
283 // there is no need to explicitly close SpdySessions, instead simply mark
284 // the sessions as deprecated so they aren't reused.
285 #if defined(OS_ANDROID) || defined(OS_WIN) || defined(OS_IOS)
286 (*it)->MakeUnavailable();
287 #else
288 (*it)->CloseSessionOnError(ERR_NETWORK_CHANGED,
289 "Closing current sessions.");
290 DCHECK(!*it);
291 #endif // defined(OS_ANDROID) || defined(OS_WIN) || defined(OS_IOS)
292 DCHECK(!IsSessionAvailable(*it));
294 http_server_properties_->ClearAllSpdySettings();
297 void SpdySessionPool::OnSSLConfigChanged() {
298 CloseCurrentSessions(ERR_NETWORK_CHANGED);
301 void SpdySessionPool::OnCertAdded(const X509Certificate* cert) {
302 CloseCurrentSessions(ERR_CERT_DATABASE_CHANGED);
305 void SpdySessionPool::OnCACertChanged(const X509Certificate* cert) {
306 // Per wtc, we actually only need to CloseCurrentSessions when trust is
307 // reduced. CloseCurrentSessions now because OnCACertChanged does not
308 // tell us this.
309 // See comments in ClientSocketPoolManager::OnCACertChanged.
310 CloseCurrentSessions(ERR_CERT_DATABASE_CHANGED);
313 bool SpdySessionPool::IsSessionAvailable(
314 const base::WeakPtr<SpdySession>& session) const {
315 for (AvailableSessionMap::const_iterator it = available_sessions_.begin();
316 it != available_sessions_.end(); ++it) {
317 if (it->second.get() == session.get())
318 return true;
320 return false;
323 const SpdySessionKey& SpdySessionPool::NormalizeListKey(
324 const SpdySessionKey& key) const {
325 if (!force_single_domain_)
326 return key;
328 static SpdySessionKey* single_domain_key = NULL;
329 if (!single_domain_key) {
330 HostPortPair single_domain = HostPortPair("singledomain.com", 80);
331 single_domain_key = new SpdySessionKey(single_domain,
332 ProxyServer::Direct(),
333 kPrivacyModeDisabled);
335 return *single_domain_key;
338 void SpdySessionPool::MapKeyToAvailableSession(
339 const SpdySessionKey& key,
340 const base::WeakPtr<SpdySession>& session) {
341 DCHECK(ContainsKey(sessions_, session.get()));
342 const SpdySessionKey& normalized_key = NormalizeListKey(key);
343 std::pair<AvailableSessionMap::iterator, bool> result =
344 available_sessions_.insert(std::make_pair(normalized_key, session));
345 CHECK(result.second);
348 SpdySessionPool::AvailableSessionMap::iterator
349 SpdySessionPool::LookupAvailableSessionByKey(
350 const SpdySessionKey& key) {
351 const SpdySessionKey& normalized_key = NormalizeListKey(key);
352 return available_sessions_.find(normalized_key);
355 void SpdySessionPool::UnmapKey(const SpdySessionKey& key) {
356 AvailableSessionMap::iterator it = LookupAvailableSessionByKey(key);
357 CHECK(it != available_sessions_.end());
358 available_sessions_.erase(it);
361 void SpdySessionPool::RemoveAliases(const SpdySessionKey& key) {
362 // Walk the aliases map, find references to this pair.
363 // TODO(mbelshe): Figure out if this is too expensive.
364 for (AliasMap::iterator it = aliases_.begin(); it != aliases_.end(); ) {
365 if (it->second.Equals(key)) {
366 AliasMap::iterator old_it = it;
367 ++it;
368 aliases_.erase(old_it);
369 } else {
370 ++it;
375 SpdySessionPool::WeakSessionList SpdySessionPool::GetCurrentSessions() const {
376 WeakSessionList current_sessions;
377 for (SessionSet::const_iterator it = sessions_.begin();
378 it != sessions_.end(); ++it) {
379 current_sessions.push_back((*it)->GetWeakPtr());
381 return current_sessions;
384 void SpdySessionPool::CloseCurrentSessionsHelper(
385 Error error,
386 const std::string& description,
387 bool idle_only) {
388 WeakSessionList current_sessions = GetCurrentSessions();
389 for (WeakSessionList::const_iterator it = current_sessions.begin();
390 it != current_sessions.end(); ++it) {
391 if (!*it)
392 continue;
394 if (idle_only && (*it)->is_active())
395 continue;
397 (*it)->CloseSessionOnError(error, description);
398 DCHECK(!IsSessionAvailable(*it));
399 DCHECK(!*it);
403 } // namespace net