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;
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 = ((in_addr *)(Hostent->h_addr))->s_addr;
551 return LclAddr.sin_addr.s_addr;
554 // psnet_get_ip() attempts to get the local IP address of this machine
555 // returns 0 on failure, and 1 on success
556 int psnet_get_ip( SOCKET s )
560 struct sockaddr_in local_addr;
562 if ( Psnet_my_addr_valid ){
566 memset(&local_addr, 0, sizeof(struct sockaddr_in));
567 len = sizeof(struct sockaddr_in);
568 rval = getsockname(s, (struct sockaddr *)&local_addr, &len );
569 if ( rval == SOCKET_ERROR )
572 // now we should have an IP address of this machine.
573 memcpy(Psnet_my_addr.addr, &(local_addr.sin_addr), 4);
574 Psnet_my_addr.port = ntohs(local_addr.sin_port);
576 Psnet_my_addr_valid = 1;
580 // -------------------------------------------------------------------------------------------------
587 #ifndef PSNET_RELIABLE_OLD_SCHOOL
588 psnet_reliable_close();
591 if ( Network_status != NETWORK_STATUS_RUNNING )
595 WSACancelBlockingCall();
598 if ( TCP_listen_socket != (SOCKET)INVALID_SOCKET ) {
599 shutdown( TCP_listen_socket, 1 );
600 closesocket( TCP_listen_socket );
603 if ( TCP_reliable_socket != (SOCKET)INVALID_SOCKET ) {
604 shutdown( TCP_reliable_socket, 1 );
605 closesocket( TCP_reliable_socket );
608 if ( TCP_socket != (SOCKET)INVALID_SOCKET ) {
609 shutdown( TCP_socket, 1 );
610 closesocket( TCP_socket );
615 //Warning( LOCATION, "Error closing wsock!\n" );
619 Network_status = NETWORK_STATUS_NOT_INITIALIZED;
622 // function to initialize a reliable socket. All it does is call the socket() command.
623 // returns 1 on success, 0 on failure.
624 int psnet_init_stream( SOCKET *s, int type )
628 SDL_assert(type == NET_TCP);
630 sock = socket(AF_INET,SOCK_STREAM,0);
631 if ( sock == (SOCKET)INVALID_SOCKET )
639 // called by psnet_init to initialize the listen socket used by a host/server
640 int psnet_init_reliable(ushort port, int should_listen, int type)
642 SOCKET sock = 0; // JAS: Get rid of optimized warning
643 struct sockaddr_in sockaddr; // UDP/TCP socket structure
645 // set up the reliable TCP transport socket
646 if ( !psnet_init_stream(&sock, type) ) {
647 nprintf(("Network", "Unable to initialize reliable socket on port %d (%d)!\n" , port, WSAGetLastError() ));
648 return INVALID_SOCKET;
651 // bind the socket to the port
652 SDL_assert(type == NET_TCP);
654 memset( &sockaddr, 0, sizeof(struct sockaddr_in) );
655 sockaddr.sin_family = AF_INET;
656 sockaddr.sin_addr.s_addr = INADDR_ANY; //fill in with our IP
657 sockaddr.sin_port = htons( port );
658 if ( bind(sock, (struct sockaddr*)&sockaddr, sizeof (sockaddr)) == SOCKET_ERROR) {
659 nprintf(("Network", "Unable to bind reliable socket on port %d (%d)!\n" , port, WSAGetLastError() ));
660 return INVALID_SOCKET;
664 // set up the listen on the Reliable_socket port
665 if ( should_listen && listen(sock, 5) ) {
666 nprintf(("Network", "Unable to listen on Listen Socket (%d)!\n" , WSAGetLastError() ));
667 return INVALID_SOCKET;
670 // make any reliable sockets which we create that aren't listening non-blocking sockets
671 if ( !should_listen ) {
676 error = ioctlsocket( sock, FIONBIO, &arg );
677 if ( error == SOCKET_ERROR ) {
678 nprintf(("Network", "Unable to make reliable socket non-blocking -- %d", WSAGetLastError() ));
679 return INVALID_SOCKET;
682 // set the reuse option
683 if ( psnet_set_socket_mode(sock, SO_REUSEADDR, 1) == SOCKET_ERROR ) {
684 error = WSAGetLastError();
685 nprintf(("Network", "Error setting socket to reuse address -- %d\n", error));
693 void psnet_socket_options( SOCKET sock )
696 int ret, cursize, bufsize, trysize;
697 SOCKLEN_T cursizesize;
699 // Set the mode of the socket to allow broadcasting. We need to be able to broadcast
700 // when a game is searched for in IPX mode.
702 if(setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char *)&broadcast, sizeof(broadcast) )){
708 // try and increase the size of my receive buffer
709 bufsize = MAX_RECEIVE_BUFSIZE;
711 // set the current size of the receive buffer
712 cursizesize = sizeof(int);
713 getsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char *)&cursize, &cursizesize);
714 for ( trysize = bufsize; trysize >= cursize; trysize >>= 1 ) {
715 ret = setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char *)&trysize, sizeof(trysize));
716 if ( ret == SOCKET_ERROR ) {
719 wserr = WSAGetLastError();
720 if ( (wserr == WSAENOPROTOOPT) || (wserr == WSAEINVAL) )
725 getsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char *)&cursize, &cursizesize);
726 nprintf(("Network", "Receive buffer set to %d\n", cursize));
728 // set the current size of the send buffer
729 cursizesize = sizeof(int);
730 getsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *)&cursize, &cursizesize);
731 for ( trysize = bufsize; trysize >= cursize; trysize >>= 1 ) {
732 ret = setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *)&trysize, sizeof(trysize));
733 if ( ret == SOCKET_ERROR ) {
736 wserr = WSAGetLastError();
737 if ( (wserr == WSAENOPROTOOPT) || (wserr == WSAEINVAL) )
742 getsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *)&cursize, &cursizesize);
743 nprintf(("Network", "Send buffer set to %d\n", cursize));
747 // psnet_init called at game startup time and initializes all sockets that the game might use (i.e. for both
749 void psnet_init( int protocol, int port_num )
751 const char *internet_connection;
756 // UDP/TCP socket structure
757 struct sockaddr_in sockaddr;
761 #if defined(DEMO) || defined(OEM_BUILD) // not for FS2_DEMO
765 // GAME PORT INITIALIZATION STUFF
766 if ( Network_status == NETWORK_STATUS_RUNNING )
769 // 'lan' should be a safe default in 2015
770 internet_connection = os_config_read_string("Network", "NetworkConnection", "LAN");
772 if ( !SDL_strcasecmp(internet_connection, NOX("dialup")) ) {
773 ml_string("psnet_init() detected dialup connection");
775 Psnet_connection = NETWORK_CONNECTION_DIALUP;
776 } else if ( !SDL_strcasecmp(internet_connection, NOX("lan")) ) {
777 ml_string("psnet_init() detected lan connection");
779 Psnet_connection = NETWORK_CONNECTION_LAN;
781 ml_string("psnet_init() detected no connection");
783 Psnet_connection = NETWORK_CONNECTION_NONE;
786 Network_status = NETWORK_STATUS_NO_WINSOCK;
789 if (WSAStartup(0x101, &wsa_data )){
794 // get the port for running this game on. Be careful that it cannot be out of bounds
795 Psnet_default_port = DEFAULT_GAME_PORT;
796 if ( (port_num > 1023) && (port_num < USHRT_MAX) ) {
797 Psnet_default_port = (ushort)port_num;
800 #ifndef PSNET_RELIABLE_OLD_SCHOOL
801 if(!psnet_reliable_init()){
802 nprintf(("Network","PSNET RELIABLE : init failed - no networking available!\n"));
807 // initialize TCP now
808 TCP_socket = INVALID_SOCKET;
809 TCP_reliable_socket = INVALID_SOCKET;
810 TCP_listen_socket = INVALID_SOCKET;
812 Network_status = NETWORK_STATUS_NO_PROTOCOL;
813 TCP_socket = socket( AF_INET, SOCK_DGRAM, 0 );
814 if ( TCP_socket == (SOCKET)INVALID_SOCKET ) {
815 Tcp_failure_code = WSAGetLastError();
816 nprintf(("Network", "Error on TCP startup %d\n", Tcp_failure_code));
821 memset(&sockaddr,0,sizeof(struct sockaddr_in));
822 sockaddr.sin_family = AF_INET;
824 sockaddr.sin_addr.s_addr = INADDR_ANY; //fill in with our IP
826 sockaddr.sin_port = htons( Psnet_default_port );
827 if ( bind(TCP_socket, (struct sockaddr*)&sockaddr, sizeof (sockaddr)) == SOCKET_ERROR) {
828 Tcp_failure_code = WSAGetLastError();
829 nprintf(( "Network", "Couldn't bind TCP socket (%d)! Invalidating TCP\n", Tcp_failure_code ));
833 #ifdef PSNET_RELIABLE_OLD_SCHOOL
834 // set up reliable socket (using SPX).
835 TCP_reliable_socket = psnet_init_reliable( 0, 0, NET_TCP );
836 if ( TCP_reliable_socket == (SOCKET)INVALID_SOCKET ) {
837 Tcp_failure_code = WSAGetLastError();
838 nprintf(( "Network", "Couldn't initialize TCP reliable socket (OLD SCHOOL) (%d)! Invalidating TCP\n", Tcp_failure_code ));
842 TCP_listen_socket = psnet_init_reliable( (u_short)(Psnet_default_port-1), 1, NET_TCP );
843 if ( TCP_listen_socket == (SOCKET)INVALID_SOCKET ) {
844 Tcp_failure_code = WSAGetLastError();
845 nprintf(( "Network", "Couldn't initialize TCP listen socket (OLD SCHOOL) (%d)! Invalidating TCP\n", Tcp_failure_code ));
852 psnet_socket_options( TCP_socket );
853 Tcp_can_broadcast = Can_broadcast;
856 // fire up a second UDP socket for "reliable" transport
857 #ifndef PSNET_RELIABLE_OLD_SCHOOL
858 TCP_reliable_socket = socket( AF_INET, SOCK_DGRAM, 0 );
859 if ( TCP_reliable_socket != INVALID_SOCKET ) {
861 memset(&sockaddr,0,sizeof(struct sockaddr_in));
862 sockaddr.sin_family = AF_INET;
864 sockaddr.sin_addr.s_addr = INADDR_ANY; //fill in with our IP
865 //unsigned long my_ip = sock_get_ip();
866 //memcpy(&sockaddr.sin_addr.s_addr,&my_ip,sizeof(uint));
868 sockaddr.sin_port = htons( (ushort)(port+1) );
869 if ( bind(TCP_reliable_socket, (struct sockaddr*)&sockaddr, sizeof (sockaddr)) == SOCKET_ERROR) {
870 nprintf(( "Network", "Couldn't bind TCP socket (%d)! Invalidating TCP\n", WSAGetLastError() ));
874 psnet_socket_options( TCP_reliable_socket );
881 Network_status = NETWORK_STATUS_RUNNING;
883 nprintf(("Network","TCP Initialized\n"));
885 // with TCP initialized, see if the RAS services are installed
889 psnet_frame_int = -1; // for counting bytes per frame
892 #ifdef PSNET_BUFFER_OLD_SCHOOL
896 // initialize the packet buffer stuff. We use an array (the packet_free_list) to determine
897 // which of the packet buffers we can use next.
899 for (i=0; i<MAX_PACKET_BUFFERS; i++ ) {
900 packet_buffers[i].sequence_number = -1;
901 packet_free_list[i] = (short)i;
903 Num_packet_buffers = 0;
904 Largest_packet_index = 0;
906 // initialize the new buffering system
911 #define MAX_TMPBUF_SIZE 1024
913 #ifdef PSNET_RELIABLE_OLD_SCHOOL
914 // function to shutdown and close the given socket. It takes a couple of things into consideration
915 // when closing, such as possibly reiniting reliable sockets if they are closed here.
916 void psnet_rel_close_socket( PSNET_SOCKET *p_sockp )
922 sockp = (SOCKET *)p_sockp;
924 if ( *sockp == (SOCKET)INVALID_SOCKET )
928 if ( *sockp == TCP_reliable_socket )
929 nprintf(("network", "Closing my relibale TCP socket\n"));
931 nprintf(("Network", "Closing client's reliable socket\n"));
934 // make the socket blocking
935 //unsigned long val = 0;
936 //rval = ioctlsocket(*sockp,FIONBIO,&val);
937 //if ( rval == SOCKET_ERROR ) {
938 // error = WSAGetLastError();
939 // nprintf(("Network", "Error %d when trying to make reliable socket blocking.\n", error));
942 // set the socket to linger with a timeout of 0
946 rval = setsockopt(*sockp,SOL_SOCKET,SO_LINGER,(char*)&l_val,sizeof(linger));
947 if ( rval == SOCKET_ERROR ) {
948 error = WSAGetLastError();
949 nprintf(("Network", "Error %d when trying to set linger value.\n", error));
952 // see if this socket is my Reliable_socket. If so, I will have to reinitialize it!
954 if ( *sockp == TCP_reliable_socket )
955 reinit_type = NET_TCP;
957 // if this is the server connection, mark it as done
958 if (*sockp == (SOCKET)Serverconn) {
959 Serverconn = 0xffffffff;
963 rval = shutdown( *sockp, 2); // shut the whole damn thing down.
964 if ( rval == SOCKET_ERROR ) {
965 error = WSAGetLastError();
966 nprintf(("Network", "Error %d on socket shutdown\n", error));
970 shutdown( *sockp, 1 );
972 while ( rval && (rval != SOCKET_ERROR) ) {
973 char tmp_buf[MAX_TMPBUF_SIZE];
975 rval = recv( *sockp, tmp_buf, MAX_TMPBUF_SIZE, 0 );
976 if ( rval == SOCKET_ERROR ) {
977 error = WSAGetLastError();
978 if ( NETCALL_WOULDBLOCK(error) )
983 rval = closesocket( *sockp );
984 if ( rval == SOCKET_ERROR ) {
986 error = WSAGetLastError();
987 nprintf(("Network", "Error %d on closing socket\n", error ));
991 *sockp = INVALID_SOCKET;
993 // see if we need to reinitialize
994 if ( reinit_type != -1 ) {
995 if ( reinit_type == NET_TCP){
996 TCP_reliable_socket = psnet_init_reliable( 0, 0, NET_TCP);
997 Reliable_socket = TCP_reliable_socket;
1002 // function to shutdown and close the given socket. It takes a couple of things into consideration
1003 // when closing, such as possibly reiniting reliable sockets if they are closed here.
1004 void psnet_close_socket( PSNET_SOCKET *p_sockp )
1008 // copy the address to be removed
1009 memcpy(&remove,&((net_addr_t*)(*p_sockp)),sizeof(net_addr_t));
1011 // remove it from the reliable address list
1012 psnet_reliable_notify_drop_addr(&remove);
1014 // invalidate the passed in "socket"
1019 // function to check the status of the reliable socket and try to re-initialize it if necessary.
1020 // win95 seems to have trouble doing a reinit of the socket immediately after close, so this
1021 // function exists to check the status, and reinitialize if we need to
1022 int psnet_rel_check()
1024 // if our Reliable_socket is valid, simply return true to indicate all is well.
1025 if ( Reliable_socket != (SOCKET)INVALID_SOCKET )
1028 // based on our protocol type, try to reinitialize the socket we need.
1029 SDL_assert(Socket_type == NET_TCP);
1031 TCP_reliable_socket = psnet_init_reliable( 0, 0, NET_TCP);
1032 Reliable_socket = TCP_reliable_socket;
1034 // return our status.
1035 if ( Reliable_socket == (SOCKET)INVALID_SOCKET )
1041 // this function is called from a high level at FreeSpace to set the protocol that the user wishes to use
1042 int psnet_use_protocol( int protocol )
1044 // zero out my address
1045 Psnet_my_addr_valid = 0;
1046 memset( &Psnet_my_addr, 0, sizeof(Psnet_my_addr) );
1048 // wait until we choose a protocol to determine if we can broadcast
1051 SDL_assert(protocol == NET_TCP);
1053 if ( Network_status != NETWORK_STATUS_RUNNING )
1056 // assign the TCP_* sockets to the socket values used elsewhere
1057 Unreliable_socket = TCP_socket;
1058 Reliable_socket = TCP_reliable_socket;
1059 Listen_socket = TCP_listen_socket;
1061 Can_broadcast = Tcp_can_broadcast;
1063 nprintf(("Network","Psnet : TCP broadcast\n"));
1066 nprintf(("Network","Psnet using - NET_TCP\n"));
1068 Psnet_my_addr.type = protocol;
1069 Socket_type = protocol;
1074 #define MAX_CONNECT_TRIES 10
1076 // attacmpt to connect() to the server's tcp socket. socket parameter is simply assigned to the
1077 // Reliable_socket socket created in psnet_init
1078 void psnet_rel_connect_to_server( PSNET_SOCKET *psocket, net_addr_t *server_addr)
1080 struct sockaddr_in sockaddr; // UDP/TCP socket structure
1081 struct sockaddr *addr; // pointer to struct sockaddr to make coding easier
1083 ubyte iaddr[IP_ADDRESS_LENGTH];
1085 int name_length, val;
1087 memset(iaddr, 0x00, IP_ADDRESS_LENGTH);
1088 memcpy(iaddr, server_addr->addr, IP_ADDRESS_LENGTH);
1089 port = (u_short)(server_addr->port - 1);
1091 socket = (SOCKET *)psocket;
1093 SDL_assert(Socket_type == NET_TCP);
1095 sockaddr.sin_family = AF_INET;
1096 memcpy(&sockaddr.sin_addr.s_addr, iaddr, 4);
1097 sockaddr.sin_port = htons(port);
1098 addr = (struct sockaddr *)&sockaddr;
1099 name_length = sizeof(sockaddr);
1102 ml_string(NOX("Attempting to perform reliable TCP connect to server"));
1104 // connect this guys Reliable_socket to the socket parameter passed in
1105 *socket = INVALID_SOCKET;
1106 val = connect(Reliable_socket, addr, name_length);
1108 // I suppose that we could have a valid socket right away
1109 if ( val != SOCKET_ERROR ) {
1110 *socket = Reliable_socket;
1114 error = WSAGetLastError();
1115 if ( NETCALL_WOULDBLOCK(error) ) { // use select to find out when socket is writeable
1116 int is_set, num_tries;
1118 struct timeval timeout;
1120 // call select -- and return if an error leaving our connection to the client invalid
1124 FD_SET( Reliable_socket, &wfds );
1126 timeout.tv_usec = 500000; //500000 micro seconds is 1/2 second
1128 is_set = select( Reliable_socket+1, NULL, &wfds, NULL, &timeout);
1130 // check for error on select first
1131 if ( is_set == SOCKET_ERROR ) {
1132 nprintf(("Network", "Error on select for connect %d\n", WSAGetLastError() ));
1134 } else if (is_set) { // if set, then we have connection, move forward
1137 SDL_Delay(10); // sleep for 10 ms and try again
1140 } while ( num_tries < MAX_CONNECT_TRIES );
1142 if ( num_tries == MAX_CONNECT_TRIES )
1145 *socket = Reliable_socket;
1148 nprintf(("Network", "Connecting with server failed %d\n", error ));
1149 *socket = INVALID_SOCKET;
1153 // if we have a connection, get my address from getsockname
1154 if ( *socket == Reliable_socket ) {
1155 if ( !psnet_get_ip(Reliable_socket) ) {
1156 *socket = INVALID_SOCKET;
1160 Serverconn = *socket;
1165 void psnet_calc_bytes_per_frame()
1170 // -------------------------------------------------------------------------------------------------
1175 int psnet_same_no_port( net_addr_t * a1, net_addr_t * a2 )
1177 if ( !memcmp(a1->addr, a2->addr, IP_ADDRESS_LENGTH) )
1182 int psnet_same( net_addr_t * a1, net_addr_t * a2 )
1184 return psnet_same_no_port( a1, a2 );
1186 if ( !memcmp(a1->addr, a2->addr, 6) && a1->port == a2->port)
1192 // -------------------------------------------------------------------------------------------------
1197 char* psnet_addr_to_string( char * text, const int max_textlen, net_addr_t * address )
1200 if ( Network_status != NETWORK_STATUS_RUNNING ) {
1201 SDL_strlcpy( text, XSTR("[no networking]",910), max_textlen );
1207 SDL_assert(address->type == NET_TCP);
1209 switch ( address->type ) {
1211 memcpy(&temp_addr.s_addr, address->addr, 4);
1212 SDL_strlcpy( text, inet_ntoa(temp_addr), max_textlen );
1225 // -------------------------------------------------------------------------------------------------
1226 // psnet_undescribe()
1230 void psnet_string_to_addr( net_addr_t * address, char * text, const int max_textlen )
1233 char str[255], *c, *port;
1236 if ( Network_status != NETWORK_STATUS_RUNNING ) {
1237 SDL_strlcpy( text, XSTR("[no networking]",910), max_textlen );
1241 // copy the text string to local storage to look for ports
1242 SDL_assert( strlen(text) < 255 );
1243 SDL_strlcpy(str, text, SDL_arraysize(str));
1244 c = strrchr(str, ':');
1251 switch ( address->type ) {
1253 addr.s_addr = inet_addr(str);
1254 // if we get INADDR_NONE returns, then we need to try and resolve the host
1256 if ( addr.s_addr == INADDR_NONE ) {
1257 he = gethostbyname( str );
1258 // returns a non-null pointer if successful, so get the address
1260 addr.s_addr = ((in_addr *)(he->h_addr))->s_addr; // this is the address in network byte order
1262 addr.s_addr = INADDR_NONE;
1266 memset(address->addr, 0x00, IP_ADDRESS_LENGTH);
1267 memcpy(address->addr, &addr.s_addr, 4);
1269 address->port = (ushort)(atoi(port));
1280 // psnet_get_socket_data() will get data out of the socket and stuff it into the packet_buffers
1281 // The original psnet_get() now calls this function, then determines which of the packet buffers
1282 // to package up and use
1283 void psnet_get_socket_data(SOCKET socket, int flags = PSNET_FLAG_RAW)
1285 struct sockaddr_in ip_addr; // UDP/TCP socket structure
1290 net_addr_t from_addr;
1291 network_checksum_packet packet_read;
1292 network_checksum_packet packet_data;
1294 // clear the addresses to remove compiler warnings
1295 memset(&ip_addr, 0, sizeof(struct sockaddr_in));
1297 if ( Network_status != NETWORK_STATUS_RUNNING ) {
1298 nprintf(("Network","Network ==> socket not inited in psnet_get\n"));
1303 #ifdef PSNET_BUFFER_OLD_SCHOOL
1305 // if there are no more packet buffers that we can use, then we must bail here before reading
1307 if ( Num_packet_buffers >= MAX_PACKET_BUFFERS ) {
1308 nprintf(("Network", "Packet buffer overrun in psnet_get()\n"));
1313 // check if there is any data on the socket to be read. The amount of data that can be
1314 // atomically read is stored in len.
1317 FD_SET( socket, &rfds );
1319 timeout.tv_usec = 0;
1321 if ( select( socket+1, &rfds, NULL, NULL, &timeout) == SOCKET_ERROR ) {
1322 nprintf(("Network", "Error %d doing a socket select on read\n", WSAGetLastError()));
1326 // if the read file descriptor is not set, then bail!
1327 if ( !FD_ISSET(socket, &rfds ) )
1330 // get data off the socket and process
1331 read_len = SOCKET_ERROR;
1332 switch ( Socket_type ) {
1334 from_len = sizeof(struct sockaddr_in);
1335 if(flags & PSNET_FLAG_RAW){
1336 read_len = recvfrom( socket, (char*)packet_read.data, MAX_PACKET_SIZE, 0, (struct sockaddr*)&ip_addr, &from_len );
1338 read_len = recvfrom( socket, (char *)&packet_read, sizeof(packet_data), 0, (struct sockaddr*)&ip_addr, &from_len );
1347 // set the from_addr for storage into the packet buffer structure
1348 from_addr.type = Socket_type;
1350 switch ( Socket_type ) {
1352 if(socket == Reliable_socket){
1353 from_addr.port = Psnet_default_port;
1355 from_addr.port = ntohs( ip_addr.sin_port );
1357 memset(from_addr.addr, 0x00, IP_ADDRESS_LENGTH);
1358 memcpy(from_addr.addr, &ip_addr.sin_addr.s_addr, 4);
1366 if ( read_len == SOCKET_ERROR ) {
1368 int x = WSAGetLastError();
1369 nprintf(("Network", "Read error on socket. Winsock error %d \n", x));
1374 #ifndef PSNET_RELIABLE_OLD_SCHOOL
1376 // now we check to see if this is a reliable packet, and act accordindly
1377 if(socket == Reliable_socket){
1378 // this function processes the incoming packet, and determines if the system should continue to process the data
1379 shave_size = psnet_reliable_should_process(&from_addr,packet_read.data,read_len);
1383 // copy in from data+2, so we skip the reliable data header
1384 memcpy(packet_data.data,packet_read.data + shave_size,read_len);
1386 // subtract out the size of the reliable header
1387 read_len -= shave_size;
1390 memcpy(packet_data.data,packet_read.data,read_len);
1393 memcpy(packet_data.data,packet_read.data,read_len);
1396 #ifdef PSNET_BUFFER_OLD_SCHOOL
1400 // if we had no error reading from the socket, then determine if we need to calculate a
1401 // checksum on the packet
1402 if ( !(flags & PSNET_FLAG_RAW) && (packet_data.flags & PSNET_FLAG_CHECKSUM) ) {
1405 // calculate the size of the data that is actual real data
1406 len = read_len - (sizeof(packet_data) - MAX_CHECKSUM_PACKET_SIZE);
1407 checksum = psnet_calc_checksum( packet_data.data, len );
1408 if ( checksum != packet_data.checksum ) {
1409 nprintf(("Network", "bad checksum on incoming packet -- discarding\n"));
1412 data = packet_data.data;
1413 packet_id = packet_data.sequence_number;
1415 network_naked_packet *packet;
1417 // just read in the raw socket data and length
1418 if(flags & PSNET_FLAG_RAW){
1419 data = packet_data.data;
1424 // we don't have a checksum packet. cast the data to the naked packet type and
1425 // copy it over to passed parameters
1426 packet = (network_naked_packet *)&packet_data;
1428 len = read_len - (sizeof(network_naked_packet) - MAX_PACKET_SIZE);
1429 data = packet->data;
1431 packet_id = packet->sequence_number;
1435 // look at the sequence number compared to what we last received
1436 if ( Last_packet_id > -1 ) {
1437 if ( packet_id != (Last_packet_id+1) ) {
1438 //if ( packet_id < Last_packet_id )
1439 // nprintf(("network", "packet %d came in delayed (last id was %d\n", packet_id, Last_packet_id));
1440 //else if ( packet_id > (Last_packet_id+1) )
1441 // nprintf(("Network", "missed %d packet(s). last id %d. This id %d\n", (packet_id - Last_packet_id), Last_packet_id, packet_id));
1444 Last_packet_id = packet_id;
1447 psnet_do_net_stats( &from_addr, read_len, 1 );
1448 psnet_bytes_read_frame += read_len;
1451 // put all of the data (length, who from, etc.) into the next available packet buffer
1452 // slot. We should be assured of a slot here because of the check at the beginning
1453 // of the while loop
1454 SDL_assert ( Num_packet_buffers < MAX_PACKET_BUFFERS );
1455 id = packet_free_list[ Num_packet_buffers++ ];
1456 if (id > Largest_packet_index ) Largest_packet_index = id;
1457 packet_buffers[id].len = len; // use the flags field of the packet structure to hold the data length
1458 packet_buffers[id].sequence_number = packet_id;
1459 packet_buffers[id].from_addr = from_addr;
1460 memcpy( packet_buffers[id].data, data, len );
1463 psnet_do_net_stats( &from_addr, read_len, 1 );
1464 psnet_bytes_read_frame += read_len;
1467 // buffer the packet
1468 psnet_buffer_packet(packet_data.data,read_len,&from_addr);
1473 // -------------------------------------------------------------------------------------------------
1478 int psnet_send( net_addr_t * who_to, void * data, int len, int flags, int reliable_socket )
1482 struct sockaddr_in sockaddr; // UDP/TCP socket structure
1484 ubyte iaddr[IP_ADDRESS_LENGTH], *send_data;
1487 struct timeval timeout;
1489 if(!reliable_socket){
1490 send_sock = Unreliable_socket;
1492 send_sock = Reliable_socket;
1495 if ( Network_status != NETWORK_STATUS_RUNNING ) {
1496 nprintf(("Network","Network ==> Socket not inited in psnet_send\n"));
1500 if ( psnet_same( who_to, &Psnet_my_addr) ){
1504 memset(iaddr, 0x00, IP_ADDRESS_LENGTH);
1505 memcpy(iaddr, who_to->addr, IP_ADDRESS_LENGTH);
1507 if ( memcmp(iaddr, Null_address, IP_ADDRESS_LENGTH) == 0) {
1508 nprintf(("Network","Network ==> send to address is 0 in psnet_send\n"));
1512 if(send_sock == Unreliable_socket){
1513 port = who_to->port;
1514 } else if(send_sock == Reliable_socket){
1515 port = DEFAULT_GAME_PORT + 1;
1517 port = who_to->port;
1521 nprintf(("Network","Network ==> destination port %d invalid in psnet_send\n", port));
1525 #ifdef PSNET_BUFFER_OLD_SCHOOL
1526 network_checksum_packet Send_network_checksum_packet;
1527 network_naked_packet Send_network_naked_packet;
1529 // determine from the flags whether or not this packet should have a checksum.
1530 if ( flags & PSNET_FLAG_CHECKSUM ) {
1531 // can't send raw data with a checksum, dumbass!
1532 SDL_assert(!(flags & PSNET_FLAG_RAW));
1534 Send_network_checksum_packet.sequence_number = Next_packet_id++;
1535 Send_network_checksum_packet.flags = PSNET_FLAG_CHECKSUM;
1537 Send_network_checksum_packet.checksum = psnet_calc_checksum(data, len);
1538 memcpy( Send_network_checksum_packet.data, data, len );
1539 send_len = sizeof(Send_network_checksum_packet) - MAX_CHECKSUM_PACKET_SIZE + len;
1540 send_data = (ubyte *)&Send_network_checksum_packet;
1542 // send standard psnet stuff
1543 if(!(flags & PSNET_FLAG_RAW)){
1544 Send_network_naked_packet.sequence_number = Next_packet_id++;
1545 Send_network_naked_packet.flags = 0;
1547 memcpy(Send_network_naked_packet.data, data, len);
1548 send_len = sizeof(Send_network_naked_packet) - MAX_PACKET_SIZE + len; // gets us the real size of the structure
1549 send_data = (ubyte *)&Send_network_naked_packet;
1553 send_data = (ubyte*)data;
1558 send_data = (ubyte*)data;
1564 FD_SET( send_sock, &wfds );
1566 timeout.tv_usec = 0;
1568 if ( select( send_sock+1, NULL, &wfds, NULL, &timeout) == SOCKET_ERROR ) {
1569 nprintf(("Network", "Error on blocking select for write %d\n", WSAGetLastError() ));
1573 // if the write file descriptor is not set, then bail!
1574 if ( !FD_ISSET(send_sock, &wfds ) )
1578 switch ( who_to->type ) {
1581 sockaddr.sin_family = AF_INET;
1582 memcpy(&sockaddr.sin_addr.s_addr, iaddr, 4);
1583 sockaddr.sin_port = htons(port);
1585 ret = sendto( send_sock, (char *)send_data, send_len, 0, (struct sockaddr*)&sockaddr, sizeof(sockaddr) );
1589 SDL_assert(0); // unknown protocol
1594 if ( ret != SOCKET_ERROR ) {
1596 psnet_bytes_written_frame += send_len;
1597 psnet_do_net_stats( who_to, send_len, 0 );
1601 //Warning( LOCATION, "Couldn't send data (0x%x)!\n", WSAGetLastError() );
1605 #ifdef PSNET_BUFFER_OLD_SCHOOL
1606 // routine to "free" a packet buffer
1607 void free_packet( int id )
1609 packet_buffers[id].sequence_number = -1;
1610 packet_free_list[ --Num_packet_buffers ] = (short)id;
1611 if ( Largest_packet_index == id)
1612 while ((--Largest_packet_index>0) && (packet_buffers[Largest_packet_index].sequence_number == -1 ));
1616 #ifdef PSNET_RELIABLE_OLD_SCHOOL
1617 // psnet_send_reliable sends the given data through the given reliable socket.
1619 #define MAX_RSEND_BUFFER 2048
1620 ubyte rsend_buffer[MAX_RSEND_BUFFER];
1622 int psnet_rel_send( PSNET_SOCKET psocket, ubyte *data, int length, int flags )
1625 int num_sent, total_sent, error, retries;
1627 unsigned short s_length;
1629 socket = (SOCKET)psocket;
1632 if ( Network_status != NETWORK_STATUS_RUNNING ) {
1633 nprintf(("Network","Network ==> Socket not inited in psnet_send\n"));
1637 if ( socket == (SOCKET)INVALID_SOCKET ) // might happen in race conditions -- should get cleaned up.
1640 SDL_assert( length < MAX_RSEND_BUFFER );
1642 // copy the length of the data into the beginning of the buffer. then put the data into the buffer
1643 // after the length value
1644 SDL_assert( length > 0 );
1645 s_length = (ushort)length;
1646 memcpy( &rsend_buffer[0], &s_length, sizeof(s_length) );
1647 memcpy( &rsend_buffer[2], data, length );
1653 num_sent = send( socket, (char *)rsend_buffer, length+sizeof(s_length), 0 );
1654 if ( num_sent == SOCKET_ERROR ) {
1655 error = WSAGetLastError();
1656 if ( !NETCALL_WOULDBLOCK(error) || (retries > MAX_SEND_RETRIES) ) { // means that we would block on send -- not really an error
1658 // if error is would block, then set error to aborted connection
1659 if ( NETCALL_WOULDBLOCK(error) )
1660 error = WSAECONNABORTED;
1662 multi_eval_socket_error(socket, error);
1665 retries++; // keep a try count
1668 send_data += num_sent;
1669 total_sent += num_sent;
1671 } while ( length > 0 );
1674 psnet_bytes_written_frame += total_sent;
1677 //index = psnet_find_stats_loc( who_to );
1678 //if ( index != -1 )
1679 // Psnet_stats[index].total_written += send_len;
1684 // get data off the reliable socket
1685 int psnet_rel_get( PSNET_SOCKET psocket, ubyte *buffer, int max_len, int flags)
1687 int from_len, total_read, error;
1690 struct timeval timeout;
1692 ubyte rread_buffer[2];
1694 socket = (SOCKET)psocket;
1696 // see if there is data to be read
1698 FD_SET( socket, &rfds );
1700 timeout.tv_usec = 0;
1702 if ( select( socket+1, &rfds, NULL, NULL, &timeout) == SOCKET_ERROR ) {
1703 nprintf(("Network", "Error on select for read reliable: %d\n", WSAGetLastError() ));
1707 // if no data, then we can leave.
1708 if ( !FD_ISSET(socket, &rfds ) )
1711 // we know we have data to read. We must read the two byte length of the packet first
1715 from_len = recv(socket, (char *)(&rread_buffer[total_read]), read_len - total_read, 0);
1717 // from_len will be 0 when back end gracefully closes connection. We will assume that since
1718 // the close is graceful, we will info from him telling us he's left. So we'll ignore
1719 // this condition here.
1720 if ( from_len == 0 ) {
1721 nprintf(("Network", "Dumping player because recv returned 0\n"));
1722 multi_eval_socket_error( socket, WSAECONNRESET ); // this error drops player from game.
1726 // on a socket error, we need to check for WSAEWOULDBLOCK meaning that there is no more
1728 else if ( from_len == SOCKET_ERROR ) {
1729 error = WSAGetLastError();
1730 if ( !NETCALL_WOULDBLOCK(error) )
1731 multi_eval_socket_error( socket, error );
1732 return 0; // get it next frame?
1735 total_read += from_len;
1736 } while ( total_read < read_len );
1740 memcpy(&read_len, &rread_buffer[0], 2);
1741 SDL_assert( (read_len > 0) && (read_len < max_len) );
1742 if ( read_len == 0 )
1746 from_len = recv(socket, (char *)(buffer + total_read), read_len - total_read, 0);
1748 // from_len will be 0 when back end gracefully closes connection. We will assume that since
1749 // the close is graceful, we will info from him telling us he's left. So we'll ignore
1750 // this condition here.
1751 if ( from_len == 0 ) {
1752 nprintf(("Network", "Dumping player because recv returned 0\n"));
1753 multi_eval_socket_error( socket, WSAECONNRESET ); // this error drops player from game.
1757 // on a socket error, we need to check for WSAEWOULDBLOCK meaning that there is no more
1759 else if ( from_len == SOCKET_ERROR ) {
1760 error = WSAGetLastError();
1761 if ( !NETCALL_WOULDBLOCK(error) ) {
1762 multi_eval_socket_error( socket, error );
1768 total_read += from_len;
1769 } while ( total_read < read_len );
1774 // psnet_send_reliable sends the given data through the given reliable socket.
1775 int psnet_send_reliable( PSNET_SOCKET psocket, ubyte *data, int length, int flags )
1777 // don't do anything if the socket is null
1778 if(psocket == NULL){
1782 // send a reliable data packet
1783 return psnet_reliable_send(data,length,(net_addr_t*)psocket);
1786 int psnet_get_reliable( PSNET_SOCKET psocket, ubyte *buffer, int max_len, int flags)
1789 int best, best_id, i, n, size;
1791 // call the routine to read data out of the socket (which stuffs it into the packet buffers)
1792 psnet_get_socket_data(Reliable_socket,flags);
1794 #ifdef PSNET_BUFFER_OLD_SCHOOL
1795 // now determine which (if any) of the packet buffers we should look at!
1800 for (i=0; i <= Largest_packet_index; i++ ) {
1801 if ( packet_buffers[i].sequence_number > -1 ) {
1803 if ( best == -1 || (packet_buffers[i].sequence_number < best) ) {
1804 best = packet_buffers[i].sequence_number;
1810 //mprintf( (0, "Best id = %d, pn = %d, last_ecb = %x, len=%x, ne = %d\n", best_id, best, last_ecb, lastlen, neterrors ));
1811 //mprintf( (1, "<%d> ", neterrors ));
1813 if ( best_id < 0 ) return 0;
1815 size = packet_buffers[best_id].len;
1816 memcpy( buffer, packet_buffers[best_id].data, size );
1817 memcpy( psocket, &packet_buffers[best_id].from_addr, sizeof(net_addr_t) );
1818 free_packet(best_id);
1827 // function which checks the Listen_socket for possibly incoming requests to be connected.
1828 // returns 0 on error or nothing waiting. 1 if we should try to accept
1829 int psnet_rel_check_for_listen(net_addr_t *from_addr)
1833 SOCKET sock; // when trying to accept, this is new socket
1834 struct sockaddr_in ip_addr; // UDP/TCP socket structure
1840 FD_SET( Listen_socket, &rfds );
1842 timeout.tv_usec = 0;
1844 if ( select(Listen_socket+1, &rfds, NULL, NULL, &timeout) == SOCKET_ERROR ) {
1845 nprintf(("Network", "Error %d doing select on listen socket\n", WSAGetLastError() ));
1849 // check to see if Listen_socket has something -- if not, return
1850 if ( !FD_ISSET(Listen_socket, &rfds) )
1851 return INVALID_SOCKET;
1853 sock = INVALID_SOCKET;
1854 switch ( Socket_type ) {
1856 from_len = sizeof(struct sockaddr_in);
1857 sock = accept( Listen_socket, (struct sockaddr*)&ip_addr, &from_len );
1858 from_addr->port = ntohs( ip_addr.sin_port );
1859 memset(from_addr->addr, 0x00, IP_ADDRESS_LENGTH);
1860 memcpy(from_addr->addr, &ip_addr.sin_addr.s_addr, 4);
1861 nprintf(("Network","Accepted TCP connected!!\n"));
1869 if ( !psnet_get_ip(sock) ) {
1870 return INVALID_SOCKET;
1873 // make the new socket non-blocking
1874 if(sock != (SOCKET)INVALID_SOCKET){
1876 error = ioctlsocket( sock, FIONBIO, &arg );
1877 if ( error == SOCKET_ERROR ) {
1878 nprintf(("Network", "Unable to make accepted socket non-blocking -- %d", WSAGetLastError() ));
1879 return INVALID_SOCKET;
1887 int psnet_rel_get_status(PSNET_SOCKET psocket)
1890 SOCKLEN_T error_code_size = sizeof(error_code);
1893 socket = (SOCKET)psocket;
1895 if (socket == (SOCKET)INVALID_SOCKET) {
1899 if ( getsockopt(socket, SOL_SOCKET, SO_ERROR, (char*)&error_code, &error_code_size) ) {
1903 if ( !error_code ) {
1904 return RNF_CONNECTED;
1907 if ( NETCALL_WOULDBLOCK(error_code) ) {
1908 return RNF_CONNECTING;
1911 return RNF_DISCONNECTED;
1914 // psnet_get() will call the above function to read data out of the socket. It will then determine
1915 // which of the buffers we should use and pass to the routine which called us
1916 int psnet_get( void * data, net_addr_t* from_addr, int flags )
1918 // USE THIS CODE TO TEST NON-BUFFERED SOCKET READS. OUT-OF-ORDER PACKETS DROP TO NEARLY 0
1923 int read_len,from_len;
1924 struct sockaddr_in ip_addr;
1926 FD_SET( Unreliable_socket, &rfds );
1928 timeout.tv_usec = 0;
1930 if ( select( Unreliable_socket+1, &rfds, NULL, NULL, &timeout) == SOCKET_ERROR ) {
1931 nprintf(("Network", "Error %d doing a socket select on read\n", WSAGetLastError()));
1935 // if the read file descriptor is not set, then bail!
1936 if ( !FD_ISSET(Unreliable_socket, &rfds ) )
1939 // get data off the socket and process
1940 read_len = SOCKET_ERROR;
1941 from_len = sizeof(struct sockaddr_in);
1942 read_len = recvfrom( Unreliable_socket, (char*)data, MAX_PACKET_SIZE, 0, (struct sockaddr*)&ip_addr, &from_len );
1943 from_addr->port = ntohs( ip_addr.sin_port );
1944 memset(from_addr->addr, 0x00, 6);
1945 memcpy(from_addr->addr, &ip_addr.sin_addr.S_un.S_addr, 4);
1949 // call the routine to read data out of the socket (which stuffs it into the packet buffers)
1950 psnet_get_socket_data(Unreliable_socket,flags);
1952 #ifdef PSNET_BUFFER_OLD_SCHOOL
1953 int best, best_id, i, n, size;
1955 // now determine which (if any) of the packet buffers we should look at!
1960 for (i=0; i <= Largest_packet_index; i++ ) {
1961 if ( packet_buffers[i].sequence_number > -1 ) {
1963 if ( best == -1 || (packet_buffers[i].sequence_number < best) ) {
1964 best = packet_buffers[i].sequence_number;
1970 //mprintf( (0, "Best id = %d, pn = %d, last_ecb = %x, len=%x, ne = %d\n", best_id, best, last_ecb, lastlen, neterrors ));
1971 //mprintf( (1, "<%d> ", neterrors ));
1973 if ( best_id < 0 ) return 0;
1975 size = packet_buffers[best_id].len;
1976 memcpy( data, packet_buffers[best_id].data, size );
1977 memcpy( from_addr, &packet_buffers[best_id].from_addr, sizeof(net_addr_t) );
1978 free_packet(best_id);
1984 // try and get a free buffer and return its size
1985 if(psnet_buffer_get_next((ubyte*)data,&buffer_size,from_addr)){
1996 // -------------------------------------------------------------------------------------------------
1997 // psnet_broadcast()
2001 int psnet_broadcast( net_addr_t * who_to, void * data, int len, int flags )
2003 if ( Network_status != NETWORK_STATUS_RUNNING ) {
2004 nprintf(("Network","Network ==> Socket not inited in psnet_broadcast\n"));
2008 if ( !Can_broadcast ) {
2009 nprintf(("Network", "Cannot broadcast -- returning without doing anything\n"));
2013 ubyte broadcast[IP_ADDRESS_LENGTH] = {0xff, 0xff, 0xff, 0xff};
2015 // broadcasting works on a local subnet which is all we really want to do for now anyway.
2016 // we might keep this in as an option for freespace later.
2017 switch ( who_to->type ) {
2020 memcpy(who_to->addr, broadcast, IP_ADDRESS_LENGTH);
2021 psnet_send(who_to, data, len, flags);
2029 // called to clear out the socket of any remaining data
2033 ubyte data[MAX_PACKET_SIZE];
2034 net_addr_t from_addr;
2036 while ( psnet_get( data, &from_addr ) > 0 ) ;
2042 // function to keep track of bytes read/written on average during the frame
2043 void psnet_calc_socket_stats()
2045 if ( psnet_frame_int == -1 ) {
2047 for ( i = 0; i < PSNET_FRAME_FILTER; i++ ) {
2048 psnet_read_sizes[i] = 0;
2049 psnet_write_sizes[i] = 0;
2051 psnet_read_total = 0;
2052 psnet_write_total = 0;
2053 psnet_frame_int = 0;
2055 psnet_read_total -= psnet_read_sizes[psnet_frame_int];
2056 psnet_write_total -= psnet_write_sizes[psnet_frame_int];
2058 psnet_read_total += psnet_bytes_read_frame;
2059 psnet_write_total += psnet_bytes_written_frame;
2061 psnet_read_sizes[psnet_frame_int] = psnet_bytes_read_frame;
2062 psnet_write_sizes[psnet_frame_int] = psnet_bytes_written_frame;
2064 psnet_frame_int = (psnet_frame_int + 1 ) % PSNET_FRAME_FILTER;
2066 if ( psnet_frame_count > 0 ) {
2067 if ( psnet_frame_count >= PSNET_FRAME_FILTER )
2068 Psnet_bytes_read = psnet_read_total / PSNET_FRAME_FILTER;
2070 Psnet_bytes_read = psnet_read_total / psnet_frame_count;
2072 if ( psnet_frame_count >= PSNET_FRAME_FILTER )
2073 Psnet_bytes_written = psnet_write_total / PSNET_FRAME_FILTER;
2075 Psnet_bytes_written = psnet_write_total / psnet_frame_count;
2078 psnet_frame_count++;
2079 psnet_bytes_read_frame = 0;
2080 psnet_bytes_written_frame = 0;
2084 int psnet_is_valid_numeric_ip(char *ip)
2088 int val1,val2,val3,val4;
2090 // get the first ip value
2091 SDL_strlcpy(copy, ip, SDL_arraysize(copy));
2092 token = strtok(copy,".");
2096 // get the value of the token
2098 if((val1 < 0) || (val1 > 255)){
2104 token = strtok(NULL,".");
2108 // get the value of the token
2110 if((val2 < 0) || (val2 > 255)){
2116 token = strtok(NULL,".");
2120 // get the value of the token
2122 if((val3 < 0) || (val3 > 255)){
2128 token = strtok(NULL,"");
2132 // get the value of the token
2134 if((val4 < 0) || (val4 > 255)){
2139 // make sure he hasn't entered all 0's
2140 if((val1 == 0) && (val2 == 0) && (val3 == 0) && (val4 == 0)){
2149 // returns true or false if the given string is a valid ip string or not.
2150 // allow port allows us to append the port number on the end of the ip string with
2152 // so we must be sure to remove the port number
2153 int psnet_is_valid_ip_string( char *ip_string, int allow_port )
2156 struct hostent *host_ent;
2159 // our addresses may have ports, so make local copy and remove port number
2160 SDL_assert( strlen(ip_string) < 255 );
2161 SDL_strlcpy(str, ip_string, SDL_arraysize(str));
2162 c = strrchr(str, ':');
2167 addr.s_addr = inet_addr(ip_string);
2168 if ( addr.s_addr != INADDR_NONE ){
2169 // make sure the ip string is a valid format string
2170 if(psnet_is_valid_numeric_ip(ip_string)){
2175 // try name resolution
2176 host_ent = gethostbyname( ip_string );
2181 // valid host entry so return 1;
2186 // ------------------------------------------------------------------------------------------------------
2187 // PACKET BUFFERING FUNCTIONS
2190 #ifndef PSNET_BUFFER_OLD_SCHOOL
2192 // a sequence number of -1 will indicate that this packet is not valid
2193 static network_packet_buffer Psnet_buffers[MAX_PACKET_BUFFERS];
2194 static int Psnet_seq_number = 0;
2195 static int Psnet_lowest_id = 0;
2196 static int Psnet_highest_id = 0;
2198 // initialize the buffering system
2199 void psnet_buffer_init()
2203 // blast the buffer clean
2204 memset(Psnet_buffers,0,sizeof(network_packet_buffer) * MAX_PACKET_BUFFERS);
2206 // set all buffer sequence #'s to -1
2207 for(idx=0;idx<MAX_PACKET_BUFFERS;idx++){
2208 Psnet_buffers[idx].sequence_number = -1;
2211 // initialize the sequence #
2212 Psnet_seq_number = 0;
2213 Psnet_lowest_id = -1;
2214 Psnet_highest_id = -1;
2217 // buffer a packet (maintain order!)
2218 void psnet_buffer_packet(ubyte *data, int length, net_addr_t *from)
2223 // find the first empty packet
2224 for(idx=0;idx<MAX_PACKET_BUFFERS;idx++){
2225 if(Psnet_buffers[idx].sequence_number == -1){
2231 // if we didn't find the buffer, report an overrun
2233 nprintf(("Network","WARNING - Buffer overrun in psnet\n"));
2236 memcpy(Psnet_buffers[idx].data,data,length);
2237 Psnet_buffers[idx].len = length;
2238 memcpy(&Psnet_buffers[idx].from_addr,from,sizeof(net_addr_t));
2239 Psnet_buffers[idx].sequence_number = Psnet_seq_number;
2241 // keep track of the highest id#
2242 Psnet_highest_id = Psnet_seq_number++;
2244 // set the lowest id# for the first time
2245 if(Psnet_lowest_id == -1){
2246 Psnet_lowest_id = Psnet_highest_id;
2251 // get the index of the next packet in order!
2252 int psnet_buffer_get_next(ubyte *data, int *length, net_addr_t *from)
2257 // if there are no buffers, do nothing
2258 if((Psnet_lowest_id == -1) || (Psnet_lowest_id > Psnet_highest_id)){
2262 // search until we find the lowest packet index id#
2263 for(idx=0;idx<MAX_PACKET_BUFFERS;idx++){
2264 // if we found the buffer
2265 if(Psnet_buffers[idx].sequence_number == Psnet_lowest_id){
2271 // at this point, we should _always_ have found the buffer
2272 SDL_assert(found_buf);
2274 // copy out the buffer data
2275 memcpy(data,Psnet_buffers[idx].data,Psnet_buffers[idx].len);
2276 *length = Psnet_buffers[idx].len;
2277 memcpy(from,&Psnet_buffers[idx].from_addr,sizeof(net_addr_t));
2279 // now we need to cleanup the packet list
2281 // mark the buffer as free
2282 Psnet_buffers[idx].sequence_number = -1;
2290 // initialize the buffering system
2291 void psnet_buffer_init() {}
2293 // buffer a packet (maintain order!)
2294 void psnet_buffer_packet(ubyte *data, int length) {}
2296 // get the index of the next packet in order!
2297 int psnet_buffer_get_next() { return -1; }
2301 // ------------------------------------------------------------------------------------------------------
2302 // RELIABLE UDP FUNCTIONS
2305 // verbose debug output
2306 #define PSNET_RELIABLE_VERBOSE
2308 // overall buffer space allocated to the buffers
2309 #define PSNET_RELIABLE_MAX_OUT_BUFFER_SIZE (1<<18) // 256k
2310 #define PSNET_RELIABLE_MAX_IN_BUFFER_SIZE (1<<12) // 4k
2312 // outgoing reliable packets
2313 typedef struct reliable_packet_out {
2314 ubyte data[MAX_PACKET_SIZE]; // data in the original packet
2315 ushort packet_size; // size of the original packet
2316 ushort player_flags; // bitflags indexing (1<<N) into the Psnet_reliable_addr[N] array
2317 ushort player_acks; // bitflags indexing (1<<N) into the Psnet_reliable_addr[N] array
2318 int player_stamps[MAX_PLAYERS]; // timeouts for each player
2319 ubyte num_resends[MAX_PLAYERS]; // # of times we've resent to a given player
2320 ushort out_id; // identifier of the packet
2321 fix age; // how old this packet is
2322 } reliable_packet_out;
2324 // incoming reliable packets
2325 typedef struct reliable_packet_in {
2326 ushort in_id; // identifier of the received packet
2327 fix age; // when we received the packet
2328 } reliable_packet_in;
2330 // # of outgoing and incoming buffers we'll allocate
2331 #define PSNET_RELIABLE_NUM_OUT_BUFFERS (int)(PSNET_RELIABLE_MAX_OUT_BUFFER_SIZE / sizeof(reliable_packet_out))
2332 #define PSNET_RELIABLE_NUM_IN_BUFFERS (int)(PSNET_RELIABLE_MAX_IN_BUFFER_SIZE / sizeof(reliable_packet_in))
2334 // timeout to be used for the packets
2335 #define PSNET_RELIABLE_TIMEOUT 1500 // in ms
2337 // # of repeats to use
2338 #define PSNET_RELIABLE_REPEAT 8 // repeat this many times max
2341 #define PSNET_RELIABLE_INVALID 0
2344 #define PSNET_RELIABLE_ACK 0xffff
2346 // the outgoing and incoming buffers themselves
2347 reliable_packet_out *Psnet_reliable_out[PSNET_RELIABLE_NUM_OUT_BUFFERS];
2348 reliable_packet_in *Psnet_reliable_in[PSNET_RELIABLE_NUM_IN_BUFFERS];
2350 // psnet reliable address list
2351 net_addr_t Psnet_reliable_addr[MAX_PLAYERS]; // address of registered "reliable" addrs
2352 int Psnet_reliable_addr_flags; // bitflags indicating which of the above are valid
2354 // my local identifier # (will only use lower 12 bits)
2355 ushort Psnet_reliable_local_id = 0x1;
2357 // is the reliable system initialized
2358 int Psnet_reliable_inited = 0;
2360 // # of times a packet has not been delivered
2361 int Psnet_reliable_fail_count = 0;
2363 // # of times packets have had to be resent
2364 int Psnet_reliable_resend_count = 0;
2366 // # of times we've run out of packets and had to overwrite existing ones
2367 int Psnet_reliable_overwrite_count = 0;
2369 // forward declarations ------------------------------------------------------
2371 // free up all used buffers
2372 void psnet_reliable_free_all_buffers();
2374 // get the index of the passed address or -1 if it doesn't exist
2375 int psnet_reliable_addr_index(net_addr_t *addr);
2377 // get the index into the address array from the passed bitflag
2378 int psnet_reliable_index_addr(int flags);
2380 // kill all outgoing packets belonging to the passed index
2381 void psnet_reliable_kill_outgoing(int index);
2383 // generate a unique id #, given the passed in value and the address it came from, return PSNET_RELIABLE_INVALID
2384 // upper 12 bytes should be valid # and the lower 4 should be free for this function to fill in
2385 ushort psnet_reliable_get_unique_id(ushort id_num,net_addr_t *from);
2387 // get the upper 12 bit version of my id# and increment the original
2388 ushort psnet_reliable_get_next_id();
2390 // get the index of a free outgoing relible packet buffer, killing the oldest if necessary
2391 int psnet_reliable_get_free_outgoing();
2393 // get the index of a free incoming relible packet buffer, killing the oldest if necessary
2394 int psnet_reliable_get_free_incoming();
2396 // actually send the data contained with the reliable_packet_out
2397 int psnet_reliable_send_packet(reliable_packet_out *out,int force_index = 0);
2399 // evaluate the status of a reliable packet - and free it up if the thing is _done_
2400 void psnet_reliable_evaluate_status(reliable_packet_out *out);
2402 // determine if the passed id# exists in the in-packet list, return the instance where it exists, or -1 if it doesn't
2403 int psnet_reliable_find_in_id(ushort id_num);
2405 // determine if the passed id# exists in the out-packet list, return the instance where it exists, or -1 if it doesn't
2406 int psnet_reliable_find_out_id(ushort id_num);
2408 // send an ack to the specified address
2409 void psnet_reliable_send_ack(net_addr_t *addr,ushort id_num);
2412 // extern functions -----------------------------------------------------------
2414 // initialize the psnet reliable system (return 0 on fail, 1 on success)
2415 int psnet_reliable_init()
2419 // if the system is already inited, do nothing
2420 if(Psnet_reliable_inited){
2424 #ifdef PSNET_RELIABLE_VERBOSE
2425 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",
2426 PSNET_RELIABLE_MAX_OUT_BUFFER_SIZE,PSNET_RELIABLE_NUM_OUT_BUFFERS,PSNET_RELIABLE_MAX_IN_BUFFER_SIZE,PSNET_RELIABLE_NUM_IN_BUFFERS));
2430 for(idx=0;idx<PSNET_RELIABLE_NUM_OUT_BUFFERS;idx++){
2431 Psnet_reliable_out[idx] = NULL;
2433 for(idx=0;idx<PSNET_RELIABLE_NUM_IN_BUFFERS;idx++){
2434 Psnet_reliable_in[idx] = NULL;
2437 // initialize all outgoing buffers
2438 for(idx=0;idx<PSNET_RELIABLE_NUM_OUT_BUFFERS;idx++){
2439 Psnet_reliable_out[idx] = NULL;
2440 Psnet_reliable_out[idx] = (reliable_packet_out*)malloc(sizeof(reliable_packet_out));
2442 // if we failed to allocate the buffer, return failure
2443 if(Psnet_reliable_out[idx] == NULL){
2444 psnet_reliable_free_all_buffers();
2447 memset(Psnet_reliable_out[idx],0,sizeof(reliable_packet_out));
2450 // initialize all incoming buffers
2451 for(idx=0;idx<PSNET_RELIABLE_NUM_IN_BUFFERS;idx++){
2452 Psnet_reliable_in[idx] = NULL;
2453 Psnet_reliable_in[idx] = (reliable_packet_in*)malloc(sizeof(reliable_packet_in));
2455 // if we failed to allocate the buffer, return failure
2456 if(Psnet_reliable_in[idx] == NULL){
2457 psnet_reliable_free_all_buffers();
2460 memset(Psnet_reliable_in[idx],0,sizeof(reliable_packet_in));
2463 // blast the reliable address list free
2464 memset(Psnet_reliable_addr,0,sizeof(net_addr_t) * MAX_PLAYERS);
2465 Psnet_reliable_addr_flags = 0;
2467 // set the system to be initialized
2468 Psnet_reliable_inited = 1;
2470 // initialize my local id #
2471 Psnet_reliable_local_id = 0x1;
2473 // initialize the packet delivery fail count
2474 Psnet_reliable_fail_count = 0;
2476 // intialize the packet necessary resend count
2477 Psnet_reliable_resend_count = 0;
2479 // initialize # of times we've run out of packets and had to overwrite existing ones
2480 Psnet_reliable_overwrite_count = 0;
2486 // shutdown the reliable system (free up buffers, etc)
2487 void psnet_reliable_close()
2489 // if the system is not initialized, don't do anything
2490 if(!Psnet_reliable_inited){
2494 // free up all buffers
2495 psnet_reliable_free_all_buffers();
2497 // blast all addresses clean
2498 memset(Psnet_reliable_addr,0,sizeof(net_addr_t) * MAX_PLAYERS);
2499 Psnet_reliable_addr_flags = 0;
2501 // set the system as being uninitialized
2502 Psnet_reliable_inited = 0;
2505 // notify the reliable system of a new address at index N
2506 void psnet_reliable_notify_new_addr(net_addr_t *addr,int index)
2508 // copy in the address
2509 memcpy(&Psnet_reliable_addr[index],addr,sizeof(net_addr_t));
2511 // set the bit indicating its validity
2512 Psnet_reliable_addr_flags |= (1<<index);
2515 // notify the reliable system of a drop at index N
2516 void psnet_reliable_notify_drop_addr(net_addr_t *addr)
2520 // do a lookup for the address
2521 index = psnet_reliable_addr_index(addr);
2523 // clear out all packets belonging exclusively to this address
2524 psnet_reliable_kill_outgoing(index);
2526 // clear the address and its existence bit
2527 memset(&Psnet_reliable_addr[index],0,sizeof(net_addr_t));
2528 Psnet_reliable_addr_flags &= ~(1<<index);
2532 // send a reliable data packet
2533 int psnet_reliable_send(ubyte *data,int packet_size,net_addr_t *addr)
2537 reliable_packet_out *p;
2539 // if the system is not initialized, don't do anything
2540 if(!Psnet_reliable_inited){
2544 // try and find a guy to send to
2545 to_index = psnet_reliable_addr_index(addr);
2547 nprintf(("Network","PSNET RELIABLE : could not find player for outgoing packet!\n"));
2551 // attempt to get a free buffer
2552 free_buffer = psnet_reliable_get_free_outgoing();
2553 if(free_buffer == -1){
2554 Int3(); // should never happen - we should always overwrite the oldest buffer
2557 // setup the data for the outgoing packet
2558 p = Psnet_reliable_out[free_buffer];
2559 memcpy(p->data,data,packet_size);
2560 p->packet_size = (ushort)packet_size;
2561 p->player_flags |= (1<<to_index);
2562 memset(p->player_stamps,0xf,sizeof(int) * MAX_PLAYERS);
2563 p->player_stamps[to_index] = timestamp(PSNET_RELIABLE_TIMEOUT);
2564 p->out_id = psnet_reliable_get_next_id();
2565 p->age = timer_get_fixed_seconds();
2568 return psnet_reliable_send_packet(p);
2571 // process frame for all reliable stuff (call once per frame)
2572 void psnet_reliable_process()
2575 reliable_packet_out *p;
2577 // if the system is not initialized, don't do anything
2578 if(!Psnet_reliable_inited){
2582 // go through all active packets
2583 for(idx=0;idx<PSNET_RELIABLE_NUM_OUT_BUFFERS;idx++){
2584 // if the packet is active
2585 if(Psnet_reliable_out[idx]->out_id != PSNET_RELIABLE_INVALID){
2586 p = Psnet_reliable_out[idx];
2588 // loop through all active players and see if we need to resend
2589 for(s_idx=0;s_idx<MAX_PLAYERS;s_idx++){
2590 // if the packet is active for this player and he hasn't acked
2591 if(p->player_flags & (1<<s_idx) && !(p->player_acks & (1<<s_idx))){
2592 // if the timestamp has elapsed
2593 if((p->player_stamps[s_idx] != -1) && timestamp_elapsed(p->player_stamps[s_idx])){
2594 // if we are at max resends, bomb!
2595 if(p->num_resends[s_idx] >= PSNET_RELIABLE_REPEAT){
2596 #ifdef PSNET_RELIABLE_VERBOSE
2597 nprintf(("Network","PSNET RELIABLE : packet failed to be delivered (%d retries) !!\n",PSNET_RELIABLE_REPEAT));
2599 p->player_flags &= ~(1<<s_idx);
2601 // increment the fail count
2602 Psnet_reliable_fail_count++;
2604 // otherwise resend the packet
2606 // actually send the data contained with the reliable_packet_out
2607 psnet_reliable_send_packet(p,s_idx);
2609 // increment the resend count
2610 Psnet_reliable_resend_count++;
2612 #ifdef PSNET_RELIABLE_VERBOSE
2613 nprintf(("Network","PSNET RELIABLE : resending packet\n"));
2620 // evaluate if this packet has completed
2621 psnet_reliable_evaluate_status(p);
2626 // determine if the passed in reliable data should be processed, and sends an ack if necessary
2627 // return # of bytes which should be stripped off the data (reliable data header)
2628 int psnet_reliable_should_process(net_addr_t *addr,ubyte *data,int packet_size)
2630 ushort id_num,unique_id;
2634 reliable_packet_in *p;
2636 // get the reliable packet id #
2637 memcpy(&id_num,data,sizeof(ushort));
2639 // if the id# is an ack, get the id# do a lookup
2640 if(id_num == PSNET_RELIABLE_ACK){
2641 #ifdef PSNET_RELIABLE_VERBOSE
2642 nprintf(("Network","PSNET RELIABLE : ACK 1\n"));
2646 memcpy(&id_num,data+2,sizeof(ushort));
2648 // get the packet index
2649 // unique_id = psnet_reliable_get_unique_id(id_num,addr);
2651 packet_index = psnet_reliable_find_out_id(unique_id);
2652 player_index = psnet_reliable_addr_index(addr);
2653 if((packet_index != -1) && (player_index != -1)){
2654 #ifdef PSNET_RELIABLE_VERBOSE
2655 nprintf(("Network","PSNET RELIABLE : ACK 2\n"));
2658 Psnet_reliable_out[packet_index]->player_acks |= (1<<player_index);
2660 // check to see if this packet is _done_
2661 psnet_reliable_evaluate_status(Psnet_reliable_out[packet_index]);
2664 // return 4 bytes processed
2668 // otherwise - see if this is a new packet
2669 packet_index = psnet_reliable_find_in_id(id_num);
2670 if(packet_index == -1){
2672 free_index = psnet_reliable_get_free_incoming();
2673 if(free_index == -1){
2677 // setup the incoming packet
2678 p = Psnet_reliable_in[free_index];
2679 p->age = timer_get_fixed_seconds();
2680 p->in_id = psnet_reliable_get_unique_id(id_num,addr);
2683 psnet_reliable_send_ack(addr,id_num);
2685 // return 2 bytes processed
2688 // send another ack for good measure
2690 psnet_reliable_send_ack(addr,id_num);
2696 // forward definitions --------------------------------------------
2698 // free up all used buffers
2699 void psnet_reliable_free_all_buffers()
2703 // free all outgoing buffers
2704 for(idx=0;idx<PSNET_RELIABLE_NUM_OUT_BUFFERS;idx++){
2705 // if the buffer is not null, free it
2706 if(Psnet_reliable_out[idx] != NULL){
2707 free(Psnet_reliable_out[idx]);
2708 Psnet_reliable_out[idx] = NULL;
2712 // free all incoming buffers
2713 for(idx=0;idx<PSNET_RELIABLE_NUM_IN_BUFFERS;idx++){
2714 // if the buffer is not null, free it
2715 if(Psnet_reliable_in[idx] != NULL){
2716 free(Psnet_reliable_in[idx]);
2717 Psnet_reliable_in[idx] = NULL;
2722 // get the index of the passed address or -1 if it doesn't exist
2723 int psnet_reliable_addr_index(net_addr_t *addr)
2727 // look through all valid addresses
2728 for(idx=0;idx<MAX_PLAYERS;idx++){
2729 if((Psnet_reliable_addr_flags & (1<<idx)) && psnet_same(addr,&Psnet_reliable_addr[idx])){
2734 // couldn't find the address
2738 // get the index into the address array from the passed bitflag
2739 int psnet_reliable_index_addr(int flags)
2743 // look through all the bits in the flags
2744 for(idx=0;idx<MAX_PLAYERS;idx++){
2745 if(flags & (1<<idx)){
2750 // couldn't find any
2754 // kill all outgoing packets belonging to the passed index
2755 void psnet_reliable_kill_outgoing(int index)
2759 // go through all buffers
2760 for(idx=0;idx<PSNET_RELIABLE_NUM_OUT_BUFFERS;idx++){
2761 if(Psnet_reliable_out[idx]->out_id != PSNET_RELIABLE_INVALID){
2762 // if it is exclusively his, kill the whole packet
2763 if(Psnet_reliable_out[idx]->player_flags == (1<<index)){
2764 memset(Psnet_reliable_out[idx],0,sizeof(reliable_packet_out));
2767 // if it belongs to him and other players, kill his entry
2768 else if(Psnet_reliable_out[idx]->player_flags & (1<<index)){
2769 Psnet_reliable_out[idx]->player_flags &= ~(1<<index);
2770 Psnet_reliable_out[idx]->num_resends[index] = 0;
2776 // generate a unique id #, given the passed in value and the address it came from, return PSNET_RELIABLE_INVALID
2777 // upper 12 bytes should be valid # and the lower 4 should be free for this function to fill in
2778 ushort psnet_reliable_get_unique_id(ushort id_num,net_addr_t *from)
2783 // if the lower 4 bits are not clear, we've got a problem
2788 // lookup through the Psnet_reliable_addr[] list and try and find the index
2789 for(idx=0;idx<MAX_PLAYERS;idx++){
2790 if(idx == 1 /*(Psnet_reliable_addr_flags & (1<<idx)) && (psnet_same(from,&Psnet_reliable_addr[idx]))*/){
2791 // fill in the lower 4 bits
2793 id_num |= (cast & 0xf);
2798 // couldn't find an id#
2799 return PSNET_RELIABLE_INVALID;
2802 // get the upper 12 bit version of my id# and increment the original
2803 ushort psnet_reliable_get_next_id()
2805 ushort id_num = Psnet_reliable_local_id;
2807 // clear out the upper 4 bits
2810 // shift 4 bits to the left
2813 // increment the local id #
2814 if(Psnet_reliable_local_id == 0x0fff){
2815 Psnet_reliable_local_id = 0x1;
2817 Psnet_reliable_local_id++;
2820 // return the shifted value
2824 // get the index of a free outgoing relible packet buffer, killing the oldest if necessary
2825 int psnet_reliable_get_free_outgoing()
2828 int oldest_index = -1;
2831 // search through all buffers
2832 for(idx=0;idx<PSNET_RELIABLE_NUM_OUT_BUFFERS;idx++){
2833 if(Psnet_reliable_out[idx]->out_id == PSNET_RELIABLE_INVALID){
2837 // keep track of the oldest packet
2838 if((oldest_index == -1) || (Psnet_reliable_out[idx]->age < oldest)){
2840 oldest = Psnet_reliable_out[idx]->age;
2844 // if we got here, all of our buffers are full, so we should kill the oldest one
2845 memset(Psnet_reliable_out[oldest_index],0,sizeof(reliable_packet_out));
2846 Psnet_reliable_overwrite_count = 0;
2847 #ifdef PSNET_RELIABLE_VERBOSE
2848 nprintf(("Network","PSNET RELIABLE : overwriting old send buffer\n"));
2850 return oldest_index;
2853 // get the index of a free incoming relible packet buffer, killing the oldest if necessary
2854 int psnet_reliable_get_free_incoming()
2857 int oldest_index = -1;
2860 // search through all buffers
2861 for(idx=0;idx<PSNET_RELIABLE_NUM_IN_BUFFERS;idx++){
2862 if(Psnet_reliable_in[idx]->in_id == PSNET_RELIABLE_INVALID){
2866 // keep track of the oldest packet
2867 if((oldest_index == -1) || (Psnet_reliable_in[idx]->age < oldest)){
2869 oldest = Psnet_reliable_in[idx]->age;
2873 // if we got here, all of our buffers are full, so we should kill the oldest one
2874 memset(Psnet_reliable_in[oldest_index],0,sizeof(reliable_packet_in));
2875 #ifdef PSNET_RELIABLE_VERBOSE
2876 nprintf(("Network","PSNET RELIABLE : overwriting old recv buffer\n"));
2878 return oldest_index;
2881 // actually send the data contained with the reliable_packet_out
2882 int psnet_reliable_send_packet(reliable_packet_out *out,int force_index)
2884 ubyte data[MAX_PACKET_SIZE];
2886 int packet_size = 2 + out->packet_size;
2888 // stick the identifier on the front of the packet
2889 memcpy(data,&out->out_id,sizeof(ushort));
2891 // copy in the actual data
2892 memcpy(data+2,out->data,out->packet_size);
2894 // send the packet and update the timestamp for all players
2896 // send to one specified player in the packet
2898 if(force_index != 0){
2899 if(out->player_flags & (1<<force_index) && !(out->player_acks & (1<<force_index))){
2900 bytes_sent = psnet_send(&Psnet_reliable_addr[force_index],data,packet_size,PSNET_FLAG_RAW,1);
2901 out->player_stamps[force_index] = timestamp(PSNET_RELIABLE_TIMEOUT);
2902 out->num_resends[force_index]++;
2905 // send to all players contained in the packet
2907 for(idx=0;idx<MAX_PLAYERS;idx++){
2908 // if this guy is flagged and he exists and he hasn't already acked
2909 if(out->player_flags & (1<<idx) && (Psnet_reliable_addr_flags & (1<<idx)) && !(out->player_acks & (1<<idx))){
2910 bytes_sent = psnet_send(&Psnet_reliable_addr[idx],data,packet_size,PSNET_FLAG_RAW,1);
2911 out->player_stamps[idx] = timestamp(PSNET_RELIABLE_TIMEOUT);
2912 out->num_resends[idx]++;
2921 // evaluate the status of a reliable packet - and free it up if the thing is _done_
2922 void psnet_reliable_evaluate_status(reliable_packet_out *out)
2926 // check to see if all players have acked or failed miserably
2928 for(idx=0;idx<MAX_PLAYERS;idx++){
2929 // if the packet is active for this guy but he has not acked yet
2930 if((out->player_flags & (1<<idx)) && !(out->player_acks & (1<<idx))){
2936 // if its ok to annihilate this packet, do so
2938 memset(out,0,sizeof(reliable_packet_out));
2942 // determine if the passed id# exists in the in-packet list, return the instance where it exists, or -1 if it doesn't
2943 int psnet_reliable_find_in_id(ushort id_num)
2947 // if the id is 0, its invalid
2948 if(id_num == PSNET_RELIABLE_INVALID){
2952 // look through all in packets
2953 for(idx=0;idx<PSNET_RELIABLE_NUM_IN_BUFFERS;idx++){
2954 if(id_num == Psnet_reliable_in[idx]->in_id){
2963 // determine if the passed id# exists in the out-packet list, return the instance where it exists, or -1 if it doesn't
2964 int psnet_reliable_find_out_id(ushort id_num)
2968 // if the id is 0, its invalid
2969 if(id_num == PSNET_RELIABLE_INVALID){
2973 // look through all in packets
2974 for(idx=0;idx<PSNET_RELIABLE_NUM_OUT_BUFFERS;idx++){
2975 if(id_num == Psnet_reliable_out[idx]->out_id){
2984 // send an ack to the specified address
2985 void psnet_reliable_send_ack(net_addr_t *addr,ushort id_num)
2991 val = PSNET_RELIABLE_ACK;
2992 memcpy(data,&val,sizeof(ushort));
2995 memcpy(data+2,&id_num,sizeof(ushort));
2998 psnet_send(addr,data,4,PSNET_FLAG_RAW,Reliable_socket);
3001 // wrappers around select() and recvfrom() for lagging/losing data, and for sorting through different packet types
3002 int RECVFROM(SOCKET s, char * buf, int len, int flags, sockaddr *from, int *fromlen, int psnet_type)
3008 // if we have no buffer! The user should have made sure this wasn't the case by calling SELECT()
3009 ret = psnet_buffer_get_next((ubyte*)buf, &ret_len, &addr);
3015 // otherwise, stuff the outgoing data
3016 ((struct sockaddr_in*)from)->sin_port = htons(addr.port);
3017 memcpy(&((struct sockaddr_in*)from)->sin_addr.s_addr, addr.addr, 4);
3018 ((struct sockaddr_in*)from)->sin_family = AF_INET;
3019 *fromlen = sizeof(struct sockaddr_in);
3021 // return bytes read
3025 int SELECT(int nfds, fd_set *readfds, fd_set *writefds, fd_set*exceptfds, struct timeval* timeout, int psnet_type)
3027 // if this is a check for writability, just return the select
3028 if(writefds != NULL){
3029 return select(nfds, readfds, writefds, exceptfds, timeout);
3032 // do we have any buffers in here?
3033 if((Psnet_lowest_id == -1) || (Psnet_lowest_id > Psnet_highest_id)){
3041 // wrappers around sendto to sorting through different packet types
3042 int SENDTO(SOCKET s, char * buf, int len, int flags, sockaddr * to, int tolen, int psnet_type)
3044 return sendto(s, buf, len, flags, (struct sockaddr *)to, tolen);
3047 // call this once per frame to read everything off of our socket
3048 void PSNET_TOP_LAYER_PROCESS()
3050 psnet_get_socket_data(Unreliable_socket);
3053 #endif // #ifndef PSNET2