3 * Copyright 2012, 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/turnport.h"
32 #include "talk/base/asyncpacketsocket.h"
33 #include "talk/base/byteorder.h"
34 #include "talk/base/common.h"
35 #include "talk/base/logging.h"
36 #include "talk/base/nethelpers.h"
37 #include "talk/base/socketaddress.h"
38 #include "talk/base/stringencode.h"
39 #include "talk/p2p/base/common.h"
40 #include "talk/p2p/base/stun.h"
44 // TODO(juberti): Move to stun.h when relay messages have been renamed.
45 static const int TURN_ALLOCATE_REQUEST = STUN_ALLOCATE_REQUEST;
47 // TODO(juberti): Extract to turnmessage.h
48 static const int TURN_DEFAULT_PORT = 3478;
49 static const int TURN_CHANNEL_NUMBER_START = 0x4000;
50 static const int TURN_PERMISSION_TIMEOUT = 5 * 60 * 1000; // 5 minutes
52 static const size_t TURN_CHANNEL_HEADER_SIZE = 4U;
54 inline bool IsTurnChannelData(uint16 msg_type) {
55 return ((msg_type & 0xC000) == 0x4000); // MSB are 0b01
58 static int GetRelayPreference(cricket::ProtocolType proto, bool secure) {
59 int relay_preference = ICE_TYPE_PREFERENCE_RELAY;
60 if (proto == cricket::PROTO_TCP) {
61 relay_preference -= 1;
63 relay_preference -= 1;
66 ASSERT(relay_preference >= 0);
67 return relay_preference;
70 class TurnAllocateRequest : public StunRequest {
72 explicit TurnAllocateRequest(TurnPort* port);
73 virtual void Prepare(StunMessage* request);
74 virtual void OnResponse(StunMessage* response);
75 virtual void OnErrorResponse(StunMessage* response);
76 virtual void OnTimeout();
79 // Handles authentication challenge from the server.
80 void OnAuthChallenge(StunMessage* response, int code);
81 void OnUnknownAttribute(StunMessage* response);
86 class TurnRefreshRequest : public StunRequest {
88 explicit TurnRefreshRequest(TurnPort* port);
89 virtual void Prepare(StunMessage* request);
90 virtual void OnResponse(StunMessage* response);
91 virtual void OnErrorResponse(StunMessage* response);
92 virtual void OnTimeout();
98 class TurnCreatePermissionRequest : public StunRequest,
99 public sigslot::has_slots<> {
101 TurnCreatePermissionRequest(TurnPort* port, TurnEntry* entry,
102 const talk_base::SocketAddress& ext_addr);
103 virtual void Prepare(StunMessage* request);
104 virtual void OnResponse(StunMessage* response);
105 virtual void OnErrorResponse(StunMessage* response);
106 virtual void OnTimeout();
109 void OnEntryDestroyed(TurnEntry* entry);
113 talk_base::SocketAddress ext_addr_;
116 class TurnChannelBindRequest : public StunRequest,
117 public sigslot::has_slots<> {
119 TurnChannelBindRequest(TurnPort* port, TurnEntry* entry, int channel_id,
120 const talk_base::SocketAddress& ext_addr);
121 virtual void Prepare(StunMessage* request);
122 virtual void OnResponse(StunMessage* response);
123 virtual void OnErrorResponse(StunMessage* response);
124 virtual void OnTimeout();
127 void OnEntryDestroyed(TurnEntry* entry);
132 talk_base::SocketAddress ext_addr_;
135 // Manages a "connection" to a remote destination. We will attempt to bring up
136 // a channel for this remote destination to reduce the overhead of sending data.
137 class TurnEntry : public sigslot::has_slots<> {
139 enum BindState { STATE_UNBOUND, STATE_BINDING, STATE_BOUND };
140 TurnEntry(TurnPort* port, int channel_id,
141 const talk_base::SocketAddress& ext_addr);
143 TurnPort* port() { return port_; }
145 int channel_id() const { return channel_id_; }
146 const talk_base::SocketAddress& address() const { return ext_addr_; }
147 BindState state() const { return state_; }
149 // Helper methods to send permission and channel bind requests.
150 void SendCreatePermissionRequest();
151 void SendChannelBindRequest(int delay);
152 // Sends a packet to the given destination address.
153 // This will wrap the packet in STUN if necessary.
154 int Send(const void* data, size_t size, bool payload,
155 const talk_base::PacketOptions& options);
157 void OnCreatePermissionSuccess();
158 void OnCreatePermissionError(StunMessage* response, int code);
159 void OnChannelBindSuccess();
160 void OnChannelBindError(StunMessage* response, int code);
161 // Signal sent when TurnEntry is destroyed.
162 sigslot::signal1<TurnEntry*> SignalDestroyed;
167 talk_base::SocketAddress ext_addr_;
171 TurnPort::TurnPort(talk_base::Thread* thread,
172 talk_base::PacketSocketFactory* factory,
173 talk_base::Network* network,
174 talk_base::AsyncPacketSocket* socket,
175 const std::string& username,
176 const std::string& password,
177 const ProtocolAddress& server_address,
178 const RelayCredentials& credentials)
179 : Port(thread, factory, network, socket->GetLocalAddress().ipaddr(),
181 server_address_(server_address),
182 credentials_(credentials),
186 request_manager_(thread),
187 next_channel_number_(TURN_CHANNEL_NUMBER_START),
189 request_manager_.SignalSendPacket.connect(this, &TurnPort::OnSendStunPacket);
192 TurnPort::TurnPort(talk_base::Thread* thread,
193 talk_base::PacketSocketFactory* factory,
194 talk_base::Network* network,
195 const talk_base::IPAddress& ip,
196 int min_port, int max_port,
197 const std::string& username,
198 const std::string& password,
199 const ProtocolAddress& server_address,
200 const RelayCredentials& credentials)
201 : Port(thread, RELAY_PORT_TYPE, factory, network, ip, min_port, max_port,
203 server_address_(server_address),
204 credentials_(credentials),
208 request_manager_(thread),
209 next_channel_number_(TURN_CHANNEL_NUMBER_START),
211 request_manager_.SignalSendPacket.connect(this, &TurnPort::OnSendStunPacket);
214 TurnPort::~TurnPort() {
215 // TODO(juberti): Should this even be necessary?
216 while (!entries_.empty()) {
217 DestroyEntry(entries_.front()->address());
220 resolver_->Destroy(false);
222 if (!SharedSocket()) {
227 void TurnPort::PrepareAddress() {
228 if (credentials_.username.empty() ||
229 credentials_.password.empty()) {
230 LOG(LS_ERROR) << "Allocation can't be started without setting the"
231 << " TURN server credentials for the user.";
236 if (!server_address_.address.port()) {
237 // We will set default TURN port, if no port is set in the address.
238 server_address_.address.SetPort(TURN_DEFAULT_PORT);
241 if (server_address_.address.IsUnresolved()) {
242 ResolveTurnAddress(server_address_.address);
244 // If protocol family of server address doesn't match with local, return.
245 if (!IsCompatibleAddress(server_address_.address)) {
246 LOG(LS_ERROR) << "Server IP address family does not match with "
247 << "local host address family type";
252 LOG_J(LS_INFO, this) << "Trying to connect to TURN server via "
253 << ProtoToString(server_address_.proto) << " @ "
254 << server_address_.address.ToSensitiveString();
255 if (server_address_.proto == PROTO_UDP && !SharedSocket()) {
256 socket_ = socket_factory()->CreateUdpSocket(
257 talk_base::SocketAddress(ip(), 0), min_port(), max_port());
258 } else if (server_address_.proto == PROTO_TCP) {
259 ASSERT(!SharedSocket());
260 int opts = talk_base::PacketSocketFactory::OPT_STUN;
261 // If secure bit is enabled in server address, use TLS over TCP.
262 if (server_address_.secure) {
263 opts |= talk_base::PacketSocketFactory::OPT_TLS;
265 socket_ = socket_factory()->CreateClientTcpSocket(
266 talk_base::SocketAddress(ip(), 0), server_address_.address,
267 proxy(), user_agent(), opts);
275 // Apply options if any.
276 for (SocketOptionsMap::iterator iter = socket_options_.begin();
277 iter != socket_options_.end(); ++iter) {
278 socket_->SetOption(iter->first, iter->second);
281 if (!SharedSocket()) {
282 // If socket is shared, AllocationSequence will receive the packet.
283 socket_->SignalReadPacket.connect(this, &TurnPort::OnReadPacket);
286 socket_->SignalReadyToSend.connect(this, &TurnPort::OnReadyToSend);
288 if (server_address_.proto == PROTO_TCP) {
289 socket_->SignalConnect.connect(this, &TurnPort::OnSocketConnect);
290 socket_->SignalClose.connect(this, &TurnPort::OnSocketClose);
292 // If its UDP, send AllocateRequest now.
293 // For TCP and TLS AllcateRequest will be sent by OnSocketConnect.
294 SendRequest(new TurnAllocateRequest(this), 0);
299 void TurnPort::OnSocketConnect(talk_base::AsyncPacketSocket* socket) {
300 ASSERT(server_address_.proto == PROTO_TCP);
301 // Do not use this port if the socket bound to a different address than
302 // the one we asked for. This is seen in Chrome, where TCP sockets cannot be
303 // given a binding address, and the platform is expected to pick the
304 // correct local address.
305 if (socket->GetLocalAddress().ipaddr() != ip()) {
306 LOG(LS_WARNING) << "Socket is bound to a different address then the "
307 << "local port. Discarding TURN port.";
312 LOG(LS_INFO) << "TurnPort connected to " << socket->GetRemoteAddress()
314 SendRequest(new TurnAllocateRequest(this), 0);
317 void TurnPort::OnSocketClose(talk_base::AsyncPacketSocket* socket, int error) {
318 LOG_J(LS_WARNING, this) << "Connection with server failed, error=" << error;
324 Connection* TurnPort::CreateConnection(const Candidate& address,
325 CandidateOrigin origin) {
326 // TURN-UDP can only connect to UDP candidates.
327 if (address.protocol() != UDP_PROTOCOL_NAME) {
331 if (!IsCompatibleAddress(address.address())) {
335 // Create an entry, if needed, so we can get our permissions set up correctly.
336 CreateEntry(address.address());
338 // A TURN port will have two candiates, STUN and TURN. STUN may not
339 // present in all cases. If present stun candidate will be added first
340 // and TURN candidate later.
341 for (size_t index = 0; index < Candidates().size(); ++index) {
342 if (Candidates()[index].type() == RELAY_PORT_TYPE) {
343 ProxyConnection* conn = new ProxyConnection(this, index, address);
344 conn->SignalDestroyed.connect(this, &TurnPort::OnConnectionDestroyed);
352 int TurnPort::SetOption(talk_base::Socket::Option opt, int value) {
354 // If socket is not created yet, these options will be applied during socket
356 socket_options_[opt] = value;
359 return socket_->SetOption(opt, value);
362 int TurnPort::GetOption(talk_base::Socket::Option opt, int* value) {
364 SocketOptionsMap::const_iterator it = socket_options_.find(opt);
365 if (it == socket_options_.end()) {
372 return socket_->GetOption(opt, value);
375 int TurnPort::GetError() {
379 int TurnPort::SendTo(const void* data, size_t size,
380 const talk_base::SocketAddress& addr,
381 const talk_base::PacketOptions& options,
383 // Try to find an entry for this specific address; we should have one.
384 TurnEntry* entry = FindEntry(addr);
385 ASSERT(entry != NULL);
391 error_ = EWOULDBLOCK;
395 // Send the actual contents to the server using the usual mechanism.
396 int sent = entry->Send(data, size, payload, options);
401 // The caller of the function is expecting the number of user data bytes,
402 // rather than the size of the packet.
403 return static_cast<int>(size);
406 void TurnPort::OnReadPacket(
407 talk_base::AsyncPacketSocket* socket, const char* data, size_t size,
408 const talk_base::SocketAddress& remote_addr,
409 const talk_base::PacketTime& packet_time) {
410 ASSERT(socket == socket_);
411 ASSERT(remote_addr == server_address_.address);
413 // The message must be at least the size of a channel header.
414 if (size < TURN_CHANNEL_HEADER_SIZE) {
415 LOG_J(LS_WARNING, this) << "Received TURN message that was too short";
419 // Check the message type, to see if is a Channel Data message.
420 // The message will either be channel data, a TURN data indication, or
421 // a response to a previous request.
422 uint16 msg_type = talk_base::GetBE16(data);
423 if (IsTurnChannelData(msg_type)) {
424 HandleChannelData(msg_type, data, size, packet_time);
425 } else if (msg_type == TURN_DATA_INDICATION) {
426 HandleDataIndication(data, size, packet_time);
428 // This must be a response for one of our requests.
429 // Check success responses, but not errors, for MESSAGE-INTEGRITY.
430 if (IsStunSuccessResponseType(msg_type) &&
431 !StunMessage::ValidateMessageIntegrity(data, size, hash())) {
432 LOG_J(LS_WARNING, this) << "Received TURN message with invalid "
433 << "message integrity, msg_type=" << msg_type;
436 request_manager_.CheckResponse(data, size);
440 void TurnPort::OnReadyToSend(talk_base::AsyncPacketSocket* socket) {
442 Port::OnReadyToSend();
446 void TurnPort::ResolveTurnAddress(const talk_base::SocketAddress& address) {
450 resolver_ = socket_factory()->CreateAsyncResolver();
451 resolver_->SignalDone.connect(this, &TurnPort::OnResolveResult);
452 resolver_->Start(address);
455 void TurnPort::OnResolveResult(talk_base::AsyncResolverInterface* resolver) {
456 ASSERT(resolver == resolver_);
457 talk_base::SocketAddress resolved_address;
458 if (resolver_->GetError() != 0 ||
459 !resolver_->GetResolvedAddress(ip().family(), &resolved_address)) {
460 LOG_J(LS_WARNING, this) << "TURN host lookup received error "
461 << resolver_->GetError();
465 // Signal needs both resolved and unresolved address. After signal is sent
466 // we can copy resolved address back into |server_address_|.
467 SignalResolvedServerAddress(this, server_address_.address,
469 server_address_.address = resolved_address;
473 void TurnPort::OnSendStunPacket(const void* data, size_t size,
474 StunRequest* request) {
475 talk_base::PacketOptions options(DefaultDscpValue());
476 if (Send(data, size, options) < 0) {
477 LOG_J(LS_ERROR, this) << "Failed to send TURN message, err="
478 << socket_->GetError();
482 void TurnPort::OnStunAddress(const talk_base::SocketAddress& address) {
483 if (server_address_.proto == PROTO_UDP &&
484 address != socket_->GetLocalAddress()) {
485 AddAddress(address, // Candidate address.
486 socket_->GetLocalAddress(), // Base address.
487 socket_->GetLocalAddress(), // Related address.
490 ICE_TYPE_PREFERENCE_SRFLX,
495 void TurnPort::OnAllocateSuccess(const talk_base::SocketAddress& address,
496 const talk_base::SocketAddress& stun_address) {
497 // For relayed candidate, Base is the candidate itself.
499 AddAddress(address, // Candidate address.
500 address, // Base address.
501 stun_address, // Related address.
504 GetRelayPreference(server_address_.proto, server_address_.secure),
508 void TurnPort::OnAllocateError() {
509 // We will send SignalPortError asynchronously as this can be sent during
510 // port initialization. This way it will not be blocking other port
512 thread()->Post(this, MSG_ERROR);
515 void TurnPort::OnMessage(talk_base::Message* message) {
516 if (message->message_id == MSG_ERROR) {
517 SignalPortError(this);
521 Port::OnMessage(message);
524 void TurnPort::OnAllocateRequestTimeout() {
528 void TurnPort::HandleDataIndication(const char* data, size_t size,
529 const talk_base::PacketTime& packet_time) {
530 // Read in the message, and process according to RFC5766, Section 10.4.
531 talk_base::ByteBuffer buf(data, size);
533 if (!msg.Read(&buf)) {
534 LOG_J(LS_WARNING, this) << "Received invalid TURN data indication";
538 // Check mandatory attributes.
539 const StunAddressAttribute* addr_attr =
540 msg.GetAddress(STUN_ATTR_XOR_PEER_ADDRESS);
542 LOG_J(LS_WARNING, this) << "Missing STUN_ATTR_XOR_PEER_ADDRESS attribute "
543 << "in data indication.";
547 const StunByteStringAttribute* data_attr =
548 msg.GetByteString(STUN_ATTR_DATA);
550 LOG_J(LS_WARNING, this) << "Missing STUN_ATTR_DATA attribute in "
551 << "data indication.";
555 // Verify that the data came from somewhere we think we have a permission for.
556 talk_base::SocketAddress ext_addr(addr_attr->GetAddress());
557 if (!HasPermission(ext_addr.ipaddr())) {
558 LOG_J(LS_WARNING, this) << "Received TURN data indication with invalid "
559 << "peer address, addr="
560 << ext_addr.ToSensitiveString();
564 DispatchPacket(data_attr->bytes(), data_attr->length(), ext_addr,
565 PROTO_UDP, packet_time);
568 void TurnPort::HandleChannelData(int channel_id, const char* data,
570 const talk_base::PacketTime& packet_time) {
571 // Read the message, and process according to RFC5766, Section 11.6.
573 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
574 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
575 // | Channel Number | Length |
576 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
578 // / Application Data /
581 // | +-------------------------------+
583 // +-------------------------------+
585 // Extract header fields from the message.
586 uint16 len = talk_base::GetBE16(data + 2);
587 if (len > size - TURN_CHANNEL_HEADER_SIZE) {
588 LOG_J(LS_WARNING, this) << "Received TURN channel data message with "
589 << "incorrect length, len=" << len;
592 // Allowing messages larger than |len|, as ChannelData can be padded.
594 TurnEntry* entry = FindEntry(channel_id);
596 LOG_J(LS_WARNING, this) << "Received TURN channel data message for invalid "
597 << "channel, channel_id=" << channel_id;
601 DispatchPacket(data + TURN_CHANNEL_HEADER_SIZE, len, entry->address(),
602 PROTO_UDP, packet_time);
605 void TurnPort::DispatchPacket(const char* data, size_t size,
606 const talk_base::SocketAddress& remote_addr,
607 ProtocolType proto, const talk_base::PacketTime& packet_time) {
608 if (Connection* conn = GetConnection(remote_addr)) {
609 conn->OnReadPacket(data, size, packet_time);
611 Port::OnReadPacket(data, size, remote_addr, proto);
615 bool TurnPort::ScheduleRefresh(int lifetime) {
616 // Lifetime is in seconds; we schedule a refresh for one minute less.
617 if (lifetime < 2 * 60) {
618 LOG_J(LS_WARNING, this) << "Received response with lifetime that was "
619 << "too short, lifetime=" << lifetime;
623 SendRequest(new TurnRefreshRequest(this), (lifetime - 60) * 1000);
627 void TurnPort::SendRequest(StunRequest* req, int delay) {
628 request_manager_.SendDelayed(req, delay);
631 void TurnPort::AddRequestAuthInfo(StunMessage* msg) {
632 // If we've gotten the necessary data from the server, add it to our request.
633 VERIFY(!hash_.empty());
634 VERIFY(msg->AddAttribute(new StunByteStringAttribute(
635 STUN_ATTR_USERNAME, credentials_.username)));
636 VERIFY(msg->AddAttribute(new StunByteStringAttribute(
637 STUN_ATTR_REALM, realm_)));
638 VERIFY(msg->AddAttribute(new StunByteStringAttribute(
639 STUN_ATTR_NONCE, nonce_)));
640 VERIFY(msg->AddMessageIntegrity(hash()));
643 int TurnPort::Send(const void* data, size_t len,
644 const talk_base::PacketOptions& options) {
645 return socket_->SendTo(data, len, server_address_.address, options);
648 void TurnPort::UpdateHash() {
649 VERIFY(ComputeStunCredentialHash(credentials_.username, realm_,
650 credentials_.password, &hash_));
653 bool TurnPort::UpdateNonce(StunMessage* response) {
654 // When stale nonce error received, we should update
655 // hash and store realm and nonce.
656 // Check the mandatory attributes.
657 const StunByteStringAttribute* realm_attr =
658 response->GetByteString(STUN_ATTR_REALM);
660 LOG(LS_ERROR) << "Missing STUN_ATTR_REALM attribute in "
661 << "stale nonce error response.";
664 set_realm(realm_attr->GetString());
666 const StunByteStringAttribute* nonce_attr =
667 response->GetByteString(STUN_ATTR_NONCE);
669 LOG(LS_ERROR) << "Missing STUN_ATTR_NONCE attribute in "
670 << "stale nonce error response.";
673 set_nonce(nonce_attr->GetString());
677 static bool MatchesIP(TurnEntry* e, talk_base::IPAddress ipaddr) {
678 return e->address().ipaddr() == ipaddr;
680 bool TurnPort::HasPermission(const talk_base::IPAddress& ipaddr) const {
681 return (std::find_if(entries_.begin(), entries_.end(),
682 std::bind2nd(std::ptr_fun(MatchesIP), ipaddr)) != entries_.end());
685 static bool MatchesAddress(TurnEntry* e, talk_base::SocketAddress addr) {
686 return e->address() == addr;
688 TurnEntry* TurnPort::FindEntry(const talk_base::SocketAddress& addr) const {
689 EntryList::const_iterator it = std::find_if(entries_.begin(), entries_.end(),
690 std::bind2nd(std::ptr_fun(MatchesAddress), addr));
691 return (it != entries_.end()) ? *it : NULL;
694 static bool MatchesChannelId(TurnEntry* e, int id) {
695 return e->channel_id() == id;
697 TurnEntry* TurnPort::FindEntry(int channel_id) const {
698 EntryList::const_iterator it = std::find_if(entries_.begin(), entries_.end(),
699 std::bind2nd(std::ptr_fun(MatchesChannelId), channel_id));
700 return (it != entries_.end()) ? *it : NULL;
703 TurnEntry* TurnPort::CreateEntry(const talk_base::SocketAddress& addr) {
704 ASSERT(FindEntry(addr) == NULL);
705 TurnEntry* entry = new TurnEntry(this, next_channel_number_++, addr);
706 entries_.push_back(entry);
710 void TurnPort::DestroyEntry(const talk_base::SocketAddress& addr) {
711 TurnEntry* entry = FindEntry(addr);
712 ASSERT(entry != NULL);
713 entry->SignalDestroyed(entry);
714 entries_.remove(entry);
718 void TurnPort::OnConnectionDestroyed(Connection* conn) {
719 // Destroying TurnEntry for the connection, which is already destroyed.
720 DestroyEntry(conn->remote_candidate().address());
723 TurnAllocateRequest::TurnAllocateRequest(TurnPort* port)
724 : StunRequest(new TurnMessage()),
728 void TurnAllocateRequest::Prepare(StunMessage* request) {
729 // Create the request as indicated in RFC 5766, Section 6.1.
730 request->SetType(TURN_ALLOCATE_REQUEST);
731 StunUInt32Attribute* transport_attr = StunAttribute::CreateUInt32(
732 STUN_ATTR_REQUESTED_TRANSPORT);
733 transport_attr->SetValue(IPPROTO_UDP << 24);
734 VERIFY(request->AddAttribute(transport_attr));
735 if (!port_->hash().empty()) {
736 port_->AddRequestAuthInfo(request);
740 void TurnAllocateRequest::OnResponse(StunMessage* response) {
741 // Check mandatory attributes as indicated in RFC5766, Section 6.3.
742 const StunAddressAttribute* mapped_attr =
743 response->GetAddress(STUN_ATTR_XOR_MAPPED_ADDRESS);
745 LOG_J(LS_WARNING, port_) << "Missing STUN_ATTR_XOR_MAPPED_ADDRESS "
746 << "attribute in allocate success response";
750 // Using XOR-Mapped-Address for stun.
751 port_->OnStunAddress(mapped_attr->GetAddress());
753 const StunAddressAttribute* relayed_attr =
754 response->GetAddress(STUN_ATTR_XOR_RELAYED_ADDRESS);
756 LOG_J(LS_WARNING, port_) << "Missing STUN_ATTR_XOR_RELAYED_ADDRESS "
757 << "attribute in allocate success response";
761 const StunUInt32Attribute* lifetime_attr =
762 response->GetUInt32(STUN_ATTR_TURN_LIFETIME);
763 if (!lifetime_attr) {
764 LOG_J(LS_WARNING, port_) << "Missing STUN_ATTR_TURN_LIFETIME attribute in "
765 << "allocate success response";
768 // Notify the port the allocate succeeded, and schedule a refresh request.
769 port_->OnAllocateSuccess(relayed_attr->GetAddress(),
770 mapped_attr->GetAddress());
771 port_->ScheduleRefresh(lifetime_attr->value());
774 void TurnAllocateRequest::OnErrorResponse(StunMessage* response) {
775 // Process error response according to RFC5766, Section 6.4.
776 const StunErrorCodeAttribute* error_code = response->GetErrorCode();
777 switch (error_code->code()) {
778 case STUN_ERROR_UNAUTHORIZED: // Unauthrorized.
779 OnAuthChallenge(response, error_code->code());
782 LOG_J(LS_WARNING, port_) << "Allocate response error, code="
783 << error_code->code();
784 port_->OnAllocateError();
788 void TurnAllocateRequest::OnTimeout() {
789 LOG_J(LS_WARNING, port_) << "Allocate request timeout";
790 port_->OnAllocateRequestTimeout();
793 void TurnAllocateRequest::OnAuthChallenge(StunMessage* response, int code) {
794 // If we failed to authenticate even after we sent our credentials, fail hard.
795 if (code == STUN_ERROR_UNAUTHORIZED && !port_->hash().empty()) {
796 LOG_J(LS_WARNING, port_) << "Failed to authenticate with the server "
797 << "after challenge.";
798 port_->OnAllocateError();
802 // Check the mandatory attributes.
803 const StunByteStringAttribute* realm_attr =
804 response->GetByteString(STUN_ATTR_REALM);
806 LOG_J(LS_WARNING, port_) << "Missing STUN_ATTR_REALM attribute in "
807 << "allocate unauthorized response.";
810 port_->set_realm(realm_attr->GetString());
812 const StunByteStringAttribute* nonce_attr =
813 response->GetByteString(STUN_ATTR_NONCE);
815 LOG_J(LS_WARNING, port_) << "Missing STUN_ATTR_NONCE attribute in "
816 << "allocate unauthorized response.";
819 port_->set_nonce(nonce_attr->GetString());
821 // Send another allocate request, with the received realm and nonce values.
822 port_->SendRequest(new TurnAllocateRequest(port_), 0);
825 TurnRefreshRequest::TurnRefreshRequest(TurnPort* port)
826 : StunRequest(new TurnMessage()),
830 void TurnRefreshRequest::Prepare(StunMessage* request) {
831 // Create the request as indicated in RFC 5766, Section 7.1.
832 // No attributes need to be included.
833 request->SetType(TURN_REFRESH_REQUEST);
834 port_->AddRequestAuthInfo(request);
837 void TurnRefreshRequest::OnResponse(StunMessage* response) {
838 // Check mandatory attributes as indicated in RFC5766, Section 7.3.
839 const StunUInt32Attribute* lifetime_attr =
840 response->GetUInt32(STUN_ATTR_TURN_LIFETIME);
841 if (!lifetime_attr) {
842 LOG_J(LS_WARNING, port_) << "Missing STUN_ATTR_TURN_LIFETIME attribute in "
843 << "refresh success response.";
847 // Schedule a refresh based on the returned lifetime value.
848 port_->ScheduleRefresh(lifetime_attr->value());
851 void TurnRefreshRequest::OnErrorResponse(StunMessage* response) {
852 // TODO(juberti): Handle 437 error response as a success.
853 const StunErrorCodeAttribute* error_code = response->GetErrorCode();
854 LOG_J(LS_WARNING, port_) << "Refresh response error, code="
855 << error_code->code();
857 if (error_code->code() == STUN_ERROR_STALE_NONCE) {
858 if (port_->UpdateNonce(response)) {
859 // Send RefreshRequest immediately.
860 port_->SendRequest(new TurnRefreshRequest(port_), 0);
865 void TurnRefreshRequest::OnTimeout() {
868 TurnCreatePermissionRequest::TurnCreatePermissionRequest(
869 TurnPort* port, TurnEntry* entry,
870 const talk_base::SocketAddress& ext_addr)
871 : StunRequest(new TurnMessage()),
874 ext_addr_(ext_addr) {
875 entry_->SignalDestroyed.connect(
876 this, &TurnCreatePermissionRequest::OnEntryDestroyed);
879 void TurnCreatePermissionRequest::Prepare(StunMessage* request) {
880 // Create the request as indicated in RFC5766, Section 9.1.
881 request->SetType(TURN_CREATE_PERMISSION_REQUEST);
882 VERIFY(request->AddAttribute(new StunXorAddressAttribute(
883 STUN_ATTR_XOR_PEER_ADDRESS, ext_addr_)));
884 port_->AddRequestAuthInfo(request);
887 void TurnCreatePermissionRequest::OnResponse(StunMessage* response) {
889 entry_->OnCreatePermissionSuccess();
893 void TurnCreatePermissionRequest::OnErrorResponse(StunMessage* response) {
895 const StunErrorCodeAttribute* error_code = response->GetErrorCode();
896 entry_->OnCreatePermissionError(response, error_code->code());
900 void TurnCreatePermissionRequest::OnTimeout() {
901 LOG_J(LS_WARNING, port_) << "Create permission timeout";
904 void TurnCreatePermissionRequest::OnEntryDestroyed(TurnEntry* entry) {
905 ASSERT(entry_ == entry);
909 TurnChannelBindRequest::TurnChannelBindRequest(
910 TurnPort* port, TurnEntry* entry,
911 int channel_id, const talk_base::SocketAddress& ext_addr)
912 : StunRequest(new TurnMessage()),
915 channel_id_(channel_id),
916 ext_addr_(ext_addr) {
917 entry_->SignalDestroyed.connect(
918 this, &TurnChannelBindRequest::OnEntryDestroyed);
921 void TurnChannelBindRequest::Prepare(StunMessage* request) {
922 // Create the request as indicated in RFC5766, Section 11.1.
923 request->SetType(TURN_CHANNEL_BIND_REQUEST);
924 VERIFY(request->AddAttribute(new StunUInt32Attribute(
925 STUN_ATTR_CHANNEL_NUMBER, channel_id_ << 16)));
926 VERIFY(request->AddAttribute(new StunXorAddressAttribute(
927 STUN_ATTR_XOR_PEER_ADDRESS, ext_addr_)));
928 port_->AddRequestAuthInfo(request);
931 void TurnChannelBindRequest::OnResponse(StunMessage* response) {
933 entry_->OnChannelBindSuccess();
934 // Refresh the channel binding just under the permission timeout
935 // threshold. The channel binding has a longer lifetime, but
936 // this is the easiest way to keep both the channel and the
937 // permission from expiring.
938 entry_->SendChannelBindRequest(TURN_PERMISSION_TIMEOUT - 60 * 1000);
942 void TurnChannelBindRequest::OnErrorResponse(StunMessage* response) {
944 const StunErrorCodeAttribute* error_code = response->GetErrorCode();
945 entry_->OnChannelBindError(response, error_code->code());
949 void TurnChannelBindRequest::OnTimeout() {
950 LOG_J(LS_WARNING, port_) << "Channel bind timeout";
953 void TurnChannelBindRequest::OnEntryDestroyed(TurnEntry* entry) {
954 ASSERT(entry_ == entry);
958 TurnEntry::TurnEntry(TurnPort* port, int channel_id,
959 const talk_base::SocketAddress& ext_addr)
961 channel_id_(channel_id),
963 state_(STATE_UNBOUND) {
964 // Creating permission for |ext_addr_|.
965 SendCreatePermissionRequest();
968 void TurnEntry::SendCreatePermissionRequest() {
969 port_->SendRequest(new TurnCreatePermissionRequest(
970 port_, this, ext_addr_), 0);
973 void TurnEntry::SendChannelBindRequest(int delay) {
974 port_->SendRequest(new TurnChannelBindRequest(
975 port_, this, channel_id_, ext_addr_), delay);
978 int TurnEntry::Send(const void* data, size_t size, bool payload,
979 const talk_base::PacketOptions& options) {
980 talk_base::ByteBuffer buf;
981 if (state_ != STATE_BOUND) {
982 // If we haven't bound the channel yet, we have to use a Send Indication.
984 msg.SetType(TURN_SEND_INDICATION);
985 msg.SetTransactionID(
986 talk_base::CreateRandomString(kStunTransactionIdLength));
987 VERIFY(msg.AddAttribute(new StunXorAddressAttribute(
988 STUN_ATTR_XOR_PEER_ADDRESS, ext_addr_)));
989 VERIFY(msg.AddAttribute(new StunByteStringAttribute(
990 STUN_ATTR_DATA, data, size)));
991 VERIFY(msg.Write(&buf));
993 // If we're sending real data, request a channel bind that we can use later.
994 if (state_ == STATE_UNBOUND && payload) {
995 SendChannelBindRequest(0);
996 state_ = STATE_BINDING;
999 // If the channel is bound, we can send the data as a Channel Message.
1000 buf.WriteUInt16(channel_id_);
1001 buf.WriteUInt16(static_cast<uint16>(size));
1002 buf.WriteBytes(reinterpret_cast<const char*>(data), size);
1004 return port_->Send(buf.Data(), buf.Length(), options);
1007 void TurnEntry::OnCreatePermissionSuccess() {
1008 LOG_J(LS_INFO, port_) << "Create permission for "
1009 << ext_addr_.ToSensitiveString()
1011 // For success result code will be 0.
1012 port_->SignalCreatePermissionResult(port_, ext_addr_, 0);
1015 void TurnEntry::OnCreatePermissionError(StunMessage* response, int code) {
1016 LOG_J(LS_WARNING, port_) << "Create permission for "
1017 << ext_addr_.ToSensitiveString()
1018 << " failed, code=" << code;
1019 if (code == STUN_ERROR_STALE_NONCE) {
1020 if (port_->UpdateNonce(response)) {
1021 SendCreatePermissionRequest();
1024 // Send signal with error code.
1025 port_->SignalCreatePermissionResult(port_, ext_addr_, code);
1029 void TurnEntry::OnChannelBindSuccess() {
1030 LOG_J(LS_INFO, port_) << "Channel bind for " << ext_addr_.ToSensitiveString()
1032 ASSERT(state_ == STATE_BINDING || state_ == STATE_BOUND);
1033 state_ = STATE_BOUND;
1036 void TurnEntry::OnChannelBindError(StunMessage* response, int code) {
1037 // TODO(mallinath) - Implement handling of error response for channel
1038 // bind request as per http://tools.ietf.org/html/rfc5766#section-11.3
1039 LOG_J(LS_WARNING, port_) << "Channel bind for "
1040 << ext_addr_.ToSensitiveString()
1041 << " failed, code=" << code;
1042 if (code == STUN_ERROR_STALE_NONCE) {
1043 if (port_->UpdateNonce(response)) {
1044 // Send channel bind request with fresh nonce.
1045 SendChannelBindRequest(0);
1050 } // namespace cricket