stun.c 72.5 KB
Newer Older
aymeric's avatar
aymeric committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
 /*
  The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack.
  Copyright (C) 2001  Simon MORLAT simon.morlat@linphone.org

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

/* ====================================================================
 * The Vovida Software License, Version 1.0 
 * 
 * Copyright (c) 2000 Vovida Networks, Inc.  All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 
 * 3. The names "VOCAL", "Vovida Open Communication Application Library",
 *    and "Vovida Open Communication Application Library (VOCAL)" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact vocal@vovida.org.
 *
 * 4. Products derived from this software may not be called "VOCAL", nor
 *    may "VOCAL" appear in their name, without prior written
 *    permission of Vovida Networks, Inc.
 * 
 * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
 * NON-INFRINGEMENT ARE DISCLAIMED.  IN NO EVENT SHALL VOVIDA
 * NETWORKS, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT DAMAGES
 * IN EXCESS OF $1,000, NOR FOR ANY INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
 * DAMAGE.
 * 
 * ====================================================================
 * 
 * This software consists of voluntary contributions made by Vovida
 * Networks, Inc. and many individuals on behalf of Vovida Networks,
 * Inc.  For more information on Vovida Networks, Inc., please see
 * <http://www.vovida.org/>.
 *
 */

#ifndef _WIN32_WCE
#include <errno.h>
#endif

#include <assert.h>

#if defined(WIN32) || defined(_WIN32_WCE)
#include <winsock2.h>
#include <stdlib.h>
/* #include <io.h> */
#include <time.h>
#include <ctype.h> /*for isdigit() */
#else

#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h> 
#include <arpa/inet.h>
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/nameser.h>
#include <resolv.h>
#include <net/if.h>

#endif


aymeric's avatar
aymeric committed
102
//#define NOSSL
aymeric's avatar
aymeric committed
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
/*
  #if defined(__sparc__) || defined(WIN32)
  #define NOSSL
  #endif
  #define NOSSL
*/

#include "ortp/stun_udp.h"
#include "ortp/stun.h"
#include "ortp/ortp.h"

static char *ipaddr(const StunAddress4 *addr)
{
   static char tmp[512];
   struct in_addr inaddr;
   char *atmp;
   inaddr.s_addr = htonl(addr->addr);
   atmp = (char *)inet_ntoa(inaddr);
   
   snprintf(tmp, 512, "%s:%i", atmp, addr->port);
   return tmp;
}

static void
aymeric's avatar
aymeric committed
127 128 129 130
computeHmac_longterm(char* hmac, const char* input, int length,
                     const char *username, const char *realm, const char *password);
static void
computeHmac_shortterm(char* hmac, const char* input, int length, const char* key);
aymeric's avatar
aymeric committed
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171

static bool_t 
stunParseAtrAddress( char* body, unsigned int hdrLen,  StunAtrAddress4 *result )
{
   if ( hdrLen != 8 )
   {
      ortp_error("stun: hdrLen wrong for Address\n");
      return FALSE;
   }
   result->pad = *body++;
   result->family = *body++;
   if (result->family == IPv4Family)
   {
      UInt16 nport;
      UInt32 naddr;
      memcpy(&nport, body, 2); body+=2;
      result->ipv4.port = ntohs(nport);

      memcpy(&naddr, body, 4); body+=4;
      result->ipv4.addr = ntohl(naddr);
      return TRUE;
   }
   else if (result->family == IPv6Family)
   {
      ortp_error("stun: ipv6 not supported\n");
   }
   else
   {
      ortp_error("stun: bad address family: %i\n", result->family);
   }
	
   return FALSE;
}

static bool_t 
stunParseAtrChangeRequest( char* body, unsigned int hdrLen,  StunAtrChangeRequest *result )
{
   if ( hdrLen != 4 )
   {
     /* ortp_error("stun: hdr length = %i expecting %i\n",hdrLen, sizeof(result)); */
		
aymeric's avatar
aymeric committed
172
      ortp_error("stun: Incorrect size for SA_CHANGEREQUEST");
aymeric's avatar
aymeric committed
173 174 175 176 177 178 179 180 181 182 183 184 185
      return FALSE;
   }
   else
   {
      memcpy(&result->value, body, 4);
      result->value = ntohl(result->value);
      return TRUE;
   }
}

static bool_t 
stunParseAtrError( char* body, unsigned int hdrLen,  StunAtrError *result )
{
aymeric's avatar
aymeric committed
186
   if ( hdrLen >= sizeof(StunAtrError) )
aymeric's avatar
aymeric committed
187
   {
aymeric's avatar
aymeric committed
188
      ortp_error("stun: Incorrect size for SA_ERRORCODE");
aymeric's avatar
aymeric committed
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
      return FALSE;
   }
   else
   {
      memcpy(&result->pad, body, 2); body+=2;
      result->pad = ntohs(result->pad);
      result->errorClass = *body++;
      result->number = *body++;
		
      result->sizeReason = hdrLen - 4;
      memcpy(&result->reason, body, result->sizeReason);
      result->reason[result->sizeReason] = 0;
      return TRUE;
   }
}

static bool_t 
stunParseAtrUnknown( char* body, unsigned int hdrLen,  StunAtrUnknown *result )
{
   if ( hdrLen >= sizeof(result) )
   {
aymeric's avatar
aymeric committed
210
      ortp_error("stun: Incorrect size for SA_UNKNOWNATTRIBUTE");
aymeric's avatar
aymeric committed
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
      return FALSE;
   }
   else
   {
      int i;
      if (hdrLen % 4 != 0) return FALSE;
      result->numAttributes = hdrLen / 4;
      for (i=0; i<result->numAttributes; i++)
      {
         memcpy(&result->attrType[i], body, 2); body+=2;
         result->attrType[i] = ntohs(result->attrType[i]);
      }
      return TRUE;
   }
}

static bool_t 
stunParseAtrString( char* body, unsigned int hdrLen,  StunAtrString *result )
{
   if ( hdrLen >= STUN_MAX_STRING )
   {
      ortp_error("stun: String is too large");
      return FALSE;
   }
   else
   {
      result->sizeValue = hdrLen;
      memcpy(&result->value, body, hdrLen);
      result->value[hdrLen] = 0;
      return TRUE;
   }
}


static bool_t 
stunParseAtrIntegrity( char* body, unsigned int hdrLen,  StunAtrIntegrity *result )
{
   if ( hdrLen != 20)
   {
aymeric's avatar
aymeric committed
250
      ortp_error("stun: SA_MESSAGEINTEGRITY must be 20 bytes");
aymeric's avatar
aymeric committed
251 252 253 254 255 256 257 258 259
      return FALSE;
   }
   else
   {
      memcpy(&result->hash, body, hdrLen);
      return TRUE;
   }
}

aymeric's avatar
aymeric committed
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 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
static bool_t 
turnParseAtrChannelNumber( char* body, unsigned int hdrLen,  TurnAtrChannelNumber *result )
{
   if ( hdrLen >= sizeof(result) )
   {
      ortp_error("stun: Incorrect size for TA_CHANNELNUMBER");
      return FALSE;
   }
   else
   {
      if (hdrLen % 4 != 0) return FALSE;
      memcpy(&result->channelNumber, body, 2);
      body+=2;
      result->channelNumber = ntohs(result->channelNumber);
      memcpy(&result->rffu, body, 2);
      body+=2;
      result->rffu = ntohs(result->rffu);
      return TRUE;
   }
}

static bool_t 
turnParseAtrLifetime( char* body, unsigned int hdrLen,  TurnAtrLifetime *result )
{
   if ( hdrLen != sizeof(result) )
   {
      ortp_error("stun: Incorrect size for TA_LIFETIME");
      return FALSE;
   }
   else
   {
      memcpy(&result->lifetime, body, 4);
      result->lifetime = ntohl(result->lifetime);
      return TRUE;
   }
}

