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 SGSocket::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 SGSocket::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 SGSocket::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 ) {
224 } else if ( dir == SG_IO_BI && sock_style == SOCK_STREAM ) {
225 // this means server for TCP sockets
227 // Setup socket to listen on. Set "port" before making this
228 // call. A port of "0" indicates that we want to let the os
229 // pick any available port.
230 sock = make_server_socket();
231 // TODO: check for error.
233 FG_LOG( FG_IO, FG_INFO, "socket is connected to port = " << port );
236 // Specify the maximum length of the connection queue
237 listen( sock, SG_MAX_SOCKET_QUEUE );
239 FG_LOG( FG_IO, FG_ALERT,
240 "Error: bidirection mode not available for UDP sockets." );
245 FG_LOG( FG_IO, FG_ALERT, "Error opening socket: " << hostname
254 // read data from socket (server)
255 // read a block of data of specified size
256 int SGSocket::read( char *buf, int length ) {
259 // check for potential input
262 FD_SET(sock, &ready);
267 // test for any input available on sock (returning immediately, even if
269 select(32, &ready, 0, 0, &tv);
271 if ( FD_ISSET(sock, &ready) ) {
272 result = readsocket( sock, buf, length );
273 if ( result != length ) {
274 FG_LOG( FG_IO, FG_INFO,
275 "Warning: read() not enough bytes." );
283 // read a line of data, length is max size of input buffer
284 int SGSocket::readline( char *buf, int length ) {
287 // check for potential input
290 FD_SET(sock, &ready);
295 // test for any input read on sock (returning immediately, even if
297 int rc = select(32, &ready, 0, 0, &tv);
298 // FG_LOG( FG_IO, FG_DEBUG, "select returned " << rc );
300 if ( FD_ISSET(sock, &ready) ) {
301 // read a chunk, keep in the save buffer until we have the
302 // requested amount read
304 char *buf_ptr = save_buf + save_len;
305 result = readsocket( sock, buf_ptr, SG_IO_MAX_MSG_SIZE - save_len );
307 // cout << "current read = " << buf_ptr << endl;
308 // cout << "current save_buf = " << save_buf << endl;
309 // cout << "save_len = " << save_len << endl;
312 // look for the end of line in save_buf
314 for ( i = 0; i < save_len && save_buf[i] != '\n'; ++i );
315 if ( save_buf[i] == '\n' ) {
318 // no end of line yet
319 // cout << "no eol found" << endl;
322 // cout << "line length = " << result << endl;
324 // we found an end of line
326 // copy to external buffer
327 strncpy( buf, save_buf, result );
329 // cout << "sg_socket line = " << buf << endl;
332 for ( i = result; i < save_len; ++i ) {
333 save_buf[ i - result ] = save_buf[i];
341 // write data to socket (client)
342 int SGSocket::write( char *buf, int length ) {
343 bool error_condition = false;
345 if ( writesocket(sock, buf, length) < 0 ) {
346 FG_LOG( FG_IO, FG_ALERT, "Error writing to socket: " << port );
347 error_condition = true;
351 // check for any new client connection requests
354 FD_SET(sock, &ready);
359 // test for any input on sock (returning immediately, even if
361 select(32, &ready, 0, 0, &tv);
363 // any new connections?
364 if ( FD_ISSET(sock, &ready) ) {
365 int msgsock = accept(sock, 0, 0);
367 FG_LOG( FG_IO, FG_ALERT,
368 "Error: accept() failed in write()" );
371 client_connections.push_back( msgsock );
375 FG_LOG( FG_IO, FG_INFO, "Client connections = " <<
376 client_connections.size() );
377 for ( int i = 0; i < (int)client_connections.size(); ++i ) {
378 int msgsock = client_connections[i];
380 // read and junk any possible incoming messages.
381 // char junk[ SG_IO_MAX_MSG_SIZE ];
382 // std::read( msgsock, junk, SG_IO_MAX_MSG_SIZE );
384 // write the interesting data to the socket
385 if ( writesocket(msgsock, buf, length) == SOCKET_ERROR ) {
386 FG_LOG( FG_IO, FG_ALERT, "Error writing to socket: " << port );
387 error_condition = true;
389 #ifdef _POSIX_SYNCHRONIZED_IO
390 // fdatasync(msgsock);
398 if ( error_condition ) {
406 // write null terminated string to socket (server)
407 int SGSocket::writestring( char *str ) {
408 int length = strlen( str );
409 return write( str, length );
414 bool SGSocket::close() {
416 for ( int i = 0; i < (int)client_connections.size(); ++i ) {
417 int msgsock = client_connections[i];
418 closesocket( msgsock );
427 // configure the socket as non-blocking
428 bool SGSocket::nonblock() {
429 #if defined(_MSC_VER)
431 if (ioctlsocket( sock, FIONBIO, &arg ) != 0) {
432 int error_code = WSAGetLastError();
433 FG_LOG( FG_IO, FG_ALERT,
434 "Error " << error_code << ": unable to set non-blocking mode"
439 fcntl( sock, F_SETFL, O_NONBLOCK );
444 #if defined(_MSC_VER)
446 bool SGSocket::wsock_init = false;
449 SGSocket::wsastartup() {
450 WORD wVersionRequested;
453 //wVersionRequested = MAKEWORD( 2, 2 );
454 wVersionRequested = MAKEWORD( 1, 1 );
455 int err = WSAStartup( wVersionRequested, &wsaData );
458 FG_LOG( FG_IO, FG_ALERT, "Error: Couldn't load winsock" );
463 if ( LOBYTE( wsaData.wVersion ) != 2 ||
464 HIBYTE( wsaData.wVersion ) != 2 ) {
465 FG_LOG( FG_IO, FG_ALERT, "Couldn't load a suitable winsock");