stun.c 56.9 KB
Newer Older
Pekka Pessi's avatar
Pekka Pessi committed
1 2 3 4 5 6 7
/*
 * This file is part of the Sofia-SIP package
 *
 * Copyright (C) 2005 Nokia Corporation.
 *
 * 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 28 29 30
 * 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
 *
 * See RFC 3489 for further information.
 *
 * @author Tat Chan <Tat.Chan@nokia.com>
31
 * @author Martti Mela <Martti.Mela@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 41
#include <assert.h>

42
#define SU_ROOT_MAGIC_T struct stun_magic_t
43
#define SU_WAKEUP_ARG_T struct stun_handle_s
44
/* #define SU_TIMER_ARG_T  union stun_object_u */
45

Pekka Pessi's avatar
Pekka Pessi committed
46
#include "stun.h"
47
#include "stun_internal.h"
48
#include "stun_tag.h"
Pekka Pessi's avatar
Pekka Pessi committed
49 50

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

56

Pekka Pessi's avatar
Pekka Pessi committed
57 58
#include <openssl/opensslv.h>

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

62
enum {
63
  STUN_SENDTO_TIMEOUT = 1000,
Martti Mela's avatar
Martti Mela committed
64
  STUN_TLS_CONNECT_TIMEOUT = 8000,
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
typedef enum stun_action_s {
  stun_action_no_action,
  stun_action_binding_request,
  stun_action_keepalive,
  stun_action_get_nattype,
  stun_action_get_lifetime,
} stun_action_t;

#define CHG_IP		0x001
#define CHG_PORT	0x004

#if 0

char const *stun_nattype(stun_handle_t *sh)
{
  switch(sh->sh_nattype) {
  case STUN_NAT_UNKNOWN: return stun_nat_unknown;
  case STUN_OPEN_INTERNET: return stun_open_internet;
  case STUN_UDP_BLOCKED: return stun_udp_blocked;
  case STUN_SYM_UDP_FW: return stun_sym_udp_fw;
  case STUN_NAT_FULL_CONE: return stun_nat_full_cone;
  case STUN_NAT_SYM: return stun_nat_sym;
  case STUN_NAT_RES_CONE: return stun_nat_res_cone;
  case STUN_NAT_PORT_RES_CONE: return stun_nat_port_res_cone;
  default: return "INVALID NAT TYPE";
  }
}

#endif
Pekka Pessi's avatar
Pekka Pessi committed
97

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

struct stun_request_s {
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
  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 */

  su_localinfo_t  sr_localinfo;     /**< local addrinfo */
  su_sockaddr_t   sr_local_addr[1]; /**< local address */

#if 0
  int             sr_root_index;      /**< Index from su_root_register */
#endif
  int             sr_state;           /**< Progress states */
  int             sr_retry_count;     /**< current retry number */
  long            sr_timeout;         /**< timeout for next sendto() */
  stun_action_t   sr_action;          /**< Request type for protocol engine */
  int             sr_request_mask;    /**< Mask consisting of chg_ip and chg_port */
124 125
};

126

Martti Mela's avatar
Martti Mela committed
127
struct stun_handle_s
Pekka Pessi's avatar
Pekka Pessi committed
128
{
129 130 131 132
  su_home_t       sh_home[1];
  su_root_t      *sh_root;          /**< event loop */
  int             sh_root_index;    /**< object index of su_root_register() */
  su_timer_t     *sh_connect_timer; /**< timer for TLS connection */
133

134
  stun_request_t *sh_requests; /**< outgoing requests list */
135

136
  int             sh_max_retries;   /**< max resend for sendto() */
137

138 139
  su_addrinfo_t   sh_pri_info;      /**< server primary info */
  su_sockaddr_t   sh_pri_addr[1];   /**< server primary address */
140

141 142
  su_addrinfo_t   sh_sec_info;      /**< server secondary info */
  su_sockaddr_t   sh_sec_addr[1];   /**< server secondary address */
143

144 145
  su_localinfo_t  sh_localinfo;     /**< local addrinfo */
  su_sockaddr_t   sh_local_addr[1]; /**< local address */
146

147
  su_socket_t     sh_tls_socket;       /**< outbound socket */
148 149

#if 0  
150
  stun_msg_t     *sh_binding_request;     /**< binding request for server */
151
#endif
Martti Mela's avatar
Martti Mela committed
152

153 154 155 156 157
  SSL_CTX        *sh_ctx;          /**< SSL context for TLS */
  SSL            *sh_ssl;          /**< SSL handle for TLS */
  stun_msg_t      sh_tls_request;
  stun_msg_t      sh_tls_response;
  int             sh_nattype;     /**< NAT-type, see stun_common.h */
Martti Mela's avatar
Martti Mela committed
158

Martti Mela's avatar
Martti Mela committed
159

160

161 162
  stun_event_f    sh_callback;     /**< callback for calling application */ 
  stun_magic_t   *sh_context;      /**< application context */
163

164 165
  stun_buffer_t   sh_username;
  stun_buffer_t   sh_passwd;
166

167
  int             sh_use_msgint;  /**< use message integrity? */
168

169
  int             sh_state;      /**< Progress states */
Martti Mela's avatar
Martti Mela committed
170

Pekka Pessi's avatar
Pekka Pessi committed
171

172
  int            sh_bind_socket;
173
  int            ss_root_index;   /**< object index of su_root_register() */
Pekka Pessi's avatar
Pekka Pessi committed
174 175
};

Martti Mela's avatar
Martti Mela committed
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
#define STUN_STATE_STR(x) case x: return #x

char const *stun_str_state(stun_states_t state)
{
  switch (state) {
  STUN_STATE_STR(stun_no_assigned_event);
  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);
  STUN_STATE_STR(stun_bind_init);
  STUN_STATE_STR(stun_bind_started);
  STUN_STATE_STR(stun_bind_sending);
  STUN_STATE_STR(stun_bind_sent);
  STUN_STATE_STR(stun_bind_receiving);
  STUN_STATE_STR(stun_bind_processing);
  STUN_STATE_STR(stun_bind_done);
  STUN_STATE_STR(stun_tls_connection_timeout);
  STUN_STATE_STR(stun_tls_connection_failed);
  STUN_STATE_STR(stun_tls_ssl_connect_failed);
  STUN_STATE_STR(stun_request_not_found);
  STUN_STATE_STR(stun_bind_error);
  STUN_STATE_STR(stun_bind_timeout);
  
  case stun_error:
  default: return "stun_error";
  }
}

