bind.c 13.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/*
 * This file is part of the Nice GLib ICE library.
 *
 * (C) 2007 Nokia Corporation. All rights reserved.
 *  Contact: Rémi Denis-Courmont
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is the Nice GLib ICE library.
 *
 * The Initial Developers of the Original Code are Collabora Ltd and Nokia
 * Corporation. All Rights Reserved.
 *
 * Contributors:
 *   Rémi Denis-Courmont, Nokia
 *
 * Alternatively, the contents of this file may be used under the terms of the
 * the GNU Lesser General Public License Version 2.1 (the "LGPL"), in which
 * case the provisions of LGPL are applicable instead of those above. If you
 * wish to allow use of your version of this file only under the terms of the
 * LGPL and not to allow others to use your version of this file under the
 * MPL, indicate your decision by deleting the provisions above and replace
 * them with the notice and other provisions required by the LGPL. If you do
 * not delete the provisions above, a recipient may use your version of this
 * file under either the MPL or the LGPL.
 */

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

40
41
#ifdef _WIN32
#include <winsock2.h>
42
#include <ws2tcpip.h>
43
#include "win32_common.h"
44
#define close closesocket
45
#else
46
47
#include <sys/types.h>
#include <sys/socket.h>
48
49
#include <netinet/in.h>
#include <stdint.h>
50
51
#include <stdbool.h>
#include <unistd.h>
52
#include <errno.h>
53
#include <sys/time.h>
54
#endif
55

56
57
58
59
60
61

#ifdef HAVE_POLL
# include <poll.h>
#endif


62
#include "bind.h"
63
#include "stun/stunagent.h"
64
65
66
67
68
69
70

#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <errno.h>
#include <fcntl.h>
Youness Alaoui's avatar
Youness Alaoui committed
71
#include "timer.h"
72
73


74

75

Youness Alaoui's avatar
Youness Alaoui committed
76
/** Non-blocking mode STUN binding discovery */
77

Youness Alaoui's avatar
Youness Alaoui committed
78
79
size_t stun_usage_bind_create (StunAgent *agent, StunMessage *msg,
    uint8_t *buffer, size_t buffer_len)
80
{
Youness Alaoui's avatar
Youness Alaoui committed
81
  stun_agent_init_request (agent, msg, buffer, buffer_len, STUN_BINDING);
82

Youness Alaoui's avatar
Youness Alaoui committed
83
  return stun_agent_finish_message (agent, msg, NULL, 0);
84
85
}

Youness Alaoui's avatar
Youness Alaoui committed
86
87
88
StunUsageBindReturn stun_usage_bind_process (StunMessage *msg,
    struct sockaddr *addr, socklen_t *addrlen,
    struct sockaddr *alternate_server, socklen_t *alternate_server_len)
