stun.c 81.7 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 25 26 27
 * 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
 *
 */

/**
 * @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 34 35 36 37 38 39
 * @author Pekka Pessi <Pekka.Pessi@nokia.com>
 * @author Kai Vehmanen <Kai.Vehmanen@nokia.com>
 * 
 * @date Created: Thu Jul 24 17:21:00 2003 ppessi
 */

#include "config.h" 

40
#include <assert.h>
41
#include <string.h>
42

43
#define SU_ROOT_MAGIC_T struct stun_magic_t
44

45
#include "sofia-sip/stun.h"
46
#include "stun_internal.h"
47
#include "sofia-sip/stun_tag.h"
Pekka Pessi's avatar
Pekka Pessi committed
48

49 50 51 52 53
#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
54

Martti Mela's avatar
Martti Mela committed
55
#if defined(HAVE_OPENSSL)
Pekka Pessi's avatar
Pekka Pessi committed
56
#include <openssl/opensslv.h>
Martti Mela's avatar
Martti Mela committed
57
#endif
Pekka Pessi's avatar
Pekka Pessi committed
58

59 60 61 62
#if !defined(ETIMEDOUT) && defined(_WIN32)
#define ETIMEDOUT WSAETIMEDOUT
#endif

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

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

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

78
enum {
79
  STUN_SENDTO_TIMEOUT = 1000,
80
  STUN_TLS_CONNECT_TIMEOUT = 8000,
81 82
};

83 84 85 86 87 88 89 90 91 92 93 94 95
/**
 * States of STUN requests. See stun_state_e for states
 * discovery processes.
 */ 
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;
96

97 98 99
#define CHG_IP		0x001
#define CHG_PORT	0x004

100 101 102 103 104 105 106 107 108 109
#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)

110
struct stun_discovery_s {
111
  stun_discovery_t   *sd_next, **sd_prev; /**< Linked list */
112

113 114 115
  stun_handle_t          *sd_handle;
  stun_discovery_f        sd_callback;
  stun_discovery_magic_t *sd_magic;
116

117 118 119
  tagi_t          *sd_tags;          /** stored tags for the discovery */


120 121 122 123 124 125 126 127 128 129
  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 */
130 131
  su_sockaddr_t    sd_bind_addr[1]; /**< local address */

132
  su_socket_t      sd_socket2;       /**< Alternative socket */
133

134
  int              sd_index;         /**< root_register index */
135

Martti Mela's avatar
Martti Mela committed
136
  /* Binding discovery */
137
  su_sockaddr_t    sd_addr_seen_outside[1];   /**< local address */
Martti Mela's avatar
Martti Mela committed
138

139
  /* NAT type related */
140
  stun_nattype_t   sd_nattype;       /**< Determined NAT type */
141 142
  int              sd_mapped_addr_match; /** Mapped addresses match? */
  int              sd_first;         /**< These are the requests  */
143 144 145
  int              sd_second;
  int              sd_third;
  int              sd_fourth;
146 147 148 149 150

  /* Life time related */
  int              sd_lt_cur;
  int              sd_lt;
  int              sd_lt_max;
151 152 153 154

  /* Keepalive timeout */
  unsigned int     sd_timeout;
  su_timer_t      *sd_timer;
155 156
};

157
struct stun_request_s {
158
  su_timer_t       *sr_timer;
159 160 161 162
  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 */

163
  su_socket_t       sr_socket;          /**< Alternative socket */
164 165
  su_localinfo_t    sr_localinfo;       /**< local addrinfo */
  su_sockaddr_t     sr_local_addr[1];   /**< local address */
166
  su_sockaddr_t     sr_destination[1];
167

168
  stun_state_t      sr_state;           /**< Progress states */
169 170
  int               sr_retry_count;     /**< current retry number */
  long              sr_timeout;         /**< timeout for next sendto() */
171 172

  int               sr_from_y;
173 174 175
  int               sr_request_mask;    /**< Mask consisting of chg_ip and chg_port */
  stun_discovery_t *sr_discovery;
};
176

Martti Mela's avatar
Martti Mela committed
177
struct stun_handle_s
Pekka Pessi's avatar
Pekka Pessi committed
178
{
179 180 181
  su_home_t       sh_home[1];
  su_root_t      *sh_root;          /**< event loop */
  int             sh_root_index;    /**< object index of su_root_register() */
182

183
  stun_request_t *sh_requests; /**< outgoing requests list */
184
  stun_discovery_t *sh_discoveries; /**< Actions list */
185

186
  int             sh_max_retries;   /**< max resend for sendto() */
187

188 189
  su_addrinfo_t   sh_pri_info;      /**< server primary info */
  su_sockaddr_t   sh_pri_addr[1];   /**< server primary address */
190

191 192
  su_addrinfo_t   sh_sec_info;      /**< server secondary info */
  su_sockaddr_t   sh_sec_addr[1];   /**< server secondary address */
193

194 195
  su_localinfo_t  sh_localinfo;     /**< local addrinfo */
  su_sockaddr_t   sh_local_addr[1]; /**< local address */
196

197 198
  char           *sh_domain;        /**< domain address for DNS-SRV lookups */

199 200
  stun_dns_lookup_t  *sh_dns_lookup;
  stun_action_t       sh_dns_pend_action; 
201 202 203
  stun_discovery_f    sh_dns_pend_cb;
  stun_discovery_magic_t *sh_dns_pend_ctx;
  tagi_t             *sh_dns_pend_tags;
204

Martti Mela's avatar
Martti Mela committed
205
#if defined(HAVE_OPENSSL)
206 207
  SSL_CTX        *sh_ctx;           /**< SSL context for TLS */
  SSL            *sh_ssl;           /**< SSL handle for TLS */
Martti Mela's avatar
Martti Mela committed
208 209 210 211 212
#else
  void           *sh_ctx;           /**< SSL context for TLS */
  void           *sh_ssl;           /**< SSL handle for TLS */
#endif

213 214
  stun_msg_t      sh_tls_request;
  stun_msg_t      sh_tls_response;
215
  int             sh_nattype;       /**< NAT-type, see stun_common.h */
216

217 218
  stun_buffer_t   sh_username;
  stun_buffer_t   sh_passwd;
219

220 221
  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
222 223
};

