2 * Copyright (C) Volition, Inc. 1999. All rights reserved.
4 * All source code herein is the property of Volition, Inc. You may not sell
5 * or otherwise commercially exploit the source or things you created based on
10 * $Logfile: /Freespace2/code/Network/PsNet.cpp $
15 * C file containing application level network-interface.
18 * Revision 1.5 2002/06/09 04:41:24 relnev
19 * added copyright header
21 * Revision 1.4 2002/06/02 02:29:39 relnev
24 * Revision 1.3 2002/05/26 20:49:54 theoddone33
27 * Revision 1.2 2002/05/07 03:16:48 theoddone33
28 * The Great Newline Fix
30 * Revision 1.1.1.1 2002/05/03 03:28:10 root
34 * 7 7/15/99 9:20a Andsager
35 * FS2_DEMO initial checkin
37 * 6 11/19/98 4:19p Dave
38 * Put IPX sockets back in psnet. Consolidated all multiplayer config
41 * 5 11/19/98 8:04a Dave
42 * Full support for D3-style reliable sockets. Revamped packet lag/loss
43 * system, made it receiver side and at the lowest possible level.
45 * 4 11/17/98 11:12a Dave
46 * Removed player identification by address. Now assign explicit id #'s.
48 * 3 10/09/98 2:57p Dave
49 * Starting splitting up OS stuff.
51 * 2 10/07/98 10:53a Dave
54 * 1 10/07/98 10:50a Dave
56 * 107 9/15/98 4:04p Allender
57 * added back in the -ip_addr command line switch because it needs to be
58 * in the standalone server only executable
60 * 106 9/14/98 11:28a Allender
61 * support for server bashing of address when received from client. Added
62 * a cmdline.cfg file to process command line arguments from a file
64 * 105 9/08/98 2:20p Allender
65 * temporary code to force IP address to a specific value.
67 * 104 8/21/98 1:15p Dave
68 * Put in log system hooks in useful places.
70 * 103 8/12/98 4:50p Allender
71 * fix error with new write socket code
73 * 102 8/11/98 11:45a Allender
74 * fix major problem in psnet_send where select() would block until ready
75 * to send, which for slow modems could be a long time. Doesn't block,
76 * and now correctly returns when socket is not set for writing
78 * 101 8/07/98 10:40a Allender
79 * new command line flags for starting netgames. Only starting currently
80 * works, and PXO isn't implemented yet
82 * 100 7/28/98 4:43p Allender
83 * fix bug where error on receiving of reliable data would sometimes
86 * 99 7/06/98 5:05p Allender
87 * dont use default port to send UDP data to. Use port stored in address
89 * 98 6/13/98 9:32p Mike
90 * Kill last character in file which caused "Find in Files" to report the
91 * file as "not a text file."
93 * 97 6/13/98 6:01p Hoffoss
94 * Externalized all new (or forgot to be added) strings to all the code.
96 * 96 6/13/98 3:19p Hoffoss
97 * NOX()ed out a bunch of strings that shouldn't be translated.
99 * 95 6/10/98 2:56p Dave
100 * Substantial changes to reduce bandwidth and latency problems.
102 * 94 6/05/98 9:55a Lawrance
105 * 93 5/24/98 2:17p Allender
106 * make reliable socket read all data before returning
108 * 92 5/22/98 10:54a Allender
109 * new dialog information for networking to tell user if connection type
110 * doesn't match the setup specified type
112 * 91 5/21/98 3:31p Allender
113 * more RAS stuff -- fix possible problem when unable to read data on
116 * 90 5/20/98 4:34p John
117 * fixed some bugs with rasenum connections. HAd to specify ansi versions
118 * in dll. Also, my pc returned 0 connections, before that still said
119 * there was a connection.
127 #include <windowsx.h>
132 #include <raserror.h>
140 #include "multiutil.h"
141 #include "multilag.h"
142 #include "osregistry.h"
144 #include "multi_log.h"
149 // old style packet buffering
150 // #define PSNET_BUFFER_OLD_SCHOOL
152 // sockets for IPX and TCP
154 SOCKET IPX_reliable_socket;
155 SOCKET IPX_listen_socket;
158 SOCKET TCP_reliable_socket;
159 SOCKET TCP_listen_socket;
161 // the sockets that the game will use when selecting network type
162 SOCKET Unreliable_socket = INVALID_SOCKET;
163 SOCKET Reliable_socket = INVALID_SOCKET;
164 SOCKET Listen_socket = INVALID_SOCKET;
166 BOOL Psnet_my_addr_valid;
167 net_addr Psnet_my_addr;
169 ubyte Null_address[6];
172 int Can_broadcast; // can we do broadcasting on our socket?
173 int Ipx_can_broadcast = 0;
174 int Tcp_can_broadcast = 0;
177 int Tcp_failure_code = 0;
178 int Ipx_failure_code = 0;
180 int Psnet_connection;
182 ushort Psnet_default_port;
184 // specified their internet connnection type
185 #define NETWORK_CONNECTION_NONE 1
186 #define NETWORK_CONNECTION_DIALUP 2
187 #define NETWORK_CONNECTION_LAN 3
189 // defines and variables to indicate network connection status
190 #define NETWORK_STATUS_NOT_INITIALIZED 1
191 #define NETWORK_STATUS_NO_WINSOCK 2 // winsock failed to initialize
192 #define NETWORK_STATUS_NO_PROTOCOL 3 // specified protocol doesn't appear to be loaded
193 #define NETWORK_STATUS_NO_RELIABLE 4
194 #define NETWORK_STATUS_RUNNING 5 // everything should be running
196 // defintion of structures that actually leave this machine. psnet_send give us only
197 // the data that we want to send. We will add a header onto this data (packet sequence
198 // number, possibly a checksum). We must include a 2 byte flags variable into both structure
199 // since the receiving end of this packet must know whether or not to checksum the packet.
201 // use the pack pragma to pack these structures to 2 byte aligment. Really only needed for
204 #pragma pack(push, 2)
206 // packet def for a checksum'ed packet
207 #define MAX_CHECKSUM_PACKET_SIZE 1024
208 typedef struct network_checksum_packet
213 ubyte data[MAX_CHECKSUM_PACKET_SIZE];
214 } network_checksum_packet;
216 // definition for a non-checksum packet
217 typedef struct network_packet
221 ubyte data[MAX_PACKET_SIZE];
222 } network_naked_packet;
224 // structure definition for our packet buffers
225 typedef struct network_packet_buffer
230 ubyte data[MAX_PACKET_SIZE];
231 } network_packet_buffer;
235 #define MAX_PACKET_BUFFERS 96
237 #ifdef PSNET_BUFFER_OLD_SCHOOL
238 static network_packet_buffer packet_buffers[MAX_PACKET_BUFFERS]; // buffer to hold packets sent to us
239 static short packet_free_list[MAX_PACKET_BUFFERS]; // contains id's of free packet buffers
240 static Num_packet_buffers;
241 static int Largest_packet_index = 0;
247 // variables to keep track of bytes read/written during the course of network play
250 #define PSNET_FRAME_FILTER 32
251 #define MAX_NET_STATS 32
255 net_addr addr; // stats for this address
256 int total_read; // total bytes read
257 int total_written; // total bytes read.
265 net_stats Psnet_stats[MAX_NET_STATS];
266 socket_xlate Psnet_socket_addr[MAX_NET_STATS];
268 int psnet_bytes_read_frame; // running count of bytes read this frame
269 int psnet_bytes_written_frame; // running count of bytes written this frame
271 int Psnet_bytes_read; // globally available numbers for printing on the hud
272 int Psnet_bytes_written;
274 int psnet_read_sizes[PSNET_FRAME_FILTER];
275 int psnet_write_sizes[PSNET_FRAME_FILTER];
277 int psnet_read_total;
278 int psnet_write_total;
280 int psnet_frame_count;
284 #define MAXHOSTNAME 128
286 #define MAX_RECEIVE_BUFSIZE (1<<15) // 32 K, eh?
287 #define MAX_SEND_RETRIES 20 // number of retries when sending would block
288 #define MAX_LINGER_TIME 0 // in seconds -- when lingering to close a socket
292 int psnet_same_no_port( net_addr * a1, net_addr * a2 );
294 // do stats for a particular address. num_bytes is the number of bytes either read or
295 // written (depending on the read flag. read flag is true when reading, 0 when writing
296 void psnet_do_net_stats( net_addr *addr, int num_bytes, int read )
300 for ( i = 0; i < MAX_NET_STATS; i++ ) {
301 if ( !Psnet_stats[i].in_use )
303 if ( addr && psnet_same_no_port(&Psnet_stats[i].addr, addr) )
307 if ( i == MAX_NET_STATS ) {
308 // find the first NULL entry
309 for ( i = 0; i < MAX_NET_STATS; i++ ) {
310 if ( !Psnet_stats[i].in_use )
313 if ( i == MAX_NET_STATS ) {
314 Int3(); // we should always have a slot
317 Psnet_stats[i].addr = *addr;
318 Psnet_stats[i].in_use = 1;
321 Psnet_stats[i].total_read += num_bytes;
323 Psnet_stats[i].total_written += num_bytes;
326 // returns the stats for the given network address. returns 1 when (i.e. net_addr was found),
327 // 0 otherwise. total read and total written are returned in the parameters
328 int psnet_get_stats( net_addr *addr, int *tr, int *tw )
332 for ( i = 0; i < MAX_NET_STATS; i++ ) {
333 if ( !Psnet_stats[i].in_use )
336 if ( addr && psnet_same_no_port(&Psnet_stats[i].addr, addr) )
340 if ( i == MAX_NET_STATS )
343 *tr = Psnet_stats[i].total_read;
344 *tw = Psnet_stats[i].total_written;
349 void psnet_stats_init()
353 for ( i = 0; i < MAX_NET_STATS; i++ ) {
354 Psnet_stats[i].in_use = 0;
355 Psnet_stats[i].total_read = 0;
356 Psnet_stats[i].total_written = 0;
357 Psnet_socket_addr[i].socket = INVALID_SOCKET;
363 #define NETWORK_STATUS_NOT_INITIALIZED 1
364 #define NETWORK_STATUS_NO_WINSOCK 2 // winsock failed to initialize
365 #define NETWORK_STATUS_NO_TCPIP 3 // TCP/IP doesn't appear to be loaded
366 #define NETWORK_STATUS_RUNNING 4 // everything should be running
368 // function called from high level FreeSpace code to determine the status of the networking
369 // code returns one of a handful of macros
370 int psnet_get_network_status()
372 // first case is when "none" is selected
373 if ( Psnet_connection == NETWORK_CONNECTION_NONE ) {
374 return NETWORK_ERROR_NO_TYPE;
377 // first, check the connection status of the network
378 if ( Network_status == NETWORK_STATUS_NO_WINSOCK )
379 return NETWORK_ERROR_NO_WINSOCK;
381 if ( Network_status == NETWORK_STATUS_NO_TCPIP )
382 return NETWORK_ERROR_NO_TCPIP;
384 // network is running -- be sure that the RAS people know to connect if they currently cannot.
386 if ( Psnet_connection == NETWORK_CONNECTION_DIALUP ) {
387 // if on a dialup connection, be sure that RAS is active.
388 if ( !Ras_connected ) {
389 return NETWORK_ERROR_CONNECT_TO_ISP;
391 } else if ( Psnet_connection == NETWORK_CONNECTION_LAN ) {
392 // if on a LAN, and they have a dialup connection active, return error to indicate that they need
393 // to pick the right connection type
394 if ( Ras_connected ) {
395 return NETWORK_ERROR_LAN_AND_RAS;
398 return NETWORK_ERROR_NONE;
401 DWORD (__stdcall *pRasEnumConnections)(LPRASCONN lprasconn, LPDWORD lpcb, LPDWORD lpcConnections) = NULL;
402 DWORD (__stdcall *pRasGetConnectStatus)(HRASCONN hrasconn, LPRASCONNSTATUS lprasconnstatus ) = NULL;
403 DWORD (__stdcall *pRasGetProjectionInfo)(HRASCONN hrasconn, RASPROJECTION rasprojection, LPVOID lpprojection, LPDWORD lpcb ) = NULL;
405 // functions to get the status of a RAS connection
406 void psnet_ras_status()
409 unsigned long size, num_connections, i;
410 RASCONN rasbuffer[25];
411 HINSTANCE ras_handle;
415 // first, call a LoadLibrary to load the RAS api
416 ras_handle = LoadLibrary( NOX("rasapi32.dll") );
417 if ( ras_handle == NULL ) {
421 pRasEnumConnections = (DWORD (__stdcall *)(LPRASCONN, LPDWORD, LPDWORD))GetProcAddress(ras_handle, NOX("RasEnumConnectionsA"));
422 if (!pRasEnumConnections) {
423 FreeLibrary( ras_handle );
426 pRasGetConnectStatus = (DWORD (__stdcall *)(HRASCONN, LPRASCONNSTATUS))GetProcAddress(ras_handle, NOX("RasGetConnectStatusA"));
427 if (!pRasGetConnectStatus) {
428 FreeLibrary( ras_handle );
431 pRasGetProjectionInfo = (DWORD (__stdcall *)(HRASCONN, RASPROJECTION, LPVOID, LPDWORD))GetProcAddress(ras_handle, NOX("RasGetProjectionInfoA"));
432 if (!pRasGetProjectionInfo) {
433 FreeLibrary( ras_handle );
437 size = sizeof(rasbuffer);
438 rasbuffer[0].dwSize = sizeof(RASCONN);
440 rval = pRasEnumConnections( rasbuffer, &size, &num_connections );
442 FreeLibrary( ras_handle );
446 // JAS: My computer gets to this point, but I have no RAS connections,
448 if ( num_connections < 1 ) {
449 nprintf(("Network", "Found no connections\n" ));
450 FreeLibrary( ras_handle );
454 nprintf(("Network", "Found %d connections\n", num_connections));
456 for (i = 0; i < num_connections; i++ ) {
457 RASCONNSTATUS status;
461 nprintf(("Network", "Connection %d:\n", i));
462 nprintf(("Network", "Entry Name: %s\n", rasbuffer[i].szEntryName));
463 nprintf(("Network", "Device Type: %s\n", rasbuffer[i].szDeviceType));
464 nprintf(("Network", "Device Name: %s\n", rasbuffer[i].szDeviceName));
466 // get the connection status
467 status.dwSize = sizeof(RASCONNSTATUS);
468 rval = pRasGetConnectStatus(rasbuffer[i].hrasconn, &status);
470 FreeLibrary( ras_handle );
474 nprintf(("Network", "\tStatus: %s\n", (status.rasconnstate==RASCS_Connected)?"Connected":"Not Connected"));
476 // get the projection informatiom
477 size = sizeof(projection);
478 projection.dwSize = size;
479 rval = pRasGetProjectionInfo(rasbuffer[i].hrasconn, RASP_PppIp, &projection, &size );
481 FreeLibrary( ras_handle );
485 printf(("Network", "\tIP Address: %s\n", projection.szIpAddress));
490 FreeLibrary( ras_handle );
493 // -------------------------------------------------------------------------------------------------
494 // netmisc_calc_checksum() calculates the checksum of a block of memory.
497 ushort psnet_calc_checksum( void * vptr, int len )
499 ubyte * ptr = (ubyte *)vptr;
500 unsigned int sum1,sum2;
506 if (sum1 >= 255 ) sum1 -= 255;
511 return (unsigned short)((sum1<<8)+ sum2);
514 // -------------------------------------------------------------------------------------------------
515 // psnet_set_socket_mode()
519 uint psnet_set_socket_mode(SOCKET sock_id, int opt, BOOL toggle)
521 return (setsockopt(sock_id, SOL_SOCKET, opt, (char *)&toggle, sizeof(toggle)));
525 // -------------------------------------------------------------------------------------------------
526 // sock_get_ip() returns the IP address of this computer.
532 char LclHost[MAXHOSTNAME];
534 struct sockaddr_in LclAddr;
535 struct sockaddr_in RmtAddr;
539 // Init local address to zero
540 LclAddr.sin_addr.s_addr = INADDR_ANY;
542 // Get the local host name
543 nRet = gethostname(LclHost, MAXHOSTNAME );
544 if (nRet != SOCKET_ERROR ) {
545 // Resolve host name for local address
546 Hostent = gethostbyname((char *)LclHost);
548 LclAddr.sin_addr.s_addr = *((u_long FAR *)(Hostent->h_addr));
551 return LclAddr.sin_addr.s_addr;
557 // psnet_get_ip() attempts to get the local IP address of this machine
558 // returns 0 on failure, and 1 on success
559 int psnet_get_ip( SOCKET s )
562 struct sockaddr_in local_addr;
564 if ( Psnet_my_addr_valid ){
568 memset(&local_addr, 0, sizeof(struct sockaddr_in));
569 len = sizeof(struct sockaddr_in);
570 rval = getsockname(s, (struct sockaddr *)&local_addr, &len );
571 if ( rval == SOCKET_ERROR )
574 // now we should have an IP address of this machine.
575 memcpy(Psnet_my_addr.addr, &(local_addr.sin_addr), 4);
576 Psnet_my_addr.port = ntohs(local_addr.sin_port);
578 Psnet_my_addr_valid = 1;
582 // -------------------------------------------------------------------------------------------------
589 #ifndef PSNET_RELIABLE_OLD_SCHOOL
590 psnet_reliable_close();
593 if ( Network_status != NETWORK_STATUS_RUNNING )
596 WSACancelBlockingCall();
598 if ( TCP_listen_socket != INVALID_SOCKET ) {
599 shutdown( TCP_listen_socket, 1 );
600 closesocket( TCP_listen_socket );
603 if ( TCP_reliable_socket != INVALID_SOCKET ) {
604 shutdown( TCP_reliable_socket, 1 );
605 closesocket( TCP_reliable_socket );
608 if ( TCP_socket != INVALID_SOCKET ) {
609 shutdown( TCP_socket, 1 );
610 closesocket( TCP_socket );
614 //Warning( LOCATION, "Error closing wsock!\n" );
617 Network_status = NETWORK_STATUS_NOT_INITIALIZED;
620 // function to initialize a reliable socket. All it does is call the socket() command.
621 // returns 1 on success, 0 on failure.
622 int psnet_init_stream( SOCKET *s, int type )
628 sock = socket(AF_IPX,SOCK_STREAM,NSPROTO_SPX);
629 if ( sock == INVALID_SOCKET )
634 sock = socket(AF_INET,SOCK_STREAM,0);
635 if ( sock == INVALID_SOCKET )
649 // called by psnet_init to initialize the listen socket used by a host/server
650 int psnet_init_reliable(ushort port, int should_listen, int type)
652 SOCKET sock = 0; // JAS: Get rid of optimized warning
653 struct sockaddr_in sockaddr; // UDP/TCP socket structure
654 SOCKADDR_IPX ipx_addr; // IPX socket structure
656 // set up the reliable TCP transport socket
657 if ( !psnet_init_stream(&sock, type) ) {
658 nprintf(("Network", "Unable to initialize reliable socket on port %d (%d)!\n" , port, WSAGetLastError() ));
659 return INVALID_SOCKET;
662 // bind the socket to the port
665 memset(&ipx_addr, 0, sizeof(SOCKADDR_IPX));
666 ipx_addr.sa_socket = htons( port );
667 ipx_addr.sa_family = AF_IPX;
668 if (bind(sock, (struct sockaddr *)&ipx_addr, sizeof(SOCKADDR_IPX)) == SOCKET_ERROR) {
669 nprintf(("Network", "Unable to bind reliable socket on port %d (%d)!\n" , port, WSAGetLastError() ));
670 return INVALID_SOCKET;
675 memset( &sockaddr, 0, sizeof(struct sockaddr_in) );
676 sockaddr.sin_family = AF_INET;
677 sockaddr.sin_addr.s_addr = INADDR_ANY; //fill in with our IP
678 sockaddr.sin_port = htons( port );
679 if ( bind(sock, (struct sockaddr*)&sockaddr, sizeof (sockaddr)) == SOCKET_ERROR) {
680 nprintf(("Network", "Unable to bind reliable socket on port %d (%d)!\n" , port, WSAGetLastError() ));
681 return INVALID_SOCKET;
687 return INVALID_SOCKET;
691 // set up the listen on the Reliable_socket port
692 if ( should_listen && listen(sock, 5) ) {
693 nprintf(("Network", "Unable to listen on Listen Socket (%d)!\n" , WSAGetLastError() ));
694 return INVALID_SOCKET;
697 // make any reliable sockets which we create that aren't listening non-blocking sockets
698 if ( !should_listen ) {
703 error = ioctlsocket( sock, FIONBIO, &arg );
704 if ( error == SOCKET_ERROR ) {
705 nprintf(("Network", "Unable to make reliable socket non-blocking -- %d", WSAGetLastError() ));
706 return INVALID_SOCKET;
709 // set the reuse option
710 if ( psnet_set_socket_mode(sock, SO_REUSEADDR, 1) == SOCKET_ERROR ) {
711 error = WSAGetLastError();
712 nprintf(("Network", "Error setting socket to reuse address -- %d\n", error));
720 void psnet_socket_options( SOCKET sock )
723 int ret, cursize, cursizesize, bufsize, trysize;
725 // Set the mode of the socket to allow broadcasting. We need to be able to broadcast
726 // when a game is searched for in IPX mode.
728 if(setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char *)&broadcast, sizeof(broadcast) )){
734 // try and increase the size of my receive buffer
735 bufsize = MAX_RECEIVE_BUFSIZE;
737 // set the current size of the receive buffer
738 cursizesize = sizeof(int);
739 getsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char *)&cursize, &cursizesize);
740 for ( trysize = bufsize; trysize >= cursize; trysize >>= 1 ) {
741 ret = setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char *)&trysize, sizeof(trysize));
742 if ( ret == SOCKET_ERROR ) {
745 wserr = WSAGetLastError();
746 if ( (wserr == WSAENOPROTOOPT) || (wserr == WSAEINVAL) )
751 getsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char *)&cursize, &cursizesize);
752 nprintf(("Network", "Receive buffer set to %d\n", cursize));
754 // set the current size of the send buffer
755 cursizesize = sizeof(int);
756 getsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *)&cursize, &cursizesize);
757 for ( trysize = bufsize; trysize >= cursize; trysize >>= 1 ) {
758 ret = setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *)&trysize, sizeof(trysize));
759 if ( ret == SOCKET_ERROR ) {
762 wserr = WSAGetLastError();
763 if ( (wserr == WSAENOPROTOOPT) || (wserr == WSAEINVAL) )
768 getsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *)&cursize, &cursizesize);
769 nprintf(("Network", "Send buffer set to %d\n", cursize));
773 // psnet_init called at game startup time and initializes all sockets that the game might use (i.e. for both
775 void psnet_init( int protocol, int port_num )
777 char *internet_connection;
780 // UDP/TCP socket structure
781 struct sockaddr_in sockaddr;
783 // IPX socket structure
784 //SOCKADDR_IPX ipx_addr;
786 #if defined(DEMO) || defined(OEM_BUILD) // not for FS2_DEMO
790 // GAME PORT INITIALIZATION STUFF
791 if ( Network_status == NETWORK_STATUS_RUNNING )
794 internet_connection = os_config_read_string(NULL, "NetworkConnection", "none");
795 if ( !SDL_strcasecmp(internet_connection, NOX("dialup")) ) {
796 Psnet_connection = NETWORK_CONNECTION_DIALUP;
797 } else if ( !SDL_strcasecmp(internet_connection, NOX("lan")) ) {
798 Psnet_connection = NETWORK_CONNECTION_LAN;
800 Psnet_connection = NETWORK_CONNECTION_NONE;
803 Network_status = NETWORK_STATUS_NO_WINSOCK;
804 if (WSAStartup(0x101, &wsa_data )){
808 // get the port for running this game on. Be careful that it cannot be out of bounds
809 Psnet_default_port = DEFAULT_GAME_PORT;
810 if ( (port_num > 1023) && (port_num < USHRT_MAX) ) {
811 Psnet_default_port = (ushort)port_num;
814 #ifndef PSNET_RELIABLE_OLD_SCHOOL
815 if(!psnet_reliable_init()){
816 nprintf(("Network","PSNET RELIABLE : init failed - no networking available!\n"));
821 // initialize TCP now
822 TCP_socket = INVALID_SOCKET;
823 TCP_reliable_socket = INVALID_SOCKET;
824 TCP_listen_socket = INVALID_SOCKET;
826 Network_status = NETWORK_STATUS_NO_TCPIP;
827 TCP_socket = socket( AF_INET, SOCK_DGRAM, 0 );
828 if ( TCP_socket == INVALID_SOCKET ) {
829 Tcp_failure_code = WSAGetLastError();
830 nprintf(("Network", "Error on TCP startup %d\n", Tcp_failure_code));
835 memset(&sockaddr,0,sizeof(struct sockaddr_in));
836 sockaddr.sin_family = AF_INET;
838 sockaddr.sin_addr.s_addr = INADDR_ANY; //fill in with our IP
840 sockaddr.sin_port = htons( Psnet_default_port );
841 if ( bind(TCP_socket, (struct sockaddr*)&sockaddr, sizeof (sockaddr)) == SOCKET_ERROR) {
842 Tcp_failure_code = WSAGetLastError();
843 nprintf(( "Network", "Couldn't bind TCP socket (%d)! Invalidating TCP\n", Tcp_failure_code ));
847 #ifdef PSNET_RELIABLE_OLD_SCHOOL
848 // set up reliable socket (using SPX).
849 TCP_reliable_socket = psnet_init_reliable( 0, 0, NET_TCP );
850 if ( TCP_reliable_socket == INVALID_SOCKET ) {
851 Tcp_failure_code = WSAGetLastError();
852 nprintf(( "Network", "Couldn't initialize TCP reliable socket (OLD SCHOOL) (%d)! Invalidating TCP\n", Tcp_failure_code ));
856 TCP_listen_socket = psnet_init_reliable( (u_short)(Psnet_default_port-1), 1, NET_TCP );
857 if ( TCP_listen_socket == INVALID_SOCKET ) {
858 Tcp_failure_code = WSAGetLastError();
859 nprintf(( "Network", "Couldn't initialize TCP listen socket (OLD SCHOOL) (%d)! Invalidating TCP\n", Tcp_failure_code ));
864 psnet_socket_options( TCP_socket );
865 Tcp_can_broadcast = Can_broadcast;
868 // fire up a second UDP socket for "reliable" transport
869 #ifndef PSNET_RELIABLE_OLD_SCHOOL
870 TCP_reliable_socket = socket( AF_INET, SOCK_DGRAM, 0 );
871 if ( TCP_reliable_socket != INVALID_SOCKET ) {
873 memset(&sockaddr,0,sizeof(struct sockaddr_in));
874 sockaddr.sin_family = AF_INET;
876 sockaddr.sin_addr.s_addr = INADDR_ANY; //fill in with our IP
877 //unsigned long my_ip = sock_get_ip();
878 //memcpy(&sockaddr.sin_addr.s_addr,&my_ip,sizeof(uint));
880 sockaddr.sin_port = htons( (ushort)(port+1) );
881 if ( bind(TCP_reliable_socket, (struct sockaddr*)&sockaddr, sizeof (sockaddr)) == SOCKET_ERROR) {
882 nprintf(( "Network", "Couldn't bind TCP socket (%d)! Invalidating TCP\n", WSAGetLastError() ));
886 psnet_socket_options( TCP_reliable_socket );
893 Network_status = NETWORK_STATUS_RUNNING;
895 nprintf(("Network","TCP Initialized\n"));
897 // with TCP initialized, see if the RAS services are installed
901 psnet_frame_int = -1; // for counting bytes per frame
904 #ifdef PSNET_BUFFER_OLD_SCHOOL
908 // initialize the packet buffer stuff. We use an array (the packet_free_list) to determine
909 // which of the packet buffers we can use next.
911 for (i=0; i<MAX_PACKET_BUFFERS; i++ ) {
912 packet_buffers[i].sequence_number = -1;
913 packet_free_list[i] = (short)i;
915 Num_packet_buffers = 0;
916 Largest_packet_index = 0;
918 // initialize the new buffering system
923 #define MAX_TMPBUF_SIZE 1024
925 #ifdef PSNET_RELIABLE_OLD_SCHOOL
926 // function to shutdown and close the given socket. It takes a couple of things into consideration
927 // when closing, such as possibly reiniting reliable sockets if they are closed here.
928 void psnet_rel_close_socket( PSNET_SOCKET *p_sockp )
934 sockp = (SOCKET *)p_sockp;
936 if ( *sockp == INVALID_SOCKET )
940 if ( *sockp == IPX_reliable_socket )
941 nprintf(("Network", "Closing my reliable IPX socket\n"));
942 else if ( *sockp == TCP_reliable_socket )
943 nprintf(("network", "Closing my relibale TCP socket\n"));
945 nprintf(("Network", "Closing client's reliable socket\n"));
948 // make the socket blocking
949 //unsigned long val = 0;
950 //rval = ioctlsocket(*sockp,FIONBIO,&val);
951 //if ( rval == SOCKET_ERROR ) {
952 // error = WSAGetLastError();
953 // nprintf(("Network", "Error %d when trying to make reliable socket blocking.\n", error));
956 // set the socket to linger with a timeout of 0
960 rval = setsockopt(*sockp,SOL_SOCKET,SO_LINGER,(char*)&l_val,sizeof(linger));
961 if ( rval == SOCKET_ERROR ) {
962 error = WSAGetLastError();
963 nprintf(("Network", "Error %d when trying to set linger value.\n", error));
966 // see if this socket is my Reliable_socket. If so, I will have to reinitialize it!
968 if ( *sockp == IPX_reliable_socket )
969 reinit_type = NET_IPX;
970 else if ( *sockp == TCP_reliable_socket )
971 reinit_type = NET_TCP;
974 rval = shutdown( *sockp, 2); // shut the whole damn thing down.
975 if ( rval == SOCKET_ERROR ) {
976 error = WSAGetLastError();
977 nprintf(("Network", "Error %d on socket shutdown\n", error));
981 shutdown( *sockp, 1 );
983 while ( rval && (rval != SOCKET_ERROR) ) {
984 char tmp_buf[MAX_TMPBUF_SIZE];
986 rval = recv( *sockp, tmp_buf, MAX_TMPBUF_SIZE, 0 );
987 if ( rval == SOCKET_ERROR ) {
990 error = WSAGetLastError();
991 if ( error == WSAEWOULDBLOCK )
996 rval = closesocket( *sockp );
997 if ( rval == SOCKET_ERROR ) {
998 error = WSAGetLastError();
999 nprintf(("Network", "Error %d on closing socket\n", error ));
1002 *sockp = INVALID_SOCKET;
1004 // see if we need to reinitialize
1005 if ( reinit_type != -1 ) {
1008 port = Psnet_default_port;
1009 if ( reinit_type == NET_IPX ){
1010 IPX_reliable_socket = psnet_init_reliable( 0, 0, NET_IPX);
1011 Reliable_socket = IPX_reliable_socket;
1013 else if ( reinit_type == NET_TCP){
1014 TCP_reliable_socket = psnet_init_reliable( 0, 0, NET_TCP);
1015 Reliable_socket = TCP_reliable_socket;
1020 // function to shutdown and close the given socket. It takes a couple of things into consideration
1021 // when closing, such as possibly reiniting reliable sockets if they are closed here.
1022 void psnet_close_socket( PSNET_SOCKET *p_sockp )
1026 // copy the address to be removed
1027 memcpy(&remove,&((net_addr*)(*p_sockp)),sizeof(net_addr));
1029 // remove it from the reliable address list
1030 psnet_reliable_notify_drop_addr(&remove);
1032 // invalidate the passed in "socket"
1037 // function to check the status of the reliable socket and try to re-initialize it if necessary.
1038 // win95 seems to have trouble doing a reinit of the socket immediately after close, so this
1039 // function exists to check the status, and reinitialize if we need to
1040 int psnet_rel_check()
1042 // if our Reliable_socket is valid, simply return true to indicate all is well.
1043 if ( Reliable_socket != INVALID_SOCKET )
1046 // based on our protocol type, try to reinitialize the socket we need.
1047 switch( Socket_type ) {
1050 IPX_reliable_socket = psnet_init_reliable( 0, 0, NET_IPX);
1051 Reliable_socket = IPX_reliable_socket;
1055 TCP_reliable_socket = psnet_init_reliable( 0, 0, NET_TCP);
1056 Reliable_socket = TCP_reliable_socket;
1061 // return our status.
1062 if ( Reliable_socket == INVALID_SOCKET )
1068 // this function is called from a high level at FreeSpace to set the protocol that the user wishes to use
1069 int psnet_use_protocol( int protocol )
1072 SOCKADDR_IPX ipx_addr;
1074 // zero out my address
1075 Psnet_my_addr_valid = 0;
1076 memset( &Psnet_my_addr, 0, sizeof(Psnet_my_addr) );
1078 // wait until we choose a protocol to determine if we can broadcast
1081 switch ( protocol ) {
1085 // assign the IPX_* sockets to the socket values used elsewhere
1086 Unreliable_socket = IPX_socket;
1087 Reliable_socket = IPX_reliable_socket;
1088 Listen_socket = IPX_listen_socket;
1090 Can_broadcast = Ipx_can_broadcast;
1092 nprintf(("Network","Psnet : IPX broadcast\n"));
1095 // get the socket name for the IPX_socket, and put it into My_addr
1096 len = sizeof(SOCKADDR_IPX);
1097 if ( getsockname(IPX_socket, (struct sockaddr *)&ipx_addr, &len) == SOCKET_ERROR ) {
1098 nprintf(("Network", "Unable to get sock name for IPX unreliable socket (%d)\n", WSAGetLastError() ));
1102 memcpy(Psnet_my_addr.net_id, ipx_addr.sa_netnum, 4);
1103 memcpy(Psnet_my_addr.addr, ipx_addr.sa_nodenum, 6);
1104 Psnet_my_addr.port = DEFAULT_GAME_PORT;
1106 nprintf(("Network","Psnet using - NET_IPX\n"));
1110 if ( Network_status != NETWORK_STATUS_RUNNING )
1113 // assign the TCP_* sockets to the socket values used elsewhere
1114 Unreliable_socket = TCP_socket;
1115 Reliable_socket = TCP_reliable_socket;
1116 Listen_socket = TCP_listen_socket;
1118 Can_broadcast = Tcp_can_broadcast;
1120 nprintf(("Network","Psnet : TCP broadcast\n"));
1123 nprintf(("Network","Psnet using - NET_TCP\n"));
1131 Psnet_my_addr.type = protocol;
1132 Socket_type = protocol;
1137 #define MAX_CONNECT_TRIES 10
1139 // attacmpt to connect() to the server's tcp socket. socket parameter is simply assigned to the
1140 // Reliable_socket socket created in psnet_init
1141 void psnet_rel_connect_to_server( PSNET_SOCKET *psocket, net_addr *server_addr)
1143 struct sockaddr_in sockaddr; // UDP/TCP socket structure
1144 SOCKADDR_IPX ipx_addr; // IPX socket structure
1145 struct sockaddr *addr; // pointer to struct sockaddr to make coding easier
1149 int name_length, val;
1151 memset(iaddr, 0x00, 6);
1152 memcpy(iaddr, server_addr->addr, 6);
1153 port = (u_short)(server_addr->port - 1);
1155 socket = (SOCKET *)psocket;
1157 switch( Socket_type ) {
1159 ipx_addr.sa_family = AF_IPX;
1160 memcpy(ipx_addr.sa_nodenum, iaddr, 6);
1161 memcpy(ipx_addr.sa_netnum, server_addr->net_id, 4);
1162 ipx_addr.sa_socket = htons(port);
1163 addr = (struct sockaddr *)&ipx_addr;
1164 name_length = sizeof(ipx_addr);
1168 sockaddr.sin_family = AF_INET;
1169 memcpy(&sockaddr.sin_addr.s_addr, iaddr, 4);
1170 sockaddr.sin_port = htons(port);
1171 addr = (struct sockaddr *)&sockaddr;
1172 name_length = sizeof(sockaddr);
1181 ml_string(NOX("Attempting to perform reliable TCP connect to server"));
1183 // connect this guys Reliable_socket to the socket parameter passed in
1184 *socket = INVALID_SOCKET;
1185 val = connect(Reliable_socket, addr, name_length);
1187 // I suppose that we could have a valid socket right away
1188 if ( val != SOCKET_ERROR ) {
1189 *socket = Reliable_socket;
1193 error = WSAGetLastError();
1194 if ( error == WSAEWOULDBLOCK ) { // use select to find out when socket is writeable
1195 int is_set, num_tries;
1197 struct timeval timeout;
1199 // call select -- and return if an error leaving our connection to the client invalid
1203 FD_SET( Reliable_socket, &wfds );
1205 timeout.tv_usec = 500000; //500000 micro seconds is 1/2 second
1207 is_set = select( -1, NULL, &wfds, NULL, &timeout);
1209 is_set = select( Reliable_socket+1, NULL, &wfds, NULL, &timeout);
1211 // check for error on select first
1212 if ( is_set == SOCKET_ERROR ) {
1213 nprintf(("Network", "Error on select for connect %d\n", WSAGetLastError() ));
1215 } else if (is_set) { // if set, then we have connection, move forward
1218 SDL_Delay(10); // sleep for 10 ms and try again
1221 } while ( num_tries < MAX_CONNECT_TRIES );
1223 if ( num_tries == MAX_CONNECT_TRIES )
1226 *socket = Reliable_socket;
1229 nprintf(("Network", "Connecting with server failed %d\n", error ));
1230 *socket = INVALID_SOCKET;
1234 // if we have a connection, get my address from getsockname
1235 if ( *socket == Reliable_socket ) {
1236 if ( !psnet_get_ip(Reliable_socket) ) {
1237 *socket = INVALID_SOCKET;
1244 void psnet_calc_bytes_per_frame()
1249 // -------------------------------------------------------------------------------------------------
1254 int psnet_same_no_port( net_addr * a1, net_addr * a2 )
1256 if ( !memcmp(a1->addr, a2->addr, 6) )
1261 int psnet_same( net_addr * a1, net_addr * a2 )
1263 return psnet_same_no_port( a1, a2 );
1265 if ( !memcmp(a1->addr, a2->addr, 6) && a1->port == a2->port)
1271 // -------------------------------------------------------------------------------------------------
1276 char* psnet_addr_to_string( char * text, const int max_textlen, net_addr * address )
1279 if ( Network_status != NETWORK_STATUS_RUNNING ) {
1280 SDL_strlcpy( text, XSTR("[no networking]",910), max_textlen );
1286 switch ( address->type ) {
1288 SDL_snprintf(text, max_textlen, "%x %x %x %x: %x %x %x %x %x %x", address->net_id[0],
1301 memcpy(&temp_addr.s_addr, address->addr, 4);
1302 SDL_strlcpy( text, inet_ntoa(temp_addr), max_textlen );
1315 // -------------------------------------------------------------------------------------------------
1316 // psnet_undescribe()
1320 void psnet_string_to_addr( net_addr * address, char * text, const int max_textlen )
1323 char str[255], *c, *port;
1326 if ( Network_status != NETWORK_STATUS_RUNNING ) {
1327 SDL_strlcpy( text, XSTR("[no networking]",910), max_textlen );
1331 // copy the text string to local storage to look for ports
1332 SDL_assert( strlen(text) < 255 );
1333 SDL_strlcpy(str, text, sizeof(str));
1334 c = strrchr(str, ':');
1341 switch ( address->type ) {
1343 Int3(); // no support for this yet
1347 addr.s_addr = inet_addr(str);
1348 // if we get INADDR_NONE returns, then we need to try and resolve the host
1350 if ( addr.s_addr == INADDR_NONE ) {
1351 he = gethostbyname( str );
1352 // returns a non-null pointer if successful, so get the address
1354 addr.s_addr = ((in_addr *)(he->h_addr))->s_addr; // this is the address in network byte order
1356 addr.s_addr = INADDR_NONE;
1360 memset(address->addr, 0x00, 6);
1361 memcpy(address->addr, &addr.s_addr, 4);
1363 address->port = (ushort)(atoi(port));
1374 // psnet_get_socket_data() will get data out of the socket and stuff it into the packet_buffers
1375 // The original psnet_get() now calls this function, then determines which of the packet buffers
1376 // to package up and use
1377 void psnet_get_socket_data(SOCKET socket, int flags = PSNET_FLAG_RAW)
1379 struct sockaddr_in ip_addr; // UDP/TCP socket structure
1380 SOCKADDR_IPX ipx_addr; // IPX socket structure
1383 int read_len, from_len;
1385 network_checksum_packet packet_read;
1386 network_checksum_packet packet_data;
1388 // clear the addresses to remove compiler warnings
1389 memset(&ip_addr, 0, sizeof(struct sockaddr_in));
1390 memset(&ipx_addr, 0, sizeof(SOCKADDR_IPX));
1392 if ( Network_status != NETWORK_STATUS_RUNNING ) {
1393 nprintf(("Network","Network ==> socket not inited in psnet_get\n"));
1398 #ifdef PSNET_BUFFER_OLD_SCHOOL
1400 // if there are no more packet buffers that we can use, then we must bail here before reading
1402 if ( Num_packet_buffers >= MAX_PACKET_BUFFERS ) {
1403 nprintf(("Network", "Packet buffer overrun in psnet_get()\n"));
1408 // check if there is any data on the socket to be read. The amount of data that can be
1409 // atomically read is stored in len.
1412 FD_SET( socket, &rfds );
1414 timeout.tv_usec = 0;
1417 if ( select( -1, &rfds, NULL, NULL, &timeout) == SOCKET_ERROR ) {
1419 if ( select( socket+1, &rfds, NULL, NULL, &timeout) == SOCKET_ERROR ) {
1421 nprintf(("Network", "Error %d doing a socket select on read\n", WSAGetLastError()));
1425 // if the read file descriptor is not set, then bail!
1426 if ( !FD_ISSET(socket, &rfds ) )
1429 // get data off the socket and process
1430 read_len = SOCKET_ERROR;
1431 switch ( Socket_type ) {
1433 from_len = sizeof(SOCKADDR_IPX);
1434 if(flags & PSNET_FLAG_RAW){
1435 read_len = recvfrom( socket, (char*)packet_read.data, MAX_PACKET_SIZE, 0, (struct sockaddr*)&ipx_addr, &from_len );
1437 read_len = recvfrom( socket, (char *)&packet_read, sizeof(packet_data), 0, (struct sockaddr*)&ipx_addr, &from_len );
1442 from_len = sizeof(struct sockaddr_in);
1443 if(flags & PSNET_FLAG_RAW){
1444 read_len = recvfrom( socket, (char*)packet_read.data, MAX_PACKET_SIZE, 0, (struct sockaddr*)&ip_addr, &from_len );
1446 read_len = recvfrom( socket, (char *)&packet_read, sizeof(packet_data), 0, (struct sockaddr*)&ip_addr, &from_len );
1455 // set the from_addr for storage into the packet buffer structure
1456 from_addr.type = Socket_type;
1458 switch ( Socket_type ) {
1460 if(socket == Reliable_socket){
1461 from_addr.port = Psnet_default_port;
1463 from_addr.port = ntohs( ipx_addr.sa_socket );
1465 memcpy(from_addr.addr, ipx_addr.sa_nodenum, 6 );
1466 memcpy(from_addr.net_id, ipx_addr.sa_netnum, 4 );
1470 if(socket == Reliable_socket){
1471 from_addr.port = Psnet_default_port;
1473 from_addr.port = ntohs( ip_addr.sin_port );
1475 memset(from_addr.addr, 0x00, 6);
1476 memcpy(from_addr.addr, &ip_addr.sin_addr.S_un.S_addr, 4);
1484 if ( read_len == SOCKET_ERROR ) {
1485 int x = WSAGetLastError();
1486 nprintf(("Network", "Read error on socket. Winsock error %d \n", x));
1490 #ifndef PSNET_RELIABLE_OLD_SCHOOL
1492 // now we check to see if this is a reliable packet, and act accordindly
1493 if(socket == Reliable_socket){
1494 // this function processes the incoming packet, and determines if the system should continue to process the data
1495 shave_size = psnet_reliable_should_process(&from_addr,packet_read.data,read_len);
1499 // copy in from data+2, so we skip the reliable data header
1500 memcpy(packet_data.data,packet_read.data + shave_size,read_len);
1502 // subtract out the size of the reliable header
1503 read_len -= shave_size;
1506 memcpy(packet_data.data,packet_read.data,read_len);
1509 memcpy(packet_data.data,packet_read.data,read_len);
1512 #ifdef PSNET_BUFFER_OLD_SCHOOL
1516 // if we had no error reading from the socket, then determine if we need to calculate a
1517 // checksum on the packet
1518 if ( !(flags & PSNET_FLAG_RAW) && (packet_data.flags & PSNET_FLAG_CHECKSUM) ) {
1521 // calculate the size of the data that is actual real data
1522 len = read_len - (sizeof(packet_data) - MAX_CHECKSUM_PACKET_SIZE);
1523 checksum = psnet_calc_checksum( packet_data.data, len );
1524 if ( checksum != packet_data.checksum ) {
1525 nprintf(("Network", "bad checksum on incoming packet -- discarding\n"));
1528 data = packet_data.data;
1529 packet_id = packet_data.sequence_number;
1531 network_naked_packet *packet;
1533 // just read in the raw socket data and length
1534 if(flags & PSNET_FLAG_RAW){
1535 data = packet_data.data;
1540 // we don't have a checksum packet. cast the data to the naked packet type and
1541 // copy it over to passed parameters
1542 packet = (network_naked_packet *)&packet_data;
1544 len = read_len - (sizeof(network_naked_packet) - MAX_PACKET_SIZE);
1545 data = packet->data;
1547 packet_id = packet->sequence_number;
1551 // look at the sequence number compared to what we last received
1552 if ( Last_packet_id > -1 ) {
1553 if ( packet_id != (Last_packet_id+1) ) {
1554 //if ( packet_id < Last_packet_id )
1555 // nprintf(("network", "packet %d came in delayed (last id was %d\n", packet_id, Last_packet_id));
1556 //else if ( packet_id > (Last_packet_id+1) )
1557 // nprintf(("Network", "missed %d packet(s). last id %d. This id %d\n", (packet_id - Last_packet_id), Last_packet_id, packet_id));
1560 Last_packet_id = packet_id;
1563 psnet_do_net_stats( &from_addr, read_len, 1 );
1564 psnet_bytes_read_frame += read_len;
1567 // put all of the data (length, who from, etc.) into the next available packet buffer
1568 // slot. We should be assured of a slot here because of the check at the beginning
1569 // of the while loop
1570 SDL_assert ( Num_packet_buffers < MAX_PACKET_BUFFERS );
1571 id = packet_free_list[ Num_packet_buffers++ ];
1572 if (id > Largest_packet_index ) Largest_packet_index = id;
1573 packet_buffers[id].len = len; // use the flags field of the packet structure to hold the data length
1574 packet_buffers[id].sequence_number = packet_id;
1575 packet_buffers[id].from_addr = from_addr;
1576 memcpy( packet_buffers[id].data, data, len );
1579 psnet_do_net_stats( &from_addr, read_len, 1 );
1580 psnet_bytes_read_frame += read_len;
1583 // buffer the packet
1584 psnet_buffer_packet(packet_data.data,read_len,&from_addr);
1589 // -------------------------------------------------------------------------------------------------
1594 int psnet_send( net_addr * who_to, void * data, int len, int flags, int reliable_socket )
1598 struct sockaddr_in sockaddr; // UDP/TCP socket structure
1599 SOCKADDR_IPX ipx_addr; // IPX socket structure
1601 ubyte iaddr[6], *send_data;
1604 struct timeval timeout;
1606 if(!reliable_socket){
1607 send_sock = Unreliable_socket;
1609 send_sock = Reliable_socket;
1612 if ( Network_status != NETWORK_STATUS_RUNNING ) {
1613 nprintf(("Network","Network ==> Socket not inited in psnet_send\n"));
1617 if ( psnet_same( who_to, &Psnet_my_addr) ){
1621 memset(iaddr, 0x00, 6);
1622 memcpy(iaddr, who_to->addr, 6);
1624 if ( memcmp(iaddr, Null_address, 6) == 0) {
1625 nprintf(("Network","Network ==> send to address is 0 in psnet_send\n"));
1629 if(send_sock == Unreliable_socket){
1630 port = who_to->port;
1631 } else if(send_sock == Reliable_socket){
1632 port = DEFAULT_GAME_PORT + 1;
1634 port = who_to->port;
1638 nprintf(("Network","Network ==> destination port %d invalid in psnet_send\n", port));
1642 #ifdef PSNET_BUFFER_OLD_SCHOOL
1643 network_checksum_packet Send_network_checksum_packet;
1644 network_naked_packet Send_network_naked_packet;
1646 // determine from the flags whether or not this packet should have a checksum.
1647 if ( flags & PSNET_FLAG_CHECKSUM ) {
1648 // can't send raw data with a checksum, dumbass!
1649 SDL_assert(!(flags & PSNET_FLAG_RAW));
1651 Send_network_checksum_packet.sequence_number = Next_packet_id++;
1652 Send_network_checksum_packet.flags = PSNET_FLAG_CHECKSUM;
1654 Send_network_checksum_packet.checksum = psnet_calc_checksum(data, len);
1655 memcpy( Send_network_checksum_packet.data, data, len );
1656 send_len = sizeof(Send_network_checksum_packet) - MAX_CHECKSUM_PACKET_SIZE + len;
1657 send_data = (ubyte *)&Send_network_checksum_packet;
1659 // send standard psnet stuff
1660 if(!(flags & PSNET_FLAG_RAW)){
1661 Send_network_naked_packet.sequence_number = Next_packet_id++;
1662 Send_network_naked_packet.flags = 0;
1664 memcpy(Send_network_naked_packet.data, data, len);
1665 send_len = sizeof(Send_network_naked_packet) - MAX_PACKET_SIZE + len; // gets us the real size of the structure
1666 send_data = (ubyte *)&Send_network_naked_packet;
1670 send_data = (ubyte*)data;
1675 send_data = (ubyte*)data;
1681 FD_SET( send_sock, &wfds );
1683 timeout.tv_usec = 0;
1686 if ( select( -1, NULL, &wfds, NULL, &timeout) == SOCKET_ERROR ) {
1688 if ( select( send_sock+1, NULL, &wfds, NULL, &timeout) == SOCKET_ERROR ) {
1690 nprintf(("Network", "Error on blocking select for write %d\n", WSAGetLastError() ));
1694 // if the write file descriptor is not set, then bail!
1695 if ( !FD_ISSET(send_sock, &wfds ) )
1699 switch ( who_to->type ) {
1702 ipx_addr.sa_socket = htons(port);
1703 ipx_addr.sa_family = AF_IPX;
1704 memcpy(ipx_addr.sa_nodenum, iaddr, 6);
1705 memcpy(ipx_addr.sa_netnum, who_to->net_id, 4);
1707 ret = sendto(send_sock, (char *)send_data, send_len, 0, (struct sockaddr*)&ipx_addr, sizeof(ipx_addr));
1708 if ( (ret != SOCKET_ERROR) && (ret != send_len) )
1709 nprintf(("Network", "requested to send %d bytes -- sent %d instead!!!\n", send_len, ret));
1715 sockaddr.sin_family = AF_INET;
1716 memcpy(&sockaddr.sin_addr.s_addr, iaddr, 4);
1717 sockaddr.sin_port = htons(port);
1719 ret = sendto( send_sock, (char *)send_data, send_len, 0, (struct sockaddr*)&sockaddr, sizeof(sockaddr) );
1723 SDL_assert(0); // unknown protocol
1728 if ( ret != SOCKET_ERROR ) {
1730 psnet_bytes_written_frame += send_len;
1731 psnet_do_net_stats( who_to, send_len, 0 );
1735 //Warning( LOCATION, "Couldn't send data (0x%x)!\n", WSAGetLastError() );
1739 #ifdef PSNET_BUFFER_OLD_SCHOOL
1740 // routine to "free" a packet buffer
1741 void free_packet( int id )
1743 packet_buffers[id].sequence_number = -1;
1744 packet_free_list[ --Num_packet_buffers ] = (short)id;
1745 if ( Largest_packet_index == id)
1746 while ((--Largest_packet_index>0) && (packet_buffers[Largest_packet_index].sequence_number == -1 ));
1750 #ifdef PSNET_RELIABLE_OLD_SCHOOL
1751 // psnet_send_reliable sends the given data through the given reliable socket.
1753 #define MAX_RSEND_BUFFER 2048
1754 ubyte rsend_buffer[MAX_RSEND_BUFFER];
1756 int psnet_rel_send( PSNET_SOCKET psocket, ubyte *data, int length, int flags )
1759 int num_sent, total_sent, error, retries;
1761 unsigned short s_length;
1763 socket = (SOCKET)psocket;
1766 if ( Network_status != NETWORK_STATUS_RUNNING ) {
1767 nprintf(("Network","Network ==> Socket not inited in psnet_send\n"));
1771 if ( socket == INVALID_SOCKET ) // might happen in race conditions -- should get cleaned up.
1774 SDL_assert( length < MAX_RSEND_BUFFER );
1776 // copy the length of the data into the beginning of the buffer. then put the data into the buffer
1777 // after the length value
1778 SDL_assert( length > 0 );
1779 s_length = (ushort)length;
1780 memcpy( &rsend_buffer[0], &s_length, sizeof(s_length) );
1781 memcpy( &rsend_buffer[2], data, length );
1787 num_sent = send( socket, (char *)rsend_buffer, length+sizeof(s_length), 0 );
1788 if ( num_sent == SOCKET_ERROR ) {
1789 error = WSAGetLastError();
1790 if ( (error != WSAEWOULDBLOCK) || (retries > MAX_SEND_RETRIES) ) { // means that we would block on send -- not really an error
1792 // if error is would block, then set error to aborted connection
1793 if ( error == WSAEWOULDBLOCK )
1794 error = WSAECONNABORTED;
1796 multi_eval_socket_error(socket, error);
1799 retries++; // keep a try count
1802 send_data += num_sent;
1803 total_sent += num_sent;
1805 } while ( length > 0 );
1808 psnet_bytes_written_frame += total_sent;
1811 //index = psnet_find_stats_loc( who_to );
1812 //if ( index != -1 )
1813 // Psnet_stats[index].total_written += send_len;
1818 // get data off the reliable socket
1819 int psnet_rel_get( PSNET_SOCKET psocket, ubyte *buffer, int max_len, int flags)
1821 int from_len, total_read, error;
1824 struct timeval timeout;
1826 ubyte rread_buffer[2];
1828 socket = (SOCKET)psocket;
1830 // see if there is data to be read
1832 FD_SET( socket, &rfds );
1834 timeout.tv_usec = 0;
1837 if ( select( -1, &rfds, NULL, NULL, &timeout) == SOCKET_ERROR ) {
1839 if ( select( socket+1, &rfds, NULL, NULL, &timeout) == SOCKET_ERROR ) {
1841 nprintf(("Network", "Error on select for read reliable: %d\n", WSAGetLastError() ));
1845 // if no data, then we can leave.
1846 if ( !FD_ISSET(socket, &rfds ) )
1849 // we know we have data to read. We must read the two byte length of the packet first
1853 from_len = recv(socket, (char *)(&rread_buffer[total_read]), read_len - total_read, 0);
1855 // from_len will be 0 when back end gracefully closes connection. We will assume that since
1856 // the close is graceful, we will info from him telling us he's left. So we'll ignore
1857 // this condition here.
1858 if ( from_len == 0 ) {
1859 nprintf(("Network", "Dumping player because recv returned 0\n"));
1860 multi_eval_socket_error( socket, WSAECONNRESET ); // this error drops player from game.
1864 // on a socket error, we need to check for WSAEWOULDBLOCK meaning that there is no more
1866 else if ( from_len == SOCKET_ERROR ) {
1867 error = WSAGetLastError();
1868 if ( error != WSAEWOULDBLOCK )
1869 multi_eval_socket_error( socket, error );
1870 return 0; // get it next frame?
1873 total_read += from_len;
1874 } while ( total_read < read_len );
1878 memcpy(&read_len, &rread_buffer[0], 2);
1879 SDL_assert( (read_len > 0) && (read_len < max_len) );
1880 if ( read_len == 0 )
1884 from_len = recv(socket, (char *)(buffer + total_read), read_len - total_read, 0);
1886 // from_len will be 0 when back end gracefully closes connection. We will assume that since
1887 // the close is graceful, we will info from him telling us he's left. So we'll ignore
1888 // this condition here.
1889 if ( from_len == 0 ) {
1890 nprintf(("Network", "Dumping player because recv returned 0\n"));
1891 multi_eval_socket_error( socket, WSAECONNRESET ); // this error drops player from game.
1895 // on a socket error, we need to check for WSAEWOULDBLOCK meaning that there is no more
1897 else if ( from_len == SOCKET_ERROR ) {
1898 error = WSAGetLastError();
1899 if ( error != WSAEWOULDBLOCK ) {
1900 multi_eval_socket_error( socket, error );
1906 total_read += from_len;
1907 } while ( total_read < read_len );
1912 // psnet_send_reliable sends the given data through the given reliable socket.
1913 int psnet_send_reliable( PSNET_SOCKET psocket, ubyte *data, int length, int flags )
1915 // don't do anything if the socket is null
1916 if(psocket == NULL){
1920 // send a reliable data packet
1921 return psnet_reliable_send(data,length,(net_addr*)psocket);
1924 int psnet_get_reliable( PSNET_SOCKET psocket, ubyte *buffer, int max_len, int flags)
1927 int best, best_id, i, n, size;
1929 // call the routine to read data out of the socket (which stuffs it into the packet buffers)
1930 psnet_get_socket_data(Reliable_socket,flags);
1932 #ifdef PSNET_BUFFER_OLD_SCHOOL
1933 // now determine which (if any) of the packet buffers we should look at!
1938 for (i=0; i <= Largest_packet_index; i++ ) {
1939 if ( packet_buffers[i].sequence_number > -1 ) {
1941 if ( best == -1 || (packet_buffers[i].sequence_number < best) ) {
1942 best = packet_buffers[i].sequence_number;
1948 //mprintf( (0, "Best id = %d, pn = %d, last_ecb = %x, len=%x, ne = %d\n", best_id, best, last_ecb, lastlen, neterrors ));
1949 //mprintf( (1, "<%d> ", neterrors ));
1951 if ( best_id < 0 ) return 0;
1953 size = packet_buffers[best_id].len;
1954 memcpy( buffer, packet_buffers[best_id].data, size );
1955 memcpy( psocket, &packet_buffers[best_id].from_addr, sizeof(net_addr) );
1956 free_packet(best_id);
1965 // function which checks the Listen_socket for possibly incoming requests to be connected.
1966 // returns 0 on error or nothing waiting. 1 if we should try to accept
1967 int psnet_rel_check_for_listen(net_addr *from_addr)
1971 SOCKET sock; // when trying to accept, this is new socket
1972 struct sockaddr_in ip_addr; // UDP/TCP socket structure
1973 SOCKADDR_IPX ipx_addr; // IPX socket structure
1974 int from_len, error;
1978 FD_SET( Listen_socket, &rfds );
1980 timeout.tv_usec = 0;
1983 if ( select(-1, &rfds, NULL, NULL, &timeout) == SOCKET_ERROR ) {
1985 if ( select(Listen_socket+1, &rfds, NULL, NULL, &timeout) == SOCKET_ERROR ) {
1987 nprintf(("Network", "Error %d doing select on listen socket\n", WSAGetLastError() ));
1991 // check to see if Listen_socket has something -- if not, return
1992 if ( !FD_ISSET(Listen_socket, &rfds) )
1993 return INVALID_SOCKET;
1995 sock = INVALID_SOCKET;
1996 switch ( Socket_type ) {
1998 from_len = sizeof(SOCKADDR_IPX);
1999 sock = accept( Listen_socket, (struct sockaddr*)&ipx_addr, &from_len );
2000 from_addr->port = ntohs( ipx_addr.sa_socket );
2001 memcpy(from_addr->addr, ipx_addr.sa_nodenum, 6 );
2002 memcpy(from_addr->net_id, ipx_addr.sa_netnum, 4 );
2003 nprintf(("Network","Accepted SPX connection!!\n"));
2007 from_len = sizeof(struct sockaddr_in);
2008 sock = accept( Listen_socket, (struct sockaddr*)&ip_addr, &from_len );
2009 from_addr->port = ntohs( ip_addr.sin_port );
2010 memset(from_addr->addr, 0x00, 6);
2011 memcpy(from_addr->addr, &ip_addr.sin_addr.S_un.S_addr, 4);
2012 nprintf(("Network","Accepted TCP connected!!\n"));
2020 if ( !psnet_get_ip(sock) ) {
2021 return INVALID_SOCKET;
2024 // make the new socket non-blocking
2025 if(sock != INVALID_SOCKET){
2027 error = ioctlsocket( sock, FIONBIO, &arg );
2028 if ( error == SOCKET_ERROR ) {
2029 nprintf(("Network", "Unable to make accepted socket non-blocking -- %d", WSAGetLastError() ));
2030 return INVALID_SOCKET;
2038 // psnet_get() will call the above function to read data out of the socket. It will then determine
2039 // which of the buffers we should use and pass to the routine which called us
2040 int psnet_get( void * data, net_addr* from_addr, int flags )
2042 // USE THIS CODE TO TEST NON-BUFFERED SOCKET READS. OUT-OF-ORDER PACKETS DROP TO NEARLY 0
2047 int read_len,from_len;
2048 struct sockaddr_in ip_addr;
2050 FD_SET( Unreliable_socket, &rfds );
2052 timeout.tv_usec = 0;
2055 if ( select( -1, &rfds, NULL, NULL, &timeout) == SOCKET_ERROR ) {
2057 if ( select( Unreliable_socket+1, &rfds, NULL, NULL, &timeout) == SOCKET_ERROR ) {
2059 nprintf(("Network", "Error %d doing a socket select on read\n", WSAGetLastError()));
2063 // if the read file descriptor is not set, then bail!
2064 if ( !FD_ISSET(Unreliable_socket, &rfds ) )
2067 // get data off the socket and process
2068 read_len = SOCKET_ERROR;
2069 from_len = sizeof(struct sockaddr_in);
2070 read_len = recvfrom( Unreliable_socket, (char*)data, MAX_PACKET_SIZE, 0, (struct sockaddr*)&ip_addr, &from_len );
2071 from_addr->port = ntohs( ip_addr.sin_port );
2072 memset(from_addr->addr, 0x00, 6);
2073 memcpy(from_addr->addr, &ip_addr.sin_addr.S_un.S_addr, 4);
2077 // call the routine to read data out of the socket (which stuffs it into the packet buffers)
2078 psnet_get_socket_data(Unreliable_socket,flags);
2080 #ifdef PSNET_BUFFER_OLD_SCHOOL
2081 int best, best_id, i, n, size;
2083 // now determine which (if any) of the packet buffers we should look at!
2088 for (i=0; i <= Largest_packet_index; i++ ) {
2089 if ( packet_buffers[i].sequence_number > -1 ) {
2091 if ( best == -1 || (packet_buffers[i].sequence_number < best) ) {
2092 best = packet_buffers[i].sequence_number;
2098 //mprintf( (0, "Best id = %d, pn = %d, last_ecb = %x, len=%x, ne = %d\n", best_id, best, last_ecb, lastlen, neterrors ));
2099 //mprintf( (1, "<%d> ", neterrors ));
2101 if ( best_id < 0 ) return 0;
2103 size = packet_buffers[best_id].len;
2104 memcpy( data, packet_buffers[best_id].data, size );
2105 memcpy( from_addr, &packet_buffers[best_id].from_addr, sizeof(net_addr) );
2106 free_packet(best_id);
2112 // try and get a free buffer and return its size
2113 if(psnet_buffer_get_next((ubyte*)data,&buffer_size,from_addr)){
2124 // -------------------------------------------------------------------------------------------------
2125 // psnet_broadcast()
2129 int psnet_broadcast( net_addr * who_to, void * data, int len, int flags )
2131 if ( Network_status != NETWORK_STATUS_RUNNING ) {
2132 nprintf(("Network","Network ==> Socket not inited in psnet_broadcast\n"));
2136 if ( !Can_broadcast ) {
2137 nprintf(("Network", "Cannot broadcast -- returning without doing anything\n"));
2141 ubyte broadcast[6] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
2143 // broadcasting works on a local subnet which is all we really want to do for now anyway.
2144 // we might keep this in as an option for freespace later.
2145 switch ( who_to->type ) {
2149 memcpy(who_to->addr, broadcast, 6);
2150 psnet_send(who_to, data, len, flags);
2158 // called to clear out the socket of any remaining data
2162 ubyte data[MAX_PACKET_SIZE];
2165 while ( psnet_get( data, &from_addr ) > 0 ) ;
2171 // function to keep track of bytes read/written on average during the frame
2172 void psnet_calc_socket_stats()
2174 if ( psnet_frame_int == -1 ) {
2176 for ( i = 0; i < PSNET_FRAME_FILTER; i++ ) {
2177 psnet_read_sizes[i] = 0;
2178 psnet_write_sizes[i] = 0;
2180 psnet_read_total = 0;
2181 psnet_write_total = 0;
2182 psnet_frame_int = 0;
2184 psnet_read_total -= psnet_read_sizes[psnet_frame_int];
2185 psnet_write_total -= psnet_write_sizes[psnet_frame_int];
2187 psnet_read_total += psnet_bytes_read_frame;
2188 psnet_write_total += psnet_bytes_written_frame;
2190 psnet_read_sizes[psnet_frame_int] = psnet_bytes_read_frame;
2191 psnet_write_sizes[psnet_frame_int] = psnet_bytes_written_frame;
2193 psnet_frame_int = (psnet_frame_int + 1 ) % PSNET_FRAME_FILTER;
2195 if ( psnet_frame_count > 0 ) {
2196 if ( psnet_frame_count >= PSNET_FRAME_FILTER )
2197 Psnet_bytes_read = psnet_read_total / PSNET_FRAME_FILTER;
2199 Psnet_bytes_read = psnet_read_total / psnet_frame_count;
2201 if ( psnet_frame_count >= PSNET_FRAME_FILTER )
2202 Psnet_bytes_written = psnet_write_total / PSNET_FRAME_FILTER;
2204 Psnet_bytes_written = psnet_write_total / psnet_frame_count;
2207 psnet_frame_count++;
2208 psnet_bytes_read_frame = 0;
2209 psnet_bytes_written_frame = 0;
2213 int psnet_is_valid_numeric_ip(char *ip)
2217 int val1,val2,val3,val4;
2219 // get the first ip value
2220 SDL_strlcpy(copy, ip, sizeof(copy));
2221 token = strtok(copy,".");
2225 // get the value of the token
2227 if((val1 < 0) || (val1 > 255)){
2233 token = strtok(NULL,".");
2237 // get the value of the token
2239 if((val2 < 0) || (val2 > 255)){
2245 token = strtok(NULL,".");
2249 // get the value of the token
2251 if((val3 < 0) || (val3 > 255)){
2257 token = strtok(NULL,"");
2261 // get the value of the token
2263 if((val4 < 0) || (val4 > 255)){
2268 // make sure he hasn't entered all 0's
2269 if((val1 == 0) && (val2 == 0) && (val3 == 0) && (val4 == 0)){
2278 // returns true or false if the given string is a valid ip string or not.
2279 // allow port allows us to append the port number on the end of the ip string with
2281 // so we must be sure to remove the port number
2282 int psnet_is_valid_ip_string( char *ip_string, int allow_port )
2285 struct hostent *host_ent;
2288 // our addresses may have ports, so make local copy and remove port number
2289 SDL_assert( strlen(ip_string) < 255 );
2290 SDL_strlcpy(str, ip_string, sizeof(str));
2291 c = strrchr(str, ':');
2296 addr.s_addr = inet_addr(ip_string);
2297 if ( addr.s_addr != INADDR_NONE ){
2298 // make sure the ip string is a valid format string
2299 if(psnet_is_valid_numeric_ip(ip_string)){
2304 // try name resolution
2305 host_ent = gethostbyname( ip_string );
2310 // valid host entry so return 1;
2315 // ------------------------------------------------------------------------------------------------------
2316 // PACKET BUFFERING FUNCTIONS
2319 #ifndef PSNET_BUFFER_OLD_SCHOOL
2321 // a sequence number of -1 will indicate that this packet is not valid
2322 static network_packet_buffer Psnet_buffers[MAX_PACKET_BUFFERS];
2323 static int Psnet_seq_number = 0;
2324 static int Psnet_lowest_id = 0;
2325 static int Psnet_highest_id = 0;
2327 // initialize the buffering system
2328 void psnet_buffer_init()
2332 // blast the buffer clean
2333 memset(Psnet_buffers,0,sizeof(network_packet_buffer) * MAX_PACKET_BUFFERS);
2335 // set all buffer sequence #'s to -1
2336 for(idx=0;idx<MAX_PACKET_BUFFERS;idx++){
2337 Psnet_buffers[idx].sequence_number = -1;
2340 // initialize the sequence #
2341 Psnet_seq_number = 0;
2342 Psnet_lowest_id = -1;
2343 Psnet_highest_id = -1;
2346 // buffer a packet (maintain order!)
2347 void psnet_buffer_packet(ubyte *data, int length, net_addr *from)
2352 // find the first empty packet
2353 for(idx=0;idx<MAX_PACKET_BUFFERS;idx++){
2354 if(Psnet_buffers[idx].sequence_number == -1){
2360 // if we didn't find the buffer, report an overrun
2362 nprintf(("Network","WARNING - Buffer overrun in psnet\n"));
2365 memcpy(Psnet_buffers[idx].data,data,length);
2366 Psnet_buffers[idx].len = length;
2367 memcpy(&Psnet_buffers[idx].from_addr,from,sizeof(net_addr));
2368 Psnet_buffers[idx].sequence_number = Psnet_seq_number;
2370 // keep track of the highest id#
2371 Psnet_highest_id = Psnet_seq_number++;
2373 // set the lowest id# for the first time
2374 if(Psnet_lowest_id == -1){
2375 Psnet_lowest_id = Psnet_highest_id;
2380 // get the index of the next packet in order!
2381 int psnet_buffer_get_next(ubyte *data, int *length, net_addr *from)
2386 // if there are no buffers, do nothing
2387 if((Psnet_lowest_id == -1) || (Psnet_lowest_id > Psnet_highest_id)){
2391 // search until we find the lowest packet index id#
2392 for(idx=0;idx<MAX_PACKET_BUFFERS;idx++){
2393 // if we found the buffer
2394 if(Psnet_buffers[idx].sequence_number == Psnet_lowest_id){
2400 // at this point, we should _always_ have found the buffer
2401 SDL_assert(found_buf);
2403 // copy out the buffer data
2404 memcpy(data,Psnet_buffers[idx].data,Psnet_buffers[idx].len);
2405 *length = Psnet_buffers[idx].len;
2406 memcpy(from,&Psnet_buffers[idx].from_addr,sizeof(net_addr));
2408 // now we need to cleanup the packet list
2410 // mark the buffer as free
2411 Psnet_buffers[idx].sequence_number = -1;
2419 // initialize the buffering system
2420 void psnet_buffer_init() {}
2422 // buffer a packet (maintain order!)
2423 void psnet_buffer_packet(ubyte *data, int length) {}
2425 // get the index of the next packet in order!
2426 int psnet_buffer_get_next() { return -1; }
2430 // ------------------------------------------------------------------------------------------------------
2431 // RELIABLE UDP FUNCTIONS
2434 // verbose debug output
2435 #define PSNET_RELIABLE_VERBOSE
2437 // overall buffer space allocated to the buffers
2438 #define PSNET_RELIABLE_MAX_OUT_BUFFER_SIZE (1<<18) // 256k
2439 #define PSNET_RELIABLE_MAX_IN_BUFFER_SIZE (1<<12) // 4k
2441 // outgoing reliable packets
2442 typedef struct reliable_packet_out {
2443 ubyte data[MAX_PACKET_SIZE]; // data in the original packet
2444 ushort packet_size; // size of the original packet
2445 ushort player_flags; // bitflags indexing (1<<N) into the Psnet_reliable_addr[N] array
2446 ushort player_acks; // bitflags indexing (1<<N) into the Psnet_reliable_addr[N] array
2447 int player_stamps[MAX_PLAYERS]; // timeouts for each player
2448 ubyte num_resends[MAX_PLAYERS]; // # of times we've resent to a given player
2449 ushort out_id; // identifier of the packet
2450 fix age; // how old this packet is
2451 } reliable_packet_out;
2453 // incoming reliable packets
2454 typedef struct reliable_packet_in {
2455 ushort in_id; // identifier of the received packet
2456 fix age; // when we received the packet
2457 } reliable_packet_in;
2459 // # of outgoing and incoming buffers we'll allocate
2460 #define PSNET_RELIABLE_NUM_OUT_BUFFERS (PSNET_RELIABLE_MAX_OUT_BUFFER_SIZE / sizeof(reliable_packet_out))
2461 #define PSNET_RELIABLE_NUM_IN_BUFFERS (PSNET_RELIABLE_MAX_IN_BUFFER_SIZE / sizeof(reliable_packet_in))
2463 // timeout to be used for the packets
2464 #define PSNET_RELIABLE_TIMEOUT 1500 // in ms
2466 // # of repeats to use
2467 #define PSNET_RELIABLE_REPEAT 8 // repeat this many times max
2470 #define PSNET_RELIABLE_INVALID 0
2473 #define PSNET_RELIABLE_ACK 0xffff
2475 // the outgoing and incoming buffers themselves
2476 reliable_packet_out *Psnet_reliable_out[PSNET_RELIABLE_NUM_OUT_BUFFERS];
2477 reliable_packet_in *Psnet_reliable_in[PSNET_RELIABLE_NUM_IN_BUFFERS];
2479 // psnet reliable address list
2480 net_addr Psnet_reliable_addr[MAX_PLAYERS]; // address of registered "reliable" addrs
2481 int Psnet_reliable_addr_flags; // bitflags indicating which of the above are valid
2483 // my local identifier # (will only use lower 12 bits)
2484 ushort Psnet_reliable_local_id = 0x1;
2486 // is the reliable system initialized
2487 int Psnet_reliable_inited = 0;
2489 // # of times a packet has not been delivered
2490 int Psnet_reliable_fail_count = 0;
2492 // # of times packets have had to be resent
2493 int Psnet_reliable_resend_count = 0;
2495 // # of times we've run out of packets and had to overwrite existing ones
2496 int Psnet_reliable_overwrite_count = 0;
2498 // forward declarations ------------------------------------------------------
2500 // free up all used buffers
2501 void psnet_reliable_free_all_buffers();
2503 // get the index of the passed address or -1 if it doesn't exist
2504 int psnet_reliable_addr_index(net_addr *addr);
2506 // get the index into the address array from the passed bitflag
2507 int psnet_reliable_index_addr(int flags);
2509 // kill all outgoing packets belonging to the passed index
2510 void psnet_reliable_kill_outgoing(int index);
2512 // generate a unique id #, given the passed in value and the address it came from, return PSNET_RELIABLE_INVALID
2513 // upper 12 bytes should be valid # and the lower 4 should be free for this function to fill in
2514 ushort psnet_reliable_get_unique_id(ushort id_num,net_addr *from);
2516 // get the upper 12 bit version of my id# and increment the original
2517 ushort psnet_reliable_get_next_id();
2519 // get the index of a free outgoing relible packet buffer, killing the oldest if necessary
2520 int psnet_reliable_get_free_outgoing();
2522 // get the index of a free incoming relible packet buffer, killing the oldest if necessary
2523 int psnet_reliable_get_free_incoming();
2525 // actually send the data contained with the reliable_packet_out
2526 int psnet_reliable_send_packet(reliable_packet_out *out,int force_index = 0);
2528 // evaluate the status of a reliable packet - and free it up if the thing is _done_
2529 void psnet_reliable_evaluate_status(reliable_packet_out *out);
2531 // determine if the passed id# exists in the in-packet list, return the instance where it exists, or -1 if it doesn't
2532 int psnet_reliable_find_in_id(ushort id_num);
2534 // determine if the passed id# exists in the out-packet list, return the instance where it exists, or -1 if it doesn't
2535 int psnet_reliable_find_out_id(ushort id_num);
2537 // send an ack to the specified address
2538 void psnet_reliable_send_ack(net_addr *addr,ushort id_num);
2541 // extern functions -----------------------------------------------------------
2543 // initialize the psnet reliable system (return 0 on fail, 1 on success)
2544 int psnet_reliable_init()
2548 // if the system is already inited, do nothing
2549 if(Psnet_reliable_inited){
2553 #ifdef PSNET_RELIABLE_VERBOSE
2554 nprintf(("Network","PSNET RELIABLE SIZES : \n OUT BUFFER SIZE : %d\n OUT BUFFER COUNT %d\n IN BUFFER SIZE %d\n IN BUFFER COUNT %d\n",
2555 PSNET_RELIABLE_MAX_OUT_BUFFER_SIZE,PSNET_RELIABLE_NUM_OUT_BUFFERS,PSNET_RELIABLE_MAX_IN_BUFFER_SIZE,PSNET_RELIABLE_NUM_IN_BUFFERS));
2559 for(idx=0;idx<PSNET_RELIABLE_NUM_OUT_BUFFERS;idx++){
2560 Psnet_reliable_out[idx] = NULL;
2562 for(idx=0;idx<PSNET_RELIABLE_NUM_IN_BUFFERS;idx++){
2563 Psnet_reliable_in[idx] = NULL;
2566 // initialize all outgoing buffers
2567 for(idx=0;idx<PSNET_RELIABLE_NUM_OUT_BUFFERS;idx++){
2568 Psnet_reliable_out[idx] = NULL;
2569 Psnet_reliable_out[idx] = (reliable_packet_out*)malloc(sizeof(reliable_packet_out));
2571 // if we failed to allocate the buffer, return failure
2572 if(Psnet_reliable_out[idx] == NULL){
2573 psnet_reliable_free_all_buffers();
2576 memset(Psnet_reliable_out[idx],0,sizeof(reliable_packet_out));
2579 // initialize all incoming buffers
2580 for(idx=0;idx<PSNET_RELIABLE_NUM_IN_BUFFERS;idx++){
2581 Psnet_reliable_in[idx] = NULL;
2582 Psnet_reliable_in[idx] = (reliable_packet_in*)malloc(sizeof(reliable_packet_in));
2584 // if we failed to allocate the buffer, return failure
2585 if(Psnet_reliable_in[idx] == NULL){
2586 psnet_reliable_free_all_buffers();
2589 memset(Psnet_reliable_in[idx],0,sizeof(reliable_packet_in));
2592 // blast the reliable address list free
2593 memset(Psnet_reliable_addr,0,sizeof(net_addr) * MAX_PLAYERS);
2594 Psnet_reliable_addr_flags = 0;
2596 // set the system to be initialized
2597 Psnet_reliable_inited = 1;
2599 // initialize my local id #
2600 Psnet_reliable_local_id = 0x1;
2602 // initialize the packet delivery fail count
2603 Psnet_reliable_fail_count = 0;
2605 // intialize the packet necessary resend count
2606 Psnet_reliable_resend_count = 0;
2608 // initialize # of times we've run out of packets and had to overwrite existing ones
2609 Psnet_reliable_overwrite_count = 0;
2615 // shutdown the reliable system (free up buffers, etc)
2616 void psnet_reliable_close()
2618 // if the system is not initialized, don't do anything
2619 if(!Psnet_reliable_inited){
2623 // free up all buffers
2624 psnet_reliable_free_all_buffers();
2626 // blast all addresses clean
2627 memset(Psnet_reliable_addr,0,sizeof(net_addr) * MAX_PLAYERS);
2628 Psnet_reliable_addr_flags = 0;
2630 // set the system as being uninitialized
2631 Psnet_reliable_inited = 0;
2634 // notify the reliable system of a new address at index N
2635 void psnet_reliable_notify_new_addr(net_addr *addr,int index)
2637 // copy in the address
2638 memcpy(&Psnet_reliable_addr[index],addr,sizeof(net_addr));
2640 // set the bit indicating its validity
2641 Psnet_reliable_addr_flags |= (1<<index);
2644 // notify the reliable system of a drop at index N
2645 void psnet_reliable_notify_drop_addr(net_addr *addr)
2649 // do a lookup for the address
2650 index = psnet_reliable_addr_index(addr);
2652 // clear out all packets belonging exclusively to this address
2653 psnet_reliable_kill_outgoing(index);
2655 // clear the address and its existence bit
2656 memset(&Psnet_reliable_addr[index],0,sizeof(net_addr));
2657 Psnet_reliable_addr_flags &= ~(1<<index);
2661 // send a reliable data packet
2662 int psnet_reliable_send(ubyte *data,int packet_size,net_addr *addr)
2666 reliable_packet_out *p;
2668 // if the system is not initialized, don't do anything
2669 if(!Psnet_reliable_inited){
2673 // try and find a guy to send to
2675 to_index = psnet_reliable_addr_index(addr);
2677 nprintf(("Network","PSNET RELIABLE : could not find player for outgoing packet!\n"));
2681 // attempt to get a free buffer
2683 free_buffer = psnet_reliable_get_free_outgoing();
2684 if(free_buffer == -1){
2685 Int3(); // should never happen - we should always overwrite the oldest buffer
2688 // setup the data for the outgoing packet
2689 p = Psnet_reliable_out[free_buffer];
2690 memcpy(p->data,data,packet_size);
2691 p->packet_size = (ushort)packet_size;
2692 p->player_flags |= (1<<to_index);
2693 memset(p->player_stamps,0xf,sizeof(int) * MAX_PLAYERS);
2694 p->player_stamps[to_index] = timestamp(PSNET_RELIABLE_TIMEOUT);
2695 p->out_id = psnet_reliable_get_next_id();
2696 p->age = timer_get_fixed_seconds();
2699 return psnet_reliable_send_packet(p);
2702 // process frame for all reliable stuff (call once per frame)
2703 void psnet_reliable_process()
2706 reliable_packet_out *p;
2708 // if the system is not initialized, don't do anything
2709 if(!Psnet_reliable_inited){
2713 // go through all active packets
2714 for(idx=0;idx<PSNET_RELIABLE_NUM_OUT_BUFFERS;idx++){
2715 // if the packet is active
2716 if(Psnet_reliable_out[idx]->out_id != PSNET_RELIABLE_INVALID){
2717 p = Psnet_reliable_out[idx];
2719 // loop through all active players and see if we need to resend
2720 for(s_idx=0;s_idx<MAX_PLAYERS;s_idx++){
2721 // if the packet is active for this player and he hasn't acked
2722 if(p->player_flags & (1<<s_idx) && !(p->player_acks & (1<<s_idx))){
2723 // if the timestamp has elapsed
2724 if((p->player_stamps[s_idx] != -1) && timestamp_elapsed(p->player_stamps[s_idx])){
2725 // if we are at max resends, bomb!
2726 if(p->num_resends[s_idx] >= PSNET_RELIABLE_REPEAT){
2727 #ifdef PSNET_RELIABLE_VERBOSE
2728 nprintf(("Network","PSNET RELIABLE : packet failed to be delivered (%d retries) !!\n",PSNET_RELIABLE_REPEAT));
2730 p->player_flags &= ~(1<<s_idx);
2732 // increment the fail count
2733 Psnet_reliable_fail_count++;
2735 // otherwise resend the packet
2737 // actually send the data contained with the reliable_packet_out
2738 psnet_reliable_send_packet(p,s_idx);
2740 // increment the resend count
2741 Psnet_reliable_resend_count++;
2743 #ifdef PSNET_RELIABLE_VERBOSE
2744 nprintf(("Network","PSNET RELIABLE : resending packet\n"));
2751 // evaluate if this packet has completed
2752 psnet_reliable_evaluate_status(p);
2757 // determine if the passed in reliable data should be processed, and sends an ack if necessary
2758 // return # of bytes which should be stripped off the data (reliable data header)
2759 int psnet_reliable_should_process(net_addr *addr,ubyte *data,int packet_size)
2761 ushort id_num,ack_code,unique_id;
2765 reliable_packet_in *p;
2767 // get the reliable packet id #
2768 memcpy(&id_num,data,sizeof(ushort));
2770 // if the id# is an ack, get the id# do a lookup
2771 if(id_num == PSNET_RELIABLE_ACK){
2772 #ifdef PSNET_RELIABLE_VERBOSE
2773 nprintf(("Network","PSNET RELIABLE : ACK 1\n"));
2779 memcpy(&id_num,data+2,sizeof(ushort));
2781 // get the packet index
2782 // unique_id = psnet_reliable_get_unique_id(id_num,addr);
2784 packet_index = psnet_reliable_find_out_id(unique_id);
2785 player_index = psnet_reliable_addr_index(addr);
2786 if((packet_index != -1) && (player_index != -1)){
2787 #ifdef PSNET_RELIABLE_VERBOSE
2788 nprintf(("Network","PSNET RELIABLE : ACK 2\n"));
2791 Psnet_reliable_out[packet_index]->player_acks |= (1<<player_index);
2793 // check to see if this packet is _done_
2794 psnet_reliable_evaluate_status(Psnet_reliable_out[packet_index]);
2797 // return 4 bytes processed
2801 // otherwise - see if this is a new packet
2802 packet_index = psnet_reliable_find_in_id(id_num);
2803 if(packet_index == -1){
2806 free_index = psnet_reliable_get_free_incoming();
2807 if(free_index == -1){
2811 // setup the incoming packet
2812 p = Psnet_reliable_in[free_index];
2813 p->age = timer_get_fixed_seconds();
2814 p->in_id = psnet_reliable_get_unique_id(id_num,addr);
2817 psnet_reliable_send_ack(addr,id_num);
2819 // return 2 bytes processed
2822 // send another ack for good measure
2824 psnet_reliable_send_ack(addr,id_num);
2830 // forward definitions --------------------------------------------
2832 // free up all used buffers
2833 void psnet_reliable_free_all_buffers()
2837 // free all outgoing buffers
2838 for(idx=0;idx<PSNET_RELIABLE_NUM_OUT_BUFFERS;idx++){
2839 // if the buffer is not null, free it
2840 if(Psnet_reliable_out[idx] != NULL){
2841 free(Psnet_reliable_out[idx]);
2842 Psnet_reliable_out[idx] = NULL;
2846 // free all incoming buffers
2847 for(idx=0;idx<PSNET_RELIABLE_NUM_IN_BUFFERS;idx++){
2848 // if the buffer is not null, free it
2849 if(Psnet_reliable_in[idx] != NULL){
2850 free(Psnet_reliable_in[idx]);
2851 Psnet_reliable_in[idx] = NULL;
2856 // get the index of the passed address or -1 if it doesn't exist
2857 int psnet_reliable_addr_index(net_addr *addr)
2861 // look through all valid addresses
2862 for(idx=0;idx<MAX_PLAYERS;idx++){
2863 if((Psnet_reliable_addr_flags & (1<<idx)) && psnet_same(addr,&Psnet_reliable_addr[idx])){
2868 // couldn't find the address
2872 // get the index into the address array from the passed bitflag
2873 int psnet_reliable_index_addr(int flags)
2877 // look through all the bits in the flags
2878 for(idx=0;idx<MAX_PLAYERS;idx++){
2879 if(flags & (1<<idx)){
2884 // couldn't find any
2888 // kill all outgoing packets belonging to the passed index
2889 void psnet_reliable_kill_outgoing(int index)
2893 // go through all buffers
2894 for(idx=0;idx<PSNET_RELIABLE_NUM_OUT_BUFFERS;idx++){
2895 if(Psnet_reliable_out[idx]->out_id != PSNET_RELIABLE_INVALID){
2896 // if it is exclusively his, kill the whole packet
2897 if(Psnet_reliable_out[idx]->player_flags == (1<<index)){
2898 memset(Psnet_reliable_out[idx],0,sizeof(reliable_packet_out));
2901 // if it belongs to him and other players, kill his entry
2902 else if(Psnet_reliable_out[idx]->player_flags & (1<<index)){
2903 Psnet_reliable_out[idx]->player_flags &= ~(1<<index);
2904 Psnet_reliable_out[idx]->num_resends[index] = 0;
2910 // generate a unique id #, given the passed in value and the address it came from, return PSNET_RELIABLE_INVALID
2911 // upper 12 bytes should be valid # and the lower 4 should be free for this function to fill in
2912 ushort psnet_reliable_get_unique_id(ushort id_num,net_addr *from)
2917 // if the lower 4 bits are not clear, we've got a problem
2922 // lookup through the Psnet_reliable_addr[] list and try and find the index
2923 for(idx=0;idx<MAX_PLAYERS;idx++){
2924 if((idx == 1) /*(Psnet_reliable_addr_flags & (1<<idx)) && (psnet_same(from,&Psnet_reliable_addr[idx]))*/){
2925 // fill in the lower 4 bits
2927 id_num |= (cast & 0xf);
2932 // couldn't find an id#
2933 return PSNET_RELIABLE_INVALID;
2936 // get the upper 12 bit version of my id# and increment the original
2937 ushort psnet_reliable_get_next_id()
2939 ushort id_num = Psnet_reliable_local_id;
2941 // clear out the upper 4 bits
2944 // shift 4 bits to the left
2947 // increment the local id #
2948 if(Psnet_reliable_local_id == 0x0fff){
2949 Psnet_reliable_local_id = 0x1;
2951 Psnet_reliable_local_id++;
2954 // return the shifted value
2958 // get the index of a free outgoing relible packet buffer, killing the oldest if necessary
2959 int psnet_reliable_get_free_outgoing()
2962 int oldest_index = -1;
2965 // search through all buffers
2966 for(idx=0;idx<PSNET_RELIABLE_NUM_OUT_BUFFERS;idx++){
2967 if(Psnet_reliable_out[idx]->out_id == PSNET_RELIABLE_INVALID){
2971 // keep track of the oldest packet
2972 if((oldest_index == -1) || (Psnet_reliable_out[idx]->age < oldest)){
2974 oldest = Psnet_reliable_out[idx]->age;
2978 // if we got here, all of our buffers are full, so we should kill the oldest one
2979 memset(Psnet_reliable_out[oldest_index],0,sizeof(reliable_packet_out));
2980 Psnet_reliable_overwrite_count = 0;
2981 #ifdef PSNET_RELIABLE_VERBOSE
2982 nprintf(("Network","PSNET RELIABLE : overwriting old send buffer\n"));
2984 return oldest_index;
2987 // get the index of a free incoming relible packet buffer, killing the oldest if necessary
2988 int psnet_reliable_get_free_incoming()
2991 int oldest_index = -1;
2994 // search through all buffers
2995 for(idx=0;idx<PSNET_RELIABLE_NUM_IN_BUFFERS;idx++){
2996 if(Psnet_reliable_in[idx]->in_id == PSNET_RELIABLE_INVALID){
3000 // keep track of the oldest packet
3001 if((oldest_index == -1) || (Psnet_reliable_in[idx]->age < oldest)){
3003 oldest = Psnet_reliable_in[idx]->age;
3007 // if we got here, all of our buffers are full, so we should kill the oldest one
3008 memset(Psnet_reliable_in[oldest_index],0,sizeof(reliable_packet_in));
3009 #ifdef PSNET_RELIABLE_VERBOSE
3010 nprintf(("Network","PSNET RELIABLE : overwriting old recv buffer\n"));
3012 return oldest_index;
3015 // actually send the data contained with the reliable_packet_out
3016 int psnet_reliable_send_packet(reliable_packet_out *out,int force_index)
3018 ubyte data[MAX_PACKET_SIZE];
3020 int packet_size = 2 + out->packet_size;
3022 // stick the identifier on the front of the packet
3023 memcpy(data,&out->out_id,sizeof(ushort));
3025 // copy in the actual data
3026 memcpy(data+2,out->data,out->packet_size);
3028 // send the packet and update the timestamp for all players
3030 // send to one specified player in the packet
3032 if(force_index != 0){
3033 if(out->player_flags & (1<<force_index) && !(out->player_acks & (1<<force_index))){
3034 bytes_sent = psnet_send(&Psnet_reliable_addr[force_index],data,packet_size,PSNET_FLAG_RAW,1);
3035 out->player_stamps[force_index] = timestamp(PSNET_RELIABLE_TIMEOUT);
3036 out->num_resends[force_index]++;
3039 // send to all players contained in the packet
3041 for(idx=0;idx<MAX_PLAYERS;idx++){
3042 // if this guy is flagged and he exists and he hasn't already acked
3043 if(out->player_flags & (1<<idx) && (Psnet_reliable_addr_flags & (1<<idx)) && !(out->player_acks & (1<<idx))){
3044 bytes_sent = psnet_send(&Psnet_reliable_addr[idx],data,packet_size,PSNET_FLAG_RAW,1);
3045 out->player_stamps[idx] = timestamp(PSNET_RELIABLE_TIMEOUT);
3046 out->num_resends[idx]++;
3055 // evaluate the status of a reliable packet - and free it up if the thing is _done_
3056 void psnet_reliable_evaluate_status(reliable_packet_out *out)
3060 // check to see if all players have acked or failed miserably
3062 for(idx=0;idx<MAX_PLAYERS;idx++){
3063 // if the packet is active for this guy but he has not acked yet
3064 if((out->player_flags & (1<<idx)) && !(out->player_acks & (1<<idx))){
3070 // if its ok to annihilate this packet, do so
3072 memset(out,0,sizeof(reliable_packet_out));
3076 // determine if the passed id# exists in the in-packet list, return the instance where it exists, or -1 if it doesn't
3077 int psnet_reliable_find_in_id(ushort id_num)
3081 // if the id is 0, its invalid
3082 if(id_num == PSNET_RELIABLE_INVALID){
3086 // look through all in packets
3087 for(idx=0;idx<PSNET_RELIABLE_NUM_IN_BUFFERS;idx++){
3088 if(id_num == Psnet_reliable_in[idx]->in_id){
3097 // determine if the passed id# exists in the out-packet list, return the instance where it exists, or -1 if it doesn't
3098 int psnet_reliable_find_out_id(ushort id_num)
3102 // if the id is 0, its invalid
3103 if(id_num == PSNET_RELIABLE_INVALID){
3107 // look through all in packets
3108 for(idx=0;idx<PSNET_RELIABLE_NUM_OUT_BUFFERS;idx++){
3109 if(id_num == Psnet_reliable_out[idx]->out_id){
3118 // send an ack to the specified address
3119 void psnet_reliable_send_ack(net_addr *addr,ushort id_num)
3125 val = PSNET_RELIABLE_ACK;
3126 memcpy(data,&val,sizeof(ushort));
3129 memcpy(data+2,&id_num,sizeof(ushort));
3132 psnet_send(addr,data,4,PSNET_FLAG_RAW,Reliable_socket);
3135 #endif // #ifndef PSNET2