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