summaryrefslogtreecommitdiff
path: root/tests/check/transmitter/stunalternd.c
blob: 32dc809f118514eac5a5ca6c31e255b3c8a579f7 (plain)
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
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
266
267
268
269
270
271
272
273
274
275
276
277
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
327
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
/* Farstream unit tests for FsRawUdpTransmitter
 * This file is taken from the Nice GLib ICE library. 
 *
 * (C) 2007-2009 Nokia Corporation
 *  @contributor: RĂ©mi Denis-Courmont
 * (C) 2008-2009 Collabora Ltd
 *  @author: Youness Alaoui <youness.alaoui@collabora.co.uk>
 *  @author: Olivier Crete <olivier.crete@collabora.co.uk>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA
 */

#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>

#include <sys/types.h>

#include <sys/socket.h>
#include <netinet/in.h>

#include <unistd.h>
#include <getopt.h>
#include <errno.h>
#include <limits.h>

#include <pthread.h>

#ifndef SOL_IP
# define SOL_IP IPPROTO_IP
#endif

#ifndef SOL_IPV6
# define SOL_IPV6 IPPROTO_IPV6
#endif

#ifndef IPV6_RECVPKTINFO
# define IPV6_RECVPKTINFO IPV6_PKTINFO
#endif

/** Default port for STUN binding discovery */
#define IPPORT_STUN  3478

#include <stun/stunagent.h>
#include "stunalternd.h"

static const uint16_t known_attributes[] =  {
  0
};

/**
 * Creates a listening socket
 */
int listen_socket (GSocketFamily fam, int type, int proto, unsigned int port)
{
  int yes = 1;
  int fd = socket (fam, type, proto);
  union {
    struct sockaddr addr;
    struct sockaddr_in in;
    struct sockaddr_in6 in6;
    struct sockaddr_storage storage;
  } addr;
  socklen_t socklen;

  if (fd == -1)
  {
    perror ("Error creating socket");
    return -1;
  }
  if (fd < 3)
    goto error;

  memset (&addr, 0, sizeof (addr));

  switch (fam)
  {
    case G_SOCKET_FAMILY_IPV4:
      addr.storage.ss_family = AF_INET;
      addr.in.sin_port = htons (port);
      socklen = sizeof (struct sockaddr_in);
      break;

    case G_SOCKET_FAMILY_IPV6:
      addr.storage.ss_family = AF_INET6;
      addr.in6.sin6_port = htons (port);
      socklen = sizeof (struct sockaddr_in6);
      break;
    default:
      socklen = 0;
      g_assert_not_reached ();
  }

  if (bind (fd, (struct sockaddr *)&addr, socklen))
  {
    perror ("Error binding to port");
    goto error;
  }

  if ((type == SOCK_DGRAM) || (type == SOCK_RAW))
  {
    switch (fam)
    {
      case AF_INET:
#ifdef IP_RECVERR
        setsockopt (fd, SOL_IP, IP_RECVERR, &yes, sizeof (yes));
#endif
        break;
      case AF_INET6:
#ifdef IPV6_RECVERR
        setsockopt (fd, SOL_IPV6, IPV6_RECVERR, &yes, sizeof (yes));
#endif
        break;
      default:
        g_assert_not_reached ();
        break;
    }
  }
  else
  {
    if (listen (fd, INT_MAX))
    {
      perror ("Error listening on port");
      goto error;
    }
  }

  return fd;

error:
  close (fd);
  return -1;
}


/** Dequeue error from a socket if applicable */
static int recv_err (int fd)
{
  struct msghdr hdr;
#ifdef MSG_ERRQUEUE
  memset (&hdr, 0, sizeof (hdr));
  return recvmsg (fd, &hdr, MSG_ERRQUEUE) >= 0;
#endif
}


/** Receives a message or dequeues an error from a socket */
ssize_t recv_safe (int fd, struct msghdr *msg)
{
  ssize_t len = recvmsg (fd, msg, 0);
  if (len == -1)
    recv_err (fd);
  else
  if (msg->msg_flags & MSG_TRUNC)
  {
    errno = EMSGSIZE;
    return -1;
  }

  return len;
}


/** Sends a message through a socket */
ssize_t send_safe (int fd, const struct msghdr *msg)
{
  ssize_t len;

  do
    len = sendmsg (fd, msg, 0);
  while ((len == -1) && (recv_err (fd) == 0));

  return len;
}


static int dgram_process (int sock, StunAgent *oldagent, StunAgent *newagent,
    struct sockaddr *alt_addr, socklen_t alt_addr_len)
{
  struct sockaddr_storage addr;
  uint8_t buf[STUN_MAX_MESSAGE_SIZE];
  char ctlbuf[256];
  struct iovec iov = { buf, sizeof (buf) };
  StunMessage request;
  StunMessage response;
  StunValidationStatus validation;
  StunAgent *agent = NULL;

