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 SG_LOG( SG_IO, SG_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 SG_LOG( SG_IO, SG_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 SG_LOG( SG_IO, SG_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 SG_LOG( SG_IO, SG_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 SG_LOG( SG_IO, SG_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 SG_LOG( SG_IO, SG_INFO, "Make client socket()" );
122 // Create the socket.
123 sock = socket (PF_INET, sock_style, 0);
124 if (sock == INVALID_SOCKET) {
125 SG_LOG( SG_IO, SG_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 SG_LOG( SG_IO, SG_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, (char *)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, (const char*)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( const SGProtocolDir d ) {
188 if ( port_str == "" || port_str == "any" ) {
191 port = atoi( port_str.c_str() );
194 // client_connections.clear();
196 if ( get_dir() == SG_IO_IN ) {
197 // this means server for now
199 // Setup socket to listen on. Set "port" before making this
200 // call. A port of "0" indicates that we want to let the os
201 // pick any available port.
202 sock = make_server_socket();
203 if ( sock == INVALID_SOCKET ) {
204 SG_LOG( SG_IO, SG_ALERT, "socket creation failed" );
208 SG_LOG( SG_IO, SG_INFO, "socket is connected to port = " << port );
210 if ( sock_style == SOCK_DGRAM ) {
215 // Specify the maximum length of the connection queue
216 listen( sock, SG_MAX_SOCKET_QUEUE );
219 } else if ( get_dir() == SG_IO_OUT ) {
220 // this means client for now
222 sock = make_client_socket();
223 // TODO: check for error.
225 if ( sock_style == SOCK_DGRAM ) {
229 } else if ( get_dir() == SG_IO_BI && sock_style == SOCK_STREAM ) {
230 // this means server for TCP sockets
232 // Setup socket to listen on. Set "port" before making this
233 // call. A port of "0" indicates that we want to let the os
234 // pick any available port.
235 sock = make_server_socket();
236 // TODO: check for error.
238 SG_LOG( SG_IO, SG_INFO, "socket is connected to port = " << port );
241 // Specify the maximum length of the connection queue
242 listen( sock, SG_MAX_SOCKET_QUEUE );
244 SG_LOG( SG_IO, SG_ALERT,
245 "Error: bidirection mode not available for UDP sockets." );
250 SG_LOG( SG_IO, SG_ALERT, "Error opening socket: " << hostname
255 // extra SOCK_STREAM stuff
256 msgsock = INVALID_SOCKET;
263 // read data from socket (server)
264 // read a block of data of specified size
265 int SGSocket::read( char *buf, int length ) {
266 if ( sock == INVALID_SOCKET ) {
271 // check for potential input
274 FD_SET(sock, &ready);
279 // test for any input available on sock (returning immediately, even if
281 select(32, &ready, 0, 0, &tv);
283 if ( FD_ISSET(sock, &ready) ) {
284 // cout << "data ready" << endl;
286 if ( sock_style == SOCK_STREAM ) {
287 if ( msgsock == INVALID_SOCKET ) {
288 msgsock = accept(sock, 0, 0);
292 result = readsocket( sock, buf, length );
295 result = readsocket( sock, buf, length );
298 if ( result != length ) {
299 SG_LOG( SG_IO, SG_INFO,
300 "Warning: read() not enough bytes." );
308 // read a line of data, length is max size of input buffer
309 int SGSocket::readline( char *buf, int length ) {
310 if ( sock == INVALID_SOCKET ) {
314 // cout << "sock = " << sock << endl;
316 // check for potential input
319 FD_SET(sock, &ready);
324 // test for any input read on sock (returning immediately, even if
326 int result = select(32, &ready, 0, 0, &tv);
327 // cout << "result = " << result << endl;
329 if ( FD_ISSET(sock, &ready) ) {
330 // cout << "fd change state\n";
331 // read a chunk, keep in the save buffer until we have the
332 // requested amount read
334 if ( sock_style == SOCK_STREAM ) {
335 // cout << "sock_stream\n";
336 if ( msgsock == INVALID_SOCKET ) {
337 // cout << "msgsock == invalid\n";
338 msgsock = accept(sock, 0, 0);
342 // cout << "ready to read\n";
343 char *buf_ptr = save_buf + save_len;
344 result = readsocket( sock, buf_ptr, SG_IO_MAX_MSG_SIZE
346 // cout << "read result = " << result << endl;
354 // Try and detect that the remote end died. This
355 // could cause problems so if you see connections
356 // dropping for unexplained reasons, LOOK HERE!
357 if ( result == 0 && save_len == 0 && first_read == true ) {
358 SG_LOG( SG_IO, SG_ALERT,
359 "Connection closed by foreign host." );
365 char *buf_ptr = save_buf + save_len;
366 result = readsocket( sock, buf_ptr, SG_IO_MAX_MSG_SIZE - save_len );
370 // cout << "current read = " << buf_ptr << endl;
371 // cout << "current save_buf = " << save_buf << endl;
372 // cout << "save_len = " << save_len << endl;
374 // cout << "no data ready\n";
377 // look for the end of line in save_buf
379 for ( i = 0; i < save_len && save_buf[i] != '\n'; ++i );
380 if ( save_buf[i] == '\n' ) {
383 // no end of line yet
384 // cout << "no eol found" << endl;
387 // cout << "line length = " << result << endl;
389 // we found an end of line
391 // copy to external buffer
392 strncpy( buf, save_buf, result );
394 // cout << "sg_socket line = " << buf << endl;
397 for ( i = result; i < save_len; ++i ) {
398 save_buf[ i - result ] = save_buf[i];
406 // write data to socket (client)
407 int SGSocket::write( const char *buf, const int length ) {
408 if ( sock == INVALID_SOCKET ) {
412 bool error_condition = false;
414 if ( writesocket(sock, buf, length) < 0 ) {
415 SG_LOG( SG_IO, SG_ALERT, "Error writing to socket: " << port );
416 error_condition = true;
420 // check for any new client connection requests
423 FD_SET(sock, &ready);
428 // test for any input on sock (returning immediately, even if
430 select(32, &ready, 0, 0, &tv);
432 // any new connections?
433 if ( FD_ISSET(sock, &ready) ) {
434 int msgsock = accept(sock, 0, 0);
436 SG_LOG( SG_IO, SG_ALERT,
437 "Error: accept() failed in write()" );
440 client_connections.push_back( msgsock );
444 SG_LOG( SG_IO, SG_INFO, "Client connections = " <<
445 client_connections.size() );
446 for ( int i = 0; i < (int)client_connections.size(); ++i ) {
447 int msgsock = client_connections[i];
449 // read and junk any possible incoming messages.
450 // char junk[ SG_IO_MAX_MSG_SIZE ];
451 // std::read( msgsock, junk, SG_IO_MAX_MSG_SIZE );
453 // write the interesting data to the socket
454 if ( writesocket(msgsock, buf, length) == SOCKET_ERROR ) {
455 SG_LOG( SG_IO, SG_ALERT, "Error writing to socket: " << port );
456 error_condition = true;
458 #ifdef _POSIX_SYNCHRONIZED_IO
459 // fdatasync(msgsock);
467 if ( error_condition ) {
475 // write null terminated string to socket (server)
476 int SGSocket::writestring( const char *str ) {
477 if ( sock == INVALID_SOCKET ) {
481 int length = strlen( str );
482 return write( str, length );
487 bool SGSocket::close() {
488 if ( sock == INVALID_SOCKET ) {
497 // configure the socket as non-blocking
498 bool SGSocket::nonblock() {
499 if ( sock == INVALID_SOCKET ) {
503 #if defined(_MSC_VER)
505 if (ioctlsocket( sock, FIONBIO, &arg ) != 0) {
506 int error_code = WSAGetLastError();
507 SG_LOG( SG_IO, SG_ALERT,
508 "Error " << error_code << ": unable to set non-blocking mode"
513 fcntl( sock, F_SETFL, O_NONBLOCK );
518 #if defined(_MSC_VER)
520 bool SGSocket::wsock_init = false;
523 SGSocket::wsastartup() {
524 WORD wVersionRequested;
527 //wVersionRequested = MAKEWORD( 2, 2 );
528 wVersionRequested = MAKEWORD( 1, 1 );
529 int err = WSAStartup( wVersionRequested, &wsaData );
532 SG_LOG( SG_IO, SG_ALERT, "Error: Couldn't load winsock" );
537 if ( LOBYTE( wsaData.wVersion ) != 2 ||
538 HIBYTE( wsaData.wVersion ) != 2 ) {
539 SG_LOG( SG_IO, SG_ALERT, "Couldn't load a suitable winsock");