1 // fg_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()
34 # include <sys/timeb.h> // select()
35 # include <winsock2.h> // socket(), bind(), listen(), accept(),
36 // struct sockaddr_in, gethostbyname()
47 #include <simgear/debug/logstream.hxx>
49 #include "fg_socket.hxx"
54 FGSocket::FGSocket() :
60 FGSocket::~FGSocket() {
64 int FGSocket::make_server_socket () {
65 struct sockaddr_in name;
67 #if defined( __CYGWIN__ ) || defined( __CYGWIN32__ ) || defined( sgi ) || defined( _MSC_VER )
74 sock = socket (PF_INET, SOCK_STREAM, 0);
76 FG_LOG( FG_IO, FG_ALERT,
77 "Error: socket() failed in make_server_socket()" );
81 // Give the socket a name.
82 name.sin_family = AF_INET;
83 name.sin_addr.s_addr = INADDR_ANY;
84 name.sin_port = htons(port); // set port to zero to let system pick
85 name.sin_addr.s_addr = htonl (INADDR_ANY);
86 if (bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0) {
87 FG_LOG( FG_IO, FG_ALERT,
88 "Error: bind() failed in make_server_socket()" );
92 // Find the assigned port number
93 length = sizeof(struct sockaddr_in);
94 if ( getsockname(sock, (struct sockaddr *) &name, &length) ) {
95 FG_LOG( FG_IO, FG_ALERT,
96 "Error: getsockname() failed in make_server_socket()" );
99 port = ntohs(name.sin_port);
105 int FGSocket::make_client_socket () {
106 struct sockaddr_in name;
109 FG_LOG( FG_IO, FG_INFO, "Make client socket()" );
111 // Create the socket.
112 sock = socket (PF_INET, SOCK_STREAM, 0);
114 FG_LOG( FG_IO, FG_ALERT,
115 "Error: socket() failed in make_client_socket()" );
119 // specify address family
120 name.sin_family = AF_INET;
122 // get the hosts official name/info
123 hp = gethostbyname( hostname.c_str() );
125 // Connect this socket to the host and the port specified on the
127 #if defined( __CYGWIN__ ) || defined( __CYGWIN32__ )
128 bcopy(hp->h_addr, (char *)(&(name.sin_addr.s_addr)), hp->h_length);
130 bcopy(hp->h_addr, &(name.sin_addr.s_addr), hp->h_length);
132 name.sin_port = htons(port);
134 if ( connect(sock, (struct sockaddr *) &name,
135 sizeof(struct sockaddr_in)) < 0 )
138 FG_LOG( FG_IO, FG_ALERT,
139 "Error: connect() failed in make_client_socket()" );
147 // If specified as a server (out direction for now) open the master
148 // listening socket. If specified as a client, open a connection to a
151 bool FGSocket::open( FGProtocol::fgProtocolDir dir ) {
152 if ( port_str == "" || port_str == "any" ) {
155 port = atoi( port_str.c_str() );
158 client_connections.clear();
160 if ( dir == FGProtocol::out ) {
161 // this means server for now
163 // Setup socket to listen on. Set "port" before making this
164 // call. A port of "0" indicates that we want to let the os
165 // pick any available port.
166 sock = make_server_socket();
167 FG_LOG( FG_IO, FG_INFO, "socket is connected to port = " << port );
169 // Specify the maximum length of the connection queue
170 listen(sock, FG_MAX_SOCKET_QUEUE);
172 } else if ( dir == FGProtocol::in ) {
173 // this means client for now
175 sock = make_client_socket();
177 FG_LOG( FG_IO, FG_ALERT,
178 "Error: bidirection mode not available yet for sockets." );
183 FG_LOG( FG_IO, FG_ALERT, "Error opening socket: " << hostname
192 // read data from socket (client)
193 // read a block of data of specified size
194 int FGSocket::read( char *buf, int length ) {
197 // check for potential input
200 FD_SET(sock, &ready);
205 // test for any input read on sock (returning immediately, even if
207 select(32, &ready, 0, 0, &tv);
209 if ( FD_ISSET(sock, &ready) ) {
210 result = std::read( sock, buf, length );
211 if ( result != length ) {
212 FG_LOG( FG_IO, FG_INFO,
213 "Warning: read() not enough bytes." );
221 // read a line of data, length is max size of input buffer
222 int FGSocket::readline( char *buf, int length ) {
225 // check for potential input
228 FD_SET(sock, &ready);
233 // test for any input read on sock (returning immediately, even if
235 select(32, &ready, 0, 0, &tv);
237 if ( FD_ISSET(sock, &ready) ) {
238 // read a chunk, keep in the save buffer until we have the
239 // requested amount read
241 char *buf_ptr = save_buf + save_len;
242 result = std::read( sock, buf_ptr, FG_MAX_MSG_SIZE - save_len );
244 // cout << "current read = " << buf_ptr << endl;
245 // cout << "current save_buf = " << save_buf << endl;
246 // cout << "save_len = " << save_len << endl;
249 // look for the end of line in save_buf
251 for ( i = 0; i < save_len && save_buf[i] != '\n'; ++i );
252 if ( save_buf[i] == '\n' ) {
255 // no end of line yet
256 // cout << "no eol found" << endl;
259 // cout << "line length = " << result << endl;
261 // we found an end of line
263 // copy to external buffer
264 strncpy( buf, save_buf, result );
266 // cout << "fg_socket line = " << buf << endl;
269 for ( i = result; i < save_len; ++i ) {
270 save_buf[ i - result ] = save_buf[i];
278 // write data to socket (server)
279 int FGSocket::write( char *buf, int length ) {
281 // check for any new client connection requests
284 FD_SET(sock, &ready);
289 // test for any input on sock (returning immediately, even if
291 select(32, &ready, 0, 0, &tv);
293 // any new connections?
294 if ( FD_ISSET(sock, &ready) ) {
295 int msgsock = accept(sock, 0, 0);
297 FG_LOG( FG_IO, FG_ALERT,
298 "Error: accept() failed in write()" );
301 client_connections.push_back( msgsock );
305 bool error_condition = false;
306 FG_LOG( FG_IO, FG_INFO, "Client connections = " <<
307 client_connections.size() );
308 for ( int i = 0; i < (int)client_connections.size(); ++i ) {
309 int msgsock = client_connections[i];
311 // read and junk any possible incoming messages.
312 // char junk[ FG_MAX_MSG_SIZE ];
313 // std::read( msgsock, junk, FG_MAX_MSG_SIZE );
315 // write the interesting data to the socket
316 if ( std::write(msgsock, buf, length) < 0 ) {
317 FG_LOG( FG_IO, FG_ALERT, "Error writing to socket: " << port );
318 error_condition = true;
320 #ifdef _POSIX_SYNCHRONIZED_IO
321 // fdatasync(msgsock);
328 if ( error_condition ) {
336 // write null terminated string to socket (server)
337 int FGSocket::writestring( char *str ) {
338 int length = strlen( str );
339 return write( str, length );
344 bool FGSocket::close() {
345 for ( int i = 0; i < (int)client_connections.size(); ++i ) {
346 int msgsock = client_connections[i];
347 std::close( msgsock );