1// Copyright 2013 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/host/it2me/it2me_native_messaging_host.h"
6
7#include <string>
8
9#include "base/basictypes.h"
10#include "base/bind.h"
11#include "base/callback.h"
12#include "base/callback_helpers.h"
13#include "base/message_loop/message_loop.h"
14#include "base/run_loop.h"
15#include "base/strings/string_number_conversions.h"
16#include "base/strings/stringize_macros.h"
17#include "base/threading/thread.h"
18#include "base/values.h"
19#include "net/base/net_util.h"
20#include "net/url_request/url_fetcher.h"
21#include "remoting/base/auth_token_util.h"
22#include "remoting/base/service_urls.h"
23#include "remoting/host/chromoting_host_context.h"
24#include "remoting/host/host_exit_codes.h"
25#include "remoting/protocol/name_value_map.h"
26
27namespace remoting {
28
29namespace {
30
31const remoting::protocol::NameMapElement<It2MeHostState> kIt2MeHostStates[] = {
32    {kDisconnected, "DISCONNECTED"},
33    {kStarting, "STARTING"},
34    {kRequestedAccessCode, "REQUESTED_ACCESS_CODE"},
35    {kReceivedAccessCode, "RECEIVED_ACCESS_CODE"},
36    {kConnected, "CONNECTED"},
37    {kDisconnecting, "DISCONNECTING"},
38    {kError, "ERROR"},
39    {kInvalidDomainError, "INVALID_DOMAIN_ERROR"}, };
40
41}  // namespace
42
43It2MeNativeMessagingHost::It2MeNativeMessagingHost(
44    scoped_refptr<AutoThreadTaskRunner> task_runner,
45    scoped_ptr<extensions::NativeMessagingChannel> channel,
46    scoped_ptr<It2MeHostFactory> factory)
47    : channel_(channel.Pass()),
48      factory_(factory.Pass()),
49      weak_factory_(this) {
50  weak_ptr_ = weak_factory_.GetWeakPtr();
51
52  // Initialize the host context to manage the threads for the it2me host.
53  // The native messaging host, rather than the It2MeHost object, owns and
54  // maintains the lifetime of the host context.
55
56  host_context_.reset(ChromotingHostContext::Create(task_runner).release());
57
58  const ServiceUrls* service_urls = ServiceUrls::GetInstance();
59  const bool xmpp_server_valid =
60      net::ParseHostAndPort(service_urls->xmpp_server_address(),
61                            &xmpp_server_config_.host,
62                            &xmpp_server_config_.port);
63  DCHECK(xmpp_server_valid);
64
65  xmpp_server_config_.use_tls = service_urls->xmpp_server_use_tls();
66  directory_bot_jid_ = service_urls->directory_bot_jid();
67}
68
69It2MeNativeMessagingHost::~It2MeNativeMessagingHost() {
70  DCHECK(task_runner()->BelongsToCurrentThread());
71
72  if (it2me_host_.get()) {
73    it2me_host_->Disconnect();
74    it2me_host_ = NULL;
75  }
76}
77
78void It2MeNativeMessagingHost::Start(const base::Closure& quit_closure) {
79  DCHECK(task_runner()->BelongsToCurrentThread());
80  DCHECK(!quit_closure.is_null());
81
82  quit_closure_ = quit_closure;
83
84  channel_->Start(this);
85}
86
87void It2MeNativeMessagingHost::OnMessage(scoped_ptr<base::Value> message) {
88  DCHECK(task_runner()->BelongsToCurrentThread());
89
90  scoped_ptr<base::DictionaryValue> message_dict(
91      static_cast<base::DictionaryValue*>(message.release()));
92  scoped_ptr<base::DictionaryValue> response(new base::DictionaryValue());
93
94  // If the client supplies an ID, it will expect it in the response. This
95  // might be a string or a number, so cope with both.
96  const base::Value* id;
97  if (message_dict->Get("id", &id))
98    response->Set("id", id->DeepCopy());
99
100  std::string type;
101  if (!message_dict->GetString("type", &type)) {
102    SendErrorAndExit(response.Pass(), "'type' not found in request.");
103    return;
104  }
105
106  response->SetString("type", type + "Response");
107
108  if (type == "hello") {
109    ProcessHello(*message_dict, response.Pass());
110  } else if (type == "connect") {
111    ProcessConnect(*message_dict, response.Pass());
112  } else if (type == "disconnect") {
113    ProcessDisconnect(*message_dict, response.Pass());
114  } else {
115    SendErrorAndExit(response.Pass(), "Unsupported request type: " + type);
116  }
117}
118
119void It2MeNativeMessagingHost::OnDisconnect() {
120  if (!quit_closure_.is_null())
121    base::ResetAndReturn(&quit_closure_).Run();
122}
123
124void It2MeNativeMessagingHost::ProcessHello(
125    const base::DictionaryValue& message,
126    scoped_ptr<base::DictionaryValue> response) const {
127  DCHECK(task_runner()->BelongsToCurrentThread());
128
129  response->SetString("version", STRINGIZE(VERSION));
130
131  // This list will be populated when new features are added.
132  scoped_ptr<base::ListValue> supported_features_list(new base::ListValue());
133  response->Set("supportedFeatures", supported_features_list.release());
134
135  channel_->SendMessage(response.PassAs<base::Value>());
136}
137
138void It2MeNativeMessagingHost::ProcessConnect(
139    const base::DictionaryValue& message,
140    scoped_ptr<base::DictionaryValue> response) {
141  DCHECK(task_runner()->BelongsToCurrentThread());
142
143  if (it2me_host_.get()) {
144    SendErrorAndExit(response.Pass(),
145                     "Connect can be called only when disconnected.");
146    return;
147  }
148
149  XmppSignalStrategy::XmppServerConfig xmpp_config = xmpp_server_config_;
150
151  if (!message.GetString("userName", &xmpp_config.username)) {
152    SendErrorAndExit(response.Pass(), "'userName' not found in request.");
153    return;
154  }
155
156  std::string auth_service_with_token;
157  if (!message.GetString("authServiceWithToken", &auth_service_with_token)) {
158    SendErrorAndExit(response.Pass(),
159                     "'authServiceWithToken' not found in request.");
160    return;
161  }
162
163  ParseAuthTokenWithService(auth_service_with_token,
164                            &xmpp_config.auth_token,
165                            &xmpp_config.auth_service);
166  if (xmpp_config.auth_token.empty()) {
167    SendErrorAndExit(
168        response.Pass(),
169        "Invalid 'authServiceWithToken': " + auth_service_with_token);
170    return;
171  }
172
173#if !defined(NDEBUG)
174  std::string address;
175  if (!message.GetString("xmppServerAddress", &address)) {
176    SendErrorAndExit(response.Pass(),
177                     "'xmppServerAddress' not found in request.");
178    return;
179  }
180
181  if (!net::ParseHostAndPort(
182           address, &xmpp_server_config_.host, &xmpp_server_config_.port)) {
183    SendErrorAndExit(response.Pass(),
184                     "Invalid 'xmppServerAddress': " + address);
185    return;
186  }
187
188  if (!message.GetBoolean("xmppServerUseTls", &xmpp_server_config_.use_tls)) {
189    SendErrorAndExit(response.Pass(),
190                     "'xmppServerUseTls' not found in request.");
191    return;
192  }
193
194  if (!message.GetString("directoryBotJid", &directory_bot_jid_)) {
195    SendErrorAndExit(response.Pass(),
196                     "'directoryBotJid' not found in request.");
197    return;
198  }
199#endif  // !defined(NDEBUG)
200
201  // Create the It2Me host and start connecting.
202  it2me_host_ = factory_->CreateIt2MeHost(host_context_.get(),
203                                          host_context_->ui_task_runner(),
204                                          weak_ptr_,
205                                          xmpp_config,
206                                          directory_bot_jid_);
207  it2me_host_->Connect();
208
209  channel_->SendMessage(response.PassAs<base::Value>());
210}
211
212void It2MeNativeMessagingHost::ProcessDisconnect(
213    const base::DictionaryValue& message,
214    scoped_ptr<base::DictionaryValue> response) {
215  DCHECK(task_runner()->BelongsToCurrentThread());
216
217  if (it2me_host_.get()) {
218    it2me_host_->Disconnect();
219    it2me_host_ = NULL;
220  }
221  channel_->SendMessage(response.PassAs<base::Value>());
222}
223
224void It2MeNativeMessagingHost::SendErrorAndExit(
225    scoped_ptr<base::DictionaryValue> response,
226    const std::string& description) const {
227  DCHECK(task_runner()->BelongsToCurrentThread());
228
229  LOG(ERROR) << description;
230
231  response->SetString("type", "error");
232  response->SetString("description", description);
233  channel_->SendMessage(response.PassAs<base::Value>());
234
235  // Trigger a host shutdown by sending a NULL message.
236  channel_->SendMessage(scoped_ptr<base::Value>());
237}
238
239void It2MeNativeMessagingHost::OnStateChanged(It2MeHostState state) {
240  DCHECK(task_runner()->BelongsToCurrentThread());
241
242  state_ = state;
243
244  scoped_ptr<base::DictionaryValue> message(new base::DictionaryValue());
245
246  message->SetString("type", "hostStateChanged");
247  message->SetString("state",
248                     It2MeNativeMessagingHost::HostStateToString(state));
249
250  switch (state_) {
251    case kReceivedAccessCode:
252      message->SetString("accessCode", access_code_);
253      message->SetInteger("accessCodeLifetime",
254                          access_code_lifetime_.InSeconds());
255      break;
256
257    case kConnected:
258      message->SetString("client", client_username_);
259      break;
260
261    case kDisconnected:
262      client_username_.clear();
263      break;
264
265    default:
266      ;
267  }
268
269  channel_->SendMessage(message.PassAs<base::Value>());
270}
271
272void It2MeNativeMessagingHost::OnNatPolicyChanged(bool nat_traversal_enabled) {
273  DCHECK(task_runner()->BelongsToCurrentThread());
274
275  scoped_ptr<base::DictionaryValue> message(new base::DictionaryValue());
276
277  message->SetString("type", "natPolicyChanged");
278  message->SetBoolean("natTraversalEnabled", nat_traversal_enabled);
279  channel_->SendMessage(message.PassAs<base::Value>());
280}
281
282// Stores the Access Code for the web-app to query.
283void It2MeNativeMessagingHost::OnStoreAccessCode(
284    const std::string& access_code,
285    base::TimeDelta access_code_lifetime) {
286  DCHECK(task_runner()->BelongsToCurrentThread());
287
288  access_code_ = access_code;
289  access_code_lifetime_ = access_code_lifetime;
290}
291
292// Stores the client user's name for the web-app to query.
293void It2MeNativeMessagingHost::OnClientAuthenticated(
294    const std::string& client_username) {
295  DCHECK(task_runner()->BelongsToCurrentThread());
296
297  client_username_ = client_username;
298}
299
300scoped_refptr<AutoThreadTaskRunner>
301It2MeNativeMessagingHost::task_runner() const {
302  return host_context_->ui_task_runner();
303}
304
305/* static */
306std::string It2MeNativeMessagingHost::HostStateToString(
307    It2MeHostState host_state) {
308  return ValueToName(kIt2MeHostStates, host_state);
309}
310
311}  // namespace remoting
312
313