/* NAT TYPES */
typedef enum stun_nattype_t {
  stun_nat_unknown,
  stun_open_internet,
  stun_udp_blocked,
  stun_sym_udp_fw,
  stun_nat_full_cone,
  stun_nat_sym,
  stun_nat_res_cone,
  stun_nat_port_res_cone,
} stun_nattype_e;


char const *stun_nattype_str[] = {
  "NAT type undetermined",
  "Open Internet",
  "UDP traffic is blocked or server unreachable",
  "Symmetric UDP Firewall",
  "Full-Cone NAT",
  "Symmetric NAT",
  "Restricted Cone NAT",
  "Port Restricted Cone NAT",
};


char const *stun_nattype(stun_handle_t *sh)
{
  return stun_nattype_str[sh->sh_nattype];
}


Pekka Pessi's avatar
Pekka Pessi committed
238
char const stun_version[] = 
Pekka Pessi's avatar
Pekka Pessi committed
239
 "sofia-sip-stun using " OPENSSL_VERSION_TEXT;
Pekka Pessi's avatar
Pekka Pessi committed
240

241

242 243 244 245 246 247 248 249 250
static
int process_binding_request(stun_request_t *req, stun_msg_t *binding_response);
static
int process_get_nattype(stun_request_t *req, stun_msg_t *binding_response);
static
int process_get_lifetime(stun_request_t *req, stun_msg_t *binding_response);

static
stun_request_t *stun_create_request(stun_handle_t *sh, stun_action_t action);
251 252 253 254 255 256 257 258
static
int stun_send_binding_request(stun_request_t *req,
			      su_sockaddr_t *srvr_addr);
static
int stun_bind_callback(stun_magic_t *m, su_wait_t *w, stun_handle_t *self);
static
void stun_sendto_timer_cb(su_root_magic_t *magic, 
			  su_timer_t *t,
259
			  su_timer_arg_t *arg);
260

261 262
static
void stun_tls_connect_timer_cb(su_root_magic_t *magic, 
263 264
			       su_timer_t *t,
			       su_timer_arg_t *arg);
265 266 267 268




269
/**
Martti Mela's avatar
Martti Mela committed
270 271
 *  Return the socket associated with the stun_socket_t structure
 */
272
int stun_handle_get_bind_socket(stun_handle_t *sh)
Martti Mela's avatar
Martti Mela committed
273
{
274 275
  assert(sh);
  return sh->sh_bind_socket;
Martti Mela's avatar
Martti Mela committed
276 277 278 279 280
}


/**
 * Return su_root_t assigned to stun_handle_t.
281
 *
Martti Mela's avatar
Martti Mela committed
282
 * @param self stun_handle_t object
283 284
 * @return su_root_t object, NULL if self not given.
 */
Martti Mela's avatar
Martti Mela committed
285
su_root_t *stun_handle_root(stun_handle_t *self)
286
{
287
  return self ? self->sh_root : NULL;
288 289 290
}


Pekka Pessi's avatar
Pekka Pessi committed
291
/**
Martti Mela's avatar
Martti Mela committed
292
 * Check if a STUN handle should be created.
Pekka Pessi's avatar
Pekka Pessi committed
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
 *
 * Return true either there is a tag STUNTAG_SERVER() in list or if
 * STUN_SERVER environment variable is set.
 *
 * @param tag,value,... tag-value list
 */
int stun_is_requested(tag_type_t tag, tag_value_t value, ...)
{
  ta_list ta;
  tagi_t const *t;
  char const *stun_server;

  ta_start(ta, tag, value);
  t = tl_find(ta_args(ta), stuntag_server);
  stun_server = t && t->t_value ? (char *)t->t_value : getenv("STUN_SERVER");
  ta_end(ta);

  return stun_server != NULL;
}