static bool_t 
turnParseAtrData( char* body, unsigned int hdrLen,  TurnAtrData *result )
{
   if ( hdrLen >= 1500 )
   {
      ortp_error("stun: Incorrect size for TA_DATA");
      return FALSE;
   }
   else
   {
      result->sizeValue = hdrLen;
      memcpy(&result->value, body, hdrLen);
      result->value[hdrLen] = 0;
      return TRUE;
   }
}

static bool_t 
turnParseAtrRequestedTransport( char* body, unsigned int hdrLen,  TurnAtrRequestedTransport *result )
{
   if ( hdrLen != 4 )
   {
      ortp_error("stun: Incorrect size for TA_REQUESTEDTRANSPORT");
      return FALSE;
   }
   result->proto = *body++;
   result->pad1 = *body++;
   result->pad2 = *body++;
   result->pad3 = *body++;
   return TRUE;
}

#ifdef ORTP_BIGENDIAN
#define htonq(n) n
#define ntohq(n) n
#else /* little endian */
static inline UInt64
htonq (UInt64 v)
{
  return htonl ((UInt32) (v >> 32))
    | (UInt64) htonl ((UInt32) v) << 32;
}
static inline UInt64
ntohq (UInt64 v)
{
  return ntohl ((UInt32) (v >> 32))
    | (UInt64) ntohl ((UInt32) v) << 32;
}
#endif /* little endian */

static bool_t 
turnParseAtrReservationToken( char* body, unsigned int hdrLen,  TurnAtrReservationToken *result )
{
  if ( hdrLen != 8 )
  {
    ortp_error("stun: Incorrect size for TA_RESERVATIONTOKEN");
    return FALSE;
  }
  memcpy(&result->value, body, 8);
  result->value = ntohq(result->value);
  return TRUE;
}

static bool_t 
turnParseAtrFingerprint( char* body, unsigned int hdrLen, TurnAtrFingerprint *result )
{
  if ( hdrLen != 4 )
  {
    ortp_error("stun: Incorrect size for SA_FINGERPRINT");
    return FALSE;
  }

  memcpy(&result->fingerprint, body, 4);
  result->fingerprint = ntohl(result->fingerprint);
  return TRUE;
}

static bool_t 
iceParseAtrPriority( char* body, unsigned int hdrLen, IceAtrPriority *result )
{
  if ( hdrLen != sizeof(result) )
  {
    ortp_error("stun: Incorrect size for ICEA_PRIORITY");
    return FALSE;
  }

  memcpy(&result->priority, body, 4);
  result->priority = ntohl(result->priority);
  return TRUE;
}

static bool_t 
iceParseAtrIceControll( char* body, unsigned int hdrLen, IceAtrIceControll *result )
{
  if ( hdrLen != sizeof(result) )
  {
    ortp_error("stun: Incorrect size for ICEA_ICECONTROLLED/ICEA_ICECONTROLLING");
    return FALSE;
  }
  memcpy(&result->value, body, 8);
  result->value = ntohq(result->value);
  return TRUE;
} 
aymeric's avatar
aymeric committed
400 401

