stunmessage.c 16.6 KB
Newer Older
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
/*
 * This file is part of the Nice GLib ICE library.
 *
 * (C) 2007 Nokia Corporation. All rights reserved.
 *  Contact: Rémi Denis-Courmont
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is the Nice GLib ICE library.
 *
 * The Initial Developers of the Original Code are Collabora Ltd and Nokia
 * Corporation. All Rights Reserved.
 *
 * Contributors:
 *   Rémi Denis-Courmont, Nokia
 *
 * Alternatively, the contents of this file may be used under the terms of the
 * the GNU Lesser General Public License Version 2.1 (the "LGPL"), in which
 * case the provisions of LGPL are applicable instead of those above. If you
 * wish to allow use of your version of this file only under the terms of the
 * LGPL and not to allow others to use your version of this file under the
 * MPL, indicate your decision by deleting the provisions above and replace
 * them with the notice and other provisions required by the LGPL. If you do
 * not delete the provisions above, a recipient may use your version of this
 * file under either the MPL or the LGPL.
 */

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

Youness Alaoui's avatar
Youness Alaoui committed
40 41 42 43
#include "stunmessage.h"

#ifdef _WIN32
#include <winsock2.h>
44
#include <ws2tcpip.h>
Youness Alaoui's avatar
Youness Alaoui committed
45
#else
46 47
#include <sys/types.h>
#include <sys/socket.h>
Youness Alaoui's avatar
Youness Alaoui committed
48
#endif
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63


#include <string.h>
#include <stdlib.h>

bool stun_message_init (StunMessage *msg, stun_class_t c, stun_method_t m,
    const stun_transid_t id)
{

  if (msg->buffer_len < STUN_MESSAGE_HEADER_LENGTH)
    return FALSE;

  memset (msg->buffer, 0, 4);
  stun_set_type (msg->buffer, c, m);

64
  memcpy (msg->buffer + STUN_MESSAGE_TRANS_ID_POS,
65
      id, STUN_MESSAGE_TRANS_ID_LEN);
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80

  return TRUE;
}

uint16_t stun_message_length (const StunMessage *msg)
{
  return stun_getw (msg->buffer + STUN_MESSAGE_LENGTH_POS) +
      STUN_MESSAGE_HEADER_LENGTH;
}




const void *
stun_message_find (const StunMessage *msg, stun_attr_type_t type,
81
    uint16_t *palen)
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
{
  size_t length = stun_message_length (msg);
  size_t offset = 0;


  offset = STUN_MESSAGE_ATTRIBUTES_POS;

  while (offset < length)
  {
    uint16_t atype = stun_getw (msg->buffer + offset);
    size_t alen = stun_getw (msg->buffer + offset + STUN_ATTRIBUTE_TYPE_LEN);


    offset += STUN_ATTRIBUTE_VALUE_POS;

    if (atype == type)
    {
      *palen = alen;
      return msg->buffer + offset;
    }

    /* Look for and ignore misordered attributes */
    switch (atype)
    {
106
      case STUN_ATTRIBUTE_MESSAGE_INTEGRITY:
107
        /* Only fingerprint may come after M-I */
108
        if (type == STUN_ATTRIBUTE_FINGERPRINT)
109 110
          break;

111
      case STUN_ATTRIBUTE_FINGERPRINT:
112 113 114 115 116 117 118 119 120 121 122 123
        /* Nothing may come after FPR */
        return NULL;
    }

    alen = stun_align (alen);
    offset += alen;
  }

  return NULL;
}


124 125
StunMessageReturn
stun_message_find_flag (const StunMessage *msg, stun_attr_type_t type)
126 127 128 129 130 131
{
  const void *ptr;
  uint16_t len;

  ptr = stun_message_find (msg, type, &len);
  if (ptr == NULL)
132 133 134
    return STUN_MESSAGE_RETURN_NOT_FOUND;
  return (len == 0) ? STUN_MESSAGE_RETURN_SUCCESS :
      STUN_MESSAGE_RETURN_INVALID;
135 136 137
}


138
StunMessageReturn
139
stun_message_find32 (const StunMessage *msg, stun_attr_type_t type,
140
    uint32_t *pval)
141 142 143 144 145 146
{
  const void *ptr;
  uint16_t len;

  ptr = stun_message_find (msg, type, &len);
  if (ptr == NULL)
147
    return STUN_MESSAGE_RETURN_NOT_FOUND;
148 149 150 151 152 153 154

  if (len == 4)
  {
    uint32_t val;

    memcpy (&val, ptr, sizeof (val));
    *pval = ntohl (val);
155
    return STUN_MESSAGE_RETURN_SUCCESS;
156
  }
157
  return STUN_MESSAGE_RETURN_INVALID;
158 159 160
}


