3
* Copyright 2004--2005, Google Inc.
5
* Redistribution and use in source and binary forms, with or without
6
* modification, are permitted provided that the following conditions are met:
8
* 1. Redistributions of source code must retain the above copyright notice,
9
* this list of conditions and the following disclaimer.
10
* 2. Redistributions in binary form must reproduce the above copyright notice,
11
* this list of conditions and the following disclaimer in the documentation
12
* and/or other materials provided with the distribution.
13
* 3. The name of the author may not be used to endorse or promote products
14
* derived from this software without specific prior written permission.
16
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
#include "talk/p2p/base/relayserver.h"
36
#include "talk/base/asynctcpsocket.h"
37
#include "talk/base/helpers.h"
38
#include "talk/base/logging.h"
39
#include "talk/base/socketadapters.h"
43
// By default, we require a ping every 90 seconds.
44
const int MAX_LIFETIME = 15 * 60 * 1000;
46
// The number of bytes in each of the usernames we use.
47
const uint32 USERNAME_LENGTH = 16;
49
static const uint32 kMessageAcceptConnection = 1;
51
// Calls SendTo on the given socket and logs any bad results.
52
void Send(talk_base::AsyncPacketSocket* socket, const char* bytes, size_t size,
53
const talk_base::SocketAddress& addr) {
54
int result = socket->SendTo(bytes, size, addr);
55
if (result < static_cast<int>(size)) {
56
LOG(LS_ERROR) << "SendTo wrote only " << result << " of " << size
58
} else if (result < 0) {
59
LOG_ERR(LS_ERROR) << "SendTo";
63
// Sends the given STUN message on the given socket.
64
void SendStun(const StunMessage& msg,
65
talk_base::AsyncPacketSocket* socket,
66
const talk_base::SocketAddress& addr) {
67
talk_base::ByteBuffer buf;
69
Send(socket, buf.Data(), buf.Length(), addr);
72
// Constructs a STUN error response and sends it on the given socket.
73
void SendStunError(const StunMessage& msg, talk_base::AsyncPacketSocket* socket,
74
const talk_base::SocketAddress& remote_addr, int error_code,
75
const char* error_desc, const std::string& magic_cookie) {
77
err_msg.SetType(GetStunErrorResponseType(msg.type()));
78
err_msg.SetTransactionID(msg.transaction_id());
80
StunByteStringAttribute* magic_cookie_attr =
81
StunAttribute::CreateByteString(cricket::STUN_ATTR_MAGIC_COOKIE);
82
if (magic_cookie.size() == 0) {
83
magic_cookie_attr->CopyBytes(cricket::TURN_MAGIC_COOKIE_VALUE,
84
sizeof(cricket::TURN_MAGIC_COOKIE_VALUE));
86
magic_cookie_attr->CopyBytes(magic_cookie.c_str(), magic_cookie.size());
88
err_msg.AddAttribute(magic_cookie_attr);
90
StunErrorCodeAttribute* err_code = StunAttribute::CreateErrorCode();
91
err_code->SetErrorClass(error_code / 100);
92
err_code->SetNumber(error_code % 100);
93
err_code->SetReason(error_desc);
94
err_msg.AddAttribute(err_code);
96
SendStun(err_msg, socket, remote_addr);
99
RelayServer::RelayServer(talk_base::Thread* thread)
100
: thread_(thread), log_bindings_(true) {
103
RelayServer::~RelayServer() {
104
// Deleting the binding will cause it to be removed from the map.
105
while (!bindings_.empty())
106
delete bindings_.begin()->second;
107
for (size_t i = 0; i < internal_sockets_.size(); ++i)
108
delete internal_sockets_[i];
109
for (size_t i = 0; i < external_sockets_.size(); ++i)
110
delete external_sockets_[i];
111
while (!server_sockets_.empty()) {
112
talk_base::AsyncSocket* socket = server_sockets_.begin()->first;
113
server_sockets_.erase(server_sockets_.begin()->first);
118
void RelayServer::AddInternalSocket(talk_base::AsyncPacketSocket* socket) {
119
ASSERT(internal_sockets_.end() ==
120
std::find(internal_sockets_.begin(), internal_sockets_.end(), socket));
121
internal_sockets_.push_back(socket);
122
socket->SignalReadPacket.connect(this, &RelayServer::OnInternalPacket);
125
void RelayServer::RemoveInternalSocket(talk_base::AsyncPacketSocket* socket) {
126
SocketList::iterator iter =
127
std::find(internal_sockets_.begin(), internal_sockets_.end(), socket);
128
ASSERT(iter != internal_sockets_.end());
129
internal_sockets_.erase(iter);
130
socket->SignalReadPacket.disconnect(this);
133
void RelayServer::AddExternalSocket(talk_base::AsyncPacketSocket* socket) {
134
ASSERT(external_sockets_.end() ==
135
std::find(external_sockets_.begin(), external_sockets_.end(), socket));
136
external_sockets_.push_back(socket);
137
socket->SignalReadPacket.connect(this, &RelayServer::OnExternalPacket);
140
void RelayServer::RemoveExternalSocket(talk_base::AsyncPacketSocket* socket) {
141
SocketList::iterator iter =
142
std::find(external_sockets_.begin(), external_sockets_.end(), socket);
143
ASSERT(iter != external_sockets_.end());
144
external_sockets_.erase(iter);
145
socket->SignalReadPacket.disconnect(this);
148
void RelayServer::AddInternalServerSocket(talk_base::AsyncSocket* socket,
149
cricket::ProtocolType proto) {
150
ASSERT(server_sockets_.end() ==
151
server_sockets_.find(socket));
152
server_sockets_[socket] = proto;
153
socket->SignalReadEvent.connect(this, &RelayServer::OnReadEvent);
156
void RelayServer::RemoveInternalServerSocket(
157
talk_base::AsyncSocket* socket) {
158
ServerSocketMap::iterator iter = server_sockets_.find(socket);
159
ASSERT(iter != server_sockets_.end());
160
server_sockets_.erase(iter);
161
socket->SignalReadEvent.disconnect(this);
164
int RelayServer::GetConnectionCount() const {
165
return connections_.size();
168
talk_base::SocketAddressPair RelayServer::GetConnection(int connection) const {
170
for (ConnectionMap::const_iterator it = connections_.begin();
171
it != connections_.end(); ++it) {
172
if (i == connection) {
173
return it->second->addr_pair();
177
return talk_base::SocketAddressPair();
180
bool RelayServer::HasConnection(const talk_base::SocketAddress& address) const {
181
for (ConnectionMap::const_iterator it = connections_.begin();
182
it != connections_.end(); ++it) {
183
if (it->second->addr_pair().destination() == address) {
190
void RelayServer::OnReadEvent(talk_base::AsyncSocket* socket) {
191
ASSERT(server_sockets_.find(socket) != server_sockets_.end());
192
AcceptConnection(socket);
195
void RelayServer::OnInternalPacket(
196
talk_base::AsyncPacketSocket* socket, const char* bytes, size_t size,
197
const talk_base::SocketAddress& remote_addr) {
199
// Get the address of the connection we just received on.
200
talk_base::SocketAddressPair ap(remote_addr, socket->GetLocalAddress());
201
ASSERT(!ap.destination().IsAny());
203
// If this did not come from an existing connection, it should be a STUN
205
ConnectionMap::iterator piter = connections_.find(ap);
206
if (piter == connections_.end()) {
207
HandleStunAllocate(bytes, size, ap, socket);
211
RelayServerConnection* int_conn = piter->second;
213
// Handle STUN requests to the server itself.
214
if (int_conn->binding()->HasMagicCookie(bytes, size)) {
215
HandleStun(int_conn, bytes, size);
219
// Otherwise, this is a non-wrapped packet that we are to forward. Make sure
220
// that this connection has been locked. (Otherwise, we would not know what
221
// address to forward to.)
222
if (!int_conn->locked()) {
223
LOG(LS_WARNING) << "Dropping packet: connection not locked";
227
// Forward this to the destination address into the connection.
228
RelayServerConnection* ext_conn = int_conn->binding()->GetExternalConnection(
229
int_conn->default_destination());
230
if (ext_conn && ext_conn->locked()) {
231
// TODO: Check the HMAC.
232
ext_conn->Send(bytes, size);
234
// This happens very often and is not an error.
235
LOG(LS_INFO) << "Dropping packet: no external connection";
239
void RelayServer::OnExternalPacket(
240
talk_base::AsyncPacketSocket* socket, const char* bytes, size_t size,
241
const talk_base::SocketAddress& remote_addr) {
243
// Get the address of the connection we just received on.
244
talk_base::SocketAddressPair ap(remote_addr, socket->GetLocalAddress());
245
ASSERT(!ap.destination().IsAny());
247
// If this connection already exists, then forward the traffic.
248
ConnectionMap::iterator piter = connections_.find(ap);
249
if (piter != connections_.end()) {
250
// TODO: Check the HMAC.
251
RelayServerConnection* ext_conn = piter->second;
252
RelayServerConnection* int_conn =
253
ext_conn->binding()->GetInternalConnection(
254
ext_conn->addr_pair().source());
255
ASSERT(int_conn != NULL);
256
int_conn->Send(bytes, size, ext_conn->addr_pair().source());
257
ext_conn->Lock(); // allow outgoing packets
261
// The first packet should always be a STUN / TURN packet. If it isn't, then
262
// we should just ignore this packet.
264
talk_base::ByteBuffer buf(bytes, size);
265
if (!msg.Read(&buf)) {
266
LOG(LS_WARNING) << "Dropping packet: first packet not STUN";
270
// The initial packet should have a username (which identifies the binding).
271
const StunByteStringAttribute* username_attr =
272
msg.GetByteString(STUN_ATTR_USERNAME);
273
if (!username_attr) {
274
LOG(LS_WARNING) << "Dropping packet: no username";
278
uint32 length = talk_base::_min(static_cast<uint32>(username_attr->length()),
280
std::string username(username_attr->bytes(), length);
281
// TODO: Check the HMAC.
283
// The binding should already be present.
284
BindingMap::iterator biter = bindings_.find(username);
285
if (biter == bindings_.end()) {
286
LOG(LS_WARNING) << "Dropping packet: no binding with username";
290
// Add this authenticted connection to the binding.
291
RelayServerConnection* ext_conn =
292
new RelayServerConnection(biter->second, ap, socket);
293
ext_conn->binding()->AddExternalConnection(ext_conn);
294
AddConnection(ext_conn);
296
// We always know where external packets should be forwarded, so we can lock
297
// them from the beginning.
300
// Send this message on the appropriate internal connection.
301
RelayServerConnection* int_conn = ext_conn->binding()->GetInternalConnection(
302
ext_conn->addr_pair().source());
303
ASSERT(int_conn != NULL);
304
int_conn->Send(bytes, size, ext_conn->addr_pair().source());
307
bool RelayServer::HandleStun(
308
const char* bytes, size_t size, const talk_base::SocketAddress& remote_addr,
309
talk_base::AsyncPacketSocket* socket, std::string* username,
312
// Parse this into a stun message.
313
talk_base::ByteBuffer buf(bytes, size);
314
if (!msg->Read(&buf)) {
315
SendStunError(*msg, socket, remote_addr, 400, "Bad Request", "");
319
// The initial packet should have a username (which identifies the binding).
320
const StunByteStringAttribute* username_attr =
321
msg->GetByteString(STUN_ATTR_USERNAME);
322
if (!username_attr) {
323
SendStunError(*msg, socket, remote_addr, 432, "Missing Username", "");
327
// Record the username if requested.
329
username->append(username_attr->bytes(), username_attr->length());
331
// TODO: Check for unknown attributes (<= 0x7fff)
336
void RelayServer::HandleStunAllocate(
337
const char* bytes, size_t size, const talk_base::SocketAddressPair& ap,
338
talk_base::AsyncPacketSocket* socket) {
340
// Make sure this is a valid STUN request.
342
std::string username;
343
if (!HandleStun(bytes, size, ap.source(), socket, &username, &request))
346
// Make sure this is a an allocate request.
347
if (request.type() != STUN_ALLOCATE_REQUEST) {
348
SendStunError(request,
352
"Operation Not Supported",
357
// TODO: Check the HMAC.
359
// Find or create the binding for this username.
361
RelayServerBinding* binding;
363
BindingMap::iterator biter = bindings_.find(username);
364
if (biter != bindings_.end()) {
365
binding = biter->second;
367
// NOTE: In the future, bindings will be created by the bot only. This
368
// else-branch will then disappear.
370
// Compute the appropriate lifetime for this binding.
371
uint32 lifetime = MAX_LIFETIME;
372
const StunUInt32Attribute* lifetime_attr =
373
request.GetUInt32(STUN_ATTR_LIFETIME);
375
lifetime = talk_base::_min(lifetime, lifetime_attr->value() * 1000);
377
binding = new RelayServerBinding(this, username, "0", lifetime);
378
binding->SignalTimeout.connect(this, &RelayServer::OnTimeout);
379
bindings_[username] = binding;
382
LOG(LS_INFO) << "Added new binding " << username << ", "
383
<< bindings_.size() << " total";
387
// Add this connection to the binding. It starts out unlocked.
388
RelayServerConnection* int_conn =
389
new RelayServerConnection(binding, ap, socket);
390
binding->AddInternalConnection(int_conn);
391
AddConnection(int_conn);
393
// Now that we have a connection, this other method takes over.
394
HandleStunAllocate(int_conn, request);
397
void RelayServer::HandleStun(
398
RelayServerConnection* int_conn, const char* bytes, size_t size) {
400
// Make sure this is a valid STUN request.
402
std::string username;
403
if (!HandleStun(bytes, size, int_conn->addr_pair().source(),
404
int_conn->socket(), &username, &request))
407
// Make sure the username is the one were were expecting.
408
if (username != int_conn->binding()->username()) {
409
int_conn->SendStunError(request, 430, "Stale Credentials");
413
// TODO: Check the HMAC.
415
// Send this request to the appropriate handler.
416
if (request.type() == STUN_SEND_REQUEST)
417
HandleStunSend(int_conn, request);
418
else if (request.type() == STUN_ALLOCATE_REQUEST)
419
HandleStunAllocate(int_conn, request);
421
int_conn->SendStunError(request, 600, "Operation Not Supported");
424
void RelayServer::HandleStunAllocate(
425
RelayServerConnection* int_conn, const StunMessage& request) {
427
// Create a response message that includes an address with which external
428
// clients can communicate.
430
StunMessage response;
431
response.SetType(STUN_ALLOCATE_RESPONSE);
432
response.SetTransactionID(request.transaction_id());
434
StunByteStringAttribute* magic_cookie_attr =
435
StunAttribute::CreateByteString(cricket::STUN_ATTR_MAGIC_COOKIE);
436
magic_cookie_attr->CopyBytes(int_conn->binding()->magic_cookie().c_str(),
437
int_conn->binding()->magic_cookie().size());
438
response.AddAttribute(magic_cookie_attr);
440
size_t index = rand() % external_sockets_.size();
441
talk_base::SocketAddress ext_addr =
442
external_sockets_[index]->GetLocalAddress();
444
StunAddressAttribute* addr_attr =
445
StunAttribute::CreateAddress(STUN_ATTR_MAPPED_ADDRESS);
446
addr_attr->SetIP(ext_addr.ipaddr());
447
addr_attr->SetPort(ext_addr.port());
448
response.AddAttribute(addr_attr);
450
StunUInt32Attribute* res_lifetime_attr =
451
StunAttribute::CreateUInt32(STUN_ATTR_LIFETIME);
452
res_lifetime_attr->SetValue(int_conn->binding()->lifetime() / 1000);
453
response.AddAttribute(res_lifetime_attr);
455
// TODO: Support transport-prefs (preallocate RTCP port).
456
// TODO: Support bandwidth restrictions.
457
// TODO: Add message integrity check.
459
// Send a response to the caller.
460
int_conn->SendStun(response);
463
void RelayServer::HandleStunSend(
464
RelayServerConnection* int_conn, const StunMessage& request) {
466
const StunAddressAttribute* addr_attr =
467
request.GetAddress(STUN_ATTR_DESTINATION_ADDRESS);
469
int_conn->SendStunError(request, 400, "Bad Request");
473
const StunByteStringAttribute* data_attr =
474
request.GetByteString(STUN_ATTR_DATA);
476
int_conn->SendStunError(request, 400, "Bad Request");
480
talk_base::SocketAddress ext_addr(addr_attr->ipaddr(), addr_attr->port());
481
RelayServerConnection* ext_conn =
482
int_conn->binding()->GetExternalConnection(ext_addr);
484
// Create a new connection to establish the relationship with this binding.
485
ASSERT(external_sockets_.size() == 1);
486
talk_base::AsyncPacketSocket* socket = external_sockets_[0];
487
talk_base::SocketAddressPair ap(ext_addr, socket->GetLocalAddress());
488
ext_conn = new RelayServerConnection(int_conn->binding(), ap, socket);
489
ext_conn->binding()->AddExternalConnection(ext_conn);
490
AddConnection(ext_conn);
493
// If this connection has pinged us, then allow outgoing traffic.
494
if (ext_conn->locked())
495
ext_conn->Send(data_attr->bytes(), data_attr->length());
497
const StunUInt32Attribute* options_attr =
498
request.GetUInt32(STUN_ATTR_OPTIONS);
499
if (options_attr && (options_attr->value() & 0x01)) {
500
int_conn->set_default_destination(ext_addr);
503
StunMessage response;
504
response.SetType(STUN_SEND_RESPONSE);
505
response.SetTransactionID(request.transaction_id());
507
StunByteStringAttribute* magic_cookie_attr =
508
StunAttribute::CreateByteString(cricket::STUN_ATTR_MAGIC_COOKIE);
509
magic_cookie_attr->CopyBytes(int_conn->binding()->magic_cookie().c_str(),
510
int_conn->binding()->magic_cookie().size());
511
response.AddAttribute(magic_cookie_attr);
513
StunUInt32Attribute* options2_attr =
514
StunAttribute::CreateUInt32(cricket::STUN_ATTR_OPTIONS);
515
options2_attr->SetValue(0x01);
516
response.AddAttribute(options2_attr);
518
int_conn->SendStun(response);
522
void RelayServer::AddConnection(RelayServerConnection* conn) {
523
ASSERT(connections_.find(conn->addr_pair()) == connections_.end());
524
connections_[conn->addr_pair()] = conn;
527
void RelayServer::RemoveConnection(RelayServerConnection* conn) {
528
ConnectionMap::iterator iter = connections_.find(conn->addr_pair());
529
ASSERT(iter != connections_.end());
530
connections_.erase(iter);
533
void RelayServer::RemoveBinding(RelayServerBinding* binding) {
534
BindingMap::iterator iter = bindings_.find(binding->username());
535
ASSERT(iter != bindings_.end());
536
bindings_.erase(iter);
539
LOG(LS_INFO) << "Removed binding " << binding->username() << ", "
540
<< bindings_.size() << " remaining";
544
void RelayServer::OnMessage(talk_base::Message *pmsg) {
545
ASSERT(pmsg->message_id == kMessageAcceptConnection);
546
talk_base::MessageData* data = pmsg->pdata;
547
talk_base::AsyncSocket* socket =
548
static_cast <talk_base::TypedMessageData<talk_base::AsyncSocket*>*>
550
AcceptConnection(socket);
554
void RelayServer::OnTimeout(RelayServerBinding* binding) {
555
// This call will result in all of the necessary clean-up. We can't call
556
// delete here, because you can't delete an object that is signaling you.
557
thread_->Dispose(binding);
560
void RelayServer::AcceptConnection(talk_base::AsyncSocket* server_socket) {
561
// Check if someone is trying to connect to us.
562
talk_base::SocketAddress accept_addr;
563
talk_base::AsyncSocket* accepted_socket =
564
server_socket->Accept(&accept_addr);
565
if (accepted_socket != NULL) {
566
// We had someone trying to connect, now check which protocol to
567
// use and create a packet socket.
568
ASSERT(server_sockets_[server_socket] == cricket::PROTO_TCP ||
569
server_sockets_[server_socket] == cricket::PROTO_SSLTCP);
570
if (server_sockets_[server_socket] == cricket::PROTO_SSLTCP) {
571
accepted_socket = new talk_base::AsyncSSLServerSocket(accepted_socket);
573
talk_base::AsyncTCPSocket* tcp_socket =
574
new talk_base::AsyncTCPSocket(accepted_socket, false);
576
// Finally add the socket so it can start communicating with the client.
577
AddInternalSocket(tcp_socket);
581
RelayServerConnection::RelayServerConnection(
582
RelayServerBinding* binding, const talk_base::SocketAddressPair& addrs,
583
talk_base::AsyncPacketSocket* socket)
584
: binding_(binding), addr_pair_(addrs), socket_(socket), locked_(false) {
585
// The creation of a new connection constitutes a use of the binding.
586
binding_->NoteUsed();
589
RelayServerConnection::~RelayServerConnection() {
590
// Remove this connection from the server's map (if it exists there).
591
binding_->server()->RemoveConnection(this);
594
void RelayServerConnection::Send(const char* data, size_t size) {
595
// Note that the binding has been used again.
596
binding_->NoteUsed();
598
cricket::Send(socket_, data, size, addr_pair_.source());
601
void RelayServerConnection::Send(
602
const char* data, size_t size, const talk_base::SocketAddress& from_addr) {
603
// If the from address is known to the client, we don't need to send it.
604
if (locked() && (from_addr == default_dest_)) {
609
// Wrap the given data in a data-indication packet.
612
msg.SetType(STUN_DATA_INDICATION);
614
StunByteStringAttribute* magic_cookie_attr =
615
StunAttribute::CreateByteString(cricket::STUN_ATTR_MAGIC_COOKIE);
616
magic_cookie_attr->CopyBytes(binding_->magic_cookie().c_str(),
617
binding_->magic_cookie().size());
618
msg.AddAttribute(magic_cookie_attr);
620
StunAddressAttribute* addr_attr =
621
StunAttribute::CreateAddress(STUN_ATTR_SOURCE_ADDRESS2);
622
addr_attr->SetIP(from_addr.ipaddr());
623
addr_attr->SetPort(from_addr.port());
624
msg.AddAttribute(addr_attr);
626
StunByteStringAttribute* data_attr =
627
StunAttribute::CreateByteString(STUN_ATTR_DATA);
628
ASSERT(size <= 65536);
629
data_attr->CopyBytes(data, uint16(size));
630
msg.AddAttribute(data_attr);
635
void RelayServerConnection::SendStun(const StunMessage& msg) {
636
// Note that the binding has been used again.
637
binding_->NoteUsed();
639
cricket::SendStun(msg, socket_, addr_pair_.source());
642
void RelayServerConnection::SendStunError(
643
const StunMessage& request, int error_code, const char* error_desc) {
644
// An error does not indicate use. If no legitimate use off the binding
645
// occurs, we want it to be cleaned up even if errors are still occuring.
647
cricket::SendStunError(
648
request, socket_, addr_pair_.source(), error_code, error_desc,
649
binding_->magic_cookie());
652
void RelayServerConnection::Lock() {
656
void RelayServerConnection::Unlock() {
660
// IDs used for posted messages:
661
const uint32 MSG_LIFETIME_TIMER = 1;
663
RelayServerBinding::RelayServerBinding(
664
RelayServer* server, const std::string& username,
665
const std::string& password, uint32 lifetime)
666
: server_(server), username_(username), password_(password),
667
lifetime_(lifetime) {
668
// For now, every connection uses the standard magic cookie value.
669
magic_cookie_.append(
670
reinterpret_cast<const char*>(TURN_MAGIC_COOKIE_VALUE),
671
sizeof(TURN_MAGIC_COOKIE_VALUE));
673
// Initialize the last-used time to now.
676
// Set the first timeout check.
677
server_->thread()->PostDelayed(lifetime_, this, MSG_LIFETIME_TIMER);
680
RelayServerBinding::~RelayServerBinding() {
681
// Clear the outstanding timeout check.
682
server_->thread()->Clear(this);
684
// Clean up all of the connections.
685
for (size_t i = 0; i < internal_connections_.size(); ++i)
686
delete internal_connections_[i];
687
for (size_t i = 0; i < external_connections_.size(); ++i)
688
delete external_connections_[i];
690
// Remove this binding from the server's map.
691
server_->RemoveBinding(this);
694
void RelayServerBinding::AddInternalConnection(RelayServerConnection* conn) {
695
internal_connections_.push_back(conn);
698
void RelayServerBinding::AddExternalConnection(RelayServerConnection* conn) {
699
external_connections_.push_back(conn);
702
void RelayServerBinding::NoteUsed() {
703
last_used_ = talk_base::Time();
706
bool RelayServerBinding::HasMagicCookie(const char* bytes, size_t size) const {
707
if (size < 24 + magic_cookie_.size()) {
710
return 0 == std::memcmp(
711
bytes + 24, magic_cookie_.c_str(), magic_cookie_.size());
715
RelayServerConnection* RelayServerBinding::GetInternalConnection(
716
const talk_base::SocketAddress& ext_addr) {
718
// Look for an internal connection that is locked to this address.
719
for (size_t i = 0; i < internal_connections_.size(); ++i) {
720
if (internal_connections_[i]->locked() &&
721
(ext_addr == internal_connections_[i]->default_destination()))
722
return internal_connections_[i];
725
// If one was not found, we send to the first connection.
726
ASSERT(internal_connections_.size() > 0);
727
return internal_connections_[0];
730
RelayServerConnection* RelayServerBinding::GetExternalConnection(
731
const talk_base::SocketAddress& ext_addr) {
732
for (size_t i = 0; i < external_connections_.size(); ++i) {
733
if (ext_addr == external_connections_[i]->addr_pair().source())
734
return external_connections_[i];
739
void RelayServerBinding::OnMessage(talk_base::Message *pmsg) {
740
if (pmsg->message_id == MSG_LIFETIME_TIMER) {
741
ASSERT(!pmsg->pdata);
743
// If the lifetime timeout has been exceeded, then send a signal.
744
// Otherwise, just keep waiting.
745
if (talk_base::Time() >= last_used_ + lifetime_) {
746
LOG(LS_INFO) << "Expiring binding " << username_;
749
server_->thread()->PostDelayed(lifetime_, this, MSG_LIFETIME_TIMER);
757
} // namespace cricket