224

225 226
#define STUN_STATE_STR(x) case x: return #x

227
char const *stun_str_state(stun_state_t state)
228 229 230
{
  switch (state) {
  STUN_STATE_STR(stun_no_assigned_event);
231
  /* STUN_STATE_STR(stun_req_dispose_me); */
232 233 234 235 236
  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);
237 238
  /* STUN_STATE_STR(stun_req_discovery_init); */
  /* STUN_STATE_STR(stun_req_discovery_processing); */
239
  STUN_STATE_STR(stun_discovery_done);
240 241 242
  STUN_STATE_STR(stun_tls_connection_timeout);
  STUN_STATE_STR(stun_tls_connection_failed);
  STUN_STATE_STR(stun_tls_ssl_connect_failed);
243
  STUN_STATE_STR(stun_discovery_timeout);
244
  /* STUN_STATE_STR(stun_req_timeout); */
245 246 247 248 249 250
  
  case stun_error:
  default: return "stun_error";
  }
}

251 252
/** 
 * Returns the NAT type attached to STUN discovery handle.
253 254 255
 *
 * @see stun_nattype_str().
 * @see stun_test_nattype().
256
 */
257
char const *stun_nattype_str(stun_discovery_t *sd)
258
{
259 260 261 262 263
  char const *stun_nattype_str[] = {
    "NAT type undetermined",
    "Open Internet",
    "UDP traffic is blocked or server unreachable",
    "Symmetric UDP Firewall",
264 265 266 267 268 269
    "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)",
270 271
  };

272 273 274 275
  if (sd)
    return stun_nattype_str[sd->sd_nattype];
  else
    return stun_nattype_str[stun_nat_unknown];
276 277
}

278 279 280 281 282 283 284 285 286 287 288 289 290 291
/**
 * Returns the detected NAT type.
 * 
 * @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;
}

292 293 294 295
su_addrinfo_t const *stun_server_address(stun_handle_t *sh)
{
  return &sh->sh_pri_info;
}
296

297 298
int stun_lifetime(stun_discovery_t *sd)
{
299
  return sd ? sd->sd_lt_cur : -1;
300 301 302
}


Martti Mela's avatar
Martti Mela committed
303
#if defined(HAVE_OPENSSL)
Pekka Pessi's avatar
Pekka Pessi committed
304
char const stun_version[] = 
Pekka Pessi's avatar
Pekka Pessi committed
305
 "sofia-sip-stun using " OPENSSL_VERSION_TEXT;
Martti Mela's avatar
Martti Mela committed
306 307 308 309
#else
char const stun_version[] = 
 "sofia-sip-stun";
#endif
Pekka Pessi's avatar
Pekka Pessi committed
310

311 312 313 314 315 316 317 318 319 320
static int do_action(stun_handle_t *sh, stun_msg_t *binding_response);
static int stun_tls_callback(su_root_magic_t *m, su_wait_t *w, su_wakeup_arg_t *arg);
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);
321
static int process_test_lifetime(stun_request_t *req, stun_msg_t *binding_response);
322 323 324

static stun_request_t *stun_request_create(stun_discovery_t *sd);
static int stun_send_binding_request(stun_request_t *req,
325
			      su_sockaddr_t *srvr_addr);
326
static int stun_bind_callback(stun_magic_t *m, su_wait_t *w, su_wakeup_arg_t *arg);
327 328

/* timers */
329 330 331 332 333 334
static void stun_sendto_timer_cb(su_root_magic_t *magic, 
				 su_timer_t *t,
				 su_timer_arg_t *arg);
static void stun_tls_connect_timer_cb(su_root_magic_t *magic, 
				      su_timer_t *t,
				      su_timer_arg_t *arg);
335 336 337
static void stun_test_lifetime_timer_cb(su_root_magic_t *magic, 
					su_timer_t *t,
					su_timer_arg_t *arg);
338 339 340 341 342 343
static void stun_keepalive_timer_cb(su_root_magic_t *magic, 
				    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);
344 345 346 347 348
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
349 350 351

/**
 * Return su_root_t assigned to stun_handle_t.
352
 *
Martti Mela's avatar
Martti Mela committed
353
 * @param self stun_handle_t object
354 355
 * @return su_root_t object, NULL if self not given.
 */
356
su_root_t *stun_root(stun_handle_t *self)
357
{
358
  return self ? self->sh_root : NULL;
359 360 361
}