161 162
StunMessageReturn
stun_message_find64 (const StunMessage *msg, stun_attr_type_t type,
163 164 165 166 167 168 169
    uint64_t *pval)
{
  const void *ptr;
  uint16_t len;

  ptr = stun_message_find (msg, type, &len);
  if (ptr == NULL)
170
    return STUN_MESSAGE_RETURN_NOT_FOUND;
171 172 173 174 175 176 177

  if (len == 8)
  {
    uint32_t tab[2];

    memcpy (tab, ptr, sizeof (tab));
    *pval = ((uint64_t)ntohl (tab[0]) << 32) | ntohl (tab[1]);
178
    return STUN_MESSAGE_RETURN_SUCCESS;
179
  }
180
  return STUN_MESSAGE_RETURN_INVALID;
181 182 183
}


184 185
StunMessageReturn
stun_message_find_string (const StunMessage *msg, stun_attr_type_t type,
186 187 188 189 190 191 192
    char *buf, size_t buflen)
{
  const unsigned char *ptr;
  uint16_t len;

  ptr = stun_message_find (msg, type, &len);
  if (ptr == NULL)
193
    return STUN_MESSAGE_RETURN_NOT_FOUND;
194 195

  if (len >= buflen)
196
    return STUN_MESSAGE_RETURN_NOT_ENOUGH_SPACE;
197 198 199

  memcpy (buf, ptr, len);
  buf[len] = '\0';
200
  return STUN_MESSAGE_RETURN_SUCCESS;
201 202 203
}


204
StunMessageReturn
205
stun_message_find_addr (const StunMessage *msg, stun_attr_type_t type,
206
    struct sockaddr *addr, socklen_t *addrlen)
207 208 209 210 211 212
{
  const uint8_t *ptr;
  uint16_t len;

  ptr = stun_message_find (msg, type, &len);
  if (ptr == NULL)
213
    return STUN_MESSAGE_RETURN_NOT_FOUND;
214 215

  if (len < 4)
216
    return STUN_MESSAGE_RETURN_INVALID;
217 218 219 220 221 222

  switch (ptr[1])
  {
    case 1:
      {
        struct sockaddr_in *ip4 = (struct sockaddr_in *)addr;
223
        if (((size_t) *addrlen < sizeof (*ip4)) || (len != 8))
224 225
        {
          *addrlen = sizeof (*ip4);
226
          return STUN_MESSAGE_RETURN_INVALID;
227 228 229 230 231 232 233 234 235 236
        }

        memset (ip4, 0, *addrlen);
        ip4->sin_family = AF_INET;
#ifdef HAVE_SA_LEN
        ip4->sin_len =
#endif
            *addrlen = sizeof (*ip4);
        memcpy (&ip4->sin_port, ptr + 2, 2);
        memcpy (&ip4->sin_addr, ptr + 4, 4);
237
        return STUN_MESSAGE_RETURN_SUCCESS;
238 239 240 241 242
      }

    case 2:
      {
        struct sockaddr_in6 *ip6 = (struct sockaddr_in6 *)addr;
243
        if (((size_t) *addrlen < sizeof (*ip6)) || (len != 20))
244 245
        {
          *addrlen = sizeof (*ip6);
246
          return STUN_MESSAGE_RETURN_INVALID;
247 248 249 250 251 252 253 254 255 256
        }

        memset (ip6, 0, *addrlen);
        ip6->sin6_family = AF_INET6;
#ifdef HAVE_SA_LEN
        ip6->sin6_len =
#endif
            *addrlen = sizeof (*ip6);
        memcpy (&ip6->sin6_port, ptr + 2, 2);
        memcpy (&ip6->sin6_addr, ptr + 4, 16);
257
        return STUN_MESSAGE_RETURN_SUCCESS;
258 259 260
      }
  }

261
  return STUN_MESSAGE_RETURN_UNSUPPORTED_ADDRESS;
262 263
}

264
StunMessageReturn
265
stun_message_find_xor_addr (const StunMessage *msg, stun_attr_type_t type,
266 267
    struct sockaddr *addr,
    socklen_t *addrlen)
268
{
269
  StunMessageReturn val = stun_message_find_addr (msg, type, addr, addrlen);
270 271 272
  if (val)
    return val;

273 274 275
  return stun_xor_address (msg, addr, *addrlen, STUN_MAGIC_COOKIE);
}

