stun.c 77.6 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
 /*
  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/>.
 *
 */

70 71 72 73
#ifdef HAVE_CONFIG_H
#include "ortp-config.h"
#endif

aymeric's avatar
aymeric committed
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 102 103 104 105
#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


106 107 108
#if !defined(HAVE_OPENSSL_HMAC_H) || !defined(HAVE_OPENSSL_MD5_H)
#define NOSSL 1
#endif
aymeric's avatar
aymeric committed
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137

#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 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)
   {
aymeric's avatar
aymeric committed
138 139
      uint16_t nport;
      uint32_t naddr;
aymeric's avatar
aymeric committed
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
      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
166
      ortp_error("stun: Incorrect size for SA_CHANGEREQUEST");
aymeric's avatar
aymeric committed
167 168 169 170 171 172 173 174 175 176 177 178 179
      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
180
   if ( hdrLen < 4 || hdrLen >= 128+4)
aymeric's avatar
aymeric committed
181
   {
aymeric's avatar
aymeric committed
182
      ortp_error("stun: Incorrect size for SA_ERRORCODE");
aymeric's avatar
aymeric committed
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
      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
204
      ortp_error("stun: Incorrect size for SA_UNKNOWNATTRIBUTE");
aymeric's avatar
aymeric committed
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
      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
244
      ortp_error("stun: SA_MESSAGEINTEGRITY must be 20 bytes");
aymeric's avatar
aymeric committed
245 246 247 248 249 250 251 252 253
      return FALSE;
   }
   else
   {
      memcpy(&result->hash, body, hdrLen);
      return TRUE;
   }
}

aymeric's avatar
aymeric committed
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 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
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;
}

