1 // sg_socket.cxx -- Socket I/O routines
3 // Written by Curtis Olson, started November 1999.
5 // Copyright (C) 1999 Curtis L. Olson - curt@flightgear.org
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 #include <simgear/compiler.h>
26 #if !defined(_MSC_VER)
27 # include <sys/time.h> // select()
28 # include <sys/types.h> // socket(), bind(), select(), accept()
29 # include <sys/socket.h> // socket(), bind(), listen(), accept()
30 # include <netinet/in.h> // struct sockaddr_in
31 # include <netdb.h> // gethostbyname()
32 # include <unistd.h> // select(), fsync()/fdatasync(), fcntl()
33 # include <fcntl.h> // fcntl()
40 #include <simgear/debug/logstream.hxx>
42 #include "sg_socket.hxx"
45 SGSocket::SGSocket( const string& host, const string& port,
46 const string& style ) :
52 if (!wsock_init && !wsastartup()) {
53 FG_LOG( FG_IO, FG_ALERT, "Winsock not available");
57 if ( style == "udp" ) {
58 sock_style = SOCK_DGRAM;
59 } else if ( style == "tcp" ) {
60 sock_style = SOCK_STREAM;
62 sock_style = SOCK_DGRAM;
63 FG_LOG( FG_IO, FG_ALERT,
64 "Error: SGSocket() unknown style = " << style );
67 set_type( sgSocketType );
71 SGSocket::~SGSocket() {
75 SGSocket::SocketType SGSocket::make_server_socket () {
76 struct sockaddr_in name;
78 #if defined( __CYGWIN__ ) || defined( __CYGWIN32__ ) || defined( sgi ) || defined( _MSC_VER )
85 sock = socket (PF_INET, sock_style, 0);
86 if (sock == INVALID_SOCKET) {
87 FG_LOG( FG_IO, FG_ALERT,
88 "Error: socket() failed in make_server_socket()" );
89 return INVALID_SOCKET;
92 // Give the socket a name.
93 name.sin_family = AF_INET;
94 name.sin_addr.s_addr = INADDR_ANY;
95 name.sin_port = htons(port); // set port to zero to let system pick
96 name.sin_addr.s_addr = htonl (INADDR_ANY);
97 if (bind (sock, (struct sockaddr *) &name, sizeof (name)) != 0) {
98 FG_LOG( FG_IO, FG_ALERT,
99 "Error: bind() failed in make_server_socket()" );
100 return INVALID_SOCKET;
103 // Find the assigned port number
104 length = sizeof(struct sockaddr_in);
105 if ( getsockname(sock, (struct sockaddr *) &name, &length) ) {
106 FG_LOG( FG_IO, FG_ALERT,
107 "Error: getsockname() failed in make_server_socket()" );
108 return INVALID_SOCKET;
110 port = ntohs(name.sin_port);
116 SGSocket::SocketType SGSocket::make_client_socket () {
117 struct sockaddr_in name;
120 FG_LOG( FG_IO, FG_INFO, "Make client socket()" );
122 // Create the socket.
123 sock = socket (PF_INET, sock_style, 0);
124 if (sock == INVALID_SOCKET) {
125 FG_LOG( FG_IO, FG_ALERT,
126 "Error: socket() failed in make_server_socket()" );
127 return INVALID_SOCKET;
130 // specify address family
131 name.sin_family = AF_INET;
133 // get the hosts official name/info
134 hp = gethostbyname( hostname.c_str() );
136 // Connect this socket to the host and the port specified on the
138 #if defined( __CYGWIN__ ) || defined( __CYGWIN32__ )
139 bcopy(hp->h_addr, (char *)(&(name.sin_addr.s_addr)), hp->h_length);
141 bcopy(hp->h_addr, &(name.sin_addr.s_addr), hp->h_length);
143 name.sin_port = htons(port);
145 if ( connect(sock, (struct sockaddr *) &name,
146 sizeof(struct sockaddr_in)) != 0 )
149 FG_LOG( FG_IO, FG_ALERT,
150 "Error: connect() failed in make_client_socket()" );
151 return INVALID_SOCKET;
159 size_t readsocket( int fd, void *buf, size_t count ) {
160 #if defined(_MSC_VER)
161 return ::recv( fd, buf, count, 0 );
163 return ::read( fd, buf, count );
167 size_t writesocket( int fd, const void *buf, size_t count ) {
168 #if defined(_MSC_VER)
169 return ::send( fd, buf, count, 0 );
171 return ::write( fd, buf, count );
175 #if !defined(_MSC_VER)
176 int closesocket( int fd ) {
177 return ::close( fd );
182 // If specified as a server (in direction for now) open the master
183 // listening socket. If specified as a client (out direction), open a
184 // connection to a server.
185 bool SGSocket::open( SGProtocolDir dir ) {
186 if ( port_str == "" || port_str == "any" ) {
189 port = atoi( port_str.c_str() );
192 // client_connections.clear();
194 if ( dir == SG_IO_IN ) {
195 // this means server for now
197 // Setup socket to listen on. Set "port" before making this
198 // call. A port of "0" indicates that we want to let the os
199 // pick any available port.
200 sock = make_server_socket();
201 // TODO: check for error.
203 FG_LOG( FG_IO, FG_INFO, "socket is connected to port = " << port );
205 if ( sock_style == SOCK_DGRAM ) {
210 // Specify the maximum length of the connection queue
211 listen( sock, SG_MAX_SOCKET_QUEUE );
214 } else if ( dir == SG_IO_OUT ) {
215 // this means client for now
217 sock = make_client_socket();
218 // TODO: check for error.
220 if ( sock_style == SOCK_DGRAM ) {
225 FG_LOG( FG_IO, FG_ALERT,
226 "Error: bidirection mode not available yet for sockets." );
231 FG_LOG( FG_IO, FG_ALERT, "Error opening socket: " << hostname
240 // read data from socket (server)
241 // read a block of data of specified size
242 int SGSocket::read( char *buf, int length ) {
245 // check for potential input
248 FD_SET(sock, &ready);
253 // test for any input available on sock (returning immediately, even if
255 select(32, &ready, 0, 0, &tv);
257 if ( FD_ISSET(sock, &ready) ) {
258 result = readsocket( sock, buf, length );
259 if ( result != length ) {
260 FG_LOG( FG_IO, FG_INFO,
261 "Warning: read() not enough bytes." );
269 // read a line of data, length is max size of input buffer
270 int SGSocket::readline( char *buf, int length ) {
273 // check for potential input
276 FD_SET(sock, &ready);
281 // test for any input read on sock (returning immediately, even if
283 int rc = select(32, &ready, 0, 0, &tv);
284 // FG_LOG( FG_IO, FG_DEBUG, "select returned " << rc );
286 if ( FD_ISSET(sock, &ready) ) {
287 // read a chunk, keep in the save buffer until we have the
288 // requested amount read
290 char *buf_ptr = save_buf + save_len;
291 result = readsocket( sock, buf_ptr, SG_IO_MAX_MSG_SIZE - save_len );
293 // cout << "current read = " << buf_ptr << endl;
294 // cout << "current save_buf = " << save_buf << endl;
295 // cout << "save_len = " << save_len << endl;
298 // look for the end of line in save_buf
300 for ( i = 0; i < save_len && save_buf[i] != '\n'; ++i );
301 if ( save_buf[i] == '\n' ) {
304 // no end of line yet
305 // cout << "no eol found" << endl;
308 // cout << "line length = " << result << endl;
310 // we found an end of line
312 // copy to external buffer
313 strncpy( buf, save_buf, result );
315 // cout << "sg_socket line = " << buf << endl;
318 for ( i = result; i < save_len; ++i ) {
319 save_buf[ i - result ] = save_buf[i];
327 // write data to socket (client)
328 int SGSocket::write( char *buf, int length ) {
329 bool error_condition = false;
331 if ( writesocket(sock, buf, length) < 0 ) {
332 FG_LOG( FG_IO, FG_ALERT, "Error writing to socket: " << port );
333 error_condition = true;
337 // check for any new client connection requests
340 FD_SET(sock, &ready);
345 // test for any input on sock (returning immediately, even if
347 select(32, &ready, 0, 0, &tv);
349 // any new connections?
350 if ( FD_ISSET(sock, &ready) ) {
351 int msgsock = accept(sock, 0, 0);
353 FG_LOG( FG_IO, FG_ALERT,
354 "Error: accept() failed in write()" );
357 client_connections.push_back( msgsock );
361 FG_LOG( FG_IO, FG_INFO, "Client connections = " <<
362 client_connections.size() );
363 for ( int i = 0; i < (int)client_connections.size(); ++i ) {
364 int msgsock = client_connections[i];
366 // read and junk any possible incoming messages.
367 // char junk[ SG_IO_MAX_MSG_SIZE ];
368 // std::read( msgsock, junk, SG_IO_MAX_MSG_SIZE );
370 // write the interesting data to the socket
371 if ( writesocket(msgsock, buf, length) == SOCKET_ERROR ) {
372 FG_LOG( FG_IO, FG_ALERT, "Error writing to socket: " << port );
373 error_condition = true;
375 #ifdef _POSIX_SYNCHRONIZED_IO
376 // fdatasync(msgsock);
384 if ( error_condition ) {
392 // write null terminated string to socket (server)
393 int SGSocket::writestring( char *str ) {
394 int length = strlen( str );
395 return write( str, length );
400 bool SGSocket::close() {
402 for ( int i = 0; i < (int)client_connections.size(); ++i ) {
403 int msgsock = client_connections[i];
404 closesocket( msgsock );
413 // configure the socket as non-blocking
414 bool SGSocket::nonblock() {
415 #if defined(_MSC_VER)
417 if (ioctlsocket( sock, FIONBIO, &arg ) != 0) {
418 int error_code = WSAGetLastError();
419 FG_LOG( FG_IO, FG_ALERT,
420 "Error " << error_code << ": unable to set non-blocking mode"
425 fcntl( sock, F_SETFL, O_NONBLOCK );
430 #if defined(_MSC_VER)
432 bool SGSocket::wsock_init = false;
435 SGSocket::wsastartup() {
436 WORD wVersionRequested;
439 //wVersionRequested = MAKEWORD( 2, 2 );
440 wVersionRequested = MAKEWORD( 1, 1 );
441 int err = WSAStartup( wVersionRequested, &wsaData );
444 FG_LOG( FG_IO, FG_ALERT, "Error: Couldn't load winsock" );
449 if ( LOBYTE( wsaData.wVersion ) != 2 ||
450 HIBYTE( wsaData.wVersion ) != 2 ) {
451 FG_LOG( FG_IO, FG_ALERT, "Couldn't load a suitable winsock");