bool_t
aymeric's avatar
aymeric committed
402
stunParseMessage( char* buf, unsigned int bufLen, StunMessage *msg)
aymeric's avatar
aymeric committed
403 404 405
{
   char* body;
   unsigned int size;
aymeric's avatar
aymeric committed
406
	 ortp_debug("stun: Received stun message: %i bytes\n", bufLen);
aymeric's avatar
aymeric committed
407 408 409 410
   memset(msg, 0, sizeof(msg));
	
   if (sizeof(StunMsgHdr) > bufLen)
   {
aymeric's avatar
aymeric committed
411
      ortp_warning("stun: message too short\n");
aymeric's avatar
aymeric committed
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
      return FALSE;
   }

   memcpy(&msg->msgHdr, buf, sizeof(StunMsgHdr));
   msg->msgHdr.msgType = ntohs(msg->msgHdr.msgType);
   msg->msgHdr.msgLength = ntohs(msg->msgHdr.msgLength);

   if (msg->msgHdr.msgLength + sizeof(StunMsgHdr) != bufLen)
   {
      ortp_warning("stun: Message header length doesn't match message size: %i - %i\n", msg->msgHdr.msgLength, bufLen);
      return FALSE;
   }

   body = buf + sizeof(StunMsgHdr);
   size = msg->msgHdr.msgLength;
	
   /*ortp_message("stun: bytes after header = %i\n", size); */
	
   while ( size > 0 )
   {
      /* !jf! should check that there are enough bytes left in the buffer */
		
      StunAtrHdr* attr = (StunAtrHdr*)body; /*reinterpret_cast<StunAtrHdr*>(body);*/
		
      unsigned int attrLen = ntohs(attr->length);
      int atrType = ntohs(attr->type);
		
      if ( attrLen+4 > size ) 
      {
         ortp_error("stun: claims attribute is larger than size of message (attribute type=%i)\n", atrType);
         return FALSE;
      }
		
      body += 4; /* skip the length and type in attribute header */
      size -= 4;
		
aymeric's avatar
aymeric committed
448
      if (atrType == SA_MAPPEDADDRESS)
aymeric's avatar
aymeric committed
449 450 451 452
      {
            msg->hasMappedAddress = TRUE;
            if ( stunParseAtrAddress(  body,  attrLen,  &msg->mappedAddress )== FALSE )
            {
aymeric's avatar
aymeric committed
453
               ortp_error("stun: problem parsing SA_MAPPEDADDRESS\n");
aymeric's avatar
aymeric committed
454 455 456 457
               return FALSE;
            }
            else
            {
aymeric's avatar
aymeric committed
458
               ortp_debug("stun: SA_MAPPEDADDRESS = %s\n", ipaddr(&msg->mappedAddress.ipv4));
aymeric's avatar
aymeric committed
459 460 461
            }
					
      }
aymeric's avatar
aymeric committed
462
      else if (atrType == SA_RESPONSEADDRESS)
aymeric's avatar
aymeric committed
463 464 465 466
      {
            msg->hasResponseAddress = TRUE;
            if ( stunParseAtrAddress(  body,  attrLen,  &msg->responseAddress )== FALSE )
            {
aymeric's avatar
aymeric committed
467
               ortp_error("stun: problem parsing SA_RESPONSEADDRESS");
aymeric's avatar
aymeric committed
468 469 470 471
               return FALSE;
            }
            else
            {
aymeric's avatar
aymeric committed
472
               ortp_debug("stun: SA_RESPONSEADDRESS = %s\n", ipaddr(&msg->responseAddress.ipv4));
aymeric's avatar
aymeric committed
473 474
            }
      }
aymeric's avatar
aymeric committed
475
      else if (atrType == SA_CHANGEREQUEST)
aymeric's avatar
aymeric committed
476 477 478 479
      {
            msg->hasChangeRequest = TRUE;
            if (stunParseAtrChangeRequest( body, attrLen, &msg->changeRequest) == FALSE)
            {
aymeric's avatar
aymeric committed
480
               ortp_error("stun: problem parsing SA_CHANGEREQUEST\n");
aymeric's avatar
aymeric committed
481 482 483 484
               return FALSE;
            }
            else
            {
aymeric's avatar
aymeric committed
485
               ortp_debug("stun: SA_CHANGEREQUEST = %i\n", msg->changeRequest.value);
aymeric's avatar
aymeric committed
486 487
            }
      }
aymeric's avatar
aymeric committed
488
      else if (atrType == SA_SOURCEADDRESS)
aymeric's avatar
aymeric committed
489 490 491 492
      {
            msg->hasSourceAddress = TRUE;
            if ( stunParseAtrAddress(  body,  attrLen,  &msg->sourceAddress )== FALSE )
            {
aymeric's avatar
aymeric committed
493
               ortp_error("stun: problem parsing SA_SOURCEADDRESS\n");
aymeric's avatar
aymeric committed
494 495 496 497
               return FALSE;
            }
            else
            {
aymeric's avatar
aymeric committed
498
               ortp_debug("stun: SA_SOURCEADDRESS = %s\n", ipaddr(&msg->sourceAddress.ipv4) );
aymeric's avatar
aymeric committed
499 500
            }
      }
aymeric's avatar
aymeric committed
501
      else if (atrType == SA_CHANGEDADDRESS)
aymeric's avatar
aymeric committed
502 503 504 505
      {
            msg->hasChangedAddress = TRUE;
            if ( stunParseAtrAddress(  body,  attrLen,  &msg->changedAddress )== FALSE )
            {
aymeric's avatar
aymeric committed
506
               ortp_error("stun: problem parsing SA_CHANGEDADDRESS\n");
aymeric's avatar
aymeric committed
507 508 509 510
               return FALSE;
            }
            else
            {
aymeric's avatar
aymeric committed
511
               ortp_debug("stun: SA_CHANGEDADDRESS = %s\n", ipaddr(&msg->changedAddress.ipv4));
aymeric's avatar
aymeric committed
512 513
            }
      }
aymeric's avatar
aymeric committed
514
      else if (atrType == SA_USERNAME)
aymeric's avatar
aymeric committed
515 516 517 518
      {
            msg->hasUsername = TRUE;
            if (stunParseAtrString( body, attrLen, &msg->username) == FALSE)
            {
aymeric's avatar
aymeric committed
519
               ortp_error("stun: problem parsing SA_USERNAME");
aymeric's avatar
aymeric committed
520 521 522 523
               return FALSE;
            }
            else
            {
aymeric's avatar
aymeric committed
524
               ortp_debug("stun: SA_USERNAME = %s\n", msg->username.value );
aymeric's avatar
aymeric committed
525 526
            }					
      }
aymeric's avatar
aymeric committed
527
      else if (atrType == SA_PASSWORD)
aymeric's avatar
aymeric committed
528 529 530 531
      {
            msg->hasPassword = TRUE;
            if (stunParseAtrString( body, attrLen, &msg->password) == FALSE)
            {
aymeric's avatar
aymeric committed
532
               ortp_error("stun: problem parsing SA_PASSWORD");
aymeric's avatar
aymeric committed
533 534 535 536
               return FALSE;
            }
            else
            {
aymeric's avatar
aymeric committed
537
               ortp_debug("stun: SA_PASSWORD = %s\n", msg->password.value );
aymeric's avatar
aymeric committed
538 539
            }
      }
aymeric's avatar
aymeric committed
540
      else if (atrType == SA_MESSAGEINTEGRITY)
aymeric's avatar
aymeric committed
541 542 543 544
      {
            msg->hasMessageIntegrity = TRUE;
            if (stunParseAtrIntegrity( body, attrLen, &msg->messageIntegrity) == FALSE)
            {
aymeric's avatar
aymeric committed
545
               ortp_error("stun: problem parsing SA_MESSAGEINTEGRITY");
aymeric's avatar
aymeric committed
546
               return FALSE;
aymeric's avatar
aymeric committed
547
            }					
aymeric's avatar
aymeric committed
548
      }
aymeric's avatar
aymeric committed
549
      else if (atrType == SA_ERRORCODE)
aymeric's avatar
aymeric committed
550 551 552 553
      {
            msg->hasErrorCode = TRUE;
            if (stunParseAtrError(body, attrLen, &msg->errorCode) == FALSE)
            {
aymeric's avatar
aymeric committed
554
               ortp_error("stun: problem parsing SA_ERRORCODE");
aymeric's avatar
aymeric committed
555 556 557 558
               return FALSE;
            }
            else
            {
aymeric's avatar
aymeric committed
559
               ortp_debug("stun: SA_ERRORCODE = %i %i %s\n",
aymeric's avatar
aymeric committed
560 561 562 563 564 565
                                   msg->errorCode.errorClass ,
                                   msg->errorCode.number ,
                                   msg->errorCode.reason );
            }
					 
      }
aymeric's avatar
aymeric committed
566
      else if (atrType == SA_UNKNOWNATTRIBUTE)
aymeric's avatar
aymeric committed
567 568 569 570
      {
           msg->hasUnknownAttributes = TRUE;
            if (stunParseAtrUnknown(body, attrLen, &msg->unknownAttributes) == FALSE)
            {
aymeric's avatar
aymeric committed
571
               ortp_error("stun: problem parsing SA_UNKNOWNATTRIBUTE");
aymeric's avatar
aymeric committed
572 573 574
               return FALSE;
            }
      }
aymeric's avatar
aymeric committed
575
      else if (atrType == SA_REFLECTEDFROM)
aymeric's avatar
aymeric committed
576 577 578 579
      {
            msg->hasReflectedFrom = TRUE;
            if ( stunParseAtrAddress(  body,  attrLen,  &msg->reflectedFrom ) == FALSE )
            {
aymeric's avatar
aymeric committed
580 581 582 583 584 585 586 587 588 589
               ortp_error("stun: problem parsing SA_REFLECTEDFROM");
               return FALSE;
            }
      }
      else if (atrType == SA_REALM)
      {
            msg->hasRealm = TRUE;
            if (stunParseAtrString( body, attrLen, &msg->realmName) == FALSE)
            {
               ortp_error("stun: problem parsing SA_REALM");
aymeric's avatar
aymeric committed
590 591
               return FALSE;
            }
aymeric's avatar
aymeric committed
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
            else
            {
               ortp_debug("stun: SA_REALM = %s\n", msg->realmName.value );
            }
      }
      else if (atrType == SA_NONCE)
      {
            msg->hasNonce = TRUE;
            if (stunParseAtrString( body, attrLen, &msg->nonceName) == FALSE)
            {
               ortp_error("stun: problem parsing SA_NONCE");
               return FALSE;
            }
            else
            {
               ortp_debug("stun: SA_NONCE = %s\n", msg->nonceName.value );
            }
aymeric's avatar
aymeric committed
609
      }
aymeric's avatar
aymeric committed
610
      else if (atrType == SA_XORMAPPEDADDRESS || atrType == SA_XORMAPPEDADDRESS2)
aymeric's avatar
aymeric committed
611 612 613 614
      { 
           msg->hasXorMappedAddress = TRUE;
            if ( stunParseAtrAddress(  body,  attrLen,  &msg->xorMappedAddress ) == FALSE )
            {
aymeric's avatar
aymeric committed
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
               ortp_error("stun: problem parsing SA_XORMAPPEDADDRESS");
               return FALSE;
            }
            else
            {
               ortp_debug("stun: SA_XORMAPPEDADDRESS = %s\n", ipaddr(&msg->xorMappedAddress.ipv4) );
            }
      }
      else if (atrType == SA_XORONLY)
      {
            ortp_warning("stun: SA_XORONLY - non standard extension ignored\n" );
      }
      else if (atrType == SA_SECONDARYADDRESS)
      {
            ortp_debug("stun: SA_SECONDARYADDRESS - non standard extension ignored\n" );
      }
      else if (atrType == SA_SOFTWARE)
      {
            msg->hasSoftware = TRUE;
            if (stunParseAtrString( body, attrLen, &msg->softwareName) == FALSE)
            {
               ortp_error("stun: problem parsing SA_SOFTWARE");
aymeric's avatar
aymeric committed
637 638 639 640
               return FALSE;
            }
            else
            {
aymeric's avatar
aymeric committed
641
               ortp_debug("stun: SA_SOFTWARE = %s\n", msg->softwareName.value );
aymeric's avatar
aymeric committed
642 643
            }
      }
aymeric's avatar
aymeric committed
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
      else if (atrType == TA_CHANNELNUMBER)
      {
           msg->hasChannelNumberAttributes = TRUE;
            if (turnParseAtrChannelNumber(body, attrLen, &msg->channelNumberAttributes) == FALSE)
            {
               ortp_error("stun: problem parsing TA_CHANNELNUMBER");
               return FALSE;
            }					
      }
      else if (atrType == TA_LIFETIME)
      {
           msg->hasLifetimeAttributes = TRUE;
            if (turnParseAtrLifetime(body, attrLen, &msg->lifetimeAttributes) == FALSE)
            {
               ortp_error("stun: problem parsing TA_LIFETIME");
               return FALSE;
            }					
      }
      else if (atrType == TA_DEPRECATEDBANDWIDTH)
      {
           ortp_warning("stun: deprecated attribute TA_DEPRECATEDBANDWIDTH");
      }
      else if (atrType == TA_XORPEERADDRESS)
aymeric's avatar
aymeric committed
667
      {
aymeric's avatar
aymeric committed
668 669 670 671 672 673 674 675 676 677
            msg->hasXorPeerAddress = TRUE;
            if ( stunParseAtrAddress(  body,  attrLen,  &msg->xorPeerAddress )== FALSE )
            {
               ortp_error("stun: problem parsing SA_XORPEERADDRESS\n");
               return FALSE;
            }
            else
            {
               ortp_debug("stun: SA_XORPEERADDRESS = %s\n", ipaddr(&msg->xorPeerAddress.ipv4));
            }
aymeric's avatar
aymeric committed
678
      }
aymeric's avatar
aymeric committed
679
      else if (atrType == TA_DATA)
aymeric's avatar
aymeric committed
680
      {
aymeric's avatar
aymeric committed
681 682
            msg->hasData = TRUE;
            if (turnParseAtrData( body, attrLen, &msg->data) == FALSE)
aymeric's avatar
aymeric committed
683
            {
aymeric's avatar
aymeric committed
684
               ortp_error("stun: problem parsing TA_DATA");
aymeric's avatar
aymeric committed
685 686 687 688 689 690
               return FALSE;
            }
            else
            {
            }
      }
aymeric's avatar
aymeric committed
691
      else if (atrType == TA_XORRELAYEDADDRESS)
aymeric's avatar
aymeric committed
692
      {
aymeric's avatar
aymeric committed
693 694
            msg->hasXorRelayedAddress = TRUE;
            if ( stunParseAtrAddress(  body,  attrLen,  &msg->xorRelayedAddress )== FALSE )
aymeric's avatar
aymeric committed
695
            {
aymeric's avatar
aymeric committed
696
               ortp_error("stun: problem parsing TA_XORRELAYEDADDRESS\n");
aymeric's avatar
aymeric committed
697 698 699 700
               return FALSE;
            }
            else
            {
aymeric's avatar
aymeric committed
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 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 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
               ortp_debug("stun: TA_XORRELAYEDADDRESS = %s\n", ipaddr(&msg->xorRelayedAddress.ipv4));
            }
      }
      else if (atrType == TA_EVENPORT)
      {
           ortp_warning("stun: do we need this... TA_EVENPORT");
      }
      else if (atrType == TA_REQUESTEDTRANSPORT)
      {
            msg->hasRequestedTransport = TRUE;
            if ( turnParseAtrRequestedTransport(  body,  attrLen,  &msg->requestedTransport )== FALSE )
            {
               ortp_error("stun: problem parsing TA_REQUESTEDTRANSPORT\n");
               return FALSE;
            }
      }
      else if (atrType == TA_DONTFRAGMENT)
      {
            msg->hasDontFragment = TRUE;
      }
      else if (atrType == TA_DEPRECATEDTIMERVAL)
      {
           ortp_warning("stun: deprecated attribute TA_DEPRECATEDTIMERVAL");
      }
      else if (atrType == TA_RESERVATIONTOKEN)
      {
            msg->hasReservationToken = TRUE;
            if ( turnParseAtrReservationToken(  body,  attrLen,  &msg->reservationToken)== FALSE )
            {
               ortp_error("stun: problem parsing TA_RESERVATIONTOKEN\n");
               return FALSE;
            }
      }
      else if (atrType == SA_FINGERPRINT)
      {
            msg->hasFingerprint = TRUE;
            if ( turnParseAtrFingerprint(  body,  attrLen,  &msg->fingerprint)== FALSE )
            {
               ortp_error("stun: problem parsing SA_FINGERPRINT\n");
               return FALSE;
            }
      }
      else if (atrType == ICEA_PRIORITY)
      {
            msg->hasLifetimeAttributes = TRUE;
            if (iceParseAtrPriority(body, attrLen, &msg->priority) == FALSE)
            {
               ortp_error("stun: problem parsing ICEA_PRIORITY");
               return FALSE;
            }					
      }
      else if (atrType == ICEA_USECANDIDATE)
      {
            msg->hasUseCandidate = TRUE;
      }
      else if (atrType == ICEA_ICECONTROLLED)
      {
           msg->hasIceControlled = TRUE;
           if (iceParseAtrIceControll(body, attrLen, &msg->iceControlled) == FALSE)
            {
               ortp_error("stun: problem parsing ICEA_ICECONTROLLED");
               return FALSE;
            }
      }
      else if (atrType == ICEA_ICECONTROLLING)
      {
           msg->hasIceControlling = TRUE;
           if (iceParseAtrIceControll(body, attrLen, &msg->iceControlling) == FALSE)
            {
               ortp_error("stun: problem parsing ICEA_ICECONTROLLING");
               return FALSE;
aymeric's avatar
aymeric committed
772 773 774 775 776 777
            }
      }
      else
      {
            if ( atrType <= 0x7FFF ) 
            {
aymeric's avatar
aymeric committed
778 779
              ortp_error("stun: Unknown Comprehension-Required attribute: %04x\n", atrType );
              return FALSE;
aymeric's avatar
aymeric committed
780
            }
aymeric's avatar
aymeric committed
781 782
            else
              ortp_warning("stun: Unknown attribute: %04x\n", atrType );
aymeric's avatar
aymeric committed
783 784
      }
		
aymeric's avatar
aymeric committed
785 786 787
      if (attrLen%4>0)
        attrLen += (4-(attrLen%4));
      
aymeric's avatar
aymeric committed
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
      body += attrLen;
      size -= attrLen;
   }
    
   return TRUE;
}