aymeric's avatar
aymeric committed
323 324
#if defined(htonq)
#elif defined(ORTP_BIGENDIAN)
325 326 327
#define htonq(n) n
#define ntohq(n) n
#else /* little endian */
aymeric's avatar
aymeric committed
328 329
static inline uint64_t
htonq (uint64_t v)
330
{
aymeric's avatar
aymeric committed
331 332
  return htonl ((uint32_t) (v >> 32))
    | (uint64_t) htonl ((uint32_t) v) << 32;
333
}
aymeric's avatar
aymeric committed
334 335
static inline uint64_t
ntohq (uint64_t v)
336
{
aymeric's avatar
aymeric committed
337 338
  return ntohl ((uint32_t) (v >> 32))
    | (uint64_t) ntohl ((uint32_t) v) << 32;
339 340
}
#endif /* little endian */
aymeric's avatar
aymeric committed
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355

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 
aymeric's avatar
aymeric committed
356
stunParseAtrFingerprint( char* body, unsigned int hdrLen, StunAtrFingerprint *result )
aymeric's avatar
aymeric committed
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
{
  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 )
{
372
  if ( hdrLen != 4 )
aymeric's avatar
aymeric committed
373 374 375 376 377 378 379 380 381 382 383 384 385
  {
    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 )
{
386
  if ( hdrLen != 8 )
aymeric's avatar
aymeric committed
387 388 389 390 391 392 393 394
  {
    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
395 396

bool_t
aymeric's avatar
aymeric committed
397
stunParseMessage( char* buf, unsigned int bufLen, StunMessage *msg)
aymeric's avatar
aymeric committed
398 399 400
{
   char* body;
   unsigned int size;
aymeric's avatar
aymeric committed
401
	 ortp_debug("stun: Received stun message: %i bytes\n", bufLen);
aymeric's avatar
aymeric committed
402 403 404 405
   memset(msg, 0, sizeof(msg));
	
   if (sizeof(StunMsgHdr) > bufLen)
   {
aymeric's avatar
aymeric committed
406
      ortp_warning("stun: message too short\n");
aymeric's avatar
aymeric committed
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
      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
443
      if (atrType == SA_MAPPEDADDRESS)
aymeric's avatar
aymeric committed
444 445 446 447
      {
            msg->hasMappedAddress = TRUE;
            if ( stunParseAtrAddress(  body,  attrLen,  &msg->mappedAddress )== FALSE )
            {
aymeric's avatar
aymeric committed
448
               ortp_error("stun: problem parsing SA_MAPPEDADDRESS\n");
aymeric's avatar
aymeric committed
449 450 451 452
               return FALSE;
            }
            else
            {
aymeric's avatar
aymeric committed
453
               ortp_debug("stun: SA_MAPPEDADDRESS = %s\n", ipaddr(&msg->mappedAddress.ipv4));
aymeric's avatar
aymeric committed
454 455 456
            }
					
      }
aymeric's avatar
aymeric committed
457
      else if (atrType == SA_RESPONSEADDRESS)
aymeric's avatar
aymeric committed
458 459 460 461
      {
            msg->hasResponseAddress = TRUE;
            if ( stunParseAtrAddress(  body,  attrLen,  &msg->responseAddress )== FALSE )
            {
aymeric's avatar
aymeric committed
462
               ortp_error("stun: problem parsing SA_RESPONSEADDRESS");
aymeric's avatar
aymeric committed
463 464 465 466
               return FALSE;
            }
            else
            {
aymeric's avatar
aymeric committed
467
               ortp_debug("stun: SA_RESPONSEADDRESS = %s\n", ipaddr(&msg->responseAddress.ipv4));
aymeric's avatar
aymeric committed
468 469
            }
      }
aymeric's avatar
aymeric committed
470
      else if (atrType == SA_CHANGEREQUEST)
aymeric's avatar
aymeric committed
471 472 473 474
      {
            msg->hasChangeRequest = TRUE;
            if (stunParseAtrChangeRequest( body, attrLen, &msg->changeRequest) == FALSE)
            {
aymeric's avatar
aymeric committed
475
               ortp_error("stun: problem parsing SA_CHANGEREQUEST\n");
aymeric's avatar
aymeric committed
476 477 478 479
               return FALSE;
            }
            else
            {
aymeric's avatar
aymeric committed
480
               ortp_debug("stun: SA_CHANGEREQUEST = %i\n", msg->changeRequest.value);
aymeric's avatar
aymeric committed
481 482
            }
      }
aymeric's avatar
aymeric committed
483
      else if (atrType == SA_SOURCEADDRESS)
aymeric's avatar
aymeric committed
484 485 486 487
      {
            msg->hasSourceAddress = TRUE;
            if ( stunParseAtrAddress(  body,  attrLen,  &msg->sourceAddress )== FALSE )
            {
aymeric's avatar
aymeric committed
488
               ortp_error("stun: problem parsing SA_SOURCEADDRESS\n");
aymeric's avatar
aymeric committed
489 490 491 492
               return FALSE;
            }
            else
            {
aymeric's avatar
aymeric committed
493
               ortp_debug("stun: SA_SOURCEADDRESS = %s\n", ipaddr(&msg->sourceAddress.ipv4) );
aymeric's avatar
aymeric committed
494 495
            }
      }
aymeric's avatar
aymeric committed
496
      else if (atrType == SA_CHANGEDADDRESS)
aymeric's avatar
aymeric committed
497 498 499 500
      {
            msg->hasChangedAddress = TRUE;
            if ( stunParseAtrAddress(  body,  attrLen,  &msg->changedAddress )== FALSE )
            {
aymeric's avatar
aymeric committed
501
               ortp_error("stun: problem parsing SA_CHANGEDADDRESS\n");
aymeric's avatar
aymeric committed
502 503 504 505
               return FALSE;
            }
            else
            {
aymeric's avatar
aymeric committed
506
               ortp_debug("stun: SA_CHANGEDADDRESS = %s\n", ipaddr(&msg->changedAddress.ipv4));
aymeric's avatar
aymeric committed
507 508
            }
      }
aymeric's avatar
aymeric committed
509
      else if (atrType == SA_USERNAME)
aymeric's avatar
aymeric committed
510 511 512 513
      {
            msg->hasUsername = TRUE;
            if (stunParseAtrString( body, attrLen, &msg->username) == FALSE)
            {
aymeric's avatar
aymeric committed
514
               ortp_error("stun: problem parsing SA_USERNAME");
aymeric's avatar
aymeric committed
515 516 517 518
               return FALSE;
            }
            else
            {
aymeric's avatar
aymeric committed
519
               ortp_debug("stun: SA_USERNAME = %s\n", msg->username.value );
aymeric's avatar
aymeric committed
520 521
            }					
      }
aymeric's avatar
aymeric committed
522
      else if (atrType == SA_PASSWORD)
aymeric's avatar
aymeric committed
523 524 525 526
      {
            msg->hasPassword = TRUE;
            if (stunParseAtrString( body, attrLen, &msg->password) == FALSE)
            {
aymeric's avatar
aymeric committed
527
               ortp_error("stun: problem parsing SA_PASSWORD");
aymeric's avatar
aymeric committed
528 529 530 531
               return FALSE;
            }
            else
            {
aymeric's avatar
aymeric committed
532
               ortp_debug("stun: SA_PASSWORD = %s\n", msg->password.value );
aymeric's avatar
aymeric committed
533 534
            }
      }
aymeric's avatar
aymeric committed
535
      else if (atrType == SA_MESSAGEINTEGRITY)
aymeric's avatar
aymeric committed
536 537 538 539
      {
            msg->hasMessageIntegrity = TRUE;
            if (stunParseAtrIntegrity( body, attrLen, &msg->messageIntegrity) == FALSE)
            {
aymeric's avatar
aymeric committed
540
               ortp_error("stun: problem parsing SA_MESSAGEINTEGRITY");
aymeric's avatar
aymeric committed
541
               return FALSE;
aymeric's avatar
aymeric committed
542
            }					
aymeric's avatar
aymeric committed
543
      }
aymeric's avatar
aymeric committed
544
      else if (atrType == SA_ERRORCODE)
aymeric's avatar
aymeric committed
545 546 547 548
      {
            msg->hasErrorCode = TRUE;
            if (stunParseAtrError(body, attrLen, &msg->errorCode) == FALSE)
            {
aymeric's avatar
aymeric committed
549
               ortp_error("stun: problem parsing SA_ERRORCODE");
aymeric's avatar
aymeric committed
550 551 552 553
               return FALSE;
            }
            else
            {
aymeric's avatar
aymeric committed
554
               ortp_debug("stun: SA_ERRORCODE = %i %i %s\n",
aymeric's avatar
aymeric committed
555 556 557 558 559 560
                                   msg->errorCode.errorClass ,
                                   msg->errorCode.number ,
                                   msg->errorCode.reason );
            }
					 
      }
aymeric's avatar
aymeric committed
561
      else if (atrType == SA_UNKNOWNATTRIBUTE)
aymeric's avatar
aymeric committed
562 563 564 565
      {
           msg->hasUnknownAttributes = TRUE;
            if (stunParseAtrUnknown(body, attrLen, &msg->unknownAttributes) == FALSE)
            {
aymeric's avatar
aymeric committed
566
               ortp_error("stun: problem parsing SA_UNKNOWNATTRIBUTE");
aymeric's avatar
aymeric committed
567 568 569
               return FALSE;
            }
      }
aymeric's avatar
aymeric committed
570
      else if (atrType == SA_REFLECTEDFROM)
aymeric's avatar
aymeric committed
571 572 573 574
      {
            msg->hasReflectedFrom = TRUE;
            if ( stunParseAtrAddress(  body,  attrLen,  &msg->reflectedFrom ) == FALSE )
            {
aymeric's avatar
aymeric committed
575 576 577 578 579 580 581 582 583 584
               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
585 586
               return FALSE;
            }
aymeric's avatar
aymeric committed
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
            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
604
      }
aymeric's avatar
aymeric committed
605
      else if (atrType == SA_XORMAPPEDADDRESS || atrType == SA_XORMAPPEDADDRESS2)
aymeric's avatar
aymeric committed
606 607 608 609
      { 
           msg->hasXorMappedAddress = TRUE;
            if ( stunParseAtrAddress(  body,  attrLen,  &msg->xorMappedAddress ) == FALSE )
            {
aymeric's avatar
aymeric committed
610 611 612 613 614
               ortp_error("stun: problem parsing SA_XORMAPPEDADDRESS");
               return FALSE;
            }
            else
            {
615 616 617 618 619
				uint32_t cookie = 0x2112A442;
      			uint16_t cookie16 = 0x2112A442 >> 16;
      			msg->xorMappedAddress.ipv4.port = msg->xorMappedAddress.ipv4.port^cookie16;
      			msg->xorMappedAddress.ipv4.addr = msg->xorMappedAddress.ipv4.addr^cookie;
				ortp_debug("stun: SA_XORMAPPEDADDRESS = %s\n", ipaddr(&msg->xorMappedAddress.ipv4) );
aymeric's avatar
aymeric committed
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
            }
      }
      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
636 637 638 639
               return FALSE;
            }
            else
            {
aymeric's avatar
aymeric committed
640
               ortp_debug("stun: SA_SOFTWARE = %s\n", msg->softwareName.value );
aymeric's avatar
aymeric committed
641 642
            }
      }
aymeric's avatar
aymeric committed
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
      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
666
      {
aymeric's avatar
aymeric committed
667 668 669 670 671 672 673 674 675 676
            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
677
      }
aymeric's avatar
aymeric committed
678
      else if (atrType == TA_DATA)
aymeric's avatar
aymeric committed
679
      {
aymeric's avatar
aymeric committed
680 681
            msg->hasData = TRUE;
            if (turnParseAtrData( body, attrLen, &msg->data) == FALSE)
aymeric's avatar
aymeric committed
682
            {
aymeric's avatar
aymeric committed
683
               ortp_error("stun: problem parsing TA_DATA");
aymeric's avatar
aymeric committed
684 685 686 687 688 689
               return FALSE;
            }
            else
            {
            }
      }
aymeric's avatar
aymeric committed
690
      else if (atrType == TA_XORRELAYEDADDRESS)
aymeric's avatar
aymeric committed
691
      {
aymeric's avatar
aymeric committed
692 693
            msg->hasXorRelayedAddress = TRUE;
            if ( stunParseAtrAddress(  body,  attrLen,  &msg->xorRelayedAddress )== FALSE )
aymeric's avatar
aymeric committed
694
            {
aymeric's avatar
aymeric committed
695
               ortp_error("stun: problem parsing TA_XORRELAYEDADDRESS\n");
aymeric's avatar
aymeric committed
696 697 698 699
               return FALSE;
            }
            else
            {
aymeric's avatar
aymeric committed
700 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
               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;
aymeric's avatar
aymeric committed
736
            if ( stunParseAtrFingerprint(  body,  attrLen,  &msg->fingerprint)== FALSE )
aymeric's avatar
aymeric committed
737 738 739 740 741 742 743
            {
               ortp_error("stun: problem parsing SA_FINGERPRINT\n");
               return FALSE;
            }
      }
      else if (atrType == ICEA_PRIORITY)
      {
744
            msg->hasPriority = TRUE;
aymeric's avatar
aymeric committed
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
            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
771 772 773 774 775 776
            }
      }
      else
      {
            if ( atrType <= 0x7FFF ) 
            {
aymeric's avatar
aymeric committed
777 778
              ortp_error("stun: Unknown Comprehension-Required attribute: %04x\n", atrType );
              return FALSE;
aymeric's avatar
aymeric committed
779
            }
aymeric's avatar
aymeric committed
780 781
            else
              ortp_warning("stun: Unknown attribute: %04x\n", atrType );
aymeric's avatar
aymeric committed
782 783
      }
		
aymeric's avatar
aymeric committed
784 785 786
      if (attrLen%4>0)
        attrLen += (4-(attrLen%4));
      
aymeric's avatar
aymeric committed
787 788 789 790 791 792 793 794 795
      body += attrLen;
      size -= attrLen;
   }
    
   return TRUE;
}


static char* 
aymeric's avatar
aymeric committed
796
encode16(char* buf, uint16_t data)
aymeric's avatar
aymeric committed
797
{
aymeric's avatar
aymeric committed
798 799 800
   uint16_t ndata = htons(data);
   memcpy(buf, &ndata, sizeof(uint16_t));
   return buf + sizeof(uint16_t);
aymeric's avatar
aymeric committed
801 802 803
}

static char* 
aymeric's avatar
aymeric committed
804
encode32(char* buf, uint32_t data)
aymeric's avatar
aymeric committed
805
{
aymeric's avatar
aymeric committed
806 807 808
   uint32_t ndata = htonl(data);
   memcpy(buf, &ndata, sizeof(uint32_t));
   return buf + sizeof(uint32_t);
aymeric's avatar
aymeric committed
809 810
}

811
static char* 
aymeric's avatar
aymeric committed
812
encode64(char* buf, uint64_t data)
813
{
aymeric's avatar
aymeric committed
814 815 816
   uint64_t ndata = htonq(data);
   memcpy(buf, &ndata, sizeof(uint64_t));
   return buf + sizeof(uint64_t);
817
}
aymeric's avatar
aymeric committed
818 819 820 821 822 823 824 825 826 827

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


static char* 
aymeric's avatar
aymeric committed
828
encodeAtrAddress4(char* ptr, uint16_t type, const StunAtrAddress4 *atr)
aymeric's avatar
aymeric committed
829 830 831 832 833 834 835 836 837 838 839 840 841 842
{
   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
843
   ptr = encode16(ptr, SA_CHANGEREQUEST);
aymeric's avatar
aymeric committed
844 845 846 847 848 849 850 851
   ptr = encode16(ptr, 4);
   ptr = encode32(ptr, atr->value);
   return ptr;
}

static char* 
encodeAtrError(char* ptr, const StunAtrError *atr)
{
aymeric's avatar
aymeric committed
852 853 854
   int padding;
   int i;

aymeric's avatar
aymeric committed
855
   ptr = encode16(ptr, SA_ERRORCODE);
aymeric's avatar
aymeric committed
856
   ptr = encode16(ptr, 4 + atr->sizeReason);
aymeric's avatar
aymeric committed
857 858 859 860
   ptr = encode16(ptr, atr->pad);
   *ptr++ = atr->errorClass;
   *ptr++ = atr->number;
   ptr = encode(ptr, atr->reason, atr->sizeReason);
aymeric's avatar
aymeric committed
861 862 863 864 865 866 867 868 869

   padding = (atr->sizeReason+4) % 4;
   if (padding>0)
   {
     for (i=0;i<4-padding;i++)
     {
       *ptr++ = 0;
     }
   }
aymeric's avatar
aymeric committed
870 871 872 873 874 875 876 877
   return ptr;
}


static char* 
encodeAtrUnknown(char* ptr, const StunAtrUnknown *atr)
{
   int i;
aymeric's avatar
aymeric committed
878
   ptr = encode16(ptr, SA_UNKNOWNATTRIBUTE);
aymeric's avatar
aymeric committed
879 880 881 882 883 884 885 886 887
   ptr = encode16(ptr, 2+2*atr->numAttributes);
   for (i=0; i<atr->numAttributes; i++)
   {
      ptr = encode16(ptr, atr->attrType[i]);
   }
   return ptr;
}

static char* 
aymeric's avatar
aymeric committed
888
encodeAtrString(char* ptr, uint16_t type, const StunAtrString *atr)
aymeric's avatar
aymeric committed
889
{
aymeric's avatar
aymeric committed
890 891
   int padding;
   int i;
aymeric's avatar
aymeric committed
892 893 894 895
	
   ptr = encode16(ptr, type);
   ptr = encode16(ptr, atr->sizeValue);
   ptr = encode(ptr, atr->value, atr->sizeValue);
aymeric's avatar
aymeric committed
896 897 898 899 900 901 902 903 904

   padding = atr->sizeValue % 4;
   if (padding>0)
   {
     for (i=0;i<4-padding;i++)
     {
       *ptr++ = 0;
     }
   }
aymeric's avatar
aymeric committed
905 906 907 908 909 910 911
   return ptr;
}


static char* 
encodeAtrIntegrity(char* ptr, const StunAtrIntegrity *atr)
{
aymeric's avatar
aymeric committed
912
   ptr = encode16(ptr, SA_MESSAGEINTEGRITY);
aymeric's avatar
aymeric committed
913 914 915 916 917
   ptr = encode16(ptr, 20);
   ptr = encode(ptr, atr->hash, sizeof(atr->hash));
   return ptr;
}

aymeric's avatar
aymeric committed
918 919 920
static char*
encodeAtrFingerprint(char* ptr, const StunAtrFingerprint *atr)
{
aymeric's avatar
aymeric committed
921
	uint32_t val;
aymeric's avatar
aymeric committed
922 923 924 925 926 927 928 929
	ptr = encode16(ptr, SA_FINGERPRINT);
	ptr = encode16(ptr, 4);

	val = atr->fingerprint;
	val ^= 0x5354554E;
	ptr = encode32(ptr, val);
	return ptr;
}
aymeric's avatar
aymeric committed
930

aymeric's avatar
aymeric committed
931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
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;
}