Pekka Pessi's avatar
Pekka Pessi committed
362
/**
Martti Mela's avatar
Martti Mela committed
363
 * Check if a STUN handle should be created.
Pekka Pessi's avatar
Pekka Pessi committed
364
 *
365 366 367 368 369 370 371
 * Return true if STUNTAG_SERVER() or STUNTAG_DOMAIN() tags have 
 * been specified, or otherwise if STUN_SERVER environment variable 
 * 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
372 373 374 375 376 377
 *
 * @param tag,value,... tag-value list
 */
int stun_is_requested(tag_type_t tag, tag_value_t value, ...)
{
  ta_list ta;
378
  tagi_t const *t, *t2;
Pekka Pessi's avatar
Pekka Pessi committed
379 380
  char const *stun_server;

Martti Mela's avatar
Martti Mela committed
381
  enter;
Martti Mela's avatar
Martti Mela committed
382

Pekka Pessi's avatar
Pekka Pessi committed
383 384
  ta_start(ta, tag, value);
  t = tl_find(ta_args(ta), stuntag_server);
385 386 387 388
  t2 = tl_find(ta_args(ta), stuntag_domain);
  if (t && t->t_value) 
    stun_server = (char *)t->t_value;
  else if (t2 && t2->t_value)
389
    stun_server = (char *)t2->t_value;
390 391
  else
    stun_server = getenv("STUN_SERVER");
Pekka Pessi's avatar
Pekka Pessi committed
392 393 394 395 396
  ta_end(ta);

  return stun_server != NULL;
}

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 424 425 426 427 428 429 430 431 432

/** 
 * Creates a STUN handle.
 *
 * The created handles can be used for STUN binding discovery, 
 * keepalives, and other STUN usages.
 *
 * @param root eventloop to used by the stun state machine
 * @param tag,value,... tag-value list 
 *
 * @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;
  
  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());

433 434
  ta_end(ta);

435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
  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));
  }

  SU_DEBUG_5(("%s(\"%s\"): called\n", 
	      __func__, server));

  /* fail, if no server or a domain for a DNS-SRV lookup is specified */
452 453
  if (!server && !domain) {
    errno = ENOENT;
454
    return NULL;
455
  }
456 457 458 459 460 461 462 463 464 465 466 467 468 469
  
  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;
  
  if (server) {
470
    err = stun_atoaddr(stun->sh_home, AF_INET, &stun->sh_pri_info, server);
471 472
    if (err < 0) {
      errno = ENOENT;
473
      return NULL;
474
    }
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
  }

  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);
  
  stun->sh_nattype = stun_nat_unknown;
  
  /* initialize random number generator */
  srand(time(NULL));
495
 
496 497 498
  return stun;
}

499 500 501 502 503
/** 
 * Performs shared secret request/response processing.
 * Result will be trigged in STUN handle callback (state
 * one of stun_tls_*).
 **/
504 505 506 507
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
508
{
509
#if defined(HAVE_OPENSSL)
Martti Mela's avatar
Martti Mela committed
510 511 512 513 514 515
  int events = -1;
  int one, err = -1;
  su_wait_t wait[1] = { SU_WAIT_INIT };
  su_socket_t s = SOCKET_ERROR;
  int family;
  su_addrinfo_t *ai = NULL;
516
  stun_discovery_t *sd;
Martti Mela's avatar
Martti Mela committed
517
  /* stun_request_t *req; */
Martti Mela's avatar
Martti Mela committed
518

519 520
  ta_list ta;

Martti Mela's avatar
Martti Mela committed
521
  assert(sh);
Martti Mela's avatar
Martti Mela committed
522

Martti Mela's avatar
Martti Mela committed
523
  enter;
Martti Mela's avatar
Martti Mela committed
524

525 526
  if (!sh->sh_pri_addr[0].su_port) {
    /* no STUN server address, perform a DNS-SRV lookup */
527 528 529
   
    ta_list ta;
    ta_start(ta, tag, value);
530
    SU_DEBUG_5(("Delaying STUN shared-secret req. for DNS-SRV query.\n"));
531 532 533 534
    err = priv_dns_queue_action(sh, stun_action_tls_query, sdf, magic, ta_tags(ta));
    ta_end(ta);
       
    return err;
535 536
  }

Martti Mela's avatar
Martti Mela committed
537 538 539
  ai = &sh->sh_pri_info;

  if (sh->sh_use_msgint == 1) {
540
    SU_DEBUG_3(("%s: Obtaining shared secret.\n", __func__));
Martti Mela's avatar
Martti Mela committed
541 542 543 544 545 546 547 548 549
  }
  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);

550
  if (s == SOCKET_ERROR) {
Martti Mela's avatar
Martti Mela committed
551 552 553 554 555 556 557 558 559
    STUN_ERROR(errno, socket);
    return -1;
  }

  /* asynchronous connect() */
  if (su_setblocking(s, 0) < 0) {
    STUN_ERROR(errno, su_setblocking);
    return -1;
  }
560

Martti Mela's avatar
Martti Mela committed
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
  if (setsockopt(s, SOL_TCP, TCP_NODELAY,
		 (void *)&one, sizeof one) == -1) {
    STUN_ERROR(errno, setsockopt);
    return -1;
  }

  /* Do an asynchronous connect(). Three error codes are ok,
   * others cause return -1. */
  if (connect(s, (struct sockaddr *) &sh->sh_pri_addr, 
	      ai->ai_addrlen) == SOCKET_ERROR) {
    err = su_errno();
    if (err != EINPROGRESS && err != EAGAIN && err != EWOULDBLOCK) {
      STUN_ERROR(err, connect);
      return -1;
    }
  }

  SU_DEBUG_9(("%s: %s: %s\n", __func__, "connect",
	      su_strerror(err)));
  
