]> git.mxchange.org Git - simgear.git/blob - simgear/io/sg_socket.cxx
Cleaned up a few poluting #defines.
[simgear.git] / simgear / io / sg_socket.cxx
1 // sg_socket.cxx -- Socket I/O routines
2 //
3 // Written by Curtis Olson, started November 1999.
4 //
5 // Copyright (C) 1999  Curtis L. Olson - curt@flightgear.org
6 //
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.
11 //
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.
16 //
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.
20 //
21 // $Id$
22
23
24 #include <simgear/compiler.h>
25
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()
34 #endif
35
36 #if defined( sgi )
37 #include <strings.h>
38 #endif
39
40 #include <simgear/debug/logstream.hxx>
41
42 #include "sg_socket.hxx"
43
44
45 SGSocket::SGSocket( const string& host, const string& port, 
46                     const string& style ) :
47     hostname(host),
48     port_str(port),
49     save_len(0)
50 {
51 #if defined(_MSC_VER)
52     if (!wsock_init && !wsastartup()) {
53         FG_LOG( FG_IO, FG_ALERT, "Winsock not available");
54     }
55 #endif
56
57     if ( style == "udp" ) {
58         sock_style = SOCK_DGRAM;
59     } else if ( style == "tcp" ) {
60         sock_style = SOCK_STREAM;
61     } else {
62         sock_style = SOCK_DGRAM;
63         FG_LOG( FG_IO, FG_ALERT,
64                 "Error: SGSocket() unknown style = " << style );
65     }
66
67     set_type( sgSocketType );
68 }
69
70
71 SGSocket::~SGSocket() {
72 }
73
74
75 SGSocket::SocketType SGSocket::make_server_socket () {
76     struct sockaddr_in name;
77
78 #if defined( __CYGWIN__ ) || defined( __CYGWIN32__ ) || defined( sgi ) || defined( _MSC_VER )
79     int length;
80 #else
81     socklen_t length;
82 #endif
83      
84     // Create the socket.
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;
90     }
91      
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;
101     }
102
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;
109     }
110     port = ntohs(name.sin_port);
111
112     return sock;
113 }
114
115
116 SGSocket::SocketType SGSocket::make_client_socket () {
117     struct sockaddr_in name;
118     struct hostent *hp;
119      
120     FG_LOG( FG_IO, FG_INFO, "Make client socket()" );
121
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;
128     }
129      
130     // specify address family
131     name.sin_family = AF_INET;
132
133     // get the hosts official name/info
134     hp = gethostbyname( hostname.c_str() );
135
136     // Connect this socket to the host and the port specified on the
137     // command line
138 #if defined( __CYGWIN__ ) || defined( __CYGWIN32__ )
139     bcopy(hp->h_addr, (char *)(&(name.sin_addr.s_addr)), hp->h_length);
140 #else
141     bcopy(hp->h_addr, &(name.sin_addr.s_addr), hp->h_length);
142 #endif
143     name.sin_port = htons(port);
144
145     if ( connect(sock, (struct sockaddr *) &name, 
146                  sizeof(struct sockaddr_in)) != 0 )
147     {
148         closesocket(sock);
149         FG_LOG( FG_IO, FG_ALERT, 
150                 "Error: connect() failed in make_client_socket()" );
151         return INVALID_SOCKET;
152     }
153
154     return sock;
155 }
156
157
158 // Wrapper functions
159 size_t SGSocket::readsocket( int fd, void *buf, size_t count ) {
160 #if defined(_MSC_VER)
161     return ::recv( fd, buf, count, 0 );
162 #else
163     return ::read( fd, buf, count );
164 #endif
165 }
166
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 );
170 #else
171     return ::write( fd, buf, count );
172 #endif
173 }
174
175 #if !defined(_MSC_VER)
176 int SGSocket::closesocket( int fd ) {
177     return ::close( fd );
178 }
179 #endif
180
181
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" ) {
187         port = 0; 
188     } else {
189         port = atoi( port_str.c_str() );
190     }
191     
192     // client_connections.clear();
193
194     if ( dir == SG_IO_IN ) {
195         // this means server for now
196
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.
202
203         FG_LOG( FG_IO, FG_INFO, "socket is connected to port = " << port );
204
205         if ( sock_style == SOCK_DGRAM ) {
206             // Non-blocking UDP
207             nonblock();
208         } else {
209             // Blocking TCP
210             // Specify the maximum length of the connection queue
211             listen( sock, SG_MAX_SOCKET_QUEUE );
212         }
213
214     } else if ( dir == SG_IO_OUT ) {
215         // this means client for now
216
217         sock = make_client_socket();
218         // TODO: check for error.
219
220         if ( sock_style == SOCK_DGRAM ) {
221             // Non-blocking UDP
222             nonblock();
223         }
224     } else if ( dir == SG_IO_BI && sock_style == SOCK_STREAM ) {
225         // this means server for TCP sockets
226
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.
232
233         FG_LOG( FG_IO, FG_INFO, "socket is connected to port = " << port );
234
235         // Blocking TCP
236         // Specify the maximum length of the connection queue
237         listen( sock, SG_MAX_SOCKET_QUEUE );
238     } else {
239         FG_LOG( FG_IO, FG_ALERT, 
240                 "Error:  bidirection mode not available for UDP sockets." );
241         return false;
242     }
243
244     if ( sock < 0 ) {
245         FG_LOG( FG_IO, FG_ALERT, "Error opening socket: " << hostname
246                 << ":" << port );
247         return false;
248     }
249
250     return true;
251 }
252
253
254 // read data from socket (server)
255 // read a block of data of specified size
256 int SGSocket::read( char *buf, int length ) {
257     int result = 0;
258
259     // check for potential input
260     fd_set ready;
261     FD_ZERO(&ready);
262     FD_SET(sock, &ready);
263     struct timeval tv;
264     tv.tv_sec = 0;
265     tv.tv_usec = 0;
266
267     // test for any input available on sock (returning immediately, even if
268     // nothing)
269     select(32, &ready, 0, 0, &tv);
270
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." );
276         }
277     }
278
279     return result;
280 }
281
282
283 // read a line of data, length is max size of input buffer
284 int SGSocket::readline( char *buf, int length ) {
285     int result = 0;
286
287     // check for potential input
288     fd_set ready;
289     FD_ZERO(&ready);
290     FD_SET(sock, &ready);
291     struct timeval tv;
292     tv.tv_sec = 0;
293     tv.tv_usec = 0;
294
295     // test for any input read on sock (returning immediately, even if
296     // nothing)
297     int rc = select(32, &ready, 0, 0, &tv);
298     // FG_LOG( FG_IO, FG_DEBUG, "select returned " << rc );
299
300     if ( FD_ISSET(sock, &ready) ) {
301         // read a chunk, keep in the save buffer until we have the
302         // requested amount read
303
304         char *buf_ptr = save_buf + save_len;
305         result = readsocket( sock, buf_ptr, SG_IO_MAX_MSG_SIZE - save_len );
306         save_len += result;
307         // cout << "current read = " << buf_ptr << endl;
308         // cout << "current save_buf = " << save_buf << endl;
309         // cout << "save_len = " << save_len << endl;
310     }
311
312     // look for the end of line in save_buf
313     int i;
314     for ( i = 0; i < save_len && save_buf[i] != '\n'; ++i );
315     if ( save_buf[i] == '\n' ) {
316         result = i + 1;
317     } else {
318         // no end of line yet
319         // cout << "no eol found" << endl;
320         return 0;
321     }
322     // cout << "line length = " << result << endl;
323
324     // we found an end of line
325
326     // copy to external buffer
327     strncpy( buf, save_buf, result );
328     buf[result] = '\0';
329     // cout << "sg_socket line = " << buf << endl;
330     
331     // shift save buffer
332     for ( i = result; i < save_len; ++i ) {
333         save_buf[ i - result ] = save_buf[i];
334     }
335     save_len -= result;
336
337     return result;
338 }
339
340
341 // write data to socket (client)
342 int SGSocket::write( char *buf, int length ) {
343     bool error_condition = false;
344
345     if ( writesocket(sock, buf, length) < 0 ) {
346         FG_LOG( FG_IO, FG_ALERT, "Error writing to socket: " << port );
347         error_condition = true;
348     }
349
350 #if 0 
351     // check for any new client connection requests
352     fd_set ready;
353     FD_ZERO(&ready);
354     FD_SET(sock, &ready);
355     struct timeval tv;
356     tv.tv_sec = 0;
357     tv.tv_usec = 0;
358
359     // test for any input on sock (returning immediately, even if
360     // nothing)
361     select(32, &ready, 0, 0, &tv);
362
363     // any new connections?
364     if ( FD_ISSET(sock, &ready) ) {
365         int msgsock = accept(sock, 0, 0);
366         if ( msgsock < 0 ) {
367             FG_LOG( FG_IO, FG_ALERT, 
368                     "Error: accept() failed in write()" );
369             return 0;
370         } else {
371             client_connections.push_back( msgsock );
372         }
373     }
374
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];
379
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 );
383
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;
388         } else {
389 #ifdef _POSIX_SYNCHRONIZED_IO
390             // fdatasync(msgsock);
391 #else
392             // fsync(msgsock);
393 #endif
394         }
395     }
396 #endif
397
398     if ( error_condition ) {
399         return 0;
400     }
401
402     return length;
403 }
404
405
406 // write null terminated string to socket (server)
407 int SGSocket::writestring( char *str ) {
408     int length = strlen( str );
409     return write( str, length );
410 }
411
412
413 // close the port
414 bool SGSocket::close() {
415 #if 0
416     for ( int i = 0; i < (int)client_connections.size(); ++i ) {
417         int msgsock = client_connections[i];
418         closesocket( msgsock );
419     }
420 #endif
421
422     closesocket( sock );
423     return true;
424 }
425
426
427 // configure the socket as non-blocking
428 bool SGSocket::nonblock() {
429 #if defined(_MSC_VER)
430     u_long arg = 1;
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"
435 );
436             return false;
437     }
438 #else
439     fcntl( sock, F_SETFL, O_NONBLOCK );
440 #endif
441     return true;
442 }
443
444 #if defined(_MSC_VER)
445
446 bool SGSocket::wsock_init = false;
447
448 bool
449 SGSocket::wsastartup() {
450     WORD wVersionRequested;
451     WSADATA wsaData;
452
453     //wVersionRequested = MAKEWORD( 2, 2 );
454     wVersionRequested = MAKEWORD( 1, 1 );
455     int err = WSAStartup( wVersionRequested, &wsaData );
456     if (err != 0)
457     {
458         FG_LOG( FG_IO, FG_ALERT, "Error: Couldn't load winsock" );
459         return false;
460     }
461
462 #if 0
463     if ( LOBYTE( wsaData.wVersion ) != 2 ||
464         HIBYTE( wsaData.wVersion ) != 2 ) {
465         FG_LOG( FG_IO, FG_ALERT, "Couldn't load a suitable winsock");
466         WSACleanup( );
467         return false;
468     }
469 #endif
470     wsock_init = true;
471     return true;
472 }
473 #endif