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 "webrtc/p2p/base/relayport.h"
29 #include "webrtc/base/asyncpacketsocket.h"
30 #include "webrtc/base/helpers.h"
31 #include "webrtc/base/logging.h"
35 static const uint32 kMessageConnectTimeout = 1;
36 static const int kKeepAliveDelay = 10 * 60 * 1000;
37 static const int kRetryTimeout = 50 * 1000; // ICE says 50 secs
38 // How long to wait for a socket to connect to remote host in milliseconds
39 // before trying another connection.
40 static const int kSoftConnectTimeoutMs = 3 * 1000;
42 // Handles a connection to one address/port/protocol combination for a
43 // particular RelayEntry.
44 class RelayConnection : public sigslot::has_slots<> {
46 RelayConnection(const ProtocolAddress* protocol_address,
47 rtc::AsyncPacketSocket* socket,
50 rtc::AsyncPacketSocket* socket() const { return socket_; }
52 const ProtocolAddress* protocol_address() {
53 return protocol_address_;
56 rtc::SocketAddress GetAddress() const {
57 return protocol_address_->address;
60 ProtocolType GetProtocol() const {
61 return protocol_address_->proto;
64 int SetSocketOption(rtc::Socket::Option opt, int value);
66 // Validates a response to a STUN allocate request.
67 bool CheckResponse(StunMessage* msg);
69 // Sends data to the relay server.
70 int Send(const void* pv, size_t cb, const rtc::PacketOptions& options);
72 // Sends a STUN allocate request message to the relay server.
73 void SendAllocateRequest(RelayEntry* entry, int delay);
75 // Return the latest error generated by the socket.
76 int GetError() { return socket_->GetError(); }
78 // Called on behalf of a StunRequest to write data to the socket. This is
79 // already STUN intended for the server, so no wrapping is necessary.
80 void OnSendPacket(const void* data, size_t size, StunRequest* req);
83 rtc::AsyncPacketSocket* socket_;
84 const ProtocolAddress* protocol_address_;
85 StunRequestManager *request_manager_;
88 // Manages a number of connections to the relayserver, one for each
89 // available protocol. We aim to use each connection for only a
90 // specific destination address so that we can avoid wrapping every
91 // packet in a STUN send / data indication.
92 class RelayEntry : public rtc::MessageHandler,
93 public sigslot::has_slots<> {
95 RelayEntry(RelayPort* port, const rtc::SocketAddress& ext_addr);
98 RelayPort* port() { return port_; }
100 const rtc::SocketAddress& address() const { return ext_addr_; }
101 void set_address(const rtc::SocketAddress& addr) { ext_addr_ = addr; }
103 bool connected() const { return connected_; }
104 bool locked() const { return locked_; }
106 // Returns the last error on the socket of this entry.
109 // Returns the most preferred connection of the given
110 // ones. Connections are rated based on protocol in the order of:
111 // UDP, TCP and SSLTCP, where UDP is the most preferred protocol
112 static RelayConnection* GetBestConnection(RelayConnection* conn1,
113 RelayConnection* conn2);
115 // Sends the STUN requests to the server to initiate this connection.
118 // Called when this entry becomes connected. The address given is the one
119 // exposed to the outside world on the relay server.
120 void OnConnect(const rtc::SocketAddress& mapped_addr,
121 RelayConnection* socket);
123 // Sends a packet to the given destination address using the socket of this
124 // entry. This will wrap the packet in STUN if necessary.
125 int SendTo(const void* data, size_t size,
126 const rtc::SocketAddress& addr,
127 const rtc::PacketOptions& options);
129 // Schedules a keep-alive allocate request.
130 void ScheduleKeepAlive();
132 void SetServerIndex(size_t sindex) { server_index_ = sindex; }
134 // Sets this option on the socket of each connection.
135 int SetSocketOption(rtc::Socket::Option opt, int value);
137 size_t ServerIndex() const { return server_index_; }
139 // Try a different server address
140 void HandleConnectFailure(rtc::AsyncPacketSocket* socket);
142 // Implementation of the MessageHandler Interface.
143 virtual void OnMessage(rtc::Message *pmsg);
147 rtc::SocketAddress ext_addr_;
148 size_t server_index_;
151 RelayConnection* current_connection_;
153 // Called when a TCP connection is established or fails
154 void OnSocketConnect(rtc::AsyncPacketSocket* socket);
155 void OnSocketClose(rtc::AsyncPacketSocket* socket, int error);
157 // Called when a packet is received on this socket.
159 rtc::AsyncPacketSocket* socket,
160 const char* data, size_t size,
161 const rtc::SocketAddress& remote_addr,
162 const rtc::PacketTime& packet_time);
163 // Called when the socket is currently able to send.
164 void OnReadyToSend(rtc::AsyncPacketSocket* socket);
166 // Sends the given data on the socket to the server with no wrapping. This
167 // returns the number of bytes written or -1 if an error occurred.
168 int SendPacket(const void* data, size_t size,
169 const rtc::PacketOptions& options);
172 // Handles an allocate request for a particular RelayEntry.
173 class AllocateRequest : public StunRequest {
175 AllocateRequest(RelayEntry* entry, RelayConnection* connection);
176 virtual ~AllocateRequest() {}
178 virtual void Prepare(StunMessage* request);
180 virtual int GetNextDelay();
182 virtual void OnResponse(StunMessage* response);
183 virtual void OnErrorResponse(StunMessage* response);
184 virtual void OnTimeout();
188 RelayConnection* connection_;
192 RelayPort::RelayPort(
193 rtc::Thread* thread, rtc::PacketSocketFactory* factory,
194 rtc::Network* network, const rtc::IPAddress& ip,
195 int min_port, int max_port, const std::string& username,
196 const std::string& password)
197 : Port(thread, RELAY_PORT_TYPE, factory, network, ip, min_port, max_port,
202 new RelayEntry(this, rtc::SocketAddress()));
203 // TODO: set local preference value for TCP based candidates.
206 RelayPort::~RelayPort() {
207 for (size_t i = 0; i < entries_.size(); ++i)
209 thread()->Clear(this);
212 void RelayPort::AddServerAddress(const ProtocolAddress& addr) {
213 // Since HTTP proxies usually only allow 443,
214 // let's up the priority on PROTO_SSLTCP
215 if (addr.proto == PROTO_SSLTCP &&
216 (proxy().type == rtc::PROXY_HTTPS ||
217 proxy().type == rtc::PROXY_UNKNOWN)) {
218 server_addr_.push_front(addr);
220 server_addr_.push_back(addr);
224 void RelayPort::AddExternalAddress(const ProtocolAddress& addr) {
225 std::string proto_name = ProtoToString(addr.proto);
226 for (std::vector<ProtocolAddress>::iterator it = external_addr_.begin();
227 it != external_addr_.end(); ++it) {
228 if ((it->address == addr.address) && (it->proto == addr.proto)) {
229 LOG(INFO) << "Redundant relay address: " << proto_name
230 << " @ " << addr.address.ToSensitiveString();
234 external_addr_.push_back(addr);
237 void RelayPort::SetReady() {
239 std::vector<ProtocolAddress>::iterator iter;
240 for (iter = external_addr_.begin();
241 iter != external_addr_.end(); ++iter) {
242 std::string proto_name = ProtoToString(iter->proto);
243 // In case of Gturn, related address is set to null socket address.
244 // This is due to as mapped address stun attribute is used for allocated
246 AddAddress(iter->address, iter->address, rtc::SocketAddress(),
247 proto_name, "", RELAY_PORT_TYPE,
248 ICE_TYPE_PREFERENCE_RELAY, 0, false);
251 SignalPortComplete(this);
255 const ProtocolAddress * RelayPort::ServerAddress(size_t index) const {
256 if (index < server_addr_.size())
257 return &server_addr_[index];
261 bool RelayPort::HasMagicCookie(const char* data, size_t size) {
262 if (size < 24 + sizeof(TURN_MAGIC_COOKIE_VALUE)) {
265 return memcmp(data + 24,
266 TURN_MAGIC_COOKIE_VALUE,
267 sizeof(TURN_MAGIC_COOKIE_VALUE)) == 0;
271 void RelayPort::PrepareAddress() {
272 // We initiate a connect on the first entry. If this completes, it will fill
273 // in the server address as the address of this port.
274 ASSERT(entries_.size() == 1);
275 entries_[0]->Connect();
279 Connection* RelayPort::CreateConnection(const Candidate& address,
280 CandidateOrigin origin) {
281 // We only create conns to non-udp sockets if they are incoming on this port
282 if ((address.protocol() != UDP_PROTOCOL_NAME) &&
283 (origin != ORIGIN_THIS_PORT)) {
287 // We don't support loopback on relays
288 if (address.type() == Type()) {
292 if (!IsCompatibleAddress(address.address())) {
297 for (size_t i = 0; i < Candidates().size(); ++i) {
298 const Candidate& local = Candidates()[i];
299 if (local.protocol() == address.protocol()) {
305 Connection * conn = new ProxyConnection(this, index, address);
310 int RelayPort::SendTo(const void* data, size_t size,
311 const rtc::SocketAddress& addr,
312 const rtc::PacketOptions& options,
314 // Try to find an entry for this specific address. Note that the first entry
315 // created was not given an address initially, so it can be set to the first
316 // address that comes along.
317 RelayEntry* entry = 0;
319 for (size_t i = 0; i < entries_.size(); ++i) {
320 if (entries_[i]->address().IsNil() && payload) {
322 entry->set_address(addr);
324 } else if (entries_[i]->address() == addr) {
330 // If we did not find one, then we make a new one. This will not be useable
331 // until it becomes connected, however.
332 if (!entry && payload) {
333 entry = new RelayEntry(this, addr);
334 if (!entries_.empty()) {
335 entry->SetServerIndex(entries_[0]->ServerIndex());
338 entries_.push_back(entry);
341 // If the entry is connected, then we can send on it (though wrapping may
342 // still be necessary). Otherwise, we can't yet use this connection, so we
343 // default to the first one.
344 if (!entry || !entry->connected()) {
345 ASSERT(!entries_.empty());
347 if (!entry->connected()) {
348 error_ = EWOULDBLOCK;
353 // Send the actual contents to the server using the usual mechanism.
354 int sent = entry->SendTo(data, size, addr, options);
357 error_ = entry->GetError();
360 // The caller of the function is expecting the number of user data bytes,
361 // rather than the size of the packet.
362 return static_cast<int>(size);
365 int RelayPort::SetOption(rtc::Socket::Option opt, int value) {
367 for (size_t i = 0; i < entries_.size(); ++i) {
368 if (entries_[i]->SetSocketOption(opt, value) < 0) {
370 error_ = entries_[i]->GetError();
373 options_.push_back(OptionValue(opt, value));
377 int RelayPort::GetOption(rtc::Socket::Option opt, int* value) {
378 std::vector<OptionValue>::iterator it;
379 for (it = options_.begin(); it < options_.end(); ++it) {
380 if (it->first == opt) {
388 int RelayPort::GetError() {
392 void RelayPort::OnReadPacket(
393 const char* data, size_t size,
394 const rtc::SocketAddress& remote_addr,
396 const rtc::PacketTime& packet_time) {
397 if (Connection* conn = GetConnection(remote_addr)) {
398 conn->OnReadPacket(data, size, packet_time);
400 Port::OnReadPacket(data, size, remote_addr, proto);
404 RelayConnection::RelayConnection(const ProtocolAddress* protocol_address,
405 rtc::AsyncPacketSocket* socket,
408 protocol_address_(protocol_address) {
409 request_manager_ = new StunRequestManager(thread);
410 request_manager_->SignalSendPacket.connect(this,
411 &RelayConnection::OnSendPacket);
414 RelayConnection::~RelayConnection() {
415 delete request_manager_;
419 int RelayConnection::SetSocketOption(rtc::Socket::Option opt,
422 return socket_->SetOption(opt, value);
427 bool RelayConnection::CheckResponse(StunMessage* msg) {
428 return request_manager_->CheckResponse(msg);
431 void RelayConnection::OnSendPacket(const void* data, size_t size,
433 // TODO(mallinath) Find a way to get DSCP value from Port.
434 rtc::PacketOptions options; // Default dscp set to NO_CHANGE.
435 int sent = socket_->SendTo(data, size, GetAddress(), options);
437 LOG(LS_VERBOSE) << "OnSendPacket: failed sending to " << GetAddress() <<
438 strerror(socket_->GetError());
443 int RelayConnection::Send(const void* pv, size_t cb,
444 const rtc::PacketOptions& options) {
445 return socket_->SendTo(pv, cb, GetAddress(), options);
448 void RelayConnection::SendAllocateRequest(RelayEntry* entry, int delay) {
449 request_manager_->SendDelayed(new AllocateRequest(entry, this), delay);
452 RelayEntry::RelayEntry(RelayPort* port,
453 const rtc::SocketAddress& ext_addr)
454 : port_(port), ext_addr_(ext_addr),
455 server_index_(0), connected_(false), locked_(false),
456 current_connection_(NULL) {
459 RelayEntry::~RelayEntry() {
460 // Remove all RelayConnections and dispose sockets.
461 delete current_connection_;
462 current_connection_ = NULL;
465 void RelayEntry::Connect() {
466 // If we're already connected, return.
470 // If we've exhausted all options, bail out.
471 const ProtocolAddress* ra = port()->ServerAddress(server_index_);
473 LOG(LS_WARNING) << "No more relay addresses left to try";
477 // Remove any previous connection.
478 if (current_connection_) {
479 port()->thread()->Dispose(current_connection_);
480 current_connection_ = NULL;
483 // Try to set up our new socket.
484 LOG(LS_INFO) << "Connecting to relay via " << ProtoToString(ra->proto) <<
485 " @ " << ra->address.ToSensitiveString();
487 rtc::AsyncPacketSocket* socket = NULL;
489 if (ra->proto == PROTO_UDP) {
490 // UDP sockets are simple.
491 socket = port_->socket_factory()->CreateUdpSocket(
492 rtc::SocketAddress(port_->ip(), 0),
493 port_->min_port(), port_->max_port());
494 } else if (ra->proto == PROTO_TCP || ra->proto == PROTO_SSLTCP) {
495 int opts = (ra->proto == PROTO_SSLTCP) ?
496 rtc::PacketSocketFactory::OPT_SSLTCP : 0;
497 socket = port_->socket_factory()->CreateClientTcpSocket(
498 rtc::SocketAddress(port_->ip(), 0), ra->address,
499 port_->proxy(), port_->user_agent(), opts);
501 LOG(LS_WARNING) << "Unknown protocol (" << ra->proto << ")";
505 LOG(LS_WARNING) << "Socket creation failed";
508 // If we failed to get a socket, move on to the next protocol.
510 port()->thread()->Post(this, kMessageConnectTimeout);
514 // Otherwise, create the new connection and configure any socket options.
515 socket->SignalReadPacket.connect(this, &RelayEntry::OnReadPacket);
516 socket->SignalReadyToSend.connect(this, &RelayEntry::OnReadyToSend);
517 current_connection_ = new RelayConnection(ra, socket, port()->thread());
518 for (size_t i = 0; i < port_->options().size(); ++i) {
519 current_connection_->SetSocketOption(port_->options()[i].first,
520 port_->options()[i].second);
523 // If we're trying UDP, start binding requests.
524 // If we're trying TCP, wait for connection with a fixed timeout.
525 if ((ra->proto == PROTO_TCP) || (ra->proto == PROTO_SSLTCP)) {
526 socket->SignalClose.connect(this, &RelayEntry::OnSocketClose);
527 socket->SignalConnect.connect(this, &RelayEntry::OnSocketConnect);
528 port()->thread()->PostDelayed(kSoftConnectTimeoutMs, this,
529 kMessageConnectTimeout);
531 current_connection_->SendAllocateRequest(this, 0);
535 int RelayEntry::GetError() {
536 if (current_connection_ != NULL) {
537 return current_connection_->GetError();
542 RelayConnection* RelayEntry::GetBestConnection(RelayConnection* conn1,
543 RelayConnection* conn2) {
544 return conn1->GetProtocol() <= conn2->GetProtocol() ? conn1 : conn2;
547 void RelayEntry::OnConnect(const rtc::SocketAddress& mapped_addr,
548 RelayConnection* connection) {
549 // We are connected, notify our parent.
550 ProtocolType proto = PROTO_UDP;
551 LOG(INFO) << "Relay allocate succeeded: " << ProtoToString(proto)
552 << " @ " << mapped_addr.ToSensitiveString();
555 port_->AddExternalAddress(ProtocolAddress(mapped_addr, proto));
559 int RelayEntry::SendTo(const void* data, size_t size,
560 const rtc::SocketAddress& addr,
561 const rtc::PacketOptions& options) {
562 // If this connection is locked to the address given, then we can send the
563 // packet with no wrapper.
564 if (locked_ && (ext_addr_ == addr))
565 return SendPacket(data, size, options);
567 // Otherwise, we must wrap the given data in a STUN SEND request so that we
568 // can communicate the destination address to the server.
570 // Note that we do not use a StunRequest here. This is because there is
571 // likely no reason to resend this packet. If it is late, we just drop it.
572 // The next send to this address will try again.
574 RelayMessage request;
575 request.SetType(STUN_SEND_REQUEST);
577 StunByteStringAttribute* magic_cookie_attr =
578 StunAttribute::CreateByteString(STUN_ATTR_MAGIC_COOKIE);
579 magic_cookie_attr->CopyBytes(TURN_MAGIC_COOKIE_VALUE,
580 sizeof(TURN_MAGIC_COOKIE_VALUE));
581 VERIFY(request.AddAttribute(magic_cookie_attr));
583 StunByteStringAttribute* username_attr =
584 StunAttribute::CreateByteString(STUN_ATTR_USERNAME);
585 username_attr->CopyBytes(port_->username_fragment().c_str(),
586 port_->username_fragment().size());
587 VERIFY(request.AddAttribute(username_attr));
589 StunAddressAttribute* addr_attr =
590 StunAttribute::CreateAddress(STUN_ATTR_DESTINATION_ADDRESS);
591 addr_attr->SetIP(addr.ipaddr());
592 addr_attr->SetPort(addr.port());
593 VERIFY(request.AddAttribute(addr_attr));
596 if (ext_addr_ == addr) {
597 StunUInt32Attribute* options_attr =
598 StunAttribute::CreateUInt32(STUN_ATTR_OPTIONS);
599 options_attr->SetValue(0x1);
600 VERIFY(request.AddAttribute(options_attr));
603 StunByteStringAttribute* data_attr =
604 StunAttribute::CreateByteString(STUN_ATTR_DATA);
605 data_attr->CopyBytes(data, size);
606 VERIFY(request.AddAttribute(data_attr));
608 // TODO: compute the HMAC.
613 return SendPacket(buf.Data(), buf.Length(), options);
616 void RelayEntry::ScheduleKeepAlive() {
617 if (current_connection_) {
618 current_connection_->SendAllocateRequest(this, kKeepAliveDelay);
622 int RelayEntry::SetSocketOption(rtc::Socket::Option opt, int value) {
623 // Set the option on all available sockets.
624 int socket_error = 0;
625 if (current_connection_) {
626 socket_error = current_connection_->SetSocketOption(opt, value);
631 void RelayEntry::HandleConnectFailure(
632 rtc::AsyncPacketSocket* socket) {
633 // Make sure it's the current connection that has failed, it might
634 // be an old socked that has not yet been disposed.
636 (current_connection_ && socket == current_connection_->socket())) {
637 if (current_connection_)
638 port()->SignalConnectFailure(current_connection_->protocol_address());
640 // Try to connect to the next server address.
646 void RelayEntry::OnMessage(rtc::Message *pmsg) {
647 ASSERT(pmsg->message_id == kMessageConnectTimeout);
648 if (current_connection_) {
649 const ProtocolAddress* ra = current_connection_->protocol_address();
650 LOG(LS_WARNING) << "Relay " << ra->proto << " connection to " <<
651 ra->address << " timed out";
653 // Currently we connect to each server address in sequence. If we
654 // have more addresses to try, treat this is an error and move on to
655 // the next address, otherwise give this connection more time and
656 // await the real timeout.
658 // TODO: Connect to servers in parallel to speed up connect time
659 // and to avoid giving up too early.
660 port_->SignalSoftTimeout(ra);
661 HandleConnectFailure(current_connection_->socket());
663 HandleConnectFailure(NULL);
667 void RelayEntry::OnSocketConnect(rtc::AsyncPacketSocket* socket) {
668 LOG(INFO) << "relay tcp connected to " <<
669 socket->GetRemoteAddress().ToSensitiveString();
670 if (current_connection_ != NULL) {
671 current_connection_->SendAllocateRequest(this, 0);
675 void RelayEntry::OnSocketClose(rtc::AsyncPacketSocket* socket,
677 PLOG(LERROR, error) << "Relay connection failed: socket closed";
678 HandleConnectFailure(socket);
681 void RelayEntry::OnReadPacket(
682 rtc::AsyncPacketSocket* socket,
683 const char* data, size_t size,
684 const rtc::SocketAddress& remote_addr,
685 const rtc::PacketTime& packet_time) {
686 // ASSERT(remote_addr == port_->server_addr());
687 // TODO: are we worried about this?
689 if (current_connection_ == NULL || socket != current_connection_->socket()) {
690 // This packet comes from an unknown address.
691 LOG(WARNING) << "Dropping packet: unknown address";
695 // If the magic cookie is not present, then this is an unwrapped packet sent
696 // by the server, The actual remote address is the one we recorded.
697 if (!port_->HasMagicCookie(data, size)) {
699 port_->OnReadPacket(data, size, ext_addr_, PROTO_UDP, packet_time);
701 LOG(WARNING) << "Dropping packet: entry not locked";
706 rtc::ByteBuffer buf(data, size);
708 if (!msg.Read(&buf)) {
709 LOG(INFO) << "Incoming packet was not STUN";
713 // The incoming packet should be a STUN ALLOCATE response, SEND response, or
715 if (current_connection_->CheckResponse(&msg)) {
717 } else if (msg.type() == STUN_SEND_RESPONSE) {
718 if (const StunUInt32Attribute* options_attr =
719 msg.GetUInt32(STUN_ATTR_OPTIONS)) {
720 if (options_attr->value() & 0x1) {
725 } else if (msg.type() != STUN_DATA_INDICATION) {
726 LOG(INFO) << "Received BAD stun type from server: " << msg.type();
730 // This must be a data indication.
732 const StunAddressAttribute* addr_attr =
733 msg.GetAddress(STUN_ATTR_SOURCE_ADDRESS2);
735 LOG(INFO) << "Data indication has no source address";
737 } else if (addr_attr->family() != 1) {
738 LOG(INFO) << "Source address has bad family";
742 rtc::SocketAddress remote_addr2(addr_attr->ipaddr(), addr_attr->port());
744 const StunByteStringAttribute* data_attr = msg.GetByteString(STUN_ATTR_DATA);
746 LOG(INFO) << "Data indication has no data";
750 // Process the actual data and remote address in the normal manner.
751 port_->OnReadPacket(data_attr->bytes(), data_attr->length(), remote_addr2,
752 PROTO_UDP, packet_time);
755 void RelayEntry::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
757 port_->OnReadyToSend();
761 int RelayEntry::SendPacket(const void* data, size_t size,
762 const rtc::PacketOptions& options) {
764 if (current_connection_) {
765 // We are connected, no need to send packets anywere else than to
766 // the current connection.
767 sent = current_connection_->Send(data, size, options);
772 AllocateRequest::AllocateRequest(RelayEntry* entry,
773 RelayConnection* connection)
774 : StunRequest(new RelayMessage()),
776 connection_(connection) {
777 start_time_ = rtc::Time();
780 void AllocateRequest::Prepare(StunMessage* request) {
781 request->SetType(STUN_ALLOCATE_REQUEST);
783 StunByteStringAttribute* username_attr =
784 StunAttribute::CreateByteString(STUN_ATTR_USERNAME);
785 username_attr->CopyBytes(
786 entry_->port()->username_fragment().c_str(),
787 entry_->port()->username_fragment().size());
788 VERIFY(request->AddAttribute(username_attr));
791 int AllocateRequest::GetNextDelay() {
792 int delay = 100 * rtc::_max(1 << count_, 2);
799 void AllocateRequest::OnResponse(StunMessage* response) {
800 const StunAddressAttribute* addr_attr =
801 response->GetAddress(STUN_ATTR_MAPPED_ADDRESS);
803 LOG(INFO) << "Allocate response missing mapped address.";
804 } else if (addr_attr->family() != 1) {
805 LOG(INFO) << "Mapped address has bad family";
807 rtc::SocketAddress addr(addr_attr->ipaddr(), addr_attr->port());
808 entry_->OnConnect(addr, connection_);
811 // We will do a keep-alive regardless of whether this request suceeds.
812 // This should have almost no impact on network usage.
813 entry_->ScheduleKeepAlive();
816 void AllocateRequest::OnErrorResponse(StunMessage* response) {
817 const StunErrorCodeAttribute* attr = response->GetErrorCode();
819 LOG(INFO) << "Bad allocate response error code";
821 LOG(INFO) << "Allocate error response:"
822 << " code=" << attr->code()
823 << " reason='" << attr->reason() << "'";
826 if (rtc::TimeSince(start_time_) <= kRetryTimeout)
827 entry_->ScheduleKeepAlive();
830 void AllocateRequest::OnTimeout() {
831 LOG(INFO) << "Allocate request timed out";
832 entry_->HandleConnectFailure(connection_->socket());
835 } // namespace cricket