581
  sd = stun_discovery_create(sh, stun_action_tls_query, sdf, magic);
Martti Mela's avatar
Martti Mela committed
582
  sd->sd_socket = s;
Martti Mela's avatar
Martti Mela committed
583
  /* req = stun_request_create(sd); */
Martti Mela's avatar
Martti Mela committed
584

Martti Mela's avatar
Martti Mela committed
585
  events = SU_WAIT_CONNECT | SU_WAIT_ERR;
Martti Mela's avatar
Martti Mela committed
586 587 588
  if (su_wait_create(wait, s, events) == -1)
    STUN_ERROR(errno, su_wait_create);

Martti Mela's avatar
Martti Mela committed
589
  /* su_root_eventmask(sh->sh_root, sh->sh_root_index, s, events); */
590 591

  if ((sd->sd_index =
Martti Mela's avatar
Martti Mela committed
592
       su_root_register(sh->sh_root, wait, stun_tls_callback, (su_wakeup_arg_t *) sd, 0)) == -1) {
Martti Mela's avatar
Martti Mela committed
593 594 595 596
    STUN_ERROR(errno, su_root_register);
    return -1;
  }

597 598 599 600
  ta_start(ta, tag, value);
  sd->sd_tags = tl_adup(sh->sh_home, ta_args(ta));
  ta_end(ta);

601
  sd->sd_state = stun_tls_connecting;
Martti Mela's avatar
Martti Mela committed
602 603 604 605

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

606 607
  sd->sd_timer = su_timer_create(su_root_task(sh->sh_root),
				 STUN_TLS_CONNECT_TIMEOUT);
Martti Mela's avatar
Martti Mela committed
608

609
  su_timer_set(sd->sd_timer, stun_tls_connect_timer_cb, (su_wakeup_arg_t *) sd);
Martti Mela's avatar
Martti Mela committed
610 611

  return 0;
612 613 614
#else /* !HAVE_OPENSSL */
  return -1;
#endif
Martti Mela's avatar
Martti Mela committed
615 616
}

617
static stun_request_t *stun_request_create(stun_discovery_t *sd)
618
{
619
  stun_handle_t *sh = sd->sd_handle;
620 621
  stun_request_t *req = NULL;

Martti Mela's avatar
Martti Mela committed
622
  enter;
Martti Mela's avatar
Martti Mela committed
623

624
  req = calloc(sizeof(stun_request_t), 1);
625 626
  if (!req)
    return NULL;
627

628
  req->sr_handle = sh;
629
  req->sr_discovery = sd;
630 631

  /* This is the default */
632
  req->sr_socket = sd->sd_socket;
633 634 635 636 637 638 639
  
  req->sr_localinfo.li_addrlen = sizeof(su_sockaddr_t);
  req->sr_localinfo.li_addr = req->sr_local_addr;
  
  /* default timeout for next sendto() */
  req->sr_timeout = STUN_SENDTO_TIMEOUT;
  req->sr_retry_count = 0;
640
  /* req->sr_action = action; */
641 642 643
  req->sr_request_mask = 0;
  
  req->sr_msg = calloc(sizeof(stun_msg_t), 1);
644

645
  req->sr_state = stun_req_discovery_init;
646
  memcpy(req->sr_local_addr, sd->sd_bind_addr, sizeof(su_sockaddr_t));
647

648 649 650 651 652 653
  /* Insert this request to the request queue */
  if (sh->sh_requests)
    x_insert(sh->sh_requests, req, sr);
  else
    sh->sh_requests = req;

654 655 656
  return req;
}

657
void stun_request_destroy(stun_request_t *req)
658
{
659
  stun_handle_t *sh;
660 661
  assert(req);

Martti Mela's avatar
Martti Mela committed
662
  enter;
Martti Mela's avatar
Martti Mela committed
663

664 665
  sh = req->sr_handle;

666 667 668
  if (x_is_inserted(req, sr))
    x_remove(req, sr);

669 670 671
  if (!x_is_inserted(req, sr) && !req->sr_next)
    sh->sh_requests = NULL;

672
  req->sr_handle = NULL;
673
  req->sr_discovery = NULL;
674
  /* memset(req->sr_destination, 0, sizeof(su_sockaddr_t)); */
675

676 677 678 679 680 681 682 683 684 685
  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;
  }
686

687
  free(req);
688 689 690

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

691 692 693
  return;
}

694

