Give names to all utility processes.
[chromium-blink-merge.git] / remoting / host / it2me / it2me_native_messaging_host.cc
blob7af2db741aacb653a441080105bce436a574f7a1
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"
7 #include <string>
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 "media/base/media.h"
20 #include "net/base/net_util.h"
21 #include "net/url_request/url_request_context_getter.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"
27 namespace remoting {
29 namespace {
31 const 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"},
42 } // namespace
44 It2MeNativeMessagingHost::It2MeNativeMessagingHost(
45 scoped_ptr<ChromotingHostContext> context,
46 scoped_ptr<It2MeHostFactory> factory)
47 : client_(nullptr),
48 host_context_(context.Pass()),
49 factory_(factory.Pass()),
50 weak_factory_(this) {
51 weak_ptr_ = weak_factory_.GetWeakPtr();
53 // Ensures runtime specific CPU features are initialized.
54 media::InitializeCPUSpecificMediaFeatures();
56 const ServiceUrls* service_urls = ServiceUrls::GetInstance();
57 const bool xmpp_server_valid =
58 net::ParseHostAndPort(service_urls->xmpp_server_address(),
59 &xmpp_server_config_.host,
60 &xmpp_server_config_.port);
61 DCHECK(xmpp_server_valid);
63 xmpp_server_config_.use_tls = service_urls->xmpp_server_use_tls();
64 directory_bot_jid_ = service_urls->directory_bot_jid();
67 It2MeNativeMessagingHost::~It2MeNativeMessagingHost() {
68 DCHECK(task_runner()->BelongsToCurrentThread());
70 if (it2me_host_.get()) {
71 it2me_host_->Disconnect();
72 it2me_host_ = nullptr;
76 void It2MeNativeMessagingHost::OnMessage(const std::string& message) {
77 DCHECK(task_runner()->BelongsToCurrentThread());
79 scoped_ptr<base::DictionaryValue> response(new base::DictionaryValue());
80 scoped_ptr<base::Value> message_value(base::JSONReader::Read(message));
81 if (!message_value->IsType(base::Value::TYPE_DICTIONARY)) {
82 LOG(ERROR) << "Received a message that's not a dictionary.";
83 client_->CloseChannel(std::string());
84 return;
87 scoped_ptr<base::DictionaryValue> message_dict(
88 static_cast<base::DictionaryValue*>(message_value.release()));
90 // If the client supplies an ID, it will expect it in the response. This
91 // might be a string or a number, so cope with both.
92 const base::Value* id;
93 if (message_dict->Get("id", &id))
94 response->Set("id", id->DeepCopy());
96 std::string type;
97 if (!message_dict->GetString("type", &type)) {
98 SendErrorAndExit(response.Pass(), "'type' not found in request.");
99 return;
102 response->SetString("type", type + "Response");
104 if (type == "hello") {
105 ProcessHello(*message_dict, response.Pass());
106 } else if (type == "connect") {
107 ProcessConnect(*message_dict, response.Pass());
108 } else if (type == "disconnect") {
109 ProcessDisconnect(*message_dict, response.Pass());
110 } else {
111 SendErrorAndExit(response.Pass(), "Unsupported request type: " + type);
115 void It2MeNativeMessagingHost::Start(Client* client) {
116 DCHECK(task_runner()->BelongsToCurrentThread());
117 client_ = client;
120 void It2MeNativeMessagingHost::SendMessageToClient(
121 scoped_ptr<base::DictionaryValue> message) const {
122 DCHECK(task_runner()->BelongsToCurrentThread());
123 std::string message_json;
124 base::JSONWriter::Write(message.get(), &message_json);
125 client_->PostMessageFromNativeHost(message_json);
128 void It2MeNativeMessagingHost::ProcessHello(
129 const base::DictionaryValue& message,
130 scoped_ptr<base::DictionaryValue> response) const {
131 DCHECK(task_runner()->BelongsToCurrentThread());
133 response->SetString("version", STRINGIZE(VERSION));
135 // This list will be populated when new features are added.
136 scoped_ptr<base::ListValue> supported_features_list(new base::ListValue());
137 response->Set("supportedFeatures", supported_features_list.release());
139 SendMessageToClient(response.Pass());
142 void It2MeNativeMessagingHost::ProcessConnect(
143 const base::DictionaryValue& message,
144 scoped_ptr<base::DictionaryValue> response) {
145 DCHECK(task_runner()->BelongsToCurrentThread());
147 if (it2me_host_.get()) {
148 SendErrorAndExit(response.Pass(),
149 "Connect can be called only when disconnected.");
150 return;
153 XmppSignalStrategy::XmppServerConfig xmpp_config = xmpp_server_config_;
155 if (!message.GetString("userName", &xmpp_config.username)) {
156 SendErrorAndExit(response.Pass(), "'userName' not found in request.");
157 return;
160 std::string auth_service_with_token;
161 if (!message.GetString("authServiceWithToken", &auth_service_with_token)) {
162 SendErrorAndExit(response.Pass(),
163 "'authServiceWithToken' not found in request.");
164 return;
167 // For backward compatibility the webapp still passes OAuth service as part of
168 // the authServiceWithToken field. But auth service part is always expected to
169 // be set to oauth2.
170 const char kOAuth2ServicePrefix[] = "oauth2:";
171 if (!StartsWithASCII(auth_service_with_token, kOAuth2ServicePrefix, true)) {
172 SendErrorAndExit(response.Pass(), "Invalid 'authServiceWithToken': " +
173 auth_service_with_token);
174 return;
177 xmpp_config.auth_token =
178 auth_service_with_token.substr(strlen(kOAuth2ServicePrefix));
180 #if !defined(NDEBUG)
181 std::string address;
182 if (!message.GetString("xmppServerAddress", &address)) {
183 SendErrorAndExit(response.Pass(),
184 "'xmppServerAddress' not found in request.");
185 return;
188 if (!net::ParseHostAndPort(
189 address, &xmpp_server_config_.host, &xmpp_server_config_.port)) {
190 SendErrorAndExit(response.Pass(),
191 "Invalid 'xmppServerAddress': " + address);
192 return;
195 if (!message.GetBoolean("xmppServerUseTls", &xmpp_server_config_.use_tls)) {
196 SendErrorAndExit(response.Pass(),
197 "'xmppServerUseTls' not found in request.");
198 return;
201 if (!message.GetString("directoryBotJid", &directory_bot_jid_)) {
202 SendErrorAndExit(response.Pass(),
203 "'directoryBotJid' not found in request.");
204 return;
206 #endif // !defined(NDEBUG)
208 // Create the It2Me host and start connecting.
209 it2me_host_ = factory_->CreateIt2MeHost(host_context_->Copy(),
210 weak_ptr_,
211 xmpp_config,
212 directory_bot_jid_);
213 it2me_host_->Connect();
215 SendMessageToClient(response.Pass());
218 void It2MeNativeMessagingHost::ProcessDisconnect(
219 const base::DictionaryValue& message,
220 scoped_ptr<base::DictionaryValue> response) {
221 DCHECK(task_runner()->BelongsToCurrentThread());
223 if (it2me_host_.get()) {
224 it2me_host_->Disconnect();
225 it2me_host_ = nullptr;
227 SendMessageToClient(response.Pass());
230 void It2MeNativeMessagingHost::SendErrorAndExit(
231 scoped_ptr<base::DictionaryValue> response,
232 const std::string& description) const {
233 DCHECK(task_runner()->BelongsToCurrentThread());
235 LOG(ERROR) << description;
237 response->SetString("type", "error");
238 response->SetString("description", description);
239 SendMessageToClient(response.Pass());
241 // Trigger a host shutdown by sending an empty message.
242 client_->CloseChannel(std::string());
245 void It2MeNativeMessagingHost::OnStateChanged(It2MeHostState state) {
246 DCHECK(task_runner()->BelongsToCurrentThread());
248 state_ = state;
250 scoped_ptr<base::DictionaryValue> message(new base::DictionaryValue());
252 message->SetString("type", "hostStateChanged");
253 message->SetString("state",
254 It2MeNativeMessagingHost::HostStateToString(state));
256 switch (state_) {
257 case kReceivedAccessCode:
258 message->SetString("accessCode", access_code_);
259 message->SetInteger("accessCodeLifetime",
260 access_code_lifetime_.InSeconds());
261 break;
263 case kConnected:
264 message->SetString("client", client_username_);
265 break;
267 case kDisconnected:
268 client_username_.clear();
269 break;
271 default:
275 SendMessageToClient(message.Pass());
278 void It2MeNativeMessagingHost::OnNatPolicyChanged(bool nat_traversal_enabled) {
279 DCHECK(task_runner()->BelongsToCurrentThread());
281 scoped_ptr<base::DictionaryValue> message(new base::DictionaryValue());
283 message->SetString("type", "natPolicyChanged");
284 message->SetBoolean("natTraversalEnabled", nat_traversal_enabled);
285 SendMessageToClient(message.Pass());
288 // Stores the Access Code for the web-app to query.
289 void It2MeNativeMessagingHost::OnStoreAccessCode(
290 const std::string& access_code,
291 base::TimeDelta access_code_lifetime) {
292 DCHECK(task_runner()->BelongsToCurrentThread());
294 access_code_ = access_code;
295 access_code_lifetime_ = access_code_lifetime;
298 // Stores the client user's name for the web-app to query.
299 void It2MeNativeMessagingHost::OnClientAuthenticated(
300 const std::string& client_username) {
301 DCHECK(task_runner()->BelongsToCurrentThread());
303 client_username_ = client_username;
306 scoped_refptr<base::SingleThreadTaskRunner>
307 It2MeNativeMessagingHost::task_runner() const {
308 return host_context_->ui_task_runner();
311 /* static */
312 std::string It2MeNativeMessagingHost::HostStateToString(
313 It2MeHostState host_state) {
314 return ValueToName(kIt2MeHostStates, host_state);
317 } // namespace remoting