89
{
90
91
  int code = -1;
  StunMessageReturn val;
92

93
  if (stun_message_get_method (msg) != STUN_BINDING)
94
    return STUN_USAGE_BIND_RETURN_INVALID;
95

Youness Alaoui's avatar
Youness Alaoui committed
96
  switch (stun_message_get_class (msg))
97
  {
Youness Alaoui's avatar
Youness Alaoui committed
98
99
    case STUN_REQUEST:
    case STUN_INDICATION:
100
      return STUN_USAGE_BIND_RETURN_INVALID;
Youness Alaoui's avatar
Youness Alaoui committed
101
102

    case STUN_RESPONSE:
103
      break;
Youness Alaoui's avatar
Youness Alaoui committed
104
105

    case STUN_ERROR:
106
      if (stun_message_find_error (msg, &code) != STUN_MESSAGE_RETURN_SUCCESS) {
Youness Alaoui's avatar
Youness Alaoui committed
107
        /* missing ERROR-CODE: ignore message */
108
        return STUN_USAGE_BIND_RETURN_INVALID;
Youness Alaoui's avatar
Youness Alaoui committed
109
110
111
112
113
114
115
116
      }

      /* NOTE: currently we ignore unauthenticated messages if the context
       * is authenticated, for security reasons. */
      stun_debug (" STUN error message received (code: %d)\n", code);

      /* ALTERNATE-SERVER mechanism */
      if ((code / 100) == 3) {
117
118
        if (alternate_server && alternate_server_len) {
          if (stun_message_find_addr (msg, STUN_ATTRIBUTE_ALTERNATE_SERVER,
119
120
                  alternate_server,
                  alternate_server_len) != STUN_MESSAGE_RETURN_SUCCESS) {
121
122
123
124
125
126
127
128
            stun_debug (" Unexpectedly missing ALTERNATE-SERVER attribute\n");
            return STUN_USAGE_BIND_RETURN_ERROR;
          }
        } else {
          if (!stun_message_has_attribute (msg, STUN_ATTRIBUTE_ALTERNATE_SERVER)) {
            stun_debug (" Unexpectedly missing ALTERNATE-SERVER attribute\n");
            return STUN_USAGE_BIND_RETURN_ERROR;
          }
Youness Alaoui's avatar
Youness Alaoui committed
129
130
131
132
133
134
135
        }

        stun_debug ("Found alternate server\n");
        return STUN_USAGE_BIND_RETURN_ALTERNATE_SERVER;

      }
      return STUN_USAGE_BIND_RETURN_ERROR;
136
137
  }

Youness Alaoui's avatar
Youness Alaoui committed
138
139
140
  stun_debug ("Received %u-bytes STUN message\n", stun_message_length (msg));

  val = stun_message_find_xor_addr (msg,
141
      STUN_ATTRIBUTE_XOR_MAPPED_ADDRESS, addr, addrlen);
142
  if (val != STUN_MESSAGE_RETURN_SUCCESS)
143
  {
144
    stun_debug (" No XOR-MAPPED-ADDRESS: %d\n", val);
Youness Alaoui's avatar
Youness Alaoui committed
145
    val = stun_message_find_addr (msg,
146
        STUN_ATTRIBUTE_MAPPED_ADDRESS, addr, addrlen);
147
    if (val != STUN_MESSAGE_RETURN_SUCCESS)
148
    {
149
      stun_debug (" No MAPPED-ADDRESS: %d\n", val);
Youness Alaoui's avatar
Youness Alaoui committed
150
      return STUN_USAGE_BIND_RETURN_ERROR;
151
152
153
    }
  }

154
  stun_debug (" Mapped address found!\n");
Youness Alaoui's avatar
Youness Alaoui committed
155
156
  return STUN_USAGE_BIND_RETURN_SUCCESS;

157
158
}

159

Youness Alaoui's avatar
Youness Alaoui committed
160
/** Binding keep-alive (Binding discovery indication!) */
161

Youness Alaoui's avatar
Youness Alaoui committed
162
163
164
size_t
stun_usage_bind_keepalive (StunAgent *agent, StunMessage *msg,
    uint8_t *buf, size_t len)
165
{
166

Youness Alaoui's avatar
Youness Alaoui committed
167
168
169
  stun_agent_init_indication (agent, msg,
      buf, len, STUN_BINDING);
  return stun_agent_finish_message (agent, msg, NULL, 0);
170
171
}

172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265


typedef struct stun_trans_s
{

  int fd;
  int own_fd;
  socklen_t dstlen;
  struct sockaddr_storage dst;
} StunTransport;


typedef enum {
  STUN_USAGE_TRANS_RETURN_SUCCESS,
  STUN_USAGE_TRANS_RETURN_ERROR,
  STUN_USAGE_TRANS_RETURN_RETRY,
  STUN_USAGE_TRANS_RETURN_INVALID_ADDRESS,
  STUN_USAGE_TRANS_RETURN_UNSUPPORTED,
} StunUsageTransReturn;




static StunUsageTransReturn
stun_trans_init (StunTransport *tr, int fd,
    const struct sockaddr *srv, socklen_t srvlen)
{
  assert (fd != -1);

  if ((size_t) srvlen > sizeof (tr->dst))
    return STUN_USAGE_TRANS_RETURN_INVALID_ADDRESS;

  tr->own_fd = -1;
  tr->fd = fd;

  tr->dstlen = srvlen;
  memcpy (&tr->dst, srv, srvlen);

  return STUN_USAGE_TRANS_RETURN_SUCCESS;
}