Pekka Pessi's avatar
Pekka Pessi committed
695
/** Destroy a STUN client */ 
Martti Mela's avatar
Martti Mela committed
696
void stun_handle_destroy(stun_handle_t *sh)
Pekka Pessi's avatar
Pekka Pessi committed
697
{ 
698
  stun_discovery_t *sd = NULL, *kill = NULL;
699
  stun_request_t *a, *b;
Pekka Pessi's avatar
Pekka Pessi committed
700

Martti Mela's avatar
Martti Mela committed
701
  enter;
Martti Mela's avatar
Martti Mela committed
702

703 704
  if (sh->sh_dns_lookup)
    stun_dns_lookup_destroy(sh->sh_dns_lookup);
705

706 707 708
  if (sh->sh_dns_pend_tags)
    su_free(sh->sh_home, sh->sh_dns_pend_tags);

709 710 711 712 713 714 715
  for (a = sh->sh_requests; a; ) {
    b = a->sr_next;
    stun_request_destroy(a);
    a = b;
  }


Martti Mela's avatar
Martti Mela committed
716 717
  /* There can be several discoveries using the same socket. It is
     still enough to deregister the socket in first of them */
718 719 720
  for (sd = sh->sh_discoveries; sd; ) {
    kill = sd;
    sd = sd->sd_next;
721

722 723 724
    /* Index has same value as sockfd, right? ... or not? */
    if (kill->sd_index != -1)
      su_root_deregister(sh->sh_root, kill->sd_index);
725 726
    if (kill->sd_action == stun_action_tls_query)
      su_close(kill->sd_socket);
727 728

    stun_discovery_destroy(kill);
Martti Mela's avatar
Martti Mela committed
729
  }
Martti Mela's avatar
Martti Mela committed
730

731 732 733 734 735
  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
736
  su_home_zap(sh->sh_home);
Martti Mela's avatar
Martti Mela committed
737 738
}

Pekka Pessi's avatar
Pekka Pessi committed
739

740
/** Create wait object and register it to the handle callback */
741 742
static
int assign_socket(stun_discovery_t *sd, su_socket_t s, int register_socket) 
743
{
744
  stun_handle_t *sh = sd->sd_handle;
745
  int events;
Martti Mela's avatar
Martti Mela committed
746
  stun_discovery_t *tmp;
747 748 749 750 751 752
  /* su_localinfo_t clientinfo[1]; */
  su_sockaddr_t bind_addr;
  socklen_t bind_len;
  char ipaddr[SU_ADDRSIZE + 2] = { 0 };
  su_sockaddr_t *sa;
  int err;
753
  
754 755
  su_wait_t wait[1] = { SU_WAIT_INIT };

Martti Mela's avatar
Martti Mela committed
756 757
  enter;

758 759
  if (s == SOCKET_ERROR) {
    SU_DEBUG_3(("%s: invalid socket\n", __func__));
760 761 762
    return errno = EINVAL, -1;
  }

Martti Mela's avatar
Martti Mela committed
763
  for (tmp = sh->sh_discoveries; tmp; tmp = tmp->sd_next) {
764 765 766 767 768 769
    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
770
  }
771
  sd->sd_socket = s;
Martti Mela's avatar
Martti Mela committed
772

773
  if (!register_socket)
774 775
    return 0;

776 777 778 779 780 781 782 783
  /* set socket asynchronous */
  if (su_setblocking(s, 0) < 0) {
    STUN_ERROR(errno, su_setblocking);

    su_close(s);
    return -1;
  }

784
  /* xxx -- check if socket is already assigned to this root */
785 786 787 788 789 790 791 792
  events = SU_WAIT_IN | SU_WAIT_ERR;

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

  /* Register receiving function with events specified above */
793 794
  if ((sd->sd_index = su_root_register(sh->sh_root,
				       wait, stun_bind_callback,
Martti Mela's avatar
Martti Mela committed
795
				       (su_wakeup_arg_t *) sd, 0)) < 0) {
796 797 798 799
    STUN_ERROR(errno, su_root_register);
    return -1;
  }

Martti Mela's avatar
Martti Mela committed
800 801
  SU_DEBUG_7(("%s: socket registered.\n", __func__));

802
  sa = (void *) &bind_addr;
803 804
  bind_len = SU_SOCKADDR_SIZE(sa);
  memset(sa, 0, bind_len);
805 806 807 808 809 810 811 812 813 814 815 816 817
  /* if bound check the error */
  err = getsockname(s, (struct sockaddr *) sa, &bind_len);
  if (err < 0 && errno == SOCKET_ERROR) {
    STUN_ERROR(errno, getsockname);
    return -1;
  }

  /* Not bound - bind it */
  if (sa->su_port == 0) {
#if defined (__CYGWIN__)
    get_localinfo(clientinfo);
#endif

818 819
    sa->su_family = AF_INET;

820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
    if ((err = bind(s, (struct sockaddr *) sa, bind_len)) < 0) {
      STUN_ERROR(errno, bind);
      SU_DEBUG_3(("%s: Error binding to %s:%u\n", __func__, 
		  inet_ntop(sa->su_family, SU_ADDR(sa), 
			    ipaddr, sizeof(ipaddr)),
		  (unsigned) ntohs(sa->su_port)));
      return -1;
    }

    /* bind_len = clientinfo->li_addrlen; */
    /* clientinfo->li_addrlen = bind_len; */
    sa->su_len = bind_len; /* ? */
  }

  memcpy(&sd->sd_bind_addr, &bind_addr, sizeof bind_addr);

  if (getsockname(s, (struct sockaddr *) &bind_addr, &bind_len) != 0) {
    STUN_ERROR(errno, getsockname);
    return -1;
  }

  SU_DEBUG_3(("%s: local socket is bound to %s:%u\n", __func__,
	      inet_ntop(bind_addr.su_family, SU_ADDR(&bind_addr), 
			ipaddr, sizeof(ipaddr)),
	      (unsigned) ntohs(bind_addr.su_port)));

  return 0;
847 848
}