static char* 
encode16(char* buf, UInt16 data)
{
   UInt16 ndata = htons(data);
   memcpy(buf, &ndata, sizeof(UInt16));
   return buf + sizeof(UInt16);
}

static char* 
encode32(char* buf, UInt32 data)
{
   UInt32 ndata = htonl(data);
   memcpy(buf, &ndata, sizeof(UInt32));
   return buf + sizeof(UInt32);
}


static char* 
encode(char* buf, const char* data, unsigned int length)
{
   memcpy(buf, data, length);
   return buf + length;
}


static char* 
encodeAtrAddress4(char* ptr, UInt16 type, const StunAtrAddress4 *atr)
{
   ptr = encode16(ptr, type);
   ptr = encode16(ptr, 8);
   *ptr++ = atr->pad;
   *ptr++ = IPv4Family;
   ptr = encode16(ptr, atr->ipv4.port);
   ptr = encode32(ptr, atr->ipv4.addr);
	
   return ptr;
}

static char* 
encodeAtrChangeRequest(char* ptr, const StunAtrChangeRequest *atr)
{
aymeric's avatar
aymeric committed
837
   ptr = encode16(ptr, SA_CHANGEREQUEST);
aymeric's avatar
aymeric committed
838 839 840 841 842 843 844 845
   ptr = encode16(ptr, 4);
   ptr = encode32(ptr, atr->value);
   return ptr;
}

static char* 
encodeAtrError(char* ptr, const StunAtrError *atr)
{
aymeric's avatar
aymeric committed
846
   ptr = encode16(ptr, SA_ERRORCODE);
aymeric's avatar
aymeric committed
847 848 849 850 851 852 853 854 855 856 857 858 859
   ptr = encode16(ptr, 6 + atr->sizeReason);
   ptr = encode16(ptr, atr->pad);
   *ptr++ = atr->errorClass;
   *ptr++ = atr->number;
   ptr = encode(ptr, atr->reason, atr->sizeReason);
   return ptr;
}