/*
 * Creates and connects a socket. This is useful when a socket is to be used
 * for multiple consecutive transactions (e.g. TURN).
 */
static int stun_socket (int family, int type, int proto)
{
  int fd = socket (family, type, proto);
  if (fd == -1)
    return -1;

#ifdef FD_CLOEXEC
  fcntl (fd, F_SETFD, fcntl (fd, F_GETFD) | FD_CLOEXEC);
#endif
#ifdef O_NONBLOCK
  fcntl (fd, F_SETFL, fcntl (fd, F_GETFL) | O_NONBLOCK);
#endif

#ifdef MSG_ERRQUEUE
  if (type == SOCK_DGRAM)
  {
    /* Linux specifics for ICMP errors on non-connected sockets */
    int yes = 1;
    switch (family)
    {
      case AF_INET:
        setsockopt (fd, SOL_IP, IP_RECVERR, &yes, sizeof (yes));
        break;
      case AF_INET6:
        setsockopt (fd, SOL_IPV6, IPV6_RECVERR, &yes, sizeof (yes));
        break;
    }
  }
#endif

  return fd;
}


static StunUsageTransReturn
stun_trans_create (StunTransport *tr, int type, int proto,
    const struct sockaddr *srv, socklen_t srvlen)
{
  StunUsageTransReturn val = STUN_USAGE_TRANS_RETURN_ERROR;
  int fd;

  if ((size_t) srvlen < sizeof(*srv))
    return STUN_USAGE_TRANS_RETURN_INVALID_ADDRESS;

  fd = stun_socket (srv->sa_family, type, proto);
  if (fd == -1)
    return STUN_USAGE_TRANS_RETURN_ERROR;

266
267
  if (type != SOCK_DGRAM) {
    if (connect (fd, srv, srvlen) &&
268
#ifdef _WIN32
269
        (WSAGetLastError () != WSAEINPROGRESS)) {
270
#else
271
      (errno != EINPROGRESS)) {
272
#endif
273
274
275
276
277
      goto error;
    }
    val = stun_trans_init (tr, fd, NULL, 0);
  } else {
    val = stun_trans_init (tr, fd, srv, srvlen);
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
  }

  if (val)
    goto error;

  tr->own_fd = tr->fd;
  return STUN_USAGE_TRANS_RETURN_SUCCESS;

error:
  close (fd);
  return val;
}


static void stun_trans_deinit (StunTransport *tr)
{
  int saved = errno;

  assert (tr->fd != -1);

  if (tr->own_fd != -1)
    close (tr->own_fd);

  tr->own_fd = -1;
  tr->fd = -1;

  errno = saved;
}


#ifndef MSG_DONTWAIT
# define MSG_DONTWAIT 0
#endif
#ifndef MSG_NOSIGNAL
# define MSG_NOSIGNAL 0
#endif


static int stun_err_dequeue (int fd)
{
#ifdef MSG_ERRQUEUE
  struct msghdr hdr;
  int saved_errno = errno, ret;

  memset (&hdr, 0, sizeof (hdr));
  ret = (recvmsg (fd, &hdr, MSG_ERRQUEUE) >= 0);
  errno = saved_errno;
  return ret;
#else
327
  (void) fd;
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
  return 0;
#endif
}


static ssize_t
stun_trans_sendto (StunTransport *tr, const uint8_t *buf, size_t len,
                     const struct sockaddr *dst, socklen_t dstlen)
{
  static const int flags = MSG_DONTWAIT | MSG_NOSIGNAL;
  ssize_t val;

  do
  {
    if (dstlen > 0)
      val = sendto (tr->fd, (void *)buf, len, flags, dst, dstlen);
    else
      val = send (tr->fd, (void *)buf, len, flags);
  }
  while ((val == -1) && stun_err_dequeue (tr->fd));

  return val;
}


