You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

741 lines
25 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * Copyright 2004 The WebRTC Project Authors. All rights reserved.
  3. *
  4. * Use of this source code is governed by a BSD-style license
  5. * that can be found in the LICENSE file in the root of the source
  6. * tree. An additional intellectual property rights grant can be found
  7. * in the file PATENTS. All contributing project authors may
  8. * be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #include "p2p/base/relay_server.h"
  11. #ifdef WEBRTC_POSIX
  12. #include <errno.h>
  13. #endif // WEBRTC_POSIX
  14. #include <algorithm>
  15. #include <utility>
  16. #include "absl/algorithm/container.h"
  17. #include "rtc_base/async_tcp_socket.h"
  18. #include "rtc_base/checks.h"
  19. #include "rtc_base/helpers.h"
  20. #include "rtc_base/logging.h"
  21. #include "rtc_base/numerics/safe_conversions.h"
  22. #include "rtc_base/server_socket_adapters.h"
  23. namespace cricket {
  24. // By default, we require a ping every 90 seconds.
  25. const int MAX_LIFETIME = 15 * 60 * 1000;
  26. // The number of bytes in each of the usernames we use.
  27. const uint32_t USERNAME_LENGTH = 16;
  28. // Calls SendTo on the given socket and logs any bad results.
  29. void Send(rtc::AsyncPacketSocket* socket,
  30. const char* bytes,
  31. size_t size,
  32. const rtc::SocketAddress& addr) {
  33. rtc::PacketOptions options;
  34. int result = socket->SendTo(bytes, size, addr, options);
  35. if (result < static_cast<int>(size)) {
  36. RTC_LOG(LS_ERROR) << "SendTo wrote only " << result << " of " << size
  37. << " bytes";
  38. } else if (result < 0) {
  39. RTC_LOG_ERR(LS_ERROR) << "SendTo";
  40. }
  41. }
  42. // Sends the given STUN message on the given socket.
  43. void SendStun(const StunMessage& msg,
  44. rtc::AsyncPacketSocket* socket,
  45. const rtc::SocketAddress& addr) {
  46. rtc::ByteBufferWriter buf;
  47. msg.Write(&buf);
  48. Send(socket, buf.Data(), buf.Length(), addr);
  49. }
  50. // Constructs a STUN error response and sends it on the given socket.
  51. void SendStunError(const StunMessage& msg,
  52. rtc::AsyncPacketSocket* socket,
  53. const rtc::SocketAddress& remote_addr,
  54. int error_code,
  55. const char* error_desc,
  56. const std::string& magic_cookie) {
  57. RelayMessage err_msg;
  58. err_msg.SetType(GetStunErrorResponseType(msg.type()));
  59. err_msg.SetTransactionID(msg.transaction_id());
  60. auto magic_cookie_attr =
  61. StunAttribute::CreateByteString(cricket::STUN_ATTR_MAGIC_COOKIE);
  62. if (magic_cookie.size() == 0) {
  63. magic_cookie_attr->CopyBytes(cricket::TURN_MAGIC_COOKIE_VALUE,
  64. sizeof(cricket::TURN_MAGIC_COOKIE_VALUE));
  65. } else {
  66. magic_cookie_attr->CopyBytes(magic_cookie.c_str(), magic_cookie.size());
  67. }
  68. err_msg.AddAttribute(std::move(magic_cookie_attr));
  69. auto err_code = StunAttribute::CreateErrorCode();
  70. err_code->SetClass(error_code / 100);
  71. err_code->SetNumber(error_code % 100);
  72. err_code->SetReason(error_desc);
  73. err_msg.AddAttribute(std::move(err_code));
  74. SendStun(err_msg, socket, remote_addr);
  75. }
  76. RelayServer::RelayServer(rtc::Thread* thread)
  77. : thread_(thread), random_(rtc::SystemTimeNanos()), log_bindings_(true) {}
  78. RelayServer::~RelayServer() {
  79. // Deleting the binding will cause it to be removed from the map.
  80. while (!bindings_.empty())
  81. delete bindings_.begin()->second;
  82. for (size_t i = 0; i < internal_sockets_.size(); ++i)
  83. delete internal_sockets_[i];
  84. for (size_t i = 0; i < external_sockets_.size(); ++i)
  85. delete external_sockets_[i];
  86. for (size_t i = 0; i < removed_sockets_.size(); ++i)
  87. delete removed_sockets_[i];
  88. while (!server_sockets_.empty()) {
  89. rtc::AsyncSocket* socket = server_sockets_.begin()->first;
  90. server_sockets_.erase(server_sockets_.begin()->first);
  91. delete socket;
  92. }
  93. }
  94. void RelayServer::AddInternalSocket(rtc::AsyncPacketSocket* socket) {
  95. RTC_DCHECK(!absl::c_linear_search(internal_sockets_, socket));
  96. internal_sockets_.push_back(socket);
  97. socket->SignalReadPacket.connect(this, &RelayServer::OnInternalPacket);
  98. }
  99. void RelayServer::RemoveInternalSocket(rtc::AsyncPacketSocket* socket) {
  100. auto iter = absl::c_find(internal_sockets_, socket);
  101. RTC_DCHECK(iter != internal_sockets_.end());
  102. internal_sockets_.erase(iter);
  103. removed_sockets_.push_back(socket);
  104. socket->SignalReadPacket.disconnect(this);
  105. }
  106. void RelayServer::AddExternalSocket(rtc::AsyncPacketSocket* socket) {
  107. RTC_DCHECK(!absl::c_linear_search(external_sockets_, socket));
  108. external_sockets_.push_back(socket);
  109. socket->SignalReadPacket.connect(this, &RelayServer::OnExternalPacket);
  110. }
  111. void RelayServer::RemoveExternalSocket(rtc::AsyncPacketSocket* socket) {
  112. auto iter = absl::c_find(external_sockets_, socket);
  113. RTC_DCHECK(iter != external_sockets_.end());
  114. external_sockets_.erase(iter);
  115. removed_sockets_.push_back(socket);
  116. socket->SignalReadPacket.disconnect(this);
  117. }
  118. void RelayServer::AddInternalServerSocket(rtc::AsyncSocket* socket,
  119. cricket::ProtocolType proto) {
  120. RTC_DCHECK(server_sockets_.end() == server_sockets_.find(socket));
  121. server_sockets_[socket] = proto;
  122. socket->SignalReadEvent.connect(this, &RelayServer::OnReadEvent);
  123. }
  124. void RelayServer::RemoveInternalServerSocket(rtc::AsyncSocket* socket) {
  125. auto iter = server_sockets_.find(socket);
  126. RTC_DCHECK(iter != server_sockets_.end());
  127. server_sockets_.erase(iter);
  128. socket->SignalReadEvent.disconnect(this);
  129. }
  130. int RelayServer::GetConnectionCount() const {
  131. return static_cast<int>(connections_.size());
  132. }
  133. rtc::SocketAddressPair RelayServer::GetConnection(int connection) const {
  134. int i = 0;
  135. for (const auto& entry : connections_) {
  136. if (i == connection) {
  137. return entry.second->addr_pair();
  138. }
  139. ++i;
  140. }
  141. return rtc::SocketAddressPair();
  142. }
  143. bool RelayServer::HasConnection(const rtc::SocketAddress& address) const {
  144. for (const auto& entry : connections_) {
  145. if (entry.second->addr_pair().destination() == address) {
  146. return true;
  147. }
  148. }
  149. return false;
  150. }
  151. void RelayServer::OnReadEvent(rtc::AsyncSocket* socket) {
  152. RTC_DCHECK(server_sockets_.find(socket) != server_sockets_.end());
  153. AcceptConnection(socket);
  154. }
  155. void RelayServer::OnInternalPacket(rtc::AsyncPacketSocket* socket,
  156. const char* bytes,
  157. size_t size,
  158. const rtc::SocketAddress& remote_addr,
  159. const int64_t& /* packet_time_us */) {
  160. // Get the address of the connection we just received on.
  161. rtc::SocketAddressPair ap(remote_addr, socket->GetLocalAddress());
  162. RTC_DCHECK(!ap.destination().IsNil());
  163. // If this did not come from an existing connection, it should be a STUN
  164. // allocate request.
  165. auto piter = connections_.find(ap);
  166. if (piter == connections_.end()) {
  167. HandleStunAllocate(bytes, size, ap, socket);
  168. return;
  169. }
  170. RelayServerConnection* int_conn = piter->second;
  171. // Handle STUN requests to the server itself.
  172. if (int_conn->binding()->HasMagicCookie(bytes, size)) {
  173. HandleStun(int_conn, bytes, size);
  174. return;
  175. }
  176. // Otherwise, this is a non-wrapped packet that we are to forward. Make sure
  177. // that this connection has been locked. (Otherwise, we would not know what
  178. // address to forward to.)
  179. if (!int_conn->locked()) {
  180. RTC_LOG(LS_WARNING) << "Dropping packet: connection not locked";
  181. return;
  182. }
  183. // Forward this to the destination address into the connection.
  184. RelayServerConnection* ext_conn = int_conn->binding()->GetExternalConnection(
  185. int_conn->default_destination());
  186. if (ext_conn && ext_conn->locked()) {
  187. // TODO(?): Check the HMAC.
  188. ext_conn->Send(bytes, size);
  189. } else {
  190. // This happens very often and is not an error.
  191. RTC_LOG(LS_INFO) << "Dropping packet: no external connection";
  192. }
  193. }
  194. void RelayServer::OnExternalPacket(rtc::AsyncPacketSocket* socket,
  195. const char* bytes,
  196. size_t size,
  197. const rtc::SocketAddress& remote_addr,
  198. const int64_t& /* packet_time_us */) {
  199. // Get the address of the connection we just received on.
  200. rtc::SocketAddressPair ap(remote_addr, socket->GetLocalAddress());
  201. RTC_DCHECK(!ap.destination().IsNil());
  202. // If this connection already exists, then forward the traffic.
  203. auto piter = connections_.find(ap);
  204. if (piter != connections_.end()) {
  205. // TODO(?): Check the HMAC.
  206. RelayServerConnection* ext_conn = piter->second;
  207. RelayServerConnection* int_conn =
  208. ext_conn->binding()->GetInternalConnection(
  209. ext_conn->addr_pair().source());
  210. RTC_DCHECK(int_conn != NULL);
  211. int_conn->Send(bytes, size, ext_conn->addr_pair().source());
  212. ext_conn->Lock(); // allow outgoing packets
  213. return;
  214. }
  215. // The first packet should always be a STUN / TURN packet. If it isn't, then
  216. // we should just ignore this packet.
  217. RelayMessage msg;
  218. rtc::ByteBufferReader buf(bytes, size);
  219. if (!msg.Read(&buf)) {
  220. RTC_LOG(LS_WARNING) << "Dropping packet: first packet not STUN";
  221. return;
  222. }
  223. // The initial packet should have a username (which identifies the binding).
  224. const StunByteStringAttribute* username_attr =
  225. msg.GetByteString(STUN_ATTR_USERNAME);
  226. if (!username_attr) {
  227. RTC_LOG(LS_WARNING) << "Dropping packet: no username";
  228. return;
  229. }
  230. uint32_t length =
  231. std::min(static_cast<uint32_t>(username_attr->length()), USERNAME_LENGTH);
  232. std::string username(username_attr->bytes(), length);
  233. // TODO(?): Check the HMAC.
  234. // The binding should already be present.
  235. auto biter = bindings_.find(username);
  236. if (biter == bindings_.end()) {
  237. RTC_LOG(LS_WARNING) << "Dropping packet: no binding with username";
  238. return;
  239. }
  240. // Add this authenticted connection to the binding.
  241. RelayServerConnection* ext_conn =
  242. new RelayServerConnection(biter->second, ap, socket);
  243. ext_conn->binding()->AddExternalConnection(ext_conn);
  244. AddConnection(ext_conn);
  245. // We always know where external packets should be forwarded, so we can lock
  246. // them from the beginning.
  247. ext_conn->Lock();
  248. // Send this message on the appropriate internal connection.
  249. RelayServerConnection* int_conn = ext_conn->binding()->GetInternalConnection(
  250. ext_conn->addr_pair().source());
  251. RTC_DCHECK(int_conn != NULL);
  252. int_conn->Send(bytes, size, ext_conn->addr_pair().source());
  253. }
  254. bool RelayServer::HandleStun(const char* bytes,
  255. size_t size,
  256. const rtc::SocketAddress& remote_addr,
  257. rtc::AsyncPacketSocket* socket,
  258. std::string* username,
  259. StunMessage* msg) {
  260. // Parse this into a stun message. Eat the message if this fails.
  261. rtc::ByteBufferReader buf(bytes, size);
  262. if (!msg->Read(&buf)) {
  263. return false;
  264. }
  265. // The initial packet should have a username (which identifies the binding).
  266. const StunByteStringAttribute* username_attr =
  267. msg->GetByteString(STUN_ATTR_USERNAME);
  268. if (!username_attr) {
  269. SendStunError(*msg, socket, remote_addr, 432, "Missing Username", "");
  270. return false;
  271. }
  272. // Record the username if requested.
  273. if (username)
  274. username->append(username_attr->bytes(), username_attr->length());
  275. // TODO(?): Check for unknown attributes (<= 0x7fff)
  276. return true;
  277. }
  278. void RelayServer::HandleStunAllocate(const char* bytes,
  279. size_t size,
  280. const rtc::SocketAddressPair& ap,
  281. rtc::AsyncPacketSocket* socket) {
  282. // Make sure this is a valid STUN request.
  283. RelayMessage request;
  284. std::string username;
  285. if (!HandleStun(bytes, size, ap.source(), socket, &username, &request))
  286. return;
  287. // Make sure this is a an allocate request.
  288. if (request.type() != STUN_ALLOCATE_REQUEST) {
  289. SendStunError(request, socket, ap.source(), 600, "Operation Not Supported",
  290. "");
  291. return;
  292. }
  293. // TODO(?): Check the HMAC.
  294. // Find or create the binding for this username.
  295. RelayServerBinding* binding;
  296. auto biter = bindings_.find(username);
  297. if (biter != bindings_.end()) {
  298. binding = biter->second;
  299. } else {
  300. // NOTE: In the future, bindings will be created by the bot only. This
  301. // else-branch will then disappear.
  302. // Compute the appropriate lifetime for this binding.
  303. int lifetime = MAX_LIFETIME;
  304. const StunUInt32Attribute* lifetime_attr =
  305. request.GetUInt32(STUN_ATTR_LIFETIME);
  306. if (lifetime_attr)
  307. lifetime =
  308. std::min(lifetime, static_cast<int>(lifetime_attr->value() * 1000));
  309. binding = new RelayServerBinding(this, username, "0", lifetime);
  310. binding->SignalTimeout.connect(this, &RelayServer::OnTimeout);
  311. bindings_[username] = binding;
  312. if (log_bindings_) {
  313. RTC_LOG(LS_INFO) << "Added new binding " << username << ", "
  314. << bindings_.size() << " total";
  315. }
  316. }
  317. // Add this connection to the binding. It starts out unlocked.
  318. RelayServerConnection* int_conn =
  319. new RelayServerConnection(binding, ap, socket);
  320. binding->AddInternalConnection(int_conn);
  321. AddConnection(int_conn);
  322. // Now that we have a connection, this other method takes over.
  323. HandleStunAllocate(int_conn, request);
  324. }
  325. void RelayServer::HandleStun(RelayServerConnection* int_conn,
  326. const char* bytes,
  327. size_t size) {
  328. // Make sure this is a valid STUN request.
  329. RelayMessage request;
  330. std::string username;
  331. if (!HandleStun(bytes, size, int_conn->addr_pair().source(),
  332. int_conn->socket(), &username, &request))
  333. return;
  334. // Make sure the username is the one were were expecting.
  335. if (username != int_conn->binding()->username()) {
  336. int_conn->SendStunError(request, 430, "Stale Credentials");
  337. return;
  338. }
  339. // TODO(?): Check the HMAC.
  340. // Send this request to the appropriate handler.
  341. if (request.type() == STUN_SEND_REQUEST)
  342. HandleStunSend(int_conn, request);
  343. else if (request.type() == STUN_ALLOCATE_REQUEST)
  344. HandleStunAllocate(int_conn, request);
  345. else
  346. int_conn->SendStunError(request, 600, "Operation Not Supported");
  347. }
  348. void RelayServer::HandleStunAllocate(RelayServerConnection* int_conn,
  349. const StunMessage& request) {
  350. // Create a response message that includes an address with which external
  351. // clients can communicate.
  352. RelayMessage response;
  353. response.SetType(STUN_ALLOCATE_RESPONSE);
  354. response.SetTransactionID(request.transaction_id());
  355. auto magic_cookie_attr =
  356. StunAttribute::CreateByteString(cricket::STUN_ATTR_MAGIC_COOKIE);
  357. magic_cookie_attr->CopyBytes(int_conn->binding()->magic_cookie().c_str(),
  358. int_conn->binding()->magic_cookie().size());
  359. response.AddAttribute(std::move(magic_cookie_attr));
  360. RTC_DCHECK_GT(external_sockets_.size(), 0);
  361. size_t index =
  362. random_.Rand(rtc::dchecked_cast<uint32_t>(external_sockets_.size() - 1));
  363. rtc::SocketAddress ext_addr = external_sockets_[index]->GetLocalAddress();
  364. auto addr_attr = StunAttribute::CreateAddress(STUN_ATTR_MAPPED_ADDRESS);
  365. addr_attr->SetIP(ext_addr.ipaddr());
  366. addr_attr->SetPort(ext_addr.port());
  367. response.AddAttribute(std::move(addr_attr));
  368. auto res_lifetime_attr = StunAttribute::CreateUInt32(STUN_ATTR_LIFETIME);
  369. res_lifetime_attr->SetValue(int_conn->binding()->lifetime() / 1000);
  370. response.AddAttribute(std::move(res_lifetime_attr));
  371. // TODO(?): Support transport-prefs (preallocate RTCP port).
  372. // TODO(?): Support bandwidth restrictions.
  373. // TODO(?): Add message integrity check.
  374. // Send a response to the caller.
  375. int_conn->SendStun(response);
  376. }
  377. void RelayServer::HandleStunSend(RelayServerConnection* int_conn,
  378. const StunMessage& request) {
  379. const StunAddressAttribute* addr_attr =
  380. request.GetAddress(STUN_ATTR_DESTINATION_ADDRESS);
  381. if (!addr_attr) {
  382. int_conn->SendStunError(request, 400, "Bad Request");
  383. return;
  384. }
  385. const StunByteStringAttribute* data_attr =
  386. request.GetByteString(STUN_ATTR_DATA);
  387. if (!data_attr) {
  388. int_conn->SendStunError(request, 400, "Bad Request");
  389. return;
  390. }
  391. rtc::SocketAddress ext_addr(addr_attr->ipaddr(), addr_attr->port());
  392. RelayServerConnection* ext_conn =
  393. int_conn->binding()->GetExternalConnection(ext_addr);
  394. if (!ext_conn) {
  395. // Create a new connection to establish the relationship with this binding.
  396. RTC_DCHECK(external_sockets_.size() == 1);
  397. rtc::AsyncPacketSocket* socket = external_sockets_[0];
  398. rtc::SocketAddressPair ap(ext_addr, socket->GetLocalAddress());
  399. ext_conn = new RelayServerConnection(int_conn->binding(), ap, socket);
  400. ext_conn->binding()->AddExternalConnection(ext_conn);
  401. AddConnection(ext_conn);
  402. }
  403. // If this connection has pinged us, then allow outgoing traffic.
  404. if (ext_conn->locked())
  405. ext_conn->Send(data_attr->bytes(), data_attr->length());
  406. const StunUInt32Attribute* options_attr =
  407. request.GetUInt32(STUN_ATTR_OPTIONS);
  408. if (options_attr && (options_attr->value() & 0x01)) {
  409. int_conn->set_default_destination(ext_addr);
  410. int_conn->Lock();
  411. RelayMessage response;
  412. response.SetType(STUN_SEND_RESPONSE);
  413. response.SetTransactionID(request.transaction_id());
  414. auto magic_cookie_attr =
  415. StunAttribute::CreateByteString(cricket::STUN_ATTR_MAGIC_COOKIE);
  416. magic_cookie_attr->CopyBytes(int_conn->binding()->magic_cookie().c_str(),
  417. int_conn->binding()->magic_cookie().size());
  418. response.AddAttribute(std::move(magic_cookie_attr));
  419. auto options2_attr =
  420. StunAttribute::CreateUInt32(cricket::STUN_ATTR_OPTIONS);
  421. options2_attr->SetValue(0x01);
  422. response.AddAttribute(std::move(options2_attr));
  423. int_conn->SendStun(response);
  424. }
  425. }
  426. void RelayServer::AddConnection(RelayServerConnection* conn) {
  427. RTC_DCHECK(connections_.find(conn->addr_pair()) == connections_.end());
  428. connections_[conn->addr_pair()] = conn;
  429. }
  430. void RelayServer::RemoveConnection(RelayServerConnection* conn) {
  431. auto iter = connections_.find(conn->addr_pair());
  432. RTC_DCHECK(iter != connections_.end());
  433. connections_.erase(iter);
  434. }
  435. void RelayServer::RemoveBinding(RelayServerBinding* binding) {
  436. auto iter = bindings_.find(binding->username());
  437. RTC_DCHECK(iter != bindings_.end());
  438. bindings_.erase(iter);
  439. if (log_bindings_) {
  440. RTC_LOG(LS_INFO) << "Removed binding " << binding->username() << ", "
  441. << bindings_.size() << " remaining";
  442. }
  443. }
  444. void RelayServer::OnMessage(rtc::Message* pmsg) {
  445. static const uint32_t kMessageAcceptConnection = 1;
  446. RTC_DCHECK(pmsg->message_id == kMessageAcceptConnection);
  447. rtc::MessageData* data = pmsg->pdata;
  448. rtc::AsyncSocket* socket =
  449. static_cast<rtc::TypedMessageData<rtc::AsyncSocket*>*>(data)->data();
  450. AcceptConnection(socket);
  451. delete data;
  452. }
  453. void RelayServer::OnTimeout(RelayServerBinding* binding) {
  454. // This call will result in all of the necessary clean-up. We can't call
  455. // delete here, because you can't delete an object that is signaling you.
  456. thread_->Dispose(binding);
  457. }
  458. void RelayServer::AcceptConnection(rtc::AsyncSocket* server_socket) {
  459. // Check if someone is trying to connect to us.
  460. rtc::SocketAddress accept_addr;
  461. rtc::AsyncSocket* accepted_socket = server_socket->Accept(&accept_addr);
  462. if (accepted_socket != NULL) {
  463. // We had someone trying to connect, now check which protocol to
  464. // use and create a packet socket.
  465. RTC_DCHECK(server_sockets_[server_socket] == cricket::PROTO_TCP ||
  466. server_sockets_[server_socket] == cricket::PROTO_SSLTCP);
  467. if (server_sockets_[server_socket] == cricket::PROTO_SSLTCP) {
  468. accepted_socket = new rtc::AsyncSSLServerSocket(accepted_socket);
  469. }
  470. rtc::AsyncTCPSocket* tcp_socket =
  471. new rtc::AsyncTCPSocket(accepted_socket, false);
  472. // Finally add the socket so it can start communicating with the client.
  473. AddInternalSocket(tcp_socket);
  474. }
  475. }
  476. RelayServerConnection::RelayServerConnection(
  477. RelayServerBinding* binding,
  478. const rtc::SocketAddressPair& addrs,
  479. rtc::AsyncPacketSocket* socket)
  480. : binding_(binding), addr_pair_(addrs), socket_(socket), locked_(false) {
  481. // The creation of a new connection constitutes a use of the binding.
  482. binding_->NoteUsed();
  483. }
  484. RelayServerConnection::~RelayServerConnection() {
  485. // Remove this connection from the server's map (if it exists there).
  486. binding_->server()->RemoveConnection(this);
  487. }
  488. void RelayServerConnection::Send(const char* data, size_t size) {
  489. // Note that the binding has been used again.
  490. binding_->NoteUsed();
  491. cricket::Send(socket_, data, size, addr_pair_.source());
  492. }
  493. void RelayServerConnection::Send(const char* data,
  494. size_t size,
  495. const rtc::SocketAddress& from_addr) {
  496. // If the from address is known to the client, we don't need to send it.
  497. if (locked() && (from_addr == default_dest_)) {
  498. Send(data, size);
  499. return;
  500. }
  501. // Wrap the given data in a data-indication packet.
  502. RelayMessage msg;
  503. msg.SetType(STUN_DATA_INDICATION);
  504. auto magic_cookie_attr =
  505. StunAttribute::CreateByteString(cricket::STUN_ATTR_MAGIC_COOKIE);
  506. magic_cookie_attr->CopyBytes(binding_->magic_cookie().c_str(),
  507. binding_->magic_cookie().size());
  508. msg.AddAttribute(std::move(magic_cookie_attr));
  509. auto addr_attr = StunAttribute::CreateAddress(STUN_ATTR_SOURCE_ADDRESS2);
  510. addr_attr->SetIP(from_addr.ipaddr());
  511. addr_attr->SetPort(from_addr.port());
  512. msg.AddAttribute(std::move(addr_attr));
  513. auto data_attr = StunAttribute::CreateByteString(STUN_ATTR_DATA);
  514. RTC_DCHECK(size <= 65536);
  515. data_attr->CopyBytes(data, uint16_t(size));
  516. msg.AddAttribute(std::move(data_attr));
  517. SendStun(msg);
  518. }
  519. void RelayServerConnection::SendStun(const StunMessage& msg) {
  520. // Note that the binding has been used again.
  521. binding_->NoteUsed();
  522. cricket::SendStun(msg, socket_, addr_pair_.source());
  523. }
  524. void RelayServerConnection::SendStunError(const StunMessage& request,
  525. int error_code,
  526. const char* error_desc) {
  527. // An error does not indicate use. If no legitimate use off the binding
  528. // occurs, we want it to be cleaned up even if errors are still occuring.
  529. cricket::SendStunError(request, socket_, addr_pair_.source(), error_code,
  530. error_desc, binding_->magic_cookie());
  531. }
  532. void RelayServerConnection::Lock() {
  533. locked_ = true;
  534. }
  535. void RelayServerConnection::Unlock() {
  536. locked_ = false;
  537. }
  538. // IDs used for posted messages:
  539. const uint32_t MSG_LIFETIME_TIMER = 1;
  540. RelayServerBinding::RelayServerBinding(RelayServer* server,
  541. const std::string& username,
  542. const std::string& password,
  543. int lifetime)
  544. : server_(server),
  545. username_(username),
  546. password_(password),
  547. lifetime_(lifetime) {
  548. // For now, every connection uses the standard magic cookie value.
  549. magic_cookie_.append(reinterpret_cast<const char*>(TURN_MAGIC_COOKIE_VALUE),
  550. sizeof(TURN_MAGIC_COOKIE_VALUE));
  551. // Initialize the last-used time to now.
  552. NoteUsed();
  553. // Set the first timeout check.
  554. server_->thread()->PostDelayed(RTC_FROM_HERE, lifetime_, this,
  555. MSG_LIFETIME_TIMER);
  556. }
  557. RelayServerBinding::~RelayServerBinding() {
  558. // Clear the outstanding timeout check.
  559. server_->thread()->Clear(this);
  560. // Clean up all of the connections.
  561. for (size_t i = 0; i < internal_connections_.size(); ++i)
  562. delete internal_connections_[i];
  563. for (size_t i = 0; i < external_connections_.size(); ++i)
  564. delete external_connections_[i];
  565. // Remove this binding from the server's map.
  566. server_->RemoveBinding(this);
  567. }
  568. void RelayServerBinding::AddInternalConnection(RelayServerConnection* conn) {
  569. internal_connections_.push_back(conn);
  570. }
  571. void RelayServerBinding::AddExternalConnection(RelayServerConnection* conn) {
  572. external_connections_.push_back(conn);
  573. }
  574. void RelayServerBinding::NoteUsed() {
  575. last_used_ = rtc::TimeMillis();
  576. }
  577. bool RelayServerBinding::HasMagicCookie(const char* bytes, size_t size) const {
  578. if (size < 24 + magic_cookie_.size()) {
  579. return false;
  580. } else {
  581. return memcmp(bytes + 24, magic_cookie_.c_str(), magic_cookie_.size()) == 0;
  582. }
  583. }
  584. RelayServerConnection* RelayServerBinding::GetInternalConnection(
  585. const rtc::SocketAddress& ext_addr) {
  586. // Look for an internal connection that is locked to this address.
  587. for (size_t i = 0; i < internal_connections_.size(); ++i) {
  588. if (internal_connections_[i]->locked() &&
  589. (ext_addr == internal_connections_[i]->default_destination()))
  590. return internal_connections_[i];
  591. }
  592. // If one was not found, we send to the first connection.
  593. RTC_DCHECK(internal_connections_.size() > 0);
  594. return internal_connections_[0];
  595. }
  596. RelayServerConnection* RelayServerBinding::GetExternalConnection(
  597. const rtc::SocketAddress& ext_addr) {
  598. for (size_t i = 0; i < external_connections_.size(); ++i) {
  599. if (ext_addr == external_connections_[i]->addr_pair().source())
  600. return external_connections_[i];
  601. }
  602. return 0;
  603. }
  604. void RelayServerBinding::OnMessage(rtc::Message* pmsg) {
  605. if (pmsg->message_id == MSG_LIFETIME_TIMER) {
  606. RTC_DCHECK(!pmsg->pdata);
  607. // If the lifetime timeout has been exceeded, then send a signal.
  608. // Otherwise, just keep waiting.
  609. if (rtc::TimeMillis() >= last_used_ + lifetime_) {
  610. RTC_LOG(LS_INFO) << "Expiring binding " << username_;
  611. SignalTimeout(this);
  612. } else {
  613. server_->thread()->PostDelayed(RTC_FROM_HERE, lifetime_, this,
  614. MSG_LIFETIME_TIMER);
  615. }
  616. } else {
  617. RTC_NOTREACHED();
  618. }
  619. }
  620. } // namespace cricket