]> icculus.org git repositories - taylor/freespace2.git/blob - src/network/psnet.cpp
switch to SDL_min/SDL_max (fixes compiler errors)
[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         struct sockaddr_in RmtAddr;
538         SOCKET hSock;
539         int nRet;
540
541         // Init local address to zero
542         LclAddr.sin_addr.s_addr = INADDR_ANY;
543         
544         // Get the local host name
545         nRet = gethostname(LclHost, MAXHOSTNAME );
546         if (nRet != SOCKET_ERROR )      {
547                 // Resolve host name for local address
548                 Hostent = gethostbyname((char *)LclHost);
549                 if ( Hostent )
550                         LclAddr.sin_addr.s_addr = ((in_addr *)(Hostent->h_addr))->s_addr;
551         }
552                         
553         return LclAddr.sin_addr.s_addr;
554
555         RmtAddr = RmtAddr;
556         hSock = hSock;
557 }
558
559 // psnet_get_ip() attempts to get the local IP address of this machine
560 // returns 0 on failure, and 1 on success
561 int psnet_get_ip( SOCKET s )
562 {
563         int rval;
564         SOCKLEN_T len;
565         struct sockaddr_in local_addr;
566
567         if ( Psnet_my_addr_valid ){
568                 return 1;
569         }
570
571         memset(&local_addr, 0, sizeof(struct sockaddr_in));
572         len = sizeof(struct sockaddr_in);
573         rval = getsockname(s, (struct sockaddr *)&local_addr, &len );
574         if ( rval == SOCKET_ERROR )
575                 return 0;
576
577         // now we should have an IP address of this machine.
578         memcpy(Psnet_my_addr.addr, &(local_addr.sin_addr), 4);
579         Psnet_my_addr.port = ntohs(local_addr.sin_port);        
580
581         Psnet_my_addr_valid = 1;
582         return 1;
583 }
584
585 // -------------------------------------------------------------------------------------------------
586 // psnet_close()
587 //
588 //
589
590 void psnet_close()
591 {
592 #ifndef PSNET_RELIABLE_OLD_SCHOOL
593         psnet_reliable_close(); 
594 #endif
595
596         if ( Network_status != NETWORK_STATUS_RUNNING )
597                 return;
598
599 #ifndef PLAT_UNIX
600         WSACancelBlockingCall();
601 #endif
602
603         if ( TCP_listen_socket != (SOCKET)INVALID_SOCKET ) {
604                 shutdown( TCP_listen_socket, 1 );
605                 closesocket( TCP_listen_socket );
606         }
607
608         if ( TCP_reliable_socket != (SOCKET)INVALID_SOCKET ) {
609                 shutdown( TCP_reliable_socket, 1 );
610                 closesocket( TCP_reliable_socket );
611         }
612
613         if ( TCP_socket != (SOCKET)INVALID_SOCKET ) {
614                 shutdown( TCP_socket, 1 );
615                 closesocket( TCP_socket );
616         }
617
618 #ifndef PLAT_UNIX
619         if (WSACleanup())       {
620                 //Warning( LOCATION, "Error closing wsock!\n" );
621         }
622 #endif
623         
624         Network_status = NETWORK_STATUS_NOT_INITIALIZED;
625 }
626
627 // function to initialize a reliable socket.  All it does is call the socket() command.
628 // returns 1 on success, 0 on failure.
629 int psnet_init_stream( SOCKET *s, int type )
630 {
631         SOCKET sock;
632
633         SDL_assert(type == NET_TCP);
634
635         sock = socket(AF_INET,SOCK_STREAM,0);
636         if ( sock == (SOCKET)INVALID_SOCKET )
637                 return 0;
638
639         *s = sock;
640
641         return 1;
642 }
643
644 // called by psnet_init to initialize the listen socket used by a host/server
645 int psnet_init_reliable(ushort port, int should_listen, int type)
646 {
647         SOCKET sock = 0;                // JAS: Get rid of optimized warning
648         struct sockaddr_in sockaddr;            // UDP/TCP socket structure
649
650         // set up the reliable TCP transport socket
651         if ( !psnet_init_stream(&sock, type) ) {
652                 nprintf(("Network", "Unable to initialize reliable socket on port %d (%d)!\n"  , port, WSAGetLastError() )); 
653                 return INVALID_SOCKET;
654         }
655
656         // bind the socket to the port
657         SDL_assert(type == NET_TCP);
658
659         memset( &sockaddr, 0, sizeof(struct sockaddr_in) );
660         sockaddr.sin_family = AF_INET;
661         sockaddr.sin_addr.s_addr = INADDR_ANY;  //fill in with our IP
662         sockaddr.sin_port = htons( port );
663         if ( bind(sock, (struct sockaddr*)&sockaddr, sizeof (sockaddr)) == SOCKET_ERROR) {
664                 nprintf(("Network", "Unable to bind reliable socket on port %d (%d)!\n"  , port, WSAGetLastError() ));
665                 return INVALID_SOCKET;
666         }
667
668
669         // set up the listen on the Reliable_socket port
670         if ( should_listen && listen(sock, 5) ) {
671                 nprintf(("Network", "Unable to listen on Listen Socket (%d)!\n"  , WSAGetLastError() )); 
672                 return INVALID_SOCKET;
673         }
674
675         // make any reliable sockets which we create that aren't listening non-blocking sockets
676         if ( !should_listen ) {
677                 int error;
678                 unsigned long arg;
679
680                 arg = TRUE;
681                 error = ioctlsocket( sock, FIONBIO, &arg );
682                 if ( error == SOCKET_ERROR ) {
683                         nprintf(("Network", "Unable to make reliable socket non-blocking -- %d", WSAGetLastError() ));
684                         return INVALID_SOCKET;
685                 }
686
687                 // set the reuse option
688                 if ( psnet_set_socket_mode(sock, SO_REUSEADDR, 1) == SOCKET_ERROR ) {
689                         error = WSAGetLastError();
690                         nprintf(("Network", "Error setting socket to reuse address -- %d\n", error));
691                 }
692
693         }
694
695         return sock;
696 }
697
698 void psnet_socket_options( SOCKET sock )
699 {
700         int broadcast;
701         int ret, cursize, bufsize, trysize;
702         SOCKLEN_T cursizesize;
703
704         // Set the mode of the socket to allow broadcasting.  We need to be able to broadcast
705         // when a game is searched for in IPX mode.
706         broadcast = 1;
707         if(setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char *)&broadcast, sizeof(broadcast) )){
708                 Can_broadcast = 0;
709         } else {
710                 Can_broadcast = 1;
711         }
712
713         // try and increase the size of my receive buffer
714         bufsize = MAX_RECEIVE_BUFSIZE;
715         
716         // set the current size of the receive buffer
717         cursizesize = sizeof(int);
718         getsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char *)&cursize, &cursizesize);
719         for ( trysize = bufsize; trysize >= cursize; trysize >>= 1 ) {
720                 ret = setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char *)&trysize, sizeof(trysize));
721                 if ( ret == SOCKET_ERROR ) {
722                         int wserr;
723
724                         wserr = WSAGetLastError();
725                         if ( (wserr == WSAENOPROTOOPT) || (wserr == WSAEINVAL) )
726                                 break;
727                 } else
728                         break;
729         }
730         getsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char *)&cursize, &cursizesize);
731         nprintf(("Network", "Receive buffer set to %d\n", cursize));
732
733         // set the current size of the send buffer
734         cursizesize = sizeof(int);
735         getsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *)&cursize, &cursizesize);
736         for ( trysize = bufsize; trysize >= cursize; trysize >>= 1 ) {
737                 ret = setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *)&trysize, sizeof(trysize));
738                 if ( ret == SOCKET_ERROR ) {
739                         int wserr;
740
741                         wserr = WSAGetLastError();
742                         if ( (wserr == WSAENOPROTOOPT) || (wserr == WSAEINVAL) )
743                                 break;
744                 } else
745                         break;
746         }
747         getsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *)&cursize, &cursizesize);
748         nprintf(("Network", "Send buffer set to %d\n", cursize));
749 }
750
751
752 // psnet_init called at game startup time and initializes all sockets that the game might use (i.e. for both
753 // IPX and TCP).
754 void psnet_init( int protocol, int port_num )
755 {       
756         const char *internet_connection;
757 #ifndef PLAT_UNIX
758         WSADATA wsa_data;
759 #endif
760
761         // UDP/TCP socket structure
762         struct sockaddr_in sockaddr;
763
764         Tcp_active = 0;
765
766 #if defined(DEMO) || defined(OEM_BUILD) // not for FS2_DEMO
767         return;
768 #endif
769
770         // GAME PORT INITIALIZATION STUFF
771         if ( Network_status == NETWORK_STATUS_RUNNING )
772                 return;
773
774         // 'lan' should be a safe default in 2015
775         internet_connection = os_config_read_string("Network", "NetworkConnection", "LAN");
776
777         if ( !SDL_strcasecmp(internet_connection, NOX("dialup")) ) {
778                 ml_string("psnet_init() detected dialup connection");
779
780                 Psnet_connection = NETWORK_CONNECTION_DIALUP;
781         } else if ( !SDL_strcasecmp(internet_connection, NOX("lan")) ) {
782                 ml_string("psnet_init() detected lan connection");
783
784                 Psnet_connection = NETWORK_CONNECTION_LAN;
785         } else {
786                 ml_string("psnet_init() detected no connection");
787
788                 Psnet_connection = NETWORK_CONNECTION_NONE;
789         }
790
791         Network_status = NETWORK_STATUS_NO_WINSOCK;
792
793 #ifndef PLAT_UNIX
794         if (WSAStartup(0x101, &wsa_data )){
795                 return;
796         }
797 #endif
798
799         // get the port for running this game on.  Be careful that it cannot be out of bounds
800         Psnet_default_port = DEFAULT_GAME_PORT;
801         if ( (port_num > 1023) && (port_num < USHRT_MAX) ) {
802                 Psnet_default_port = (ushort)port_num;
803         }
804
805 #ifndef PSNET_RELIABLE_OLD_SCHOOL
806         if(!psnet_reliable_init()){
807                 nprintf(("Network","PSNET RELIABLE : init failed - no networking available!\n"));
808                 return;
809         }
810 #endif
811
812         // initialize TCP now
813         TCP_socket = INVALID_SOCKET;
814         TCP_reliable_socket = INVALID_SOCKET;
815         TCP_listen_socket = INVALID_SOCKET;
816
817         Network_status = NETWORK_STATUS_NO_PROTOCOL;
818         TCP_socket = socket( AF_INET, SOCK_DGRAM, 0 );
819         if ( TCP_socket == (SOCKET)INVALID_SOCKET ) {
820                 Tcp_failure_code = WSAGetLastError();
821                 nprintf(("Network", "Error on TCP startup %d\n", Tcp_failure_code));
822                 return;
823         }
824
825         // bind the socket
826         memset(&sockaddr,0,sizeof(struct sockaddr_in));
827         sockaddr.sin_family = AF_INET; 
828
829         sockaddr.sin_addr.s_addr = INADDR_ANY;  //fill in with our IP
830
831         sockaddr.sin_port = htons( Psnet_default_port );
832         if ( bind(TCP_socket, (struct sockaddr*)&sockaddr, sizeof (sockaddr)) == SOCKET_ERROR) {
833                 Tcp_failure_code = WSAGetLastError();
834                 nprintf(( "Network", "Couldn't bind TCP socket (%d)! Invalidating TCP\n", Tcp_failure_code )); 
835                 return;
836         }
837
838 #ifdef PSNET_RELIABLE_OLD_SCHOOL
839         // set up reliable socket (using SPX).
840         TCP_reliable_socket = psnet_init_reliable( 0, 0, NET_TCP );
841         if ( TCP_reliable_socket == (SOCKET)INVALID_SOCKET ) {
842                 Tcp_failure_code = WSAGetLastError();
843                 nprintf(( "Network", "Couldn't initialize TCP reliable socket (OLD SCHOOL) (%d)! Invalidating TCP\n", Tcp_failure_code )); 
844                 return;
845         }
846
847         TCP_listen_socket = psnet_init_reliable( (u_short)(Psnet_default_port-1), 1, NET_TCP );
848         if ( TCP_listen_socket == (SOCKET)INVALID_SOCKET ) {
849                 Tcp_failure_code = WSAGetLastError();
850                 nprintf(( "Network", "Couldn't initialize TCP listen socket (OLD SCHOOL) (%d)! Invalidating TCP\n", Tcp_failure_code )); 
851                 return;
852         }
853 #endif
854
855         Tcp_active = 1;
856
857         psnet_socket_options( TCP_socket );             
858         Tcp_can_broadcast = Can_broadcast;
859         Can_broadcast = 0;
860
861 // fire up a second UDP socket for "reliable" transport
862 #ifndef PSNET_RELIABLE_OLD_SCHOOL
863         TCP_reliable_socket = socket( AF_INET, SOCK_DGRAM, 0 );
864         if ( TCP_reliable_socket != INVALID_SOCKET )    {
865                 // bind the socket
866                 memset(&sockaddr,0,sizeof(struct sockaddr_in));
867                 sockaddr.sin_family = AF_INET; 
868
869                 sockaddr.sin_addr.s_addr = INADDR_ANY;  //fill in with our IP
870                 //unsigned long my_ip = sock_get_ip();
871                 //memcpy(&sockaddr.sin_addr.s_addr,&my_ip,sizeof(uint));
872
873                 sockaddr.sin_port = htons( (ushort)(port+1) );
874                 if ( bind(TCP_reliable_socket, (struct sockaddr*)&sockaddr, sizeof (sockaddr)) == SOCKET_ERROR) {
875                         nprintf(( "Network", "Couldn't bind TCP socket (%d)! Invalidating TCP\n", WSAGetLastError() )); 
876                         goto tcp_done;
877                 }
878
879                 psnet_socket_options( TCP_reliable_socket );            
880                 Can_broadcast = 0;
881         }
882 #endif
883
884         psnet_ras_status();
885
886         Network_status = NETWORK_STATUS_RUNNING;
887
888         nprintf(("Network","TCP Initialized\n"));
889
890         // with TCP initialized, see if the RAS services are installed
891
892
893 #ifndef NDEBUG
894         psnet_frame_int = -1;           // for counting bytes per frame
895 #endif
896
897 #ifdef PSNET_BUFFER_OLD_SCHOOL
898         Next_packet_id = 0;
899         Last_packet_id = -1;
900
901         // initialize the packet buffer stuff.  We use an array (the packet_free_list) to determine
902         // which of the packet buffers we can use next.
903         int i;
904         for (i=0; i<MAX_PACKET_BUFFERS; i++ )   {
905                 packet_buffers[i].sequence_number = -1;
906                 packet_free_list[i] = (short)i;
907         }
908         Num_packet_buffers = 0;
909         Largest_packet_index = 0;
910 #else
911         // initialize the new buffering system
912         psnet_buffer_init();
913 #endif
914 }
915
916 #define MAX_TMPBUF_SIZE 1024
917
918 #ifdef PSNET_RELIABLE_OLD_SCHOOL
919 // function to shutdown and close the given socket.  It takes a couple of things into consideration
920 // when closing, such as possibly reiniting reliable sockets if they are closed here.
921 void psnet_rel_close_socket( PSNET_SOCKET *p_sockp )
922 {
923         int reinit_type;
924         int error, rval;
925         SOCKET *sockp;
926
927         sockp = (SOCKET *)p_sockp;
928
929         if ( *sockp == (SOCKET)INVALID_SOCKET )
930                 return;
931
932 #ifndef NDEBUG
933         if ( *sockp == TCP_reliable_socket )
934                 nprintf(("network", "Closing my relibale TCP socket\n"));
935         else 
936                 nprintf(("Network", "Closing client's reliable socket\n"));
937 #endif
938
939         // make the socket blocking
940         //unsigned long val = 0;
941         //rval = ioctlsocket(*sockp,FIONBIO,&val);
942         //if ( rval == SOCKET_ERROR ) {
943         //      error = WSAGetLastError();
944         //      nprintf(("Network", "Error %d when trying to make reliable socket blocking.\n", error));
945         //}
946
947         // set the socket to linger with a timeout of 0
948         linger l_val;
949         l_val.l_onoff = 1;
950         l_val.l_linger = 0;
951         rval = setsockopt(*sockp,SOL_SOCKET,SO_LINGER,(char*)&l_val,sizeof(linger));
952         if ( rval == SOCKET_ERROR ) {
953                 error = WSAGetLastError();
954                 nprintf(("Network", "Error %d when trying to set linger value.\n", error));
955         }
956
957         // see if this socket is my Reliable_socket.  If so, I will have to reinitialize it!
958         reinit_type = -1;
959         if ( *sockp == TCP_reliable_socket )
960                 reinit_type = NET_TCP;
961
962         // if this is the server connection, mark it as done
963         if (*sockp == (SOCKET)Serverconn) {
964                 Serverconn = 0xffffffff;
965         }
966
967         /*
968         rval = shutdown( *sockp, 2);            // shut the whole damn thing down.
969         if ( rval == SOCKET_ERROR ) {
970                 error = WSAGetLastError();
971                 nprintf(("Network", "Error %d on socket shutdown\n", error));
972         }
973         */
974
975         shutdown( *sockp, 1 );
976         rval = 1;
977         while ( rval && (rval != SOCKET_ERROR) ) {
978                 char tmp_buf[MAX_TMPBUF_SIZE];
979
980                 rval = recv( *sockp, tmp_buf, MAX_TMPBUF_SIZE, 0 );
981                 if ( rval == SOCKET_ERROR ) {
982                         error = WSAGetLastError();
983                         if ( NETCALL_WOULDBLOCK(error) )
984                                 break;
985                 }
986         }
987
988         rval = closesocket( *sockp );
989         if ( rval == SOCKET_ERROR ) {
990 #ifndef NDEBUG
991                 error = WSAGetLastError();
992                 nprintf(("Network", "Error %d on closing socket\n", error ));
993 #endif
994         }
995
996         *sockp = INVALID_SOCKET;
997
998         // see if we need to reinitialize
999         if ( reinit_type != -1 ) {
1000                 if ( reinit_type == NET_TCP){
1001                         TCP_reliable_socket = psnet_init_reliable( 0, 0, NET_TCP);
1002                         Reliable_socket = TCP_reliable_socket;
1003                 }
1004         }
1005 }
1006 #else
1007 // function to shutdown and close the given socket.  It takes a couple of things into consideration
1008 // when closing, such as possibly reiniting reliable sockets if they are closed here.
1009 void psnet_close_socket( PSNET_SOCKET *p_sockp )
1010 {
1011         net_addr_t remove;
1012
1013         // copy the address to be removed
1014         memcpy(&remove,&((net_addr_t*)(*p_sockp)),sizeof(net_addr_t));
1015
1016         // remove it from the reliable address list
1017         psnet_reliable_notify_drop_addr(&remove);
1018
1019         // invalidate the passed in "socket"
1020         *p_sockp = NULL;
1021 }
1022 #endif
1023
1024 // function to check the status of the reliable socket and try to re-initialize it if necessary.
1025 // win95 seems to have trouble doing a reinit of the socket immediately after close, so this
1026 // function exists to check the status, and reinitialize if we need to
1027 int psnet_rel_check()
1028 {
1029         // if our Reliable_socket is valid, simply return true to indicate all is well.
1030         if ( Reliable_socket != (SOCKET)INVALID_SOCKET )
1031                 return 1;
1032
1033         // based on our protocol type, try to reinitialize the socket we need.
1034         SDL_assert(Socket_type == NET_TCP);
1035
1036         TCP_reliable_socket = psnet_init_reliable( 0, 0, NET_TCP);
1037         Reliable_socket = TCP_reliable_socket;
1038
1039         // return our status.
1040         if ( Reliable_socket == (SOCKET)INVALID_SOCKET )
1041                 return 0;
1042
1043         return 1;
1044 }
1045
1046 // this function is called from a high level at FreeSpace to set the protocol that the user wishes to use
1047 int psnet_use_protocol( int protocol )
1048 {
1049         // zero out my address
1050         Psnet_my_addr_valid = 0;
1051         memset( &Psnet_my_addr, 0, sizeof(Psnet_my_addr) );
1052
1053         // wait until we choose a protocol to determine if we can broadcast
1054         Can_broadcast = 0;
1055
1056         SDL_assert(protocol == NET_TCP);
1057
1058         if ( Network_status != NETWORK_STATUS_RUNNING )
1059                 return 0;
1060
1061         // assign the TCP_* sockets to the socket values used elsewhere
1062         Unreliable_socket = TCP_socket;
1063         Reliable_socket = TCP_reliable_socket;
1064         Listen_socket = TCP_listen_socket;
1065
1066         Can_broadcast = Tcp_can_broadcast;
1067         if(Can_broadcast){
1068                 nprintf(("Network","Psnet : TCP broadcast\n"));
1069         }
1070
1071         nprintf(("Network","Psnet using - NET_TCP\n"));
1072
1073         Psnet_my_addr.type = protocol;
1074         Socket_type = protocol;
1075
1076         return 1;
1077 }
1078
1079 #define MAX_CONNECT_TRIES       10
1080
1081 // attacmpt to connect() to the server's tcp socket.  socket parameter is simply assigned to the
1082 // Reliable_socket socket created in psnet_init
1083 void psnet_rel_connect_to_server( PSNET_SOCKET *psocket, net_addr_t *server_addr)
1084 {
1085         struct sockaddr_in sockaddr;                            // UDP/TCP socket structure
1086         struct sockaddr *addr;                                          // pointer to struct sockaddr to make coding easier
1087         SOCKET *socket;
1088         ubyte iaddr[IP_ADDRESS_LENGTH];
1089         u_short port;
1090         int name_length, val;
1091
1092         memset(iaddr, 0x00, IP_ADDRESS_LENGTH);
1093         memcpy(iaddr, server_addr->addr, IP_ADDRESS_LENGTH);
1094         port = (u_short)(server_addr->port - 1);
1095
1096         socket = (SOCKET *)psocket;
1097
1098         SDL_assert(Socket_type == NET_TCP);
1099
1100         sockaddr.sin_family = AF_INET;
1101         memcpy(&sockaddr.sin_addr.s_addr, iaddr, 4);
1102         sockaddr.sin_port = htons(port);
1103         addr = (struct sockaddr *)&sockaddr;
1104         name_length = sizeof(sockaddr);
1105
1106         // NETLOG
1107         ml_string(NOX("Attempting to perform reliable TCP connect to server"));
1108
1109         // connect this guys Reliable_socket to the socket parameter passed in
1110         *socket = INVALID_SOCKET;
1111         val = connect(Reliable_socket, addr, name_length);
1112
1113          // I suppose that we could have a valid socket right away
1114         if ( val != SOCKET_ERROR ) {
1115                 *socket = Reliable_socket;
1116         } else {
1117                 int error;
1118
1119                 error = WSAGetLastError();
1120                 if ( NETCALL_WOULDBLOCK(error) ) {                      // use select to find out when socket is writeable
1121                         int is_set, num_tries;
1122                         fd_set wfds;
1123                         struct timeval timeout;
1124
1125                         // call select -- and return if an error leaving our connection to the client invalid
1126                         num_tries = 0;
1127                         do {
1128                                 FD_ZERO(&wfds);
1129                                 FD_SET( Reliable_socket, &wfds );
1130                                 timeout.tv_sec = 0;
1131                                 timeout.tv_usec = 500000;                       //500000 micro seconds is 1/2 second
1132
1133                                 is_set = select( Reliable_socket+1, NULL, &wfds, NULL, &timeout);
1134
1135                                 // check for error on select first
1136                                 if ( is_set == SOCKET_ERROR ) {
1137                                         nprintf(("Network", "Error on select for connect %d\n", WSAGetLastError() ));
1138                                         return;
1139                                 } else if (is_set) {                    // if set, then we have connection, move forward
1140                                         break;
1141                                 } else {
1142                                         SDL_Delay(10);                                  // sleep for 10 ms and try again
1143                                         num_tries++;
1144                                 }
1145                         } while ( num_tries < MAX_CONNECT_TRIES );
1146
1147                         if ( num_tries == MAX_CONNECT_TRIES )
1148                                 return;
1149
1150                         *socket = Reliable_socket;
1151
1152                 } else {
1153                         nprintf(("Network", "Connecting with server failed %d\n", error ));
1154                         *socket = INVALID_SOCKET;
1155                 }
1156         }
1157
1158         // if we have a connection, get my address from getsockname
1159         if ( *socket == Reliable_socket ) {
1160                 if ( !psnet_get_ip(Reliable_socket) ) {
1161                         *socket = INVALID_SOCKET;
1162                         return;
1163                 }
1164
1165                 Serverconn = *socket;
1166         }
1167 }
1168
1169 #ifndef NDEBUG
1170 void psnet_calc_bytes_per_frame()
1171 {
1172 }
1173 #endif
1174
1175 // -------------------------------------------------------------------------------------------------
1176 // psnet_same()
1177 //
1178 //
1179
1180 int psnet_same_no_port( net_addr_t * a1, net_addr_t * a2 )
1181 {
1182         if ( !memcmp(a1->addr, a2->addr, IP_ADDRESS_LENGTH) )
1183                 return 1;
1184         return 0;
1185 }
1186
1187 int psnet_same( net_addr_t * a1, net_addr_t * a2 )
1188 {
1189         return psnet_same_no_port( a1, a2 );
1190 /*
1191         if ( !memcmp(a1->addr, a2->addr, 6)  && a1->port == a2->port)
1192                 return 1;
1193         return 0;
1194 */
1195 }
1196
1197 // -------------------------------------------------------------------------------------------------
1198 // psnet_describe()
1199 //
1200 //
1201
1202 char* psnet_addr_to_string( char * text, const int max_textlen, net_addr_t * address )
1203 {
1204
1205         if ( Network_status != NETWORK_STATUS_RUNNING )         {
1206                 SDL_strlcpy( text, XSTR("[no networking]",910), max_textlen );
1207                 return text;
1208         }
1209
1210         in_addr temp_addr;
1211
1212         SDL_assert(address->type == NET_TCP);
1213
1214         switch ( address->type ) {
1215                 case NET_TCP:
1216                         memcpy(&temp_addr.s_addr, address->addr, 4);
1217                         SDL_strlcpy( text, inet_ntoa(temp_addr), max_textlen );
1218                         break;
1219
1220                 default:
1221                         // SDL_assert(0);
1222                         break;
1223
1224         } // end switch
1225         
1226         return text;
1227 }
1228
1229
1230 // -------------------------------------------------------------------------------------------------
1231 // psnet_undescribe()
1232 //
1233 //
1234
1235 void psnet_string_to_addr( net_addr_t * address, char * text, const int max_textlen )
1236 {
1237         struct hostent *he;
1238         char str[255], *c, *port;
1239         in_addr addr;
1240
1241         if ( Network_status != NETWORK_STATUS_RUNNING ) {
1242                 SDL_strlcpy( text, XSTR("[no networking]",910), max_textlen );
1243                 return;
1244         }
1245
1246         // copy the text string to local storage to look for ports
1247         SDL_assert( strlen(text) < 255 );
1248         SDL_strlcpy(str, text, SDL_arraysize(str));
1249         c = strrchr(str, ':');
1250         port = NULL;
1251         if ( c ) {
1252                 *c = '\0';
1253                 port = c+1;
1254         }
1255
1256         switch ( address->type ) {
1257                 case NET_TCP:
1258                         addr.s_addr = inet_addr(str);
1259                         // if we get INADDR_NONE returns, then we need to try and resolve the host
1260                         // name
1261                         if ( addr.s_addr == INADDR_NONE ) {
1262                                 he = gethostbyname( str );
1263                                 // returns a non-null pointer if successful, so get the address
1264                                 if ( he ) {
1265                                         addr.s_addr = ((in_addr *)(he->h_addr))->s_addr;                        // this is the address in network byte order
1266                                 } else {
1267                                         addr.s_addr = INADDR_NONE;
1268                                 }
1269                         }
1270
1271                         memset(address->addr, 0x00, IP_ADDRESS_LENGTH);
1272                         memcpy(address->addr, &addr.s_addr, 4);
1273                         if ( port )
1274                                 address->port = (ushort)(atoi(port));
1275                         break;
1276
1277                 default:
1278                         SDL_assert(0);
1279                         break;
1280
1281         } // end switch
1282
1283 }
1284
1285 // psnet_get_socket_data() will get data out of the socket and stuff it into the packet_buffers
1286 // The original psnet_get() now calls this function, then determines which of the packet buffers
1287 // to package up and use
1288 void psnet_get_socket_data(SOCKET socket, int flags = PSNET_FLAG_RAW)
1289 {
1290         struct sockaddr_in ip_addr;                             // UDP/TCP socket structure
1291         fd_set  rfds;
1292         timeval timeout;
1293         int             read_len;
1294         SOCKLEN_T from_len;
1295         net_addr_t      from_addr;
1296         network_checksum_packet packet_read;    
1297         network_checksum_packet packet_data;
1298
1299         // clear the addresses to remove compiler warnings
1300         memset(&ip_addr, 0, sizeof(struct sockaddr_in));
1301
1302         if ( Network_status != NETWORK_STATUS_RUNNING ) {
1303                 nprintf(("Network","Network ==> socket not inited in psnet_get\n"));
1304                 return;
1305         }
1306
1307         while ( 1 ) {           
1308 #ifdef PSNET_BUFFER_OLD_SCHOOL
1309                 int packet_id, id;
1310                 // if there are no more packet buffers that we can use, then we must bail here before reading
1311                 // any data!!!!
1312                 if ( Num_packet_buffers >= MAX_PACKET_BUFFERS ) {
1313                         nprintf(("Network", "Packet buffer overrun in psnet_get()\n"));
1314                         break;
1315                 }
1316 #endif
1317
1318                 // check if there is any data on the socket to be read.  The amount of data that can be 
1319                 // atomically read is stored in len.
1320
1321                 FD_ZERO(&rfds);
1322                 FD_SET( socket, &rfds );
1323                 timeout.tv_sec = 0;
1324                 timeout.tv_usec = 0;
1325
1326                 if ( select( socket+1, &rfds, NULL, NULL, &timeout) == SOCKET_ERROR ) {
1327                         nprintf(("Network", "Error %d doing a socket select on read\n", WSAGetLastError()));
1328                         break;
1329                 }
1330
1331                 // if the read file descriptor is not set, then bail!
1332                 if ( !FD_ISSET(socket, &rfds ) )
1333                         return;
1334
1335                 // get data off the socket and process
1336                 read_len = SOCKET_ERROR;
1337                 switch ( Socket_type ) {
1338                 case NET_TCP:
1339                         from_len = sizeof(struct sockaddr_in);
1340                         if(flags & PSNET_FLAG_RAW){
1341                                 read_len = recvfrom( socket, (char*)packet_read.data, MAX_PACKET_SIZE, 0,  (struct sockaddr*)&ip_addr, &from_len );
1342                         } else {
1343                                 read_len = recvfrom( socket, (char *)&packet_read, sizeof(packet_data), 0,  (struct sockaddr*)&ip_addr, &from_len );
1344                         }
1345                         break;
1346                 
1347                 default:
1348                         Int3();
1349                         break;
1350                 }
1351
1352                 // set the from_addr for storage into the packet buffer structure
1353                 from_addr.type = Socket_type;
1354
1355                 switch ( Socket_type ) {
1356                 case NET_TCP:
1357                         if(socket == Reliable_socket){
1358                                 from_addr.port = Psnet_default_port;
1359                         } else {
1360                                 from_addr.port = ntohs( ip_addr.sin_port );
1361                         }
1362                         memset(from_addr.addr, 0x00, IP_ADDRESS_LENGTH);
1363                         memcpy(from_addr.addr, &ip_addr.sin_addr.s_addr, 4);
1364                         break;
1365
1366                 default:
1367                         SDL_assert(0);
1368                         break;
1369                 }
1370
1371                 if ( read_len == SOCKET_ERROR ) {
1372 #ifndef NDEBUG
1373                         int x = WSAGetLastError();
1374                         nprintf(("Network", "Read error on socket.  Winsock error %d \n", x));
1375 #endif
1376                         break;
1377                 }               
1378
1379 #ifndef PSNET_RELIABLE_OLD_SCHOOL
1380                 int shave_size;
1381                 // now we check to see if this is a reliable packet, and act accordindly
1382                 if(socket == Reliable_socket){
1383                         // this function processes the incoming packet, and determines if the system should continue to process the data
1384                         shave_size = psnet_reliable_should_process(&from_addr,packet_read.data,read_len);
1385                         if(!shave_size){                                
1386                                 continue;
1387                         } else {
1388                                 // copy in from data+2, so we skip the reliable data header
1389                                 memcpy(packet_data.data,packet_read.data + shave_size,read_len);
1390
1391                                 // subtract out the size of the reliable header
1392                                 read_len -= shave_size;
1393                         }
1394                 } else {
1395                         memcpy(packet_data.data,packet_read.data,read_len);
1396                 }
1397 #else
1398                 memcpy(packet_data.data,packet_read.data,read_len);
1399 #endif
1400
1401 #ifdef PSNET_BUFFER_OLD_SCHOOL
1402                 ubyte           *data;
1403                 int len;
1404
1405                 // if we had no error reading from the socket, then determine if we need to calculate a
1406                 // checksum on the packet               
1407                 if ( !(flags & PSNET_FLAG_RAW) && (packet_data.flags & PSNET_FLAG_CHECKSUM) ) {
1408                         ushort checksum;                        
1409
1410                         // calculate the size of the data that is actual real data
1411                         len = read_len - (sizeof(packet_data) - MAX_CHECKSUM_PACKET_SIZE);
1412                         checksum = psnet_calc_checksum( packet_data.data, len );
1413                         if ( checksum != packet_data.checksum ) {
1414                                 nprintf(("Network", "bad checksum on incoming packet -- discarding\n"));
1415                                 return;
1416                         }
1417                         data = packet_data.data;
1418                         packet_id = packet_data.sequence_number;
1419                 } else {
1420                         network_naked_packet *packet;
1421
1422                         // just read in the raw socket data and length
1423                         if(flags & PSNET_FLAG_RAW){
1424                                 data = packet_data.data;
1425                                 len = read_len;
1426
1427                                 packet_id = 0;
1428                         } else {
1429                                 // we don't have a checksum packet.  cast the data to the naked packet type and
1430                                 // copy it over to passed parameters
1431                                 packet = (network_naked_packet *)&packet_data;                          
1432         
1433                                 len = read_len - (sizeof(network_naked_packet) - MAX_PACKET_SIZE);
1434                                 data = packet->data;                            
1435
1436                                 packet_id = packet->sequence_number;
1437                         }                       
1438                 }
1439
1440                 // look at the sequence number compared to what we last received                
1441                 if ( Last_packet_id > -1 ) {
1442                         if ( packet_id != (Last_packet_id+1) ) {
1443                                 //if ( packet_id < Last_packet_id )
1444                                 //      nprintf(("network", "packet %d came in delayed (last id was %d\n", packet_id, Last_packet_id));
1445                                 //else if ( packet_id > (Last_packet_id+1) )
1446                                 //      nprintf(("Network", "missed %d packet(s).  last id %d.  This id %d\n", (packet_id - Last_packet_id), Last_packet_id, packet_id));
1447                         }
1448                 }
1449                 Last_packet_id = packet_id;                             
1450
1451 #ifndef NDEBUG
1452                 psnet_do_net_stats( &from_addr, read_len, 1 );
1453                 psnet_bytes_read_frame += read_len;
1454 #endif
1455
1456                 // put all of the data (length, who from, etc.) into the next available packet buffer
1457                 // slot.  We should be assured of a slot here because of the check at the beginning
1458                 // of the while loop
1459                 SDL_assert ( Num_packet_buffers < MAX_PACKET_BUFFERS );
1460                 id = packet_free_list[ Num_packet_buffers++ ];
1461                 if (id > Largest_packet_index ) Largest_packet_index = id;
1462                 packet_buffers[id].len = len;           // use the flags field of the packet structure to hold the data length
1463                 packet_buffers[id].sequence_number =  packet_id;
1464                 packet_buffers[id].from_addr = from_addr;
1465                 memcpy( packet_buffers[id].data, data, len );           
1466 #else
1467 #ifndef NDEBUG
1468                 psnet_do_net_stats( &from_addr, read_len, 1 );
1469                 psnet_bytes_read_frame += read_len;
1470 #endif
1471
1472                 // buffer the packet
1473                 psnet_buffer_packet(packet_data.data,read_len,&from_addr);
1474 #endif
1475         }
1476 }
1477
1478 // -------------------------------------------------------------------------------------------------
1479 // psnet_send()
1480 //
1481 //
1482
1483 int psnet_send( net_addr_t * who_to, void * data, int len, int flags, int reliable_socket )
1484 {
1485         
1486         SOCKET send_sock;
1487         struct sockaddr_in sockaddr;                            // UDP/TCP socket structure
1488         int ret, send_len;
1489         ubyte iaddr[IP_ADDRESS_LENGTH], *send_data;
1490         short port;
1491         fd_set  wfds;
1492         struct timeval timeout;
1493
1494         if(!reliable_socket){
1495                 send_sock = Unreliable_socket;
1496         } else {
1497                 send_sock = Reliable_socket;
1498         }
1499
1500         if ( Network_status != NETWORK_STATUS_RUNNING ) {
1501                 nprintf(("Network","Network ==> Socket not inited in psnet_send\n"));
1502                 return 0;
1503         }
1504
1505         if ( psnet_same( who_to, &Psnet_my_addr) ){
1506                 return 0;
1507         }
1508
1509         memset(iaddr, 0x00, IP_ADDRESS_LENGTH);
1510         memcpy(iaddr, who_to->addr, IP_ADDRESS_LENGTH);
1511
1512         if ( memcmp(iaddr, Null_address, IP_ADDRESS_LENGTH) == 0) {
1513                 nprintf(("Network","Network ==> send to address is 0 in psnet_send\n"));
1514                 return 0;
1515         }
1516
1517         if(send_sock == Unreliable_socket){
1518                 port = who_to->port;
1519         } else if(send_sock == Reliable_socket){
1520                 port = DEFAULT_GAME_PORT + 1;
1521         } else {
1522                 port = who_to->port;
1523         }
1524                 
1525         if ( port == 0) {
1526                 nprintf(("Network","Network ==> destination port %d invalid in psnet_send\n", port));
1527                 return 0;
1528         }
1529
1530 #ifdef PSNET_BUFFER_OLD_SCHOOL
1531         network_checksum_packet         Send_network_checksum_packet;
1532         network_naked_packet                    Send_network_naked_packet;
1533
1534         // determine from the flags whether or not this packet should have a checksum.
1535         if ( flags & PSNET_FLAG_CHECKSUM ) {      
1536                 // can't send raw data with a checksum, dumbass!
1537                 SDL_assert(!(flags & PSNET_FLAG_RAW));
1538
1539                 Send_network_checksum_packet.sequence_number = Next_packet_id++;
1540                 Send_network_checksum_packet.flags = PSNET_FLAG_CHECKSUM;
1541                                                 
1542                 Send_network_checksum_packet.checksum = psnet_calc_checksum(data, len);
1543                 memcpy( Send_network_checksum_packet.data, data, len );
1544                 send_len = sizeof(Send_network_checksum_packet) - MAX_CHECKSUM_PACKET_SIZE + len;
1545                 send_data = (ubyte *)&Send_network_checksum_packet;
1546         } else {                
1547                 // send standard psnet stuff
1548                 if(!(flags & PSNET_FLAG_RAW)){
1549                         Send_network_naked_packet.sequence_number = Next_packet_id++;           
1550                         Send_network_naked_packet.flags = 0;
1551                                                 
1552                         memcpy(Send_network_naked_packet.data, data, len);
1553                         send_len = sizeof(Send_network_naked_packet) - MAX_PACKET_SIZE + len;           // gets us the real size of the structure
1554                         send_data = (ubyte *)&Send_network_naked_packet;
1555                 }
1556                 // send raw data
1557                 else {
1558                         send_data = (ubyte*)data;
1559                         send_len = len;
1560                 }
1561         }
1562 #else
1563         send_data = (ubyte*)data;
1564         send_len = len;
1565 #endif
1566
1567
1568         FD_ZERO(&wfds);
1569         FD_SET( send_sock, &wfds );
1570         timeout.tv_sec = 0;
1571         timeout.tv_usec = 0;
1572
1573         if ( select( send_sock+1, NULL, &wfds, NULL, &timeout) == SOCKET_ERROR ) {
1574                 nprintf(("Network", "Error on blocking select for write %d\n", WSAGetLastError() ));
1575                 return 0;
1576         }
1577
1578         // if the write file descriptor is not set, then bail!
1579         if ( !FD_ISSET(send_sock, &wfds ) )
1580                 return 0;
1581
1582         ret = SOCKET_ERROR;
1583         switch ( who_to->type ) {
1584
1585                 case NET_TCP:
1586                         sockaddr.sin_family = AF_INET; 
1587                         memcpy(&sockaddr.sin_addr.s_addr, iaddr, 4);
1588                         sockaddr.sin_port = htons(port); 
1589
1590                         ret = sendto( send_sock, (char *)send_data, send_len, 0, (struct sockaddr*)&sockaddr, sizeof(sockaddr) );
1591                         break;
1592
1593                 default:
1594                         SDL_assert(0);  // unknown protocol
1595                         break;
1596
1597         } // end switch
1598
1599         if ( ret != SOCKET_ERROR )      {
1600 #ifndef NDEBUG
1601                 psnet_bytes_written_frame += send_len;
1602                 psnet_do_net_stats( who_to, send_len, 0 );
1603 #endif
1604                 return 1;
1605         }
1606         //Warning( LOCATION, "Couldn't send data (0x%x)!\n", WSAGetLastError() ); 
1607         return 0;
1608 }
1609
1610 #ifdef PSNET_BUFFER_OLD_SCHOOL
1611 // routine to "free" a packet buffer
1612 void free_packet( int id )
1613 {
1614         packet_buffers[id].sequence_number = -1;
1615         packet_free_list[ --Num_packet_buffers ] = (short)id;
1616         if ( Largest_packet_index == id)
1617                 while ((--Largest_packet_index>0) && (packet_buffers[Largest_packet_index].sequence_number == -1 ));
1618 }
1619 #endif
1620
1621 #ifdef PSNET_RELIABLE_OLD_SCHOOL
1622 // psnet_send_reliable sends the given data through the given reliable socket.
1623
1624 #define MAX_RSEND_BUFFER                2048
1625 ubyte rsend_buffer[MAX_RSEND_BUFFER];
1626
1627 int psnet_rel_send( PSNET_SOCKET psocket, ubyte *data, int length, int flags )
1628 {
1629         ubyte *send_data;
1630         int num_sent, total_sent, error, retries;
1631         SOCKET socket;
1632         unsigned short s_length;
1633
1634         socket = (SOCKET)psocket;       
1635
1636         // basic checks
1637         if ( Network_status != NETWORK_STATUS_RUNNING ) {
1638                 nprintf(("Network","Network ==> Socket not inited in psnet_send\n"));
1639                 return 0;
1640         }
1641
1642         if ( socket == (SOCKET)INVALID_SOCKET )         // might happen in race conditions -- should get cleaned up.
1643                 return 0;
1644
1645         SDL_assert( length < MAX_RSEND_BUFFER );
1646
1647         // copy the length of the data into the beginning of the buffer.  then put the data into the buffer
1648         // after the length value
1649         SDL_assert( length > 0 );
1650         s_length = (ushort)length;
1651         memcpy( &rsend_buffer[0], &s_length, sizeof(s_length) );
1652         memcpy( &rsend_buffer[2], data, length );
1653
1654         retries = 0;
1655         total_sent = 0;
1656         send_data = data;
1657         do {
1658                 num_sent = send( socket, (char *)rsend_buffer, length+sizeof(s_length), 0 );
1659                 if ( num_sent == SOCKET_ERROR ) {
1660                         error = WSAGetLastError();
1661                         if ( !NETCALL_WOULDBLOCK(error) || (retries > MAX_SEND_RETRIES) )       {               // means that we would block on send -- not really an error
1662
1663                                 // if error is would block, then set error to aborted connection
1664                                 if ( NETCALL_WOULDBLOCK(error) )
1665                                         error = WSAECONNABORTED;
1666
1667                                 multi_eval_socket_error(socket, error);
1668                                 return 0;
1669                         }
1670                         retries++;                                                                                      // keep a try count
1671                 } else {
1672                         length -= num_sent;
1673                         send_data += num_sent;
1674                         total_sent += num_sent;
1675                 }
1676         } while ( length > 0 );
1677
1678 #ifndef NDEBUG
1679         psnet_bytes_written_frame += total_sent;
1680
1681         //int index;
1682         //index = psnet_find_stats_loc( who_to );
1683         //if ( index != -1 )
1684         //      Psnet_stats[index].total_written += send_len;
1685 #endif
1686         return 1;
1687 }
1688
1689 // get data off the reliable socket
1690 int psnet_rel_get( PSNET_SOCKET psocket, ubyte *buffer, int max_len, int flags)
1691 {
1692         int from_len, total_read, error;
1693         SOCKET socket;
1694         fd_set rfds;
1695         struct timeval timeout;
1696         short read_len;
1697         ubyte rread_buffer[2];
1698
1699         socket = (SOCKET)psocket;
1700
1701         // see if there is data to be read
1702         FD_ZERO(&rfds);
1703         FD_SET( socket, &rfds );
1704         timeout.tv_sec = 0;
1705         timeout.tv_usec = 0;
1706
1707         if ( select( socket+1, &rfds, NULL, NULL, &timeout) == SOCKET_ERROR ) {
1708                 nprintf(("Network", "Error on select for read reliable: %d\n", WSAGetLastError() ));
1709                 return 0;
1710         }
1711
1712         // if no data, then we can leave.
1713         if ( !FD_ISSET(socket, &rfds ) )
1714                 return 0;
1715
1716         // we know we have data to read.  We must read the two byte length of the packet first
1717         total_read = 0;
1718         read_len = 2;
1719         do {
1720                 from_len = recv(socket, (char *)(&rread_buffer[total_read]), read_len - total_read, 0);
1721
1722                 // from_len will be 0 when back end gracefully closes connection.  We will assume that since
1723                 // the close is graceful, we will info from him telling us he's left.  So we'll ignore
1724                 // this condition here.
1725                 if ( from_len == 0 ) {
1726                         nprintf(("Network", "Dumping player because recv returned 0\n"));
1727                         multi_eval_socket_error( socket, WSAECONNRESET );               // this error drops player from game.
1728                         return 0;
1729                 }
1730
1731                 // on a socket error, we need to check for WSAEWOULDBLOCK meaning that there is no more
1732                 // data to be read.
1733                 else if ( from_len == SOCKET_ERROR ) {
1734                         error = WSAGetLastError();
1735                         if ( !NETCALL_WOULDBLOCK(error) )
1736                                 multi_eval_socket_error( socket, error );
1737                         return 0;               // get it next frame?
1738                 }
1739
1740                 total_read += from_len;
1741         } while ( total_read < read_len );
1742
1743
1744         total_read = 0;
1745         memcpy(&read_len, &rread_buffer[0], 2);
1746         SDL_assert( (read_len > 0) && (read_len < max_len) );
1747         if ( read_len == 0 )
1748                 return 0;
1749
1750         do {
1751                 from_len = recv(socket, (char *)(buffer + total_read), read_len - total_read, 0);
1752
1753                 // from_len will be 0 when back end gracefully closes connection.  We will assume that since
1754                 // the close is graceful, we will info from him telling us he's left.  So we'll ignore
1755                 // this condition here.
1756                 if ( from_len == 0 ) {
1757                         nprintf(("Network", "Dumping player because recv returned 0\n"));
1758                         multi_eval_socket_error( socket, WSAECONNRESET );               // this error drops player from game.
1759                         return 0;
1760                 }
1761
1762                 // on a socket error, we need to check for WSAEWOULDBLOCK meaning that there is no more
1763                 // data to be read.
1764                 else if ( from_len == SOCKET_ERROR ) {
1765                         error = WSAGetLastError();
1766                         if ( !NETCALL_WOULDBLOCK(error) ) {
1767                                 multi_eval_socket_error( socket, error );
1768                                 return 0;
1769                         }
1770                         continue;
1771                 }
1772
1773                 total_read += from_len;
1774         } while ( total_read < read_len );
1775
1776         return total_read;
1777 }
1778 #else
1779 // psnet_send_reliable sends the given data through the given reliable socket.
1780 int psnet_send_reliable( PSNET_SOCKET psocket, ubyte *data, int length, int flags )
1781 {
1782         // don't do anything if the socket is null
1783         if(psocket == NULL){
1784                 return 0;
1785         }
1786         
1787         // send a reliable data packet
1788         return psnet_reliable_send(data,length,(net_addr_t*)psocket);
1789 }
1790
1791 int psnet_get_reliable( PSNET_SOCKET psocket, ubyte *buffer, int max_len, int flags)
1792
1793 {
1794         int best, best_id, i, n, size;
1795
1796         // call the routine to read data out of the socket (which stuffs it into the packet buffers)
1797         psnet_get_socket_data(Reliable_socket,flags);
1798
1799 #ifdef PSNET_BUFFER_OLD_SCHOOL
1800         // now determine which (if any) of the packet buffers we should look at!
1801         best = -1;
1802         n = 0;
1803         best_id = -1;
1804
1805         for (i=0; i <= Largest_packet_index; i++ )      {
1806                 if ( packet_buffers[i].sequence_number > -1 ) {
1807                         n++;
1808                         if ( best == -1 || (packet_buffers[i].sequence_number < best) ) {
1809                                 best = packet_buffers[i].sequence_number;
1810                                 best_id = i;
1811                         }
1812                 }                       
1813         }
1814
1815         //mprintf( (0, "Best id = %d, pn = %d, last_ecb = %x, len=%x, ne = %d\n", best_id, best, last_ecb, lastlen, neterrors ));
1816         //mprintf( (1, "<%d> ", neterrors ));
1817
1818         if ( best_id < 0 ) return 0;
1819
1820         size = packet_buffers[best_id].len;
1821         memcpy( buffer, packet_buffers[best_id].data, size );
1822         memcpy( psocket, &packet_buffers[best_id].from_addr, sizeof(net_addr_t) );
1823         free_packet(best_id);
1824
1825         return size;    
1826 #else
1827         return 0;
1828 #endif
1829 }
1830 #endif
1831
1832 // function which checks the Listen_socket for possibly incoming requests to be connected.
1833 // returns 0 on error or nothing waiting.  1 if we should try to accept
1834 int psnet_rel_check_for_listen(net_addr_t *from_addr)
1835 {
1836         fd_set  rfds;
1837         timeval timeout;
1838         SOCKET  sock;                           // when trying to accept, this is new socket
1839         struct sockaddr_in ip_addr;                             // UDP/TCP socket structure
1840         SOCKLEN_T from_len;
1841         int error;
1842         unsigned long arg;
1843
1844         FD_ZERO(&rfds);
1845         FD_SET( Listen_socket, &rfds );
1846         timeout.tv_sec = 0;
1847         timeout.tv_usec = 0;
1848
1849         if ( select(Listen_socket+1, &rfds, NULL, NULL, &timeout) == SOCKET_ERROR ) {
1850                 nprintf(("Network", "Error %d doing select on listen socket\n", WSAGetLastError() ));
1851                 return 0;
1852         }
1853
1854         // check to see if Listen_socket has something -- if not, return
1855         if ( !FD_ISSET(Listen_socket, &rfds) )
1856                 return INVALID_SOCKET;
1857
1858         sock = INVALID_SOCKET;
1859         switch ( Socket_type ) {
1860         case NET_TCP:
1861                 from_len = sizeof(struct sockaddr_in);
1862                 sock = accept( Listen_socket, (struct sockaddr*)&ip_addr, &from_len );
1863                 from_addr->port = ntohs( ip_addr.sin_port );
1864                 memset(from_addr->addr, 0x00, IP_ADDRESS_LENGTH);
1865                 memcpy(from_addr->addr, &ip_addr.sin_addr.s_addr, 4);
1866                 nprintf(("Network","Accepted TCP connected!!\n"));
1867                 break;
1868         
1869         default:
1870                 Int3();
1871                 break;
1872         }
1873
1874         if ( !psnet_get_ip(sock) ) {
1875                 return INVALID_SOCKET;
1876         }
1877
1878         // make the new socket non-blocking
1879         if(sock != (SOCKET)INVALID_SOCKET){
1880                 arg = TRUE;
1881                 error = ioctlsocket( sock, FIONBIO, &arg );
1882                 if ( error == SOCKET_ERROR ) {
1883                         nprintf(("Network", "Unable to make accepted socket non-blocking -- %d", WSAGetLastError() ));
1884                         return INVALID_SOCKET;
1885                 }
1886         }
1887
1888         return sock;
1889
1890 }
1891
1892 int psnet_rel_get_status(PSNET_SOCKET psocket)
1893 {
1894         int error_code;
1895         SOCKLEN_T error_code_size = sizeof(error_code);
1896         SOCKET socket;
1897
1898         socket = (SOCKET)psocket;
1899
1900         if (socket == (SOCKET)INVALID_SOCKET) {
1901                 return RNF_UNUSED;
1902         }
1903
1904         if ( getsockopt(socket, SOL_SOCKET, SO_ERROR, (char*)&error_code, &error_code_size) ) {
1905                 return RNF_BROKEN;
1906         }
1907
1908         if ( !error_code ) {
1909                 return RNF_CONNECTED;
1910         }
1911
1912         if ( NETCALL_WOULDBLOCK(error_code) ) {
1913                 return RNF_CONNECTING;
1914         }
1915
1916         return RNF_DISCONNECTED;
1917 }
1918
1919 // psnet_get() will call the above function to read data out of the socket.  It will then determine
1920 // which of the buffers we should use and pass to the routine which called us
1921 int psnet_get( void * data, net_addr_t* from_addr, int flags )
1922 {                       
1923         // USE THIS CODE TO TEST NON-BUFFERED SOCKET READS. OUT-OF-ORDER PACKETS DROP TO NEARLY 0
1924         // - Dave
1925         /*
1926         fd_set  rfds;
1927         timeval timeout;
1928         int read_len,from_len;
1929         struct sockaddr_in ip_addr;
1930         FD_ZERO(&rfds);
1931         FD_SET( Unreliable_socket, &rfds );
1932         timeout.tv_sec = 0;
1933         timeout.tv_usec = 0;
1934
1935         if ( select( Unreliable_socket+1, &rfds, NULL, NULL, &timeout) == SOCKET_ERROR ) {
1936                 nprintf(("Network", "Error %d doing a socket select on read\n", WSAGetLastError()));
1937                 return 0;
1938         }
1939
1940         // if the read file descriptor is not set, then bail!
1941         if ( !FD_ISSET(Unreliable_socket, &rfds ) )
1942                 return 0;
1943
1944         // get data off the socket and process
1945         read_len = SOCKET_ERROR;        
1946         from_len = sizeof(struct sockaddr_in);
1947         read_len = recvfrom( Unreliable_socket, (char*)data, MAX_PACKET_SIZE, 0,  (struct sockaddr*)&ip_addr, &from_len );
1948         from_addr->port = ntohs( ip_addr.sin_port );    
1949         memset(from_addr->addr, 0x00, 6);
1950         memcpy(from_addr->addr, &ip_addr.sin_addr.S_un.S_addr, 4);      
1951         return read_len;        
1952         */
1953         
1954         // call the routine to read data out of the socket (which stuffs it into the packet buffers)
1955         psnet_get_socket_data(Unreliable_socket,flags);
1956
1957 #ifdef PSNET_BUFFER_OLD_SCHOOL
1958         int best, best_id, i, n, size;
1959
1960         // now determine which (if any) of the packet buffers we should look at!
1961         best = -1;
1962         n = 0;
1963         best_id = -1;
1964
1965         for (i=0; i <= Largest_packet_index; i++ )      {
1966                 if ( packet_buffers[i].sequence_number > -1 ) {
1967                         n++;
1968                         if ( best == -1 || (packet_buffers[i].sequence_number < best) ) {
1969                                 best = packet_buffers[i].sequence_number;
1970                                 best_id = i;
1971                         }
1972                 }                       
1973         }
1974
1975         //mprintf( (0, "Best id = %d, pn = %d, last_ecb = %x, len=%x, ne = %d\n", best_id, best, last_ecb, lastlen, neterrors ));
1976         //mprintf( (1, "<%d> ", neterrors ));
1977
1978         if ( best_id < 0 ) return 0;
1979
1980         size = packet_buffers[best_id].len;
1981         memcpy( data, packet_buffers[best_id].data, size );
1982         memcpy( from_addr, &packet_buffers[best_id].from_addr, sizeof(net_addr_t) );
1983         free_packet(best_id);
1984
1985         return size;
1986 #else
1987         int buffer_size;
1988
1989         // try and get a free buffer and return its size
1990         if(psnet_buffer_get_next((ubyte*)data,&buffer_size,from_addr)){
1991                 return buffer_size;
1992         }
1993
1994         // return nothing
1995         return 0;
1996 #endif
1997 }
1998
1999
2000
2001 // -------------------------------------------------------------------------------------------------
2002 // psnet_broadcast()
2003 //
2004 //
2005
2006 int psnet_broadcast( net_addr_t * who_to, void * data, int len, int flags )
2007 {
2008         if ( Network_status != NETWORK_STATUS_RUNNING ) {
2009                 nprintf(("Network","Network ==> Socket not inited in psnet_broadcast\n"));
2010                 return 0;
2011         }
2012
2013         if ( !Can_broadcast ) {
2014                 nprintf(("Network", "Cannot broadcast -- returning without doing anything\n"));
2015                 return 0;
2016         }
2017
2018         ubyte broadcast[IP_ADDRESS_LENGTH] = {0xff, 0xff, 0xff, 0xff};
2019
2020         // broadcasting works on a local subnet which is all we really want to do for now anyway.
2021         // we might keep this in as an option for freespace later.
2022         switch ( who_to->type ) {
2023                 case NET_TCP:
2024
2025                         memcpy(who_to->addr, broadcast, IP_ADDRESS_LENGTH);
2026                         psnet_send(who_to, data, len, flags);
2027                         break;
2028         
2029         } // end switch
2030
2031         return 1;
2032 }
2033
2034 // called to clear out the socket of any remaining data
2035
2036 void psnet_flush()
2037 {
2038         ubyte data[MAX_PACKET_SIZE];
2039         net_addr_t from_addr;
2040
2041         while ( psnet_get( data, &from_addr ) > 0 ) ;
2042 }
2043
2044
2045
2046 #ifndef NDEBUG
2047 // function to keep track of bytes read/written on average during the frame
2048 void psnet_calc_socket_stats()
2049 {
2050         if ( psnet_frame_int == -1 )    {
2051                 int i;
2052                 for ( i = 0; i < PSNET_FRAME_FILTER; i++ ) {
2053                         psnet_read_sizes[i] = 0;
2054                         psnet_write_sizes[i] = 0;
2055                 }
2056                 psnet_read_total = 0;
2057                 psnet_write_total = 0;
2058                 psnet_frame_int = 0;
2059         }
2060         psnet_read_total -= psnet_read_sizes[psnet_frame_int];
2061         psnet_write_total -= psnet_write_sizes[psnet_frame_int];
2062
2063         psnet_read_total += psnet_bytes_read_frame;
2064         psnet_write_total += psnet_bytes_written_frame;
2065
2066         psnet_read_sizes[psnet_frame_int] = psnet_bytes_read_frame;
2067         psnet_write_sizes[psnet_frame_int] = psnet_bytes_written_frame;
2068
2069         psnet_frame_int = (psnet_frame_int + 1 ) % PSNET_FRAME_FILTER;
2070
2071         if ( psnet_frame_count > 0 )    {
2072                 if ( psnet_frame_count >= PSNET_FRAME_FILTER )
2073                         Psnet_bytes_read = psnet_read_total / PSNET_FRAME_FILTER;
2074                 else
2075                         Psnet_bytes_read = psnet_read_total / psnet_frame_count;
2076
2077                 if ( psnet_frame_count >= PSNET_FRAME_FILTER )
2078                         Psnet_bytes_written = psnet_write_total / PSNET_FRAME_FILTER;
2079                 else
2080                         Psnet_bytes_written = psnet_write_total / psnet_frame_count;
2081         }
2082
2083         psnet_frame_count++;
2084         psnet_bytes_read_frame = 0;
2085         psnet_bytes_written_frame = 0;
2086 }
2087 #endif
2088
2089 int psnet_is_valid_numeric_ip(char *ip)
2090 {
2091         char *token;
2092         char copy[100];
2093         int val1,val2,val3,val4;
2094
2095         // get the first ip value
2096         SDL_strlcpy(copy, ip, SDL_arraysize(copy));
2097         token = strtok(copy,".");
2098         if(token == NULL){
2099                 return 0;
2100         } else {
2101                 // get the value of the token
2102                 val1 = atoi(token);
2103                 if((val1 < 0) || (val1 > 255)){
2104                         return 0;
2105                 }
2106         }
2107
2108         // second ip value
2109         token = strtok(NULL,".");
2110         if(token == NULL){
2111                 return 0;
2112         } else {
2113                 // get the value of the token
2114                 val2 = atoi(token);
2115                 if((val2 < 0) || (val2 > 255)){
2116                         return 0;
2117                 }
2118         }
2119
2120         // third ip value
2121         token = strtok(NULL,".");
2122         if(token == NULL){
2123                 return 0;
2124         } else {
2125                 // get the value of the token
2126                 val3 = atoi(token);
2127                 if((val3 < 0) || (val3 > 255)){
2128                         return 0;
2129                 }
2130         }
2131
2132         // third ip value
2133         token = strtok(NULL,"");
2134         if(token == NULL){
2135                 return 0;
2136         } else {
2137                 // get the value of the token
2138                 val4 = atoi(token);
2139                 if((val4 < 0) || (val4 > 255)){
2140                         return 0;
2141                 }
2142         }
2143
2144         // make sure he hasn't entered all 0's
2145         if((val1 == 0) && (val2 == 0) && (val3 == 0) && (val4 == 0)){
2146                 return 0;
2147         }
2148
2149         // valid
2150         return 1;
2151 }
2152
2153
2154 // returns true or false if the given string is a valid ip string or not.
2155 // allow port allows us to append the port number on the end of the ip string with
2156 // <addr>:<port#>
2157 // so we must be sure to remove the port number
2158 int psnet_is_valid_ip_string( char *ip_string, int allow_port )
2159 {
2160         in_addr addr;
2161         struct hostent *host_ent;
2162         char str[255], *c;
2163
2164         // our addresses may have ports, so make local copy and remove port number
2165         SDL_assert( strlen(ip_string) < 255 );
2166         SDL_strlcpy(str, ip_string, SDL_arraysize(str));
2167         c = strrchr(str, ':');
2168         if ( c ){
2169                 *c = '\0';
2170         }       
2171
2172         addr.s_addr = inet_addr(ip_string);
2173         if ( addr.s_addr != INADDR_NONE ){
2174                 // make sure the ip string is a valid format string
2175                 if(psnet_is_valid_numeric_ip(ip_string)){
2176                         return 1;
2177                 }
2178         }
2179
2180         // try name resolution
2181         host_ent = gethostbyname( ip_string );
2182         if ( !host_ent ){
2183                 return 0;
2184         }
2185
2186         // valid host entry so return 1;
2187         return 1;
2188 }
2189
2190
2191 // ------------------------------------------------------------------------------------------------------
2192 // PACKET BUFFERING FUNCTIONS
2193 //
2194
2195 #ifndef PSNET_BUFFER_OLD_SCHOOL
2196
2197 // a sequence number of -1 will indicate that this packet is not valid
2198 static network_packet_buffer Psnet_buffers[MAX_PACKET_BUFFERS];
2199 static int Psnet_seq_number = 0;
2200 static int Psnet_lowest_id = 0;
2201 static int Psnet_highest_id = 0;
2202
2203 // initialize the buffering system
2204 void psnet_buffer_init()
2205 {
2206         int idx;
2207         
2208         // blast the buffer clean
2209         memset(Psnet_buffers,0,sizeof(network_packet_buffer) * MAX_PACKET_BUFFERS);
2210         
2211         // set all buffer sequence #'s to -1
2212         for(idx=0;idx<MAX_PACKET_BUFFERS;idx++){
2213                 Psnet_buffers[idx].sequence_number = -1;
2214         }
2215
2216         // initialize the sequence #
2217         Psnet_seq_number = 0;
2218         Psnet_lowest_id = -1;
2219         Psnet_highest_id = -1;
2220 }
2221
2222 // buffer a packet (maintain order!)
2223 void psnet_buffer_packet(ubyte *data, int length, net_addr_t *from)
2224 {
2225         int idx;
2226         int found_buf = 0;
2227         
2228         // find the first empty packet
2229         for(idx=0;idx<MAX_PACKET_BUFFERS;idx++){
2230                 if(Psnet_buffers[idx].sequence_number == -1){
2231                         found_buf = 1;
2232                         break;
2233                 }
2234         }
2235
2236         // if we didn't find the buffer, report an overrun
2237         if(!found_buf){
2238                 nprintf(("Network","WARNING - Buffer overrun in psnet\n"));
2239         } else {
2240                 // copy in the data
2241                 memcpy(Psnet_buffers[idx].data,data,length);
2242                 Psnet_buffers[idx].len = length;
2243                 memcpy(&Psnet_buffers[idx].from_addr,from,sizeof(net_addr_t));
2244                 Psnet_buffers[idx].sequence_number = Psnet_seq_number;
2245                 
2246                 // keep track of the highest id#
2247                 Psnet_highest_id = Psnet_seq_number++;
2248
2249                 // set the lowest id# for the first time
2250                 if(Psnet_lowest_id == -1){
2251                         Psnet_lowest_id = Psnet_highest_id;
2252                 }
2253         }
2254 }
2255
2256 // get the index of the next packet in order!
2257 int psnet_buffer_get_next(ubyte *data, int *length, net_addr_t *from)
2258 {       
2259         int idx;
2260         int found_buf = 0;
2261
2262         // if there are no buffers, do nothing
2263         if((Psnet_lowest_id == -1) || (Psnet_lowest_id > Psnet_highest_id)){
2264                 return 0;
2265         }
2266
2267         // search until we find the lowest packet index id#
2268         for(idx=0;idx<MAX_PACKET_BUFFERS;idx++){
2269                 // if we found the buffer
2270                 if(Psnet_buffers[idx].sequence_number == Psnet_lowest_id){
2271                         found_buf = 1;
2272                         break;
2273                 }
2274         }
2275
2276         // at this point, we should _always_ have found the buffer
2277         SDL_assert(found_buf);
2278         
2279         // copy out the buffer data
2280         memcpy(data,Psnet_buffers[idx].data,Psnet_buffers[idx].len);
2281         *length = Psnet_buffers[idx].len;
2282         memcpy(from,&Psnet_buffers[idx].from_addr,sizeof(net_addr_t));
2283
2284         // now we need to cleanup the packet list
2285
2286         // mark the buffer as free
2287         Psnet_buffers[idx].sequence_number = -1;
2288         Psnet_lowest_id++;
2289
2290         return 1;
2291 }
2292
2293 #else 
2294
2295 // initialize the buffering system
2296 void psnet_buffer_init() {}
2297
2298 // buffer a packet (maintain order!)
2299 void psnet_buffer_packet(ubyte *data, int length) {}
2300
2301 // get the index of the next packet in order!
2302 int psnet_buffer_get_next() {   return -1; }
2303
2304 #endif
2305
2306 // ------------------------------------------------------------------------------------------------------
2307 // RELIABLE UDP FUNCTIONS
2308 //
2309
2310 // verbose debug output
2311 #define PSNET_RELIABLE_VERBOSE
2312
2313 // overall buffer space allocated to the buffers
2314 #define PSNET_RELIABLE_MAX_OUT_BUFFER_SIZE                                                      (1<<18)                 // 256k
2315 #define PSNET_RELIABLE_MAX_IN_BUFFER_SIZE                                                               (1<<12)                 // 4k
2316
2317 // outgoing reliable packets
2318 typedef struct reliable_packet_out {
2319         ubyte                   data[MAX_PACKET_SIZE];                                  // data in the original packet
2320         ushort          packet_size;                                                            // size of the original packet
2321         ushort          player_flags;                                                           // bitflags indexing (1<<N) into the Psnet_reliable_addr[N] array
2322         ushort          player_acks;                                                            // bitflags indexing (1<<N) into the Psnet_reliable_addr[N] array
2323         int                     player_stamps[MAX_PLAYERS];                     // timeouts for each player
2324         ubyte                   num_resends[MAX_PLAYERS];                               // # of times we've resent to a given player
2325         ushort          out_id;                                                                         // identifier of the packet
2326         fix                     age;                                                                                    // how old this packet is
2327 } reliable_packet_out;
2328
2329 // incoming reliable packets
2330 typedef struct reliable_packet_in {
2331         ushort          in_id;                                                                          // identifier of the received packet
2332         fix                     age;                                                                                    // when we received the packet
2333 } reliable_packet_in;
2334
2335 // # of outgoing and incoming buffers we'll allocate
2336 #define PSNET_RELIABLE_NUM_OUT_BUFFERS                                  (int)(PSNET_RELIABLE_MAX_OUT_BUFFER_SIZE / sizeof(reliable_packet_out))
2337 #define PSNET_RELIABLE_NUM_IN_BUFFERS                                   (int)(PSNET_RELIABLE_MAX_IN_BUFFER_SIZE / sizeof(reliable_packet_in))
2338
2339 // timeout to be used for the packets
2340 #define PSNET_RELIABLE_TIMEOUT                                                  1500                            // in ms
2341
2342 // # of repeats to use
2343 #define PSNET_RELIABLE_REPEAT                                                           8                                       // repeat this many times max
2344
2345 // invalid id#
2346 #define PSNET_RELIABLE_INVALID                                                  0               
2347
2348 // ack code
2349 #define PSNET_RELIABLE_ACK                                                                      0xffff
2350
2351 // the outgoing and incoming buffers themselves
2352 reliable_packet_out *Psnet_reliable_out[PSNET_RELIABLE_NUM_OUT_BUFFERS];
2353 reliable_packet_in *Psnet_reliable_in[PSNET_RELIABLE_NUM_IN_BUFFERS];
2354
2355 // psnet reliable address list
2356 net_addr_t Psnet_reliable_addr[MAX_PLAYERS];                    // address of registered "reliable" addrs
2357 int Psnet_reliable_addr_flags;                                                  // bitflags indicating which of the above are valid
2358
2359 // my local identifier # (will only use lower 12 bits)
2360 ushort Psnet_reliable_local_id = 0x1;
2361
2362 // is the reliable system initialized
2363 int Psnet_reliable_inited = 0;
2364
2365 // # of times a packet has not been delivered
2366 int Psnet_reliable_fail_count = 0;
2367
2368 // # of times packets have had to be resent
2369 int Psnet_reliable_resend_count = 0;
2370
2371 // # of times we've run out of packets and had to overwrite existing ones
2372 int Psnet_reliable_overwrite_count = 0;
2373
2374 // forward declarations ------------------------------------------------------
2375
2376 // free up all used buffers 
2377 void psnet_reliable_free_all_buffers();
2378
2379 // get the index of the passed address or -1 if it doesn't exist
2380 int psnet_reliable_addr_index(net_addr_t *addr);
2381
2382 // get the index into the address array from the passed bitflag
2383 int psnet_reliable_index_addr(int flags);
2384
2385 // kill all outgoing packets belonging to the passed index
2386 void psnet_reliable_kill_outgoing(int index);
2387
2388 // generate a unique id #, given the passed in value and the address it came from, return PSNET_RELIABLE_INVALID
2389 // upper 12 bytes should be valid # and the lower 4 should be free for this function to fill in
2390 ushort psnet_reliable_get_unique_id(ushort id_num,net_addr_t *from);
2391
2392 // get the upper 12 bit version of my id# and increment the original
2393 ushort psnet_reliable_get_next_id();
2394
2395 // get the index of a free outgoing relible packet buffer, killing the oldest if necessary
2396 int psnet_reliable_get_free_outgoing();
2397
2398 // get the index of a free incoming relible packet buffer, killing the oldest if necessary
2399 int psnet_reliable_get_free_incoming();
2400
2401 // actually send the data contained with the reliable_packet_out
2402 int psnet_reliable_send_packet(reliable_packet_out *out,int force_index = 0);
2403
2404 // evaluate the status of a reliable packet - and free it up if the thing is _done_
2405 void psnet_reliable_evaluate_status(reliable_packet_out *out);
2406
2407 // determine if the passed id# exists in the in-packet list, return the instance where it exists, or -1 if it doesn't
2408 int psnet_reliable_find_in_id(ushort id_num);
2409
2410 // determine if the passed id# exists in the out-packet list, return the instance where it exists, or -1 if it doesn't
2411 int psnet_reliable_find_out_id(ushort id_num);
2412
2413 // send an ack to the specified address
2414 void psnet_reliable_send_ack(net_addr_t *addr,ushort id_num);
2415
2416
2417 // extern functions -----------------------------------------------------------
2418
2419 // initialize the psnet reliable system (return 0 on fail, 1 on success)
2420 int psnet_reliable_init()
2421 {
2422         int idx;
2423
2424         // if the system is already inited, do nothing
2425         if(Psnet_reliable_inited){
2426                 return 1;
2427         }
2428         
2429 #ifdef PSNET_RELIABLE_VERBOSE
2430         nprintf(("Network","PSNET RELIABLE SIZES : \n   OUT BUFFER SIZE : %d\n   OUT BUFFER COUNT %d\n   IN BUFFER SIZE %d\n   IN BUFFER COUNT %d\n",
2431                                 PSNET_RELIABLE_MAX_OUT_BUFFER_SIZE,PSNET_RELIABLE_NUM_OUT_BUFFERS,PSNET_RELIABLE_MAX_IN_BUFFER_SIZE,PSNET_RELIABLE_NUM_IN_BUFFERS));
2432 #endif
2433
2434         // null all buffers
2435         for(idx=0;idx<PSNET_RELIABLE_NUM_OUT_BUFFERS;idx++){
2436                 Psnet_reliable_out[idx] = NULL;
2437         }
2438         for(idx=0;idx<PSNET_RELIABLE_NUM_IN_BUFFERS;idx++){
2439                 Psnet_reliable_in[idx] = NULL;
2440         }
2441
2442         // initialize all outgoing buffers
2443         for(idx=0;idx<PSNET_RELIABLE_NUM_OUT_BUFFERS;idx++){
2444                 Psnet_reliable_out[idx] = NULL;
2445                 Psnet_reliable_out[idx] = (reliable_packet_out*)malloc(sizeof(reliable_packet_out));
2446
2447                 // if we failed to allocate the buffer, return failure
2448                 if(Psnet_reliable_out[idx] == NULL){
2449                         psnet_reliable_free_all_buffers();
2450                         return 0;
2451                 }
2452                 memset(Psnet_reliable_out[idx],0,sizeof(reliable_packet_out));
2453         }
2454
2455         // initialize all incoming buffers
2456         for(idx=0;idx<PSNET_RELIABLE_NUM_IN_BUFFERS;idx++){
2457                 Psnet_reliable_in[idx] = NULL;
2458                 Psnet_reliable_in[idx] = (reliable_packet_in*)malloc(sizeof(reliable_packet_in));
2459
2460                 // if we failed to allocate the buffer, return failure
2461                 if(Psnet_reliable_in[idx] == NULL){
2462                         psnet_reliable_free_all_buffers();
2463                         return 0;
2464                 }
2465                 memset(Psnet_reliable_in[idx],0,sizeof(reliable_packet_in));
2466         }
2467
2468         // blast the reliable address list free
2469         memset(Psnet_reliable_addr,0,sizeof(net_addr_t) * MAX_PLAYERS);
2470         Psnet_reliable_addr_flags = 0;
2471
2472         // set the system to be initialized
2473         Psnet_reliable_inited = 1;
2474
2475         // initialize my local id #
2476         Psnet_reliable_local_id = 0x1;
2477
2478         // initialize the packet delivery fail count
2479         Psnet_reliable_fail_count = 0;
2480
2481         // intialize the packet necessary resend count
2482         Psnet_reliable_resend_count = 0;
2483
2484         // initialize # of times we've run out of packets and had to overwrite existing ones
2485         Psnet_reliable_overwrite_count = 0;
2486
2487         // return success
2488         return 1;
2489 }
2490
2491 // shutdown the reliable system (free up buffers, etc)
2492 void psnet_reliable_close()
2493 {
2494         // if the system is not initialized, don't do anything
2495         if(!Psnet_reliable_inited){
2496                 return;
2497         }
2498
2499         // free up all buffers
2500         psnet_reliable_free_all_buffers();
2501
2502         // blast all addresses clean
2503         memset(Psnet_reliable_addr,0,sizeof(net_addr_t) * MAX_PLAYERS);
2504         Psnet_reliable_addr_flags = 0;
2505
2506         // set the system as being uninitialized
2507         Psnet_reliable_inited = 0;
2508 }
2509
2510 // notify the reliable system of a new address at index N
2511 void psnet_reliable_notify_new_addr(net_addr_t *addr,int index)
2512 {
2513         // copy in the address
2514         memcpy(&Psnet_reliable_addr[index],addr,sizeof(net_addr_t));
2515
2516         // set the bit indicating its validity
2517         Psnet_reliable_addr_flags |= (1<<index);
2518 }
2519
2520 // notify the reliable system of a drop at index N
2521 void psnet_reliable_notify_drop_addr(net_addr_t *addr)
2522 {
2523         int index;
2524
2525         // do a lookup for the address
2526         index = psnet_reliable_addr_index(addr);
2527         if(index != -1){                
2528                 // clear out all packets belonging exclusively to this address
2529                 psnet_reliable_kill_outgoing(index);
2530
2531                 // clear the address and its existence bit
2532                 memset(&Psnet_reliable_addr[index],0,sizeof(net_addr_t));
2533                 Psnet_reliable_addr_flags &= ~(1<<index);
2534         }
2535 }
2536
2537 // send a reliable data packet
2538 int psnet_reliable_send(ubyte *data,int packet_size,net_addr_t *addr)
2539 {
2540         int free_buffer;
2541         int to_index;
2542         reliable_packet_out *p;
2543         
2544         // if the system is not initialized, don't do anything
2545         if(!Psnet_reliable_inited){
2546                 return 0;
2547         }
2548
2549         // try and find a guy to send to 
2550         to_index = -1;
2551         to_index = psnet_reliable_addr_index(addr);
2552         if(to_index == -1){
2553                 nprintf(("Network","PSNET RELIABLE : could not find player for outgoing packet!\n"));
2554                 return 0;
2555         }
2556
2557         // attempt to get a free buffer
2558         free_buffer = -1;
2559         free_buffer = psnet_reliable_get_free_outgoing();
2560         if(free_buffer == -1){
2561                 Int3();                                         // should never happen - we should always overwrite the oldest buffer
2562         }
2563
2564         // setup the data for the outgoing packet
2565         p = Psnet_reliable_out[free_buffer];
2566         memcpy(p->data,data,packet_size);
2567         p->packet_size = (ushort)packet_size;
2568         p->player_flags |= (1<<to_index);
2569         memset(p->player_stamps,0xf,sizeof(int) * MAX_PLAYERS);
2570         p->player_stamps[to_index] = timestamp(PSNET_RELIABLE_TIMEOUT);
2571         p->out_id = psnet_reliable_get_next_id();
2572         p->age = timer_get_fixed_seconds();
2573
2574         // send the packet
2575         return psnet_reliable_send_packet(p);
2576 }
2577
2578 // process frame for all reliable stuff (call once per frame)
2579 void psnet_reliable_process()
2580 {
2581         int idx,s_idx;
2582         reliable_packet_out *p;
2583         
2584         // if the system is not initialized, don't do anything
2585         if(!Psnet_reliable_inited){
2586                 return;
2587         }
2588
2589         // go through all active packets
2590         for(idx=0;idx<PSNET_RELIABLE_NUM_OUT_BUFFERS;idx++){
2591                 // if the packet is active
2592                 if(Psnet_reliable_out[idx]->out_id != PSNET_RELIABLE_INVALID){
2593                         p = Psnet_reliable_out[idx];
2594
2595                         // loop through all active players and see if we need to resend
2596                         for(s_idx=0;s_idx<MAX_PLAYERS;s_idx++){
2597                                 // if the packet is active for this player and he hasn't acked
2598                                 if(p->player_flags & (1<<s_idx) && !(p->player_acks & (1<<s_idx))){
2599                                         // if the timestamp has elapsed
2600                                         if((p->player_stamps[s_idx] != -1) && timestamp_elapsed(p->player_stamps[s_idx])){
2601                                                 // if we are at max resends, bomb!
2602                                                 if(p->num_resends[s_idx] >= PSNET_RELIABLE_REPEAT){
2603 #ifdef PSNET_RELIABLE_VERBOSE
2604                                                         nprintf(("Network","PSNET RELIABLE : packet failed to be delivered (%d retries) !!\n",PSNET_RELIABLE_REPEAT));
2605 #endif
2606                                                         p->player_flags &= ~(1<<s_idx);
2607
2608                                                         // increment the fail count
2609                                                         Psnet_reliable_fail_count++;
2610                                                 }
2611                                                 // otherwise resend the packet
2612                                                 else {
2613                                                         // actually send the data contained with the reliable_packet_out
2614                                                         psnet_reliable_send_packet(p,s_idx);
2615
2616                                                         // increment the resend count
2617                                                         Psnet_reliable_resend_count++;
2618
2619 #ifdef PSNET_RELIABLE_VERBOSE
2620                                                         nprintf(("Network","PSNET RELIABLE : resending packet\n"));
2621 #endif
2622                                                 }
2623                                         }
2624                                 }
2625                         }
2626
2627                         // evaluate if this packet has completed
2628                         psnet_reliable_evaluate_status(p);
2629                 }
2630         }
2631 }
2632
2633 // determine if the passed in reliable data should be processed, and sends an ack if necessary
2634 // return # of bytes which should be stripped off the data (reliable data header)
2635 int psnet_reliable_should_process(net_addr_t *addr,ubyte *data,int packet_size)
2636 {
2637         ushort id_num,unique_id;
2638         int packet_index;
2639         int player_index;
2640         int free_index;
2641         reliable_packet_in *p;
2642
2643         // get the reliable packet id #
2644         memcpy(&id_num,data,sizeof(ushort));
2645
2646         // if the id# is an ack, get the id# do a lookup
2647         if(id_num == PSNET_RELIABLE_ACK){
2648 #ifdef PSNET_RELIABLE_VERBOSE
2649                 nprintf(("Network","PSNET RELIABLE : ACK 1\n"));
2650 #endif
2651
2652                 // get the id#
2653                 memcpy(&id_num,data+2,sizeof(ushort));
2654
2655                 // get the packet index
2656                 // unique_id = psnet_reliable_get_unique_id(id_num,addr);
2657                 unique_id = id_num;
2658                 packet_index = psnet_reliable_find_out_id(unique_id);
2659                 player_index = psnet_reliable_addr_index(addr);                 
2660                 if((packet_index != -1) && (player_index != -1)){
2661 #ifdef PSNET_RELIABLE_VERBOSE
2662                         nprintf(("Network","PSNET RELIABLE : ACK 2\n"));
2663 #endif
2664
2665                         Psnet_reliable_out[packet_index]->player_acks |= (1<<player_index);
2666                         
2667                         // check to see if this packet is _done_
2668                         psnet_reliable_evaluate_status(Psnet_reliable_out[packet_index]);                       
2669                 }
2670
2671                 // return 4 bytes processed
2672                 return 4;
2673         }
2674
2675         // otherwise - see if this is a new packet
2676         packet_index = psnet_reliable_find_in_id(id_num);
2677         if(packet_index == -1){
2678                 // get a free index
2679                 free_index = -1;
2680                 free_index = psnet_reliable_get_free_incoming();
2681                 if(free_index == -1){
2682                         Int3();
2683                 }
2684
2685                 // setup the incoming packet
2686                 p = Psnet_reliable_in[free_index];
2687                 p->age = timer_get_fixed_seconds();
2688                 p->in_id = psnet_reliable_get_unique_id(id_num,addr);
2689
2690                 // send an ack
2691                 psnet_reliable_send_ack(addr,id_num);
2692
2693                 // return 2 bytes processed
2694                 return 2;
2695         }
2696         // send another ack for good measure
2697         else {
2698                 psnet_reliable_send_ack(addr,id_num);
2699         }
2700
2701         return 0;       
2702 }
2703
2704 // forward definitions --------------------------------------------
2705
2706 // free up all used buffers
2707 void psnet_reliable_free_all_buffers()
2708 {
2709         int idx;
2710
2711         // free all outgoing buffers
2712         for(idx=0;idx<PSNET_RELIABLE_NUM_OUT_BUFFERS;idx++){
2713                 // if the buffer is not null, free it
2714                 if(Psnet_reliable_out[idx] != NULL){
2715                         free(Psnet_reliable_out[idx]);
2716                         Psnet_reliable_out[idx] = NULL;
2717                 }
2718         }
2719
2720         // free all incoming buffers
2721         for(idx=0;idx<PSNET_RELIABLE_NUM_IN_BUFFERS;idx++){
2722                 // if the buffer is not null, free it
2723                 if(Psnet_reliable_in[idx] != NULL){
2724                         free(Psnet_reliable_in[idx]);
2725                         Psnet_reliable_in[idx] = NULL;
2726                 }
2727         }
2728 }
2729
2730 // get the index of the passed address or -1 if it doesn't exist
2731 int psnet_reliable_addr_index(net_addr_t *addr)
2732 {
2733         int idx;
2734
2735         // look through all valid addresses
2736         for(idx=0;idx<MAX_PLAYERS;idx++){
2737                 if((Psnet_reliable_addr_flags & (1<<idx)) && psnet_same(addr,&Psnet_reliable_addr[idx])){
2738                         return idx;
2739                 }
2740         }
2741
2742         // couldn't find the address
2743         return -1;
2744 }
2745
2746 // get the index into the address array from the passed bitflag
2747 int psnet_reliable_index_addr(int flags)
2748 {
2749         int idx;
2750
2751         // look through all the bits in the flags
2752         for(idx=0;idx<MAX_PLAYERS;idx++){
2753                 if(flags & (1<<idx)){
2754                         return idx;
2755                 }
2756         }
2757
2758         // couldn't find any
2759         return -1;
2760 }
2761
2762 // kill all outgoing packets belonging to the passed index
2763 void psnet_reliable_kill_outgoing(int index)
2764 {
2765         int idx;
2766
2767         // go through all buffers
2768         for(idx=0;idx<PSNET_RELIABLE_NUM_OUT_BUFFERS;idx++){
2769                 if(Psnet_reliable_out[idx]->out_id != PSNET_RELIABLE_INVALID){
2770                         // if it is exclusively his, kill the whole packet
2771                         if(Psnet_reliable_out[idx]->player_flags == (1<<index)){
2772                                 memset(Psnet_reliable_out[idx],0,sizeof(reliable_packet_out));
2773                                 continue;
2774                         } 
2775                         // if it belongs to him and other players, kill his entry
2776                         else if(Psnet_reliable_out[idx]->player_flags & (1<<index)){
2777                                 Psnet_reliable_out[idx]->player_flags &= ~(1<<index);
2778                                 Psnet_reliable_out[idx]->num_resends[index] = 0;
2779                         }
2780                 }
2781         }
2782 }
2783
2784 // generate a unique id #, given the passed in value and the address it came from, return PSNET_RELIABLE_INVALID
2785 // upper 12 bytes should be valid # and the lower 4 should be free for this function to fill in
2786 ushort psnet_reliable_get_unique_id(ushort id_num,net_addr_t *from)
2787 {
2788         int idx;
2789         ushort cast;
2790         
2791         // if the lower 4 bits are not clear, we've got a problem
2792         if(id_num & 0xf){
2793                 Int3();
2794         }
2795
2796         // lookup through the Psnet_reliable_addr[] list and try and find the index
2797         for(idx=0;idx<MAX_PLAYERS;idx++){
2798                 if((idx == 1) /*(Psnet_reliable_addr_flags & (1<<idx)) && (psnet_same(from,&Psnet_reliable_addr[idx]))*/){
2799                         // fill in the lower 4 bits
2800                         cast = (ushort)idx;
2801                         id_num |= (cast & 0xf);
2802                         return id_num;
2803                 }
2804         }
2805
2806         // couldn't find an id#
2807         return PSNET_RELIABLE_INVALID;
2808 }
2809
2810 // get the upper 12 bit version of my id# and increment the original
2811 ushort psnet_reliable_get_next_id()
2812 {
2813         ushort id_num = Psnet_reliable_local_id;
2814
2815         // clear out the upper 4 bits
2816         id_num &= 0x0fff;
2817
2818         // shift 4 bits to the left
2819         id_num <<= 4;
2820
2821         // increment the local id #
2822         if(Psnet_reliable_local_id == 0x0fff){
2823                 Psnet_reliable_local_id = 0x1;
2824         } else {
2825                 Psnet_reliable_local_id++;
2826         }
2827
2828         // return the shifted value
2829         return id_num;
2830 }
2831
2832 // get the index of a free outgoing relible packet buffer, killing the oldest if necessary
2833 int psnet_reliable_get_free_outgoing()
2834 {
2835         fix oldest = -1;
2836         int oldest_index = -1;
2837         int idx;
2838
2839         // search through all buffers
2840         for(idx=0;idx<PSNET_RELIABLE_NUM_OUT_BUFFERS;idx++){
2841                 if(Psnet_reliable_out[idx]->out_id == PSNET_RELIABLE_INVALID){
2842                         return idx;
2843                 }
2844
2845                 // keep track of the oldest packet
2846                 if((oldest_index == -1) || (Psnet_reliable_out[idx]->age < oldest)){
2847                         oldest_index = idx;
2848                         oldest = Psnet_reliable_out[idx]->age;
2849                 }
2850         }
2851
2852         // if we got here, all of our buffers are full, so we should kill the oldest one
2853         memset(Psnet_reliable_out[oldest_index],0,sizeof(reliable_packet_out));
2854         Psnet_reliable_overwrite_count = 0;
2855 #ifdef PSNET_RELIABLE_VERBOSE
2856         nprintf(("Network","PSNET RELIABLE : overwriting old send buffer\n"));
2857 #endif
2858         return oldest_index;
2859 }
2860
2861 // get the index of a free incoming relible packet buffer, killing the oldest if necessary
2862 int psnet_reliable_get_free_incoming()
2863 {
2864         fix oldest = -1;
2865         int oldest_index = -1;
2866         int idx;
2867
2868         // search through all buffers
2869         for(idx=0;idx<PSNET_RELIABLE_NUM_IN_BUFFERS;idx++){
2870                 if(Psnet_reliable_in[idx]->in_id == PSNET_RELIABLE_INVALID){
2871                         return idx;
2872                 }
2873
2874                 // keep track of the oldest packet
2875                 if((oldest_index == -1) || (Psnet_reliable_in[idx]->age < oldest)){
2876                         oldest_index = idx;
2877                         oldest = Psnet_reliable_in[idx]->age;
2878                 }
2879         }
2880
2881         // if we got here, all of our buffers are full, so we should kill the oldest one
2882         memset(Psnet_reliable_in[oldest_index],0,sizeof(reliable_packet_in));   
2883 #ifdef PSNET_RELIABLE_VERBOSE
2884         nprintf(("Network","PSNET RELIABLE : overwriting old recv buffer\n"));
2885 #endif
2886         return oldest_index;
2887 }
2888
2889 // actually send the data contained with the reliable_packet_out
2890 int psnet_reliable_send_packet(reliable_packet_out *out,int force_index)
2891 {       
2892         ubyte data[MAX_PACKET_SIZE];    
2893         int idx,bytes_sent;
2894         int packet_size = 2 + out->packet_size;
2895
2896         // stick the identifier on the front of the packet
2897         memcpy(data,&out->out_id,sizeof(ushort));
2898
2899         // copy in the actual data
2900         memcpy(data+2,out->data,out->packet_size);
2901
2902         // send the packet and update the timestamp for all players
2903         
2904         // send to one specified player in the packet
2905         bytes_sent = 0;
2906         if(force_index != 0){
2907                 if(out->player_flags & (1<<force_index) && !(out->player_acks & (1<<force_index))){
2908                         bytes_sent = psnet_send(&Psnet_reliable_addr[force_index],data,packet_size,PSNET_FLAG_RAW,1);                   
2909                         out->player_stamps[force_index] = timestamp(PSNET_RELIABLE_TIMEOUT);
2910                         out->num_resends[force_index]++;
2911                 }
2912         }
2913         // send to all players contained in the packet
2914         else {
2915                 for(idx=0;idx<MAX_PLAYERS;idx++){
2916                         // if this guy is flagged and he exists and he hasn't already acked
2917                         if(out->player_flags & (1<<idx) && (Psnet_reliable_addr_flags & (1<<idx)) && !(out->player_acks & (1<<idx))){
2918                                 bytes_sent = psnet_send(&Psnet_reliable_addr[idx],data,packet_size,PSNET_FLAG_RAW,1);                           
2919                                 out->player_stamps[idx] = timestamp(PSNET_RELIABLE_TIMEOUT);
2920                                 out->num_resends[idx]++;
2921                         }
2922                 }
2923         }
2924
2925         // return success
2926         return bytes_sent;
2927 }
2928
2929 // evaluate the status of a reliable packet - and free it up if the thing is _done_
2930 void psnet_reliable_evaluate_status(reliable_packet_out *out)
2931 {
2932         int idx,ok;
2933
2934         // check to see if all players have acked or failed miserably
2935         ok = 1;
2936         for(idx=0;idx<MAX_PLAYERS;idx++){
2937                 // if the packet is active for this guy but he has not acked yet
2938                 if((out->player_flags & (1<<idx)) && !(out->player_acks & (1<<idx))){
2939                         ok = 0;
2940                         break;
2941                 }
2942         }
2943
2944         // if its ok to annihilate this packet, do so
2945         if(ok){
2946                 memset(out,0,sizeof(reliable_packet_out));
2947         }
2948 }
2949
2950 // determine if the passed id# exists in the in-packet list, return the instance where it exists, or -1 if it doesn't
2951 int psnet_reliable_find_in_id(ushort id_num)
2952 {
2953         int idx;
2954
2955         // if the id is 0, its invalid
2956         if(id_num == PSNET_RELIABLE_INVALID){
2957                 return -1;
2958         }
2959
2960         // look through all in packets
2961         for(idx=0;idx<PSNET_RELIABLE_NUM_IN_BUFFERS;idx++){
2962                 if(id_num == Psnet_reliable_in[idx]->in_id){
2963                         return idx;
2964                 }
2965         }
2966
2967         // couldn't find it 
2968         return -1;
2969 }
2970
2971 // determine if the passed id# exists in the out-packet list, return the instance where it exists, or -1 if it doesn't
2972 int psnet_reliable_find_out_id(ushort id_num)
2973 {
2974         int idx;
2975
2976         // if the id is 0, its invalid
2977         if(id_num == PSNET_RELIABLE_INVALID){
2978                 return -1;
2979         }
2980
2981         // look through all in packets
2982         for(idx=0;idx<PSNET_RELIABLE_NUM_OUT_BUFFERS;idx++){
2983                 if(id_num == Psnet_reliable_out[idx]->out_id){
2984                         return idx;
2985                 }
2986         }
2987
2988         // couldn't find it 
2989         return -1;
2990 }
2991
2992 // send an ack to the specified address
2993 void psnet_reliable_send_ack(net_addr_t *addr,ushort id_num)
2994 {
2995         ubyte data[10];
2996         ushort val;
2997
2998         // add in the ack
2999         val = PSNET_RELIABLE_ACK;
3000         memcpy(data,&val,sizeof(ushort));
3001
3002         // add in the id#
3003         memcpy(data+2,&id_num,sizeof(ushort));
3004
3005         // send the data
3006         psnet_send(addr,data,4,PSNET_FLAG_RAW,Reliable_socket);
3007 }
3008
3009 // wrappers around select() and recvfrom() for lagging/losing data, and for sorting through different packet types
3010 int RECVFROM(SOCKET s, char * buf, int len, int flags, sockaddr *from, int *fromlen, int psnet_type)
3011 {
3012         net_addr_t addr;
3013         int ret;
3014         int ret_len;
3015
3016         // if we have no buffer! The user should have made sure this wasn't the case by calling SELECT()
3017         ret = psnet_buffer_get_next((ubyte*)buf, &ret_len, &addr);
3018         if(!ret){
3019                 Int3();
3020                 return -1;
3021         }
3022
3023         // otherwise, stuff the outgoing data
3024         ((struct sockaddr_in*)from)->sin_port = htons(addr.port);
3025         memcpy(&((struct sockaddr_in*)from)->sin_addr.s_addr, addr.addr, 4);
3026         ((struct sockaddr_in*)from)->sin_family = AF_INET;
3027         *fromlen = sizeof(struct sockaddr_in);
3028
3029         // return bytes read
3030         return ret_len;
3031 }
3032
3033 int SELECT(int nfds, fd_set *readfds, fd_set *writefds, fd_set*exceptfds, struct timeval* timeout, int psnet_type)
3034 {
3035         // if this is a check for writability, just return the select
3036         if(writefds != NULL){
3037                 return select(nfds, readfds, writefds, exceptfds, timeout);
3038         }
3039
3040         // do we have any buffers in here?
3041         if((Psnet_lowest_id == -1) || (Psnet_lowest_id > Psnet_highest_id)){
3042                 return 0;
3043         }
3044
3045         // yo
3046         return 1;
3047 }
3048
3049 // wrappers around sendto to sorting through different packet types
3050 int SENDTO(SOCKET s, char * buf, int len, int flags, sockaddr * to, int tolen, int psnet_type)
3051 {
3052         return sendto(s, buf, len, flags, (struct sockaddr *)to, tolen);
3053 }
3054
3055 // call this once per frame to read everything off of our socket
3056 void PSNET_TOP_LAYER_PROCESS()
3057 {
3058         psnet_get_socket_data(Unreliable_socket);
3059 }
3060
3061 #endif  // #ifndef PSNET2