blob: aad0070d345a190bde89f9fbdd1b0c735491806c [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
19#include "webrtc/base/asynctcpsocket.h"
20#include "webrtc/base/helpers.h"
21#include "webrtc/base/logging.h"
22#include "webrtc/base/socketadapters.h"
23
24namespace cricket {
25
26// By default, we require a ping every 90 seconds.
27const int MAX_LIFETIME = 15 * 60 * 1000;
28
29// The number of bytes in each of the usernames we use.
Peter Boström0c4e06b2015-10-07 12:23:21 +020030const uint32_t USERNAME_LENGTH = 16;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000031
32// Calls SendTo on the given socket and logs any bad results.
33void Send(rtc::AsyncPacketSocket* socket, const char* bytes, size_t size,
34 const rtc::SocketAddress& addr) {
35 rtc::PacketOptions options;
36 int result = socket->SendTo(bytes, size, addr, options);
37 if (result < static_cast<int>(size)) {
38 LOG(LS_ERROR) << "SendTo wrote only " << result << " of " << size
39 << " bytes";
40 } else if (result < 0) {
41 LOG_ERR(LS_ERROR) << "SendTo";
42 }
43}
44
45// Sends the given STUN message on the given socket.
46void SendStun(const StunMessage& msg,
47 rtc::AsyncPacketSocket* socket,
48 const rtc::SocketAddress& addr) {
49 rtc::ByteBuffer buf;
50 msg.Write(&buf);
51 Send(socket, buf.Data(), buf.Length(), addr);
52}
53
54// Constructs a STUN error response and sends it on the given socket.
55void SendStunError(const StunMessage& msg, rtc::AsyncPacketSocket* socket,
56 const rtc::SocketAddress& remote_addr, int error_code,
57 const char* error_desc, const std::string& magic_cookie) {
58 RelayMessage err_msg;
59 err_msg.SetType(GetStunErrorResponseType(msg.type()));
60 err_msg.SetTransactionID(msg.transaction_id());
61
62 StunByteStringAttribute* magic_cookie_attr =
63 StunAttribute::CreateByteString(cricket::STUN_ATTR_MAGIC_COOKIE);
64 if (magic_cookie.size() == 0) {
65 magic_cookie_attr->CopyBytes(cricket::TURN_MAGIC_COOKIE_VALUE,
66 sizeof(cricket::TURN_MAGIC_COOKIE_VALUE));
67 } else {
68 magic_cookie_attr->CopyBytes(magic_cookie.c_str(), magic_cookie.size());
69 }
70 err_msg.AddAttribute(magic_cookie_attr);
71
72 StunErrorCodeAttribute* err_code = StunAttribute::CreateErrorCode();
73 err_code->SetClass(error_code / 100);
74 err_code->SetNumber(error_code % 100);
75 err_code->SetReason(error_desc);
76 err_msg.AddAttribute(err_code);
77
78 SendStun(err_msg, socket, remote_addr);
79}
80
81RelayServer::RelayServer(rtc::Thread* thread)
82 : thread_(thread), log_bindings_(true) {
83}
84
85RelayServer::~RelayServer() {
86 // Deleting the binding will cause it to be removed from the map.
87 while (!bindings_.empty())
88 delete bindings_.begin()->second;
89 for (size_t i = 0; i < internal_sockets_.size(); ++i)
90 delete internal_sockets_[i];
91 for (size_t i = 0; i < external_sockets_.size(); ++i)
92 delete external_sockets_[i];
93 for (size_t i = 0; i < removed_sockets_.size(); ++i)
94 delete removed_sockets_[i];
95 while (!server_sockets_.empty()) {
96 rtc::AsyncSocket* socket = server_sockets_.begin()->first;
97 server_sockets_.erase(server_sockets_.begin()->first);
98 delete socket;
99 }
100}
101
102void RelayServer::AddInternalSocket(rtc::AsyncPacketSocket* socket) {
103 ASSERT(internal_sockets_.end() ==
104 std::find(internal_sockets_.begin(), internal_sockets_.end(), socket));
105 internal_sockets_.push_back(socket);
106 socket->SignalReadPacket.connect(this, &RelayServer::OnInternalPacket);
107}
108
109void RelayServer::RemoveInternalSocket(rtc::AsyncPacketSocket* socket) {
110 SocketList::iterator iter =
111 std::find(internal_sockets_.begin(), internal_sockets_.end(), socket);
112 ASSERT(iter != internal_sockets_.end());
113 internal_sockets_.erase(iter);
114 removed_sockets_.push_back(socket);
115 socket->SignalReadPacket.disconnect(this);
116}
117
118void RelayServer::AddExternalSocket(rtc::AsyncPacketSocket* socket) {
119 ASSERT(external_sockets_.end() ==
120 std::find(external_sockets_.begin(), external_sockets_.end(), socket));
121 external_sockets_.push_back(socket);
122 socket->SignalReadPacket.connect(this, &RelayServer::OnExternalPacket);
123}
124
125void RelayServer::RemoveExternalSocket(rtc::AsyncPacketSocket* socket) {
126 SocketList::iterator iter =
127 std::find(external_sockets_.begin(), external_sockets_.end(), socket);
128 ASSERT(iter != external_sockets_.end());
129 external_sockets_.erase(iter);
130 removed_sockets_.push_back(socket);
131 socket->SignalReadPacket.disconnect(this);
132}
133
134void RelayServer::AddInternalServerSocket(rtc::AsyncSocket* socket,
135 cricket::ProtocolType proto) {
136 ASSERT(server_sockets_.end() ==
137 server_sockets_.find(socket));
138 server_sockets_[socket] = proto;
139 socket->SignalReadEvent.connect(this, &RelayServer::OnReadEvent);
140}
141
142void RelayServer::RemoveInternalServerSocket(
143 rtc::AsyncSocket* socket) {
144 ServerSocketMap::iterator iter = server_sockets_.find(socket);
145 ASSERT(iter != server_sockets_.end());
146 server_sockets_.erase(iter);
147 socket->SignalReadEvent.disconnect(this);
148}
149
150int RelayServer::GetConnectionCount() const {
151 return static_cast<int>(connections_.size());
152}
153
154rtc::SocketAddressPair RelayServer::GetConnection(int connection) const {
155 int i = 0;
156 for (ConnectionMap::const_iterator it = connections_.begin();
157 it != connections_.end(); ++it) {
158 if (i == connection) {
159 return it->second->addr_pair();
160 }
161 ++i;
162 }
163 return rtc::SocketAddressPair();
164}
165
166bool RelayServer::HasConnection(const rtc::SocketAddress& address) const {
167 for (ConnectionMap::const_iterator it = connections_.begin();
168 it != connections_.end(); ++it) {
169 if (it->second->addr_pair().destination() == address) {
170 return true;
171 }
172 }
173 return false;
174}
175
176void RelayServer::OnReadEvent(rtc::AsyncSocket* socket) {
177 ASSERT(server_sockets_.find(socket) != server_sockets_.end());
178 AcceptConnection(socket);
179}
180
181void RelayServer::OnInternalPacket(
182 rtc::AsyncPacketSocket* socket, const char* bytes, size_t size,
183 const rtc::SocketAddress& remote_addr,
184 const rtc::PacketTime& packet_time) {
185
186 // Get the address of the connection we just received on.
187 rtc::SocketAddressPair ap(remote_addr, socket->GetLocalAddress());
188 ASSERT(!ap.destination().IsNil());
189
190 // If this did not come from an existing connection, it should be a STUN
191 // allocate request.
192 ConnectionMap::iterator piter = connections_.find(ap);
193 if (piter == connections_.end()) {
194 HandleStunAllocate(bytes, size, ap, socket);
195 return;
196 }
197
198 RelayServerConnection* int_conn = piter->second;
199
200 // Handle STUN requests to the server itself.
201 if (int_conn->binding()->HasMagicCookie(bytes, size)) {
202 HandleStun(int_conn, bytes, size);
203 return;
204 }
205
206 // Otherwise, this is a non-wrapped packet that we are to forward. Make sure
207 // that this connection has been locked. (Otherwise, we would not know what
208 // address to forward to.)
209 if (!int_conn->locked()) {
210 LOG(LS_WARNING) << "Dropping packet: connection not locked";
211 return;
212 }
213
214 // Forward this to the destination address into the connection.
215 RelayServerConnection* ext_conn = int_conn->binding()->GetExternalConnection(
216 int_conn->default_destination());
217 if (ext_conn && ext_conn->locked()) {
218 // TODO: Check the HMAC.
219 ext_conn->Send(bytes, size);
220 } else {
221 // This happens very often and is not an error.
222 LOG(LS_INFO) << "Dropping packet: no external connection";
223 }
224}
225
226void RelayServer::OnExternalPacket(
227 rtc::AsyncPacketSocket* socket, const char* bytes, size_t size,
228 const rtc::SocketAddress& remote_addr,
229 const rtc::PacketTime& packet_time) {
230
231 // Get the address of the connection we just received on.
232 rtc::SocketAddressPair ap(remote_addr, socket->GetLocalAddress());
233 ASSERT(!ap.destination().IsNil());
234
235 // If this connection already exists, then forward the traffic.
236 ConnectionMap::iterator piter = connections_.find(ap);
237 if (piter != connections_.end()) {
238 // TODO: Check the HMAC.
239 RelayServerConnection* ext_conn = piter->second;
240 RelayServerConnection* int_conn =
241 ext_conn->binding()->GetInternalConnection(
242 ext_conn->addr_pair().source());
243 ASSERT(int_conn != NULL);
244 int_conn->Send(bytes, size, ext_conn->addr_pair().source());
245 ext_conn->Lock(); // allow outgoing packets
246 return;
247 }
248
249 // The first packet should always be a STUN / TURN packet. If it isn't, then
250 // we should just ignore this packet.
251 RelayMessage msg;
252 rtc::ByteBuffer buf(bytes, size);
253 if (!msg.Read(&buf)) {
254 LOG(LS_WARNING) << "Dropping packet: first packet not STUN";
255 return;
256 }
257
258 // The initial packet should have a username (which identifies the binding).
259 const StunByteStringAttribute* username_attr =
260 msg.GetByteString(STUN_ATTR_USERNAME);
261 if (!username_attr) {
262 LOG(LS_WARNING) << "Dropping packet: no username";
263 return;
264 }
265
Peter Boström0c4e06b2015-10-07 12:23:21 +0200266 uint32_t length =
267 std::min(static_cast<uint32_t>(username_attr->length()), USERNAME_LENGTH);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000268 std::string username(username_attr->bytes(), length);
269 // TODO: Check the HMAC.
270
271 // The binding should already be present.
272 BindingMap::iterator biter = bindings_.find(username);
273 if (biter == bindings_.end()) {
274 LOG(LS_WARNING) << "Dropping packet: no binding with username";
275 return;
276 }
277
278 // Add this authenticted connection to the binding.
279 RelayServerConnection* ext_conn =
280 new RelayServerConnection(biter->second, ap, socket);
281 ext_conn->binding()->AddExternalConnection(ext_conn);
282 AddConnection(ext_conn);
283
284 // We always know where external packets should be forwarded, so we can lock
285 // them from the beginning.
286 ext_conn->Lock();
287
288 // Send this message on the appropriate internal connection.
289 RelayServerConnection* int_conn = ext_conn->binding()->GetInternalConnection(
290 ext_conn->addr_pair().source());
291 ASSERT(int_conn != NULL);
292 int_conn->Send(bytes, size, ext_conn->addr_pair().source());
293}
294
295bool RelayServer::HandleStun(
296 const char* bytes, size_t size, const rtc::SocketAddress& remote_addr,
297 rtc::AsyncPacketSocket* socket, std::string* username,
298 StunMessage* msg) {
299
300 // Parse this into a stun message. Eat the message if this fails.
301 rtc::ByteBuffer buf(bytes, size);
302 if (!msg->Read(&buf)) {
303 return false;
304 }
305
306 // The initial packet should have a username (which identifies the binding).
307 const StunByteStringAttribute* username_attr =
308 msg->GetByteString(STUN_ATTR_USERNAME);
309 if (!username_attr) {
310 SendStunError(*msg, socket, remote_addr, 432, "Missing Username", "");
311 return false;
312 }
313
314 // Record the username if requested.
315 if (username)
316 username->append(username_attr->bytes(), username_attr->length());
317
318 // TODO: Check for unknown attributes (<= 0x7fff)
319
320 return true;
321}
322
323void RelayServer::HandleStunAllocate(
324 const char* bytes, size_t size, const rtc::SocketAddressPair& ap,
325 rtc::AsyncPacketSocket* socket) {
326
327 // Make sure this is a valid STUN request.
328 RelayMessage request;
329 std::string username;
330 if (!HandleStun(bytes, size, ap.source(), socket, &username, &request))
331 return;
332
333 // Make sure this is a an allocate request.
334 if (request.type() != STUN_ALLOCATE_REQUEST) {
335 SendStunError(request,
336 socket,
337 ap.source(),
338 600,
339 "Operation Not Supported",
340 "");
341 return;
342 }
343
344 // TODO: Check the HMAC.
345
346 // Find or create the binding for this username.
347
348 RelayServerBinding* binding;
349
350 BindingMap::iterator biter = bindings_.find(username);
351 if (biter != bindings_.end()) {
352 binding = biter->second;
353 } else {
354 // NOTE: In the future, bindings will be created by the bot only. This
355 // else-branch will then disappear.
356
357 // Compute the appropriate lifetime for this binding.
honghaiz34b11eb2016-03-16 08:55:44 -0700358 int lifetime = MAX_LIFETIME;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000359 const StunUInt32Attribute* lifetime_attr =
360 request.GetUInt32(STUN_ATTR_LIFETIME);
361 if (lifetime_attr)
honghaiz34b11eb2016-03-16 08:55:44 -0700362 lifetime =
363 std::min(lifetime, static_cast<int>(lifetime_attr->value() * 1000));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000364
365 binding = new RelayServerBinding(this, username, "0", lifetime);
366 binding->SignalTimeout.connect(this, &RelayServer::OnTimeout);
367 bindings_[username] = binding;
368
369 if (log_bindings_) {
370 LOG(LS_INFO) << "Added new binding " << username << ", "
371 << bindings_.size() << " total";
372 }
373 }
374
375 // Add this connection to the binding. It starts out unlocked.
376 RelayServerConnection* int_conn =
377 new RelayServerConnection(binding, ap, socket);
378 binding->AddInternalConnection(int_conn);
379 AddConnection(int_conn);
380
381 // Now that we have a connection, this other method takes over.
382 HandleStunAllocate(int_conn, request);
383}
384
385void RelayServer::HandleStun(
386 RelayServerConnection* int_conn, const char* bytes, size_t size) {
387
388 // Make sure this is a valid STUN request.
389 RelayMessage request;
390 std::string username;
391 if (!HandleStun(bytes, size, int_conn->addr_pair().source(),
392 int_conn->socket(), &username, &request))
393 return;
394
395 // Make sure the username is the one were were expecting.
396 if (username != int_conn->binding()->username()) {
397 int_conn->SendStunError(request, 430, "Stale Credentials");
398 return;
399 }
400
401 // TODO: Check the HMAC.
402
403 // Send this request to the appropriate handler.
404 if (request.type() == STUN_SEND_REQUEST)
405 HandleStunSend(int_conn, request);
406 else if (request.type() == STUN_ALLOCATE_REQUEST)
407 HandleStunAllocate(int_conn, request);
408 else
409 int_conn->SendStunError(request, 600, "Operation Not Supported");
410}
411
412void RelayServer::HandleStunAllocate(
413 RelayServerConnection* int_conn, const StunMessage& request) {
414
415 // Create a response message that includes an address with which external
416 // clients can communicate.
417
418 RelayMessage response;
419 response.SetType(STUN_ALLOCATE_RESPONSE);
420 response.SetTransactionID(request.transaction_id());
421
422 StunByteStringAttribute* magic_cookie_attr =
423 StunAttribute::CreateByteString(cricket::STUN_ATTR_MAGIC_COOKIE);
424 magic_cookie_attr->CopyBytes(int_conn->binding()->magic_cookie().c_str(),
425 int_conn->binding()->magic_cookie().size());
426 response.AddAttribute(magic_cookie_attr);
427
428 size_t index = rand() % external_sockets_.size();
429 rtc::SocketAddress ext_addr =
430 external_sockets_[index]->GetLocalAddress();
431
432 StunAddressAttribute* addr_attr =
433 StunAttribute::CreateAddress(STUN_ATTR_MAPPED_ADDRESS);
434 addr_attr->SetIP(ext_addr.ipaddr());
435 addr_attr->SetPort(ext_addr.port());
436 response.AddAttribute(addr_attr);
437
438 StunUInt32Attribute* res_lifetime_attr =
439 StunAttribute::CreateUInt32(STUN_ATTR_LIFETIME);
440 res_lifetime_attr->SetValue(int_conn->binding()->lifetime() / 1000);
441 response.AddAttribute(res_lifetime_attr);
442
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.
473 ASSERT(external_sockets_.size() == 1);
474 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
495 StunByteStringAttribute* magic_cookie_attr =
496 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());
499 response.AddAttribute(magic_cookie_attr);
500
501 StunUInt32Attribute* options2_attr =
502 StunAttribute::CreateUInt32(cricket::STUN_ATTR_OPTIONS);
503 options2_attr->SetValue(0x01);
504 response.AddAttribute(options2_attr);
505
506 int_conn->SendStun(response);
507 }
508}
509
510void RelayServer::AddConnection(RelayServerConnection* conn) {
511 ASSERT(connections_.find(conn->addr_pair()) == connections_.end());
512 connections_[conn->addr_pair()] = conn;
513}
514
515void RelayServer::RemoveConnection(RelayServerConnection* conn) {
516 ConnectionMap::iterator iter = connections_.find(conn->addr_pair());
517 ASSERT(iter != connections_.end());
518 connections_.erase(iter);
519}
520
521void RelayServer::RemoveBinding(RelayServerBinding* binding) {
522 BindingMap::iterator iter = bindings_.find(binding->username());
523 ASSERT(iter != bindings_.end());
524 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) {
533#if ENABLE_DEBUG
Peter Boström0c4e06b2015-10-07 12:23:21 +0200534 static const uint32_t kMessageAcceptConnection = 1;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000535 ASSERT(pmsg->message_id == kMessageAcceptConnection);
536#endif
537 rtc::MessageData* data = pmsg->pdata;
538 rtc::AsyncSocket* socket =
539 static_cast <rtc::TypedMessageData<rtc::AsyncSocket*>*>
540 (data)->data();
541 AcceptConnection(socket);
542 delete data;
543}
544
545void RelayServer::OnTimeout(RelayServerBinding* binding) {
546 // This call will result in all of the necessary clean-up. We can't call
547 // delete here, because you can't delete an object that is signaling you.
548 thread_->Dispose(binding);
549}
550
551void RelayServer::AcceptConnection(rtc::AsyncSocket* server_socket) {
552 // Check if someone is trying to connect to us.
553 rtc::SocketAddress accept_addr;
554 rtc::AsyncSocket* accepted_socket =
555 server_socket->Accept(&accept_addr);
556 if (accepted_socket != NULL) {
557 // We had someone trying to connect, now check which protocol to
558 // use and create a packet socket.
559 ASSERT(server_sockets_[server_socket] == cricket::PROTO_TCP ||
560 server_sockets_[server_socket] == cricket::PROTO_SSLTCP);
561 if (server_sockets_[server_socket] == cricket::PROTO_SSLTCP) {
562 accepted_socket = new rtc::AsyncSSLServerSocket(accepted_socket);
563 }
564 rtc::AsyncTCPSocket* tcp_socket =
565 new rtc::AsyncTCPSocket(accepted_socket, false);
566
567 // Finally add the socket so it can start communicating with the client.
568 AddInternalSocket(tcp_socket);
569 }
570}
571
572RelayServerConnection::RelayServerConnection(
573 RelayServerBinding* binding, const rtc::SocketAddressPair& addrs,
574 rtc::AsyncPacketSocket* socket)
575 : binding_(binding), addr_pair_(addrs), socket_(socket), locked_(false) {
576 // The creation of a new connection constitutes a use of the binding.
577 binding_->NoteUsed();
578}
579
580RelayServerConnection::~RelayServerConnection() {
581 // Remove this connection from the server's map (if it exists there).
582 binding_->server()->RemoveConnection(this);
583}
584
585void RelayServerConnection::Send(const char* data, size_t size) {
586 // Note that the binding has been used again.
587 binding_->NoteUsed();
588
589 cricket::Send(socket_, data, size, addr_pair_.source());
590}
591
592void RelayServerConnection::Send(
593 const char* data, size_t size, const rtc::SocketAddress& from_addr) {
594 // If the from address is known to the client, we don't need to send it.
595 if (locked() && (from_addr == default_dest_)) {
596 Send(data, size);
597 return;
598 }
599
600 // Wrap the given data in a data-indication packet.
601
602 RelayMessage msg;
603 msg.SetType(STUN_DATA_INDICATION);
604
605 StunByteStringAttribute* magic_cookie_attr =
606 StunAttribute::CreateByteString(cricket::STUN_ATTR_MAGIC_COOKIE);
607 magic_cookie_attr->CopyBytes(binding_->magic_cookie().c_str(),
608 binding_->magic_cookie().size());
609 msg.AddAttribute(magic_cookie_attr);
610
611 StunAddressAttribute* addr_attr =
612 StunAttribute::CreateAddress(STUN_ATTR_SOURCE_ADDRESS2);
613 addr_attr->SetIP(from_addr.ipaddr());
614 addr_attr->SetPort(from_addr.port());
615 msg.AddAttribute(addr_attr);
616
617 StunByteStringAttribute* data_attr =
618 StunAttribute::CreateByteString(STUN_ATTR_DATA);
619 ASSERT(size <= 65536);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200620 data_attr->CopyBytes(data, uint16_t(size));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000621 msg.AddAttribute(data_attr);
622
623 SendStun(msg);
624}
625
626void RelayServerConnection::SendStun(const StunMessage& msg) {
627 // Note that the binding has been used again.
628 binding_->NoteUsed();
629
630 cricket::SendStun(msg, socket_, addr_pair_.source());
631}
632
633void RelayServerConnection::SendStunError(
634 const StunMessage& request, int error_code, const char* error_desc) {
635 // An error does not indicate use. If no legitimate use off the binding
636 // occurs, we want it to be cleaned up even if errors are still occuring.
637
638 cricket::SendStunError(
639 request, socket_, addr_pair_.source(), error_code, error_desc,
640 binding_->magic_cookie());
641}
642
643void RelayServerConnection::Lock() {
644 locked_ = true;
645}
646
647void RelayServerConnection::Unlock() {
648 locked_ = false;
649}
650
651// IDs used for posted messages:
Peter Boström0c4e06b2015-10-07 12:23:21 +0200652const uint32_t MSG_LIFETIME_TIMER = 1;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000653
Peter Boström0c4e06b2015-10-07 12:23:21 +0200654RelayServerBinding::RelayServerBinding(RelayServer* server,
655 const std::string& username,
656 const std::string& password,
honghaiz34b11eb2016-03-16 08:55:44 -0700657 int lifetime)
Peter Boström0c4e06b2015-10-07 12:23:21 +0200658 : server_(server),
659 username_(username),
660 password_(password),
661 lifetime_(lifetime) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000662 // For now, every connection uses the standard magic cookie value.
663 magic_cookie_.append(
664 reinterpret_cast<const char*>(TURN_MAGIC_COOKIE_VALUE),
665 sizeof(TURN_MAGIC_COOKIE_VALUE));
666
667 // Initialize the last-used time to now.
668 NoteUsed();
669
670 // Set the first timeout check.
671 server_->thread()->PostDelayed(lifetime_, this, MSG_LIFETIME_TIMER);
672}
673
674RelayServerBinding::~RelayServerBinding() {
675 // Clear the outstanding timeout check.
676 server_->thread()->Clear(this);
677
678 // Clean up all of the connections.
679 for (size_t i = 0; i < internal_connections_.size(); ++i)
680 delete internal_connections_[i];
681 for (size_t i = 0; i < external_connections_.size(); ++i)
682 delete external_connections_[i];
683
684 // Remove this binding from the server's map.
685 server_->RemoveBinding(this);
686}
687
688void RelayServerBinding::AddInternalConnection(RelayServerConnection* conn) {
689 internal_connections_.push_back(conn);
690}
691
692void RelayServerBinding::AddExternalConnection(RelayServerConnection* conn) {
693 external_connections_.push_back(conn);
694}
695
696void RelayServerBinding::NoteUsed() {
honghaiz34b11eb2016-03-16 08:55:44 -0700697 last_used_ = rtc::Time64();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000698}
699
700bool RelayServerBinding::HasMagicCookie(const char* bytes, size_t size) const {
701 if (size < 24 + magic_cookie_.size()) {
702 return false;
703 } else {
704 return memcmp(bytes + 24, magic_cookie_.c_str(), magic_cookie_.size()) == 0;
705 }
706}
707
708RelayServerConnection* RelayServerBinding::GetInternalConnection(
709 const rtc::SocketAddress& ext_addr) {
710
711 // Look for an internal connection that is locked to this address.
712 for (size_t i = 0; i < internal_connections_.size(); ++i) {
713 if (internal_connections_[i]->locked() &&
714 (ext_addr == internal_connections_[i]->default_destination()))
715 return internal_connections_[i];
716 }
717
718 // If one was not found, we send to the first connection.
719 ASSERT(internal_connections_.size() > 0);
720 return internal_connections_[0];
721}
722
723RelayServerConnection* RelayServerBinding::GetExternalConnection(
724 const rtc::SocketAddress& ext_addr) {
725 for (size_t i = 0; i < external_connections_.size(); ++i) {
726 if (ext_addr == external_connections_[i]->addr_pair().source())
727 return external_connections_[i];
728 }
729 return 0;
730}
731
732void RelayServerBinding::OnMessage(rtc::Message *pmsg) {
733 if (pmsg->message_id == MSG_LIFETIME_TIMER) {
734 ASSERT(!pmsg->pdata);
735
736 // If the lifetime timeout has been exceeded, then send a signal.
737 // Otherwise, just keep waiting.
honghaiz34b11eb2016-03-16 08:55:44 -0700738 if (rtc::Time64() >= last_used_ + lifetime_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000739 LOG(LS_INFO) << "Expiring binding " << username_;
740 SignalTimeout(this);
741 } else {
742 server_->thread()->PostDelayed(lifetime_, this, MSG_LIFETIME_TIMER);
743 }
744
745 } else {
746 ASSERT(false);
747 }
748}
749
750} // namespace cricket