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 "remoting/jingle_glue/xmpp_signal_strategy.h" 6 7 #include "base/bind.h" 8 #include "base/location.h" 9 #include "base/logging.h" 10 #include "base/single_thread_task_runner.h" 11 #include "base/strings/string_util.h" 12 #include "base/thread_task_runner_handle.h" 13 #include "jingle/glue/chrome_async_socket.h" 14 #include "jingle/glue/task_pump.h" 15 #include "jingle/glue/xmpp_client_socket_factory.h" 16 #include "jingle/notifier/base/gaia_constants.h" 17 #include "jingle/notifier/base/gaia_token_pre_xmpp_auth.h" 18 #include "net/socket/client_socket_factory.h" 19 #include "net/url_request/url_request_context_getter.h" 20 #include "third_party/libjingle/source/talk/base/thread.h" 21 #include "third_party/libjingle/source/talk/xmpp/prexmppauth.h" 22 #include "third_party/libjingle/source/talk/xmpp/saslcookiemechanism.h" 23 24 const char kDefaultResourceName[] = "chromoting"; 25 26 // Use 58 seconds keep-alive interval, in case routers terminate 27 // connections that are idle for more than a minute. 28 const int kKeepAliveIntervalSeconds = 50; 29 30 // Read buffer size used by ChromeAsyncSocket for read and write buffers. Most 31 // of XMPP messages are smaller than 4kB. 32 const size_t kReadBufferSize = 4096; 33 const size_t kWriteBufferSize = 4096; 34 35 namespace remoting { 36 37 XmppSignalStrategy::XmppSignalStrategy( 38 scoped_refptr<net::URLRequestContextGetter> request_context_getter, 39 const std::string& username, 40 const std::string& auth_token, 41 const std::string& auth_token_service, 42 const XmppSignalStrategy::XmppServerConfig& xmpp_server_config) 43 : request_context_getter_(request_context_getter), 44 username_(username), 45 auth_token_(auth_token), 46 auth_token_service_(auth_token_service), 47 resource_name_(kDefaultResourceName), 48 xmpp_client_(NULL), 49 xmpp_server_config_(xmpp_server_config), 50 state_(DISCONNECTED), 51 error_(OK) { 52 #if defined(NDEBUG) 53 CHECK(xmpp_server_config_.use_tls); 54 #endif 55 } 56 57 XmppSignalStrategy::~XmppSignalStrategy() { 58 Disconnect(); 59 60 // Destroying task runner will destroy XmppClient, but XmppClient may be on 61 // the stack and it doesn't handle this case properly, so we need to delay 62 // destruction. 63 base::ThreadTaskRunnerHandle::Get()->DeleteSoon( 64 FROM_HERE, task_runner_.release()); 65 } 66 67 void XmppSignalStrategy::Connect() { 68 DCHECK(CalledOnValidThread()); 69 70 // Disconnect first if we are currently connected. 71 Disconnect(); 72 73 buzz::XmppClientSettings settings; 74 buzz::Jid login_jid(username_); 75 settings.set_user(login_jid.node()); 76 settings.set_host(login_jid.domain()); 77 settings.set_resource(resource_name_); 78 settings.set_token_service(auth_token_service_); 79 settings.set_auth_token(buzz::AUTH_MECHANISM_GOOGLE_TOKEN, auth_token_); 80 settings.set_server(talk_base::SocketAddress( 81 xmpp_server_config_.host, xmpp_server_config_.port)); 82 settings.set_use_tls( 83 xmpp_server_config_.use_tls ? buzz::TLS_ENABLED : buzz::TLS_DISABLED); 84 85 scoped_ptr<jingle_glue::XmppClientSocketFactory> socket_factory( 86 new jingle_glue::XmppClientSocketFactory( 87 net::ClientSocketFactory::GetDefaultFactory(), 88 net::SSLConfig(), request_context_getter_, false)); 89 buzz::AsyncSocket* socket = new jingle_glue::ChromeAsyncSocket( 90 socket_factory.release(), kReadBufferSize, kWriteBufferSize); 91 92 task_runner_.reset(new jingle_glue::TaskPump()); 93 xmpp_client_ = new buzz::XmppClient(task_runner_.get()); 94 xmpp_client_->Connect( 95 settings, std::string(), socket, CreatePreXmppAuth(settings)); 96 xmpp_client_->SignalStateChange 97 .connect(this, &XmppSignalStrategy::OnConnectionStateChanged); 98 xmpp_client_->engine()->AddStanzaHandler(this, buzz::XmppEngine::HL_TYPE); 99 xmpp_client_->Start(); 100 101 SetState(CONNECTING); 102 } 103 104 void XmppSignalStrategy::Disconnect() { 105 DCHECK(CalledOnValidThread()); 106 107 if (xmpp_client_) { 108 xmpp_client_->engine()->RemoveStanzaHandler(this); 109 110 xmpp_client_->Disconnect(); 111 112 // |xmpp_client_| should be set to NULL in OnConnectionStateChanged() 113 // in response to Disconnect() call above. 114 DCHECK(xmpp_client_ == NULL); 115 } 116 } 117 118 SignalStrategy::State XmppSignalStrategy::GetState() const { 119 DCHECK(CalledOnValidThread()); 120 return state_; 121 } 122 123 SignalStrategy::Error XmppSignalStrategy::GetError() const { 124 DCHECK(CalledOnValidThread()); 125 return error_; 126 } 127 128 std::string XmppSignalStrategy::GetLocalJid() const { 129 DCHECK(CalledOnValidThread()); 130 return xmpp_client_->jid().Str(); 131 } 132 133 void XmppSignalStrategy::AddListener(Listener* listener) { 134 DCHECK(CalledOnValidThread()); 135 listeners_.AddObserver(listener); 136 } 137 138 void XmppSignalStrategy::RemoveListener(Listener* listener) { 139 DCHECK(CalledOnValidThread()); 140 listeners_.RemoveObserver(listener); 141 } 142 143 bool XmppSignalStrategy::SendStanza(scoped_ptr<buzz::XmlElement> stanza) { 144 DCHECK(CalledOnValidThread()); 145 if (!xmpp_client_) { 146 LOG(INFO) << "Dropping signalling message because XMPP " 147 "connection has been terminated."; 148 return false; 149 } 150 151 buzz::XmppReturnStatus status = xmpp_client_->SendStanza(stanza.release()); 152 return status == buzz::XMPP_RETURN_OK || status == buzz::XMPP_RETURN_PENDING; 153 } 154 155 std::string XmppSignalStrategy::GetNextId() { 156 DCHECK(CalledOnValidThread()); 157 if (!xmpp_client_) { 158 // If the connection has been terminated then it doesn't matter 159 // what Id we return. 160 return std::string(); 161 } 162 return xmpp_client_->NextId(); 163 } 164 165 bool XmppSignalStrategy::HandleStanza(const buzz::XmlElement* stanza) { 166 DCHECK(CalledOnValidThread()); 167 ObserverListBase<Listener>::Iterator it(listeners_); 168 Listener* listener; 169 while ((listener = it.GetNext()) != NULL) { 170 if (listener->OnSignalStrategyIncomingStanza(stanza)) 171 return true; 172 } 173 return false; 174 } 175 176 void XmppSignalStrategy::SetAuthInfo(const std::string& username, 177 const std::string& auth_token, 178 const std::string& auth_token_service) { 179 DCHECK(CalledOnValidThread()); 180 username_ = username; 181 auth_token_ = auth_token; 182 auth_token_service_ = auth_token_service; 183 } 184 185 void XmppSignalStrategy::SetResourceName(const std::string &resource_name) { 186 DCHECK(CalledOnValidThread()); 187 resource_name_ = resource_name; 188 } 189 190 void XmppSignalStrategy::OnConnectionStateChanged( 191 buzz::XmppEngine::State state) { 192 DCHECK(CalledOnValidThread()); 193 194 if (state == buzz::XmppEngine::STATE_OPEN) { 195 keep_alive_timer_.Start( 196 FROM_HERE, base::TimeDelta::FromSeconds(kKeepAliveIntervalSeconds), 197 this, &XmppSignalStrategy::SendKeepAlive); 198 SetState(CONNECTED); 199 } else if (state == buzz::XmppEngine::STATE_CLOSED) { 200 // Make sure we dump errors to the log. 201 int subcode; 202 buzz::XmppEngine::Error error = xmpp_client_->GetError(&subcode); 203 LOG(INFO) << "XMPP connection was closed: error=" << error 204 << ", subcode=" << subcode; 205 206 keep_alive_timer_.Stop(); 207 208 // Client is destroyed by the TaskRunner after the client is 209 // closed. Reset the pointer so we don't try to use it later. 210 xmpp_client_ = NULL; 211 212 switch (error) { 213 case buzz::XmppEngine::ERROR_UNAUTHORIZED: 214 case buzz::XmppEngine::ERROR_AUTH: 215 case buzz::XmppEngine::ERROR_MISSING_USERNAME: 216 error_ = AUTHENTICATION_FAILED; 217 break; 218 219 default: 220 error_ = NETWORK_ERROR; 221 } 222 223 SetState(DISCONNECTED); 224 } 225 } 226 227 void XmppSignalStrategy::SetState(State new_state) { 228 if (state_ != new_state) { 229 state_ = new_state; 230 FOR_EACH_OBSERVER(Listener, listeners_, 231 OnSignalStrategyStateChange(new_state)); 232 } 233 } 234 235 void XmppSignalStrategy::SendKeepAlive() { 236 xmpp_client_->SendRaw(" "); 237 } 238 239 // static 240 buzz::PreXmppAuth* XmppSignalStrategy::CreatePreXmppAuth( 241 const buzz::XmppClientSettings& settings) { 242 buzz::Jid jid(settings.user(), settings.host(), buzz::STR_EMPTY); 243 std::string mechanism = notifier::kDefaultGaiaAuthMechanism; 244 if (settings.token_service() == "oauth2") { 245 mechanism = "X-OAUTH2"; 246 } 247 248 return new notifier::GaiaTokenPreXmppAuth( 249 jid.Str(), settings.auth_token(), settings.token_service(), mechanism); 250 } 251 252 } // namespace remoting 253