blob: 62ef5d98ee8be1528c8662c9eeda19ca1bcb9a50 [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
Steve Anton10542f22019-01-11 09:11:00 -080011#include "p2p/base/turn_server.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"
Steve Anton10542f22019-01-11 09:11:00 -080017#include "p2p/base/async_stun_tcp_socket.h"
18#include "p2p/base/packet_socket_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "p2p/base/stun.h"
20#include "rtc_base/bind.h"
Steve Anton10542f22019-01-11 09:11:00 -080021#include "rtc_base/byte_buffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "rtc_base/checks.h"
23#include "rtc_base/helpers.h"
24#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080025#include "rtc_base/message_digest.h"
26#include "rtc_base/socket_adapters.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020027#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#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());
Karl Wiberg918f50c2018-07-05 11:40:33 +0200117 resp->AddAttribute(absl::make_unique<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() {
Seth Hampsonaed71642018-06-11 07:41:32 -0700132 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000133 for (InternalSocketMap::iterator it = server_sockets_.begin();
134 it != server_sockets_.end(); ++it) {
135 rtc::AsyncPacketSocket* socket = it->first;
136 delete socket;
137 }
138
139 for (ServerSocketMap::iterator it = server_listen_sockets_.begin();
140 it != server_listen_sockets_.end(); ++it) {
141 rtc::AsyncSocket* socket = it->first;
142 delete socket;
143 }
144}
145
146void TurnServer::AddInternalSocket(rtc::AsyncPacketSocket* socket,
147 ProtocolType proto) {
Seth Hampsonaed71642018-06-11 07:41:32 -0700148 RTC_DCHECK(thread_checker_.CalledOnValidThread());
nisseede5da42017-01-12 05:15:36 -0800149 RTC_DCHECK(server_sockets_.end() == server_sockets_.find(socket));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000150 server_sockets_[socket] = proto;
151 socket->SignalReadPacket.connect(this, &TurnServer::OnInternalPacket);
152}
153
154void TurnServer::AddInternalServerSocket(rtc::AsyncSocket* socket,
155 ProtocolType proto) {
Seth Hampsonaed71642018-06-11 07:41:32 -0700156 RTC_DCHECK(thread_checker_.CalledOnValidThread());
nisseede5da42017-01-12 05:15:36 -0800157 RTC_DCHECK(server_listen_sockets_.end() ==
158 server_listen_sockets_.find(socket));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000159 server_listen_sockets_[socket] = proto;
160 socket->SignalReadEvent.connect(this, &TurnServer::OnNewInternalConnection);
161}
162
163void TurnServer::SetExternalSocketFactory(
164 rtc::PacketSocketFactory* factory,
165 const rtc::SocketAddress& external_addr) {
Seth Hampsonaed71642018-06-11 07:41:32 -0700166 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000167 external_socket_factory_.reset(factory);
168 external_addr_ = external_addr;
169}
170
171void TurnServer::OnNewInternalConnection(rtc::AsyncSocket* socket) {
Seth Hampsonaed71642018-06-11 07:41:32 -0700172 RTC_DCHECK(thread_checker_.CalledOnValidThread());
nisseede5da42017-01-12 05:15:36 -0800173 RTC_DCHECK(server_listen_sockets_.find(socket) !=
174 server_listen_sockets_.end());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000175 AcceptConnection(socket);
176}
177
178void TurnServer::AcceptConnection(rtc::AsyncSocket* server_socket) {
Seth Hampsonaed71642018-06-11 07:41:32 -0700179 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000180 // Check if someone is trying to connect to us.
181 rtc::SocketAddress accept_addr;
182 rtc::AsyncSocket* accepted_socket = server_socket->Accept(&accept_addr);
183 if (accepted_socket != NULL) {
184 ProtocolType proto = server_listen_sockets_[server_socket];
185 cricket::AsyncStunTCPSocket* tcp_socket =
186 new cricket::AsyncStunTCPSocket(accepted_socket, false);
187
188 tcp_socket->SignalClose.connect(this, &TurnServer::OnInternalSocketClose);
189 // Finally add the socket so it can start communicating with the client.
190 AddInternalSocket(tcp_socket, proto);
191 }
192}
193
194void TurnServer::OnInternalSocketClose(rtc::AsyncPacketSocket* socket,
195 int err) {
Seth Hampsonaed71642018-06-11 07:41:32 -0700196 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000197 DestroyInternalSocket(socket);
198}
199
200void TurnServer::OnInternalPacket(rtc::AsyncPacketSocket* socket,
Niels Möllere6933812018-11-05 13:01:41 +0100201 const char* data,
202 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000203 const rtc::SocketAddress& addr,
Niels Möllere6933812018-11-05 13:01:41 +0100204 const int64_t& /* packet_time_us */) {
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,
Niels Möllere6933812018-11-05 13:01:41 +0100845 const char* data,
846 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000847 const rtc::SocketAddress& addr,
Niels Möllere6933812018-11-05 13:01:41 +0100848 const int64_t& /* packet_time_us */) {
nisseede5da42017-01-12 05:15:36 -0800849 RTC_DCHECK(external_socket_.get() == socket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000850 Channel* channel = FindChannel(addr);
851 if (channel) {
852 // There is a channel bound to this address. Send as a channel message.
jbauchf1f87202016-03-30 06:43:37 -0700853 rtc::ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000854 buf.WriteUInt16(channel->id());
Peter Boström0c4e06b2015-10-07 12:23:21 +0200855 buf.WriteUInt16(static_cast<uint16_t>(size));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000856 buf.WriteBytes(data, size);
857 server_->Send(&conn_, buf);
Taylor Brandstetteref184702016-06-23 17:35:47 -0700858 } else if (!server_->enable_permission_checks_ ||
859 HasPermission(addr.ipaddr())) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000860 // No channel, but a permission exists. Send as a data indication.
861 TurnMessage msg;
862 msg.SetType(TURN_DATA_INDICATION);
863 msg.SetTransactionID(
864 rtc::CreateRandomString(kStunTransactionIdLength));
Karl Wiberg918f50c2018-07-05 11:40:33 +0200865 msg.AddAttribute(absl::make_unique<StunXorAddressAttribute>(
nissecc99bc22017-02-02 01:31:30 -0800866 STUN_ATTR_XOR_PEER_ADDRESS, addr));
zsteinf42cc9d2017-03-27 16:17:19 -0700867 msg.AddAttribute(
Karl Wiberg918f50c2018-07-05 11:40:33 +0200868 absl::make_unique<StunByteStringAttribute>(STUN_ATTR_DATA, data, size));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000869 server_->SendStun(&conn_, &msg);
870 } else {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200871 RTC_LOG(LS_WARNING)
872 << ToString()
Jonas Olssonabbe8412018-04-03 13:40:05 +0200873 << ": Received external packet without permission, peer="
874 << addr.ToString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000875 }
876}
877
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000878int TurnServerAllocation::ComputeLifetime(const TurnMessage* msg) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000879 // Return the smaller of our default lifetime and the requested lifetime.
honghaiz34b11eb2016-03-16 08:55:44 -0700880 int lifetime = kDefaultAllocationTimeout / 1000; // convert to seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000881 const StunUInt32Attribute* lifetime_attr = msg->GetUInt32(STUN_ATTR_LIFETIME);
honghaiz34b11eb2016-03-16 08:55:44 -0700882 if (lifetime_attr && static_cast<int>(lifetime_attr->value()) < lifetime) {
883 lifetime = static_cast<int>(lifetime_attr->value());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000884 }
885 return lifetime;
886}
887
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000888bool TurnServerAllocation::HasPermission(const rtc::IPAddress& addr) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000889 return (FindPermission(addr) != NULL);
890}
891
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000892void TurnServerAllocation::AddPermission(const rtc::IPAddress& addr) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000893 Permission* perm = FindPermission(addr);
894 if (!perm) {
895 perm = new Permission(thread_, addr);
896 perm->SignalDestroyed.connect(
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000897 this, &TurnServerAllocation::OnPermissionDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000898 perms_.push_back(perm);
899 } else {
900 perm->Refresh();
901 }
902}
903
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000904TurnServerAllocation::Permission* TurnServerAllocation::FindPermission(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000905 const rtc::IPAddress& addr) const {
906 for (PermissionList::const_iterator it = perms_.begin();
907 it != perms_.end(); ++it) {
908 if ((*it)->peer() == addr)
909 return *it;
910 }
911 return NULL;
912}
913
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000914TurnServerAllocation::Channel* TurnServerAllocation::FindChannel(
915 int channel_id) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000916 for (ChannelList::const_iterator it = channels_.begin();
917 it != channels_.end(); ++it) {
918 if ((*it)->id() == channel_id)
919 return *it;
920 }
921 return NULL;
922}
923
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000924TurnServerAllocation::Channel* TurnServerAllocation::FindChannel(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000925 const rtc::SocketAddress& addr) const {
926 for (ChannelList::const_iterator it = channels_.begin();
927 it != channels_.end(); ++it) {
928 if ((*it)->peer() == addr)
929 return *it;
930 }
931 return NULL;
932}
933
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000934void TurnServerAllocation::SendResponse(TurnMessage* msg) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000935 // Success responses always have M-I.
936 msg->AddMessageIntegrity(key_);
937 server_->SendStun(&conn_, msg);
938}
939
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000940void TurnServerAllocation::SendBadRequestResponse(const TurnMessage* req) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000941 SendErrorResponse(req, STUN_ERROR_BAD_REQUEST, STUN_ERROR_REASON_BAD_REQUEST);
942}
943
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000944void TurnServerAllocation::SendErrorResponse(const TurnMessage* req, int code,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000945 const std::string& reason) {
946 server_->SendErrorResponse(&conn_, req, code, reason);
947}
948
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000949void TurnServerAllocation::SendExternal(const void* data, size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000950 const rtc::SocketAddress& peer) {
951 rtc::PacketOptions options;
952 external_socket_->SendTo(data, size, peer, options);
953}
954
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000955void TurnServerAllocation::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -0800956 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_TIMEOUT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000957 SignalDestroyed(this);
958 delete this;
959}
960
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000961void TurnServerAllocation::OnPermissionDestroyed(Permission* perm) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000962 PermissionList::iterator it = std::find(perms_.begin(), perms_.end(), perm);
nisseede5da42017-01-12 05:15:36 -0800963 RTC_DCHECK(it != perms_.end());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000964 perms_.erase(it);
965}
966
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000967void TurnServerAllocation::OnChannelDestroyed(Channel* channel) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000968 ChannelList::iterator it =
969 std::find(channels_.begin(), channels_.end(), channel);
nisseede5da42017-01-12 05:15:36 -0800970 RTC_DCHECK(it != channels_.end());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000971 channels_.erase(it);
972}
973
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000974TurnServerAllocation::Permission::Permission(rtc::Thread* thread,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000975 const rtc::IPAddress& peer)
976 : thread_(thread), peer_(peer) {
977 Refresh();
978}
979
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000980TurnServerAllocation::Permission::~Permission() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000981 thread_->Clear(this, MSG_ALLOCATION_TIMEOUT);
982}
983
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000984void TurnServerAllocation::Permission::Refresh() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000985 thread_->Clear(this, MSG_ALLOCATION_TIMEOUT);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700986 thread_->PostDelayed(RTC_FROM_HERE, kPermissionTimeout, this,
987 MSG_ALLOCATION_TIMEOUT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000988}
989
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000990void TurnServerAllocation::Permission::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -0800991 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_TIMEOUT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000992 SignalDestroyed(this);
993 delete this;
994}
995
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000996TurnServerAllocation::Channel::Channel(rtc::Thread* thread, int id,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000997 const rtc::SocketAddress& peer)
998 : thread_(thread), id_(id), peer_(peer) {
999 Refresh();
1000}
1001
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001002TurnServerAllocation::Channel::~Channel() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001003 thread_->Clear(this, MSG_ALLOCATION_TIMEOUT);
1004}
1005
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001006void TurnServerAllocation::Channel::Refresh() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001007 thread_->Clear(this, MSG_ALLOCATION_TIMEOUT);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001008 thread_->PostDelayed(RTC_FROM_HERE, kChannelTimeout, this,
1009 MSG_ALLOCATION_TIMEOUT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001010}
1011
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001012void TurnServerAllocation::Channel::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -08001013 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_TIMEOUT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001014 SignalDestroyed(this);
1015 delete this;
1016}
1017
1018} // namespace cricket