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 talk_base::PacketOptions options;
55 int result = socket->SendTo(bytes, size, addr, options);
56 if (result < static_cast<int>(size)) {
57 LOG(LS_ERROR) << "SendTo wrote only " << result << " of " << size
59 } else if (result < 0) {
60 LOG_ERR(LS_ERROR) << "SendTo";
64 // Sends the given STUN message on the given socket.
65 void SendStun(const StunMessage& msg,
66 talk_base::AsyncPacketSocket* socket,
67 const talk_base::SocketAddress& addr) {
68 talk_base::ByteBuffer buf;
70 Send(socket, buf.Data(), buf.Length(), addr);
73 // Constructs a STUN error response and sends it on the given socket.
74 void SendStunError(const StunMessage& msg, talk_base::AsyncPacketSocket* socket,
75 const talk_base::SocketAddress& remote_addr, int error_code,
76 const char* error_desc, const std::string& magic_cookie) {
78 err_msg.SetType(GetStunErrorResponseType(msg.type()));
79 err_msg.SetTransactionID(msg.transaction_id());
81 StunByteStringAttribute* magic_cookie_attr =
82 StunAttribute::CreateByteString(cricket::STUN_ATTR_MAGIC_COOKIE);
83 if (magic_cookie.size() == 0) {
84 magic_cookie_attr->CopyBytes(cricket::TURN_MAGIC_COOKIE_VALUE,
85 sizeof(cricket::TURN_MAGIC_COOKIE_VALUE));
87 magic_cookie_attr->CopyBytes(magic_cookie.c_str(), magic_cookie.size());
89 err_msg.AddAttribute(magic_cookie_attr);
91 StunErrorCodeAttribute* err_code = StunAttribute::CreateErrorCode();
92 err_code->SetClass(error_code / 100);
93 err_code->SetNumber(error_code % 100);
94 err_code->SetReason(error_desc);
95 err_msg.AddAttribute(err_code);
97 SendStun(err_msg, socket, remote_addr);
100 RelayServer::RelayServer(talk_base::Thread* thread)
101 : thread_(thread), log_bindings_(true) {
104 RelayServer::~RelayServer() {
105 // Deleting the binding will cause it to be removed from the map.
106 while (!bindings_.empty())
107 delete bindings_.begin()->second;
108 for (size_t i = 0; i < internal_sockets_.size(); ++i)
109 delete internal_sockets_[i];
110 for (size_t i = 0; i < external_sockets_.size(); ++i)
111 delete external_sockets_[i];
112 for (size_t i = 0; i < removed_sockets_.size(); ++i)
113 delete removed_sockets_[i];
114 while (!server_sockets_.empty()) {
115 talk_base::AsyncSocket* socket = server_sockets_.begin()->first;
116 server_sockets_.erase(server_sockets_.begin()->first);
121 void RelayServer::AddInternalSocket(talk_base::AsyncPacketSocket* socket) {
122 ASSERT(internal_sockets_.end() ==
123 std::find(internal_sockets_.begin(), internal_sockets_.end(), socket));
124 internal_sockets_.push_back(socket);
125 socket->SignalReadPacket.connect(this, &RelayServer::OnInternalPacket);
128 void RelayServer::RemoveInternalSocket(talk_base::AsyncPacketSocket* socket) {
129 SocketList::iterator iter =
130 std::find(internal_sockets_.begin(), internal_sockets_.end(), socket);
131 ASSERT(iter != internal_sockets_.end());
132 internal_sockets_.erase(iter);
133 removed_sockets_.push_back(socket);
134 socket->SignalReadPacket.disconnect(this);
137 void RelayServer::AddExternalSocket(talk_base::AsyncPacketSocket* socket) {
138 ASSERT(external_sockets_.end() ==
139 std::find(external_sockets_.begin(), external_sockets_.end(), socket));
140 external_sockets_.push_back(socket);
141 socket->SignalReadPacket.connect(this, &RelayServer::OnExternalPacket);
144 void RelayServer::RemoveExternalSocket(talk_base::AsyncPacketSocket* socket) {
145 SocketList::iterator iter =
146 std::find(external_sockets_.begin(), external_sockets_.end(), socket);
147 ASSERT(iter != external_sockets_.end());
148 external_sockets_.erase(iter);
149 removed_sockets_.push_back(socket);
150 socket->SignalReadPacket.disconnect(this);
153 void RelayServer::AddInternalServerSocket(talk_base::AsyncSocket* socket,
154 cricket::ProtocolType proto) {
155 ASSERT(server_sockets_.end() ==
156 server_sockets_.find(socket));
157 server_sockets_[socket] = proto;
158 socket->SignalReadEvent.connect(this, &RelayServer::OnReadEvent);
161 void RelayServer::RemoveInternalServerSocket(
162 talk_base::AsyncSocket* socket) {
163 ServerSocketMap::iterator iter = server_sockets_.find(socket);
164 ASSERT(iter != server_sockets_.end());
165 server_sockets_.erase(iter);
166 socket->SignalReadEvent.disconnect(this);
169 int RelayServer::GetConnectionCount() const {
170 return static_cast<int>(connections_.size());
173 talk_base::SocketAddressPair RelayServer::GetConnection(int connection) const {
175 for (ConnectionMap::const_iterator it = connections_.begin();
176 it != connections_.end(); ++it) {
177 if (i == connection) {
178 return it->second->addr_pair();
182 return talk_base::SocketAddressPair();
185 bool RelayServer::HasConnection(const talk_base::SocketAddress& address) const {
186 for (ConnectionMap::const_iterator it = connections_.begin();
187 it != connections_.end(); ++it) {
188 if (it->second->addr_pair().destination() == address) {
195 void RelayServer::OnReadEvent(talk_base::AsyncSocket* socket) {
196 ASSERT(server_sockets_.find(socket) != server_sockets_.end());
197 AcceptConnection(socket);
200 void RelayServer::OnInternalPacket(
201 talk_base::AsyncPacketSocket* socket, const char* bytes, size_t size,
202 const talk_base::SocketAddress& remote_addr,
203 const talk_base::PacketTime& packet_time) {
205 // Get the address of the connection we just received on.
206 talk_base::SocketAddressPair ap(remote_addr, socket->GetLocalAddress());
207 ASSERT(!ap.destination().IsNil());
209 // If this did not come from an existing connection, it should be a STUN
211 ConnectionMap::iterator piter = connections_.find(ap);
212 if (piter == connections_.end()) {
213 HandleStunAllocate(bytes, size, ap, socket);
217 RelayServerConnection* int_conn = piter->second;
219 // Handle STUN requests to the server itself.
220 if (int_conn->binding()->HasMagicCookie(bytes, size)) {
221 HandleStun(int_conn, bytes, size);
225 // Otherwise, this is a non-wrapped packet that we are to forward. Make sure
226 // that this connection has been locked. (Otherwise, we would not know what
227 // address to forward to.)
228 if (!int_conn->locked()) {
229 LOG(LS_WARNING) << "Dropping packet: connection not locked";
233 // Forward this to the destination address into the connection.
234 RelayServerConnection* ext_conn = int_conn->binding()->GetExternalConnection(
235 int_conn->default_destination());
236 if (ext_conn && ext_conn->locked()) {
237 // TODO: Check the HMAC.
238 ext_conn->Send(bytes, size);
240 // This happens very often and is not an error.
241 LOG(LS_INFO) << "Dropping packet: no external connection";
245 void RelayServer::OnExternalPacket(
246 talk_base::AsyncPacketSocket* socket, const char* bytes, size_t size,
247 const talk_base::SocketAddress& remote_addr,
248 const talk_base::PacketTime& packet_time) {
250 // Get the address of the connection we just received on.
251 talk_base::SocketAddressPair ap(remote_addr, socket->GetLocalAddress());
252 ASSERT(!ap.destination().IsNil());
254 // If this connection already exists, then forward the traffic.
255 ConnectionMap::iterator piter = connections_.find(ap);
256 if (piter != connections_.end()) {
257 // TODO: Check the HMAC.
258 RelayServerConnection* ext_conn = piter->second;
259 RelayServerConnection* int_conn =
260 ext_conn->binding()->GetInternalConnection(
261 ext_conn->addr_pair().source());
262 ASSERT(int_conn != NULL);
263 int_conn->Send(bytes, size, ext_conn->addr_pair().source());
264 ext_conn->Lock(); // allow outgoing packets
268 // The first packet should always be a STUN / TURN packet. If it isn't, then
269 // we should just ignore this packet.
271 talk_base::ByteBuffer buf(bytes, size);
272 if (!msg.Read(&buf)) {
273 LOG(LS_WARNING) << "Dropping packet: first packet not STUN";
277 // The initial packet should have a username (which identifies the binding).
278 const StunByteStringAttribute* username_attr =
279 msg.GetByteString(STUN_ATTR_USERNAME);
280 if (!username_attr) {
281 LOG(LS_WARNING) << "Dropping packet: no username";
285 uint32 length = talk_base::_min(static_cast<uint32>(username_attr->length()),
287 std::string username(username_attr->bytes(), length);
288 // TODO: Check the HMAC.
290 // The binding should already be present.
291 BindingMap::iterator biter = bindings_.find(username);
292 if (biter == bindings_.end()) {
293 LOG(LS_WARNING) << "Dropping packet: no binding with username";
297 // Add this authenticted connection to the binding.
298 RelayServerConnection* ext_conn =
299 new RelayServerConnection(biter->second, ap, socket);
300 ext_conn->binding()->AddExternalConnection(ext_conn);
301 AddConnection(ext_conn);
303 // We always know where external packets should be forwarded, so we can lock
304 // them from the beginning.
307 // Send this message on the appropriate internal connection.
308 RelayServerConnection* int_conn = ext_conn->binding()->GetInternalConnection(
309 ext_conn->addr_pair().source());
310 ASSERT(int_conn != NULL);
311 int_conn->Send(bytes, size, ext_conn->addr_pair().source());
314 bool RelayServer::HandleStun(
315 const char* bytes, size_t size, const talk_base::SocketAddress& remote_addr,
316 talk_base::AsyncPacketSocket* socket, std::string* username,
319 // Parse this into a stun message. Eat the message if this fails.
320 talk_base::ByteBuffer buf(bytes, size);
321 if (!msg->Read(&buf)) {
325 // The initial packet should have a username (which identifies the binding).
326 const StunByteStringAttribute* username_attr =
327 msg->GetByteString(STUN_ATTR_USERNAME);
328 if (!username_attr) {
329 SendStunError(*msg, socket, remote_addr, 432, "Missing Username", "");
333 // Record the username if requested.
335 username->append(username_attr->bytes(), username_attr->length());
337 // TODO: Check for unknown attributes (<= 0x7fff)
342 void RelayServer::HandleStunAllocate(
343 const char* bytes, size_t size, const talk_base::SocketAddressPair& ap,
344 talk_base::AsyncPacketSocket* socket) {
346 // Make sure this is a valid STUN request.
347 RelayMessage request;
348 std::string username;
349 if (!HandleStun(bytes, size, ap.source(), socket, &username, &request))
352 // Make sure this is a an allocate request.
353 if (request.type() != STUN_ALLOCATE_REQUEST) {
354 SendStunError(request,
358 "Operation Not Supported",
363 // TODO: Check the HMAC.
365 // Find or create the binding for this username.
367 RelayServerBinding* binding;
369 BindingMap::iterator biter = bindings_.find(username);
370 if (biter != bindings_.end()) {
371 binding = biter->second;
373 // NOTE: In the future, bindings will be created by the bot only. This
374 // else-branch will then disappear.
376 // Compute the appropriate lifetime for this binding.
377 uint32 lifetime = MAX_LIFETIME;
378 const StunUInt32Attribute* lifetime_attr =
379 request.GetUInt32(STUN_ATTR_LIFETIME);
381 lifetime = talk_base::_min(lifetime, lifetime_attr->value() * 1000);
383 binding = new RelayServerBinding(this, username, "0", lifetime);
384 binding->SignalTimeout.connect(this, &RelayServer::OnTimeout);
385 bindings_[username] = binding;
388 LOG(LS_INFO) << "Added new binding " << username << ", "
389 << bindings_.size() << " total";
393 // Add this connection to the binding. It starts out unlocked.
394 RelayServerConnection* int_conn =
395 new RelayServerConnection(binding, ap, socket);
396 binding->AddInternalConnection(int_conn);
397 AddConnection(int_conn);
399 // Now that we have a connection, this other method takes over.
400 HandleStunAllocate(int_conn, request);
403 void RelayServer::HandleStun(
404 RelayServerConnection* int_conn, const char* bytes, size_t size) {
406 // Make sure this is a valid STUN request.
407 RelayMessage request;
408 std::string username;
409 if (!HandleStun(bytes, size, int_conn->addr_pair().source(),
410 int_conn->socket(), &username, &request))
413 // Make sure the username is the one were were expecting.
414 if (username != int_conn->binding()->username()) {
415 int_conn->SendStunError(request, 430, "Stale Credentials");
419 // TODO: Check the HMAC.
421 // Send this request to the appropriate handler.
422 if (request.type() == STUN_SEND_REQUEST)
423 HandleStunSend(int_conn, request);
424 else if (request.type() == STUN_ALLOCATE_REQUEST)
425 HandleStunAllocate(int_conn, request);
427 int_conn->SendStunError(request, 600, "Operation Not Supported");
430 void RelayServer::HandleStunAllocate(
431 RelayServerConnection* int_conn, const StunMessage& request) {
433 // Create a response message that includes an address with which external
434 // clients can communicate.
436 RelayMessage response;
437 response.SetType(STUN_ALLOCATE_RESPONSE);
438 response.SetTransactionID(request.transaction_id());
440 StunByteStringAttribute* magic_cookie_attr =
441 StunAttribute::CreateByteString(cricket::STUN_ATTR_MAGIC_COOKIE);
442 magic_cookie_attr->CopyBytes(int_conn->binding()->magic_cookie().c_str(),
443 int_conn->binding()->magic_cookie().size());
444 response.AddAttribute(magic_cookie_attr);
446 size_t index = rand() % external_sockets_.size();
447 talk_base::SocketAddress ext_addr =
448 external_sockets_[index]->GetLocalAddress();
450 StunAddressAttribute* addr_attr =
451 StunAttribute::CreateAddress(STUN_ATTR_MAPPED_ADDRESS);
452 addr_attr->SetIP(ext_addr.ipaddr());
453 addr_attr->SetPort(ext_addr.port());
454 response.AddAttribute(addr_attr);
456 StunUInt32Attribute* res_lifetime_attr =
457 StunAttribute::CreateUInt32(STUN_ATTR_LIFETIME);
458 res_lifetime_attr->SetValue(int_conn->binding()->lifetime() / 1000);
459 response.AddAttribute(res_lifetime_attr);
461 // TODO: Support transport-prefs (preallocate RTCP port).
462 // TODO: Support bandwidth restrictions.
463 // TODO: Add message integrity check.
465 // Send a response to the caller.
466 int_conn->SendStun(response);
469 void RelayServer::HandleStunSend(
470 RelayServerConnection* int_conn, const StunMessage& request) {
472 const StunAddressAttribute* addr_attr =
473 request.GetAddress(STUN_ATTR_DESTINATION_ADDRESS);
475 int_conn->SendStunError(request, 400, "Bad Request");
479 const StunByteStringAttribute* data_attr =
480 request.GetByteString(STUN_ATTR_DATA);
482 int_conn->SendStunError(request, 400, "Bad Request");
486 talk_base::SocketAddress ext_addr(addr_attr->ipaddr(), addr_attr->port());
487 RelayServerConnection* ext_conn =
488 int_conn->binding()->GetExternalConnection(ext_addr);
490 // Create a new connection to establish the relationship with this binding.
491 ASSERT(external_sockets_.size() == 1);
492 talk_base::AsyncPacketSocket* socket = external_sockets_[0];
493 talk_base::SocketAddressPair ap(ext_addr, socket->GetLocalAddress());
494 ext_conn = new RelayServerConnection(int_conn->binding(), ap, socket);
495 ext_conn->binding()->AddExternalConnection(ext_conn);
496 AddConnection(ext_conn);
499 // If this connection has pinged us, then allow outgoing traffic.
500 if (ext_conn->locked())
501 ext_conn->Send(data_attr->bytes(), data_attr->length());
503 const StunUInt32Attribute* options_attr =
504 request.GetUInt32(STUN_ATTR_OPTIONS);
505 if (options_attr && (options_attr->value() & 0x01)) {
506 int_conn->set_default_destination(ext_addr);
509 RelayMessage response;
510 response.SetType(STUN_SEND_RESPONSE);
511 response.SetTransactionID(request.transaction_id());
513 StunByteStringAttribute* magic_cookie_attr =
514 StunAttribute::CreateByteString(cricket::STUN_ATTR_MAGIC_COOKIE);
515 magic_cookie_attr->CopyBytes(int_conn->binding()->magic_cookie().c_str(),
516 int_conn->binding()->magic_cookie().size());
517 response.AddAttribute(magic_cookie_attr);
519 StunUInt32Attribute* options2_attr =
520 StunAttribute::CreateUInt32(cricket::STUN_ATTR_OPTIONS);
521 options2_attr->SetValue(0x01);
522 response.AddAttribute(options2_attr);
524 int_conn->SendStun(response);
528 void RelayServer::AddConnection(RelayServerConnection* conn) {
529 ASSERT(connections_.find(conn->addr_pair()) == connections_.end());
530 connections_[conn->addr_pair()] = conn;
533 void RelayServer::RemoveConnection(RelayServerConnection* conn) {
534 ConnectionMap::iterator iter = connections_.find(conn->addr_pair());
535 ASSERT(iter != connections_.end());
536 connections_.erase(iter);
539 void RelayServer::RemoveBinding(RelayServerBinding* binding) {
540 BindingMap::iterator iter = bindings_.find(binding->username());
541 ASSERT(iter != bindings_.end());
542 bindings_.erase(iter);
545 LOG(LS_INFO) << "Removed binding " << binding->username() << ", "
546 << bindings_.size() << " remaining";
550 void RelayServer::OnMessage(talk_base::Message *pmsg) {
551 ASSERT(pmsg->message_id == kMessageAcceptConnection);
552 talk_base::MessageData* data = pmsg->pdata;
553 talk_base::AsyncSocket* socket =
554 static_cast <talk_base::TypedMessageData<talk_base::AsyncSocket*>*>
556 AcceptConnection(socket);
560 void RelayServer::OnTimeout(RelayServerBinding* binding) {
561 // This call will result in all of the necessary clean-up. We can't call
562 // delete here, because you can't delete an object that is signaling you.
563 thread_->Dispose(binding);
566 void RelayServer::AcceptConnection(talk_base::AsyncSocket* server_socket) {
567 // Check if someone is trying to connect to us.
568 talk_base::SocketAddress accept_addr;
569 talk_base::AsyncSocket* accepted_socket =
570 server_socket->Accept(&accept_addr);
571 if (accepted_socket != NULL) {
572 // We had someone trying to connect, now check which protocol to
573 // use and create a packet socket.
574 ASSERT(server_sockets_[server_socket] == cricket::PROTO_TCP ||
575 server_sockets_[server_socket] == cricket::PROTO_SSLTCP);
576 if (server_sockets_[server_socket] == cricket::PROTO_SSLTCP) {
577 accepted_socket = new talk_base::AsyncSSLServerSocket(accepted_socket);
579 talk_base::AsyncTCPSocket* tcp_socket =
580 new talk_base::AsyncTCPSocket(accepted_socket, false);
582 // Finally add the socket so it can start communicating with the client.
583 AddInternalSocket(tcp_socket);
587 RelayServerConnection::RelayServerConnection(
588 RelayServerBinding* binding, const talk_base::SocketAddressPair& addrs,
589 talk_base::AsyncPacketSocket* socket)
590 : binding_(binding), addr_pair_(addrs), socket_(socket), locked_(false) {
591 // The creation of a new connection constitutes a use of the binding.
592 binding_->NoteUsed();
595 RelayServerConnection::~RelayServerConnection() {
596 // Remove this connection from the server's map (if it exists there).
597 binding_->server()->RemoveConnection(this);
600 void RelayServerConnection::Send(const char* data, size_t size) {
601 // Note that the binding has been used again.
602 binding_->NoteUsed();
604 cricket::Send(socket_, data, size, addr_pair_.source());
607 void RelayServerConnection::Send(
608 const char* data, size_t size, const talk_base::SocketAddress& from_addr) {
609 // If the from address is known to the client, we don't need to send it.
610 if (locked() && (from_addr == default_dest_)) {
615 // Wrap the given data in a data-indication packet.
618 msg.SetType(STUN_DATA_INDICATION);
620 StunByteStringAttribute* magic_cookie_attr =
621 StunAttribute::CreateByteString(cricket::STUN_ATTR_MAGIC_COOKIE);
622 magic_cookie_attr->CopyBytes(binding_->magic_cookie().c_str(),
623 binding_->magic_cookie().size());
624 msg.AddAttribute(magic_cookie_attr);
626 StunAddressAttribute* addr_attr =
627 StunAttribute::CreateAddress(STUN_ATTR_SOURCE_ADDRESS2);
628 addr_attr->SetIP(from_addr.ipaddr());
629 addr_attr->SetPort(from_addr.port());
630 msg.AddAttribute(addr_attr);
632 StunByteStringAttribute* data_attr =
633 StunAttribute::CreateByteString(STUN_ATTR_DATA);
634 ASSERT(size <= 65536);
635 data_attr->CopyBytes(data, uint16(size));
636 msg.AddAttribute(data_attr);
641 void RelayServerConnection::SendStun(const StunMessage& msg) {
642 // Note that the binding has been used again.
643 binding_->NoteUsed();
645 cricket::SendStun(msg, socket_, addr_pair_.source());
648 void RelayServerConnection::SendStunError(
649 const StunMessage& request, int error_code, const char* error_desc) {
650 // An error does not indicate use. If no legitimate use off the binding
651 // occurs, we want it to be cleaned up even if errors are still occuring.
653 cricket::SendStunError(
654 request, socket_, addr_pair_.source(), error_code, error_desc,
655 binding_->magic_cookie());
658 void RelayServerConnection::Lock() {
662 void RelayServerConnection::Unlock() {
666 // IDs used for posted messages:
667 const uint32 MSG_LIFETIME_TIMER = 1;
669 RelayServerBinding::RelayServerBinding(
670 RelayServer* server, const std::string& username,
671 const std::string& password, uint32 lifetime)
672 : server_(server), username_(username), password_(password),
673 lifetime_(lifetime) {
674 // For now, every connection uses the standard magic cookie value.
675 magic_cookie_.append(
676 reinterpret_cast<const char*>(TURN_MAGIC_COOKIE_VALUE),
677 sizeof(TURN_MAGIC_COOKIE_VALUE));
679 // Initialize the last-used time to now.
682 // Set the first timeout check.
683 server_->thread()->PostDelayed(lifetime_, this, MSG_LIFETIME_TIMER);
686 RelayServerBinding::~RelayServerBinding() {
687 // Clear the outstanding timeout check.
688 server_->thread()->Clear(this);
690 // Clean up all of the connections.
691 for (size_t i = 0; i < internal_connections_.size(); ++i)
692 delete internal_connections_[i];
693 for (size_t i = 0; i < external_connections_.size(); ++i)
694 delete external_connections_[i];
696 // Remove this binding from the server's map.
697 server_->RemoveBinding(this);
700 void RelayServerBinding::AddInternalConnection(RelayServerConnection* conn) {
701 internal_connections_.push_back(conn);
704 void RelayServerBinding::AddExternalConnection(RelayServerConnection* conn) {
705 external_connections_.push_back(conn);
708 void RelayServerBinding::NoteUsed() {
709 last_used_ = talk_base::Time();
712 bool RelayServerBinding::HasMagicCookie(const char* bytes, size_t size) const {
713 if (size < 24 + magic_cookie_.size()) {
716 return 0 == std::memcmp(
717 bytes + 24, magic_cookie_.c_str(), magic_cookie_.size());
721 RelayServerConnection* RelayServerBinding::GetInternalConnection(
722 const talk_base::SocketAddress& ext_addr) {
724 // Look for an internal connection that is locked to this address.
725 for (size_t i = 0; i < internal_connections_.size(); ++i) {
726 if (internal_connections_[i]->locked() &&
727 (ext_addr == internal_connections_[i]->default_destination()))
728 return internal_connections_[i];
731 // If one was not found, we send to the first connection.
732 ASSERT(internal_connections_.size() > 0);
733 return internal_connections_[0];
736 RelayServerConnection* RelayServerBinding::GetExternalConnection(
737 const talk_base::SocketAddress& ext_addr) {
738 for (size_t i = 0; i < external_connections_.size(); ++i) {
739 if (ext_addr == external_connections_[i]->addr_pair().source())
740 return external_connections_[i];
745 void RelayServerBinding::OnMessage(talk_base::Message *pmsg) {
746 if (pmsg->message_id == MSG_LIFETIME_TIMER) {
747 ASSERT(!pmsg->pdata);
749 // If the lifetime timeout has been exceeded, then send a signal.
750 // Otherwise, just keep waiting.
751 if (talk_base::Time() >= last_used_ + lifetime_) {
752 LOG(LS_INFO) << "Expiring binding " << username_;
755 server_->thread()->PostDelayed(lifetime_, this, MSG_LIFETIME_TIMER);
763 } // namespace cricket