blob: 2ea3ff445fcde9e9522d78c273a0d0f34d220100 [file] [log] [blame]
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001/*
2 * Copyright 2012 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "webrtc/p2p/base/turnport.h"
12
13#include <functional>
14
15#include "webrtc/p2p/base/common.h"
16#include "webrtc/p2p/base/stun.h"
17#include "webrtc/base/asyncpacketsocket.h"
18#include "webrtc/base/byteorder.h"
19#include "webrtc/base/common.h"
20#include "webrtc/base/logging.h"
21#include "webrtc/base/nethelpers.h"
22#include "webrtc/base/socketaddress.h"
23#include "webrtc/base/stringencode.h"
24
25namespace cricket {
26
27// TODO(juberti): Move to stun.h when relay messages have been renamed.
28static const int TURN_ALLOCATE_REQUEST = STUN_ALLOCATE_REQUEST;
29
30// TODO(juberti): Extract to turnmessage.h
31static const int TURN_DEFAULT_PORT = 3478;
32static const int TURN_CHANNEL_NUMBER_START = 0x4000;
33static const int TURN_PERMISSION_TIMEOUT = 5 * 60 * 1000; // 5 minutes
34
35static const size_t TURN_CHANNEL_HEADER_SIZE = 4U;
36
37// Retry at most twice (i.e. three different ALLOCATE requests) on
38// STUN_ERROR_ALLOCATION_MISMATCH error per rfc5766.
39static const size_t MAX_ALLOCATE_MISMATCH_RETRIES = 2;
40
41inline bool IsTurnChannelData(uint16 msg_type) {
42 return ((msg_type & 0xC000) == 0x4000); // MSB are 0b01
43}
44
45static int GetRelayPreference(cricket::ProtocolType proto, bool secure) {
46 int relay_preference = ICE_TYPE_PREFERENCE_RELAY;
47 if (proto == cricket::PROTO_TCP) {
48 relay_preference -= 1;
49 if (secure)
50 relay_preference -= 1;
51 }
52
53 ASSERT(relay_preference >= 0);
54 return relay_preference;
55}
56
57class TurnAllocateRequest : public StunRequest {
58 public:
59 explicit TurnAllocateRequest(TurnPort* port);
60 virtual void Prepare(StunMessage* request);
61 virtual void OnResponse(StunMessage* response);
62 virtual void OnErrorResponse(StunMessage* response);
63 virtual void OnTimeout();
64
65 private:
66 // Handles authentication challenge from the server.
67 void OnAuthChallenge(StunMessage* response, int code);
68 void OnTryAlternate(StunMessage* response, int code);
69 void OnUnknownAttribute(StunMessage* response);
70
71 TurnPort* port_;
72};
73
74class TurnRefreshRequest : public StunRequest {
75 public:
76 explicit TurnRefreshRequest(TurnPort* port);
77 virtual void Prepare(StunMessage* request);
78 virtual void OnResponse(StunMessage* response);
79 virtual void OnErrorResponse(StunMessage* response);
80 virtual void OnTimeout();
81
82 private:
83 TurnPort* port_;
84};
85
86class TurnCreatePermissionRequest : public StunRequest,
87 public sigslot::has_slots<> {
88 public:
89 TurnCreatePermissionRequest(TurnPort* port, TurnEntry* entry,
90 const rtc::SocketAddress& ext_addr);
91 virtual void Prepare(StunMessage* request);
92 virtual void OnResponse(StunMessage* response);
93 virtual void OnErrorResponse(StunMessage* response);
94 virtual void OnTimeout();
95
96 private:
97 void OnEntryDestroyed(TurnEntry* entry);
98
99 TurnPort* port_;
100 TurnEntry* entry_;
101 rtc::SocketAddress ext_addr_;
102};
103
104class TurnChannelBindRequest : public StunRequest,
105 public sigslot::has_slots<> {
106 public:
107 TurnChannelBindRequest(TurnPort* port, TurnEntry* entry, int channel_id,
108 const rtc::SocketAddress& ext_addr);
109 virtual void Prepare(StunMessage* request);
110 virtual void OnResponse(StunMessage* response);
111 virtual void OnErrorResponse(StunMessage* response);
112 virtual void OnTimeout();
113
114 private:
115 void OnEntryDestroyed(TurnEntry* entry);
116
117 TurnPort* port_;
118 TurnEntry* entry_;
119 int channel_id_;
120 rtc::SocketAddress ext_addr_;
121};
122
123// Manages a "connection" to a remote destination. We will attempt to bring up
124// a channel for this remote destination to reduce the overhead of sending data.
125class TurnEntry : public sigslot::has_slots<> {
126 public:
127 enum BindState { STATE_UNBOUND, STATE_BINDING, STATE_BOUND };
128 TurnEntry(TurnPort* port, int channel_id,
129 const rtc::SocketAddress& ext_addr);
130
131 TurnPort* port() { return port_; }
132
133 int channel_id() const { return channel_id_; }
134 const rtc::SocketAddress& address() const { return ext_addr_; }
135 BindState state() const { return state_; }
136
137 // Helper methods to send permission and channel bind requests.
138 void SendCreatePermissionRequest();
139 void SendChannelBindRequest(int delay);
140 // Sends a packet to the given destination address.
141 // This will wrap the packet in STUN if necessary.
142 int Send(const void* data, size_t size, bool payload,
143 const rtc::PacketOptions& options);
144
145 void OnCreatePermissionSuccess();
146 void OnCreatePermissionError(StunMessage* response, int code);
147 void OnChannelBindSuccess();
148 void OnChannelBindError(StunMessage* response, int code);
149 // Signal sent when TurnEntry is destroyed.
150 sigslot::signal1<TurnEntry*> SignalDestroyed;
151
152 private:
153 TurnPort* port_;
154 int channel_id_;
155 rtc::SocketAddress ext_addr_;
156 BindState state_;
157};
158
159TurnPort::TurnPort(rtc::Thread* thread,
160 rtc::PacketSocketFactory* factory,
161 rtc::Network* network,
162 rtc::AsyncPacketSocket* socket,
163 const std::string& username,
164 const std::string& password,
165 const ProtocolAddress& server_address,
166 const RelayCredentials& credentials,
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000167 int server_priority,
168 const std::string& origin)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000169 : Port(thread, factory, network, socket->GetLocalAddress().ipaddr(),
170 username, password),
171 server_address_(server_address),
172 credentials_(credentials),
173 socket_(socket),
174 resolver_(NULL),
175 error_(0),
176 request_manager_(thread),
177 next_channel_number_(TURN_CHANNEL_NUMBER_START),
178 connected_(false),
179 server_priority_(server_priority),
180 allocate_mismatch_retries_(0) {
181 request_manager_.SignalSendPacket.connect(this, &TurnPort::OnSendStunPacket);
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000182 request_manager_.set_origin(origin);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000183}
184
185TurnPort::TurnPort(rtc::Thread* thread,
186 rtc::PacketSocketFactory* factory,
187 rtc::Network* network,
188 const rtc::IPAddress& ip,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000189 uint16 min_port,
190 uint16 max_port,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000191 const std::string& username,
192 const std::string& password,
193 const ProtocolAddress& server_address,
194 const RelayCredentials& credentials,
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000195 int server_priority,
196 const std::string& origin)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000197 : Port(thread, RELAY_PORT_TYPE, factory, network, ip, min_port, max_port,
198 username, password),
199 server_address_(server_address),
200 credentials_(credentials),
201 socket_(NULL),
202 resolver_(NULL),
203 error_(0),
204 request_manager_(thread),
205 next_channel_number_(TURN_CHANNEL_NUMBER_START),
206 connected_(false),
207 server_priority_(server_priority),
208 allocate_mismatch_retries_(0) {
209 request_manager_.SignalSendPacket.connect(this, &TurnPort::OnSendStunPacket);
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000210 request_manager_.set_origin(origin);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000211}
212
213TurnPort::~TurnPort() {
214 // TODO(juberti): Should this even be necessary?
215 while (!entries_.empty()) {
216 DestroyEntry(entries_.front()->address());
217 }
218 if (resolver_) {
219 resolver_->Destroy(false);
220 }
221 if (!SharedSocket()) {
222 delete socket_;
223 }
224}
225
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000226rtc::SocketAddress TurnPort::GetLocalAddress() const {
227 return socket_ ? socket_->GetLocalAddress() : rtc::SocketAddress();
228}
229
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000230void TurnPort::PrepareAddress() {
231 if (credentials_.username.empty() ||
232 credentials_.password.empty()) {
233 LOG(LS_ERROR) << "Allocation can't be started without setting the"
234 << " TURN server credentials for the user.";
235 OnAllocateError();
236 return;
237 }
238
239 if (!server_address_.address.port()) {
240 // We will set default TURN port, if no port is set in the address.
241 server_address_.address.SetPort(TURN_DEFAULT_PORT);
242 }
243
244 if (server_address_.address.IsUnresolved()) {
245 ResolveTurnAddress(server_address_.address);
246 } else {
247 // If protocol family of server address doesn't match with local, return.
248 if (!IsCompatibleAddress(server_address_.address)) {
249 LOG(LS_ERROR) << "Server IP address family does not match with "
250 << "local host address family type";
251 OnAllocateError();
252 return;
253 }
254
255 // Insert the current address to prevent redirection pingpong.
256 attempted_server_addresses_.insert(server_address_.address);
257
258 LOG_J(LS_INFO, this) << "Trying to connect to TURN server via "
259 << ProtoToString(server_address_.proto) << " @ "
260 << server_address_.address.ToSensitiveString();
261 if (!CreateTurnClientSocket()) {
262 OnAllocateError();
263 } else if (server_address_.proto == PROTO_UDP) {
264 // If its UDP, send AllocateRequest now.
265 // For TCP and TLS AllcateRequest will be sent by OnSocketConnect.
266 SendRequest(new TurnAllocateRequest(this), 0);
267 }
268 }
269}
270
271bool TurnPort::CreateTurnClientSocket() {
272 ASSERT(!socket_ || SharedSocket());
273
274 if (server_address_.proto == PROTO_UDP && !SharedSocket()) {
275 socket_ = socket_factory()->CreateUdpSocket(
276 rtc::SocketAddress(ip(), 0), min_port(), max_port());
277 } else if (server_address_.proto == PROTO_TCP) {
278 ASSERT(!SharedSocket());
279 int opts = rtc::PacketSocketFactory::OPT_STUN;
280 // If secure bit is enabled in server address, use TLS over TCP.
281 if (server_address_.secure) {
282 opts |= rtc::PacketSocketFactory::OPT_TLS;
283 }
284 socket_ = socket_factory()->CreateClientTcpSocket(
285 rtc::SocketAddress(ip(), 0), server_address_.address,
286 proxy(), user_agent(), opts);
287 }
288
289 if (!socket_) {
290 error_ = SOCKET_ERROR;
291 return false;
292 }
293
294 // Apply options if any.
295 for (SocketOptionsMap::iterator iter = socket_options_.begin();
296 iter != socket_options_.end(); ++iter) {
297 socket_->SetOption(iter->first, iter->second);
298 }
299
300 if (!SharedSocket()) {
301 // If socket is shared, AllocationSequence will receive the packet.
302 socket_->SignalReadPacket.connect(this, &TurnPort::OnReadPacket);
303 }
304
305 socket_->SignalReadyToSend.connect(this, &TurnPort::OnReadyToSend);
306
307 if (server_address_.proto == PROTO_TCP) {
308 socket_->SignalConnect.connect(this, &TurnPort::OnSocketConnect);
309 socket_->SignalClose.connect(this, &TurnPort::OnSocketClose);
310 }
311 return true;
312}
313
314void TurnPort::OnSocketConnect(rtc::AsyncPacketSocket* socket) {
315 ASSERT(server_address_.proto == PROTO_TCP);
316 // Do not use this port if the socket bound to a different address than
317 // the one we asked for. This is seen in Chrome, where TCP sockets cannot be
318 // given a binding address, and the platform is expected to pick the
319 // correct local address.
guoweis@webrtc.org4fba2932014-12-18 04:45:05 +0000320
321 // Further, to workaround issue 3927 in which a proxy is forcing TCP bound to
322 // localhost only, we're allowing Loopback IP even if it's not the same as the
323 // local Turn port.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000324 if (socket->GetLocalAddress().ipaddr() != ip()) {
guoweis@webrtc.org4fba2932014-12-18 04:45:05 +0000325 if (socket->GetLocalAddress().IsLoopbackIP()) {
326 LOG(LS_WARNING) << "Socket is bound to a different address:"
327 << socket->GetLocalAddress().ipaddr().ToString()
328 << ", rather then the local port:" << ip().ToString()
329 << ". Still allowing it since it's localhost.";
330 } else {
331 LOG(LS_WARNING) << "Socket is bound to a different address:"
332 << socket->GetLocalAddress().ipaddr().ToString()
333 << ", rather then the local port:" << ip().ToString()
334 << ". Discarding TURN port.";
335 OnAllocateError();
336 return;
337 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000338 }
339
340 if (server_address_.address.IsUnresolved()) {
341 server_address_.address = socket_->GetRemoteAddress();
342 }
343
344 LOG(LS_INFO) << "TurnPort connected to " << socket->GetRemoteAddress()
345 << " using tcp.";
346 SendRequest(new TurnAllocateRequest(this), 0);
347}
348
349void TurnPort::OnSocketClose(rtc::AsyncPacketSocket* socket, int error) {
350 LOG_J(LS_WARNING, this) << "Connection with server failed, error=" << error;
351 if (!connected_) {
352 OnAllocateError();
353 }
354}
355
356void TurnPort::OnAllocateMismatch() {
357 if (allocate_mismatch_retries_ >= MAX_ALLOCATE_MISMATCH_RETRIES) {
358 LOG_J(LS_WARNING, this) << "Giving up on the port after "
359 << allocate_mismatch_retries_
360 << " retries for STUN_ERROR_ALLOCATION_MISMATCH";
361 OnAllocateError();
362 return;
363 }
364
365 LOG_J(LS_INFO, this) << "Allocating a new socket after "
366 << "STUN_ERROR_ALLOCATION_MISMATCH, retry = "
367 << allocate_mismatch_retries_ + 1;
368 if (SharedSocket()) {
369 ResetSharedSocket();
370 } else {
371 delete socket_;
372 }
373 socket_ = NULL;
374
375 PrepareAddress();
376 ++allocate_mismatch_retries_;
377}
378
379Connection* TurnPort::CreateConnection(const Candidate& address,
380 CandidateOrigin origin) {
381 // TURN-UDP can only connect to UDP candidates.
382 if (address.protocol() != UDP_PROTOCOL_NAME) {
383 return NULL;
384 }
385
386 if (!IsCompatibleAddress(address.address())) {
387 return NULL;
388 }
389
390 // Create an entry, if needed, so we can get our permissions set up correctly.
391 CreateEntry(address.address());
392
393 // A TURN port will have two candiates, STUN and TURN. STUN may not
394 // present in all cases. If present stun candidate will be added first
395 // and TURN candidate later.
396 for (size_t index = 0; index < Candidates().size(); ++index) {
397 if (Candidates()[index].type() == RELAY_PORT_TYPE) {
398 ProxyConnection* conn = new ProxyConnection(this, index, address);
399 conn->SignalDestroyed.connect(this, &TurnPort::OnConnectionDestroyed);
400 AddConnection(conn);
401 return conn;
402 }
403 }
404 return NULL;
405}
406
407int TurnPort::SetOption(rtc::Socket::Option opt, int value) {
408 if (!socket_) {
409 // If socket is not created yet, these options will be applied during socket
410 // creation.
411 socket_options_[opt] = value;
412 return 0;
413 }
414 return socket_->SetOption(opt, value);
415}
416
417int TurnPort::GetOption(rtc::Socket::Option opt, int* value) {
418 if (!socket_) {
419 SocketOptionsMap::const_iterator it = socket_options_.find(opt);
420 if (it == socket_options_.end()) {
421 return -1;
422 }
423 *value = it->second;
424 return 0;
425 }
426
427 return socket_->GetOption(opt, value);
428}
429
430int TurnPort::GetError() {
431 return error_;
432}
433
434int TurnPort::SendTo(const void* data, size_t size,
435 const rtc::SocketAddress& addr,
436 const rtc::PacketOptions& options,
437 bool payload) {
438 // Try to find an entry for this specific address; we should have one.
439 TurnEntry* entry = FindEntry(addr);
440 ASSERT(entry != NULL);
441 if (!entry) {
442 return 0;
443 }
444
445 if (!connected()) {
446 error_ = EWOULDBLOCK;
447 return SOCKET_ERROR;
448 }
449
450 // Send the actual contents to the server using the usual mechanism.
451 int sent = entry->Send(data, size, payload, options);
452 if (sent <= 0) {
453 return SOCKET_ERROR;
454 }
455
456 // The caller of the function is expecting the number of user data bytes,
457 // rather than the size of the packet.
458 return static_cast<int>(size);
459}
460
461void TurnPort::OnReadPacket(
462 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
463 const rtc::SocketAddress& remote_addr,
464 const rtc::PacketTime& packet_time) {
465 ASSERT(socket == socket_);
guoweis@webrtc.orgc51fb932014-12-18 00:30:55 +0000466
467 // This is to guard against a STUN response from previous server after
468 // alternative server redirection. TODO(guoweis): add a unit test for this
469 // race condition.
470 if (remote_addr != server_address_.address) {
471 LOG_J(LS_WARNING, this) << "Discarding TURN message from unknown address:"
472 << remote_addr.ToString()
473 << ", server_address_:"
474 << server_address_.address.ToString();
475 return;
476 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000477
478 // The message must be at least the size of a channel header.
479 if (size < TURN_CHANNEL_HEADER_SIZE) {
480 LOG_J(LS_WARNING, this) << "Received TURN message that was too short";
481 return;
482 }
483
484 // Check the message type, to see if is a Channel Data message.
485 // The message will either be channel data, a TURN data indication, or
486 // a response to a previous request.
487 uint16 msg_type = rtc::GetBE16(data);
488 if (IsTurnChannelData(msg_type)) {
489 HandleChannelData(msg_type, data, size, packet_time);
490 } else if (msg_type == TURN_DATA_INDICATION) {
491 HandleDataIndication(data, size, packet_time);
492 } else {
jiayl@webrtc.org511f8a82014-12-03 02:17:07 +0000493 if (SharedSocket() &&
494 (msg_type == STUN_BINDING_RESPONSE ||
495 msg_type == STUN_BINDING_ERROR_RESPONSE)) {
496 LOG_J(LS_VERBOSE, this) <<
497 "Ignoring STUN binding response message on shared socket.";
498 return;
499 }
500
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000501 // This must be a response for one of our requests.
502 // Check success responses, but not errors, for MESSAGE-INTEGRITY.
503 if (IsStunSuccessResponseType(msg_type) &&
504 !StunMessage::ValidateMessageIntegrity(data, size, hash())) {
505 LOG_J(LS_WARNING, this) << "Received TURN message with invalid "
506 << "message integrity, msg_type=" << msg_type;
507 return;
508 }
509 request_manager_.CheckResponse(data, size);
510 }
511}
512
513void TurnPort::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
514 if (connected_) {
515 Port::OnReadyToSend();
516 }
517}
518
519
520// Update current server address port with the alternate server address port.
521bool TurnPort::SetAlternateServer(const rtc::SocketAddress& address) {
522 // Check if we have seen this address before and reject if we did.
523 AttemptedServerSet::iterator iter = attempted_server_addresses_.find(address);
524 if (iter != attempted_server_addresses_.end()) {
525 LOG_J(LS_WARNING, this) << "Redirection to ["
526 << address.ToSensitiveString()
527 << "] ignored, allocation failed.";
528 return false;
529 }
530
531 // If protocol family of server address doesn't match with local, return.
532 if (!IsCompatibleAddress(address)) {
533 LOG(LS_WARNING) << "Server IP address family does not match with "
534 << "local host address family type";
535 return false;
536 }
537
538 LOG_J(LS_INFO, this) << "Redirecting from TURN server ["
539 << server_address_.address.ToSensitiveString()
540 << "] to TURN server ["
541 << address.ToSensitiveString()
542 << "]";
543 server_address_ = ProtocolAddress(address, server_address_.proto,
544 server_address_.secure);
545
546 // Insert the current address to prevent redirection pingpong.
547 attempted_server_addresses_.insert(server_address_.address);
548 return true;
549}
550
551void TurnPort::ResolveTurnAddress(const rtc::SocketAddress& address) {
552 if (resolver_)
553 return;
554
555 resolver_ = socket_factory()->CreateAsyncResolver();
556 resolver_->SignalDone.connect(this, &TurnPort::OnResolveResult);
557 resolver_->Start(address);
558}
559
560void TurnPort::OnResolveResult(rtc::AsyncResolverInterface* resolver) {
561 ASSERT(resolver == resolver_);
562 // If DNS resolve is failed when trying to connect to the server using TCP,
563 // one of the reason could be due to DNS queries blocked by firewall.
564 // In such cases we will try to connect to the server with hostname, assuming
565 // socket layer will resolve the hostname through a HTTP proxy (if any).
566 if (resolver_->GetError() != 0 && server_address_.proto == PROTO_TCP) {
567 if (!CreateTurnClientSocket()) {
568 OnAllocateError();
569 }
570 return;
571 }
572
573 // Copy the original server address in |resolved_address|. For TLS based
574 // sockets we need hostname along with resolved address.
575 rtc::SocketAddress resolved_address = server_address_.address;
576 if (resolver_->GetError() != 0 ||
577 !resolver_->GetResolvedAddress(ip().family(), &resolved_address)) {
578 LOG_J(LS_WARNING, this) << "TURN host lookup received error "
579 << resolver_->GetError();
580 error_ = resolver_->GetError();
581 OnAllocateError();
582 return;
583 }
584 // Signal needs both resolved and unresolved address. After signal is sent
585 // we can copy resolved address back into |server_address_|.
586 SignalResolvedServerAddress(this, server_address_.address,
587 resolved_address);
588 server_address_.address = resolved_address;
589 PrepareAddress();
590}
591
592void TurnPort::OnSendStunPacket(const void* data, size_t size,
593 StunRequest* request) {
594 rtc::PacketOptions options(DefaultDscpValue());
595 if (Send(data, size, options) < 0) {
596 LOG_J(LS_ERROR, this) << "Failed to send TURN message, err="
597 << socket_->GetError();
598 }
599}
600
601void TurnPort::OnStunAddress(const rtc::SocketAddress& address) {
602 // STUN Port will discover STUN candidate, as it's supplied with first TURN
603 // server address.
604 // Why not using this address? - P2PTransportChannel will start creating
605 // connections after first candidate, which means it could start creating the
606 // connections before TURN candidate added. For that to handle, we need to
607 // supply STUN candidate from this port to UDPPort, and TurnPort should have
608 // handle to UDPPort to pass back the address.
609}
610
611void TurnPort::OnAllocateSuccess(const rtc::SocketAddress& address,
612 const rtc::SocketAddress& stun_address) {
613 connected_ = true;
614
615 rtc::SocketAddress related_address = stun_address;
616 if (!(candidate_filter() & CF_REFLEXIVE)) {
617 // If candidate filter only allows relay type of address, empty raddr to
618 // avoid local address leakage.
619 related_address = rtc::EmptySocketAddressWithFamily(stun_address.family());
620 }
621
622 // For relayed candidate, Base is the candidate itself.
623 AddAddress(address, // Candidate address.
624 address, // Base address.
625 related_address, // Related address.
626 UDP_PROTOCOL_NAME,
627 "", // TCP canddiate type, empty for turn candidates.
628 RELAY_PORT_TYPE,
629 GetRelayPreference(server_address_.proto, server_address_.secure),
630 server_priority_,
631 true);
632}
633
634void TurnPort::OnAllocateError() {
635 // We will send SignalPortError asynchronously as this can be sent during
636 // port initialization. This way it will not be blocking other port
637 // creation.
638 thread()->Post(this, MSG_ERROR);
639}
640
641void TurnPort::OnMessage(rtc::Message* message) {
642 if (message->message_id == MSG_ERROR) {
643 SignalPortError(this);
644 return;
645 } else if (message->message_id == MSG_ALLOCATE_MISMATCH) {
646 OnAllocateMismatch();
647 return;
648 }
649
650 Port::OnMessage(message);
651}
652
653void TurnPort::OnAllocateRequestTimeout() {
654 OnAllocateError();
655}
656
657void TurnPort::HandleDataIndication(const char* data, size_t size,
658 const rtc::PacketTime& packet_time) {
659 // Read in the message, and process according to RFC5766, Section 10.4.
660 rtc::ByteBuffer buf(data, size);
661 TurnMessage msg;
662 if (!msg.Read(&buf)) {
663 LOG_J(LS_WARNING, this) << "Received invalid TURN data indication";
664 return;
665 }
666
667 // Check mandatory attributes.
668 const StunAddressAttribute* addr_attr =
669 msg.GetAddress(STUN_ATTR_XOR_PEER_ADDRESS);
670 if (!addr_attr) {
671 LOG_J(LS_WARNING, this) << "Missing STUN_ATTR_XOR_PEER_ADDRESS attribute "
672 << "in data indication.";
673 return;
674 }
675
676 const StunByteStringAttribute* data_attr =
677 msg.GetByteString(STUN_ATTR_DATA);
678 if (!data_attr) {
679 LOG_J(LS_WARNING, this) << "Missing STUN_ATTR_DATA attribute in "
680 << "data indication.";
681 return;
682 }
683
684 // Verify that the data came from somewhere we think we have a permission for.
685 rtc::SocketAddress ext_addr(addr_attr->GetAddress());
686 if (!HasPermission(ext_addr.ipaddr())) {
687 LOG_J(LS_WARNING, this) << "Received TURN data indication with invalid "
688 << "peer address, addr="
689 << ext_addr.ToSensitiveString();
690 return;
691 }
692
693 DispatchPacket(data_attr->bytes(), data_attr->length(), ext_addr,
694 PROTO_UDP, packet_time);
695}
696
697void TurnPort::HandleChannelData(int channel_id, const char* data,
698 size_t size,
699 const rtc::PacketTime& packet_time) {
700 // Read the message, and process according to RFC5766, Section 11.6.
701 // 0 1 2 3
702 // 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
703 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
704 // | Channel Number | Length |
705 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
706 // | |
707 // / Application Data /
708 // / /
709 // | |
710 // | +-------------------------------+
711 // | |
712 // +-------------------------------+
713
714 // Extract header fields from the message.
715 uint16 len = rtc::GetBE16(data + 2);
716 if (len > size - TURN_CHANNEL_HEADER_SIZE) {
717 LOG_J(LS_WARNING, this) << "Received TURN channel data message with "
718 << "incorrect length, len=" << len;
719 return;
720 }
721 // Allowing messages larger than |len|, as ChannelData can be padded.
722
723 TurnEntry* entry = FindEntry(channel_id);
724 if (!entry) {
725 LOG_J(LS_WARNING, this) << "Received TURN channel data message for invalid "
726 << "channel, channel_id=" << channel_id;
727 return;
728 }
729
730 DispatchPacket(data + TURN_CHANNEL_HEADER_SIZE, len, entry->address(),
731 PROTO_UDP, packet_time);
732}
733
734void TurnPort::DispatchPacket(const char* data, size_t size,
735 const rtc::SocketAddress& remote_addr,
736 ProtocolType proto, const rtc::PacketTime& packet_time) {
737 if (Connection* conn = GetConnection(remote_addr)) {
738 conn->OnReadPacket(data, size, packet_time);
739 } else {
740 Port::OnReadPacket(data, size, remote_addr, proto);
741 }
742}
743
744bool TurnPort::ScheduleRefresh(int lifetime) {
745 // Lifetime is in seconds; we schedule a refresh for one minute less.
746 if (lifetime < 2 * 60) {
747 LOG_J(LS_WARNING, this) << "Received response with lifetime that was "
748 << "too short, lifetime=" << lifetime;
749 return false;
750 }
751
752 SendRequest(new TurnRefreshRequest(this), (lifetime - 60) * 1000);
753 return true;
754}
755
756void TurnPort::SendRequest(StunRequest* req, int delay) {
757 request_manager_.SendDelayed(req, delay);
758}
759
760void TurnPort::AddRequestAuthInfo(StunMessage* msg) {
761 // If we've gotten the necessary data from the server, add it to our request.
762 VERIFY(!hash_.empty());
763 VERIFY(msg->AddAttribute(new StunByteStringAttribute(
764 STUN_ATTR_USERNAME, credentials_.username)));
765 VERIFY(msg->AddAttribute(new StunByteStringAttribute(
766 STUN_ATTR_REALM, realm_)));
767 VERIFY(msg->AddAttribute(new StunByteStringAttribute(
768 STUN_ATTR_NONCE, nonce_)));
769 VERIFY(msg->AddMessageIntegrity(hash()));
770}
771
772int TurnPort::Send(const void* data, size_t len,
773 const rtc::PacketOptions& options) {
774 return socket_->SendTo(data, len, server_address_.address, options);
775}
776
777void TurnPort::UpdateHash() {
778 VERIFY(ComputeStunCredentialHash(credentials_.username, realm_,
779 credentials_.password, &hash_));
780}
781
782bool TurnPort::UpdateNonce(StunMessage* response) {
783 // When stale nonce error received, we should update
784 // hash and store realm and nonce.
785 // Check the mandatory attributes.
786 const StunByteStringAttribute* realm_attr =
787 response->GetByteString(STUN_ATTR_REALM);
788 if (!realm_attr) {
789 LOG(LS_ERROR) << "Missing STUN_ATTR_REALM attribute in "
790 << "stale nonce error response.";
791 return false;
792 }
793 set_realm(realm_attr->GetString());
794
795 const StunByteStringAttribute* nonce_attr =
796 response->GetByteString(STUN_ATTR_NONCE);
797 if (!nonce_attr) {
798 LOG(LS_ERROR) << "Missing STUN_ATTR_NONCE attribute in "
799 << "stale nonce error response.";
800 return false;
801 }
802 set_nonce(nonce_attr->GetString());
803 return true;
804}
805
806static bool MatchesIP(TurnEntry* e, rtc::IPAddress ipaddr) {
807 return e->address().ipaddr() == ipaddr;
808}
809bool TurnPort::HasPermission(const rtc::IPAddress& ipaddr) const {
810 return (std::find_if(entries_.begin(), entries_.end(),
811 std::bind2nd(std::ptr_fun(MatchesIP), ipaddr)) != entries_.end());
812}
813
814static bool MatchesAddress(TurnEntry* e, rtc::SocketAddress addr) {
815 return e->address() == addr;
816}
817TurnEntry* TurnPort::FindEntry(const rtc::SocketAddress& addr) const {
818 EntryList::const_iterator it = std::find_if(entries_.begin(), entries_.end(),
819 std::bind2nd(std::ptr_fun(MatchesAddress), addr));
820 return (it != entries_.end()) ? *it : NULL;
821}
822
823static bool MatchesChannelId(TurnEntry* e, int id) {
824 return e->channel_id() == id;
825}
826TurnEntry* TurnPort::FindEntry(int channel_id) const {
827 EntryList::const_iterator it = std::find_if(entries_.begin(), entries_.end(),
828 std::bind2nd(std::ptr_fun(MatchesChannelId), channel_id));
829 return (it != entries_.end()) ? *it : NULL;
830}
831
832TurnEntry* TurnPort::CreateEntry(const rtc::SocketAddress& addr) {
833 ASSERT(FindEntry(addr) == NULL);
834 TurnEntry* entry = new TurnEntry(this, next_channel_number_++, addr);
835 entries_.push_back(entry);
836 return entry;
837}
838
839void TurnPort::DestroyEntry(const rtc::SocketAddress& addr) {
840 TurnEntry* entry = FindEntry(addr);
841 ASSERT(entry != NULL);
842 entry->SignalDestroyed(entry);
843 entries_.remove(entry);
844 delete entry;
845}
846
847void TurnPort::OnConnectionDestroyed(Connection* conn) {
848 // Destroying TurnEntry for the connection, which is already destroyed.
849 DestroyEntry(conn->remote_candidate().address());
850}
851
852TurnAllocateRequest::TurnAllocateRequest(TurnPort* port)
853 : StunRequest(new TurnMessage()),
854 port_(port) {
855}
856
857void TurnAllocateRequest::Prepare(StunMessage* request) {
858 // Create the request as indicated in RFC 5766, Section 6.1.
859 request->SetType(TURN_ALLOCATE_REQUEST);
860 StunUInt32Attribute* transport_attr = StunAttribute::CreateUInt32(
861 STUN_ATTR_REQUESTED_TRANSPORT);
862 transport_attr->SetValue(IPPROTO_UDP << 24);
863 VERIFY(request->AddAttribute(transport_attr));
864 if (!port_->hash().empty()) {
865 port_->AddRequestAuthInfo(request);
866 }
867}
868
869void TurnAllocateRequest::OnResponse(StunMessage* response) {
870 // Check mandatory attributes as indicated in RFC5766, Section 6.3.
871 const StunAddressAttribute* mapped_attr =
872 response->GetAddress(STUN_ATTR_XOR_MAPPED_ADDRESS);
873 if (!mapped_attr) {
874 LOG_J(LS_WARNING, port_) << "Missing STUN_ATTR_XOR_MAPPED_ADDRESS "
875 << "attribute in allocate success response";
876 return;
877 }
878 // Using XOR-Mapped-Address for stun.
879 port_->OnStunAddress(mapped_attr->GetAddress());
880
881 const StunAddressAttribute* relayed_attr =
882 response->GetAddress(STUN_ATTR_XOR_RELAYED_ADDRESS);
883 if (!relayed_attr) {
884 LOG_J(LS_WARNING, port_) << "Missing STUN_ATTR_XOR_RELAYED_ADDRESS "
885 << "attribute in allocate success response";
886 return;
887 }
888
889 const StunUInt32Attribute* lifetime_attr =
890 response->GetUInt32(STUN_ATTR_TURN_LIFETIME);
891 if (!lifetime_attr) {
892 LOG_J(LS_WARNING, port_) << "Missing STUN_ATTR_TURN_LIFETIME attribute in "
893 << "allocate success response";
894 return;
895 }
896 // Notify the port the allocate succeeded, and schedule a refresh request.
897 port_->OnAllocateSuccess(relayed_attr->GetAddress(),
898 mapped_attr->GetAddress());
899 port_->ScheduleRefresh(lifetime_attr->value());
900}
901
902void TurnAllocateRequest::OnErrorResponse(StunMessage* response) {
903 // Process error response according to RFC5766, Section 6.4.
904 const StunErrorCodeAttribute* error_code = response->GetErrorCode();
905 switch (error_code->code()) {
906 case STUN_ERROR_UNAUTHORIZED: // Unauthrorized.
907 OnAuthChallenge(response, error_code->code());
908 break;
909 case STUN_ERROR_TRY_ALTERNATE:
910 OnTryAlternate(response, error_code->code());
911 break;
912 case STUN_ERROR_ALLOCATION_MISMATCH:
913 // We must handle this error async because trying to delete the socket in
914 // OnErrorResponse will cause a deadlock on the socket.
915 port_->thread()->Post(port_, TurnPort::MSG_ALLOCATE_MISMATCH);
916 break;
917 default:
918 LOG_J(LS_WARNING, port_) << "Allocate response error, code="
919 << error_code->code();
920 port_->OnAllocateError();
921 }
922}
923
924void TurnAllocateRequest::OnTimeout() {
925 LOG_J(LS_WARNING, port_) << "Allocate request timeout";
926 port_->OnAllocateRequestTimeout();
927}
928
929void TurnAllocateRequest::OnAuthChallenge(StunMessage* response, int code) {
930 // If we failed to authenticate even after we sent our credentials, fail hard.
931 if (code == STUN_ERROR_UNAUTHORIZED && !port_->hash().empty()) {
932 LOG_J(LS_WARNING, port_) << "Failed to authenticate with the server "
933 << "after challenge.";
934 port_->OnAllocateError();
935 return;
936 }
937
938 // Check the mandatory attributes.
939 const StunByteStringAttribute* realm_attr =
940 response->GetByteString(STUN_ATTR_REALM);
941 if (!realm_attr) {
942 LOG_J(LS_WARNING, port_) << "Missing STUN_ATTR_REALM attribute in "
943 << "allocate unauthorized response.";
944 return;
945 }
946 port_->set_realm(realm_attr->GetString());
947
948 const StunByteStringAttribute* nonce_attr =
949 response->GetByteString(STUN_ATTR_NONCE);
950 if (!nonce_attr) {
951 LOG_J(LS_WARNING, port_) << "Missing STUN_ATTR_NONCE attribute in "
952 << "allocate unauthorized response.";
953 return;
954 }
955 port_->set_nonce(nonce_attr->GetString());
956
957 // Send another allocate request, with the received realm and nonce values.
958 port_->SendRequest(new TurnAllocateRequest(port_), 0);
959}
960
961void TurnAllocateRequest::OnTryAlternate(StunMessage* response, int code) {
962 // TODO(guoweis): Currently, we only support UDP redirect
963 if (port_->server_address().proto != PROTO_UDP) {
964 LOG_J(LS_WARNING, port_) << "Receiving 300 Alternate Server on non-UDP "
965 << "allocating request from ["
966 << port_->server_address().address.ToSensitiveString()
967 << "], failed as currently not supported";
968 port_->OnAllocateError();
969 return;
970 }
971
972 // According to RFC 5389 section 11, there are use cases where
973 // authentication of response is not possible, we're not validating
974 // message integrity.
975
976 // Get the alternate server address attribute value.
977 const StunAddressAttribute* alternate_server_attr =
978 response->GetAddress(STUN_ATTR_ALTERNATE_SERVER);
979 if (!alternate_server_attr) {
980 LOG_J(LS_WARNING, port_) << "Missing STUN_ATTR_ALTERNATE_SERVER "
981 << "attribute in try alternate error response";
982 port_->OnAllocateError();
983 return;
984 }
985 if (!port_->SetAlternateServer(alternate_server_attr->GetAddress())) {
986 port_->OnAllocateError();
987 return;
988 }
989
990 // Check the attributes.
991 const StunByteStringAttribute* realm_attr =
992 response->GetByteString(STUN_ATTR_REALM);
993 if (realm_attr) {
994 LOG_J(LS_INFO, port_) << "Applying STUN_ATTR_REALM attribute in "
995 << "try alternate error response.";
996 port_->set_realm(realm_attr->GetString());
997 }
998
999 const StunByteStringAttribute* nonce_attr =
1000 response->GetByteString(STUN_ATTR_NONCE);
1001 if (nonce_attr) {
1002 LOG_J(LS_INFO, port_) << "Applying STUN_ATTR_NONCE attribute in "
1003 << "try alternate error response.";
1004 port_->set_nonce(nonce_attr->GetString());
1005 }
1006
1007 // Send another allocate request to alternate server,
1008 // with the received realm and nonce values.
1009 port_->SendRequest(new TurnAllocateRequest(port_), 0);
1010}
1011
1012TurnRefreshRequest::TurnRefreshRequest(TurnPort* port)
1013 : StunRequest(new TurnMessage()),
1014 port_(port) {
1015}
1016
1017void TurnRefreshRequest::Prepare(StunMessage* request) {
1018 // Create the request as indicated in RFC 5766, Section 7.1.
1019 // No attributes need to be included.
1020 request->SetType(TURN_REFRESH_REQUEST);
1021 port_->AddRequestAuthInfo(request);
1022}
1023
1024void TurnRefreshRequest::OnResponse(StunMessage* response) {
1025 // Check mandatory attributes as indicated in RFC5766, Section 7.3.
1026 const StunUInt32Attribute* lifetime_attr =
1027 response->GetUInt32(STUN_ATTR_TURN_LIFETIME);
1028 if (!lifetime_attr) {
1029 LOG_J(LS_WARNING, port_) << "Missing STUN_ATTR_TURN_LIFETIME attribute in "
1030 << "refresh success response.";
1031 return;
1032 }
1033
1034 // Schedule a refresh based on the returned lifetime value.
1035 port_->ScheduleRefresh(lifetime_attr->value());
1036}
1037
1038void TurnRefreshRequest::OnErrorResponse(StunMessage* response) {
1039 const StunErrorCodeAttribute* error_code = response->GetErrorCode();
1040 LOG_J(LS_WARNING, port_) << "Refresh response error, code="
1041 << error_code->code();
1042
1043 if (error_code->code() == STUN_ERROR_STALE_NONCE) {
1044 if (port_->UpdateNonce(response)) {
1045 // Send RefreshRequest immediately.
1046 port_->SendRequest(new TurnRefreshRequest(port_), 0);
1047 }
1048 }
1049}
1050
1051void TurnRefreshRequest::OnTimeout() {
1052}
1053
1054TurnCreatePermissionRequest::TurnCreatePermissionRequest(
1055 TurnPort* port, TurnEntry* entry,
1056 const rtc::SocketAddress& ext_addr)
1057 : StunRequest(new TurnMessage()),
1058 port_(port),
1059 entry_(entry),
1060 ext_addr_(ext_addr) {
1061 entry_->SignalDestroyed.connect(
1062 this, &TurnCreatePermissionRequest::OnEntryDestroyed);
1063}
1064
1065void TurnCreatePermissionRequest::Prepare(StunMessage* request) {
1066 // Create the request as indicated in RFC5766, Section 9.1.
1067 request->SetType(TURN_CREATE_PERMISSION_REQUEST);
1068 VERIFY(request->AddAttribute(new StunXorAddressAttribute(
1069 STUN_ATTR_XOR_PEER_ADDRESS, ext_addr_)));
1070 port_->AddRequestAuthInfo(request);
1071}
1072
1073void TurnCreatePermissionRequest::OnResponse(StunMessage* response) {
1074 if (entry_) {
1075 entry_->OnCreatePermissionSuccess();
1076 }
1077}
1078
1079void TurnCreatePermissionRequest::OnErrorResponse(StunMessage* response) {
1080 if (entry_) {
1081 const StunErrorCodeAttribute* error_code = response->GetErrorCode();
1082 entry_->OnCreatePermissionError(response, error_code->code());
1083 }
1084}
1085
1086void TurnCreatePermissionRequest::OnTimeout() {
1087 LOG_J(LS_WARNING, port_) << "Create permission timeout";
1088}
1089
1090void TurnCreatePermissionRequest::OnEntryDestroyed(TurnEntry* entry) {
1091 ASSERT(entry_ == entry);
1092 entry_ = NULL;
1093}
1094
1095TurnChannelBindRequest::TurnChannelBindRequest(
1096 TurnPort* port, TurnEntry* entry,
1097 int channel_id, const rtc::SocketAddress& ext_addr)
1098 : StunRequest(new TurnMessage()),
1099 port_(port),
1100 entry_(entry),
1101 channel_id_(channel_id),
1102 ext_addr_(ext_addr) {
1103 entry_->SignalDestroyed.connect(
1104 this, &TurnChannelBindRequest::OnEntryDestroyed);
1105}
1106
1107void TurnChannelBindRequest::Prepare(StunMessage* request) {
1108 // Create the request as indicated in RFC5766, Section 11.1.
1109 request->SetType(TURN_CHANNEL_BIND_REQUEST);
1110 VERIFY(request->AddAttribute(new StunUInt32Attribute(
1111 STUN_ATTR_CHANNEL_NUMBER, channel_id_ << 16)));
1112 VERIFY(request->AddAttribute(new StunXorAddressAttribute(
1113 STUN_ATTR_XOR_PEER_ADDRESS, ext_addr_)));
1114 port_->AddRequestAuthInfo(request);
1115}
1116
1117void TurnChannelBindRequest::OnResponse(StunMessage* response) {
1118 if (entry_) {
1119 entry_->OnChannelBindSuccess();
1120 // Refresh the channel binding just under the permission timeout
1121 // threshold. The channel binding has a longer lifetime, but
1122 // this is the easiest way to keep both the channel and the
1123 // permission from expiring.
1124 entry_->SendChannelBindRequest(TURN_PERMISSION_TIMEOUT - 60 * 1000);
1125 }
1126}
1127
1128void TurnChannelBindRequest::OnErrorResponse(StunMessage* response) {
1129 if (entry_) {
1130 const StunErrorCodeAttribute* error_code = response->GetErrorCode();
1131 entry_->OnChannelBindError(response, error_code->code());
1132 }
1133}
1134
1135void TurnChannelBindRequest::OnTimeout() {
1136 LOG_J(LS_WARNING, port_) << "Channel bind timeout";
1137}
1138
1139void TurnChannelBindRequest::OnEntryDestroyed(TurnEntry* entry) {
1140 ASSERT(entry_ == entry);
1141 entry_ = NULL;
1142}
1143
1144TurnEntry::TurnEntry(TurnPort* port, int channel_id,
1145 const rtc::SocketAddress& ext_addr)
1146 : port_(port),
1147 channel_id_(channel_id),
1148 ext_addr_(ext_addr),
1149 state_(STATE_UNBOUND) {
1150 // Creating permission for |ext_addr_|.
1151 SendCreatePermissionRequest();
1152}
1153
1154void TurnEntry::SendCreatePermissionRequest() {
1155 port_->SendRequest(new TurnCreatePermissionRequest(
1156 port_, this, ext_addr_), 0);
1157}
1158
1159void TurnEntry::SendChannelBindRequest(int delay) {
1160 port_->SendRequest(new TurnChannelBindRequest(
1161 port_, this, channel_id_, ext_addr_), delay);
1162}
1163
1164int TurnEntry::Send(const void* data, size_t size, bool payload,
1165 const rtc::PacketOptions& options) {
1166 rtc::ByteBuffer buf;
1167 if (state_ != STATE_BOUND) {
1168 // If we haven't bound the channel yet, we have to use a Send Indication.
1169 TurnMessage msg;
1170 msg.SetType(TURN_SEND_INDICATION);
1171 msg.SetTransactionID(
1172 rtc::CreateRandomString(kStunTransactionIdLength));
1173 VERIFY(msg.AddAttribute(new StunXorAddressAttribute(
1174 STUN_ATTR_XOR_PEER_ADDRESS, ext_addr_)));
1175 VERIFY(msg.AddAttribute(new StunByteStringAttribute(
1176 STUN_ATTR_DATA, data, size)));
1177 VERIFY(msg.Write(&buf));
1178
1179 // If we're sending real data, request a channel bind that we can use later.
1180 if (state_ == STATE_UNBOUND && payload) {
1181 SendChannelBindRequest(0);
1182 state_ = STATE_BINDING;
1183 }
1184 } else {
1185 // If the channel is bound, we can send the data as a Channel Message.
1186 buf.WriteUInt16(channel_id_);
1187 buf.WriteUInt16(static_cast<uint16>(size));
1188 buf.WriteBytes(reinterpret_cast<const char*>(data), size);
1189 }
1190 return port_->Send(buf.Data(), buf.Length(), options);
1191}
1192
1193void TurnEntry::OnCreatePermissionSuccess() {
1194 LOG_J(LS_INFO, port_) << "Create permission for "
1195 << ext_addr_.ToSensitiveString()
1196 << " succeeded";
1197 // For success result code will be 0.
1198 port_->SignalCreatePermissionResult(port_, ext_addr_, 0);
1199}
1200
1201void TurnEntry::OnCreatePermissionError(StunMessage* response, int code) {
1202 LOG_J(LS_WARNING, port_) << "Create permission for "
1203 << ext_addr_.ToSensitiveString()
1204 << " failed, code=" << code;
1205 if (code == STUN_ERROR_STALE_NONCE) {
1206 if (port_->UpdateNonce(response)) {
1207 SendCreatePermissionRequest();
1208 }
1209 } else {
1210 // Send signal with error code.
1211 port_->SignalCreatePermissionResult(port_, ext_addr_, code);
1212 }
1213}
1214
1215void TurnEntry::OnChannelBindSuccess() {
1216 LOG_J(LS_INFO, port_) << "Channel bind for " << ext_addr_.ToSensitiveString()
1217 << " succeeded";
1218 ASSERT(state_ == STATE_BINDING || state_ == STATE_BOUND);
1219 state_ = STATE_BOUND;
1220}
1221
1222void TurnEntry::OnChannelBindError(StunMessage* response, int code) {
1223 // TODO(mallinath) - Implement handling of error response for channel
1224 // bind request as per http://tools.ietf.org/html/rfc5766#section-11.3
1225 LOG_J(LS_WARNING, port_) << "Channel bind for "
1226 << ext_addr_.ToSensitiveString()
1227 << " failed, code=" << code;
1228 if (code == STUN_ERROR_STALE_NONCE) {
1229 if (port_->UpdateNonce(response)) {
1230 // Send channel bind request with fresh nonce.
1231 SendChannelBindRequest(0);
1232 }
1233 }
1234}
1235
1236} // namespace cricket