313
/** 
Martti Mela's avatar
Martti Mela committed
314
 * Creates a STUN handle 
315
 *
Pekka Pessi's avatar
Pekka Pessi committed
316
 * @param server hostname or IPv4 address 
317
 * @param msg_integrity true if msg integr. should be used
318 319
 *
 */
Martti Mela's avatar
Martti Mela committed
320
stun_handle_t *stun_handle_create(stun_magic_t *context,
321
				  su_root_t *root,
322
				  stun_event_f cb,
323
				  char const *server, 
324
				  int msg_integrity)
325
{
Martti Mela's avatar
Martti Mela committed
326
  return stun_handle_tcreate(context,
327 328 329
			     root,
			     cb,
			     STUNTAG_SERVER(server), 
330 331 332 333 334
			     STUNTAG_INTEGRITY(msg_integrity), 
			     TAG_END());
}

/** 
Martti Mela's avatar
Martti Mela committed
335
 * Create a STUN handle 
336 337 338
 *
 * @param tag,value,... tag-value list 
 *
Pekka Pessi's avatar
Pekka Pessi committed
339
 * @TAGS
340 341 342 343
 * @TAG STUNTAG_SERVER() stun server hostname or dotted IPv4 address
 * @TAG STUNTAG_INTEGRITY() true if msg integrity should be used
 *
 */
Martti Mela's avatar
Martti Mela committed
344
stun_handle_t *stun_handle_tcreate(stun_magic_t *context,
345
				   su_root_t *root,
346
				   stun_event_f cb,
347
				   tag_type_t tag, tag_value_t value, ...)
Pekka Pessi's avatar
Pekka Pessi committed
348
{
Martti Mela's avatar
Martti Mela committed
349
  stun_handle_t *stun = NULL;
350 351
  char const *server = NULL;
  int msg_integrity = 1;
352
  int err;
353
  ta_list ta;
354
  
355 356 357 358 359 360 361
  ta_start(ta, tag, value);

  tl_gets(ta_args(ta),
	  STUNTAG_SERVER_REF(server),
	  STUNTAG_INTEGRITY_REF(msg_integrity),
	  TAG_END());

362 363 364 365 366 367 368
  stun = su_home_clone(NULL, sizeof(*stun));

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

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

375
  SU_DEBUG_5(("%s(\"%s\"): called\n", 
Martti Mela's avatar
Martti Mela committed
376
	      "stun_handle_tcreate", server));
377

378 379
  if (!server)
    return NULL;
380
  
381
  err = stun_atoaddr(AF_INET, &stun->sh_pri_info, stun->sh_pri_addr, server);
382

383 384
  if (err < 0)
    return NULL;
385

386 387
  stun->sh_pri_info.ai_addrlen = 16;
  stun->sh_pri_info.ai_addr = &stun->sh_pri_addr->su_sa;
Pekka Pessi's avatar
Pekka Pessi committed
388

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

392 393
  stun->sh_localinfo.li_addrlen = 16;
  stun->sh_localinfo.li_addr = stun->sh_local_addr;
394

395
  stun->sh_nattype = stun_nat_unknown;
396

397 398 399 400
  stun->sh_root     = root;
  stun->sh_context  = context;
  stun->sh_callback = cb;
  stun->sh_use_msgint = msg_integrity;
Pekka Pessi's avatar
Pekka Pessi committed
401 402


403
  stun->sh_max_retries = STUN_MAX_RETRX;
Martti Mela's avatar
Martti Mela committed
404

405
  /* initialize username and password */
406 407
  stun_init_buffer(&stun->sh_username);
  stun_init_buffer(&stun->sh_passwd);
408
  
409
  stun->sh_nattype = stun_nat_unknown;
410 411 412 413
  
  /* initialize random number generator */
  srand(time(NULL));
  
414 415
  ta_end(ta);

Pekka Pessi's avatar
Pekka Pessi committed
416 417 418
  return stun;
}

419

420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
stun_request_t *stun_action_create_binding_req(stun_handle_t *sh)
{
  return stun_create_request(sh, stun_action_binding_request);
}

stun_request_t *stun_action_create_nattype_discovery(stun_handle_t *sh)
{
  return stun_create_request(sh, stun_action_get_nattype);
}

stun_request_t *stun_action_create_timeout_discovery(stun_handle_t *sh)
{
  return stun_create_request(sh, stun_action_get_lifetime);
}

stun_request_t *stun_action_create_keepalive(stun_handle_t *sh)
{
  return stun_create_request(sh, stun_action_keepalive);
}


