stun_udp.c 13.3 KB
Newer Older
jehan's avatar
jehan 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
 /*
  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/>.
 *
 */

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
73
#if !defined(_WIN32) && !defined(_WIN32_WCE)
jehan's avatar
jehan committed
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
#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
#include <assert.h>

#include <time.h>

90
#if defined(_WIN32) || defined(_WIN32_WCE)
jehan's avatar
jehan committed
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112

#include <winsock2.h>
#include <stdlib.h>
/* #include <io.h> */

#else

#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>

#endif

#include <string.h>

jehan's avatar
jehan committed
113
#include "mediastreamer2/stun_udp.h"
jehan's avatar
jehan committed
114 115
#include "ortp/ortp.h"

116
#if !defined(_WIN32) && !defined(_WIN32_WCE)
jehan's avatar
jehan committed
117 118 119 120 121 122 123 124 125 126 127 128 129 130 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 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
int getErrno() { return errno; }
#else
int getErrno() { return WSAGetLastError(); }
#endif

Socket
openPort( unsigned short port, unsigned int interfaceIp )
{
   struct sockaddr_in addr;
   Socket fd;
    
   fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
   if ( fd == INVALID_SOCKET )
   {
	  ortp_error("stun_udp: Could not create a UDP socket");
      return INVALID_SOCKET;
   }
   
   memset((char*) &(addr),0, sizeof((addr)));
   addr.sin_family = AF_INET;
   addr.sin_addr.s_addr = htonl(INADDR_ANY);
   addr.sin_port = htons(port);
    
   if ( (interfaceIp != 0) && 
        ( interfaceIp != 0x100007f ) )
   {
      addr.sin_addr.s_addr = htonl(interfaceIp);
      //ortp_debug("Binding to interface 0x%lu\n",(unsigned long) htonl(interfaceIp));
   }
	
   if ( bind( fd,(struct sockaddr*)&addr, sizeof(addr)) != 0 )
   {
      int e = getErrno();
        
      switch (e)
      {
         case 0:
         {
            ortp_error("stun_udp: Could not bind socket");;
            return INVALID_SOCKET;
         }
         case EADDRINUSE:
         {
            ortp_error("stun_udp: Port %i for receiving UDP is in use", port);
            return INVALID_SOCKET;
         }
         break;
         case EADDRNOTAVAIL:
         {
            ortp_error("stun_udp: Cannot assign requested address");
            return INVALID_SOCKET;
         }
         break;
         default:
         {
#if !defined(_WIN32_WCE)
			 ortp_error("stun_udp: Could not bind UDP receive port Error=%i %s",
                   e, strerror(e));
#else
			 ortp_error("stun_udp: Could not bind UDP receive port Error=%i",
                   e);
#endif
            return INVALID_SOCKET;
         }
         break;
      }
   }

	 ortp_debug("stun: opened port %i with fd %i\n", port, fd);
   
   /* assert( fd != INVALID_SOCKET  ); */
	
   return fd;
}


bool_t 
getMessage( Socket fd, char* buf, int* len,
            unsigned int* srcIp, unsigned short* srcPort)
{
   /* assert( fd != INVALID_SOCKET ); */
	
   int originalSize = *len;
   struct sockaddr_in from;
   int fromLen = sizeof(from);
   	

   int err;
   struct timeval tv;
   fd_set fdSet; 
207
#if defined(_WIN32) || defined(_WIN32_WCE)
jehan's avatar
jehan committed
208 209 210 211 212 213 214 215 216 217 218 219 220
   unsigned int fdSetSize;
#else
   int fdSetSize;
#endif

   if (originalSize <= 0)
   {
	   return FALSE;
   }

   tv.tv_sec=1;
   tv.tv_usec=0; /* 150 ms */
   FD_ZERO(&fdSet); fdSetSize=0;
221
   FD_SET(fd,&fdSet); fdSetSize = (unsigned int)fd+1;
jehan's avatar
jehan committed
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 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

   err = select(fdSetSize, &fdSet, NULL, NULL, &tv);
   if ( err == SOCKET_ERROR )
   {
      int e = getErrno();
      switch (e)
      {
         case ENOTSOCK:
            ortp_error("stun_udp: Error fd not a socket");
            break;
         case ECONNRESET:
            ortp_error("stun_udp: Error connection reset - host not reachable");
            break;
				
         default:
            ortp_error("stun_udp: Socket Error=%i", e);
      }
      return FALSE;
   }

    if (err==0)
    {
        ortp_error("stun_udp: Connection timeout with stun server!");
        *len = 0;
        return FALSE;
    }

    if (FD_ISSET (fd, &fdSet))
    {
        *len = recvfrom(fd,
                        buf,
                        originalSize,
                        0,
                        (struct sockaddr *)&from,
                        (socklen_t*)&fromLen);
        	
        if ( *len == SOCKET_ERROR )
        {
            int e = getErrno();
        		
            switch (e)
            {
                case ENOTSOCK:
                    ortp_error("stun_udp: Error fd not a socket");
                    break;
                case ECONNRESET:
                    ortp_error("stun_udp: Error connection reset - host not reachable");
                    break;
        				
                default:
                    ortp_error("stun_udp: Socket Error=%i", e);
            }
        		
            return FALSE;
        }
        	
        if ( *len < 0 )
        {
            ortp_error("stun_udp: socket closed? negative len");
            return FALSE;
        }
            
        if ( *len == 0 )
        {
            ortp_error("stun_udp: socket closed? zero len");
            return FALSE;
        }
            
        *srcPort = ntohs(from.sin_port);
        *srcIp = ntohl(from.sin_addr.s_addr);
        	
        if ( (*len)+1 >= originalSize )
        {
            ortp_error("stun_udp: Received a message that was too large");
            return FALSE;
        }
        buf[*len]=0;
            
        return TRUE;
    }
    return FALSE;
}