849

850 851 852 853
/**
 * Helper function needed by Cygwin builds.
 */
#if defined (__CYGWIN__)
854 855 856
static int get_localinfo(su_localinfo_t *clientinfo)
{
  su_localinfo_t  hints[1] = {{ LI_CANONNAME | LI_NUMERIC }}, *li, *res = NULL;
857
  su_sockaddr_t *sa;
858 859 860
  int i, error, found = 0;
  char ipaddr[SU_ADDRSIZE + 2] = { 0 };

861

Martti Mela's avatar
Martti Mela committed
862
  hints->li_family = AF_INET;
863
  if ((error = su_getlocalinfo(hints, &res)) == 0) {
864 865 866 867 868 869 870
    
    /* try to bind to the first available address */
    for (i = 0, li = res; li; li = li->li_next) {
      if (li->li_family != AF_INET)
	continue;
      
      clientinfo->li_family = li->li_family;
Martti Mela's avatar
Martti Mela committed
871
      clientinfo->li_addrlen = li->li_addrlen;
872
      
873
      sa = clientinfo->li_addr;
Martti Mela's avatar
Martti Mela committed
874
      memcpy(sa, li->li_addr, sizeof(su_sockaddr_t));
875 876 877 878
      SU_DEBUG_3(("%s: local address found to be %s.\n",
		  __func__, 
		  inet_ntop(clientinfo->li_family, SU_ADDR(sa),
			    ipaddr, sizeof(ipaddr))));
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896
      found = 1;
      break;
    }
    
    if (!found) {
      STUN_ERROR(error, su_getlocalinfo);
      return -1;
    }
  }
  else {
    STUN_ERROR(error, su_getlocalinfo);
    return -1;
  }
  if (res)
    su_freelocalinfo(res);

  return 0;
}
897
#endif
898

899 900 901 902 903 904 905 906
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;

907
  res = stun_dns_lookup_udp_addr(self, &udp_target, &udp_port);
908
  if (res == 0 && udp_target) {
909
    /* XXX: assumption that same host and port used for UDP/TLS */
910 911 912 913 914 915
    stun_atoaddr(sh->sh_home, AF_INET, &sh->sh_pri_info, udp_target);
    
    if (udp_port) 
      sh->sh_pri_addr[0].su_port = htons(udp_port);
    else
      sh->sh_pri_addr[0].su_port = htons(STUN_DEFAULT_PORT);
916

917 918
    /* step: now that server address is known, continue 
     *       the pending action */
919

920 921
    SU_DEBUG_5(("STUN server address found, running queue actions (%d).\n",
		sh->sh_dns_pend_action));
922

923 924 925 926
    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;
927

928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
    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;
      
    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;
      
    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;
      
    default:
      SU_DEBUG_5(("Warning: unknown pending STUN DNS-SRV action.\n"));
    }
943
      }
944 945 946 947 948 949
  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);
950 951
    }
  }
952 953 954 955 956

  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;
957 958 959
}

/**
960 961
 * Queus a discovery process for later execution when DNS-SRV lookup
 * has been completed.
962
 */
963 964 965 966 967
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, ...)
968
{
969
  ta_list ta;
970

971 972 973
  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);
974
      ta_start(ta, tag, value);
975
      assert(sh->sh_dns_pend_tags == NULL);
976 977 978 979 980
      sh->sh_dns_pend_tags = tl_tlist(sh->sh_home, 
				      ta_tags(ta));
      ta_end(ta);
      sh->sh_dns_pend_cb = sdf;
      sh->sh_dns_pend_ctx = magic;
981 982

    }
983
    sh->sh_dns_pend_action |= action;
984 985

    return 0;
986
  }
987 988
  
  return -1;
989 990 991 992 993 994 995 996 997
}

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);
  }
998
  return res;
999 1000
}

1001 1002 1003 1004 1005
/** 
 * Performs a STUN Binding Discovery (see RFC3489/3489bis) process
 *
 * To integrity protect the discovery process, first call 
 * stun_request_shared_secret() on the handle 'sh'.
Pekka Pessi's avatar
Pekka Pessi committed
1006
 *
1007 1008 1009 1010
 * 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'.
Pekka Pessi's avatar
Pekka Pessi committed
1011
 * 
1012 1013 1014
 * @param sh       pointer to valid stun handle
 * @param sdf      callback to signal process progress
 * @param magic    context pointer attached to 'sdf'
Pekka Pessi's avatar
Pekka Pessi committed
1015
 *
1016
 * @TAGS
1017 1018
 * @TAG STUNTAG_SOCKET Bind socket for STUN (socket handle).
 * @TAG STUNTAG_REGISTER_SOCKET Register socket for eventloop owned by STUN (boolean)
1019

Pekka Pessi's avatar
Pekka Pessi committed
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
 * @return
 * On success, zero is returned.  Upon error, -1 is returned, and @e errno is
 * set appropriately.
 * 
 * @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.
 * @ERROR EACCESS   	  The address is protected, and the user is not 
 *                  	  the super-user.
 * @ERROR ENOTSOCK  	  Argument is a descriptor for a file, not a socket.
 * @ERROR EAGAIN          Operation in progress. Application should call 
 *                        stun_bind() again when there is data available on 
 *                        the socket.
 */