static char* 
encodeAtrUnknown(char* ptr, const StunAtrUnknown *atr)
{
   int i;
aymeric's avatar
aymeric committed
860
   ptr = encode16(ptr, SA_UNKNOWNATTRIBUTE);
aymeric's avatar
aymeric committed
861 862 863 864 865 866 867 868 869 870 871
   ptr = encode16(ptr, 2+2*atr->numAttributes);
   for (i=0; i<atr->numAttributes; i++)
   {
      ptr = encode16(ptr, atr->attrType[i]);
   }
   return ptr;
}

static char* 
encodeAtrString(char* ptr, UInt16 type, const StunAtrString *atr)
{
aymeric's avatar
aymeric committed
872 873
   int padding;
   int i;
aymeric's avatar
aymeric committed
874 875 876 877
	
   ptr = encode16(ptr, type);
   ptr = encode16(ptr, atr->sizeValue);
   ptr = encode(ptr, atr->value, atr->sizeValue);
aymeric's avatar
aymeric committed
878 879 880 881 882 883 884 885 886

   padding = atr->sizeValue % 4;
   if (padding>0)
   {
     for (i=0;i<4-padding;i++)
     {
       *ptr++ = 0;
     }
   }
aymeric's avatar
aymeric committed
887 888 889 890 891 892 893
   return ptr;
}


static char* 
encodeAtrIntegrity(char* ptr, const StunAtrIntegrity *atr)
{
aymeric's avatar
aymeric committed
894
   ptr = encode16(ptr, SA_MESSAGEINTEGRITY);
aymeric's avatar
aymeric committed
895 896 897 898 899 900
   ptr = encode16(ptr, 20);
   ptr = encode(ptr, atr->hash, sizeof(atr->hash));
   return ptr;
}


aymeric's avatar
aymeric committed
901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
static char* 
encodeAtrRequestedTransport(char* ptr, const TurnAtrRequestedTransport *atr)
{
   ptr = encode16(ptr, TA_REQUESTEDTRANSPORT);
   ptr = encode16(ptr, 4);
   *ptr++ = atr->proto;
   *ptr++ = atr->pad1;
   *ptr++ = atr->pad2;
   *ptr++ = atr->pad3;
   return ptr;
}

static char* 
encodeAtrLifeTime(char* ptr, const TurnAtrLifetime *atr)
{
   ptr = encode16(ptr, TA_LIFETIME);
   ptr = encode16(ptr, 4);
   ptr = encode32(ptr, atr->lifetime);
   return ptr;
}

static char* 
encodeAtrDontFragment(char* ptr)
{
   ptr = encode16(ptr, TA_DONTFRAGMENT);
   ptr = encode16(ptr, 0);
   return ptr;
}

aymeric's avatar
aymeric committed
930 931 932 933
unsigned int
stunEncodeMessage( const StunMessage *msg, 
                   char* buf, 
                   unsigned int bufLen, 
aymeric's avatar
aymeric committed
934
                   const StunAtrString *password)
aymeric's avatar
aymeric committed
935 936 937 938 939 940
{
   char* ptr = buf;
   char* lengthp;
   ptr = encode16(ptr, msg->msgHdr.msgType);
   lengthp = ptr;
   ptr = encode16(ptr, 0);
aymeric's avatar
aymeric committed
941 942
   ptr = encode32(ptr, msg->msgHdr.magic_cookie);
   ptr = encode(ptr, (const char*)msg->msgHdr.tr_id.octet, sizeof(msg->msgHdr.tr_id));
aymeric's avatar
aymeric committed
943
	
aymeric's avatar
aymeric committed
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
   ortp_debug("stun: Encoding stun message: ");

   if (msg->hasRequestedTransport)
   {
      ortp_debug("stun: Encoding TA_REQUESTEDTRANSPORT: %i\n", msg->requestedTransport.proto );
      ptr = encodeAtrRequestedTransport (ptr, &msg->requestedTransport);
   }
   if (msg->hasLifetimeAttributes)
   {
      ortp_debug("stun: Encoding TA_LIFETIME: %i\n", msg->lifetimeAttributes.lifetime );
      ptr = encodeAtrLifeTime (ptr, &msg->lifetimeAttributes);
   }
   if (msg->hasDontFragment)
   {
      ortp_debug("stun: Encoding TA_DONTFRAGMENT: DF\n");
      ptr = encodeAtrDontFragment (ptr);
   }

aymeric's avatar
aymeric committed
962 963
   if (msg->hasMappedAddress)
   {
aymeric's avatar
aymeric committed
964 965
      ortp_debug("stun: Encoding SA_MAPPEDADDRESS: %s\n", ipaddr(&msg->mappedAddress.ipv4) );
      ptr = encodeAtrAddress4 (ptr, SA_MAPPEDADDRESS, &msg->mappedAddress);
aymeric's avatar
aymeric committed
966 967 968
   }
   if (msg->hasResponseAddress)
   {
aymeric's avatar
aymeric committed
969 970
      ortp_debug("stun: Encoding SA_RESPONSEADDRESS: %s\n", ipaddr(&msg->responseAddress.ipv4) );
      ptr = encodeAtrAddress4(ptr, SA_RESPONSEADDRESS, &msg->responseAddress);
aymeric's avatar
aymeric committed
971 972 973
   }
   if (msg->hasChangeRequest)
   {
aymeric's avatar
aymeric committed
974
      ortp_debug("stun: Encoding SA_CHANGEREQUEST: %i\n", msg->changeRequest.value );
aymeric's avatar
aymeric committed
975 976 977 978
      ptr = encodeAtrChangeRequest(ptr, &msg->changeRequest);
   }
   if (msg->hasSourceAddress)
   {
aymeric's avatar
aymeric committed
979 980
      ortp_debug("stun: Encoding SA_SOURCEADDRESS: %s\n", ipaddr(&msg->sourceAddress.ipv4) );
      ptr = encodeAtrAddress4(ptr, SA_SOURCEADDRESS, &msg->sourceAddress);
aymeric's avatar
aymeric committed
981 982 983
   }
   if (msg->hasChangedAddress)
   {
aymeric's avatar
aymeric committed
984 985
      ortp_debug("stun: Encoding SA_CHANGEDADDRESS: %s\n", ipaddr(&msg->changedAddress.ipv4) );
      ptr = encodeAtrAddress4(ptr, SA_CHANGEDADDRESS, &msg->changedAddress);
aymeric's avatar
aymeric committed
986 987 988
   }
   if (msg->hasUsername)
   {
aymeric's avatar
aymeric committed
989 990
      ortp_debug("stun: Encoding SA_USERNAME: %s\n", msg->username.value );
      ptr = encodeAtrString(ptr, SA_USERNAME, &msg->username);
aymeric's avatar
aymeric committed
991
   }
aymeric's avatar
aymeric committed
992 993 994 995 996
   //if (msg->hasPassword)
   //{
   //   ortp_debug("stun: Encoding SA_PASSWORD: %s\n", msg->password.value );
   //   ptr = encodeAtrString(ptr, SA_PASSWORD, &msg->password);
   //}
aymeric's avatar
aymeric committed
997 998
   if (msg->hasErrorCode)
   {
aymeric's avatar
aymeric committed
999
      ortp_debug("stun: Encoding SA_ERRORCODE: class=%i number=%i reason=%s\n" 
aymeric's avatar
aymeric committed
1000 1001 1002 1003 1004 1005 1006 1007
                          , msg->errorCode.errorClass 
                          , msg->errorCode.number
                          , msg->errorCode.reason );
      
      ptr = encodeAtrError(ptr, &msg->errorCode);
   }
   if (msg->hasUnknownAttributes)
   {
aymeric's avatar
aymeric committed
1008
      ortp_debug("stun: Encoding SA_UNKNOWNATTRIBUTE: ???");
aymeric's avatar
aymeric committed
1009 1010 1011 1012
      ptr = encodeAtrUnknown(ptr, &msg->unknownAttributes);
   }
   if (msg->hasReflectedFrom)
   {
aymeric's avatar
aymeric committed
1013 1014
      ortp_debug("stun: Encoding SA_REFLECTEDFROM: %s\n", ipaddr(&msg->reflectedFrom.ipv4) );
      ptr = encodeAtrAddress4(ptr, SA_REFLECTEDFROM, &msg->reflectedFrom);
aymeric's avatar
aymeric committed
1015
   }
aymeric's avatar
aymeric committed
1016
   if (msg->hasNonce)
aymeric's avatar
aymeric committed
1017
   {
aymeric's avatar
aymeric committed
1018 1019
      ortp_debug("stun: Encoding SA_NONCE: %s\n", msg->nonceName.value );
      ptr = encodeAtrString(ptr, SA_NONCE, &msg->nonceName);
aymeric's avatar
aymeric committed
1020
   }
aymeric's avatar
aymeric committed
1021
   if (msg->hasRealm)
aymeric's avatar
aymeric committed
1022
   {
aymeric's avatar
aymeric committed
1023 1024
      ortp_debug("stun: Encoding SA_REALM: %s\n", msg->realmName.value );
      ptr = encodeAtrString(ptr, SA_REALM, &msg->realmName);
aymeric's avatar
aymeric committed
1025
   }
aymeric's avatar
aymeric committed
1026 1027
   
   if (msg->hasXorMappedAddress)
aymeric's avatar
aymeric committed
1028
   {
aymeric's avatar
aymeric committed
1029 1030
      ortp_debug("stun: Encoding SA_XORMAPPEDADDRESS: %s\n", ipaddr(&msg->xorMappedAddress.ipv4) );
      ptr = encodeAtrAddress4 (ptr, SA_XORMAPPEDADDRESS, &msg->xorMappedAddress);
aymeric's avatar
aymeric committed
1031
   }
aymeric's avatar
aymeric committed
1032
   if (msg->hasSoftware)
aymeric's avatar
aymeric committed
1033
   {
aymeric's avatar
aymeric committed
1034 1035
      ortp_debug("stun: Encoding SA_SOFTWARE: %s\n", msg->softwareName.value );
      ptr = encodeAtrString(ptr, SA_SOFTWARE, &msg->softwareName);
aymeric's avatar
aymeric committed
1036 1037
   }

aymeric's avatar
aymeric committed
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
   if (msg->hasMessageIntegrity
     &&password!=NULL && password->sizeValue > 0
     &&msg->username.sizeValue>0
     &&msg->realmName.sizeValue>0)
   {
      StunAtrIntegrity integrity;
      //ortp_debug("stun: HMAC with password: %s\n", password->value );

      encode16(lengthp, (UInt16)(ptr - buf - sizeof(StunMsgHdr)+24));
      computeHmac_longterm(integrity.hash, buf, (int)(ptr-buf) ,
        msg->username.value, msg->realmName.value, password->value);
      ptr = encodeAtrIntegrity(ptr, &integrity);
   }
   else if (msg->hasMessageIntegrity
     &&password!=NULL && password->sizeValue > 0
     &&msg->username.sizeValue>0)
aymeric's avatar
aymeric committed
1054 1055
   {
      StunAtrIntegrity integrity;
aymeric's avatar
aymeric committed
1056
      //ortp_debug("stun: HMAC with password: %s\n", password->value );
aymeric's avatar
aymeric committed
1057

aymeric's avatar
aymeric committed
1058 1059 1060
      encode16(lengthp, (UInt16)(ptr - buf - sizeof(StunMsgHdr)+24));
      computeHmac_shortterm(integrity.hash, buf, (int)(ptr-buf) ,
        password->value);
aymeric's avatar
aymeric committed
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
      ptr = encodeAtrIntegrity(ptr, &integrity);
   }
	
   encode16(lengthp, (UInt16)(ptr - buf - sizeof(StunMsgHdr)));
   return (int)(ptr - buf);
}

