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.

356 lines
13 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * Copyright 2012 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. #ifndef P2P_BASE_TURN_SERVER_H_
  11. #define P2P_BASE_TURN_SERVER_H_
  12. #include <list>
  13. #include <map>
  14. #include <memory>
  15. #include <set>
  16. #include <string>
  17. #include <utility>
  18. #include <vector>
  19. #include "p2p/base/port_interface.h"
  20. #include "rtc_base/async_invoker.h"
  21. #include "rtc_base/async_packet_socket.h"
  22. #include "rtc_base/message_queue.h"
  23. #include "rtc_base/socket_address.h"
  24. #include "rtc_base/third_party/sigslot/sigslot.h"
  25. #include "rtc_base/thread_checker.h"
  26. namespace rtc {
  27. class ByteBufferWriter;
  28. class PacketSocketFactory;
  29. class Thread;
  30. } // namespace rtc
  31. namespace cricket {
  32. class StunMessage;
  33. class TurnMessage;
  34. class TurnServer;
  35. // The default server port for TURN, as specified in RFC5766.
  36. const int TURN_SERVER_PORT = 3478;
  37. // Encapsulates the client's connection to the server.
  38. class TurnServerConnection {
  39. public:
  40. TurnServerConnection() : proto_(PROTO_UDP), socket_(NULL) {}
  41. TurnServerConnection(const rtc::SocketAddress& src,
  42. ProtocolType proto,
  43. rtc::AsyncPacketSocket* socket);
  44. const rtc::SocketAddress& src() const { return src_; }
  45. rtc::AsyncPacketSocket* socket() { return socket_; }
  46. bool operator==(const TurnServerConnection& t) const;
  47. bool operator<(const TurnServerConnection& t) const;
  48. std::string ToString() const;
  49. private:
  50. rtc::SocketAddress src_;
  51. rtc::SocketAddress dst_;
  52. cricket::ProtocolType proto_;
  53. rtc::AsyncPacketSocket* socket_;
  54. };
  55. // Encapsulates a TURN allocation.
  56. // The object is created when an allocation request is received, and then
  57. // handles TURN messages (via HandleTurnMessage) and channel data messages
  58. // (via HandleChannelData) for this allocation when received by the server.
  59. // The object self-deletes and informs the server if its lifetime timer expires.
  60. class TurnServerAllocation : public rtc::MessageHandler,
  61. public sigslot::has_slots<> {
  62. public:
  63. TurnServerAllocation(TurnServer* server_,
  64. rtc::Thread* thread,
  65. const TurnServerConnection& conn,
  66. rtc::AsyncPacketSocket* server_socket,
  67. const std::string& key);
  68. ~TurnServerAllocation() override;
  69. TurnServerConnection* conn() { return &conn_; }
  70. const std::string& key() const { return key_; }
  71. const std::string& transaction_id() const { return transaction_id_; }
  72. const std::string& username() const { return username_; }
  73. const std::string& origin() const { return origin_; }
  74. const std::string& last_nonce() const { return last_nonce_; }
  75. void set_last_nonce(const std::string& nonce) { last_nonce_ = nonce; }
  76. std::string ToString() const;
  77. void HandleTurnMessage(const TurnMessage* msg);
  78. void HandleChannelData(const char* data, size_t size);
  79. sigslot::signal1<TurnServerAllocation*> SignalDestroyed;
  80. private:
  81. class Channel;
  82. class Permission;
  83. typedef std::list<Permission*> PermissionList;
  84. typedef std::list<Channel*> ChannelList;
  85. void HandleAllocateRequest(const TurnMessage* msg);
  86. void HandleRefreshRequest(const TurnMessage* msg);
  87. void HandleSendIndication(const TurnMessage* msg);
  88. void HandleCreatePermissionRequest(const TurnMessage* msg);
  89. void HandleChannelBindRequest(const TurnMessage* msg);
  90. void OnExternalPacket(rtc::AsyncPacketSocket* socket,
  91. const char* data,
  92. size_t size,
  93. const rtc::SocketAddress& addr,
  94. const int64_t& packet_time_us);
  95. static int ComputeLifetime(const TurnMessage* msg);
  96. bool HasPermission(const rtc::IPAddress& addr);
  97. void AddPermission(const rtc::IPAddress& addr);
  98. Permission* FindPermission(const rtc::IPAddress& addr) const;
  99. Channel* FindChannel(int channel_id) const;
  100. Channel* FindChannel(const rtc::SocketAddress& addr) const;
  101. void SendResponse(TurnMessage* msg);
  102. void SendBadRequestResponse(const TurnMessage* req);
  103. void SendErrorResponse(const TurnMessage* req,
  104. int code,
  105. const std::string& reason);
  106. void SendExternal(const void* data,
  107. size_t size,
  108. const rtc::SocketAddress& peer);
  109. void OnPermissionDestroyed(Permission* perm);
  110. void OnChannelDestroyed(Channel* channel);
  111. void OnMessage(rtc::Message* msg) override;
  112. TurnServer* server_;
  113. rtc::Thread* thread_;
  114. TurnServerConnection conn_;
  115. std::unique_ptr<rtc::AsyncPacketSocket> external_socket_;
  116. std::string key_;
  117. std::string transaction_id_;
  118. std::string username_;
  119. std::string origin_;
  120. std::string last_nonce_;
  121. PermissionList perms_;
  122. ChannelList channels_;
  123. };
  124. // An interface through which the MD5 credential hash can be retrieved.
  125. class TurnAuthInterface {
  126. public:
  127. // Gets HA1 for the specified user and realm.
  128. // HA1 = MD5(A1) = MD5(username:realm:password).
  129. // Return true if the given username and realm are valid, or false if not.
  130. virtual bool GetKey(const std::string& username,
  131. const std::string& realm,
  132. std::string* key) = 0;
  133. virtual ~TurnAuthInterface() = default;
  134. };
  135. // An interface enables Turn Server to control redirection behavior.
  136. class TurnRedirectInterface {
  137. public:
  138. virtual bool ShouldRedirect(const rtc::SocketAddress& address,
  139. rtc::SocketAddress* out) = 0;
  140. virtual ~TurnRedirectInterface() {}
  141. };
  142. class StunMessageObserver {
  143. public:
  144. virtual void ReceivedMessage(const TurnMessage* msg) = 0;
  145. virtual void ReceivedChannelData(const char* data, size_t size) = 0;
  146. virtual ~StunMessageObserver() {}
  147. };
  148. // The core TURN server class. Give it a socket to listen on via
  149. // AddInternalServerSocket, and a factory to create external sockets via
  150. // SetExternalSocketFactory, and it's ready to go.
  151. // Not yet wired up: TCP support.
  152. class TurnServer : public sigslot::has_slots<> {
  153. public:
  154. typedef std::map<TurnServerConnection, std::unique_ptr<TurnServerAllocation>>
  155. AllocationMap;
  156. explicit TurnServer(rtc::Thread* thread);
  157. ~TurnServer() override;
  158. // Gets/sets the realm value to use for the server.
  159. const std::string& realm() const {
  160. RTC_DCHECK(thread_checker_.IsCurrent());
  161. return realm_;
  162. }
  163. void set_realm(const std::string& realm) {
  164. RTC_DCHECK(thread_checker_.IsCurrent());
  165. realm_ = realm;
  166. }
  167. // Gets/sets the value for the SOFTWARE attribute for TURN messages.
  168. const std::string& software() const {
  169. RTC_DCHECK(thread_checker_.IsCurrent());
  170. return software_;
  171. }
  172. void set_software(const std::string& software) {
  173. RTC_DCHECK(thread_checker_.IsCurrent());
  174. software_ = software;
  175. }
  176. const AllocationMap& allocations() const {
  177. RTC_DCHECK(thread_checker_.IsCurrent());
  178. return allocations_;
  179. }
  180. // Sets the authentication callback; does not take ownership.
  181. void set_auth_hook(TurnAuthInterface* auth_hook) {
  182. RTC_DCHECK(thread_checker_.IsCurrent());
  183. auth_hook_ = auth_hook;
  184. }
  185. void set_redirect_hook(TurnRedirectInterface* redirect_hook) {
  186. RTC_DCHECK(thread_checker_.IsCurrent());
  187. redirect_hook_ = redirect_hook;
  188. }
  189. void set_enable_otu_nonce(bool enable) {
  190. RTC_DCHECK(thread_checker_.IsCurrent());
  191. enable_otu_nonce_ = enable;
  192. }
  193. // If set to true, reject CreatePermission requests to RFC1918 addresses.
  194. void set_reject_private_addresses(bool filter) {
  195. RTC_DCHECK(thread_checker_.IsCurrent());
  196. reject_private_addresses_ = filter;
  197. }
  198. void set_enable_permission_checks(bool enable) {
  199. RTC_DCHECK(thread_checker_.IsCurrent());
  200. enable_permission_checks_ = enable;
  201. }
  202. // Starts listening for packets from internal clients.
  203. void AddInternalSocket(rtc::AsyncPacketSocket* socket, ProtocolType proto);
  204. // Starts listening for the connections on this socket. When someone tries
  205. // to connect, the connection will be accepted and a new internal socket
  206. // will be added.
  207. void AddInternalServerSocket(rtc::AsyncSocket* socket, ProtocolType proto);
  208. // Specifies the factory to use for creating external sockets.
  209. void SetExternalSocketFactory(rtc::PacketSocketFactory* factory,
  210. const rtc::SocketAddress& address);
  211. // For testing only.
  212. std::string SetTimestampForNextNonce(int64_t timestamp) {
  213. RTC_DCHECK(thread_checker_.IsCurrent());
  214. ts_for_next_nonce_ = timestamp;
  215. return GenerateNonce(timestamp);
  216. }
  217. void SetStunMessageObserver(std::unique_ptr<StunMessageObserver> observer) {
  218. RTC_DCHECK(thread_checker_.IsCurrent());
  219. stun_message_observer_ = std::move(observer);
  220. }
  221. private:
  222. std::string GenerateNonce(int64_t now) const;
  223. void OnInternalPacket(rtc::AsyncPacketSocket* socket,
  224. const char* data,
  225. size_t size,
  226. const rtc::SocketAddress& address,
  227. const int64_t& packet_time_us);
  228. void OnNewInternalConnection(rtc::AsyncSocket* socket);
  229. // Accept connections on this server socket.
  230. void AcceptConnection(rtc::AsyncSocket* server_socket);
  231. void OnInternalSocketClose(rtc::AsyncPacketSocket* socket, int err);
  232. void HandleStunMessage(TurnServerConnection* conn,
  233. const char* data,
  234. size_t size);
  235. void HandleBindingRequest(TurnServerConnection* conn, const StunMessage* msg);
  236. void HandleAllocateRequest(TurnServerConnection* conn,
  237. const TurnMessage* msg,
  238. const std::string& key);
  239. bool GetKey(const StunMessage* msg, std::string* key);
  240. bool CheckAuthorization(TurnServerConnection* conn,
  241. const StunMessage* msg,
  242. const char* data,
  243. size_t size,
  244. const std::string& key);
  245. bool ValidateNonce(const std::string& nonce) const;
  246. TurnServerAllocation* FindAllocation(TurnServerConnection* conn);
  247. TurnServerAllocation* CreateAllocation(TurnServerConnection* conn,
  248. int proto,
  249. const std::string& key);
  250. void SendErrorResponse(TurnServerConnection* conn,
  251. const StunMessage* req,
  252. int code,
  253. const std::string& reason);
  254. void SendErrorResponseWithRealmAndNonce(TurnServerConnection* conn,
  255. const StunMessage* req,
  256. int code,
  257. const std::string& reason);
  258. void SendErrorResponseWithAlternateServer(TurnServerConnection* conn,
  259. const StunMessage* req,
  260. const rtc::SocketAddress& addr);
  261. void SendStun(TurnServerConnection* conn, StunMessage* msg);
  262. void Send(TurnServerConnection* conn, const rtc::ByteBufferWriter& buf);
  263. void OnAllocationDestroyed(TurnServerAllocation* allocation);
  264. void DestroyInternalSocket(rtc::AsyncPacketSocket* socket);
  265. // Just clears |sockets_to_delete_|; called asynchronously.
  266. void FreeSockets();
  267. typedef std::map<rtc::AsyncPacketSocket*, ProtocolType> InternalSocketMap;
  268. typedef std::map<rtc::AsyncSocket*, ProtocolType> ServerSocketMap;
  269. rtc::Thread* thread_;
  270. rtc::ThreadChecker thread_checker_;
  271. std::string nonce_key_;
  272. std::string realm_;
  273. std::string software_;
  274. TurnAuthInterface* auth_hook_;
  275. TurnRedirectInterface* redirect_hook_;
  276. // otu - one-time-use. Server will respond with 438 if it's
  277. // sees the same nonce in next transaction.
  278. bool enable_otu_nonce_;
  279. bool reject_private_addresses_ = false;
  280. // Check for permission when receiving an external packet.
  281. bool enable_permission_checks_ = true;
  282. InternalSocketMap server_sockets_;
  283. ServerSocketMap server_listen_sockets_;
  284. // Used when we need to delete a socket asynchronously.
  285. std::vector<std::unique_ptr<rtc::AsyncPacketSocket>> sockets_to_delete_;
  286. std::unique_ptr<rtc::PacketSocketFactory> external_socket_factory_;
  287. rtc::SocketAddress external_addr_;
  288. AllocationMap allocations_;
  289. rtc::AsyncInvoker invoker_;
  290. // For testing only. If this is non-zero, the next NONCE will be generated
  291. // from this value, and it will be reset to 0 after generating the NONCE.
  292. int64_t ts_for_next_nonce_ = 0;
  293. // For testing only. Used to observe STUN messages received.
  294. std::unique_ptr<StunMessageObserver> stun_message_observer_;
  295. friend class TurnServerAllocation;
  296. };
  297. } // namespace cricket
  298. #endif // P2P_BASE_TURN_SERVER_H_