1035 1036 1037 1038 1039
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
1040
{
1041
  su_socket_t s = SOCKET_ERROR;
1042
  stun_request_t *req = NULL;
1043
  stun_discovery_t *sd = NULL;
1044
  ta_list ta;
1045
  int index, s_reg = 0;
1046
  
Martti Mela's avatar
Martti Mela committed
1047
  enter;
1048 1049 1050

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

1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
  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;
  }

1063
  ta_start(ta, tag, value);
Pekka Pessi's avatar
Pekka Pessi committed
1064

1065 1066
  tl_gets(ta_args(ta),
	  STUNTAG_SOCKET_REF(s),
1067
	  STUNTAG_REGISTER_EVENTS_REF(s_reg),
1068 1069
	  TAG_END());

1070 1071
  ta_end(ta);

1072
  sd = stun_discovery_create(sh, stun_action_binding_request, sdf, magic);
1073
  if ((index = assign_socket(sd, s, s_reg)) < 0)
1074
    return -1;
1075

1076 1077
  req = stun_request_create(sd);

1078
  if (stun_make_binding_req(sh, req, req->sr_msg, 0, 0) < 0) {
1079
    stun_discovery_destroy(sd);
1080
    stun_free_message(req->sr_msg);
1081
    return -1;
1082
  }
Pekka Pessi's avatar
Pekka Pessi committed
1083

1084 1085
  /* note: we always report success if bind() succeeds */
  return priv_stun_bind_send(sh, req, sd);
Pekka Pessi's avatar
Pekka Pessi committed
1086 1087
}

Martti Mela's avatar
Martti Mela committed
1088

1089 1090 1091 1092 1093 1094
/** 
 * 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
1095 1096 1097
 * This function returns the local address seen from outside.
 * Note that the address is not valid until the event stun_clien_done is launched.
 */
1098 1099 1100
int stun_discovery_get_address(stun_discovery_t *sd,
			       void *addr,
			       socklen_t *return_addrlen)
Martti Mela's avatar
Martti Mela committed
1101
{
1102 1103
  int siz;
  
Martti Mela's avatar
Martti Mela committed
1104
  enter;
Martti Mela's avatar
Martti Mela committed
1105

1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
  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);
  
  return 0;
Martti Mela's avatar
Martti Mela committed
1119 1120
}

1121 1122 1123 1124
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
1125
{
1126
  stun_discovery_t *sd = NULL;
Martti Mela's avatar
Martti Mela committed
1127

Martti Mela's avatar
Martti Mela committed
1128
  enter;
Martti Mela's avatar
Martti Mela committed
1129

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

1132 1133
  sd->sd_action = action;
  sd->sd_handle = sh;
1134 1135
  sd->sd_callback = sdf;
  sd->sd_magic = magic;
1136

1137 1138 1139 1140
  sd->sd_lt_cur = 0;
  sd->sd_lt = STUN_LIFETIME_EST;
  sd->sd_lt_max = STUN_LIFETIME_MAX;

1141 1142 1143 1144 1145 1146 1147 1148 1149
  sd->sd_pri_info.ai_addrlen = 16;
  sd->sd_pri_info.ai_addr = &sd->sd_pri_addr->su_sa;

  /* Insert this action to the discovery queue */
  if (sh->sh_discoveries)
    x_insert(sh->sh_discoveries, sd, sd);
  else
    sh->sh_discoveries = sd;

1150
  return sd;
1151
}
Martti Mela's avatar
Martti Mela committed
1152

1153
static int stun_discovery_destroy(stun_discovery_t *sd)
1154
{
Martti Mela's avatar
Martti Mela committed
1155 1156
  stun_handle_t *sh;

Martti Mela's avatar
Martti Mela committed
1157
  enter;
Martti Mela's avatar
Martti Mela committed
1158

Martti Mela's avatar
Martti Mela committed
1159 1160 1161 1162 1163
  if (!sd)
    return errno = EFAULT, -1;

  sh = sd->sd_handle;

1164 1165 1166
  if (sd->sd_timer) 
    su_timer_destroy(sd->sd_timer), sd->sd_timer = NULL;

Martti Mela's avatar
Martti Mela committed
1167 1168 1169 1170 1171 1172 1173
  /* if we are in the queue*/
  if (x_is_inserted(sd, sd))
    x_remove(sd, sd);
  /* if we were the only one */
  else if (!sd->sd_next)
    sh->sh_discoveries = NULL;

1174 1175
  sd->sd_next = NULL;

1176 1177 1178
  free(sd);
  return 0;
}
Martti Mela's avatar
Martti Mela committed
1179

1180
/**
1181 1182 1183 1184 1185 1186
 * Initiates STUN discovery process to find out NAT 
 * characteristics. 
 *
 * Process partly follows the algorithm defined in RFC3489 section 
 * 10.1. Due the known limitations of RFC3489, some of the tests
 * are done. 
1187
 *
1188
 * Note: does not support STUNTAG_DOMAIN() even if specified to
1189
 * stun_handle_init().
1190
 *
1191 1192 1193 1194 1195
 * @TAGS
 * @TAG STUNTAG_SOCKET Bind socket for STUN
 * @TAG STUNTAG_REGISTER_SOCKET Register socket for eventloop owned by STUN
 * @TAG STUNTAG_SERVER() stun server hostname or dotted IPv4 address
 *
1196
 * @return 0 on success, non-zero on error
1197
 */