960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
static char* 
encodeAtrUseCandidate(char* ptr)
{
   ptr = encode16(ptr, ICEA_USECANDIDATE);
   ptr = encode16(ptr, 0);
   return ptr;
}

static char* 
encodeAtrPriority(char* ptr, const IceAtrPriority *atr)
{
   ptr = encode16(ptr, ICEA_PRIORITY);
   ptr = encode16(ptr, 4);
   ptr = encode32(ptr, atr->priority);
   return ptr;
}

static char* 
aymeric's avatar
aymeric committed
978
encodeAtrIceControll(char* ptr, uint16_t type, const IceAtrIceControll *atr)
979 980 981 982 983 984 985
{
   ptr = encode16(ptr, type);
   ptr = encode16(ptr, 8);
   ptr = encode64(ptr, atr->value);
   return ptr;
}

aymeric's avatar
aymeric committed
986 987 988 989
unsigned int
stunEncodeMessage( const StunMessage *msg, 
                   char* buf, 
                   unsigned int bufLen, 
aymeric's avatar
aymeric committed
990
                   const StunAtrString *password)
aymeric's avatar
aymeric committed
991 992 993 994 995 996
{
   char* ptr = buf;
   char* lengthp;
   ptr = encode16(ptr, msg->msgHdr.msgType);
   lengthp = ptr;
   ptr = encode16(ptr, 0);
aymeric's avatar
aymeric committed
997 998
   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
999
	
aymeric's avatar
aymeric committed
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
   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);
