stun.c 80.5 KB
Newer Older
Pekka Pessi's avatar
Pekka Pessi committed
1 2 3
/*
 * This file is part of the Sofia-SIP package
 *
4
 * Copyright (C) 2005-2006 Nokia Corporation.
Pekka Pessi's avatar
Pekka Pessi committed
5 6 7
 *
 * Contact: Pekka Pessi <pekka.pessi@nokia.com>
 *
8
 * This library is free software; you can redistribute it and/or
Pekka Pessi's avatar
Pekka Pessi committed
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 * 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 St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

25
/**@internal
Pekka Pessi's avatar
Pekka Pessi committed
26 27
 * @file stun.c STUN client module
 *
28
 * See RFC 3489/3489bis for further information.
Pekka Pessi's avatar
Pekka Pessi committed
29
 *
30
 * @author Martti Mela <Martti.Mela@nokia.com>
31
 * @author Tat Chan <Tat.Chan@nokia.com>
Pekka Pessi's avatar
Pekka Pessi committed
32 33
 * @author Pekka Pessi <Pekka.Pessi@nokia.com>
 * @author Kai Vehmanen <Kai.Vehmanen@nokia.com>
34
 *
Pekka Pessi's avatar
Pekka Pessi committed
35 36 37
 * @date Created: Thu Jul 24 17:21:00 2003 ppessi
 */

38
#include "config.h"
Pekka Pessi's avatar
Pekka Pessi committed
39

40
#include <assert.h>
41
#include <string.h>
42
#include <time.h>
Michael Jerris's avatar
Michael Jerris committed
43
#include <stdlib.h>
44

45
#define SU_ROOT_MAGIC_T struct stun_magic_t
46

47
#include <sofia-sip/stun.h>
48
#include "stun_internal.h"
49
#include <sofia-sip/stun_tag.h>
Pekka Pessi's avatar
Pekka Pessi committed
50

51 52 53 54 55
#include <sofia-sip/su_alloc.h>
#include <sofia-sip/su_tagarg.h>
#include <sofia-sip/su_log.h>
#include <sofia-sip/su.h>
#include <sofia-sip/su_localinfo.h>
Pekka Pessi's avatar
Pekka Pessi committed
56

57 58 59 60
#if HAVE_NETINET_TCP_H
#include <netinet/tcp.h>
#endif

61
#if HAVE_OPENSSL
Pekka Pessi's avatar
Pekka Pessi committed
62
#include <openssl/opensslv.h>
Martti Mela's avatar
Martti Mela committed
63
#endif
Pekka Pessi's avatar
Pekka Pessi committed
64

Pekka Pessi's avatar
Pekka Pessi committed
65 66 67 68 69
/* Missing socket symbols */
#ifndef SOL_TCP
#define SOL_TCP IPPROTO_TCP
#endif

70 71 72 73 74 75 76
#if HAVE_FUNC
#elif HAVE_FUNCTION
#define __func__ __FUNCTION__
#else
static char const __func__[] = "stun";
#endif

77 78 79 80
#ifndef SU_DEBUG
#define SU_DEBUG 3
#endif

Pekka Pessi's avatar
Pekka Pessi committed
81
/** STUN log. */
82
su_log_t stun_log[] = { SU_LOG_INIT("stun", "STUN_DEBUG", SU_DEBUG) };
83

Pekka Pessi's avatar
Pekka Pessi committed
84
/**@var char const STUN_DEBUG[]
85 86 87 88 89
 *
 * Environment variable determining the debug log level for @b stun module.
 *
 * The STUN_DEBUG environment variable is used to determine the debug logging
 * level for @b stun module. The default level is 3.
90
 *
91 92
 * @sa <sofia-sip/su_debug.h>, stun_log, SOFIA_DEBUG
 */
Pekka Pessi's avatar
Pekka Pessi committed
93
extern char const STUN_DEBUG[];
Pekka Pessi's avatar
Pekka Pessi committed
94

95
enum {
96
  STUN_SENDTO_TIMEOUT = 1000,
97
  STUN_TLS_CONNECT_TIMEOUT = 8000,
98 99
};

100 101 102
/**
 * States of STUN requests. See stun_state_e for states
 * discovery processes.
103
 */
104 105 106 107 108 109 110 111 112
typedef enum stun_req_state_e {
  stun_req_no_assigned_event,
  stun_req_dispose_me,            /**< request can be disposed */
  stun_req_discovery_init,
  stun_req_discovery_processing,

  stun_req_error,
  stun_req_timeout
} stun_req_state_t;
113

114 115 116
#define CHG_IP		0x001
#define CHG_PORT	0x004