276
StunMessageReturn
277
stun_message_find_xor_addr_full (const StunMessage *msg, stun_attr_type_t type,
278
    struct sockaddr *addr,  socklen_t *addrlen,
279 280
    uint32_t magic_cookie)
{
281
  StunMessageReturn val = stun_message_find_addr (msg, type, addr, addrlen);
282 283 284 285
  if (val)
    return val;

  return stun_xor_address (msg, addr, *addrlen, magic_cookie);
286 287
}

288 289
StunMessageReturn
stun_message_find_error (const StunMessage *msg, int *code)
290 291
{
  uint16_t alen;
292
  const uint8_t *ptr = stun_message_find (msg, STUN_ATTRIBUTE_ERROR_CODE, &alen);
293 294 295
  uint8_t class, number;

  if (ptr == NULL)
296
    return STUN_MESSAGE_RETURN_NOT_FOUND;
297
  if (alen < 4)
298
    return STUN_MESSAGE_RETURN_INVALID;
299 300 301 302

  class = ptr[2] & 0x7;
  number = ptr[3];
  if ((class < 3) || (class > 6) || (number > 99))
303
    return STUN_MESSAGE_RETURN_INVALID;
304 305

  *code = (class * 100) + number;
306
  return STUN_MESSAGE_RETURN_SUCCESS;
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
}

/**
 * Reserves room for appending an attribute to an unfinished STUN message.
 * @param msg STUN message buffer
 * @param msize STUN message buffer size
 * @param type message type (host byte order)
 * @param length attribute payload byte length
 * @return a pointer to an unitialized buffer of <length> bytes to
 * where the attribute payload must be written, or NULL if there is not
 * enough room in the STUN message buffer. Return value is always on a
 * 32-bits boundary.
 */
void *
stun_message_append (StunMessage *msg, stun_attr_type_t type, size_t length)
{
  uint8_t *a;
324
  uint16_t mlen = stun_message_length (msg);
325

326
  if ((size_t)mlen + STUN_ATTRIBUTE_HEADER_LENGTH + length > msg->buffer_len)
327 328 329
    return NULL;


330
  a = msg->buffer + mlen;
331 332 333
  a = stun_setw (a, type);
  /* NOTE: If cookie is not present, we need to force the attribute length
   * to a multiple of 4 for compatibility with old RFC3489 */
334
  a = stun_setw (a, stun_has_cookie (msg) ? length : stun_align (length));
335

336
  mlen +=  4 + length;
337 338 339 340
  /* Add padding if needed */
  memset (a + length, ' ', stun_padding (length));
  mlen += stun_padding (length);

341
  stun_setw (msg->buffer + STUN_MESSAGE_LENGTH_POS, mlen - STUN_MESSAGE_HEADER_LENGTH);
342 343 344 345 346 347 348 349 350 351 352 353 354
  return a;
}


/**
 * Appends an attribute from memory.
 * @param msg STUN message buffer
 * @param msize STUN message buffer size
 * @param type attribute type (host byte order)
 * @param data memory address to copy payload from
 * @param len attribute payload length
 * @return 0 on success, ENOBUFS on error.
 */
355
StunMessageReturn
356 357 358 359 360
stun_message_append_bytes (StunMessage *msg, stun_attr_type_t type,
    const void *data, size_t len)
{
  void *ptr = stun_message_append (msg, type, len);
  if (ptr == NULL)
361
    return STUN_MESSAGE_RETURN_NOT_ENOUGH_SPACE;
362 363

  memcpy (ptr, data, len);
364
  return STUN_MESSAGE_RETURN_SUCCESS;
365 366 367
}


368 369
StunMessageReturn
stun_message_append_flag (StunMessage *msg, stun_attr_type_t type)
370 371 372 373 374
{
  return stun_message_append_bytes (msg, type, NULL, 0);
}


375
StunMessageReturn
376 377 378 379 380 381 382 383
stun_message_append32 (StunMessage *msg, stun_attr_type_t type,
    uint32_t value)
{
  value = htonl (value);
  return stun_message_append_bytes (msg, type, &value, 4);
}


384 385
StunMessageReturn
stun_message_append64 (StunMessage *msg, stun_attr_type_t type,
386 387 388 389 390 391 392 393 394
    uint64_t value)
{
  uint32_t tab[2];
  tab[0] = htonl ((uint32_t)(value >> 32));
  tab[1] = htonl ((uint32_t)value);
  return stun_message_append_bytes (msg, type, tab, 8);
}


395
StunMessageReturn
396 397 398 399 400 401
stun_message_append_string (StunMessage * msg, stun_attr_type_t type,
    const char *str)
{
  return stun_message_append_bytes (msg, type, str, strlen (str));
}