int 
stunRand(void)
{
   /* return 32 bits of random stuff */
   /* assert( sizeof(int) == 4 ); */
   static bool_t init=FALSE;
   if ( !init )
   { 
      UInt64 tick;
      int seed;
      init = TRUE;

#if defined(_WIN32_WCE)
      tick = GetTickCount ();
#elif defined(_MSC_VER)
      {
      volatile unsigned int lowtick=0,hightick=0;
      __asm
         {
            rdtsc 
               mov lowtick, eax
               mov hightick, edx
               }
      tick = hightick;
      tick <<= 32;
      tick |= lowtick;
      }
#elif defined(__GNUC__) && ( defined(__i686__) || defined(__i386__) )
      asm("rdtsc" : "=A" (tick));
#elif defined(__GNUC__) && defined(__amd64__)
      asm("rdtsc" : "=A" (tick));
#elif defined (__SUNPRO_CC) && defined( __sparc__ )	
      tick = gethrtime();
#elif defined(__MACH__) 
      {
	int fd=open("/dev/random",O_RDONLY);
	read(fd,&tick,sizeof(tick));
	closesocket(fd);
      }
1107
#elif defined(__linux) || defined(HAVE_DEV_RANDOM) 
aymeric's avatar
aymeric committed
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
      {
 	fd_set fdSet;
	int maxFd=0;
	struct timeval tv;
	int e;

        int fd=open("/dev/random",O_RDONLY);

	if (fd<0)
	{
	    ortp_message("stun: Failed to open random device\n");
	    return random();
	}
        FD_ZERO(&fdSet);
        FD_SET(fd,&fdSet);
        maxFd=fd+1;

	tv.tv_sec = 0;
	tv.tv_usec = 500;

	e = select( maxFd, &fdSet, NULL,NULL, &tv );
	if (e <= 0)
	{
           ortp_error("stun: Failed to get data from random device\n");
           closesocket(fd);
	   return random();
	}
	read(fd,&tick,sizeof(tick));
	closesocket(fd);
      }
#else
#     error Need some way to seed the random number generator 
#endif 
      seed = (int)(tick);
#if	defined(_WIN32) || defined(_WIN32_WCE)
      srand(seed);
#else
      srandom(seed);
#endif
   }
	
#if	defined(_WIN32) || defined(_WIN32_WCE)
   /* assert( RAND_MAX == 0x7fff ); */
   {
       int r1 = rand();
       int r2 = rand();
       int ret = (r1<<16) + r2;
	
       return ret;
   }
#else
   return random(); 
#endif
}


/* return a random number to use as a port */
static int
randomPort()
{
   int min=0x4000;
   int max=0x7FFF;
	
   int ret = stunRand();
   ret = ret|min;
   ret = ret&max;
	
   return ret;
}


#ifdef NOSSL
static void
aymeric's avatar
aymeric committed
1181 1182 1183 1184 1185 1186 1187
computeHmac_longterm(char* hmac, const char* input, int length,
                     const char *username, const char *realm, const char *password)
{
   strncpy(hmac,"hmac-not-implemented",20);
}
static void
computeHmac_shortterm(char* hmac, const char* input, int length, const char* key)
aymeric's avatar
aymeric committed
1188 1189 1190 1191 1192
{
   strncpy(hmac,"hmac-not-implemented",20);
}
#else
#include <openssl/hmac.h>
aymeric's avatar
aymeric committed
1193
#include <openssl/md5.h>
aymeric's avatar
aymeric committed
1194 1195

static void
aymeric's avatar
aymeric committed
1196 1197
computeHmac_longterm(char* hmac, const char* input, int length,
                     const char *username, const char *realm, const char *password)
