stun.c 31.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 31 32 33 34 35 36 37 38
 * 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>
 * @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" 

39 40
#include <assert.h>

Pekka Pessi's avatar
Pekka Pessi committed
41
#include "stun.h"
42
#include "stun_tag.h"
Pekka Pessi's avatar
Pekka Pessi committed
43 44

#include <su_alloc.h>
45
#include <su_tagarg.h>
Pekka Pessi's avatar
Pekka Pessi committed
46 47 48 49
#include <su_log.h>
#include <su.h>
#include <su_localinfo.h>

Pekka Pessi's avatar
Pekka Pessi committed
50 51
#include <openssl/opensslv.h>

Pekka Pessi's avatar
Pekka Pessi committed
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
#define STUN_DEBUG 5		/* default log level */

/** STUN log. */
su_log_t stun_log[] = { SU_LOG_INIT("stun", "STUN_DEBUG", STUN_DEBUG) }; 
#define SU_LOG (stun_log)

#include <su_debug.h>

char const stun_nat_unknown[] = "NAT type undetermined",
  stun_open_internet[] = "Open Internet",
  stun_udp_blocked[] = "UDP traffic is blocked, or Server unreachable",
  stun_sym_udp_fw[] = "Symmetric UDP Firewall",
  stun_nat_full_cone[] = "Full-Cone NAT",
  stun_nat_sym[] = "Symmetric NAT",
  stun_nat_res_cone[] = "Restricted Cone NAT",
  stun_nat_port_res_cone[] = "Port Restricted Cone NAT";

69 70 71 72 73 74 75 76 77 78 79
/**
 * States of the STUN client->server query process.
 */ 
enum stun_client_state_e {
  stun_cstate_init,             /**< Initial state */
  stun_cstate_started,          /**< Discovery process started */
  stun_cstate_received,         /**< Received server reply */
  stun_cstate_processing,       /**< Processing server reply */
  stun_cstate_done,             /**< Initial state */
};

Pekka Pessi's avatar
Pekka Pessi committed
80 81 82
struct stun_engine_s
{
  su_home_t      stun_home[1];
83 84 85 86 87
  su_sockaddr_t  stun_srvr4[2]; /**< primary and secondary addresses */
  int            use_msgint;    /**< use message integrity? */
  stun_buffer_t  username;
  stun_buffer_t  password;
  int            nattype;       /**< NAT-type, see stun_common.h */
Pekka Pessi's avatar
Pekka Pessi committed
88 89 90 91 92 93
};

struct stun_socket_s
{
  stun_engine_t *ss_engine;
  int            ss_sockfd;
94
  int            ss_state;      /**< State for STUN protocol ? */
Pekka Pessi's avatar
Pekka Pessi committed
95 96
};

Pekka Pessi's avatar
Pekka Pessi committed
97
char const stun_version[] = 
Pekka Pessi's avatar
Pekka Pessi committed
98
 "sofia-sip-stun using " OPENSSL_VERSION_TEXT;
Pekka Pessi's avatar
Pekka Pessi committed
99

Pekka Pessi's avatar
Pekka Pessi committed
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
/**
 * Check if a STUN engine should be created.
 *
 * 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;
}

122 123 124
/** 
 * Creates a STUN engine 
 *
Pekka Pessi's avatar
Pekka Pessi committed
125
 * @param server hostname or IPv4 address 
126
 * @param msg_integrity true if msg integr. should be used
127 128
 *
 */
Pekka Pessi's avatar
Pekka Pessi committed
129
stun_engine_t *stun_engine_create(char const *server, 
130
				  int msg_integrity)
131 132 133 134 135 136 137
{
  return stun_engine_tcreate(STUNTAG_SERVER(server), 
			     STUNTAG_INTEGRITY(msg_integrity), 
			     TAG_END());
}

/** 
Pekka Pessi's avatar
Pekka Pessi committed
138
 * Create a STUN engine 
139 140 141
 *
 * @param tag,value,... tag-value list 
 *
Pekka Pessi's avatar
Pekka Pessi committed
142
 * @TAGS
143 144 145 146 147
 * @TAG STUNTAG_SERVER() stun server hostname or dotted IPv4 address
 * @TAG STUNTAG_INTEGRITY() true if msg integrity should be used
 *
 */
