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