summaryrefslogtreecommitdiffstats
path: root/remoting/jingle_glue/xmpp_signal_strategy.cc
blob: 5969817e450e491e43695d3cbc220f119eb4950e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "remoting/jingle_glue/xmpp_signal_strategy.h"

#include "base/bind.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "jingle/notifier/base/gaia_token_pre_xmpp_auth.h"
#include "remoting/jingle_glue/jingle_thread.h"
#include "remoting/jingle_glue/xmpp_socket_adapter.h"
#include "third_party/libjingle/source/talk/base/asyncsocket.h"
#include "third_party/libjingle/source/talk/xmpp/prexmppauth.h"
#include "third_party/libjingle/source/talk/xmpp/saslcookiemechanism.h"

namespace {

const char kDefaultResourceName[] = "chromoting";

// Use 58 seconds keep-alive interval, in case routers terminate
// connections that are idle for more than a minute.
const int kKeepAliveIntervalSeconds = 50;

void DisconnectXmppClient(buzz::XmppClient* client) {
  client->Disconnect();
}

}  // namespace

namespace remoting {

XmppSignalStrategy::XmppSignalStrategy(JingleThread* jingle_thread,
                                       const std::string& username,
                                       const std::string& auth_token,
                                       const std::string& auth_token_service)
   : thread_(jingle_thread),
     username_(username),
     auth_token_(auth_token),
     auth_token_service_(auth_token_service),
     resource_name_(kDefaultResourceName),
     xmpp_client_(NULL),
     state_(DISCONNECTED),
     error_(OK) {
}

XmppSignalStrategy::~XmppSignalStrategy() {
  Disconnect();
}

void XmppSignalStrategy::Connect() {
  DCHECK(CalledOnValidThread());

  // Disconnect first if we are currently connected.
  Disconnect();

  buzz::XmppClientSettings settings;
  buzz::Jid login_jid(username_);
  settings.set_user(login_jid.node());
  settings.set_host(login_jid.domain());
  settings.set_resource(resource_name_);
  settings.set_use_tls(buzz::TLS_ENABLED);
  settings.set_token_service(auth_token_service_);
  settings.set_auth_token(buzz::AUTH_MECHANISM_GOOGLE_TOKEN, auth_token_);
  settings.set_server(talk_base::SocketAddress("talk.google.com", 5222));

  buzz::AsyncSocket* socket = new XmppSocketAdapter(settings, false);

  xmpp_client_ = new buzz::XmppClient(thread_->task_pump());
  xmpp_client_->Connect(settings, "", socket, CreatePreXmppAuth(settings));
  xmpp_client_->SignalStateChange.connect(
      this, &XmppSignalStrategy::OnConnectionStateChanged);
  xmpp_client_->engine()->AddStanzaHandler(this, buzz::XmppEngine::HL_TYPE);
  xmpp_client_->Start();

  SetState(CONNECTING);
}

void XmppSignalStrategy::Disconnect() {
  DCHECK(CalledOnValidThread());

  if (xmpp_client_) {
    xmpp_client_->engine()->RemoveStanzaHandler(this);

    xmpp_client_->Disconnect();

    // |xmpp_client_| should be set to NULL in OnConnectionStateChanged()
    // in response to Disconnect() call above.
    DCHECK(xmpp_client_ == NULL);
  }
}

SignalStrategy::State XmppSignalStrategy::GetState() const {
  DCHECK(CalledOnValidThread());
  return state_;
}

SignalStrategy::Error XmppSignalStrategy::GetError() const {
  DCHECK(CalledOnValidThread());
  return error_;
}

std::string XmppSignalStrategy::GetLocalJid() const {
  DCHECK(CalledOnValidThread());
  return xmpp_client_->jid().Str();
}

void XmppSignalStrategy::AddListener(Listener* listener) {
  DCHECK(CalledOnValidThread());
  listeners_.AddObserver(listener);
}

void XmppSignalStrategy::RemoveListener(Listener* listener) {
  DCHECK(CalledOnValidThread());
  listeners_.RemoveObserver(listener);
}

bool XmppSignalStrategy::SendStanza(scoped_ptr<buzz::XmlElement> stanza) {
  DCHECK(CalledOnValidThread());
  if (!xmpp_client_) {
    LOG(INFO) << "Dropping signalling message because XMPP "
        "connection has been terminated.";
    return false;
  }

  buzz::XmppReturnStatus status = xmpp_client_->SendStanza(stanza.release());
  return status == buzz::XMPP_RETURN_OK || status == buzz::XMPP_RETURN_PENDING;
}

std::string XmppSignalStrategy::GetNextId() {
  DCHECK(CalledOnValidThread());
  if (!xmpp_client_) {
    // If the connection has been terminated then it doesn't matter
    // what Id we return.
    return "";
  }
  return xmpp_client_->NextId();
}

bool XmppSignalStrategy::HandleStanza(const buzz::XmlElement* stanza) {
  DCHECK(CalledOnValidThread());
  ObserverListBase<Listener>::Iterator it(listeners_);
  Listener* listener;
  while ((listener = it.GetNext()) != NULL) {
    if (listener->OnSignalStrategyIncomingStanza(stanza))
      return true;
  }
  return false;
}

void XmppSignalStrategy::SetAuthInfo(const std::string& username,
                                     const std::string& auth_token,
                                     const std::string& auth_token_service) {
  DCHECK(CalledOnValidThread());
  username_ = username;
  auth_token_ = auth_token;
  auth_token_service_ = auth_token_service;
}

void XmppSignalStrategy::SetResourceName(const std::string &resource_name) {
  DCHECK(CalledOnValidThread());
  resource_name_ = resource_name;
}

void XmppSignalStrategy::OnConnectionStateChanged(
    buzz::XmppEngine::State state) {
  DCHECK(CalledOnValidThread());

  if (state == buzz::XmppEngine::STATE_OPEN) {
    keep_alive_timer_.Start(
        FROM_HERE, base::TimeDelta::FromSeconds(kKeepAliveIntervalSeconds),
        this, &XmppSignalStrategy::SendKeepAlive);
    SetState(CONNECTED);
  } else if (state == buzz::XmppEngine::STATE_CLOSED) {
    // Make sure we dump errors to the log.
    int subcode;
    buzz::XmppEngine::Error error = xmpp_client_->GetError(&subcode);
    LOG(INFO) << "XMPP connection was closed: error=" << error
              << ", subcode=" << subcode;

    keep_alive_timer_.Stop();

    // Client is destroyed by the TaskRunner after the client is
    // closed. Reset the pointer so we don't try to use it later.
    xmpp_client_ = NULL;

    switch (error) {
      case buzz::XmppEngine::ERROR_UNAUTHORIZED:
      case buzz::XmppEngine::ERROR_AUTH:
      case buzz::XmppEngine::ERROR_MISSING_USERNAME:
        error_ = AUTHENTICATION_FAILED;
        break;

      default:
        error_ = NETWORK_ERROR;
    }

    SetState(DISCONNECTED);
  }
}

void XmppSignalStrategy::SetState(State new_state) {
  if (state_ != new_state) {
    state_ = new_state;
    FOR_EACH_OBSERVER(Listener, listeners_,
                      OnSignalStrategyStateChange(new_state));
  }
}

void XmppSignalStrategy::SendKeepAlive() {
  xmpp_client_->SendRaw(" ");
}

// static
buzz::PreXmppAuth* XmppSignalStrategy::CreatePreXmppAuth(
    const buzz::XmppClientSettings& settings) {
  buzz::Jid jid(settings.user(), settings.host(), buzz::STR_EMPTY);
  std::string mechanism = notifier::GaiaTokenPreXmppAuth::kDefaultAuthMechanism;
  if (settings.token_service() == "oauth2") {
    mechanism = "X-OAUTH2";
  }

  return new notifier::GaiaTokenPreXmppAuth(
      jid.Str(), settings.auth_token(), settings.token_service(), mechanism);
}

}  // namespace remoting