This source file includes following definitions.
- ShouldRestorePreviousBackoff
- weak_ptr_factory_
- Initialize
- GetConnectionHandler
- ConnectWithBackoff
- IsEndpointReachable
- SignalConnectionReset
- NextRetryAttempt
- OnConnectionTypeChanged
- OnIPAddressChanged
- GetCurrentEndpoint
- ConnectImpl
- InitHandler
- CreateBackoffEntry
- CreateConnectionHandler
- NowTicks
- OnConnectDone
- ConnectionHandlerCallback
- OnProxyResolveDone
- ReconsiderProxyAfterError
- ReportSuccessfulProxyConnection
- CloseSocket
#include "google_apis/gcm/engine/connection_factory_impl.h"
#include "base/message_loop/message_loop.h"
#include "base/metrics/histogram.h"
#include "base/metrics/sparse_histogram.h"
#include "google_apis/gcm/engine/connection_handler_impl.h"
#include "google_apis/gcm/protocol/mcs.pb.h"
#include "net/base/net_errors.h"
#include "net/http/http_network_session.h"
#include "net/http/http_request_headers.h"
#include "net/proxy/proxy_info.h"
#include "net/socket/client_socket_handle.h"
#include "net/socket/client_socket_pool_manager.h"
#include "net/ssl/ssl_config_service.h"
namespace gcm {
namespace {
const int kReadTimeoutMs = 30000;
const int kConnectionResetWindowSecs = 10;
bool ShouldRestorePreviousBackoff(const base::TimeTicks& login_time,
const base::TimeTicks& now_ticks) {
return !login_time.is_null() &&
now_ticks - login_time <=
base::TimeDelta::FromSeconds(kConnectionResetWindowSecs);
}
}
ConnectionFactoryImpl::ConnectionFactoryImpl(
const std::vector<GURL>& mcs_endpoints,
const net::BackoffEntry::Policy& backoff_policy,
scoped_refptr<net::HttpNetworkSession> network_session,
net::NetLog* net_log)
: mcs_endpoints_(mcs_endpoints),
next_endpoint_(0),
last_successful_endpoint_(0),
backoff_policy_(backoff_policy),
network_session_(network_session),
bound_net_log_(
net::BoundNetLog::Make(net_log, net::NetLog::SOURCE_SOCKET)),
pac_request_(NULL),
connecting_(false),
waiting_for_backoff_(false),
logging_in_(false),
weak_ptr_factory_(this) {
DCHECK_GE(mcs_endpoints_.size(), 1U);
}
ConnectionFactoryImpl::~ConnectionFactoryImpl() {
if (pac_request_) {
network_session_->proxy_service()->CancelPacRequest(pac_request_);
pac_request_ = NULL;
}
}
void ConnectionFactoryImpl::Initialize(
const BuildLoginRequestCallback& request_builder,
const ConnectionHandler::ProtoReceivedCallback& read_callback,
const ConnectionHandler::ProtoSentCallback& write_callback) {
DCHECK(!connection_handler_);
previous_backoff_ = CreateBackoffEntry(&backoff_policy_);
backoff_entry_ = CreateBackoffEntry(&backoff_policy_);
request_builder_ = request_builder;
net::NetworkChangeNotifier::AddIPAddressObserver(this);
net::NetworkChangeNotifier::AddConnectionTypeObserver(this);
connection_handler_ = CreateConnectionHandler(
base::TimeDelta::FromMilliseconds(kReadTimeoutMs),
read_callback,
write_callback,
base::Bind(&ConnectionFactoryImpl::ConnectionHandlerCallback,
weak_ptr_factory_.GetWeakPtr())).Pass();
}
ConnectionHandler* ConnectionFactoryImpl::GetConnectionHandler() const {
return connection_handler_.get();
}
void ConnectionFactoryImpl::Connect() {
DCHECK(connection_handler_);
if (connecting_ || waiting_for_backoff_)
return;
if (IsEndpointReachable())
return;
ConnectWithBackoff();
}
void ConnectionFactoryImpl::ConnectWithBackoff() {
if (connecting_ || IsEndpointReachable()) {
waiting_for_backoff_ = false;
return;
}
if (backoff_entry_->ShouldRejectRequest()) {
DVLOG(1) << "Delaying MCS endpoint connection for "
<< backoff_entry_->GetTimeUntilRelease().InMilliseconds()
<< " milliseconds.";
waiting_for_backoff_ = true;
base::MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&ConnectionFactoryImpl::ConnectWithBackoff,
weak_ptr_factory_.GetWeakPtr()),
backoff_entry_->GetTimeUntilRelease());
return;
}
DVLOG(1) << "Attempting connection to MCS endpoint.";
waiting_for_backoff_ = false;
ConnectImpl();
}
bool ConnectionFactoryImpl::IsEndpointReachable() const {
return connection_handler_ && connection_handler_->CanSendMessage();
}
void ConnectionFactoryImpl::SignalConnectionReset(
ConnectionResetReason reason) {
if (connecting_) {
DVLOG(1) << "Connection in progress, ignoring reset.";
return;
}
UMA_HISTOGRAM_ENUMERATION("GCM.ConnectionResetReason",
reason,
CONNECTION_RESET_COUNT);
if (!last_login_time_.is_null()) {
UMA_HISTOGRAM_CUSTOM_TIMES("GCM.ConnectionUpTime",
NowTicks() - last_login_time_,
base::TimeDelta::FromSeconds(1),
base::TimeDelta::FromHours(24),
50);
}
CloseSocket();
DCHECK(!IsEndpointReachable());
if (waiting_for_backoff_ && reason != NETWORK_CHANGE) {
DVLOG(1) << "Backoff expiration pending, ignoring reset.";
return;
}
if (logging_in_) {
logging_in_ = false;
backoff_entry_->InformOfRequest(false);
} else if (reason == LOGIN_FAILURE ||
ShouldRestorePreviousBackoff(last_login_time_, NowTicks())) {
backoff_entry_.swap(previous_backoff_);
backoff_entry_->InformOfRequest(false);
} else if (reason == NETWORK_CHANGE) {
ConnectImpl();
return;
} else {
DCHECK_EQ(0, backoff_entry_->failure_count());
}
DCHECK(!connecting_);
DCHECK(!waiting_for_backoff_);
last_login_time_ = base::TimeTicks();
Connect();
}
base::TimeTicks ConnectionFactoryImpl::NextRetryAttempt() const {
if (!backoff_entry_)
return base::TimeTicks();
return backoff_entry_->GetReleaseTime();
}
void ConnectionFactoryImpl::OnConnectionTypeChanged(
net::NetworkChangeNotifier::ConnectionType type) {
if (type == net::NetworkChangeNotifier::CONNECTION_NONE)
return;
DVLOG(1) << "Connection type changed to " << type << ", reconnecting.";
SignalConnectionReset(NETWORK_CHANGE);
}
void ConnectionFactoryImpl::OnIPAddressChanged() {
DVLOG(1) << "IP Address changed, reconnecting.";
SignalConnectionReset(NETWORK_CHANGE);
}
GURL ConnectionFactoryImpl::GetCurrentEndpoint() const {
if (IsEndpointReachable())
return mcs_endpoints_[last_successful_endpoint_];
return mcs_endpoints_[next_endpoint_];
}
void ConnectionFactoryImpl::ConnectImpl() {
DCHECK(!IsEndpointReachable());
DCHECK(!socket_handle_.socket());
connecting_ = true;
int status = network_session_->proxy_service()->ResolveProxy(
GetCurrentEndpoint(),
&proxy_info_,
base::Bind(&ConnectionFactoryImpl::OnProxyResolveDone,
weak_ptr_factory_.GetWeakPtr()),
&pac_request_,
bound_net_log_);
if (status != net::ERR_IO_PENDING)
OnProxyResolveDone(status);
}
void ConnectionFactoryImpl::InitHandler() {
mcs_proto::LoginRequest login_request;
if (!request_builder_.is_null()) {
request_builder_.Run(&login_request);
DCHECK(login_request.IsInitialized());
}
connection_handler_->Init(login_request, socket_handle_.socket());
}
scoped_ptr<net::BackoffEntry> ConnectionFactoryImpl::CreateBackoffEntry(
const net::BackoffEntry::Policy* const policy) {
return scoped_ptr<net::BackoffEntry>(new net::BackoffEntry(policy));
}
scoped_ptr<ConnectionHandler> ConnectionFactoryImpl::CreateConnectionHandler(
base::TimeDelta read_timeout,
const ConnectionHandler::ProtoReceivedCallback& read_callback,
const ConnectionHandler::ProtoSentCallback& write_callback,
const ConnectionHandler::ConnectionChangedCallback& connection_callback) {
return make_scoped_ptr<ConnectionHandler>(
new ConnectionHandlerImpl(read_timeout,
read_callback,
write_callback,
connection_callback));
}
base::TimeTicks ConnectionFactoryImpl::NowTicks() {
return base::TimeTicks::Now();
}
void ConnectionFactoryImpl::OnConnectDone(int result) {
if (result != net::OK) {
result = ReconsiderProxyAfterError(result);
DCHECK_NE(result, net::OK);
if (result == net::ERR_IO_PENDING)
return;
LOG(ERROR) << "Failed to connect to MCS endpoint with error " << result;
UMA_HISTOGRAM_BOOLEAN("GCM.ConnectionSuccessRate", false);
CloseSocket();
backoff_entry_->InformOfRequest(false);
UMA_HISTOGRAM_SPARSE_SLOWLY("GCM.ConnectionFailureErrorCode", result);
next_endpoint_++;
if (next_endpoint_ >= mcs_endpoints_.size())
next_endpoint_ = 0;
connecting_ = false;
Connect();
return;
}
UMA_HISTOGRAM_BOOLEAN("GCM.ConnectionSuccessRate", true);
UMA_HISTOGRAM_COUNTS("GCM.ConnectionEndpoint", next_endpoint_);
UMA_HISTOGRAM_BOOLEAN("GCM.ConnectedViaProxy",
!(proxy_info_.is_empty() || proxy_info_.is_direct()));
ReportSuccessfulProxyConnection();
last_successful_endpoint_ = next_endpoint_;
next_endpoint_ = 0;
connecting_ = false;
logging_in_ = true;
DVLOG(1) << "MCS endpoint socket connection success, starting login.";
InitHandler();
}
void ConnectionFactoryImpl::ConnectionHandlerCallback(int result) {
DCHECK(!connecting_);
if (result != net::OK) {
UMA_HISTOGRAM_SPARSE_SLOWLY("GCM.ConnectionDisconnectErrorCode", result);
SignalConnectionReset(SOCKET_FAILURE);
return;
}
DVLOG(1) << "Handshake complete.";
last_login_time_ = NowTicks();
previous_backoff_.swap(backoff_entry_);
backoff_entry_->Reset();
logging_in_ = false;
}
void ConnectionFactoryImpl::OnProxyResolveDone(int status) {
pac_request_ = NULL;
DVLOG(1) << "Proxy resolution status: " << status;
DCHECK_NE(status, net::ERR_IO_PENDING);
if (status == net::OK) {
proxy_info_.RemoveProxiesWithoutScheme(
net::ProxyServer::SCHEME_DIRECT |
net::ProxyServer::SCHEME_HTTP | net::ProxyServer::SCHEME_HTTPS |
net::ProxyServer::SCHEME_SOCKS4 | net::ProxyServer::SCHEME_SOCKS5);
if (proxy_info_.is_empty()) {
status = net::ERR_NO_SUPPORTED_PROXIES;
}
}
if (status != net::OK) {
OnConnectDone(status);
return;
}
DVLOG(1) << "Resolved proxy with PAC:" << proxy_info_.ToPacString();
net::SSLConfig ssl_config;
network_session_->ssl_config_service()->GetSSLConfig(&ssl_config);
status = net::InitSocketHandleForTlsConnect(
net::HostPortPair::FromURL(GetCurrentEndpoint()),
network_session_.get(),
proxy_info_,
ssl_config,
ssl_config,
net::PRIVACY_MODE_DISABLED,
bound_net_log_,
&socket_handle_,
base::Bind(&ConnectionFactoryImpl::OnConnectDone,
weak_ptr_factory_.GetWeakPtr()));
if (status != net::ERR_IO_PENDING)
OnConnectDone(status);
}
int ConnectionFactoryImpl::ReconsiderProxyAfterError(int error) {
DCHECK(!pac_request_);
DCHECK_NE(error, net::OK);
DCHECK_NE(error, net::ERR_IO_PENDING);
switch (error) {
case net::ERR_PROXY_CONNECTION_FAILED:
case net::ERR_NAME_NOT_RESOLVED:
case net::ERR_INTERNET_DISCONNECTED:
case net::ERR_ADDRESS_UNREACHABLE:
case net::ERR_CONNECTION_CLOSED:
case net::ERR_CONNECTION_TIMED_OUT:
case net::ERR_CONNECTION_RESET:
case net::ERR_CONNECTION_REFUSED:
case net::ERR_CONNECTION_ABORTED:
case net::ERR_TIMED_OUT:
case net::ERR_TUNNEL_CONNECTION_FAILED:
case net::ERR_SOCKS_CONNECTION_FAILED:
case net::ERR_PROXY_CERTIFICATE_INVALID:
case net::ERR_SSL_PROTOCOL_ERROR:
break;
case net::ERR_SOCKS_CONNECTION_HOST_UNREACHABLE:
return net::ERR_ADDRESS_UNREACHABLE;
default:
return error;
}
net::SSLConfig ssl_config;
network_session_->ssl_config_service()->GetSSLConfig(&ssl_config);
if (proxy_info_.is_https() && ssl_config.send_client_cert) {
network_session_->ssl_client_auth_cache()->Remove(
proxy_info_.proxy_server().host_port_pair());
}
int status = network_session_->proxy_service()->ReconsiderProxyAfterError(
GetCurrentEndpoint(), &proxy_info_,
base::Bind(&ConnectionFactoryImpl::OnProxyResolveDone,
weak_ptr_factory_.GetWeakPtr()),
&pac_request_,
bound_net_log_);
if (status == net::OK || status == net::ERR_IO_PENDING) {
CloseSocket();
} else {
status = error;
}
if (status == net::OK) {
base::MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&ConnectionFactoryImpl::OnProxyResolveDone,
weak_ptr_factory_.GetWeakPtr(), status));
status = net::ERR_IO_PENDING;
}
return status;
}
void ConnectionFactoryImpl::ReportSuccessfulProxyConnection() {
if (network_session_ && network_session_->proxy_service())
network_session_->proxy_service()->ReportSuccess(proxy_info_);
}
void ConnectionFactoryImpl::CloseSocket() {
if (connection_handler_)
connection_handler_->Reset();
if (socket_handle_.socket() && socket_handle_.socket()->IsConnected())
socket_handle_.socket()->Disconnect();
socket_handle_.Reset();
}
}