]> icculus.org git repositories - taylor/freespace2.git/blob - src/network/psnet.cpp
first pass at emscripten support
[taylor/freespace2.git] / src / network / psnet.cpp
1 /*
2  * Copyright (C) Volition, Inc. 1999.  All rights reserved.
3  *
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
6  * the source.
7  */
8
9 /*
10  * $Logfile: /Freespace2/code/Network/PsNet.cpp $
11  * $Revision$
12  * $Date$
13  * $Author$
14  *
15  * C file containing application level network-interface.
16  *
17  * $Log$
18  * Revision 1.5  2002/06/09 04:41:24  relnev
19  * added copyright header
20  *
21  * Revision 1.4  2002/06/02 02:29:39  relnev
22  * net fixes
23  *
24  * Revision 1.3  2002/05/26 20:49:54  theoddone33
25  * More progress
26  *
27  * Revision 1.2  2002/05/07 03:16:48  theoddone33
28  * The Great Newline Fix
29  *
30  * Revision 1.1.1.1  2002/05/03 03:28:10  root
31  * Initial import.
32  *
33  * 
34  * 7     7/15/99 9:20a Andsager
35  * FS2_DEMO initial checkin
36  * 
37  * 6     11/19/98 4:19p Dave
38  * Put IPX sockets back in psnet. Consolidated all multiplayer config
39  * files into one.
40  * 
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.
44  * 
45  * 4     11/17/98 11:12a Dave
46  * Removed player identification by address. Now assign explicit id #'s.
47  * 
48  * 3     10/09/98 2:57p Dave
49  * Starting splitting up OS stuff.
50  * 
51  * 2     10/07/98 10:53a Dave
52  * Initial checkin.
53  * 
54  * 1     10/07/98 10:50a Dave
55  * 
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
59  * 
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
63  * 
64  * 105   9/08/98 2:20p Allender
65  * temporary code to force IP address to a specific value.
66  * 
67  * 104   8/21/98 1:15p Dave
68  * Put in log system hooks in useful places.
69  * 
70  * 103   8/12/98 4:50p Allender
71  * fix error with new write socket code
72  * 
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
77  * 
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
81  * 
82  * 100   7/28/98 4:43p Allender
83  * fix bug where error on receiving of reliable data would sometimes
84  * infinate loop
85  * 
86  * 99    7/06/98 5:05p Allender
87  * dont use default port to send UDP data to.  Use port stored in address
88  * 
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."
92  * 
93  * 97    6/13/98 6:01p Hoffoss
94  * Externalized all new (or forgot to be added) strings to all the code.
95  * 
96  * 96    6/13/98 3:19p Hoffoss
97  * NOX()ed out a bunch of strings that shouldn't be translated.
98  * 
99  * 95    6/10/98 2:56p Dave
100  * Substantial changes to reduce bandwidth and latency problems.
101  * 
102  * 94    6/05/98 9:55a Lawrance
103  * OEM changes
104  * 
105  * 93    5/24/98 2:17p Allender
106  * make reliable socket read all data before returning
107  * 
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
111  * 
112  * 91    5/21/98 3:31p Allender
113  * more RAS stuff -- fix possible problem when unable to read data on
114  * reliable socket
115  * 
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.
120  *
121  * $NoKeywords: $
122  */
123
124
125 #ifndef PLAT_UNIX
126 #include <winsock2.h>
127 #include <ras.h>
128 #include <raserror.h>
129 #else
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>
135 #include <netdb.h>
136 #include <errno.h>
137 #endif
138 #include <stdio.h>
139 #include <limits.h>
140
141 #include "pstypes.h"
142 #include "psnet.h"
143 #include "multi.h"
144 #include "multiutil.h"
145 #include "multilag.h"
146 #include "osregistry.h"
147 #include "timer.h"
148 #include "multi_log.h"
149 #include "cmdline.h"
150
151 #ifndef PSNET2
152
153 // old style packet buffering
154 // #define PSNET_BUFFER_OLD_SCHOOL
155
156 // sockets for TCP
157 SOCKET TCP_socket;
158 SOCKET TCP_reliable_socket;
159 SOCKET TCP_listen_socket;
160
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;
165
166 int             Psnet_my_addr_valid;
167 net_addr_t Psnet_my_addr;
168
169 ubyte Null_address[IP_ADDRESS_LENGTH];
170
171 int Socket_type;
172 int Can_broadcast;                      // can we do broadcasting on our socket?
173 int Tcp_can_broadcast = 0;
174
175 int Tcp_active = 0;
176
177 int Network_status;
178 int Tcp_failure_code = 0;
179 int Ras_connected;
180 int Psnet_connection;
181
182 ushort  Psnet_default_port;
183
184 unsigned int Serverconn = 0xffffffff;
185
186 // specified their internet connnection type
187 #define NETWORK_CONNECTION_NONE                 1
188 #define NETWORK_CONNECTION_DIALUP               2
189 #define NETWORK_CONNECTION_LAN                  3
190
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
197
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.
202
203 // use the pack pragma to pack these structures to 2 byte aligment.  Really only needed for
204 // the naked packet.
205
206 #pragma pack(push, 2)
207
208 // packet def for a checksum'ed packet
209 #define MAX_CHECKSUM_PACKET_SIZE                1024
210 typedef struct network_checksum_packet
211 {
212         int             sequence_number;
213         ushort  flags;
214         ushort  checksum;
215         ubyte           data[MAX_CHECKSUM_PACKET_SIZE];
216 } network_checksum_packet;
217
218 // definition for a non-checksum packet
219 typedef struct network_packet
220 {
221         int             sequence_number;
222         ushort  flags;
223         ubyte           data[MAX_PACKET_SIZE];
224 } network_naked_packet;
225
226 // structure definition for our packet buffers
227 typedef struct network_packet_buffer
228 {
229         int             sequence_number;
230         int             len;
231         net_addr_t      from_addr;
232         ubyte           data[MAX_PACKET_SIZE];
233 } network_packet_buffer;
234
235 #pragma pack(pop)
236
237 #define MAX_PACKET_BUFFERS              96
238
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;
244
245         int     Next_packet_id;
246         int     Last_packet_id;
247 #endif
248
249 // variables to keep track of bytes read/written during the course of network play
250 #ifndef NDEBUG
251
252 #define PSNET_FRAME_FILTER              32
253 #define MAX_NET_STATS                   32
254
255 typedef struct {
256         int                             in_use;
257         net_addr_t                      addr;                                           // stats for this address
258         int                             total_read;                                     // total bytes read
259         int                             total_written;                          // total bytes read.
260 } net_stats;
261
262 typedef struct {
263         net_addr_t                      addr;
264         SOCKET                  socket;
265 } socket_xlate;
266
267 net_stats Psnet_stats[MAX_NET_STATS];
268 socket_xlate Psnet_socket_addr[MAX_NET_STATS];
269
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
272
273 int     Psnet_bytes_read;                                       // globally available numbers for printing on the hud
274 int     Psnet_bytes_written;
275
276 int     psnet_read_sizes[PSNET_FRAME_FILTER];
277 int     psnet_write_sizes[PSNET_FRAME_FILTER];
278
279 int     psnet_read_total;
280 int     psnet_write_total;
281 int     psnet_frame_int;
282 int     psnet_frame_count;
283
284 #endif
285
286 #define MAXHOSTNAME                     128
287
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
291
292 #ifndef NDEBUG
293
294 int psnet_same_no_port( net_addr_t * a1, net_addr_t * a2 );
295
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 )
299 {
300         int i;  
301
302         for ( i = 0; i < MAX_NET_STATS; i++ ) {
303                 if ( !Psnet_stats[i].in_use )
304                         continue;
305                 if ( addr && psnet_same_no_port(&Psnet_stats[i].addr, addr) )
306                         break;
307         }
308
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 )
313                                 break;
314                 }
315                 if ( i == MAX_NET_STATS ) {
316                         Int3();                         // we should always have a slot
317                         return;
318                 }
319                 Psnet_stats[i].addr = *addr;
320                 Psnet_stats[i].in_use = 1;
321         }
322         if ( read )
323                 Psnet_stats[i].total_read += num_bytes;
324         else
325                 Psnet_stats[i].total_written += num_bytes;
326 }
327
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 )
331 {
332         int i;
333
334         for ( i = 0; i < MAX_NET_STATS; i++ ) {
335                 if ( !Psnet_stats[i].in_use )
336                         continue;
337
338                 if ( addr && psnet_same_no_port(&Psnet_stats[i].addr, addr) )
339                         break;
340         }
341
342         if ( i == MAX_NET_STATS )
343                 return 0;
344
345         *tr = Psnet_stats[i].total_read;
346         *tw = Psnet_stats[i].total_written;
347
348         return 1;
349 }
350
351 void psnet_stats_init()
352 {
353         int i;
354
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;
360         }
361 }
362
363 #endif
364
365
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()
369 {
370         // first case is when "none" is selected
371         if ( Psnet_connection == NETWORK_CONNECTION_NONE ) {
372                 return NETWORK_ERROR_NO_TYPE;
373         }
374
375         // first, check the connection status of the network
376         if ( Network_status == NETWORK_STATUS_NO_WINSOCK )
377                 return NETWORK_ERROR_NO_WINSOCK;
378
379         if ( Network_status == NETWORK_STATUS_NO_PROTOCOL )
380                 return NETWORK_ERROR_NO_PROTOCOL;
381         
382         // network is running -- be sure that the RAS people know to connect if they currently cannot.
383         
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;
388                 }
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;
394                 }
395         }
396         return NETWORK_ERROR_NONE;
397 }
398
399 #ifndef PLAT_UNIX
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;
403 #endif
404
405 // functions to get the status of a RAS connection
406 void psnet_ras_status()
407 {
408 #ifndef PLAT_UNIX
409         int rval;
410         unsigned long size, num_connections, i;
411         RASCONN rasbuffer[25];
412         HINSTANCE ras_handle;
413
414         Ras_connected = 0;
415
416         // first, call a LoadLibrary to load the RAS api
417         ras_handle = LoadLibrary( (LPCWSTR)"rasapi32.dll" );
418         if ( ras_handle == NULL ) {
419                 return;
420         }
421
422         pRasEnumConnections = (DWORD (__stdcall *)(LPRASCONN, LPDWORD, LPDWORD))GetProcAddress(ras_handle, NOX("RasEnumConnectionsA"));
423         if (!pRasEnumConnections)       {
424                 FreeLibrary( ras_handle );
425                 return;
426         }
427         pRasGetConnectStatus = (DWORD (__stdcall *)(HRASCONN, LPRASCONNSTATUS))GetProcAddress(ras_handle, NOX("RasGetConnectStatusA"));
428         if (!pRasGetConnectStatus)      {
429                 FreeLibrary( ras_handle );
430                 return;
431         }
432         pRasGetProjectionInfo = (DWORD (__stdcall *)(HRASCONN, RASPROJECTION, LPVOID, LPDWORD))GetProcAddress(ras_handle, NOX("RasGetProjectionInfoA"));
433         if (!pRasGetProjectionInfo)     {
434                 FreeLibrary( ras_handle );
435                 return;
436         }
437
438         size = sizeof(rasbuffer);
439         rasbuffer[0].dwSize = sizeof(RASCONN);
440
441         rval = pRasEnumConnections( rasbuffer, &size, &num_connections );
442         if ( rval ) {
443                 FreeLibrary( ras_handle );
444                 return;
445         }
446
447         // JAS: My computer gets to this point, but I have no RAS connections,
448         // so just exit
449         if ( num_connections < 1 )      {
450                 nprintf(("Network", "Found no connections\n" )); 
451                 FreeLibrary( ras_handle );
452                 return;
453         }
454
455         nprintf(("Network", "Found %d connections\n", num_connections));
456
457         for (i = 0; i < num_connections; i++ ) {
458                 RASCONNSTATUS status;
459                 RASPPPIP projection;
460                 unsigned long size;
461
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));
466
467                 // get the connection status
468                 status.dwSize = sizeof(RASCONNSTATUS);
469                 rval = pRasGetConnectStatus(rasbuffer[i].hrasconn, &status);
470                 if ( rval != 0 ) {
471                         FreeLibrary( ras_handle );
472                         return;
473                 }
474
475                 nprintf(("Network", "\tStatus: %s\n", (status.rasconnstate==RASCS_Connected)?"Connected":"Not Connected"));
476
477                 // get the projection informatiom
478                 size = sizeof(projection);
479                 projection.dwSize = size;
480                 rval = pRasGetProjectionInfo(rasbuffer[i].hrasconn, RASP_PppIp, &projection, &size );
481                 if ( rval != 0 ) {
482                         FreeLibrary( ras_handle );
483                         return;
484                 }
485
486                 nprintf(("Network", "\tIP Address: %s\n", projection.szIpAddress));
487         }
488
489         Ras_connected = 1;
490
491         FreeLibrary( ras_handle );
492 #endif
493 }
494
495 // -------------------------------------------------------------------------------------------------
496 // netmisc_calc_checksum() calculates the checksum of a block of memory.
497 //
498 //
499 ushort psnet_calc_checksum( void * vptr, int len )
500 {
501         ubyte * ptr = (ubyte *)vptr;
502         unsigned int sum1,sum2;
503
504         sum1 = sum2 = 0;
505
506         while(len--)    {
507                 sum1 += *ptr++;
508                 if (sum1 >= 255 ) sum1 -= 255;
509                 sum2 += sum1;
510         }
511         sum2 %= 255;
512         
513         return (unsigned short)((sum1<<8)+ sum2);
514 }
515
516 // -------------------------------------------------------------------------------------------------
517 // psnet_set_socket_mode()
518 //
519 //
520
521 int psnet_set_socket_mode(SOCKET sock_id, int opt, int toggle)
522 {
523         return (setsockopt(sock_id, SOL_SOCKET, opt, (char *)&toggle, sizeof(toggle)));
524 }
525
526
527 // -------------------------------------------------------------------------------------------------
528 // sock_get_ip() returns the IP address of this computer.
529 //
530 //
531
532 uint sock_get_ip()
533 {
534         char LclHost[MAXHOSTNAME];
535         struct hostent *Hostent;
536         struct sockaddr_in LclAddr;
537         int nRet;
538
539         // Init local address to zero
540         LclAddr.sin_addr.s_addr = INADDR_ANY;
541         
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);
547                 if ( Hostent )
548                         LclAddr.sin_addr.s_addr = ((in_addr *)(Hostent->h_addr))->s_addr;
549         }
550                         
551         return LclAddr.sin_addr.s_addr;
552 }
553
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 )
557 {
558         int rval;
559         SOCKLEN_T len;
560         struct sockaddr_in local_addr;
561
562         if ( Psnet_my_addr_valid ){
563                 return 1;
564         }
565
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 )
570                 return 0;
571
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);        
575
576         Psnet_my_addr_valid = 1;
577         return 1;
578 }
579
580 // -------------------------------------------------------------------------------------------------
581 // psnet_close()
582 //
583 //
584
585 void psnet_close()
586 {
587 #ifndef PSNET_RELIABLE_OLD_SCHOOL
588         psnet_reliable_close(); 
589 #endif
590
591         if ( Network_status != NETWORK_STATUS_RUNNING )
592                 return;
593
594 #ifndef PLAT_UNIX
595         WSACancelBlockingCall();
596 #endif
597
598         if ( TCP_listen_socket != (SOCKET)INVALID_SOCKET ) {
599                 shutdown( TCP_listen_socket, 1 );
600                 closesocket( TCP_listen_socket );
601         }
602
603         if ( TCP_reliable_socket != (SOCKET)INVALID_SOCKET ) {
604                 shutdown( TCP_reliable_socket, 1 );
605                 closesocket( TCP_reliable_socket );
606         }
607
608         if ( TCP_socket != (SOCKET)INVALID_SOCKET ) {
609                 shutdown( TCP_socket, 1 );
610                 closesocket( TCP_socket );
611         }
612
613 #ifndef PLAT_UNIX
614         if (WSACleanup())       {
615                 //Warning( LOCATION, "Error closing wsock!\n" );
616         }
617 #endif
618         
619         Network_status = NETWORK_STATUS_NOT_INITIALIZED;
620 }
621
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 )
625 {
626         SOCKET sock;
627
628         SDL_assert(type == NET_TCP);
629
630         sock = socket(AF_INET,SOCK_STREAM,0);
631         if ( sock == (SOCKET)INVALID_SOCKET )
632                 return 0;
633
634         *s = sock;
635
636         return 1;
637 }
638
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)
641 {
642         SOCKET sock = 0;                // JAS: Get rid of optimized warning
643         struct sockaddr_in sockaddr;            // UDP/TCP socket structure
644
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;
649         }
650
651         // bind the socket to the port
652         SDL_assert(type == NET_TCP);
653
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;
661         }
662
663
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;
668         }
669
670         // make any reliable sockets which we create that aren't listening non-blocking sockets
671         if ( !should_listen ) {
672                 int error;
673                 unsigned long arg;
674
675                 arg = TRUE;
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;
680                 }
681
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));
686                 }
687
688         }
689
690         return sock;
691 }
692
693 void psnet_socket_options( SOCKET sock )
694 {
695         int broadcast;
696         int ret, cursize, bufsize, trysize;
697         SOCKLEN_T cursizesize;
698
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.
701         broadcast = 1;
702         if(setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char *)&broadcast, sizeof(broadcast) )){
703                 Can_broadcast = 0;
704         } else {
705                 Can_broadcast = 1;
706         }
707
708         // try and increase the size of my receive buffer
709         bufsize = MAX_RECEIVE_BUFSIZE;
710         
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 ) {
717                         int wserr;
718
719                         wserr = WSAGetLastError();
720                         if ( (wserr == WSAENOPROTOOPT) || (wserr == WSAEINVAL) )
721                                 break;
722                 } else
723                         break;
724         }
725         getsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char *)&cursize, &cursizesize);
726         nprintf(("Network", "Receive buffer set to %d\n", cursize));
727
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 ) {
734                         int wserr;
735
736                         wserr = WSAGetLastError();
737                         if ( (wserr == WSAENOPROTOOPT) || (wserr == WSAEINVAL) )
738                                 break;
739                 } else
740                         break;
741         }
742         getsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *)&cursize, &cursizesize);
743         nprintf(("Network", "Send buffer set to %d\n", cursize));
744 }
745
746
747 // psnet_init called at game startup time and initializes all sockets that the game might use (i.e. for both
748 // IPX and TCP).
749 void psnet_init( int protocol, int port_num )
750 {       
751         const char *internet_connection;
752 #ifndef PLAT_UNIX
753         WSADATA wsa_data;
754 #endif
755
756         // UDP/TCP socket structure
757         struct sockaddr_in sockaddr;
758
759         Tcp_active = 0;
760
761 #if defined(DEMO) || defined(OEM_BUILD) // not for FS2_DEMO
762         return;
763 #endif
764
765         // GAME PORT INITIALIZATION STUFF
766         if ( Network_status == NETWORK_STATUS_RUNNING )
767                 return;
768
769         // 'lan' should be a safe default in 2015
770         internet_connection = os_config_read_string("Network", "NetworkConnection", "LAN");
771
772         if ( !SDL_strcasecmp(internet_connection, NOX("dialup")) ) {
773                 ml_string("psnet_init() detected dialup connection");
774
775                 Psnet_connection = NETWORK_CONNECTION_DIALUP;
776         } else if ( !SDL_strcasecmp(internet_connection, NOX("lan")) ) {
777                 ml_string("psnet_init() detected lan connection");
778
779                 Psnet_connection = NETWORK_CONNECTION_LAN;
780         } else {
781                 ml_string("psnet_init() detected no connection");
782
783                 Psnet_connection = NETWORK_CONNECTION_NONE;
784         }
785
786         Network_status = NETWORK_STATUS_NO_WINSOCK;
787
788 #ifndef PLAT_UNIX
789         if (WSAStartup(0x101, &wsa_data )){
790                 return;
791         }
792 #endif
793
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;
798         }
799
800 #ifndef PSNET_RELIABLE_OLD_SCHOOL
801         if(!psnet_reliable_init()){
802                 nprintf(("Network","PSNET RELIABLE : init failed - no networking available!\n"));
803                 return;
804         }
805 #endif
806
807         // initialize TCP now
808         TCP_socket = INVALID_SOCKET;
809         TCP_reliable_socket = INVALID_SOCKET;
810         TCP_listen_socket = INVALID_SOCKET;
811
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));
817                 return;
818         }
819
820         // bind the socket
821         memset(&sockaddr,0,sizeof(struct sockaddr_in));
822         sockaddr.sin_family = AF_INET; 
823
824         sockaddr.sin_addr.s_addr = INADDR_ANY;  //fill in with our IP
825
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 )); 
830                 return;
831         }
832
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 )); 
839                 return;
840         }
841
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 )); 
846                 return;
847         }
848 #endif
849
850         Tcp_active = 1;
851
852         psnet_socket_options( TCP_socket );             
853         Tcp_can_broadcast = Can_broadcast;
854         Can_broadcast = 0;
855
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 )    {
860                 // bind the socket
861                 memset(&sockaddr,0,sizeof(struct sockaddr_in));
862                 sockaddr.sin_family = AF_INET; 
863
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));
867
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() )); 
871                         goto tcp_done;
872                 }
873
874                 psnet_socket_options( TCP_reliable_socket );            
875                 Can_broadcast = 0;
876         }
877 #endif
878
879         psnet_ras_status();
880
881         Network_status = NETWORK_STATUS_RUNNING;
882
883         nprintf(("Network","TCP Initialized\n"));
884
885         // with TCP initialized, see if the RAS services are installed
886
887
888 #ifndef NDEBUG
889         psnet_frame_int = -1;           // for counting bytes per frame
890 #endif
891
892 #ifdef PSNET_BUFFER_OLD_SCHOOL
893         Next_packet_id = 0;
894         Last_packet_id = -1;
895
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.
898         int i;
899         for (i=0; i<MAX_PACKET_BUFFERS; i++ )   {
900                 packet_buffers[i].sequence_number = -1;
901                 packet_free_list[i] = (short)i;
902         }
903         Num_packet_buffers = 0;
904         Largest_packet_index = 0;
905 #else
906         // initialize the new buffering system
907         psnet_buffer_init();
908 #endif
909 }
910
911 #define MAX_TMPBUF_SIZE 1024
912
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 )
917 {
918         int reinit_type;
919         int error, rval;
920         SOCKET *sockp;
921
922         sockp = (SOCKET *)p_sockp;
923
924         if ( *sockp == (SOCKET)INVALID_SOCKET )
925                 return;
926
927 #ifndef NDEBUG
928         if ( *sockp == TCP_reliable_socket )
929                 nprintf(("network", "Closing my relibale TCP socket\n"));
930         else 
931                 nprintf(("Network", "Closing client's reliable socket\n"));
932 #endif
933
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));
940         //}
941
942         // set the socket to linger with a timeout of 0
943         linger l_val;
944         l_val.l_onoff = 1;
945         l_val.l_linger = 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));
950         }
951
952         // see if this socket is my Reliable_socket.  If so, I will have to reinitialize it!
953         reinit_type = -1;
954         if ( *sockp == TCP_reliable_socket )
955                 reinit_type = NET_TCP;
956
957         // if this is the server connection, mark it as done
958         if (*sockp == (SOCKET)Serverconn) {
959                 Serverconn = 0xffffffff;
960         }
961
962         /*
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));
967         }
968         */
969
970         shutdown( *sockp, 1 );
971         rval = 1;
972         while ( rval && (rval != SOCKET_ERROR) ) {
973                 char tmp_buf[MAX_TMPBUF_SIZE];
974
975                 rval = recv( *sockp, tmp_buf, MAX_TMPBUF_SIZE, 0 );
976                 if ( rval == SOCKET_ERROR ) {
977                         error = WSAGetLastError();
978                         if ( NETCALL_WOULDBLOCK(error) )
979                                 break;
980                 }
981         }
982
983         rval = closesocket( *sockp );
984         if ( rval == SOCKET_ERROR ) {
985 #ifndef NDEBUG
986                 error = WSAGetLastError();
987                 nprintf(("Network", "Error %d on closing socket\n", error ));
988 #endif
989         }
990
991         *sockp = INVALID_SOCKET;
992
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;
998                 }
999         }
1000 }
1001 #else
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 )
1005 {
1006         net_addr_t remove;
1007
1008         // copy the address to be removed
1009         memcpy(&remove,&((net_addr_t*)(*p_sockp)),sizeof(net_addr_t));
1010
1011         // remove it from the reliable address list
1012         psnet_reliable_notify_drop_addr(&remove);
1013
1014         // invalidate the passed in "socket"
1015         *p_sockp = NULL;
1016 }
1017 #endif
1018
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()
1023 {
1024         // if our Reliable_socket is valid, simply return true to indicate all is well.
1025         if ( Reliable_socket != (SOCKET)INVALID_SOCKET )
1026                 return 1;
1027
1028         // based on our protocol type, try to reinitialize the socket we need.
1029         SDL_assert(Socket_type == NET_TCP);
1030
1031         TCP_reliable_socket = psnet_init_reliable( 0, 0, NET_TCP);
1032         Reliable_socket = TCP_reliable_socket;
1033
1034         // return our status.
1035         if ( Reliable_socket == (SOCKET)INVALID_SOCKET )
1036                 return 0;
1037
1038         return 1;
1039 }
1040
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 )
1043 {
1044         // zero out my address
1045         Psnet_my_addr_valid = 0;
1046         memset( &Psnet_my_addr, 0, sizeof(Psnet_my_addr) );
1047
1048         // wait until we choose a protocol to determine if we can broadcast
1049         Can_broadcast = 0;
1050
1051         SDL_assert(protocol == NET_TCP);
1052
1053         if ( Network_status != NETWORK_STATUS_RUNNING )
1054                 return 0;
1055
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;
1060
1061         Can_broadcast = Tcp_can_broadcast;
1062         if(Can_broadcast){
1063                 nprintf(("Network","Psnet : TCP broadcast\n"));
1064         }
1065
1066         nprintf(("Network","Psnet using - NET_TCP\n"));
1067
1068         Psnet_my_addr.type = protocol;
1069         Socket_type = protocol;
1070
1071         return 1;
1072 }
1073
1074 #define MAX_CONNECT_TRIES       10
1075
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)
1079 {
1080         struct sockaddr_in sockaddr;                            // UDP/TCP socket structure
1081         struct sockaddr *addr;                                          // pointer to struct sockaddr to make coding easier
1082         SOCKET *socket;
1083         ubyte iaddr[IP_ADDRESS_LENGTH];
1084         u_short port;
1085         int name_length, val;
1086
1087         memset(iaddr, 0x00, IP_ADDRESS_LENGTH);
1088         memcpy(iaddr, server_addr->addr, IP_ADDRESS_LENGTH);
1089         port = (u_short)(server_addr->port - 1);
1090
1091         socket = (SOCKET *)psocket;
1092
1093         SDL_assert(Socket_type == NET_TCP);
1094
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);
1100
1101         // NETLOG
1102         ml_string(NOX("Attempting to perform reliable TCP connect to server"));
1103
1104         // connect this guys Reliable_socket to the socket parameter passed in
1105         *socket = INVALID_SOCKET;
1106         val = connect(Reliable_socket, addr, name_length);
1107
1108          // I suppose that we could have a valid socket right away
1109         if ( val != SOCKET_ERROR ) {
1110                 *socket = Reliable_socket;
1111         } else {
1112                 int error;
1113
1114                 error = WSAGetLastError();
1115                 if ( NETCALL_WOULDBLOCK(error) ) {                      // use select to find out when socket is writeable
1116                         int is_set, num_tries;
1117                         fd_set wfds;
1118                         struct timeval timeout;
1119
1120                         // call select -- and return if an error leaving our connection to the client invalid
1121                         num_tries = 0;
1122                         do {
1123                                 FD_ZERO(&wfds);
1124                                 FD_SET( Reliable_socket, &wfds );
1125                                 timeout.tv_sec = 0;
1126                                 timeout.tv_usec = 500000;                       //500000 micro seconds is 1/2 second
1127
1128                                 is_set = select( Reliable_socket+1, NULL, &wfds, NULL, &timeout);
1129
1130                                 // check for error on select first
1131                                 if ( is_set == SOCKET_ERROR ) {
1132                                         nprintf(("Network", "Error on select for connect %d\n", WSAGetLastError() ));
1133                                         return;
1134                                 } else if (is_set) {                    // if set, then we have connection, move forward
1135                                         break;
1136                                 } else {
1137                                         SDL_Delay(10);                                  // sleep for 10 ms and try again
1138                                         num_tries++;
1139                                 }
1140                         } while ( num_tries < MAX_CONNECT_TRIES );
1141
1142                         if ( num_tries == MAX_CONNECT_TRIES )
1143                                 return;
1144
1145                         *socket = Reliable_socket;
1146
1147                 } else {
1148                         nprintf(("Network", "Connecting with server failed %d\n", error ));
1149                         *socket = INVALID_SOCKET;
1150                 }
1151         }
1152
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;
1157                         return;
1158                 }
1159
1160                 Serverconn = *socket;
1161         }
1162 }
1163
1164 #ifndef NDEBUG
1165 void psnet_calc_bytes_per_frame()
1166 {
1167 }
1168 #endif
1169
1170 // -------------------------------------------------------------------------------------------------
1171 // psnet_same()
1172 //
1173 //
1174
1175 int psnet_same_no_port( net_addr_t * a1, net_addr_t * a2 )
1176 {
1177         if ( !memcmp(a1->addr, a2->addr, IP_ADDRESS_LENGTH) )
1178                 return 1;
1179         return 0;
1180 }
1181
1182 int psnet_same( net_addr_t * a1, net_addr_t * a2 )
1183 {
1184         return psnet_same_no_port( a1, a2 );
1185 /*
1186         if ( !memcmp(a1->addr, a2->addr, 6)  && a1->port == a2->port)
1187                 return 1;
1188         return 0;
1189 */
1190 }
1191
1192 // -------------------------------------------------------------------------------------------------
1193 // psnet_describe()
1194 //
1195 //
1196
1197 char* psnet_addr_to_string( char * text, const int max_textlen, net_addr_t * address )
1198 {
1199
1200         if ( Network_status != NETWORK_STATUS_RUNNING )         {
1201                 SDL_strlcpy( text, XSTR("[no networking]",910), max_textlen );
1202                 return text;
1203         }
1204
1205         in_addr temp_addr;
1206
1207         SDL_assert(address->type == NET_TCP);
1208
1209         switch ( address->type ) {
1210                 case NET_TCP:
1211                         memcpy(&temp_addr.s_addr, address->addr, 4);
1212                         SDL_strlcpy( text, inet_ntoa(temp_addr), max_textlen );
1213                         break;
1214
1215                 default:
1216                         // SDL_assert(0);
1217                         break;
1218
1219         } // end switch
1220         
1221         return text;
1222 }
1223
1224
1225 // -------------------------------------------------------------------------------------------------
1226 // psnet_undescribe()
1227 //
1228 //
1229
1230 void psnet_string_to_addr( net_addr_t * address, char * text, const int max_textlen )
1231 {
1232         struct hostent *he;
1233         char str[255], *c, *port;
1234         in_addr addr;
1235
1236         if ( Network_status != NETWORK_STATUS_RUNNING ) {
1237                 SDL_strlcpy( text, XSTR("[no networking]",910), max_textlen );
1238                 return;
1239         }
1240
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, ':');
1245         port = NULL;
1246         if ( c ) {
1247                 *c = '\0';
1248                 port = c+1;
1249         }
1250
1251         switch ( address->type ) {
1252                 case NET_TCP:
1253                         addr.s_addr = inet_addr(str);
1254                         // if we get INADDR_NONE returns, then we need to try and resolve the host
1255                         // name
1256                         if ( addr.s_addr == INADDR_NONE ) {
1257                                 he = gethostbyname( str );
1258                                 // returns a non-null pointer if successful, so get the address
1259                                 if ( he ) {
1260                                         addr.s_addr = ((in_addr *)(he->h_addr))->s_addr;                        // this is the address in network byte order
1261                                 } else {
1262                                         addr.s_addr = INADDR_NONE;
1263                                 }
1264                         }
1265
1266                         memset(address->addr, 0x00, IP_ADDRESS_LENGTH);
1267                         memcpy(address->addr, &addr.s_addr, 4);
1268                         if ( port )
1269                                 address->port = (ushort)(atoi(port));
1270                         break;
1271
1272                 default:
1273                         SDL_assert(0);
1274                         break;
1275
1276         } // end switch
1277
1278 }
1279
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)
1284 {
1285         struct sockaddr_in ip_addr;                             // UDP/TCP socket structure
1286         fd_set  rfds;
1287         timeval timeout;
1288         int             read_len;
1289         SOCKLEN_T from_len;
1290         net_addr_t      from_addr;
1291         network_checksum_packet packet_read;    
1292         network_checksum_packet packet_data;
1293
1294         // clear the addresses to remove compiler warnings
1295         memset(&ip_addr, 0, sizeof(struct sockaddr_in));
1296
1297         if ( Network_status != NETWORK_STATUS_RUNNING ) {
1298                 nprintf(("Network","Network ==> socket not inited in psnet_get\n"));
1299                 return;
1300         }
1301
1302         while ( 1 ) {           
1303 #ifdef PSNET_BUFFER_OLD_SCHOOL
1304                 int packet_id, id;
1305                 // if there are no more packet buffers that we can use, then we must bail here before reading
1306                 // any data!!!!
1307                 if ( Num_packet_buffers >= MAX_PACKET_BUFFERS ) {
1308                         nprintf(("Network", "Packet buffer overrun in psnet_get()\n"));
1309                         break;
1310                 }
1311 #endif
1312
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.
1315
1316                 FD_ZERO(&rfds);
1317                 FD_SET( socket, &rfds );
1318                 timeout.tv_sec = 0;
1319                 timeout.tv_usec = 0;
1320
1321                 if ( select( socket+1, &rfds, NULL, NULL, &timeout) == SOCKET_ERROR ) {
1322                         nprintf(("Network", "Error %d doing a socket select on read\n", WSAGetLastError()));
1323                         break;
1324                 }
1325
1326                 // if the read file descriptor is not set, then bail!
1327                 if ( !FD_ISSET(socket, &rfds ) )
1328                         return;
1329
1330                 // get data off the socket and process
1331                 read_len = SOCKET_ERROR;
1332                 switch ( Socket_type ) {
1333                 case NET_TCP:
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 );
1337                         } else {
1338                                 read_len = recvfrom( socket, (char *)&packet_read, sizeof(packet_data), 0,  (struct sockaddr*)&ip_addr, &from_len );
1339                         }
1340                         break;
1341                 
1342                 default:
1343                         Int3();
1344                         break;
1345                 }
1346
1347                 // set the from_addr for storage into the packet buffer structure
1348                 from_addr.type = Socket_type;
1349
1350                 switch ( Socket_type ) {
1351                 case NET_TCP:
1352                         if(socket == Reliable_socket){
1353                                 from_addr.port = Psnet_default_port;
1354                         } else {
1355                                 from_addr.port = ntohs( ip_addr.sin_port );
1356                         }
1357                         memset(from_addr.addr, 0x00, IP_ADDRESS_LENGTH);
1358                         memcpy(from_addr.addr, &ip_addr.sin_addr.s_addr, 4);
1359                         break;
1360
1361                 default:
1362                         SDL_assert(0);
1363                         break;
1364                 }
1365
1366                 if ( read_len == SOCKET_ERROR ) {
1367 #ifndef NDEBUG
1368                         int x = WSAGetLastError();
1369                         nprintf(("Network", "Read error on socket.  Winsock error %d \n", x));
1370 #endif
1371                         break;
1372                 }               
1373
1374 #ifndef PSNET_RELIABLE_OLD_SCHOOL
1375                 int shave_size;
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);
1380                         if(!shave_size){                                
1381                                 continue;
1382                         } else {
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);
1385
1386                                 // subtract out the size of the reliable header
1387                                 read_len -= shave_size;
1388                         }
1389                 } else {
1390                         memcpy(packet_data.data,packet_read.data,read_len);
1391                 }
1392 #else
1393                 memcpy(packet_data.data,packet_read.data,read_len);
1394 #endif
1395
1396 #ifdef PSNET_BUFFER_OLD_SCHOOL
1397                 ubyte           *data;
1398                 int len;
1399
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) ) {
1403                         ushort checksum;                        
1404
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"));
1410                                 return;
1411                         }
1412                         data = packet_data.data;
1413                         packet_id = packet_data.sequence_number;
1414                 } else {
1415                         network_naked_packet *packet;
1416
1417                         // just read in the raw socket data and length
1418                         if(flags & PSNET_FLAG_RAW){
1419                                 data = packet_data.data;
1420                                 len = read_len;
1421
1422                                 packet_id = 0;
1423                         } else {
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;                          
1427         
1428                                 len = read_len - (sizeof(network_naked_packet) - MAX_PACKET_SIZE);
1429                                 data = packet->data;                            
1430
1431                                 packet_id = packet->sequence_number;
1432                         }                       
1433                 }
1434
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));
1442                         }
1443                 }
1444                 Last_packet_id = packet_id;                             
1445
1446 #ifndef NDEBUG
1447                 psnet_do_net_stats( &from_addr, read_len, 1 );
1448                 psnet_bytes_read_frame += read_len;
1449 #endif
1450
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 );           
1461 #else
1462 #ifndef NDEBUG
1463                 psnet_do_net_stats( &from_addr, read_len, 1 );
1464                 psnet_bytes_read_frame += read_len;
1465 #endif
1466
1467                 // buffer the packet
1468                 psnet_buffer_packet(packet_data.data,read_len,&from_addr);
1469 #endif
1470         }
1471 }
1472
1473 // -------------------------------------------------------------------------------------------------
1474 // psnet_send()
1475 //
1476 //
1477
1478 int psnet_send( net_addr_t * who_to, void * data, int len, int flags, int reliable_socket )
1479 {
1480         
1481         SOCKET send_sock;
1482         struct sockaddr_in sockaddr;                            // UDP/TCP socket structure
1483         int ret, send_len;
1484         ubyte iaddr[IP_ADDRESS_LENGTH], *send_data;
1485         short port;
1486         fd_set  wfds;
1487         struct timeval timeout;
1488
1489         if(!reliable_socket){
1490                 send_sock = Unreliable_socket;
1491         } else {
1492                 send_sock = Reliable_socket;
1493         }
1494
1495         if ( Network_status != NETWORK_STATUS_RUNNING ) {
1496                 nprintf(("Network","Network ==> Socket not inited in psnet_send\n"));
1497                 return 0;
1498         }
1499
1500         if ( psnet_same( who_to, &Psnet_my_addr) ){
1501                 return 0;
1502         }
1503
1504         memset(iaddr, 0x00, IP_ADDRESS_LENGTH);
1505         memcpy(iaddr, who_to->addr, IP_ADDRESS_LENGTH);
1506
1507         if ( memcmp(iaddr, Null_address, IP_ADDRESS_LENGTH) == 0) {
1508                 nprintf(("Network","Network ==> send to address is 0 in psnet_send\n"));
1509                 return 0;
1510         }
1511
1512         if(send_sock == Unreliable_socket){
1513                 port = who_to->port;
1514         } else if(send_sock == Reliable_socket){
1515                 port = DEFAULT_GAME_PORT + 1;
1516         } else {
1517                 port = who_to->port;
1518         }
1519                 
1520         if ( port == 0) {
1521                 nprintf(("Network","Network ==> destination port %d invalid in psnet_send\n", port));
1522                 return 0;
1523         }
1524
1525 #ifdef PSNET_BUFFER_OLD_SCHOOL
1526         network_checksum_packet         Send_network_checksum_packet;
1527         network_naked_packet                    Send_network_naked_packet;
1528
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));
1533
1534                 Send_network_checksum_packet.sequence_number = Next_packet_id++;
1535                 Send_network_checksum_packet.flags = PSNET_FLAG_CHECKSUM;
1536                                                 
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;
1541         } else {                
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;
1546                                                 
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;
1550                 }
1551                 // send raw data
1552                 else {
1553                         send_data = (ubyte*)data;
1554                         send_len = len;
1555                 }
1556         }
1557 #else
1558         send_data = (ubyte*)data;
1559         send_len = len;
1560 #endif
1561
1562
1563         FD_ZERO(&wfds);
1564         FD_SET( send_sock, &wfds );
1565         timeout.tv_sec = 0;
1566         timeout.tv_usec = 0;
1567
1568         if ( select( send_sock+1, NULL, &wfds, NULL, &timeout) == SOCKET_ERROR ) {
1569                 nprintf(("Network", "Error on blocking select for write %d\n", WSAGetLastError() ));
1570                 return 0;
1571         }
1572
1573         // if the write file descriptor is not set, then bail!
1574         if ( !FD_ISSET(send_sock, &wfds ) )
1575                 return 0;
1576
1577         ret = SOCKET_ERROR;
1578         switch ( who_to->type ) {
1579
1580                 case NET_TCP:
1581                         sockaddr.sin_family = AF_INET; 
1582                         memcpy(&sockaddr.sin_addr.s_addr, iaddr, 4);
1583                         sockaddr.sin_port = htons(port); 
1584
1585                         ret = sendto( send_sock, (char *)send_data, send_len, 0, (struct sockaddr*)&sockaddr, sizeof(sockaddr) );
1586                         break;
1587
1588                 default:
1589                         SDL_assert(0);  // unknown protocol
1590                         break;
1591
1592         } // end switch
1593
1594         if ( ret != SOCKET_ERROR )      {
1595 #ifndef NDEBUG
1596                 psnet_bytes_written_frame += send_len;
1597                 psnet_do_net_stats( who_to, send_len, 0 );
1598 #endif
1599                 return 1;
1600         }
1601         //Warning( LOCATION, "Couldn't send data (0x%x)!\n", WSAGetLastError() ); 
1602         return 0;
1603 }
1604
1605 #ifdef PSNET_BUFFER_OLD_SCHOOL
1606 // routine to "free" a packet buffer
1607 void free_packet( int id )
1608 {
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 ));
1613 }
1614 #endif
1615
1616 #ifdef PSNET_RELIABLE_OLD_SCHOOL
1617 // psnet_send_reliable sends the given data through the given reliable socket.
1618
1619 #define MAX_RSEND_BUFFER                2048
1620 ubyte rsend_buffer[MAX_RSEND_BUFFER];
1621
1622 int psnet_rel_send( PSNET_SOCKET psocket, ubyte *data, int length, int flags )
1623 {
1624         ubyte *send_data;
1625         int num_sent, total_sent, error, retries;
1626         SOCKET socket;
1627         unsigned short s_length;
1628
1629         socket = (SOCKET)psocket;       
1630
1631         // basic checks
1632         if ( Network_status != NETWORK_STATUS_RUNNING ) {
1633                 nprintf(("Network","Network ==> Socket not inited in psnet_send\n"));
1634                 return 0;
1635         }
1636
1637         if ( socket == (SOCKET)INVALID_SOCKET )         // might happen in race conditions -- should get cleaned up.
1638                 return 0;
1639
1640         SDL_assert( length < MAX_RSEND_BUFFER );
1641
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 );
1648
1649         retries = 0;
1650         total_sent = 0;
1651         send_data = data;
1652         do {
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
1657
1658                                 // if error is would block, then set error to aborted connection
1659                                 if ( NETCALL_WOULDBLOCK(error) )
1660                                         error = WSAECONNABORTED;
1661
1662                                 multi_eval_socket_error(socket, error);
1663                                 return 0;
1664                         }
1665                         retries++;                                                                                      // keep a try count
1666                 } else {
1667                         length -= num_sent;
1668                         send_data += num_sent;
1669                         total_sent += num_sent;
1670                 }
1671         } while ( length > 0 );
1672
1673 #ifndef NDEBUG
1674         psnet_bytes_written_frame += total_sent;
1675
1676         //int index;
1677         //index = psnet_find_stats_loc( who_to );
1678         //if ( index != -1 )
1679         //      Psnet_stats[index].total_written += send_len;
1680 #endif
1681         return 1;
1682 }
1683
1684 // get data off the reliable socket
1685 int psnet_rel_get( PSNET_SOCKET psocket, ubyte *buffer, int max_len, int flags)
1686 {
1687         int from_len, total_read, error;
1688         SOCKET socket;
1689         fd_set rfds;
1690         struct timeval timeout;
1691         short read_len;
1692         ubyte rread_buffer[2];
1693
1694         socket = (SOCKET)psocket;
1695
1696         // see if there is data to be read
1697         FD_ZERO(&rfds);
1698         FD_SET( socket, &rfds );
1699         timeout.tv_sec = 0;
1700         timeout.tv_usec = 0;
1701
1702         if ( select( socket+1, &rfds, NULL, NULL, &timeout) == SOCKET_ERROR ) {
1703                 nprintf(("Network", "Error on select for read reliable: %d\n", WSAGetLastError() ));
1704                 return 0;
1705         }
1706
1707         // if no data, then we can leave.
1708         if ( !FD_ISSET(socket, &rfds ) )
1709                 return 0;
1710
1711         // we know we have data to read.  We must read the two byte length of the packet first
1712         total_read = 0;
1713         read_len = 2;
1714         do {
1715                 from_len = recv(socket, (char *)(&rread_buffer[total_read]), read_len - total_read, 0);
1716
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.
1723                         return 0;
1724                 }
1725
1726                 // on a socket error, we need to check for WSAEWOULDBLOCK meaning that there is no more
1727                 // data to be read.
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?
1733                 }
1734
1735                 total_read += from_len;
1736         } while ( total_read < read_len );
1737
1738
1739         total_read = 0;
1740         memcpy(&read_len, &rread_buffer[0], 2);
1741         SDL_assert( (read_len > 0) && (read_len < max_len) );
1742         if ( read_len == 0 )
1743                 return 0;
1744
1745         do {
1746                 from_len = recv(socket, (char *)(buffer + total_read), read_len - total_read, 0);
1747
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.
1754                         return 0;
1755                 }
1756
1757                 // on a socket error, we need to check for WSAEWOULDBLOCK meaning that there is no more
1758                 // data to be read.
1759                 else if ( from_len == SOCKET_ERROR ) {
1760                         error = WSAGetLastError();
1761                         if ( !NETCALL_WOULDBLOCK(error) ) {
1762                                 multi_eval_socket_error( socket, error );
1763                                 return 0;
1764                         }
1765                         continue;
1766                 }
1767
1768                 total_read += from_len;
1769         } while ( total_read < read_len );
1770
1771         return total_read;
1772 }
1773 #else
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 )
1776 {
1777         // don't do anything if the socket is null
1778         if(psocket == NULL){
1779                 return 0;
1780         }
1781         
1782         // send a reliable data packet
1783         return psnet_reliable_send(data,length,(net_addr_t*)psocket);
1784 }
1785
1786 int psnet_get_reliable( PSNET_SOCKET psocket, ubyte *buffer, int max_len, int flags)
1787
1788 {
1789         int best, best_id, i, n, size;
1790
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);
1793
1794 #ifdef PSNET_BUFFER_OLD_SCHOOL
1795         // now determine which (if any) of the packet buffers we should look at!
1796         best = -1;
1797         n = 0;
1798         best_id = -1;
1799
1800         for (i=0; i <= Largest_packet_index; i++ )      {
1801                 if ( packet_buffers[i].sequence_number > -1 ) {
1802                         n++;
1803                         if ( best == -1 || (packet_buffers[i].sequence_number < best) ) {
1804                                 best = packet_buffers[i].sequence_number;
1805                                 best_id = i;
1806                         }
1807                 }                       
1808         }
1809
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 ));
1812
1813         if ( best_id < 0 ) return 0;
1814
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);
1819
1820         return size;    
1821 #else
1822         return 0;
1823 #endif
1824 }
1825 #endif
1826
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)
1830 {
1831         fd_set  rfds;
1832         timeval timeout;
1833         SOCKET  sock;                           // when trying to accept, this is new socket
1834         struct sockaddr_in ip_addr;                             // UDP/TCP socket structure
1835         SOCKLEN_T from_len;
1836         int error;
1837         unsigned long arg;
1838
1839         FD_ZERO(&rfds);
1840         FD_SET( Listen_socket, &rfds );
1841         timeout.tv_sec = 0;
1842         timeout.tv_usec = 0;
1843
1844         if ( select(Listen_socket+1, &rfds, NULL, NULL, &timeout) == SOCKET_ERROR ) {
1845                 nprintf(("Network", "Error %d doing select on listen socket\n", WSAGetLastError() ));
1846                 return 0;
1847         }
1848
1849         // check to see if Listen_socket has something -- if not, return
1850         if ( !FD_ISSET(Listen_socket, &rfds) )
1851                 return INVALID_SOCKET;
1852
1853         sock = INVALID_SOCKET;
1854         switch ( Socket_type ) {
1855         case NET_TCP:
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"));
1862                 break;
1863         
1864         default:
1865                 Int3();
1866                 break;
1867         }
1868
1869         if ( !psnet_get_ip(sock) ) {
1870                 return INVALID_SOCKET;
1871         }
1872
1873         // make the new socket non-blocking
1874         if(sock != (SOCKET)INVALID_SOCKET){
1875                 arg = TRUE;
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;
1880                 }
1881         }
1882
1883         return sock;
1884
1885 }
1886
1887 int psnet_rel_get_status(PSNET_SOCKET psocket)
1888 {
1889         int error_code;
1890         SOCKLEN_T error_code_size = sizeof(error_code);
1891         SOCKET socket;
1892
1893         socket = (SOCKET)psocket;
1894
1895         if (socket == (SOCKET)INVALID_SOCKET) {
1896                 return RNF_UNUSED;
1897         }
1898
1899         if ( getsockopt(socket, SOL_SOCKET, SO_ERROR, (char*)&error_code, &error_code_size) ) {
1900                 return RNF_BROKEN;
1901         }
1902
1903         if ( !error_code ) {
1904                 return RNF_CONNECTED;
1905         }
1906
1907         if ( NETCALL_WOULDBLOCK(error_code) ) {
1908                 return RNF_CONNECTING;
1909         }
1910
1911         return RNF_DISCONNECTED;
1912 }
1913
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 )
1917 {                       
1918         // USE THIS CODE TO TEST NON-BUFFERED SOCKET READS. OUT-OF-ORDER PACKETS DROP TO NEARLY 0
1919         // - Dave
1920         /*
1921         fd_set  rfds;
1922         timeval timeout;
1923         int read_len,from_len;
1924         struct sockaddr_in ip_addr;
1925         FD_ZERO(&rfds);
1926         FD_SET( Unreliable_socket, &rfds );
1927         timeout.tv_sec = 0;
1928         timeout.tv_usec = 0;
1929
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()));
1932                 return 0;
1933         }
1934
1935         // if the read file descriptor is not set, then bail!
1936         if ( !FD_ISSET(Unreliable_socket, &rfds ) )
1937                 return 0;
1938
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);      
1946         return read_len;        
1947         */
1948         
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);
1951
1952 #ifdef PSNET_BUFFER_OLD_SCHOOL
1953         int best, best_id, i, n, size;
1954
1955         // now determine which (if any) of the packet buffers we should look at!
1956         best = -1;
1957         n = 0;
1958         best_id = -1;
1959
1960         for (i=0; i <= Largest_packet_index; i++ )      {
1961                 if ( packet_buffers[i].sequence_number > -1 ) {
1962                         n++;
1963                         if ( best == -1 || (packet_buffers[i].sequence_number < best) ) {
1964                                 best = packet_buffers[i].sequence_number;
1965                                 best_id = i;
1966                         }
1967                 }                       
1968         }
1969
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 ));
1972
1973         if ( best_id < 0 ) return 0;
1974
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);
1979
1980         return size;
1981 #else
1982         int buffer_size;
1983
1984         // try and get a free buffer and return its size
1985         if(psnet_buffer_get_next((ubyte*)data,&buffer_size,from_addr)){
1986                 return buffer_size;
1987         }
1988
1989         // return nothing
1990         return 0;
1991 #endif
1992 }
1993
1994
1995
1996 // -------------------------------------------------------------------------------------------------
1997 // psnet_broadcast()
1998 //
1999 //
2000
2001 int psnet_broadcast( net_addr_t * who_to, void * data, int len, int flags )
2002 {
2003         if ( Network_status != NETWORK_STATUS_RUNNING ) {
2004                 nprintf(("Network","Network ==> Socket not inited in psnet_broadcast\n"));
2005                 return 0;
2006         }
2007
2008         if ( !Can_broadcast ) {
2009                 nprintf(("Network", "Cannot broadcast -- returning without doing anything\n"));
2010                 return 0;
2011         }
2012
2013         ubyte broadcast[IP_ADDRESS_LENGTH] = {0xff, 0xff, 0xff, 0xff};
2014
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 ) {
2018                 case NET_TCP:
2019
2020                         memcpy(who_to->addr, broadcast, IP_ADDRESS_LENGTH);
2021                         psnet_send(who_to, data, len, flags);
2022                         break;
2023         
2024         } // end switch
2025
2026         return 1;
2027 }
2028
2029 // called to clear out the socket of any remaining data
2030
2031 void psnet_flush()
2032 {
2033         ubyte data[MAX_PACKET_SIZE];
2034         net_addr_t from_addr;
2035
2036         while ( psnet_get( data, &from_addr ) > 0 ) ;
2037 }
2038
2039
2040
2041 #ifndef NDEBUG
2042 // function to keep track of bytes read/written on average during the frame
2043 void psnet_calc_socket_stats()
2044 {
2045         if ( psnet_frame_int == -1 )    {
2046                 int i;
2047                 for ( i = 0; i < PSNET_FRAME_FILTER; i++ ) {
2048                         psnet_read_sizes[i] = 0;
2049                         psnet_write_sizes[i] = 0;
2050                 }
2051                 psnet_read_total = 0;
2052                 psnet_write_total = 0;
2053                 psnet_frame_int = 0;
2054         }
2055         psnet_read_total -= psnet_read_sizes[psnet_frame_int];
2056         psnet_write_total -= psnet_write_sizes[psnet_frame_int];
2057
2058         psnet_read_total += psnet_bytes_read_frame;
2059         psnet_write_total += psnet_bytes_written_frame;
2060
2061         psnet_read_sizes[psnet_frame_int] = psnet_bytes_read_frame;
2062         psnet_write_sizes[psnet_frame_int] = psnet_bytes_written_frame;
2063
2064         psnet_frame_int = (psnet_frame_int + 1 ) % PSNET_FRAME_FILTER;
2065
2066         if ( psnet_frame_count > 0 )    {
2067                 if ( psnet_frame_count >= PSNET_FRAME_FILTER )
2068                         Psnet_bytes_read = psnet_read_total / PSNET_FRAME_FILTER;
2069                 else
2070                         Psnet_bytes_read = psnet_read_total / psnet_frame_count;
2071
2072                 if ( psnet_frame_count >= PSNET_FRAME_FILTER )
2073                         Psnet_bytes_written = psnet_write_total / PSNET_FRAME_FILTER;
2074                 else
2075                         Psnet_bytes_written = psnet_write_total / psnet_frame_count;
2076         }
2077
2078         psnet_frame_count++;
2079         psnet_bytes_read_frame = 0;
2080         psnet_bytes_written_frame = 0;
2081 }
2082 #endif
2083
2084 int psnet_is_valid_numeric_ip(char *ip)
2085 {
2086         char *token;
2087         char copy[100];
2088         int val1,val2,val3,val4;
2089
2090         // get the first ip value
2091         SDL_strlcpy(copy, ip, SDL_arraysize(copy));
2092         token = strtok(copy,".");
2093         if(token == NULL){
2094                 return 0;
2095         } else {
2096                 // get the value of the token
2097                 val1 = atoi(token);
2098                 if((val1 < 0) || (val1 > 255)){
2099                         return 0;
2100                 }
2101         }
2102
2103         // second ip value
2104         token = strtok(NULL,".");
2105         if(token == NULL){
2106                 return 0;
2107         } else {
2108                 // get the value of the token
2109                 val2 = atoi(token);
2110                 if((val2 < 0) || (val2 > 255)){
2111                         return 0;
2112                 }
2113         }
2114
2115         // third ip value
2116         token = strtok(NULL,".");
2117         if(token == NULL){
2118                 return 0;
2119         } else {
2120                 // get the value of the token
2121                 val3 = atoi(token);
2122                 if((val3 < 0) || (val3 > 255)){
2123                         return 0;
2124                 }
2125         }
2126
2127         // third ip value
2128         token = strtok(NULL,"");
2129         if(token == NULL){
2130                 return 0;
2131         } else {
2132                 // get the value of the token
2133                 val4 = atoi(token);
2134                 if((val4 < 0) || (val4 > 255)){
2135                         return 0;
2136                 }
2137         }
2138
2139         // make sure he hasn't entered all 0's
2140         if((val1 == 0) && (val2 == 0) && (val3 == 0) && (val4 == 0)){
2141                 return 0;
2142         }
2143
2144         // valid
2145         return 1;
2146 }
2147
2148
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
2151 // <addr>:<port#>
2152 // so we must be sure to remove the port number
2153 int psnet_is_valid_ip_string( char *ip_string, int allow_port )
2154 {
2155         in_addr addr;
2156         struct hostent *host_ent;
2157         char str[255], *c;
2158
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, ':');
2163         if ( c ){
2164                 *c = '\0';
2165         }       
2166
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)){
2171                         return 1;
2172                 }
2173         }
2174
2175         // try name resolution
2176         host_ent = gethostbyname( ip_string );
2177         if ( !host_ent ){
2178                 return 0;
2179         }
2180
2181         // valid host entry so return 1;
2182         return 1;
2183 }
2184
2185
2186 // ------------------------------------------------------------------------------------------------------
2187 // PACKET BUFFERING FUNCTIONS
2188 //
2189
2190 #ifndef PSNET_BUFFER_OLD_SCHOOL
2191
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;
2197
2198 // initialize the buffering system
2199 void psnet_buffer_init()
2200 {
2201         int idx;
2202         
2203         // blast the buffer clean
2204         memset(Psnet_buffers,0,sizeof(network_packet_buffer) * MAX_PACKET_BUFFERS);
2205         
2206         // set all buffer sequence #'s to -1
2207         for(idx=0;idx<MAX_PACKET_BUFFERS;idx++){
2208                 Psnet_buffers[idx].sequence_number = -1;
2209         }
2210
2211         // initialize the sequence #
2212         Psnet_seq_number = 0;
2213         Psnet_lowest_id = -1;
2214         Psnet_highest_id = -1;
2215 }
2216
2217 // buffer a packet (maintain order!)
2218 void psnet_buffer_packet(ubyte *data, int length, net_addr_t *from)
2219 {
2220         int idx;
2221         int found_buf = 0;
2222         
2223         // find the first empty packet
2224         for(idx=0;idx<MAX_PACKET_BUFFERS;idx++){
2225                 if(Psnet_buffers[idx].sequence_number == -1){
2226                         found_buf = 1;
2227                         break;
2228                 }
2229         }
2230
2231         // if we didn't find the buffer, report an overrun
2232         if(!found_buf){
2233                 nprintf(("Network","WARNING - Buffer overrun in psnet\n"));
2234         } else {
2235                 // copy in the data
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;
2240                 
2241                 // keep track of the highest id#
2242                 Psnet_highest_id = Psnet_seq_number++;
2243
2244                 // set the lowest id# for the first time
2245                 if(Psnet_lowest_id == -1){
2246                         Psnet_lowest_id = Psnet_highest_id;
2247                 }
2248         }
2249 }
2250
2251 // get the index of the next packet in order!
2252 int psnet_buffer_get_next(ubyte *data, int *length, net_addr_t *from)
2253 {       
2254         int idx;
2255         int found_buf = 0;
2256
2257         // if there are no buffers, do nothing
2258         if((Psnet_lowest_id == -1) || (Psnet_lowest_id > Psnet_highest_id)){
2259                 return 0;
2260         }
2261
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){
2266                         found_buf = 1;
2267                         break;
2268                 }
2269         }
2270
2271         // at this point, we should _always_ have found the buffer
2272         SDL_assert(found_buf);
2273         
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));
2278
2279         // now we need to cleanup the packet list
2280
2281         // mark the buffer as free
2282         Psnet_buffers[idx].sequence_number = -1;
2283         Psnet_lowest_id++;
2284
2285         return 1;
2286 }
2287
2288 #else 
2289
2290 // initialize the buffering system
2291 void psnet_buffer_init() {}
2292
2293 // buffer a packet (maintain order!)
2294 void psnet_buffer_packet(ubyte *data, int length) {}
2295
2296 // get the index of the next packet in order!
2297 int psnet_buffer_get_next() {   return -1; }
2298
2299 #endif
2300
2301 // ------------------------------------------------------------------------------------------------------
2302 // RELIABLE UDP FUNCTIONS
2303 //
2304
2305 // verbose debug output
2306 #define PSNET_RELIABLE_VERBOSE
2307
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
2311
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;
2323
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;
2329
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))
2333
2334 // timeout to be used for the packets
2335 #define PSNET_RELIABLE_TIMEOUT                                                  1500                            // in ms
2336
2337 // # of repeats to use
2338 #define PSNET_RELIABLE_REPEAT                                                           8                                       // repeat this many times max
2339
2340 // invalid id#
2341 #define PSNET_RELIABLE_INVALID                                                  0               
2342
2343 // ack code
2344 #define PSNET_RELIABLE_ACK                                                                      0xffff
2345
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];
2349
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
2353
2354 // my local identifier # (will only use lower 12 bits)
2355 ushort Psnet_reliable_local_id = 0x1;
2356
2357 // is the reliable system initialized
2358 int Psnet_reliable_inited = 0;
2359
2360 // # of times a packet has not been delivered
2361 int Psnet_reliable_fail_count = 0;
2362
2363 // # of times packets have had to be resent
2364 int Psnet_reliable_resend_count = 0;
2365
2366 // # of times we've run out of packets and had to overwrite existing ones
2367 int Psnet_reliable_overwrite_count = 0;
2368
2369 // forward declarations ------------------------------------------------------
2370
2371 // free up all used buffers 
2372 void psnet_reliable_free_all_buffers();
2373
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);
2376
2377 // get the index into the address array from the passed bitflag
2378 int psnet_reliable_index_addr(int flags);
2379
2380 // kill all outgoing packets belonging to the passed index
2381 void psnet_reliable_kill_outgoing(int index);
2382
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);
2386
2387 // get the upper 12 bit version of my id# and increment the original
2388 ushort psnet_reliable_get_next_id();
2389
2390 // get the index of a free outgoing relible packet buffer, killing the oldest if necessary
2391 int psnet_reliable_get_free_outgoing();
2392
2393 // get the index of a free incoming relible packet buffer, killing the oldest if necessary
2394 int psnet_reliable_get_free_incoming();
2395
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);
2398
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);
2401
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);
2404
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);
2407
2408 // send an ack to the specified address
2409 void psnet_reliable_send_ack(net_addr_t *addr,ushort id_num);
2410
2411
2412 // extern functions -----------------------------------------------------------
2413
2414 // initialize the psnet reliable system (return 0 on fail, 1 on success)
2415 int psnet_reliable_init()
2416 {
2417         int idx;
2418
2419         // if the system is already inited, do nothing
2420         if(Psnet_reliable_inited){
2421                 return 1;
2422         }
2423         
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));
2427 #endif
2428
2429         // null all buffers
2430         for(idx=0;idx<PSNET_RELIABLE_NUM_OUT_BUFFERS;idx++){
2431                 Psnet_reliable_out[idx] = NULL;
2432         }
2433         for(idx=0;idx<PSNET_RELIABLE_NUM_IN_BUFFERS;idx++){
2434                 Psnet_reliable_in[idx] = NULL;
2435         }
2436
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));
2441
2442                 // if we failed to allocate the buffer, return failure
2443                 if(Psnet_reliable_out[idx] == NULL){
2444                         psnet_reliable_free_all_buffers();
2445                         return 0;
2446                 }
2447                 memset(Psnet_reliable_out[idx],0,sizeof(reliable_packet_out));
2448         }
2449
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));
2454
2455                 // if we failed to allocate the buffer, return failure
2456                 if(Psnet_reliable_in[idx] == NULL){
2457                         psnet_reliable_free_all_buffers();
2458                         return 0;
2459                 }
2460                 memset(Psnet_reliable_in[idx],0,sizeof(reliable_packet_in));
2461         }
2462
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;
2466
2467         // set the system to be initialized
2468         Psnet_reliable_inited = 1;
2469
2470         // initialize my local id #
2471         Psnet_reliable_local_id = 0x1;
2472
2473         // initialize the packet delivery fail count
2474         Psnet_reliable_fail_count = 0;
2475
2476         // intialize the packet necessary resend count
2477         Psnet_reliable_resend_count = 0;
2478
2479         // initialize # of times we've run out of packets and had to overwrite existing ones
2480         Psnet_reliable_overwrite_count = 0;
2481
2482         // return success
2483         return 1;
2484 }
2485
2486 // shutdown the reliable system (free up buffers, etc)
2487 void psnet_reliable_close()
2488 {
2489         // if the system is not initialized, don't do anything
2490         if(!Psnet_reliable_inited){
2491                 return;
2492         }
2493
2494         // free up all buffers
2495         psnet_reliable_free_all_buffers();
2496
2497         // blast all addresses clean
2498         memset(Psnet_reliable_addr,0,sizeof(net_addr_t) * MAX_PLAYERS);
2499         Psnet_reliable_addr_flags = 0;
2500
2501         // set the system as being uninitialized
2502         Psnet_reliable_inited = 0;
2503 }
2504
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)
2507 {
2508         // copy in the address
2509         memcpy(&Psnet_reliable_addr[index],addr,sizeof(net_addr_t));
2510
2511         // set the bit indicating its validity
2512         Psnet_reliable_addr_flags |= (1<<index);
2513 }
2514
2515 // notify the reliable system of a drop at index N
2516 void psnet_reliable_notify_drop_addr(net_addr_t *addr)
2517 {
2518         int index;
2519
2520         // do a lookup for the address
2521         index = psnet_reliable_addr_index(addr);
2522         if(index != -1){                
2523                 // clear out all packets belonging exclusively to this address
2524                 psnet_reliable_kill_outgoing(index);
2525
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);
2529         }
2530 }
2531
2532 // send a reliable data packet
2533 int psnet_reliable_send(ubyte *data,int packet_size,net_addr_t *addr)
2534 {
2535         int free_buffer;
2536         int to_index;
2537         reliable_packet_out *p;
2538         
2539         // if the system is not initialized, don't do anything
2540         if(!Psnet_reliable_inited){
2541                 return 0;
2542         }
2543
2544         // try and find a guy to send to 
2545         to_index = psnet_reliable_addr_index(addr);
2546         if(to_index == -1){
2547                 nprintf(("Network","PSNET RELIABLE : could not find player for outgoing packet!\n"));
2548                 return 0;
2549         }
2550
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
2555         }
2556
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();
2566
2567         // send the packet
2568         return psnet_reliable_send_packet(p);
2569 }
2570
2571 // process frame for all reliable stuff (call once per frame)
2572 void psnet_reliable_process()
2573 {
2574         int idx,s_idx;
2575         reliable_packet_out *p;
2576         
2577         // if the system is not initialized, don't do anything
2578         if(!Psnet_reliable_inited){
2579                 return;
2580         }
2581
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];
2587
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));
2598 #endif
2599                                                         p->player_flags &= ~(1<<s_idx);
2600
2601                                                         // increment the fail count
2602                                                         Psnet_reliable_fail_count++;
2603                                                 }
2604                                                 // otherwise resend the packet
2605                                                 else {
2606                                                         // actually send the data contained with the reliable_packet_out
2607                                                         psnet_reliable_send_packet(p,s_idx);
2608
2609                                                         // increment the resend count
2610                                                         Psnet_reliable_resend_count++;
2611
2612 #ifdef PSNET_RELIABLE_VERBOSE
2613                                                         nprintf(("Network","PSNET RELIABLE : resending packet\n"));
2614 #endif
2615                                                 }
2616                                         }
2617                                 }
2618                         }
2619
2620                         // evaluate if this packet has completed
2621                         psnet_reliable_evaluate_status(p);
2622                 }
2623         }
2624 }
2625
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)
2629 {
2630         ushort id_num,unique_id;
2631         int packet_index;
2632         int player_index;
2633         int free_index;
2634         reliable_packet_in *p;
2635
2636         // get the reliable packet id #
2637         memcpy(&id_num,data,sizeof(ushort));
2638
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"));
2643 #endif
2644
2645                 // get the id#
2646                 memcpy(&id_num,data+2,sizeof(ushort));
2647
2648                 // get the packet index
2649                 // unique_id = psnet_reliable_get_unique_id(id_num,addr);
2650                 unique_id = id_num;
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"));
2656 #endif
2657
2658                         Psnet_reliable_out[packet_index]->player_acks |= (1<<player_index);
2659                         
2660                         // check to see if this packet is _done_
2661                         psnet_reliable_evaluate_status(Psnet_reliable_out[packet_index]);                       
2662                 }
2663
2664                 // return 4 bytes processed
2665                 return 4;
2666         }
2667
2668         // otherwise - see if this is a new packet
2669         packet_index = psnet_reliable_find_in_id(id_num);
2670         if(packet_index == -1){
2671                 // get a free index
2672                 free_index = psnet_reliable_get_free_incoming();
2673                 if(free_index == -1){
2674                         Int3();
2675                 }
2676
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);
2681
2682                 // send an ack
2683                 psnet_reliable_send_ack(addr,id_num);
2684
2685                 // return 2 bytes processed
2686                 return 2;
2687         }
2688         // send another ack for good measure
2689         else {
2690                 psnet_reliable_send_ack(addr,id_num);
2691         }
2692
2693         return 0;       
2694 }
2695
2696 // forward definitions --------------------------------------------
2697
2698 // free up all used buffers
2699 void psnet_reliable_free_all_buffers()
2700 {
2701         int idx;
2702
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;
2709                 }
2710         }
2711
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;
2718                 }
2719         }
2720 }
2721
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)
2724 {
2725         int idx;
2726
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])){
2730                         return idx;
2731                 }
2732         }
2733
2734         // couldn't find the address
2735         return -1;
2736 }
2737
2738 // get the index into the address array from the passed bitflag
2739 int psnet_reliable_index_addr(int flags)
2740 {
2741         int idx;
2742
2743         // look through all the bits in the flags
2744         for(idx=0;idx<MAX_PLAYERS;idx++){
2745                 if(flags & (1<<idx)){
2746                         return idx;
2747                 }
2748         }
2749
2750         // couldn't find any
2751         return -1;
2752 }
2753
2754 // kill all outgoing packets belonging to the passed index
2755 void psnet_reliable_kill_outgoing(int index)
2756 {
2757         int idx;
2758
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));
2765                                 continue;
2766                         } 
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;
2771                         }
2772                 }
2773         }
2774 }
2775
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)
2779 {
2780         int idx;
2781         ushort cast;
2782         
2783         // if the lower 4 bits are not clear, we've got a problem
2784         if(id_num & 0xf){
2785                 Int3();
2786         }
2787
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
2792                         cast = (ushort)idx;
2793                         id_num |= (cast & 0xf);
2794                         return id_num;
2795                 }
2796         }
2797
2798         // couldn't find an id#
2799         return PSNET_RELIABLE_INVALID;
2800 }
2801
2802 // get the upper 12 bit version of my id# and increment the original
2803 ushort psnet_reliable_get_next_id()
2804 {
2805         ushort id_num = Psnet_reliable_local_id;
2806
2807         // clear out the upper 4 bits
2808         id_num &= 0x0fff;
2809
2810         // shift 4 bits to the left
2811         id_num <<= 4;
2812
2813         // increment the local id #
2814         if(Psnet_reliable_local_id == 0x0fff){
2815                 Psnet_reliable_local_id = 0x1;
2816         } else {
2817                 Psnet_reliable_local_id++;
2818         }
2819
2820         // return the shifted value
2821         return id_num;
2822 }
2823
2824 // get the index of a free outgoing relible packet buffer, killing the oldest if necessary
2825 int psnet_reliable_get_free_outgoing()
2826 {
2827         fix oldest = -1;
2828         int oldest_index = -1;
2829         int idx;
2830
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){
2834                         return idx;
2835                 }
2836
2837                 // keep track of the oldest packet
2838                 if((oldest_index == -1) || (Psnet_reliable_out[idx]->age < oldest)){
2839                         oldest_index = idx;
2840                         oldest = Psnet_reliable_out[idx]->age;
2841                 }
2842         }
2843
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"));
2849 #endif
2850         return oldest_index;
2851 }
2852
2853 // get the index of a free incoming relible packet buffer, killing the oldest if necessary
2854 int psnet_reliable_get_free_incoming()
2855 {
2856         fix oldest = -1;
2857         int oldest_index = -1;
2858         int idx;
2859
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){
2863                         return idx;
2864                 }
2865
2866                 // keep track of the oldest packet
2867                 if((oldest_index == -1) || (Psnet_reliable_in[idx]->age < oldest)){
2868                         oldest_index = idx;
2869                         oldest = Psnet_reliable_in[idx]->age;
2870                 }
2871         }
2872
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"));
2877 #endif
2878         return oldest_index;
2879 }
2880
2881 // actually send the data contained with the reliable_packet_out
2882 int psnet_reliable_send_packet(reliable_packet_out *out,int force_index)
2883 {       
2884         ubyte data[MAX_PACKET_SIZE];    
2885         int idx,bytes_sent;
2886         int packet_size = 2 + out->packet_size;
2887
2888         // stick the identifier on the front of the packet
2889         memcpy(data,&out->out_id,sizeof(ushort));
2890
2891         // copy in the actual data
2892         memcpy(data+2,out->data,out->packet_size);
2893
2894         // send the packet and update the timestamp for all players
2895         
2896         // send to one specified player in the packet
2897         bytes_sent = 0;
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]++;
2903                 }
2904         }
2905         // send to all players contained in the packet
2906         else {
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]++;
2913                         }
2914                 }
2915         }
2916
2917         // return success
2918         return bytes_sent;
2919 }
2920
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)
2923 {
2924         int idx,ok;
2925
2926         // check to see if all players have acked or failed miserably
2927         ok = 1;
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))){
2931                         ok = 0;
2932                         break;
2933                 }
2934         }
2935
2936         // if its ok to annihilate this packet, do so
2937         if(ok){
2938                 memset(out,0,sizeof(reliable_packet_out));
2939         }
2940 }
2941
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)
2944 {
2945         int idx;
2946
2947         // if the id is 0, its invalid
2948         if(id_num == PSNET_RELIABLE_INVALID){
2949                 return -1;
2950         }
2951
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){
2955                         return idx;
2956                 }
2957         }
2958
2959         // couldn't find it 
2960         return -1;
2961 }
2962
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)
2965 {
2966         int idx;
2967
2968         // if the id is 0, its invalid
2969         if(id_num == PSNET_RELIABLE_INVALID){
2970                 return -1;
2971         }
2972
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){
2976                         return idx;
2977                 }
2978         }
2979
2980         // couldn't find it 
2981         return -1;
2982 }
2983
2984 // send an ack to the specified address
2985 void psnet_reliable_send_ack(net_addr_t *addr,ushort id_num)
2986 {
2987         ubyte data[10];
2988         ushort val;
2989
2990         // add in the ack
2991         val = PSNET_RELIABLE_ACK;
2992         memcpy(data,&val,sizeof(ushort));
2993
2994         // add in the id#
2995         memcpy(data+2,&id_num,sizeof(ushort));
2996
2997         // send the data
2998         psnet_send(addr,data,4,PSNET_FLAG_RAW,Reliable_socket);
2999 }
3000
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)
3003 {
3004         net_addr_t addr;
3005         int ret;
3006         int ret_len;
3007
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);
3010         if(!ret){
3011                 Int3();
3012                 return -1;
3013         }
3014
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);
3020
3021         // return bytes read
3022         return ret_len;
3023 }
3024
3025 int SELECT(int nfds, fd_set *readfds, fd_set *writefds, fd_set*exceptfds, struct timeval* timeout, int psnet_type)
3026 {
3027         // if this is a check for writability, just return the select
3028         if(writefds != NULL){
3029                 return select(nfds, readfds, writefds, exceptfds, timeout);
3030         }
3031
3032         // do we have any buffers in here?
3033         if((Psnet_lowest_id == -1) || (Psnet_lowest_id > Psnet_highest_id)){
3034                 return 0;
3035         }
3036
3037         // yo
3038         return 1;
3039 }
3040
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)
3043 {
3044         return sendto(s, buf, len, flags, (struct sockaddr *)to, tolen);
3045 }
3046
3047 // call this once per frame to read everything off of our socket
3048 void PSNET_TOP_LAYER_PROCESS()
3049 {
3050         psnet_get_socket_data(Unreliable_socket);
3051 }
3052
3053 #endif  // #ifndef PSNET2