turn_server.h 13 KB

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