blob: 2a154aa76b9b3414e795f0e55eed9e819135433b [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
Steve Anton6c38cc72017-11-29 10:25:58 -080014#include <utility>
Taylor Brandstetter734262c2016-08-01 16:37:14 -070015
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020016#include "p2p/base/asyncstuntcpsocket.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020017#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
Steve Anton6c38cc72017-11-29 10:25:58 -080033// static const int IPPROTO_UDP = 17;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000034static 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);
Steve Antonf2737d22017-10-31 16:27:34 -070064 ~Permission() override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000065
66 const rtc::IPAddress& peer() const { return peer_; }
67 void Refresh();
68
69 sigslot::signal1<Permission*> SignalDestroyed;
70
71 private:
Steve Antonf2737d22017-10-31 16:27:34 -070072 void OnMessage(rtc::Message* msg) override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000073
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);
Steve Antonf2737d22017-10-31 16:27:34 -070085 ~Channel() override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000086
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:
Steve Antonf2737d22017-10-31 16:27:34 -070094 void OnMessage(rtc::Message* msg) override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000095
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) {
Steve Anton6c38cc72017-11-29 10:25:58 -0800199 return;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000200 }
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 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200214 if (stun_message_observer_ != nullptr) {
215 stun_message_observer_->ReceivedChannelData(data, size);
216 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000217 }
218}
219
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000220void TurnServer::HandleStunMessage(TurnServerConnection* conn, const char* data,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000221 size_t size) {
222 TurnMessage msg;
jbauchf1f87202016-03-30 06:43:37 -0700223 rtc::ByteBufferReader buf(data, size);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000224 if (!msg.Read(&buf) || (buf.Length() > 0)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100225 RTC_LOG(LS_WARNING) << "Received invalid STUN message";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000226 return;
227 }
228
Jonas Orelandbdcee282017-10-10 14:01:40 +0200229 if (stun_message_observer_ != nullptr) {
230 stun_message_observer_->ReceivedMessage(&msg);
231 }
232
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000233 // If it's a STUN binding request, handle that specially.
234 if (msg.type() == STUN_BINDING_REQUEST) {
235 HandleBindingRequest(conn, &msg);
236 return;
237 }
238
239 if (redirect_hook_ != NULL && msg.type() == STUN_ALLOCATE_REQUEST) {
240 rtc::SocketAddress address;
241 if (redirect_hook_->ShouldRedirect(conn->src(), &address)) {
242 SendErrorResponseWithAlternateServer(
243 conn, &msg, address);
244 return;
245 }
246 }
247
248 // Look up the key that we'll use to validate the M-I. If we have an
249 // existing allocation, the key will already be cached.
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000250 TurnServerAllocation* allocation = FindAllocation(conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000251 std::string key;
252 if (!allocation) {
253 GetKey(&msg, &key);
254 } else {
255 key = allocation->key();
256 }
257
258 // Ensure the message is authorized; only needed for requests.
259 if (IsStunRequestType(msg.type())) {
260 if (!CheckAuthorization(conn, &msg, data, size, key)) {
261 return;
262 }
263 }
264
265 if (!allocation && msg.type() == STUN_ALLOCATE_REQUEST) {
266 HandleAllocateRequest(conn, &msg, key);
267 } else if (allocation &&
268 (msg.type() != STUN_ALLOCATE_REQUEST ||
269 msg.transaction_id() == allocation->transaction_id())) {
270 // This is a non-allocate request, or a retransmit of an allocate.
271 // Check that the username matches the previous username used.
272 if (IsStunRequestType(msg.type()) &&
273 msg.GetByteString(STUN_ATTR_USERNAME)->GetString() !=
274 allocation->username()) {
275 SendErrorResponse(conn, &msg, STUN_ERROR_WRONG_CREDENTIALS,
276 STUN_ERROR_REASON_WRONG_CREDENTIALS);
277 return;
278 }
279 allocation->HandleTurnMessage(&msg);
280 } else {
281 // Allocation mismatch.
282 SendErrorResponse(conn, &msg, STUN_ERROR_ALLOCATION_MISMATCH,
283 STUN_ERROR_REASON_ALLOCATION_MISMATCH);
284 }
285}
286
287bool TurnServer::GetKey(const StunMessage* msg, std::string* key) {
288 const StunByteStringAttribute* username_attr =
289 msg->GetByteString(STUN_ATTR_USERNAME);
290 if (!username_attr) {
291 return false;
292 }
293
294 std::string username = username_attr->GetString();
295 return (auth_hook_ != NULL && auth_hook_->GetKey(username, realm_, key));
296}
297
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000298bool TurnServer::CheckAuthorization(TurnServerConnection* conn,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000299 const StunMessage* msg,
300 const char* data, size_t size,
301 const std::string& key) {
302 // RFC 5389, 10.2.2.
nisseede5da42017-01-12 05:15:36 -0800303 RTC_DCHECK(IsStunRequestType(msg->type()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000304 const StunByteStringAttribute* mi_attr =
305 msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY);
306 const StunByteStringAttribute* username_attr =
307 msg->GetByteString(STUN_ATTR_USERNAME);
308 const StunByteStringAttribute* realm_attr =
309 msg->GetByteString(STUN_ATTR_REALM);
310 const StunByteStringAttribute* nonce_attr =
311 msg->GetByteString(STUN_ATTR_NONCE);
312
313 // Fail if no M-I.
314 if (!mi_attr) {
315 SendErrorResponseWithRealmAndNonce(conn, msg, STUN_ERROR_UNAUTHORIZED,
316 STUN_ERROR_REASON_UNAUTHORIZED);
317 return false;
318 }
319
320 // Fail if there is M-I but no username, nonce, or realm.
321 if (!username_attr || !realm_attr || !nonce_attr) {
322 SendErrorResponse(conn, msg, STUN_ERROR_BAD_REQUEST,
323 STUN_ERROR_REASON_BAD_REQUEST);
324 return false;
325 }
326
327 // Fail if bad nonce.
328 if (!ValidateNonce(nonce_attr->GetString())) {
329 SendErrorResponseWithRealmAndNonce(conn, msg, STUN_ERROR_STALE_NONCE,
330 STUN_ERROR_REASON_STALE_NONCE);
331 return false;
332 }
333
334 // Fail if bad username or M-I.
335 // We need |data| and |size| for the call to ValidateMessageIntegrity.
336 if (key.empty() || !StunMessage::ValidateMessageIntegrity(data, size, key)) {
337 SendErrorResponseWithRealmAndNonce(conn, msg, STUN_ERROR_UNAUTHORIZED,
338 STUN_ERROR_REASON_UNAUTHORIZED);
339 return false;
340 }
341
342 // Fail if one-time-use nonce feature is enabled.
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000343 TurnServerAllocation* allocation = FindAllocation(conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000344 if (enable_otu_nonce_ && allocation &&
345 allocation->last_nonce() == nonce_attr->GetString()) {
346 SendErrorResponseWithRealmAndNonce(conn, msg, STUN_ERROR_STALE_NONCE,
347 STUN_ERROR_REASON_STALE_NONCE);
348 return false;
349 }
350
351 if (allocation) {
352 allocation->set_last_nonce(nonce_attr->GetString());
353 }
354 // Success.
355 return true;
356}
357
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000358void TurnServer::HandleBindingRequest(TurnServerConnection* conn,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000359 const StunMessage* req) {
360 StunMessage response;
361 InitResponse(req, &response);
362
363 // Tell the user the address that we received their request from.
zsteinf42cc9d2017-03-27 16:17:19 -0700364 auto mapped_addr_attr = rtc::MakeUnique<StunXorAddressAttribute>(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000365 STUN_ATTR_XOR_MAPPED_ADDRESS, conn->src());
zsteinf42cc9d2017-03-27 16:17:19 -0700366 response.AddAttribute(std::move(mapped_addr_attr));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000367
368 SendStun(conn, &response);
369}
370
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000371void TurnServer::HandleAllocateRequest(TurnServerConnection* conn,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000372 const TurnMessage* msg,
373 const std::string& key) {
374 // Check the parameters in the request.
375 const StunUInt32Attribute* transport_attr =
376 msg->GetUInt32(STUN_ATTR_REQUESTED_TRANSPORT);
377 if (!transport_attr) {
378 SendErrorResponse(conn, msg, STUN_ERROR_BAD_REQUEST,
379 STUN_ERROR_REASON_BAD_REQUEST);
380 return;
381 }
382
383 // Only UDP is supported right now.
384 int proto = transport_attr->value() >> 24;
385 if (proto != IPPROTO_UDP) {
386 SendErrorResponse(conn, msg, STUN_ERROR_UNSUPPORTED_PROTOCOL,
387 STUN_ERROR_REASON_UNSUPPORTED_PROTOCOL);
388 return;
389 }
390
391 // Create the allocation and let it send the success response.
392 // If the actual socket allocation fails, send an internal error.
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000393 TurnServerAllocation* alloc = CreateAllocation(conn, proto, key);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000394 if (alloc) {
395 alloc->HandleTurnMessage(msg);
396 } else {
397 SendErrorResponse(conn, msg, STUN_ERROR_SERVER_ERROR,
398 "Failed to allocate socket");
399 }
400}
401
honghaiz34b11eb2016-03-16 08:55:44 -0700402std::string TurnServer::GenerateNonce(int64_t now) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000403 // Generate a nonce of the form hex(now + HMAC-MD5(nonce_key_, now))
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000404 std::string input(reinterpret_cast<const char*>(&now), sizeof(now));
405 std::string nonce = rtc::hex_encode(input.c_str(), input.size());
406 nonce += rtc::ComputeHmac(rtc::DIGEST_MD5, nonce_key_, input);
nisseede5da42017-01-12 05:15:36 -0800407 RTC_DCHECK(nonce.size() == kNonceSize);
honghaiz34b11eb2016-03-16 08:55:44 -0700408
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000409 return nonce;
410}
411
412bool TurnServer::ValidateNonce(const std::string& nonce) const {
413 // Check the size.
414 if (nonce.size() != kNonceSize) {
415 return false;
416 }
417
418 // Decode the timestamp.
honghaiz34b11eb2016-03-16 08:55:44 -0700419 int64_t then;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000420 char* p = reinterpret_cast<char*>(&then);
421 size_t len = rtc::hex_decode(p, sizeof(then),
422 nonce.substr(0, sizeof(then) * 2));
423 if (len != sizeof(then)) {
424 return false;
425 }
426
427 // Verify the HMAC.
428 if (nonce.substr(sizeof(then) * 2) != rtc::ComputeHmac(
429 rtc::DIGEST_MD5, nonce_key_, std::string(p, sizeof(then)))) {
430 return false;
431 }
432
433 // Validate the timestamp.
nisse1bffc1d2016-05-02 08:18:55 -0700434 return rtc::TimeMillis() - then < kNonceTimeout;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000435}
436
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000437TurnServerAllocation* TurnServer::FindAllocation(TurnServerConnection* conn) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000438 AllocationMap::const_iterator it = allocations_.find(*conn);
deadbeef97943662016-07-12 11:04:50 -0700439 return (it != allocations_.end()) ? it->second.get() : nullptr;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000440}
441
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000442TurnServerAllocation* TurnServer::CreateAllocation(TurnServerConnection* conn,
443 int proto,
444 const std::string& key) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000445 rtc::AsyncPacketSocket* external_socket = (external_socket_factory_) ?
446 external_socket_factory_->CreateUdpSocket(external_addr_, 0, 0) : NULL;
447 if (!external_socket) {
448 return NULL;
449 }
450
451 // The Allocation takes ownership of the socket.
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000452 TurnServerAllocation* allocation = new TurnServerAllocation(this,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000453 thread_, *conn, external_socket, key);
454 allocation->SignalDestroyed.connect(this, &TurnServer::OnAllocationDestroyed);
deadbeef97943662016-07-12 11:04:50 -0700455 allocations_[*conn].reset(allocation);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000456 return allocation;
457}
458
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000459void TurnServer::SendErrorResponse(TurnServerConnection* conn,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000460 const StunMessage* req,
461 int code, const std::string& reason) {
462 TurnMessage resp;
463 InitErrorResponse(req, code, reason, &resp);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100464 RTC_LOG(LS_INFO) << "Sending error response, type=" << resp.type()
465 << ", code=" << code << ", reason=" << reason;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000466 SendStun(conn, &resp);
467}
468
469void TurnServer::SendErrorResponseWithRealmAndNonce(
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000470 TurnServerConnection* conn, const StunMessage* msg,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000471 int code, const std::string& reason) {
472 TurnMessage resp;
473 InitErrorResponse(msg, code, reason, &resp);
honghaizc463e202016-02-01 15:19:08 -0800474
nisse1bffc1d2016-05-02 08:18:55 -0700475 int64_t timestamp = rtc::TimeMillis();
honghaizc463e202016-02-01 15:19:08 -0800476 if (ts_for_next_nonce_) {
477 timestamp = ts_for_next_nonce_;
478 ts_for_next_nonce_ = 0;
479 }
zsteinf42cc9d2017-03-27 16:17:19 -0700480 resp.AddAttribute(rtc::MakeUnique<StunByteStringAttribute>(
481 STUN_ATTR_NONCE, GenerateNonce(timestamp)));
nissecc99bc22017-02-02 01:31:30 -0800482 resp.AddAttribute(
zsteinf42cc9d2017-03-27 16:17:19 -0700483 rtc::MakeUnique<StunByteStringAttribute>(STUN_ATTR_REALM, realm_));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000484 SendStun(conn, &resp);
485}
486
487void TurnServer::SendErrorResponseWithAlternateServer(
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000488 TurnServerConnection* conn, const StunMessage* msg,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000489 const rtc::SocketAddress& addr) {
490 TurnMessage resp;
491 InitErrorResponse(msg, STUN_ERROR_TRY_ALTERNATE,
492 STUN_ERROR_REASON_TRY_ALTERNATE_SERVER, &resp);
zsteinf42cc9d2017-03-27 16:17:19 -0700493 resp.AddAttribute(
494 rtc::MakeUnique<StunAddressAttribute>(STUN_ATTR_ALTERNATE_SERVER, addr));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000495 SendStun(conn, &resp);
496}
497
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000498void TurnServer::SendStun(TurnServerConnection* conn, StunMessage* msg) {
jbauchf1f87202016-03-30 06:43:37 -0700499 rtc::ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000500 // Add a SOFTWARE attribute if one is set.
501 if (!software_.empty()) {
zsteinf42cc9d2017-03-27 16:17:19 -0700502 msg->AddAttribute(rtc::MakeUnique<StunByteStringAttribute>(
503 STUN_ATTR_SOFTWARE, software_));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000504 }
505 msg->Write(&buf);
506 Send(conn, buf);
507}
508
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000509void TurnServer::Send(TurnServerConnection* conn,
jbauchf1f87202016-03-30 06:43:37 -0700510 const rtc::ByteBufferWriter& buf) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000511 rtc::PacketOptions options;
512 conn->socket()->SendTo(buf.Data(), buf.Length(), conn->src(), options);
513}
514
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000515void TurnServer::OnAllocationDestroyed(TurnServerAllocation* allocation) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000516 // Removing the internal socket if the connection is not udp.
517 rtc::AsyncPacketSocket* socket = allocation->conn()->socket();
518 InternalSocketMap::iterator iter = server_sockets_.find(socket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000519 // Skip if the socket serving this allocation is UDP, as this will be shared
520 // by all allocations.
Taylor Brandstetter716d07a2016-06-27 14:07:41 -0700521 // Note: We may not find a socket if it's a TCP socket that was closed, and
522 // the allocation is only now timing out.
523 if (iter != server_sockets_.end() && iter->second != cricket::PROTO_UDP) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000524 DestroyInternalSocket(socket);
525 }
526
527 AllocationMap::iterator it = allocations_.find(*(allocation->conn()));
deadbeef97943662016-07-12 11:04:50 -0700528 if (it != allocations_.end()) {
529 it->second.release();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000530 allocations_.erase(it);
deadbeef97943662016-07-12 11:04:50 -0700531 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000532}
533
534void TurnServer::DestroyInternalSocket(rtc::AsyncPacketSocket* socket) {
535 InternalSocketMap::iterator iter = server_sockets_.find(socket);
536 if (iter != server_sockets_.end()) {
537 rtc::AsyncPacketSocket* socket = iter->first;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000538 server_sockets_.erase(iter);
deadbeef824f5862016-08-24 15:06:53 -0700539 // We must destroy the socket async to avoid invalidating the sigslot
540 // callback list iterator inside a sigslot callback. (In other words,
541 // deleting an object from within a callback from that object).
542 sockets_to_delete_.push_back(
543 std::unique_ptr<rtc::AsyncPacketSocket>(socket));
544 invoker_.AsyncInvoke<void>(RTC_FROM_HERE, rtc::Thread::Current(),
545 rtc::Bind(&TurnServer::FreeSockets, this));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000546 }
547}
548
deadbeef824f5862016-08-24 15:06:53 -0700549void TurnServer::FreeSockets() {
550 sockets_to_delete_.clear();
551}
552
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000553TurnServerConnection::TurnServerConnection(const rtc::SocketAddress& src,
554 ProtocolType proto,
555 rtc::AsyncPacketSocket* socket)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000556 : src_(src),
557 dst_(socket->GetRemoteAddress()),
558 proto_(proto),
559 socket_(socket) {
560}
561
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000562bool TurnServerConnection::operator==(const TurnServerConnection& c) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000563 return src_ == c.src_ && dst_ == c.dst_ && proto_ == c.proto_;
564}
565
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000566bool TurnServerConnection::operator<(const TurnServerConnection& c) const {
Taylor Brandstetter734262c2016-08-01 16:37:14 -0700567 return std::tie(src_, dst_, proto_) < std::tie(c.src_, c.dst_, c.proto_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000568}
569
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000570std::string TurnServerConnection::ToString() const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000571 const char* const kProtos[] = {
572 "unknown", "udp", "tcp", "ssltcp"
573 };
574 std::ostringstream ost;
575 ost << src_.ToString() << "-" << dst_.ToString() << ":"<< kProtos[proto_];
576 return ost.str();
577}
578
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000579TurnServerAllocation::TurnServerAllocation(TurnServer* server,
580 rtc::Thread* thread,
581 const TurnServerConnection& conn,
582 rtc::AsyncPacketSocket* socket,
583 const std::string& key)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000584 : server_(server),
585 thread_(thread),
586 conn_(conn),
587 external_socket_(socket),
588 key_(key) {
589 external_socket_->SignalReadPacket.connect(
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000590 this, &TurnServerAllocation::OnExternalPacket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000591}
592
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000593TurnServerAllocation::~TurnServerAllocation() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000594 for (ChannelList::iterator it = channels_.begin();
595 it != channels_.end(); ++it) {
596 delete *it;
597 }
598 for (PermissionList::iterator it = perms_.begin();
599 it != perms_.end(); ++it) {
600 delete *it;
601 }
602 thread_->Clear(this, MSG_ALLOCATION_TIMEOUT);
Jonas Olssond7d762d2018-03-28 09:47:51 +0200603 RTC_LOG(LS_INFO) << ToString() << ": Allocation destroyed";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000604}
605
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000606std::string TurnServerAllocation::ToString() const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000607 std::ostringstream ost;
608 ost << "Alloc[" << conn_.ToString() << "]";
609 return ost.str();
610}
611
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000612void TurnServerAllocation::HandleTurnMessage(const TurnMessage* msg) {
nisseede5da42017-01-12 05:15:36 -0800613 RTC_DCHECK(msg != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000614 switch (msg->type()) {
615 case STUN_ALLOCATE_REQUEST:
616 HandleAllocateRequest(msg);
617 break;
618 case TURN_REFRESH_REQUEST:
619 HandleRefreshRequest(msg);
620 break;
621 case TURN_SEND_INDICATION:
622 HandleSendIndication(msg);
623 break;
624 case TURN_CREATE_PERMISSION_REQUEST:
625 HandleCreatePermissionRequest(msg);
626 break;
627 case TURN_CHANNEL_BIND_REQUEST:
628 HandleChannelBindRequest(msg);
629 break;
630 default:
631 // Not sure what to do with this, just eat it.
Jonas Olssond7d762d2018-03-28 09:47:51 +0200632 RTC_LOG(LS_WARNING) << ToString()
633 << ": Invalid TURN message type received: "
634 << msg->type();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000635 }
636}
637
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000638void TurnServerAllocation::HandleAllocateRequest(const TurnMessage* msg) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000639 // Copy the important info from the allocate request.
640 transaction_id_ = msg->transaction_id();
641 const StunByteStringAttribute* username_attr =
642 msg->GetByteString(STUN_ATTR_USERNAME);
nisseede5da42017-01-12 05:15:36 -0800643 RTC_DCHECK(username_attr != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000644 username_ = username_attr->GetString();
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000645 const StunByteStringAttribute* origin_attr =
646 msg->GetByteString(STUN_ATTR_ORIGIN);
647 if (origin_attr) {
648 origin_ = origin_attr->GetString();
649 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000650
651 // Figure out the lifetime and start the allocation timer.
652 int lifetime_secs = ComputeLifetime(msg);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700653 thread_->PostDelayed(RTC_FROM_HERE, lifetime_secs * 1000, this,
654 MSG_ALLOCATION_TIMEOUT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000655
Jonas Olssond7d762d2018-03-28 09:47:51 +0200656 RTC_LOG(LS_INFO) << ToString()
657 << ": Created allocation with lifetime=" << lifetime_secs;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000658
659 // We've already validated all the important bits; just send a response here.
660 TurnMessage response;
661 InitResponse(msg, &response);
662
zsteinf42cc9d2017-03-27 16:17:19 -0700663 auto mapped_addr_attr = rtc::MakeUnique<StunXorAddressAttribute>(
664 STUN_ATTR_XOR_MAPPED_ADDRESS, conn_.src());
665 auto relayed_addr_attr = rtc::MakeUnique<StunXorAddressAttribute>(
666 STUN_ATTR_XOR_RELAYED_ADDRESS, external_socket_->GetLocalAddress());
667 auto lifetime_attr =
668 rtc::MakeUnique<StunUInt32Attribute>(STUN_ATTR_LIFETIME, lifetime_secs);
669 response.AddAttribute(std::move(mapped_addr_attr));
670 response.AddAttribute(std::move(relayed_addr_attr));
671 response.AddAttribute(std::move(lifetime_attr));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000672
673 SendResponse(&response);
674}
675
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000676void TurnServerAllocation::HandleRefreshRequest(const TurnMessage* msg) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000677 // Figure out the new lifetime.
678 int lifetime_secs = ComputeLifetime(msg);
679
680 // Reset the expiration timer.
681 thread_->Clear(this, MSG_ALLOCATION_TIMEOUT);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700682 thread_->PostDelayed(RTC_FROM_HERE, lifetime_secs * 1000, this,
683 MSG_ALLOCATION_TIMEOUT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000684
Jonas Olssond7d762d2018-03-28 09:47:51 +0200685 RTC_LOG(LS_INFO) << ToString()
686 << ": Refreshed allocation, lifetime=" << lifetime_secs;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000687
688 // Send a success response with a LIFETIME attribute.
689 TurnMessage response;
690 InitResponse(msg, &response);
691
zsteinf42cc9d2017-03-27 16:17:19 -0700692 auto lifetime_attr =
693 rtc::MakeUnique<StunUInt32Attribute>(STUN_ATTR_LIFETIME, lifetime_secs);
694 response.AddAttribute(std::move(lifetime_attr));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000695
696 SendResponse(&response);
697}
698
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000699void TurnServerAllocation::HandleSendIndication(const TurnMessage* msg) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000700 // Check mandatory attributes.
701 const StunByteStringAttribute* data_attr = msg->GetByteString(STUN_ATTR_DATA);
702 const StunAddressAttribute* peer_attr =
703 msg->GetAddress(STUN_ATTR_XOR_PEER_ADDRESS);
704 if (!data_attr || !peer_attr) {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200705 RTC_LOG(LS_WARNING) << ToString()
706 << ": Received invalid send indication";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000707 return;
708 }
709
710 // If a permission exists, send the data on to the peer.
711 if (HasPermission(peer_attr->GetAddress().ipaddr())) {
712 SendExternal(data_attr->bytes(), data_attr->length(),
713 peer_attr->GetAddress());
714 } else {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200715 RTC_LOG(LS_WARNING) << ToString()
716 << ": Received send indication without permission"
717 " peer="
Jonas Olssonabbe8412018-04-03 13:40:05 +0200718 << peer_attr->GetAddress().ToString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000719 }
720}
721
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000722void TurnServerAllocation::HandleCreatePermissionRequest(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000723 const TurnMessage* msg) {
724 // Check mandatory attributes.
725 const StunAddressAttribute* peer_attr =
726 msg->GetAddress(STUN_ATTR_XOR_PEER_ADDRESS);
727 if (!peer_attr) {
728 SendBadRequestResponse(msg);
729 return;
730 }
731
deadbeef376e1232015-11-25 09:00:08 -0800732 if (server_->reject_private_addresses_ &&
733 rtc::IPIsPrivate(peer_attr->GetAddress().ipaddr())) {
734 SendErrorResponse(msg, STUN_ERROR_FORBIDDEN, STUN_ERROR_REASON_FORBIDDEN);
735 return;
736 }
737
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000738 // Add this permission.
739 AddPermission(peer_attr->GetAddress().ipaddr());
740
Jonas Olssond7d762d2018-03-28 09:47:51 +0200741 RTC_LOG(LS_INFO) << ToString()
Jonas Olssonabbe8412018-04-03 13:40:05 +0200742 << ": Created permission, peer="
743 << peer_attr->GetAddress().ToString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000744
745 // Send a success response.
746 TurnMessage response;
747 InitResponse(msg, &response);
748 SendResponse(&response);
749}
750
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000751void TurnServerAllocation::HandleChannelBindRequest(const TurnMessage* msg) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000752 // Check mandatory attributes.
753 const StunUInt32Attribute* channel_attr =
754 msg->GetUInt32(STUN_ATTR_CHANNEL_NUMBER);
755 const StunAddressAttribute* peer_attr =
756 msg->GetAddress(STUN_ATTR_XOR_PEER_ADDRESS);
757 if (!channel_attr || !peer_attr) {
758 SendBadRequestResponse(msg);
759 return;
760 }
761
762 // Check that channel id is valid.
763 int channel_id = channel_attr->value() >> 16;
764 if (channel_id < kMinChannelNumber || channel_id > kMaxChannelNumber) {
765 SendBadRequestResponse(msg);
766 return;
767 }
768
769 // Check that this channel id isn't bound to another transport address, and
770 // that this transport address isn't bound to another channel id.
771 Channel* channel1 = FindChannel(channel_id);
772 Channel* channel2 = FindChannel(peer_attr->GetAddress());
773 if (channel1 != channel2) {
774 SendBadRequestResponse(msg);
775 return;
776 }
777
778 // Add or refresh this channel.
779 if (!channel1) {
780 channel1 = new Channel(thread_, channel_id, peer_attr->GetAddress());
781 channel1->SignalDestroyed.connect(this,
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000782 &TurnServerAllocation::OnChannelDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000783 channels_.push_back(channel1);
784 } else {
785 channel1->Refresh();
786 }
787
788 // Channel binds also refresh permissions.
789 AddPermission(peer_attr->GetAddress().ipaddr());
790
Jonas Olssond7d762d2018-03-28 09:47:51 +0200791 RTC_LOG(LS_INFO) << ToString()
792 << ": Bound channel, id=" << channel_id
Jonas Olssonabbe8412018-04-03 13:40:05 +0200793 << ", peer=" << peer_attr->GetAddress().ToString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000794
795 // Send a success response.
796 TurnMessage response;
797 InitResponse(msg, &response);
798 SendResponse(&response);
799}
800
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000801void TurnServerAllocation::HandleChannelData(const char* data, size_t size) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000802 // Extract the channel number from the data.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200803 uint16_t channel_id = rtc::GetBE16(data);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000804 Channel* channel = FindChannel(channel_id);
805 if (channel) {
806 // Send the data to the peer address.
807 SendExternal(data + TURN_CHANNEL_HEADER_SIZE,
808 size - TURN_CHANNEL_HEADER_SIZE, channel->peer());
809 } else {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200810 RTC_LOG(LS_WARNING) << ToString()
811 << ": Received channel data for invalid channel, id="
812 << channel_id;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000813 }
814}
815
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000816void TurnServerAllocation::OnExternalPacket(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000817 rtc::AsyncPacketSocket* socket,
818 const char* data, size_t size,
819 const rtc::SocketAddress& addr,
820 const rtc::PacketTime& packet_time) {
nisseede5da42017-01-12 05:15:36 -0800821 RTC_DCHECK(external_socket_.get() == socket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000822 Channel* channel = FindChannel(addr);
823 if (channel) {
824 // There is a channel bound to this address. Send as a channel message.
jbauchf1f87202016-03-30 06:43:37 -0700825 rtc::ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000826 buf.WriteUInt16(channel->id());
Peter Boström0c4e06b2015-10-07 12:23:21 +0200827 buf.WriteUInt16(static_cast<uint16_t>(size));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000828 buf.WriteBytes(data, size);
829 server_->Send(&conn_, buf);
Taylor Brandstetteref184702016-06-23 17:35:47 -0700830 } else if (!server_->enable_permission_checks_ ||
831 HasPermission(addr.ipaddr())) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000832 // No channel, but a permission exists. Send as a data indication.
833 TurnMessage msg;
834 msg.SetType(TURN_DATA_INDICATION);
835 msg.SetTransactionID(
836 rtc::CreateRandomString(kStunTransactionIdLength));
zsteinf42cc9d2017-03-27 16:17:19 -0700837 msg.AddAttribute(rtc::MakeUnique<StunXorAddressAttribute>(
nissecc99bc22017-02-02 01:31:30 -0800838 STUN_ATTR_XOR_PEER_ADDRESS, addr));
zsteinf42cc9d2017-03-27 16:17:19 -0700839 msg.AddAttribute(
840 rtc::MakeUnique<StunByteStringAttribute>(STUN_ATTR_DATA, data, size));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000841 server_->SendStun(&conn_, &msg);
842 } else {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200843 RTC_LOG(LS_WARNING)
844 << ToString()
Jonas Olssonabbe8412018-04-03 13:40:05 +0200845 << ": Received external packet without permission, peer="
846 << addr.ToString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000847 }
848}
849
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000850int TurnServerAllocation::ComputeLifetime(const TurnMessage* msg) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000851 // Return the smaller of our default lifetime and the requested lifetime.
honghaiz34b11eb2016-03-16 08:55:44 -0700852 int lifetime = kDefaultAllocationTimeout / 1000; // convert to seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000853 const StunUInt32Attribute* lifetime_attr = msg->GetUInt32(STUN_ATTR_LIFETIME);
honghaiz34b11eb2016-03-16 08:55:44 -0700854 if (lifetime_attr && static_cast<int>(lifetime_attr->value()) < lifetime) {
855 lifetime = static_cast<int>(lifetime_attr->value());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000856 }
857 return lifetime;
858}
859
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000860bool TurnServerAllocation::HasPermission(const rtc::IPAddress& addr) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000861 return (FindPermission(addr) != NULL);
862}
863
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000864void TurnServerAllocation::AddPermission(const rtc::IPAddress& addr) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000865 Permission* perm = FindPermission(addr);
866 if (!perm) {
867 perm = new Permission(thread_, addr);
868 perm->SignalDestroyed.connect(
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000869 this, &TurnServerAllocation::OnPermissionDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000870 perms_.push_back(perm);
871 } else {
872 perm->Refresh();
873 }
874}
875
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000876TurnServerAllocation::Permission* TurnServerAllocation::FindPermission(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000877 const rtc::IPAddress& addr) const {
878 for (PermissionList::const_iterator it = perms_.begin();
879 it != perms_.end(); ++it) {
880 if ((*it)->peer() == addr)
881 return *it;
882 }
883 return NULL;
884}
885
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000886TurnServerAllocation::Channel* TurnServerAllocation::FindChannel(
887 int channel_id) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000888 for (ChannelList::const_iterator it = channels_.begin();
889 it != channels_.end(); ++it) {
890 if ((*it)->id() == channel_id)
891 return *it;
892 }
893 return NULL;
894}
895
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000896TurnServerAllocation::Channel* TurnServerAllocation::FindChannel(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000897 const rtc::SocketAddress& addr) const {
898 for (ChannelList::const_iterator it = channels_.begin();
899 it != channels_.end(); ++it) {
900 if ((*it)->peer() == addr)
901 return *it;
902 }
903 return NULL;
904}
905
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000906void TurnServerAllocation::SendResponse(TurnMessage* msg) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000907 // Success responses always have M-I.
908 msg->AddMessageIntegrity(key_);
909 server_->SendStun(&conn_, msg);
910}
911
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000912void TurnServerAllocation::SendBadRequestResponse(const TurnMessage* req) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000913 SendErrorResponse(req, STUN_ERROR_BAD_REQUEST, STUN_ERROR_REASON_BAD_REQUEST);
914}
915
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000916void TurnServerAllocation::SendErrorResponse(const TurnMessage* req, int code,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000917 const std::string& reason) {
918 server_->SendErrorResponse(&conn_, req, code, reason);
919}
920
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000921void TurnServerAllocation::SendExternal(const void* data, size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000922 const rtc::SocketAddress& peer) {
923 rtc::PacketOptions options;
924 external_socket_->SendTo(data, size, peer, options);
925}
926
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000927void TurnServerAllocation::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -0800928 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_TIMEOUT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000929 SignalDestroyed(this);
930 delete this;
931}
932
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000933void TurnServerAllocation::OnPermissionDestroyed(Permission* perm) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000934 PermissionList::iterator it = std::find(perms_.begin(), perms_.end(), perm);
nisseede5da42017-01-12 05:15:36 -0800935 RTC_DCHECK(it != perms_.end());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000936 perms_.erase(it);
937}
938
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000939void TurnServerAllocation::OnChannelDestroyed(Channel* channel) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000940 ChannelList::iterator it =
941 std::find(channels_.begin(), channels_.end(), channel);
nisseede5da42017-01-12 05:15:36 -0800942 RTC_DCHECK(it != channels_.end());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000943 channels_.erase(it);
944}
945
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000946TurnServerAllocation::Permission::Permission(rtc::Thread* thread,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000947 const rtc::IPAddress& peer)
948 : thread_(thread), peer_(peer) {
949 Refresh();
950}
951
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000952TurnServerAllocation::Permission::~Permission() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000953 thread_->Clear(this, MSG_ALLOCATION_TIMEOUT);
954}
955
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000956void TurnServerAllocation::Permission::Refresh() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000957 thread_->Clear(this, MSG_ALLOCATION_TIMEOUT);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700958 thread_->PostDelayed(RTC_FROM_HERE, kPermissionTimeout, this,
959 MSG_ALLOCATION_TIMEOUT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000960}
961
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000962void TurnServerAllocation::Permission::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -0800963 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_TIMEOUT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000964 SignalDestroyed(this);
965 delete this;
966}
967
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000968TurnServerAllocation::Channel::Channel(rtc::Thread* thread, int id,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000969 const rtc::SocketAddress& peer)
970 : thread_(thread), id_(id), peer_(peer) {
971 Refresh();
972}
973
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000974TurnServerAllocation::Channel::~Channel() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000975 thread_->Clear(this, MSG_ALLOCATION_TIMEOUT);
976}
977
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000978void TurnServerAllocation::Channel::Refresh() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000979 thread_->Clear(this, MSG_ALLOCATION_TIMEOUT);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700980 thread_->PostDelayed(RTC_FROM_HERE, kChannelTimeout, this,
981 MSG_ALLOCATION_TIMEOUT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000982}
983
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000984void TurnServerAllocation::Channel::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -0800985 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_TIMEOUT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000986 SignalDestroyed(this);
987 delete this;
988}
989
990} // namespace cricket