1016
   }		  
aymeric's avatar
aymeric committed
1017 1018
   if (msg->hasMappedAddress)
   {
aymeric's avatar
aymeric committed
1019 1020
      ortp_debug("stun: Encoding SA_MAPPEDADDRESS: %s\n", ipaddr(&msg->mappedAddress.ipv4) );
      ptr = encodeAtrAddress4 (ptr, SA_MAPPEDADDRESS, &msg->mappedAddress);
aymeric's avatar
aymeric committed
1021 1022 1023
   }
   if (msg->hasResponseAddress)
   {
aymeric's avatar
aymeric committed
1024 1025
      ortp_debug("stun: Encoding SA_RESPONSEADDRESS: %s\n", ipaddr(&msg->responseAddress.ipv4) );
      ptr = encodeAtrAddress4(ptr, SA_RESPONSEADDRESS, &msg->responseAddress);
aymeric's avatar
aymeric committed
1026 1027 1028
   }
   if (msg->hasChangeRequest)
   {
aymeric's avatar
aymeric committed
1029
      ortp_debug("stun: Encoding SA_CHANGEREQUEST: %i\n", msg->changeRequest.value );
aymeric's avatar
aymeric committed
1030 1031 1032 1033
      ptr = encodeAtrChangeRequest(ptr, &msg->changeRequest);
   }
   if (msg->hasSourceAddress)
   {
aymeric's avatar
aymeric committed
1034 1035
      ortp_debug("stun: Encoding SA_SOURCEADDRESS: %s\n", ipaddr(&msg->sourceAddress.ipv4) );
      ptr = encodeAtrAddress4(ptr, SA_SOURCEADDRESS, &msg->sourceAddress);
aymeric's avatar
aymeric committed
1036 1037 1038
   }
   if (msg->hasChangedAddress)
   {
aymeric's avatar
aymeric committed
1039 1040
      ortp_debug("stun: Encoding SA_CHANGEDADDRESS: %s\n", ipaddr(&msg->changedAddress.ipv4) );
      ptr = encodeAtrAddress4(ptr, SA_CHANGEDADDRESS, &msg->changedAddress);
aymeric's avatar
aymeric committed
1041 1042 1043
   }
   if (msg->hasUsername)
   {
aymeric's avatar
aymeric committed
1044 1045
      ortp_debug("stun: Encoding SA_USERNAME: %s\n", msg->username.value );
      ptr = encodeAtrString(ptr, SA_USERNAME, &msg->username);
aymeric's avatar
aymeric committed
1046
   }
