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.

913 lines
31 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * libjingle
  3. * Copyright 2012, 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/turnserver.h"
  28. #include "talk/base/asyncpacketsocket.h"
  29. #include "talk/base/bytebuffer.h"
  30. #include "talk/base/helpers.h"
  31. #include "talk/base/logging.h"
  32. #include "talk/base/messagedigest.h"
  33. #include "talk/base/packetsocketfactory.h"
  34. #include "talk/base/stringencode.h"
  35. #include "talk/base/thread.h"
  36. #include "talk/p2p/base/common.h"
  37. #include "talk/p2p/base/stun.h"
  38. namespace cricket {
  39. // TODO(juberti): Move this all to a future turnmessage.h
  40. //static const int IPPROTO_UDP = 17;
  41. static const int kNonceTimeout = 60 * 60 * 1000; // 60 minutes
  42. static const int kDefaultAllocationTimeout = 10 * 60 * 1000; // 10 minutes
  43. static const int kPermissionTimeout = 5 * 60 * 1000; // 5 minutes
  44. static const int kChannelTimeout = 10 * 60 * 1000; // 10 minutes
  45. static const int kMinChannelNumber = 0x4000;
  46. static const int kMaxChannelNumber = 0x7FFF;
  47. static const size_t kNonceKeySize = 16;
  48. static const size_t kNonceSize = 40;
  49. static const size_t TURN_CHANNEL_HEADER_SIZE = 4U;
  50. inline bool IsTurnChannelData(uint16 msg_type) {
  51. // The first two bits of a channel data message are 0b01.
  52. return ((msg_type & 0xC000) == 0x4000);
  53. }
  54. // IDs used for posted messages.
  55. enum {
  56. MSG_TIMEOUT,
  57. };
  58. // Encapsulates a TURN allocation.
  59. // The object is created when an allocation request is received, and then
  60. // handles TURN messages (via HandleTurnMessage) and channel data messages
  61. // (via HandleChannelData) for this allocation when received by the server.
  62. // The object self-deletes and informs the server if its lifetime timer expires.
  63. class TurnServer::Allocation : public talk_base::MessageHandler,
  64. public sigslot::has_slots<> {
  65. public:
  66. Allocation(TurnServer* server_,
  67. talk_base::Thread* thread, const Connection& conn,
  68. talk_base::AsyncPacketSocket* server_socket,
  69. const std::string& key);
  70. virtual ~Allocation();
  71. const Connection& conn() const { return conn_; }
  72. const std::string& key() const { return key_; }
  73. const std::string& transaction_id() const { return transaction_id_; }
  74. const std::string& username() const { return username_; }
  75. std::string ToString() const;
  76. void HandleTurnMessage(const TurnMessage* msg);
  77. void HandleChannelData(const char* data, size_t size);
  78. sigslot::signal1<Allocation*> SignalDestroyed;
  79. private:
  80. typedef std::list<Permission*> PermissionList;
  81. typedef std::list<Channel*> ChannelList;
  82. void HandleAllocateRequest(const TurnMessage* msg);
  83. void HandleRefreshRequest(const TurnMessage* msg);
  84. void HandleSendIndication(const TurnMessage* msg);
  85. void HandleCreatePermissionRequest(const TurnMessage* msg);
  86. void HandleChannelBindRequest(const TurnMessage* msg);
  87. void OnExternalPacket(talk_base::AsyncPacketSocket* socket,
  88. const char* data, size_t size,
  89. const talk_base::SocketAddress& addr);
  90. static int ComputeLifetime(const TurnMessage* msg);
  91. bool HasPermission(const talk_base::IPAddress& addr);
  92. void AddPermission(const talk_base::IPAddress& addr);
  93. Permission* FindPermission(const talk_base::IPAddress& addr) const;
  94. Channel* FindChannel(int channel_id) const;
  95. Channel* FindChannel(const talk_base::SocketAddress& addr) const;
  96. void SendResponse(TurnMessage* msg);
  97. void SendBadRequestResponse(const TurnMessage* req);
  98. void SendErrorResponse(const TurnMessage* req, int code,
  99. const std::string& reason);
  100. void SendExternal(const void* data, size_t size,
  101. const talk_base::SocketAddress& peer);
  102. void OnPermissionDestroyed(Permission* perm);
  103. void OnChannelDestroyed(Channel* channel);
  104. virtual void OnMessage(talk_base::Message* msg);
  105. TurnServer* server_;
  106. talk_base::Thread* thread_;
  107. Connection conn_;
  108. talk_base::scoped_ptr<talk_base::AsyncPacketSocket> external_socket_;
  109. std::string key_;
  110. std::string transaction_id_;
  111. std::string username_;
  112. PermissionList perms_;
  113. ChannelList channels_;
  114. };
  115. // Encapsulates a TURN permission.
  116. // The object is created when a create permission request is received by an
  117. // allocation, and self-deletes when its lifetime timer expires.
  118. class TurnServer::Permission : public talk_base::MessageHandler {
  119. public:
  120. Permission(talk_base::Thread* thread, const talk_base::IPAddress& peer);
  121. ~Permission();
  122. const talk_base::IPAddress& peer() const { return peer_; }
  123. void Refresh();
  124. sigslot::signal1<Permission*> SignalDestroyed;
  125. private:
  126. virtual void OnMessage(talk_base::Message* msg);
  127. talk_base::Thread* thread_;
  128. talk_base::IPAddress peer_;
  129. };
  130. // Encapsulates a TURN channel binding.
  131. // The object is created when a channel bind request is received by an
  132. // allocation, and self-deletes when its lifetime timer expires.
  133. class TurnServer::Channel : public talk_base::MessageHandler {
  134. public:
  135. Channel(talk_base::Thread* thread, int id,
  136. const talk_base::SocketAddress& peer);
  137. ~Channel();
  138. int id() const { return id_; }
  139. const talk_base::SocketAddress& peer() const { return peer_; }
  140. void Refresh();
  141. sigslot::signal1<Channel*> SignalDestroyed;
  142. private:
  143. virtual void OnMessage(talk_base::Message* msg);
  144. talk_base::Thread* thread_;
  145. int id_;
  146. talk_base::SocketAddress peer_;
  147. };
  148. static bool InitResponse(const StunMessage* req, StunMessage* resp) {
  149. int resp_type = (req) ? GetStunSuccessResponseType(req->type()) : -1;
  150. if (resp_type == -1)
  151. return false;
  152. resp->SetType(resp_type);
  153. resp->SetTransactionID(req->transaction_id());
  154. return true;
  155. }
  156. static bool InitErrorResponse(const StunMessage* req, int code,
  157. const std::string& reason, StunMessage* resp) {
  158. int resp_type = (req) ? GetStunErrorResponseType(req->type()) : -1;
  159. if (resp_type == -1)
  160. return false;
  161. resp->SetType(resp_type);
  162. resp->SetTransactionID(req->transaction_id());
  163. VERIFY(resp->AddAttribute(new cricket::StunErrorCodeAttribute(
  164. STUN_ATTR_ERROR_CODE, code, reason)));
  165. return true;
  166. }
  167. TurnServer::TurnServer(talk_base::Thread* thread)
  168. : thread_(thread),
  169. nonce_key_(talk_base::CreateRandomString(kNonceKeySize)),
  170. auth_hook_(NULL) {
  171. }
  172. TurnServer::~TurnServer() {
  173. for (AllocationMap::iterator it = allocations_.begin();
  174. it != allocations_.end(); ++it) {
  175. delete it->second;
  176. }
  177. }
  178. void TurnServer::AddInternalServerSocket(talk_base::AsyncPacketSocket* socket) {
  179. ASSERT(server_socket_ == NULL);
  180. server_socket_.reset(socket);
  181. socket->SignalReadPacket.connect(this, &TurnServer::OnInternalPacket);
  182. }
  183. void TurnServer::SetExternalSocketFactory(
  184. talk_base::PacketSocketFactory* factory,
  185. const talk_base::SocketAddress& external_addr) {
  186. external_socket_factory_.reset(factory);
  187. external_addr_ = external_addr;
  188. }
  189. void TurnServer::OnInternalPacket(talk_base::AsyncPacketSocket* socket,
  190. const char* data, size_t size,
  191. const talk_base::SocketAddress& addr) {
  192. // Fail if the packet is too small to even contain a channel header.
  193. if (size < TURN_CHANNEL_HEADER_SIZE) {
  194. return;
  195. }
  196. Connection conn(addr, socket->GetLocalAddress(), TURNPROTO_UDP);
  197. uint16 msg_type = talk_base::GetBE16(data);
  198. if (!IsTurnChannelData(msg_type)) {
  199. // This is a STUN message.
  200. HandleStunMessage(conn, data, size);
  201. } else {
  202. // This is a channel message; let the allocation handle it.
  203. Allocation* allocation = FindAllocation(conn);
  204. if (allocation) {
  205. allocation->HandleChannelData(data, size);
  206. }
  207. }
  208. }
  209. void TurnServer::HandleStunMessage(const Connection& conn, const char* data,
  210. size_t size) {
  211. TurnMessage msg;
  212. talk_base::ByteBuffer buf(data, size);
  213. if (!msg.Read(&buf) || (buf.Length() > 0)) {
  214. LOG(LS_WARNING) << "Received invalid STUN message";
  215. return;
  216. }
  217. // If it's a STUN binding request, handle that specially.
  218. if (msg.type() == STUN_BINDING_REQUEST) {
  219. HandleBindingRequest(conn, &msg);
  220. return;
  221. }
  222. // Look up the key that we'll use to validate the M-I. If we have an
  223. // existing allocation, the key will already be cached.
  224. Allocation* allocation = FindAllocation(conn);
  225. std::string key;
  226. if (!allocation) {
  227. GetKey(&msg, &key);
  228. } else {
  229. key = allocation->key();
  230. }
  231. // Ensure the message is authorized; only needed for requests.
  232. if (IsStunRequestType(msg.type())) {
  233. if (!CheckAuthorization(conn, &msg, data, size, key)) {
  234. return;
  235. }
  236. }
  237. if (!allocation && msg.type() == STUN_ALLOCATE_REQUEST) {
  238. // This is a new allocate request.
  239. HandleAllocateRequest(conn, &msg, key);
  240. } else if (allocation &&
  241. (msg.type() != STUN_ALLOCATE_REQUEST ||
  242. msg.transaction_id() == allocation->transaction_id())) {
  243. // This is a non-allocate request, or a retransmit of an allocate.
  244. // Check that the username matches the previous username used.
  245. if (IsStunRequestType(msg.type()) &&
  246. msg.GetByteString(STUN_ATTR_USERNAME)->GetString() !=
  247. allocation->username()) {
  248. SendErrorResponse(conn, &msg, STUN_ERROR_WRONG_CREDENTIALS,
  249. STUN_ERROR_REASON_WRONG_CREDENTIALS);
  250. return;
  251. }
  252. allocation->HandleTurnMessage(&msg);
  253. } else {
  254. // Allocation mismatch.
  255. SendErrorResponse(conn, &msg, STUN_ERROR_ALLOCATION_MISMATCH,
  256. STUN_ERROR_REASON_ALLOCATION_MISMATCH);
  257. }
  258. }
  259. bool TurnServer::GetKey(const StunMessage* msg, std::string* key) {
  260. const StunByteStringAttribute* username_attr =
  261. msg->GetByteString(STUN_ATTR_USERNAME);
  262. if (!username_attr) {
  263. return false;
  264. }
  265. std::string username = username_attr->GetString();
  266. return (auth_hook_ != NULL && auth_hook_->GetKey(username, realm_, key));
  267. }
  268. bool TurnServer::CheckAuthorization(const Connection& conn,
  269. const StunMessage* msg,
  270. const char* data, size_t size,
  271. const std::string& key) {
  272. // RFC 5389, 10.2.2.
  273. ASSERT(IsStunRequestType(msg->type()));
  274. const StunByteStringAttribute* mi_attr =
  275. msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY);
  276. const StunByteStringAttribute* username_attr =
  277. msg->GetByteString(STUN_ATTR_USERNAME);
  278. const StunByteStringAttribute* realm_attr =
  279. msg->GetByteString(STUN_ATTR_REALM);
  280. const StunByteStringAttribute* nonce_attr =
  281. msg->GetByteString(STUN_ATTR_NONCE);
  282. // Fail if no M-I.
  283. if (!mi_attr) {
  284. SendErrorResponseWithRealmAndNonce(conn, msg, STUN_ERROR_UNAUTHORIZED,
  285. STUN_ERROR_REASON_UNAUTHORIZED);
  286. return false;
  287. }
  288. // Fail if there is M-I but no username, nonce, or realm.
  289. if (!username_attr || !realm_attr || !nonce_attr) {
  290. SendErrorResponse(conn, msg, STUN_ERROR_BAD_REQUEST,
  291. STUN_ERROR_REASON_BAD_REQUEST);
  292. return false;
  293. }
  294. // Fail if bad nonce.
  295. if (!ValidateNonce(nonce_attr->GetString())) {
  296. SendErrorResponseWithRealmAndNonce(conn, msg, STUN_ERROR_STALE_NONCE,
  297. STUN_ERROR_REASON_STALE_NONCE);
  298. return false;
  299. }
  300. // Fail if bad username or M-I.
  301. // We need |data| and |size| for the call to ValidateMessageIntegrity.
  302. if (key.empty() || !StunMessage::ValidateMessageIntegrity(data, size, key)) {
  303. SendErrorResponseWithRealmAndNonce(conn, msg, STUN_ERROR_UNAUTHORIZED,
  304. STUN_ERROR_REASON_UNAUTHORIZED);
  305. return false;
  306. }
  307. // Success.
  308. return true;
  309. }
  310. void TurnServer::HandleBindingRequest(const Connection& conn,
  311. const StunMessage* req) {
  312. StunMessage response;
  313. InitResponse(req, &response);
  314. // Tell the user the address that we received their request from.
  315. StunAddressAttribute* mapped_addr_attr;
  316. mapped_addr_attr = new StunXorAddressAttribute(
  317. STUN_ATTR_XOR_MAPPED_ADDRESS, conn.src());
  318. VERIFY(response.AddAttribute(mapped_addr_attr));
  319. SendStun(conn, &response);
  320. }
  321. void TurnServer::HandleAllocateRequest(const Connection& conn,
  322. const TurnMessage* msg,
  323. const std::string& key) {
  324. // Check the parameters in the request.
  325. const StunUInt32Attribute* transport_attr =
  326. msg->GetUInt32(STUN_ATTR_REQUESTED_TRANSPORT);
  327. if (!transport_attr) {
  328. SendErrorResponse(conn, msg, STUN_ERROR_BAD_REQUEST,
  329. STUN_ERROR_REASON_BAD_REQUEST);
  330. return;
  331. }
  332. // Only UDP is supported right now.
  333. int proto = transport_attr->value() >> 24;
  334. if (proto != IPPROTO_UDP) {
  335. SendErrorResponse(conn, msg, STUN_ERROR_UNSUPPORTED_PROTOCOL,
  336. STUN_ERROR_REASON_UNSUPPORTED_PROTOCOL);
  337. return;
  338. }
  339. // Create the allocation and let it send the success response.
  340. // If the actual socket allocation fails, send an internal error.
  341. Allocation* alloc = CreateAllocation(conn, proto, key);
  342. if (alloc) {
  343. alloc->HandleTurnMessage(msg);
  344. } else {
  345. SendErrorResponse(conn, msg, STUN_ERROR_SERVER_ERROR,
  346. "Failed to allocate socket");
  347. }
  348. }
  349. std::string TurnServer::GenerateNonce() const {
  350. // Generate a nonce of the form hex(now + HMAC-MD5(nonce_key_, now))
  351. uint32 now = talk_base::Time();
  352. std::string input(reinterpret_cast<const char*>(&now), sizeof(now));
  353. std::string nonce = talk_base::hex_encode(input.c_str(), input.size());
  354. nonce += talk_base::ComputeHmac(talk_base::DIGEST_MD5, nonce_key_, input);
  355. ASSERT(nonce.size() == kNonceSize);
  356. return nonce;
  357. }
  358. bool TurnServer::ValidateNonce(const std::string& nonce) const {
  359. // Check the size.
  360. if (nonce.size() != kNonceSize) {
  361. return false;
  362. }
  363. // Decode the timestamp.
  364. uint32 then;
  365. char* p = reinterpret_cast<char*>(&then);
  366. size_t len = talk_base::hex_decode(p, sizeof(then),
  367. nonce.substr(0, sizeof(then) * 2));
  368. if (len != sizeof(then)) {
  369. return false;
  370. }
  371. // Verify the HMAC.
  372. if (nonce.substr(sizeof(then) * 2) != talk_base::ComputeHmac(
  373. talk_base::DIGEST_MD5, nonce_key_, std::string(p, sizeof(then)))) {
  374. return false;
  375. }
  376. // Validate the timestamp.
  377. return talk_base::TimeSince(then) < kNonceTimeout;
  378. }
  379. TurnServer::Allocation* TurnServer::FindAllocation(const Connection& conn) {
  380. AllocationMap::const_iterator it = allocations_.find(conn);
  381. return (it != allocations_.end()) ? it->second : NULL;
  382. }
  383. TurnServer::Allocation* TurnServer::CreateAllocation(const Connection& conn,
  384. int proto,
  385. const std::string& key) {
  386. talk_base::AsyncPacketSocket* external_socket = (external_socket_factory_) ?
  387. external_socket_factory_->CreateUdpSocket(external_addr_, 0, 0) : NULL;
  388. if (!external_socket) {
  389. return NULL;
  390. }
  391. // The Allocation takes ownership of the socket.
  392. Allocation* allocation = new Allocation(this,
  393. thread_, conn, external_socket, key);
  394. allocation->SignalDestroyed.connect(this, &TurnServer::OnAllocationDestroyed);
  395. allocations_[conn] = allocation;
  396. return allocation;
  397. }
  398. void TurnServer::SendErrorResponse(const Connection& conn,
  399. const StunMessage* req,
  400. int code, const std::string& reason) {
  401. TurnMessage resp;
  402. InitErrorResponse(req, code, reason, &resp);
  403. LOG(LS_INFO) << "Sending error response, type=" << resp.type()
  404. << ", code=" << code << ", reason=" << reason;
  405. SendStun(conn, &resp);
  406. }
  407. void TurnServer::SendErrorResponseWithRealmAndNonce(const Connection& conn,
  408. const StunMessage* msg,
  409. int code,
  410. const std::string& reason) {
  411. TurnMessage resp;
  412. InitErrorResponse(msg, code, reason, &resp);
  413. VERIFY(resp.AddAttribute(new StunByteStringAttribute(
  414. STUN_ATTR_NONCE, GenerateNonce())));
  415. VERIFY(resp.AddAttribute(new StunByteStringAttribute(
  416. STUN_ATTR_REALM, realm_)));
  417. SendStun(conn, &resp);
  418. }
  419. void TurnServer::SendStun(const Connection& conn, StunMessage* msg) {
  420. talk_base::ByteBuffer buf;
  421. // Add a SOFTWARE attribute if one is set.
  422. if (!software_.empty()) {
  423. VERIFY(msg->AddAttribute(
  424. new StunByteStringAttribute(STUN_ATTR_SOFTWARE, software_)));
  425. }
  426. msg->Write(&buf);
  427. Send(conn, buf);
  428. }
  429. void TurnServer::Send(const Connection& conn,
  430. const talk_base::ByteBuffer& buf) {
  431. // TODO(juberti): Pick which socket to send on, once we have TCP support.
  432. server_socket_->SendTo(buf.Data(), buf.Length(), conn.src());
  433. }
  434. void TurnServer::OnAllocationDestroyed(Allocation* allocation) {
  435. AllocationMap::iterator it = allocations_.find(allocation->conn());
  436. if (it != allocations_.end())
  437. allocations_.erase(it);
  438. }
  439. TurnServer::Connection::Connection(const talk_base::SocketAddress& src,
  440. const talk_base::SocketAddress& dst,
  441. ProtocolType proto)
  442. : src_(src), dst_(dst), proto_(proto) {
  443. }
  444. bool TurnServer::Connection::operator==(const Connection& c) const {
  445. return src_ == c.src_ && dst_ == c.dst_ && proto_ == c.proto_;
  446. }
  447. bool TurnServer::Connection::operator<(const Connection& c) const {
  448. return src_ < c.src_ || dst_ < c.dst_ || proto_ < c.proto_;
  449. }
  450. std::string TurnServer::Connection::ToString() const {
  451. const char* const kProtos[] = {
  452. "unknown", "udp", "tcp", "ssltcp"
  453. };
  454. std::ostringstream ost;
  455. ost << src_.ToString() << "-" << dst_.ToString() << ":"<< kProtos[proto_];
  456. return ost.str();
  457. }
  458. TurnServer::Allocation::Allocation(TurnServer* server,
  459. talk_base::Thread* thread,
  460. const Connection& conn,
  461. talk_base::AsyncPacketSocket* socket,
  462. const std::string& key)
  463. : server_(server),
  464. thread_(thread),
  465. conn_(conn),
  466. external_socket_(socket),
  467. key_(key) {
  468. external_socket_->SignalReadPacket.connect(
  469. this, &TurnServer::Allocation::OnExternalPacket);
  470. }
  471. TurnServer::Allocation::~Allocation() {
  472. for (ChannelList::iterator it = channels_.begin();
  473. it != channels_.end(); ++it) {
  474. delete *it;
  475. }
  476. for (PermissionList::iterator it = perms_.begin();
  477. it != perms_.end(); ++it) {
  478. delete *it;
  479. }
  480. thread_->Clear(this, MSG_TIMEOUT);
  481. LOG_J(LS_INFO, this) << "Allocation destroyed";
  482. }
  483. std::string TurnServer::Allocation::ToString() const {
  484. std::ostringstream ost;
  485. ost << "Alloc[" << conn_.ToString() << "]";
  486. return ost.str();
  487. }
  488. void TurnServer::Allocation::HandleTurnMessage(const TurnMessage* msg) {
  489. ASSERT(msg != NULL);
  490. switch (msg->type()) {
  491. case STUN_ALLOCATE_REQUEST:
  492. HandleAllocateRequest(msg);
  493. break;
  494. case TURN_REFRESH_REQUEST:
  495. HandleRefreshRequest(msg);
  496. break;
  497. case TURN_SEND_INDICATION:
  498. HandleSendIndication(msg);
  499. break;
  500. case TURN_CREATE_PERMISSION_REQUEST:
  501. HandleCreatePermissionRequest(msg);
  502. break;
  503. case TURN_CHANNEL_BIND_REQUEST:
  504. HandleChannelBindRequest(msg);
  505. break;
  506. default:
  507. // Not sure what to do with this, just eat it.
  508. LOG_J(LS_WARNING, this) << "Invalid TURN message type received: "
  509. << msg->type();
  510. }
  511. }
  512. void TurnServer::Allocation::HandleAllocateRequest(const TurnMessage* msg) {
  513. // Copy the important info from the allocate request.
  514. transaction_id_ = msg->transaction_id();
  515. const StunByteStringAttribute* username_attr =
  516. msg->GetByteString(STUN_ATTR_USERNAME);
  517. ASSERT(username_attr != NULL);
  518. username_ = username_attr->GetString();
  519. // Figure out the lifetime and start the allocation timer.
  520. int lifetime_secs = ComputeLifetime(msg);
  521. thread_->PostDelayed(lifetime_secs * 1000, this, MSG_TIMEOUT);
  522. LOG_J(LS_INFO, this) << "Created allocation, lifetime=" << lifetime_secs;
  523. // We've already validated all the important bits; just send a response here.
  524. TurnMessage response;
  525. InitResponse(msg, &response);
  526. StunAddressAttribute* mapped_addr_attr =
  527. new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, conn_.src());
  528. StunAddressAttribute* relayed_addr_attr =
  529. new StunXorAddressAttribute(STUN_ATTR_XOR_RELAYED_ADDRESS,
  530. external_socket_->GetLocalAddress());
  531. StunUInt32Attribute* lifetime_attr =
  532. new StunUInt32Attribute(STUN_ATTR_LIFETIME, lifetime_secs);
  533. VERIFY(response.AddAttribute(mapped_addr_attr));
  534. VERIFY(response.AddAttribute(relayed_addr_attr));
  535. VERIFY(response.AddAttribute(lifetime_attr));
  536. SendResponse(&response);
  537. }
  538. void TurnServer::Allocation::HandleRefreshRequest(const TurnMessage* msg) {
  539. // Figure out the new lifetime.
  540. int lifetime_secs = ComputeLifetime(msg);
  541. // Reset the expiration timer.
  542. thread_->Clear(this, MSG_TIMEOUT);
  543. thread_->PostDelayed(lifetime_secs * 1000, this, MSG_TIMEOUT);
  544. LOG_J(LS_INFO, this) << "Refreshed allocation, lifetime=" << lifetime_secs;
  545. // Send a success response with a LIFETIME attribute.
  546. TurnMessage response;
  547. InitResponse(msg, &response);
  548. StunUInt32Attribute* lifetime_attr =
  549. new StunUInt32Attribute(STUN_ATTR_LIFETIME, lifetime_secs);
  550. VERIFY(response.AddAttribute(lifetime_attr));
  551. SendResponse(&response);
  552. }
  553. void TurnServer::Allocation::HandleSendIndication(const TurnMessage* msg) {
  554. // Check mandatory attributes.
  555. const StunByteStringAttribute* data_attr = msg->GetByteString(STUN_ATTR_DATA);
  556. const StunAddressAttribute* peer_attr =
  557. msg->GetAddress(STUN_ATTR_XOR_PEER_ADDRESS);
  558. if (!data_attr || !peer_attr) {
  559. LOG_J(LS_WARNING, this) << "Received invalid send indication";
  560. return;
  561. }
  562. // If a permission exists, send the data on to the peer.
  563. if (HasPermission(peer_attr->GetAddress().ipaddr())) {
  564. SendExternal(data_attr->bytes(), data_attr->length(),
  565. peer_attr->GetAddress());
  566. } else {
  567. LOG_J(LS_WARNING, this) << "Received send indication without permission"
  568. << "peer=" << peer_attr->GetAddress();
  569. }
  570. }
  571. void TurnServer::Allocation::HandleCreatePermissionRequest(
  572. const TurnMessage* msg) {
  573. // Check mandatory attributes.
  574. const StunAddressAttribute* peer_attr =
  575. msg->GetAddress(STUN_ATTR_XOR_PEER_ADDRESS);
  576. if (!peer_attr) {
  577. SendBadRequestResponse(msg);
  578. return;
  579. }
  580. // Add this permission.
  581. AddPermission(peer_attr->GetAddress().ipaddr());
  582. LOG_J(LS_INFO, this) << "Created permission, peer="
  583. << peer_attr->GetAddress();
  584. // Send a success response.
  585. TurnMessage response;
  586. InitResponse(msg, &response);
  587. SendResponse(&response);
  588. }
  589. void TurnServer::Allocation::HandleChannelBindRequest(const TurnMessage* msg) {
  590. // Check mandatory attributes.
  591. const StunUInt32Attribute* channel_attr =
  592. msg->GetUInt32(STUN_ATTR_CHANNEL_NUMBER);
  593. const StunAddressAttribute* peer_attr =
  594. msg->GetAddress(STUN_ATTR_XOR_PEER_ADDRESS);
  595. if (!channel_attr || !peer_attr) {
  596. SendBadRequestResponse(msg);
  597. return;
  598. }
  599. // Check that channel id is valid.
  600. int channel_id = channel_attr->value() >> 16;
  601. if (channel_id < kMinChannelNumber || channel_id > kMaxChannelNumber) {
  602. SendBadRequestResponse(msg);
  603. return;
  604. }
  605. // Check that this channel id isn't bound to another transport address, and
  606. // that this transport address isn't bound to another channel id.
  607. Channel* channel1 = FindChannel(channel_id);
  608. Channel* channel2 = FindChannel(peer_attr->GetAddress());
  609. if (channel1 != channel2) {
  610. SendBadRequestResponse(msg);
  611. return;
  612. }
  613. // Add or refresh this channel.
  614. if (!channel1) {
  615. channel1 = new Channel(thread_, channel_id, peer_attr->GetAddress());
  616. channel1->SignalDestroyed.connect(this,
  617. &TurnServer::Allocation::OnChannelDestroyed);
  618. channels_.push_back(channel1);
  619. } else {
  620. channel1->Refresh();
  621. }
  622. // Channel binds also refresh permissions.
  623. AddPermission(peer_attr->GetAddress().ipaddr());
  624. LOG_J(LS_INFO, this) << "Bound channel, id=" << channel_id
  625. << ", peer=" << peer_attr->GetAddress();
  626. // Send a success response.
  627. TurnMessage response;
  628. InitResponse(msg, &response);
  629. SendResponse(&response);
  630. }
  631. void TurnServer::Allocation::HandleChannelData(const char* data, size_t size) {
  632. // Extract the channel number from the data.
  633. uint16 channel_id = talk_base::GetBE16(data);
  634. Channel* channel = FindChannel(channel_id);
  635. if (channel) {
  636. // Send the data to the peer address.
  637. SendExternal(data + TURN_CHANNEL_HEADER_SIZE,
  638. size - TURN_CHANNEL_HEADER_SIZE, channel->peer());
  639. } else {
  640. LOG_J(LS_WARNING, this) << "Received channel data for invalid channel, id="
  641. << channel_id;
  642. }
  643. }
  644. void TurnServer::Allocation::OnExternalPacket(
  645. talk_base::AsyncPacketSocket* socket,
  646. const char* data, size_t size,
  647. const talk_base::SocketAddress& addr) {
  648. ASSERT(external_socket_.get() == socket);
  649. Channel* channel = FindChannel(addr);
  650. if (channel) {
  651. // There is a channel bound to this address. Send as a channel message.
  652. talk_base::ByteBuffer buf;
  653. buf.WriteUInt16(channel->id());
  654. buf.WriteUInt16(size);
  655. buf.WriteBytes(data, size);
  656. server_->Send(conn_, buf);
  657. } else if (HasPermission(addr.ipaddr())) {
  658. // No channel, but a permission exists. Send as a data indication.
  659. TurnMessage msg;
  660. msg.SetType(TURN_DATA_INDICATION);
  661. msg.SetTransactionID(
  662. talk_base::CreateRandomString(kStunTransactionIdLength));
  663. VERIFY(msg.AddAttribute(new StunXorAddressAttribute(
  664. STUN_ATTR_XOR_PEER_ADDRESS, addr)));
  665. VERIFY(msg.AddAttribute(new StunByteStringAttribute(
  666. STUN_ATTR_DATA, data, size)));
  667. server_->SendStun(conn_, &msg);
  668. } else {
  669. LOG_J(LS_WARNING, this) << "Received external packet without permission, "
  670. << "peer=" << addr;
  671. }
  672. }
  673. int TurnServer::Allocation::ComputeLifetime(const TurnMessage* msg) {
  674. // Return the smaller of our default lifetime and the requested lifetime.
  675. uint32 lifetime = kDefaultAllocationTimeout / 1000; // convert to seconds
  676. const StunUInt32Attribute* lifetime_attr = msg->GetUInt32(STUN_ATTR_LIFETIME);
  677. if (lifetime_attr && lifetime_attr->value() < lifetime) {
  678. lifetime = lifetime_attr->value();
  679. }
  680. return lifetime;
  681. }
  682. bool TurnServer::Allocation::HasPermission(const talk_base::IPAddress& addr) {
  683. return (FindPermission(addr) != NULL);
  684. }
  685. void TurnServer::Allocation::AddPermission(const talk_base::IPAddress& addr) {
  686. Permission* perm = FindPermission(addr);
  687. if (!perm) {
  688. perms_.push_back(new Permission(thread_, addr));
  689. } else {
  690. perm->Refresh();
  691. }
  692. }
  693. TurnServer::Permission* TurnServer::Allocation::FindPermission(
  694. const talk_base::IPAddress& addr) const {
  695. for (PermissionList::const_iterator it = perms_.begin();
  696. it != perms_.end(); ++it) {
  697. if ((*it)->peer() == addr)
  698. return *it;
  699. }
  700. return NULL;
  701. }
  702. TurnServer::Channel* TurnServer::Allocation::FindChannel(int channel_id) const {
  703. for (ChannelList::const_iterator it = channels_.begin();
  704. it != channels_.end(); ++it) {
  705. if ((*it)->id() == channel_id)
  706. return *it;
  707. }
  708. return NULL;
  709. }
  710. TurnServer::Channel* TurnServer::Allocation::FindChannel(
  711. const talk_base::SocketAddress& addr) const {
  712. for (ChannelList::const_iterator it = channels_.begin();
  713. it != channels_.end(); ++it) {
  714. if ((*it)->peer() == addr)
  715. return *it;
  716. }
  717. return NULL;
  718. }
  719. void TurnServer::Allocation::SendResponse(TurnMessage* msg) {
  720. // Success responses always have M-I.
  721. msg->AddMessageIntegrity(key_);
  722. server_->SendStun(conn_, msg);
  723. }
  724. void TurnServer::Allocation::SendBadRequestResponse(const TurnMessage* req) {
  725. SendErrorResponse(req, STUN_ERROR_BAD_REQUEST, STUN_ERROR_REASON_BAD_REQUEST);
  726. }
  727. void TurnServer::Allocation::SendErrorResponse(const TurnMessage* req, int code,
  728. const std::string& reason) {
  729. server_->SendErrorResponse(conn_, req, code, reason);
  730. }
  731. void TurnServer::Allocation::SendExternal(const void* data, size_t size,
  732. const talk_base::SocketAddress& peer) {
  733. external_socket_->SendTo(data, size, peer);
  734. }
  735. void TurnServer::Allocation::OnMessage(talk_base::Message* msg) {
  736. ASSERT(msg->message_id == MSG_TIMEOUT);
  737. SignalDestroyed(this);
  738. delete this;
  739. }
  740. void TurnServer::Allocation::OnPermissionDestroyed(Permission* perm) {
  741. PermissionList::iterator it = std::find(perms_.begin(), perms_.end(), perm);
  742. ASSERT(it != perms_.end());
  743. perms_.erase(it);
  744. }
  745. void TurnServer::Allocation::OnChannelDestroyed(Channel* channel) {
  746. ChannelList::iterator it =
  747. std::find(channels_.begin(), channels_.end(), channel);
  748. ASSERT(it != channels_.end());
  749. channels_.erase(it);
  750. }
  751. TurnServer::Permission::Permission(talk_base::Thread* thread,
  752. const talk_base::IPAddress& peer)
  753. : thread_(thread), peer_(peer) {
  754. Refresh();
  755. }
  756. TurnServer::Permission::~Permission() {
  757. thread_->Clear(this, MSG_TIMEOUT);
  758. }
  759. void TurnServer::Permission::Refresh() {
  760. thread_->Clear(this, MSG_TIMEOUT);
  761. thread_->PostDelayed(kPermissionTimeout, this, MSG_TIMEOUT);
  762. }
  763. void TurnServer::Permission::OnMessage(talk_base::Message* msg) {
  764. ASSERT(msg->message_id == MSG_TIMEOUT);
  765. SignalDestroyed(this);
  766. delete this;
  767. }
  768. TurnServer::Channel::Channel(talk_base::Thread* thread, int id,
  769. const talk_base::SocketAddress& peer)
  770. : thread_(thread), id_(id), peer_(peer) {
  771. Refresh();
  772. }
  773. TurnServer::Channel::~Channel() {
  774. thread_->Clear(this, MSG_TIMEOUT);
  775. }
  776. void TurnServer::Channel::Refresh() {
  777. thread_->Clear(this, MSG_TIMEOUT);
  778. thread_->PostDelayed(kChannelTimeout, this, MSG_TIMEOUT);
  779. }
  780. void TurnServer::Channel::OnMessage(talk_base::Message* msg) {
  781. ASSERT(msg->message_id == MSG_TIMEOUT);
  782. SignalDestroyed(this);
  783. delete this;
  784. }
  785. } // namespace cricket