1198 1199 1200 1201 1202
int stun_test_nattype(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
1203
{
1204
  int err = 0, index = 0, s_reg = 0;
1205
  ta_list ta;
1206
  char const *server = NULL;
1207 1208
  stun_request_t *req = NULL;
  stun_discovery_t *sd = NULL;
1209
  su_sockaddr_t bind_addr;
1210
  su_socket_t s = SOCKET_ERROR;
1211 1212 1213
  socklen_t bind_len;
  su_sockaddr_t *destination = NULL;

Martti Mela's avatar
Martti Mela committed
1214
  enter;
Martti Mela's avatar
Martti Mela committed
1215

1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
  if (!sh->sh_pri_addr[0].su_port) {
    /* no STUN server address, perform a DNS-SRV lookup */
   
    ta_list ta;
    ta_start(ta, tag, value);
    SU_DEBUG_5(("Delaying STUN get-nat-type req. for DNS-SRV query.\n"));
    err = priv_dns_queue_action(sh, stun_action_test_nattype, sdf, magic, ta_tags(ta));
    ta_end(ta);
       
    return err;
  }

  ta_start(ta, tag, value);
1229 1230
  tl_gets(ta_args(ta),
	  STUNTAG_SOCKET_REF(s),
1231
	  STUNTAG_REGISTER_EVENTS_REF(s_reg),
1232
	  STUNTAG_SERVER_REF(server),
1233 1234
	  TAG_END());

1235 1236
  ta_end(ta);

1237 1238 1239 1240
  bind_len = sizeof bind_addr;

  if (s < 0)
    return errno = EFAULT, -1;
1241

1242
  sd = stun_discovery_create(sh, stun_action_test_nattype, sdf, magic);
1243 1244
  sd->sd_mapped_addr_match = -1;

1245
  if ((index = assign_socket(sd, s, s_reg)) < 0)
1246
    return errno = EFAULT, -1;
1247

1248
  /* If no server given, use default address from stun_handle_init() */
1249
  if (!server) {
1250 1251
    /* memcpy(&sd->sd_pri_info, &sh->sh_pri_info, sizeof(su_addrinfo_t)); */
    memcpy(sd->sd_pri_addr, sh->sh_pri_addr, sizeof(su_sockaddr_t));
1252 1253
  }
  else {
1254
    err = stun_atoaddr(sh->sh_home, AF_INET, &sd->sd_pri_info, server);
1255
    memcpy(sd->sd_pri_addr, &sd->sd_pri_info.ai_addr, sizeof(su_sockaddr_t));
1256
  }
1257
  destination = (su_sockaddr_t *) sd->sd_pri_addr;
1258

1259 1260 1261 1262 1263
  req = stun_request_create(sd);
  if (stun_make_binding_req(sh, req, req->sr_msg, 
			    STUNTAG_CHANGE_IP(0), 
			    STUNTAG_CHANGE_PORT(0),
			    TAG_END()) < 0) 
1264
    return -1;
1265

1266
  err = stun_send_binding_request(req, destination);
1267 1268 1269 1270
  if (err < 0) {
    stun_free_message(req->sr_msg);
    return -1;
  }
Martti Mela's avatar
Martti Mela committed
1271

1272 1273
  /* Same Public IP and port, Test III, server ip 0 or 1 should be
     the same */
1274 1275 1276 1277 1278
  req = stun_request_create(sd);
  if (stun_make_binding_req(sh, req, req->sr_msg, 
			    STUNTAG_CHANGE_IP(0), 
			    STUNTAG_CHANGE_PORT(1),
			    TAG_END()) < 0) 
1279 1280
    return -1;

1281
  err = stun_send_binding_request(req, destination);
1282 1283 1284
  if (err < 0) {
    stun_free_message(req->sr_msg);
    return -1;
Pekka Pessi's avatar
Pekka Pessi committed
1285
  }
1286
  req = NULL;
1287

1288 1289 1290 1291 1292
  req = stun_request_create(sd);
  if (stun_make_binding_req(sh, req, req->sr_msg, 
			    STUNTAG_CHANGE_IP(1), 
			    STUNTAG_CHANGE_PORT(1),
			    TAG_END()) < 0) 
1293
    return -1;
1294
  
1295
  err = stun_send_binding_request(req, destination);
1296 1297 1298 1299
  if (err < 0) {
    stun_free_message(req->sr_msg);
  }

1300
  return err;
Pekka Pessi's avatar
Pekka Pessi committed
1301
}
1302

Pekka Pessi's avatar
Pekka Pessi committed
1303 1304 1305 1306
/********************************************************************
 * Internal functions
 *******************************************************************/

Martti Mela's avatar
Martti Mela committed
1307
#if defined(HAVE_OPENSSL)
1308
static int stun_tls_callback(su_root_magic_t *m, su_wait_t *w, su_wakeup_arg_t *arg)
Pekka Pessi's avatar
Pekka Pessi committed
1309
{
Martti Mela's avatar
Martti Mela committed
1310 1311
  stun_discovery_t *sd = arg;
  stun_handle_t *self = sd->sd_handle;
1312
  stun_msg_t *msg_req, *resp;
1313
  int z, err = -1;
Pekka Pessi's avatar
Pekka Pessi committed
1314 1315 1316 1317 1318
  SSL_CTX* ctx;
  SSL *ssl;
  X509* server_cert;
  unsigned char buf[512];
  stun_attr_t *password, *username;
1319
  int state;