blob: 3a97d4e66450605140e0b23db7c13c1fca688fa5 [file] [log] [blame]
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001/*
2 * Copyright 2004 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
11#include "webrtc/p2p/base/relayserver.h"
12
13#ifdef WEBRTC_POSIX
14#include <errno.h>
15#endif // WEBRTC_POSIX
16
17#include <algorithm>
18
Edward Lemurc20978e2017-07-06 19:44:34 +020019#include "webrtc/rtc_base/asynctcpsocket.h"
20#include "webrtc/rtc_base/checks.h"
21#include "webrtc/rtc_base/helpers.h"
22#include "webrtc/rtc_base/logging.h"
23#include "webrtc/rtc_base/socketadapters.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000024
25namespace cricket {
26
27// By default, we require a ping every 90 seconds.
28const int MAX_LIFETIME = 15 * 60 * 1000;
29
30// The number of bytes in each of the usernames we use.
Peter Boström0c4e06b2015-10-07 12:23:21 +020031const uint32_t USERNAME_LENGTH = 16;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000032
33// Calls SendTo on the given socket and logs any bad results.
34void Send(rtc::AsyncPacketSocket* socket, const char* bytes, size_t size,
35 const rtc::SocketAddress& addr) {
36 rtc::PacketOptions options;
37 int result = socket->SendTo(bytes, size, addr, options);
38 if (result < static_cast<int>(size)) {
39 LOG(LS_ERROR) << "SendTo wrote only " << result << " of " << size
40 << " bytes";
41 } else if (result < 0) {
42 LOG_ERR(LS_ERROR) << "SendTo";
43 }
44}
45
46// Sends the given STUN message on the given socket.
47void SendStun(const StunMessage& msg,
48 rtc::AsyncPacketSocket* socket,
49 const rtc::SocketAddress& addr) {
jbauchf1f87202016-03-30 06:43:37 -070050 rtc::ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000051 msg.Write(&buf);
52 Send(socket, buf.Data(), buf.Length(), addr);
53}
54
55// Constructs a STUN error response and sends it on the given socket.
56void SendStunError(const StunMessage& msg, rtc::AsyncPacketSocket* socket,
57 const rtc::SocketAddress& remote_addr, int error_code,
58 const char* error_desc, const std::string& magic_cookie) {
59 RelayMessage err_msg;
60 err_msg.SetType(GetStunErrorResponseType(msg.type()));
61 err_msg.SetTransactionID(msg.transaction_id());
62
zsteinf42cc9d2017-03-27 16:17:19 -070063 auto magic_cookie_attr =
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000064 StunAttribute::CreateByteString(cricket::STUN_ATTR_MAGIC_COOKIE);
65 if (magic_cookie.size() == 0) {
66 magic_cookie_attr->CopyBytes(cricket::TURN_MAGIC_COOKIE_VALUE,
67 sizeof(cricket::TURN_MAGIC_COOKIE_VALUE));
68 } else {
69 magic_cookie_attr->CopyBytes(magic_cookie.c_str(), magic_cookie.size());
70 }
zsteinf42cc9d2017-03-27 16:17:19 -070071 err_msg.AddAttribute(std::move(magic_cookie_attr));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000072
zsteinf42cc9d2017-03-27 16:17:19 -070073 auto err_code = StunAttribute::CreateErrorCode();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000074 err_code->SetClass(error_code / 100);
75 err_code->SetNumber(error_code % 100);
76 err_code->SetReason(error_desc);
zsteinf42cc9d2017-03-27 16:17:19 -070077 err_msg.AddAttribute(std::move(err_code));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000078
79 SendStun(err_msg, socket, remote_addr);
80}
81
82RelayServer::RelayServer(rtc::Thread* thread)
83 : thread_(thread), log_bindings_(true) {
84}
85
86RelayServer::~RelayServer() {
87 // Deleting the binding will cause it to be removed from the map.
88 while (!bindings_.empty())
89 delete bindings_.begin()->second;
90 for (size_t i = 0; i < internal_sockets_.size(); ++i)
91 delete internal_sockets_[i];
92 for (size_t i = 0; i < external_sockets_.size(); ++i)
93 delete external_sockets_[i];
94 for (size_t i = 0; i < removed_sockets_.size(); ++i)
95 delete removed_sockets_[i];
96 while (!server_sockets_.empty()) {
97 rtc::AsyncSocket* socket = server_sockets_.begin()->first;
98 server_sockets_.erase(server_sockets_.begin()->first);
99 delete socket;
100 }
101}
102
103void RelayServer::AddInternalSocket(rtc::AsyncPacketSocket* socket) {
nisseede5da42017-01-12 05:15:36 -0800104 RTC_DCHECK(internal_sockets_.end() == std::find(internal_sockets_.begin(),
105 internal_sockets_.end(),
106 socket));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000107 internal_sockets_.push_back(socket);
108 socket->SignalReadPacket.connect(this, &RelayServer::OnInternalPacket);
109}
110
111void RelayServer::RemoveInternalSocket(rtc::AsyncPacketSocket* socket) {
112 SocketList::iterator iter =
113 std::find(internal_sockets_.begin(), internal_sockets_.end(), socket);
nisseede5da42017-01-12 05:15:36 -0800114 RTC_DCHECK(iter != internal_sockets_.end());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000115 internal_sockets_.erase(iter);
116 removed_sockets_.push_back(socket);
117 socket->SignalReadPacket.disconnect(this);
118}
119
120void RelayServer::AddExternalSocket(rtc::AsyncPacketSocket* socket) {
nisseede5da42017-01-12 05:15:36 -0800121 RTC_DCHECK(external_sockets_.end() == std::find(external_sockets_.begin(),
122 external_sockets_.end(),
123 socket));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000124 external_sockets_.push_back(socket);
125 socket->SignalReadPacket.connect(this, &RelayServer::OnExternalPacket);
126}
127
128void RelayServer::RemoveExternalSocket(rtc::AsyncPacketSocket* socket) {
129 SocketList::iterator iter =
130 std::find(external_sockets_.begin(), external_sockets_.end(), socket);
nisseede5da42017-01-12 05:15:36 -0800131 RTC_DCHECK(iter != external_sockets_.end());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000132 external_sockets_.erase(iter);
133 removed_sockets_.push_back(socket);
134 socket->SignalReadPacket.disconnect(this);
135}
136
137void RelayServer::AddInternalServerSocket(rtc::AsyncSocket* socket,
138 cricket::ProtocolType proto) {
nisseede5da42017-01-12 05:15:36 -0800139 RTC_DCHECK(server_sockets_.end() == server_sockets_.find(socket));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000140 server_sockets_[socket] = proto;
141 socket->SignalReadEvent.connect(this, &RelayServer::OnReadEvent);
142}
143
144void RelayServer::RemoveInternalServerSocket(
145 rtc::AsyncSocket* socket) {
146 ServerSocketMap::iterator iter = server_sockets_.find(socket);
nisseede5da42017-01-12 05:15:36 -0800147 RTC_DCHECK(iter != server_sockets_.end());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000148 server_sockets_.erase(iter);
149 socket->SignalReadEvent.disconnect(this);
150}
151
152int RelayServer::GetConnectionCount() const {
153 return static_cast<int>(connections_.size());
154}
155
156rtc::SocketAddressPair RelayServer::GetConnection(int connection) const {
157 int i = 0;
158 for (ConnectionMap::const_iterator it = connections_.begin();
159 it != connections_.end(); ++it) {
160 if (i == connection) {
161 return it->second->addr_pair();
162 }
163 ++i;
164 }
165 return rtc::SocketAddressPair();
166}
167
168bool RelayServer::HasConnection(const rtc::SocketAddress& address) const {
169 for (ConnectionMap::const_iterator it = connections_.begin();
170 it != connections_.end(); ++it) {
171 if (it->second->addr_pair().destination() == address) {
172 return true;
173 }
174 }
175 return false;
176}
177
178void RelayServer::OnReadEvent(rtc::AsyncSocket* socket) {
nisseede5da42017-01-12 05:15:36 -0800179 RTC_DCHECK(server_sockets_.find(socket) != server_sockets_.end());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000180 AcceptConnection(socket);
181}
182
183void RelayServer::OnInternalPacket(
184 rtc::AsyncPacketSocket* socket, const char* bytes, size_t size,
185 const rtc::SocketAddress& remote_addr,
186 const rtc::PacketTime& packet_time) {
187
188 // Get the address of the connection we just received on.
189 rtc::SocketAddressPair ap(remote_addr, socket->GetLocalAddress());
nisseede5da42017-01-12 05:15:36 -0800190 RTC_DCHECK(!ap.destination().IsNil());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000191
192 // If this did not come from an existing connection, it should be a STUN
193 // allocate request.
194 ConnectionMap::iterator piter = connections_.find(ap);
195 if (piter == connections_.end()) {
196 HandleStunAllocate(bytes, size, ap, socket);
197 return;
198 }
199
200 RelayServerConnection* int_conn = piter->second;
201
202 // Handle STUN requests to the server itself.
203 if (int_conn->binding()->HasMagicCookie(bytes, size)) {
204 HandleStun(int_conn, bytes, size);
205 return;
206 }
207
208 // Otherwise, this is a non-wrapped packet that we are to forward. Make sure
209 // that this connection has been locked. (Otherwise, we would not know what
210 // address to forward to.)
211 if (!int_conn->locked()) {
212 LOG(LS_WARNING) << "Dropping packet: connection not locked";
213 return;
214 }
215
216 // Forward this to the destination address into the connection.
217 RelayServerConnection* ext_conn = int_conn->binding()->GetExternalConnection(
218 int_conn->default_destination());
219 if (ext_conn && ext_conn->locked()) {
220 // TODO: Check the HMAC.
221 ext_conn->Send(bytes, size);
222 } else {
223 // This happens very often and is not an error.
224 LOG(LS_INFO) << "Dropping packet: no external connection";
225 }
226}
227
228void RelayServer::OnExternalPacket(
229 rtc::AsyncPacketSocket* socket, const char* bytes, size_t size,
230 const rtc::SocketAddress& remote_addr,
231 const rtc::PacketTime& packet_time) {
232
233 // Get the address of the connection we just received on.
234 rtc::SocketAddressPair ap(remote_addr, socket->GetLocalAddress());
nisseede5da42017-01-12 05:15:36 -0800235 RTC_DCHECK(!ap.destination().IsNil());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000236
237 // If this connection already exists, then forward the traffic.
238 ConnectionMap::iterator piter = connections_.find(ap);
239 if (piter != connections_.end()) {
240 // TODO: Check the HMAC.
241 RelayServerConnection* ext_conn = piter->second;
242 RelayServerConnection* int_conn =
243 ext_conn->binding()->GetInternalConnection(
244 ext_conn->addr_pair().source());
nisseede5da42017-01-12 05:15:36 -0800245 RTC_DCHECK(int_conn != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000246 int_conn->Send(bytes, size, ext_conn->addr_pair().source());
247 ext_conn->Lock(); // allow outgoing packets
248 return;
249 }
250
251 // The first packet should always be a STUN / TURN packet. If it isn't, then
252 // we should just ignore this packet.
253 RelayMessage msg;
jbauchf1f87202016-03-30 06:43:37 -0700254 rtc::ByteBufferReader buf(bytes, size);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000255 if (!msg.Read(&buf)) {
256 LOG(LS_WARNING) << "Dropping packet: first packet not STUN";
257 return;
258 }
259
260 // The initial packet should have a username (which identifies the binding).
261 const StunByteStringAttribute* username_attr =
262 msg.GetByteString(STUN_ATTR_USERNAME);
263 if (!username_attr) {
264 LOG(LS_WARNING) << "Dropping packet: no username";
265 return;
266 }
267
Peter Boström0c4e06b2015-10-07 12:23:21 +0200268 uint32_t length =
269 std::min(static_cast<uint32_t>(username_attr->length()), USERNAME_LENGTH);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000270 std::string username(username_attr->bytes(), length);
271 // TODO: Check the HMAC.
272
273 // The binding should already be present.
274 BindingMap::iterator biter = bindings_.find(username);
275 if (biter == bindings_.end()) {
276 LOG(LS_WARNING) << "Dropping packet: no binding with username";
277 return;
278 }
279
280 // Add this authenticted connection to the binding.
281 RelayServerConnection* ext_conn =
282 new RelayServerConnection(biter->second, ap, socket);
283 ext_conn->binding()->AddExternalConnection(ext_conn);
284 AddConnection(ext_conn);
285
286 // We always know where external packets should be forwarded, so we can lock
287 // them from the beginning.
288 ext_conn->Lock();
289
290 // Send this message on the appropriate internal connection.
291 RelayServerConnection* int_conn = ext_conn->binding()->GetInternalConnection(
292 ext_conn->addr_pair().source());
nisseede5da42017-01-12 05:15:36 -0800293 RTC_DCHECK(int_conn != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000294 int_conn->Send(bytes, size, ext_conn->addr_pair().source());
295}
296
297bool RelayServer::HandleStun(
298 const char* bytes, size_t size, const rtc::SocketAddress& remote_addr,
299 rtc::AsyncPacketSocket* socket, std::string* username,
300 StunMessage* msg) {
301
302 // Parse this into a stun message. Eat the message if this fails.
jbauchf1f87202016-03-30 06:43:37 -0700303 rtc::ByteBufferReader buf(bytes, size);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000304 if (!msg->Read(&buf)) {
305 return false;
306 }
307
308 // The initial packet should have a username (which identifies the binding).
309 const StunByteStringAttribute* username_attr =
310 msg->GetByteString(STUN_ATTR_USERNAME);
311 if (!username_attr) {
312 SendStunError(*msg, socket, remote_addr, 432, "Missing Username", "");
313 return false;
314 }
315
316 // Record the username if requested.
317 if (username)
318 username->append(username_attr->bytes(), username_attr->length());
319
320 // TODO: Check for unknown attributes (<= 0x7fff)
321
322 return true;
323}
324
325void RelayServer::HandleStunAllocate(
326 const char* bytes, size_t size, const rtc::SocketAddressPair& ap,
327 rtc::AsyncPacketSocket* socket) {
328
329 // Make sure this is a valid STUN request.
330 RelayMessage request;
331 std::string username;
332 if (!HandleStun(bytes, size, ap.source(), socket, &username, &request))
333 return;
334
335 // Make sure this is a an allocate request.
336 if (request.type() != STUN_ALLOCATE_REQUEST) {
337 SendStunError(request,
338 socket,
339 ap.source(),
340 600,
341 "Operation Not Supported",
342 "");
343 return;
344 }
345
346 // TODO: Check the HMAC.
347
348 // Find or create the binding for this username.
349
350 RelayServerBinding* binding;
351
352 BindingMap::iterator biter = bindings_.find(username);
353 if (biter != bindings_.end()) {
354 binding = biter->second;
355 } else {
356 // NOTE: In the future, bindings will be created by the bot only. This
357 // else-branch will then disappear.
358
359 // Compute the appropriate lifetime for this binding.
honghaiz34b11eb2016-03-16 08:55:44 -0700360 int lifetime = MAX_LIFETIME;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000361 const StunUInt32Attribute* lifetime_attr =
362 request.GetUInt32(STUN_ATTR_LIFETIME);
363 if (lifetime_attr)
honghaiz34b11eb2016-03-16 08:55:44 -0700364 lifetime =
365 std::min(lifetime, static_cast<int>(lifetime_attr->value() * 1000));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000366
367 binding = new RelayServerBinding(this, username, "0", lifetime);
368 binding->SignalTimeout.connect(this, &RelayServer::OnTimeout);
369 bindings_[username] = binding;
370
371 if (log_bindings_) {
372 LOG(LS_INFO) << "Added new binding " << username << ", "
373 << bindings_.size() << " total";
374 }
375 }
376
377 // Add this connection to the binding. It starts out unlocked.
378 RelayServerConnection* int_conn =
379 new RelayServerConnection(binding, ap, socket);
380 binding->AddInternalConnection(int_conn);
381 AddConnection(int_conn);
382
383 // Now that we have a connection, this other method takes over.
384 HandleStunAllocate(int_conn, request);
385}
386
387void RelayServer::HandleStun(
388 RelayServerConnection* int_conn, const char* bytes, size_t size) {
389
390 // Make sure this is a valid STUN request.
391 RelayMessage request;
392 std::string username;
393 if (!HandleStun(bytes, size, int_conn->addr_pair().source(),
394 int_conn->socket(), &username, &request))
395 return;
396
397 // Make sure the username is the one were were expecting.
398 if (username != int_conn->binding()->username()) {
399 int_conn->SendStunError(request, 430, "Stale Credentials");
400 return;
401 }
402
403 // TODO: Check the HMAC.
404
405 // Send this request to the appropriate handler.
406 if (request.type() == STUN_SEND_REQUEST)
407 HandleStunSend(int_conn, request);
408 else if (request.type() == STUN_ALLOCATE_REQUEST)
409 HandleStunAllocate(int_conn, request);
410 else
411 int_conn->SendStunError(request, 600, "Operation Not Supported");
412}
413
414void RelayServer::HandleStunAllocate(
415 RelayServerConnection* int_conn, const StunMessage& request) {
416
417 // Create a response message that includes an address with which external
418 // clients can communicate.
419
420 RelayMessage response;
421 response.SetType(STUN_ALLOCATE_RESPONSE);
422 response.SetTransactionID(request.transaction_id());
423
zsteinf42cc9d2017-03-27 16:17:19 -0700424 auto magic_cookie_attr =
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000425 StunAttribute::CreateByteString(cricket::STUN_ATTR_MAGIC_COOKIE);
426 magic_cookie_attr->CopyBytes(int_conn->binding()->magic_cookie().c_str(),
427 int_conn->binding()->magic_cookie().size());
zsteinf42cc9d2017-03-27 16:17:19 -0700428 response.AddAttribute(std::move(magic_cookie_attr));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000429
430 size_t index = rand() % external_sockets_.size();
431 rtc::SocketAddress ext_addr =
432 external_sockets_[index]->GetLocalAddress();
433
zsteinf42cc9d2017-03-27 16:17:19 -0700434 auto addr_attr = StunAttribute::CreateAddress(STUN_ATTR_MAPPED_ADDRESS);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000435 addr_attr->SetIP(ext_addr.ipaddr());
436 addr_attr->SetPort(ext_addr.port());
zsteinf42cc9d2017-03-27 16:17:19 -0700437 response.AddAttribute(std::move(addr_attr));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000438
zsteinf42cc9d2017-03-27 16:17:19 -0700439 auto res_lifetime_attr = StunAttribute::CreateUInt32(STUN_ATTR_LIFETIME);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000440 res_lifetime_attr->SetValue(int_conn->binding()->lifetime() / 1000);
zsteinf42cc9d2017-03-27 16:17:19 -0700441 response.AddAttribute(std::move(res_lifetime_attr));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000442
443 // TODO: Support transport-prefs (preallocate RTCP port).
444 // TODO: Support bandwidth restrictions.
445 // TODO: Add message integrity check.
446
447 // Send a response to the caller.
448 int_conn->SendStun(response);
449}
450
451void RelayServer::HandleStunSend(
452 RelayServerConnection* int_conn, const StunMessage& request) {
453
454 const StunAddressAttribute* addr_attr =
455 request.GetAddress(STUN_ATTR_DESTINATION_ADDRESS);
456 if (!addr_attr) {
457 int_conn->SendStunError(request, 400, "Bad Request");
458 return;
459 }
460
461 const StunByteStringAttribute* data_attr =
462 request.GetByteString(STUN_ATTR_DATA);
463 if (!data_attr) {
464 int_conn->SendStunError(request, 400, "Bad Request");
465 return;
466 }
467
468 rtc::SocketAddress ext_addr(addr_attr->ipaddr(), addr_attr->port());
469 RelayServerConnection* ext_conn =
470 int_conn->binding()->GetExternalConnection(ext_addr);
471 if (!ext_conn) {
472 // Create a new connection to establish the relationship with this binding.
nisseede5da42017-01-12 05:15:36 -0800473 RTC_DCHECK(external_sockets_.size() == 1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000474 rtc::AsyncPacketSocket* socket = external_sockets_[0];
475 rtc::SocketAddressPair ap(ext_addr, socket->GetLocalAddress());
476 ext_conn = new RelayServerConnection(int_conn->binding(), ap, socket);
477 ext_conn->binding()->AddExternalConnection(ext_conn);
478 AddConnection(ext_conn);
479 }
480
481 // If this connection has pinged us, then allow outgoing traffic.
482 if (ext_conn->locked())
483 ext_conn->Send(data_attr->bytes(), data_attr->length());
484
485 const StunUInt32Attribute* options_attr =
486 request.GetUInt32(STUN_ATTR_OPTIONS);
487 if (options_attr && (options_attr->value() & 0x01)) {
488 int_conn->set_default_destination(ext_addr);
489 int_conn->Lock();
490
491 RelayMessage response;
492 response.SetType(STUN_SEND_RESPONSE);
493 response.SetTransactionID(request.transaction_id());
494
zsteinf42cc9d2017-03-27 16:17:19 -0700495 auto magic_cookie_attr =
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000496 StunAttribute::CreateByteString(cricket::STUN_ATTR_MAGIC_COOKIE);
497 magic_cookie_attr->CopyBytes(int_conn->binding()->magic_cookie().c_str(),
498 int_conn->binding()->magic_cookie().size());
zsteinf42cc9d2017-03-27 16:17:19 -0700499 response.AddAttribute(std::move(magic_cookie_attr));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000500
zsteinf42cc9d2017-03-27 16:17:19 -0700501 auto options2_attr =
502 StunAttribute::CreateUInt32(cricket::STUN_ATTR_OPTIONS);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000503 options2_attr->SetValue(0x01);
zsteinf42cc9d2017-03-27 16:17:19 -0700504 response.AddAttribute(std::move(options2_attr));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000505
506 int_conn->SendStun(response);
507 }
508}
509
510void RelayServer::AddConnection(RelayServerConnection* conn) {
nisseede5da42017-01-12 05:15:36 -0800511 RTC_DCHECK(connections_.find(conn->addr_pair()) == connections_.end());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000512 connections_[conn->addr_pair()] = conn;
513}
514
515void RelayServer::RemoveConnection(RelayServerConnection* conn) {
516 ConnectionMap::iterator iter = connections_.find(conn->addr_pair());
nisseede5da42017-01-12 05:15:36 -0800517 RTC_DCHECK(iter != connections_.end());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000518 connections_.erase(iter);
519}
520
521void RelayServer::RemoveBinding(RelayServerBinding* binding) {
522 BindingMap::iterator iter = bindings_.find(binding->username());
nisseede5da42017-01-12 05:15:36 -0800523 RTC_DCHECK(iter != bindings_.end());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000524 bindings_.erase(iter);
525
526 if (log_bindings_) {
527 LOG(LS_INFO) << "Removed binding " << binding->username() << ", "
528 << bindings_.size() << " remaining";
529 }
530}
531
532void RelayServer::OnMessage(rtc::Message *pmsg) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200533 static const uint32_t kMessageAcceptConnection = 1;
nisseede5da42017-01-12 05:15:36 -0800534 RTC_DCHECK(pmsg->message_id == kMessageAcceptConnection);
535
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000536 rtc::MessageData* data = pmsg->pdata;
537 rtc::AsyncSocket* socket =
538 static_cast <rtc::TypedMessageData<rtc::AsyncSocket*>*>
539 (data)->data();
540 AcceptConnection(socket);
541 delete data;
542}
543
544void RelayServer::OnTimeout(RelayServerBinding* binding) {
545 // This call will result in all of the necessary clean-up. We can't call
546 // delete here, because you can't delete an object that is signaling you.
547 thread_->Dispose(binding);
548}
549
550void RelayServer::AcceptConnection(rtc::AsyncSocket* server_socket) {
551 // Check if someone is trying to connect to us.
552 rtc::SocketAddress accept_addr;
553 rtc::AsyncSocket* accepted_socket =
554 server_socket->Accept(&accept_addr);
555 if (accepted_socket != NULL) {
556 // We had someone trying to connect, now check which protocol to
557 // use and create a packet socket.
nisseede5da42017-01-12 05:15:36 -0800558 RTC_DCHECK(server_sockets_[server_socket] == cricket::PROTO_TCP ||
559 server_sockets_[server_socket] == cricket::PROTO_SSLTCP);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000560 if (server_sockets_[server_socket] == cricket::PROTO_SSLTCP) {
561 accepted_socket = new rtc::AsyncSSLServerSocket(accepted_socket);
562 }
563 rtc::AsyncTCPSocket* tcp_socket =
564 new rtc::AsyncTCPSocket(accepted_socket, false);
565
566 // Finally add the socket so it can start communicating with the client.
567 AddInternalSocket(tcp_socket);
568 }
569}
570
571RelayServerConnection::RelayServerConnection(
572 RelayServerBinding* binding, const rtc::SocketAddressPair& addrs,
573 rtc::AsyncPacketSocket* socket)
574 : binding_(binding), addr_pair_(addrs), socket_(socket), locked_(false) {
575 // The creation of a new connection constitutes a use of the binding.
576 binding_->NoteUsed();
577}
578
579RelayServerConnection::~RelayServerConnection() {
580 // Remove this connection from the server's map (if it exists there).
581 binding_->server()->RemoveConnection(this);
582}
583
584void RelayServerConnection::Send(const char* data, size_t size) {
585 // Note that the binding has been used again.
586 binding_->NoteUsed();
587
588 cricket::Send(socket_, data, size, addr_pair_.source());
589}
590
591void RelayServerConnection::Send(
592 const char* data, size_t size, const rtc::SocketAddress& from_addr) {
593 // If the from address is known to the client, we don't need to send it.
594 if (locked() && (from_addr == default_dest_)) {
595 Send(data, size);
596 return;
597 }
598
599 // Wrap the given data in a data-indication packet.
600
601 RelayMessage msg;
602 msg.SetType(STUN_DATA_INDICATION);
603
zsteinf42cc9d2017-03-27 16:17:19 -0700604 auto magic_cookie_attr =
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000605 StunAttribute::CreateByteString(cricket::STUN_ATTR_MAGIC_COOKIE);
606 magic_cookie_attr->CopyBytes(binding_->magic_cookie().c_str(),
607 binding_->magic_cookie().size());
zsteinf42cc9d2017-03-27 16:17:19 -0700608 msg.AddAttribute(std::move(magic_cookie_attr));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000609
zsteinf42cc9d2017-03-27 16:17:19 -0700610 auto addr_attr = StunAttribute::CreateAddress(STUN_ATTR_SOURCE_ADDRESS2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000611 addr_attr->SetIP(from_addr.ipaddr());
612 addr_attr->SetPort(from_addr.port());
zsteinf42cc9d2017-03-27 16:17:19 -0700613 msg.AddAttribute(std::move(addr_attr));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000614
zsteinf42cc9d2017-03-27 16:17:19 -0700615 auto data_attr = StunAttribute::CreateByteString(STUN_ATTR_DATA);
nisseede5da42017-01-12 05:15:36 -0800616 RTC_DCHECK(size <= 65536);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200617 data_attr->CopyBytes(data, uint16_t(size));
zsteinf42cc9d2017-03-27 16:17:19 -0700618 msg.AddAttribute(std::move(data_attr));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000619
620 SendStun(msg);
621}
622
623void RelayServerConnection::SendStun(const StunMessage& msg) {
624 // Note that the binding has been used again.
625 binding_->NoteUsed();
626
627 cricket::SendStun(msg, socket_, addr_pair_.source());
628}
629
630void RelayServerConnection::SendStunError(
631 const StunMessage& request, int error_code, const char* error_desc) {
632 // An error does not indicate use. If no legitimate use off the binding
633 // occurs, we want it to be cleaned up even if errors are still occuring.
634
635 cricket::SendStunError(
636 request, socket_, addr_pair_.source(), error_code, error_desc,
637 binding_->magic_cookie());
638}
639
640void RelayServerConnection::Lock() {
641 locked_ = true;
642}
643
644void RelayServerConnection::Unlock() {
645 locked_ = false;
646}
647
648// IDs used for posted messages:
Peter Boström0c4e06b2015-10-07 12:23:21 +0200649const uint32_t MSG_LIFETIME_TIMER = 1;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000650
Peter Boström0c4e06b2015-10-07 12:23:21 +0200651RelayServerBinding::RelayServerBinding(RelayServer* server,
652 const std::string& username,
653 const std::string& password,
honghaiz34b11eb2016-03-16 08:55:44 -0700654 int lifetime)
Peter Boström0c4e06b2015-10-07 12:23:21 +0200655 : server_(server),
656 username_(username),
657 password_(password),
658 lifetime_(lifetime) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000659 // For now, every connection uses the standard magic cookie value.
660 magic_cookie_.append(
661 reinterpret_cast<const char*>(TURN_MAGIC_COOKIE_VALUE),
662 sizeof(TURN_MAGIC_COOKIE_VALUE));
663
664 // Initialize the last-used time to now.
665 NoteUsed();
666
667 // Set the first timeout check.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700668 server_->thread()->PostDelayed(RTC_FROM_HERE, lifetime_, this,
669 MSG_LIFETIME_TIMER);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000670}
671
672RelayServerBinding::~RelayServerBinding() {
673 // Clear the outstanding timeout check.
674 server_->thread()->Clear(this);
675
676 // Clean up all of the connections.
677 for (size_t i = 0; i < internal_connections_.size(); ++i)
678 delete internal_connections_[i];
679 for (size_t i = 0; i < external_connections_.size(); ++i)
680 delete external_connections_[i];
681
682 // Remove this binding from the server's map.
683 server_->RemoveBinding(this);
684}
685
686void RelayServerBinding::AddInternalConnection(RelayServerConnection* conn) {
687 internal_connections_.push_back(conn);
688}
689
690void RelayServerBinding::AddExternalConnection(RelayServerConnection* conn) {
691 external_connections_.push_back(conn);
692}
693
694void RelayServerBinding::NoteUsed() {
nisse1bffc1d2016-05-02 08:18:55 -0700695 last_used_ = rtc::TimeMillis();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000696}
697
698bool RelayServerBinding::HasMagicCookie(const char* bytes, size_t size) const {
699 if (size < 24 + magic_cookie_.size()) {
700 return false;
701 } else {
702 return memcmp(bytes + 24, magic_cookie_.c_str(), magic_cookie_.size()) == 0;
703 }
704}
705
706RelayServerConnection* RelayServerBinding::GetInternalConnection(
707 const rtc::SocketAddress& ext_addr) {
708
709 // Look for an internal connection that is locked to this address.
710 for (size_t i = 0; i < internal_connections_.size(); ++i) {
711 if (internal_connections_[i]->locked() &&
712 (ext_addr == internal_connections_[i]->default_destination()))
713 return internal_connections_[i];
714 }
715
716 // If one was not found, we send to the first connection.
nisseede5da42017-01-12 05:15:36 -0800717 RTC_DCHECK(internal_connections_.size() > 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000718 return internal_connections_[0];
719}
720
721RelayServerConnection* RelayServerBinding::GetExternalConnection(
722 const rtc::SocketAddress& ext_addr) {
723 for (size_t i = 0; i < external_connections_.size(); ++i) {
724 if (ext_addr == external_connections_[i]->addr_pair().source())
725 return external_connections_[i];
726 }
727 return 0;
728}
729
730void RelayServerBinding::OnMessage(rtc::Message *pmsg) {
731 if (pmsg->message_id == MSG_LIFETIME_TIMER) {
nisseede5da42017-01-12 05:15:36 -0800732 RTC_DCHECK(!pmsg->pdata);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000733
734 // If the lifetime timeout has been exceeded, then send a signal.
735 // Otherwise, just keep waiting.
nisse1bffc1d2016-05-02 08:18:55 -0700736 if (rtc::TimeMillis() >= last_used_ + lifetime_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000737 LOG(LS_INFO) << "Expiring binding " << username_;
738 SignalTimeout(this);
739 } else {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700740 server_->thread()->PostDelayed(RTC_FROM_HERE, lifetime_, this,
741 MSG_LIFETIME_TIMER);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000742 }
743
744 } else {
nissec80e7412017-01-11 05:56:46 -0800745 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000746 }
747}
748
749} // namespace cricket