aymeric's avatar
aymeric committed
1047 1048 1049 1050 1051
   //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
1052 1053
   if (msg->hasErrorCode)
   {
aymeric's avatar
aymeric committed
1054
      ortp_debug("stun: Encoding SA_ERRORCODE: class=%i number=%i reason=%s\n" 
aymeric's avatar
aymeric committed
1055 1056 1057 1058 1059 1060 1061 1062
                          , msg->errorCode.errorClass 
                          , msg->errorCode.number
                          , msg->errorCode.reason );
      
      ptr = encodeAtrError(ptr, &msg->errorCode);
   }
   if (msg->hasUnknownAttributes)
   {
aymeric's avatar
aymeric committed
1063
      ortp_debug("stun: Encoding SA_UNKNOWNATTRIBUTE: ???");
aymeric's avatar
aymeric committed
1064 1065 1066 1067
      ptr = encodeAtrUnknown(ptr, &msg->unknownAttributes);
   }
   if (msg->hasReflectedFrom)
   {
aymeric's avatar
aymeric committed
1068 1069
      ortp_debug("stun: Encoding SA_REFLECTEDFROM: %s\n", ipaddr(&msg->reflectedFrom.ipv4) );
      ptr = encodeAtrAddress4(ptr, SA_REFLECTEDFROM, &msg->reflectedFrom);
aymeric's avatar
aymeric committed
1070
   }