stun_engine_t *stun_engine_tcreate(tag_type_t tag, tag_value_t value, ...)
Pekka Pessi's avatar
Pekka Pessi committed
148 149
{
  stun_engine_t *stun;
150 151 152
  char const *server = NULL;
  int msg_integrity = 1;
  ta_list ta;
153
  su_sockaddr_t su[1];
Pekka Pessi's avatar
Pekka Pessi committed
154 155

  SU_DEBUG_5(("%s(\"%s\"): called\n", 
156 157 158 159 160 161 162 163 164 165 166 167 168 169
	      "stun_engine_tcreate", server));

  ta_start(ta, tag, value);

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

  /* Enviroment overrides */
  if (getenv("STUN_SERVER")) {
    server = getenv("STUN_SERVER");
    SU_DEBUG_5(("stun: using STUN_SERVER=%s\n", server));
  }
170 171 172 173 174 175 176 177

  memset(su, 0, (sizeof su));

  if (server) {
    if (stun_atoaddr(&su->su_sin, server) != 0)
      return NULL;
  }

Pekka Pessi's avatar
Pekka Pessi committed
178 179 180 181 182 183 184
  stun = su_home_clone(NULL, sizeof(*stun));

  if (stun) {
    /* Store server address in *stun, run discovery process?? 
     * I suppose this may block for the moment
     */
    memset(&stun->stun_srvr4[0], 0, sizeof(stun->stun_srvr4[0]));
185 186 187 188 189

    if (server) {
      if (su->su_sin.sin_port == 0)
	su->su_sin.sin_port = htons(STUN_DEFAULT_PORT);
      stun->stun_srvr4[0] = su[0];
Pekka Pessi's avatar
Pekka Pessi committed
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
    }

    /* alternative address set to 0 */
    memset(&stun->stun_srvr4[1], 0, sizeof(stun->stun_srvr4[1])); 
    /* initialize username and password */
    stun_init_buffer(&stun->username);
    stun_init_buffer(&stun->password);

    stun->nattype = STUN_NAT_UNKNOWN;

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

    stun->use_msgint = 0;
    if(msg_integrity) {
      /* get shared secret */ 
      SU_DEBUG_3(("Contacting Server to obtain shared secret. Please wait.\n"));
      if(stun_get_sharedsecret(stun)==0) {
	SU_DEBUG_3(("Shared secret obtained from server.\n"));
	stun->use_msgint = 1;
      }
      else {
	SU_DEBUG_3(("Shared secret NOT obtained from server. Proceed without username/password.\n"));
      } 
    }
  }

  return stun;
}

/** Destroy a STUN client */ 
void stun_engine_destroy(stun_engine_t *stun)
{ 
  su_home_zap(stun->stun_home);
}

stun_socket_t *stun_socket_create(stun_engine_t *se, int sockfd)
{
  stun_socket_t *ss;

  if (se == NULL) return errno = EINVAL, NULL;

  ss = su_zalloc(se->stun_home, sizeof *ss);

  if (ss) {
    ss->ss_engine = se;
    ss->ss_sockfd = sockfd;
  }

  return ss;
}

void stun_socket_destroy(stun_socket_t *ss)
{
  if (ss)
    su_free(ss->ss_engine->stun_home, ss);
}

/** 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.
 * 
 */
int stun_bind(stun_socket_t *ss,
	      struct sockaddr *my_addr, 
	      socklen_t *addrlen,
	      int *lifetime)
{
  int retval = -1, sockfd;
  struct sockaddr_in *clnt_addr=0, bind_addr;
  socklen_t bind_len;
  /* testing su_getlocalinfo() */
  su_localinfo_t  hints[1] = {{ LI_CANONNAME | LI_NUMERIC }}, *li, *res = NULL;
  int i, error, found=0;
  
  /*   if (ss == NULL || my_addr == NULL || addrlen == NULL) */
  if (ss == NULL) 
    return errno = EFAULT, -1;

  clnt_addr = (struct sockaddr_in *)my_addr;

  if (clnt_addr==NULL || clnt_addr->sin_addr.s_addr == 0) {
    if((error = su_getlocalinfo(hints, &res)) == 0) {
      /* try to bind to the first available address */
      for(i=0, li = res; li; li = li->li_next) {
        if(li->li_family == AF_INET) {
          memcpy(clnt_addr, &li->li_addr->su_sin, sizeof(li->li_addr->su_sin));
          SU_DEBUG_3(("stun: local address found to be %s:%u\n", 
          inet_ntoa(clnt_addr->sin_addr), (unsigned)ntohs(clnt_addr->sin_port)));
          found=1;
          break;
        }
      }
305 306


Pekka Pessi's avatar
Pekka Pessi committed
307 308
      if(!found) {
        SU_DEBUG_5(("stun: su_getlocalinfo: %s\n", su_gli_strerror(error)));
309
	return errno = EFAULT, -1;
Pekka Pessi's avatar
Pekka Pessi committed
310 311 312 313 314 315
      }
    }
    else {
      SU_DEBUG_5(("stun: su_getlocalinfo: %s\n", su_gli_strerror(error)));
      return errno = EFAULT, -1;
    }
316
    if (res) su_freelocalinfo(res);
Pekka Pessi's avatar
Pekka Pessi committed
317 318 319 320 321 322
  }

  /* run protocol here... */
  sockfd = ss->ss_sockfd;

  if(bind(sockfd, (struct sockaddr *)clnt_addr, *addrlen)<0) {
323
    SU_DEBUG_3(("stun: Error binding to %s:%u\n", inet_ntoa(clnt_addr->sin_addr), (unsigned)ntohs(clnt_addr->sin_port)));
Pekka Pessi's avatar
Pekka Pessi committed
324 325 326 327 328 329
    return -1;
  }

  bind_len = sizeof(bind_addr);
  getsockname(sockfd, (struct sockaddr *)&bind_addr, &bind_len);
  
330
  SU_DEBUG_3(("stun: Local socket bound to: %s:%u\n", inet_ntoa(bind_addr.sin_addr), 
Pekka Pessi's avatar
Pekka Pessi committed
331
	      (unsigned)ntohs(bind_addr.sin_port)));
332

Pekka Pessi's avatar
Pekka Pessi committed
333 334 335

  retval = stun_bind_test(ss, (struct sockaddr_in *)&ss->ss_engine->stun_srvr4[0], 
			  clnt_addr, 0, 0);
336 337 338 339 340 341 342 343 344 345

  if (ss->ss_state != stun_cstate_done) {
    SU_DEBUG_3(("stun: Error in STUN discovery process.\n"));
    /* make sure the returned clnt_addr matches the local socket */
    if (*addrlen < bind_len)
      return errno = EFAULT, -1;
    else 
      memcpy(my_addr, &bind_addr, bind_len);
  }

Pekka Pessi's avatar
Pekka Pessi committed
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
  if (lifetime) {
    if (retval == 0)
      *lifetime = 3600;
    else
      *lifetime = -1;
  }

  /* note: we always report success if bind() succeeds */
  return 0;

}

