blob: e564db346d30dd49b25549fb4e00a35acc3fc38f [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_);
guoweis@webrtc.orgc51fb932014-12-18 00:30:55 +0000445
446 // This is to guard against a STUN response from previous server after
447 // alternative server redirection. TODO(guoweis): add a unit test for this
448 // race condition.
449 if (remote_addr != server_address_.address) {
450 LOG_J(LS_WARNING, this) << "Discarding TURN message from unknown address:"
451 << remote_addr.ToString()
452 << ", server_address_:"
453 << server_address_.address.ToString();
454 return;
455 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000456
457 // The message must be at least the size of a channel header.
458 if (size < TURN_CHANNEL_HEADER_SIZE) {
459 LOG_J(LS_WARNING, this) << "Received TURN message that was too short";
460 return;
461 }
462
463 // Check the message type, to see if is a Channel Data message.
464 // The message will either be channel data, a TURN data indication, or
465 // a response to a previous request.
466 uint16 msg_type = rtc::GetBE16(data);
467 if (IsTurnChannelData(msg_type)) {
468 HandleChannelData(msg_type, data, size, packet_time);
469 } else if (msg_type == TURN_DATA_INDICATION) {
470 HandleDataIndication(data, size, packet_time);
471 } else {
jiayl@webrtc.org511f8a82014-12-03 02:17:07 +0000472 if (SharedSocket() &&
473 (msg_type == STUN_BINDING_RESPONSE ||
474 msg_type == STUN_BINDING_ERROR_RESPONSE)) {
475 LOG_J(LS_VERBOSE, this) <<
476 "Ignoring STUN binding response message on shared socket.";
477 return;
478 }
479
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000480 // This must be a response for one of our requests.
481 // Check success responses, but not errors, for MESSAGE-INTEGRITY.
482 if (IsStunSuccessResponseType(msg_type) &&
483 !StunMessage::ValidateMessageIntegrity(data, size, hash())) {
484 LOG_J(LS_WARNING, this) << "Received TURN message with invalid "
485 << "message integrity, msg_type=" << msg_type;
486 return;
487 }
488 request_manager_.CheckResponse(data, size);
489 }
490}
491
492void TurnPort::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
493 if (connected_) {
494 Port::OnReadyToSend();
495 }
496}
497
498
499// Update current server address port with the alternate server address port.
500bool TurnPort::SetAlternateServer(const rtc::SocketAddress& address) {
501 // Check if we have seen this address before and reject if we did.
502 AttemptedServerSet::iterator iter = attempted_server_addresses_.find(address);
503 if (iter != attempted_server_addresses_.end()) {
504 LOG_J(LS_WARNING, this) << "Redirection to ["
505 << address.ToSensitiveString()
506 << "] ignored, allocation failed.";
507 return false;
508 }
509
510 // If protocol family of server address doesn't match with local, return.
511 if (!IsCompatibleAddress(address)) {
512 LOG(LS_WARNING) << "Server IP address family does not match with "
513 << "local host address family type";
514 return false;
515 }
516
517 LOG_J(LS_INFO, this) << "Redirecting from TURN server ["
518 << server_address_.address.ToSensitiveString()
519 << "] to TURN server ["
520 << address.ToSensitiveString()
521 << "]";
522 server_address_ = ProtocolAddress(address, server_address_.proto,
523 server_address_.secure);
524
525 // Insert the current address to prevent redirection pingpong.
526 attempted_server_addresses_.insert(server_address_.address);
527 return true;
528}
529
530void TurnPort::ResolveTurnAddress(const rtc::SocketAddress& address) {
531 if (resolver_)
532 return;
533
534 resolver_ = socket_factory()->CreateAsyncResolver();
535 resolver_->SignalDone.connect(this, &TurnPort::OnResolveResult);
536 resolver_->Start(address);
537}
538
539void TurnPort::OnResolveResult(rtc::AsyncResolverInterface* resolver) {
540 ASSERT(resolver == resolver_);
541 // If DNS resolve is failed when trying to connect to the server using TCP,
542 // one of the reason could be due to DNS queries blocked by firewall.
543 // In such cases we will try to connect to the server with hostname, assuming
544 // socket layer will resolve the hostname through a HTTP proxy (if any).
545 if (resolver_->GetError() != 0 && server_address_.proto == PROTO_TCP) {
546 if (!CreateTurnClientSocket()) {
547 OnAllocateError();
548 }
549 return;
550 }
551
552 // Copy the original server address in |resolved_address|. For TLS based
553 // sockets we need hostname along with resolved address.
554 rtc::SocketAddress resolved_address = server_address_.address;
555 if (resolver_->GetError() != 0 ||
556 !resolver_->GetResolvedAddress(ip().family(), &resolved_address)) {
557 LOG_J(LS_WARNING, this) << "TURN host lookup received error "
558 << resolver_->GetError();
559 error_ = resolver_->GetError();
560 OnAllocateError();
561 return;
562 }
563 // Signal needs both resolved and unresolved address. After signal is sent
564 // we can copy resolved address back into |server_address_|.
565 SignalResolvedServerAddress(this, server_address_.address,
566 resolved_address);
567 server_address_.address = resolved_address;
568 PrepareAddress();
569}
570
571void TurnPort::OnSendStunPacket(const void* data, size_t size,
572 StunRequest* request) {
573 rtc::PacketOptions options(DefaultDscpValue());
574 if (Send(data, size, options) < 0) {
575 LOG_J(LS_ERROR, this) << "Failed to send TURN message, err="
576 << socket_->GetError();
577 }
578}
579
580void TurnPort::OnStunAddress(const rtc::SocketAddress& address) {
581 // STUN Port will discover STUN candidate, as it's supplied with first TURN
582 // server address.
583 // Why not using this address? - P2PTransportChannel will start creating
584 // connections after first candidate, which means it could start creating the
585 // connections before TURN candidate added. For that to handle, we need to
586 // supply STUN candidate from this port to UDPPort, and TurnPort should have
587 // handle to UDPPort to pass back the address.
588}
589
590void TurnPort::OnAllocateSuccess(const rtc::SocketAddress& address,
591 const rtc::SocketAddress& stun_address) {
592 connected_ = true;
593
594 rtc::SocketAddress related_address = stun_address;
595 if (!(candidate_filter() & CF_REFLEXIVE)) {
596 // If candidate filter only allows relay type of address, empty raddr to
597 // avoid local address leakage.
598 related_address = rtc::EmptySocketAddressWithFamily(stun_address.family());
599 }
600
601 // For relayed candidate, Base is the candidate itself.
602 AddAddress(address, // Candidate address.
603 address, // Base address.
604 related_address, // Related address.
605 UDP_PROTOCOL_NAME,
606 "", // TCP canddiate type, empty for turn candidates.
607 RELAY_PORT_TYPE,
608 GetRelayPreference(server_address_.proto, server_address_.secure),
609 server_priority_,
610 true);
611}
612
613void TurnPort::OnAllocateError() {
614 // We will send SignalPortError asynchronously as this can be sent during
615 // port initialization. This way it will not be blocking other port
616 // creation.
617 thread()->Post(this, MSG_ERROR);
618}
619
620void TurnPort::OnMessage(rtc::Message* message) {
621 if (message->message_id == MSG_ERROR) {
622 SignalPortError(this);
623 return;
624 } else if (message->message_id == MSG_ALLOCATE_MISMATCH) {
625 OnAllocateMismatch();
626 return;
627 }
628
629 Port::OnMessage(message);
630}
631
632void TurnPort::OnAllocateRequestTimeout() {
633 OnAllocateError();
634}
635
636void TurnPort::HandleDataIndication(const char* data, size_t size,
637 const rtc::PacketTime& packet_time) {
638 // Read in the message, and process according to RFC5766, Section 10.4.
639 rtc::ByteBuffer buf(data, size);
640 TurnMessage msg;
641 if (!msg.Read(&buf)) {
642 LOG_J(LS_WARNING, this) << "Received invalid TURN data indication";
643 return;
644 }
645
646 // Check mandatory attributes.
647 const StunAddressAttribute* addr_attr =
648 msg.GetAddress(STUN_ATTR_XOR_PEER_ADDRESS);
649 if (!addr_attr) {
650 LOG_J(LS_WARNING, this) << "Missing STUN_ATTR_XOR_PEER_ADDRESS attribute "
651 << "in data indication.";
652 return;
653 }
654
655 const StunByteStringAttribute* data_attr =
656 msg.GetByteString(STUN_ATTR_DATA);
657 if (!data_attr) {
658 LOG_J(LS_WARNING, this) << "Missing STUN_ATTR_DATA attribute in "
659 << "data indication.";
660 return;
661 }
662
663 // Verify that the data came from somewhere we think we have a permission for.
664 rtc::SocketAddress ext_addr(addr_attr->GetAddress());
665 if (!HasPermission(ext_addr.ipaddr())) {
666 LOG_J(LS_WARNING, this) << "Received TURN data indication with invalid "
667 << "peer address, addr="
668 << ext_addr.ToSensitiveString();
669 return;
670 }
671
672 DispatchPacket(data_attr->bytes(), data_attr->length(), ext_addr,
673 PROTO_UDP, packet_time);
674}
675
676void TurnPort::HandleChannelData(int channel_id, const char* data,
677 size_t size,
678 const rtc::PacketTime& packet_time) {
679 // Read the message, and process according to RFC5766, Section 11.6.
680 // 0 1 2 3
681 // 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
682 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
683 // | Channel Number | Length |
684 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
685 // | |
686 // / Application Data /
687 // / /
688 // | |
689 // | +-------------------------------+
690 // | |
691 // +-------------------------------+
692
693 // Extract header fields from the message.
694 uint16 len = rtc::GetBE16(data + 2);
695 if (len > size - TURN_CHANNEL_HEADER_SIZE) {
696 LOG_J(LS_WARNING, this) << "Received TURN channel data message with "
697 << "incorrect length, len=" << len;
698 return;
699 }
700 // Allowing messages larger than |len|, as ChannelData can be padded.
701
702 TurnEntry* entry = FindEntry(channel_id);
703 if (!entry) {
704 LOG_J(LS_WARNING, this) << "Received TURN channel data message for invalid "
705 << "channel, channel_id=" << channel_id;
706 return;
707 }
708
709 DispatchPacket(data + TURN_CHANNEL_HEADER_SIZE, len, entry->address(),
710 PROTO_UDP, packet_time);
711}
712
713void TurnPort::DispatchPacket(const char* data, size_t size,
714 const rtc::SocketAddress& remote_addr,
715 ProtocolType proto, const rtc::PacketTime& packet_time) {
716 if (Connection* conn = GetConnection(remote_addr)) {
717 conn->OnReadPacket(data, size, packet_time);
718 } else {
719 Port::OnReadPacket(data, size, remote_addr, proto);
720 }
721}
722
723bool TurnPort::ScheduleRefresh(int lifetime) {
724 // Lifetime is in seconds; we schedule a refresh for one minute less.
725 if (lifetime < 2 * 60) {
726 LOG_J(LS_WARNING, this) << "Received response with lifetime that was "
727 << "too short, lifetime=" << lifetime;
728 return false;
729 }
730
731 SendRequest(new TurnRefreshRequest(this), (lifetime - 60) * 1000);
732 return true;
733}
734
735void TurnPort::SendRequest(StunRequest* req, int delay) {
736 request_manager_.SendDelayed(req, delay);
737}
738
739void TurnPort::AddRequestAuthInfo(StunMessage* msg) {
740 // If we've gotten the necessary data from the server, add it to our request.
741 VERIFY(!hash_.empty());
742 VERIFY(msg->AddAttribute(new StunByteStringAttribute(
743 STUN_ATTR_USERNAME, credentials_.username)));
744 VERIFY(msg->AddAttribute(new StunByteStringAttribute(
745 STUN_ATTR_REALM, realm_)));
746 VERIFY(msg->AddAttribute(new StunByteStringAttribute(
747 STUN_ATTR_NONCE, nonce_)));
748 VERIFY(msg->AddMessageIntegrity(hash()));
749}
750
751int TurnPort::Send(const void* data, size_t len,
752 const rtc::PacketOptions& options) {
753 return socket_->SendTo(data, len, server_address_.address, options);
754}
755
756void TurnPort::UpdateHash() {
757 VERIFY(ComputeStunCredentialHash(credentials_.username, realm_,
758 credentials_.password, &hash_));
759}
760
761bool TurnPort::UpdateNonce(StunMessage* response) {
762 // When stale nonce error received, we should update
763 // hash and store realm and nonce.
764 // Check the mandatory attributes.
765 const StunByteStringAttribute* realm_attr =
766 response->GetByteString(STUN_ATTR_REALM);
767 if (!realm_attr) {
768 LOG(LS_ERROR) << "Missing STUN_ATTR_REALM attribute in "
769 << "stale nonce error response.";
770 return false;
771 }
772 set_realm(realm_attr->GetString());
773
774 const StunByteStringAttribute* nonce_attr =
775 response->GetByteString(STUN_ATTR_NONCE);
776 if (!nonce_attr) {
777 LOG(LS_ERROR) << "Missing STUN_ATTR_NONCE attribute in "
778 << "stale nonce error response.";
779 return false;
780 }
781 set_nonce(nonce_attr->GetString());
782 return true;
783}
784
785static bool MatchesIP(TurnEntry* e, rtc::IPAddress ipaddr) {
786 return e->address().ipaddr() == ipaddr;
787}
788bool TurnPort::HasPermission(const rtc::IPAddress& ipaddr) const {
789 return (std::find_if(entries_.begin(), entries_.end(),
790 std::bind2nd(std::ptr_fun(MatchesIP), ipaddr)) != entries_.end());
791}
792
793static bool MatchesAddress(TurnEntry* e, rtc::SocketAddress addr) {
794 return e->address() == addr;
795}
796TurnEntry* TurnPort::FindEntry(const rtc::SocketAddress& addr) const {
797 EntryList::const_iterator it = std::find_if(entries_.begin(), entries_.end(),
798 std::bind2nd(std::ptr_fun(MatchesAddress), addr));
799 return (it != entries_.end()) ? *it : NULL;
800}
801
802static bool MatchesChannelId(TurnEntry* e, int id) {
803 return e->channel_id() == id;
804}
805TurnEntry* TurnPort::FindEntry(int channel_id) const {
806 EntryList::const_iterator it = std::find_if(entries_.begin(), entries_.end(),
807 std::bind2nd(std::ptr_fun(MatchesChannelId), channel_id));
808 return (it != entries_.end()) ? *it : NULL;
809}
810
811TurnEntry* TurnPort::CreateEntry(const rtc::SocketAddress& addr) {
812 ASSERT(FindEntry(addr) == NULL);
813 TurnEntry* entry = new TurnEntry(this, next_channel_number_++, addr);
814 entries_.push_back(entry);
815 return entry;
816}
817
818void TurnPort::DestroyEntry(const rtc::SocketAddress& addr) {
819 TurnEntry* entry = FindEntry(addr);
820 ASSERT(entry != NULL);
821 entry->SignalDestroyed(entry);
822 entries_.remove(entry);
823 delete entry;
824}
825
826void TurnPort::OnConnectionDestroyed(Connection* conn) {
827 // Destroying TurnEntry for the connection, which is already destroyed.
828 DestroyEntry(conn->remote_candidate().address());
829}
830
831TurnAllocateRequest::TurnAllocateRequest(TurnPort* port)
832 : StunRequest(new TurnMessage()),
833 port_(port) {
834}
835
836void TurnAllocateRequest::Prepare(StunMessage* request) {
837 // Create the request as indicated in RFC 5766, Section 6.1.
838 request->SetType(TURN_ALLOCATE_REQUEST);
839 StunUInt32Attribute* transport_attr = StunAttribute::CreateUInt32(
840 STUN_ATTR_REQUESTED_TRANSPORT);
841 transport_attr->SetValue(IPPROTO_UDP << 24);
842 VERIFY(request->AddAttribute(transport_attr));
843 if (!port_->hash().empty()) {
844 port_->AddRequestAuthInfo(request);
845 }
846}
847
848void TurnAllocateRequest::OnResponse(StunMessage* response) {
849 // Check mandatory attributes as indicated in RFC5766, Section 6.3.
850 const StunAddressAttribute* mapped_attr =
851 response->GetAddress(STUN_ATTR_XOR_MAPPED_ADDRESS);
852 if (!mapped_attr) {
853 LOG_J(LS_WARNING, port_) << "Missing STUN_ATTR_XOR_MAPPED_ADDRESS "
854 << "attribute in allocate success response";
855 return;
856 }
857 // Using XOR-Mapped-Address for stun.
858 port_->OnStunAddress(mapped_attr->GetAddress());
859
860 const StunAddressAttribute* relayed_attr =
861 response->GetAddress(STUN_ATTR_XOR_RELAYED_ADDRESS);
862 if (!relayed_attr) {
863 LOG_J(LS_WARNING, port_) << "Missing STUN_ATTR_XOR_RELAYED_ADDRESS "
864 << "attribute in allocate success response";
865 return;
866 }
867
868 const StunUInt32Attribute* lifetime_attr =
869 response->GetUInt32(STUN_ATTR_TURN_LIFETIME);
870 if (!lifetime_attr) {
871 LOG_J(LS_WARNING, port_) << "Missing STUN_ATTR_TURN_LIFETIME attribute in "
872 << "allocate success response";
873 return;
874 }
875 // Notify the port the allocate succeeded, and schedule a refresh request.
876 port_->OnAllocateSuccess(relayed_attr->GetAddress(),
877 mapped_attr->GetAddress());
878 port_->ScheduleRefresh(lifetime_attr->value());
879}
880
881void TurnAllocateRequest::OnErrorResponse(StunMessage* response) {
882 // Process error response according to RFC5766, Section 6.4.
883 const StunErrorCodeAttribute* error_code = response->GetErrorCode();
884 switch (error_code->code()) {
885 case STUN_ERROR_UNAUTHORIZED: // Unauthrorized.
886 OnAuthChallenge(response, error_code->code());
887 break;
888 case STUN_ERROR_TRY_ALTERNATE:
889 OnTryAlternate(response, error_code->code());
890 break;
891 case STUN_ERROR_ALLOCATION_MISMATCH:
892 // We must handle this error async because trying to delete the socket in
893 // OnErrorResponse will cause a deadlock on the socket.
894 port_->thread()->Post(port_, TurnPort::MSG_ALLOCATE_MISMATCH);
895 break;
896 default:
897 LOG_J(LS_WARNING, port_) << "Allocate response error, code="
898 << error_code->code();
899 port_->OnAllocateError();
900 }
901}
902
903void TurnAllocateRequest::OnTimeout() {
904 LOG_J(LS_WARNING, port_) << "Allocate request timeout";
905 port_->OnAllocateRequestTimeout();
906}
907
908void TurnAllocateRequest::OnAuthChallenge(StunMessage* response, int code) {
909 // If we failed to authenticate even after we sent our credentials, fail hard.
910 if (code == STUN_ERROR_UNAUTHORIZED && !port_->hash().empty()) {
911 LOG_J(LS_WARNING, port_) << "Failed to authenticate with the server "
912 << "after challenge.";
913 port_->OnAllocateError();
914 return;
915 }
916
917 // Check the mandatory attributes.
918 const StunByteStringAttribute* realm_attr =
919 response->GetByteString(STUN_ATTR_REALM);
920 if (!realm_attr) {
921 LOG_J(LS_WARNING, port_) << "Missing STUN_ATTR_REALM attribute in "
922 << "allocate unauthorized response.";
923 return;
924 }
925 port_->set_realm(realm_attr->GetString());
926
927 const StunByteStringAttribute* nonce_attr =
928 response->GetByteString(STUN_ATTR_NONCE);
929 if (!nonce_attr) {
930 LOG_J(LS_WARNING, port_) << "Missing STUN_ATTR_NONCE attribute in "
931 << "allocate unauthorized response.";
932 return;
933 }
934 port_->set_nonce(nonce_attr->GetString());
935
936 // Send another allocate request, with the received realm and nonce values.
937 port_->SendRequest(new TurnAllocateRequest(port_), 0);
938}
939
940void TurnAllocateRequest::OnTryAlternate(StunMessage* response, int code) {
941 // TODO(guoweis): Currently, we only support UDP redirect
942 if (port_->server_address().proto != PROTO_UDP) {
943 LOG_J(LS_WARNING, port_) << "Receiving 300 Alternate Server on non-UDP "
944 << "allocating request from ["
945 << port_->server_address().address.ToSensitiveString()
946 << "], failed as currently not supported";
947 port_->OnAllocateError();
948 return;
949 }
950
951 // According to RFC 5389 section 11, there are use cases where
952 // authentication of response is not possible, we're not validating
953 // message integrity.
954
955 // Get the alternate server address attribute value.
956 const StunAddressAttribute* alternate_server_attr =
957 response->GetAddress(STUN_ATTR_ALTERNATE_SERVER);
958 if (!alternate_server_attr) {
959 LOG_J(LS_WARNING, port_) << "Missing STUN_ATTR_ALTERNATE_SERVER "
960 << "attribute in try alternate error response";
961 port_->OnAllocateError();
962 return;
963 }
964 if (!port_->SetAlternateServer(alternate_server_attr->GetAddress())) {
965 port_->OnAllocateError();
966 return;
967 }
968
969 // Check the attributes.
970 const StunByteStringAttribute* realm_attr =
971 response->GetByteString(STUN_ATTR_REALM);
972 if (realm_attr) {
973 LOG_J(LS_INFO, port_) << "Applying STUN_ATTR_REALM attribute in "
974 << "try alternate error response.";
975 port_->set_realm(realm_attr->GetString());
976 }
977
978 const StunByteStringAttribute* nonce_attr =
979 response->GetByteString(STUN_ATTR_NONCE);
980 if (nonce_attr) {
981 LOG_J(LS_INFO, port_) << "Applying STUN_ATTR_NONCE attribute in "
982 << "try alternate error response.";
983 port_->set_nonce(nonce_attr->GetString());
984 }
985
986 // Send another allocate request to alternate server,
987 // with the received realm and nonce values.
988 port_->SendRequest(new TurnAllocateRequest(port_), 0);
989}
990
991TurnRefreshRequest::TurnRefreshRequest(TurnPort* port)
992 : StunRequest(new TurnMessage()),
993 port_(port) {
994}
995
996void TurnRefreshRequest::Prepare(StunMessage* request) {
997 // Create the request as indicated in RFC 5766, Section 7.1.
998 // No attributes need to be included.
999 request->SetType(TURN_REFRESH_REQUEST);
1000 port_->AddRequestAuthInfo(request);
1001}
1002
1003void TurnRefreshRequest::OnResponse(StunMessage* response) {
1004 // Check mandatory attributes as indicated in RFC5766, Section 7.3.
1005 const StunUInt32Attribute* lifetime_attr =
1006 response->GetUInt32(STUN_ATTR_TURN_LIFETIME);
1007 if (!lifetime_attr) {
1008 LOG_J(LS_WARNING, port_) << "Missing STUN_ATTR_TURN_LIFETIME attribute in "
1009 << "refresh success response.";
1010 return;
1011 }
1012
1013 // Schedule a refresh based on the returned lifetime value.
1014 port_->ScheduleRefresh(lifetime_attr->value());
1015}
1016
1017void TurnRefreshRequest::OnErrorResponse(StunMessage* response) {
1018 const StunErrorCodeAttribute* error_code = response->GetErrorCode();
1019 LOG_J(LS_WARNING, port_) << "Refresh response error, code="
1020 << error_code->code();
1021
1022 if (error_code->code() == STUN_ERROR_STALE_NONCE) {
1023 if (port_->UpdateNonce(response)) {
1024 // Send RefreshRequest immediately.
1025 port_->SendRequest(new TurnRefreshRequest(port_), 0);
1026 }
1027 }
1028}
1029
1030void TurnRefreshRequest::OnTimeout() {
1031}
1032
1033TurnCreatePermissionRequest::TurnCreatePermissionRequest(
1034 TurnPort* port, TurnEntry* entry,
1035 const rtc::SocketAddress& ext_addr)
1036 : StunRequest(new TurnMessage()),
1037 port_(port),
1038 entry_(entry),
1039 ext_addr_(ext_addr) {
1040 entry_->SignalDestroyed.connect(
1041 this, &TurnCreatePermissionRequest::OnEntryDestroyed);
1042}
1043
1044void TurnCreatePermissionRequest::Prepare(StunMessage* request) {
1045 // Create the request as indicated in RFC5766, Section 9.1.
1046 request->SetType(TURN_CREATE_PERMISSION_REQUEST);
1047 VERIFY(request->AddAttribute(new StunXorAddressAttribute(
1048 STUN_ATTR_XOR_PEER_ADDRESS, ext_addr_)));
1049 port_->AddRequestAuthInfo(request);
1050}
1051
1052void TurnCreatePermissionRequest::OnResponse(StunMessage* response) {
1053 if (entry_) {
1054 entry_->OnCreatePermissionSuccess();
1055 }
1056}
1057
1058void TurnCreatePermissionRequest::OnErrorResponse(StunMessage* response) {
1059 if (entry_) {
1060 const StunErrorCodeAttribute* error_code = response->GetErrorCode();
1061 entry_->OnCreatePermissionError(response, error_code->code());
1062 }
1063}
1064
1065void TurnCreatePermissionRequest::OnTimeout() {
1066 LOG_J(LS_WARNING, port_) << "Create permission timeout";
1067}
1068
1069void TurnCreatePermissionRequest::OnEntryDestroyed(TurnEntry* entry) {
1070 ASSERT(entry_ == entry);
1071 entry_ = NULL;
1072}
1073
1074TurnChannelBindRequest::TurnChannelBindRequest(
1075 TurnPort* port, TurnEntry* entry,
1076 int channel_id, const rtc::SocketAddress& ext_addr)
1077 : StunRequest(new TurnMessage()),
1078 port_(port),
1079 entry_(entry),
1080 channel_id_(channel_id),
1081 ext_addr_(ext_addr) {
1082 entry_->SignalDestroyed.connect(
1083 this, &TurnChannelBindRequest::OnEntryDestroyed);
1084}
1085
1086void TurnChannelBindRequest::Prepare(StunMessage* request) {
1087 // Create the request as indicated in RFC5766, Section 11.1.
1088 request->SetType(TURN_CHANNEL_BIND_REQUEST);
1089 VERIFY(request->AddAttribute(new StunUInt32Attribute(
1090 STUN_ATTR_CHANNEL_NUMBER, channel_id_ << 16)));
1091 VERIFY(request->AddAttribute(new StunXorAddressAttribute(
1092 STUN_ATTR_XOR_PEER_ADDRESS, ext_addr_)));
1093 port_->AddRequestAuthInfo(request);
1094}
1095
1096void TurnChannelBindRequest::OnResponse(StunMessage* response) {
1097 if (entry_) {
1098 entry_->OnChannelBindSuccess();
1099 // Refresh the channel binding just under the permission timeout
1100 // threshold. The channel binding has a longer lifetime, but
1101 // this is the easiest way to keep both the channel and the
1102 // permission from expiring.
1103 entry_->SendChannelBindRequest(TURN_PERMISSION_TIMEOUT - 60 * 1000);
1104 }
1105}
1106
1107void TurnChannelBindRequest::OnErrorResponse(StunMessage* response) {
1108 if (entry_) {
1109 const StunErrorCodeAttribute* error_code = response->GetErrorCode();
1110 entry_->OnChannelBindError(response, error_code->code());
1111 }
1112}
1113
1114void TurnChannelBindRequest::OnTimeout() {
1115 LOG_J(LS_WARNING, port_) << "Channel bind timeout";
1116}
1117
1118void TurnChannelBindRequest::OnEntryDestroyed(TurnEntry* entry) {
1119 ASSERT(entry_ == entry);
1120 entry_ = NULL;
1121}
1122
1123TurnEntry::TurnEntry(TurnPort* port, int channel_id,
1124 const rtc::SocketAddress& ext_addr)
1125 : port_(port),
1126 channel_id_(channel_id),
1127 ext_addr_(ext_addr),
1128 state_(STATE_UNBOUND) {
1129 // Creating permission for |ext_addr_|.
1130 SendCreatePermissionRequest();
1131}
1132
1133void TurnEntry::SendCreatePermissionRequest() {
1134 port_->SendRequest(new TurnCreatePermissionRequest(
1135 port_, this, ext_addr_), 0);
1136}
1137
1138void TurnEntry::SendChannelBindRequest(int delay) {
1139 port_->SendRequest(new TurnChannelBindRequest(
1140 port_, this, channel_id_, ext_addr_), delay);
1141}
1142
1143int TurnEntry::Send(const void* data, size_t size, bool payload,
1144 const rtc::PacketOptions& options) {
1145 rtc::ByteBuffer buf;
1146 if (state_ != STATE_BOUND) {
1147 // If we haven't bound the channel yet, we have to use a Send Indication.
1148 TurnMessage msg;
1149 msg.SetType(TURN_SEND_INDICATION);
1150 msg.SetTransactionID(
1151 rtc::CreateRandomString(kStunTransactionIdLength));
1152 VERIFY(msg.AddAttribute(new StunXorAddressAttribute(
1153 STUN_ATTR_XOR_PEER_ADDRESS, ext_addr_)));
1154 VERIFY(msg.AddAttribute(new StunByteStringAttribute(
1155 STUN_ATTR_DATA, data, size)));
1156 VERIFY(msg.Write(&buf));
1157
1158 // If we're sending real data, request a channel bind that we can use later.
1159 if (state_ == STATE_UNBOUND && payload) {
1160 SendChannelBindRequest(0);
1161 state_ = STATE_BINDING;
1162 }
1163 } else {
1164 // If the channel is bound, we can send the data as a Channel Message.
1165 buf.WriteUInt16(channel_id_);
1166 buf.WriteUInt16(static_cast<uint16>(size));
1167 buf.WriteBytes(reinterpret_cast<const char*>(data), size);
1168 }
1169 return port_->Send(buf.Data(), buf.Length(), options);
1170}
1171
1172void TurnEntry::OnCreatePermissionSuccess() {
1173 LOG_J(LS_INFO, port_) << "Create permission for "
1174 << ext_addr_.ToSensitiveString()
1175 << " succeeded";
1176 // For success result code will be 0.
1177 port_->SignalCreatePermissionResult(port_, ext_addr_, 0);
1178}
1179
1180void TurnEntry::OnCreatePermissionError(StunMessage* response, int code) {
1181 LOG_J(LS_WARNING, port_) << "Create permission for "
1182 << ext_addr_.ToSensitiveString()
1183 << " failed, code=" << code;
1184 if (code == STUN_ERROR_STALE_NONCE) {
1185 if (port_->UpdateNonce(response)) {
1186 SendCreatePermissionRequest();
1187 }
1188 } else {
1189 // Send signal with error code.
1190 port_->SignalCreatePermissionResult(port_, ext_addr_, code);
1191 }
1192}
1193
1194void TurnEntry::OnChannelBindSuccess() {
1195 LOG_J(LS_INFO, port_) << "Channel bind for " << ext_addr_.ToSensitiveString()
1196 << " succeeded";
1197 ASSERT(state_ == STATE_BINDING || state_ == STATE_BOUND);
1198 state_ = STATE_BOUND;
1199}
1200
1201void TurnEntry::OnChannelBindError(StunMessage* response, int code) {
1202 // TODO(mallinath) - Implement handling of error response for channel
1203 // bind request as per http://tools.ietf.org/html/rfc5766#section-11.3
1204 LOG_J(LS_WARNING, port_) << "Channel bind for "
1205 << ext_addr_.ToSensitiveString()
1206 << " failed, code=" << code;
1207 if (code == STUN_ERROR_STALE_NONCE) {
1208 if (port_->UpdateNonce(response)) {
1209 // Send channel bind request with fresh nonce.
1210 SendChannelBindRequest(0);
1211 }
1212 }
1213}
1214
1215} // namespace cricket