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.
5 #include "remoting/host/it2me/it2me_native_messaging_host.h"
9 #include "base/basictypes.h"
10 #include "base/bind.h"
11 #include "base/callback.h"
12 #include "base/json/json_reader.h"
13 #include "base/json/json_writer.h"
14 #include "base/strings/string_number_conversions.h"
15 #include "base/strings/string_util.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_request_context_getter.h"
21 #include "remoting/base/service_urls.h"
22 #include "remoting/host/chromoting_host_context.h"
23 #include "remoting/host/host_exit_codes.h"
24 #include "remoting/protocol/name_value_map.h"
30 const remoting::protocol::NameMapElement
<It2MeHostState
> kIt2MeHostStates
[] = {
31 {kDisconnected
, "DISCONNECTED"},
32 {kStarting
, "STARTING"},
33 {kRequestedAccessCode
, "REQUESTED_ACCESS_CODE"},
34 {kReceivedAccessCode
, "RECEIVED_ACCESS_CODE"},
35 {kConnected
, "CONNECTED"},
36 {kDisconnecting
, "DISCONNECTING"},
38 {kInvalidDomainError
, "INVALID_DOMAIN_ERROR"},
43 It2MeNativeMessagingHost::It2MeNativeMessagingHost(
44 scoped_ptr
<ChromotingHostContext
> context
,
45 scoped_ptr
<It2MeHostFactory
> factory
)
47 host_context_(context
.Pass()),
48 factory_(factory
.Pass()),
50 weak_ptr_
= weak_factory_
.GetWeakPtr();
52 const ServiceUrls
* service_urls
= ServiceUrls::GetInstance();
53 const bool xmpp_server_valid
=
54 net::ParseHostAndPort(service_urls
->xmpp_server_address(),
55 &xmpp_server_config_
.host
,
56 &xmpp_server_config_
.port
);
57 DCHECK(xmpp_server_valid
);
59 xmpp_server_config_
.use_tls
= service_urls
->xmpp_server_use_tls();
60 directory_bot_jid_
= service_urls
->directory_bot_jid();
63 It2MeNativeMessagingHost::~It2MeNativeMessagingHost() {
64 DCHECK(task_runner()->BelongsToCurrentThread());
66 if (it2me_host_
.get()) {
67 it2me_host_
->Disconnect();
68 it2me_host_
= nullptr;
72 void It2MeNativeMessagingHost::OnMessage(const std::string
& message
) {
73 DCHECK(task_runner()->BelongsToCurrentThread());
75 scoped_ptr
<base::DictionaryValue
> response(new base::DictionaryValue());
76 scoped_ptr
<base::Value
> message_value
= base::JSONReader::Read(message
);
77 if (!message_value
->IsType(base::Value::TYPE_DICTIONARY
)) {
78 LOG(ERROR
) << "Received a message that's not a dictionary.";
79 client_
->CloseChannel(std::string());
83 scoped_ptr
<base::DictionaryValue
> message_dict(
84 static_cast<base::DictionaryValue
*>(message_value
.release()));
86 // If the client supplies an ID, it will expect it in the response. This
87 // might be a string or a number, so cope with both.
88 const base::Value
* id
;
89 if (message_dict
->Get("id", &id
))
90 response
->Set("id", id
->DeepCopy());
93 if (!message_dict
->GetString("type", &type
)) {
94 SendErrorAndExit(response
.Pass(), "'type' not found in request.");
98 response
->SetString("type", type
+ "Response");
100 if (type
== "hello") {
101 ProcessHello(*message_dict
, response
.Pass());
102 } else if (type
== "connect") {
103 ProcessConnect(*message_dict
, response
.Pass());
104 } else if (type
== "disconnect") {
105 ProcessDisconnect(*message_dict
, response
.Pass());
107 SendErrorAndExit(response
.Pass(), "Unsupported request type: " + type
);
111 void It2MeNativeMessagingHost::Start(Client
* client
) {
112 DCHECK(task_runner()->BelongsToCurrentThread());
114 #if !defined(OS_CHROMEOS)
115 log_message_handler_
.reset(
116 new LogMessageHandler(
117 base::Bind(&It2MeNativeMessagingHost::SendMessageToClient
,
118 base::Unretained(this))));
119 #endif // !defined(OS_CHROMEOS)
122 void It2MeNativeMessagingHost::SendMessageToClient(
123 scoped_ptr
<base::Value
> message
) const {
124 DCHECK(task_runner()->BelongsToCurrentThread());
125 std::string message_json
;
126 base::JSONWriter::Write(*message
, &message_json
);
127 client_
->PostMessageFromNativeHost(message_json
);
130 void It2MeNativeMessagingHost::ProcessHello(
131 const base::DictionaryValue
& message
,
132 scoped_ptr
<base::DictionaryValue
> response
) const {
133 DCHECK(task_runner()->BelongsToCurrentThread());
135 response
->SetString("version", STRINGIZE(VERSION
));
137 // This list will be populated when new features are added.
138 scoped_ptr
<base::ListValue
> supported_features_list(new base::ListValue());
139 response
->Set("supportedFeatures", supported_features_list
.release());
141 SendMessageToClient(response
.Pass());
144 void It2MeNativeMessagingHost::ProcessConnect(
145 const base::DictionaryValue
& message
,
146 scoped_ptr
<base::DictionaryValue
> response
) {
147 DCHECK(task_runner()->BelongsToCurrentThread());
149 if (it2me_host_
.get()) {
150 SendErrorAndExit(response
.Pass(),
151 "Connect can be called only when disconnected.");
155 XmppSignalStrategy::XmppServerConfig xmpp_config
= xmpp_server_config_
;
157 if (!message
.GetString("userName", &xmpp_config
.username
)) {
158 SendErrorAndExit(response
.Pass(), "'userName' not found in request.");
162 std::string auth_service_with_token
;
163 if (!message
.GetString("authServiceWithToken", &auth_service_with_token
)) {
164 SendErrorAndExit(response
.Pass(),
165 "'authServiceWithToken' not found in request.");
169 // For backward compatibility the webapp still passes OAuth service as part of
170 // the authServiceWithToken field. But auth service part is always expected to
172 const char kOAuth2ServicePrefix
[] = "oauth2:";
173 if (!base::StartsWith(auth_service_with_token
, kOAuth2ServicePrefix
,
174 base::CompareCase::SENSITIVE
)) {
175 SendErrorAndExit(response
.Pass(), "Invalid 'authServiceWithToken': " +
176 auth_service_with_token
);
180 xmpp_config
.auth_token
=
181 auth_service_with_token
.substr(strlen(kOAuth2ServicePrefix
));
185 if (!message
.GetString("xmppServerAddress", &address
)) {
186 SendErrorAndExit(response
.Pass(),
187 "'xmppServerAddress' not found in request.");
191 if (!net::ParseHostAndPort(
192 address
, &xmpp_server_config_
.host
, &xmpp_server_config_
.port
)) {
193 SendErrorAndExit(response
.Pass(),
194 "Invalid 'xmppServerAddress': " + address
);
198 if (!message
.GetBoolean("xmppServerUseTls", &xmpp_server_config_
.use_tls
)) {
199 SendErrorAndExit(response
.Pass(),
200 "'xmppServerUseTls' not found in request.");
204 if (!message
.GetString("directoryBotJid", &directory_bot_jid_
)) {
205 SendErrorAndExit(response
.Pass(),
206 "'directoryBotJid' not found in request.");
209 #endif // !defined(NDEBUG)
211 // Create the It2Me host and start connecting.
212 it2me_host_
= factory_
->CreateIt2MeHost(host_context_
->Copy(),
216 it2me_host_
->Connect();
218 SendMessageToClient(response
.Pass());
221 void It2MeNativeMessagingHost::ProcessDisconnect(
222 const base::DictionaryValue
& message
,
223 scoped_ptr
<base::DictionaryValue
> response
) {
224 DCHECK(task_runner()->BelongsToCurrentThread());
226 if (it2me_host_
.get()) {
227 it2me_host_
->Disconnect();
228 it2me_host_
= nullptr;
230 SendMessageToClient(response
.Pass());
233 void It2MeNativeMessagingHost::SendErrorAndExit(
234 scoped_ptr
<base::DictionaryValue
> response
,
235 const std::string
& description
) const {
236 DCHECK(task_runner()->BelongsToCurrentThread());
238 LOG(ERROR
) << description
;
240 response
->SetString("type", "error");
241 response
->SetString("description", description
);
242 SendMessageToClient(response
.Pass());
244 // Trigger a host shutdown by sending an empty message.
245 client_
->CloseChannel(std::string());
248 void It2MeNativeMessagingHost::OnStateChanged(
249 It2MeHostState state
,
250 const std::string
& error_message
) {
251 DCHECK(task_runner()->BelongsToCurrentThread());
255 scoped_ptr
<base::DictionaryValue
> message(new base::DictionaryValue());
257 message
->SetString("type", "hostStateChanged");
258 message
->SetString("state",
259 It2MeNativeMessagingHost::HostStateToString(state
));
262 case kReceivedAccessCode
:
263 message
->SetString("accessCode", access_code_
);
264 message
->SetInteger("accessCodeLifetime",
265 access_code_lifetime_
.InSeconds());
269 message
->SetString("client", client_username_
);
273 client_username_
.clear();
277 // kError is an internal-only state, sent to the web-app by a separate
278 // "error" message so that errors that occur before the "connect" message
279 // is sent can be communicated.
280 message
->SetString("type", "error");
281 message
->SetString("description", error_message
);
288 SendMessageToClient(message
.Pass());
291 void It2MeNativeMessagingHost::OnNatPolicyChanged(bool nat_traversal_enabled
) {
292 DCHECK(task_runner()->BelongsToCurrentThread());
294 scoped_ptr
<base::DictionaryValue
> message(new base::DictionaryValue());
296 message
->SetString("type", "natPolicyChanged");
297 message
->SetBoolean("natTraversalEnabled", nat_traversal_enabled
);
298 SendMessageToClient(message
.Pass());
301 // Stores the Access Code for the web-app to query.
302 void It2MeNativeMessagingHost::OnStoreAccessCode(
303 const std::string
& access_code
,
304 base::TimeDelta access_code_lifetime
) {
305 DCHECK(task_runner()->BelongsToCurrentThread());
307 access_code_
= access_code
;
308 access_code_lifetime_
= access_code_lifetime
;
311 // Stores the client user's name for the web-app to query.
312 void It2MeNativeMessagingHost::OnClientAuthenticated(
313 const std::string
& client_username
) {
314 DCHECK(task_runner()->BelongsToCurrentThread());
316 client_username_
= client_username
;
319 scoped_refptr
<base::SingleThreadTaskRunner
>
320 It2MeNativeMessagingHost::task_runner() const {
321 return host_context_
->ui_task_runner();
325 std::string
It2MeNativeMessagingHost::HostStateToString(
326 It2MeHostState host_state
) {
327 return ValueToName(kIt2MeHostStates
, host_state
);
330 } // namespace remoting