blob: 565a087720a52f334d2e57154e81652f848282c9 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle
3 * Copyright 2012, Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#include "talk/p2p/base/turnserver.h"
29
30#include "talk/base/bytebuffer.h"
31#include "talk/base/helpers.h"
32#include "talk/base/logging.h"
33#include "talk/base/messagedigest.h"
34#include "talk/base/socketadapters.h"
35#include "talk/base/stringencode.h"
36#include "talk/base/thread.h"
37#include "talk/p2p/base/asyncstuntcpsocket.h"
38#include "talk/p2p/base/common.h"
39#include "talk/p2p/base/packetsocketfactory.h"
40#include "talk/p2p/base/stun.h"
41
42namespace cricket {
43
44// TODO(juberti): Move this all to a future turnmessage.h
45//static const int IPPROTO_UDP = 17;
46static const int kNonceTimeout = 60 * 60 * 1000; // 60 minutes
47static const int kDefaultAllocationTimeout = 10 * 60 * 1000; // 10 minutes
48static const int kPermissionTimeout = 5 * 60 * 1000; // 5 minutes
49static const int kChannelTimeout = 10 * 60 * 1000; // 10 minutes
50
51static const int kMinChannelNumber = 0x4000;
52static const int kMaxChannelNumber = 0x7FFF;
53
54static const size_t kNonceKeySize = 16;
55static const size_t kNonceSize = 40;
56
57static const size_t TURN_CHANNEL_HEADER_SIZE = 4U;
58
59// TODO(mallinath) - Move these to a common place.
60static const size_t kMaxPacketSize = 64 * 1024;
61
62inline bool IsTurnChannelData(uint16 msg_type) {
63 // The first two bits of a channel data message are 0b01.
64 return ((msg_type & 0xC000) == 0x4000);
65}
66
67// IDs used for posted messages.
68enum {
69 MSG_TIMEOUT,
70};
71
72// Encapsulates a TURN allocation.
73// The object is created when an allocation request is received, and then
74// handles TURN messages (via HandleTurnMessage) and channel data messages
75// (via HandleChannelData) for this allocation when received by the server.
76// The object self-deletes and informs the server if its lifetime timer expires.
77class TurnServer::Allocation : public talk_base::MessageHandler,
78 public sigslot::has_slots<> {
79 public:
80 Allocation(TurnServer* server_,
81 talk_base::Thread* thread, const Connection& conn,
82 talk_base::AsyncPacketSocket* server_socket,
83 const std::string& key);
84 virtual ~Allocation();
85
86 Connection* conn() { return &conn_; }
87 const std::string& key() const { return key_; }
88 const std::string& transaction_id() const { return transaction_id_; }
89 const std::string& username() const { return username_; }
90 const std::string& last_nonce() const { return last_nonce_; }
91 void set_last_nonce(const std::string& nonce) { last_nonce_ = nonce; }
92
93 std::string ToString() const;
94
95 void HandleTurnMessage(const TurnMessage* msg);
96 void HandleChannelData(const char* data, size_t size);
97
98 sigslot::signal1<Allocation*> SignalDestroyed;
99
100 private:
101 typedef std::list<Permission*> PermissionList;
102 typedef std::list<Channel*> ChannelList;
103
104 void HandleAllocateRequest(const TurnMessage* msg);
105 void HandleRefreshRequest(const TurnMessage* msg);
106 void HandleSendIndication(const TurnMessage* msg);
107 void HandleCreatePermissionRequest(const TurnMessage* msg);
108 void HandleChannelBindRequest(const TurnMessage* msg);
109
110 void OnExternalPacket(talk_base::AsyncPacketSocket* socket,
111 const char* data, size_t size,
112 const talk_base::SocketAddress& addr);
113
114 static int ComputeLifetime(const TurnMessage* msg);
115 bool HasPermission(const talk_base::IPAddress& addr);
116 void AddPermission(const talk_base::IPAddress& addr);
117 Permission* FindPermission(const talk_base::IPAddress& addr) const;
118 Channel* FindChannel(int channel_id) const;
119 Channel* FindChannel(const talk_base::SocketAddress& addr) const;
120
121 void SendResponse(TurnMessage* msg);
122 void SendBadRequestResponse(const TurnMessage* req);
123 void SendErrorResponse(const TurnMessage* req, int code,
124 const std::string& reason);
125 void SendExternal(const void* data, size_t size,
126 const talk_base::SocketAddress& peer);
127
128 void OnPermissionDestroyed(Permission* perm);
129 void OnChannelDestroyed(Channel* channel);
130 virtual void OnMessage(talk_base::Message* msg);
131
132 TurnServer* server_;
133 talk_base::Thread* thread_;
134 Connection conn_;
135 talk_base::scoped_ptr<talk_base::AsyncPacketSocket> external_socket_;
136 std::string key_;
137 std::string transaction_id_;
138 std::string username_;
139 std::string last_nonce_;
140 PermissionList perms_;
141 ChannelList channels_;
142};
143
144// Encapsulates a TURN permission.
145// The object is created when a create permission request is received by an
146// allocation, and self-deletes when its lifetime timer expires.
147class TurnServer::Permission : public talk_base::MessageHandler {
148 public:
149 Permission(talk_base::Thread* thread, const talk_base::IPAddress& peer);
150 ~Permission();
151
152 const talk_base::IPAddress& peer() const { return peer_; }
153 void Refresh();
154
155 sigslot::signal1<Permission*> SignalDestroyed;
156
157 private:
158 virtual void OnMessage(talk_base::Message* msg);
159
160 talk_base::Thread* thread_;
161 talk_base::IPAddress peer_;
162};
163
164// Encapsulates a TURN channel binding.
165// The object is created when a channel bind request is received by an
166// allocation, and self-deletes when its lifetime timer expires.
167class TurnServer::Channel : public talk_base::MessageHandler {
168 public:
169 Channel(talk_base::Thread* thread, int id,
170 const talk_base::SocketAddress& peer);
171 ~Channel();
172
173 int id() const { return id_; }
174 const talk_base::SocketAddress& peer() const { return peer_; }
175 void Refresh();
176
177 sigslot::signal1<Channel*> SignalDestroyed;
178
179 private:
180 virtual void OnMessage(talk_base::Message* msg);
181
182 talk_base::Thread* thread_;
183 int id_;
184 talk_base::SocketAddress peer_;
185};
186
187static bool InitResponse(const StunMessage* req, StunMessage* resp) {
188 int resp_type = (req) ? GetStunSuccessResponseType(req->type()) : -1;
189 if (resp_type == -1)
190 return false;
191 resp->SetType(resp_type);
192 resp->SetTransactionID(req->transaction_id());
193 return true;
194}
195
196static bool InitErrorResponse(const StunMessage* req, int code,
197 const std::string& reason, StunMessage* resp) {
198 int resp_type = (req) ? GetStunErrorResponseType(req->type()) : -1;
199 if (resp_type == -1)
200 return false;
201 resp->SetType(resp_type);
202 resp->SetTransactionID(req->transaction_id());
203 VERIFY(resp->AddAttribute(new cricket::StunErrorCodeAttribute(
204 STUN_ATTR_ERROR_CODE, code, reason)));
205 return true;
206}
207
208TurnServer::TurnServer(talk_base::Thread* thread)
209 : thread_(thread),
210 nonce_key_(talk_base::CreateRandomString(kNonceKeySize)),
211 auth_hook_(NULL),
212 enable_otu_nonce_(false) {
213}
214
215TurnServer::~TurnServer() {
216 for (AllocationMap::iterator it = allocations_.begin();
217 it != allocations_.end(); ++it) {
218 delete it->second;
219 }
220
221 for (InternalSocketMap::iterator it = server_sockets_.begin();
222 it != server_sockets_.end(); ++it) {
223 talk_base::AsyncPacketSocket* socket = it->first;
224 delete socket;
225 }
226
227 for (ServerSocketMap::iterator it = server_listen_sockets_.begin();
228 it != server_listen_sockets_.end(); ++it) {
229 talk_base::AsyncSocket* socket = it->first;
230 delete socket;
231 }
232}
233
234void TurnServer::AddInternalSocket(talk_base::AsyncPacketSocket* socket,
235 ProtocolType proto) {
236 ASSERT(server_sockets_.end() == server_sockets_.find(socket));
237 server_sockets_[socket] = proto;
238 socket->SignalReadPacket.connect(this, &TurnServer::OnInternalPacket);
239}
240
241void TurnServer::AddInternalServerSocket(talk_base::AsyncSocket* socket,
242 ProtocolType proto) {
243 ASSERT(server_listen_sockets_.end() ==
244 server_listen_sockets_.find(socket));
245 server_listen_sockets_[socket] = proto;
246 socket->SignalReadEvent.connect(this, &TurnServer::OnNewInternalConnection);
247}
248
249void TurnServer::SetExternalSocketFactory(
250 talk_base::PacketSocketFactory* factory,
251 const talk_base::SocketAddress& external_addr) {
252 external_socket_factory_.reset(factory);
253 external_addr_ = external_addr;
254}
255
256void TurnServer::OnNewInternalConnection(talk_base::AsyncSocket* socket) {
257 ASSERT(server_listen_sockets_.find(socket) != server_listen_sockets_.end());
258 AcceptConnection(socket);
259}
260
261void TurnServer::AcceptConnection(talk_base::AsyncSocket* server_socket) {
262 // Check if someone is trying to connect to us.
263 talk_base::SocketAddress accept_addr;
264 talk_base::AsyncSocket* accepted_socket = server_socket->Accept(&accept_addr);
265 if (accepted_socket != NULL) {
266 ProtocolType proto = server_listen_sockets_[server_socket];
267 if (proto == PROTO_SSLTCP) {
268 accepted_socket = new talk_base::AsyncSSLServerSocket(accepted_socket);
269 }
270 cricket::AsyncStunTCPSocket* tcp_socket =
271 new cricket::AsyncStunTCPSocket(accepted_socket, false);
272
273 tcp_socket->SignalClose.connect(this, &TurnServer::OnInternalSocketClose);
274 // Finally add the socket so it can start communicating with the client.
275 AddInternalSocket(tcp_socket, proto);
276 }
277}
278
279void TurnServer::OnInternalSocketClose(talk_base::AsyncPacketSocket* socket,
280 int err) {
281 DestroyInternalSocket(socket);
282}
283
284void TurnServer::OnInternalPacket(talk_base::AsyncPacketSocket* socket,
285 const char* data, size_t size,
286 const talk_base::SocketAddress& addr) {
287 // Fail if the packet is too small to even contain a channel header.
288 if (size < TURN_CHANNEL_HEADER_SIZE) {
289 return;
290 }
291 InternalSocketMap::iterator iter = server_sockets_.find(socket);
292 ASSERT(iter != server_sockets_.end());
293 Connection conn(addr, iter->second, socket);
294 uint16 msg_type = talk_base::GetBE16(data);
295 if (!IsTurnChannelData(msg_type)) {
296 // This is a STUN message.
297 HandleStunMessage(&conn, data, size);
298 } else {
299 // This is a channel message; let the allocation handle it.
300 Allocation* allocation = FindAllocation(&conn);
301 if (allocation) {
302 allocation->HandleChannelData(data, size);
303 }
304 }
305}
306
307void TurnServer::HandleStunMessage(Connection* conn, const char* data,
308 size_t size) {
309 TurnMessage msg;
310 talk_base::ByteBuffer buf(data, size);
311 if (!msg.Read(&buf) || (buf.Length() > 0)) {
312 LOG(LS_WARNING) << "Received invalid STUN message";
313 return;
314 }
315
316 // If it's a STUN binding request, handle that specially.
317 if (msg.type() == STUN_BINDING_REQUEST) {
318 HandleBindingRequest(conn, &msg);
319 return;
320 }
321
322 // Look up the key that we'll use to validate the M-I. If we have an
323 // existing allocation, the key will already be cached.
324 Allocation* allocation = FindAllocation(conn);
325 std::string key;
326 if (!allocation) {
327 GetKey(&msg, &key);
328 } else {
329 key = allocation->key();
330 }
331
332 // Ensure the message is authorized; only needed for requests.
333 if (IsStunRequestType(msg.type())) {
334 if (!CheckAuthorization(conn, &msg, data, size, key)) {
335 return;
336 }
337 }
338
339 if (!allocation && msg.type() == STUN_ALLOCATE_REQUEST) {
340 // This is a new allocate request.
341 HandleAllocateRequest(conn, &msg, key);
342 } else if (allocation &&
343 (msg.type() != STUN_ALLOCATE_REQUEST ||
344 msg.transaction_id() == allocation->transaction_id())) {
345 // This is a non-allocate request, or a retransmit of an allocate.
346 // Check that the username matches the previous username used.
347 if (IsStunRequestType(msg.type()) &&
348 msg.GetByteString(STUN_ATTR_USERNAME)->GetString() !=
349 allocation->username()) {
350 SendErrorResponse(conn, &msg, STUN_ERROR_WRONG_CREDENTIALS,
351 STUN_ERROR_REASON_WRONG_CREDENTIALS);
352 return;
353 }
354 allocation->HandleTurnMessage(&msg);
355 } else {
356 // Allocation mismatch.
357 SendErrorResponse(conn, &msg, STUN_ERROR_ALLOCATION_MISMATCH,
358 STUN_ERROR_REASON_ALLOCATION_MISMATCH);
359 }
360}
361
362bool TurnServer::GetKey(const StunMessage* msg, std::string* key) {
363 const StunByteStringAttribute* username_attr =
364 msg->GetByteString(STUN_ATTR_USERNAME);
365 if (!username_attr) {
366 return false;
367 }
368
369 std::string username = username_attr->GetString();
370 return (auth_hook_ != NULL && auth_hook_->GetKey(username, realm_, key));
371}
372
373bool TurnServer::CheckAuthorization(Connection* conn,
374 const StunMessage* msg,
375 const char* data, size_t size,
376 const std::string& key) {
377 // RFC 5389, 10.2.2.
378 ASSERT(IsStunRequestType(msg->type()));
379 const StunByteStringAttribute* mi_attr =
380 msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY);
381 const StunByteStringAttribute* username_attr =
382 msg->GetByteString(STUN_ATTR_USERNAME);
383 const StunByteStringAttribute* realm_attr =
384 msg->GetByteString(STUN_ATTR_REALM);
385 const StunByteStringAttribute* nonce_attr =
386 msg->GetByteString(STUN_ATTR_NONCE);
387
388 // Fail if no M-I.
389 if (!mi_attr) {
390 SendErrorResponseWithRealmAndNonce(conn, msg, STUN_ERROR_UNAUTHORIZED,
391 STUN_ERROR_REASON_UNAUTHORIZED);
392 return false;
393 }
394
395 // Fail if there is M-I but no username, nonce, or realm.
396 if (!username_attr || !realm_attr || !nonce_attr) {
397 SendErrorResponse(conn, msg, STUN_ERROR_BAD_REQUEST,
398 STUN_ERROR_REASON_BAD_REQUEST);
399 return false;
400 }
401
402 // Fail if bad nonce.
403 if (!ValidateNonce(nonce_attr->GetString())) {
404 SendErrorResponseWithRealmAndNonce(conn, msg, STUN_ERROR_STALE_NONCE,
405 STUN_ERROR_REASON_STALE_NONCE);
406 return false;
407 }
408
409 // Fail if bad username or M-I.
410 // We need |data| and |size| for the call to ValidateMessageIntegrity.
411 if (key.empty() || !StunMessage::ValidateMessageIntegrity(data, size, key)) {
412 SendErrorResponseWithRealmAndNonce(conn, msg, STUN_ERROR_UNAUTHORIZED,
413 STUN_ERROR_REASON_UNAUTHORIZED);
414 return false;
415 }
416
417 // Fail if one-time-use nonce feature is enabled.
418 Allocation* allocation = FindAllocation(conn);
419 if (enable_otu_nonce_ && allocation &&
420 allocation->last_nonce() == nonce_attr->GetString()) {
421 SendErrorResponseWithRealmAndNonce(conn, msg, STUN_ERROR_STALE_NONCE,
422 STUN_ERROR_REASON_STALE_NONCE);
423 return false;
424 }
425
426 if (allocation) {
427 allocation->set_last_nonce(nonce_attr->GetString());
428 }
429 // Success.
430 return true;
431}
432
433void TurnServer::HandleBindingRequest(Connection* conn,
434 const StunMessage* req) {
435 StunMessage response;
436 InitResponse(req, &response);
437
438 // Tell the user the address that we received their request from.
439 StunAddressAttribute* mapped_addr_attr;
440 mapped_addr_attr = new StunXorAddressAttribute(
441 STUN_ATTR_XOR_MAPPED_ADDRESS, conn->src());
442 VERIFY(response.AddAttribute(mapped_addr_attr));
443
444 SendStun(conn, &response);
445}
446
447void TurnServer::HandleAllocateRequest(Connection* conn,
448 const TurnMessage* msg,
449 const std::string& key) {
450 // Check the parameters in the request.
451 const StunUInt32Attribute* transport_attr =
452 msg->GetUInt32(STUN_ATTR_REQUESTED_TRANSPORT);
453 if (!transport_attr) {
454 SendErrorResponse(conn, msg, STUN_ERROR_BAD_REQUEST,
455 STUN_ERROR_REASON_BAD_REQUEST);
456 return;
457 }
458
459 // Only UDP is supported right now.
460 int proto = transport_attr->value() >> 24;
461 if (proto != IPPROTO_UDP) {
462 SendErrorResponse(conn, msg, STUN_ERROR_UNSUPPORTED_PROTOCOL,
463 STUN_ERROR_REASON_UNSUPPORTED_PROTOCOL);
464 return;
465 }
466
467 // Create the allocation and let it send the success response.
468 // If the actual socket allocation fails, send an internal error.
469 Allocation* alloc = CreateAllocation(conn, proto, key);
470 if (alloc) {
471 alloc->HandleTurnMessage(msg);
472 } else {
473 SendErrorResponse(conn, msg, STUN_ERROR_SERVER_ERROR,
474 "Failed to allocate socket");
475 }
476}
477
478std::string TurnServer::GenerateNonce() const {
479 // Generate a nonce of the form hex(now + HMAC-MD5(nonce_key_, now))
480 uint32 now = talk_base::Time();
481 std::string input(reinterpret_cast<const char*>(&now), sizeof(now));
482 std::string nonce = talk_base::hex_encode(input.c_str(), input.size());
483 nonce += talk_base::ComputeHmac(talk_base::DIGEST_MD5, nonce_key_, input);
484 ASSERT(nonce.size() == kNonceSize);
485 return nonce;
486}
487
488bool TurnServer::ValidateNonce(const std::string& nonce) const {
489 // Check the size.
490 if (nonce.size() != kNonceSize) {
491 return false;
492 }
493
494 // Decode the timestamp.
495 uint32 then;
496 char* p = reinterpret_cast<char*>(&then);
497 size_t len = talk_base::hex_decode(p, sizeof(then),
498 nonce.substr(0, sizeof(then) * 2));
499 if (len != sizeof(then)) {
500 return false;
501 }
502
503 // Verify the HMAC.
504 if (nonce.substr(sizeof(then) * 2) != talk_base::ComputeHmac(
505 talk_base::DIGEST_MD5, nonce_key_, std::string(p, sizeof(then)))) {
506 return false;
507 }
508
509 // Validate the timestamp.
510 return talk_base::TimeSince(then) < kNonceTimeout;
511}
512
513TurnServer::Allocation* TurnServer::FindAllocation(Connection* conn) {
514 AllocationMap::const_iterator it = allocations_.find(*conn);
515 return (it != allocations_.end()) ? it->second : NULL;
516}
517
518TurnServer::Allocation* TurnServer::CreateAllocation(Connection* conn,
519 int proto,
520 const std::string& key) {
521 talk_base::AsyncPacketSocket* external_socket = (external_socket_factory_) ?
522 external_socket_factory_->CreateUdpSocket(external_addr_, 0, 0) : NULL;
523 if (!external_socket) {
524 return NULL;
525 }
526
527 // The Allocation takes ownership of the socket.
528 Allocation* allocation = new Allocation(this,
529 thread_, *conn, external_socket, key);
530 allocation->SignalDestroyed.connect(this, &TurnServer::OnAllocationDestroyed);
531 allocations_[*conn] = allocation;
532 return allocation;
533}
534
535void TurnServer::SendErrorResponse(Connection* conn,
536 const StunMessage* req,
537 int code, const std::string& reason) {
538 TurnMessage resp;
539 InitErrorResponse(req, code, reason, &resp);
540 LOG(LS_INFO) << "Sending error response, type=" << resp.type()
541 << ", code=" << code << ", reason=" << reason;
542 SendStun(conn, &resp);
543}
544
545void TurnServer::SendErrorResponseWithRealmAndNonce(
546 Connection* conn, const StunMessage* msg,
547 int code, const std::string& reason) {
548 TurnMessage resp;
549 InitErrorResponse(msg, code, reason, &resp);
550 VERIFY(resp.AddAttribute(new StunByteStringAttribute(
551 STUN_ATTR_NONCE, GenerateNonce())));
552 VERIFY(resp.AddAttribute(new StunByteStringAttribute(
553 STUN_ATTR_REALM, realm_)));
554 SendStun(conn, &resp);
555}
556
557void TurnServer::SendStun(Connection* conn, StunMessage* msg) {
558 talk_base::ByteBuffer buf;
559 // Add a SOFTWARE attribute if one is set.
560 if (!software_.empty()) {
561 VERIFY(msg->AddAttribute(
562 new StunByteStringAttribute(STUN_ATTR_SOFTWARE, software_)));
563 }
564 msg->Write(&buf);
565 Send(conn, buf);
566}
567
568void TurnServer::Send(Connection* conn,
569 const talk_base::ByteBuffer& buf) {
570 conn->socket()->SendTo(buf.Data(), buf.Length(), conn->src());
571}
572
573void TurnServer::OnAllocationDestroyed(Allocation* allocation) {
574 // Removing the internal socket if the connection is not udp.
575 talk_base::AsyncPacketSocket* socket = allocation->conn()->socket();
576 InternalSocketMap::iterator iter = server_sockets_.find(socket);
577 ASSERT(iter != server_sockets_.end());
578 // Skip if the socket serving this allocation is UDP, as this will be shared
579 // by all allocations.
580 if (iter->second != cricket::PROTO_UDP) {
581 DestroyInternalSocket(socket);
582 }
583
584 AllocationMap::iterator it = allocations_.find(*(allocation->conn()));
585 if (it != allocations_.end())
586 allocations_.erase(it);
587}
588
589void TurnServer::DestroyInternalSocket(talk_base::AsyncPacketSocket* socket) {
590 InternalSocketMap::iterator iter = server_sockets_.find(socket);
591 if (iter != server_sockets_.end()) {
592 talk_base::AsyncPacketSocket* socket = iter->first;
593 delete socket;
594 server_sockets_.erase(iter);
595 }
596}
597
598TurnServer::Connection::Connection(const talk_base::SocketAddress& src,
599 ProtocolType proto,
600 talk_base::AsyncPacketSocket* socket)
601 : src_(src),
602 dst_(socket->GetRemoteAddress()),
603 proto_(proto),
604 socket_(socket) {
605}
606
607bool TurnServer::Connection::operator==(const Connection& c) const {
608 return src_ == c.src_ && dst_ == c.dst_ && proto_ == c.proto_;
609}
610
611bool TurnServer::Connection::operator<(const Connection& c) const {
612 return src_ < c.src_ || dst_ < c.dst_ || proto_ < c.proto_;
613}
614
615std::string TurnServer::Connection::ToString() const {
616 const char* const kProtos[] = {
617 "unknown", "udp", "tcp", "ssltcp"
618 };
619 std::ostringstream ost;
620 ost << src_.ToString() << "-" << dst_.ToString() << ":"<< kProtos[proto_];
621 return ost.str();
622}
623
624TurnServer::Allocation::Allocation(TurnServer* server,
625 talk_base::Thread* thread,
626 const Connection& conn,
627 talk_base::AsyncPacketSocket* socket,
628 const std::string& key)
629 : server_(server),
630 thread_(thread),
631 conn_(conn),
632 external_socket_(socket),
633 key_(key) {
634 external_socket_->SignalReadPacket.connect(
635 this, &TurnServer::Allocation::OnExternalPacket);
636}
637
638TurnServer::Allocation::~Allocation() {
639 for (ChannelList::iterator it = channels_.begin();
640 it != channels_.end(); ++it) {
641 delete *it;
642 }
643 for (PermissionList::iterator it = perms_.begin();
644 it != perms_.end(); ++it) {
645 delete *it;
646 }
647 thread_->Clear(this, MSG_TIMEOUT);
648 LOG_J(LS_INFO, this) << "Allocation destroyed";
649}
650
651std::string TurnServer::Allocation::ToString() const {
652 std::ostringstream ost;
653 ost << "Alloc[" << conn_.ToString() << "]";
654 return ost.str();
655}
656
657void TurnServer::Allocation::HandleTurnMessage(const TurnMessage* msg) {
658 ASSERT(msg != NULL);
659 switch (msg->type()) {
660 case STUN_ALLOCATE_REQUEST:
661 HandleAllocateRequest(msg);
662 break;
663 case TURN_REFRESH_REQUEST:
664 HandleRefreshRequest(msg);
665 break;
666 case TURN_SEND_INDICATION:
667 HandleSendIndication(msg);
668 break;
669 case TURN_CREATE_PERMISSION_REQUEST:
670 HandleCreatePermissionRequest(msg);
671 break;
672 case TURN_CHANNEL_BIND_REQUEST:
673 HandleChannelBindRequest(msg);
674 break;
675 default:
676 // Not sure what to do with this, just eat it.
677 LOG_J(LS_WARNING, this) << "Invalid TURN message type received: "
678 << msg->type();
679 }
680}
681
682void TurnServer::Allocation::HandleAllocateRequest(const TurnMessage* msg) {
683 // Copy the important info from the allocate request.
684 transaction_id_ = msg->transaction_id();
685 const StunByteStringAttribute* username_attr =
686 msg->GetByteString(STUN_ATTR_USERNAME);
687 ASSERT(username_attr != NULL);
688 username_ = username_attr->GetString();
689
690 // Figure out the lifetime and start the allocation timer.
691 int lifetime_secs = ComputeLifetime(msg);
692 thread_->PostDelayed(lifetime_secs * 1000, this, MSG_TIMEOUT);
693
694 LOG_J(LS_INFO, this) << "Created allocation, lifetime=" << lifetime_secs;
695
696 // We've already validated all the important bits; just send a response here.
697 TurnMessage response;
698 InitResponse(msg, &response);
699
700 StunAddressAttribute* mapped_addr_attr =
701 new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, conn_.src());
702 StunAddressAttribute* relayed_addr_attr =
703 new StunXorAddressAttribute(STUN_ATTR_XOR_RELAYED_ADDRESS,
704 external_socket_->GetLocalAddress());
705 StunUInt32Attribute* lifetime_attr =
706 new StunUInt32Attribute(STUN_ATTR_LIFETIME, lifetime_secs);
707 VERIFY(response.AddAttribute(mapped_addr_attr));
708 VERIFY(response.AddAttribute(relayed_addr_attr));
709 VERIFY(response.AddAttribute(lifetime_attr));
710
711 SendResponse(&response);
712}
713
714void TurnServer::Allocation::HandleRefreshRequest(const TurnMessage* msg) {
715 // Figure out the new lifetime.
716 int lifetime_secs = ComputeLifetime(msg);
717
718 // Reset the expiration timer.
719 thread_->Clear(this, MSG_TIMEOUT);
720 thread_->PostDelayed(lifetime_secs * 1000, this, MSG_TIMEOUT);
721
722 LOG_J(LS_INFO, this) << "Refreshed allocation, lifetime=" << lifetime_secs;
723
724 // Send a success response with a LIFETIME attribute.
725 TurnMessage response;
726 InitResponse(msg, &response);
727
728 StunUInt32Attribute* lifetime_attr =
729 new StunUInt32Attribute(STUN_ATTR_LIFETIME, lifetime_secs);
730 VERIFY(response.AddAttribute(lifetime_attr));
731
732 SendResponse(&response);
733}
734
735void TurnServer::Allocation::HandleSendIndication(const TurnMessage* msg) {
736 // Check mandatory attributes.
737 const StunByteStringAttribute* data_attr = msg->GetByteString(STUN_ATTR_DATA);
738 const StunAddressAttribute* peer_attr =
739 msg->GetAddress(STUN_ATTR_XOR_PEER_ADDRESS);
740 if (!data_attr || !peer_attr) {
741 LOG_J(LS_WARNING, this) << "Received invalid send indication";
742 return;
743 }
744
745 // If a permission exists, send the data on to the peer.
746 if (HasPermission(peer_attr->GetAddress().ipaddr())) {
747 SendExternal(data_attr->bytes(), data_attr->length(),
748 peer_attr->GetAddress());
749 } else {
750 LOG_J(LS_WARNING, this) << "Received send indication without permission"
751 << "peer=" << peer_attr->GetAddress();
752 }
753}
754
755void TurnServer::Allocation::HandleCreatePermissionRequest(
756 const TurnMessage* msg) {
757 // Check mandatory attributes.
758 const StunAddressAttribute* peer_attr =
759 msg->GetAddress(STUN_ATTR_XOR_PEER_ADDRESS);
760 if (!peer_attr) {
761 SendBadRequestResponse(msg);
762 return;
763 }
764
765 // Add this permission.
766 AddPermission(peer_attr->GetAddress().ipaddr());
767
768 LOG_J(LS_INFO, this) << "Created permission, peer="
769 << peer_attr->GetAddress();
770
771 // Send a success response.
772 TurnMessage response;
773 InitResponse(msg, &response);
774 SendResponse(&response);
775}
776
777void TurnServer::Allocation::HandleChannelBindRequest(const TurnMessage* msg) {
778 // Check mandatory attributes.
779 const StunUInt32Attribute* channel_attr =
780 msg->GetUInt32(STUN_ATTR_CHANNEL_NUMBER);
781 const StunAddressAttribute* peer_attr =
782 msg->GetAddress(STUN_ATTR_XOR_PEER_ADDRESS);
783 if (!channel_attr || !peer_attr) {
784 SendBadRequestResponse(msg);
785 return;
786 }
787
788 // Check that channel id is valid.
789 int channel_id = channel_attr->value() >> 16;
790 if (channel_id < kMinChannelNumber || channel_id > kMaxChannelNumber) {
791 SendBadRequestResponse(msg);
792 return;
793 }
794
795 // Check that this channel id isn't bound to another transport address, and
796 // that this transport address isn't bound to another channel id.
797 Channel* channel1 = FindChannel(channel_id);
798 Channel* channel2 = FindChannel(peer_attr->GetAddress());
799 if (channel1 != channel2) {
800 SendBadRequestResponse(msg);
801 return;
802 }
803
804 // Add or refresh this channel.
805 if (!channel1) {
806 channel1 = new Channel(thread_, channel_id, peer_attr->GetAddress());
807 channel1->SignalDestroyed.connect(this,
808 &TurnServer::Allocation::OnChannelDestroyed);
809 channels_.push_back(channel1);
810 } else {
811 channel1->Refresh();
812 }
813
814 // Channel binds also refresh permissions.
815 AddPermission(peer_attr->GetAddress().ipaddr());
816
817 LOG_J(LS_INFO, this) << "Bound channel, id=" << channel_id
818 << ", peer=" << peer_attr->GetAddress();
819
820 // Send a success response.
821 TurnMessage response;
822 InitResponse(msg, &response);
823 SendResponse(&response);
824}
825
826void TurnServer::Allocation::HandleChannelData(const char* data, size_t size) {
827 // Extract the channel number from the data.
828 uint16 channel_id = talk_base::GetBE16(data);
829 Channel* channel = FindChannel(channel_id);
830 if (channel) {
831 // Send the data to the peer address.
832 SendExternal(data + TURN_CHANNEL_HEADER_SIZE,
833 size - TURN_CHANNEL_HEADER_SIZE, channel->peer());
834 } else {
835 LOG_J(LS_WARNING, this) << "Received channel data for invalid channel, id="
836 << channel_id;
837 }
838}
839
840void TurnServer::Allocation::OnExternalPacket(
841 talk_base::AsyncPacketSocket* socket,
842 const char* data, size_t size,
843 const talk_base::SocketAddress& addr) {
844 ASSERT(external_socket_.get() == socket);
845 Channel* channel = FindChannel(addr);
846 if (channel) {
847 // There is a channel bound to this address. Send as a channel message.
848 talk_base::ByteBuffer buf;
849 buf.WriteUInt16(channel->id());
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000850 buf.WriteUInt16(static_cast<uint16>(size));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000851 buf.WriteBytes(data, size);
852 server_->Send(&conn_, buf);
853 } else if (HasPermission(addr.ipaddr())) {
854 // No channel, but a permission exists. Send as a data indication.
855 TurnMessage msg;
856 msg.SetType(TURN_DATA_INDICATION);
857 msg.SetTransactionID(
858 talk_base::CreateRandomString(kStunTransactionIdLength));
859 VERIFY(msg.AddAttribute(new StunXorAddressAttribute(
860 STUN_ATTR_XOR_PEER_ADDRESS, addr)));
861 VERIFY(msg.AddAttribute(new StunByteStringAttribute(
862 STUN_ATTR_DATA, data, size)));
863 server_->SendStun(&conn_, &msg);
864 } else {
865 LOG_J(LS_WARNING, this) << "Received external packet without permission, "
866 << "peer=" << addr;
867 }
868}
869
870int TurnServer::Allocation::ComputeLifetime(const TurnMessage* msg) {
871 // Return the smaller of our default lifetime and the requested lifetime.
872 uint32 lifetime = kDefaultAllocationTimeout / 1000; // convert to seconds
873 const StunUInt32Attribute* lifetime_attr = msg->GetUInt32(STUN_ATTR_LIFETIME);
874 if (lifetime_attr && lifetime_attr->value() < lifetime) {
875 lifetime = lifetime_attr->value();
876 }
877 return lifetime;
878}
879
880bool TurnServer::Allocation::HasPermission(const talk_base::IPAddress& addr) {
881 return (FindPermission(addr) != NULL);
882}
883
884void TurnServer::Allocation::AddPermission(const talk_base::IPAddress& addr) {
885 Permission* perm = FindPermission(addr);
886 if (!perm) {
887 perm = new Permission(thread_, addr);
888 perm->SignalDestroyed.connect(
889 this, &TurnServer::Allocation::OnPermissionDestroyed);
890 perms_.push_back(perm);
891 } else {
892 perm->Refresh();
893 }
894}
895
896TurnServer::Permission* TurnServer::Allocation::FindPermission(
897 const talk_base::IPAddress& addr) const {
898 for (PermissionList::const_iterator it = perms_.begin();
899 it != perms_.end(); ++it) {
900 if ((*it)->peer() == addr)
901 return *it;
902 }
903 return NULL;
904}
905
906TurnServer::Channel* TurnServer::Allocation::FindChannel(int channel_id) const {
907 for (ChannelList::const_iterator it = channels_.begin();
908 it != channels_.end(); ++it) {
909 if ((*it)->id() == channel_id)
910 return *it;
911 }
912 return NULL;
913}
914
915TurnServer::Channel* TurnServer::Allocation::FindChannel(
916 const talk_base::SocketAddress& addr) const {
917 for (ChannelList::const_iterator it = channels_.begin();
918 it != channels_.end(); ++it) {
919 if ((*it)->peer() == addr)
920 return *it;
921 }
922 return NULL;
923}
924
925void TurnServer::Allocation::SendResponse(TurnMessage* msg) {
926 // Success responses always have M-I.
927 msg->AddMessageIntegrity(key_);
928 server_->SendStun(&conn_, msg);
929}
930
931void TurnServer::Allocation::SendBadRequestResponse(const TurnMessage* req) {
932 SendErrorResponse(req, STUN_ERROR_BAD_REQUEST, STUN_ERROR_REASON_BAD_REQUEST);
933}
934
935void TurnServer::Allocation::SendErrorResponse(const TurnMessage* req, int code,
936 const std::string& reason) {
937 server_->SendErrorResponse(&conn_, req, code, reason);
938}
939
940void TurnServer::Allocation::SendExternal(const void* data, size_t size,
941 const talk_base::SocketAddress& peer) {
942 external_socket_->SendTo(data, size, peer);
943}
944
945void TurnServer::Allocation::OnMessage(talk_base::Message* msg) {
946 ASSERT(msg->message_id == MSG_TIMEOUT);
947 SignalDestroyed(this);
948 delete this;
949}
950
951void TurnServer::Allocation::OnPermissionDestroyed(Permission* perm) {
952 PermissionList::iterator it = std::find(perms_.begin(), perms_.end(), perm);
953 ASSERT(it != perms_.end());
954 perms_.erase(it);
955}
956
957void TurnServer::Allocation::OnChannelDestroyed(Channel* channel) {
958 ChannelList::iterator it =
959 std::find(channels_.begin(), channels_.end(), channel);
960 ASSERT(it != channels_.end());
961 channels_.erase(it);
962}
963
964TurnServer::Permission::Permission(talk_base::Thread* thread,
965 const talk_base::IPAddress& peer)
966 : thread_(thread), peer_(peer) {
967 Refresh();
968}
969
970TurnServer::Permission::~Permission() {
971 thread_->Clear(this, MSG_TIMEOUT);
972}
973
974void TurnServer::Permission::Refresh() {
975 thread_->Clear(this, MSG_TIMEOUT);
976 thread_->PostDelayed(kPermissionTimeout, this, MSG_TIMEOUT);
977}
978
979void TurnServer::Permission::OnMessage(talk_base::Message* msg) {
980 ASSERT(msg->message_id == MSG_TIMEOUT);
981 SignalDestroyed(this);
982 delete this;
983}
984
985TurnServer::Channel::Channel(talk_base::Thread* thread, int id,
986 const talk_base::SocketAddress& peer)
987 : thread_(thread), id_(id), peer_(peer) {
988 Refresh();
989}
990
991TurnServer::Channel::~Channel() {
992 thread_->Clear(this, MSG_TIMEOUT);
993}
994
995void TurnServer::Channel::Refresh() {
996 thread_->Clear(this, MSG_TIMEOUT);
997 thread_->PostDelayed(kChannelTimeout, this, MSG_TIMEOUT);
998}
999
1000void TurnServer::Channel::OnMessage(talk_base::Message* msg) {
1001 ASSERT(msg->message_id == MSG_TIMEOUT);
1002 SignalDestroyed(this);
1003 delete this;
1004}
1005
1006} // namespace cricket