Home | History | Annotate | Download | only in spdy
      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   CloseCurrentSessions(ERR_NETWORK_CHANGED);
    282   http_server_properties_->ClearAllSpdySettings();
    283 }
    284 
    285 void SpdySessionPool::OnSSLConfigChanged() {
    286   CloseCurrentSessions(ERR_NETWORK_CHANGED);
    287 }
    288 
    289 void SpdySessionPool::OnCertAdded(const X509Certificate* cert) {
    290   CloseCurrentSessions(ERR_CERT_DATABASE_CHANGED);
    291 }
    292 
    293 void SpdySessionPool::OnCACertChanged(const X509Certificate* cert) {
    294   // Per wtc, we actually only need to CloseCurrentSessions when trust is
    295   // reduced. CloseCurrentSessions now because OnCACertChanged does not
    296   // tell us this.
    297   // See comments in ClientSocketPoolManager::OnCACertChanged.
    298   CloseCurrentSessions(ERR_CERT_DATABASE_CHANGED);
    299 }
    300 
    301 bool SpdySessionPool::IsSessionAvailable(
    302     const base::WeakPtr<SpdySession>& session) const {
    303   for (AvailableSessionMap::const_iterator it = available_sessions_.begin();
    304        it != available_sessions_.end(); ++it) {
    305     if (it->second.get() == session.get())
    306       return true;
    307   }
    308   return false;
    309 }
    310 
    311 const SpdySessionKey& SpdySessionPool::NormalizeListKey(
    312     const SpdySessionKey& key) const {
    313   if (!force_single_domain_)
    314     return key;
    315 
    316   static SpdySessionKey* single_domain_key = NULL;
    317   if (!single_domain_key) {
    318     HostPortPair single_domain = HostPortPair("singledomain.com", 80);
    319     single_domain_key = new SpdySessionKey(single_domain,
    320                                            ProxyServer::Direct(),
    321                                            kPrivacyModeDisabled);
    322   }
    323   return *single_domain_key;
    324 }
    325 
    326 void SpdySessionPool::MapKeyToAvailableSession(
    327     const SpdySessionKey& key,
    328     const base::WeakPtr<SpdySession>& session) {
    329   DCHECK(ContainsKey(sessions_, session.get()));
    330   const SpdySessionKey& normalized_key = NormalizeListKey(key);
    331   std::pair<AvailableSessionMap::iterator, bool> result =
    332       available_sessions_.insert(std::make_pair(normalized_key, session));
    333   CHECK(result.second);
    334 }
    335 
    336 SpdySessionPool::AvailableSessionMap::iterator
    337 SpdySessionPool::LookupAvailableSessionByKey(
    338     const SpdySessionKey& key) {
    339   const SpdySessionKey& normalized_key = NormalizeListKey(key);
    340   return available_sessions_.find(normalized_key);
    341 }
    342 
    343 void SpdySessionPool::UnmapKey(const SpdySessionKey& key) {
    344   AvailableSessionMap::iterator it = LookupAvailableSessionByKey(key);
    345   CHECK(it != available_sessions_.end());
    346   available_sessions_.erase(it);
    347 }
    348 
    349 void SpdySessionPool::RemoveAliases(const SpdySessionKey& key) {
    350   // Walk the aliases map, find references to this pair.
    351   // TODO(mbelshe):  Figure out if this is too expensive.
    352   for (AliasMap::iterator it = aliases_.begin(); it != aliases_.end(); ) {
    353     if (it->second.Equals(key)) {
    354       AliasMap::iterator old_it = it;
    355       ++it;
    356       aliases_.erase(old_it);
    357     } else {
    358       ++it;
    359     }
    360   }
    361 }
    362 
    363 SpdySessionPool::WeakSessionList SpdySessionPool::GetCurrentSessions() const {
    364   WeakSessionList current_sessions;
    365   for (SessionSet::const_iterator it = sessions_.begin();
    366        it != sessions_.end(); ++it) {
    367     current_sessions.push_back((*it)->GetWeakPtr());
    368   }
    369   return current_sessions;
    370 }
    371 
    372 void SpdySessionPool::CloseCurrentSessionsHelper(
    373     Error error,
    374     const std::string& description,
    375     bool idle_only) {
    376   WeakSessionList current_sessions = GetCurrentSessions();
    377   for (WeakSessionList::const_iterator it = current_sessions.begin();
    378        it != current_sessions.end(); ++it) {
    379     if (!*it)
    380       continue;
    381 
    382     if (idle_only && (*it)->is_active())
    383       continue;
    384 
    385     (*it)->CloseSessionOnError(error, description);
    386     DCHECK(!IsSessionAvailable(*it));
    387     DCHECK(!*it);
    388   }
    389 }
    390 
    391 }  // namespace net
    392