aymeric's avatar
aymeric committed
1198 1199
{
   unsigned int resultSize=0;
aymeric's avatar
aymeric committed
1200
   unsigned char HA1[16];
aymeric's avatar
aymeric committed
1201
   char HA1_text[1024];
aymeric's avatar
aymeric committed
1202 1203

   snprintf(HA1_text, sizeof(HA1_text), "%s:%s:%s", username, realm, password);
aymeric's avatar
aymeric committed
1204
   MD5((unsigned char *)HA1_text, strlen(HA1_text), HA1);
aymeric's avatar
aymeric committed
1205

aymeric's avatar
aymeric committed
1206
   HMAC(EVP_sha1(), 
aymeric's avatar
aymeric committed
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
        HA1, 16, 
        (const unsigned char*) input, length, 
        (unsigned char*)hmac, &resultSize);
}

static void
computeHmac_shortterm(char* hmac, const char* input, int length, const char* key)
{
   unsigned int resultSize=0;
   HMAC(EVP_sha1(), 
        key, strlen(key), 
aymeric's avatar
aymeric committed
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
        (const unsigned char*) input, length, 
        (unsigned char*)hmac, &resultSize);
}
#endif

UInt64
stunGetSystemTimeSecs(void)
{
   UInt64 time=0;
#if	defined(_WIN32) || defined(_WIN32_WCE)
   SYSTEMTIME t;
   /*  CJ TODO - this probably has bug on wrap around every 24 hours */
   GetSystemTime( &t );
   time = (t.wHour*60+t.wMinute)*60+t.wSecond; 
#else
   struct timeval now;
   gettimeofday( &now , NULL );
   /* assert( now ); */
   time = now.tv_sec;
#endif
   return time;
}


/* returns TRUE if it scucceeded */
bool_t 
aymeric's avatar
aymeric committed
1244
stunParseHostName( const char* peerName,
aymeric's avatar
aymeric committed
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
                   UInt32* ip,
                   UInt16* portVal,
                   UInt16 defaultPort )
{
   struct in_addr sin_addr;
    
   char host[512];
   char* port = NULL;
   int portNum = defaultPort;
   char* sep;
   struct hostent* h;

   strncpy(host,peerName,512);
   host[512-1]='\0';
	
   /* pull out the port part if present. */
   sep = strchr(host,':');
	
   if ( sep == NULL )
   {
      portNum = defaultPort;
   }
   else
   {
      char* endPtr=NULL;
      *sep = '\0';
      port = sep + 1;
      /* set port part */
      
		
      portNum = strtol(port,&endPtr,10);
		
      if ( endPtr != NULL )
      {
         if ( *endPtr != '\0' )
         {
            portNum = defaultPort;
         }
      }
   }
    
   if ( portNum < 1024 ) return FALSE;
   if ( portNum >= 0xFFFF ) return FALSE;
	
   /* figure out the host part */
	
#if	defined(_WIN32) || defined(_WIN32_WCE)
   /* assert( strlen(host) >= 1 ); */
   if ( isdigit( host[0] ) )
   {
      /* assume it is a ip address */
      unsigned long a = inet_addr(host);
      /* cerr << "a=0x" << hex << a << dec ); */
		
      *ip = ntohl( a );
   }
   else
   {
      /* assume it is a host name */
      h = gethostbyname( host );
		
      if ( h == NULL )
      {
         /*int err = getErrno();*/

         /* ortp_message("stun: error was %i\n", err); */
         /* std::cerr << "error was " << err << std::endl; */
         /* assert( err != WSANOTINITIALISED ); */
			
         *ip = ntohl( 0x7F000001L );
			
         return FALSE;
      }
      else
      {
         sin_addr = *(struct in_addr*)h->h_addr;
         *ip = ntohl( sin_addr.s_addr );
      }
   }
	
#else
   h = gethostbyname( host );
   if ( h == NULL )
   {
      /* 
	 int err = getErrno();
	 ortp_message("stun: error was %i\n", err);
      */
      *ip = ntohl( 0x7F000001L );
      return FALSE;
   }
   else
   {
      sin_addr = *(struct in_addr*)h->h_addr;
      *ip = ntohl( sin_addr.s_addr );
   }
#endif
	
   *portVal = portNum;
	
   return TRUE;
}


bool_t
aymeric's avatar
aymeric committed
1350
stunParseServerName( const char* name, StunAddress4 *addr)
aymeric's avatar
aymeric committed
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
{
   /* assert(name); */
	
   /* TODO - put in DNS SRV stuff. */
	
   bool_t ret = stunParseHostName( name, &addr->addr, &addr->port, 3478); 
   if ( ret != TRUE ) 
   {
       addr->port=0xFFFF;
   }	
   return ret;
}


static void
stunCreateErrorResponse(StunMessage *response, int cl, int number, const char* msg)
{
aymeric's avatar
aymeric committed
1368
   response->msgHdr.msgType = (STUN_METHOD_BINDING | STUN_ERR_RESP);
aymeric's avatar
aymeric committed
1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
   response->hasErrorCode = TRUE;
   response->errorCode.errorClass = cl;
   response->errorCode.number = number;
   strcpy(response->errorCode.reason, msg);
}

#if 0
static void
stunCreateSharedSecretErrorResponse(StunMessage& response, int cl, int number, const char* msg)
{
   response.msgHdr.msgType = SharedSecretErrorResponseMsg;
   response.hasErrorCode = TRUE;
   response.errorCode.errorClass = cl;
   response.errorCode.number = number;
   strcpy(response.errorCode.reason, msg);
}
#endif

aymeric's avatar
aymeric committed
1387
#if 0
aymeric's avatar
aymeric committed
1388 1389 1390 1391
static void
stunCreateSharedSecretResponse(const StunMessage *request, const StunAddress4 *source, StunMessage *response)
{
   response->msgHdr.msgType = SharedSecretResponseMsg;
aymeric's avatar
aymeric committed
1392
   response->msgHdr.tr_id = request->msgHdr.tr_id;
aymeric's avatar
aymeric committed
1393 1394 1395 1396 1397 1398 1399
	
   response->hasUsername = TRUE;
   stunCreateUserName( source, &response->username);
	
   response->hasPassword = TRUE;
   stunCreatePassword( &response->username, &response->password);
}
aymeric's avatar
aymeric committed
1400
#endif
aymeric's avatar
aymeric committed
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414

/* This funtion takes a single message sent to a stun server, parses
   and constructs an apropriate repsonse - returns TRUE if message is
   valid */
bool_t
stunServerProcessMsg( char* buf,
                      unsigned int bufLen,
                      StunAddress4 *from, 
                      StunAddress4 *myAddr,
                      StunAddress4 *altAddr, 
                      StunMessage *resp,
                      StunAddress4 *destination,
                      StunAtrString *hmacPassword,
                      bool_t* changePort,
aymeric's avatar
aymeric committed
1415
                      bool_t* changeIp)
