turn_unittest.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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 code copied from nICEr. License 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. #include <stdlib.h>
  34. #include <iostream>
  35. #include "sigslot.h"
  36. #include "logging.h"
  37. #include "nspr.h"
  38. #include "nss.h"
  39. #include "ssl.h"
  40. #include "nsThreadUtils.h"
  41. #include "nsXPCOM.h"
  42. #include "runnable_utils.h"
  43. #define GTEST_HAS_RTTI 0
  44. #include "gtest/gtest.h"
  45. #include "gtest_utils.h"
  46. #define USE_TURN
  47. // nICEr includes
  48. extern "C" {
  49. #include "nr_api.h"
  50. #include "registry.h"
  51. #include "async_timer.h"
  52. #include "r_crc32.h"
  53. #include "ice_util.h"
  54. #include "transport_addr.h"
  55. #include "nr_crypto.h"
  56. #include "nr_socket.h"
  57. #include "nr_socket_local.h"
  58. #include "nr_socket_buffered_stun.h"
  59. #include "stun_client_ctx.h"
  60. #include "turn_client_ctx.h"
  61. }
  62. #include "nricemediastream.h"
  63. #include "nricectxhandler.h"
  64. using namespace mozilla;
  65. static std::string kDummyTurnServer("192.0.2.1"); // From RFC 5737
  66. class TurnClient : public MtransportTest {
  67. public:
  68. TurnClient()
  69. : MtransportTest(),
  70. real_socket_(nullptr),
  71. net_socket_(nullptr),
  72. buffered_socket_(nullptr),
  73. net_fd_(nullptr),
  74. turn_ctx_(nullptr),
  75. allocated_(false),
  76. received_(0),
  77. protocol_(IPPROTO_UDP) {
  78. }
  79. ~TurnClient() {
  80. }
  81. static void SetUpTestCase() {
  82. NrIceCtx::InitializeGlobals(false, false, false);
  83. }
  84. void SetTcp() {
  85. protocol_ = IPPROTO_TCP;
  86. }
  87. void Init_s() {
  88. int r;
  89. nr_transport_addr addr;
  90. r = nr_ip4_port_to_transport_addr(0, 0, protocol_, &addr);
  91. ASSERT_EQ(0, r);
  92. r = nr_socket_local_create(nullptr, &addr, &real_socket_);
  93. ASSERT_EQ(0, r);
  94. if (protocol_ == IPPROTO_TCP) {
  95. int r =
  96. nr_socket_buffered_stun_create(real_socket_, 100000, TURN_TCP_FRAMING,
  97. &buffered_socket_);
  98. ASSERT_EQ(0, r);
  99. net_socket_ = buffered_socket_;
  100. } else {
  101. net_socket_ = real_socket_;
  102. }
  103. r = nr_str_port_to_transport_addr(turn_server_.c_str(), 3478,
  104. protocol_, &addr);
  105. ASSERT_EQ(0, r);
  106. std::vector<unsigned char> password_vec(
  107. turn_password_.begin(), turn_password_.end());
  108. Data password;
  109. INIT_DATA(password, &password_vec[0], password_vec.size());
  110. r = nr_turn_client_ctx_create("test", net_socket_,
  111. turn_user_.c_str(),
  112. &password,
  113. &addr, &turn_ctx_);
  114. ASSERT_EQ(0, r);
  115. r = nr_socket_getfd(net_socket_, &net_fd_);
  116. ASSERT_EQ(0, r);
  117. NR_ASYNC_WAIT(net_fd_, NR_ASYNC_WAIT_READ, socket_readable_cb,
  118. (void *)this);
  119. }
  120. void TearDown_s() {
  121. nr_turn_client_ctx_destroy(&turn_ctx_);
  122. if (net_fd_) {
  123. NR_ASYNC_CANCEL(net_fd_, NR_ASYNC_WAIT_READ);
  124. }
  125. nr_socket_destroy(&buffered_socket_);
  126. }
  127. void TearDown() {
  128. RUN_ON_THREAD(test_utils_->sts_target(),
  129. WrapRunnable(this, &TurnClient::TearDown_s),
  130. NS_DISPATCH_SYNC);
  131. }
  132. void Allocate_s() {
  133. Init_s();
  134. ASSERT_TRUE(turn_ctx_);
  135. int r = nr_turn_client_allocate(turn_ctx_,
  136. allocate_success_cb,
  137. this);
  138. ASSERT_EQ(0, r);
  139. }
  140. void Allocate(bool expect_success=true) {
  141. RUN_ON_THREAD(test_utils_->sts_target(),
  142. WrapRunnable(this, &TurnClient::Allocate_s),
  143. NS_DISPATCH_SYNC);
  144. if (expect_success) {
  145. ASSERT_TRUE_WAIT(allocated_, 5000);
  146. }
  147. else {
  148. PR_Sleep(10000);
  149. ASSERT_FALSE(allocated_);
  150. }
  151. }
  152. void Allocated() {
  153. if (turn_ctx_->state!=NR_TURN_CLIENT_STATE_ALLOCATED) {
  154. std::cerr << "Allocation failed" << std::endl;
  155. return;
  156. }
  157. allocated_ = true;
  158. int r;
  159. nr_transport_addr addr;
  160. r = nr_turn_client_get_relayed_address(turn_ctx_, &addr);
  161. ASSERT_EQ(0, r);
  162. relay_addr_ = addr.as_string;
  163. std::cerr << "Allocation succeeded with addr=" << relay_addr_ << std::endl;
  164. }
  165. void Deallocate_s() {
  166. ASSERT_TRUE(turn_ctx_);
  167. std::cerr << "De-Allocating..." << std::endl;
  168. int r = nr_turn_client_deallocate(turn_ctx_);
  169. ASSERT_EQ(0, r);
  170. }
  171. void Deallocate() {
  172. RUN_ON_THREAD(test_utils_->sts_target(),
  173. WrapRunnable(this, &TurnClient::Deallocate_s),
  174. NS_DISPATCH_SYNC);
  175. }
  176. void RequestPermission_s(const std::string& target) {
  177. nr_transport_addr addr;
  178. int r;
  179. // Expected pattern here is "IP4:127.0.0.1:3487"
  180. ASSERT_EQ(0, target.compare(0, 4, "IP4:"));
  181. size_t offset = target.rfind(':');
  182. ASSERT_NE(std::string::npos, offset);
  183. std::string host = target.substr(4, offset - 4);
  184. std::string port = target.substr(offset + 1);
  185. r = nr_str_port_to_transport_addr(host.c_str(),
  186. atoi(port.c_str()),
  187. IPPROTO_UDP,
  188. &addr);
  189. ASSERT_EQ(0, r);
  190. r = nr_turn_client_ensure_perm(turn_ctx_, &addr);
  191. ASSERT_EQ(0, r);
  192. }
  193. void RequestPermission(const std::string& target) {
  194. RUN_ON_THREAD(test_utils_->sts_target(),
  195. WrapRunnable(this, &TurnClient::RequestPermission_s, target),
  196. NS_DISPATCH_SYNC);
  197. }
  198. void Readable(NR_SOCKET s, int how, void *arg) {
  199. // Re-arm
  200. std::cerr << "Socket is readable" << std::endl;
  201. NR_ASYNC_WAIT(s, how, socket_readable_cb, arg);
  202. UCHAR buf[8192];
  203. size_t len_s;
  204. nr_transport_addr addr;
  205. int r = nr_socket_recvfrom(net_socket_, buf, sizeof(buf), &len_s, 0, &addr);
  206. if (r) {
  207. std::cerr << "Error reading from socket" << std::endl;
  208. return;
  209. }
  210. ASSERT_LT(len_s, (size_t)INT_MAX);
  211. int len = (int)len_s;
  212. if (nr_is_stun_response_message(buf, len)) {
  213. std::cerr << "STUN response" << std::endl;
  214. r = nr_turn_client_process_response(turn_ctx_, buf, len, &addr);
  215. if (r && r != R_REJECTED && r != R_RETRY) {
  216. std::cerr << "Error processing STUN: " << r << std::endl;
  217. }
  218. } else if (nr_is_stun_indication_message(buf, len)) {
  219. std::cerr << "STUN indication" << std::endl;
  220. /* Process the indication */
  221. unsigned char data[NR_STUN_MAX_MESSAGE_SIZE];
  222. size_t datal;
  223. nr_transport_addr remote_addr;
  224. r = nr_turn_client_parse_data_indication(turn_ctx_, &addr,
  225. buf, len,
  226. data, &datal, sizeof(data),
  227. &remote_addr);
  228. ASSERT_EQ(0, r);
  229. std::cerr << "Received " << datal << " bytes from "
  230. << remote_addr.as_string << std::endl;
  231. received_ += datal;
  232. for (size_t i=0; i < datal; i++) {
  233. ASSERT_EQ(i & 0xff, data[i]);
  234. }
  235. }
  236. else {
  237. if (nr_is_stun_message(buf, len)) {
  238. std::cerr << "STUN message of unexpected type" << std::endl;
  239. } else {
  240. std::cerr << "Not a STUN message" << std::endl;
  241. }
  242. return;
  243. }
  244. }
  245. void SendTo_s(const std::string& target, int expect_return) {
  246. nr_transport_addr addr;
  247. int r;
  248. // Expected pattern here is "IP4:127.0.0.1:3487"
  249. ASSERT_EQ(0, target.compare(0, 4, "IP4:"));
  250. size_t offset = target.rfind(':');
  251. ASSERT_NE(std::string::npos, offset);
  252. std::string host = target.substr(4, offset - 4);
  253. std::string port = target.substr(offset + 1);
  254. r = nr_str_port_to_transport_addr(host.c_str(),
  255. atoi(port.c_str()),
  256. IPPROTO_UDP,
  257. &addr);
  258. ASSERT_EQ(0, r);
  259. unsigned char test[100];
  260. for (size_t i=0; i<sizeof(test); i++) {
  261. test[i] = i & 0xff;
  262. }
  263. std::cerr << "Sending test message to " << target << " ..." << std::endl;
  264. r = nr_turn_client_send_indication(turn_ctx_,
  265. test, sizeof(test), 0,
  266. &addr);
  267. if (expect_return >= 0) {
  268. ASSERT_EQ(expect_return, r);
  269. }
  270. }
  271. void SendTo(const std::string& target, int expect_return=0) {
  272. RUN_ON_THREAD(test_utils_->sts_target(),
  273. WrapRunnable(this, &TurnClient::SendTo_s, target,
  274. expect_return),
  275. NS_DISPATCH_SYNC);
  276. }
  277. int received() const { return received_; }
  278. static void socket_readable_cb(NR_SOCKET s, int how, void *arg) {
  279. static_cast<TurnClient *>(arg)->Readable(s, how, arg);
  280. }
  281. static void allocate_success_cb(NR_SOCKET s, int how, void *arg){
  282. static_cast<TurnClient *>(arg)->Allocated();
  283. }
  284. protected:
  285. std::string turn_server_;
  286. nr_socket *real_socket_;
  287. nr_socket *net_socket_;
  288. nr_socket *buffered_socket_;
  289. NR_SOCKET net_fd_;
  290. nr_turn_client_ctx *turn_ctx_;
  291. std::string relay_addr_;
  292. bool allocated_;
  293. int received_;
  294. int protocol_;
  295. };
  296. TEST_F(TurnClient, Allocate) {
  297. if (WarnIfTurnNotConfigured())
  298. return;
  299. Allocate();
  300. }
  301. TEST_F(TurnClient, AllocateTcp) {
  302. if (WarnIfTurnNotConfigured())
  303. return;
  304. SetTcp();
  305. Allocate();
  306. }
  307. TEST_F(TurnClient, AllocateAndHold) {
  308. if (WarnIfTurnNotConfigured())
  309. return;
  310. Allocate();
  311. PR_Sleep(20000);
  312. ASSERT_TRUE(turn_ctx_->state == NR_TURN_CLIENT_STATE_ALLOCATED);
  313. }
  314. TEST_F(TurnClient, SendToSelf) {
  315. if (WarnIfTurnNotConfigured())
  316. return;
  317. Allocate();
  318. SendTo(relay_addr_);
  319. ASSERT_TRUE_WAIT(received() == 100, 5000);
  320. SendTo(relay_addr_);
  321. ASSERT_TRUE_WAIT(received() == 200, 1000);
  322. }
  323. TEST_F(TurnClient, SendToSelfTcp) {
  324. if (WarnIfTurnNotConfigured())
  325. return;
  326. SetTcp();
  327. Allocate();
  328. SendTo(relay_addr_);
  329. ASSERT_TRUE_WAIT(received() == 100, 5000);
  330. SendTo(relay_addr_);
  331. ASSERT_TRUE_WAIT(received() == 200, 1000);
  332. }
  333. TEST_F(TurnClient, PermissionDenied) {
  334. if (WarnIfTurnNotConfigured())
  335. return;
  336. Allocate();
  337. RequestPermission(relay_addr_);
  338. PR_Sleep(1000);
  339. /* Fake a 403 response */
  340. nr_turn_permission *perm;
  341. perm = STAILQ_FIRST(&turn_ctx_->permissions);
  342. ASSERT_TRUE(perm);
  343. while (perm) {
  344. perm->stun->last_error_code = 403;
  345. std::cerr << "Set 403's on permission" << std::endl;
  346. perm = STAILQ_NEXT(perm, entry);
  347. }
  348. SendTo(relay_addr_, R_NOT_PERMITTED);
  349. ASSERT_TRUE(received() == 0);
  350. //TODO: We should check if we can still send to a second destination, but
  351. // we would need a second TURN client as one client can only handle one
  352. // allocation (maybe as part of bug 1128128 ?).
  353. }
  354. TEST_F(TurnClient, DeallocateReceiveFailure) {
  355. if (WarnIfTurnNotConfigured())
  356. return;
  357. Allocate();
  358. SendTo(relay_addr_);
  359. ASSERT_TRUE_WAIT(received() == 100, 5000);
  360. Deallocate();
  361. turn_ctx_->state = NR_TURN_CLIENT_STATE_ALLOCATED;
  362. SendTo(relay_addr_);
  363. PR_Sleep(1000);
  364. ASSERT_TRUE(received() == 100);
  365. }
  366. TEST_F(TurnClient, DeallocateReceiveFailureTcp) {
  367. if (WarnIfTurnNotConfigured())
  368. return;
  369. SetTcp();
  370. Allocate();
  371. SendTo(relay_addr_);
  372. ASSERT_TRUE_WAIT(received() == 100, 5000);
  373. Deallocate();
  374. turn_ctx_->state = NR_TURN_CLIENT_STATE_ALLOCATED;
  375. /* Either the connection got closed by the TURN server already, then the send
  376. * is going to fail, which we simply ignore. Or the connection is still alive
  377. * and we cand send the data, but it should not get forwarded to us. In either
  378. * case we should not receive more data. */
  379. SendTo(relay_addr_, -1);
  380. PR_Sleep(1000);
  381. ASSERT_TRUE(received() == 100);
  382. }
  383. TEST_F(TurnClient, AllocateDummyServer) {
  384. if (WarnIfTurnNotConfigured())
  385. return;
  386. turn_server_ = kDummyTurnServer;
  387. Allocate(false);
  388. }