1 // Copyright 2014 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/signaling/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/xmpp/prexmppauth.h"
21 #include "third_party/libjingle/source/talk/xmpp/saslcookiemechanism.h"
22 #include "third_party/webrtc/base/thread.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.
31 //
32 // TODO(sergeyu): Currently jingle::ChromeAsyncSocket fails Write() when the
33 // write buffer is full and talk::XmppClient just ignores the error. As result
34 // chunks of data sent to the server are dropped (and they may not be full XMPP
35 // stanzas). The problem needs to be fixed either in XmppClient on
36 // ChromeAsyncSocket (e.g. ChromeAsyncSocket could close the connection when
37 // buffer is full).
38 const size_t kReadBufferSize = 64 * 1024;
39 const size_t kWriteBufferSize = 64 * 1024;
40
41 namespace remoting {
42
XmppServerConfig()43 XmppSignalStrategy::XmppServerConfig::XmppServerConfig() {}
~XmppServerConfig()44 XmppSignalStrategy::XmppServerConfig::~XmppServerConfig() {}
45
XmppSignalStrategy(net::ClientSocketFactory * socket_factory,scoped_refptr<net::URLRequestContextGetter> request_context_getter,const XmppSignalStrategy::XmppServerConfig & xmpp_server_config)46 XmppSignalStrategy::XmppSignalStrategy(
47 net::ClientSocketFactory* socket_factory,
48 scoped_refptr<net::URLRequestContextGetter> request_context_getter,
49 const XmppSignalStrategy::XmppServerConfig& xmpp_server_config)
50 : socket_factory_(socket_factory),
51 request_context_getter_(request_context_getter),
52 resource_name_(kDefaultResourceName),
53 xmpp_client_(NULL),
54 xmpp_server_config_(xmpp_server_config),
55 state_(DISCONNECTED),
56 error_(OK) {
57 #if defined(NDEBUG)
58 CHECK(xmpp_server_config_.use_tls);
59 #endif
60 }
61
~XmppSignalStrategy()62 XmppSignalStrategy::~XmppSignalStrategy() {
63 Disconnect();
64
65 // Destroying task runner will destroy XmppClient, but XmppClient may be on
66 // the stack and it doesn't handle this case properly, so we need to delay
67 // destruction.
68 base::ThreadTaskRunnerHandle::Get()->DeleteSoon(
69 FROM_HERE, task_runner_.release());
70 }
71
Connect()72 void XmppSignalStrategy::Connect() {
73 DCHECK(CalledOnValidThread());
74
75 // Disconnect first if we are currently connected.
76 Disconnect();
77
78 buzz::XmppClientSettings settings;
79 buzz::Jid login_jid(xmpp_server_config_.username);
80 settings.set_user(login_jid.node());
81 settings.set_host(login_jid.domain());
82 settings.set_resource(resource_name_);
83 settings.set_token_service(xmpp_server_config_.auth_service);
84 settings.set_auth_token(buzz::AUTH_MECHANISM_GOOGLE_TOKEN,
85 xmpp_server_config_.auth_token);
86 settings.set_server(rtc::SocketAddress(
87 xmpp_server_config_.host, xmpp_server_config_.port));
88 settings.set_use_tls(
89 xmpp_server_config_.use_tls ? buzz::TLS_ENABLED : buzz::TLS_DISABLED);
90
91 scoped_ptr<jingle_glue::XmppClientSocketFactory> xmpp_socket_factory(
92 new jingle_glue::XmppClientSocketFactory(
93 socket_factory_, net::SSLConfig(), request_context_getter_, false));
94 buzz::AsyncSocket* socket = new jingle_glue::ChromeAsyncSocket(
95 xmpp_socket_factory.release(), kReadBufferSize, kWriteBufferSize);
96
97 task_runner_.reset(new jingle_glue::TaskPump());
98 xmpp_client_ = new buzz::XmppClient(task_runner_.get());
99 xmpp_client_->Connect(
100 settings, std::string(), socket, CreatePreXmppAuth(settings));
101 xmpp_client_->SignalStateChange
102 .connect(this, &XmppSignalStrategy::OnConnectionStateChanged);
103 xmpp_client_->engine()->AddStanzaHandler(this, buzz::XmppEngine::HL_TYPE);
104 xmpp_client_->Start();
105
106 SetState(CONNECTING);
107 }
108
Disconnect()109 void XmppSignalStrategy::Disconnect() {
110 DCHECK(CalledOnValidThread());
111
112 if (xmpp_client_) {
113 xmpp_client_->engine()->RemoveStanzaHandler(this);
114
115 xmpp_client_->Disconnect();
116
117 // |xmpp_client_| should be set to NULL in OnConnectionStateChanged()
118 // in response to Disconnect() call above.
119 DCHECK(xmpp_client_ == NULL);
120 }
121 }
122
GetState() const123 SignalStrategy::State XmppSignalStrategy::GetState() const {
124 DCHECK(CalledOnValidThread());
125 return state_;
126 }
127
GetError() const128 SignalStrategy::Error XmppSignalStrategy::GetError() const {
129 DCHECK(CalledOnValidThread());
130 return error_;
131 }
132
GetLocalJid() const133 std::string XmppSignalStrategy::GetLocalJid() const {
134 DCHECK(CalledOnValidThread());
135 return xmpp_client_->jid().Str();
136 }
137
AddListener(Listener * listener)138 void XmppSignalStrategy::AddListener(Listener* listener) {
139 DCHECK(CalledOnValidThread());
140 listeners_.AddObserver(listener);
141 }
142
RemoveListener(Listener * listener)143 void XmppSignalStrategy::RemoveListener(Listener* listener) {
144 DCHECK(CalledOnValidThread());
145 listeners_.RemoveObserver(listener);
146 }
147
SendStanza(scoped_ptr<buzz::XmlElement> stanza)148 bool XmppSignalStrategy::SendStanza(scoped_ptr<buzz::XmlElement> stanza) {
149 DCHECK(CalledOnValidThread());
150 if (!xmpp_client_) {
151 VLOG(0) << "Dropping signalling message because XMPP "
152 "connection has been terminated.";
153 return false;
154 }
155
156 buzz::XmppReturnStatus status = xmpp_client_->SendStanza(stanza.release());
157 return status == buzz::XMPP_RETURN_OK || status == buzz::XMPP_RETURN_PENDING;
158 }
159
GetNextId()160 std::string XmppSignalStrategy::GetNextId() {
161 DCHECK(CalledOnValidThread());
162 if (!xmpp_client_) {
163 // If the connection has been terminated then it doesn't matter
164 // what Id we return.
165 return std::string();
166 }
167 return xmpp_client_->NextId();
168 }
169
HandleStanza(const buzz::XmlElement * stanza)170 bool XmppSignalStrategy::HandleStanza(const buzz::XmlElement* stanza) {
171 DCHECK(CalledOnValidThread());
172 ObserverListBase<Listener>::Iterator it(listeners_);
173 Listener* listener;
174 while ((listener = it.GetNext()) != NULL) {
175 if (listener->OnSignalStrategyIncomingStanza(stanza))
176 return true;
177 }
178 return false;
179 }
180
SetAuthInfo(const std::string & username,const std::string & auth_token,const std::string & auth_service)181 void XmppSignalStrategy::SetAuthInfo(const std::string& username,
182 const std::string& auth_token,
183 const std::string& auth_service) {
184 DCHECK(CalledOnValidThread());
185 xmpp_server_config_.username = username;
186 xmpp_server_config_.auth_token = auth_token;
187 xmpp_server_config_.auth_service = auth_service;
188 }
189
SetResourceName(const std::string & resource_name)190 void XmppSignalStrategy::SetResourceName(const std::string &resource_name) {
191 DCHECK(CalledOnValidThread());
192 resource_name_ = resource_name;
193 }
194
OnConnectionStateChanged(buzz::XmppEngine::State state)195 void XmppSignalStrategy::OnConnectionStateChanged(
196 buzz::XmppEngine::State state) {
197 DCHECK(CalledOnValidThread());
198
199 if (state == buzz::XmppEngine::STATE_OPEN) {
200 keep_alive_timer_.Start(
201 FROM_HERE, base::TimeDelta::FromSeconds(kKeepAliveIntervalSeconds),
202 this, &XmppSignalStrategy::SendKeepAlive);
203 SetState(CONNECTED);
204 } else if (state == buzz::XmppEngine::STATE_CLOSED) {
205 // Make sure we dump errors to the log.
206 int subcode;
207 buzz::XmppEngine::Error error = xmpp_client_->GetError(&subcode);
208 VLOG(0) << "XMPP connection was closed: error=" << error
209 << ", subcode=" << subcode;
210
211 keep_alive_timer_.Stop();
212
213 // Client is destroyed by the TaskRunner after the client is
214 // closed. Reset the pointer so we don't try to use it later.
215 xmpp_client_ = NULL;
216
217 switch (error) {
218 case buzz::XmppEngine::ERROR_UNAUTHORIZED:
219 case buzz::XmppEngine::ERROR_AUTH:
220 case buzz::XmppEngine::ERROR_MISSING_USERNAME:
221 error_ = AUTHENTICATION_FAILED;
222 break;
223
224 default:
225 error_ = NETWORK_ERROR;
226 }
227
228 SetState(DISCONNECTED);
229 }
230 }
231
SetState(State new_state)232 void XmppSignalStrategy::SetState(State new_state) {
233 if (state_ != new_state) {
234 state_ = new_state;
235 FOR_EACH_OBSERVER(Listener, listeners_,
236 OnSignalStrategyStateChange(new_state));
237 }
238 }
239
SendKeepAlive()240 void XmppSignalStrategy::SendKeepAlive() {
241 xmpp_client_->SendRaw(" ");
242 }
243
244 // static
CreatePreXmppAuth(const buzz::XmppClientSettings & settings)245 buzz::PreXmppAuth* XmppSignalStrategy::CreatePreXmppAuth(
246 const buzz::XmppClientSettings& settings) {
247 buzz::Jid jid(settings.user(), settings.host(), buzz::STR_EMPTY);
248 std::string mechanism = notifier::kDefaultGaiaAuthMechanism;
249 if (settings.token_service() == "oauth2") {
250 mechanism = "X-OAUTH2";
251 }
252
253 return new notifier::GaiaTokenPreXmppAuth(
254 jid.Str(), settings.auth_token(), settings.token_service(), mechanism);
255 }
256
257 } // namespace remoting
258