402
StunMessageReturn
403
stun_message_append_addr (StunMessage *msg, stun_attr_type_t type,
404
    const struct sockaddr *addr, socklen_t addrlen)
405 406 407 408 409 410
{
  const void *pa;
  uint8_t *ptr;
  uint16_t alen, port;
  uint8_t family;

411
  if ((size_t) addrlen < sizeof (struct sockaddr))
412
    return STUN_MESSAGE_RETURN_INVALID;
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428

  switch (addr->sa_family)
  {
    case AF_INET:
      {
        const struct sockaddr_in *ip4 = (const struct sockaddr_in *)addr;
        family = 1;
        port = ip4->sin_port;
        alen = 4;
        pa = &ip4->sin_addr;
        break;
      }

    case AF_INET6:
      {
        const struct sockaddr_in6 *ip6 = (const struct sockaddr_in6 *)addr;
429
        if ((size_t) addrlen < sizeof (*ip6))
430
          return STUN_MESSAGE_RETURN_INVALID;
431 432 433 434 435 436 437 438 439

        family = 2;
        port = ip6->sin6_port;
        alen = 16;
        pa = &ip6->sin6_addr;
        break;
      }

    default:
440
      return STUN_MESSAGE_RETURN_UNSUPPORTED_ADDRESS;
441 442 443 444
  }

  ptr = stun_message_append (msg, type, 4 + alen);
  if (ptr == NULL)
445
    return STUN_MESSAGE_RETURN_NOT_ENOUGH_SPACE;
446 447 448 449 450

  ptr[0] = 0;
  ptr[1] = family;
  memcpy (ptr + 2, &port, 2);
  memcpy (ptr + 4, pa, alen);
451
  return STUN_MESSAGE_RETURN_SUCCESS;
452 453 454
}


455 456
StunMessageReturn
stun_message_append_xor_addr (StunMessage *msg, stun_attr_type_t type,
457
    const struct sockaddr *addr, socklen_t addrlen)
458
{
459
  StunMessageReturn val;
460 461 462
  /* Must be big enough to hold any supported address: */
  struct sockaddr_storage xor;

463
  if ((size_t) addrlen > sizeof (xor))
464 465 466
    addrlen = sizeof (xor);
  memcpy (&xor, addr, addrlen);

467 468 469 470 471 472 473 474 475
  val = stun_xor_address (msg, (struct sockaddr *)&xor, addrlen,
      STUN_MAGIC_COOKIE);
  if (val)
    return val;

  return stun_message_append_addr (msg, type, (struct sockaddr *)&xor,
      addrlen);
}

476 477
StunMessageReturn
stun_message_append_xor_addr_full (StunMessage *msg, stun_attr_type_t type,
478
    const struct sockaddr *addr, socklen_t addrlen,
479 480
    uint32_t magic_cookie)
{
481
  StunMessageReturn val;
482 483 484
  /* Must be big enough to hold any supported address: */
  struct sockaddr_storage xor;

485
  if ((size_t) addrlen > sizeof (xor))
486 487 488 489
    addrlen = sizeof (xor);
  memcpy (&xor, addr, addrlen);

  val = stun_xor_address (msg, (struct sockaddr *)&xor, addrlen, magic_cookie);
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
  if (val)
    return val;

  return stun_message_append_addr (msg, type, (struct sockaddr *)&xor,
      addrlen);
}



/**
 * Appends an ERROR-CODE attribute.
 * @param msg STUN message buffer
 * @param msize STUN message buffer size
 * @param code STUN host-byte order integer error code
 * @return 0 on success, or ENOBUFS otherwise
 */
506
StunMessageReturn
507 508 509 510 511 512
stun_message_append_error (StunMessage *msg, stun_error_t code)
{
  const char *str = stun_strerror (code);
  size_t len = strlen (str);
  div_t d = div (code, 100);

513
  uint8_t *ptr = stun_message_append (msg, STUN_ATTRIBUTE_ERROR_CODE, 4 + len);
514
  if (ptr == NULL)
515
    return STUN_MESSAGE_RETURN_NOT_ENOUGH_SPACE;
516 517 518 519 520

  memset (ptr, 0, 2);
  ptr[2] = d.quot;
  ptr[3] = d.rem;
  memcpy (ptr + 4, str, len);
521
  return STUN_MESSAGE_RETURN_SUCCESS;
522 523
}

