blob: 7e4c43672f4468d3b3d8295b604a6d8a36e73131 [file] [log] [blame]
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001/*
2 * Copyright 2012 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "p2p/base/turnserver.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000012
Taylor Brandstetter734262c2016-08-01 16:37:14 -070013#include <tuple> // for std::tie
14
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020015#include "p2p/base/asyncstuntcpsocket.h"
16#include "p2p/base/common.h"
17#include "p2p/base/packetsocketfactory.h"
18#include "p2p/base/stun.h"
19#include "rtc_base/bind.h"
20#include "rtc_base/bytebuffer.h"
21#include "rtc_base/checks.h"
22#include "rtc_base/helpers.h"
23#include "rtc_base/logging.h"
24#include "rtc_base/messagedigest.h"
25#include "rtc_base/ptr_util.h"
26#include "rtc_base/socketadapters.h"
27#include "rtc_base/stringencode.h"
28#include "rtc_base/thread.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000029
30namespace cricket {
31
32// TODO(juberti): Move this all to a future turnmessage.h
33//static const int IPPROTO_UDP = 17;
34static const int kNonceTimeout = 60 * 60 * 1000; // 60 minutes
35static const int kDefaultAllocationTimeout = 10 * 60 * 1000; // 10 minutes
36static const int kPermissionTimeout = 5 * 60 * 1000; // 5 minutes
37static const int kChannelTimeout = 10 * 60 * 1000; // 10 minutes
38
39static const int kMinChannelNumber = 0x4000;
40static const int kMaxChannelNumber = 0x7FFF;
41
42static const size_t kNonceKeySize = 16;
honghaiz34b11eb2016-03-16 08:55:44 -070043static const size_t kNonceSize = 48;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000044
45static const size_t TURN_CHANNEL_HEADER_SIZE = 4U;
46
47// TODO(mallinath) - Move these to a common place.
Peter Boström0c4e06b2015-10-07 12:23:21 +020048inline bool IsTurnChannelData(uint16_t msg_type) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000049 // The first two bits of a channel data message are 0b01.
50 return ((msg_type & 0xC000) == 0x4000);
51}
52
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +000053// IDs used for posted messages for TurnServerAllocation.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000054enum {
55 MSG_ALLOCATION_TIMEOUT,
56};
57
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000058// Encapsulates a TURN permission.
59// The object is created when a create permission request is received by an
60// allocation, and self-deletes when its lifetime timer expires.
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +000061class TurnServerAllocation::Permission : public rtc::MessageHandler {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000062 public:
63 Permission(rtc::Thread* thread, const rtc::IPAddress& peer);
64 ~Permission();
65
66 const rtc::IPAddress& peer() const { return peer_; }
67 void Refresh();
68
69 sigslot::signal1<Permission*> SignalDestroyed;
70
71 private:
72 virtual void OnMessage(rtc::Message* msg);
73
74 rtc::Thread* thread_;
75 rtc::IPAddress peer_;
76};
77
78// Encapsulates a TURN channel binding.
79// The object is created when a channel bind request is received by an
80// allocation, and self-deletes when its lifetime timer expires.
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +000081class TurnServerAllocation::Channel : public rtc::MessageHandler {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000082 public:
83 Channel(rtc::Thread* thread, int id,
84 const rtc::SocketAddress& peer);
85 ~Channel();
86
87 int id() const { return id_; }
88 const rtc::SocketAddress& peer() const { return peer_; }
89 void Refresh();
90
91 sigslot::signal1<Channel*> SignalDestroyed;
92
93 private:
94 virtual void OnMessage(rtc::Message* msg);
95
96 rtc::Thread* thread_;
97 int id_;
98 rtc::SocketAddress peer_;
99};
100
101static bool InitResponse(const StunMessage* req, StunMessage* resp) {
102 int resp_type = (req) ? GetStunSuccessResponseType(req->type()) : -1;
103 if (resp_type == -1)
104 return false;
105 resp->SetType(resp_type);
106 resp->SetTransactionID(req->transaction_id());
107 return true;
108}
109
110static bool InitErrorResponse(const StunMessage* req, int code,
111 const std::string& reason, StunMessage* resp) {
112 int resp_type = (req) ? GetStunErrorResponseType(req->type()) : -1;
113 if (resp_type == -1)
114 return false;
115 resp->SetType(resp_type);
116 resp->SetTransactionID(req->transaction_id());
zsteinf42cc9d2017-03-27 16:17:19 -0700117 resp->AddAttribute(rtc::MakeUnique<cricket::StunErrorCodeAttribute>(
nissecc99bc22017-02-02 01:31:30 -0800118 STUN_ATTR_ERROR_CODE, code, reason));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000119 return true;
120}
121
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000122
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000123TurnServer::TurnServer(rtc::Thread* thread)
124 : thread_(thread),
125 nonce_key_(rtc::CreateRandomString(kNonceKeySize)),
126 auth_hook_(NULL),
127 redirect_hook_(NULL),
128 enable_otu_nonce_(false) {
129}
130
131TurnServer::~TurnServer() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000132 for (InternalSocketMap::iterator it = server_sockets_.begin();
133 it != server_sockets_.end(); ++it) {
134 rtc::AsyncPacketSocket* socket = it->first;
135 delete socket;
136 }
137
138 for (ServerSocketMap::iterator it = server_listen_sockets_.begin();
139 it != server_listen_sockets_.end(); ++it) {
140 rtc::AsyncSocket* socket = it->first;
141 delete socket;
142 }
143}
144
145void TurnServer::AddInternalSocket(rtc::AsyncPacketSocket* socket,
146 ProtocolType proto) {
nisseede5da42017-01-12 05:15:36 -0800147 RTC_DCHECK(server_sockets_.end() == server_sockets_.find(socket));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000148 server_sockets_[socket] = proto;
149 socket->SignalReadPacket.connect(this, &TurnServer::OnInternalPacket);
150}
151
152void TurnServer::AddInternalServerSocket(rtc::AsyncSocket* socket,
153 ProtocolType proto) {
nisseede5da42017-01-12 05:15:36 -0800154 RTC_DCHECK(server_listen_sockets_.end() ==
155 server_listen_sockets_.find(socket));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000156 server_listen_sockets_[socket] = proto;
157 socket->SignalReadEvent.connect(this, &TurnServer::OnNewInternalConnection);
158}
159
160void TurnServer::SetExternalSocketFactory(
161 rtc::PacketSocketFactory* factory,
162 const rtc::SocketAddress& external_addr) {
163 external_socket_factory_.reset(factory);
164 external_addr_ = external_addr;
165}
166
167void TurnServer::OnNewInternalConnection(rtc::AsyncSocket* socket) {
nisseede5da42017-01-12 05:15:36 -0800168 RTC_DCHECK(server_listen_sockets_.find(socket) !=
169 server_listen_sockets_.end());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000170 AcceptConnection(socket);
171}
172
173void TurnServer::AcceptConnection(rtc::AsyncSocket* server_socket) {
174 // Check if someone is trying to connect to us.
175 rtc::SocketAddress accept_addr;
176 rtc::AsyncSocket* accepted_socket = server_socket->Accept(&accept_addr);
177 if (accepted_socket != NULL) {
178 ProtocolType proto = server_listen_sockets_[server_socket];
179 cricket::AsyncStunTCPSocket* tcp_socket =
180 new cricket::AsyncStunTCPSocket(accepted_socket, false);
181
182 tcp_socket->SignalClose.connect(this, &TurnServer::OnInternalSocketClose);
183 // Finally add the socket so it can start communicating with the client.
184 AddInternalSocket(tcp_socket, proto);
185 }
186}
187
188void TurnServer::OnInternalSocketClose(rtc::AsyncPacketSocket* socket,
189 int err) {
190 DestroyInternalSocket(socket);
191}
192
193void TurnServer::OnInternalPacket(rtc::AsyncPacketSocket* socket,
194 const char* data, size_t size,
195 const rtc::SocketAddress& addr,
196 const rtc::PacketTime& packet_time) {
197 // Fail if the packet is too small to even contain a channel header.
198 if (size < TURN_CHANNEL_HEADER_SIZE) {
199 return;
200 }
201 InternalSocketMap::iterator iter = server_sockets_.find(socket);
nisseede5da42017-01-12 05:15:36 -0800202 RTC_DCHECK(iter != server_sockets_.end());
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000203 TurnServerConnection conn(addr, iter->second, socket);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200204 uint16_t msg_type = rtc::GetBE16(data);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000205 if (!IsTurnChannelData(msg_type)) {
206 // This is a STUN message.
207 HandleStunMessage(&conn, data, size);
208 } else {
209 // This is a channel message; let the allocation handle it.
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000210 TurnServerAllocation* allocation = FindAllocation(&conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000211 if (allocation) {
212 allocation->HandleChannelData(data, size);
213 }
214 }
215}
216
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000217void TurnServer::HandleStunMessage(TurnServerConnection* conn, const char* data,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000218 size_t size) {
219 TurnMessage msg;
jbauchf1f87202016-03-30 06:43:37 -0700220 rtc::ByteBufferReader buf(data, size);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000221 if (!msg.Read(&buf) || (buf.Length() > 0)) {
222 LOG(LS_WARNING) << "Received invalid STUN message";
223 return;
224 }
225
226 // If it's a STUN binding request, handle that specially.
227 if (msg.type() == STUN_BINDING_REQUEST) {
228 HandleBindingRequest(conn, &msg);
229 return;
230 }
231
232 if (redirect_hook_ != NULL && msg.type() == STUN_ALLOCATE_REQUEST) {
233 rtc::SocketAddress address;
234 if (redirect_hook_->ShouldRedirect(conn->src(), &address)) {
235 SendErrorResponseWithAlternateServer(
236 conn, &msg, address);
237 return;
238 }
239 }
240
241 // Look up the key that we'll use to validate the M-I. If we have an
242 // existing allocation, the key will already be cached.
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000243 TurnServerAllocation* allocation = FindAllocation(conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000244 std::string key;
245 if (!allocation) {
246 GetKey(&msg, &key);
247 } else {
248 key = allocation->key();
249 }
250
251 // Ensure the message is authorized; only needed for requests.
252 if (IsStunRequestType(msg.type())) {
253 if (!CheckAuthorization(conn, &msg, data, size, key)) {
254 return;
255 }
256 }
257
258 if (!allocation && msg.type() == STUN_ALLOCATE_REQUEST) {
259 HandleAllocateRequest(conn, &msg, key);
260 } else if (allocation &&
261 (msg.type() != STUN_ALLOCATE_REQUEST ||
262 msg.transaction_id() == allocation->transaction_id())) {
263 // This is a non-allocate request, or a retransmit of an allocate.
264 // Check that the username matches the previous username used.
265 if (IsStunRequestType(msg.type()) &&
266 msg.GetByteString(STUN_ATTR_USERNAME)->GetString() !=
267 allocation->username()) {
268 SendErrorResponse(conn, &msg, STUN_ERROR_WRONG_CREDENTIALS,
269 STUN_ERROR_REASON_WRONG_CREDENTIALS);
270 return;
271 }
272 allocation->HandleTurnMessage(&msg);
273 } else {
274 // Allocation mismatch.
275 SendErrorResponse(conn, &msg, STUN_ERROR_ALLOCATION_MISMATCH,
276 STUN_ERROR_REASON_ALLOCATION_MISMATCH);
277 }
278}
279
280bool TurnServer::GetKey(const StunMessage* msg, std::string* key) {
281 const StunByteStringAttribute* username_attr =
282 msg->GetByteString(STUN_ATTR_USERNAME);
283 if (!username_attr) {
284 return false;
285 }
286
287 std::string username = username_attr->GetString();
288 return (auth_hook_ != NULL && auth_hook_->GetKey(username, realm_, key));
289}
290
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000291bool TurnServer::CheckAuthorization(TurnServerConnection* conn,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000292 const StunMessage* msg,
293 const char* data, size_t size,
294 const std::string& key) {
295 // RFC 5389, 10.2.2.
nisseede5da42017-01-12 05:15:36 -0800296 RTC_DCHECK(IsStunRequestType(msg->type()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000297 const StunByteStringAttribute* mi_attr =
298 msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY);
299 const StunByteStringAttribute* username_attr =
300 msg->GetByteString(STUN_ATTR_USERNAME);
301 const StunByteStringAttribute* realm_attr =
302 msg->GetByteString(STUN_ATTR_REALM);
303 const StunByteStringAttribute* nonce_attr =
304 msg->GetByteString(STUN_ATTR_NONCE);
305
306 // Fail if no M-I.
307 if (!mi_attr) {
308 SendErrorResponseWithRealmAndNonce(conn, msg, STUN_ERROR_UNAUTHORIZED,
309 STUN_ERROR_REASON_UNAUTHORIZED);
310 return false;
311 }
312
313 // Fail if there is M-I but no username, nonce, or realm.
314 if (!username_attr || !realm_attr || !nonce_attr) {
315 SendErrorResponse(conn, msg, STUN_ERROR_BAD_REQUEST,
316 STUN_ERROR_REASON_BAD_REQUEST);
317 return false;
318 }
319
320 // Fail if bad nonce.
321 if (!ValidateNonce(nonce_attr->GetString())) {
322 SendErrorResponseWithRealmAndNonce(conn, msg, STUN_ERROR_STALE_NONCE,
323 STUN_ERROR_REASON_STALE_NONCE);
324 return false;
325 }
326
327 // Fail if bad username or M-I.
328 // We need |data| and |size| for the call to ValidateMessageIntegrity.
329 if (key.empty() || !StunMessage::ValidateMessageIntegrity(data, size, key)) {
330 SendErrorResponseWithRealmAndNonce(conn, msg, STUN_ERROR_UNAUTHORIZED,
331 STUN_ERROR_REASON_UNAUTHORIZED);
332 return false;
333 }
334
335 // Fail if one-time-use nonce feature is enabled.
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000336 TurnServerAllocation* allocation = FindAllocation(conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000337 if (enable_otu_nonce_ && allocation &&
338 allocation->last_nonce() == nonce_attr->GetString()) {
339 SendErrorResponseWithRealmAndNonce(conn, msg, STUN_ERROR_STALE_NONCE,
340 STUN_ERROR_REASON_STALE_NONCE);
341 return false;
342 }
343
344 if (allocation) {
345 allocation->set_last_nonce(nonce_attr->GetString());
346 }
347 // Success.
348 return true;
349}
350
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000351void TurnServer::HandleBindingRequest(TurnServerConnection* conn,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000352 const StunMessage* req) {
353 StunMessage response;
354 InitResponse(req, &response);
355
356 // Tell the user the address that we received their request from.
zsteinf42cc9d2017-03-27 16:17:19 -0700357 auto mapped_addr_attr = rtc::MakeUnique<StunXorAddressAttribute>(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000358 STUN_ATTR_XOR_MAPPED_ADDRESS, conn->src());
zsteinf42cc9d2017-03-27 16:17:19 -0700359 response.AddAttribute(std::move(mapped_addr_attr));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000360
361 SendStun(conn, &response);
362}
363
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000364void TurnServer::HandleAllocateRequest(TurnServerConnection* conn,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000365 const TurnMessage* msg,
366 const std::string& key) {
367 // Check the parameters in the request.
368 const StunUInt32Attribute* transport_attr =
369 msg->GetUInt32(STUN_ATTR_REQUESTED_TRANSPORT);
370 if (!transport_attr) {
371 SendErrorResponse(conn, msg, STUN_ERROR_BAD_REQUEST,
372 STUN_ERROR_REASON_BAD_REQUEST);
373 return;
374 }
375
376 // Only UDP is supported right now.
377 int proto = transport_attr->value() >> 24;
378 if (proto != IPPROTO_UDP) {
379 SendErrorResponse(conn, msg, STUN_ERROR_UNSUPPORTED_PROTOCOL,
380 STUN_ERROR_REASON_UNSUPPORTED_PROTOCOL);
381 return;
382 }
383
384 // Create the allocation and let it send the success response.
385 // If the actual socket allocation fails, send an internal error.
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000386 TurnServerAllocation* alloc = CreateAllocation(conn, proto, key);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000387 if (alloc) {
388 alloc->HandleTurnMessage(msg);
389 } else {
390 SendErrorResponse(conn, msg, STUN_ERROR_SERVER_ERROR,
391 "Failed to allocate socket");
392 }
393}
394
honghaiz34b11eb2016-03-16 08:55:44 -0700395std::string TurnServer::GenerateNonce(int64_t now) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000396 // Generate a nonce of the form hex(now + HMAC-MD5(nonce_key_, now))
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000397 std::string input(reinterpret_cast<const char*>(&now), sizeof(now));
398 std::string nonce = rtc::hex_encode(input.c_str(), input.size());
399 nonce += rtc::ComputeHmac(rtc::DIGEST_MD5, nonce_key_, input);
nisseede5da42017-01-12 05:15:36 -0800400 RTC_DCHECK(nonce.size() == kNonceSize);
honghaiz34b11eb2016-03-16 08:55:44 -0700401
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000402 return nonce;
403}
404
405bool TurnServer::ValidateNonce(const std::string& nonce) const {
406 // Check the size.
407 if (nonce.size() != kNonceSize) {
408 return false;
409 }
410
411 // Decode the timestamp.
honghaiz34b11eb2016-03-16 08:55:44 -0700412 int64_t then;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000413 char* p = reinterpret_cast<char*>(&then);
414 size_t len = rtc::hex_decode(p, sizeof(then),
415 nonce.substr(0, sizeof(then) * 2));
416 if (len != sizeof(then)) {
417 return false;
418 }
419
420 // Verify the HMAC.
421 if (nonce.substr(sizeof(then) * 2) != rtc::ComputeHmac(
422 rtc::DIGEST_MD5, nonce_key_, std::string(p, sizeof(then)))) {
423 return false;
424 }
425
426 // Validate the timestamp.
nisse1bffc1d2016-05-02 08:18:55 -0700427 return rtc::TimeMillis() - then < kNonceTimeout;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000428}
429
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000430TurnServerAllocation* TurnServer::FindAllocation(TurnServerConnection* conn) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000431 AllocationMap::const_iterator it = allocations_.find(*conn);
deadbeef97943662016-07-12 11:04:50 -0700432 return (it != allocations_.end()) ? it->second.get() : nullptr;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000433}
434
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000435TurnServerAllocation* TurnServer::CreateAllocation(TurnServerConnection* conn,
436 int proto,
437 const std::string& key) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000438 rtc::AsyncPacketSocket* external_socket = (external_socket_factory_) ?
439 external_socket_factory_->CreateUdpSocket(external_addr_, 0, 0) : NULL;
440 if (!external_socket) {
441 return NULL;
442 }
443
444 // The Allocation takes ownership of the socket.
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000445 TurnServerAllocation* allocation = new TurnServerAllocation(this,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000446 thread_, *conn, external_socket, key);
447 allocation->SignalDestroyed.connect(this, &TurnServer::OnAllocationDestroyed);
deadbeef97943662016-07-12 11:04:50 -0700448 allocations_[*conn].reset(allocation);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000449 return allocation;
450}
451
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000452void TurnServer::SendErrorResponse(TurnServerConnection* conn,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000453 const StunMessage* req,
454 int code, const std::string& reason) {
455 TurnMessage resp;
456 InitErrorResponse(req, code, reason, &resp);
457 LOG(LS_INFO) << "Sending error response, type=" << resp.type()
458 << ", code=" << code << ", reason=" << reason;
459 SendStun(conn, &resp);
460}
461
462void TurnServer::SendErrorResponseWithRealmAndNonce(
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000463 TurnServerConnection* conn, const StunMessage* msg,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000464 int code, const std::string& reason) {
465 TurnMessage resp;
466 InitErrorResponse(msg, code, reason, &resp);
honghaizc463e202016-02-01 15:19:08 -0800467
nisse1bffc1d2016-05-02 08:18:55 -0700468 int64_t timestamp = rtc::TimeMillis();
honghaizc463e202016-02-01 15:19:08 -0800469 if (ts_for_next_nonce_) {
470 timestamp = ts_for_next_nonce_;
471 ts_for_next_nonce_ = 0;
472 }
zsteinf42cc9d2017-03-27 16:17:19 -0700473 resp.AddAttribute(rtc::MakeUnique<StunByteStringAttribute>(
474 STUN_ATTR_NONCE, GenerateNonce(timestamp)));
nissecc99bc22017-02-02 01:31:30 -0800475 resp.AddAttribute(
zsteinf42cc9d2017-03-27 16:17:19 -0700476 rtc::MakeUnique<StunByteStringAttribute>(STUN_ATTR_REALM, realm_));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000477 SendStun(conn, &resp);
478}
479
480void TurnServer::SendErrorResponseWithAlternateServer(
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000481 TurnServerConnection* conn, const StunMessage* msg,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000482 const rtc::SocketAddress& addr) {
483 TurnMessage resp;
484 InitErrorResponse(msg, STUN_ERROR_TRY_ALTERNATE,
485 STUN_ERROR_REASON_TRY_ALTERNATE_SERVER, &resp);
zsteinf42cc9d2017-03-27 16:17:19 -0700486 resp.AddAttribute(
487 rtc::MakeUnique<StunAddressAttribute>(STUN_ATTR_ALTERNATE_SERVER, addr));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000488 SendStun(conn, &resp);
489}
490
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000491void TurnServer::SendStun(TurnServerConnection* conn, StunMessage* msg) {
jbauchf1f87202016-03-30 06:43:37 -0700492 rtc::ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000493 // Add a SOFTWARE attribute if one is set.
494 if (!software_.empty()) {
zsteinf42cc9d2017-03-27 16:17:19 -0700495 msg->AddAttribute(rtc::MakeUnique<StunByteStringAttribute>(
496 STUN_ATTR_SOFTWARE, software_));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000497 }
498 msg->Write(&buf);
499 Send(conn, buf);
500}
501
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000502void TurnServer::Send(TurnServerConnection* conn,
jbauchf1f87202016-03-30 06:43:37 -0700503 const rtc::ByteBufferWriter& buf) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000504 rtc::PacketOptions options;
505 conn->socket()->SendTo(buf.Data(), buf.Length(), conn->src(), options);
506}
507
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000508void TurnServer::OnAllocationDestroyed(TurnServerAllocation* allocation) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000509 // Removing the internal socket if the connection is not udp.
510 rtc::AsyncPacketSocket* socket = allocation->conn()->socket();
511 InternalSocketMap::iterator iter = server_sockets_.find(socket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000512 // Skip if the socket serving this allocation is UDP, as this will be shared
513 // by all allocations.
Taylor Brandstetter716d07a2016-06-27 14:07:41 -0700514 // Note: We may not find a socket if it's a TCP socket that was closed, and
515 // the allocation is only now timing out.
516 if (iter != server_sockets_.end() && iter->second != cricket::PROTO_UDP) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000517 DestroyInternalSocket(socket);
518 }
519
520 AllocationMap::iterator it = allocations_.find(*(allocation->conn()));
deadbeef97943662016-07-12 11:04:50 -0700521 if (it != allocations_.end()) {
522 it->second.release();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000523 allocations_.erase(it);
deadbeef97943662016-07-12 11:04:50 -0700524 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000525}
526
527void TurnServer::DestroyInternalSocket(rtc::AsyncPacketSocket* socket) {
528 InternalSocketMap::iterator iter = server_sockets_.find(socket);
529 if (iter != server_sockets_.end()) {
530 rtc::AsyncPacketSocket* socket = iter->first;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000531 server_sockets_.erase(iter);
deadbeef824f5862016-08-24 15:06:53 -0700532 // We must destroy the socket async to avoid invalidating the sigslot
533 // callback list iterator inside a sigslot callback. (In other words,
534 // deleting an object from within a callback from that object).
535 sockets_to_delete_.push_back(
536 std::unique_ptr<rtc::AsyncPacketSocket>(socket));
537 invoker_.AsyncInvoke<void>(RTC_FROM_HERE, rtc::Thread::Current(),
538 rtc::Bind(&TurnServer::FreeSockets, this));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000539 }
540}
541
deadbeef824f5862016-08-24 15:06:53 -0700542void TurnServer::FreeSockets() {
543 sockets_to_delete_.clear();
544}
545
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000546TurnServerConnection::TurnServerConnection(const rtc::SocketAddress& src,
547 ProtocolType proto,
548 rtc::AsyncPacketSocket* socket)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000549 : src_(src),
550 dst_(socket->GetRemoteAddress()),
551 proto_(proto),
552 socket_(socket) {
553}
554
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000555bool TurnServerConnection::operator==(const TurnServerConnection& c) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000556 return src_ == c.src_ && dst_ == c.dst_ && proto_ == c.proto_;
557}
558
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000559bool TurnServerConnection::operator<(const TurnServerConnection& c) const {
Taylor Brandstetter734262c2016-08-01 16:37:14 -0700560 return std::tie(src_, dst_, proto_) < std::tie(c.src_, c.dst_, c.proto_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000561}
562
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000563std::string TurnServerConnection::ToString() const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000564 const char* const kProtos[] = {
565 "unknown", "udp", "tcp", "ssltcp"
566 };
567 std::ostringstream ost;
568 ost << src_.ToString() << "-" << dst_.ToString() << ":"<< kProtos[proto_];
569 return ost.str();
570}
571
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000572TurnServerAllocation::TurnServerAllocation(TurnServer* server,
573 rtc::Thread* thread,
574 const TurnServerConnection& conn,
575 rtc::AsyncPacketSocket* socket,
576 const std::string& key)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000577 : server_(server),
578 thread_(thread),
579 conn_(conn),
580 external_socket_(socket),
581 key_(key) {
582 external_socket_->SignalReadPacket.connect(
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000583 this, &TurnServerAllocation::OnExternalPacket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000584}
585
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000586TurnServerAllocation::~TurnServerAllocation() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000587 for (ChannelList::iterator it = channels_.begin();
588 it != channels_.end(); ++it) {
589 delete *it;
590 }
591 for (PermissionList::iterator it = perms_.begin();
592 it != perms_.end(); ++it) {
593 delete *it;
594 }
595 thread_->Clear(this, MSG_ALLOCATION_TIMEOUT);
596 LOG_J(LS_INFO, this) << "Allocation destroyed";
597}
598
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000599std::string TurnServerAllocation::ToString() const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000600 std::ostringstream ost;
601 ost << "Alloc[" << conn_.ToString() << "]";
602 return ost.str();
603}
604
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000605void TurnServerAllocation::HandleTurnMessage(const TurnMessage* msg) {
nisseede5da42017-01-12 05:15:36 -0800606 RTC_DCHECK(msg != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000607 switch (msg->type()) {
608 case STUN_ALLOCATE_REQUEST:
609 HandleAllocateRequest(msg);
610 break;
611 case TURN_REFRESH_REQUEST:
612 HandleRefreshRequest(msg);
613 break;
614 case TURN_SEND_INDICATION:
615 HandleSendIndication(msg);
616 break;
617 case TURN_CREATE_PERMISSION_REQUEST:
618 HandleCreatePermissionRequest(msg);
619 break;
620 case TURN_CHANNEL_BIND_REQUEST:
621 HandleChannelBindRequest(msg);
622 break;
623 default:
624 // Not sure what to do with this, just eat it.
625 LOG_J(LS_WARNING, this) << "Invalid TURN message type received: "
626 << msg->type();
627 }
628}
629
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000630void TurnServerAllocation::HandleAllocateRequest(const TurnMessage* msg) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000631 // Copy the important info from the allocate request.
632 transaction_id_ = msg->transaction_id();
633 const StunByteStringAttribute* username_attr =
634 msg->GetByteString(STUN_ATTR_USERNAME);
nisseede5da42017-01-12 05:15:36 -0800635 RTC_DCHECK(username_attr != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000636 username_ = username_attr->GetString();
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000637 const StunByteStringAttribute* origin_attr =
638 msg->GetByteString(STUN_ATTR_ORIGIN);
639 if (origin_attr) {
640 origin_ = origin_attr->GetString();
641 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000642
643 // Figure out the lifetime and start the allocation timer.
644 int lifetime_secs = ComputeLifetime(msg);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700645 thread_->PostDelayed(RTC_FROM_HERE, lifetime_secs * 1000, this,
646 MSG_ALLOCATION_TIMEOUT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000647
648 LOG_J(LS_INFO, this) << "Created allocation, lifetime=" << lifetime_secs;
649
650 // We've already validated all the important bits; just send a response here.
651 TurnMessage response;
652 InitResponse(msg, &response);
653
zsteinf42cc9d2017-03-27 16:17:19 -0700654 auto mapped_addr_attr = rtc::MakeUnique<StunXorAddressAttribute>(
655 STUN_ATTR_XOR_MAPPED_ADDRESS, conn_.src());
656 auto relayed_addr_attr = rtc::MakeUnique<StunXorAddressAttribute>(
657 STUN_ATTR_XOR_RELAYED_ADDRESS, external_socket_->GetLocalAddress());
658 auto lifetime_attr =
659 rtc::MakeUnique<StunUInt32Attribute>(STUN_ATTR_LIFETIME, lifetime_secs);
660 response.AddAttribute(std::move(mapped_addr_attr));
661 response.AddAttribute(std::move(relayed_addr_attr));
662 response.AddAttribute(std::move(lifetime_attr));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000663
664 SendResponse(&response);
665}
666
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000667void TurnServerAllocation::HandleRefreshRequest(const TurnMessage* msg) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000668 // Figure out the new lifetime.
669 int lifetime_secs = ComputeLifetime(msg);
670
671 // Reset the expiration timer.
672 thread_->Clear(this, MSG_ALLOCATION_TIMEOUT);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700673 thread_->PostDelayed(RTC_FROM_HERE, lifetime_secs * 1000, this,
674 MSG_ALLOCATION_TIMEOUT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000675
676 LOG_J(LS_INFO, this) << "Refreshed allocation, lifetime=" << lifetime_secs;
677
678 // Send a success response with a LIFETIME attribute.
679 TurnMessage response;
680 InitResponse(msg, &response);
681
zsteinf42cc9d2017-03-27 16:17:19 -0700682 auto lifetime_attr =
683 rtc::MakeUnique<StunUInt32Attribute>(STUN_ATTR_LIFETIME, lifetime_secs);
684 response.AddAttribute(std::move(lifetime_attr));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000685
686 SendResponse(&response);
687}
688
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000689void TurnServerAllocation::HandleSendIndication(const TurnMessage* msg) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000690 // Check mandatory attributes.
691 const StunByteStringAttribute* data_attr = msg->GetByteString(STUN_ATTR_DATA);
692 const StunAddressAttribute* peer_attr =
693 msg->GetAddress(STUN_ATTR_XOR_PEER_ADDRESS);
694 if (!data_attr || !peer_attr) {
695 LOG_J(LS_WARNING, this) << "Received invalid send indication";
696 return;
697 }
698
699 // If a permission exists, send the data on to the peer.
700 if (HasPermission(peer_attr->GetAddress().ipaddr())) {
701 SendExternal(data_attr->bytes(), data_attr->length(),
702 peer_attr->GetAddress());
703 } else {
704 LOG_J(LS_WARNING, this) << "Received send indication without permission"
705 << "peer=" << peer_attr->GetAddress();
706 }
707}
708
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000709void TurnServerAllocation::HandleCreatePermissionRequest(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000710 const TurnMessage* msg) {
711 // Check mandatory attributes.
712 const StunAddressAttribute* peer_attr =
713 msg->GetAddress(STUN_ATTR_XOR_PEER_ADDRESS);
714 if (!peer_attr) {
715 SendBadRequestResponse(msg);
716 return;
717 }
718
deadbeef376e1232015-11-25 09:00:08 -0800719 if (server_->reject_private_addresses_ &&
720 rtc::IPIsPrivate(peer_attr->GetAddress().ipaddr())) {
721 SendErrorResponse(msg, STUN_ERROR_FORBIDDEN, STUN_ERROR_REASON_FORBIDDEN);
722 return;
723 }
724
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000725 // Add this permission.
726 AddPermission(peer_attr->GetAddress().ipaddr());
727
728 LOG_J(LS_INFO, this) << "Created permission, peer="
729 << peer_attr->GetAddress();
730
731 // Send a success response.
732 TurnMessage response;
733 InitResponse(msg, &response);
734 SendResponse(&response);
735}
736
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000737void TurnServerAllocation::HandleChannelBindRequest(const TurnMessage* msg) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000738 // Check mandatory attributes.
739 const StunUInt32Attribute* channel_attr =
740 msg->GetUInt32(STUN_ATTR_CHANNEL_NUMBER);
741 const StunAddressAttribute* peer_attr =
742 msg->GetAddress(STUN_ATTR_XOR_PEER_ADDRESS);
743 if (!channel_attr || !peer_attr) {
744 SendBadRequestResponse(msg);
745 return;
746 }
747
748 // Check that channel id is valid.
749 int channel_id = channel_attr->value() >> 16;
750 if (channel_id < kMinChannelNumber || channel_id > kMaxChannelNumber) {
751 SendBadRequestResponse(msg);
752 return;
753 }
754
755 // Check that this channel id isn't bound to another transport address, and
756 // that this transport address isn't bound to another channel id.
757 Channel* channel1 = FindChannel(channel_id);
758 Channel* channel2 = FindChannel(peer_attr->GetAddress());
759 if (channel1 != channel2) {
760 SendBadRequestResponse(msg);
761 return;
762 }
763
764 // Add or refresh this channel.
765 if (!channel1) {
766 channel1 = new Channel(thread_, channel_id, peer_attr->GetAddress());
767 channel1->SignalDestroyed.connect(this,
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000768 &TurnServerAllocation::OnChannelDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000769 channels_.push_back(channel1);
770 } else {
771 channel1->Refresh();
772 }
773
774 // Channel binds also refresh permissions.
775 AddPermission(peer_attr->GetAddress().ipaddr());
776
777 LOG_J(LS_INFO, this) << "Bound channel, id=" << channel_id
778 << ", peer=" << peer_attr->GetAddress();
779
780 // Send a success response.
781 TurnMessage response;
782 InitResponse(msg, &response);
783 SendResponse(&response);
784}
785
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000786void TurnServerAllocation::HandleChannelData(const char* data, size_t size) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000787 // Extract the channel number from the data.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200788 uint16_t channel_id = rtc::GetBE16(data);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000789 Channel* channel = FindChannel(channel_id);
790 if (channel) {
791 // Send the data to the peer address.
792 SendExternal(data + TURN_CHANNEL_HEADER_SIZE,
793 size - TURN_CHANNEL_HEADER_SIZE, channel->peer());
794 } else {
795 LOG_J(LS_WARNING, this) << "Received channel data for invalid channel, id="
796 << channel_id;
797 }
798}
799
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000800void TurnServerAllocation::OnExternalPacket(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000801 rtc::AsyncPacketSocket* socket,
802 const char* data, size_t size,
803 const rtc::SocketAddress& addr,
804 const rtc::PacketTime& packet_time) {
nisseede5da42017-01-12 05:15:36 -0800805 RTC_DCHECK(external_socket_.get() == socket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000806 Channel* channel = FindChannel(addr);
807 if (channel) {
808 // There is a channel bound to this address. Send as a channel message.
jbauchf1f87202016-03-30 06:43:37 -0700809 rtc::ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000810 buf.WriteUInt16(channel->id());
Peter Boström0c4e06b2015-10-07 12:23:21 +0200811 buf.WriteUInt16(static_cast<uint16_t>(size));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000812 buf.WriteBytes(data, size);
813 server_->Send(&conn_, buf);
Taylor Brandstetteref184702016-06-23 17:35:47 -0700814 } else if (!server_->enable_permission_checks_ ||
815 HasPermission(addr.ipaddr())) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000816 // No channel, but a permission exists. Send as a data indication.
817 TurnMessage msg;
818 msg.SetType(TURN_DATA_INDICATION);
819 msg.SetTransactionID(
820 rtc::CreateRandomString(kStunTransactionIdLength));
zsteinf42cc9d2017-03-27 16:17:19 -0700821 msg.AddAttribute(rtc::MakeUnique<StunXorAddressAttribute>(
nissecc99bc22017-02-02 01:31:30 -0800822 STUN_ATTR_XOR_PEER_ADDRESS, addr));
zsteinf42cc9d2017-03-27 16:17:19 -0700823 msg.AddAttribute(
824 rtc::MakeUnique<StunByteStringAttribute>(STUN_ATTR_DATA, data, size));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000825 server_->SendStun(&conn_, &msg);
826 } else {
827 LOG_J(LS_WARNING, this) << "Received external packet without permission, "
828 << "peer=" << addr;
829 }
830}
831
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000832int TurnServerAllocation::ComputeLifetime(const TurnMessage* msg) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000833 // Return the smaller of our default lifetime and the requested lifetime.
honghaiz34b11eb2016-03-16 08:55:44 -0700834 int lifetime = kDefaultAllocationTimeout / 1000; // convert to seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000835 const StunUInt32Attribute* lifetime_attr = msg->GetUInt32(STUN_ATTR_LIFETIME);
honghaiz34b11eb2016-03-16 08:55:44 -0700836 if (lifetime_attr && static_cast<int>(lifetime_attr->value()) < lifetime) {
837 lifetime = static_cast<int>(lifetime_attr->value());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000838 }
839 return lifetime;
840}
841
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000842bool TurnServerAllocation::HasPermission(const rtc::IPAddress& addr) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000843 return (FindPermission(addr) != NULL);
844}
845
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000846void TurnServerAllocation::AddPermission(const rtc::IPAddress& addr) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000847 Permission* perm = FindPermission(addr);
848 if (!perm) {
849 perm = new Permission(thread_, addr);
850 perm->SignalDestroyed.connect(
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000851 this, &TurnServerAllocation::OnPermissionDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000852 perms_.push_back(perm);
853 } else {
854 perm->Refresh();
855 }
856}
857
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000858TurnServerAllocation::Permission* TurnServerAllocation::FindPermission(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000859 const rtc::IPAddress& addr) const {
860 for (PermissionList::const_iterator it = perms_.begin();
861 it != perms_.end(); ++it) {
862 if ((*it)->peer() == addr)
863 return *it;
864 }
865 return NULL;
866}
867
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000868TurnServerAllocation::Channel* TurnServerAllocation::FindChannel(
869 int channel_id) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000870 for (ChannelList::const_iterator it = channels_.begin();
871 it != channels_.end(); ++it) {
872 if ((*it)->id() == channel_id)
873 return *it;
874 }
875 return NULL;
876}
877
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000878TurnServerAllocation::Channel* TurnServerAllocation::FindChannel(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000879 const rtc::SocketAddress& addr) const {
880 for (ChannelList::const_iterator it = channels_.begin();
881 it != channels_.end(); ++it) {
882 if ((*it)->peer() == addr)
883 return *it;
884 }
885 return NULL;
886}
887
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000888void TurnServerAllocation::SendResponse(TurnMessage* msg) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000889 // Success responses always have M-I.
890 msg->AddMessageIntegrity(key_);
891 server_->SendStun(&conn_, msg);
892}
893
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000894void TurnServerAllocation::SendBadRequestResponse(const TurnMessage* req) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000895 SendErrorResponse(req, STUN_ERROR_BAD_REQUEST, STUN_ERROR_REASON_BAD_REQUEST);
896}
897
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000898void TurnServerAllocation::SendErrorResponse(const TurnMessage* req, int code,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000899 const std::string& reason) {
900 server_->SendErrorResponse(&conn_, req, code, reason);
901}
902
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000903void TurnServerAllocation::SendExternal(const void* data, size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000904 const rtc::SocketAddress& peer) {
905 rtc::PacketOptions options;
906 external_socket_->SendTo(data, size, peer, options);
907}
908
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000909void TurnServerAllocation::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -0800910 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_TIMEOUT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000911 SignalDestroyed(this);
912 delete this;
913}
914
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000915void TurnServerAllocation::OnPermissionDestroyed(Permission* perm) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000916 PermissionList::iterator it = std::find(perms_.begin(), perms_.end(), perm);
nisseede5da42017-01-12 05:15:36 -0800917 RTC_DCHECK(it != perms_.end());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000918 perms_.erase(it);
919}
920
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000921void TurnServerAllocation::OnChannelDestroyed(Channel* channel) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000922 ChannelList::iterator it =
923 std::find(channels_.begin(), channels_.end(), channel);
nisseede5da42017-01-12 05:15:36 -0800924 RTC_DCHECK(it != channels_.end());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000925 channels_.erase(it);
926}
927
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000928TurnServerAllocation::Permission::Permission(rtc::Thread* thread,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000929 const rtc::IPAddress& peer)
930 : thread_(thread), peer_(peer) {
931 Refresh();
932}
933
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000934TurnServerAllocation::Permission::~Permission() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000935 thread_->Clear(this, MSG_ALLOCATION_TIMEOUT);
936}
937
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000938void TurnServerAllocation::Permission::Refresh() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000939 thread_->Clear(this, MSG_ALLOCATION_TIMEOUT);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700940 thread_->PostDelayed(RTC_FROM_HERE, kPermissionTimeout, this,
941 MSG_ALLOCATION_TIMEOUT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000942}
943
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000944void TurnServerAllocation::Permission::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -0800945 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_TIMEOUT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000946 SignalDestroyed(this);
947 delete this;
948}
949
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000950TurnServerAllocation::Channel::Channel(rtc::Thread* thread, int id,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000951 const rtc::SocketAddress& peer)
952 : thread_(thread), id_(id), peer_(peer) {
953 Refresh();
954}
955
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000956TurnServerAllocation::Channel::~Channel() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000957 thread_->Clear(this, MSG_ALLOCATION_TIMEOUT);
958}
959
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000960void TurnServerAllocation::Channel::Refresh() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000961 thread_->Clear(this, MSG_ALLOCATION_TIMEOUT);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700962 thread_->PostDelayed(RTC_FROM_HERE, kChannelTimeout, this,
963 MSG_ALLOCATION_TIMEOUT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000964}
965
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000966void TurnServerAllocation::Channel::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -0800967 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_TIMEOUT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000968 SignalDestroyed(this);
969 delete this;
970}
971
972} // namespace cricket