Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / third_party / libjingle / source / talk / p2p / base / relayserver.cc
1 /*
2  * libjingle
3  * Copyright 2004--2005, 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/relayserver.h"
29
30 #ifdef POSIX
31 #include <errno.h>
32 #endif  // POSIX
33
34 #include <algorithm>
35
36 #include "talk/base/asynctcpsocket.h"
37 #include "talk/base/helpers.h"
38 #include "talk/base/logging.h"
39 #include "talk/base/socketadapters.h"
40
41 namespace cricket {
42
43 // By default, we require a ping every 90 seconds.
44 const int MAX_LIFETIME = 15 * 60 * 1000;
45
46 // The number of bytes in each of the usernames we use.
47 const uint32 USERNAME_LENGTH = 16;
48
49 static const uint32 kMessageAcceptConnection = 1;
50
51 // Calls SendTo on the given socket and logs any bad results.
52 void Send(talk_base::AsyncPacketSocket* socket, const char* bytes, size_t size,
53           const talk_base::SocketAddress& addr) {
54   talk_base::PacketOptions options;
55   int result = socket->SendTo(bytes, size, addr, options);
56   if (result < static_cast<int>(size)) {
57     LOG(LS_ERROR) << "SendTo wrote only " << result << " of " << size
58                   << " bytes";
59   } else if (result < 0) {
60     LOG_ERR(LS_ERROR) << "SendTo";
61   }
62 }
63
64 // Sends the given STUN message on the given socket.
65 void SendStun(const StunMessage& msg,
66               talk_base::AsyncPacketSocket* socket,
67               const talk_base::SocketAddress& addr) {
68   talk_base::ByteBuffer buf;
69   msg.Write(&buf);
70   Send(socket, buf.Data(), buf.Length(), addr);
71 }
72
73 // Constructs a STUN error response and sends it on the given socket.
74 void SendStunError(const StunMessage& msg, talk_base::AsyncPacketSocket* socket,
75                    const talk_base::SocketAddress& remote_addr, int error_code,
76                    const char* error_desc, const std::string& magic_cookie) {
77   RelayMessage err_msg;
78   err_msg.SetType(GetStunErrorResponseType(msg.type()));
79   err_msg.SetTransactionID(msg.transaction_id());
80
81   StunByteStringAttribute* magic_cookie_attr =
82       StunAttribute::CreateByteString(cricket::STUN_ATTR_MAGIC_COOKIE);
83   if (magic_cookie.size() == 0) {
84     magic_cookie_attr->CopyBytes(cricket::TURN_MAGIC_COOKIE_VALUE,
85                                  sizeof(cricket::TURN_MAGIC_COOKIE_VALUE));
86   } else {
87     magic_cookie_attr->CopyBytes(magic_cookie.c_str(), magic_cookie.size());
88   }
89   err_msg.AddAttribute(magic_cookie_attr);
90
91   StunErrorCodeAttribute* err_code = StunAttribute::CreateErrorCode();
92   err_code->SetClass(error_code / 100);
93   err_code->SetNumber(error_code % 100);
94   err_code->SetReason(error_desc);
95   err_msg.AddAttribute(err_code);
96
97   SendStun(err_msg, socket, remote_addr);
98 }
99
100 RelayServer::RelayServer(talk_base::Thread* thread)
101   : thread_(thread), log_bindings_(true) {
102 }
103
104 RelayServer::~RelayServer() {
105   // Deleting the binding will cause it to be removed from the map.
106   while (!bindings_.empty())
107     delete bindings_.begin()->second;
108   for (size_t i = 0; i < internal_sockets_.size(); ++i)
109     delete internal_sockets_[i];
110   for (size_t i = 0; i < external_sockets_.size(); ++i)
111     delete external_sockets_[i];
112   for (size_t i = 0; i < removed_sockets_.size(); ++i)
113     delete removed_sockets_[i];
114   while (!server_sockets_.empty()) {
115     talk_base::AsyncSocket* socket = server_sockets_.begin()->first;
116     server_sockets_.erase(server_sockets_.begin()->first);
117     delete socket;
118   }
119 }
120
121 void RelayServer::AddInternalSocket(talk_base::AsyncPacketSocket* socket) {
122   ASSERT(internal_sockets_.end() ==
123       std::find(internal_sockets_.begin(), internal_sockets_.end(), socket));
124   internal_sockets_.push_back(socket);
125   socket->SignalReadPacket.connect(this, &RelayServer::OnInternalPacket);
126 }
127
128 void RelayServer::RemoveInternalSocket(talk_base::AsyncPacketSocket* socket) {
129   SocketList::iterator iter =
130       std::find(internal_sockets_.begin(), internal_sockets_.end(), socket);
131   ASSERT(iter != internal_sockets_.end());
132   internal_sockets_.erase(iter);
133   removed_sockets_.push_back(socket);
134   socket->SignalReadPacket.disconnect(this);
135 }
136
137 void RelayServer::AddExternalSocket(talk_base::AsyncPacketSocket* socket) {
138   ASSERT(external_sockets_.end() ==
139       std::find(external_sockets_.begin(), external_sockets_.end(), socket));
140   external_sockets_.push_back(socket);
141   socket->SignalReadPacket.connect(this, &RelayServer::OnExternalPacket);
142 }
143
144 void RelayServer::RemoveExternalSocket(talk_base::AsyncPacketSocket* socket) {
145   SocketList::iterator iter =
146       std::find(external_sockets_.begin(), external_sockets_.end(), socket);
147   ASSERT(iter != external_sockets_.end());
148   external_sockets_.erase(iter);
149   removed_sockets_.push_back(socket);
150   socket->SignalReadPacket.disconnect(this);
151 }
152
153 void RelayServer::AddInternalServerSocket(talk_base::AsyncSocket* socket,
154                                           cricket::ProtocolType proto) {
155   ASSERT(server_sockets_.end() ==
156          server_sockets_.find(socket));
157   server_sockets_[socket] = proto;
158   socket->SignalReadEvent.connect(this, &RelayServer::OnReadEvent);
159 }
160
161 void RelayServer::RemoveInternalServerSocket(
162     talk_base::AsyncSocket* socket) {
163   ServerSocketMap::iterator iter = server_sockets_.find(socket);
164   ASSERT(iter != server_sockets_.end());
165   server_sockets_.erase(iter);
166   socket->SignalReadEvent.disconnect(this);
167 }
168
169 int RelayServer::GetConnectionCount() const {
170   return static_cast<int>(connections_.size());
171 }
172
173 talk_base::SocketAddressPair RelayServer::GetConnection(int connection) const {
174   int i = 0;
175   for (ConnectionMap::const_iterator it = connections_.begin();
176        it != connections_.end(); ++it) {
177     if (i == connection) {
178       return it->second->addr_pair();
179     }
180     ++i;
181   }
182   return talk_base::SocketAddressPair();
183 }
184
185 bool RelayServer::HasConnection(const talk_base::SocketAddress& address) const {
186   for (ConnectionMap::const_iterator it = connections_.begin();
187        it != connections_.end(); ++it) {
188     if (it->second->addr_pair().destination() == address) {
189       return true;
190     }
191   }
192   return false;
193 }
194
195 void RelayServer::OnReadEvent(talk_base::AsyncSocket* socket) {
196   ASSERT(server_sockets_.find(socket) != server_sockets_.end());
197   AcceptConnection(socket);
198 }
199
200 void RelayServer::OnInternalPacket(
201     talk_base::AsyncPacketSocket* socket, const char* bytes, size_t size,
202     const talk_base::SocketAddress& remote_addr,
203     const talk_base::PacketTime& packet_time) {
204
205   // Get the address of the connection we just received on.
206   talk_base::SocketAddressPair ap(remote_addr, socket->GetLocalAddress());
207   ASSERT(!ap.destination().IsNil());
208
209   // If this did not come from an existing connection, it should be a STUN
210   // allocate request.
211   ConnectionMap::iterator piter = connections_.find(ap);
212   if (piter == connections_.end()) {
213     HandleStunAllocate(bytes, size, ap, socket);
214     return;
215   }
216
217   RelayServerConnection* int_conn = piter->second;
218
219   // Handle STUN requests to the server itself.
220   if (int_conn->binding()->HasMagicCookie(bytes, size)) {
221     HandleStun(int_conn, bytes, size);
222     return;
223   }
224
225   // Otherwise, this is a non-wrapped packet that we are to forward.  Make sure
226   // that this connection has been locked.  (Otherwise, we would not know what
227   // address to forward to.)
228   if (!int_conn->locked()) {
229     LOG(LS_WARNING) << "Dropping packet: connection not locked";
230     return;
231   }
232
233   // Forward this to the destination address into the connection.
234   RelayServerConnection* ext_conn = int_conn->binding()->GetExternalConnection(
235       int_conn->default_destination());
236   if (ext_conn && ext_conn->locked()) {
237     // TODO: Check the HMAC.
238     ext_conn->Send(bytes, size);
239   } else {
240     // This happens very often and is not an error.
241     LOG(LS_INFO) << "Dropping packet: no external connection";
242   }
243 }
244
245 void RelayServer::OnExternalPacket(
246     talk_base::AsyncPacketSocket* socket, const char* bytes, size_t size,
247     const talk_base::SocketAddress& remote_addr,
248     const talk_base::PacketTime& packet_time) {
249
250   // Get the address of the connection we just received on.
251   talk_base::SocketAddressPair ap(remote_addr, socket->GetLocalAddress());
252   ASSERT(!ap.destination().IsNil());
253
254   // If this connection already exists, then forward the traffic.
255   ConnectionMap::iterator piter = connections_.find(ap);
256   if (piter != connections_.end()) {
257     // TODO: Check the HMAC.
258     RelayServerConnection* ext_conn = piter->second;
259     RelayServerConnection* int_conn =
260         ext_conn->binding()->GetInternalConnection(
261             ext_conn->addr_pair().source());
262     ASSERT(int_conn != NULL);
263     int_conn->Send(bytes, size, ext_conn->addr_pair().source());
264     ext_conn->Lock();  // allow outgoing packets
265     return;
266   }
267
268   // The first packet should always be a STUN / TURN packet.  If it isn't, then
269   // we should just ignore this packet.
270   RelayMessage msg;
271   talk_base::ByteBuffer buf(bytes, size);
272   if (!msg.Read(&buf)) {
273     LOG(LS_WARNING) << "Dropping packet: first packet not STUN";
274     return;
275   }
276
277   // The initial packet should have a username (which identifies the binding).
278   const StunByteStringAttribute* username_attr =
279       msg.GetByteString(STUN_ATTR_USERNAME);
280   if (!username_attr) {
281     LOG(LS_WARNING) << "Dropping packet: no username";
282     return;
283   }
284
285   uint32 length = talk_base::_min(static_cast<uint32>(username_attr->length()),
286                                   USERNAME_LENGTH);
287   std::string username(username_attr->bytes(), length);
288   // TODO: Check the HMAC.
289
290   // The binding should already be present.
291   BindingMap::iterator biter = bindings_.find(username);
292   if (biter == bindings_.end()) {
293     LOG(LS_WARNING) << "Dropping packet: no binding with username";
294     return;
295   }
296
297   // Add this authenticted connection to the binding.
298   RelayServerConnection* ext_conn =
299       new RelayServerConnection(biter->second, ap, socket);
300   ext_conn->binding()->AddExternalConnection(ext_conn);
301   AddConnection(ext_conn);
302
303   // We always know where external packets should be forwarded, so we can lock
304   // them from the beginning.
305   ext_conn->Lock();
306
307   // Send this message on the appropriate internal connection.
308   RelayServerConnection* int_conn = ext_conn->binding()->GetInternalConnection(
309       ext_conn->addr_pair().source());
310   ASSERT(int_conn != NULL);
311   int_conn->Send(bytes, size, ext_conn->addr_pair().source());
312 }
313
314 bool RelayServer::HandleStun(
315     const char* bytes, size_t size, const talk_base::SocketAddress& remote_addr,
316     talk_base::AsyncPacketSocket* socket, std::string* username,
317     StunMessage* msg) {
318
319   // Parse this into a stun message. Eat the message if this fails.
320   talk_base::ByteBuffer buf(bytes, size);
321   if (!msg->Read(&buf)) {
322     return false;
323   }
324
325   // The initial packet should have a username (which identifies the binding).
326   const StunByteStringAttribute* username_attr =
327       msg->GetByteString(STUN_ATTR_USERNAME);
328   if (!username_attr) {
329     SendStunError(*msg, socket, remote_addr, 432, "Missing Username", "");
330     return false;
331   }
332
333   // Record the username if requested.
334   if (username)
335     username->append(username_attr->bytes(), username_attr->length());
336
337   // TODO: Check for unknown attributes (<= 0x7fff)
338
339   return true;
340 }
341
342 void RelayServer::HandleStunAllocate(
343     const char* bytes, size_t size, const talk_base::SocketAddressPair& ap,
344     talk_base::AsyncPacketSocket* socket) {
345
346   // Make sure this is a valid STUN request.
347   RelayMessage request;
348   std::string username;
349   if (!HandleStun(bytes, size, ap.source(), socket, &username, &request))
350     return;
351
352   // Make sure this is a an allocate request.
353   if (request.type() != STUN_ALLOCATE_REQUEST) {
354     SendStunError(request,
355                   socket,
356                   ap.source(),
357                   600,
358                   "Operation Not Supported",
359                   "");
360     return;
361   }
362
363   // TODO: Check the HMAC.
364
365   // Find or create the binding for this username.
366
367   RelayServerBinding* binding;
368
369   BindingMap::iterator biter = bindings_.find(username);
370   if (biter != bindings_.end()) {
371     binding = biter->second;
372   } else {
373     // NOTE: In the future, bindings will be created by the bot only.  This
374     //       else-branch will then disappear.
375
376     // Compute the appropriate lifetime for this binding.
377     uint32 lifetime = MAX_LIFETIME;
378     const StunUInt32Attribute* lifetime_attr =
379         request.GetUInt32(STUN_ATTR_LIFETIME);
380     if (lifetime_attr)
381       lifetime = talk_base::_min(lifetime, lifetime_attr->value() * 1000);
382
383     binding = new RelayServerBinding(this, username, "0", lifetime);
384     binding->SignalTimeout.connect(this, &RelayServer::OnTimeout);
385     bindings_[username] = binding;
386
387     if (log_bindings_) {
388       LOG(LS_INFO) << "Added new binding " << username << ", "
389                    << bindings_.size() << " total";
390     }
391   }
392
393   // Add this connection to the binding.  It starts out unlocked.
394   RelayServerConnection* int_conn =
395       new RelayServerConnection(binding, ap, socket);
396   binding->AddInternalConnection(int_conn);
397   AddConnection(int_conn);
398
399   // Now that we have a connection, this other method takes over.
400   HandleStunAllocate(int_conn, request);
401 }
402
403 void RelayServer::HandleStun(
404     RelayServerConnection* int_conn, const char* bytes, size_t size) {
405
406   // Make sure this is a valid STUN request.
407   RelayMessage request;
408   std::string username;
409   if (!HandleStun(bytes, size, int_conn->addr_pair().source(),
410                   int_conn->socket(), &username, &request))
411     return;
412
413   // Make sure the username is the one were were expecting.
414   if (username != int_conn->binding()->username()) {
415     int_conn->SendStunError(request, 430, "Stale Credentials");
416     return;
417   }
418
419   // TODO: Check the HMAC.
420
421   // Send this request to the appropriate handler.
422   if (request.type() == STUN_SEND_REQUEST)
423     HandleStunSend(int_conn, request);
424   else if (request.type() == STUN_ALLOCATE_REQUEST)
425     HandleStunAllocate(int_conn, request);
426   else
427     int_conn->SendStunError(request, 600, "Operation Not Supported");
428 }
429
430 void RelayServer::HandleStunAllocate(
431     RelayServerConnection* int_conn, const StunMessage& request) {
432
433   // Create a response message that includes an address with which external
434   // clients can communicate.
435
436   RelayMessage response;
437   response.SetType(STUN_ALLOCATE_RESPONSE);
438   response.SetTransactionID(request.transaction_id());
439
440   StunByteStringAttribute* magic_cookie_attr =
441       StunAttribute::CreateByteString(cricket::STUN_ATTR_MAGIC_COOKIE);
442   magic_cookie_attr->CopyBytes(int_conn->binding()->magic_cookie().c_str(),
443                                int_conn->binding()->magic_cookie().size());
444   response.AddAttribute(magic_cookie_attr);
445
446   size_t index = rand() % external_sockets_.size();
447   talk_base::SocketAddress ext_addr =
448       external_sockets_[index]->GetLocalAddress();
449
450   StunAddressAttribute* addr_attr =
451       StunAttribute::CreateAddress(STUN_ATTR_MAPPED_ADDRESS);
452   addr_attr->SetIP(ext_addr.ipaddr());
453   addr_attr->SetPort(ext_addr.port());
454   response.AddAttribute(addr_attr);
455
456   StunUInt32Attribute* res_lifetime_attr =
457       StunAttribute::CreateUInt32(STUN_ATTR_LIFETIME);
458   res_lifetime_attr->SetValue(int_conn->binding()->lifetime() / 1000);
459   response.AddAttribute(res_lifetime_attr);
460
461   // TODO: Support transport-prefs (preallocate RTCP port).
462   // TODO: Support bandwidth restrictions.
463   // TODO: Add message integrity check.
464
465   // Send a response to the caller.
466   int_conn->SendStun(response);
467 }
468
469 void RelayServer::HandleStunSend(
470     RelayServerConnection* int_conn, const StunMessage& request) {
471
472   const StunAddressAttribute* addr_attr =
473       request.GetAddress(STUN_ATTR_DESTINATION_ADDRESS);
474   if (!addr_attr) {
475     int_conn->SendStunError(request, 400, "Bad Request");
476     return;
477   }
478
479   const StunByteStringAttribute* data_attr =
480       request.GetByteString(STUN_ATTR_DATA);
481   if (!data_attr) {
482     int_conn->SendStunError(request, 400, "Bad Request");
483     return;
484   }
485
486   talk_base::SocketAddress ext_addr(addr_attr->ipaddr(), addr_attr->port());
487   RelayServerConnection* ext_conn =
488       int_conn->binding()->GetExternalConnection(ext_addr);
489   if (!ext_conn) {
490     // Create a new connection to establish the relationship with this binding.
491     ASSERT(external_sockets_.size() == 1);
492     talk_base::AsyncPacketSocket* socket = external_sockets_[0];
493     talk_base::SocketAddressPair ap(ext_addr, socket->GetLocalAddress());
494     ext_conn = new RelayServerConnection(int_conn->binding(), ap, socket);
495     ext_conn->binding()->AddExternalConnection(ext_conn);
496     AddConnection(ext_conn);
497   }
498
499   // If this connection has pinged us, then allow outgoing traffic.
500   if (ext_conn->locked())
501     ext_conn->Send(data_attr->bytes(), data_attr->length());
502
503   const StunUInt32Attribute* options_attr =
504       request.GetUInt32(STUN_ATTR_OPTIONS);
505   if (options_attr && (options_attr->value() & 0x01)) {
506     int_conn->set_default_destination(ext_addr);
507     int_conn->Lock();
508
509     RelayMessage response;
510     response.SetType(STUN_SEND_RESPONSE);
511     response.SetTransactionID(request.transaction_id());
512
513     StunByteStringAttribute* magic_cookie_attr =
514         StunAttribute::CreateByteString(cricket::STUN_ATTR_MAGIC_COOKIE);
515     magic_cookie_attr->CopyBytes(int_conn->binding()->magic_cookie().c_str(),
516                                  int_conn->binding()->magic_cookie().size());
517     response.AddAttribute(magic_cookie_attr);
518
519     StunUInt32Attribute* options2_attr =
520       StunAttribute::CreateUInt32(cricket::STUN_ATTR_OPTIONS);
521     options2_attr->SetValue(0x01);
522     response.AddAttribute(options2_attr);
523
524     int_conn->SendStun(response);
525   }
526 }
527
528 void RelayServer::AddConnection(RelayServerConnection* conn) {
529   ASSERT(connections_.find(conn->addr_pair()) == connections_.end());
530   connections_[conn->addr_pair()] = conn;
531 }
532
533 void RelayServer::RemoveConnection(RelayServerConnection* conn) {
534   ConnectionMap::iterator iter = connections_.find(conn->addr_pair());
535   ASSERT(iter != connections_.end());
536   connections_.erase(iter);
537 }
538
539 void RelayServer::RemoveBinding(RelayServerBinding* binding) {
540   BindingMap::iterator iter = bindings_.find(binding->username());
541   ASSERT(iter != bindings_.end());
542   bindings_.erase(iter);
543
544   if (log_bindings_) {
545     LOG(LS_INFO) << "Removed binding " << binding->username() << ", "
546                  << bindings_.size() << " remaining";
547   }
548 }
549
550 void RelayServer::OnMessage(talk_base::Message *pmsg) {
551   ASSERT(pmsg->message_id == kMessageAcceptConnection);
552   talk_base::MessageData* data = pmsg->pdata;
553   talk_base::AsyncSocket* socket =
554       static_cast <talk_base::TypedMessageData<talk_base::AsyncSocket*>*>
555       (data)->data();
556   AcceptConnection(socket);
557   delete data;
558 }
559
560 void RelayServer::OnTimeout(RelayServerBinding* binding) {
561   // This call will result in all of the necessary clean-up. We can't call
562   // delete here, because you can't delete an object that is signaling you.
563   thread_->Dispose(binding);
564 }
565
566 void RelayServer::AcceptConnection(talk_base::AsyncSocket* server_socket) {
567   // Check if someone is trying to connect to us.
568   talk_base::SocketAddress accept_addr;
569   talk_base::AsyncSocket* accepted_socket =
570       server_socket->Accept(&accept_addr);
571   if (accepted_socket != NULL) {
572     // We had someone trying to connect, now check which protocol to
573     // use and create a packet socket.
574     ASSERT(server_sockets_[server_socket] == cricket::PROTO_TCP ||
575            server_sockets_[server_socket] == cricket::PROTO_SSLTCP);
576     if (server_sockets_[server_socket] == cricket::PROTO_SSLTCP) {
577       accepted_socket = new talk_base::AsyncSSLServerSocket(accepted_socket);
578     }
579     talk_base::AsyncTCPSocket* tcp_socket =
580         new talk_base::AsyncTCPSocket(accepted_socket, false);
581
582     // Finally add the socket so it can start communicating with the client.
583     AddInternalSocket(tcp_socket);
584   }
585 }
586
587 RelayServerConnection::RelayServerConnection(
588     RelayServerBinding* binding, const talk_base::SocketAddressPair& addrs,
589     talk_base::AsyncPacketSocket* socket)
590   : binding_(binding), addr_pair_(addrs), socket_(socket), locked_(false) {
591   // The creation of a new connection constitutes a use of the binding.
592   binding_->NoteUsed();
593 }
594
595 RelayServerConnection::~RelayServerConnection() {
596   // Remove this connection from the server's map (if it exists there).
597   binding_->server()->RemoveConnection(this);
598 }
599
600 void RelayServerConnection::Send(const char* data, size_t size) {
601   // Note that the binding has been used again.
602   binding_->NoteUsed();
603
604   cricket::Send(socket_, data, size, addr_pair_.source());
605 }
606
607 void RelayServerConnection::Send(
608     const char* data, size_t size, const talk_base::SocketAddress& from_addr) {
609   // If the from address is known to the client, we don't need to send it.
610   if (locked() && (from_addr == default_dest_)) {
611     Send(data, size);
612     return;
613   }
614
615   // Wrap the given data in a data-indication packet.
616
617   RelayMessage msg;
618   msg.SetType(STUN_DATA_INDICATION);
619
620   StunByteStringAttribute* magic_cookie_attr =
621       StunAttribute::CreateByteString(cricket::STUN_ATTR_MAGIC_COOKIE);
622   magic_cookie_attr->CopyBytes(binding_->magic_cookie().c_str(),
623                                binding_->magic_cookie().size());
624   msg.AddAttribute(magic_cookie_attr);
625
626   StunAddressAttribute* addr_attr =
627       StunAttribute::CreateAddress(STUN_ATTR_SOURCE_ADDRESS2);
628   addr_attr->SetIP(from_addr.ipaddr());
629   addr_attr->SetPort(from_addr.port());
630   msg.AddAttribute(addr_attr);
631
632   StunByteStringAttribute* data_attr =
633       StunAttribute::CreateByteString(STUN_ATTR_DATA);
634   ASSERT(size <= 65536);
635   data_attr->CopyBytes(data, uint16(size));
636   msg.AddAttribute(data_attr);
637
638   SendStun(msg);
639 }
640
641 void RelayServerConnection::SendStun(const StunMessage& msg) {
642   // Note that the binding has been used again.
643   binding_->NoteUsed();
644
645   cricket::SendStun(msg, socket_, addr_pair_.source());
646 }
647
648 void RelayServerConnection::SendStunError(
649       const StunMessage& request, int error_code, const char* error_desc) {
650   // An error does not indicate use.  If no legitimate use off the binding
651   // occurs, we want it to be cleaned up even if errors are still occuring.
652
653   cricket::SendStunError(
654       request, socket_, addr_pair_.source(), error_code, error_desc,
655       binding_->magic_cookie());
656 }
657
658 void RelayServerConnection::Lock() {
659   locked_ = true;
660 }
661
662 void RelayServerConnection::Unlock() {
663   locked_ = false;
664 }
665
666 // IDs used for posted messages:
667 const uint32 MSG_LIFETIME_TIMER = 1;
668
669 RelayServerBinding::RelayServerBinding(
670     RelayServer* server, const std::string& username,
671     const std::string& password, uint32 lifetime)
672   : server_(server), username_(username), password_(password),
673     lifetime_(lifetime) {
674   // For now, every connection uses the standard magic cookie value.
675   magic_cookie_.append(
676       reinterpret_cast<const char*>(TURN_MAGIC_COOKIE_VALUE),
677       sizeof(TURN_MAGIC_COOKIE_VALUE));
678
679   // Initialize the last-used time to now.
680   NoteUsed();
681
682   // Set the first timeout check.
683   server_->thread()->PostDelayed(lifetime_, this, MSG_LIFETIME_TIMER);
684 }
685
686 RelayServerBinding::~RelayServerBinding() {
687   // Clear the outstanding timeout check.
688   server_->thread()->Clear(this);
689
690   // Clean up all of the connections.
691   for (size_t i = 0; i < internal_connections_.size(); ++i)
692     delete internal_connections_[i];
693   for (size_t i = 0; i < external_connections_.size(); ++i)
694     delete external_connections_[i];
695
696   // Remove this binding from the server's map.
697   server_->RemoveBinding(this);
698 }
699
700 void RelayServerBinding::AddInternalConnection(RelayServerConnection* conn) {
701   internal_connections_.push_back(conn);
702 }
703
704 void RelayServerBinding::AddExternalConnection(RelayServerConnection* conn) {
705   external_connections_.push_back(conn);
706 }
707
708 void RelayServerBinding::NoteUsed() {
709   last_used_ = talk_base::Time();
710 }
711
712 bool RelayServerBinding::HasMagicCookie(const char* bytes, size_t size) const {
713   if (size < 24 + magic_cookie_.size()) {
714     return false;
715   } else {
716     return 0 == std::memcmp(
717         bytes + 24, magic_cookie_.c_str(), magic_cookie_.size());
718   }
719 }
720
721 RelayServerConnection* RelayServerBinding::GetInternalConnection(
722     const talk_base::SocketAddress& ext_addr) {
723
724   // Look for an internal connection that is locked to this address.
725   for (size_t i = 0; i < internal_connections_.size(); ++i) {
726     if (internal_connections_[i]->locked() &&
727         (ext_addr == internal_connections_[i]->default_destination()))
728       return internal_connections_[i];
729   }
730
731   // If one was not found, we send to the first connection.
732   ASSERT(internal_connections_.size() > 0);
733   return internal_connections_[0];
734 }
735
736 RelayServerConnection* RelayServerBinding::GetExternalConnection(
737     const talk_base::SocketAddress& ext_addr) {
738   for (size_t i = 0; i < external_connections_.size(); ++i) {
739     if (ext_addr == external_connections_[i]->addr_pair().source())
740       return external_connections_[i];
741   }
742   return 0;
743 }
744
745 void RelayServerBinding::OnMessage(talk_base::Message *pmsg) {
746   if (pmsg->message_id == MSG_LIFETIME_TIMER) {
747     ASSERT(!pmsg->pdata);
748
749     // If the lifetime timeout has been exceeded, then send a signal.
750     // Otherwise, just keep waiting.
751     if (talk_base::Time() >= last_used_ + lifetime_) {
752       LOG(LS_INFO) << "Expiring binding " << username_;
753       SignalTimeout(this);
754     } else {
755       server_->thread()->PostDelayed(lifetime_, this, MSG_LIFETIME_TIMER);
756     }
757
758   } else {
759     ASSERT(false);
760   }
761 }
762
763 }  // namespace cricket