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.
126 #include <winsock2.h>
128 #include <raserror.h>
130 #include <sys/types.h>
131 #include <sys/socket.h>
132 #include <netinet/in.h>
133 #include <arpa/inet.h>
134 #include <sys/ioctl.h>
144 #include "multiutil.h"
145 #include "multilag.h"
146 #include "osregistry.h"
148 #include "multi_log.h"
153 // old style packet buffering
154 // #define PSNET_BUFFER_OLD_SCHOOL
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 int Psnet_my_addr_valid;
167 net_addr_t Psnet_my_addr;
169 ubyte Null_address[IP_ADDRESS_LENGTH];
172 int Can_broadcast; // can we do broadcasting on our socket?
173 int Tcp_can_broadcast = 0;
178 int Tcp_failure_code = 0;
180 int Psnet_connection;
182 ushort Psnet_default_port;
184 unsigned int Serverconn = 0xffffffff;
186 // specified their internet connnection type
187 #define NETWORK_CONNECTION_NONE 1
188 #define NETWORK_CONNECTION_DIALUP 2
189 #define NETWORK_CONNECTION_LAN 3
191 // defines and variables to indicate network connection status
192 #define NETWORK_STATUS_NOT_INITIALIZED 1
193 #define NETWORK_STATUS_NO_WINSOCK 2 // winsock failed to initialize
194 #define NETWORK_STATUS_NO_PROTOCOL 3 // specified protocol doesn't appear to be loaded
195 #define NETWORK_STATUS_NO_RELIABLE 4
196 #define NETWORK_STATUS_RUNNING 5 // everything should be running
198 // defintion of structures that actually leave this machine. psnet_send give us only
199 // the data that we want to send. We will add a header onto this data (packet sequence
200 // number, possibly a checksum). We must include a 2 byte flags variable into both structure
201 // since the receiving end of this packet must know whether or not to checksum the packet.
203 // use the pack pragma to pack these structures to 2 byte aligment. Really only needed for
206 #pragma pack(push, 2)
208 // packet def for a checksum'ed packet
209 #define MAX_CHECKSUM_PACKET_SIZE 1024
210 typedef struct network_checksum_packet
215 ubyte data[MAX_CHECKSUM_PACKET_SIZE];
216 } network_checksum_packet;
218 // definition for a non-checksum packet
219 typedef struct network_packet
223 ubyte data[MAX_PACKET_SIZE];
224 } network_naked_packet;
226 // structure definition for our packet buffers
227 typedef struct network_packet_buffer
231 net_addr_t from_addr;
232 ubyte data[MAX_PACKET_SIZE];
233 } network_packet_buffer;
237 #define MAX_PACKET_BUFFERS 96
239 #ifdef PSNET_BUFFER_OLD_SCHOOL
240 static network_packet_buffer packet_buffers[MAX_PACKET_BUFFERS]; // buffer to hold packets sent to us
241 static short packet_free_list[MAX_PACKET_BUFFERS]; // contains id's of free packet buffers
242 static Num_packet_buffers;
243 static int Largest_packet_index = 0;
249 // variables to keep track of bytes read/written during the course of network play
252 #define PSNET_FRAME_FILTER 32
253 #define MAX_NET_STATS 32
257 net_addr_t addr; // stats for this address
258 int total_read; // total bytes read
259 int total_written; // total bytes read.
267 net_stats Psnet_stats[MAX_NET_STATS];
268 socket_xlate Psnet_socket_addr[MAX_NET_STATS];
270 int psnet_bytes_read_frame; // running count of bytes read this frame
271 int psnet_bytes_written_frame; // running count of bytes written this frame
273 int Psnet_bytes_read; // globally available numbers for printing on the hud
274 int Psnet_bytes_written;
276 int psnet_read_sizes[PSNET_FRAME_FILTER];
277 int psnet_write_sizes[PSNET_FRAME_FILTER];
279 int psnet_read_total;
280 int psnet_write_total;
282 int psnet_frame_count;
286 #define MAXHOSTNAME 128
288 #define MAX_RECEIVE_BUFSIZE (1<<15) // 32 K, eh?
289 #define MAX_SEND_RETRIES 20 // number of retries when sending would block
290 #define MAX_LINGER_TIME 0 // in seconds -- when lingering to close a socket
294 int psnet_same_no_port( net_addr_t * a1, net_addr_t * a2 );
296 // do stats for a particular address. num_bytes is the number of bytes either read or
297 // written (depending on the read flag. read flag is true when reading, 0 when writing
298 void psnet_do_net_stats( net_addr_t *addr, int num_bytes, int read )
302 for ( i = 0; i < MAX_NET_STATS; i++ ) {
303 if ( !Psnet_stats[i].in_use )
305 if ( addr && psnet_same_no_port(&Psnet_stats[i].addr, addr) )
309 if ( i == MAX_NET_STATS ) {
310 // find the first NULL entry
311 for ( i = 0; i < MAX_NET_STATS; i++ ) {
312 if ( !Psnet_stats[i].in_use )
315 if ( i == MAX_NET_STATS ) {
316 Int3(); // we should always have a slot
319 Psnet_stats[i].addr = *addr;
320 Psnet_stats[i].in_use = 1;
323 Psnet_stats[i].total_read += num_bytes;
325 Psnet_stats[i].total_written += num_bytes;
328 // returns the stats for the given network address. returns 1 when (i.e. net_addr was found),
329 // 0 otherwise. total read and total written are returned in the parameters
330 int psnet_get_stats( net_addr_t *addr, int *tr, int *tw )
334 for ( i = 0; i < MAX_NET_STATS; i++ ) {
335 if ( !Psnet_stats[i].in_use )
338 if ( addr && psnet_same_no_port(&Psnet_stats[i].addr, addr) )
342 if ( i == MAX_NET_STATS )
345 *tr = Psnet_stats[i].total_read;
346 *tw = Psnet_stats[i].total_written;
351 void psnet_stats_init()
355 for ( i = 0; i < MAX_NET_STATS; i++ ) {
356 Psnet_stats[i].in_use = 0;
357 Psnet_stats[i].total_read = 0;
358 Psnet_stats[i].total_written = 0;
359 Psnet_socket_addr[i].socket = INVALID_SOCKET;
366 // function called from high level FreeSpace code to determine the status of the networking
367 // code returns one of a handful of macros
368 int psnet_get_network_status()
370 // first case is when "none" is selected
371 if ( Psnet_connection == NETWORK_CONNECTION_NONE ) {
372 return NETWORK_ERROR_NO_TYPE;
375 // first, check the connection status of the network
376 if ( Network_status == NETWORK_STATUS_NO_WINSOCK )
377 return NETWORK_ERROR_NO_WINSOCK;
379 if ( Network_status == NETWORK_STATUS_NO_PROTOCOL )
380 return NETWORK_ERROR_NO_PROTOCOL;
382 // network is running -- be sure that the RAS people know to connect if they currently cannot.
384 if ( Psnet_connection == NETWORK_CONNECTION_DIALUP ) {
385 // if on a dialup connection, be sure that RAS is active.
386 if ( !Ras_connected ) {
387 return NETWORK_ERROR_CONNECT_TO_ISP;
389 } else if ( Psnet_connection == NETWORK_CONNECTION_LAN ) {
390 // if on a LAN, and they have a dialup connection active, return error to indicate that they need
391 // to pick the right connection type
392 if ( Ras_connected ) {
393 return NETWORK_ERROR_LAN_AND_RAS;
396 return NETWORK_ERROR_NONE;
400 DWORD (__stdcall *pRasEnumConnections)(LPRASCONN lprasconn, LPDWORD lpcb, LPDWORD lpcConnections) = NULL;
401 DWORD (__stdcall *pRasGetConnectStatus)(HRASCONN hrasconn, LPRASCONNSTATUS lprasconnstatus ) = NULL;
402 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()
410 unsigned long size, num_connections, i;
411 RASCONN rasbuffer[25];
412 HINSTANCE ras_handle;
416 // first, call a LoadLibrary to load the RAS api
417 ras_handle = LoadLibrary( (LPCWSTR)"rasapi32.dll" );
418 if ( ras_handle == NULL ) {
422 pRasEnumConnections = (DWORD (__stdcall *)(LPRASCONN, LPDWORD, LPDWORD))GetProcAddress(ras_handle, NOX("RasEnumConnectionsA"));
423 if (!pRasEnumConnections) {
424 FreeLibrary( ras_handle );
427 pRasGetConnectStatus = (DWORD (__stdcall *)(HRASCONN, LPRASCONNSTATUS))GetProcAddress(ras_handle, NOX("RasGetConnectStatusA"));
428 if (!pRasGetConnectStatus) {
429 FreeLibrary( ras_handle );
432 pRasGetProjectionInfo = (DWORD (__stdcall *)(HRASCONN, RASPROJECTION, LPVOID, LPDWORD))GetProcAddress(ras_handle, NOX("RasGetProjectionInfoA"));
433 if (!pRasGetProjectionInfo) {
434 FreeLibrary( ras_handle );
438 size = sizeof(rasbuffer);
439 rasbuffer[0].dwSize = sizeof(RASCONN);
441 rval = pRasEnumConnections( rasbuffer, &size, &num_connections );
443 FreeLibrary( ras_handle );
447 // JAS: My computer gets to this point, but I have no RAS connections,
449 if ( num_connections < 1 ) {
450 nprintf(("Network", "Found no connections\n" ));
451 FreeLibrary( ras_handle );
455 nprintf(("Network", "Found %d connections\n", num_connections));
457 for (i = 0; i < num_connections; i++ ) {
458 RASCONNSTATUS status;
462 nprintf(("Network", "Connection %d:\n", i));
463 nprintf(("Network", "Entry Name: %s\n", rasbuffer[i].szEntryName));
464 nprintf(("Network", "Device Type: %s\n", rasbuffer[i].szDeviceType));
465 nprintf(("Network", "Device Name: %s\n", rasbuffer[i].szDeviceName));
467 // get the connection status
468 status.dwSize = sizeof(RASCONNSTATUS);
469 rval = pRasGetConnectStatus(rasbuffer[i].hrasconn, &status);
471 FreeLibrary( ras_handle );
475 nprintf(("Network", "\tStatus: %s\n", (status.rasconnstate==RASCS_Connected)?"Connected":"Not Connected"));
477 // get the projection informatiom
478 size = sizeof(projection);
479 projection.dwSize = size;
480 rval = pRasGetProjectionInfo(rasbuffer[i].hrasconn, RASP_PppIp, &projection, &size );
482 FreeLibrary( ras_handle );
486 nprintf(("Network", "\tIP Address: %s\n", projection.szIpAddress));
491 FreeLibrary( ras_handle );
495 // -------------------------------------------------------------------------------------------------
496 // netmisc_calc_checksum() calculates the checksum of a block of memory.
499 ushort psnet_calc_checksum( void * vptr, int len )
501 ubyte * ptr = (ubyte *)vptr;
502 unsigned int sum1,sum2;
508 if (sum1 >= 255 ) sum1 -= 255;
513 return (unsigned short)((sum1<<8)+ sum2);
516 // -------------------------------------------------------------------------------------------------
517 // psnet_set_socket_mode()
521 int psnet_set_socket_mode(SOCKET sock_id, int opt, int toggle)
523 return (setsockopt(sock_id, SOL_SOCKET, opt, (char *)&toggle, sizeof(toggle)));
527 // -------------------------------------------------------------------------------------------------
528 // sock_get_ip() returns the IP address of this computer.
534 char LclHost[MAXHOSTNAME];
535 struct hostent *Hostent;
536 struct sockaddr_in LclAddr;
537 struct sockaddr_in RmtAddr;
541 // Init local address to zero
542 LclAddr.sin_addr.s_addr = INADDR_ANY;
544 // Get the local host name
545 nRet = gethostname(LclHost, MAXHOSTNAME );
546 if (nRet != SOCKET_ERROR ) {
547 // Resolve host name for local address
548 Hostent = gethostbyname((char *)LclHost);
550 LclAddr.sin_addr.s_addr = ((in_addr *)(Hostent->h_addr))->s_addr;
553 return LclAddr.sin_addr.s_addr;
559 // psnet_get_ip() attempts to get the local IP address of this machine
560 // returns 0 on failure, and 1 on success
561 int psnet_get_ip( SOCKET s )
565 struct sockaddr_in local_addr;
567 if ( Psnet_my_addr_valid ){
571 memset(&local_addr, 0, sizeof(struct sockaddr_in));
572 len = sizeof(struct sockaddr_in);
573 rval = getsockname(s, (struct sockaddr *)&local_addr, &len );
574 if ( rval == SOCKET_ERROR )
577 // now we should have an IP address of this machine.
578 memcpy(Psnet_my_addr.addr, &(local_addr.sin_addr), 4);
579 Psnet_my_addr.port = ntohs(local_addr.sin_port);
581 Psnet_my_addr_valid = 1;
585 // -------------------------------------------------------------------------------------------------
592 #ifndef PSNET_RELIABLE_OLD_SCHOOL
593 psnet_reliable_close();
596 if ( Network_status != NETWORK_STATUS_RUNNING )
600 WSACancelBlockingCall();
603 if ( TCP_listen_socket != (SOCKET)INVALID_SOCKET ) {
604 shutdown( TCP_listen_socket, 1 );
605 closesocket( TCP_listen_socket );
608 if ( TCP_reliable_socket != (SOCKET)INVALID_SOCKET ) {
609 shutdown( TCP_reliable_socket, 1 );
610 closesocket( TCP_reliable_socket );
613 if ( TCP_socket != (SOCKET)INVALID_SOCKET ) {
614 shutdown( TCP_socket, 1 );
615 closesocket( TCP_socket );
620 //Warning( LOCATION, "Error closing wsock!\n" );
624 Network_status = NETWORK_STATUS_NOT_INITIALIZED;
627 // function to initialize a reliable socket. All it does is call the socket() command.
628 // returns 1 on success, 0 on failure.
629 int psnet_init_stream( SOCKET *s, int type )
633 SDL_assert(type == NET_TCP);
635 sock = socket(AF_INET,SOCK_STREAM,0);
636 if ( sock == (SOCKET)INVALID_SOCKET )
644 // called by psnet_init to initialize the listen socket used by a host/server
645 int psnet_init_reliable(ushort port, int should_listen, int type)
647 SOCKET sock = 0; // JAS: Get rid of optimized warning
648 struct sockaddr_in sockaddr; // UDP/TCP socket structure
650 // set up the reliable TCP transport socket
651 if ( !psnet_init_stream(&sock, type) ) {
652 nprintf(("Network", "Unable to initialize reliable socket on port %d (%d)!\n" , port, WSAGetLastError() ));
653 return INVALID_SOCKET;
656 // bind the socket to the port
657 SDL_assert(type == NET_TCP);
659 memset( &sockaddr, 0, sizeof(struct sockaddr_in) );
660 sockaddr.sin_family = AF_INET;
661 sockaddr.sin_addr.s_addr = INADDR_ANY; //fill in with our IP
662 sockaddr.sin_port = htons( port );
663 if ( bind(sock, (struct sockaddr*)&sockaddr, sizeof (sockaddr)) == SOCKET_ERROR) {
664 nprintf(("Network", "Unable to bind reliable socket on port %d (%d)!\n" , port, WSAGetLastError() ));
665 return INVALID_SOCKET;
669 // set up the listen on the Reliable_socket port
670 if ( should_listen && listen(sock, 5) ) {
671 nprintf(("Network", "Unable to listen on Listen Socket (%d)!\n" , WSAGetLastError() ));
672 return INVALID_SOCKET;
675 // make any reliable sockets which we create that aren't listening non-blocking sockets
676 if ( !should_listen ) {
681 error = ioctlsocket( sock, FIONBIO, &arg );
682 if ( error == SOCKET_ERROR ) {
683 nprintf(("Network", "Unable to make reliable socket non-blocking -- %d", WSAGetLastError() ));
684 return INVALID_SOCKET;
687 // set the reuse option
688 if ( psnet_set_socket_mode(sock, SO_REUSEADDR, 1) == SOCKET_ERROR ) {
689 error = WSAGetLastError();
690 nprintf(("Network", "Error setting socket to reuse address -- %d\n", error));
698 void psnet_socket_options( SOCKET sock )
701 int ret, cursize, bufsize, trysize;
702 SOCKLEN_T cursizesize;
704 // Set the mode of the socket to allow broadcasting. We need to be able to broadcast
705 // when a game is searched for in IPX mode.
707 if(setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char *)&broadcast, sizeof(broadcast) )){
713 // try and increase the size of my receive buffer
714 bufsize = MAX_RECEIVE_BUFSIZE;
716 // set the current size of the receive buffer
717 cursizesize = sizeof(int);
718 getsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char *)&cursize, &cursizesize);
719 for ( trysize = bufsize; trysize >= cursize; trysize >>= 1 ) {
720 ret = setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char *)&trysize, sizeof(trysize));
721 if ( ret == SOCKET_ERROR ) {
724 wserr = WSAGetLastError();
725 if ( (wserr == WSAENOPROTOOPT) || (wserr == WSAEINVAL) )
730 getsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char *)&cursize, &cursizesize);
731 nprintf(("Network", "Receive buffer set to %d\n", cursize));
733 // set the current size of the send buffer
734 cursizesize = sizeof(int);
735 getsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *)&cursize, &cursizesize);
736 for ( trysize = bufsize; trysize >= cursize; trysize >>= 1 ) {
737 ret = setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *)&trysize, sizeof(trysize));
738 if ( ret == SOCKET_ERROR ) {
741 wserr = WSAGetLastError();
742 if ( (wserr == WSAENOPROTOOPT) || (wserr == WSAEINVAL) )
747 getsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *)&cursize, &cursizesize);
748 nprintf(("Network", "Send buffer set to %d\n", cursize));
752 // psnet_init called at game startup time and initializes all sockets that the game might use (i.e. for both
754 void psnet_init( int protocol, int port_num )
756 const char *internet_connection;
761 // UDP/TCP socket structure
762 struct sockaddr_in sockaddr;
766 #if defined(DEMO) || defined(OEM_BUILD) // not for FS2_DEMO
770 // GAME PORT INITIALIZATION STUFF
771 if ( Network_status == NETWORK_STATUS_RUNNING )
774 // 'lan' should be a safe default in 2015
775 internet_connection = os_config_read_string("Network", "NetworkConnection", "LAN");
777 if ( !SDL_strcasecmp(internet_connection, NOX("dialup")) ) {
778 ml_string("psnet_init() detected dialup connection");
780 Psnet_connection = NETWORK_CONNECTION_DIALUP;
781 } else if ( !SDL_strcasecmp(internet_connection, NOX("lan")) ) {
782 ml_string("psnet_init() detected lan connection");
784 Psnet_connection = NETWORK_CONNECTION_LAN;
786 ml_string("psnet_init() detected no connection");
788 Psnet_connection = NETWORK_CONNECTION_NONE;
791 Network_status = NETWORK_STATUS_NO_WINSOCK;
794 if (WSAStartup(0x101, &wsa_data )){
799 // get the port for running this game on. Be careful that it cannot be out of bounds
800 Psnet_default_port = DEFAULT_GAME_PORT;
801 if ( (port_num > 1023) && (port_num < USHRT_MAX) ) {
802 Psnet_default_port = (ushort)port_num;
805 #ifndef PSNET_RELIABLE_OLD_SCHOOL
806 if(!psnet_reliable_init()){
807 nprintf(("Network","PSNET RELIABLE : init failed - no networking available!\n"));
812 // initialize TCP now
813 TCP_socket = INVALID_SOCKET;
814 TCP_reliable_socket = INVALID_SOCKET;
815 TCP_listen_socket = INVALID_SOCKET;
817 Network_status = NETWORK_STATUS_NO_PROTOCOL;
818 TCP_socket = socket( AF_INET, SOCK_DGRAM, 0 );
819 if ( TCP_socket == (SOCKET)INVALID_SOCKET ) {
820 Tcp_failure_code = WSAGetLastError();
821 nprintf(("Network", "Error on TCP startup %d\n", Tcp_failure_code));
826 memset(&sockaddr,0,sizeof(struct sockaddr_in));
827 sockaddr.sin_family = AF_INET;
829 sockaddr.sin_addr.s_addr = INADDR_ANY; //fill in with our IP
831 sockaddr.sin_port = htons( Psnet_default_port );
832 if ( bind(TCP_socket, (struct sockaddr*)&sockaddr, sizeof (sockaddr)) == SOCKET_ERROR) {
833 Tcp_failure_code = WSAGetLastError();
834 nprintf(( "Network", "Couldn't bind TCP socket (%d)! Invalidating TCP\n", Tcp_failure_code ));
838 #ifdef PSNET_RELIABLE_OLD_SCHOOL
839 // set up reliable socket (using SPX).
840 TCP_reliable_socket = psnet_init_reliable( 0, 0, NET_TCP );
841 if ( TCP_reliable_socket == (SOCKET)INVALID_SOCKET ) {
842 Tcp_failure_code = WSAGetLastError();
843 nprintf(( "Network", "Couldn't initialize TCP reliable socket (OLD SCHOOL) (%d)! Invalidating TCP\n", Tcp_failure_code ));
847 TCP_listen_socket = psnet_init_reliable( (u_short)(Psnet_default_port-1), 1, NET_TCP );
848 if ( TCP_listen_socket == (SOCKET)INVALID_SOCKET ) {
849 Tcp_failure_code = WSAGetLastError();
850 nprintf(( "Network", "Couldn't initialize TCP listen socket (OLD SCHOOL) (%d)! Invalidating TCP\n", Tcp_failure_code ));
857 psnet_socket_options( TCP_socket );
858 Tcp_can_broadcast = Can_broadcast;
861 // fire up a second UDP socket for "reliable" transport
862 #ifndef PSNET_RELIABLE_OLD_SCHOOL
863 TCP_reliable_socket = socket( AF_INET, SOCK_DGRAM, 0 );
864 if ( TCP_reliable_socket != INVALID_SOCKET ) {
866 memset(&sockaddr,0,sizeof(struct sockaddr_in));
867 sockaddr.sin_family = AF_INET;
869 sockaddr.sin_addr.s_addr = INADDR_ANY; //fill in with our IP
870 //unsigned long my_ip = sock_get_ip();
871 //memcpy(&sockaddr.sin_addr.s_addr,&my_ip,sizeof(uint));
873 sockaddr.sin_port = htons( (ushort)(port+1) );
874 if ( bind(TCP_reliable_socket, (struct sockaddr*)&sockaddr, sizeof (sockaddr)) == SOCKET_ERROR) {
875 nprintf(( "Network", "Couldn't bind TCP socket (%d)! Invalidating TCP\n", WSAGetLastError() ));
879 psnet_socket_options( TCP_reliable_socket );
886 Network_status = NETWORK_STATUS_RUNNING;
888 nprintf(("Network","TCP Initialized\n"));
890 // with TCP initialized, see if the RAS services are installed
894 psnet_frame_int = -1; // for counting bytes per frame
897 #ifdef PSNET_BUFFER_OLD_SCHOOL
901 // initialize the packet buffer stuff. We use an array (the packet_free_list) to determine
902 // which of the packet buffers we can use next.
904 for (i=0; i<MAX_PACKET_BUFFERS; i++ ) {
905 packet_buffers[i].sequence_number = -1;
906 packet_free_list[i] = (short)i;
908 Num_packet_buffers = 0;
909 Largest_packet_index = 0;
911 // initialize the new buffering system
916 #define MAX_TMPBUF_SIZE 1024
918 #ifdef PSNET_RELIABLE_OLD_SCHOOL
919 // function to shutdown and close the given socket. It takes a couple of things into consideration
920 // when closing, such as possibly reiniting reliable sockets if they are closed here.
921 void psnet_rel_close_socket( PSNET_SOCKET *p_sockp )
927 sockp = (SOCKET *)p_sockp;
929 if ( *sockp == (SOCKET)INVALID_SOCKET )
933 if ( *sockp == TCP_reliable_socket )
934 nprintf(("network", "Closing my relibale TCP socket\n"));
936 nprintf(("Network", "Closing client's reliable socket\n"));
939 // make the socket blocking
940 //unsigned long val = 0;
941 //rval = ioctlsocket(*sockp,FIONBIO,&val);
942 //if ( rval == SOCKET_ERROR ) {
943 // error = WSAGetLastError();
944 // nprintf(("Network", "Error %d when trying to make reliable socket blocking.\n", error));
947 // set the socket to linger with a timeout of 0
951 rval = setsockopt(*sockp,SOL_SOCKET,SO_LINGER,(char*)&l_val,sizeof(linger));
952 if ( rval == SOCKET_ERROR ) {
953 error = WSAGetLastError();
954 nprintf(("Network", "Error %d when trying to set linger value.\n", error));
957 // see if this socket is my Reliable_socket. If so, I will have to reinitialize it!
959 if ( *sockp == TCP_reliable_socket )
960 reinit_type = NET_TCP;
962 // if this is the server connection, mark it as done
963 if (*sockp == (SOCKET)Serverconn) {
964 Serverconn = 0xffffffff;
968 rval = shutdown( *sockp, 2); // shut the whole damn thing down.
969 if ( rval == SOCKET_ERROR ) {
970 error = WSAGetLastError();
971 nprintf(("Network", "Error %d on socket shutdown\n", error));
975 shutdown( *sockp, 1 );
977 while ( rval && (rval != SOCKET_ERROR) ) {
978 char tmp_buf[MAX_TMPBUF_SIZE];
980 rval = recv( *sockp, tmp_buf, MAX_TMPBUF_SIZE, 0 );
981 if ( rval == SOCKET_ERROR ) {
982 error = WSAGetLastError();
983 if ( NETCALL_WOULDBLOCK(error) )
988 rval = closesocket( *sockp );
989 if ( rval == SOCKET_ERROR ) {
991 error = WSAGetLastError();
992 nprintf(("Network", "Error %d on closing socket\n", error ));
996 *sockp = INVALID_SOCKET;
998 // see if we need to reinitialize
999 if ( reinit_type != -1 ) {
1000 if ( reinit_type == NET_TCP){
1001 TCP_reliable_socket = psnet_init_reliable( 0, 0, NET_TCP);
1002 Reliable_socket = TCP_reliable_socket;
1007 // function to shutdown and close the given socket. It takes a couple of things into consideration
1008 // when closing, such as possibly reiniting reliable sockets if they are closed here.
1009 void psnet_close_socket( PSNET_SOCKET *p_sockp )
1013 // copy the address to be removed
1014 memcpy(&remove,&((net_addr_t*)(*p_sockp)),sizeof(net_addr_t));
1016 // remove it from the reliable address list
1017 psnet_reliable_notify_drop_addr(&remove);
1019 // invalidate the passed in "socket"
1024 // function to check the status of the reliable socket and try to re-initialize it if necessary.
1025 // win95 seems to have trouble doing a reinit of the socket immediately after close, so this
1026 // function exists to check the status, and reinitialize if we need to
1027 int psnet_rel_check()
1029 // if our Reliable_socket is valid, simply return true to indicate all is well.
1030 if ( Reliable_socket != (SOCKET)INVALID_SOCKET )
1033 // based on our protocol type, try to reinitialize the socket we need.
1034 SDL_assert(Socket_type == NET_TCP);
1036 TCP_reliable_socket = psnet_init_reliable( 0, 0, NET_TCP);
1037 Reliable_socket = TCP_reliable_socket;
1039 // return our status.
1040 if ( Reliable_socket == (SOCKET)INVALID_SOCKET )
1046 // this function is called from a high level at FreeSpace to set the protocol that the user wishes to use
1047 int psnet_use_protocol( int protocol )
1049 // zero out my address
1050 Psnet_my_addr_valid = 0;
1051 memset( &Psnet_my_addr, 0, sizeof(Psnet_my_addr) );
1053 // wait until we choose a protocol to determine if we can broadcast
1056 SDL_assert(protocol == NET_TCP);
1058 if ( Network_status != NETWORK_STATUS_RUNNING )
1061 // assign the TCP_* sockets to the socket values used elsewhere
1062 Unreliable_socket = TCP_socket;
1063 Reliable_socket = TCP_reliable_socket;
1064 Listen_socket = TCP_listen_socket;
1066 Can_broadcast = Tcp_can_broadcast;
1068 nprintf(("Network","Psnet : TCP broadcast\n"));
1071 nprintf(("Network","Psnet using - NET_TCP\n"));
1073 Psnet_my_addr.type = protocol;
1074 Socket_type = protocol;
1079 #define MAX_CONNECT_TRIES 10
1081 // attacmpt to connect() to the server's tcp socket. socket parameter is simply assigned to the
1082 // Reliable_socket socket created in psnet_init
1083 void psnet_rel_connect_to_server( PSNET_SOCKET *psocket, net_addr_t *server_addr)
1085 struct sockaddr_in sockaddr; // UDP/TCP socket structure
1086 struct sockaddr *addr; // pointer to struct sockaddr to make coding easier
1088 ubyte iaddr[IP_ADDRESS_LENGTH];
1090 int name_length, val;
1092 memset(iaddr, 0x00, IP_ADDRESS_LENGTH);
1093 memcpy(iaddr, server_addr->addr, IP_ADDRESS_LENGTH);
1094 port = (u_short)(server_addr->port - 1);
1096 socket = (SOCKET *)psocket;
1098 SDL_assert(Socket_type == NET_TCP);
1100 sockaddr.sin_family = AF_INET;
1101 memcpy(&sockaddr.sin_addr.s_addr, iaddr, 4);
1102 sockaddr.sin_port = htons(port);
1103 addr = (struct sockaddr *)&sockaddr;
1104 name_length = sizeof(sockaddr);
1107 ml_string(NOX("Attempting to perform reliable TCP connect to server"));
1109 // connect this guys Reliable_socket to the socket parameter passed in
1110 *socket = INVALID_SOCKET;
1111 val = connect(Reliable_socket, addr, name_length);
1113 // I suppose that we could have a valid socket right away
1114 if ( val != SOCKET_ERROR ) {
1115 *socket = Reliable_socket;
1119 error = WSAGetLastError();
1120 if ( NETCALL_WOULDBLOCK(error) ) { // use select to find out when socket is writeable
1121 int is_set, num_tries;
1123 struct timeval timeout;
1125 // call select -- and return if an error leaving our connection to the client invalid
1129 FD_SET( Reliable_socket, &wfds );
1131 timeout.tv_usec = 500000; //500000 micro seconds is 1/2 second
1133 is_set = select( Reliable_socket+1, NULL, &wfds, NULL, &timeout);
1135 // check for error on select first
1136 if ( is_set == SOCKET_ERROR ) {
1137 nprintf(("Network", "Error on select for connect %d\n", WSAGetLastError() ));
1139 } else if (is_set) { // if set, then we have connection, move forward
1142 SDL_Delay(10); // sleep for 10 ms and try again
1145 } while ( num_tries < MAX_CONNECT_TRIES );
1147 if ( num_tries == MAX_CONNECT_TRIES )
1150 *socket = Reliable_socket;
1153 nprintf(("Network", "Connecting with server failed %d\n", error ));
1154 *socket = INVALID_SOCKET;
1158 // if we have a connection, get my address from getsockname
1159 if ( *socket == Reliable_socket ) {
1160 if ( !psnet_get_ip(Reliable_socket) ) {
1161 *socket = INVALID_SOCKET;
1165 Serverconn = *socket;
1170 void psnet_calc_bytes_per_frame()
1175 // -------------------------------------------------------------------------------------------------
1180 int psnet_same_no_port( net_addr_t * a1, net_addr_t * a2 )
1182 if ( !memcmp(a1->addr, a2->addr, IP_ADDRESS_LENGTH) )
1187 int psnet_same( net_addr_t * a1, net_addr_t * a2 )
1189 return psnet_same_no_port( a1, a2 );
1191 if ( !memcmp(a1->addr, a2->addr, 6) && a1->port == a2->port)
1197 // -------------------------------------------------------------------------------------------------
1202 char* psnet_addr_to_string( char * text, const int max_textlen, net_addr_t * address )
1205 if ( Network_status != NETWORK_STATUS_RUNNING ) {
1206 SDL_strlcpy( text, XSTR("[no networking]",910), max_textlen );
1212 SDL_assert(address->type == NET_TCP);
1214 switch ( address->type ) {
1216 memcpy(&temp_addr.s_addr, address->addr, 4);
1217 SDL_strlcpy( text, inet_ntoa(temp_addr), max_textlen );
1230 // -------------------------------------------------------------------------------------------------
1231 // psnet_undescribe()
1235 void psnet_string_to_addr( net_addr_t * address, char * text, const int max_textlen )
1238 char str[255], *c, *port;
1241 if ( Network_status != NETWORK_STATUS_RUNNING ) {
1242 SDL_strlcpy( text, XSTR("[no networking]",910), max_textlen );
1246 // copy the text string to local storage to look for ports
1247 SDL_assert( strlen(text) < 255 );
1248 SDL_strlcpy(str, text, SDL_arraysize(str));
1249 c = strrchr(str, ':');
1256 switch ( address->type ) {
1258 addr.s_addr = inet_addr(str);
1259 // if we get INADDR_NONE returns, then we need to try and resolve the host
1261 if ( addr.s_addr == INADDR_NONE ) {
1262 he = gethostbyname( str );
1263 // returns a non-null pointer if successful, so get the address
1265 addr.s_addr = ((in_addr *)(he->h_addr))->s_addr; // this is the address in network byte order
1267 addr.s_addr = INADDR_NONE;
1271 memset(address->addr, 0x00, IP_ADDRESS_LENGTH);
1272 memcpy(address->addr, &addr.s_addr, 4);
1274 address->port = (ushort)(atoi(port));
1285 // psnet_get_socket_data() will get data out of the socket and stuff it into the packet_buffers
1286 // The original psnet_get() now calls this function, then determines which of the packet buffers
1287 // to package up and use
1288 void psnet_get_socket_data(SOCKET socket, int flags = PSNET_FLAG_RAW)
1290 struct sockaddr_in ip_addr; // UDP/TCP socket structure
1295 net_addr_t from_addr;
1296 network_checksum_packet packet_read;
1297 network_checksum_packet packet_data;
1299 // clear the addresses to remove compiler warnings
1300 memset(&ip_addr, 0, sizeof(struct sockaddr_in));
1302 if ( Network_status != NETWORK_STATUS_RUNNING ) {
1303 nprintf(("Network","Network ==> socket not inited in psnet_get\n"));
1308 #ifdef PSNET_BUFFER_OLD_SCHOOL
1310 // if there are no more packet buffers that we can use, then we must bail here before reading
1312 if ( Num_packet_buffers >= MAX_PACKET_BUFFERS ) {
1313 nprintf(("Network", "Packet buffer overrun in psnet_get()\n"));
1318 // check if there is any data on the socket to be read. The amount of data that can be
1319 // atomically read is stored in len.
1322 FD_SET( socket, &rfds );
1324 timeout.tv_usec = 0;
1326 if ( select( socket+1, &rfds, NULL, NULL, &timeout) == SOCKET_ERROR ) {
1327 nprintf(("Network", "Error %d doing a socket select on read\n", WSAGetLastError()));
1331 // if the read file descriptor is not set, then bail!
1332 if ( !FD_ISSET(socket, &rfds ) )
1335 // get data off the socket and process
1336 read_len = SOCKET_ERROR;
1337 switch ( Socket_type ) {
1339 from_len = sizeof(struct sockaddr_in);
1340 if(flags & PSNET_FLAG_RAW){
1341 read_len = recvfrom( socket, (char*)packet_read.data, MAX_PACKET_SIZE, 0, (struct sockaddr*)&ip_addr, &from_len );
1343 read_len = recvfrom( socket, (char *)&packet_read, sizeof(packet_data), 0, (struct sockaddr*)&ip_addr, &from_len );
1352 // set the from_addr for storage into the packet buffer structure
1353 from_addr.type = Socket_type;
1355 switch ( Socket_type ) {
1357 if(socket == Reliable_socket){
1358 from_addr.port = Psnet_default_port;
1360 from_addr.port = ntohs( ip_addr.sin_port );
1362 memset(from_addr.addr, 0x00, IP_ADDRESS_LENGTH);
1363 memcpy(from_addr.addr, &ip_addr.sin_addr.s_addr, 4);
1371 if ( read_len == SOCKET_ERROR ) {
1373 int x = WSAGetLastError();
1374 nprintf(("Network", "Read error on socket. Winsock error %d \n", x));
1379 #ifndef PSNET_RELIABLE_OLD_SCHOOL
1381 // now we check to see if this is a reliable packet, and act accordindly
1382 if(socket == Reliable_socket){
1383 // this function processes the incoming packet, and determines if the system should continue to process the data
1384 shave_size = psnet_reliable_should_process(&from_addr,packet_read.data,read_len);
1388 // copy in from data+2, so we skip the reliable data header
1389 memcpy(packet_data.data,packet_read.data + shave_size,read_len);
1391 // subtract out the size of the reliable header
1392 read_len -= shave_size;
1395 memcpy(packet_data.data,packet_read.data,read_len);
1398 memcpy(packet_data.data,packet_read.data,read_len);
1401 #ifdef PSNET_BUFFER_OLD_SCHOOL
1405 // if we had no error reading from the socket, then determine if we need to calculate a
1406 // checksum on the packet
1407 if ( !(flags & PSNET_FLAG_RAW) && (packet_data.flags & PSNET_FLAG_CHECKSUM) ) {
1410 // calculate the size of the data that is actual real data
1411 len = read_len - (sizeof(packet_data) - MAX_CHECKSUM_PACKET_SIZE);
1412 checksum = psnet_calc_checksum( packet_data.data, len );
1413 if ( checksum != packet_data.checksum ) {
1414 nprintf(("Network", "bad checksum on incoming packet -- discarding\n"));
1417 data = packet_data.data;
1418 packet_id = packet_data.sequence_number;
1420 network_naked_packet *packet;
1422 // just read in the raw socket data and length
1423 if(flags & PSNET_FLAG_RAW){
1424 data = packet_data.data;
1429 // we don't have a checksum packet. cast the data to the naked packet type and
1430 // copy it over to passed parameters
1431 packet = (network_naked_packet *)&packet_data;
1433 len = read_len - (sizeof(network_naked_packet) - MAX_PACKET_SIZE);
1434 data = packet->data;
1436 packet_id = packet->sequence_number;
1440 // look at the sequence number compared to what we last received
1441 if ( Last_packet_id > -1 ) {
1442 if ( packet_id != (Last_packet_id+1) ) {
1443 //if ( packet_id < Last_packet_id )
1444 // nprintf(("network", "packet %d came in delayed (last id was %d\n", packet_id, Last_packet_id));
1445 //else if ( packet_id > (Last_packet_id+1) )
1446 // nprintf(("Network", "missed %d packet(s). last id %d. This id %d\n", (packet_id - Last_packet_id), Last_packet_id, packet_id));
1449 Last_packet_id = packet_id;
1452 psnet_do_net_stats( &from_addr, read_len, 1 );
1453 psnet_bytes_read_frame += read_len;
1456 // put all of the data (length, who from, etc.) into the next available packet buffer
1457 // slot. We should be assured of a slot here because of the check at the beginning
1458 // of the while loop
1459 SDL_assert ( Num_packet_buffers < MAX_PACKET_BUFFERS );
1460 id = packet_free_list[ Num_packet_buffers++ ];
1461 if (id > Largest_packet_index ) Largest_packet_index = id;
1462 packet_buffers[id].len = len; // use the flags field of the packet structure to hold the data length
1463 packet_buffers[id].sequence_number = packet_id;
1464 packet_buffers[id].from_addr = from_addr;
1465 memcpy( packet_buffers[id].data, data, len );
1468 psnet_do_net_stats( &from_addr, read_len, 1 );
1469 psnet_bytes_read_frame += read_len;
1472 // buffer the packet
1473 psnet_buffer_packet(packet_data.data,read_len,&from_addr);
1478 // -------------------------------------------------------------------------------------------------
1483 int psnet_send( net_addr_t * who_to, void * data, int len, int flags, int reliable_socket )
1487 struct sockaddr_in sockaddr; // UDP/TCP socket structure
1489 ubyte iaddr[IP_ADDRESS_LENGTH], *send_data;
1492 struct timeval timeout;
1494 if(!reliable_socket){
1495 send_sock = Unreliable_socket;
1497 send_sock = Reliable_socket;
1500 if ( Network_status != NETWORK_STATUS_RUNNING ) {
1501 nprintf(("Network","Network ==> Socket not inited in psnet_send\n"));
1505 if ( psnet_same( who_to, &Psnet_my_addr) ){
1509 memset(iaddr, 0x00, IP_ADDRESS_LENGTH);
1510 memcpy(iaddr, who_to->addr, IP_ADDRESS_LENGTH);
1512 if ( memcmp(iaddr, Null_address, IP_ADDRESS_LENGTH) == 0) {
1513 nprintf(("Network","Network ==> send to address is 0 in psnet_send\n"));
1517 if(send_sock == Unreliable_socket){
1518 port = who_to->port;
1519 } else if(send_sock == Reliable_socket){
1520 port = DEFAULT_GAME_PORT + 1;
1522 port = who_to->port;
1526 nprintf(("Network","Network ==> destination port %d invalid in psnet_send\n", port));
1530 #ifdef PSNET_BUFFER_OLD_SCHOOL
1531 network_checksum_packet Send_network_checksum_packet;
1532 network_naked_packet Send_network_naked_packet;
1534 // determine from the flags whether or not this packet should have a checksum.
1535 if ( flags & PSNET_FLAG_CHECKSUM ) {
1536 // can't send raw data with a checksum, dumbass!
1537 SDL_assert(!(flags & PSNET_FLAG_RAW));
1539 Send_network_checksum_packet.sequence_number = Next_packet_id++;
1540 Send_network_checksum_packet.flags = PSNET_FLAG_CHECKSUM;
1542 Send_network_checksum_packet.checksum = psnet_calc_checksum(data, len);
1543 memcpy( Send_network_checksum_packet.data, data, len );
1544 send_len = sizeof(Send_network_checksum_packet) - MAX_CHECKSUM_PACKET_SIZE + len;
1545 send_data = (ubyte *)&Send_network_checksum_packet;
1547 // send standard psnet stuff
1548 if(!(flags & PSNET_FLAG_RAW)){
1549 Send_network_naked_packet.sequence_number = Next_packet_id++;
1550 Send_network_naked_packet.flags = 0;
1552 memcpy(Send_network_naked_packet.data, data, len);
1553 send_len = sizeof(Send_network_naked_packet) - MAX_PACKET_SIZE + len; // gets us the real size of the structure
1554 send_data = (ubyte *)&Send_network_naked_packet;
1558 send_data = (ubyte*)data;
1563 send_data = (ubyte*)data;
1569 FD_SET( send_sock, &wfds );
1571 timeout.tv_usec = 0;
1573 if ( select( send_sock+1, NULL, &wfds, NULL, &timeout) == SOCKET_ERROR ) {
1574 nprintf(("Network", "Error on blocking select for write %d\n", WSAGetLastError() ));
1578 // if the write file descriptor is not set, then bail!
1579 if ( !FD_ISSET(send_sock, &wfds ) )
1583 switch ( who_to->type ) {
1586 sockaddr.sin_family = AF_INET;
1587 memcpy(&sockaddr.sin_addr.s_addr, iaddr, 4);
1588 sockaddr.sin_port = htons(port);
1590 ret = sendto( send_sock, (char *)send_data, send_len, 0, (struct sockaddr*)&sockaddr, sizeof(sockaddr) );
1594 SDL_assert(0); // unknown protocol
1599 if ( ret != SOCKET_ERROR ) {
1601 psnet_bytes_written_frame += send_len;
1602 psnet_do_net_stats( who_to, send_len, 0 );
1606 //Warning( LOCATION, "Couldn't send data (0x%x)!\n", WSAGetLastError() );
1610 #ifdef PSNET_BUFFER_OLD_SCHOOL
1611 // routine to "free" a packet buffer
1612 void free_packet( int id )
1614 packet_buffers[id].sequence_number = -1;
1615 packet_free_list[ --Num_packet_buffers ] = (short)id;
1616 if ( Largest_packet_index == id)
1617 while ((--Largest_packet_index>0) && (packet_buffers[Largest_packet_index].sequence_number == -1 ));
1621 #ifdef PSNET_RELIABLE_OLD_SCHOOL
1622 // psnet_send_reliable sends the given data through the given reliable socket.
1624 #define MAX_RSEND_BUFFER 2048
1625 ubyte rsend_buffer[MAX_RSEND_BUFFER];
1627 int psnet_rel_send( PSNET_SOCKET psocket, ubyte *data, int length, int flags )
1630 int num_sent, total_sent, error, retries;
1632 unsigned short s_length;
1634 socket = (SOCKET)psocket;
1637 if ( Network_status != NETWORK_STATUS_RUNNING ) {
1638 nprintf(("Network","Network ==> Socket not inited in psnet_send\n"));
1642 if ( socket == (SOCKET)INVALID_SOCKET ) // might happen in race conditions -- should get cleaned up.
1645 SDL_assert( length < MAX_RSEND_BUFFER );
1647 // copy the length of the data into the beginning of the buffer. then put the data into the buffer
1648 // after the length value
1649 SDL_assert( length > 0 );
1650 s_length = (ushort)length;
1651 memcpy( &rsend_buffer[0], &s_length, sizeof(s_length) );
1652 memcpy( &rsend_buffer[2], data, length );
1658 num_sent = send( socket, (char *)rsend_buffer, length+sizeof(s_length), 0 );
1659 if ( num_sent == SOCKET_ERROR ) {
1660 error = WSAGetLastError();
1661 if ( !NETCALL_WOULDBLOCK(error) || (retries > MAX_SEND_RETRIES) ) { // means that we would block on send -- not really an error
1663 // if error is would block, then set error to aborted connection
1664 if ( NETCALL_WOULDBLOCK(error) )
1665 error = WSAECONNABORTED;
1667 multi_eval_socket_error(socket, error);
1670 retries++; // keep a try count
1673 send_data += num_sent;
1674 total_sent += num_sent;
1676 } while ( length > 0 );
1679 psnet_bytes_written_frame += total_sent;
1682 //index = psnet_find_stats_loc( who_to );
1683 //if ( index != -1 )
1684 // Psnet_stats[index].total_written += send_len;
1689 // get data off the reliable socket
1690 int psnet_rel_get( PSNET_SOCKET psocket, ubyte *buffer, int max_len, int flags)
1692 int from_len, total_read, error;
1695 struct timeval timeout;
1697 ubyte rread_buffer[2];
1699 socket = (SOCKET)psocket;
1701 // see if there is data to be read
1703 FD_SET( socket, &rfds );
1705 timeout.tv_usec = 0;
1707 if ( select( socket+1, &rfds, NULL, NULL, &timeout) == SOCKET_ERROR ) {
1708 nprintf(("Network", "Error on select for read reliable: %d\n", WSAGetLastError() ));
1712 // if no data, then we can leave.
1713 if ( !FD_ISSET(socket, &rfds ) )
1716 // we know we have data to read. We must read the two byte length of the packet first
1720 from_len = recv(socket, (char *)(&rread_buffer[total_read]), read_len - total_read, 0);
1722 // from_len will be 0 when back end gracefully closes connection. We will assume that since
1723 // the close is graceful, we will info from him telling us he's left. So we'll ignore
1724 // this condition here.
1725 if ( from_len == 0 ) {
1726 nprintf(("Network", "Dumping player because recv returned 0\n"));
1727 multi_eval_socket_error( socket, WSAECONNRESET ); // this error drops player from game.
1731 // on a socket error, we need to check for WSAEWOULDBLOCK meaning that there is no more
1733 else if ( from_len == SOCKET_ERROR ) {
1734 error = WSAGetLastError();
1735 if ( !NETCALL_WOULDBLOCK(error) )
1736 multi_eval_socket_error( socket, error );
1737 return 0; // get it next frame?
1740 total_read += from_len;
1741 } while ( total_read < read_len );
1745 memcpy(&read_len, &rread_buffer[0], 2);
1746 SDL_assert( (read_len > 0) && (read_len < max_len) );
1747 if ( read_len == 0 )
1751 from_len = recv(socket, (char *)(buffer + total_read), read_len - total_read, 0);
1753 // from_len will be 0 when back end gracefully closes connection. We will assume that since
1754 // the close is graceful, we will info from him telling us he's left. So we'll ignore
1755 // this condition here.
1756 if ( from_len == 0 ) {
1757 nprintf(("Network", "Dumping player because recv returned 0\n"));
1758 multi_eval_socket_error( socket, WSAECONNRESET ); // this error drops player from game.
1762 // on a socket error, we need to check for WSAEWOULDBLOCK meaning that there is no more
1764 else if ( from_len == SOCKET_ERROR ) {
1765 error = WSAGetLastError();
1766 if ( !NETCALL_WOULDBLOCK(error) ) {
1767 multi_eval_socket_error( socket, error );
1773 total_read += from_len;
1774 } while ( total_read < read_len );
1779 // psnet_send_reliable sends the given data through the given reliable socket.
1780 int psnet_send_reliable( PSNET_SOCKET psocket, ubyte *data, int length, int flags )
1782 // don't do anything if the socket is null
1783 if(psocket == NULL){
1787 // send a reliable data packet
1788 return psnet_reliable_send(data,length,(net_addr_t*)psocket);
1791 int psnet_get_reliable( PSNET_SOCKET psocket, ubyte *buffer, int max_len, int flags)
1794 int best, best_id, i, n, size;
1796 // call the routine to read data out of the socket (which stuffs it into the packet buffers)
1797 psnet_get_socket_data(Reliable_socket,flags);
1799 #ifdef PSNET_BUFFER_OLD_SCHOOL
1800 // now determine which (if any) of the packet buffers we should look at!
1805 for (i=0; i <= Largest_packet_index; i++ ) {
1806 if ( packet_buffers[i].sequence_number > -1 ) {
1808 if ( best == -1 || (packet_buffers[i].sequence_number < best) ) {
1809 best = packet_buffers[i].sequence_number;
1815 //mprintf( (0, "Best id = %d, pn = %d, last_ecb = %x, len=%x, ne = %d\n", best_id, best, last_ecb, lastlen, neterrors ));
1816 //mprintf( (1, "<%d> ", neterrors ));
1818 if ( best_id < 0 ) return 0;
1820 size = packet_buffers[best_id].len;
1821 memcpy( buffer, packet_buffers[best_id].data, size );
1822 memcpy( psocket, &packet_buffers[best_id].from_addr, sizeof(net_addr_t) );
1823 free_packet(best_id);
1832 // function which checks the Listen_socket for possibly incoming requests to be connected.
1833 // returns 0 on error or nothing waiting. 1 if we should try to accept
1834 int psnet_rel_check_for_listen(net_addr_t *from_addr)
1838 SOCKET sock; // when trying to accept, this is new socket
1839 struct sockaddr_in ip_addr; // UDP/TCP socket structure
1845 FD_SET( Listen_socket, &rfds );
1847 timeout.tv_usec = 0;
1849 if ( select(Listen_socket+1, &rfds, NULL, NULL, &timeout) == SOCKET_ERROR ) {
1850 nprintf(("Network", "Error %d doing select on listen socket\n", WSAGetLastError() ));
1854 // check to see if Listen_socket has something -- if not, return
1855 if ( !FD_ISSET(Listen_socket, &rfds) )
1856 return INVALID_SOCKET;
1858 sock = INVALID_SOCKET;
1859 switch ( Socket_type ) {
1861 from_len = sizeof(struct sockaddr_in);
1862 sock = accept( Listen_socket, (struct sockaddr*)&ip_addr, &from_len );
1863 from_addr->port = ntohs( ip_addr.sin_port );
1864 memset(from_addr->addr, 0x00, IP_ADDRESS_LENGTH);
1865 memcpy(from_addr->addr, &ip_addr.sin_addr.s_addr, 4);
1866 nprintf(("Network","Accepted TCP connected!!\n"));
1874 if ( !psnet_get_ip(sock) ) {
1875 return INVALID_SOCKET;
1878 // make the new socket non-blocking
1879 if(sock != (SOCKET)INVALID_SOCKET){
1881 error = ioctlsocket( sock, FIONBIO, &arg );
1882 if ( error == SOCKET_ERROR ) {
1883 nprintf(("Network", "Unable to make accepted socket non-blocking -- %d", WSAGetLastError() ));
1884 return INVALID_SOCKET;
1892 int psnet_rel_get_status(PSNET_SOCKET psocket)
1895 SOCKLEN_T error_code_size = sizeof(error_code);
1898 socket = (SOCKET)psocket;
1900 if (socket == (SOCKET)INVALID_SOCKET) {
1904 if ( getsockopt(socket, SOL_SOCKET, SO_ERROR, (char*)&error_code, &error_code_size) ) {
1908 if ( !error_code ) {
1909 return RNF_CONNECTED;
1912 if ( NETCALL_WOULDBLOCK(error_code) ) {
1913 return RNF_CONNECTING;
1916 return RNF_DISCONNECTED;
1919 // psnet_get() will call the above function to read data out of the socket. It will then determine
1920 // which of the buffers we should use and pass to the routine which called us
1921 int psnet_get( void * data, net_addr_t* from_addr, int flags )
1923 // USE THIS CODE TO TEST NON-BUFFERED SOCKET READS. OUT-OF-ORDER PACKETS DROP TO NEARLY 0
1928 int read_len,from_len;
1929 struct sockaddr_in ip_addr;
1931 FD_SET( Unreliable_socket, &rfds );
1933 timeout.tv_usec = 0;
1935 if ( select( Unreliable_socket+1, &rfds, NULL, NULL, &timeout) == SOCKET_ERROR ) {
1936 nprintf(("Network", "Error %d doing a socket select on read\n", WSAGetLastError()));
1940 // if the read file descriptor is not set, then bail!
1941 if ( !FD_ISSET(Unreliable_socket, &rfds ) )
1944 // get data off the socket and process
1945 read_len = SOCKET_ERROR;
1946 from_len = sizeof(struct sockaddr_in);
1947 read_len = recvfrom( Unreliable_socket, (char*)data, MAX_PACKET_SIZE, 0, (struct sockaddr*)&ip_addr, &from_len );
1948 from_addr->port = ntohs( ip_addr.sin_port );
1949 memset(from_addr->addr, 0x00, 6);
1950 memcpy(from_addr->addr, &ip_addr.sin_addr.S_un.S_addr, 4);
1954 // call the routine to read data out of the socket (which stuffs it into the packet buffers)
1955 psnet_get_socket_data(Unreliable_socket,flags);
1957 #ifdef PSNET_BUFFER_OLD_SCHOOL
1958 int best, best_id, i, n, size;
1960 // now determine which (if any) of the packet buffers we should look at!
1965 for (i=0; i <= Largest_packet_index; i++ ) {
1966 if ( packet_buffers[i].sequence_number > -1 ) {
1968 if ( best == -1 || (packet_buffers[i].sequence_number < best) ) {
1969 best = packet_buffers[i].sequence_number;
1975 //mprintf( (0, "Best id = %d, pn = %d, last_ecb = %x, len=%x, ne = %d\n", best_id, best, last_ecb, lastlen, neterrors ));
1976 //mprintf( (1, "<%d> ", neterrors ));
1978 if ( best_id < 0 ) return 0;
1980 size = packet_buffers[best_id].len;
1981 memcpy( data, packet_buffers[best_id].data, size );
1982 memcpy( from_addr, &packet_buffers[best_id].from_addr, sizeof(net_addr_t) );
1983 free_packet(best_id);
1989 // try and get a free buffer and return its size
1990 if(psnet_buffer_get_next((ubyte*)data,&buffer_size,from_addr)){
2001 // -------------------------------------------------------------------------------------------------
2002 // psnet_broadcast()
2006 int psnet_broadcast( net_addr_t * who_to, void * data, int len, int flags )
2008 if ( Network_status != NETWORK_STATUS_RUNNING ) {
2009 nprintf(("Network","Network ==> Socket not inited in psnet_broadcast\n"));
2013 if ( !Can_broadcast ) {
2014 nprintf(("Network", "Cannot broadcast -- returning without doing anything\n"));
2018 ubyte broadcast[IP_ADDRESS_LENGTH] = {0xff, 0xff, 0xff, 0xff};
2020 // broadcasting works on a local subnet which is all we really want to do for now anyway.
2021 // we might keep this in as an option for freespace later.
2022 switch ( who_to->type ) {
2025 memcpy(who_to->addr, broadcast, IP_ADDRESS_LENGTH);
2026 psnet_send(who_to, data, len, flags);
2034 // called to clear out the socket of any remaining data
2038 ubyte data[MAX_PACKET_SIZE];
2039 net_addr_t from_addr;
2041 while ( psnet_get( data, &from_addr ) > 0 ) ;
2047 // function to keep track of bytes read/written on average during the frame
2048 void psnet_calc_socket_stats()
2050 if ( psnet_frame_int == -1 ) {
2052 for ( i = 0; i < PSNET_FRAME_FILTER; i++ ) {
2053 psnet_read_sizes[i] = 0;
2054 psnet_write_sizes[i] = 0;
2056 psnet_read_total = 0;
2057 psnet_write_total = 0;
2058 psnet_frame_int = 0;
2060 psnet_read_total -= psnet_read_sizes[psnet_frame_int];
2061 psnet_write_total -= psnet_write_sizes[psnet_frame_int];
2063 psnet_read_total += psnet_bytes_read_frame;
2064 psnet_write_total += psnet_bytes_written_frame;
2066 psnet_read_sizes[psnet_frame_int] = psnet_bytes_read_frame;
2067 psnet_write_sizes[psnet_frame_int] = psnet_bytes_written_frame;
2069 psnet_frame_int = (psnet_frame_int + 1 ) % PSNET_FRAME_FILTER;
2071 if ( psnet_frame_count > 0 ) {
2072 if ( psnet_frame_count >= PSNET_FRAME_FILTER )
2073 Psnet_bytes_read = psnet_read_total / PSNET_FRAME_FILTER;
2075 Psnet_bytes_read = psnet_read_total / psnet_frame_count;
2077 if ( psnet_frame_count >= PSNET_FRAME_FILTER )
2078 Psnet_bytes_written = psnet_write_total / PSNET_FRAME_FILTER;
2080 Psnet_bytes_written = psnet_write_total / psnet_frame_count;
2083 psnet_frame_count++;
2084 psnet_bytes_read_frame = 0;
2085 psnet_bytes_written_frame = 0;
2089 int psnet_is_valid_numeric_ip(char *ip)
2093 int val1,val2,val3,val4;
2095 // get the first ip value
2096 SDL_strlcpy(copy, ip, SDL_arraysize(copy));
2097 token = strtok(copy,".");
2101 // get the value of the token
2103 if((val1 < 0) || (val1 > 255)){
2109 token = strtok(NULL,".");
2113 // get the value of the token
2115 if((val2 < 0) || (val2 > 255)){
2121 token = strtok(NULL,".");
2125 // get the value of the token
2127 if((val3 < 0) || (val3 > 255)){
2133 token = strtok(NULL,"");
2137 // get the value of the token
2139 if((val4 < 0) || (val4 > 255)){
2144 // make sure he hasn't entered all 0's
2145 if((val1 == 0) && (val2 == 0) && (val3 == 0) && (val4 == 0)){
2154 // returns true or false if the given string is a valid ip string or not.
2155 // allow port allows us to append the port number on the end of the ip string with
2157 // so we must be sure to remove the port number
2158 int psnet_is_valid_ip_string( char *ip_string, int allow_port )
2161 struct hostent *host_ent;
2164 // our addresses may have ports, so make local copy and remove port number
2165 SDL_assert( strlen(ip_string) < 255 );
2166 SDL_strlcpy(str, ip_string, SDL_arraysize(str));
2167 c = strrchr(str, ':');
2172 addr.s_addr = inet_addr(ip_string);
2173 if ( addr.s_addr != INADDR_NONE ){
2174 // make sure the ip string is a valid format string
2175 if(psnet_is_valid_numeric_ip(ip_string)){
2180 // try name resolution
2181 host_ent = gethostbyname( ip_string );
2186 // valid host entry so return 1;
2191 // ------------------------------------------------------------------------------------------------------
2192 // PACKET BUFFERING FUNCTIONS
2195 #ifndef PSNET_BUFFER_OLD_SCHOOL
2197 // a sequence number of -1 will indicate that this packet is not valid
2198 static network_packet_buffer Psnet_buffers[MAX_PACKET_BUFFERS];
2199 static int Psnet_seq_number = 0;
2200 static int Psnet_lowest_id = 0;
2201 static int Psnet_highest_id = 0;
2203 // initialize the buffering system
2204 void psnet_buffer_init()
2208 // blast the buffer clean
2209 memset(Psnet_buffers,0,sizeof(network_packet_buffer) * MAX_PACKET_BUFFERS);
2211 // set all buffer sequence #'s to -1
2212 for(idx=0;idx<MAX_PACKET_BUFFERS;idx++){
2213 Psnet_buffers[idx].sequence_number = -1;
2216 // initialize the sequence #
2217 Psnet_seq_number = 0;
2218 Psnet_lowest_id = -1;
2219 Psnet_highest_id = -1;
2222 // buffer a packet (maintain order!)
2223 void psnet_buffer_packet(ubyte *data, int length, net_addr_t *from)
2228 // find the first empty packet
2229 for(idx=0;idx<MAX_PACKET_BUFFERS;idx++){
2230 if(Psnet_buffers[idx].sequence_number == -1){
2236 // if we didn't find the buffer, report an overrun
2238 nprintf(("Network","WARNING - Buffer overrun in psnet\n"));
2241 memcpy(Psnet_buffers[idx].data,data,length);
2242 Psnet_buffers[idx].len = length;
2243 memcpy(&Psnet_buffers[idx].from_addr,from,sizeof(net_addr_t));
2244 Psnet_buffers[idx].sequence_number = Psnet_seq_number;
2246 // keep track of the highest id#
2247 Psnet_highest_id = Psnet_seq_number++;
2249 // set the lowest id# for the first time
2250 if(Psnet_lowest_id == -1){
2251 Psnet_lowest_id = Psnet_highest_id;
2256 // get the index of the next packet in order!
2257 int psnet_buffer_get_next(ubyte *data, int *length, net_addr_t *from)
2262 // if there are no buffers, do nothing
2263 if((Psnet_lowest_id == -1) || (Psnet_lowest_id > Psnet_highest_id)){
2267 // search until we find the lowest packet index id#
2268 for(idx=0;idx<MAX_PACKET_BUFFERS;idx++){
2269 // if we found the buffer
2270 if(Psnet_buffers[idx].sequence_number == Psnet_lowest_id){
2276 // at this point, we should _always_ have found the buffer
2277 SDL_assert(found_buf);
2279 // copy out the buffer data
2280 memcpy(data,Psnet_buffers[idx].data,Psnet_buffers[idx].len);
2281 *length = Psnet_buffers[idx].len;
2282 memcpy(from,&Psnet_buffers[idx].from_addr,sizeof(net_addr_t));
2284 // now we need to cleanup the packet list
2286 // mark the buffer as free
2287 Psnet_buffers[idx].sequence_number = -1;
2295 // initialize the buffering system
2296 void psnet_buffer_init() {}
2298 // buffer a packet (maintain order!)
2299 void psnet_buffer_packet(ubyte *data, int length) {}
2301 // get the index of the next packet in order!
2302 int psnet_buffer_get_next() { return -1; }
2306 // ------------------------------------------------------------------------------------------------------
2307 // RELIABLE UDP FUNCTIONS
2310 // verbose debug output
2311 #define PSNET_RELIABLE_VERBOSE
2313 // overall buffer space allocated to the buffers
2314 #define PSNET_RELIABLE_MAX_OUT_BUFFER_SIZE (1<<18) // 256k
2315 #define PSNET_RELIABLE_MAX_IN_BUFFER_SIZE (1<<12) // 4k
2317 // outgoing reliable packets
2318 typedef struct reliable_packet_out {
2319 ubyte data[MAX_PACKET_SIZE]; // data in the original packet
2320 ushort packet_size; // size of the original packet
2321 ushort player_flags; // bitflags indexing (1<<N) into the Psnet_reliable_addr[N] array
2322 ushort player_acks; // bitflags indexing (1<<N) into the Psnet_reliable_addr[N] array
2323 int player_stamps[MAX_PLAYERS]; // timeouts for each player
2324 ubyte num_resends[MAX_PLAYERS]; // # of times we've resent to a given player
2325 ushort out_id; // identifier of the packet
2326 fix age; // how old this packet is
2327 } reliable_packet_out;
2329 // incoming reliable packets
2330 typedef struct reliable_packet_in {
2331 ushort in_id; // identifier of the received packet
2332 fix age; // when we received the packet
2333 } reliable_packet_in;
2335 // # of outgoing and incoming buffers we'll allocate
2336 #define PSNET_RELIABLE_NUM_OUT_BUFFERS (int)(PSNET_RELIABLE_MAX_OUT_BUFFER_SIZE / sizeof(reliable_packet_out))
2337 #define PSNET_RELIABLE_NUM_IN_BUFFERS (int)(PSNET_RELIABLE_MAX_IN_BUFFER_SIZE / sizeof(reliable_packet_in))
2339 // timeout to be used for the packets
2340 #define PSNET_RELIABLE_TIMEOUT 1500 // in ms
2342 // # of repeats to use
2343 #define PSNET_RELIABLE_REPEAT 8 // repeat this many times max
2346 #define PSNET_RELIABLE_INVALID 0
2349 #define PSNET_RELIABLE_ACK 0xffff
2351 // the outgoing and incoming buffers themselves
2352 reliable_packet_out *Psnet_reliable_out[PSNET_RELIABLE_NUM_OUT_BUFFERS];
2353 reliable_packet_in *Psnet_reliable_in[PSNET_RELIABLE_NUM_IN_BUFFERS];
2355 // psnet reliable address list
2356 net_addr_t Psnet_reliable_addr[MAX_PLAYERS]; // address of registered "reliable" addrs
2357 int Psnet_reliable_addr_flags; // bitflags indicating which of the above are valid
2359 // my local identifier # (will only use lower 12 bits)
2360 ushort Psnet_reliable_local_id = 0x1;
2362 // is the reliable system initialized
2363 int Psnet_reliable_inited = 0;
2365 // # of times a packet has not been delivered
2366 int Psnet_reliable_fail_count = 0;
2368 // # of times packets have had to be resent
2369 int Psnet_reliable_resend_count = 0;
2371 // # of times we've run out of packets and had to overwrite existing ones
2372 int Psnet_reliable_overwrite_count = 0;
2374 // forward declarations ------------------------------------------------------
2376 // free up all used buffers
2377 void psnet_reliable_free_all_buffers();
2379 // get the index of the passed address or -1 if it doesn't exist
2380 int psnet_reliable_addr_index(net_addr_t *addr);
2382 // get the index into the address array from the passed bitflag
2383 int psnet_reliable_index_addr(int flags);
2385 // kill all outgoing packets belonging to the passed index
2386 void psnet_reliable_kill_outgoing(int index);
2388 // generate a unique id #, given the passed in value and the address it came from, return PSNET_RELIABLE_INVALID
2389 // upper 12 bytes should be valid # and the lower 4 should be free for this function to fill in
2390 ushort psnet_reliable_get_unique_id(ushort id_num,net_addr_t *from);
2392 // get the upper 12 bit version of my id# and increment the original
2393 ushort psnet_reliable_get_next_id();
2395 // get the index of a free outgoing relible packet buffer, killing the oldest if necessary
2396 int psnet_reliable_get_free_outgoing();
2398 // get the index of a free incoming relible packet buffer, killing the oldest if necessary
2399 int psnet_reliable_get_free_incoming();
2401 // actually send the data contained with the reliable_packet_out
2402 int psnet_reliable_send_packet(reliable_packet_out *out,int force_index = 0);
2404 // evaluate the status of a reliable packet - and free it up if the thing is _done_
2405 void psnet_reliable_evaluate_status(reliable_packet_out *out);
2407 // determine if the passed id# exists in the in-packet list, return the instance where it exists, or -1 if it doesn't
2408 int psnet_reliable_find_in_id(ushort id_num);
2410 // determine if the passed id# exists in the out-packet list, return the instance where it exists, or -1 if it doesn't
2411 int psnet_reliable_find_out_id(ushort id_num);
2413 // send an ack to the specified address
2414 void psnet_reliable_send_ack(net_addr_t *addr,ushort id_num);
2417 // extern functions -----------------------------------------------------------
2419 // initialize the psnet reliable system (return 0 on fail, 1 on success)
2420 int psnet_reliable_init()
2424 // if the system is already inited, do nothing
2425 if(Psnet_reliable_inited){
2429 #ifdef PSNET_RELIABLE_VERBOSE
2430 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",
2431 PSNET_RELIABLE_MAX_OUT_BUFFER_SIZE,PSNET_RELIABLE_NUM_OUT_BUFFERS,PSNET_RELIABLE_MAX_IN_BUFFER_SIZE,PSNET_RELIABLE_NUM_IN_BUFFERS));
2435 for(idx=0;idx<PSNET_RELIABLE_NUM_OUT_BUFFERS;idx++){
2436 Psnet_reliable_out[idx] = NULL;
2438 for(idx=0;idx<PSNET_RELIABLE_NUM_IN_BUFFERS;idx++){
2439 Psnet_reliable_in[idx] = NULL;
2442 // initialize all outgoing buffers
2443 for(idx=0;idx<PSNET_RELIABLE_NUM_OUT_BUFFERS;idx++){
2444 Psnet_reliable_out[idx] = NULL;
2445 Psnet_reliable_out[idx] = (reliable_packet_out*)malloc(sizeof(reliable_packet_out));
2447 // if we failed to allocate the buffer, return failure
2448 if(Psnet_reliable_out[idx] == NULL){
2449 psnet_reliable_free_all_buffers();
2452 memset(Psnet_reliable_out[idx],0,sizeof(reliable_packet_out));
2455 // initialize all incoming buffers
2456 for(idx=0;idx<PSNET_RELIABLE_NUM_IN_BUFFERS;idx++){
2457 Psnet_reliable_in[idx] = NULL;
2458 Psnet_reliable_in[idx] = (reliable_packet_in*)malloc(sizeof(reliable_packet_in));
2460 // if we failed to allocate the buffer, return failure
2461 if(Psnet_reliable_in[idx] == NULL){
2462 psnet_reliable_free_all_buffers();
2465 memset(Psnet_reliable_in[idx],0,sizeof(reliable_packet_in));
2468 // blast the reliable address list free
2469 memset(Psnet_reliable_addr,0,sizeof(net_addr_t) * MAX_PLAYERS);
2470 Psnet_reliable_addr_flags = 0;
2472 // set the system to be initialized
2473 Psnet_reliable_inited = 1;
2475 // initialize my local id #
2476 Psnet_reliable_local_id = 0x1;
2478 // initialize the packet delivery fail count
2479 Psnet_reliable_fail_count = 0;
2481 // intialize the packet necessary resend count
2482 Psnet_reliable_resend_count = 0;
2484 // initialize # of times we've run out of packets and had to overwrite existing ones
2485 Psnet_reliable_overwrite_count = 0;
2491 // shutdown the reliable system (free up buffers, etc)
2492 void psnet_reliable_close()
2494 // if the system is not initialized, don't do anything
2495 if(!Psnet_reliable_inited){
2499 // free up all buffers
2500 psnet_reliable_free_all_buffers();
2502 // blast all addresses clean
2503 memset(Psnet_reliable_addr,0,sizeof(net_addr_t) * MAX_PLAYERS);
2504 Psnet_reliable_addr_flags = 0;
2506 // set the system as being uninitialized
2507 Psnet_reliable_inited = 0;
2510 // notify the reliable system of a new address at index N
2511 void psnet_reliable_notify_new_addr(net_addr_t *addr,int index)
2513 // copy in the address
2514 memcpy(&Psnet_reliable_addr[index],addr,sizeof(net_addr_t));
2516 // set the bit indicating its validity
2517 Psnet_reliable_addr_flags |= (1<<index);
2520 // notify the reliable system of a drop at index N
2521 void psnet_reliable_notify_drop_addr(net_addr_t *addr)
2525 // do a lookup for the address
2526 index = psnet_reliable_addr_index(addr);
2528 // clear out all packets belonging exclusively to this address
2529 psnet_reliable_kill_outgoing(index);
2531 // clear the address and its existence bit
2532 memset(&Psnet_reliable_addr[index],0,sizeof(net_addr_t));
2533 Psnet_reliable_addr_flags &= ~(1<<index);
2537 // send a reliable data packet
2538 int psnet_reliable_send(ubyte *data,int packet_size,net_addr_t *addr)
2542 reliable_packet_out *p;
2544 // if the system is not initialized, don't do anything
2545 if(!Psnet_reliable_inited){
2549 // try and find a guy to send to
2551 to_index = psnet_reliable_addr_index(addr);
2553 nprintf(("Network","PSNET RELIABLE : could not find player for outgoing packet!\n"));
2557 // attempt to get a free buffer
2559 free_buffer = psnet_reliable_get_free_outgoing();
2560 if(free_buffer == -1){
2561 Int3(); // should never happen - we should always overwrite the oldest buffer
2564 // setup the data for the outgoing packet
2565 p = Psnet_reliable_out[free_buffer];
2566 memcpy(p->data,data,packet_size);
2567 p->packet_size = (ushort)packet_size;
2568 p->player_flags |= (1<<to_index);
2569 memset(p->player_stamps,0xf,sizeof(int) * MAX_PLAYERS);
2570 p->player_stamps[to_index] = timestamp(PSNET_RELIABLE_TIMEOUT);
2571 p->out_id = psnet_reliable_get_next_id();
2572 p->age = timer_get_fixed_seconds();
2575 return psnet_reliable_send_packet(p);
2578 // process frame for all reliable stuff (call once per frame)
2579 void psnet_reliable_process()
2582 reliable_packet_out *p;
2584 // if the system is not initialized, don't do anything
2585 if(!Psnet_reliable_inited){
2589 // go through all active packets
2590 for(idx=0;idx<PSNET_RELIABLE_NUM_OUT_BUFFERS;idx++){
2591 // if the packet is active
2592 if(Psnet_reliable_out[idx]->out_id != PSNET_RELIABLE_INVALID){
2593 p = Psnet_reliable_out[idx];
2595 // loop through all active players and see if we need to resend
2596 for(s_idx=0;s_idx<MAX_PLAYERS;s_idx++){
2597 // if the packet is active for this player and he hasn't acked
2598 if(p->player_flags & (1<<s_idx) && !(p->player_acks & (1<<s_idx))){
2599 // if the timestamp has elapsed
2600 if((p->player_stamps[s_idx] != -1) && timestamp_elapsed(p->player_stamps[s_idx])){
2601 // if we are at max resends, bomb!
2602 if(p->num_resends[s_idx] >= PSNET_RELIABLE_REPEAT){
2603 #ifdef PSNET_RELIABLE_VERBOSE
2604 nprintf(("Network","PSNET RELIABLE : packet failed to be delivered (%d retries) !!\n",PSNET_RELIABLE_REPEAT));
2606 p->player_flags &= ~(1<<s_idx);
2608 // increment the fail count
2609 Psnet_reliable_fail_count++;
2611 // otherwise resend the packet
2613 // actually send the data contained with the reliable_packet_out
2614 psnet_reliable_send_packet(p,s_idx);
2616 // increment the resend count
2617 Psnet_reliable_resend_count++;
2619 #ifdef PSNET_RELIABLE_VERBOSE
2620 nprintf(("Network","PSNET RELIABLE : resending packet\n"));
2627 // evaluate if this packet has completed
2628 psnet_reliable_evaluate_status(p);
2633 // determine if the passed in reliable data should be processed, and sends an ack if necessary
2634 // return # of bytes which should be stripped off the data (reliable data header)
2635 int psnet_reliable_should_process(net_addr_t *addr,ubyte *data,int packet_size)
2637 ushort id_num,unique_id;
2641 reliable_packet_in *p;
2643 // get the reliable packet id #
2644 memcpy(&id_num,data,sizeof(ushort));
2646 // if the id# is an ack, get the id# do a lookup
2647 if(id_num == PSNET_RELIABLE_ACK){
2648 #ifdef PSNET_RELIABLE_VERBOSE
2649 nprintf(("Network","PSNET RELIABLE : ACK 1\n"));
2653 memcpy(&id_num,data+2,sizeof(ushort));
2655 // get the packet index
2656 // unique_id = psnet_reliable_get_unique_id(id_num,addr);
2658 packet_index = psnet_reliable_find_out_id(unique_id);
2659 player_index = psnet_reliable_addr_index(addr);
2660 if((packet_index != -1) && (player_index != -1)){
2661 #ifdef PSNET_RELIABLE_VERBOSE
2662 nprintf(("Network","PSNET RELIABLE : ACK 2\n"));
2665 Psnet_reliable_out[packet_index]->player_acks |= (1<<player_index);
2667 // check to see if this packet is _done_
2668 psnet_reliable_evaluate_status(Psnet_reliable_out[packet_index]);
2671 // return 4 bytes processed
2675 // otherwise - see if this is a new packet
2676 packet_index = psnet_reliable_find_in_id(id_num);
2677 if(packet_index == -1){
2680 free_index = psnet_reliable_get_free_incoming();
2681 if(free_index == -1){
2685 // setup the incoming packet
2686 p = Psnet_reliable_in[free_index];
2687 p->age = timer_get_fixed_seconds();
2688 p->in_id = psnet_reliable_get_unique_id(id_num,addr);
2691 psnet_reliable_send_ack(addr,id_num);
2693 // return 2 bytes processed
2696 // send another ack for good measure
2698 psnet_reliable_send_ack(addr,id_num);
2704 // forward definitions --------------------------------------------
2706 // free up all used buffers
2707 void psnet_reliable_free_all_buffers()
2711 // free all outgoing buffers
2712 for(idx=0;idx<PSNET_RELIABLE_NUM_OUT_BUFFERS;idx++){
2713 // if the buffer is not null, free it
2714 if(Psnet_reliable_out[idx] != NULL){
2715 free(Psnet_reliable_out[idx]);
2716 Psnet_reliable_out[idx] = NULL;
2720 // free all incoming buffers
2721 for(idx=0;idx<PSNET_RELIABLE_NUM_IN_BUFFERS;idx++){
2722 // if the buffer is not null, free it
2723 if(Psnet_reliable_in[idx] != NULL){
2724 free(Psnet_reliable_in[idx]);
2725 Psnet_reliable_in[idx] = NULL;
2730 // get the index of the passed address or -1 if it doesn't exist
2731 int psnet_reliable_addr_index(net_addr_t *addr)
2735 // look through all valid addresses
2736 for(idx=0;idx<MAX_PLAYERS;idx++){
2737 if((Psnet_reliable_addr_flags & (1<<idx)) && psnet_same(addr,&Psnet_reliable_addr[idx])){
2742 // couldn't find the address
2746 // get the index into the address array from the passed bitflag
2747 int psnet_reliable_index_addr(int flags)
2751 // look through all the bits in the flags
2752 for(idx=0;idx<MAX_PLAYERS;idx++){
2753 if(flags & (1<<idx)){
2758 // couldn't find any
2762 // kill all outgoing packets belonging to the passed index
2763 void psnet_reliable_kill_outgoing(int index)
2767 // go through all buffers
2768 for(idx=0;idx<PSNET_RELIABLE_NUM_OUT_BUFFERS;idx++){
2769 if(Psnet_reliable_out[idx]->out_id != PSNET_RELIABLE_INVALID){
2770 // if it is exclusively his, kill the whole packet
2771 if(Psnet_reliable_out[idx]->player_flags == (1<<index)){
2772 memset(Psnet_reliable_out[idx],0,sizeof(reliable_packet_out));
2775 // if it belongs to him and other players, kill his entry
2776 else if(Psnet_reliable_out[idx]->player_flags & (1<<index)){
2777 Psnet_reliable_out[idx]->player_flags &= ~(1<<index);
2778 Psnet_reliable_out[idx]->num_resends[index] = 0;
2784 // generate a unique id #, given the passed in value and the address it came from, return PSNET_RELIABLE_INVALID
2785 // upper 12 bytes should be valid # and the lower 4 should be free for this function to fill in
2786 ushort psnet_reliable_get_unique_id(ushort id_num,net_addr_t *from)
2791 // if the lower 4 bits are not clear, we've got a problem
2796 // lookup through the Psnet_reliable_addr[] list and try and find the index
2797 for(idx=0;idx<MAX_PLAYERS;idx++){
2798 if((idx == 1) /*(Psnet_reliable_addr_flags & (1<<idx)) && (psnet_same(from,&Psnet_reliable_addr[idx]))*/){
2799 // fill in the lower 4 bits
2801 id_num |= (cast & 0xf);
2806 // couldn't find an id#
2807 return PSNET_RELIABLE_INVALID;
2810 // get the upper 12 bit version of my id# and increment the original
2811 ushort psnet_reliable_get_next_id()
2813 ushort id_num = Psnet_reliable_local_id;
2815 // clear out the upper 4 bits
2818 // shift 4 bits to the left
2821 // increment the local id #
2822 if(Psnet_reliable_local_id == 0x0fff){
2823 Psnet_reliable_local_id = 0x1;
2825 Psnet_reliable_local_id++;
2828 // return the shifted value
2832 // get the index of a free outgoing relible packet buffer, killing the oldest if necessary
2833 int psnet_reliable_get_free_outgoing()
2836 int oldest_index = -1;
2839 // search through all buffers
2840 for(idx=0;idx<PSNET_RELIABLE_NUM_OUT_BUFFERS;idx++){
2841 if(Psnet_reliable_out[idx]->out_id == PSNET_RELIABLE_INVALID){
2845 // keep track of the oldest packet
2846 if((oldest_index == -1) || (Psnet_reliable_out[idx]->age < oldest)){
2848 oldest = Psnet_reliable_out[idx]->age;
2852 // if we got here, all of our buffers are full, so we should kill the oldest one
2853 memset(Psnet_reliable_out[oldest_index],0,sizeof(reliable_packet_out));
2854 Psnet_reliable_overwrite_count = 0;
2855 #ifdef PSNET_RELIABLE_VERBOSE
2856 nprintf(("Network","PSNET RELIABLE : overwriting old send buffer\n"));
2858 return oldest_index;
2861 // get the index of a free incoming relible packet buffer, killing the oldest if necessary
2862 int psnet_reliable_get_free_incoming()
2865 int oldest_index = -1;
2868 // search through all buffers
2869 for(idx=0;idx<PSNET_RELIABLE_NUM_IN_BUFFERS;idx++){
2870 if(Psnet_reliable_in[idx]->in_id == PSNET_RELIABLE_INVALID){
2874 // keep track of the oldest packet
2875 if((oldest_index == -1) || (Psnet_reliable_in[idx]->age < oldest)){
2877 oldest = Psnet_reliable_in[idx]->age;
2881 // if we got here, all of our buffers are full, so we should kill the oldest one
2882 memset(Psnet_reliable_in[oldest_index],0,sizeof(reliable_packet_in));
2883 #ifdef PSNET_RELIABLE_VERBOSE
2884 nprintf(("Network","PSNET RELIABLE : overwriting old recv buffer\n"));
2886 return oldest_index;
2889 // actually send the data contained with the reliable_packet_out
2890 int psnet_reliable_send_packet(reliable_packet_out *out,int force_index)
2892 ubyte data[MAX_PACKET_SIZE];
2894 int packet_size = 2 + out->packet_size;
2896 // stick the identifier on the front of the packet
2897 memcpy(data,&out->out_id,sizeof(ushort));
2899 // copy in the actual data
2900 memcpy(data+2,out->data,out->packet_size);
2902 // send the packet and update the timestamp for all players
2904 // send to one specified player in the packet
2906 if(force_index != 0){
2907 if(out->player_flags & (1<<force_index) && !(out->player_acks & (1<<force_index))){
2908 bytes_sent = psnet_send(&Psnet_reliable_addr[force_index],data,packet_size,PSNET_FLAG_RAW,1);
2909 out->player_stamps[force_index] = timestamp(PSNET_RELIABLE_TIMEOUT);
2910 out->num_resends[force_index]++;
2913 // send to all players contained in the packet
2915 for(idx=0;idx<MAX_PLAYERS;idx++){
2916 // if this guy is flagged and he exists and he hasn't already acked
2917 if(out->player_flags & (1<<idx) && (Psnet_reliable_addr_flags & (1<<idx)) && !(out->player_acks & (1<<idx))){
2918 bytes_sent = psnet_send(&Psnet_reliable_addr[idx],data,packet_size,PSNET_FLAG_RAW,1);
2919 out->player_stamps[idx] = timestamp(PSNET_RELIABLE_TIMEOUT);
2920 out->num_resends[idx]++;
2929 // evaluate the status of a reliable packet - and free it up if the thing is _done_
2930 void psnet_reliable_evaluate_status(reliable_packet_out *out)
2934 // check to see if all players have acked or failed miserably
2936 for(idx=0;idx<MAX_PLAYERS;idx++){
2937 // if the packet is active for this guy but he has not acked yet
2938 if((out->player_flags & (1<<idx)) && !(out->player_acks & (1<<idx))){
2944 // if its ok to annihilate this packet, do so
2946 memset(out,0,sizeof(reliable_packet_out));
2950 // determine if the passed id# exists in the in-packet list, return the instance where it exists, or -1 if it doesn't
2951 int psnet_reliable_find_in_id(ushort id_num)
2955 // if the id is 0, its invalid
2956 if(id_num == PSNET_RELIABLE_INVALID){
2960 // look through all in packets
2961 for(idx=0;idx<PSNET_RELIABLE_NUM_IN_BUFFERS;idx++){
2962 if(id_num == Psnet_reliable_in[idx]->in_id){
2971 // determine if the passed id# exists in the out-packet list, return the instance where it exists, or -1 if it doesn't
2972 int psnet_reliable_find_out_id(ushort id_num)
2976 // if the id is 0, its invalid
2977 if(id_num == PSNET_RELIABLE_INVALID){
2981 // look through all in packets
2982 for(idx=0;idx<PSNET_RELIABLE_NUM_OUT_BUFFERS;idx++){
2983 if(id_num == Psnet_reliable_out[idx]->out_id){
2992 // send an ack to the specified address
2993 void psnet_reliable_send_ack(net_addr_t *addr,ushort id_num)
2999 val = PSNET_RELIABLE_ACK;
3000 memcpy(data,&val,sizeof(ushort));
3003 memcpy(data+2,&id_num,sizeof(ushort));
3006 psnet_send(addr,data,4,PSNET_FLAG_RAW,Reliable_socket);
3009 // wrappers around select() and recvfrom() for lagging/losing data, and for sorting through different packet types
3010 int RECVFROM(SOCKET s, char * buf, int len, int flags, sockaddr *from, int *fromlen, int psnet_type)
3016 // if we have no buffer! The user should have made sure this wasn't the case by calling SELECT()
3017 ret = psnet_buffer_get_next((ubyte*)buf, &ret_len, &addr);
3023 // otherwise, stuff the outgoing data
3024 ((struct sockaddr_in*)from)->sin_port = htons(addr.port);
3025 memcpy(&((struct sockaddr_in*)from)->sin_addr.s_addr, addr.addr, 4);
3026 ((struct sockaddr_in*)from)->sin_family = AF_INET;
3027 *fromlen = sizeof(struct sockaddr_in);
3029 // return bytes read
3033 int SELECT(int nfds, fd_set *readfds, fd_set *writefds, fd_set*exceptfds, struct timeval* timeout, int psnet_type)
3035 // if this is a check for writability, just return the select
3036 if(writefds != NULL){
3037 return select(nfds, readfds, writefds, exceptfds, timeout);
3040 // do we have any buffers in here?
3041 if((Psnet_lowest_id == -1) || (Psnet_lowest_id > Psnet_highest_id)){
3049 // wrappers around sendto to sorting through different packet types
3050 int SENDTO(SOCKET s, char * buf, int len, int flags, sockaddr * to, int tolen, int psnet_type)
3052 return sendto(s, buf, len, flags, (struct sockaddr *)to, tolen);
3055 // call this once per frame to read everything off of our socket
3056 void PSNET_TOP_LAYER_PROCESS()
3058 psnet_get_socket_data(Unreliable_socket);
3061 #endif // #ifndef PSNET2