blob: 022113e7e746a0c59076b8b062cb310992a94e30 [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
Karl Wiberg918f50c2018-07-05 11:40:33 +020016#include "absl/memory/memory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020017#include "p2p/base/asyncstuntcpsocket.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020018#include "p2p/base/packetsocketfactory.h"
19#include "p2p/base/stun.h"
20#include "rtc_base/bind.h"
21#include "rtc_base/bytebuffer.h"
22#include "rtc_base/checks.h"
23#include "rtc_base/helpers.h"
24#include "rtc_base/logging.h"
25#include "rtc_base/messagedigest.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "rtc_base/socketadapters.h"
27#include "rtc_base/stringencode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020028#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "rtc_base/thread.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000030
31namespace cricket {
32
33// TODO(juberti): Move this all to a future turnmessage.h
Steve Anton6c38cc72017-11-29 10:25:58 -080034// static const int IPPROTO_UDP = 17;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000035static const int kNonceTimeout = 60 * 60 * 1000; // 60 minutes
36static const int kDefaultAllocationTimeout = 10 * 60 * 1000; // 10 minutes
37static const int kPermissionTimeout = 5 * 60 * 1000; // 5 minutes
38static const int kChannelTimeout = 10 * 60 * 1000; // 10 minutes
39
40static const int kMinChannelNumber = 0x4000;
41static const int kMaxChannelNumber = 0x7FFF;
42
43static const size_t kNonceKeySize = 16;
honghaiz34b11eb2016-03-16 08:55:44 -070044static const size_t kNonceSize = 48;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000045
46static const size_t TURN_CHANNEL_HEADER_SIZE = 4U;
47
48// TODO(mallinath) - Move these to a common place.
Peter Boström0c4e06b2015-10-07 12:23:21 +020049inline bool IsTurnChannelData(uint16_t msg_type) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000050 // The first two bits of a channel data message are 0b01.
51 return ((msg_type & 0xC000) == 0x4000);
52}
53
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +000054// IDs used for posted messages for TurnServerAllocation.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000055enum {
56 MSG_ALLOCATION_TIMEOUT,
57};
58
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000059// Encapsulates a TURN permission.
60// The object is created when a create permission request is received by an
61// allocation, and self-deletes when its lifetime timer expires.
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +000062class TurnServerAllocation::Permission : public rtc::MessageHandler {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000063 public:
64 Permission(rtc::Thread* thread, const rtc::IPAddress& peer);
Steve Antonf2737d22017-10-31 16:27:34 -070065 ~Permission() override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000066
67 const rtc::IPAddress& peer() const { return peer_; }
68 void Refresh();
69
70 sigslot::signal1<Permission*> SignalDestroyed;
71
72 private:
Steve Antonf2737d22017-10-31 16:27:34 -070073 void OnMessage(rtc::Message* msg) override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000074
75 rtc::Thread* thread_;
76 rtc::IPAddress peer_;
77};
78
79// Encapsulates a TURN channel binding.
80// The object is created when a channel bind request is received by an
81// allocation, and self-deletes when its lifetime timer expires.
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +000082class TurnServerAllocation::Channel : public rtc::MessageHandler {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000083 public:
84 Channel(rtc::Thread* thread, int id,
85 const rtc::SocketAddress& peer);
Steve Antonf2737d22017-10-31 16:27:34 -070086 ~Channel() override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000087
88 int id() const { return id_; }
89 const rtc::SocketAddress& peer() const { return peer_; }
90 void Refresh();
91
92 sigslot::signal1<Channel*> SignalDestroyed;
93
94 private:
Steve Antonf2737d22017-10-31 16:27:34 -070095 void OnMessage(rtc::Message* msg) override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000096
97 rtc::Thread* thread_;
98 int id_;
99 rtc::SocketAddress peer_;
100};
101
102static bool InitResponse(const StunMessage* req, StunMessage* resp) {
103 int resp_type = (req) ? GetStunSuccessResponseType(req->type()) : -1;
104 if (resp_type == -1)
105 return false;
106 resp->SetType(resp_type);
107 resp->SetTransactionID(req->transaction_id());
108 return true;
109}
110
111static bool InitErrorResponse(const StunMessage* req, int code,
112 const std::string& reason, StunMessage* resp) {
113 int resp_type = (req) ? GetStunErrorResponseType(req->type()) : -1;
114 if (resp_type == -1)
115 return false;
116 resp->SetType(resp_type);
117 resp->SetTransactionID(req->transaction_id());
Karl Wiberg918f50c2018-07-05 11:40:33 +0200118 resp->AddAttribute(absl::make_unique<cricket::StunErrorCodeAttribute>(
nissecc99bc22017-02-02 01:31:30 -0800119 STUN_ATTR_ERROR_CODE, code, reason));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000120 return true;
121}
122
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000123
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000124TurnServer::TurnServer(rtc::Thread* thread)
125 : thread_(thread),
126 nonce_key_(rtc::CreateRandomString(kNonceKeySize)),
127 auth_hook_(NULL),
128 redirect_hook_(NULL),
129 enable_otu_nonce_(false) {
130}
131
132TurnServer::~TurnServer() {
Seth Hampsonaed71642018-06-11 07:41:32 -0700133 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000134 for (InternalSocketMap::iterator it = server_sockets_.begin();
135 it != server_sockets_.end(); ++it) {
136 rtc::AsyncPacketSocket* socket = it->first;
137 delete socket;
138 }
139
140 for (ServerSocketMap::iterator it = server_listen_sockets_.begin();
141 it != server_listen_sockets_.end(); ++it) {
142 rtc::AsyncSocket* socket = it->first;
143 delete socket;
144 }
145}
146
147void TurnServer::AddInternalSocket(rtc::AsyncPacketSocket* socket,
148 ProtocolType proto) {
Seth Hampsonaed71642018-06-11 07:41:32 -0700149 RTC_DCHECK(thread_checker_.CalledOnValidThread());
nisseede5da42017-01-12 05:15:36 -0800150 RTC_DCHECK(server_sockets_.end() == server_sockets_.find(socket));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000151 server_sockets_[socket] = proto;
152 socket->SignalReadPacket.connect(this, &TurnServer::OnInternalPacket);
153}
154
155void TurnServer::AddInternalServerSocket(rtc::AsyncSocket* socket,
156 ProtocolType proto) {
Seth Hampsonaed71642018-06-11 07:41:32 -0700157 RTC_DCHECK(thread_checker_.CalledOnValidThread());
nisseede5da42017-01-12 05:15:36 -0800158 RTC_DCHECK(server_listen_sockets_.end() ==
159 server_listen_sockets_.find(socket));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000160 server_listen_sockets_[socket] = proto;
161 socket->SignalReadEvent.connect(this, &TurnServer::OnNewInternalConnection);
162}
163
164void TurnServer::SetExternalSocketFactory(
165 rtc::PacketSocketFactory* factory,
166 const rtc::SocketAddress& external_addr) {
Seth Hampsonaed71642018-06-11 07:41:32 -0700167 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000168 external_socket_factory_.reset(factory);
169 external_addr_ = external_addr;
170}
171
172void TurnServer::OnNewInternalConnection(rtc::AsyncSocket* socket) {
Seth Hampsonaed71642018-06-11 07:41:32 -0700173 RTC_DCHECK(thread_checker_.CalledOnValidThread());
nisseede5da42017-01-12 05:15:36 -0800174 RTC_DCHECK(server_listen_sockets_.find(socket) !=
175 server_listen_sockets_.end());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000176 AcceptConnection(socket);
177}
178
179void TurnServer::AcceptConnection(rtc::AsyncSocket* server_socket) {
Seth Hampsonaed71642018-06-11 07:41:32 -0700180 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000181 // Check if someone is trying to connect to us.
182 rtc::SocketAddress accept_addr;
183 rtc::AsyncSocket* accepted_socket = server_socket->Accept(&accept_addr);
184 if (accepted_socket != NULL) {
185 ProtocolType proto = server_listen_sockets_[server_socket];
186 cricket::AsyncStunTCPSocket* tcp_socket =
187 new cricket::AsyncStunTCPSocket(accepted_socket, false);
188
189 tcp_socket->SignalClose.connect(this, &TurnServer::OnInternalSocketClose);
190 // Finally add the socket so it can start communicating with the client.
191 AddInternalSocket(tcp_socket, proto);
192 }
193}
194
195void TurnServer::OnInternalSocketClose(rtc::AsyncPacketSocket* socket,
196 int err) {
Seth Hampsonaed71642018-06-11 07:41:32 -0700197 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000198 DestroyInternalSocket(socket);
199}
200
201void TurnServer::OnInternalPacket(rtc::AsyncPacketSocket* socket,
202 const char* data, size_t size,
203 const rtc::SocketAddress& addr,
204 const rtc::PacketTime& packet_time) {
Seth Hampsonaed71642018-06-11 07:41:32 -0700205 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000206 // Fail if the packet is too small to even contain a channel header.
207 if (size < TURN_CHANNEL_HEADER_SIZE) {
Steve Anton6c38cc72017-11-29 10:25:58 -0800208 return;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000209 }
210 InternalSocketMap::iterator iter = server_sockets_.find(socket);
nisseede5da42017-01-12 05:15:36 -0800211 RTC_DCHECK(iter != server_sockets_.end());
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000212 TurnServerConnection conn(addr, iter->second, socket);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200213 uint16_t msg_type = rtc::GetBE16(data);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000214 if (!IsTurnChannelData(msg_type)) {
215 // This is a STUN message.
216 HandleStunMessage(&conn, data, size);
217 } else {
218 // This is a channel message; let the allocation handle it.
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000219 TurnServerAllocation* allocation = FindAllocation(&conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000220 if (allocation) {
221 allocation->HandleChannelData(data, size);
222 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200223 if (stun_message_observer_ != nullptr) {
224 stun_message_observer_->ReceivedChannelData(data, size);
225 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000226 }
227}
228
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000229void TurnServer::HandleStunMessage(TurnServerConnection* conn, const char* data,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000230 size_t size) {
Seth Hampsonaed71642018-06-11 07:41:32 -0700231 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000232 TurnMessage msg;
jbauchf1f87202016-03-30 06:43:37 -0700233 rtc::ByteBufferReader buf(data, size);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000234 if (!msg.Read(&buf) || (buf.Length() > 0)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100235 RTC_LOG(LS_WARNING) << "Received invalid STUN message";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000236 return;
237 }
238
Jonas Orelandbdcee282017-10-10 14:01:40 +0200239 if (stun_message_observer_ != nullptr) {
240 stun_message_observer_->ReceivedMessage(&msg);
241 }
242
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000243 // If it's a STUN binding request, handle that specially.
244 if (msg.type() == STUN_BINDING_REQUEST) {
245 HandleBindingRequest(conn, &msg);
246 return;
247 }
248
249 if (redirect_hook_ != NULL && msg.type() == STUN_ALLOCATE_REQUEST) {
250 rtc::SocketAddress address;
251 if (redirect_hook_->ShouldRedirect(conn->src(), &address)) {
252 SendErrorResponseWithAlternateServer(
253 conn, &msg, address);
254 return;
255 }
256 }
257
258 // Look up the key that we'll use to validate the M-I. If we have an
259 // existing allocation, the key will already be cached.
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000260 TurnServerAllocation* allocation = FindAllocation(conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000261 std::string key;
262 if (!allocation) {
263 GetKey(&msg, &key);
264 } else {
265 key = allocation->key();
266 }
267
268 // Ensure the message is authorized; only needed for requests.
269 if (IsStunRequestType(msg.type())) {
270 if (!CheckAuthorization(conn, &msg, data, size, key)) {
271 return;
272 }
273 }
274
275 if (!allocation && msg.type() == STUN_ALLOCATE_REQUEST) {
276 HandleAllocateRequest(conn, &msg, key);
277 } else if (allocation &&
278 (msg.type() != STUN_ALLOCATE_REQUEST ||
279 msg.transaction_id() == allocation->transaction_id())) {
280 // This is a non-allocate request, or a retransmit of an allocate.
281 // Check that the username matches the previous username used.
282 if (IsStunRequestType(msg.type()) &&
283 msg.GetByteString(STUN_ATTR_USERNAME)->GetString() !=
284 allocation->username()) {
285 SendErrorResponse(conn, &msg, STUN_ERROR_WRONG_CREDENTIALS,
286 STUN_ERROR_REASON_WRONG_CREDENTIALS);
287 return;
288 }
289 allocation->HandleTurnMessage(&msg);
290 } else {
291 // Allocation mismatch.
292 SendErrorResponse(conn, &msg, STUN_ERROR_ALLOCATION_MISMATCH,
293 STUN_ERROR_REASON_ALLOCATION_MISMATCH);
294 }
295}
296
297bool TurnServer::GetKey(const StunMessage* msg, std::string* key) {
Seth Hampsonaed71642018-06-11 07:41:32 -0700298 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000299 const StunByteStringAttribute* username_attr =
300 msg->GetByteString(STUN_ATTR_USERNAME);
301 if (!username_attr) {
302 return false;
303 }
304
305 std::string username = username_attr->GetString();
306 return (auth_hook_ != NULL && auth_hook_->GetKey(username, realm_, key));
307}
308
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000309bool TurnServer::CheckAuthorization(TurnServerConnection* conn,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000310 const StunMessage* msg,
311 const char* data, size_t size,
312 const std::string& key) {
Seth Hampsonaed71642018-06-11 07:41:32 -0700313 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000314 // RFC 5389, 10.2.2.
nisseede5da42017-01-12 05:15:36 -0800315 RTC_DCHECK(IsStunRequestType(msg->type()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000316 const StunByteStringAttribute* mi_attr =
317 msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY);
318 const StunByteStringAttribute* username_attr =
319 msg->GetByteString(STUN_ATTR_USERNAME);
320 const StunByteStringAttribute* realm_attr =
321 msg->GetByteString(STUN_ATTR_REALM);
322 const StunByteStringAttribute* nonce_attr =
323 msg->GetByteString(STUN_ATTR_NONCE);
324
325 // Fail if no M-I.
326 if (!mi_attr) {
327 SendErrorResponseWithRealmAndNonce(conn, msg, STUN_ERROR_UNAUTHORIZED,
328 STUN_ERROR_REASON_UNAUTHORIZED);
329 return false;
330 }
331
332 // Fail if there is M-I but no username, nonce, or realm.
333 if (!username_attr || !realm_attr || !nonce_attr) {
334 SendErrorResponse(conn, msg, STUN_ERROR_BAD_REQUEST,
335 STUN_ERROR_REASON_BAD_REQUEST);
336 return false;
337 }
338
339 // Fail if bad nonce.
340 if (!ValidateNonce(nonce_attr->GetString())) {
341 SendErrorResponseWithRealmAndNonce(conn, msg, STUN_ERROR_STALE_NONCE,
342 STUN_ERROR_REASON_STALE_NONCE);
343 return false;
344 }
345
346 // Fail if bad username or M-I.
347 // We need |data| and |size| for the call to ValidateMessageIntegrity.
348 if (key.empty() || !StunMessage::ValidateMessageIntegrity(data, size, key)) {
349 SendErrorResponseWithRealmAndNonce(conn, msg, STUN_ERROR_UNAUTHORIZED,
350 STUN_ERROR_REASON_UNAUTHORIZED);
351 return false;
352 }
353
354 // Fail if one-time-use nonce feature is enabled.
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000355 TurnServerAllocation* allocation = FindAllocation(conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000356 if (enable_otu_nonce_ && allocation &&
357 allocation->last_nonce() == nonce_attr->GetString()) {
358 SendErrorResponseWithRealmAndNonce(conn, msg, STUN_ERROR_STALE_NONCE,
359 STUN_ERROR_REASON_STALE_NONCE);
360 return false;
361 }
362
363 if (allocation) {
364 allocation->set_last_nonce(nonce_attr->GetString());
365 }
366 // Success.
367 return true;
368}
369
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000370void TurnServer::HandleBindingRequest(TurnServerConnection* conn,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000371 const StunMessage* req) {
Seth Hampsonaed71642018-06-11 07:41:32 -0700372 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000373 StunMessage response;
374 InitResponse(req, &response);
375
376 // Tell the user the address that we received their request from.
Karl Wiberg918f50c2018-07-05 11:40:33 +0200377 auto mapped_addr_attr = absl::make_unique<StunXorAddressAttribute>(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000378 STUN_ATTR_XOR_MAPPED_ADDRESS, conn->src());
zsteinf42cc9d2017-03-27 16:17:19 -0700379 response.AddAttribute(std::move(mapped_addr_attr));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000380
381 SendStun(conn, &response);
382}
383
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000384void TurnServer::HandleAllocateRequest(TurnServerConnection* conn,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000385 const TurnMessage* msg,
386 const std::string& key) {
Seth Hampsonaed71642018-06-11 07:41:32 -0700387 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000388 // Check the parameters in the request.
389 const StunUInt32Attribute* transport_attr =
390 msg->GetUInt32(STUN_ATTR_REQUESTED_TRANSPORT);
391 if (!transport_attr) {
392 SendErrorResponse(conn, msg, STUN_ERROR_BAD_REQUEST,
393 STUN_ERROR_REASON_BAD_REQUEST);
394 return;
395 }
396
397 // Only UDP is supported right now.
398 int proto = transport_attr->value() >> 24;
399 if (proto != IPPROTO_UDP) {
400 SendErrorResponse(conn, msg, STUN_ERROR_UNSUPPORTED_PROTOCOL,
401 STUN_ERROR_REASON_UNSUPPORTED_PROTOCOL);
402 return;
403 }
404
405 // Create the allocation and let it send the success response.
406 // If the actual socket allocation fails, send an internal error.
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000407 TurnServerAllocation* alloc = CreateAllocation(conn, proto, key);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000408 if (alloc) {
409 alloc->HandleTurnMessage(msg);
410 } else {
411 SendErrorResponse(conn, msg, STUN_ERROR_SERVER_ERROR,
412 "Failed to allocate socket");
413 }
414}
415
honghaiz34b11eb2016-03-16 08:55:44 -0700416std::string TurnServer::GenerateNonce(int64_t now) const {
Seth Hampsonaed71642018-06-11 07:41:32 -0700417 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000418 // Generate a nonce of the form hex(now + HMAC-MD5(nonce_key_, now))
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000419 std::string input(reinterpret_cast<const char*>(&now), sizeof(now));
420 std::string nonce = rtc::hex_encode(input.c_str(), input.size());
421 nonce += rtc::ComputeHmac(rtc::DIGEST_MD5, nonce_key_, input);
nisseede5da42017-01-12 05:15:36 -0800422 RTC_DCHECK(nonce.size() == kNonceSize);
honghaiz34b11eb2016-03-16 08:55:44 -0700423
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000424 return nonce;
425}
426
427bool TurnServer::ValidateNonce(const std::string& nonce) const {
Seth Hampsonaed71642018-06-11 07:41:32 -0700428 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000429 // Check the size.
430 if (nonce.size() != kNonceSize) {
431 return false;
432 }
433
434 // Decode the timestamp.
honghaiz34b11eb2016-03-16 08:55:44 -0700435 int64_t then;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000436 char* p = reinterpret_cast<char*>(&then);
437 size_t len = rtc::hex_decode(p, sizeof(then),
438 nonce.substr(0, sizeof(then) * 2));
439 if (len != sizeof(then)) {
440 return false;
441 }
442
443 // Verify the HMAC.
444 if (nonce.substr(sizeof(then) * 2) != rtc::ComputeHmac(
445 rtc::DIGEST_MD5, nonce_key_, std::string(p, sizeof(then)))) {
446 return false;
447 }
448
449 // Validate the timestamp.
nisse1bffc1d2016-05-02 08:18:55 -0700450 return rtc::TimeMillis() - then < kNonceTimeout;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000451}
452
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000453TurnServerAllocation* TurnServer::FindAllocation(TurnServerConnection* conn) {
Seth Hampsonaed71642018-06-11 07:41:32 -0700454 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000455 AllocationMap::const_iterator it = allocations_.find(*conn);
deadbeef97943662016-07-12 11:04:50 -0700456 return (it != allocations_.end()) ? it->second.get() : nullptr;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000457}
458
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000459TurnServerAllocation* TurnServer::CreateAllocation(TurnServerConnection* conn,
460 int proto,
461 const std::string& key) {
Seth Hampsonaed71642018-06-11 07:41:32 -0700462 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000463 rtc::AsyncPacketSocket* external_socket = (external_socket_factory_) ?
464 external_socket_factory_->CreateUdpSocket(external_addr_, 0, 0) : NULL;
465 if (!external_socket) {
466 return NULL;
467 }
468
469 // The Allocation takes ownership of the socket.
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000470 TurnServerAllocation* allocation = new TurnServerAllocation(this,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000471 thread_, *conn, external_socket, key);
472 allocation->SignalDestroyed.connect(this, &TurnServer::OnAllocationDestroyed);
deadbeef97943662016-07-12 11:04:50 -0700473 allocations_[*conn].reset(allocation);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000474 return allocation;
475}
476
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000477void TurnServer::SendErrorResponse(TurnServerConnection* conn,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000478 const StunMessage* req,
479 int code, const std::string& reason) {
Seth Hampsonaed71642018-06-11 07:41:32 -0700480 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000481 TurnMessage resp;
482 InitErrorResponse(req, code, reason, &resp);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100483 RTC_LOG(LS_INFO) << "Sending error response, type=" << resp.type()
484 << ", code=" << code << ", reason=" << reason;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000485 SendStun(conn, &resp);
486}
487
488void TurnServer::SendErrorResponseWithRealmAndNonce(
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000489 TurnServerConnection* conn, const StunMessage* msg,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000490 int code, const std::string& reason) {
Seth Hampsonaed71642018-06-11 07:41:32 -0700491 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000492 TurnMessage resp;
493 InitErrorResponse(msg, code, reason, &resp);
honghaizc463e202016-02-01 15:19:08 -0800494
nisse1bffc1d2016-05-02 08:18:55 -0700495 int64_t timestamp = rtc::TimeMillis();
honghaizc463e202016-02-01 15:19:08 -0800496 if (ts_for_next_nonce_) {
497 timestamp = ts_for_next_nonce_;
498 ts_for_next_nonce_ = 0;
499 }
Karl Wiberg918f50c2018-07-05 11:40:33 +0200500 resp.AddAttribute(absl::make_unique<StunByteStringAttribute>(
zsteinf42cc9d2017-03-27 16:17:19 -0700501 STUN_ATTR_NONCE, GenerateNonce(timestamp)));
nissecc99bc22017-02-02 01:31:30 -0800502 resp.AddAttribute(
Karl Wiberg918f50c2018-07-05 11:40:33 +0200503 absl::make_unique<StunByteStringAttribute>(STUN_ATTR_REALM, realm_));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000504 SendStun(conn, &resp);
505}
506
507void TurnServer::SendErrorResponseWithAlternateServer(
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000508 TurnServerConnection* conn, const StunMessage* msg,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000509 const rtc::SocketAddress& addr) {
Seth Hampsonaed71642018-06-11 07:41:32 -0700510 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000511 TurnMessage resp;
512 InitErrorResponse(msg, STUN_ERROR_TRY_ALTERNATE,
513 STUN_ERROR_REASON_TRY_ALTERNATE_SERVER, &resp);
Karl Wiberg918f50c2018-07-05 11:40:33 +0200514 resp.AddAttribute(absl::make_unique<StunAddressAttribute>(
515 STUN_ATTR_ALTERNATE_SERVER, addr));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000516 SendStun(conn, &resp);
517}
518
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000519void TurnServer::SendStun(TurnServerConnection* conn, StunMessage* msg) {
Seth Hampsonaed71642018-06-11 07:41:32 -0700520 RTC_DCHECK(thread_checker_.CalledOnValidThread());
jbauchf1f87202016-03-30 06:43:37 -0700521 rtc::ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000522 // Add a SOFTWARE attribute if one is set.
523 if (!software_.empty()) {
Karl Wiberg918f50c2018-07-05 11:40:33 +0200524 msg->AddAttribute(absl::make_unique<StunByteStringAttribute>(
zsteinf42cc9d2017-03-27 16:17:19 -0700525 STUN_ATTR_SOFTWARE, software_));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000526 }
527 msg->Write(&buf);
528 Send(conn, buf);
529}
530
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000531void TurnServer::Send(TurnServerConnection* conn,
jbauchf1f87202016-03-30 06:43:37 -0700532 const rtc::ByteBufferWriter& buf) {
Seth Hampsonaed71642018-06-11 07:41:32 -0700533 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000534 rtc::PacketOptions options;
535 conn->socket()->SendTo(buf.Data(), buf.Length(), conn->src(), options);
536}
537
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000538void TurnServer::OnAllocationDestroyed(TurnServerAllocation* allocation) {
Seth Hampsonaed71642018-06-11 07:41:32 -0700539 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000540 // Removing the internal socket if the connection is not udp.
541 rtc::AsyncPacketSocket* socket = allocation->conn()->socket();
542 InternalSocketMap::iterator iter = server_sockets_.find(socket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000543 // Skip if the socket serving this allocation is UDP, as this will be shared
544 // by all allocations.
Taylor Brandstetter716d07a2016-06-27 14:07:41 -0700545 // Note: We may not find a socket if it's a TCP socket that was closed, and
546 // the allocation is only now timing out.
547 if (iter != server_sockets_.end() && iter->second != cricket::PROTO_UDP) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000548 DestroyInternalSocket(socket);
549 }
550
551 AllocationMap::iterator it = allocations_.find(*(allocation->conn()));
deadbeef97943662016-07-12 11:04:50 -0700552 if (it != allocations_.end()) {
553 it->second.release();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000554 allocations_.erase(it);
deadbeef97943662016-07-12 11:04:50 -0700555 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000556}
557
558void TurnServer::DestroyInternalSocket(rtc::AsyncPacketSocket* socket) {
Seth Hampsonaed71642018-06-11 07:41:32 -0700559 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000560 InternalSocketMap::iterator iter = server_sockets_.find(socket);
561 if (iter != server_sockets_.end()) {
562 rtc::AsyncPacketSocket* socket = iter->first;
Qingsi Wang0ea75152018-07-02 10:48:25 -0700563 socket->SignalReadPacket.disconnect(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000564 server_sockets_.erase(iter);
deadbeef824f5862016-08-24 15:06:53 -0700565 // We must destroy the socket async to avoid invalidating the sigslot
566 // callback list iterator inside a sigslot callback. (In other words,
567 // deleting an object from within a callback from that object).
568 sockets_to_delete_.push_back(
569 std::unique_ptr<rtc::AsyncPacketSocket>(socket));
570 invoker_.AsyncInvoke<void>(RTC_FROM_HERE, rtc::Thread::Current(),
571 rtc::Bind(&TurnServer::FreeSockets, this));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000572 }
573}
574
deadbeef824f5862016-08-24 15:06:53 -0700575void TurnServer::FreeSockets() {
Seth Hampsonaed71642018-06-11 07:41:32 -0700576 RTC_DCHECK(thread_checker_.CalledOnValidThread());
deadbeef824f5862016-08-24 15:06:53 -0700577 sockets_to_delete_.clear();
578}
579
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000580TurnServerConnection::TurnServerConnection(const rtc::SocketAddress& src,
581 ProtocolType proto,
582 rtc::AsyncPacketSocket* socket)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000583 : src_(src),
584 dst_(socket->GetRemoteAddress()),
585 proto_(proto),
586 socket_(socket) {
587}
588
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000589bool TurnServerConnection::operator==(const TurnServerConnection& c) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000590 return src_ == c.src_ && dst_ == c.dst_ && proto_ == c.proto_;
591}
592
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000593bool TurnServerConnection::operator<(const TurnServerConnection& c) const {
Taylor Brandstetter734262c2016-08-01 16:37:14 -0700594 return std::tie(src_, dst_, proto_) < std::tie(c.src_, c.dst_, c.proto_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000595}
596
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000597std::string TurnServerConnection::ToString() const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000598 const char* const kProtos[] = {
599 "unknown", "udp", "tcp", "ssltcp"
600 };
Jonas Olsson366a50c2018-09-06 13:41:30 +0200601 rtc::StringBuilder ost;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000602 ost << src_.ToString() << "-" << dst_.ToString() << ":"<< kProtos[proto_];
Jonas Olsson84df1c72018-09-14 16:59:32 +0200603 return ost.Release();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000604}
605
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000606TurnServerAllocation::TurnServerAllocation(TurnServer* server,
607 rtc::Thread* thread,
608 const TurnServerConnection& conn,
609 rtc::AsyncPacketSocket* socket,
610 const std::string& key)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000611 : server_(server),
612 thread_(thread),
613 conn_(conn),
614 external_socket_(socket),
615 key_(key) {
616 external_socket_->SignalReadPacket.connect(
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000617 this, &TurnServerAllocation::OnExternalPacket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000618}
619
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000620TurnServerAllocation::~TurnServerAllocation() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000621 for (ChannelList::iterator it = channels_.begin();
622 it != channels_.end(); ++it) {
623 delete *it;
624 }
625 for (PermissionList::iterator it = perms_.begin();
626 it != perms_.end(); ++it) {
627 delete *it;
628 }
629 thread_->Clear(this, MSG_ALLOCATION_TIMEOUT);
Jonas Olssond7d762d2018-03-28 09:47:51 +0200630 RTC_LOG(LS_INFO) << ToString() << ": Allocation destroyed";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000631}
632
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000633std::string TurnServerAllocation::ToString() const {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200634 rtc::StringBuilder ost;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000635 ost << "Alloc[" << conn_.ToString() << "]";
Jonas Olsson84df1c72018-09-14 16:59:32 +0200636 return ost.Release();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000637}
638
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000639void TurnServerAllocation::HandleTurnMessage(const TurnMessage* msg) {
nisseede5da42017-01-12 05:15:36 -0800640 RTC_DCHECK(msg != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000641 switch (msg->type()) {
642 case STUN_ALLOCATE_REQUEST:
643 HandleAllocateRequest(msg);
644 break;
645 case TURN_REFRESH_REQUEST:
646 HandleRefreshRequest(msg);
647 break;
648 case TURN_SEND_INDICATION:
649 HandleSendIndication(msg);
650 break;
651 case TURN_CREATE_PERMISSION_REQUEST:
652 HandleCreatePermissionRequest(msg);
653 break;
654 case TURN_CHANNEL_BIND_REQUEST:
655 HandleChannelBindRequest(msg);
656 break;
657 default:
658 // Not sure what to do with this, just eat it.
Jonas Olssond7d762d2018-03-28 09:47:51 +0200659 RTC_LOG(LS_WARNING) << ToString()
660 << ": Invalid TURN message type received: "
661 << msg->type();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000662 }
663}
664
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000665void TurnServerAllocation::HandleAllocateRequest(const TurnMessage* msg) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000666 // Copy the important info from the allocate request.
667 transaction_id_ = msg->transaction_id();
668 const StunByteStringAttribute* username_attr =
669 msg->GetByteString(STUN_ATTR_USERNAME);
nisseede5da42017-01-12 05:15:36 -0800670 RTC_DCHECK(username_attr != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000671 username_ = username_attr->GetString();
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000672 const StunByteStringAttribute* origin_attr =
673 msg->GetByteString(STUN_ATTR_ORIGIN);
674 if (origin_attr) {
675 origin_ = origin_attr->GetString();
676 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000677
678 // Figure out the lifetime and start the allocation timer.
679 int lifetime_secs = ComputeLifetime(msg);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700680 thread_->PostDelayed(RTC_FROM_HERE, lifetime_secs * 1000, this,
681 MSG_ALLOCATION_TIMEOUT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000682
Jonas Olssond7d762d2018-03-28 09:47:51 +0200683 RTC_LOG(LS_INFO) << ToString()
684 << ": Created allocation with lifetime=" << lifetime_secs;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000685
686 // We've already validated all the important bits; just send a response here.
687 TurnMessage response;
688 InitResponse(msg, &response);
689
Karl Wiberg918f50c2018-07-05 11:40:33 +0200690 auto mapped_addr_attr = absl::make_unique<StunXorAddressAttribute>(
zsteinf42cc9d2017-03-27 16:17:19 -0700691 STUN_ATTR_XOR_MAPPED_ADDRESS, conn_.src());
Karl Wiberg918f50c2018-07-05 11:40:33 +0200692 auto relayed_addr_attr = absl::make_unique<StunXorAddressAttribute>(
zsteinf42cc9d2017-03-27 16:17:19 -0700693 STUN_ATTR_XOR_RELAYED_ADDRESS, external_socket_->GetLocalAddress());
694 auto lifetime_attr =
Karl Wiberg918f50c2018-07-05 11:40:33 +0200695 absl::make_unique<StunUInt32Attribute>(STUN_ATTR_LIFETIME, lifetime_secs);
zsteinf42cc9d2017-03-27 16:17:19 -0700696 response.AddAttribute(std::move(mapped_addr_attr));
697 response.AddAttribute(std::move(relayed_addr_attr));
698 response.AddAttribute(std::move(lifetime_attr));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000699
700 SendResponse(&response);
701}
702
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000703void TurnServerAllocation::HandleRefreshRequest(const TurnMessage* msg) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000704 // Figure out the new lifetime.
705 int lifetime_secs = ComputeLifetime(msg);
706
707 // Reset the expiration timer.
708 thread_->Clear(this, MSG_ALLOCATION_TIMEOUT);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700709 thread_->PostDelayed(RTC_FROM_HERE, lifetime_secs * 1000, this,
710 MSG_ALLOCATION_TIMEOUT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000711
Jonas Olssond7d762d2018-03-28 09:47:51 +0200712 RTC_LOG(LS_INFO) << ToString()
713 << ": Refreshed allocation, lifetime=" << lifetime_secs;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000714
715 // Send a success response with a LIFETIME attribute.
716 TurnMessage response;
717 InitResponse(msg, &response);
718
zsteinf42cc9d2017-03-27 16:17:19 -0700719 auto lifetime_attr =
Karl Wiberg918f50c2018-07-05 11:40:33 +0200720 absl::make_unique<StunUInt32Attribute>(STUN_ATTR_LIFETIME, lifetime_secs);
zsteinf42cc9d2017-03-27 16:17:19 -0700721 response.AddAttribute(std::move(lifetime_attr));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000722
723 SendResponse(&response);
724}
725
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000726void TurnServerAllocation::HandleSendIndication(const TurnMessage* msg) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000727 // Check mandatory attributes.
728 const StunByteStringAttribute* data_attr = msg->GetByteString(STUN_ATTR_DATA);
729 const StunAddressAttribute* peer_attr =
730 msg->GetAddress(STUN_ATTR_XOR_PEER_ADDRESS);
731 if (!data_attr || !peer_attr) {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200732 RTC_LOG(LS_WARNING) << ToString()
733 << ": Received invalid send indication";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000734 return;
735 }
736
737 // If a permission exists, send the data on to the peer.
738 if (HasPermission(peer_attr->GetAddress().ipaddr())) {
739 SendExternal(data_attr->bytes(), data_attr->length(),
740 peer_attr->GetAddress());
741 } else {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200742 RTC_LOG(LS_WARNING) << ToString()
743 << ": Received send indication without permission"
744 " peer="
Jonas Olssonabbe8412018-04-03 13:40:05 +0200745 << peer_attr->GetAddress().ToString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000746 }
747}
748
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000749void TurnServerAllocation::HandleCreatePermissionRequest(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000750 const TurnMessage* msg) {
751 // Check mandatory attributes.
752 const StunAddressAttribute* peer_attr =
753 msg->GetAddress(STUN_ATTR_XOR_PEER_ADDRESS);
754 if (!peer_attr) {
755 SendBadRequestResponse(msg);
756 return;
757 }
758
deadbeef376e1232015-11-25 09:00:08 -0800759 if (server_->reject_private_addresses_ &&
760 rtc::IPIsPrivate(peer_attr->GetAddress().ipaddr())) {
761 SendErrorResponse(msg, STUN_ERROR_FORBIDDEN, STUN_ERROR_REASON_FORBIDDEN);
762 return;
763 }
764
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000765 // Add this permission.
766 AddPermission(peer_attr->GetAddress().ipaddr());
767
Jonas Olssond7d762d2018-03-28 09:47:51 +0200768 RTC_LOG(LS_INFO) << ToString()
Jonas Olssonabbe8412018-04-03 13:40:05 +0200769 << ": Created permission, peer="
770 << peer_attr->GetAddress().ToString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000771
772 // Send a success response.
773 TurnMessage response;
774 InitResponse(msg, &response);
775 SendResponse(&response);
776}
777
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000778void TurnServerAllocation::HandleChannelBindRequest(const TurnMessage* msg) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000779 // Check mandatory attributes.
780 const StunUInt32Attribute* channel_attr =
781 msg->GetUInt32(STUN_ATTR_CHANNEL_NUMBER);
782 const StunAddressAttribute* peer_attr =
783 msg->GetAddress(STUN_ATTR_XOR_PEER_ADDRESS);
784 if (!channel_attr || !peer_attr) {
785 SendBadRequestResponse(msg);
786 return;
787 }
788
789 // Check that channel id is valid.
790 int channel_id = channel_attr->value() >> 16;
791 if (channel_id < kMinChannelNumber || channel_id > kMaxChannelNumber) {
792 SendBadRequestResponse(msg);
793 return;
794 }
795
796 // Check that this channel id isn't bound to another transport address, and
797 // that this transport address isn't bound to another channel id.
798 Channel* channel1 = FindChannel(channel_id);
799 Channel* channel2 = FindChannel(peer_attr->GetAddress());
800 if (channel1 != channel2) {
801 SendBadRequestResponse(msg);
802 return;
803 }
804
805 // Add or refresh this channel.
806 if (!channel1) {
807 channel1 = new Channel(thread_, channel_id, peer_attr->GetAddress());
808 channel1->SignalDestroyed.connect(this,
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000809 &TurnServerAllocation::OnChannelDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000810 channels_.push_back(channel1);
811 } else {
812 channel1->Refresh();
813 }
814
815 // Channel binds also refresh permissions.
816 AddPermission(peer_attr->GetAddress().ipaddr());
817
Jonas Olssond7d762d2018-03-28 09:47:51 +0200818 RTC_LOG(LS_INFO) << ToString()
819 << ": Bound channel, id=" << channel_id
Jonas Olssonabbe8412018-04-03 13:40:05 +0200820 << ", peer=" << peer_attr->GetAddress().ToString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000821
822 // Send a success response.
823 TurnMessage response;
824 InitResponse(msg, &response);
825 SendResponse(&response);
826}
827
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000828void TurnServerAllocation::HandleChannelData(const char* data, size_t size) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000829 // Extract the channel number from the data.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200830 uint16_t channel_id = rtc::GetBE16(data);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000831 Channel* channel = FindChannel(channel_id);
832 if (channel) {
833 // Send the data to the peer address.
834 SendExternal(data + TURN_CHANNEL_HEADER_SIZE,
835 size - TURN_CHANNEL_HEADER_SIZE, channel->peer());
836 } else {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200837 RTC_LOG(LS_WARNING) << ToString()
838 << ": Received channel data for invalid channel, id="
839 << channel_id;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000840 }
841}
842
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000843void TurnServerAllocation::OnExternalPacket(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000844 rtc::AsyncPacketSocket* socket,
845 const char* data, size_t size,
846 const rtc::SocketAddress& addr,
847 const rtc::PacketTime& packet_time) {
nisseede5da42017-01-12 05:15:36 -0800848 RTC_DCHECK(external_socket_.get() == socket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000849 Channel* channel = FindChannel(addr);
850 if (channel) {
851 // There is a channel bound to this address. Send as a channel message.
jbauchf1f87202016-03-30 06:43:37 -0700852 rtc::ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000853 buf.WriteUInt16(channel->id());
Peter Boström0c4e06b2015-10-07 12:23:21 +0200854 buf.WriteUInt16(static_cast<uint16_t>(size));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000855 buf.WriteBytes(data, size);
856 server_->Send(&conn_, buf);
Taylor Brandstetteref184702016-06-23 17:35:47 -0700857 } else if (!server_->enable_permission_checks_ ||
858 HasPermission(addr.ipaddr())) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000859 // No channel, but a permission exists. Send as a data indication.
860 TurnMessage msg;
861 msg.SetType(TURN_DATA_INDICATION);
862 msg.SetTransactionID(
863 rtc::CreateRandomString(kStunTransactionIdLength));
Karl Wiberg918f50c2018-07-05 11:40:33 +0200864 msg.AddAttribute(absl::make_unique<StunXorAddressAttribute>(
nissecc99bc22017-02-02 01:31:30 -0800865 STUN_ATTR_XOR_PEER_ADDRESS, addr));
zsteinf42cc9d2017-03-27 16:17:19 -0700866 msg.AddAttribute(
Karl Wiberg918f50c2018-07-05 11:40:33 +0200867 absl::make_unique<StunByteStringAttribute>(STUN_ATTR_DATA, data, size));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000868 server_->SendStun(&conn_, &msg);
869 } else {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200870 RTC_LOG(LS_WARNING)
871 << ToString()
Jonas Olssonabbe8412018-04-03 13:40:05 +0200872 << ": Received external packet without permission, peer="
873 << addr.ToString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000874 }
875}
876
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000877int TurnServerAllocation::ComputeLifetime(const TurnMessage* msg) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000878 // Return the smaller of our default lifetime and the requested lifetime.
honghaiz34b11eb2016-03-16 08:55:44 -0700879 int lifetime = kDefaultAllocationTimeout / 1000; // convert to seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000880 const StunUInt32Attribute* lifetime_attr = msg->GetUInt32(STUN_ATTR_LIFETIME);
honghaiz34b11eb2016-03-16 08:55:44 -0700881 if (lifetime_attr && static_cast<int>(lifetime_attr->value()) < lifetime) {
882 lifetime = static_cast<int>(lifetime_attr->value());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000883 }
884 return lifetime;
885}
886
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000887bool TurnServerAllocation::HasPermission(const rtc::IPAddress& addr) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000888 return (FindPermission(addr) != NULL);
889}
890
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000891void TurnServerAllocation::AddPermission(const rtc::IPAddress& addr) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000892 Permission* perm = FindPermission(addr);
893 if (!perm) {
894 perm = new Permission(thread_, addr);
895 perm->SignalDestroyed.connect(
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000896 this, &TurnServerAllocation::OnPermissionDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000897 perms_.push_back(perm);
898 } else {
899 perm->Refresh();
900 }
901}
902
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000903TurnServerAllocation::Permission* TurnServerAllocation::FindPermission(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000904 const rtc::IPAddress& addr) const {
905 for (PermissionList::const_iterator it = perms_.begin();
906 it != perms_.end(); ++it) {
907 if ((*it)->peer() == addr)
908 return *it;
909 }
910 return NULL;
911}
912
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000913TurnServerAllocation::Channel* TurnServerAllocation::FindChannel(
914 int channel_id) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000915 for (ChannelList::const_iterator it = channels_.begin();
916 it != channels_.end(); ++it) {
917 if ((*it)->id() == channel_id)
918 return *it;
919 }
920 return NULL;
921}
922
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000923TurnServerAllocation::Channel* TurnServerAllocation::FindChannel(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000924 const rtc::SocketAddress& addr) const {
925 for (ChannelList::const_iterator it = channels_.begin();
926 it != channels_.end(); ++it) {
927 if ((*it)->peer() == addr)
928 return *it;
929 }
930 return NULL;
931}
932
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000933void TurnServerAllocation::SendResponse(TurnMessage* msg) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000934 // Success responses always have M-I.
935 msg->AddMessageIntegrity(key_);
936 server_->SendStun(&conn_, msg);
937}
938
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000939void TurnServerAllocation::SendBadRequestResponse(const TurnMessage* req) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000940 SendErrorResponse(req, STUN_ERROR_BAD_REQUEST, STUN_ERROR_REASON_BAD_REQUEST);
941}
942
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000943void TurnServerAllocation::SendErrorResponse(const TurnMessage* req, int code,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000944 const std::string& reason) {
945 server_->SendErrorResponse(&conn_, req, code, reason);
946}
947
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000948void TurnServerAllocation::SendExternal(const void* data, size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000949 const rtc::SocketAddress& peer) {
950 rtc::PacketOptions options;
951 external_socket_->SendTo(data, size, peer, options);
952}
953
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000954void TurnServerAllocation::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -0800955 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_TIMEOUT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000956 SignalDestroyed(this);
957 delete this;
958}
959
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000960void TurnServerAllocation::OnPermissionDestroyed(Permission* perm) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000961 PermissionList::iterator it = std::find(perms_.begin(), perms_.end(), perm);
nisseede5da42017-01-12 05:15:36 -0800962 RTC_DCHECK(it != perms_.end());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000963 perms_.erase(it);
964}
965
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000966void TurnServerAllocation::OnChannelDestroyed(Channel* channel) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000967 ChannelList::iterator it =
968 std::find(channels_.begin(), channels_.end(), channel);
nisseede5da42017-01-12 05:15:36 -0800969 RTC_DCHECK(it != channels_.end());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000970 channels_.erase(it);
971}
972
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000973TurnServerAllocation::Permission::Permission(rtc::Thread* thread,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000974 const rtc::IPAddress& peer)
975 : thread_(thread), peer_(peer) {
976 Refresh();
977}
978
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000979TurnServerAllocation::Permission::~Permission() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000980 thread_->Clear(this, MSG_ALLOCATION_TIMEOUT);
981}
982
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000983void TurnServerAllocation::Permission::Refresh() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000984 thread_->Clear(this, MSG_ALLOCATION_TIMEOUT);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700985 thread_->PostDelayed(RTC_FROM_HERE, kPermissionTimeout, this,
986 MSG_ALLOCATION_TIMEOUT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000987}
988
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000989void TurnServerAllocation::Permission::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -0800990 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_TIMEOUT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000991 SignalDestroyed(this);
992 delete this;
993}
994
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000995TurnServerAllocation::Channel::Channel(rtc::Thread* thread, int id,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000996 const rtc::SocketAddress& peer)
997 : thread_(thread), id_(id), peer_(peer) {
998 Refresh();
999}
1000
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001001TurnServerAllocation::Channel::~Channel() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001002 thread_->Clear(this, MSG_ALLOCATION_TIMEOUT);
1003}
1004
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001005void TurnServerAllocation::Channel::Refresh() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001006 thread_->Clear(this, MSG_ALLOCATION_TIMEOUT);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001007 thread_->PostDelayed(RTC_FROM_HERE, kChannelTimeout, this,
1008 MSG_ALLOCATION_TIMEOUT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001009}
1010
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001011void TurnServerAllocation::Channel::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -08001012 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_TIMEOUT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001013 SignalDestroyed(this);
1014 delete this;
1015}
1016
1017} // namespace cricket