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.
5 #include "remoting/signaling/xmpp_signal_strategy.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/webrtc/base/thread.h"
21 #include "third_party/webrtc/libjingle/xmpp/prexmppauth.h"
22 #include "third_party/webrtc/libjingle/xmpp/saslcookiemechanism.h"
24 const char kDefaultResourceName
[] = "chromoting";
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;
30 // Read buffer size used by ChromeAsyncSocket for read and write buffers.
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
38 const size_t kReadBufferSize
= 64 * 1024;
39 const size_t kWriteBufferSize
= 64 * 1024;
43 XmppSignalStrategy::XmppServerConfig::XmppServerConfig() {}
44 XmppSignalStrategy::XmppServerConfig::~XmppServerConfig() {}
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
),
54 xmpp_server_config_(xmpp_server_config
),
58 CHECK(xmpp_server_config_
.use_tls
);
62 XmppSignalStrategy::~XmppSignalStrategy() {
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
68 base::ThreadTaskRunnerHandle::Get()->DeleteSoon(
69 FROM_HERE
, task_runner_
.release());
72 void XmppSignalStrategy::Connect() {
73 DCHECK(CalledOnValidThread());
75 // Disconnect first if we are currently connected.
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
));
89 xmpp_server_config_
.use_tls
? buzz::TLS_ENABLED
: buzz::TLS_DISABLED
);
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
);
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();
106 SetState(CONNECTING
);
109 void XmppSignalStrategy::Disconnect() {
110 DCHECK(CalledOnValidThread());
113 xmpp_client_
->engine()->RemoveStanzaHandler(this);
115 xmpp_client_
->Disconnect();
117 // |xmpp_client_| should be set to NULL in OnConnectionStateChanged()
118 // in response to Disconnect() call above.
119 DCHECK(xmpp_client_
== NULL
);
123 SignalStrategy::State
XmppSignalStrategy::GetState() const {
124 DCHECK(CalledOnValidThread());
128 SignalStrategy::Error
XmppSignalStrategy::GetError() const {
129 DCHECK(CalledOnValidThread());
133 std::string
XmppSignalStrategy::GetLocalJid() const {
134 DCHECK(CalledOnValidThread());
135 return xmpp_client_
->jid().Str();
138 void XmppSignalStrategy::AddListener(Listener
* listener
) {
139 DCHECK(CalledOnValidThread());
140 listeners_
.AddObserver(listener
);
143 void XmppSignalStrategy::RemoveListener(Listener
* listener
) {
144 DCHECK(CalledOnValidThread());
145 listeners_
.RemoveObserver(listener
);
148 bool XmppSignalStrategy::SendStanza(scoped_ptr
<buzz::XmlElement
> stanza
) {
149 DCHECK(CalledOnValidThread());
151 VLOG(0) << "Dropping signalling message because XMPP "
152 "connection has been terminated.";
156 buzz::XmppReturnStatus status
= xmpp_client_
->SendStanza(stanza
.release());
157 return status
== buzz::XMPP_RETURN_OK
|| status
== buzz::XMPP_RETURN_PENDING
;
160 std::string
XmppSignalStrategy::GetNextId() {
161 DCHECK(CalledOnValidThread());
163 // If the connection has been terminated then it doesn't matter
164 // what Id we return.
165 return std::string();
167 return xmpp_client_
->NextId();
170 bool XmppSignalStrategy::HandleStanza(const buzz::XmlElement
* stanza
) {
171 DCHECK(CalledOnValidThread());
172 ObserverListBase
<Listener
>::Iterator
it(listeners_
);
174 while ((listener
= it
.GetNext()) != NULL
) {
175 if (listener
->OnSignalStrategyIncomingStanza(stanza
))
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
;
190 void XmppSignalStrategy::SetResourceName(const std::string
&resource_name
) {
191 DCHECK(CalledOnValidThread());
192 resource_name_
= resource_name
;
195 void XmppSignalStrategy::OnConnectionStateChanged(
196 buzz::XmppEngine::State state
) {
197 DCHECK(CalledOnValidThread());
199 if (state
== buzz::XmppEngine::STATE_OPEN
) {
200 keep_alive_timer_
.Start(
201 FROM_HERE
, base::TimeDelta::FromSeconds(kKeepAliveIntervalSeconds
),
202 this, &XmppSignalStrategy::SendKeepAlive
);
204 } else if (state
== buzz::XmppEngine::STATE_CLOSED
) {
205 // Make sure we dump errors to the log.
207 buzz::XmppEngine::Error error
= xmpp_client_
->GetError(&subcode
);
208 VLOG(0) << "XMPP connection was closed: error=" << error
209 << ", subcode=" << subcode
;
211 keep_alive_timer_
.Stop();
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.
218 case buzz::XmppEngine::ERROR_UNAUTHORIZED
:
219 case buzz::XmppEngine::ERROR_AUTH
:
220 case buzz::XmppEngine::ERROR_MISSING_USERNAME
:
221 error_
= AUTHENTICATION_FAILED
;
225 error_
= NETWORK_ERROR
;
228 SetState(DISCONNECTED
);
232 void XmppSignalStrategy::SetState(State new_state
) {
233 if (state_
!= new_state
) {
235 FOR_EACH_OBSERVER(Listener
, listeners_
,
236 OnSignalStrategyStateChange(new_state
));
240 void XmppSignalStrategy::SendKeepAlive() {
241 xmpp_client_
->SendRaw(" ");
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";
253 return new notifier::GaiaTokenPreXmppAuth(
254 jid
.Str(), settings
.auth_token(), settings
.token_service(), mechanism
);
257 } // namespace remoting