bool_t 
sendMessage( Socket fd, char* buf, int l, 
             unsigned int dstIp, unsigned short dstPort)
{
   int s;

   if (fd == INVALID_SOCKET)
	   return FALSE;

   if ( dstPort == 0 )
   {
      /* sending on a connected port */
      s = send(fd,buf,l,0);
   }
   else
   {
      struct sockaddr_in to;
      int toLen = sizeof(to);
      if (dstIp == 0)
	  {
		  ortp_error("stun_udp: invalid IP provided (dstIP==0)");
		  return FALSE;
	  }

      memset(&to,0,toLen);
        
      to.sin_family = AF_INET;
      to.sin_port = htons(dstPort);
      to.sin_addr.s_addr = htonl(dstIp);
        
      s = sendto(fd, buf, l, 0,(struct sockaddr*)&to, toLen);
   }
    
   if ( s == SOCKET_ERROR )
   {
      int e = getErrno();
      switch (e)
      {
         case ECONNREFUSED:
         case EHOSTDOWN:
         case EHOSTUNREACH:
         {
            /* quietly ignore this */
         }
         break;
         case EAFNOSUPPORT:
         {
            ortp_error("stun_udp: err EAFNOSUPPORT in send");
         }
         break;
         default:
         {
#if !defined(_WIN32_WCE)
            ortp_error("stun_udp: err %i %s in send", e, strerror(e));
#else
            ortp_error("stun_udp: err %i in send", e);
#endif
         }
      }
      return FALSE;
   }
    
   if ( s == 0 )
   {
      ortp_error("stun_udp: no data sent in send");
      return FALSE;
   }
    
   if ( s != l )
   {
      ortp_error("stun_udp: only %i out of %i bytes sent", s, l);
      return FALSE;
   }
    
   return TRUE;
}


void
initNetwork()
{
387
#if defined(_WIN32) || defined(_WIN32_WCE)
jehan's avatar
jehan committed
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
   WORD wVersionRequested = MAKEWORD( 2, 2 );
   WSADATA wsaData;
   int err;
	
   err = WSAStartup( wVersionRequested, &wsaData );
   if ( err != 0 ) 
   {
      /* could not find a usable WinSock DLL */
      ortp_error("stun_udp: Could not load winsock");
   }
    
   /* Confirm that the WinSock DLL supports 2.2.*/
   /* Note that if the DLL supports versions greater    */
   /* than 2.2 in addition to 2.2, it will still return */
   /* 2.2 in wVersion since that is the version we      */
   /* requested.                                        */
    
   if ( LOBYTE( wsaData.wVersion ) != 2 ||
        HIBYTE( wsaData.wVersion ) != 2 ) 
   {
      /* Tell the user that we could not find a usable */
      /* WinSock DLL.                                  */
      WSACleanup( );
      ortp_error("stun_udp: Wrong winsock (!= 2.2) version");
   }    
#endif
}


/* ====================================================================
 * 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/>.
 *
 */

/* Local Variables:
   mode:c
   c-file-style:"ellemtel"
   c-file-offsets:((case-label . +))
   indent-tabs-mode:nil
   End:
*/