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.

756 lines
26 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * libjingle
  3. * Copyright 2004--2005, Google Inc.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice,
  9. * this list of conditions and the following disclaimer.
  10. * 2. Redistributions in binary form must reproduce the above copyright notice,
  11. * this list of conditions and the following disclaimer in the documentation
  12. * and/or other materials provided with the distribution.
  13. * 3. The name of the author may not be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
  17. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  18. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  19. * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  20. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  21. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
  22. * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  23. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  24. * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  25. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #include "talk/p2p/base/relayserver.h"
  28. #ifdef POSIX
  29. #include <errno.h>
  30. #endif // POSIX
  31. #include <algorithm>
  32. #include "talk/base/asynctcpsocket.h"
  33. #include "talk/base/helpers.h"
  34. #include "talk/base/logging.h"
  35. #include "talk/base/socketadapters.h"
  36. namespace cricket {
  37. // By default, we require a ping every 90 seconds.
  38. const int MAX_LIFETIME = 15 * 60 * 1000;
  39. // The number of bytes in each of the usernames we use.
  40. const uint32 USERNAME_LENGTH = 16;
  41. static const uint32 kMessageAcceptConnection = 1;
  42. // Calls SendTo on the given socket and logs any bad results.
  43. void Send(talk_base::AsyncPacketSocket* socket, const char* bytes, size_t size,
  44. const talk_base::SocketAddress& addr) {
  45. int result = socket->SendTo(bytes, size, addr);
  46. if (result < static_cast<int>(size)) {
  47. LOG(LS_ERROR) << "SendTo wrote only " << result << " of " << size
  48. << " bytes";
  49. } else if (result < 0) {
  50. LOG_ERR(LS_ERROR) << "SendTo";
  51. }
  52. }
  53. // Sends the given STUN message on the given socket.
  54. void SendStun(const StunMessage& msg,
  55. talk_base::AsyncPacketSocket* socket,
  56. const talk_base::SocketAddress& addr) {
  57. talk_base::ByteBuffer buf;
  58. msg.Write(&buf);
  59. Send(socket, buf.Data(), buf.Length(), addr);
  60. }
  61. // Constructs a STUN error response and sends it on the given socket.
  62. void SendStunError(const StunMessage& msg, talk_base::AsyncPacketSocket* socket,
  63. const talk_base::SocketAddress& remote_addr, int error_code,
  64. const char* error_desc, const std::string& magic_cookie) {
  65. RelayMessage err_msg;
  66. err_msg.SetType(GetStunErrorResponseType(msg.type()));
  67. err_msg.SetTransactionID(msg.transaction_id());
  68. StunByteStringAttribute* magic_cookie_attr =
  69. StunAttribute::CreateByteString(cricket::STUN_ATTR_MAGIC_COOKIE);
  70. if (magic_cookie.size() == 0) {
  71. magic_cookie_attr->CopyBytes(cricket::TURN_MAGIC_COOKIE_VALUE,
  72. sizeof(cricket::TURN_MAGIC_COOKIE_VALUE));
  73. } else {
  74. magic_cookie_attr->CopyBytes(magic_cookie.c_str(), magic_cookie.size());
  75. }
  76. err_msg.AddAttribute(magic_cookie_attr);
  77. StunErrorCodeAttribute* err_code = StunAttribute::CreateErrorCode();
  78. err_code->SetClass(error_code / 100);
  79. err_code->SetNumber(error_code % 100);
  80. err_code->SetReason(error_desc);
  81. err_msg.AddAttribute(err_code);
  82. SendStun(err_msg, socket, remote_addr);
  83. }
  84. RelayServer::RelayServer(talk_base::Thread* thread)
  85. : thread_(thread), log_bindings_(true) {
  86. }
  87. RelayServer::~RelayServer() {
  88. // Deleting the binding will cause it to be removed from the map.
  89. while (!bindings_.empty())
  90. delete bindings_.begin()->second;
  91. for (size_t i = 0; i < internal_sockets_.size(); ++i)
  92. delete internal_sockets_[i];
  93. for (size_t i = 0; i < external_sockets_.size(); ++i)
  94. delete external_sockets_[i];
  95. while (!server_sockets_.empty()) {
  96. talk_base::AsyncSocket* socket = server_sockets_.begin()->first;
  97. server_sockets_.erase(server_sockets_.begin()->first);
  98. delete socket;
  99. }
  100. }
  101. void RelayServer::AddInternalSocket(talk_base::AsyncPacketSocket* socket) {
  102. ASSERT(internal_sockets_.end() ==
  103. std::find(internal_sockets_.begin(), internal_sockets_.end(), socket));
  104. internal_sockets_.push_back(socket);
  105. socket->SignalReadPacket.connect(this, &RelayServer::OnInternalPacket);
  106. }
  107. void RelayServer::RemoveInternalSocket(talk_base::AsyncPacketSocket* socket) {
  108. SocketList::iterator iter =
  109. std::find(internal_sockets_.begin(), internal_sockets_.end(), socket);
  110. ASSERT(iter != internal_sockets_.end());
  111. internal_sockets_.erase(iter);
  112. socket->SignalReadPacket.disconnect(this);
  113. }
  114. void RelayServer::AddExternalSocket(talk_base::AsyncPacketSocket* socket) {
  115. ASSERT(external_sockets_.end() ==
  116. std::find(external_sockets_.begin(), external_sockets_.end(), socket));
  117. external_sockets_.push_back(socket);
  118. socket->SignalReadPacket.connect(this, &RelayServer::OnExternalPacket);
  119. }
  120. void RelayServer::RemoveExternalSocket(talk_base::AsyncPacketSocket* socket) {
  121. SocketList::iterator iter =
  122. std::find(external_sockets_.begin(), external_sockets_.end(), socket);
  123. ASSERT(iter != external_sockets_.end());
  124. external_sockets_.erase(iter);
  125. socket->SignalReadPacket.disconnect(this);
  126. }
  127. void RelayServer::AddInternalServerSocket(talk_base::AsyncSocket* socket,
  128. cricket::ProtocolType proto) {
  129. ASSERT(server_sockets_.end() ==
  130. server_sockets_.find(socket));
  131. server_sockets_[socket] = proto;
  132. socket->SignalReadEvent.connect(this, &RelayServer::OnReadEvent);
  133. }
  134. void RelayServer::RemoveInternalServerSocket(
  135. talk_base::AsyncSocket* socket) {
  136. ServerSocketMap::iterator iter = server_sockets_.find(socket);
  137. ASSERT(iter != server_sockets_.end());
  138. server_sockets_.erase(iter);
  139. socket->SignalReadEvent.disconnect(this);
  140. }
  141. int RelayServer::GetConnectionCount() const {
  142. return connections_.size();
  143. }
  144. talk_base::SocketAddressPair RelayServer::GetConnection(int connection) const {
  145. int i = 0;
  146. for (ConnectionMap::const_iterator it = connections_.begin();
  147. it != connections_.end(); ++it) {
  148. if (i == connection) {
  149. return it->second->addr_pair();
  150. }
  151. ++i;
  152. }
  153. return talk_base::SocketAddressPair();
  154. }
  155. bool RelayServer::HasConnection(const talk_base::SocketAddress& address) const {
  156. for (ConnectionMap::const_iterator it = connections_.begin();
  157. it != connections_.end(); ++it) {
  158. if (it->second->addr_pair().destination() == address) {
  159. return true;
  160. }
  161. }
  162. return false;
  163. }
  164. void RelayServer::OnReadEvent(talk_base::AsyncSocket* socket) {
  165. ASSERT(server_sockets_.find(socket) != server_sockets_.end());
  166. AcceptConnection(socket);
  167. }
  168. void RelayServer::OnInternalPacket(
  169. talk_base::AsyncPacketSocket* socket, const char* bytes, size_t size,
  170. const talk_base::SocketAddress& remote_addr) {
  171. // Get the address of the connection we just received on.
  172. talk_base::SocketAddressPair ap(remote_addr, socket->GetLocalAddress());
  173. ASSERT(!ap.destination().IsNil());
  174. // If this did not come from an existing connection, it should be a STUN
  175. // allocate request.
  176. ConnectionMap::iterator piter = connections_.find(ap);
  177. if (piter == connections_.end()) {
  178. HandleStunAllocate(bytes, size, ap, socket);
  179. return;
  180. }
  181. RelayServerConnection* int_conn = piter->second;
  182. // Handle STUN requests to the server itself.
  183. if (int_conn->binding()->HasMagicCookie(bytes, size)) {
  184. HandleStun(int_conn, bytes, size);
  185. return;
  186. }
  187. // Otherwise, this is a non-wrapped packet that we are to forward. Make sure
  188. // that this connection has been locked. (Otherwise, we would not know what
  189. // address to forward to.)
  190. if (!int_conn->locked()) {
  191. LOG(LS_WARNING) << "Dropping packet: connection not locked";
  192. return;
  193. }
  194. // Forward this to the destination address into the connection.
  195. RelayServerConnection* ext_conn = int_conn->binding()->GetExternalConnection(
  196. int_conn->default_destination());
  197. if (ext_conn && ext_conn->locked()) {
  198. // TODO: Check the HMAC.
  199. ext_conn->Send(bytes, size);
  200. } else {
  201. // This happens very often and is not an error.
  202. LOG(LS_INFO) << "Dropping packet: no external connection";
  203. }
  204. }
  205. void RelayServer::OnExternalPacket(
  206. talk_base::AsyncPacketSocket* socket, const char* bytes, size_t size,
  207. const talk_base::SocketAddress& remote_addr) {
  208. // Get the address of the connection we just received on.
  209. talk_base::SocketAddressPair ap(remote_addr, socket->GetLocalAddress());
  210. ASSERT(!ap.destination().IsNil());
  211. // If this connection already exists, then forward the traffic.
  212. ConnectionMap::iterator piter = connections_.find(ap);
  213. if (piter != connections_.end()) {
  214. // TODO: Check the HMAC.
  215. RelayServerConnection* ext_conn = piter->second;
  216. RelayServerConnection* int_conn =
  217. ext_conn->binding()->GetInternalConnection(
  218. ext_conn->addr_pair().source());
  219. ASSERT(int_conn != NULL);
  220. int_conn->Send(bytes, size, ext_conn->addr_pair().source());
  221. ext_conn->Lock(); // allow outgoing packets
  222. return;
  223. }
  224. // The first packet should always be a STUN / TURN packet. If it isn't, then
  225. // we should just ignore this packet.
  226. RelayMessage msg;
  227. talk_base::ByteBuffer buf(bytes, size);
  228. if (!msg.Read(&buf)) {
  229. LOG(LS_WARNING) << "Dropping packet: first packet not STUN";
  230. return;
  231. }
  232. // The initial packet should have a username (which identifies the binding).
  233. const StunByteStringAttribute* username_attr =
  234. msg.GetByteString(STUN_ATTR_USERNAME);
  235. if (!username_attr) {
  236. LOG(LS_WARNING) << "Dropping packet: no username";
  237. return;
  238. }
  239. uint32 length = talk_base::_min(static_cast<uint32>(username_attr->length()),
  240. USERNAME_LENGTH);
  241. std::string username(username_attr->bytes(), length);
  242. // TODO: Check the HMAC.
  243. // The binding should already be present.
  244. BindingMap::iterator biter = bindings_.find(username);
  245. if (biter == bindings_.end()) {
  246. LOG(LS_WARNING) << "Dropping packet: no binding with username";
  247. return;
  248. }
  249. // Add this authenticted connection to the binding.
  250. RelayServerConnection* ext_conn =
  251. new RelayServerConnection(biter->second, ap, socket);
  252. ext_conn->binding()->AddExternalConnection(ext_conn);
  253. AddConnection(ext_conn);
  254. // We always know where external packets should be forwarded, so we can lock
  255. // them from the beginning.
  256. ext_conn->Lock();
  257. // Send this message on the appropriate internal connection.
  258. RelayServerConnection* int_conn = ext_conn->binding()->GetInternalConnection(
  259. ext_conn->addr_pair().source());
  260. ASSERT(int_conn != NULL);
  261. int_conn->Send(bytes, size, ext_conn->addr_pair().source());
  262. }
  263. bool RelayServer::HandleStun(
  264. const char* bytes, size_t size, const talk_base::SocketAddress& remote_addr,
  265. talk_base::AsyncPacketSocket* socket, std::string* username,
  266. StunMessage* msg) {
  267. // Parse this into a stun message. Eat the message if this fails.
  268. talk_base::ByteBuffer buf(bytes, size);
  269. if (!msg->Read(&buf)) {
  270. return false;
  271. }
  272. // The initial packet should have a username (which identifies the binding).
  273. const StunByteStringAttribute* username_attr =
  274. msg->GetByteString(STUN_ATTR_USERNAME);
  275. if (!username_attr) {
  276. SendStunError(*msg, socket, remote_addr, 432, "Missing Username", "");
  277. return false;
  278. }
  279. // Record the username if requested.
  280. if (username)
  281. username->append(username_attr->bytes(), username_attr->length());
  282. // TODO: Check for unknown attributes (<= 0x7fff)
  283. return true;
  284. }
  285. void RelayServer::HandleStunAllocate(
  286. const char* bytes, size_t size, const talk_base::SocketAddressPair& ap,
  287. talk_base::AsyncPacketSocket* socket) {
  288. // Make sure this is a valid STUN request.
  289. RelayMessage request;
  290. std::string username;
  291. if (!HandleStun(bytes, size, ap.source(), socket, &username, &request))
  292. return;
  293. // Make sure this is a an allocate request.
  294. if (request.type() != STUN_ALLOCATE_REQUEST) {
  295. SendStunError(request,
  296. socket,
  297. ap.source(),
  298. 600,
  299. "Operation Not Supported",
  300. "");
  301. return;
  302. }
  303. // TODO: Check the HMAC.
  304. // Find or create the binding for this username.
  305. RelayServerBinding* binding;
  306. BindingMap::iterator biter = bindings_.find(username);
  307. if (biter != bindings_.end()) {
  308. binding = biter->second;
  309. } else {
  310. // NOTE: In the future, bindings will be created by the bot only. This
  311. // else-branch will then disappear.
  312. // Compute the appropriate lifetime for this binding.
  313. uint32 lifetime = MAX_LIFETIME;
  314. const StunUInt32Attribute* lifetime_attr =
  315. request.GetUInt32(STUN_ATTR_LIFETIME);
  316. if (lifetime_attr)
  317. lifetime = talk_base::_min(lifetime, lifetime_attr->value() * 1000);
  318. binding = new RelayServerBinding(this, username, "0", lifetime);
  319. binding->SignalTimeout.connect(this, &RelayServer::OnTimeout);
  320. bindings_[username] = binding;
  321. if (log_bindings_) {
  322. LOG(LS_INFO) << "Added new binding " << username << ", "
  323. << bindings_.size() << " total";
  324. }
  325. }
  326. // Add this connection to the binding. It starts out unlocked.
  327. RelayServerConnection* int_conn =
  328. new RelayServerConnection(binding, ap, socket);
  329. binding->AddInternalConnection(int_conn);
  330. AddConnection(int_conn);
  331. // Now that we have a connection, this other method takes over.
  332. HandleStunAllocate(int_conn, request);
  333. }
  334. void RelayServer::HandleStun(
  335. RelayServerConnection* int_conn, const char* bytes, size_t size) {
  336. // Make sure this is a valid STUN request.
  337. RelayMessage request;
  338. std::string username;
  339. if (!HandleStun(bytes, size, int_conn->addr_pair().source(),
  340. int_conn->socket(), &username, &request))
  341. return;
  342. // Make sure the username is the one were were expecting.
  343. if (username != int_conn->binding()->username()) {
  344. int_conn->SendStunError(request, 430, "Stale Credentials");
  345. return;
  346. }
  347. // TODO: Check the HMAC.
  348. // Send this request to the appropriate handler.
  349. if (request.type() == STUN_SEND_REQUEST)
  350. HandleStunSend(int_conn, request);
  351. else if (request.type() == STUN_ALLOCATE_REQUEST)
  352. HandleStunAllocate(int_conn, request);
  353. else
  354. int_conn->SendStunError(request, 600, "Operation Not Supported");
  355. }
  356. void RelayServer::HandleStunAllocate(
  357. RelayServerConnection* int_conn, const StunMessage& request) {
  358. // Create a response message that includes an address with which external
  359. // clients can communicate.
  360. RelayMessage response;
  361. response.SetType(STUN_ALLOCATE_RESPONSE);
  362. response.SetTransactionID(request.transaction_id());
  363. StunByteStringAttribute* magic_cookie_attr =
  364. StunAttribute::CreateByteString(cricket::STUN_ATTR_MAGIC_COOKIE);
  365. magic_cookie_attr->CopyBytes(int_conn->binding()->magic_cookie().c_str(),
  366. int_conn->binding()->magic_cookie().size());
  367. response.AddAttribute(magic_cookie_attr);
  368. size_t index = rand() % external_sockets_.size();
  369. talk_base::SocketAddress ext_addr =
  370. external_sockets_[index]->GetLocalAddress();
  371. StunAddressAttribute* addr_attr =
  372. StunAttribute::CreateAddress(STUN_ATTR_MAPPED_ADDRESS);
  373. addr_attr->SetIP(ext_addr.ipaddr());
  374. addr_attr->SetPort(ext_addr.port());
  375. response.AddAttribute(addr_attr);
  376. StunUInt32Attribute* res_lifetime_attr =
  377. StunAttribute::CreateUInt32(STUN_ATTR_LIFETIME);
  378. res_lifetime_attr->SetValue(int_conn->binding()->lifetime() / 1000);
  379. response.AddAttribute(res_lifetime_attr);
  380. // TODO: Support transport-prefs (preallocate RTCP port).
  381. // TODO: Support bandwidth restrictions.
  382. // TODO: Add message integrity check.
  383. // Send a response to the caller.
  384. int_conn->SendStun(response);
  385. }
  386. void RelayServer::HandleStunSend(
  387. RelayServerConnection* int_conn, const StunMessage& request) {
  388. const StunAddressAttribute* addr_attr =
  389. request.GetAddress(STUN_ATTR_DESTINATION_ADDRESS);
  390. if (!addr_attr) {
  391. int_conn->SendStunError(request, 400, "Bad Request");
  392. return;
  393. }
  394. const StunByteStringAttribute* data_attr =
  395. request.GetByteString(STUN_ATTR_DATA);
  396. if (!data_attr) {
  397. int_conn->SendStunError(request, 400, "Bad Request");
  398. return;
  399. }
  400. talk_base::SocketAddress ext_addr(addr_attr->ipaddr(), addr_attr->port());
  401. RelayServerConnection* ext_conn =
  402. int_conn->binding()->GetExternalConnection(ext_addr);
  403. if (!ext_conn) {
  404. // Create a new connection to establish the relationship with this binding.
  405. ASSERT(external_sockets_.size() == 1);
  406. talk_base::AsyncPacketSocket* socket = external_sockets_[0];
  407. talk_base::SocketAddressPair ap(ext_addr, socket->GetLocalAddress());
  408. ext_conn = new RelayServerConnection(int_conn->binding(), ap, socket);
  409. ext_conn->binding()->AddExternalConnection(ext_conn);
  410. AddConnection(ext_conn);
  411. }
  412. // If this connection has pinged us, then allow outgoing traffic.
  413. if (ext_conn->locked())
  414. ext_conn->Send(data_attr->bytes(), data_attr->length());
  415. const StunUInt32Attribute* options_attr =
  416. request.GetUInt32(STUN_ATTR_OPTIONS);
  417. if (options_attr && (options_attr->value() & 0x01)) {
  418. int_conn->set_default_destination(ext_addr);
  419. int_conn->Lock();
  420. RelayMessage response;
  421. response.SetType(STUN_SEND_RESPONSE);
  422. response.SetTransactionID(request.transaction_id());
  423. StunByteStringAttribute* magic_cookie_attr =
  424. StunAttribute::CreateByteString(cricket::STUN_ATTR_MAGIC_COOKIE);
  425. magic_cookie_attr->CopyBytes(int_conn->binding()->magic_cookie().c_str(),
  426. int_conn->binding()->magic_cookie().size());
  427. response.AddAttribute(magic_cookie_attr);
  428. StunUInt32Attribute* options2_attr =
  429. StunAttribute::CreateUInt32(cricket::STUN_ATTR_OPTIONS);
  430. options2_attr->SetValue(0x01);
  431. response.AddAttribute(options2_attr);
  432. int_conn->SendStun(response);
  433. }
  434. }
  435. void RelayServer::AddConnection(RelayServerConnection* conn) {
  436. ASSERT(connections_.find(conn->addr_pair()) == connections_.end());
  437. connections_[conn->addr_pair()] = conn;
  438. }
  439. void RelayServer::RemoveConnection(RelayServerConnection* conn) {
  440. ConnectionMap::iterator iter = connections_.find(conn->addr_pair());
  441. ASSERT(iter != connections_.end());
  442. connections_.erase(iter);
  443. }
  444. void RelayServer::RemoveBinding(RelayServerBinding* binding) {
  445. BindingMap::iterator iter = bindings_.find(binding->username());
  446. ASSERT(iter != bindings_.end());
  447. bindings_.erase(iter);
  448. if (log_bindings_) {
  449. LOG(LS_INFO) << "Removed binding " << binding->username() << ", "
  450. << bindings_.size() << " remaining";
  451. }
  452. }
  453. void RelayServer::OnMessage(talk_base::Message *pmsg) {
  454. ASSERT(pmsg->message_id == kMessageAcceptConnection);
  455. talk_base::MessageData* data = pmsg->pdata;
  456. talk_base::AsyncSocket* socket =
  457. static_cast <talk_base::TypedMessageData<talk_base::AsyncSocket*>*>
  458. (data)->data();
  459. AcceptConnection(socket);
  460. delete data;
  461. }
  462. void RelayServer::OnTimeout(RelayServerBinding* binding) {
  463. // This call will result in all of the necessary clean-up. We can't call
  464. // delete here, because you can't delete an object that is signaling you.
  465. thread_->Dispose(binding);
  466. }
  467. void RelayServer::AcceptConnection(talk_base::AsyncSocket* server_socket) {
  468. // Check if someone is trying to connect to us.
  469. talk_base::SocketAddress accept_addr;
  470. talk_base::AsyncSocket* accepted_socket =
  471. server_socket->Accept(&accept_addr);
  472. if (accepted_socket != NULL) {
  473. // We had someone trying to connect, now check which protocol to
  474. // use and create a packet socket.
  475. ASSERT(server_sockets_[server_socket] == cricket::PROTO_TCP ||
  476. server_sockets_[server_socket] == cricket::PROTO_SSLTCP);
  477. if (server_sockets_[server_socket] == cricket::PROTO_SSLTCP) {
  478. accepted_socket = new talk_base::AsyncSSLServerSocket(accepted_socket);
  479. }
  480. talk_base::AsyncTCPSocket* tcp_socket =
  481. new talk_base::AsyncTCPSocket(accepted_socket, false);
  482. // Finally add the socket so it can start communicating with the client.
  483. AddInternalSocket(tcp_socket);
  484. }
  485. }
  486. RelayServerConnection::RelayServerConnection(
  487. RelayServerBinding* binding, const talk_base::SocketAddressPair& addrs,
  488. talk_base::AsyncPacketSocket* socket)
  489. : binding_(binding), addr_pair_(addrs), socket_(socket), locked_(false) {
  490. // The creation of a new connection constitutes a use of the binding.
  491. binding_->NoteUsed();
  492. }
  493. RelayServerConnection::~RelayServerConnection() {
  494. // Remove this connection from the server's map (if it exists there).
  495. binding_->server()->RemoveConnection(this);
  496. }
  497. void RelayServerConnection::Send(const char* data, size_t size) {
  498. // Note that the binding has been used again.
  499. binding_->NoteUsed();
  500. cricket::Send(socket_, data, size, addr_pair_.source());
  501. }
  502. void RelayServerConnection::Send(
  503. const char* data, size_t size, const talk_base::SocketAddress& from_addr) {
  504. // If the from address is known to the client, we don't need to send it.
  505. if (locked() && (from_addr == default_dest_)) {
  506. Send(data, size);
  507. return;
  508. }
  509. // Wrap the given data in a data-indication packet.
  510. RelayMessage msg;
  511. msg.SetType(STUN_DATA_INDICATION);
  512. StunByteStringAttribute* magic_cookie_attr =
  513. StunAttribute::CreateByteString(cricket::STUN_ATTR_MAGIC_COOKIE);
  514. magic_cookie_attr->CopyBytes(binding_->magic_cookie().c_str(),
  515. binding_->magic_cookie().size());
  516. msg.AddAttribute(magic_cookie_attr);
  517. StunAddressAttribute* addr_attr =
  518. StunAttribute::CreateAddress(STUN_ATTR_SOURCE_ADDRESS2);
  519. addr_attr->SetIP(from_addr.ipaddr());
  520. addr_attr->SetPort(from_addr.port());
  521. msg.AddAttribute(addr_attr);
  522. StunByteStringAttribute* data_attr =
  523. StunAttribute::CreateByteString(STUN_ATTR_DATA);
  524. ASSERT(size <= 65536);
  525. data_attr->CopyBytes(data, uint16(size));
  526. msg.AddAttribute(data_attr);
  527. SendStun(msg);
  528. }
  529. void RelayServerConnection::SendStun(const StunMessage& msg) {
  530. // Note that the binding has been used again.
  531. binding_->NoteUsed();
  532. cricket::SendStun(msg, socket_, addr_pair_.source());
  533. }
  534. void RelayServerConnection::SendStunError(
  535. const StunMessage& request, int error_code, const char* error_desc) {
  536. // An error does not indicate use. If no legitimate use off the binding
  537. // occurs, we want it to be cleaned up even if errors are still occuring.
  538. cricket::SendStunError(
  539. request, socket_, addr_pair_.source(), error_code, error_desc,
  540. binding_->magic_cookie());
  541. }
  542. void RelayServerConnection::Lock() {
  543. locked_ = true;
  544. }
  545. void RelayServerConnection::Unlock() {
  546. locked_ = false;
  547. }
  548. // IDs used for posted messages:
  549. const uint32 MSG_LIFETIME_TIMER = 1;
  550. RelayServerBinding::RelayServerBinding(
  551. RelayServer* server, const std::string& username,
  552. const std::string& password, uint32 lifetime)
  553. : server_(server), username_(username), password_(password),
  554. lifetime_(lifetime) {
  555. // For now, every connection uses the standard magic cookie value.
  556. magic_cookie_.append(
  557. reinterpret_cast<const char*>(TURN_MAGIC_COOKIE_VALUE),
  558. sizeof(TURN_MAGIC_COOKIE_VALUE));
  559. // Initialize the last-used time to now.
  560. NoteUsed();
  561. // Set the first timeout check.
  562. server_->thread()->PostDelayed(lifetime_, this, MSG_LIFETIME_TIMER);
  563. }
  564. RelayServerBinding::~RelayServerBinding() {
  565. // Clear the outstanding timeout check.
  566. server_->thread()->Clear(this);
  567. // Clean up all of the connections.
  568. for (size_t i = 0; i < internal_connections_.size(); ++i)
  569. delete internal_connections_[i];
  570. for (size_t i = 0; i < external_connections_.size(); ++i)
  571. delete external_connections_[i];
  572. // Remove this binding from the server's map.
  573. server_->RemoveBinding(this);
  574. }
  575. void RelayServerBinding::AddInternalConnection(RelayServerConnection* conn) {
  576. internal_connections_.push_back(conn);
  577. }
  578. void RelayServerBinding::AddExternalConnection(RelayServerConnection* conn) {
  579. external_connections_.push_back(conn);
  580. }
  581. void RelayServerBinding::NoteUsed() {
  582. last_used_ = talk_base::Time();
  583. }
  584. bool RelayServerBinding::HasMagicCookie(const char* bytes, size_t size) const {
  585. if (size < 24 + magic_cookie_.size()) {
  586. return false;
  587. } else {
  588. return 0 == std::memcmp(
  589. bytes + 24, magic_cookie_.c_str(), magic_cookie_.size());
  590. }
  591. }
  592. RelayServerConnection* RelayServerBinding::GetInternalConnection(
  593. const talk_base::SocketAddress& ext_addr) {
  594. // Look for an internal connection that is locked to this address.
  595. for (size_t i = 0; i < internal_connections_.size(); ++i) {
  596. if (internal_connections_[i]->locked() &&
  597. (ext_addr == internal_connections_[i]->default_destination()))
  598. return internal_connections_[i];
  599. }
  600. // If one was not found, we send to the first connection.
  601. ASSERT(internal_connections_.size() > 0);
  602. return internal_connections_[0];
  603. }
  604. RelayServerConnection* RelayServerBinding::GetExternalConnection(
  605. const talk_base::SocketAddress& ext_addr) {
  606. for (size_t i = 0; i < external_connections_.size(); ++i) {
  607. if (ext_addr == external_connections_[i]->addr_pair().source())
  608. return external_connections_[i];
  609. }
  610. return 0;
  611. }
  612. void RelayServerBinding::OnMessage(talk_base::Message *pmsg) {
  613. if (pmsg->message_id == MSG_LIFETIME_TIMER) {
  614. ASSERT(!pmsg->pdata);
  615. // If the lifetime timeout has been exceeded, then send a signal.
  616. // Otherwise, just keep waiting.
  617. if (talk_base::Time() >= last_used_ + lifetime_) {
  618. LOG(LS_INFO) << "Expiring binding " << username_;
  619. SignalTimeout(this);
  620. } else {
  621. server_->thread()->PostDelayed(lifetime_, this, MSG_LIFETIME_TIMER);
  622. }
  623. } else {
  624. ASSERT(false);
  625. }
  626. }
  627. } // namespace cricket