2 simgear::Socket, adapted from PLIB Socket by James Turner
3 Copyright (C) 2010 James Turner
5 PLIB - A Suite of Portable Game Libraries
6 Copyright (C) 1998,2002 Steve Baker
8 This library is free software; you can redistribute it and/or
9 modify it under the terms of the GNU Library General Public
10 License as published by the Free Software Foundation; either
11 version 2 of the License, or (at your option) any later version.
13 This library is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Library General Public License for more details.
18 You should have received a copy of the GNU Library General Public
19 License along with this library; if not, write to the Free Software
20 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 # include <simgear_config.h>
27 #include <simgear/compiler.h>
28 #include "raw_socket.hxx"
30 #if defined(_WIN32) && !defined(__CYGWIN__)
31 # define WINSOCK // use winsock convetions, otherwise standard POSIX
38 #include <cstdio> // for snprintf
42 # include <winsock2.h>
43 # include <ws2tcpip.h>
46 # include <sys/types.h>
47 # include <sys/socket.h>
48 # include <netinet/in.h>
49 # include <arpa/inet.h>
50 # include <sys/time.h>
56 #if defined(_MSC_VER) && !defined(socklen_t)
62 #include <simgear/debug/logstream.hxx>
63 #include <simgear/structure/exception.hxx>
64 #include <simgear/threads/SGThread.hxx>
70 class Resolver : public SGThread
73 static Resolver* instance()
75 if (!static_instance) {
76 static_instance = new Resolver;
77 atexit(&Resolver::cleanup);
78 static_instance->start();
81 return static_instance;
86 static_instance->cancel();
91 // take the lock initially, thread will wait upon it once running
95 simgear::IPAddress* lookup(const string& host)
97 simgear::IPAddress* result = NULL;
99 AddressCache::iterator it = _cache.find(host);
100 if (it == _cache.end()) {
101 _cache[host] = NULL; // mark as needing looked up
102 _wait.signal(); // if the thread was sleeping, poke it
110 simgear::IPAddress* lookupSync(const string& host)
112 simgear::IPAddress* result = NULL;
114 AddressCache::iterator it = _cache.find(host);
115 if (it == _cache.end()) {
117 result = new simgear::IPAddress;
118 bool ok = lookupHost(host.c_str(), *result);
121 _cache[host] = result; // mark as needing looked up
126 } else { // found in cache, easy
134 * run method waits on a condition (_wait), and when awoken,
135 * finds any unresolved entries in _cache, resolves them, and goes
142 AddressCache::iterator it;
144 for (it = _cache.begin(); it != _cache.end(); ++it) {
145 if (it->second == NULL) {
146 string h = it->first;
149 simgear::IPAddress* addr = new simgear::IPAddress;
150 // may take seconds or even minutes!
151 lookupHost(h.c_str(), *addr);
154 // cahce may have changed while we had the lock released -
155 // so iterators may be invalid: restart the traversal
158 } // of found un-resolved entry
159 } // of un-resolved address iteration
160 } // of thread run loop
163 static Resolver* static_instance;
166 * The actual synchronous, blocking host lookup function
167 * do *not* call this with any locks (mutexs) held, since depending
168 * on local system configuration / network availability, it
169 * may block for seconds or minutes.
171 bool lookupHost(const char* host, simgear::IPAddress& addr)
173 struct addrinfo hints;
174 memset(&hints, 0, sizeof(struct addrinfo));
175 hints.ai_family = AF_INET;
178 struct addrinfo* result0 = NULL;
179 int err = getaddrinfo(host, NULL, &hints, &result0);
181 SG_LOG(SG_IO, SG_WARN, "getaddrinfo failed for '" << host << "' : " << gai_strerror(err));
184 struct addrinfo* result;
185 for (result = result0; result != NULL; result = result->ai_next) {
186 if (result->ai_family != AF_INET) { // only accept IP4 for the moment
190 if (result->ai_addrlen != addr.getAddrLen()) {
191 SG_LOG(SG_IO, SG_ALERT, "mismatch in socket address sizes: got " <<
192 result->ai_addrlen << ", expected " << addr.getAddrLen());
196 memcpy(addr.getAddr(), result->ai_addr, result->ai_addrlen);
199 } // of getaddrinfo results iteration
200 } // of getaddrinfo succeeded
202 freeaddrinfo(result0);
208 typedef std::map<string, simgear::IPAddress*> AddressCache;
212 Resolver* Resolver::static_instance = NULL;
214 } // of anonymous namespace
219 IPAddress::IPAddress ( const char* host, int port )
224 IPAddress::IPAddress( const IPAddress& other ) :
228 addr = (struct sockaddr_in*) malloc(sizeof(struct sockaddr_in));
229 memcpy(addr, other.addr, sizeof(struct sockaddr_in));
233 const IPAddress& IPAddress::operator=(const IPAddress& other)
241 addr = (struct sockaddr_in*) malloc(sizeof(struct sockaddr_in));
242 memcpy(addr, other.addr, sizeof(struct sockaddr_in));
248 void IPAddress::set ( const char* host, int port )
250 addr = (struct sockaddr_in*) malloc(sizeof(struct sockaddr_in));
251 memset(addr, 0, sizeof(struct sockaddr_in));
253 addr->sin_family = AF_INET ;
254 addr->sin_port = htons (port);
256 /* Convert a string specifying a host name or one of a few symbolic
257 ** names to a numeric IP address. This usually calls getaddrinfo()
258 ** to do the work; the names "" and "<broadcast>" are special.
261 if (!host || host[0] == '\0') {
262 addr->sin_addr.s_addr = INADDR_ANY;
266 if (strcmp(host, "<broadcast>") == 0) {
267 addr->sin_addr.s_addr = INADDR_BROADCAST;
272 IPAddress* cached = Resolver::instance()->lookupSync(host);
274 memcpy(addr, cached->getAddr(), cached->getAddrLen());
277 addr->sin_port = htons (port); // fix up port after getaddrinfo
280 IPAddress::~IPAddress()
287 bool IPAddress::lookupNonblocking(const char* host, IPAddress& addr)
289 IPAddress* cached = Resolver::instance()->lookup(host);
298 /* Create a string object representing an IP address.
299 This is always a string of the form 'dd.dd.dd.dd' (with variable
302 const char* IPAddress::getHost () const
304 static char buf [32];
305 long x = ntohl(addr->sin_addr.s_addr);
306 sprintf(buf, "%d.%d.%d.%d",
307 (int) (x>>24) & 0xff, (int) (x>>16) & 0xff,
308 (int) (x>> 8) & 0xff, (int) (x>> 0) & 0xff );
312 unsigned int IPAddress::getIP () const
314 return addr->sin_addr.s_addr;
317 unsigned int IPAddress::getPort() const
319 return ntohs(addr->sin_port);
322 void IPAddress::setPort(int port)
324 addr->sin_port = htons(port);
327 unsigned int IPAddress::getFamily () const
329 return addr->sin_family;
332 const char* IPAddress::getLocalHost ()
334 //gethostbyname(gethostname())
337 memset(buf, 0, sizeof(buf));
338 gethostname(buf, sizeof(buf)-1);
339 const hostent *hp = gethostbyname(buf);
341 if (hp && *hp->h_addr_list)
343 in_addr addr = *((in_addr*)*hp->h_addr_list);
344 const char* host = inet_ntoa(addr);
354 bool IPAddress::getBroadcast () const
356 return (addr->sin_addr.s_addr == INADDR_BROADCAST);
359 unsigned int IPAddress::getAddrLen() const
361 return sizeof(struct sockaddr_in);
364 struct sockaddr* IPAddress::getAddr() const
367 addr = (struct sockaddr_in*) malloc(sizeof(struct sockaddr_in));
368 memset(addr, 0, sizeof(struct sockaddr_in));
371 return (struct sockaddr*) addr;
386 void Socket::setHandle (int _handle)
393 bool Socket::open ( bool stream )
396 handle = ::socket ( AF_INET, (stream? SOCK_STREAM: SOCK_DGRAM), 0 ) ;
398 // Jan 26, 2010: Patch to avoid the problem of the socket resource not
399 // yet being available if the program is restarted quickly after being
402 // Reference: http://www.unixguide.net/network/socketfaq/4.5.shtml
404 // Also required for joining multicast domains
407 #if defined(_WIN32) || defined(__CYGWIN__)
408 setsockopt( handle, SOL_SOCKET, SO_REUSEADDR, (char *)&opt_boolean,
409 sizeof(opt_boolean) );
411 setsockopt( handle, SOL_SOCKET, SO_REUSEADDR, &opt_boolean,
412 sizeof(opt_boolean) );
416 return (handle != -1);
420 void Socket::setBlocking ( bool blocking )
422 assert ( handle != -1 ) ;
425 u_long nblocking = blocking? 0: 1;
426 ::ioctlsocket(handle, FIONBIO, &nblocking);
429 int delay_flag = ::fcntl (handle, F_GETFL, 0);
432 delay_flag &= (~O_NDELAY);
434 delay_flag |= O_NDELAY;
436 ::fcntl (handle, F_SETFL, delay_flag);
441 void Socket::setBroadcast ( bool broadcast )
443 assert ( handle != -1 ) ;
447 #if defined(_WIN32) || defined(__CYGWIN__)
448 result = ::setsockopt( handle, SOL_SOCKET, SO_BROADCAST, (char*)&one, sizeof(one) );
450 result = ::setsockopt( handle, SOL_SOCKET, SO_BROADCAST, &one, sizeof(one) );
453 result = ::setsockopt( handle, SOL_SOCKET, SO_BROADCAST, NULL, 0 );
457 throw sg_exception("Socket::setBroadcast failed");
462 int Socket::bind ( const char* host, int port )
465 assert ( handle != -1 ) ;
466 IPAddress addr ( host, port ) ;
468 #if !defined(WINSOCK)
469 if( (result = ::bind(handle, addr.getAddr(), addr.getAddrLen() ) ) < 0 ) {
470 SG_LOG(SG_IO, SG_ALERT, "bind(" << addr.getHost() << ":" << addr.getPort() << ") failed. Errno " << errno << " (" << strerror(errno) << ")");
475 // 224.0.0.0 - 239.255.255.255 are multicast
476 // Usage of 239.x.x.x is recommended for local scope
477 // Reference: http://tools.ietf.org/html/rfc5771
478 if( ntohl(addr.getIP()) >= 0xe0000000 && ntohl(addr.getIP()) <= 0xefffffff ) {
481 struct sockaddr_in a;
482 a.sin_addr.S_un.S_addr = INADDR_ANY;
483 a.sin_family = AF_INET;
484 a.sin_port = htons(port);
486 if( (result = ::bind(handle,(const sockaddr*)&a,sizeof(a))) < 0 ) {
487 SG_LOG(SG_IO, SG_ALERT, "bind(any:" << port << ") failed. Errno " << errno << " (" << strerror(errno) << ")");
493 mreq.imr_multiaddr.s_addr = addr.getIP();
494 mreq.imr_interface.s_addr = htonl(INADDR_ANY);
495 if( (result=::setsockopt(getHandle(), IPPROTO_IP, IP_ADD_MEMBERSHIP, (const char *)&mreq, sizeof(mreq))) != 0 ) {
496 SG_LOG(SG_IO, SG_ALERT, "setsockopt(IP_ADD_MEMBERSHIP) failed. Errno " << errno << " (" << strerror(errno) << ")");
501 else if( (result = ::bind(handle,addr.getAddr(), addr.getAddrLen())) < 0 ) {
502 SG_LOG(SG_IO, SG_ALERT, "bind(" << host << ":" << port << ") failed. Errno " << errno << " (" << strerror(errno) << ")");
511 int Socket::listen ( int backlog )
513 assert ( handle != -1 ) ;
514 return ::listen(handle,backlog);
518 int Socket::accept ( IPAddress* addr )
520 assert ( handle != -1 ) ;
524 return ::accept(handle,NULL,NULL);
528 socklen_t addr_len = addr->getAddrLen(); ;
529 return ::accept(handle, addr->getAddr(), &addr_len);
534 int Socket::connect ( const char* host, int port )
536 IPAddress addr ( host, port ) ;
537 return connect ( &addr );
541 int Socket::connect ( IPAddress* addr )
543 assert ( handle != -1 ) ;
544 if ( addr->getBroadcast() ) {
545 setBroadcast( true );
547 return ::connect(handle, addr->getAddr(), addr->getAddrLen() );
551 int Socket::send (const void * buffer, int size, int flags)
553 assert ( handle != -1 ) ;
554 return ::send (handle, (const char*)buffer, size, flags);
558 int Socket::sendto ( const void * buffer, int size,
559 int flags, const IPAddress* to )
561 assert ( handle != -1 ) ;
562 return ::sendto(handle,(const char*)buffer,size,flags,
563 (const sockaddr*) to->getAddr(), to->getAddrLen());
567 int Socket::recv (void * buffer, int size, int flags)
569 assert ( handle != -1 ) ;
570 return ::recv (handle, (char*)buffer, size, flags);
574 int Socket::recvfrom ( void * buffer, int size,
575 int flags, IPAddress* from )
577 assert ( handle != -1 ) ;
578 socklen_t fromlen = (socklen_t) from->getAddrLen() ;
579 return ::recvfrom(handle,(char*)buffer,size,flags, from->getAddr(),&fromlen);
583 void Socket::close (void)
588 ::closesocket( handle );
597 bool Socket::isNonBlockingError ()
600 int wsa_errno = WSAGetLastError();
601 if ( wsa_errno != 0 )
604 SG_LOG(SG_IO, SG_WARN, "isNonBlockingError: WSAGetLastError():" << wsa_errno);
606 case WSAEWOULDBLOCK: // always == NET_EAGAIN?
615 case EWOULDBLOCK: // always == NET_EAGAIN?
626 //////////////////////////////////////////////////////////////////////
628 // modified version by os
630 //////////////////////////////////////////////////////////////////////
631 int Socket::select ( Socket** reads, Socket** writes, int timeout )
644 for ( i=0; reads[i]; i++ )
646 int fd = reads[i]->getHandle();
654 for ( i=0; writes[i]; i++ )
656 int fd = writes[i]->getHandle();
665 /* Set up the timeout */
667 tv.tv_sec = timeout/1000;
668 tv.tv_usec = (timeout%1000)*1000;
670 // It bothers me that select()'s first argument does not appear to
671 // work as advertised... [it hangs like this if called with
672 // anything less than FD_SETSIZE, which seems wasteful?]
674 // Note: we ignore the 'exception' fd_set - I have never had a
675 // need to use it. The name is somewhat misleading - the only
676 // thing I have ever seen it used for is to detect urgent data -
677 // which is an unportable feature anyway.
679 retval = ::select (FD_SETSIZE, &r, &w, 0, &tv);
681 //remove sockets that had no activity
687 for ( k=i=0; reads[i]; i++ )
689 int fd = reads[i]->getHandle();
690 if ( FD_ISSET (fd, &r) )
692 reads[k++] = reads[i];
701 for ( k=i=0; writes[i]; i++ )
703 int fd = writes[i]->getHandle();
704 if ( FD_ISSET (fd, &w) )
706 writes[k++] = writes[i];
713 if (retval == 0) // timeout
715 if (retval == -1)// error
722 /* Init/Exit functions */
724 static void netExit ( void )
727 /* Clean up windows networking */
728 if ( WSACleanup() == SOCKET_ERROR ) {
729 if ( WSAGetLastError() == WSAEINPROGRESS ) {
730 WSACancelBlockingCall();
737 int Socket::initSockets()
740 /* Start up the windows networking */
741 WORD version_wanted = MAKEWORD(1,1);
744 if ( WSAStartup(version_wanted, &wsaData) != 0 ) {
745 throw sg_exception("WinSock initialization failed");
754 } // of namespace simgear