  struct msghdr mh =
  {
    .msg_name = (struct sockaddr *)&addr,
    .msg_namelen = sizeof (addr),
    .msg_iov = &iov,
    .msg_iovlen = 1,
    .msg_control = ctlbuf,
    .msg_controllen = sizeof (ctlbuf)
  };

  size_t len = recv_safe (sock, &mh);
  if (len == (size_t)-1)
    return -1;

  validation = stun_agent_validate (newagent, &request, buf, len, NULL, 0);

  if (validation == STUN_VALIDATION_SUCCESS) {
    agent = newagent;
  }
  else {
    validation = stun_agent_validate (oldagent, &request, buf, len, NULL, 0);
    agent = oldagent;
  }

  /* Unknown attributes */
  if (validation == STUN_VALIDATION_UNKNOWN_REQUEST_ATTRIBUTE)
  {
    stun_agent_build_unknown_attributes_error (agent, &response, buf,
        sizeof (buf), &request);
    goto send_buf;
  }

  /* Mal-formatted packets */
  if (validation != STUN_VALIDATION_SUCCESS ||
      stun_message_get_class (&request) != STUN_REQUEST) {
    return -1;
  }

  switch (stun_message_get_method (&request))
  {
    case STUN_BINDING:
      stun_agent_init_error (agent, &response, buf, sizeof (buf), &request,
          STUN_ERROR_TRY_ALTERNATE);
      stun_message_append_addr (&response, STUN_ATTRIBUTE_ALTERNATE_SERVER,
          alt_addr, alt_addr_len);
      break;

    default:
      stun_agent_init_error (agent, &response, buf, sizeof (buf),
          &request, STUN_ERROR_BAD_REQUEST);
  }

  iov.iov_len = stun_agent_finish_message (agent, &response, NULL, 0);
send_buf:

  len = send_safe (sock, &mh);
  return (len < iov.iov_len) ? -1 : 0;
}



static int
resolve_addr (char *server, unsigned int port, GSocketFamily family,
    struct sockaddr *addr, socklen_t *addr_len)
{
  GInetAddress *inetaddr;
  GSocketAddress *sockaddr;
  gboolean ret;

  inetaddr = g_inet_address_new_from_string (server);

  if (!inetaddr)
    return 0;

  if (g_inet_address_get_family (inetaddr) != family) {
    g_object_unref (inetaddr);
    return 0;
  }

  sockaddr = g_inet_socket_address_new (inetaddr, port);

  ret = g_socket_address_to_native (sockaddr, addr,
      sizeof(struct sockaddr_storage), NULL);

  g_object_unref (sockaddr);
  g_object_unref (inetaddr);

  return ret;
}

struct thread_data {
  pthread_t thread;
  struct sockaddr_storage alt_addr;
  socklen_t alt_addr_len;
  StunAgent oldagent;
  StunAgent newagent;
  int sock;
};

void * stund_thread (void *data)
{
  struct thread_data *td = data;

  pthread_setcanceltype (PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  pthread_setcancelstate (PTHREAD_CANCEL_ENABLE, NULL);

  for (;;)
    dgram_process (td->sock, &td->oldagent, &td->newagent,
        (struct sockaddr*) &td->alt_addr, td->alt_addr_len);


  return NULL;
}

void *stun_alternd_init (GSocketFamily family, char *redirect_ip,
    unsigned int redirect_port,
    unsigned int listen_port)
{
  struct thread_data *td;

  td = malloc (sizeof(struct thread_data));

  if (!redirect_port)
    redirect_port = IPPORT_STUN;

  if (!listen_port)
    listen_port = IPPORT_STUN;

  if (!resolve_addr (redirect_ip, redirect_port, family,
          (struct sockaddr *)&td->alt_addr, &td->alt_addr_len))
  {
    free (td);
    return NULL;
  }

  td->sock = listen_socket (family, SOCK_DGRAM, IPPROTO_UDP, listen_port);
  if (td->sock == -1)
  {
    free (td);
    return NULL;
  }

  stun_agent_init (&td->oldagent, known_attributes,
      STUN_COMPATIBILITY_RFC3489, 0);
  stun_agent_init (&td->newagent, known_attributes,
      STUN_COMPATIBILITY_RFC5389, STUN_AGENT_USAGE_USE_FINGERPRINT);

  pthread_create (&td->thread, NULL, stund_thread, td);

  return td;
}


void stun_alternd_stop (void *data)
{
  struct thread_data *td = data;

  pthread_cancel (td->thread);
  pthread_join (td->thread, NULL);
  free (data);
}