aymeric's avatar
aymeric committed
1071
   if (msg->hasNonce)
aymeric's avatar
aymeric committed
1072
   {
aymeric's avatar
aymeric committed
1073 1074
      ortp_debug("stun: Encoding SA_NONCE: %s\n", msg->nonceName.value );
      ptr = encodeAtrString(ptr, SA_NONCE, &msg->nonceName);
aymeric's avatar
aymeric committed
1075
   }
aymeric's avatar
aymeric committed
1076
   if (msg->hasRealm)
aymeric's avatar
aymeric committed
1077
   {
aymeric's avatar
aymeric committed
1078 1079
      ortp_debug("stun: Encoding SA_REALM: %s\n", msg->realmName.value );
      ptr = encodeAtrString(ptr, SA_REALM, &msg->realmName);
aymeric's avatar
aymeric committed
1080
   }
aymeric's avatar
aymeric committed
1081 1082
   
   if (msg->hasXorMappedAddress)
aymeric's avatar
aymeric committed
1083
   {
aymeric's avatar
aymeric committed
1084 1085
      ortp_debug("stun: Encoding SA_XORMAPPEDADDRESS: %s\n", ipaddr(&msg->xorMappedAddress.ipv4) );
      ptr = encodeAtrAddress4 (ptr, SA_XORMAPPEDADDRESS, &msg->xorMappedAddress);
aymeric's avatar
aymeric committed
1086
   }
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
   
   if (msg->hasPriority)
   {	   
      ortp_debug("stun: Encoding ICEA_PRIORITY\n");
      ptr = encodeAtrPriority (ptr, &msg->priority);
   }
   if (msg->hasUseCandidate)
   {	   
      ortp_debug("stun: Encoding ICEA_USECANDIDATE\n");
      ptr = encodeAtrUseCandidate (ptr);
   }
   if (msg->hasIceControlled)
   {	   
      ortp_debug("stun: Encoding ICEA_ICECONTROLLED\n");
      ptr = encodeAtrIceControll (ptr, ICEA_ICECONTROLLED, &msg->iceControlled);
   }
   if (msg->hasIceControlling)
   {	   
      ortp_debug("stun: Encoding ICEA_ICECONTROLLING\n");
      ptr = encodeAtrIceControll (ptr, ICEA_ICECONTROLLING, &msg->iceControlling);
   }

