chromoting_host.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. // Copyright (c) 2012 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. #include "remoting/host/chromoting_host.h"
  5. #include <stddef.h>
  6. #include <algorithm>
  7. #include <memory>
  8. #include <utility>
  9. #include "base/bind.h"
  10. #include "base/callback.h"
  11. #include "base/command_line.h"
  12. #include "base/memory/ptr_util.h"
  13. #include "base/task/single_thread_task_runner.h"
  14. #include "build/build_config.h"
  15. #include "components/webrtc/thread_wrapper.h"
  16. #include "remoting/base/constants.h"
  17. #include "remoting/base/logging.h"
  18. #include "remoting/host/desktop_environment.h"
  19. #include "remoting/host/host_config.h"
  20. #include "remoting/host/input_injector.h"
  21. #include "remoting/host/ipc_constants.h"
  22. #include "remoting/host/mojo_ipc/mojo_ipc_server.h"
  23. #include "remoting/protocol/client_stub.h"
  24. #include "remoting/protocol/host_stub.h"
  25. #include "remoting/protocol/ice_connection_to_client.h"
  26. #include "remoting/protocol/input_stub.h"
  27. #include "remoting/protocol/transport_context.h"
  28. #include "remoting/protocol/webrtc_connection_to_client.h"
  29. #if BUILDFLAG(IS_WIN)
  30. #include <windows.h>
  31. #endif
  32. using remoting::protocol::ConnectionToClient;
  33. using remoting::protocol::InputStub;
  34. namespace remoting {
  35. namespace {
  36. const net::BackoffEntry::Policy kDefaultBackoffPolicy = {
  37. // Number of initial errors (in sequence) to ignore before applying
  38. // exponential back-off rules.
  39. 5,
  40. // Initial delay for exponential back-off in ms.
  41. 2000,
  42. // Factor by which the waiting time will be multiplied.
  43. 2,
  44. // Fuzzing percentage. ex: 10% will spread requests randomly
  45. // between 90%-100% of the calculated time.
  46. 0,
  47. // Maximum amount of time we are willing to delay our request in ms.
  48. -1,
  49. // Time to keep an entry from being discarded even when it
  50. // has no significant state, -1 to never discard.
  51. -1,
  52. // Don't use initial delay unless the last request was an error.
  53. false,
  54. };
  55. } // namespace
  56. ChromotingHost::ChromotingHost(
  57. DesktopEnvironmentFactory* desktop_environment_factory,
  58. std::unique_ptr<protocol::SessionManager> session_manager,
  59. scoped_refptr<protocol::TransportContext> transport_context,
  60. scoped_refptr<base::SingleThreadTaskRunner> audio_task_runner,
  61. scoped_refptr<base::SingleThreadTaskRunner> video_encode_task_runner,
  62. const DesktopEnvironmentOptions& options)
  63. : desktop_environment_factory_(desktop_environment_factory),
  64. session_manager_(std::move(session_manager)),
  65. transport_context_(transport_context),
  66. audio_task_runner_(audio_task_runner),
  67. video_encode_task_runner_(video_encode_task_runner),
  68. status_monitor_(new HostStatusMonitor()),
  69. login_backoff_(&kDefaultBackoffPolicy),
  70. desktop_environment_options_(options) {
  71. webrtc::ThreadWrapper::EnsureForCurrentMessageLoop();
  72. }
  73. ChromotingHost::~ChromotingHost() {
  74. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  75. // Disconnect all of the clients.
  76. while (!clients_.empty()) {
  77. clients_.front()->DisconnectSession(protocol::OK);
  78. }
  79. // Destroy the session manager to make sure that |signal_strategy_| does not
  80. // have any listeners registered.
  81. session_manager_.reset();
  82. // Notify observers.
  83. if (started_) {
  84. for (auto& observer : status_monitor_->observers())
  85. observer.OnHostShutdown();
  86. }
  87. }
  88. void ChromotingHost::Start(const std::string& host_owner_email) {
  89. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  90. DCHECK(!started_);
  91. HOST_LOG << "Starting host";
  92. started_ = true;
  93. for (auto& observer : status_monitor_->observers())
  94. observer.OnHostStarted(host_owner_email);
  95. session_manager_->AcceptIncoming(base::BindRepeating(
  96. &ChromotingHost::OnIncomingSession, base::Unretained(this)));
  97. }
  98. void ChromotingHost::StartChromotingHostServices() {
  99. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  100. DCHECK(!ipc_server_);
  101. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN)
  102. ipc_server_ = std::make_unique<MojoIpcServer<mojom::ChromotingHostServices>>(
  103. GetChromotingHostServicesServerName(), this);
  104. ipc_server_->StartServer();
  105. HOST_LOG << "ChromotingHostServices IPC server has been started.";
  106. #else
  107. NOTIMPLEMENTED();
  108. #endif
  109. }
  110. void ChromotingHost::AddExtension(std::unique_ptr<HostExtension> extension) {
  111. extensions_.push_back(std::move(extension));
  112. }
  113. void ChromotingHost::SetAuthenticatorFactory(
  114. std::unique_ptr<protocol::AuthenticatorFactory> authenticator_factory) {
  115. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  116. session_manager_->set_authenticator_factory(std::move(authenticator_factory));
  117. }
  118. void ChromotingHost::SetMaximumSessionDuration(
  119. const base::TimeDelta& max_session_duration) {
  120. max_session_duration_ = max_session_duration;
  121. }
  122. ////////////////////////////////////////////////////////////////////////////
  123. // protocol::ClientSession::EventHandler implementation.
  124. void ChromotingHost::OnSessionAuthenticating(ClientSession* client) {
  125. // We treat each incoming connection as a failure to authenticate,
  126. // and clear the backoff when a connection successfully
  127. // authenticates. This allows the backoff to protect from parallel
  128. // connection attempts as well as sequential ones.
  129. if (login_backoff_.ShouldRejectRequest()) {
  130. LOG(WARNING) << "Disconnecting client " << client->client_jid() << " due to"
  131. " an overload of failed login attempts.";
  132. client->DisconnectSession(protocol::HOST_OVERLOAD);
  133. return;
  134. }
  135. login_backoff_.InformOfRequest(false);
  136. }
  137. void ChromotingHost::OnSessionAuthenticated(ClientSession* client) {
  138. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  139. login_backoff_.Reset();
  140. // Disconnect all clients, except |client|.
  141. base::WeakPtr<ChromotingHost> self = weak_factory_.GetWeakPtr();
  142. while (clients_.size() > 1) {
  143. clients_[(clients_.front().get() == client) ? 1 : 0]->DisconnectSession(
  144. protocol::OK);
  145. // Quit if the host was destroyed.
  146. if (!self)
  147. return;
  148. }
  149. // Disconnects above must have destroyed all other clients.
  150. DCHECK_EQ(clients_.size(), 1U);
  151. DCHECK(clients_.front().get() == client);
  152. // Notify observers that there is at least one authenticated client.
  153. for (auto& observer : status_monitor_->observers())
  154. observer.OnClientAuthenticated(client->client_jid());
  155. }
  156. void ChromotingHost::OnSessionChannelsConnected(ClientSession* client) {
  157. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  158. // Notify observers.
  159. for (auto& observer : status_monitor_->observers())
  160. observer.OnClientConnected(client->client_jid());
  161. }
  162. void ChromotingHost::OnSessionAuthenticationFailed(ClientSession* client) {
  163. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  164. // Notify observers.
  165. for (auto& observer : status_monitor_->observers())
  166. observer.OnClientAccessDenied(client->client_jid());
  167. }
  168. void ChromotingHost::OnSessionClosed(ClientSession* client) {
  169. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  170. auto it = std::find_if(clients_.begin(), clients_.end(),
  171. [client](const std::unique_ptr<ClientSession>& item) {
  172. return item.get() == client;
  173. });
  174. CHECK(it != clients_.end());
  175. bool was_authenticated = client->is_authenticated();
  176. std::string jid = client->client_jid();
  177. clients_.erase(it);
  178. if (was_authenticated) {
  179. for (auto& observer : status_monitor_->observers())
  180. observer.OnClientDisconnected(jid);
  181. }
  182. }
  183. void ChromotingHost::OnSessionRouteChange(
  184. ClientSession* session,
  185. const std::string& channel_name,
  186. const protocol::TransportRoute& route) {
  187. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  188. for (auto& observer : status_monitor_->observers())
  189. observer.OnClientRouteChange(session->client_jid(), channel_name, route);
  190. }
  191. void ChromotingHost::BindSessionServices(
  192. mojo::PendingReceiver<mojom::ChromotingSessionServices> receiver) {
  193. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  194. ClientSession* connected_client = GetConnectedClientSession();
  195. if (!connected_client) {
  196. LOG(WARNING) << "Session services bind request rejected: "
  197. << "No connected remote desktop client was found.";
  198. return;
  199. }
  200. #if BUILDFLAG(IS_WIN)
  201. DWORD peer_session_id;
  202. if (!ProcessIdToSessionId(ipc_server_->current_peer_pid(),
  203. &peer_session_id)) {
  204. PLOG(ERROR) << "Session services bind request rejected: "
  205. "ProcessIdToSessionId failed";
  206. return;
  207. }
  208. if (connected_client->desktop_session_id() != peer_session_id) {
  209. LOG(WARNING)
  210. << "Session services bind request rejected: "
  211. << "Remote desktop client is not connected to the current session.";
  212. return;
  213. }
  214. #endif
  215. connected_client->BindReceiver(std::move(receiver));
  216. VLOG(1) << "Session services bound for receiver ID: "
  217. << ipc_server_->current_receiver();
  218. }
  219. void ChromotingHost::OnIncomingSession(
  220. protocol::Session* session,
  221. protocol::SessionManager::IncomingSessionResponse* response) {
  222. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  223. DCHECK(started_);
  224. if (login_backoff_.ShouldRejectRequest()) {
  225. LOG(WARNING) << "Rejecting connection due to"
  226. " an overload of failed login attempts.";
  227. *response = protocol::SessionManager::OVERLOAD;
  228. return;
  229. }
  230. *response = protocol::SessionManager::ACCEPT;
  231. HOST_LOG << "Client connected: " << session->jid();
  232. // Create either IceConnectionToClient or WebrtcConnectionToClient.
  233. // TODO(sergeyu): Move this logic to the protocol layer.
  234. std::unique_ptr<protocol::ConnectionToClient> connection;
  235. if (session->config().protocol() ==
  236. protocol::SessionConfig::Protocol::WEBRTC) {
  237. connection = std::make_unique<protocol::WebrtcConnectionToClient>(
  238. base::WrapUnique(session), transport_context_, audio_task_runner_);
  239. } else {
  240. connection = std::make_unique<protocol::IceConnectionToClient>(
  241. base::WrapUnique(session), transport_context_,
  242. video_encode_task_runner_, audio_task_runner_);
  243. }
  244. // Create a ClientSession object.
  245. std::vector<HostExtension*> extension_ptrs;
  246. for (const auto& extension : extensions_)
  247. extension_ptrs.push_back(extension.get());
  248. clients_.push_back(std::make_unique<ClientSession>(
  249. this, std::move(connection), desktop_environment_factory_,
  250. desktop_environment_options_, max_session_duration_, pairing_registry_,
  251. extension_ptrs));
  252. }
  253. ClientSession* ChromotingHost::GetConnectedClientSession() const {
  254. ClientSession* connected_client = nullptr;
  255. for (auto& client : clients_) {
  256. if (client->channels_connected()) {
  257. if (connected_client) {
  258. LOG(DFATAL) << "More than one connected client is found.";
  259. return nullptr;
  260. }
  261. connected_client = client.get();
  262. }
  263. }
  264. return connected_client;
  265. }
  266. } // namespace remoting