]> git.mxchange.org Git - simgear.git/blob - simgear/io/sg_socket.cxx
Oops! fixed a typo ...
[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 {
225         FG_LOG( FG_IO, FG_ALERT, 
226                 "Error:  bidirection mode not available yet for sockets." );
227         return false;
228     }
229
230     if ( sock < 0 ) {
231         FG_LOG( FG_IO, FG_ALERT, "Error opening socket: " << hostname
232                 << ":" << port );
233         return false;
234     }
235
236     return true;
237 }
238
239
240 // read data from socket (server)
241 // read a block of data of specified size
242 int SGSocket::read( char *buf, int length ) {
243     int result = 0;
244
245     // check for potential input
246     fd_set ready;
247     FD_ZERO(&ready);
248     FD_SET(sock, &ready);
249     struct timeval tv;
250     tv.tv_sec = 0;
251     tv.tv_usec = 0;
252
253     // test for any input available on sock (returning immediately, even if
254     // nothing)
255     select(32, &ready, 0, 0, &tv);
256
257     if ( FD_ISSET(sock, &ready) ) {
258         result = readsocket( sock, buf, length );
259         if ( result != length ) {
260             FG_LOG( FG_IO, FG_INFO, 
261                     "Warning: read() not enough bytes." );
262         }
263     }
264
265     return result;
266 }
267
268
269 // read a line of data, length is max size of input buffer
270 int SGSocket::readline( char *buf, int length ) {
271     int result = 0;
272
273     // check for potential input
274     fd_set ready;
275     FD_ZERO(&ready);
276     FD_SET(sock, &ready);
277     struct timeval tv;
278     tv.tv_sec = 0;
279     tv.tv_usec = 0;
280
281     // test for any input read on sock (returning immediately, even if
282     // nothing)
283     int rc = select(32, &ready, 0, 0, &tv);
284     // FG_LOG( FG_IO, FG_DEBUG, "select returned " << rc );
285
286     if ( FD_ISSET(sock, &ready) ) {
287         // read a chunk, keep in the save buffer until we have the
288         // requested amount read
289
290         char *buf_ptr = save_buf + save_len;
291         result = readsocket( sock, buf_ptr, SG_IO_MAX_MSG_SIZE - save_len );
292         save_len += result;
293         // cout << "current read = " << buf_ptr << endl;
294         // cout << "current save_buf = " << save_buf << endl;
295         // cout << "save_len = " << save_len << endl;
296     }
297
298     // look for the end of line in save_buf
299     int i;
300     for ( i = 0; i < save_len && save_buf[i] != '\n'; ++i );
301     if ( save_buf[i] == '\n' ) {
302         result = i + 1;
303     } else {
304         // no end of line yet
305         // cout << "no eol found" << endl;
306         return 0;
307     }
308     // cout << "line length = " << result << endl;
309
310     // we found an end of line
311
312     // copy to external buffer
313     strncpy( buf, save_buf, result );
314     buf[result] = '\0';
315     // cout << "sg_socket line = " << buf << endl;
316     
317     // shift save buffer
318     for ( i = result; i < save_len; ++i ) {
319         save_buf[ i - result ] = save_buf[i];
320     }
321     save_len -= result;
322
323     return result;
324 }
325
326
327 // write data to socket (client)
328 int SGSocket::write( char *buf, int length ) {
329     bool error_condition = false;
330
331     if ( writesocket(sock, buf, length) < 0 ) {
332         FG_LOG( FG_IO, FG_ALERT, "Error writing to socket: " << port );
333         error_condition = true;
334     }
335
336 #if 0 
337     // check for any new client connection requests
338     fd_set ready;
339     FD_ZERO(&ready);
340     FD_SET(sock, &ready);
341     struct timeval tv;
342     tv.tv_sec = 0;
343     tv.tv_usec = 0;
344
345     // test for any input on sock (returning immediately, even if
346     // nothing)
347     select(32, &ready, 0, 0, &tv);
348
349     // any new connections?
350     if ( FD_ISSET(sock, &ready) ) {
351         int msgsock = accept(sock, 0, 0);
352         if ( msgsock < 0 ) {
353             FG_LOG( FG_IO, FG_ALERT, 
354                     "Error: accept() failed in write()" );
355             return 0;
356         } else {
357             client_connections.push_back( msgsock );
358         }
359     }
360
361     FG_LOG( FG_IO, FG_INFO, "Client connections = " << 
362             client_connections.size() );
363     for ( int i = 0; i < (int)client_connections.size(); ++i ) {
364         int msgsock = client_connections[i];
365
366         // read and junk any possible incoming messages.
367         // char junk[ SG_IO_MAX_MSG_SIZE ];
368         // std::read( msgsock, junk, SG_IO_MAX_MSG_SIZE );
369
370         // write the interesting data to the socket
371         if ( writesocket(msgsock, buf, length) == SOCKET_ERROR ) {
372             FG_LOG( FG_IO, FG_ALERT, "Error writing to socket: " << port );
373             error_condition = true;
374         } else {
375 #ifdef _POSIX_SYNCHRONIZED_IO
376             // fdatasync(msgsock);
377 #else
378             // fsync(msgsock);
379 #endif
380         }
381     }
382 #endif
383
384     if ( error_condition ) {
385         return 0;
386     }
387
388     return length;
389 }
390
391
392 // write null terminated string to socket (server)
393 int SGSocket::writestring( char *str ) {
394     int length = strlen( str );
395     return write( str, length );
396 }
397
398
399 // close the port
400 bool SGSocket::close() {
401 #if 0
402     for ( int i = 0; i < (int)client_connections.size(); ++i ) {
403         int msgsock = client_connections[i];
404         closesocket( msgsock );
405     }
406 #endif
407
408     closesocket( sock );
409     return true;
410 }
411
412
413 // configure the socket as non-blocking
414 bool SGSocket::nonblock() {
415 #if defined(_MSC_VER)
416     u_long arg = 1;
417     if (ioctlsocket( sock, FIONBIO, &arg ) != 0) {
418         int error_code = WSAGetLastError();
419         FG_LOG( FG_IO, FG_ALERT, 
420                 "Error " << error_code << ": unable to set non-blocking mode"
421 );
422             return false;
423     }
424 #else
425     fcntl( sock, F_SETFL, O_NONBLOCK );
426 #endif
427     return true;
428 }
429
430 #if defined(_MSC_VER)
431
432 bool SGSocket::wsock_init = false;
433
434 bool
435 SGSocket::wsastartup() {
436     WORD wVersionRequested;
437     WSADATA wsaData;
438
439     //wVersionRequested = MAKEWORD( 2, 2 );
440     wVersionRequested = MAKEWORD( 1, 1 );
441     int err = WSAStartup( wVersionRequested, &wsaData );
442     if (err != 0)
443     {
444         FG_LOG( FG_IO, FG_ALERT, "Error: Couldn't load winsock" );
445         return false;
446     }
447
448 #if 0
449     if ( LOBYTE( wsaData.wVersion ) != 2 ||
450         HIBYTE( wsaData.wVersion ) != 2 ) {
451         FG_LOG( FG_IO, FG_ALERT, "Couldn't load a suitable winsock");
452         WSACleanup( );
453         return false;
454     }
455 #endif
456     wsock_init = true;
457     return true;
458 }
459 #endif