static ssize_t
stun_trans_recvfrom (StunTransport *tr, uint8_t *buf, size_t maxlen,
                       struct sockaddr * dst,
                       socklen_t * dstlen)
{
  static const int flags = MSG_DONTWAIT | MSG_NOSIGNAL;
  ssize_t val;

  if (dstlen != NULL)
    val = recvfrom (tr->fd, (void *)buf, maxlen, flags, dst, dstlen);
  else
    val = recv (tr->fd, (void *)buf, maxlen, flags);

  if (val == -1)
    stun_err_dequeue (tr->fd);

  return val;
}


static ssize_t
stun_trans_send (StunTransport *tr, const uint8_t *buf, size_t len)
{
  return stun_trans_sendto (tr, buf, len,
      (struct sockaddr *)&tr->dst, tr->dstlen);
}

static ssize_t
stun_trans_recv (StunTransport *tr, uint8_t *buf, size_t maxlen)
{
  return stun_trans_recvfrom (tr, buf, maxlen, NULL, NULL);
}


static int stun_trans_fd (const StunTransport *tr)
{
  assert (tr != NULL);
  return tr->fd;
}


/**
 * Waits for a response or timeout to occur.
 *
 * @return ETIMEDOUT if the transaction has timed out, or 0 if an incoming
 * message needs to be processed.
 */
static StunUsageTransReturn
stun_trans_poll (StunTransport *tr, unsigned int delay)
{
#ifdef HAVE_POLL
  struct pollfd ufd;

  memset (&ufd, 0, sizeof (ufd));
  ufd.fd = stun_trans_fd (tr);

  ufd.events |= POLLIN;

  if (poll (&ufd, 1, delay) <= 0) {
    return STUN_USAGE_TRANS_RETURN_RETRY;
  }

  return STUN_USAGE_TRANS_RETURN_SUCCESS;
#else
  (void)tr;
  return STUN_USAGE_TRANS_RETURN_UNSUPPORTED;
#endif
}



Youness Alaoui's avatar
Youness Alaoui committed
424
425
426
/** Blocking mode STUN binding discovery */
StunUsageBindReturn stun_usage_bind_run (const struct sockaddr *srv,
    socklen_t srvlen, struct sockaddr *addr, socklen_t *addrlen)
