Debian Codegraph @

engine/network/lowlevel.cpp

raw
1 // ____ _ __
2 // / __ )____ _____ | | / /___ ___________
3 // / __ / __ \/ ___/ | | /| / / __ `/ ___/ ___/
4 // / /_/ / /_/ (__ ) | |/ |/ / /_/ / / (__ )
5 // /_____/\____/____/ |__/|__/\__,_/_/ /____/
6 //
7 // A futuristic real-time strategy game.
8 // This file is part of Bos Wars.
9 //
10 /**@name lowlevel.cpp - The network lowlevel. */
11 //
12 // (c) Copyright 2000-2007 by Lutz Sammer and Jimmy Salmon
13 //
14 // This program is free software; you can redistribute it and/or modify
15 // it under the terms of the GNU General Public License as published by
16 // the Free Software Foundation; only version 2 of the License.
17 //
18 // This program is distributed in the hope that it will be useful,
19 // but WITHOUT ANY WARRANTY; without even the implied warranty of
20 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 // GNU General Public License for more details.
22 //
23 // You should have received a copy of the GNU General Public License
24 // along with this program; if not, write to the Free Software
25 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
26 // 02111-1307, USA.
27 //
28
29 //@{
30
31 //----------------------------------------------------------------------------
32 // Includes
33 //----------------------------------------------------------------------------
34
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <stddef.h>
38 #include <string.h>
39 #include <fcntl.h>
40 #include <errno.h>
41
42 #ifndef _MSC_VER
43 #include <signal.h>
44 #endif
45
46 #include "stratagus.h"
47 #include "net_lowlevel.h"
48 #include "network.h"
49
50 //----------------------------------------------------------------------------
51 // Declarations
52 //----------------------------------------------------------------------------
53
54 #define MAX_LOC_IP 10
55
56 #if defined(_MSC_VER) || defined(__MINGW32__)
57 typedef const char *setsockopttype;
58 typedef char *recvfrombuftype;
59 typedef char *recvbuftype;
60 typedef const char *sendtobuftype;
61 typedef const char *sendbuftype;
62 typedef int socklen_t;
63 #else
64 typedef const void *setsockopttype;
65 typedef void *recvfrombuftype;
66 typedef void *recvbuftype;
67 typedef const void *sendtobuftype;
68 typedef const void *sendbuftype;
69 #endif
70
71 //----------------------------------------------------------------------------
72 // Variables
73 //----------------------------------------------------------------------------
74
75 int NetLastSocket; /// Last socket
76 unsigned long NetLastHost; /// Last host number (net format)
77 int NetLastPort; /// Last port number (net format)
78
79 unsigned long NetLocalAddrs[MAX_LOC_IP]; /// Local IP-Addrs of this host (net format)
80
81 //----------------------------------------------------------------------------
82 // Low level functions
83 //----------------------------------------------------------------------------
84
85 #ifdef USE_WINSOCK // {
86
87 /**
88 ** Hardware dependend network init.
89 */
90 int NetInit(void)
91 {
92 WSADATA wsaData;
93
94 // Start up the windows networking
95 if (WSAStartup(MAKEWORD(2, 2), &wsaData)) {
96 fprintf(stderr, "Couldn't initialize Winsock 2\n");
97 return -1;
98 }
99 return 0;
100 }
101
102 /**
103 ** Hardware dependend network exit.
104 */
105 void NetExit(void)
106 {
107 // Clean up windows networking
108 if (WSACleanup() == SOCKET_ERROR) {
109 if (WSAGetLastError() == WSAEINPROGRESS) {
110 WSACancelBlockingCall();
111 WSACleanup();
112 }
113 }
114 }
115
116 /**
117 ** Close an UDP socket port.
118 **
119 ** @param sockfd Socket fildes
120 */
121 void NetCloseUDP(Socket sockfd)
122 {
123 closesocket(sockfd);
124 }
125
126 /**
127 ** Close a TCP socket port.
128 **
129 ** @param sockfd Socket fildes
130 */
131 void NetCloseTCP(Socket sockfd)
132 {
133 closesocket(sockfd);
134 }
135
136 #endif // } !USE_WINSOCK
137
138 #if !defined(USE_WINSOCK) // {
139
140 /**
141 ** Hardware dependend network init.
142 */
143 int NetInit(void)
144 {
145 return 0;
146 }
147
148 /**
149 ** Hardware dependend network exit.
150 */
151 void NetExit(void)
152 {
153 }
154
155 /**
156 ** Close an UDP socket port.
157 **
158 ** @param sockfd Socket fildes
159 */
160 void NetCloseUDP(Socket sockfd)
161 {
162 close(sockfd);
163 }
164
165 /**
166 ** Close a TCP socket port.
167 **
168 ** @param sockfd Socket fildes
169 */
170 void NetCloseTCP(Socket sockfd)
171 {
172 close(sockfd);
173 }
174
175 #endif // } !USE_WINSOCK
176
177 /**
178 ** Set socket to non-blocking.
179 **
180 ** @param sockfd Socket
181 **
182 ** @return 0 for success, -1 for error
183 */
184 #ifdef USE_WINSOCK
185 int NetSetNonBlocking(Socket sockfd)
186 {
187 unsigned long opt = 1;
188 return ioctlsocket(sockfd, FIONBIO, &opt);
189 }
190 #else
191 int NetSetNonBlocking(Socket sockfd)
192 {
193 int flags = fcntl(sockfd, F_GETFL, 0);
194 return fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);
195 }
196 #endif
197
198 /**
199 ** Resolve host in name or dotted quad notation.
200 **
201 ** @param host Host name (f.e. 192.168.0.0 or stratagus.net)
202 */
203 unsigned long NetResolveHost(const std::string &host)
204 {
205 unsigned long addr;
206
207 if (!host.empty()) {
208 addr = inet_addr(host.c_str()); // try dot notation
209 if (addr == INADDR_NONE) {
210 struct hostent *he;
211
212 he = 0;
213 he = gethostbyname(host.c_str());
214 if (he) {
215 addr = 0;
216 Assert(he->h_length == 4);
217 memcpy(&addr, he->h_addr, he->h_length);
218 }
219 }
220 return addr;
221 }
222 return INADDR_NONE;
223 }
224
225 /**
226 ** Get IP-addrs of local interfaces from Network file descriptor
227 ** and store them in the NetLocalAddrs array.
228 **
229 ** @param sock local socket.
230 **
231 ** @return number of IP-addrs found.
232 */
233 #ifdef USE_WINSOCK // {
234 // ARI: MS documented this for winsock2, so I finally found it..
235 // I also found a way for winsock1.1 (= win95), but
236 // that one was too complex to start with.. -> trouble
237 // Lookout for INTRFC.EXE on the MS web site...
238 int NetSocketAddr(const Socket sock)
239 {
240 INTERFACE_INFO localAddr[MAX_LOC_IP]; // Assume there will be no more than MAX_LOC_IP interfaces
241 DWORD bytesReturned;
242 SOCKADDR_IN *pAddrInet;
243 u_long SetFlags;
244 int i;
245 int nif;
246 int wsError;
247 int numLocalAddr;
248
249 nif = 0;
250 if (sock != (Socket)-1) {
251 wsError = WSAIoctl(sock, SIO_GET_INTERFACE_LIST, NULL, 0, &localAddr,
252 sizeof(localAddr), &bytesReturned, NULL, NULL);
253 if (wsError == SOCKET_ERROR) {
254 DebugPrint("SIOCGIFCONF:WSAIoctl(SIO_GET_INTERFACE_LIST) - errno %d\n" _C_
255 WSAGetLastError());
256 }
257
258 // parse interface information
259 numLocalAddr = (bytesReturned / sizeof(INTERFACE_INFO));
260 for (i = 0; i < numLocalAddr; ++i) {
261 SetFlags = localAddr[i].iiFlags;
262 if ((SetFlags & IFF_UP) == 0) {
263 continue;
264 }
265 if ((SetFlags & IFF_LOOPBACK)) {
266 continue;
267 }
268 pAddrInet = (SOCKADDR_IN *)&localAddr[i].iiAddress;
269 NetLocalAddrs[nif] = pAddrInet->sin_addr.s_addr;
270 ++nif;
271 if (nif == MAX_LOC_IP) {
272 break;
273 }
274 }
275 }
276 return nif;
277 }
278 #else // } { !USE_WINSOCK
279 #ifdef unix // {
280 // ARI: I knew how to write this for a unix environment,
281 // but am quite certain that porting this can cause you
282 // trouble..
283 int NetSocketAddr(const Socket sock)
284 {
285 char buf[4096];
286 char *cp;
287 char *cplim;
288 struct ifconf ifc;
289 struct ifreq ifreq;
290 struct ifreq *ifr;
291 struct sockaddr_in *sap;
292 struct sockaddr_in sa;
293 int i;
294 int nif;
295
296 nif = 0;
297 if (sock != (Socket)-1) {
298 ifc.ifc_len = sizeof(buf);
299 ifc.ifc_buf = buf;
300 if (ioctl(sock, SIOCGIFCONF, (char *)&ifc) < 0) {
301 DebugPrint("SIOCGIFCONF - errno %d\n" _C_ errno);
302 return 0;
303 }
304 // with some inspiration from routed..
305 ifr = ifc.ifc_req;
306 cplim = buf + ifc.ifc_len; // skip over if's with big ifr_addr's
307 for (cp = buf; cp < cplim;
308 cp += sizeof(ifr->ifr_name) + sizeof(ifr->ifr_ifru)) {
309 ifr = (struct ifreq *)cp;
310 ifreq = *ifr;
311 if (ioctl(sock, SIOCGIFFLAGS, (char *)&ifreq) < 0) {
312 DebugPrint("%s: SIOCGIFFLAGS - errno %d\n" _C_
313 ifr->ifr_name _C_ errno);
314 continue;
315 }
316 if ((ifreq.ifr_flags & IFF_UP) == 0 ||
317 ifr->ifr_addr.sa_family == AF_UNSPEC) {
318 continue;
319 }
320 // argh, this'll have to change sometime
321 if (ifr->ifr_addr.sa_family != AF_INET) {
322 continue;
323 }
324 if (ifreq.ifr_flags & IFF_LOOPBACK) {
325 continue;
326 }
327 sap = (struct sockaddr_in *)&ifr->ifr_addr;
328 sa = *sap;
329 NetLocalAddrs[nif] = sap->sin_addr.s_addr;
330 if (ifreq.ifr_flags & IFF_POINTOPOINT) {
331 if (ioctl(sock, SIOCGIFDSTADDR, (char *)&ifreq) < 0) {
332 DebugPrint("%s: SIOCGIFDSTADDR - errno %d\n" _C_
333 ifr->ifr_name _C_ errno);
334 // failed to obtain dst addr - ignore
335 continue;
336 }
337 if (ifr->ifr_addr.sa_family == AF_UNSPEC) {
338 continue;
339 }
340 }
341 // avoid p-t-p links with common src
342 if (nif) {
343 for (i = 0; i < nif; ++i) {
344 if (sa.sin_addr.s_addr == NetLocalAddrs[i]) {
345 i = -1;
346 break;
347 }
348 }
349 if (i == -1) {
350 continue;
351 }
352 }
353 ++nif;
354 if (nif == MAX_LOC_IP) {
355 break;
356 }
357 }
358 }
359 return nif;
360 }
361 #else // } !unix
362 // Beos?? Mac??
363 int NetSocketAddr(const Socket sock)
364 {
365 NetLocalAddrs[0] = htonl(0x7f000001);
366 return 1;
367 }
368 #endif
369 #endif // } !USE_WINSOCK
370
371 /**
372 ** Open an UDP Socket port.
373 **
374 ** @param port !=0 Port to bind in host notation.
375 **
376 ** @return If success the socket fildes, -1 otherwise.
377 */
378 Socket NetOpenUDP(int port)
379 {
380 Socket sockfd;
381
382 // open the socket
383 sockfd = socket(AF_INET, SOCK_DGRAM, 0);
384 if (sockfd == INVALID_SOCKET) {
385 return (Socket)-1;
386 }
387 // bind local port
388 if (port) {
389 struct sockaddr_in sock_addr;
390
391 memset(&sock_addr, 0, sizeof(sock_addr));
392 sock_addr.sin_family = AF_INET;
393 sock_addr.sin_addr.s_addr = INADDR_ANY;
394 sock_addr.sin_port = htons(port);
395 // Bind the socket for listening
396 if (bind(sockfd, (struct sockaddr *)&sock_addr, sizeof(sock_addr)) < 0) {
397 fprintf(stderr, "Couldn't bind to local port\n");
398 NetCloseUDP(sockfd);
399 return (Socket)-1;
400 }
401 NetLastHost = sock_addr.sin_addr.s_addr;
402 NetLastPort = sock_addr.sin_port;
403 }
404 return sockfd;
405 }
406
407 /**
408 ** Open a TCP socket
409 **
410 ** @param port Bind socket to a specific port number
411 **
412 ** @return If success the socket fildes, -1 otherwise
413 */
414 Socket NetOpenTCP(int port)
415 {
416 Socket sockfd;
417
418 sockfd = socket(AF_INET, SOCK_STREAM, 0);
419 if (sockfd == INVALID_SOCKET) {
420 return (Socket)-1;
421 }
422 // bind local port
423 if (port) {
424 struct sockaddr_in sock_addr;
425 int opt;
426
427 memset(&sock_addr, 0, sizeof(sock_addr));
428 sock_addr.sin_family = AF_INET;
429 sock_addr.sin_addr.s_addr = INADDR_ANY;
430 sock_addr.sin_port = htons(port);
431
432 opt = 1;
433 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (setsockopttype)&opt, sizeof(opt));
434
435 if (bind(sockfd,(struct sockaddr *)&sock_addr, sizeof(sock_addr)) < 0) {
436 fprintf(stderr, "Couldn't bind to local port\n");
437 NetCloseTCP(sockfd);
438 return (Socket)-1;
439 }
440 NetLastHost = sock_addr.sin_addr.s_addr;
441 NetLastPort = sock_addr.sin_port;
442 }
443 NetLastSocket = sockfd;
444 return sockfd;
445 }
446
447 /**
448 ** Open a TCP connection
449 **
450 ** @param sockfd An open socket to use
451 ** @param addr Address returned from NetResolveHost
452 ** @param port Port on remote host to connect to
453 **
454 ** @return 0 if success, -1 if failure
455 */
456 int NetConnectTCP(Socket sockfd, unsigned long addr, int port)
457 {
458 struct sockaddr_in sa;
459 #ifndef __BEOS__
460 int opt;
461
462 opt = 1;
463 setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, (setsockopttype)&opt, sizeof(opt));
464 opt = 0;
465 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (setsockopttype)&opt, sizeof(opt));
466 #endif
467
468 if (addr == INADDR_NONE) {
469 return -1;
470 }
471
472 memset(&sa, 0, sizeof(sa));
473 memcpy(&sa.sin_addr, &addr, sizeof(addr));
474 sa.sin_family = AF_INET;
475 sa.sin_port = htons(port);
476
477 if (connect(sockfd, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
478 fprintf(stderr, "connect to %d.%d.%d.%d:%d failed\n",
479 NIPQUAD(ntohl(addr)), port);
480 return -1;
481 }
482
483 return sockfd;
484 }
485
486 /**
487 ** Wait for socket ready.
488 **
489 ** @param sockfd Socket fildes to probe.
490 ** @param timeout Timeout in 1/1000 seconds.
491 **
492 ** @return 1 if data is available, 0 if not, -1 if failure.
493 */
494 int NetSocketReady(Socket sockfd, int timeout)
495 {
496 int retval;
497 struct timeval tv;
498 fd_set mask;
499
500 // Check the file descriptors for available data
501 do {
502 // Set up the mask of file descriptors
503 FD_ZERO(&mask);
504 FD_SET(sockfd, &mask);
505
506 // Set up the timeout
507 tv.tv_sec = timeout / 1000;
508 tv.tv_usec = (timeout % 1000) * 1000;
509
510 // Data available?
511 retval = select(sockfd + 1, &mask, NULL, NULL, &tv);
512 #ifdef USE_WINSOCK
513 } while (retval == SOCKET_ERROR && WSAGetLastError() == WSAEINTR);
514 #else
515 } while (retval == -1 && errno == EINTR);
516 #endif
517
518 return retval;
519 }
520
521 /**
522 ** Wait for socket set ready.
523 **
524 ** @param set Socket set to probe.
525 ** @param timeout Timeout in 1/1000 seconds.
526 **
527 ** @return 1 if data is available, 0 if not, -1 if failure.
528 */
529 int NetSocketSetReady(SocketSet *set, int timeout)
530 {
531 int retval;
532 struct timeval tv;
533 fd_set mask;
534
535 // Check the file descriptors for available data
536 do {
537 // Set up the mask of file descriptors
538 FD_ZERO(&mask);
539 for (size_t i = 0; i < set->Sockets.size(); ++i) {
540 FD_SET(set->Sockets[i], &mask);
541 }
542
543 // Set up the timeout
544 tv.tv_sec = timeout / 1000;
545 tv.tv_usec = (timeout % 1000) * 1000;
546
547 // Data available?
548 retval = select(set->MaxSockFD + 1, &mask, NULL, NULL, &tv);
549 #ifdef USE_WINSOCK
550 } while (retval == SOCKET_ERROR && WSAGetLastError() == WSAEINTR);
551 #else
552 } while (retval == -1 && errno == EINTR);
553 #endif
554
555 for (size_t i = 0; i < set->Sockets.size(); ++i) {
556 set->SocketReady[i] = FD_ISSET(set->Sockets[i], &mask);
557 }
558
559 return retval;
560 }
561
562 /**
563 ** Check if a socket in a socket set is ready.
564 **
565 ** @param set Socket set
566 ** @param socket Socket to check
567 **
568 ** @return Non-zero if socket is ready
569 */
570 int NetSocketSetSocketReady(SocketSet *set, Socket socket)
571 {
572 for (size_t i = 0; i < set->Sockets.size(); ++i) {
573 if (set->Sockets[i] == socket) {
574 return set->SocketReady[i];
575 }
576 }
577 DebugPrint("Socket not found in socket set\n");
578 return 0;
579 }
580
581 /**
582 ** Receive from a UDP socket.
583 **
584 ** @param sockfd Socket
585 ** @param buf Receive message buffer.
586 ** @param len Receive message buffer length.
587 **
588 ** @return Number of bytes placed in buffer, or -1 if failure.
589 */
590 int NetRecvUDP(Socket sockfd, void *buf, int len)
591 {
592 socklen_t n;
593 int l;
594 struct sockaddr_in sock_addr;
595
596 n = sizeof(struct sockaddr_in);
597 if ((l = recvfrom(sockfd, (recvfrombuftype)buf, len, 0, (struct sockaddr *)&sock_addr, &n)) < 0) {
598 PrintFunction();
599 fprintf(stdout, "Could not read from UDP socket\n");
600 return -1;
601 }
602
603 // Packet check for validness is done higher up, we don't know who should be
604 // sending us packets at this level
605
606 NetLastHost = sock_addr.sin_addr.s_addr;
607 NetLastPort = sock_addr.sin_port;
608
609 return l;
610 }
611
612 /**
613 ** Receive from a TCP socket.
614 **
615 ** @param sockfd Socket
616 ** @param buf Receive message buffer.
617 ** @param len Receive message buffer length.
618 **
619 ** @return Number of bytes placed in buffer or -1 if failure.
620 */
621 int NetRecvTCP(Socket sockfd, void *buf, int len)
622 {
623 int ret;
624
625 NetLastSocket = sockfd;
626 ret = recv(sockfd, (recvbuftype)buf, len, 0);
627 if (ret > 0) {
628 return ret;
629 }
630 if (ret == 0) {
631 return -1;
632 }
633 #ifdef USE_WINSOCK
634 if (WSAGetLastError() == WSAEWOULDBLOCK) {
635 #else
636 if (errno == EWOULDBLOCK || errno == EAGAIN) {
637 #endif
638 return 0;
639 }
640 return ret;
641 }
642
643 /**
644 ** Send through a UPD socket to a host:port.
645 **
646 ** @param sockfd Socket
647 ** @param host Host to send to (network byte order).
648 ** @param port Port of host to send to (network byte order).
649 ** @param buf Send message buffer.
650 ** @param len Send message buffer length.
651 **
652 ** @return Number of bytes sent.
653 */
654 int NetSendUDP(Socket sockfd, unsigned long host, int port,
655 const void *buf, int len)
656 {
657 int n;
658 struct sockaddr_in sock_addr;
659
660 n = sizeof(struct sockaddr_in);
661 sock_addr.sin_addr.s_addr = host;
662 sock_addr.sin_port = port;
663 sock_addr.sin_family = AF_INET;
664
665 // if (MyRand() % 7) { return 0; }
666
667 return sendto(sockfd, (sendtobuftype)buf, len, 0, (struct sockaddr *)&sock_addr, n);
668 }
669
670 /**
671 ** Send through a TCP socket.
672 **
673 ** @param sockfd Socket
674 ** @param buf Send message buffer.
675 ** @param len Send message buffer length.
676 **
677 ** @return Number of bytes sent.
678 */
679 int NetSendTCP(Socket sockfd, const void *buf, int len)
680 {
681 return send(sockfd, (sendbuftype)buf, len, 0);
682 }
683
684 /**
685 ** Listen for connections on a TCP socket.
686 **
687 ** @param sockfd Socket
688 **
689 ** @return 0 for success, -1 for error
690 */
691 int NetListenTCP(Socket sockfd)
692 {
693 return listen(sockfd, PlayerMax);
694 }
695
696 /**
697 ** Accept a connection on a TCP socket.
698 **
699 ** @param sockfd Socket
700 **
701 ** @return If success the new socket fildes, -1 otherwise.
702 */
703 Socket NetAcceptTCP(Socket sockfd)
704 {
705 struct sockaddr_in sa;
706 socklen_t len;
707
708 len = sizeof(struct sockaddr_in);
709 NetLastSocket = accept(sockfd, (struct sockaddr *)&sa, &len);
710 NetLastHost = sa.sin_addr.s_addr;
711 NetLastPort = sa.sin_port;
712 return NetLastSocket;
713 }
714
715 /**
716 ** Add a socket to a socket set
717 **
718 ** @param socket Socket to add to the socket set
719 */
720 void SocketSet::AddSocket(Socket socket)
721 {
722 Sockets.push_back(socket);
723 SocketReady.push_back(0);
724 if (socket > MaxSockFD) {
725 MaxSockFD = socket;
726 }
727 }
728
729 /**
730 ** Delete a socket from a socket set
731 **
732 ** @param socket Socket to delete from the socket set
733 */
734 void SocketSet::DelSocket(Socket socket)
735 {
736 std::vector<Socket>::iterator i;
737 std::vector<int>::iterator j;
738
739 for (i = Sockets.begin(), j = SocketReady.begin(); i != Sockets.end(); ++i, ++j) {
740 if (*i == socket) {
741 Sockets.erase(i);
742 SocketReady.erase(j);
743 break;
744 }
745 }
746 if (socket == MaxSockFD) {
747 MaxSockFD = 0;
748 for (i = Sockets.begin(); i != Sockets.end(); ++i) {
749 if (*i > MaxSockFD) {
750 MaxSockFD = *i;
751 }
752 }
753 }
754 }
755
756 //@}