turn_port.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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_PORT_H_
  11. #define P2P_BASE_TURN_PORT_H_
  12. #include <stdio.h>
  13. #include <list>
  14. #include <map>
  15. #include <memory>
  16. #include <set>
  17. #include <string>
  18. #include <vector>
  19. #include "absl/memory/memory.h"
  20. #include "p2p/base/port.h"
  21. #include "p2p/client/basic_port_allocator.h"
  22. #include "rtc_base/async_invoker.h"
  23. #include "rtc_base/async_packet_socket.h"
  24. #include "rtc_base/ssl_certificate.h"
  25. namespace webrtc {
  26. class TurnCustomizer;
  27. }
  28. namespace cricket {
  29. extern const int STUN_ATTR_TURN_LOGGING_ID;
  30. extern const char TURN_PORT_TYPE[];
  31. class TurnAllocateRequest;
  32. class TurnEntry;
  33. class TurnPort : public Port {
  34. public:
  35. enum PortState {
  36. STATE_CONNECTING, // Initial state, cannot send any packets.
  37. STATE_CONNECTED, // Socket connected, ready to send stun requests.
  38. STATE_READY, // Received allocate success, can send any packets.
  39. STATE_RECEIVEONLY, // Had REFRESH_REQUEST error, cannot send any packets.
  40. STATE_DISCONNECTED, // TCP connection died, cannot send/receive any
  41. // packets.
  42. };
  43. // Create a TURN port using the shared UDP socket, |socket|.
  44. static std::unique_ptr<TurnPort> Create(
  45. rtc::Thread* thread,
  46. rtc::PacketSocketFactory* factory,
  47. rtc::Network* network,
  48. rtc::AsyncPacketSocket* socket,
  49. const std::string& username, // ice username.
  50. const std::string& password, // ice password.
  51. const ProtocolAddress& server_address,
  52. const RelayCredentials& credentials,
  53. int server_priority,
  54. const std::string& origin,
  55. webrtc::TurnCustomizer* customizer) {
  56. // Using `new` to access a non-public constructor.
  57. return absl::WrapUnique(new TurnPort(
  58. thread, factory, network, socket, username, password, server_address,
  59. credentials, server_priority, origin, customizer));
  60. }
  61. // TODO(steveanton): Remove once downstream clients have moved to |Create|.
  62. static std::unique_ptr<TurnPort> CreateUnique(
  63. rtc::Thread* thread,
  64. rtc::PacketSocketFactory* factory,
  65. rtc::Network* network,
  66. rtc::AsyncPacketSocket* socket,
  67. const std::string& username, // ice username.
  68. const std::string& password, // ice password.
  69. const ProtocolAddress& server_address,
  70. const RelayCredentials& credentials,
  71. int server_priority,
  72. const std::string& origin,
  73. webrtc::TurnCustomizer* customizer) {
  74. return Create(thread, factory, network, socket, username, password,
  75. server_address, credentials, server_priority, origin,
  76. customizer);
  77. }
  78. // Create a TURN port that will use a new socket, bound to |network| and
  79. // using a port in the range between |min_port| and |max_port|.
  80. static std::unique_ptr<TurnPort> Create(
  81. rtc::Thread* thread,
  82. rtc::PacketSocketFactory* factory,
  83. rtc::Network* network,
  84. uint16_t min_port,
  85. uint16_t max_port,
  86. const std::string& username, // ice username.
  87. const std::string& password, // ice password.
  88. const ProtocolAddress& server_address,
  89. const RelayCredentials& credentials,
  90. int server_priority,
  91. const std::string& origin,
  92. const std::vector<std::string>& tls_alpn_protocols,
  93. const std::vector<std::string>& tls_elliptic_curves,
  94. webrtc::TurnCustomizer* customizer,
  95. rtc::SSLCertificateVerifier* tls_cert_verifier = nullptr) {
  96. // Using `new` to access a non-public constructor.
  97. return absl::WrapUnique(
  98. new TurnPort(thread, factory, network, min_port, max_port, username,
  99. password, server_address, credentials, server_priority,
  100. origin, tls_alpn_protocols, tls_elliptic_curves,
  101. customizer, tls_cert_verifier));
  102. }
  103. // TODO(steveanton): Remove once downstream clients have moved to |Create|.
  104. static std::unique_ptr<TurnPort> CreateUnique(
  105. rtc::Thread* thread,
  106. rtc::PacketSocketFactory* factory,
  107. rtc::Network* network,
  108. uint16_t min_port,
  109. uint16_t max_port,
  110. const std::string& username, // ice username.
  111. const std::string& password, // ice password.
  112. const ProtocolAddress& server_address,
  113. const RelayCredentials& credentials,
  114. int server_priority,
  115. const std::string& origin,
  116. const std::vector<std::string>& tls_alpn_protocols,
  117. const std::vector<std::string>& tls_elliptic_curves,
  118. webrtc::TurnCustomizer* customizer,
  119. rtc::SSLCertificateVerifier* tls_cert_verifier = nullptr) {
  120. return Create(thread, factory, network, min_port, max_port, username,
  121. password, server_address, credentials, server_priority,
  122. origin, tls_alpn_protocols, tls_elliptic_curves, customizer,
  123. tls_cert_verifier);
  124. }
  125. ~TurnPort() override;
  126. const ProtocolAddress& server_address() const { return server_address_; }
  127. // Returns an empty address if the local address has not been assigned.
  128. rtc::SocketAddress GetLocalAddress() const;
  129. bool ready() const { return state_ == STATE_READY; }
  130. bool connected() const {
  131. return state_ == STATE_READY || state_ == STATE_CONNECTED;
  132. }
  133. const RelayCredentials& credentials() const { return credentials_; }
  134. ProtocolType GetProtocol() const override;
  135. virtual TlsCertPolicy GetTlsCertPolicy() const;
  136. virtual void SetTlsCertPolicy(TlsCertPolicy tls_cert_policy);
  137. void SetTurnLoggingId(const std::string& turn_logging_id);
  138. virtual std::vector<std::string> GetTlsAlpnProtocols() const;
  139. virtual std::vector<std::string> GetTlsEllipticCurves() const;
  140. // Release a TURN allocation by sending a refresh with lifetime 0.
  141. // Sets state to STATE_RECEIVEONLY.
  142. void Release();
  143. void PrepareAddress() override;
  144. Connection* CreateConnection(const Candidate& c,
  145. PortInterface::CandidateOrigin origin) override;
  146. int SendTo(const void* data,
  147. size_t size,
  148. const rtc::SocketAddress& addr,
  149. const rtc::PacketOptions& options,
  150. bool payload) override;
  151. int SetOption(rtc::Socket::Option opt, int value) override;
  152. int GetOption(rtc::Socket::Option opt, int* value) override;
  153. int GetError() override;
  154. bool HandleIncomingPacket(rtc::AsyncPacketSocket* socket,
  155. const char* data,
  156. size_t size,
  157. const rtc::SocketAddress& remote_addr,
  158. int64_t packet_time_us) override;
  159. bool CanHandleIncomingPacketsFrom(
  160. const rtc::SocketAddress& addr) const override;
  161. virtual void OnReadPacket(rtc::AsyncPacketSocket* socket,
  162. const char* data,
  163. size_t size,
  164. const rtc::SocketAddress& remote_addr,
  165. const int64_t& packet_time_us);
  166. void OnSentPacket(rtc::AsyncPacketSocket* socket,
  167. const rtc::SentPacket& sent_packet) override;
  168. virtual void OnReadyToSend(rtc::AsyncPacketSocket* socket);
  169. bool SupportsProtocol(const std::string& protocol) const override;
  170. void OnSocketConnect(rtc::AsyncPacketSocket* socket);
  171. void OnSocketClose(rtc::AsyncPacketSocket* socket, int error);
  172. const std::string& hash() const { return hash_; }
  173. const std::string& nonce() const { return nonce_; }
  174. int error() const { return error_; }
  175. void OnAllocateMismatch();
  176. rtc::AsyncPacketSocket* socket() const { return socket_; }
  177. // For testing only.
  178. rtc::AsyncInvoker* invoker() { return &invoker_; }
  179. // Signal with resolved server address.
  180. // Parameters are port, server address and resolved server address.
  181. // This signal will be sent only if server address is resolved successfully.
  182. sigslot::
  183. signal3<TurnPort*, const rtc::SocketAddress&, const rtc::SocketAddress&>
  184. SignalResolvedServerAddress;
  185. // Signal when TurnPort is closed,
  186. // e.g remote socket closed (TCP)
  187. // or receiveing a REFRESH response with lifetime 0.
  188. sigslot::signal1<TurnPort*> SignalTurnPortClosed;
  189. // All public methods/signals below are for testing only.
  190. sigslot::signal2<TurnPort*, int> SignalTurnRefreshResult;
  191. sigslot::signal3<TurnPort*, const rtc::SocketAddress&, int>
  192. SignalCreatePermissionResult;
  193. void FlushRequests(int msg_type) { request_manager_.Flush(msg_type); }
  194. bool HasRequests() { return !request_manager_.empty(); }
  195. void set_credentials(const RelayCredentials& credentials) {
  196. credentials_ = credentials;
  197. }
  198. // Finds the turn entry with |address| and sets its channel id.
  199. // Returns true if the entry is found.
  200. bool SetEntryChannelId(const rtc::SocketAddress& address, int channel_id);
  201. // Visible for testing.
  202. // Shuts down the turn port, usually because of some fatal errors.
  203. void Close();
  204. void HandleConnectionDestroyed(Connection* conn) override;
  205. protected:
  206. TurnPort(rtc::Thread* thread,
  207. rtc::PacketSocketFactory* factory,
  208. rtc::Network* network,
  209. rtc::AsyncPacketSocket* socket,
  210. const std::string& username,
  211. const std::string& password,
  212. const ProtocolAddress& server_address,
  213. const RelayCredentials& credentials,
  214. int server_priority,
  215. const std::string& origin,
  216. webrtc::TurnCustomizer* customizer);
  217. TurnPort(rtc::Thread* thread,
  218. rtc::PacketSocketFactory* factory,
  219. rtc::Network* network,
  220. uint16_t min_port,
  221. uint16_t max_port,
  222. const std::string& username,
  223. const std::string& password,
  224. const ProtocolAddress& server_address,
  225. const RelayCredentials& credentials,
  226. int server_priority,
  227. const std::string& origin,
  228. const std::vector<std::string>& tls_alpn_protocols,
  229. const std::vector<std::string>& tls_elliptic_curves,
  230. webrtc::TurnCustomizer* customizer,
  231. rtc::SSLCertificateVerifier* tls_cert_verifier = nullptr);
  232. // NOTE: This method needs to be accessible for StacPort
  233. // return true if entry was created (i.e channel_number consumed).
  234. bool CreateOrRefreshEntry(const rtc::SocketAddress& addr, int channel_number);
  235. bool CreateOrRefreshEntry(const rtc::SocketAddress& addr,
  236. int channel_number,
  237. const std::string& remote_ufrag);
  238. rtc::DiffServCodePoint StunDscpValue() const override;
  239. private:
  240. enum {
  241. MSG_ALLOCATE_ERROR = MSG_FIRST_AVAILABLE,
  242. MSG_ALLOCATE_MISMATCH,
  243. MSG_TRY_ALTERNATE_SERVER,
  244. MSG_REFRESH_ERROR,
  245. MSG_ALLOCATION_RELEASED
  246. };
  247. typedef std::list<TurnEntry*> EntryList;
  248. typedef std::map<rtc::Socket::Option, int> SocketOptionsMap;
  249. typedef std::set<rtc::SocketAddress> AttemptedServerSet;
  250. void OnMessage(rtc::Message* pmsg) override;
  251. bool CreateTurnClientSocket();
  252. void set_nonce(const std::string& nonce) { nonce_ = nonce; }
  253. void set_realm(const std::string& realm) {
  254. if (realm != realm_) {
  255. realm_ = realm;
  256. UpdateHash();
  257. }
  258. }
  259. void OnRefreshError();
  260. void HandleRefreshError();
  261. bool SetAlternateServer(const rtc::SocketAddress& address);
  262. void ResolveTurnAddress(const rtc::SocketAddress& address);
  263. void OnResolveResult(rtc::AsyncResolverInterface* resolver);
  264. void AddRequestAuthInfo(StunMessage* msg);
  265. void OnSendStunPacket(const void* data, size_t size, StunRequest* request);
  266. // Stun address from allocate success response.
  267. // Currently used only for testing.
  268. void OnStunAddress(const rtc::SocketAddress& address);
  269. void OnAllocateSuccess(const rtc::SocketAddress& address,
  270. const rtc::SocketAddress& stun_address);
  271. void OnAllocateError(int error_code, const std::string& reason);
  272. void OnAllocateRequestTimeout();
  273. void HandleDataIndication(const char* data,
  274. size_t size,
  275. int64_t packet_time_us);
  276. void HandleChannelData(int channel_id,
  277. const char* data,
  278. size_t size,
  279. int64_t packet_time_us);
  280. void DispatchPacket(const char* data,
  281. size_t size,
  282. const rtc::SocketAddress& remote_addr,
  283. ProtocolType proto,
  284. int64_t packet_time_us);
  285. bool ScheduleRefresh(uint32_t lifetime);
  286. void SendRequest(StunRequest* request, int delay);
  287. int Send(const void* data, size_t size, const rtc::PacketOptions& options);
  288. void UpdateHash();
  289. bool UpdateNonce(StunMessage* response);
  290. void ResetNonce();
  291. bool HasPermission(const rtc::IPAddress& ipaddr) const;
  292. TurnEntry* FindEntry(const rtc::SocketAddress& address) const;
  293. TurnEntry* FindEntry(int channel_id) const;
  294. bool EntryExists(TurnEntry* e);
  295. void DestroyEntry(TurnEntry* entry);
  296. // Destroys the entry only if |timestamp| matches the destruction timestamp
  297. // in |entry|.
  298. void DestroyEntryIfNotCancelled(TurnEntry* entry, int64_t timestamp);
  299. void ScheduleEntryDestruction(TurnEntry* entry);
  300. // Marks the connection with remote address |address| failed and
  301. // pruned (a.k.a. write-timed-out). Returns true if a connection is found.
  302. bool FailAndPruneConnection(const rtc::SocketAddress& address);
  303. // Reconstruct the URL of the server which the candidate is gathered from.
  304. std::string ReconstructedServerUrl(bool use_hostname);
  305. void MaybeAddTurnLoggingId(StunMessage* message);
  306. void TurnCustomizerMaybeModifyOutgoingStunMessage(StunMessage* message);
  307. bool TurnCustomizerAllowChannelData(const void* data,
  308. size_t size,
  309. bool payload);
  310. ProtocolAddress server_address_;
  311. TlsCertPolicy tls_cert_policy_ = TlsCertPolicy::TLS_CERT_POLICY_SECURE;
  312. std::vector<std::string> tls_alpn_protocols_;
  313. std::vector<std::string> tls_elliptic_curves_;
  314. rtc::SSLCertificateVerifier* tls_cert_verifier_;
  315. RelayCredentials credentials_;
  316. AttemptedServerSet attempted_server_addresses_;
  317. rtc::AsyncPacketSocket* socket_;
  318. SocketOptionsMap socket_options_;
  319. rtc::AsyncResolverInterface* resolver_;
  320. int error_;
  321. rtc::DiffServCodePoint stun_dscp_value_;
  322. StunRequestManager request_manager_;
  323. std::string realm_; // From 401/438 response message.
  324. std::string nonce_; // From 401/438 response message.
  325. std::string hash_; // Digest of username:realm:password
  326. int next_channel_number_;
  327. EntryList entries_;
  328. PortState state_;
  329. // By default the value will be set to 0. This value will be used in
  330. // calculating the candidate priority.
  331. int server_priority_;
  332. // The number of retries made due to allocate mismatch error.
  333. size_t allocate_mismatch_retries_;
  334. rtc::AsyncInvoker invoker_;
  335. // Optional TurnCustomizer that can modify outgoing messages. Once set, this
  336. // must outlive the TurnPort's lifetime.
  337. webrtc::TurnCustomizer* turn_customizer_ = nullptr;
  338. // Optional TurnLoggingId.
  339. // An identifier set by application that is added to TURN_ALLOCATE_REQUEST
  340. // and can be used to match client/backend logs.
  341. // TODO(jonaso): This should really be initialized in constructor,
  342. // but that is currently so terrible. Fix once constructor is changed
  343. // to be more easy to work with.
  344. std::string turn_logging_id_;
  345. friend class TurnEntry;
  346. friend class TurnAllocateRequest;
  347. friend class TurnRefreshRequest;
  348. friend class TurnCreatePermissionRequest;
  349. friend class TurnChannelBindRequest;
  350. };
  351. } // namespace cricket
  352. #endif // P2P_BASE_TURN_PORT_H_