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;
41 const int kDefaultXmppPort
= 5222;
42 const int kDefaultHttpsPort
= 443;
46 XmppSignalStrategy::XmppServerConfig::XmppServerConfig() {}
47 XmppSignalStrategy::XmppServerConfig::~XmppServerConfig() {}
49 XmppSignalStrategy::XmppSignalStrategy(
50 net::ClientSocketFactory
* socket_factory
,
51 const scoped_refptr
<net::URLRequestContextGetter
>& request_context_getter
,
52 const XmppSignalStrategy::XmppServerConfig
& xmpp_server_config
)
53 : socket_factory_(socket_factory
),
54 request_context_getter_(request_context_getter
),
55 resource_name_(kDefaultResourceName
),
56 xmpp_client_(nullptr),
57 xmpp_server_config_(xmpp_server_config
),
61 CHECK(xmpp_server_config_
.use_tls
);
65 XmppSignalStrategy::~XmppSignalStrategy() {
68 // Destroying task runner will destroy XmppClient, but XmppClient may be on
69 // the stack and it doesn't handle this case properly, so we need to delay
71 base::ThreadTaskRunnerHandle::Get()->DeleteSoon(
72 FROM_HERE
, task_runner_
.release());
75 void XmppSignalStrategy::Connect() {
76 DCHECK(CalledOnValidThread());
78 // Disconnect first if we are currently connected.
81 buzz::XmppClientSettings settings
;
82 buzz::Jid
login_jid(xmpp_server_config_
.username
);
83 settings
.set_user(login_jid
.node());
84 settings
.set_host(login_jid
.domain());
85 settings
.set_resource(resource_name_
);
86 settings
.set_token_service("oauth2");
87 settings
.set_auth_token(buzz::AUTH_MECHANISM_GOOGLE_TOKEN
,
88 xmpp_server_config_
.auth_token
);
90 int port
= xmpp_server_config_
.port
;
92 // Port 5222 may be blocked by firewall. talk.google.com allows connections on
93 // port 443 which can be used instead of 5222. The webapp still requests to
94 // use port 5222 for backwards compatibility with older versions of the host
95 // that do not pass correct |use_fake_ssl_client_socket| value to
96 // XmppClientSocketFactory (and so cannot connect to port 443). In case we are
97 // connecting to talk.google.com try to use port 443 anyway.
99 // TODO(sergeyu): Once all hosts support connections on port 443
100 // the webapp needs to be updated to request port 443 and these 2 lines can be
101 // removed. crbug.com/443384
102 if (xmpp_server_config_
.host
== "talk.google.com" && port
== kDefaultXmppPort
)
103 port
= kDefaultHttpsPort
;
106 rtc::SocketAddress(xmpp_server_config_
.host
, port
));
107 settings
.set_use_tls(
108 xmpp_server_config_
.use_tls
? buzz::TLS_ENABLED
: buzz::TLS_DISABLED
);
110 // Enable fake SSL handshake when connecting over HTTPS port.
111 bool use_fake_ssl_client_socket
= (port
== kDefaultHttpsPort
);
113 scoped_ptr
<jingle_glue::XmppClientSocketFactory
> xmpp_socket_factory(
114 new jingle_glue::XmppClientSocketFactory(socket_factory_
,
116 request_context_getter_
,
117 use_fake_ssl_client_socket
));
118 buzz::AsyncSocket
* socket
= new jingle_glue::ChromeAsyncSocket(
119 xmpp_socket_factory
.release(), kReadBufferSize
, kWriteBufferSize
);
121 task_runner_
.reset(new jingle_glue::TaskPump());
122 xmpp_client_
= new buzz::XmppClient(task_runner_
.get());
123 xmpp_client_
->Connect(
124 settings
, std::string(), socket
, CreatePreXmppAuth(settings
));
125 xmpp_client_
->SignalStateChange
126 .connect(this, &XmppSignalStrategy::OnConnectionStateChanged
);
127 xmpp_client_
->engine()->AddStanzaHandler(this, buzz::XmppEngine::HL_TYPE
);
128 xmpp_client_
->Start();
130 SetState(CONNECTING
);
133 void XmppSignalStrategy::Disconnect() {
134 DCHECK(CalledOnValidThread());
137 xmpp_client_
->engine()->RemoveStanzaHandler(this);
139 xmpp_client_
->Disconnect();
141 // |xmpp_client_| should be set to nullptr in OnConnectionStateChanged()
142 // in response to Disconnect() call above.
143 DCHECK(xmpp_client_
== nullptr);
147 SignalStrategy::State
XmppSignalStrategy::GetState() const {
148 DCHECK(CalledOnValidThread());
152 SignalStrategy::Error
XmppSignalStrategy::GetError() const {
153 DCHECK(CalledOnValidThread());
157 std::string
XmppSignalStrategy::GetLocalJid() const {
158 DCHECK(CalledOnValidThread());
159 return xmpp_client_
->jid().Str();
162 void XmppSignalStrategy::AddListener(Listener
* listener
) {
163 DCHECK(CalledOnValidThread());
164 listeners_
.AddObserver(listener
);
167 void XmppSignalStrategy::RemoveListener(Listener
* listener
) {
168 DCHECK(CalledOnValidThread());
169 listeners_
.RemoveObserver(listener
);
172 bool XmppSignalStrategy::SendStanza(scoped_ptr
<buzz::XmlElement
> stanza
) {
173 DCHECK(CalledOnValidThread());
175 VLOG(0) << "Dropping signalling message because XMPP "
176 "connection has been terminated.";
180 buzz::XmppReturnStatus status
= xmpp_client_
->SendStanza(stanza
.release());
181 return status
== buzz::XMPP_RETURN_OK
|| status
== buzz::XMPP_RETURN_PENDING
;
184 std::string
XmppSignalStrategy::GetNextId() {
185 DCHECK(CalledOnValidThread());
187 // If the connection has been terminated then it doesn't matter
188 // what Id we return.
189 return std::string();
191 return xmpp_client_
->NextId();
194 bool XmppSignalStrategy::HandleStanza(const buzz::XmlElement
* stanza
) {
195 DCHECK(CalledOnValidThread());
196 ObserverListBase
<Listener
>::Iterator
it(listeners_
);
198 while ((listener
= it
.GetNext()) != nullptr) {
199 if (listener
->OnSignalStrategyIncomingStanza(stanza
))
205 void XmppSignalStrategy::SetAuthInfo(const std::string
& username
,
206 const std::string
& auth_token
) {
207 DCHECK(CalledOnValidThread());
208 xmpp_server_config_
.username
= username
;
209 xmpp_server_config_
.auth_token
= auth_token
;
212 void XmppSignalStrategy::SetResourceName(const std::string
&resource_name
) {
213 DCHECK(CalledOnValidThread());
214 resource_name_
= resource_name
;
217 void XmppSignalStrategy::OnConnectionStateChanged(
218 buzz::XmppEngine::State state
) {
219 DCHECK(CalledOnValidThread());
221 if (state
== buzz::XmppEngine::STATE_OPEN
) {
222 keep_alive_timer_
.Start(
223 FROM_HERE
, base::TimeDelta::FromSeconds(kKeepAliveIntervalSeconds
),
224 this, &XmppSignalStrategy::SendKeepAlive
);
226 } else if (state
== buzz::XmppEngine::STATE_CLOSED
) {
227 // Make sure we dump errors to the log.
229 buzz::XmppEngine::Error error
= xmpp_client_
->GetError(&subcode
);
230 VLOG(0) << "XMPP connection was closed: error=" << error
231 << ", subcode=" << subcode
;
233 keep_alive_timer_
.Stop();
235 // Client is destroyed by the TaskRunner after the client is
236 // closed. Reset the pointer so we don't try to use it later.
237 xmpp_client_
= nullptr;
240 case buzz::XmppEngine::ERROR_UNAUTHORIZED
:
241 case buzz::XmppEngine::ERROR_AUTH
:
242 case buzz::XmppEngine::ERROR_MISSING_USERNAME
:
243 error_
= AUTHENTICATION_FAILED
;
247 error_
= NETWORK_ERROR
;
250 SetState(DISCONNECTED
);
254 void XmppSignalStrategy::SetState(State new_state
) {
255 if (state_
!= new_state
) {
257 FOR_EACH_OBSERVER(Listener
, listeners_
,
258 OnSignalStrategyStateChange(new_state
));
262 void XmppSignalStrategy::SendKeepAlive() {
263 xmpp_client_
->SendRaw(" ");
267 buzz::PreXmppAuth
* XmppSignalStrategy::CreatePreXmppAuth(
268 const buzz::XmppClientSettings
& settings
) {
269 buzz::Jid
jid(settings
.user(), settings
.host(), buzz::STR_EMPTY
);
270 return new notifier::GaiaTokenPreXmppAuth(
271 jid
.Str(), settings
.auth_token(), settings
.token_service(), "X-OAUTH2");
274 } // namespace remoting