nricectx.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  4. * You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. // Original author: ekr@rtfm.com
  6. // Some of this code is cut-and-pasted from nICEr. Copyright is:
  7. /*
  8. Copyright (c) 2007, Adobe Systems, Incorporated
  9. All rights reserved.
  10. Redistribution and use in source and binary forms, with or without
  11. modification, are permitted provided that the following conditions are
  12. met:
  13. * Redistributions of source code must retain the above copyright
  14. notice, this list of conditions and the following disclaimer.
  15. * Redistributions in binary form must reproduce the above copyright
  16. notice, this list of conditions and the following disclaimer in the
  17. documentation and/or other materials provided with the distribution.
  18. * Neither the name of Adobe Systems, Network Resonance nor the names of its
  19. contributors may be used to endorse or promote products derived from
  20. this software without specific prior written permission.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. */
  33. /* This Source Code Form is subject to the terms of the Mozilla Public
  34. * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  35. * You can obtain one at http://mozilla.org/MPL/2.0/. */
  36. // Original author: ekr@rtfm.com
  37. // This is a wrapper around the nICEr ICE stack
  38. #ifndef nricectx_h__
  39. #define nricectx_h__
  40. #include <string>
  41. #include <vector>
  42. #include "sigslot.h"
  43. #include "prnetdb.h"
  44. #include "mozilla/RefPtr.h"
  45. #include "mozilla/TimeStamp.h"
  46. #include "mozilla/UniquePtr.h"
  47. #include "nsAutoPtr.h"
  48. #include "nsIEventTarget.h"
  49. #include "nsITimer.h"
  50. #include "m_cpp_utils.h"
  51. typedef struct nr_ice_ctx_ nr_ice_ctx;
  52. typedef struct nr_ice_peer_ctx_ nr_ice_peer_ctx;
  53. typedef struct nr_ice_media_stream_ nr_ice_media_stream;
  54. typedef struct nr_ice_handler_ nr_ice_handler;
  55. typedef struct nr_ice_handler_vtbl_ nr_ice_handler_vtbl;
  56. typedef struct nr_ice_candidate_ nr_ice_candidate;
  57. typedef struct nr_ice_cand_pair_ nr_ice_cand_pair;
  58. typedef struct nr_ice_stun_server_ nr_ice_stun_server;
  59. typedef struct nr_ice_turn_server_ nr_ice_turn_server;
  60. typedef struct nr_resolver_ nr_resolver;
  61. typedef struct nr_proxy_tunnel_config_ nr_proxy_tunnel_config;
  62. typedef void* NR_SOCKET;
  63. namespace mozilla {
  64. // Timestamps set whenever a packet is dropped due to global rate limiting
  65. // (see nr_socket_prsock.cpp)
  66. TimeStamp nr_socket_short_term_violation_time();
  67. TimeStamp nr_socket_long_term_violation_time();
  68. class NrIceMediaStream;
  69. extern const char kNrIceTransportUdp[];
  70. extern const char kNrIceTransportTcp[];
  71. class NrIceStunServer {
  72. public:
  73. explicit NrIceStunServer(const PRNetAddr& addr) : has_addr_(true) {
  74. memcpy(&addr_, &addr, sizeof(addr));
  75. }
  76. // The main function to use. Will take either an address or a hostname.
  77. static UniquePtr<NrIceStunServer> Create(const std::string& addr, uint16_t port,
  78. const char *transport = kNrIceTransportUdp) {
  79. UniquePtr<NrIceStunServer> server(new NrIceStunServer(transport));
  80. nsresult rv = server->Init(addr, port);
  81. if (NS_FAILED(rv))
  82. return nullptr;
  83. return server;
  84. }
  85. nsresult ToNicerStunStruct(nr_ice_stun_server* server) const;
  86. protected:
  87. explicit NrIceStunServer(const char *transport) :
  88. addr_(), transport_(transport) {}
  89. nsresult Init(const std::string& addr, uint16_t port) {
  90. PRStatus status = PR_StringToNetAddr(addr.c_str(), &addr_);
  91. if (status == PR_SUCCESS) {
  92. // Parseable as an address
  93. addr_.inet.port = PR_htons(port);
  94. port_ = port;
  95. has_addr_ = true;
  96. return NS_OK;
  97. }
  98. else if (addr.size() < 256) {
  99. // Apparently this is a hostname.
  100. host_ = addr;
  101. port_ = port;
  102. has_addr_ = false;
  103. return NS_OK;
  104. }
  105. return NS_ERROR_FAILURE;
  106. }
  107. bool has_addr_;
  108. std::string host_;
  109. uint16_t port_;
  110. PRNetAddr addr_;
  111. std::string transport_;
  112. };
  113. class NrIceTurnServer : public NrIceStunServer {
  114. public:
  115. static UniquePtr<NrIceTurnServer> Create(const std::string& addr, uint16_t port,
  116. const std::string& username,
  117. const std::vector<unsigned char>& password,
  118. const char *transport = kNrIceTransportUdp) {
  119. UniquePtr<NrIceTurnServer> server(new NrIceTurnServer(username, password, transport));
  120. nsresult rv = server->Init(addr, port);
  121. if (NS_FAILED(rv))
  122. return nullptr;
  123. return server;
  124. }
  125. nsresult ToNicerTurnStruct(nr_ice_turn_server *server) const;
  126. private:
  127. NrIceTurnServer(const std::string& username,
  128. const std::vector<unsigned char>& password,
  129. const char *transport) :
  130. NrIceStunServer(transport), username_(username), password_(password) {}
  131. std::string username_;
  132. std::vector<unsigned char> password_;
  133. };
  134. class NrIceProxyServer {
  135. public:
  136. NrIceProxyServer(const std::string& host, uint16_t port,
  137. const std::string& alpn) :
  138. host_(host), port_(port), alpn_(alpn) {
  139. }
  140. NrIceProxyServer() : NrIceProxyServer("", 0, "") {}
  141. const std::string& host() const { return host_; }
  142. uint16_t port() const { return port_; }
  143. const std::string& alpn() const { return alpn_; }
  144. private:
  145. std::string host_;
  146. uint16_t port_;
  147. std::string alpn_;
  148. };
  149. class TestNat;
  150. class NrIceCtx {
  151. friend class NrIceCtxHandler;
  152. public:
  153. enum ConnectionState { ICE_CTX_INIT,
  154. ICE_CTX_CHECKING,
  155. ICE_CTX_CONNECTED,
  156. ICE_CTX_COMPLETED,
  157. ICE_CTX_FAILED,
  158. ICE_CTX_DISCONNECTED,
  159. ICE_CTX_CLOSED
  160. };
  161. enum GatheringState { ICE_CTX_GATHER_INIT,
  162. ICE_CTX_GATHER_STARTED,
  163. ICE_CTX_GATHER_COMPLETE
  164. };
  165. enum Controlling { ICE_CONTROLLING,
  166. ICE_CONTROLLED
  167. };
  168. enum Policy { ICE_POLICY_RELAY,
  169. ICE_POLICY_NO_HOST,
  170. ICE_POLICY_ALL
  171. };
  172. // initialize ICE globals, crypto, and logging
  173. static void InitializeGlobals(bool allow_loopback = false,
  174. bool tcp_enabled = true,
  175. bool allow_link_local = false);
  176. static std::string GetNewUfrag();
  177. static std::string GetNewPwd();
  178. bool Initialize();
  179. bool Initialize(const std::string& ufrag, const std::string& pwd);
  180. int SetNat(const RefPtr<TestNat>& aNat);
  181. // Deinitialize all ICE global state. Used only for testing.
  182. static void internal_DeinitializeGlobal();
  183. // Divide some timers to faster testing. Used only for testing.
  184. void internal_SetTimerAccelarator(int divider);
  185. nr_ice_ctx *ctx() { return ctx_; }
  186. nr_ice_peer_ctx *peer() { return peer_; }
  187. // Testing only.
  188. void destroy_peer_ctx();
  189. void SetStream(size_t index, NrIceMediaStream* stream);
  190. RefPtr<NrIceMediaStream> GetStream(size_t index) {
  191. if (index < streams_.size()) {
  192. return streams_[index];
  193. }
  194. return nullptr;
  195. }
  196. // Some might be null
  197. size_t GetStreamCount() const
  198. {
  199. return streams_.size();
  200. }
  201. // The name of the ctx
  202. const std::string& name() const { return name_; }
  203. // Get ufrag and password.
  204. std::string ufrag() const;
  205. std::string pwd() const;
  206. // Current state
  207. ConnectionState connection_state() const {
  208. return connection_state_;
  209. }
  210. // Current state
  211. GatheringState gathering_state() const {
  212. return gathering_state_;
  213. }
  214. // Get the global attributes
  215. std::vector<std::string> GetGlobalAttributes();
  216. // Set the other side's global attributes
  217. nsresult ParseGlobalAttributes(std::vector<std::string> attrs);
  218. // Set whether we are controlling or not.
  219. nsresult SetControlling(Controlling controlling);
  220. Controlling GetControlling();
  221. // Set whether we're allowed to produce none, relay or all candidates.
  222. // TODO(jib@mozilla.com): Work out what change means mid-connection (1181768)
  223. nsresult SetPolicy(Policy policy);
  224. Policy policy() const {
  225. return policy_;
  226. }
  227. // Set the STUN servers. Must be called before StartGathering
  228. // (if at all).
  229. nsresult SetStunServers(const std::vector<NrIceStunServer>& stun_servers);
  230. // Set the TURN servers. Must be called before StartGathering
  231. // (if at all).
  232. nsresult SetTurnServers(const std::vector<NrIceTurnServer>& turn_servers);
  233. // Provide the resolution provider. Must be called before
  234. // StartGathering.
  235. nsresult SetResolver(nr_resolver *resolver);
  236. // Provide the proxy address. Must be called before
  237. // StartGathering.
  238. nsresult SetProxyServer(const NrIceProxyServer& proxy_server);
  239. // Start ICE gathering
  240. nsresult StartGathering(bool default_route_only, bool proxy_only);
  241. // Start checking
  242. nsresult StartChecks();
  243. // Finalize the ICE negotiation. I.e., there will be no
  244. // more forking.
  245. nsresult Finalize();
  246. // Are we trickling?
  247. bool generating_trickle() const { return trickle_; }
  248. // Signals to indicate events. API users can (and should)
  249. // register for these.
  250. sigslot::signal2<NrIceCtx*, NrIceCtx::GatheringState>
  251. SignalGatheringStateChange;
  252. sigslot::signal2<NrIceCtx*, NrIceCtx::ConnectionState>
  253. SignalConnectionStateChange;
  254. // The thread to direct method calls to
  255. nsCOMPtr<nsIEventTarget> thread() { return sts_target_; }
  256. NS_INLINE_DECL_THREADSAFE_REFCOUNTING(NrIceCtx)
  257. private:
  258. NrIceCtx(const std::string& name,
  259. bool offerer,
  260. Policy policy);
  261. virtual ~NrIceCtx();
  262. DISALLOW_COPY_ASSIGN(NrIceCtx);
  263. // Callbacks for nICEr
  264. static void gather_cb(NR_SOCKET s, int h, void *arg); // ICE gather complete
  265. // Handler implementation
  266. static int select_pair(void *obj,nr_ice_media_stream *stream,
  267. int component_id, nr_ice_cand_pair **potentials,
  268. int potential_ct);
  269. static int stream_ready(void *obj, nr_ice_media_stream *stream);
  270. static int stream_failed(void *obj, nr_ice_media_stream *stream);
  271. static int ice_checking(void *obj, nr_ice_peer_ctx *pctx);
  272. static int ice_connected(void *obj, nr_ice_peer_ctx *pctx);
  273. static int ice_disconnected(void *obj, nr_ice_peer_ctx *pctx);
  274. static int msg_recvd(void *obj, nr_ice_peer_ctx *pctx,
  275. nr_ice_media_stream *stream, int component_id,
  276. unsigned char *msg, int len);
  277. static void trickle_cb(void *arg, nr_ice_ctx *ctx, nr_ice_media_stream *stream,
  278. int component_id, nr_ice_candidate *candidate);
  279. // Find a media stream by stream ptr. Gross
  280. RefPtr<NrIceMediaStream> FindStream(nr_ice_media_stream *stream);
  281. // Set the state
  282. void SetConnectionState(ConnectionState state);
  283. // Set the state
  284. void SetGatheringState(GatheringState state);
  285. ConnectionState connection_state_;
  286. GatheringState gathering_state_;
  287. const std::string name_;
  288. bool offerer_;
  289. bool ice_controlling_set_;
  290. std::vector<RefPtr<NrIceMediaStream> > streams_;
  291. nr_ice_ctx *ctx_;
  292. nr_ice_peer_ctx *peer_;
  293. nr_ice_handler_vtbl* ice_handler_vtbl_; // Must be pointer
  294. nr_ice_handler* ice_handler_; // Must be pointer
  295. bool trickle_;
  296. nsCOMPtr<nsIEventTarget> sts_target_; // The thread to run on
  297. Policy policy_;
  298. RefPtr<TestNat> nat_;
  299. };
  300. } // close namespace
  301. #endif