aymeric's avatar
aymeric committed
1109
   if (msg->hasSoftware)
aymeric's avatar
aymeric committed
1110
   {
aymeric's avatar
aymeric committed
1111 1112
      ortp_debug("stun: Encoding SA_SOFTWARE: %s\n", msg->softwareName.value );
      ptr = encodeAtrString(ptr, SA_SOFTWARE, &msg->softwareName);
aymeric's avatar
aymeric committed
1113 1114
   }

aymeric's avatar
aymeric committed
1115 1116 1117 1118 1119 1120 1121 1122
   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 );

aymeric's avatar
aymeric committed
1123
      encode16(lengthp, (uint16_t)(ptr - buf - sizeof(StunMsgHdr)+24));
aymeric's avatar
aymeric committed
1124
      stunCalculateIntegrity_longterm(integrity.hash, buf, (int)(ptr-buf) ,
aymeric's avatar
aymeric committed
1125 1126 1127 1128 1129 1130
        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
1131 1132
   {
      StunAtrIntegrity integrity;
aymeric's avatar
aymeric committed
1133
      //ortp_debug("stun: HMAC with password: %s\n", password->value );
aymeric's avatar
aymeric committed
1134

aymeric's avatar
aymeric committed
1135
      encode16(lengthp, (uint16_t)(ptr - buf - sizeof(StunMsgHdr)+24));
aymeric's avatar
aymeric committed
1136
      stunCalculateIntegrity_shortterm(integrity.hash, buf, (int)(ptr-buf) ,
aymeric's avatar
aymeric committed
1137
        password->value);
aymeric's avatar
aymeric committed
1138 1139
      ptr = encodeAtrIntegrity(ptr, &integrity);
   }
aymeric's avatar
aymeric committed
1140 1141 1142 1143 1144 1145

   if (msg->hasFingerprint)
   {
      StunAtrFingerprint fingerprint;
      //ortp_debug("stun: HMAC with password: %s\n", password->value );

aymeric's avatar
aymeric committed
1146
      encode16(lengthp, (uint16_t)(ptr - buf - sizeof(StunMsgHdr)+8));
aymeric's avatar
aymeric committed
1147 1148 1149
      fingerprint.fingerprint = stunCalculateFingerprint(buf, (int)(ptr-buf));
      ptr = encodeAtrFingerprint(ptr, &fingerprint);
   }
aymeric's avatar
aymeric committed
1150
   encode16(lengthp, (uint16_t)(ptr - buf - sizeof(StunMsgHdr)));
aymeric's avatar
aymeric committed
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
   return (int)(ptr - buf);
}

