Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / net / spdy / spdy_session_pool.cc
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.
4
5 #include "net/spdy/spdy_session_pool.h"
6
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"
14
15
16 namespace net {
17
18 namespace {
19
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
26 };
27
28 }  // namespace
29
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_ip_pooling,
36     bool enable_compression,
37     bool enable_ping_based_connection_checking,
38     NextProto default_protocol,
39     size_t stream_initial_recv_window_size,
40     size_t initial_max_concurrent_streams,
41     size_t max_concurrent_streams_limit,
42     SpdySessionPool::TimeFunc time_func,
43     const std::string& trusted_spdy_proxy)
44     : http_server_properties_(http_server_properties),
45       ssl_config_service_(ssl_config_service),
46       resolver_(resolver),
47       verify_domain_authentication_(true),
48       enable_sending_initial_data_(true),
49       force_single_domain_(force_single_domain),
50       enable_ip_pooling_(enable_ip_pooling),
51       enable_compression_(enable_compression),
52       enable_ping_based_connection_checking_(
53           enable_ping_based_connection_checking),
54       // TODO(akalin): Force callers to have a valid value of
55       // |default_protocol_|.
56       default_protocol_(
57           (default_protocol == kProtoUnknown) ?
58           kProtoSPDY3 : default_protocol),
59       stream_initial_recv_window_size_(stream_initial_recv_window_size),
60       initial_max_concurrent_streams_(initial_max_concurrent_streams),
61       max_concurrent_streams_limit_(max_concurrent_streams_limit),
62       time_func_(time_func),
63       trusted_spdy_proxy_(
64           HostPortPair::FromString(trusted_spdy_proxy)) {
65   DCHECK(default_protocol_ >= kProtoSPDYMinimumVersion &&
66          default_protocol_ <= kProtoSPDYMaximumVersion);
67   NetworkChangeNotifier::AddIPAddressObserver(this);
68   if (ssl_config_service_.get())
69     ssl_config_service_->AddObserver(this);
70   CertDatabase::GetInstance()->AddObserver(this);
71 }
72
73 SpdySessionPool::~SpdySessionPool() {
74   CloseAllSessions();
75
76   if (ssl_config_service_.get())
77     ssl_config_service_->RemoveObserver(this);
78   NetworkChangeNotifier::RemoveIPAddressObserver(this);
79   CertDatabase::GetInstance()->RemoveObserver(this);
80 }
81
82 net::Error SpdySessionPool::CreateAvailableSessionFromSocket(
83     const SpdySessionKey& key,
84     scoped_ptr<ClientSocketHandle> connection,
85     const BoundNetLog& net_log,
86     int certificate_error_code,
87     base::WeakPtr<SpdySession>* available_session,
88     bool is_secure) {
89   DCHECK_GE(default_protocol_, kProtoSPDYMinimumVersion);
90   DCHECK_LE(default_protocol_, kProtoSPDYMaximumVersion);
91
92   UMA_HISTOGRAM_ENUMERATION(
93       "Net.SpdySessionGet", IMPORTED_FROM_SOCKET, SPDY_SESSION_GET_MAX);
94
95   scoped_ptr<SpdySession> new_session(
96       new SpdySession(key,
97                       http_server_properties_,
98                       verify_domain_authentication_,
99                       enable_sending_initial_data_,
100                       enable_compression_,
101                       enable_ping_based_connection_checking_,
102                       default_protocol_,
103                       stream_initial_recv_window_size_,
104                       initial_max_concurrent_streams_,
105                       max_concurrent_streams_limit_,
106                       time_func_,
107                       trusted_spdy_proxy_,
108                       net_log.net_log()));
109
110   Error error =  new_session->InitializeWithSocket(
111       connection.Pass(), this, is_secure, certificate_error_code);
112   DCHECK_NE(error, ERR_IO_PENDING);
113
114   if (error != OK) {
115     available_session->reset();
116     return error;
117   }
118
119   *available_session = new_session->GetWeakPtr();
120   sessions_.insert(new_session.release());
121   MapKeyToAvailableSession(key, *available_session);
122
123   net_log.AddEvent(
124       NetLog::TYPE_SPDY_SESSION_POOL_IMPORTED_SESSION_FROM_SOCKET,
125       (*available_session)->net_log().source().ToEventParametersCallback());
126
127   // Look up the IP address for this session so that we can match
128   // future sessions (potentially to different domains) which can
129   // potentially be pooled with this one. Because GetPeerAddress()
130   // reports the proxy's address instead of the origin server, check
131   // to see if this is a direct connection.
132   if (enable_ip_pooling_  && key.proxy_server().is_direct()) {
133     IPEndPoint address;
134     if ((*available_session)->GetPeerAddress(&address) == OK)
135       aliases_[address] = key;
136   }
137
138   return error;
139 }
140
141 base::WeakPtr<SpdySession> SpdySessionPool::FindAvailableSession(
142     const SpdySessionKey& key,
143     const BoundNetLog& net_log) {
144   AvailableSessionMap::iterator it = LookupAvailableSessionByKey(key);
145   if (it != available_sessions_.end()) {
146     UMA_HISTOGRAM_ENUMERATION(
147         "Net.SpdySessionGet", FOUND_EXISTING, SPDY_SESSION_GET_MAX);
148     net_log.AddEvent(
149         NetLog::TYPE_SPDY_SESSION_POOL_FOUND_EXISTING_SESSION,
150         it->second->net_log().source().ToEventParametersCallback());
151     return it->second;
152   }
153
154   if (!enable_ip_pooling_)
155     return base::WeakPtr<SpdySession>();
156
157   // Look up the key's from the resolver's cache.
158   net::HostResolver::RequestInfo resolve_info(key.host_port_pair());
159   AddressList addresses;
160   int rv = resolver_->ResolveFromCache(resolve_info, &addresses, net_log);
161   DCHECK_NE(rv, ERR_IO_PENDING);
162   if (rv != OK)
163     return base::WeakPtr<SpdySession>();
164
165   // Check if we have a session through a domain alias.
166   for (AddressList::const_iterator address_it = addresses.begin();
167        address_it != addresses.end();
168        ++address_it) {
169     AliasMap::const_iterator alias_it = aliases_.find(*address_it);
170     if (alias_it == aliases_.end())
171       continue;
172
173     // We found an alias.
174     const SpdySessionKey& alias_key = alias_it->second;
175
176     // We can reuse this session only if the proxy and privacy
177     // settings match.
178     if (!(alias_key.proxy_server() == key.proxy_server()) ||
179         !(alias_key.privacy_mode() == key.privacy_mode()))
180       continue;
181
182     AvailableSessionMap::iterator available_session_it =
183         LookupAvailableSessionByKey(alias_key);
184     if (available_session_it == available_sessions_.end()) {
185       NOTREACHED();  // It shouldn't be in the aliases table if we can't get it!
186       continue;
187     }
188
189     const base::WeakPtr<SpdySession>& available_session =
190         available_session_it->second;
191     DCHECK(ContainsKey(sessions_, available_session.get()));
192     // If the session is a secure one, we need to verify that the
193     // server is authenticated to serve traffic for |host_port_proxy_pair| too.
194     if (!available_session->VerifyDomainAuthentication(
195             key.host_port_pair().host())) {
196       UMA_HISTOGRAM_ENUMERATION("Net.SpdyIPPoolDomainMatch", 0, 2);
197       continue;
198     }
199
200     UMA_HISTOGRAM_ENUMERATION("Net.SpdyIPPoolDomainMatch", 1, 2);
201     UMA_HISTOGRAM_ENUMERATION("Net.SpdySessionGet",
202                               FOUND_EXISTING_FROM_IP_POOL,
203                               SPDY_SESSION_GET_MAX);
204     net_log.AddEvent(
205         NetLog::TYPE_SPDY_SESSION_POOL_FOUND_EXISTING_SESSION_FROM_IP_POOL,
206         available_session->net_log().source().ToEventParametersCallback());
207     // Add this session to the map so that we can find it next time.
208     MapKeyToAvailableSession(key, available_session);
209     available_session->AddPooledAlias(key);
210     return available_session;
211   }
212
213   return base::WeakPtr<SpdySession>();
214 }
215
216 void SpdySessionPool::MakeSessionUnavailable(
217     const base::WeakPtr<SpdySession>& available_session) {
218   UnmapKey(available_session->spdy_session_key());
219   RemoveAliases(available_session->spdy_session_key());
220   const std::set<SpdySessionKey>& aliases = available_session->pooled_aliases();
221   for (std::set<SpdySessionKey>::const_iterator it = aliases.begin();
222        it != aliases.end(); ++it) {
223     UnmapKey(*it);
224     RemoveAliases(*it);
225   }
226   DCHECK(!IsSessionAvailable(available_session));
227 }
228
229 void SpdySessionPool::RemoveUnavailableSession(
230     const base::WeakPtr<SpdySession>& unavailable_session) {
231   DCHECK(!IsSessionAvailable(unavailable_session));
232
233   unavailable_session->net_log().AddEvent(
234       NetLog::TYPE_SPDY_SESSION_POOL_REMOVE_SESSION,
235       unavailable_session->net_log().source().ToEventParametersCallback());
236
237   SessionSet::iterator it = sessions_.find(unavailable_session.get());
238   CHECK(it != sessions_.end());
239   scoped_ptr<SpdySession> owned_session(*it);
240   sessions_.erase(it);
241 }
242
243 // Make a copy of |sessions_| in the Close* functions below to avoid
244 // reentrancy problems. Since arbitrary functions get called by close
245 // handlers, it doesn't suffice to simply increment the iterator
246 // before closing.
247
248 void SpdySessionPool::CloseCurrentSessions(net::Error error) {
249   CloseCurrentSessionsHelper(error, "Closing current sessions.",
250                              false /* idle_only */);
251 }
252
253 void SpdySessionPool::CloseCurrentIdleSessions() {
254   CloseCurrentSessionsHelper(ERR_ABORTED, "Closing idle sessions.",
255                              true /* idle_only */);
256 }
257
258 void SpdySessionPool::CloseAllSessions() {
259   while (!sessions_.empty()) {
260     CloseCurrentSessionsHelper(ERR_ABORTED, "Closing all sessions.",
261                                false /* idle_only */);
262   }
263 }
264
265 base::Value* SpdySessionPool::SpdySessionPoolInfoToValue() const {
266   base::ListValue* list = new base::ListValue();
267
268   for (AvailableSessionMap::const_iterator it = available_sessions_.begin();
269        it != available_sessions_.end(); ++it) {
270     // Only add the session if the key in the map matches the main
271     // host_port_proxy_pair (not an alias).
272     const SpdySessionKey& key = it->first;
273     const SpdySessionKey& session_key = it->second->spdy_session_key();
274     if (key.Equals(session_key))
275       list->Append(it->second->GetInfoAsValue());
276   }
277   return list;
278 }
279
280 void SpdySessionPool::OnIPAddressChanged() {
281   WeakSessionList current_sessions = GetCurrentSessions();
282   for (WeakSessionList::const_iterator it = current_sessions.begin();
283        it != current_sessions.end(); ++it) {
284     if (!*it)
285       continue;
286
287     // For OSs that terminate TCP connections upon relevant network changes
288     // there is no need to explicitly close SpdySessions, instead simply mark
289     // the sessions as deprecated so they aren't reused.
290 #if defined(OS_ANDROID) || defined(OS_WIN) || defined(OS_IOS)
291     (*it)->MakeUnavailable();
292 #else
293     (*it)->CloseSessionOnError(ERR_NETWORK_CHANGED,
294                                "Closing current sessions.");
295     DCHECK(!*it);
296 #endif  // defined(OS_ANDROID) || defined(OS_WIN) || defined(OS_IOS)
297     DCHECK(!IsSessionAvailable(*it));
298   }
299   http_server_properties_->ClearAllSpdySettings();
300 }
301
302 void SpdySessionPool::OnSSLConfigChanged() {
303   CloseCurrentSessions(ERR_NETWORK_CHANGED);
304 }
305
306 void SpdySessionPool::OnCertAdded(const X509Certificate* cert) {
307   CloseCurrentSessions(ERR_CERT_DATABASE_CHANGED);
308 }
309
310 void SpdySessionPool::OnCACertChanged(const X509Certificate* cert) {
311   // Per wtc, we actually only need to CloseCurrentSessions when trust is
312   // reduced. CloseCurrentSessions now because OnCACertChanged does not
313   // tell us this.
314   // See comments in ClientSocketPoolManager::OnCACertChanged.
315   CloseCurrentSessions(ERR_CERT_DATABASE_CHANGED);
316 }
317
318 bool SpdySessionPool::IsSessionAvailable(
319     const base::WeakPtr<SpdySession>& session) const {
320   for (AvailableSessionMap::const_iterator it = available_sessions_.begin();
321        it != available_sessions_.end(); ++it) {
322     if (it->second.get() == session.get())
323       return true;
324   }
325   return false;
326 }
327
328 const SpdySessionKey& SpdySessionPool::NormalizeListKey(
329     const SpdySessionKey& key) const {
330   if (!force_single_domain_)
331     return key;
332
333   static SpdySessionKey* single_domain_key = NULL;
334   if (!single_domain_key) {
335     HostPortPair single_domain = HostPortPair("singledomain.com", 80);
336     single_domain_key = new SpdySessionKey(single_domain,
337                                            ProxyServer::Direct(),
338                                            kPrivacyModeDisabled);
339   }
340   return *single_domain_key;
341 }
342
343 void SpdySessionPool::MapKeyToAvailableSession(
344     const SpdySessionKey& key,
345     const base::WeakPtr<SpdySession>& session) {
346   DCHECK(ContainsKey(sessions_, session.get()));
347   const SpdySessionKey& normalized_key = NormalizeListKey(key);
348   std::pair<AvailableSessionMap::iterator, bool> result =
349       available_sessions_.insert(std::make_pair(normalized_key, session));
350   CHECK(result.second);
351 }
352
353 SpdySessionPool::AvailableSessionMap::iterator
354 SpdySessionPool::LookupAvailableSessionByKey(
355     const SpdySessionKey& key) {
356   const SpdySessionKey& normalized_key = NormalizeListKey(key);
357   return available_sessions_.find(normalized_key);
358 }
359
360 void SpdySessionPool::UnmapKey(const SpdySessionKey& key) {
361   AvailableSessionMap::iterator it = LookupAvailableSessionByKey(key);
362   CHECK(it != available_sessions_.end());
363   available_sessions_.erase(it);
364 }
365
366 void SpdySessionPool::RemoveAliases(const SpdySessionKey& key) {
367   // Walk the aliases map, find references to this pair.
368   // TODO(mbelshe):  Figure out if this is too expensive.
369   for (AliasMap::iterator it = aliases_.begin(); it != aliases_.end(); ) {
370     if (it->second.Equals(key)) {
371       AliasMap::iterator old_it = it;
372       ++it;
373       aliases_.erase(old_it);
374     } else {
375       ++it;
376     }
377   }
378 }
379
380 SpdySessionPool::WeakSessionList SpdySessionPool::GetCurrentSessions() const {
381   WeakSessionList current_sessions;
382   for (SessionSet::const_iterator it = sessions_.begin();
383        it != sessions_.end(); ++it) {
384     current_sessions.push_back((*it)->GetWeakPtr());
385   }
386   return current_sessions;
387 }
388
389 void SpdySessionPool::CloseCurrentSessionsHelper(
390     Error error,
391     const std::string& description,
392     bool idle_only) {
393   WeakSessionList current_sessions = GetCurrentSessions();
394   for (WeakSessionList::const_iterator it = current_sessions.begin();
395        it != current_sessions.end(); ++it) {
396     if (!*it)
397       continue;
398
399     if (idle_only && (*it)->is_active())
400       continue;
401
402     (*it)->CloseSessionOnError(error, description);
403     DCHECK(!IsSessionAvailable(*it));
404     DCHECK(!*it);
405   }
406 }
407
408 }  // namespace net