1 // sg_socket.cxx -- Socket I/O routines
3 // Written by Curtis Olson, started November 1999.
4 // Modified by Bernie Bright <bbright@bigpond.net.au>, May 2002.
6 // Copyright (C) 1999 Curtis L. Olson - http://www.flightgear.org/~curt
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 // General Public License for more details.
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
25 # include <simgear_config.h>
28 #include <simgear/compiler.h>
32 #include <cstdlib> // for atoi
34 #include <simgear/debug/logstream.hxx>
36 #include "sg_socket.hxx"
38 bool SGSocket::init = false;
40 SGSocket::SGSocket( const string& host, const string& port_,
41 const string& style ) :
53 simgear::Socket::initSockets();
61 else if ( style != "udp" )
63 SG_LOG( SG_IO, SG_ALERT,
64 "Error: SGSocket() unknown style = " << style );
67 set_type( sgSocketType );
78 SGSocket::make_server_socket()
80 if (!sock.open( is_tcp ))
82 SG_LOG( SG_IO, SG_ALERT,
83 "Error: socket() failed in make_server_socket()" );
87 if (sock.bind( "", port ) < 0)
89 SG_LOG( SG_IO, SG_ALERT,
90 "Error: bind() failed in make_server_socket()" );
100 SGSocket::make_client_socket()
102 if (!sock.open( is_tcp ))
104 SG_LOG( SG_IO, SG_ALERT,
105 "Error: socket() failed in make_client_socket()" );
109 if (sock.connect( hostname.c_str(), port ) < 0)
111 SG_LOG( SG_IO, SG_ALERT,
112 "Error: connect() failed in make_client_socket()" );
120 // If specified as a server (in direction for now) open the master
121 // listening socket. If specified as a client (out direction), open a
122 // connection to a server.
124 SGSocket::open( SGProtocolDir direction )
126 set_dir( direction );
128 is_server = is_tcp &&
129 (direction == SG_IO_IN || direction == SG_IO_BI);
131 if ( port_str == "" || port_str == "any" ) {
134 port = atoi( port_str.c_str() );
137 if (direction == SG_IO_IN)
139 // this means server for now
141 // Setup socket to listen on. Set "port" before making this
142 // call. A port of "0" indicates that we want to let the os
143 // pick any available port.
144 if (!make_server_socket())
146 SG_LOG( SG_IO, SG_ALERT, "SG_IO_IN socket creation failed" );
158 // Specify the maximum length of the connection queue
159 sock.listen( SG_MAX_SOCKET_QUEUE );
163 else if (direction == SG_IO_OUT)
165 // this means client for now
167 if (!make_client_socket())
169 SG_LOG( SG_IO, SG_ALERT, "SG_IO_OUT socket creation failed" );
179 else if (direction == SG_IO_BI && is_tcp)
181 // this means server for TCP sockets
183 // Setup socket to listen on. Set "port" before making this
184 // call. A port of "0" indicates that we want to let the os
185 // pick any available port.
186 if (!make_server_socket())
188 SG_LOG( SG_IO, SG_ALERT, "SG_IO_BI socket creation failed" );
192 // Specify the maximum length of the connection queue
193 sock.listen( SG_MAX_SOCKET_QUEUE );
197 SG_LOG( SG_IO, SG_ALERT,
198 "Error: bidirection mode not available for UDP sockets." );
208 // read data from socket (server)
209 // read a block of data of specified size
211 SGSocket::read( char *buf, int length )
213 if (sock.getHandle() == -1 &&
214 (client == 0 || client->getHandle() == -1))
219 // test for any input available on sock (returning immediately, even if
225 if (is_tcp && is_server)
227 result = client->recv( buf, length );
231 result = sock.recv( buf, length );
234 if ( result != length )
236 SG_LOG( SG_IO, SG_INFO,
237 "Warning: read() not enough bytes." );
245 // read a line of data, length is max size of input buffer
247 SGSocket::readline( char *buf, int length )
249 if (sock.getHandle() == -1 &&
250 (client == 0 || client->getHandle() == -1))
255 // test for any input read on sock (returning immediately, even if
257 int result = this->poll();
261 // read a chunk, keep in the save buffer until we have the
262 // requested amount read
264 if (is_tcp && is_server)
266 char *buf_ptr = save_buf + save_len;
267 result = client->recv( buf_ptr, SG_IO_MAX_MSG_SIZE - save_len );
276 // Try and detect that the remote end died. This
277 // could cause problems so if you see connections
278 // dropping for unexplained reasons, LOOK HERE!
279 if (result == 0 && save_len == 0 && first_read == true)
281 SG_LOG( SG_IO, SG_ALERT,
282 "Connection closed by foreign host." );
289 char *buf_ptr = save_buf + save_len;
290 result = sock.recv( buf_ptr, SG_IO_MAX_MSG_SIZE - save_len );
295 // look for the end of line in save_buf
297 for ( i = 0; i < save_len && save_buf[i] != '\n'; ++i )
299 if (( i < save_len ) && ( save_buf[i] == '\n' )) {
302 // no end of line yet
306 // we found an end of line
309 int copy_length = result;
310 if (copy_length >= length) {
311 SG_LOG( SG_IO, SG_ALERT,
312 "Alert: readline() has line exceeding the buffer size." );
313 copy_length = length-1;
315 // copy to external buffer
316 strncpy( buf, save_buf, copy_length );
317 buf[copy_length] = '\0';
320 //memmove( save_buf+, save_buf+, ? );
321 for ( i = result; i < save_len; ++i ) {
322 save_buf[ i - result ] = save_buf[i];
330 // write data to socket (client)
332 SGSocket::write( const char *buf, const int length )
334 simgear::Socket* s = client == 0 ? &sock : client;
335 if (s->getHandle() == -1)
340 bool error_condition = false;
342 if ( s->send( buf, length ) < 0 )
344 SG_LOG( SG_IO, SG_WARN, "Error writing to socket: " << port );
345 error_condition = true;
348 if ( error_condition ) {
356 // write null terminated string to socket (server)
358 SGSocket::writestring( const char *str )
360 int length = strlen( str );
361 return this->write( str, length );
377 // configure the socket as non-blocking
381 if (sock.getHandle() == -1) {
385 sock.setBlocking( false );
392 simgear::Socket* readers[2];
394 readers[0] = client != 0 ? client : &sock;
397 simgear::Socket* writers[1];
400 int result = simgear::Socket::select( readers, writers, timeout );
402 if (result > 0 && is_server && client == 0)
404 // Accept a new client connection
405 simgear::IPAddress addr;
406 int new_fd = sock.accept( &addr );
407 SG_LOG( SG_IO, SG_INFO, "Accepted connection from "
408 << addr.getHost() << ":" << addr.getPort() );
409 client = new simgear::Socket();
410 client->setHandle( new_fd );