~ubuntu-branches/debian/experimental/kopete/experimental

« back to all changes in this revision

Viewing changes to protocols/jabber/googletalk/libjingle/talk/p2p/base/relayserver.cc

  • Committer: Package Import Robot
  • Author(s): Maximiliano Curia
  • Date: 2015-02-24 11:32:57 UTC
  • mfrom: (1.1.41 vivid)
  • Revision ID: package-import@ubuntu.com-20150224113257-gnupg4v7lzz18ij0
Tags: 4:14.12.2-1
* New upstream release (14.12.2).
* Bump Standards-Version to 3.9.6, no changes needed.

Show diffs side-by-side

added added

removed removed

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