524
int stun_message_validate_buffer_length (const uint8_t *msg, size_t length)
525 526 527 528 529 530 531
{
  size_t mlen;
  size_t len;

  if (length < 1)
  {
    stun_debug ("STUN error: No data!\n");
532
    return STUN_MESSAGE_BUFFER_INVALID;
533 534 535 536 537
  }

  if (msg[0] >> 6)
  {
    stun_debug ("STUN error: RTP or other non-protocol packet!\n");
538
    return STUN_MESSAGE_BUFFER_INVALID; // RTP or other non-STUN packet
539 540 541 542 543
  }

  if (length < 4)
  {
    stun_debug ("STUN error: Incomplete STUN message header!\n");
544
    return STUN_MESSAGE_BUFFER_INCOMPLETE;
545 546 547 548 549 550 551 552
  }

  mlen = stun_getw (msg + STUN_MESSAGE_LENGTH_POS) +
      STUN_MESSAGE_HEADER_LENGTH;

  if (stun_padding (mlen))
  {
    stun_debug ("STUN error: Invalid message length: %u!\n", (unsigned)mlen);
553
    return STUN_MESSAGE_BUFFER_INVALID; // wrong padding
554 555 556 557 558 559
  }

  if (length < mlen)
  {
    stun_debug ("STUN error: Incomplete message: %u of %u bytes!\n",
        (unsigned)length, (unsigned)mlen);
560
    return STUN_MESSAGE_BUFFER_INCOMPLETE; // partial message
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
  }

  msg += 20;
  len = mlen - 20;

  /* from then on, we know we have the entire packet in buffer */
  while (len > 0)
  {
    size_t alen = stun_align (stun_getw (msg + STUN_ATTRIBUTE_TYPE_LEN));

    /* thanks to padding check, if (end > msg) then there is not only one
     * but at least 4 bytes left */
    len -= 4;

    if (len < alen)
    {
      stun_debug ("STUN error: %u instead of %u bytes for attribute!\n",
          (unsigned)len, (unsigned)alen);
579
      return STUN_MESSAGE_BUFFER_INVALID; // no room for attribute value + padding
580 581 582 583 584 585
    }

    len -= alen;
    msg += 4 + alen;
  }

586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
  return mlen;
}

/**
 * copies STUN message transaction ID
 */
void stun_message_id (const StunMessage *msg, stun_transid_t id)
{
  memcpy (id, msg->buffer + STUN_MESSAGE_TRANS_ID_POS, STUN_MESSAGE_TRANS_ID_LEN);
}

/**
 * @return STUN message method (value from 0 to 0xfff)
 */
stun_method_t stun_message_get_method (const StunMessage *msg)
{
  uint16_t t = stun_getw (msg->buffer);
Youness Alaoui's avatar
Youness Alaoui committed
603
  /* HACK HACK HACK
604
     A google/msn data indication is 0x0115 which is contrary to the RFC 5389
Youness Alaoui's avatar
Youness Alaoui committed
605 606 607 608 609 610 611 612
     which states that 8th and 12th bits are for the class and that 0x01 is
     for indications...
     So 0x0115 is reported as a "connect error response", while it should be
     a data indication, which message type should actually be 0x0017
     This should fix the issue, and it's considered safe since the "connect"
     method doesn't exist anymore */
  if (t == 0x0115)
    t = 0x0017;
613 614 615 616 617 618 619 620 621 622 623
  return (stun_method_t)(((t & 0x3e00) >> 2) | ((t & 0x00e0) >> 1) |
                          (t & 0x000f));
}


/**
 * @return STUN message class in host byte order (value from 0 to 3)
 */
stun_class_t stun_message_get_class (const StunMessage *msg)
{
  uint16_t t = stun_getw (msg->buffer);
Youness Alaoui's avatar
Youness Alaoui committed
624
  /* HACK HACK HACK
625
     A google/msn data indication is 0x0115 which is contrary to the RFC 5389
Youness Alaoui's avatar
Youness Alaoui committed
626 627 628 629 630 631 632 633
     which states that 8th and 12th bits are for the class and that 0x01 is
     for indications...
     So 0x0115 is reported as a "connect error response", while it should be
     a data indication, which message type should actually be 0x0017
     This should fix the issue, and it's considered safe since the "connect"
     method doesn't exist anymore */
  if (t == 0x0115)
    t = 0x0017;
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
  return (stun_class_t)(((t & 0x0100) >> 7) | ((t & 0x0010) >> 4));
}

/**
 * Checks if an attribute is present within a STUN message.
 *
 * @param msg valid STUN message
 * @param type STUN attribute type (host byte order)
 *
 * @return whether there is a MESSAGE-INTEGRITY attribute
 */
bool stun_message_has_attribute (const StunMessage *msg, stun_attr_type_t type)
{
  uint16_t dummy;
  return stun_message_find (msg, type, &dummy) != NULL;
649
}