aymeric's avatar
aymeric committed
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430
{
   int i;
   StunMessage req;
   StunAddress4 mapped;
   StunAddress4 respondTo;
   UInt32 flags;
   bool_t ok;
   /* set up information for default response */
	
   memset( &req, 0 , sizeof(req) );
   memset( resp, 0 , sizeof(*resp) );
	
   *changeIp = FALSE;
   *changePort = FALSE;
	
aymeric's avatar
aymeric committed
1431
   ok = stunParseMessage( buf,bufLen, &req);
aymeric's avatar
aymeric committed
1432 1433 1434
   
   if (!ok)      /* Complete garbage, drop it on the floor */
   {
aymeric's avatar
aymeric committed
1435
      ortp_error("stun: Request did not parse");
aymeric's avatar
aymeric committed
1436 1437
      return FALSE;
   }
aymeric's avatar
aymeric committed
1438
   //ortp_debug("stun: Request parsed ok");
aymeric's avatar
aymeric committed
1439 1440 1441 1442 1443
	
   mapped = req.mappedAddress.ipv4;
   respondTo = req.responseAddress.ipv4;
   flags = req.changeRequest.value;
	
aymeric's avatar
aymeric committed
1444
   if (req.msgHdr.msgType==(STUN_METHOD_BINDING|STUN_REQUEST))
aymeric's avatar
aymeric committed
1445 1446 1447
   {
         if (!req.hasMessageIntegrity)
         {
aymeric's avatar
aymeric committed
1448
            //ortp_debug("stun: BindRequest does not contain SA_MESSAGEINTEGRITY");
aymeric's avatar
aymeric committed
1449 1450 1451
				
            if (0) /* !jf! mustAuthenticate */
            {
aymeric's avatar
aymeric committed
1452 1453
               ortp_error("stun: Received BindRequest with no SA_MESSAGEINTEGRITY. Sending 401.");
               stunCreateErrorResponse(resp, 4, 1, "Missing SA_MESSAGEINTEGRITY");
aymeric's avatar
aymeric committed
1454 1455 1456 1457 1458 1459 1460
               return TRUE;
            }
         }
         else
         {
            if (!req.hasUsername)
            {
aymeric's avatar
aymeric committed
1461 1462
               ortp_error("stun: No UserName. Send 432.");
               stunCreateErrorResponse(resp, 4, 32, "No UserName and contains SA_MESSAGEINTEGRITY");
aymeric's avatar
aymeric committed
1463 1464 1465 1466
               return TRUE;
            }
            else
            {
aymeric's avatar
aymeric committed
1467
               //ortp_debug("stun: Validating username: %s", req.username.value );
aymeric's avatar
aymeric committed
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
               /* !jf! could retrieve associated password from provisioning here */
               if (strcmp(req.username.value, "test") == 0)
               {
                  if (0)
                  {
                     /* !jf! if the credentials are stale */
                     stunCreateErrorResponse(resp, 4, 30, "Stale credentials on BindRequest");
                     return TRUE;
                  }
                  else
                  {
                     unsigned char hmac[20];
aymeric's avatar
aymeric committed
1480
                     //ortp_debug("stun: Validating SA_MESSAGEINTEGRITY");
aymeric's avatar
aymeric committed
1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501
                     /* need access to shared secret */

#ifndef NOSSL
                     {
                        unsigned int hmacSize=20;

                        HMAC(EVP_sha1(), 
                             "1234", 4, 
                             (const unsigned char*) buf, bufLen-20-4, 
                             hmac, &hmacSize);
                        /*HMAC(EVP_sha1(), 
                             "1234", 4, 
                             reinterpret_cast<const unsigned char*>(buf), bufLen-20-4, 
                             hmac, &hmacSize);
                        //assert(hmacSize == 20);
			*/
                     }
#endif
							
                     if (memcmp(buf, hmac, 20) != 0)
                     {
aymeric's avatar
aymeric committed
1502
                        ortp_error("stun: SA_MESSAGEINTEGRITY is bad. Sending ");
aymeric's avatar
aymeric committed
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
                        stunCreateErrorResponse(resp, 4, 3, "Unknown username. Try test with password 1234");
                        return TRUE;
                     }
							
                     /* need to compute this later after message is filled in */
                     resp->hasMessageIntegrity = TRUE;
                     /* assert(req.hasUsername); */
                     resp->hasUsername = TRUE;
                     resp->username = req.username; /* copy username in */
                  }
               }
               else
               {
aymeric's avatar
aymeric committed
1516
                  ortp_error("stun: Invalid username: %s Send 430", req.username.value); 
aymeric's avatar
aymeric committed
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537
               }
            }
         }
			
         /* TODO !jf! should check for unknown attributes here and send 420 listing the
            unknown attributes. */
			
         if ( respondTo.port == 0 )
         {
            /* respondTo = from; */
            memcpy(&respondTo, from, sizeof(StunAddress4));
         }
         if ( mapped.port == 0 ) 
         {
            /* mapped = from; */
            memcpy(&mapped, from, sizeof(StunAddress4));
         }

         *changeIp   = ( flags & ChangeIpFlag )?TRUE:FALSE;
         *changePort = ( flags & ChangePortFlag )?TRUE:FALSE;
			
aymeric's avatar
aymeric committed
1538 1539 1540 1541 1542 1543 1544
         //ortp_debug("stun: Request is valid:\n");
         //ortp_debug("stun: \t flags= %i\n", flags );
         //ortp_debug("stun: \t changeIp= %i\n", *changeIp );
         //ortp_debug("stun: \t changePort=%i\n", *changePort );
         //ortp_debug("stun: \t from= %i\n", from->addr );
         //ortp_debug("stun: \t respond to= %i\n", respondTo.addr );
         //ortp_debug("stun: \t mapped= %i\n", mapped.addr );
aymeric's avatar
aymeric committed
1545 1546
				
         /* form the outgoing message */
aymeric's avatar
aymeric committed
1547 1548 1549
         resp->msgHdr.msgType = (STUN_METHOD_BINDING | STUN_SUCCESS_RESP);
         resp->msgHdr.magic_cookie = ntohl(req.msgHdr.magic_cookie);
         for (i=0; i<12; i++ )
aymeric's avatar
aymeric committed
1550
         {
aymeric's avatar
aymeric committed
1551
            resp->msgHdr.tr_id.octet[i] = req.msgHdr.tr_id.octet[i];
aymeric's avatar
aymeric committed
1552 1553 1554 1555
         }
		
         if (1) /* do xorMapped address or not */
         {
aymeric's avatar
aymeric committed
1556 1557
            UInt32 cookie = 0x2112A442;
            UInt16 cookie16;
aymeric's avatar
aymeric committed
1558
            resp->hasXorMappedAddress = TRUE;
aymeric's avatar
aymeric committed
1559 1560 1561
            cookie16 = ((UInt8*)&cookie)[0]<<8  | ((UInt8*)&cookie)[1];
            resp->xorMappedAddress.ipv4.port = mapped.port^cookie16;
            resp->xorMappedAddress.ipv4.addr = mapped.addr^cookie;
aymeric's avatar
aymeric committed
1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583
         }
         
         resp->hasSourceAddress = TRUE;
         resp->sourceAddress.ipv4.port = (*changePort) ? altAddr->port : myAddr->port;
         resp->sourceAddress.ipv4.addr = (*changeIp)   ? altAddr->addr : myAddr->addr;
			
         resp->hasChangedAddress = TRUE;
         resp->changedAddress.ipv4.port = altAddr->port;
         resp->changedAddress.ipv4.addr = altAddr->addr;
	
         if ( req.hasUsername && req.username.sizeValue > 0 ) 
         {
            /* copy username in */
            resp->hasUsername = TRUE;
            /* assert( req.username.sizeValue % 4 == 0 ); */
            /* assert( req.username.sizeValue < STUN_MAX_STRING ); */
            memcpy( resp->username.value, req.username.value, req.username.sizeValue );
            resp->username.sizeValue = req.username.sizeValue;
         }
		
         if (1) /* add ServerName */
         {
aymeric's avatar
aymeric committed
1584 1585
            const char serverName[] = "oRTP   " STUN_VERSION; /* must pad to mult of 4 */
            resp->hasSoftware = TRUE;
aymeric's avatar
aymeric committed
1586 1587 1588 1589
            
            /* assert( sizeof(serverName) < STUN_MAX_STRING ); */
            /* cerr << "sizeof serverName is "  << sizeof(serverName) ); */
            /* assert( sizeof(serverName)%4 == 0 ); */
aymeric's avatar
aymeric committed
1590 1591
            memcpy( resp->softwareName.value, serverName, sizeof(serverName));
            resp->softwareName.sizeValue = sizeof(serverName);
aymeric's avatar
aymeric committed
1592 1593
         }
         
aymeric's avatar
aymeric committed
1594
#if 0
aymeric's avatar
aymeric committed
1595 1596 1597 1598 1599 1600
         if ( req.hasMessageIntegrity & req.hasUsername )  
         {
            /* this creates the password that will be used in the HMAC when then */
            /* messages is sent */
            stunCreatePassword( &req.username, hmacPassword );
         }
aymeric's avatar
aymeric committed
1601 1602
#endif

aymeric's avatar
aymeric committed
1603 1604 1605 1606