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