int 
stunRand(void)
{
   /* return 32 bits of random stuff */
   /* assert( sizeof(int) == 4 ); */
   static bool_t init=FALSE;
   if ( !init )
   { 
aymeric's avatar
aymeric committed
1162
      uint64_t tick;
aymeric's avatar
aymeric committed
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
      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;
      }
aymeric's avatar
aymeric committed
1181 1182 1183 1184 1185 1186
#elif defined(__MACH__) 
	   {
		   int fd=open("/dev/random",O_RDONLY);
		   read(fd,&tick,sizeof(tick));
		   closesocket(fd);
	   }
aymeric's avatar
aymeric committed
1187 1188 1189 1190 1191 1192
#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();
Simon Morlat's avatar
Simon Morlat committed
1193
#elif defined(__linux) || defined(__linux__) || defined(HAVE_DEV_RANDOM) 
aymeric's avatar
aymeric committed
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 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 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
      {
 	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
aymeric's avatar
aymeric committed
1266 1267
void
stunCalculateIntegrity_longterm(char* hmac, const char* input, int length,
aymeric's avatar
aymeric committed
1268 1269 1270 1271
                     const char *username, const char *realm, const char *password)
{
   strncpy(hmac,"hmac-not-implemented",20);
}
aymeric's avatar
aymeric committed
1272 1273
void
stunCalculateIntegrity_shortterm(char* hmac, const char* input, int length, const char* key)
aymeric's avatar
aymeric committed
1274 1275 1276
{
   strncpy(hmac,"hmac-not-implemented",20);
}
aymeric's avatar
aymeric committed
1277

aymeric's avatar
aymeric committed
1278 1279
#else
#include <openssl/hmac.h>
aymeric's avatar
aymeric committed
1280
#include <openssl/md5.h>
aymeric's avatar
aymeric committed
1281

aymeric's avatar
aymeric committed
1282 1283
void
stunCalculateIntegrity_longterm(char* hmac, const char* input, int length,
aymeric's avatar
aymeric committed
1284
                     const char *username, const char *realm, const char *password)
aymeric's avatar
aymeric committed
1285 1286
{
   unsigned int resultSize=0;
aymeric's avatar
aymeric committed
1287
   unsigned char HA1[16];
aymeric's avatar
aymeric committed
1288
   char HA1_text[1024];
aymeric's avatar
aymeric committed
1289 1290

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

aymeric's avatar
aymeric committed
1293
   HMAC(EVP_sha1(), 
aymeric's avatar
aymeric committed
1294 1295 1296 1297 1298
        HA1, 16, 
        (const unsigned char*) input, length, 
        (unsigned char*)hmac, &resultSize);
}

aymeric's avatar
aymeric committed
1299 1300
void
stunCalculateIntegrity_shortterm(char* hmac, const char* input, int length, const char* key)
aymeric's avatar
aymeric committed
1301 1302 1303 1304
{
   unsigned int resultSize=0;
   HMAC(EVP_sha1(), 
        key, strlen(key), 
aymeric's avatar
aymeric committed
1305 1306 1307
        (const unsigned char*) input, length, 
        (unsigned char*)hmac, &resultSize);
}
aymeric's avatar
aymeric committed
1308

aymeric's avatar
aymeric committed
1309 1310
#endif

aymeric's avatar
aymeric committed
1311
uint32_t
aymeric's avatar
aymeric committed
1312 1313
stunCalculateFingerprint(const char* input, int length)
{
aymeric's avatar
aymeric committed
1314 1315 1316
	/*-
	2  *  COPYRIGHT (C) 1986 Gary S. Brown.  You may use this program, or
	3  *  code or tables extracted from it, as desired without restriction.
aymeric's avatar
aymeric committed
1317
	4  */
aymeric's avatar
aymeric committed
1318
	static uint32_t crc32_tab[] = {
aymeric's avatar
aymeric committed
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 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
		0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
		0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
		0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
		0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
		0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
		0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e