stun_request_t *stun_create_request(stun_handle_t *sh, stun_action_t action)
442 443 444 445 446 447 448
{
  stun_request_t *req = NULL;

  req = calloc(sizeof(stun_request_t), 1);
  if (req) {
    req->sr_handle = sh;

449 450 451 452
    /* STUN bind related */
    req->sr_localinfo.li_addrlen = sizeof(su_sockaddr_t);
    req->sr_localinfo.li_addr = req->sr_local_addr;

453 454 455
    /* default timeout for next sendto() */
    req->sr_timeout = STUN_SENDTO_TIMEOUT;
    req->sr_retry_count = 0;
456 457
    req->sr_action = action;
    req->sr_request_mask = 0;
458 459 460 461 462 463 464

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

  return req;
}

465 466 467 468 469 470 471 472 473 474 475 476
void stun_destroy_request(stun_request_t *req)
{
  assert(req);

  req->sr_handle = NULL;

  free(req->sr_msg);
  free(req);

  return;
}

477

Pekka Pessi's avatar
Pekka Pessi committed
478
/** Destroy a STUN client */ 
Martti Mela's avatar
Martti Mela committed
479
void stun_handle_destroy(stun_handle_t *self)
Pekka Pessi's avatar
Pekka Pessi committed
480
{ 
481 482
  if (self->sh_bind_socket > 0)
    su_close(self->sh_bind_socket);
Pekka Pessi's avatar
Pekka Pessi committed
483

484 485
  if (self->sh_tls_socket > 0)
    su_close(self->sh_tls_socket);
Martti Mela's avatar
Martti Mela committed
486

487
  su_home_zap(self->sh_home);
Martti Mela's avatar
Martti Mela committed
488 489
}

Pekka Pessi's avatar
Pekka Pessi committed
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517

/** Bind a socket using STUN client. 
 *
 * The function stun_bind() obtains a global address for a UDP socket using
 * a STUN server. 
 * 
 * @param ss       dpointer to a STUN client object (IN)
 * @param my_addr  public address for socket (IN/OUT)
 * @param addrlen  length of pub_addr (IN/OUT)
 * @param lifetime return value pointer to lifetime of 
 *                 binding, -1 if no STUN not used (OUT)
 *
 * @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.
 * 
 */
518
int stun_handle_bind(stun_handle_t *sh,
519 520 521
		     int *lifetime,
		     tag_type_t tag, tag_value_t value,
		     ...)
Pekka Pessi's avatar
Pekka Pessi committed
522
{
523 524
  int retval = -1;
  su_socket_t s = -1;
525
  su_localinfo_t *clientinfo = NULL;
526
  su_sockaddr_t bind_addr;
Pekka Pessi's avatar
Pekka Pessi committed
527
  socklen_t bind_len;
528
  char ipaddr[SU_ADDRSIZE + 2] = { 0 };
529
  stun_request_t *req = NULL;
530
  int index;
531
  int events = -1;
Pekka Pessi's avatar
Pekka Pessi committed
532
  su_localinfo_t  hints[1] = {{ LI_CANONNAME | LI_NUMERIC }}, *li, *res = NULL;
533
  int i, error, found = 0;
534
  unsigned int port;
535
  ta_list ta;
536
  su_wait_t wait[1] = { SU_WAIT_INIT };
537
  int action = stun_action_no_action;
Pekka Pessi's avatar
Pekka Pessi committed
538
  
539
  assert(sh);
Martti Mela's avatar
Martti Mela committed
540

541
  ta_start(ta, tag, value);
Pekka Pessi's avatar
Pekka Pessi committed
542

543 544
  tl_gets(ta_args(ta),
	  STUNTAG_SOCKET_REF(s),
545
	  STUNTAG_ACTION_REF(action),
546 547 548 549 550 551 552
	  TAG_END());

  if (s < 0) {
    SU_DEBUG_3(("%s: invalid socket.\n", __func__));
    return -1;
  }

553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
  if (action != stun_action_no_action)
    req = stun_create_request(sh, action);
  else
    req = stun_action_create_binding_req(sh);

  /* Insert this request to the request queue */
  if (sh->sh_requests)
    x_insert(sh->sh_requests, req, sr);
  else
    sh->sh_requests = req;

  clientinfo = &req->sr_localinfo;

  if (action != stun_action_no_action)
    goto skip_init;

#if 0  
570
  /* Close the previous associated socket */
571 572 573
  if (sh->sh_bind_socket > 0)
    su_close(sh->sh_bind_socket);
#endif
574 575 576 577 578 579 580 581

  /* set socket asynchronous */
  if (su_setblocking(s, 0) < 0) {
    STUN_ERROR(errno, su_setblocking);

    su_close(s);
    return -1;
  }
582
  sh->sh_bind_socket = s;
Martti Mela's avatar
Martti Mela committed
583 584

  hints->li_family = AF_INET;
Martti Mela's avatar
Martti Mela committed
585
  if((error = su_getlocalinfo(hints, &res)) == 0) {
Martti Mela's avatar
Martti Mela committed
586
    
Martti Mela's avatar
Martti Mela committed
587 588 589 590 591
    /* 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;
      
592 593
      clientinfo->li_family = li->li_family;
      clientinfo->li_addrlen = li->li_addrlen;
Martti Mela's avatar
Martti Mela committed
594
      
595 596
      memcpy(clientinfo->li_addr, li->li_addr, sizeof(su_addrinfo_t));
      inet_ntop(clientinfo->li_family, SU_ADDR(clientinfo->li_addr),
597
		ipaddr, sizeof(ipaddr));
598
      port = ntohs(clientinfo->li_addr->su_port);
599 600
      SU_DEBUG_3(("%s: local address found to be %s:%u\n",
		  __func__, ipaddr, port));
Martti Mela's avatar
Martti Mela committed
601 602
      found = 1;
      break;
Pekka Pessi's avatar
Pekka Pessi committed
603
    }
Martti Mela's avatar
Martti Mela committed
604 605 606 607
    
    if (!found) {
      STUN_ERROR(error, su_getlocalinfo);
      return -1;
Pekka Pessi's avatar
Pekka Pessi committed
608 609
    }
  }
Martti Mela's avatar
Martti Mela committed
610 611 612 613 614 615
  else {
    STUN_ERROR(error, su_getlocalinfo);
    return -1;
  }
  if (res)
    su_freelocalinfo(res);
Pekka Pessi's avatar
Pekka Pessi committed
616

617
  s = sh->sh_bind_socket;
618 619 620 621 622 623 624 625 626

  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 */
627
  if ((index = su_root_register(sh->sh_root,
628
				wait, stun_bind_callback,
629
				sh, 0)) < 0) {
630 631 632
    STUN_ERROR(errno, su_root_register);
    return -1;
  }
Pekka Pessi's avatar
Pekka Pessi committed
633

634 635
  inet_ntop(clientinfo->li_family, SU_ADDR(clientinfo->li_addr), ipaddr, sizeof(ipaddr));
  if (bind(s, (struct sockaddr *) &clientinfo->li_addr, clientinfo->li_addrlen) < 0) {
636
    SU_DEBUG_3(("%s: Error binding to %s:%u\n", __func__, ipaddr,
637
		(unsigned) ntohs(clientinfo->li_addr->su_port)));
Pekka Pessi's avatar
Pekka Pessi committed
638 639 640
    return -1;
  }

641
  SU_DEBUG_3(("%s: socket bound to %s:%u\n", __func__, ipaddr,
642
	      (unsigned) ntohs(clientinfo->li_addr->su_port)));
643

644
  bind_len = clientinfo->li_addrlen;
645
  if (getsockname(s, (struct sockaddr *) &bind_addr, &bind_len) != 0) {
Martti Mela's avatar
Martti Mela committed
646 647 648
    STUN_ERROR(errno, getsockname);
    return -1;
  }
Pekka Pessi's avatar
Pekka Pessi committed
649
  
650
  inet_ntop(clientinfo->li_family, SU_ADDR(&bind_addr), ipaddr, sizeof(ipaddr));
651
  SU_DEBUG_3(("%s: Local socket bound to: %s:%u\n", __func__, ipaddr, 
652
	      (unsigned) ntohs(bind_addr.su_port)));
Pekka Pessi's avatar
Pekka Pessi committed
653

654
 skip_init:
655

656
  /* Create default message (last two params zeros) */
657
  if (stun_make_binding_req(sh, req, req->sr_msg, 0, 0) < 0) 
658 659
    return -1;

660
  retval = stun_send_binding_request(req, sh->sh_pri_addr);
661 662

  if (retval < 0) {
663
    stun_free_message(req->sr_msg);
664
  }
Pekka Pessi's avatar
Pekka Pessi committed
665 666 667 668 669 670 671 672
  if (lifetime) {
    if (retval == 0)
      *lifetime = 3600;
    else
      *lifetime = -1;
  }

  /* note: we always report success if bind() succeeds */
673 674 675

  ta_end(ta);

Pekka Pessi's avatar
Pekka Pessi committed
676 677 678 679
  return 0;

}

Martti Mela's avatar
Martti Mela committed
680 681 682 683 684

/** Return local NATed address 
 * This function returns the local address seen from outside.
 * Note that the address is not valid until the event stun_clien_done is launched.
 */
685
su_localinfo_t *stun_request_get_localinfo(stun_request_t *req)
Martti Mela's avatar
Martti Mela committed
686
{
687
  return &req->sr_localinfo;
Martti Mela's avatar
Martti Mela committed
688 689 690 691
}



692
#if 0
Pekka Pessi's avatar
Pekka Pessi committed
693 694
/** Return type of NAT
 *  This function may take a long time to finish.
Martti Mela's avatar
Martti Mela committed
695
 *  XXX - mela: not for long!!!
696
 *  nat type is set in ss->se_handle.sh_nattype
Pekka Pessi's avatar
Pekka Pessi committed
697
 */
698
int stun_handle_get_nattype(stun_handle_t *sh,
Martti Mela's avatar
Martti Mela committed
699 700 701 702 703 704 705
			    int *addrlen)
{
  int retval, lifetime, sockfd;
  socklen_t locallen, len;
  su_sockaddr_t local, /* mapped_addr1, */ mapped_addr2;
  su_localinfo_t *mapped_addr1;

706
  sockfd = sh->sh_bind_socket;
Martti Mela's avatar
Martti Mela committed
707

708
  assert(sh);
Martti Mela's avatar
Martti Mela committed
709

710 711 712
  if ((sh->sh_state != stun_bind_done) &&
      (sh->sh_state != stun_bind_timeout) &&
      (sh->sh_state != stun_bind_error))
Martti Mela's avatar
Martti Mela committed
713 714 715
    return -1;

  
716
  mapped_addr1 = stun_handle_get_local_addr(sh);
Martti Mela's avatar
Martti Mela committed
717 718 719 720 721 722 723 724

#if 0  
  len = sizeof(mapped_addr1);
  memcpy(&mapped_addr1, my_addr, len); 
  /* mapped_addr1.li_addr.su_port = 0; */ /* wild card for get_nattype */
  /* retval = stun_bind(ss, &mapped_addr1, &lifetime); */
#endif

725 726
  if (sh->sh_state == stun_bind_timeout) {
    sh->sh_nattype = stun_udp_blocked;
Martti Mela's avatar
Martti Mela committed
727 728 729
    /* otherwise unknown nat type */
    return 0;
  }
730 731
  else if (sh->sh_state == stun_bind_error) {
    sh->sh_nattype = stun_nat_unknown;
Martti Mela's avatar
Martti Mela committed
732 733 734 735 736 737 738 739 740 741 742
    return 0;
  }
  else {
    memset(&local, 0, sizeof(local));
    locallen = sizeof(local);
    getsockname(sockfd, (struct sockaddr *) &local, &locallen);

    /* Same IP and port*/
    if (memcmp(&local, &mapped_addr1->li_addr, 8) == 0) {
      /* conduct TEST II */      
      memset(&mapped_addr2, 0, sizeof(mapped_addr2));
743
      retval = stun_send_binding_request(sh, sh->sh_pri_addr, 1, 1);
Martti Mela's avatar
Martti Mela committed
744 745 746 747
      if (retval == -1) {
	if (errno == ETIMEDOUT) {
	  /* No Response: Type 3 - Sym UDP FW */
	  retval = 0;
748
	  sh->sh_nattype = stun_sym_udp_fw;	  
Martti Mela's avatar
Martti Mela committed
749 750 751 752
	} /* otherwise unknown nat type */
      } 
      else {
	/* Response: Type 1 - Open Internet */
753
	sh->sh_nattype = stun_open_internet;
Martti Mela's avatar
Martti Mela committed
754 755 756 757 758
      }
    }
    /* Different IP */
    else {
      memset(&mapped_addr2, 0, sizeof(mapped_addr2));
759
      retval = stun_send_binding_request(sh, sh->sh_pri_addr, 1, 1);
Martti Mela's avatar
Martti Mela committed
760 761 762
      if (retval == -1) {
	if (errno == ETIMEDOUT) {
	  /* No Response */
763
	  retval = stun_send_binding_request(sh, sh->sh_sec_addr, 0, 0);
Martti Mela's avatar
Martti Mela committed
764 765 766 767 768
	  /* response comes back, has to be the case */
	  if (retval == 0) {
	    if (memcmp(&mapped_addr1, &mapped_addr2, 8) == 0) {
	      /* Same Public IP and port, Test III, server ip 0 or 1 should be
		 same */
769
	      retval = stun_send_binding_request(sh, sh->sh_pri_addr, 0, 1);
Martti Mela's avatar
Martti Mela committed
770 771
	      if(retval==0) {
		/* Response: Type 6 - Restricted */
772
		sh->sh_nattype = stun_nat_res_cone;
Martti Mela's avatar
Martti Mela committed
773 774 775 776
	      }
	      else if(errno==ETIMEDOUT) {
		/* No response: Type 7 - Port Restricted */
		retval = 0;
777
		sh->sh_nattype = stun_nat_port_res_cone;
Martti Mela's avatar
Martti Mela committed
778 779 780 781
	      }
	    }
	    else {
	      /* Different Public IP: Type 5 - Sym NAT */
782
	      sh->sh_nattype = stun_nat_sym;
Martti Mela's avatar
Martti Mela committed
783 784 785 786 787 788
	    }
	  } /* otherwise there is a sudden network problem */	  
	} /* otherwise unknown nat type */
      }
      else {
	/* Response: Type 4 - Full Cone */
789
	sh->sh_nattype = stun_nat_full_cone;
Martti Mela's avatar
Martti Mela committed
790 791 792 793 794 795
      }
    }
  }
  
  return retval;
}
796
#endif /* if 0 */
Martti Mela's avatar
Martti Mela committed
797

798 799 800 801 802 803 804
int stun_handle_get_nattype(stun_handle_t *sh,
#if 0
  su_localinfo_t *my_addr,
  int *addrlen,
#endif
			    tag_type_t tag, tag_value_t value,
			    ...)
Pekka Pessi's avatar
Pekka Pessi committed
805
{
806
  int nattype = stun_nat_unknown;
807
  int retval, lifetime, sockfd;
808 809
  /* socklen_t locallen, len; */
#if 0
Martti Mela's avatar
Martti Mela committed
810 811
  struct sockaddr_in local, /* mapped_addr1, */ mapped_addr2;
  su_localinfo_t mapped_addr1;
812 813
#endif
  ta_list ta;
Pekka Pessi's avatar
Pekka Pessi committed
814
  
815
  ta_start(ta, tag, value);
Martti Mela's avatar
Martti Mela committed
816

817 818 819 820

  sockfd = sh->sh_bind_socket;

#if 0
Martti Mela's avatar
Martti Mela committed
821
  assert(my_addr && my_addr->li_addrlen != 0);
Pekka Pessi's avatar
Pekka Pessi committed
822 823
  len = sizeof(mapped_addr1);
  memcpy(&mapped_addr1, my_addr, len); 
Martti Mela's avatar
Martti Mela committed
824
  /* mapped_addr1.li_addr.su_port = 0; */ /* wild card for get_nattype */
825
#endif
Martti Mela's avatar
Martti Mela committed
826 827

  /* retval = stun_bind(ss, &mapped_addr1, &lifetime); */
828 829 830 831 832 833 834

  /* This launches the binding process, but with a different state
   * machine than the default one: get_nattype is the specified action
   * here */
  retval = stun_handle_bind(sh, &lifetime,
			    STUNTAG_ACTION(stun_action_get_nattype),
			    TAG_NEXT(ta_args(ta)));
Martti Mela's avatar
Martti Mela committed
835 836
  if (retval == -1) {
    if (errno == ETIMEDOUT) {
Pekka Pessi's avatar
Pekka Pessi committed
837 838
      /* No Response: Type 2 - UDP Blocked */
      retval = 0; /* time out is a legitimate response */
839
      nattype = stun_udp_blocked;
Pekka Pessi's avatar
Pekka Pessi committed
840 841
    } /* otherwise unknown nat type */
  }
842 843 844 845 846 847
  
  ta_end(ta);
  return 0;
}

#if 0
Pekka Pessi's avatar
Pekka Pessi committed
848 849 850
  else { /* Response comes back */
    memset(&local, 0, sizeof(local)); locallen = sizeof(local);
    getsockname(sockfd, (struct sockaddr *)&local, &locallen);
Martti Mela's avatar
Martti Mela committed
851
    if (memcmp(&local, &mapped_addr1, 8) == 0) { /* Same IP and port*/
Pekka Pessi's avatar
Pekka Pessi committed
852 853
      /* conduct TEST II */      
      memset(&mapped_addr2, 0, sizeof(mapped_addr2));
854
      retval = stun_send_binding_request(sh, sh->sh_pri_addr, &mapped_addr2, 1, 1);
Martti Mela's avatar
Martti Mela committed
855 856
      if (retval == -1) {
	if (errno == ETIMEDOUT) {
Pekka Pessi's avatar
Pekka Pessi committed
857 858 859 860 861 862 863 864 865 866 867 868
	  /* No Response: Type 3 - Sym UDP FW */
	  retval = 0;
	  nattype = STUN_SYM_UDP_FW;	  
	} /* otherwise unknown nat type */
      } 
      else {
	/* Response: Type 1 - Open Internet */
	nattype = STUN_OPEN_INTERNET;
      }
    }
    else { /* Different IP */
      memset(&mapped_addr2, 0, sizeof(mapped_addr2));
869
      retval = stun_send_binding_request(sh, sh->sh_pri_addr, &mapped_addr2, 1, 1);
Martti Mela's avatar
Martti Mela committed
870 871
      if (retval == -1) {
	if (errno == ETIMEDOUT) {
Pekka Pessi's avatar
Pekka Pessi committed
872
	  /* No Response */
873
	  retval = stun_send_binding_request(sh, sh->sh_sec_addr, &mapped_addr2, 0, 0);
Martti Mela's avatar
Martti Mela committed
874 875 876
	  /* response comes back, has to be the case */
	  if (retval == 0) {
	    if (memcmp(&mapped_addr1, &mapped_addr2, 8) == 0) {
Pekka Pessi's avatar
Pekka Pessi committed
877 878
	      /* Same Public IP and port, Test III, server ip 0 or 1 should be
		 same */
879
	      retval = stun_send_binding_request(sh, sh->sh_pri_addr, &mapped_addr2, 0, 1);
Pekka Pessi's avatar
Pekka Pessi committed
880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
	      if(retval==0) {
		/* Response: Type 6 - Restricted */
		nattype = STUN_NAT_RES_CONE;
	      }
	      else if(errno==ETIMEDOUT) {
		/* No response: Type 7 - Port Restricted */
		retval = 0;
		nattype = STUN_NAT_PORT_RES_CONE;
	      }
	    }
	    else {
	      /* Different Public IP: Type 5 - Sym NAT */
	      nattype = STUN_NAT_SYM;
	    }
	  } /* otherwise there is a sudden network problem */	  
	} /* otherwise unknown nat type */
      }
      else {
	/* Response: Type 4 - Full Cone */
	nattype = STUN_NAT_FULL_CONE;
      }
    }
  }
  
904
  sh->sh_nattype = nattype;
Pekka Pessi's avatar
Pekka Pessi committed
905 906
  return retval;
}
Martti Mela's avatar
Martti Mela committed
907
#endif /* if 0 */
Pekka Pessi's avatar
Pekka Pessi committed
908 909 910 911 912 913 914 915 916 917 918 919 920

/** Application should call this at regular intervals 
 *  while binding is active.
 */
int stun_poll(stun_socket_t *ss)
{
  return 0;
}

/********************************************************************
 * Internal functions
 *******************************************************************/

921
static 
922

Martti Mela's avatar
Martti Mela committed
923
int stun_tls_callback(su_root_magic_t *m, su_wait_t *w, stun_handle_t *self)
Pekka Pessi's avatar
Pekka Pessi committed
924
{
Martti Mela's avatar
Martti Mela committed
925
  stun_msg_t *req, *resp;
Martti Mela's avatar
Martti Mela committed
926
  int z, err;
927
  int events = su_wait_events(w, self->sh_tls_socket);
Pekka Pessi's avatar
Pekka Pessi committed
928 929 930 931 932
  SSL_CTX* ctx;
  SSL *ssl;
  X509* server_cert;
  unsigned char buf[512];
  stun_attr_t *password, *username;
Martti Mela's avatar
Martti Mela committed
933
  int state;
Martti Mela's avatar
Martti Mela committed
934

Martti Mela's avatar
Martti Mela committed
935
  SU_DEBUG_7(("%s(%p): events%s%s%s%s\n", __func__, self,
Martti Mela's avatar
Martti Mela committed
936
	      events & SU_WAIT_CONNECT ? " CONNECTED" : "",
Martti Mela's avatar
Martti Mela committed
937 938 939
	      events & SU_WAIT_ERR     ? " ERR"       : "",
	      events & SU_WAIT_IN      ? " IN"        : "",
	      events & SU_WAIT_OUT     ? " OUT"       : ""));
Martti Mela's avatar
Martti Mela committed
940

Martti Mela's avatar
Martti Mela committed
941
  if (events & SU_WAIT_ERR) {
942
    su_wait_destroy(w);
943
    su_root_deregister(self->sh_root, self->sh_root_index);
944

Martti Mela's avatar
Martti Mela committed
945
    /* Destroy the timeout timer */
946
    su_timer_destroy(self->sh_connect_timer);
Martti Mela's avatar
Martti Mela committed
947 948 949

    SU_DEBUG_3(("%s: shared secret not obtained from server. "	\
		"Proceed without username/password.\n", __func__));
950 951
    self->sh_state = stun_tls_connection_failed;
    self->sh_callback(self->sh_context, self, NULL, self->sh_state);
Martti Mela's avatar
Martti Mela committed
952 953
    return 0;
  }
Pekka Pessi's avatar
Pekka Pessi committed
954

Martti Mela's avatar
Martti Mela committed
955
  /* Can be NULL, too */
956 957 958
  ssl  = self->sh_ssl;
  req  = &self->sh_tls_request;
  resp = &self->sh_tls_response;
959

960
  state = self->sh_state;
Martti Mela's avatar
Martti Mela committed
961 962
  switch (state) {
  case stun_tls_connecting:
Pekka Pessi's avatar
Pekka Pessi committed
963

Martti Mela's avatar
Martti Mela committed
964 965 966 967 968 969 970 971 972 973 974
    /* compose shared secret request */
    if (stun_make_sharedsecret_req(req) != 0) {
      STUN_ERROR(errno, stun_make_sharedsecret_req);
      stun_free_buffer(&req->enc_buf);
      return -1;
    }
    
    /* openssl initiation */
    SSLeay_add_ssl_algorithms();
    SSL_load_error_strings();
    ctx = SSL_CTX_new(TLSv1_client_method());
975
    self->sh_ctx = ctx;
Martti Mela's avatar
Martti Mela committed
976 977 978 979 980 981 982 983 984 985 986 987 988 989 990

    if (ctx == NULL) {
      STUN_ERROR(errno, SSL_CTX_new);
      stun_free_buffer(&req->enc_buf);
      return -1;
    }
    
    if (SSL_CTX_set_cipher_list(ctx, "AES128-SHA") == 0) {
      STUN_ERROR(errno, SSL_CTX_set_cipher_list);
      stun_free_buffer(&req->enc_buf);
      return -1;
    }
    
    /* Start TLS negotiation */
    ssl = SSL_new(ctx);
991
    self->sh_ssl = ssl;
Pekka Pessi's avatar
Pekka Pessi committed
992

993
    if (SSL_set_fd(ssl, self->sh_tls_socket) == 0) {
Martti Mela's avatar
Martti Mela committed
994 995 996 997
      STUN_ERROR(err, connect);
      stun_free_buffer(&req->enc_buf);
      return -1;
    }
Pekka Pessi's avatar
Pekka Pessi committed
998

Martti Mela's avatar
Martti Mela committed
999 1000 1001
    /* No break here! Continue to SSL_connect. If SSL_continue returns
     * less than 1 because of nonblocking, have a different state
     * (ssl_connecting) for it */
Pekka Pessi's avatar
Pekka Pessi committed
1002

Martti Mela's avatar
Martti Mela committed
1003
  case stun_tls_ssl_connecting:
1004
    events = SU_WAIT_ERR | SU_WAIT_IN;
1005 1006
    su_root_eventmask(self->sh_root, self->sh_root_index,
		      self->sh_tls_socket,