/** Return type of NAT
 *  This function may take a long time to finish.
 *  NAT type is set in ss->se_engine.nattype
 */
int stun_get_nattype(stun_socket_t *ss, struct sockaddr *my_addr, int *addrlen)
{
  int nattype = STUN_NAT_UNKNOWN;
365 366
  int retval, lifetime, sockfd;
  socklen_t locallen, len;
Pekka Pessi's avatar
Pekka Pessi committed
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 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 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
  struct sockaddr_in local, mapped_addr1, mapped_addr2;
  
  sockfd = ss->ss_sockfd;
  
  len = sizeof(mapped_addr1);
  memcpy(&mapped_addr1, my_addr, len); 
  mapped_addr1.sin_port = 0; /* wild card for get_nattype */
  retval = stun_bind(ss, (struct sockaddr *)&mapped_addr1, &len, &lifetime);
  if(retval==-1) {
    if(errno==ETIMEDOUT) {
      /* No Response: Type 2 - UDP Blocked */
      retval = 0; /* time out is a legitimate response */
      nattype = STUN_UDP_BLOCKED;
    } /* otherwise unknown nat type */
  }
  else { /* Response comes back */
    memset(&local, 0, sizeof(local)); locallen = sizeof(local);
    getsockname(sockfd, (struct sockaddr *)&local, &locallen);
    if(memcmp(&local, &mapped_addr1, 8)==0) { /* Same IP and port*/
      /* conduct TEST II */      
      memset(&mapped_addr2, 0, sizeof(mapped_addr2));
      retval = stun_bind_test(ss, (struct sockaddr_in *)&ss->ss_engine->stun_srvr4[0],
			      &mapped_addr2, 1, 1);
      if(retval==-1) {
	if(errno==ETIMEDOUT) {
	  /* 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));
      retval = stun_bind_test(ss, (struct sockaddr_in *)&ss->ss_engine->stun_srvr4[0],
			      &mapped_addr2, 1, 1);
      if(retval==-1) {
	if(errno==ETIMEDOUT) {
	  /* No Response */
	  retval = stun_bind_test(ss, (struct sockaddr_in *)&ss->ss_engine->stun_srvr4[1], 
				  &mapped_addr2, 0, 0);
	  if(retval==0) { /* response comes back, has to be the case */
	    if(memcmp(&mapped_addr1, &mapped_addr2, 8)==0) {
	      /* Same Public IP and port, Test III, server ip 0 or 1 should be
		 same */
	      retval = stun_bind_test(ss, (struct sockaddr_in *)&ss->ss_engine->stun_srvr4[0],
				      &mapped_addr2, 0, 1);
	      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;
      }
    }
  }
  
  ss->ss_engine->nattype = nattype;
  return retval;
}

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

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

/** Shared secret request/response processing */
int stun_get_sharedsecret(stun_engine_t *se)
{
  stun_msg_t req, resp;
  int sockfd, z;
  SSL_CTX* ctx;
  SSL *ssl;
  X509* server_cert;
  unsigned char buf[512];
  stun_attr_t *password, *username;

  /* compose shared secret request */
  if(stun_make_sharedsecret_req(&req)!=0) {
    perror("shared secret request"); 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());

  if(ctx==NULL) {
    perror("openssl"); stun_free_buffer(&req.enc_buf); return -1;
  }

  if(SSL_CTX_set_cipher_list(ctx, "AES128-SHA")==0) {
    perror("openssl"); stun_free_buffer(&req.enc_buf); return -1;
  }

  /* open tcp connection to server */
  sockfd = socket(AF_INET, SOCK_STREAM, 0);
  if(sockfd == -1) {
    perror("socket"); stun_free_buffer(&req.enc_buf); return -1;
  }

  if(connect(sockfd, (struct sockaddr *)&se->stun_srvr4[0].su_sin, 
	     sizeof(struct sockaddr))==-1) {
    perror("connect"); stun_free_buffer(&req.enc_buf); return -1;
  }

  /* Start TLS negotiation */
  ssl = SSL_new(ctx);
  SSL_set_fd(ssl, sockfd);
  if(SSL_connect(ssl)==-1) {
    perror("SSL_connect"); stun_free_buffer(&req.enc_buf); return -1;
  }
  
  SU_DEBUG_3(("TLS connection using %s\n", SSL_get_cipher(ssl)));
  
  server_cert = SSL_get_peer_certificate(ssl); 
  if(server_cert) {
    SU_DEBUG_3(("\t subject: %s\n", X509_NAME_oneline(X509_get_subject_name(server_cert), 0, 0)));
    SU_DEBUG_3(("\t issuer: %s\n", X509_NAME_oneline(X509_get_issuer_name(server_cert), 0, 0)));
  }
  X509_free(server_cert);

  if(SSL_write(ssl, req.enc_buf.data, req.enc_buf.size)==-1) {
    perror("SSL_write"); stun_free_buffer(&req.enc_buf); return -1;
  }
  SU_DEBUG_5(("Shared Secret Request sent to server:\n"));
  debug_print(&req.enc_buf);

  z = SSL_read(ssl, buf, sizeof(buf));
  if(z<=0) {
    if (z < 0) {
      perror("SSL_read");
    }
    stun_free_buffer(&req.enc_buf);
    return -1;
  }
  resp.enc_buf.size = z;
  resp.enc_buf.data = malloc(z);
  memcpy(resp.enc_buf.data, buf, z);
  SU_DEBUG_5(("Shared Secret Response received from server:\n"));
  debug_print(&resp.enc_buf);

  /* closed TLS connection */
  SSL_shutdown(ssl);
  close(sockfd);

  SSL_free(ssl);
  SSL_CTX_free(ctx);

  stun_free_buffer(&req.enc_buf);
  
  /* process response */
  if(stun_parse_message(&resp) < 0) {
    perror("stun_parse_message"); stun_free_buffer(&resp.enc_buf); return -1;
  }

  switch(resp.stun_hdr.msg_type) {
  case SHARED_SECRET_RESPONSE:
    username = stun_get_attr(resp.stun_attr, USERNAME);
    password = stun_get_attr(resp.stun_attr, PASSWORD);
    if(username!=NULL && password!=NULL) {
      /* move result to se */
      stun_copy_buffer(&se->username, username->pattr);
      stun_copy_buffer(&se->password, password->pattr);
    }
    break;
  case SHARED_SECRET_ERROR_RESPONSE:
    if(stun_process_error_response(&resp) <0) {
      SU_DEBUG_5(("Error in Shared Secret Error Response.\n")); 
    }
    stun_free_buffer(&resp.enc_buf);
    return -1;
    
    break;
  default:
    break;
  }
  return 0;
}

/** Compose a STUN message of the format defined by stun_msg_t
 *  result encoded in enc_buf ready for sending as well.
 */
int stun_make_sharedsecret_req(stun_msg_t *msg)
{

  int i, len; 
  uint16_t tmp;

  /* compose header */
  msg->stun_hdr.msg_type = SHARED_SECRET_REQUEST;
  msg->stun_hdr.msg_len = 0; /* actual len computed by
				stun_send_message */
  for(i=0; i<8; i++) {
    msg->stun_hdr.tran_id[i] = (1+rand()%RAND_MAX_16);
  } 
  
  /* no buffer assigned yet */
  stun_init_buffer(&msg->enc_buf);
  
  msg->enc_buf.data = malloc(20);
  msg->enc_buf.size = 20;

  tmp = htons(msg->stun_hdr.msg_type); len = 0;
  memcpy(msg->enc_buf.data, &tmp, sizeof(tmp)); len+=sizeof(tmp);
  tmp = htons(msg->stun_hdr.msg_len);
  memcpy(msg->enc_buf.data+len, &tmp, sizeof(tmp)); len+=sizeof(tmp);
  for(i=0; i<8; i++) {
    tmp = htons(msg->stun_hdr.tran_id[i]);
    memcpy(msg->enc_buf.data+len, &tmp, sizeof(tmp)); len+=sizeof(tmp);
  }
  
  return 0;
}

/** This function send a binding request to the address at serv (ip,
 *  port). which could be the original or alternative socket addresses
 *  of the STUN server. Local address is provided in cli, and
 *  resulting mapped address is also saved in cli.
 *  Return 0 if successful, -1 if failed
 *
 * @return
 * On success, zero is returned.  Upon error, -1 is returned, and @e errno is
 * set appropriately.
 * 
 * @ERRORS
 * @ERROR EBADF           @a sockfd is not a valid deseriptor.
 * @ERROR EPROTONOSUPPORT @a sockfd is not an 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.
 * @ERROR ETIMEDOUT       Request timed out.
 * 
 */   
int stun_bind_test(stun_socket_t *ss, struct sockaddr_in *srvr_addr, struct sockaddr_in *clnt_addr, 
		   int chg_ip, int chg_port) 
{
  int retval = -1, sockfd, z, clnt_addr_len;
  stun_msg_t bind_req, bind_resp;
  unsigned char dgram[512];
  stun_attr_t *mapped_addr, *chg_addr;
  struct sockaddr_in recv_addr;
637
  socklen_t recv_addr_len;
Pekka Pessi's avatar
Pekka Pessi committed
638 639 640 641 642 643
  /* for retransmission */
  int num_retrx=0;
  long retrx_int=100000;
  fd_set rfds;
  struct timeval tv;
  
644 645
  ss->ss_state = stun_cstate_init;

Pekka Pessi's avatar
Pekka Pessi committed
646 647 648 649 650 651 652 653 654 655
  if (ss == NULL || srvr_addr == NULL || clnt_addr == NULL) 
    return errno = EFAULT, retval;

  /* run protocol here... */
  sockfd = ss->ss_sockfd;

  /* compose binding request */
  if(stun_make_binding_req(ss, &bind_req, chg_ip, chg_port)<0) 
    return retval;

656 657
  ss->ss_state = stun_cstate_started;

658 659
  if(stun_send_message(sockfd, srvr_addr, &bind_req, &(ss->ss_engine->password))<0) {
    stun_free_message(&bind_req);
Pekka Pessi's avatar
Pekka Pessi committed
660
    return retval;
661
  }
Pekka Pessi's avatar
Pekka Pessi committed
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681

  FD_ZERO(&rfds);
  FD_SET(sockfd, &rfds); /* Set sockfd for read monitoring */
  z = 0;
  while(num_retrx < STUN_MAX_RETRX && z <= 0) {
    if(retrx_int < 1000000) {
      tv.tv_sec = 0;
      tv.tv_usec = retrx_int;
      retrx_int *= 2; /* double retransmission period */
    }
    else {
      tv.tv_sec = 1;
      tv.tv_usec = retrx_int - 1000000;
    }
    if(select(sockfd+1, &rfds, NULL, NULL, &tv)) {
      /* response received */
      recv_addr_len = sizeof(recv_addr);
      z = recvfrom(sockfd, dgram, 512, 0,
		   (struct sockaddr *)&recv_addr, &recv_addr_len);
      if(z<0) {
682
	stun_free_message(&bind_req);
Pekka Pessi's avatar
Pekka Pessi committed
683 684 685 686 687 688 689 690 691 692 693
	return retval;
      }
      bind_resp.enc_buf.data = (unsigned char *)malloc(z);
      bind_resp.enc_buf.size = z;
      memcpy(bind_resp.enc_buf.data, dgram, z);
      SU_DEBUG_5(("response from server %s:%u\n", inet_ntoa(recv_addr.sin_addr), ntohs(recv_addr.sin_port)));
      debug_print(&bind_resp.enc_buf);      
    }
    else {
      SU_DEBUG_3(("Time out no. %d, retransmitting.\n", ++num_retrx));
      if(stun_send_message(sockfd, srvr_addr, &bind_req, &(ss->ss_engine->password))<0) {
694
	stun_free_message(&bind_req);
Pekka Pessi's avatar
Pekka Pessi committed
695 696 697 698 699
	return retval;
      }
    }
  }

700 701
  ss->ss_state = stun_cstate_received;

Pekka Pessi's avatar
Pekka Pessi committed
702
  if(num_retrx == STUN_MAX_RETRX) {
703
    stun_free_message(&bind_req);
Pekka Pessi's avatar
Pekka Pessi committed
704 705 706 707 708 709
    return errno = ETIMEDOUT, retval;
  }

  /* process response */
  if(stun_parse_message(&bind_resp) < 0) {
    SU_DEBUG_5(("Error parsing response.\n"));
710 711
    stun_free_message(&bind_req);
    stun_free_message(&bind_req);
Pekka Pessi's avatar
Pekka Pessi committed
712 713 714
    return retval;
  }

715 716
  ss->ss_state = stun_cstate_processing;

Pekka Pessi's avatar
Pekka Pessi committed
717 718 719
  switch(bind_resp.stun_hdr.msg_type) {
  case BINDING_RESPONSE:
    if(stun_validate_message_integrity(&bind_resp, &ss->ss_engine->password) <0) {
720 721
      stun_free_message(&bind_req);
      stun_free_message(&bind_resp);
Pekka Pessi's avatar
Pekka Pessi committed
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
      return retval;
    }
    memset(clnt_addr, 0, sizeof(*clnt_addr)); clnt_addr_len = sizeof(*clnt_addr);
    mapped_addr = stun_get_attr(bind_resp.stun_attr, MAPPED_ADDRESS);
    if(mapped_addr!=NULL) {
      /* mapped address is the response */      
      memcpy(clnt_addr, mapped_addr->pattr, clnt_addr_len);

      retval = 0;
    }
    /* update alternative server address */
    if(ss->ss_engine->stun_srvr4[1].su_sin.sin_family==0) {
      /* alternative server address not present */
      chg_addr = stun_get_attr(bind_resp.stun_attr, CHANGED_ADDRESS);
      if(chg_addr!=NULL) {
	memcpy(&ss->ss_engine->stun_srvr4[1].su_sin, chg_addr->pattr, sizeof(struct sockaddr_in));
      }
    }
    break;
  case BINDING_ERROR_RESPONSE:
    if(stun_process_error_response(&bind_resp)<0) {
      SU_DEBUG_3(("Error in Binding Error Response.\n"));
    }
    break;
  default:
    break;
  }
  /* return result */

751 752 753
  stun_free_message(&bind_resp);
  stun_free_message(&bind_req);

754 755
  ss->ss_state = stun_cstate_done;

Pekka Pessi's avatar
Pekka Pessi committed
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 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 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
  return retval;
}

/** Compose a STUN message of the format defined by stun_msg_t */
int stun_make_binding_req(stun_socket_t *ss, stun_msg_t *msg, int chg_ip, int chg_port) {

  int i;
  stun_attr_t *tmp, **p; 

  /* compose header */
  msg->stun_hdr.msg_type = BINDING_REQUEST;
  msg->stun_hdr.msg_len = 0; /* actual len computed by
				stun_send_message */
  for(i=0; i<8; i++) {
    msg->stun_hdr.tran_id[i] = (1+rand()%RAND_MAX_16);
  } 
  
  /* optional attributes:
   * - Response Address
   * - Change Request X
   * - Username
   * - Message-Integrity */
  msg->stun_attr = NULL;
  /* CHANGE_REQUEST */
  p = &(msg->stun_attr);
  if(chg_ip || chg_port) {
    stun_attr_changerequest_t *attr_cr;
    tmp = (stun_attr_t *) malloc(sizeof(stun_attr_t));
    tmp->attr_type = CHANGE_REQUEST;
    attr_cr = (stun_attr_changerequest_t *) malloc(sizeof(stun_attr_changerequest_t));
    attr_cr->value = (chg_ip? STUN_CR_CHANGE_IP:0)|(chg_port? STUN_CR_CHANGE_PORT:0);
    tmp->pattr = attr_cr;
    tmp->next = NULL;
    *p = tmp; p = &(tmp->next);
  }

  /* USERNAME */
  if(ss->ss_engine->use_msgint &&
     ss->ss_engine->username.data && 
     ss->ss_engine->password.data) {
    tmp = (stun_attr_t *) malloc(sizeof(stun_attr_t));
    tmp->attr_type = USERNAME;
    tmp->pattr = &ss->ss_engine->username;
    tmp->next = NULL;
    *p = tmp; p = &(tmp->next);

    /* dummy MESSAGE_INTEGRITY attribute, computed later */
    tmp = (stun_attr_t *) malloc(sizeof(stun_attr_t));
    tmp->attr_type = MESSAGE_INTEGRITY;
    tmp->pattr = NULL;
    tmp->next = NULL;
    *p = tmp; p = &(tmp->next);
  }

  /* no buffer assigned yet */
  msg->enc_buf.data = NULL;
  msg->enc_buf.size = 0;
  return 0;
}

int stun_process_response(stun_msg_t *msg) {

  /* parse msg first */
  if(stun_parse_message(msg)<0) {
    SU_DEBUG_3(("Error parsing response.\n"));
    return -1;
  }

  /* check message digest if exists */
  switch(msg->stun_hdr.msg_type) {
  case BINDING_RESPONSE:
    if(stun_process_binding_response(msg) < 0) 
      return -1;
    break;
  case BINDING_ERROR_RESPONSE:
    if(stun_process_error_response(msg) < 0)
      return -1;
    break;
  default:
    return -1;
  }

  return 0;
}


/** process binding response */
int stun_process_binding_response(stun_msg_t *msg) {
  /* currently not needed. */
  return 0;
}

/** process binding error response
 *  Report error and return
 */
int stun_process_error_response(stun_msg_t *msg) {
  stun_attr_t *attr;
  stun_attr_errorcode_t *ec;

  attr = stun_get_attr(msg->stun_attr, ERROR_CODE);
  if(attr==NULL) {perror("stun_process_error_response"); return -1;}

  ec = (stun_attr_errorcode_t *)attr->pattr;
  
  SU_DEBUG_5(("Received Binding Error Response:\n"));
  SU_DEBUG_5(("Error: %d %s\n", ec->code, ec->phrase));

  return 0;
}

int stun_set_uname_pwd(stun_engine_t *se, const unsigned char *uname, int len_uname, 
		       const unsigned char *pwd, int len_pwd) {
  se->username.data = (unsigned char *) malloc(len_uname);
  memcpy(se->username.data, uname, len_uname);
  se->username.size = len_uname;
  
  se->password.data = (unsigned char *) malloc(len_pwd);
  memcpy(se->password.data, pwd, len_pwd);
  se->password.size = len_pwd;

  se->use_msgint = 1; /* turn on message integrity ussage */
  
  return 0;
}
  
/* convert character address format to sockaddr_in */
int stun_atoaddr(struct sockaddr_in *addr, char const *in)
{
884 885 886 887 888 889 890 891 892 893 894
  su_addrinfo_t *ai_res = NULL, *ai, hints[1] = {{ 0 }};
  char const *host;
  char *port, tmp[SU_ADDRSIZE];
  int res;

  hints->ai_family = AF_INET;

  port = strstr(in, ":");
  if (port == NULL) {
    /* no port specified */
    host = in;
Pekka Pessi's avatar
Pekka Pessi committed
895 896
  }
  else {
897 898 899 900 901
    assert(port - in < strlen(in) + 1);
    memcpy(tmp, in, port - in);
    tmp[port - in] = 0;
    host = tmp;
    ++port;
Pekka Pessi's avatar
Pekka Pessi committed
902
  }
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
    
  res = su_getaddrinfo(host, NULL, hints, &ai_res);
  for (ai = ai_res; 
       ai;
       ai = ai->ai_next) {
    if (ai->ai_family == AF_INET) {
      memcpy(addr, ai_res->ai_addr, sizeof(struct sockaddr));
      break;
    }
  }

  if (port) 
    addr->sin_port = htons(atoi(port));

  if (ai_res)
    su_freeaddrinfo(ai_res);

  return res;
Pekka Pessi's avatar
Pekka Pessi committed
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939
}

char const *stun_nattype(stun_engine_t *se)
{
  switch(se->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";
  }
}

int stun_get_lifetime(stun_socket_t *ss, struct sockaddr *my_addr, int *addrlen, int *lifetime)
{
940 941
  int retval = -1, sockfdx, sockfdy;
  socklen_t x_len, y_len, recv_addr_len, mapped_len;
Pekka Pessi's avatar
Pekka Pessi committed
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
  struct sockaddr_in *clnt_addr=0, x_addr, y_addr, recv_addr, mapped_addr;
  int lt_cur=0, lt=STUN_LIFETIME_EST, lt_max = STUN_LIFETIME_MAX;
  stun_attr_t *mapped_addr_attr;
  /* testing su_getlocalinfo() */
  su_localinfo_t  hints[1] = {{ LI_CANONNAME | LI_NUMERIC }}, *li, *res = NULL;
  int i, error, found=0, z;
  fd_set rfds;
  struct timeval tv;
  stun_msg_t bind_req, bind_resp;
  unsigned char dgram[512];


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

  SU_DEBUG_3(("stun: determining binding life time, this may take a while.\n"));

  /* get local ip address */
  clnt_addr = (struct sockaddr_in *)my_addr;

  if(clnt_addr==NULL || clnt_addr->sin_addr.s_addr == 0) {
    if((error = su_getlocalinfo(hints, &res)) == 0) {
      /* try to bind to the first available address */
      for(i=0, li = res; li; li = li->li_next) {
	if(li->li_family == AF_INET) {
	  memcpy(clnt_addr, &li->li_addr->su_sin, sizeof(li->li_addr->su_sin));
	  SU_DEBUG_3(("stun: local address found to be %s:%u\n", 
		      inet_ntoa(clnt_addr->sin_addr), 
		      (unsigned)ntohs(clnt_addr->sin_port)));
	  found=1;
	  break;
	}
      }
      if(!found) {
	SU_DEBUG_5(("stun: su_getlocalinfo: %s\n", su_gli_strerror(error)));
	return errno = EFAULT, -1;
      }
    }
    else {
      SU_DEBUG_5(("stun: su_getlocalinfo: %s\n", su_gli_strerror(error)));
      return errno = EFAULT, -1;
    }
  }

  /* run protocol here... */
  sockfdx = ss->ss_sockfd;

  clnt_addr->sin_port = 0;
  /* initialize socket x */
  if(bind(sockfdx, (struct sockaddr *)clnt_addr, *addrlen)<0) {
    SU_DEBUG_3(("Error binding to %s:%u\n", inet_ntoa(clnt_addr->sin_addr), (unsigned)ntohs(clnt_addr->sin_port)));
    return retval;
  }
  x_len = sizeof(x_addr);
  getsockname(sockfdx, (struct sockaddr *)&x_addr, &x_len);  
  SU_DEBUG_3(("Local socket x bound to: %s:%u\n", inet_ntoa(x_addr.sin_addr),
	      (unsigned)ntohs(x_addr.sin_port)));

  /* initialize socket y */
  sockfdy = socket(AF_INET, SOCK_DGRAM, 0);
  if(bind(sockfdy, (struct sockaddr *)clnt_addr, *addrlen)<0) {
    SU_DEBUG_3(("Error binding to %s:%u\n", inet_ntoa(clnt_addr->sin_addr), (unsigned)ntohs(clnt_addr->sin_port)));
    return retval;
  }
  y_len = sizeof(y_addr);
  getsockname(sockfdy, (struct sockaddr *)&y_addr, &y_len);  
  SU_DEBUG_3(("Local socket y bound to: %s:%u\n", inet_ntoa(y_addr.sin_addr), 
	      (unsigned)ntohs(y_addr.sin_port)));
   
  i=1;
  while(abs(lt_cur-lt) > STUN_LIFETIME_CI) {
    SU_DEBUG_3(("STUN Lifetime determination round %d, testing lifetime of %d sec.\n", i++, lt));
    /* send request from X */
    if(stun_make_binding_req(ss, &bind_req, 0, 0) <0)
      return retval;
    if(stun_send_message(sockfdx, (struct sockaddr_in *)&ss->ss_engine->stun_srvr4[0], &bind_req, &(ss->ss_engine->password))<0)
      return retval;

    FD_ZERO(&rfds);
    FD_SET(sockfdx, &rfds); /* Set sockfdx for read monitoring */
    z = 0;
    tv.tv_sec = 5;
    tv.tv_usec = 0;
    if(select(sockfdx+1, &rfds, NULL, NULL, &tv)) {
      /* response received */
      recv_addr_len = sizeof(recv_addr);
      z = recvfrom(sockfdx, dgram, 512, 0,
		   (struct sockaddr *)&recv_addr, &recv_addr_len);
      if(z<0) {
	return retval;
      }
      bind_resp.enc_buf.data = (unsigned char *)malloc(z);
      bind_resp.enc_buf.size = z;
      memcpy(bind_resp.enc_buf.data, dgram, z);
      SU_DEBUG_3(("response from server %s:%u\n", inet_ntoa(recv_addr.sin_addr), ntohs(recv_addr.sin_port)));
      debug_print(&bind_resp.enc_buf);      
    }
    else {
      SU_DEBUG_3(("No response from server. Check configuration.\n"));
      return retval;
    }
    /* process response */
    if(stun_parse_message(&bind_resp) < 0) {
      SU_DEBUG_5(("Error parsing response.\n"));
      return retval;
    }
    if(bind_resp.stun_hdr.msg_type==BINDING_RESPONSE) {
      memset(&mapped_addr, 0, sizeof(mapped_addr)); mapped_len = sizeof(mapped_addr);
      mapped_addr_attr = stun_get_attr(bind_resp.stun_attr, MAPPED_ADDRESS);
      if(mapped_addr_attr!=NULL) {
	memcpy(&mapped_addr, mapped_addr_attr->pattr, mapped_len);
      }
      else {
	return retval;
      }
    }
    stun_free_message(&bind_req);
    stun_free_message(&bind_resp);
    sleep(lt);
    /* send from sockfdy */
    if(stun_make_binding_req(ss, &bind_req, 0, 0) <0)
      return retval;
    stun_add_response_address(&bind_req, &mapped_addr);
    if(stun_send_message(sockfdy, (struct sockaddr_in *)&ss->ss_engine->stun_srvr4[0], &bind_req, &(ss->ss_engine->password))<0)
      return retval;

    FD_ZERO(&rfds);
    FD_SET(sockfdx, &rfds); /* Set sockfdx for read monitoring */
    z = 0;
    tv.tv_sec = 5;
    tv.tv_usec = 0;
    if(select(sockfdx+1, &rfds, NULL, NULL, &tv)) {
      /* response received */
      recv_addr_len = sizeof(recv_addr);
      z = recvfrom(sockfdx, dgram, 512, 0,
		   (struct sockaddr *)&recv_addr, &recv_addr_len);
      if(z<0) {
	return retval;
      }
      /* mapping with X still valid */
      lt_cur = lt;
      lt = (int) (lt+lt_max)/2;
      SU_DEBUG_3(("Response received from socket X, lifetime at least %d sec, next trial: %d sec\n\n", 
		  lt_cur, lt));
    }
    else {
      /* no response */
      lt_max = lt;
      lt = (int) (lt+lt_cur)/2;
      SU_DEBUG_3(("No response received from socket X, lifetime at most %d sec, next trial: %d sec\n\n", 
		  lt_max, lt));
    }
  }

  *lifetime = lt_cur;
  return 0;
}

int stun_add_response_address(stun_msg_t *req, struct sockaddr_in *mapped_addr)
{
  stun_attr_sockaddr_t *addr;
  stun_attr_t *tmp;

  tmp = (stun_attr_t *)malloc(sizeof(stun_attr_t));
  tmp->attr_type = RESPONSE_ADDRESS;
  addr = malloc(sizeof(stun_attr_sockaddr_t));
  memcpy(addr, mapped_addr, sizeof(stun_attr_sockaddr_t));
  tmp->pattr = addr;
  
  if(req->stun_attr==NULL) {
    tmp->next = NULL;
  }
  else {
    tmp->next = req->stun_attr;
  }
  req->stun_attr = tmp;

  return 0;
}