427
{
428
429
  StunTimer timer;
  StunTransport trans;
430
  StunAgent agent;
Youness Alaoui's avatar
Youness Alaoui committed
431
432
  StunMessage req;
  uint8_t req_buf[STUN_MAX_MESSAGE_SIZE];
433
  StunMessage msg;
Youness Alaoui's avatar
Youness Alaoui committed
434
435
436
  uint8_t buf[STUN_MAX_MESSAGE_SIZE];
  StunValidationStatus valid;
  size_t len;
437
  StunUsageTransReturn ret;
438
  int val;
Youness Alaoui's avatar
Youness Alaoui committed
439
440
441
442
443
  struct sockaddr_storage alternate_server;
  socklen_t alternate_server_len = sizeof (alternate_server);
  StunUsageBindReturn bind_ret;

  stun_agent_init (&agent, STUN_ALL_KNOWN_ATTRIBUTES,
444
      STUN_COMPATIBILITY_RFC3489, 0);
Youness Alaoui's avatar
Youness Alaoui committed
445
446
447
448

  len = stun_usage_bind_create (&agent, &req, req_buf, sizeof(req_buf));

  ret = stun_trans_create (&trans, SOCK_DGRAM, 0, srv, srvlen);
449
  if (ret != STUN_USAGE_TRANS_RETURN_SUCCESS) {
Youness Alaoui's avatar
Youness Alaoui committed
450
451
    stun_debug ("STUN transaction failed: couldn't create transport.\n");
    return STUN_USAGE_BIND_RETURN_ERROR;
452
  }
453

Youness Alaoui's avatar
Youness Alaoui committed
454
455
456
457
  val = stun_trans_send (&trans, req_buf, len);
  if (val < -1) {
    stun_debug ("STUN transaction failed: couldn't send request.\n");
    return STUN_USAGE_BIND_RETURN_ERROR;
458
459
  }

Youness Alaoui's avatar
Youness Alaoui committed
460
461
462
  stun_timer_start (&timer);
  stun_debug ("STUN transaction started (timeout %dms).\n",
      stun_timer_remainder (&timer));
463

Youness Alaoui's avatar
Youness Alaoui committed
464
  do
465
  {
Youness Alaoui's avatar
Youness Alaoui committed
466
467
468
    for (;;) {
      unsigned delay = stun_timer_remainder (&timer);
      ret = stun_trans_poll (&trans, delay);
469
      if (ret == STUN_USAGE_TRANS_RETURN_RETRY) {
Youness Alaoui's avatar
Youness Alaoui committed
470
        switch (stun_timer_refresh (&timer)) {
471
          case STUN_USAGE_TIMER_RETURN_TIMEOUT:
Youness Alaoui's avatar
Youness Alaoui committed
472
473
            stun_debug ("STUN transaction failed: time out.\n");
            return STUN_USAGE_BIND_RETURN_TIMEOUT; // fatal error!
474
          case STUN_USAGE_TIMER_RETURN_RETRANSMIT:
Youness Alaoui's avatar
Youness Alaoui committed
475
476
477
478
479
480
481
482
            stun_debug ("STUN transaction retransmitted (timeout %dms).\n",
                stun_timer_remainder (&timer));
            val = stun_trans_send (&trans, req_buf, len);
            if (val <  -1) {
              stun_debug ("STUN transaction failed: couldn't resend request.\n");
              return STUN_USAGE_BIND_RETURN_ERROR;
            }
            continue;
483
484
          case STUN_USAGE_TIMER_RETURN_SUCCESS:
            break;
Youness Alaoui's avatar
Youness Alaoui committed
485
486
487
488
489
490
491
        }
      }
      val = stun_trans_recv (&trans, buf, sizeof (buf));
      if (val >= 0) {
        break;
      }
    }
492

Youness Alaoui's avatar
Youness Alaoui committed
493
494
495
496
497
    valid = stun_agent_validate (&agent, &msg, buf, val, NULL, NULL);
    if (valid == STUN_VALIDATION_UNKNOWN_ATTRIBUTE)
      return STUN_USAGE_BIND_RETURN_ERROR;

    if (valid != STUN_VALIDATION_SUCCESS) {
498
      ret = STUN_USAGE_TRANS_RETURN_RETRY;
Youness Alaoui's avatar
Youness Alaoui committed
499
500
501
502
503
504
505
506
507
    } else {
      bind_ret = stun_usage_bind_process (&msg, addr, addrlen,
          (struct sockaddr *) &alternate_server, &alternate_server_len);
      if (bind_ret == STUN_USAGE_BIND_RETURN_ALTERNATE_SERVER) {
        stun_trans_deinit (&trans);

        ret = stun_trans_create (&trans, SOCK_DGRAM, 0,
            (struct sockaddr *) &alternate_server, alternate_server_len);

508
        if (ret != STUN_USAGE_TRANS_RETURN_SUCCESS) {
Youness Alaoui's avatar
Youness Alaoui committed
509
510
511
512
513
514
515
516
          return STUN_USAGE_BIND_RETURN_ERROR;
        }

        val = stun_trans_send (&trans, req_buf, len);
        if (val < -1)
          return STUN_USAGE_BIND_RETURN_ERROR;

        stun_timer_start (&timer);
517
        ret = STUN_USAGE_TRANS_RETURN_RETRY;
518
      } else if (bind_ret ==  STUN_USAGE_BIND_RETURN_INVALID) {
519
        ret = STUN_USAGE_TRANS_RETURN_RETRY;
Youness Alaoui's avatar
Youness Alaoui committed
520
      } else {
521
        break;
Youness Alaoui's avatar
Youness Alaoui committed
522
523
      }
    }
524
  }
525
  while (ret == STUN_USAGE_TRANS_RETURN_RETRY);
526

527
  return bind_ret;
528
}