117 118 119 120 121 122 123 124 125 126
#define x_insert(l, n, x) \
 ((l) ? (l)->x##_prev = &(n)->x##_next : 0, \
  (n)->x##_next = (l), (n)->x##_prev = &(l), (l) = (n))

#define x_remove(n, x) \
  ((*(n)->x##_prev = (n)->x##_next) ? \
   (n)->x##_next->x##_prev = (n)->x##_prev : 0)

#define x_is_inserted(n, x) ((n)->x##_prev != NULL)

127
struct stun_discovery_s {
128
  stun_discovery_t   *sd_next, **sd_prev; /**< Linked list */
129

130 131 132
  stun_handle_t          *sd_handle;
  stun_discovery_f        sd_callback;
  stun_discovery_magic_t *sd_magic;
133

134 135 136
  tagi_t          *sd_tags;          /** stored tags for the discovery */


137 138 139 140 141 142 143 144 145 146
  su_addrinfo_t    sd_pri_info;      /**< server primary info */
  su_sockaddr_t    sd_pri_addr[1];   /**< server primary address */

  su_addrinfo_t    sd_sec_info;      /**< server secondary info */
  su_sockaddr_t    sd_sec_addr[1];   /**< server secondary address */

  stun_action_t    sd_action;        /**< My action */
  stun_state_t     sd_state;         /**< Progress states */

  su_socket_t      sd_socket;        /**< target socket */
147 148
  su_sockaddr_t    sd_bind_addr[1]; /**< local address */

149
  su_socket_t      sd_socket2;       /**< Alternative socket */
150

151
  int              sd_index;         /**< root_register index */
152

Martti Mela's avatar
Martti Mela committed
153
  /* Binding discovery */
154
  su_sockaddr_t    sd_addr_seen_outside[1];   /**< local address */
Martti Mela's avatar
Martti Mela committed
155

156
  /* NAT type related */
157
  stun_nattype_t   sd_nattype;       /**< Determined NAT type */
158 159
  int              sd_mapped_addr_match; /** Mapped addresses match? */
  int              sd_first;         /**< These are the requests  */
160 161 162
  int              sd_second;
  int              sd_third;
  int              sd_fourth;
163 164 165 166 167

  /* Life time related */
  int              sd_lt_cur;
  int              sd_lt;
  int              sd_lt_max;
168 169 170 171

  /* Keepalive timeout */
  unsigned int     sd_timeout;
  su_timer_t      *sd_timer;
172 173
};

174
struct stun_request_s {
175
  su_timer_t       *sr_timer;
176 177 178 179
  stun_request_t   *sr_next, **sr_prev; /**< Linked list */
  stun_msg_t       *sr_msg;             /**< STUN message pointer */
  stun_handle_t    *sr_handle;          /**< backpointer, STUN object */

180
  su_socket_t       sr_socket;          /**< Alternative socket */
181 182
  su_localinfo_t    sr_localinfo;       /**< local addrinfo */
  su_sockaddr_t     sr_local_addr[1];   /**< local address */
183
  su_sockaddr_t     sr_destination[1];
184

185
  stun_req_state_t  sr_state;           /**< Progress states */
186 187
  int               sr_retry_count;     /**< current retry number */
  long              sr_timeout;         /**< timeout for next sendto() */
188 189

  int               sr_from_y;
190 191 192
  int               sr_request_mask;    /**< Mask consisting of chg_ip and chg_port */
  stun_discovery_t *sr_discovery;
};
193

Martti Mela's avatar
Martti Mela committed
194
struct stun_handle_s
Pekka Pessi's avatar
Pekka Pessi committed
195
{
196 197 198
  su_home_t       sh_home[1];
  su_root_t      *sh_root;          /**< event loop */
  int             sh_root_index;    /**< object index of su_root_register() */
199

200
  stun_request_t *sh_requests; /**< outgoing requests list */
201
  stun_discovery_t *sh_discoveries; /**< Actions list */
202

203
  int             sh_max_retries;   /**< max resend for sendto() */
204

205 206
  su_addrinfo_t   sh_pri_info;      /**< server primary info */
  su_sockaddr_t   sh_pri_addr[1];   /**< server primary address */
207

208 209
  su_addrinfo_t   sh_sec_info;      /**< server secondary info */
  su_sockaddr_t   sh_sec_addr[1];   /**< server secondary address */
210

211 212
  su_localinfo_t  sh_localinfo;     /**< local addrinfo */
  su_sockaddr_t   sh_local_addr[1]; /**< local address */
213

214 215
  char           *sh_domain;        /**< domain address for DNS-SRV lookups */

216
  stun_dns_lookup_t  *sh_dns_lookup;
217
  stun_action_t       sh_dns_pend_action;
218 219 220
  stun_discovery_f    sh_dns_pend_cb;
  stun_discovery_magic_t *sh_dns_pend_ctx;
  tagi_t             *sh_dns_pend_tags;
221

222
#if HAVE_OPENSSL
223 224
  SSL_CTX        *sh_ctx;           /**< SSL context for TLS */
  SSL            *sh_ssl;           /**< SSL handle for TLS */
Martti Mela's avatar
Martti Mela committed
225 226 227 228 229
#else
  void           *sh_ctx;           /**< SSL context for TLS */
  void           *sh_ssl;           /**< SSL handle for TLS */
#endif

230 231
  stun_msg_t      sh_tls_request;
  stun_msg_t      sh_tls_response;
232
  int             sh_nattype;       /**< NAT-type, see stun_common.h */
233

234 235
  stun_buffer_t   sh_username;
  stun_buffer_t   sh_passwd;
236

237 238
  int             sh_use_msgint;    /**< try message integrity (TLS) */
  int             sh_req_msgint;    /**< require use of msg-int (TLS) */
Pekka Pessi's avatar
Pekka Pessi committed
239 240
};

241

242 243
#define STUN_STATE_STR(x) case x: return #x

244
char const *stun_str_state(stun_state_t state)
245 246 247
{
  switch (state) {
  STUN_STATE_STR(stun_no_assigned_event);
248
  /* STUN_STATE_STR(stun_req_dispose_me); */
249 250 251 252 253
  STUN_STATE_STR(stun_tls_connecting);
  STUN_STATE_STR(stun_tls_writing);
  STUN_STATE_STR(stun_tls_closing);
  STUN_STATE_STR(stun_tls_reading);
  STUN_STATE_STR(stun_tls_done);
254 255
  /* STUN_STATE_STR(stun_req_discovery_init); */
  /* STUN_STATE_STR(stun_req_discovery_processing); */
256
  STUN_STATE_STR(stun_discovery_done);
257 258 259
  STUN_STATE_STR(stun_tls_connection_timeout);
  STUN_STATE_STR(stun_tls_connection_failed);
  STUN_STATE_STR(stun_tls_ssl_connect_failed);
260
  STUN_STATE_STR(stun_discovery_timeout);
261
  /* STUN_STATE_STR(stun_req_timeout); */
262

263 264 265 266 267
  case stun_error:
  default: return "stun_error";
  }
}

268
/**
269
 * Returns the NAT type attached to STUN discovery handle.
270 271 272
 *
 * @see stun_nattype_str().
 * @see stun_test_nattype().
273
 */
274
char const *stun_nattype_str(stun_discovery_t *sd)
275
{
276 277 278 279 280
  char const *stun_nattype_str[] = {
    "NAT type undetermined",
    "Open Internet",
    "UDP traffic is blocked or server unreachable",
    "Symmetric UDP Firewall",
281 282 283 284 285 286
    "Full-Cone NAT (endpoint independent filtering and mapping)",
    "Restricted Cone NAT (endpoint independent mapping)",
    "Port Restricted Cone NAT (endpoint independent mapping)",
    "Endpoint independent filtering, endpoint dependent mapping",
    "Address dependent filtering, endpoint dependent mapping",
    "Symmetric NAT (address and port dependent filtering, endpoint dependent mapping)",
287 288
  };

289 290 291 292
  if (sd)
    return stun_nattype_str[sd->sd_nattype];
  else
    return stun_nattype_str[stun_nat_unknown];
293 294
}

295 296
/**
 * Returns the detected NAT type.
297
 *
298 299 300 301 302 303 304 305 306 307 308
 * @see stun_nattype_str().
 * @see stun_test_nattype().
 */
stun_nattype_t stun_nattype(stun_discovery_t *sd)
{
  if (!sd)
    return stun_nat_unknown;

  return sd->sd_nattype;
}

309 310 311 312
su_addrinfo_t const *stun_server_address(stun_handle_t *sh)
{
  return &sh->sh_pri_info;
}
313

314 315
int stun_lifetime(stun_discovery_t *sd)
{
316
  return sd ? sd->sd_lt_cur : -1;
317 318 319
}


320
#if HAVE_OPENSSL
321
char const stun_version[] =
Pekka Pessi's avatar
Pekka Pessi committed
322
 "sofia-sip-stun using " OPENSSL_VERSION_TEXT;
Martti Mela's avatar
Martti Mela committed
323
#else
324
char const stun_version[] =
Martti Mela's avatar
Martti Mela committed
325 326
 "sofia-sip-stun";
#endif
Pekka Pessi's avatar
Pekka Pessi committed
327

328
static int do_action(stun_handle_t *sh, stun_msg_t *binding_response);
329
#if HAVE_OPENSSL
330
static int stun_tls_callback(su_root_magic_t *m, su_wait_t *w, su_wakeup_arg_t *arg);
331
#endif
332 333 334 335 336 337 338 339
static int process_binding_request(stun_request_t *req, stun_msg_t *binding_response);
static stun_discovery_t *stun_discovery_create(stun_handle_t *sh,
					       stun_action_t action,
					       stun_discovery_f sdf,
					       stun_discovery_magic_t *magic);
static int stun_discovery_destroy(stun_discovery_t *sd);
static int action_bind(stun_request_t *req, stun_msg_t *binding_response);
static int action_determine_nattype(stun_request_t *req, stun_msg_t *binding_response);
340
static int process_test_lifetime(stun_request_t *req, stun_msg_t *binding_response);
341 342 343

static stun_request_t *stun_request_create(stun_discovery_t *sd);
static int stun_send_binding_request(stun_request_t *req,
344
			      su_sockaddr_t *srvr_addr);
345
static int stun_bind_callback(stun_magic_t *m, su_wait_t *w, su_wakeup_arg_t *arg);
346

347
#if defined (__CYGWIN__)
348
static int get_localinfo(int family, su_sockaddr_t *su, socklen_t *return_len);
349
#endif
350

351
/* timers */
352
static void stun_sendto_timer_cb(su_root_magic_t *magic,
353 354
				 su_timer_t *t,
				 su_timer_arg_t *arg);
355
#if HAVE_OPENSSL
356
static void stun_tls_connect_timer_cb(su_root_magic_t *magic,
357 358
				      su_timer_t *t,
				      su_timer_arg_t *arg);
359
#endif
360
static void stun_test_lifetime_timer_cb(su_root_magic_t *magic,
361 362
					su_timer_t *t,
					su_timer_arg_t *arg);
363
static void stun_keepalive_timer_cb(su_root_magic_t *magic,
364 365 366 367 368
				    su_timer_t *t,
				    su_timer_arg_t *arg);


static int priv_stun_bind_send(stun_handle_t *sh, stun_request_t *req, stun_discovery_t *sd);
369 370 371 372 373
static int priv_dns_queue_action(stun_handle_t *sh,
				 stun_action_t action,
				 stun_discovery_f sdf,
				 stun_discovery_magic_t *magic,
				 tag_type_t tag, tag_value_t value, ...);
Martti Mela's avatar
Martti Mela committed
374 375 376

/**
 * Return su_root_t assigned to stun_handle_t.
377
 *
Martti Mela's avatar
Martti Mela committed
378
 * @param self stun_handle_t object
379 380
 * @return su_root_t object, NULL if self not given.
 */
381
su_root_t *stun_root(stun_handle_t *self)
382
{
383
  return self ? self->sh_root : NULL;
384 385 386
}


Pekka Pessi's avatar
Pekka Pessi committed
387
/**
Martti Mela's avatar
Martti Mela committed
388
 * Check if a STUN handle should be created.
Pekka Pessi's avatar
Pekka Pessi committed
389
 *
390 391
 * Return true if STUNTAG_SERVER() or STUNTAG_DOMAIN() tags have
 * been specified, or otherwise if STUN_SERVER environment variable
392 393 394 395 396
 * is set.
 *
 * @TAGS
 * @TAG STUNTAG_DOMAIN() domain to use in DNS-SRV based STUN server
 * @TAG STUNTAG_SERVER() stun server hostname or dotted IPv4 address
Pekka Pessi's avatar
Pekka Pessi committed
397 398 399 400 401 402
 *
 * @param tag,value,... tag-value list
 */
int stun_is_requested(tag_type_t tag, tag_value_t value, ...)
{
  ta_list ta;
403
  tagi_t const *t, *t2;
Pekka Pessi's avatar
Pekka Pessi committed
404 405
  char const *stun_server;

Martti Mela's avatar
Martti Mela committed
406
  enter;
Martti Mela's avatar
Martti Mela committed
407

Pekka Pessi's avatar
Pekka Pessi committed
408 409
  ta_start(ta, tag, value);
  t = tl_find(ta_args(ta), stuntag_server);
410
  t2 = tl_find(ta_args(ta), stuntag_domain);
411
  if (t && t->t_value)
412 413
    stun_server = (char *)t->t_value;
  else if (t2 && t2->t_value)
414
    stun_server = (char *)t2->t_value;
415 416
  else
    stun_server = getenv("STUN_SERVER");
Pekka Pessi's avatar
Pekka Pessi committed
417 418 419 420 421
  ta_end(ta);

  return stun_server != NULL;
}

422

423
/**
424 425
 * Creates a STUN handle.
 *
426
 * The created handles can be used for STUN binding discovery,
427 428 429
 * keepalives, and other STUN usages.
 *
 * @param root eventloop to used by the stun state machine
430
 * @param tag,value,... tag-value list
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
 *
 * @TAGS
 * @TAG STUNTAG_DOMAIN() domain to use in DNS-SRV based STUN server
 * @TAG STUNTAG_SERVER() stun server hostname or dotted IPv4 address
 * @TAG STUNTAG_REQUIRE_INTEGRITY() true if msg integrity should be
 * used enforced
 *
 */
stun_handle_t *stun_handle_init(su_root_t *root,
				tag_type_t tag, tag_value_t value, ...)
{
  stun_handle_t *stun = NULL;
  char const *server = NULL, *domain = NULL;
  int req_msg_integrity = 1;
  int err;
  ta_list ta;
447

448 449 450 451 452 453 454 455 456 457
  enter;

  ta_start(ta, tag, value);

  tl_gets(ta_args(ta),
	  STUNTAG_SERVER_REF(server),
	  STUNTAG_DOMAIN_REF(domain),
	  STUNTAG_REQUIRE_INTEGRITY_REF(req_msg_integrity),
	  TAG_END());

458 459
  ta_end(ta);

460 461 462 463 464 465 466 467 468 469 470 471 472
  stun = su_home_clone(NULL, sizeof(*stun));

  if (!stun) {
    SU_DEBUG_3(("%s: %s failed\n", __func__, "su_home_clone()"));
    return NULL;
  }

  /* Enviroment overrides */
  if (getenv("STUN_SERVER")) {
    server = getenv("STUN_SERVER");
    SU_DEBUG_5(("%s: using STUN_SERVER=%s\n", __func__, server));
  }

473
  SU_DEBUG_5(("%s(\"%s\"): called\n",
474 475 476
	      __func__, server));

  /* fail, if no server or a domain for a DNS-SRV lookup is specified */
477 478
  if (!server && !domain) {
    errno = ENOENT;
479
    return NULL;
480
  }
481

482 483 484 485 486 487 488 489 490 491 492
  stun->sh_pri_info.ai_addrlen = 16;
  stun->sh_pri_info.ai_addr = &stun->sh_pri_addr->su_sa;

  stun->sh_sec_info.ai_addrlen = 16;
  stun->sh_sec_info.ai_addr = &stun->sh_sec_addr->su_sa;

  stun->sh_localinfo.li_addrlen = 16;
  stun->sh_localinfo.li_addr = stun->sh_local_addr;

  stun->sh_domain = su_strdup(stun->sh_home, domain);
  stun->sh_dns_lookup = NULL;
493

494
  if (server) {
495
    err = stun_atoaddr(stun->sh_home, AF_INET, &stun->sh_pri_info, server);
496 497
    if (err < 0) {
      errno = ENOENT;
498
      return NULL;
499
    }
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
  }

  stun->sh_nattype = stun_nat_unknown;

  stun->sh_root     = root;
  /* always try TLS: */
  stun->sh_use_msgint = 1;
  /* whether use of shared-secret msgint is required */
  stun->sh_req_msgint = req_msg_integrity;

  stun->sh_max_retries = STUN_MAX_RETRX;

  /* initialize username and password */
  stun_init_buffer(&stun->sh_username);
  stun_init_buffer(&stun->sh_passwd);
515

516
  stun->sh_nattype = stun_nat_unknown;
517

518 519
  /* initialize random number generator */
  srand(time(NULL));
520

521 522 523
  return stun;
}

524
/**
525 526 527 528
 * Performs shared secret request/response processing.
 * Result will be trigged in STUN handle callback (state
 * one of stun_tls_*).
 **/
529 530 531 532
int stun_obtain_shared_secret(stun_handle_t *sh,
			      stun_discovery_f sdf,
			      stun_discovery_magic_t *magic,
			      tag_type_t tag, tag_value_t value, ...)
Martti Mela's avatar
Martti Mela committed
533
{
534
#if HAVE_OPENSSL
Martti Mela's avatar
Martti Mela committed
535 536 537
  int events = -1;
  int one, err = -1;
  su_wait_t wait[1] = { SU_WAIT_INIT };
538
  su_socket_t s = INVALID_SOCKET;
Martti Mela's avatar
Martti Mela committed
539 540
  int family;
  su_addrinfo_t *ai = NULL;
541
  stun_discovery_t *sd;
Martti Mela's avatar
Martti Mela committed
542
  /* stun_request_t *req; */
Martti Mela's avatar
Martti Mela committed
543

544 545
  ta_list ta;

Martti Mela's avatar
Martti Mela committed
546
  assert(sh);
Martti Mela's avatar
Martti Mela committed
547

Martti Mela's avatar
Martti Mela committed
548
  enter;
Martti Mela's avatar
Martti Mela committed
549

550 551
  if (!sh->sh_pri_addr[0].su_port) {
    /* no STUN server address, perform a DNS-SRV lookup */
552

553 554
    ta_list ta;
    ta_start(ta, tag, value);
555
    SU_DEBUG_5(("Delaying STUN shared-secret req. for DNS-SRV query.\n"));
556 557
    err = priv_dns_queue_action(sh, stun_action_tls_query, sdf, magic, ta_tags(ta));
    ta_end(ta);
558

559
    return err;
560 561
  }

Martti Mela's avatar
Martti Mela committed
562 563 564
  ai = &sh->sh_pri_info;

  if (sh->sh_use_msgint == 1) {
565
    SU_DEBUG_3(("%s: Obtaining shared secret.\n", __func__));
Martti Mela's avatar
Martti Mela committed
566 567 568 569 570 571 572 573 574
  }
  else {
    SU_DEBUG_3(("No message integrity enabled.\n"));
    return errno = EFAULT, -1;
  }

  /* open tcp connection to server */
  s = su_socket(family = AF_INET, SOCK_STREAM, 0);

575
  if (s == INVALID_SOCKET) {
576
    return STUN_ERROR(errno, socket);
Martti Mela's avatar
Martti Mela committed
577 578 579 580
  }

  /* asynchronous connect() */
  if (su_setblocking(s, 0) < 0) {
581
    return STUN_ERROR(errno, su_setblocking);
Martti Mela's avatar
Martti Mela committed
582
  }
583

Martti Mela's avatar
Martti Mela committed
584 585
  if (setsockopt(s, SOL_TCP, TCP_NODELAY,
		 (void *)&one, sizeof one) == -1) {
586
    return STUN_ERROR(errno, setsockopt);
Martti Mela's avatar
Martti Mela committed
587 588 589 590
  }

  /* Do an asynchronous connect(). Three error codes are ok,
   * others cause return -1. */
591
  if (connect(s, (struct sockaddr *) &sh->sh_pri_addr,
Martti Mela's avatar
Martti Mela committed
592 593 594
	      ai->ai_addrlen) == SOCKET_ERROR) {
    err = su_errno();
    if (err != EINPROGRESS && err != EAGAIN && err != EWOULDBLOCK) {
595
      return STUN_ERROR(err, connect);
Martti Mela's avatar
Martti Mela committed
596 597 598 599 600
    }
  }

  SU_DEBUG_9(("%s: %s: %s\n", __func__, "connect",
	      su_strerror(err)));
601

602
  sd = stun_discovery_create(sh, stun_action_tls_query, sdf, magic);
Martti Mela's avatar
Martti Mela committed
603
  sd->sd_socket = s;
Martti Mela's avatar
Martti Mela committed
604
  /* req = stun_request_create(sd); */
Martti Mela's avatar
Martti Mela committed
605

Martti Mela's avatar
Martti Mela committed
606
  events = SU_WAIT_CONNECT | SU_WAIT_ERR;
Martti Mela's avatar
Martti Mela committed
607
  if (su_wait_create(wait, s, events) == -1)
608
    return STUN_ERROR(errno, su_wait_create);
Martti Mela's avatar
Martti Mela committed
609

Martti Mela's avatar
Martti Mela committed
610
  /* su_root_eventmask(sh->sh_root, sh->sh_root_index, s, events); */
611 612

  if ((sd->sd_index =
Martti Mela's avatar
Martti Mela committed
613
       su_root_register(sh->sh_root, wait, stun_tls_callback, (su_wakeup_arg_t *) sd, 0)) == -1) {
614
    return STUN_ERROR(errno, su_root_register);
Martti Mela's avatar
Martti Mela committed
615 616
  }

617 618 619 620
  ta_start(ta, tag, value);
  sd->sd_tags = tl_adup(sh->sh_home, ta_args(ta));
  ta_end(ta);

621
  sd->sd_state = stun_tls_connecting;
Martti Mela's avatar
Martti Mela committed
622 623 624 625

  /* Create and start timer for connect() timeout */
  SU_DEBUG_3(("%s: creating timeout timer for connect()\n", __func__));

626 627
  sd->sd_timer = su_timer_create(su_root_task(sh->sh_root),
				 STUN_TLS_CONNECT_TIMEOUT);
Martti Mela's avatar
Martti Mela committed
628

629
  su_timer_set(sd->sd_timer, stun_tls_connect_timer_cb, (su_wakeup_arg_t *) sd);
Martti Mela's avatar
Martti Mela committed
630 631

  return 0;
632 633 634
#else /* !HAVE_OPENSSL */
  return -1;
#endif
Martti Mela's avatar
Martti Mela committed
635 636
}

637
static stun_request_t *stun_request_create(stun_discovery_t *sd)
638
{
639
  stun_handle_t *sh = sd->sd_handle;
640 641
  stun_request_t *req = NULL;

Martti Mela's avatar
Martti Mela committed
642
  enter;
Martti Mela's avatar
Martti Mela committed
643

644
  req = calloc(sizeof(stun_request_t), 1);
645 646
  if (!req)
    return NULL;
647

648
  req->sr_handle = sh;
649
  req->sr_discovery = sd;
650 651

  /* This is the default */
652
  req->sr_socket = sd->sd_socket;
653

654 655
  req->sr_localinfo.li_addrlen = sizeof(su_sockaddr_t);
  req->sr_localinfo.li_addr = req->sr_local_addr;
656

657 658 659
  /* default timeout for next sendto() */
  req->sr_timeout = STUN_SENDTO_TIMEOUT;
  req->sr_retry_count = 0;
660
  /* req->sr_action = action; */
661
  req->sr_request_mask = 0;
662

663
  req->sr_msg = calloc(sizeof(stun_msg_t), 1);
664

665
  req->sr_state = stun_req_discovery_init;
666
  memcpy(req->sr_local_addr, sd->sd_bind_addr, sizeof(su_sockaddr_t));
667

668
  /* Insert this request to the request queue */
669
  x_insert(sh->sh_requests, req, sr);
670

671 672 673
  return req;
}

674
void stun_request_destroy(stun_request_t *req)
675
{
676
  stun_handle_t *sh;
677 678
  assert(req);

Martti Mela's avatar
Martti Mela committed
679
  enter;
Martti Mela's avatar
Martti Mela committed
680

681 682
  sh = req->sr_handle;

683 684 685
  if (x_is_inserted(req, sr))
    x_remove(req, sr);

686
  req->sr_handle = NULL;
687
  req->sr_discovery = NULL;
688
  /* memset(req->sr_destination, 0, sizeof(su_sockaddr_t)); */
689

690 691 692 693 694 695 696 697 698 699
  if (req->sr_timer) {
    su_timer_destroy(req->sr_timer);
    req->sr_timer = NULL;
    SU_DEBUG_7(("%s: timer destroyed.\n", __func__));
  }

  if (req->sr_msg) {
    free(req->sr_msg);
    req->sr_msg = NULL;
  }
700

701
  free(req);
702 703 704

  SU_DEBUG_9(("%s: request destroyed.\n", __func__));

705 706 707
  return;
}

708

709
/** Destroy a STUN client */
Martti Mela's avatar
Martti Mela committed
710
void stun_handle_destroy(stun_handle_t *sh)
711
{
712
  stun_discovery_t *sd = NULL, *kill = NULL;
713
  stun_request_t *a, *b;
Pekka Pessi's avatar
Pekka Pessi committed
714

Martti Mela's avatar
Martti Mela committed
715
  enter;
Martti Mela's avatar
Martti Mela committed
716

717 718
  if (sh->sh_dns_lookup)
    stun_dns_lookup_destroy(sh->sh_dns_lookup);
719

720 721 722
  if (sh->sh_dns_pend_tags)
    su_free(sh->sh_home, sh->sh_dns_pend_tags);

723 724 725 726 727 728 729
  for (a = sh->sh_requests; a; ) {
    b = a->sr_next;
    stun_request_destroy(a);
    a = b;
  }


Martti Mela's avatar
Martti Mela committed
730 731
  /* There can be several discoveries using the same socket. It is
     still enough to deregister the socket in first of them */
732 733 734
  for (sd = sh->sh_discoveries; sd; ) {
    kill = sd;
    sd = sd->sd_next;
735

736 737 738
    /* Index has same value as sockfd, right? ... or not? */
    if (kill->sd_index != -1)
      su_root_deregister(sh->sh_root, kill->sd_index);
739 740
    if (kill->sd_action == stun_action_tls_query)
      su_close(kill->sd_socket);
741 742

    stun_discovery_destroy(kill);
Martti Mela's avatar
Martti Mela committed
743
  }
Martti Mela's avatar
Martti Mela committed
744

745 746 747 748 749
  stun_free_message(&sh->sh_tls_request);
  stun_free_message(&sh->sh_tls_response);
  stun_free_buffer(&sh->sh_username);
  stun_free_buffer(&sh->sh_passwd);

Martti Mela's avatar
Martti Mela committed
750
  su_home_zap(sh->sh_home);
Martti Mela's avatar
Martti Mela committed
751 752
}

Pekka Pessi's avatar
Pekka Pessi committed
753

754
/** Create wait object and register it to the handle callback */
755
static
756
int assign_socket(stun_discovery_t *sd, su_socket_t s, int register_socket)
757
{
758
  stun_handle_t *sh = sd->sd_handle;
759
  int events;
Martti Mela's avatar
Martti Mela committed
760
  stun_discovery_t *tmp;
761
  /* su_localinfo_t clientinfo[1]; */
762 763
  su_sockaddr_t su[1];
  socklen_t sulen;
764
  char addr[SU_ADDRSIZE];
765
  int err;
766

767 768
  su_wait_t wait[1] = { SU_WAIT_INIT };

Martti Mela's avatar
Martti Mela committed
769 770
  enter;

771
  if (s == INVALID_SOCKET) {
772
    SU_DEBUG_3(("%s: invalid socket\n", __func__));
773 774 775
    return errno = EINVAL, -1;
  }

Martti Mela's avatar
Martti Mela committed
776
  for (tmp = sh->sh_discoveries; tmp; tmp = tmp->sd_next) {
777 778 779 780 781 782
    if (tmp->sd_socket == s) {
      sd->sd_socket = s;
      sd->sd_index = tmp->sd_index;
      memcpy(sd->sd_bind_addr, tmp->sd_bind_addr, sizeof(su_sockaddr_t));
      return 0;
    }
Martti Mela's avatar
Martti Mela committed
783
  }
784
  sd->sd_socket = s;
Martti Mela's avatar
Martti Mela committed
785

786
  if (!register_socket)
787 788
    return 0;

789 790
  /* set socket asynchronous */
  if (su_setblocking(s, 0) < 0) {
791
    return STUN_ERROR(errno, su_setblocking);
792 793
  }

794
  /* xxx -- check if socket is already assigned to this root */
795

796
  memset(su, 0, sulen = sizeof su);
797

798 799
  /* Try to bind it if not already bound */
  if (getsockname(s, &su->su_sa, &sulen) == -1 || su->su_port == 0) {
Martti Mela's avatar
Martti Mela committed
800

801 802
    sulen = su->su_len = sizeof su->su_sin;
    su->su_family = AF_INET;
803 804

#if defined (__CYGWIN__)
805
    get_localinfo(AF_INET, su, &sulen);
806 807
#endif

808
    if ((err = bind(s, &su->su_sa, sulen)) < 0) {
809
      SU_DEBUG_3(("%s: bind(%s:%u): %s\n",  __func__,
Michael Jerris's avatar
Michael Jerris committed
810
		  su_inet_ntop(su->su_family, SU_ADDR(su), addr, sizeof(addr)),
811 812
		  (unsigned) ntohs(su->su_port),
		  su_strerror(su_errno())));
813 814 815
      return -1;
    }

816 817 818
    if (getsockname(s, &su->su_sa, &sulen) == -1) {
      return STUN_ERROR(errno, getsockname);
    }
819 820
  }

821
  memcpy(&sd->sd_bind_addr, su, sulen);
822 823

  SU_DEBUG_3(("%s: local socket is bound to %s:%u\n", __func__,
Michael Jerris's avatar
Michael Jerris committed
824
	      su_inet_ntop(su->su_family, SU_ADDR(su), addr, sizeof(addr)),
825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
	      (unsigned) ntohs(su->su_port)));

  events = SU_WAIT_IN | SU_WAIT_ERR;

  if (su_wait_create(wait, s, events) == -1) {
    return STUN_ERROR(su_errno(), su_wait_create);
  }

  /* Register receiving function with events specified above */
  if ((sd->sd_index = su_root_register(sh->sh_root,
				       wait, stun_bind_callback,
				       (su_wakeup_arg_t *) sd, 0)) < 0) {
    return STUN_ERROR(errno, su_root_register);
  }

  SU_DEBUG_7(("%s: socket registered.\n", __func__));
841 842

  return 0;
843 844
}

845

846 847 848 849
/**
 * Helper function needed by Cygwin builds.
 */
#if defined (__CYGWIN__)
850
static int get_localinfo(int family, su_sockaddr_t *su, socklen_t *return_len)
851
{
852 853
  su_localinfo_t hints[1] = {{ LI_CANONNAME | LI_NUMERIC }}, *li, *res = NULL;
  int i, error;
854
  char addr[SU_ADDRSIZE];
855

856
  hints->li_family = family;
857

858
  if ((error = su_getlocalinfo(hints, &res)) == 0) {
859 860
    /* try to bind to the first available address */
    for (i = 0, li = res; li; li = li->li_next) {
861
      if (li->li_family != family)
862
	continue;
863 864 865 866 867 868 869
      if (li->li_scope == LI_SCOPE_HOST)
	continue;

      assert(*return_len >= li->li_addrlen);

      memcpy(su, li->li_addr, *return_len = li->li_addrlen);

870
      SU_DEBUG_3(("%s: using local address %s\n", __func__,
Michael Jerris's avatar
Michael Jerris committed
871
		  su_inet_ntop(family, SU_ADDR(su), addr, sizeof(addr))));
872 873
      break;
    }
874 875

    su_freelocalinfo(res);
876

877 878
    if (!li) {			/* Not found */
      return STUN_ERROR(error, su_getlocalinfo);
879
    }
880 881

    return 0;
882 883
  }
  else {
884
    return STUN_ERROR(error, su_getlocalinfo);
885 886
  }
}
887
#endif
888

889 890 891 892 893 894 895 896
static void priv_lookup_cb(stun_dns_lookup_t *self,
			   stun_magic_t *magic)
{
  const char *udp_target = NULL;
  uint16_t udp_port = 0;
  int res;
  stun_handle_t *sh = (stun_handle_t *)magic;

897
  res = stun_dns_lookup_udp_addr(self, &udp_target, &udp_port);
898
  if (res == 0 && udp_target) {
899
    /* XXX: assumption that same host and port used for UDP/TLS */
900
    stun_atoaddr(sh->sh_home, AF_INET, &sh->sh_pri_info, udp_target);
901 902

    if (udp_port)
903 904 905
      sh->sh_pri_addr[0].su_port = htons(udp_port);
    else
      sh->sh_pri_addr[0].su_port = htons(STUN_DEFAULT_PORT);
906

907
    /* step: now that server address is known, continue
908
     *       the pending action */
909

910 911
    SU_DEBUG_5(("STUN server address found, running queue actions (%d).\n",
		sh->sh_dns_pend_action));
912

913 914 915 916
    switch(sh->sh_dns_pend_action) {
    case stun_action_tls_query:
      stun_obtain_shared_secret(sh, sh->sh_dns_pend_cb, sh->sh_dns_pend_ctx, TAG_NEXT(sh->sh_dns_pend_tags));
      break;
917

918 919 920
    case stun_action_binding_request:
      stun_bind(sh, sh->sh_dns_pend_cb, sh->sh_dns_pend_ctx, TAG_NEXT(sh->sh_dns_pend_tags));
      break;
921

922 923 924
    case stun_action_test_lifetime:
      stun_test_lifetime(sh, sh->sh_dns_pend_cb, sh->sh_dns_pend_ctx, TAG_NEXT(sh->sh_dns_pend_tags));
      break;
925

926 927 928
    case stun_action_test_nattype:
      stun_test_nattype(sh, sh->sh_dns_pend_cb, sh->sh_dns_pend_ctx, TAG_NEXT(sh->sh_dns_pend_tags));
      break;
929

930 931 932
    default:
      SU_DEBUG_5(("Warning: unknown pending STUN DNS-SRV action.\n"));
    }
933
      }
934 935 936 937 938 939
  else {
    /* DNS lookup failed */
    SU_DEBUG_5(("Warning: STUN DNS-SRV lookup failed.\n"));
    if (sh->sh_dns_pend_cb) {
      sh->sh_dns_pend_cb(sh->sh_dns_pend_ctx, sh, NULL,
			 sh->sh_dns_pend_action, stun_error);
940 941
    }
  }
942 943 944 945 946

  su_free(sh->sh_home, sh->sh_dns_pend_tags), sh->sh_dns_pend_tags = NULL;
  sh->sh_dns_pend_action = 0;
  sh->sh_dns_pend_cb = NULL;
  sh->sh_dns_pend_ctx = NULL;
947 948 949
}

/**
950 951
 * Queus a discovery process for later execution when DNS-SRV lookup
 * has been completed.
952
 */
953 954 955 956 957
static int priv_dns_queue_action(stun_handle_t *sh,
				 stun_action_t action,
				 stun_discovery_f sdf,
				 stun_discovery_magic_t *magic,
				 tag_type_t tag, tag_value_t value, ...)
958
{
959
  ta_list ta;
960

961 962 963
  if (!sh->sh_dns_pend_action) {
    if (!sh->sh_dns_lookup) {
      sh->sh_dns_lookup = stun_dns_lookup((stun_magic_t*)sh, sh->sh_root, priv_lookup_cb, sh->sh_domain);
964
      ta_start(ta, tag, value);
965
      assert(sh->sh_dns_pend_tags == NULL);
966
      sh->sh_dns_pend_tags = tl_tlist(sh->sh_home,
967 968 969 970
				      ta_tags(ta));
      ta_end(ta);
      sh->sh_dns_pend_cb = sdf;
      sh->sh_dns_pend_ctx = magic;
971 972

    }
973
    sh->sh_dns_pend_action |= action;
974 975

    return 0;
976
  }
977

978
  return -1;
979 980 981 982 983 984 985 986 987
}

static int priv_stun_bind_send(stun_handle_t *sh, stun_request_t *req, stun_discovery_t *sd)
{
  int res = stun_send_binding_request(req, sh->sh_pri_addr);
  if (res < 0) {
    stun_free_message(req->sr_msg);
    stun_discovery_destroy(sd);
  }
988
  return res;
989 990
}

991
/**
992 993
 * Performs a STUN Binding Discovery (see RFC3489/3489bis) process
 *
994
 * To integrity protect the discovery process, first call
995
 * stun_request_shared_secret() on the handle 'sh'.
Pekka Pessi's avatar
Pekka Pessi committed
996
 *
997 998 999 1000
 * If STUNTAG_REGISTER_SOCKET() is omitted, or set to false, the
 * client is responsible for socket i/o. Other stun module will
 * perform the whole discovery process and return the results
 * via callback 'sdf'.
1001
 *
1002 1003 1004
 * @param sh       pointer to valid stun handle
 * @param sdf      callback to signal process progress
 * @param magic    context pointer attached to 'sdf'
1005
 * @param tag, value, ... list of tagged parameters.
Pekka Pessi's avatar
Pekka Pessi committed
1006
 *
1007
 * @TAGS
1008 1009 1010
 * @TAG STUNTAG_SOCKET() Bind socket handle to STUN (socket handle).
 * @TAG STUNTAG_REGISTER_SOCKET() Register socket for eventloop owned by STUN (boolean)
 *
Pekka Pessi's avatar
Pekka Pessi committed
1011 1012 1013
 * @return
 * On success, zero is returned.  Upon error, -1 is returned, and @e errno is
 * set appropriately.
1014
 *
Pekka Pessi's avatar
Pekka Pessi committed
1015 1016 1017 1018
 * @ERRORS
 * @ERROR EFAULT          An invalid address is given as argument
 * @ERROR EPROTONOSUPPORT Not a UDP socket.
 * @ERROR EINVAL          The socket is already bound to an address.
1019
 * @ERROR EACCESS   	  The address is protected, and the user is not
Pekka Pessi's avatar
Pekka Pessi committed
1020 1021
 *                  	  the super-user.
 * @ERROR ENOTSOCK  	  Argument is a descriptor for a file, not a socket.
1022 1023
 * @ERROR EAGAIN          Operation in progress. Application should call
 *                        stun_bind() again when there is data available on
Pekka Pessi's avatar
Pekka Pessi committed
1024 1025
 *                        the socket.
 */
1026 1027 1028 1029 1030
int stun_bind(stun_handle_t *sh,
	      stun_discovery_f sdf,
	      stun_discovery_magic_t *magic,
	      tag_type_t tag, tag_value_t value,
	      ...)
Pekka Pessi's avatar
Pekka Pessi committed
1031
{
1032
  su_socket_t s = INVALID_SOCKET;
1033
  stun_request_t *req = NULL;
1034
  stun_discovery_t *sd = NULL;
1035
  ta_list ta;
1036
  int s_reg = 0;
1037

Martti Mela's avatar
Martti Mela committed
1038
  enter;
1039 1040 1041

  if (sh == NULL)
    return errno = EFAULT, -1;
1042

1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
  if (!sh->sh_pri_addr[0].su_port) {
    /* no STUN server address, perform a DNS-SRV lookup */
    int err;
    ta_list ta;
    ta_start(ta, tag, value);
    SU_DEBUG_5(("Delaying STUN bind for DNS-SRV query.\n"));
    err = priv_dns_queue_action(sh, stun_action_binding_request, sdf, magic, ta_tags(ta));
    ta_end(ta);
    return err;
  }

1054
  ta_start(ta, tag, value);
Pekka Pessi's avatar
Pekka Pessi committed
1055

1056 1057
  tl_gets(ta_args(ta),
	  STUNTAG_SOCKET_REF(s),
1058
	  STUNTAG_REGISTER_EVENTS_REF(s_reg),
1059 1060
	  TAG_END());

1061 1062
  ta_end(ta);

1063
  sd = stun_discovery_create(sh, stun_action_binding_request, sdf, magic);
1064
  if (assign_socket(sd, s, s_reg) < 0)
1065
    return -1;
1066

1067 1068
  req = stun_request_create(sd);

1069
  if (stun_make_binding_req(sh, req, req->sr_msg, 0, 0) < 0) {
1070
    stun_discovery_destroy(sd);
1071
    stun_free_message(req->sr_msg);
1072
    return -1;
1073
  }
Pekka Pessi's avatar
Pekka Pessi committed
1074

1075 1076
  /* note: we always report success if bind() succeeds */
  return priv_stun_bind_send(sh, req, sd);
Pekka Pessi's avatar
Pekka Pessi committed
1077 1078
}

Martti Mela's avatar
Martti Mela committed
1079

1080
/**
1081 1082 1083 1084 1085
 * Returns the address of the public binding allocated by the NAT.
 *
 * In case of multiple on path NATs, the binding allocated by
 * the outermost NAT is returned.
 *
Martti Mela's avatar
Martti Mela committed
1086 1087 1088
 * This function returns the local address seen from outside.
 * Note that the address is not valid until the event stun_clien_done is launched.
 */
1089 1090 1091
int stun_discovery_get_address(stun_discovery_t *sd,
			       void *addr,
			       socklen_t *return_addrlen)
Martti Mela's avatar
Martti Mela committed
1092
{
1093
  socklen_t siz;
1094

Martti Mela's avatar
Martti Mela committed
1095
  enter;
Martti Mela's avatar
Martti Mela committed
1096

1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
  assert(sd && addr);

  siz = SU_SOCKADDR_SIZE(sd->sd_addr_seen_outside);

  /* Check if enough memory provided */
  if (siz > *return_addrlen)
    return errno = EFAULT, -1;
  else
    *return_addrlen = siz;

  memcpy(addr, sd->sd_addr_seen_outside, siz);
1108

1109
  return 0;
Martti Mela's avatar
Martti Mela committed
1110 1111
}

1112 1113 1114 1115
static stun_discovery_t *stun_discovery_create(stun_handle_t *sh,
					       stun_action_t action,
					       stun_discovery_f sdf,
					       stun_discovery_magic_t *magic)
Martti Mela's avatar
Martti Mela committed
1116
{
1117
  stun_discovery_t *sd = NULL;
Martti Mela's avatar
Martti Mela committed
1118

Martti Mela's avatar
Martti Mela committed
1119
  enter;
Martti Mela's avatar
Martti Mela committed
1120

1121
  sd = calloc(1, sizeof(stun_discovery_t));
Martti Mela's avatar
Martti Mela committed
1122

1123 1124
  sd->sd_action = action;
  sd->sd_handle = sh;
1125 1126
  sd->sd_callback = sdf;
  sd->sd_magic = magic;
1127

1128 1129 1130 1131
  sd->sd_lt_cur = 0;
  sd->sd_lt = STUN_LIFETIME_EST;
  sd->sd_lt_max = STUN_LIFETIME_MAX;

1132
  sd->sd_pri_info.ai_addrlen = sizeof sd->sd_pri_addr->su_sin;
1133 1134 1135
  sd->sd_pri_info.ai_addr = &sd->sd_pri_addr->su_sa;

  /* Insert this action to the discovery queue */
1136
  x_insert(sh->sh_discoveries, sd, sd);
Martti Mela's avatar