]> icculus.org git repositories - taylor/freespace2.git/blob - src/network/psnet2.cpp
make PXO pinfo popup work in an async manner
[taylor/freespace2.git] / src / network / psnet2.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/Psnet2.cpp $
11  * $Revision$
12  * $Date$
13  * $Author$
14  *
15  * C file containing application level network-interface.
16  *
17  * $Log$
18  * Revision 1.14  2005/10/02 09:30:10  taylor
19  * sync up rest of big-endian network changes.  it should at least be as good as what's in FS2_Open now, only better :)
20  *
21  * Revision 1.13  2005/10/01 22:01:28  taylor
22  * some cleanup of earlier big-endian changes
23  *
24  * Revision 1.12  2004/07/04 11:39:06  taylor
25  * fix missing debrief text, crash on exit, path separator's, warning fixes, no GR_SOFT
26  *
27  * Revision 1.11  2004/06/11 01:52:15  tigital
28  * byte-swapping changes for bigendian systems
29  *
30  * Revision 1.10  2003/08/03 16:10:30  taylor
31  * cleanup; compile warning fixes
32  *
33  * Revision 1.9  2002/07/27 19:52:54  relnev
34  * add missing structure packing
35  *
36  * Revision 1.8  2002/06/09 04:41:24  relnev
37  * added copyright header
38  *
39  * Revision 1.7  2002/06/02 05:31:17  relnev
40  * unstub
41  *
42  * Revision 1.6  2002/06/02 02:29:39  relnev
43  * net fixes
44  *
45  * Revision 1.5  2002/05/27 04:04:43  relnev
46  * 155 undefined references left
47  *
48  * Revision 1.4  2002/05/26 21:27:53  theoddone33
49  * More progress (I hate psnet2)
50  *
51  * Revision 1.3  2002/05/26 20:49:54  theoddone33
52  * More progress
53  *
54  * Revision 1.2  2002/05/07 03:16:48  theoddone33
55  * The Great Newline Fix
56  *
57  * Revision 1.1.1.1  2002/05/03 03:28:10  root
58  * Initial import.
59  *
60  * 
61  * 25    9/14/99 2:21p Dave
62  * Fixed observer mode joining and ingame stuff.
63  * 
64  * 24    9/10/99 9:44p Dave
65  * Bumped version # up. Make server reliable connects not have such a huge
66  * timeout. 
67  * 
68  * 23    9/07/99 4:01p Dave
69  * Fixed up a string.tbl paroblem (self destruct message). Make sure IPX
70  * does everything properly (setting up address when binding). Remove
71  * black rectangle background from UI_INPUTBOX.
72  * 
73  * 22    8/26/99 8:51p Dave
74  * Gave multiplayer TvT messaging a heavy dose of sanity. Cheat codes.
75  * 
76  * 21    8/16/99 4:06p Dave
77  * Big honking checkin.
78  * 
79  * 20    7/26/99 5:50p Dave
80  * Revised ingame join. Better? We'll see....
81  * 
82  * 19    7/20/99 1:49p Dave
83  * Peter Drake build. Fixed some release build warnings.
84  * 
85  * 18    7/15/99 9:20a Andsager
86  * FS2_DEMO initial checkin
87  * 
88  * 17    7/03/99 4:08p Dave
89  * Fixed wss_slots size issues. Fixed potentially nasty bug in low level
90  * reliable code.
91  * 
92  * 16    6/25/99 5:02p Jasenw
93  * Removed old debug code.
94  * 
95  * 15    6/07/99 9:51p Dave
96  * Consolidated all multiplayer ports into one.
97  * 
98  * 14    4/30/99 12:18p Dave
99  * Several minor bug fixes.
100  * 
101  * 13    4/27/99 5:55p Dave
102  * Fixed Ras_connected bug with VSDK code.
103  * 
104  * 12    4/27/99 2:59p Dave
105  * Potential fix for reliable socket connection problem.
106  * 
107  * 11    4/23/99 11:07a Dave
108  * Added lots of debug multi.log output to psnet2
109  * 
110  * 10    4/12/99 10:07p Dave
111  * Made network startup more forgiving. Added checkmarks to dogfight
112  * screen for players who hit commit.
113  * 
114  * 9     3/10/99 6:50p Dave
115  * Changed the way we buffer packets for all clients. Optimized turret
116  * fired packets. Did some weapon firing optimizations.
117  * 
118  * 8     3/09/99 6:24p Dave
119  * More work on object update revamping. Identified several sources of
120  * unnecessary bandwidth.
121  * 
122  * 7     3/08/99 7:03p Dave
123  * First run of new object update system. Looks very promising.
124  * 
125  * 6     1/24/99 11:37p Dave
126  * First full rev of beam weapons. Very customizable. Removed some bogus
127  * Int3()'s in low level net code.
128  * 
129  * 5     1/06/99 2:24p Dave
130  * Stubs and release build fixes.
131  * 
132  * 4     11/20/98 11:16a Dave
133  * Fixed up IPX support a bit. Making sure that switching modes and
134  * loading/saving pilot files maintains proper state.
135  * 
136  * 3     11/19/98 4:19p Dave
137  * Put IPX sockets back in psnet. Consolidated all multiplayer config
138  * files into one.
139  * 
140  * 2     11/19/98 8:04a Dave
141  * Full support for D3-style reliable sockets. Revamped packet lag/loss
142  * system, made it receiver side and at the lowest possible level.
143  *
144  * $NoKeywords: $
145  */
146
147 #ifndef PLAT_UNIX
148 #include <winsock2.h>
149 #include <ras.h>
150 #include <raserror.h>
151 #else
152 #include <sys/types.h>
153 #include <sys/socket.h>
154 #include <netinet/in.h>
155 #include <arpa/inet.h>
156 #include <netdb.h>
157 #include <errno.h>
158 #endif
159 #include <stdio.h>
160 #include <limits.h>
161
162 #include "pstypes.h"
163 #include "psnet.h"
164 #include "multi.h"
165 #include "multiutil.h"
166 #include "multilag.h"
167 #include "osregistry.h"
168 #include "timer.h"
169 #include "multi_log.h"
170 #include "multi_rate.h"
171 #include "cmdline.h"
172
173 #ifdef PSNET2
174
175 // -------------------------------------------------------------------------------------------------------
176 // PSNET 2 DEFINES/VARS
177 //
178
179 int             Psnet_my_addr_valid;
180 net_addr_t Psnet_my_addr;
181
182 const ubyte Null_address[4] = { 0x00, 0x00, 0x00, 0x00 };
183
184 int Socket_type;
185 int Can_broadcast;                      // can we do broadcasting on our socket?
186 int Tcp_can_broadcast = 0;
187
188 int Tcp_active = 0;
189
190 int Network_status;
191 int Tcp_failure_code = 0;
192 int Ras_connected;
193 int Psnet_connection;
194
195 ushort  Psnet_default_port;
196
197 // specified their internet connnection type
198 #define NETWORK_CONNECTION_NONE                 1
199 #define NETWORK_CONNECTION_DIALUP               2
200 #define NETWORK_CONNECTION_LAN                  3
201
202 // defines and variables to indicate network connection status
203 #define NETWORK_STATUS_NOT_INITIALIZED  1
204 #define NETWORK_STATUS_NO_WINSOCK               2                       // winsock failed to initialize
205 #define NETWORK_STATUS_NO_PROTOCOL              3                       // TCP/IP doesn't appear to be loaded
206 #define NETWORK_STATUS_NO_RELIABLE              4
207 #define NETWORK_STATUS_RUNNING                  5                       // everything should be running
208
209 // defintion of structures that actually leave this machine.  psnet_send give us only
210 // the data that we want to send.  We will add a header onto this data (packet sequence
211 // number, possibly a checksum).  We must include a 2 byte flags variable into both structure
212 // since the receiving end of this packet must know whether or not to checksum the packet.
213
214 #define MAX_TOP_LAYER_PACKET_SIZE                       680
215
216 // use the pack pragma to pack these structures to 2 byte aligment.  Really only needed for
217 // the naked packet.
218 #define MAX_PACKET_BUFFERS              75
219
220 #ifndef PLAT_UNIX
221 #pragma pack(push, 2)
222 #endif
223
224 // definition for a non-checksum packet
225 typedef struct network_packet
226 {
227         int             sequence_number;
228         ushort  flags;
229         ubyte           data[MAX_TOP_LAYER_PACKET_SIZE];
230 } network_naked_packet;
231
232 // structure definition for our packet buffers
233 typedef struct network_packet_buffer
234 {
235         int             sequence_number;
236         int             len;    
237         net_addr_t      from_addr;
238         ubyte           data[MAX_TOP_LAYER_PACKET_SIZE];
239 } network_packet_buffer;
240
241 // struct for a bunch of network packet buffers
242 typedef struct network_packet_buffer_list {
243         network_packet_buffer psnet_buffers[MAX_PACKET_BUFFERS];
244         int psnet_seq_number;
245         int psnet_lowest_id;
246         int psnet_highest_id;
247 } network_packet_buffer_list;
248
249 #ifndef PLAT_UNIX
250 #pragma pack(pop)
251 #endif
252
253
254 #define MAXHOSTNAME                     128
255
256 #define MAX_RECEIVE_BUFSIZE     4096    // 32 K, eh?
257 #define MAX_SEND_RETRIES                20                      // number of retries when sending would block
258 #define MAX_LINGER_TIME                 0                       // in seconds -- when lingering to close a socket
259
260 //Reliable UDP stuff
261 //*******************************
262 #define MAXNETBUFFERS                   150             // Maximum network buffers (For between network and upper level functions, which is 
263                                                                                                         // required in case of out of order packets
264 #define NETRETRYTIME                            0.75f           // Time after sending before we resend
265 #define MIN_NET_RETRYTIME               0.2f
266 #define NETTIMEOUT                              30                      // Time after receiving the last packet before we drop that user
267 #define NETHEARTBEATTIME                3                       // How often to send a heartbeat
268 #define MAXRELIABLESOCKETS              40                      // Max reliable sockets to open at once...
269 #define NETBUFFERSIZE                   600             // Max size of a network packet
270
271 #define RELIABLE_CONNECT_TIME           7               // how long we'll wait for a response when doing a reliable connect
272
273 int Nettimeout = NETTIMEOUT;
274
275 // Reliable packet stuff
276 #define RNT_ACK                         1                               // ACK Packet
277 #define RNT_DATA                                2                               // Data Packet
278 #define RNT_DATA_COMP           3                               // Compressed Data Packet
279 #define RNT_REQ_CONN                    4                               // Requesting a connection
280 #define RNT_DISCONNECT          5                               // Disconnecting a connection
281 #define RNT_HEARTBEAT           6                               // Heartbeat -- send every NETHEARTBEATTIME
282 #define RNT_I_AM_HERE           7
283
284 #ifndef PLAT_UNIX
285 #pragma pack(push,r_udp)
286 #pragma pack(1)
287 #define PACKED
288 #else
289 #define PACKED __attribute__((packed))
290 #endif
291
292 typedef struct {
293         ubyte                   type;                                   // packet type
294         ubyte                   compressed;                     //
295         ushort          seq;                                    // sequence packet 0-65535 used for ACKing also
296         ushort          data_len;                       // length of data
297         float                   send_time;                      // Time the packet was sent, if an ACK the time the packet being ACK'd was sent.
298         ubyte           data[NETBUFFERSIZE];    // Packet data
299 } PACKED reliable_header;
300
301 #define RELIABLE_PACKET_HEADER_ONLY_SIZE (sizeof(reliable_header)-NETBUFFERSIZE)
302 #define MAX_PING_HISTORY        10
303
304 typedef struct {
305         ubyte buffer[NETBUFFERSIZE];
306
307 } PACKED reliable_net_sendbuffer;
308
309 typedef struct {
310         ubyte buffer[NETBUFFERSIZE];
311 } PACKED reliable_net_rcvbuffer;
312
313 typedef struct {
314         reliable_net_sendbuffer *sbuffers[MAXNETBUFFERS];       // This is an array of pointers for quick sorting
315         unsigned short ssequence[MAXNETBUFFERS];                                // This is the sequence number of the given packet
316         float timesent[MAXNETBUFFERS];
317         int send_len[MAXNETBUFFERS];
318         reliable_net_rcvbuffer  *rbuffers[MAXNETBUFFERS];
319         int recv_len[MAXNETBUFFERS];
320         unsigned short rsequence[MAXNETBUFFERS];                                // This is the sequence number of the given packet
321         float last_packet_received;                                                             // For a given connection, this is the last packet we received
322         float last_packet_sent;
323         struct sockaddr addr;                                                                                                   // struct sockaddr of our peer
324         ushort status;                                                                                                  // Status of this connection
325         unsigned short oursequence;                                                             // This is the next sequence number the application is expecting
326         unsigned short theirsequence;                                                           // This is the next sequence number the peer is expecting
327         net_addr_t      net_addr;                                                                                       // A FS2 network address structure
328         ubyte connection_type;                                                                          // IP, modem, etc.
329         float pings[MAX_PING_HISTORY];
330         ubyte ping_pos;
331         unsigned int num_ping_samples;
332         float mean_ping;        
333 } reliable_socket;
334
335 reliable_socket Reliable_sockets[MAXRELIABLESOCKETS];
336
337 // socket TCP (unreliable)
338 SOCKET TCP_socket;
339
340 // the sockets that the game will use when selecting network type
341 SOCKET Unreliable_socket = INVALID_SOCKET;
342
343 // blah
344 // SOCKET Reliable_UDP_socket = INVALID_SOCKET;
345
346 float First_sent_iamhere = 0;
347 float Last_sent_iamhere = 0;
348
349 #define CONNECTSEQ 0x142                                                                                // Magic number for starting a connection, just so it isn't 0
350
351 unsigned int Serverconn = 0xffffffff;
352
353 #ifndef PLAT_UNIX
354 #pragma pack(pop,r_udp)
355 #endif
356 #undef PACKED
357
358 //*******************************
359
360 // top layer buffers
361 network_packet_buffer_list Psnet_top_buffers[PSNET_NUM_TYPES];
362
363 // -------------------------------------------------------------------------------------------------------
364 // PSNET 2 FORWARD DECLARATIONS
365 //
366
367 // if the string is a legally formatted ip string
368 int psnet_is_valid_numeric_ip(char *ip);
369
370 // functions to get the status of a RAS connection
371 unsigned int psnet_ras_status();
372
373 // set some options on a socket
374 void psnet_socket_options( SOCKET sock );
375
376 // initialize tcp socket
377 int psnet_init_tcp();
378
379 // get time in seconds
380 float psnet_get_time();
381
382 // returns the ip address of this machine. use for calling bind() with to associate with the proper
383 // IP address and network device.
384 int psnet_get_ip();
385
386 // initialize reliable sockets
387 int psnet_init_rel_tcp(int port, int should_listen);
388
389 // shutdown reliable sockets
390 void psnet_rel_close();
391
392 // initialize the buffering system
393 void psnet_buffer_init(network_packet_buffer_list *l);
394
395 // buffer a packet (maintain order!)
396 void psnet_buffer_packet(network_packet_buffer_list *l, ubyte *data, int length, net_addr_t *from);
397
398 // get the index of the next packet in order!
399 int psnet_buffer_get_next(network_packet_buffer_list *l, ubyte *data, int *length, net_addr_t *from);
400
401
402 // -------------------------------------------------------------------------------------------------------
403 // PSNET 2 TOP LAYER FUNCTIONS - these functions simply buffer and store packets based upon type (see PSNET_TYPE_* defines)
404 //
405
406 // wrappers around select() and recvfrom() for lagging/losing data
407 int RECVFROM(SOCKET s, char *buf, int len, int flags, sockaddr *from, int *fromlen, int psnet_type)
408 {
409         network_packet_buffer_list *l;
410         net_addr_t addr;
411         int ret;
412         int ret_len;
413
414         // bad type
415         SDL_assert((psnet_type >= 0) && (psnet_type < PSNET_NUM_TYPES));
416         if((psnet_type < 0) || (psnet_type >= PSNET_NUM_TYPES)){
417                 return -1;
418         }       
419         l = &Psnet_top_buffers[psnet_type];
420
421         // if we have no buffer! The user should have made sure this wasn't the case by calling SELECT()
422         ret = psnet_buffer_get_next(l, (ubyte*)buf, &ret_len, &addr);
423         if(!ret){
424                 Int3();
425                 return -1;
426         }
427
428         // otherwise, stuff the outgoing data
429         ((struct sockaddr_in*)from)->sin_port = htons(addr.port);
430         memcpy(&((struct sockaddr_in*)from)->sin_addr.s_addr, addr.addr, 4);
431         ((struct sockaddr_in*)from)->sin_family = AF_INET;
432         *fromlen = sizeof(struct sockaddr_in);
433
434         // return bytes read
435         return ret_len;
436 }
437
438 // wrappers around select() and recvfrom() for lagging/losing data
439 int SELECT(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout, int psnet_type)
440 {
441         network_packet_buffer_list *l;
442
443         // if this is a check for writability, just return the select 
444         if(writefds != NULL){
445                 return select(nfds, readfds, writefds, exceptfds, timeout);
446         }       
447         
448         // bad type
449         SDL_assert((psnet_type >= 0) && (psnet_type < PSNET_NUM_TYPES));
450         if((psnet_type < 0) || (psnet_type >= PSNET_NUM_TYPES)){
451                 return -1;
452         }       
453         l = &Psnet_top_buffers[psnet_type];     
454
455         // do we have any buffers in here?      
456         if((l->psnet_lowest_id == -1) || (l->psnet_lowest_id > l->psnet_highest_id)){
457                 return 0;
458         }
459
460         // yo
461         return 1;
462 }
463
464 // wrappers around sendto to sorting through different packet types
465 int SENDTO(SOCKET s, char * buf, int len, int flags, sockaddr *to, int tolen, int psnet_type)
466 {       
467         char outbuf[MAX_TOP_LAYER_PACKET_SIZE + 150];           
468
469         // stuff type
470         outbuf[0] = (char)psnet_type;
471         memcpy(&outbuf[1], buf, len);
472
473         // is the socket writeable?
474         
475         // send it
476         return sendto(s, outbuf, len + 1, flags, (struct sockaddr*)to, tolen);
477 }
478
479 // call this once per frame to read everything off of our socket
480 void PSNET_TOP_LAYER_PROCESS()
481 {
482         // read socket stuff
483         struct sockaddr_in ip_addr;                             // UDP/TCP socket structure
484         fd_set  rfds;
485         timeval timeout;
486         int read_len;
487         SOCKLEN_T from_len;
488         net_addr_t      from_addr;      
489         network_naked_packet packet_read;               
490
491         // clear the addresses to remove compiler warnings
492         memset(&ip_addr, 0, sizeof(struct sockaddr_in));
493
494         if ( Network_status != NETWORK_STATUS_RUNNING ) {
495                 ml_printf("Network ==> socket not inited in PSNET_TOP_LAYER_PROCESS");
496                 return;
497         }
498
499         while ( 1 ) {           
500                 // check if there is any data on the socket to be read.  The amount of data that can be 
501                 // atomically read is stored in len.
502
503                 FD_ZERO(&rfds);
504                 FD_SET( Unreliable_socket, &rfds );
505                 timeout.tv_sec = 0;
506                 timeout.tv_usec = 0;
507
508                 if ( select( Unreliable_socket+1, &rfds, NULL, NULL, &timeout) == SOCKET_ERROR ) {              
509                         ml_printf("Error %d doing a socket select on read", WSAGetLastError());
510                         break;
511                 }
512
513                 // if the read file descriptor is not set, then bail!
514                 if ( !FD_ISSET(Unreliable_socket, &rfds) ){
515                         return;
516                 }
517
518                 // get data off the socket and process
519                 from_len = sizeof(struct sockaddr_in);
520                 read_len = recvfrom( Unreliable_socket, (char*)packet_read.data, MAX_TOP_LAYER_PACKET_SIZE, 0,  (struct sockaddr*)&ip_addr, &from_len);
521
522                 // set the from_addr for storage into the packet buffer structure
523                 from_addr.type = Socket_type;
524                 from_addr.port = ntohs( ip_addr.sin_port );
525                 memcpy(from_addr.addr, &ip_addr.sin_addr.s_addr, 4);
526
527                 if ( read_len == SOCKET_ERROR ) {
528                         // int x = WSAGetLastError();
529                         ml_printf("Socket error on socket_get_data()");
530                         break;
531                 }               
532
533                 // determine the packet type
534                 int packet_type = packet_read.data[0];          
535                 // mprintf(("TOP LAYER PACKET  %d!\n", packet_type));
536                 if((packet_type < 0) || (packet_type >= PSNET_NUM_TYPES)){
537                         Int3();
538                 } else {                
539                         // buffer the packet
540                         psnet_buffer_packet(&Psnet_top_buffers[packet_type], packet_read.data + 1, read_len - 1, &from_addr);
541                 }
542         }
543 }
544
545
546 // -------------------------------------------------------------------------------------------------------
547 // PSNET 2 FUNCTIONS
548 //
549
550 // initialize psnet to use the specified port
551 void psnet_init( int protocol, int port_num )
552 {       
553         const char *internet_connection;
554 #ifndef PLAT_UNIX
555         WSADATA wsa_data;               
556 #endif
557         int idx;
558         Tcp_active = 0;
559
560 #if defined(DEMO) || defined(OEM_BUILD) // not for FS2_DEMO
561         return;
562 #endif
563
564         // GAME PORT INITIALIZATION STUFF
565         if ( Network_status == NETWORK_STATUS_RUNNING ){
566                 ml_string("Skipping psnet_init() because network already running");
567                 return;
568         }
569
570         // 'lan' should be a safe default in 2015
571         internet_connection = os_config_read_string("Network", "NetworkConnection", "LAN");
572
573         if ( !SDL_strcasecmp(internet_connection, NOX("dialup")) ) {
574                 ml_string("psnet_init() detected dialup connection");
575
576                 Psnet_connection = NETWORK_CONNECTION_DIALUP;
577         } else if ( !SDL_strcasecmp(internet_connection, NOX("lan")) ) {
578                 ml_string("psnet_init() detected lan connection");
579
580                 Psnet_connection = NETWORK_CONNECTION_LAN;
581         } else {
582                 ml_string("psnet_init() detected no connection");
583
584                 Psnet_connection = NETWORK_CONNECTION_NONE;
585         }
586
587         Network_status = NETWORK_STATUS_NO_WINSOCK;
588 #ifndef PLAT_UNIX
589         if (WSAStartup(0x101, &wsa_data )){
590                 return;
591         }
592 #endif
593
594         // get the port for running this game on.  Be careful that it cannot be out of bounds
595         Psnet_default_port = DEFAULT_GAME_PORT;
596         if ( (port_num > 1023) && (port_num < USHRT_MAX) ) {
597                 Psnet_default_port = (ushort)port_num;
598         }
599
600         // initialize TCP now   
601         Tcp_active = 1;
602         if(!psnet_init_tcp()){
603                 ml_printf("Error on TCP startup %d", Tcp_failure_code);
604
605                 Tcp_active = 0;
606         } else {
607                 if(!psnet_init_rel_tcp(Psnet_default_port + 1, 0)){
608                         ml_printf("Network", "Error on TCP startup %d", Tcp_failure_code);
609
610                         Tcp_active = 0;
611                 }
612         }
613
614         // clear reliable sockets
615         reliable_socket *rsocket;
616         int j;  
617         for(j=0; j<MAXRELIABLESOCKETS; j++){
618                 rsocket=&Reliable_sockets[j];
619                 memset(rsocket,0,sizeof(reliable_socket));
620         }
621
622         // determine if we've successfully initialized the protocol we want
623         if ( !Tcp_active ) {
624                 Network_status = NETWORK_STATUS_NO_PROTOCOL;            
625
626                 ml_string("No protocol in psnet_init()!");
627         }
628
629         // specified network timeout    
630         Nettimeout = NETTIMEOUT;
631         if(Cmdline_timeout > 0){
632                 Nettimeout = Cmdline_timeout;
633         }
634
635         // set ras status
636         psnet_ras_status();     
637
638         if(Network_status != NETWORK_STATUS_NO_PROTOCOL){                       
639                 // set network to be running
640                 Network_status = NETWORK_STATUS_RUNNING;        
641         
642                 // determine if our socket can broadcast
643                 Can_broadcast = Tcp_can_broadcast;
644         
645                 // initialize all packet type buffers
646                 for(idx=0; idx<PSNET_NUM_TYPES; idx++){
647                         psnet_buffer_init(&Psnet_top_buffers[idx]);
648                 }
649         }
650 }
651
652 // shutdown psnet
653 void psnet_close()
654 {
655         if ( Network_status != NETWORK_STATUS_RUNNING ){
656                 return;
657         }
658
659 #ifndef PLAT_UNIX
660         WSACancelBlockingCall();                
661 #endif
662
663         if ( TCP_socket != (int)INVALID_SOCKET ) {
664 #ifndef __EMSCRIPTEN__
665                 shutdown( TCP_socket, 1 );
666 #endif
667                 closesocket( TCP_socket );
668         }
669
670 #ifndef PLAT_UNIX
671         if (WSACleanup())       {
672                 //Warning( LOCATION, "Error closing wsock!\n" );
673         }
674 #endif
675
676         // close down all reliable sockets - this forces them to
677         // send a disconnect to any remote machines     
678         psnet_rel_close();
679         
680         Network_status = NETWORK_STATUS_NOT_INITIALIZED;
681 }
682
683 // set the protocol to use
684 int psnet_use_protocol( int protocol )
685 {
686         SOCKLEN_T len;
687         struct sockaddr_in              ip_addr;
688
689         // zero out my address
690         Psnet_my_addr_valid = 0;
691         memset( &Psnet_my_addr, 0, sizeof(Psnet_my_addr) );
692
693         // wait until we choose a protocol to determine if we can broadcast
694         Can_broadcast = 0;
695
696         ml_string("In psnet_use_protocol()");
697
698         if (protocol != NET_TCP) {
699                 Int3();
700                 return 0;
701         }
702
703
704         if ( Network_status != NETWORK_STATUS_RUNNING ){
705                 ml_string("Network_status != NETWORK_STATUS_RUNNING in NET_TCP in psnet_use_protocol()");
706                 return 0;
707         }
708
709         // assign the TCP_* sockets to the socket values used elsewhere
710         Unreliable_socket = TCP_socket;
711
712         Can_broadcast = Tcp_can_broadcast;
713         if(Can_broadcast){
714                 ml_printf("Psnet : TCP broadcast");
715         }
716
717         // get the socket name, and put it into My_addr
718         len = sizeof(struct sockaddr_in);
719         if ( getsockname(TCP_socket, (struct sockaddr *)&ip_addr, &len) == SOCKET_ERROR ) {
720                 ml_printf("Unable to get sock name for TCP unreliable socket (%d)", WSAGetLastError() );
721
722                 return 0;
723         }
724
725         memcpy(Psnet_my_addr.addr, &ip_addr.sin_addr, 4);
726         Psnet_my_addr.port = Psnet_default_port;
727
728         ml_printf("Psnet using - NET_TCP");
729
730
731         Psnet_my_addr.type = protocol;
732         Socket_type = protocol;
733
734         return 1;
735 }
736
737 // get the status of the network
738 int psnet_get_network_status()
739 {
740         // first case is when "none" is selected
741         if ( Psnet_connection == NETWORK_CONNECTION_NONE ) {
742                 return NETWORK_ERROR_NO_TYPE;
743         }
744
745         // first, check the connection status of the network
746         if ( Network_status == NETWORK_STATUS_NO_WINSOCK )
747                 return NETWORK_ERROR_NO_WINSOCK;
748
749         if ( Network_status == NETWORK_STATUS_NO_PROTOCOL ){
750                 return NETWORK_ERROR_NO_PROTOCOL;
751         }
752         
753         // network is running -- be sure that the RAS people know to connect if they currently cannot.
754         
755         if ( Psnet_connection == NETWORK_CONNECTION_DIALUP ) {
756                 // if on a dialup connection, be sure that RAS is active.
757                 if ( !Ras_connected ) {
758                         return NETWORK_ERROR_CONNECT_TO_ISP;
759                 }
760         } else if ( Psnet_connection == NETWORK_CONNECTION_LAN ) {
761                 // if on a LAN, and they have a dialup connection active, return error to indicate that they need
762                 // to pick the right connection type
763                 if ( Ras_connected ) {
764                         return NETWORK_ERROR_LAN_AND_RAS;
765                 }
766         }
767         return NETWORK_ERROR_NONE;
768 }
769
770 // convert a net_addr to a string
771 char* psnet_addr_to_string( char * text, const int max_textlen, net_addr_t * address )
772 {
773
774         if ( Network_status != NETWORK_STATUS_RUNNING )         {
775                 SDL_strlcpy( text, XSTR("[no networking]",910), max_textlen );
776                 return text;
777         }
778
779         in_addr temp_addr;
780
781         SDL_assert(address->type == NET_TCP);
782
783         memcpy(&temp_addr.s_addr, address->addr, 4);
784         SDL_strlcpy( text, inet_ntoa(temp_addr), max_textlen );
785
786         return text;
787 }
788
789 // convert a string to a net addr
790 void psnet_string_to_addr( net_addr_t * address, char * text, const int max_textlen )
791 {
792         struct hostent *he;
793         char str[255], *c, *port;
794         in_addr addr;
795
796         if ( Network_status != NETWORK_STATUS_RUNNING ) {
797                 SDL_strlcpy( text, XSTR("[no networking]",910), max_textlen );
798                 return;
799         }
800
801         // copy the text string to local storage to look for ports
802         SDL_assert( strlen(text) < 255 );
803         SDL_strlcpy(str, text, SDL_arraysize(str));
804         c = strrchr(str, ':');
805         port = NULL;
806         if ( c ) {
807                 *c = '\0';
808                 port = c+1;
809         }
810
811         SDL_assert(address->type == NET_TCP);
812
813
814         addr.s_addr = inet_addr(str);
815         // if we get INADDR_NONE returns, then we need to try and resolve the host
816         // name
817         if ( addr.s_addr == INADDR_NONE ) {
818                 he = gethostbyname( str );
819                 // returns a non-null pointer if successful, so get the address
820                 if ( he ) {
821                         addr.s_addr = ((in_addr *)(he->h_addr))->s_addr;                        // this is the address in network byte order
822                 } else {
823                         addr.s_addr = INADDR_NONE;
824                 }
825         }
826
827         memcpy(address->addr, &addr.s_addr, 4);
828
829         if ( port ){
830                 address->port = (ushort)(atoi(port));
831         }
832 }
833
834 // compare 2 addresses
835 int psnet_same( net_addr_t * a1, net_addr_t * a2 )
836 {
837         return ((a1->port == a2->port) && !memcmp(a1->addr, a2->addr, 4));
838 }
839
840 // send data unreliably
841 int psnet_send( net_addr_t * who_to, void * data, int len, int np_index )
842 {
843         // send data unreliably
844         SOCKET send_sock;
845         struct sockaddr_in sockaddr;                            // UDP/TCP socket structure
846         int ret, send_len;
847         ubyte iaddr[4], *send_data;
848         short port;
849         fd_set  wfds;
850         struct timeval timeout; 
851
852         // always use the reliable socket
853         send_sock = Unreliable_socket;          
854
855         if ( Network_status != NETWORK_STATUS_RUNNING ) {
856                 ml_printf("Network ==> Socket not inited in psnet_send");
857                 return 0;
858         }
859
860         if ( psnet_same( who_to, &Psnet_my_addr) ){
861                 return 0;
862         }
863
864         if (who_to->type != NET_TCP) {
865                 Int3();
866                 return 0;
867         }
868
869         memcpy(iaddr, who_to->addr, 4);
870
871         if ( memcmp(iaddr, Null_address, 4) == 0) {
872                 ml_printf("Network ==> send to address is 0 in psnet_send");
873                 return 0;
874         }
875
876         port = who_to->port;
877                 
878         if ( port == 0) {
879                 ml_printf("Network ==> destination port %d invalid in psnet_send", port);
880                 return 0;
881         }
882
883         // stuff the data with the type 
884         send_data = (ubyte*)data;
885         send_len = len;
886
887         FD_ZERO(&wfds);
888         FD_SET( send_sock, &wfds );
889         timeout.tv_sec = 0;
890         timeout.tv_usec = 0;
891
892         if ( SELECT( send_sock+1, NULL, &wfds, NULL, &timeout, PSNET_TYPE_UNRELIABLE) == SOCKET_ERROR ) {       
893                 ml_printf("Error on blocking select for write %d", WSAGetLastError() );
894                 return 0;
895         }
896
897         // if the write file descriptor is not set, then bail!
898         if ( !FD_ISSET(send_sock, &wfds ) ){
899                 return 0;
900         }
901
902         sockaddr.sin_family = AF_INET;
903         memcpy(&sockaddr.sin_addr.s_addr, iaddr, 4);
904         sockaddr.sin_port = htons(port);
905
906         multi_rate_add(np_index, "udp(h)", send_len + UDP_HEADER_SIZE);
907         multi_rate_add(np_index, "udp", send_len);
908         ret = SENDTO( send_sock, (char *)send_data, send_len, 0, (struct sockaddr*)&sockaddr, sizeof(sockaddr), PSNET_TYPE_UNRELIABLE );
909
910         if ( ret != SOCKET_ERROR )      {
911                 return 1;
912         }
913         //Warning( LOCATION, "Couldn't send data (0x%x)!\n", WSAGetLastError() ); 
914         return 0;
915 }
916
917 // get data from the unreliable socket
918 int psnet_get( void * data, net_addr_t * from_addr )
919 {                                       
920         int buffer_size;
921
922         // try and get a free buffer and return its size
923         if(psnet_buffer_get_next(&Psnet_top_buffers[PSNET_TYPE_UNRELIABLE], (ubyte*)data, &buffer_size, from_addr)){
924                 return buffer_size;
925         }
926
927         // return nothing
928         return 0;
929 }
930
931 // broadcast data on unreliable socket
932 int psnet_broadcast( net_addr_t * who_to, void * data, int len )
933 {
934         if ( Network_status != NETWORK_STATUS_RUNNING ) {
935                 ml_printf("Network ==> Socket not inited in psnet_broadcast");
936                 return 0;
937         }
938
939         if ( !Can_broadcast ) {
940                 ml_printf("Cannot broadcast -- returning without doing anything");
941                 return 0;
942         }
943
944         ubyte broadcast[4] = { 0xff, 0xff, 0xff, 0xff };
945
946         // broadcasting works on a local subnet which is all we really want to do for now anyway.
947         // we might keep this in as an option for freespace later.
948         memcpy(who_to->addr, broadcast, 4);
949         psnet_send(who_to, data, len);
950
951         return 1;
952 }
953
954 // flush all sockets
955 void psnet_flush()
956 {
957         ubyte data[MAX_TOP_LAYER_PACKET_SIZE + 250];
958         net_addr_t from_addr;
959
960         while ( psnet_get( data, &from_addr ) > 0 ) ;
961 }
962
963 // if the passed string is a valid IP string
964 int psnet_is_valid_ip_string( char *ip_string, int allow_port )
965 {
966         in_addr addr;
967         struct hostent *host_ent;
968         char str[255], *c;
969
970         // our addresses may have ports, so make local copy and remove port number
971         SDL_assert( strlen(ip_string) < 255 );
972         SDL_strlcpy(str, ip_string, SDL_arraysize(str));
973         c = strrchr(str, ':');
974         if ( c ){
975                 *c = '\0';
976         }       
977
978         addr.s_addr = inet_addr(ip_string);
979         if ( addr.s_addr != INADDR_NONE ){
980                 // make sure the ip string is a valid format string
981                 if(psnet_is_valid_numeric_ip(ip_string)){
982                         return 1;
983                 }
984         }
985
986         // try name resolution
987         host_ent = gethostbyname( ip_string );
988         if ( !host_ent ){
989                 return 0;
990         }
991
992         // valid host entry so return 1;
993         return 1;
994 }
995
996
997 // -------------------------------------------------------------------------------------------------------
998 // PSNET 2 RELIABLE SOCKET FUNCTIONS
999 //
1000
1001 // compare 2 pings
1002 int psnet_rel_ping_compare( const void *arg1, const void *arg2 )
1003 {
1004         float *ping1 = (float *)arg1;
1005         float *ping2 = (float *)arg2;
1006         
1007         if(*ping1==*ping2) return 0;
1008         else if(*ping1>*ping2) return 1;
1009         else if(*ping1<*ping2) return -1;
1010
1011         return 0;
1012 }
1013
1014 void psnet_rel_send_ack(struct sockaddr *raddr, unsigned int sig, ubyte link_type, float time_sent)
1015 {
1016         int sig_tmp;
1017         reliable_header ack_header;
1018
1019         if (link_type != NET_TCP) {
1020                 Int3();
1021                 return;
1022         }
1023
1024         ack_header.type = RNT_ACK;      
1025         ack_header.data_len = sizeof(unsigned int);
1026         ack_header.send_time = INTEL_FLOAT( time_sent );
1027         sig_tmp = INTEL_INT( sig );
1028         memcpy(&ack_header.data,&sig_tmp,sizeof(unsigned int));
1029
1030         if ( !Tcp_active ) {
1031                 ml_string("No TCP in rel_send_ack()");
1032                 return;
1033         }
1034
1035         SENDTO(Unreliable_socket, (char *)&ack_header, RELIABLE_PACKET_HEADER_ONLY_SIZE+sizeof(unsigned int), 0, raddr, sizeof(struct sockaddr), PSNET_TYPE_RELIABLE);
1036 }
1037
1038 // function to shutdown and close the given socket.  It takes a couple of things into consideration
1039 // when closing, such as possibly reiniting reliable sockets if they are closed here.
1040 void psnet_rel_close_socket( PSNET_SOCKET_RELIABLE *sockp )
1041 {
1042         reliable_header diss_conn_header;
1043
1044         if (*sockp == INVALID_SOCKET) {
1045                 return;
1046         }
1047
1048         // if the socket is out of range
1049         if(*sockp>=MAXRELIABLESOCKETS)
1050         {
1051                 ml_printf("Invalid socket id passed to nw_NewCloseSocket() -- %d",*sockp);
1052                 return;
1053         }       
1054         ml_printf("Closing socket %d",*sockp);
1055         
1056         // go through every buffer and "free it up(tm)"
1057         int i;
1058         for(i=0;i<MAXNETBUFFERS;i++){
1059                 if(Reliable_sockets[*sockp].rbuffers[i]){
1060                         if(Reliable_sockets[*sockp].rbuffers[i] != NULL){
1061                                 free(Reliable_sockets[*sockp].rbuffers[i]);
1062                         }
1063                         Reliable_sockets[*sockp].rbuffers[i] = NULL;
1064                         Reliable_sockets[*sockp].rsequence[i] = 0;
1065                 }
1066                 if(Reliable_sockets[*sockp].sbuffers[i]){
1067                         if(Reliable_sockets[*sockp].sbuffers[i] != NULL){
1068                                 free(Reliable_sockets[*sockp].sbuffers[i]);
1069                         }
1070                         Reliable_sockets[*sockp].sbuffers[i] = NULL;
1071                         Reliable_sockets[*sockp].rsequence[i] = 0;
1072                 }
1073         }
1074
1075         // send a disconnect packet to the socket on the other end
1076         diss_conn_header.type = RNT_DISCONNECT;
1077         diss_conn_header.seq = CONNECTSEQ;
1078         diss_conn_header.data_len = 0;
1079         if(*sockp==Serverconn){
1080                 Serverconn = 0xffffffff;
1081         }
1082
1083         if (Reliable_sockets[*sockp].connection_type ==  NET_TCP) {
1084                 SDL_assert(Tcp_active);
1085                 SENDTO(Unreliable_socket, (char *)&diss_conn_header,RELIABLE_PACKET_HEADER_ONLY_SIZE,0,&Reliable_sockets[*sockp].addr,sizeof(struct sockaddr), PSNET_TYPE_RELIABLE);
1086         } else {
1087                 ml_printf("Unknown protocol type in nw_CloseSocket()!");
1088                 // Int3();
1089         }
1090
1091         memset(&Reliable_sockets[*sockp],0,sizeof(reliable_socket));
1092         Reliable_sockets[*sockp].status = RNF_UNUSED;   
1093 }
1094
1095 // function to check the status of the reliable socket and try to re-initialize it if necessary.
1096 // win95 seems to have trouble doing a reinit of the socket immediately after close, so this
1097 // function exists to check the status, and reinitialize if we need to
1098 int psnet_rel_check()
1099 {
1100         return 1;
1101 }
1102
1103 // send data reliably
1104 int psnet_rel_send(PSNET_SOCKET_RELIABLE socketid, ubyte *data, int length, int np_index)
1105 {               
1106         int i;
1107         int bytesout = 0;
1108         reliable_socket *rsocket;       
1109         
1110         if(socketid >= MAXRELIABLESOCKETS){
1111                 ml_printf("Invalid socket id passed to psnet_rel_send() -- %d",socketid);
1112                 return -1;
1113         }
1114
1115         SDL_assert( length < (int)(sizeof(reliable_header)) );
1116         psnet_rel_work();
1117
1118         rsocket=&Reliable_sockets[socketid];
1119         if(rsocket->status!=RNF_CONNECTED) {
1120                 //We can't send because this isn't a connected reliable socket.
1121                 ml_printf("Can't send packet because of status %d in nw_SendReliable(). socket = %d",rsocket->status,socketid);
1122                 return -1;
1123         }
1124         
1125         // Add the new packet to the sending list and send it.
1126         for(i=0;i<MAXNETBUFFERS;i++){
1127                 if(NULL==rsocket->sbuffers[i]){                 
1128                         reliable_header send_header;
1129                         int send_this_packet=1;                 
1130                         
1131                         rsocket->send_len[i] = length;
1132                         rsocket->sbuffers[i] = (reliable_net_sendbuffer *)malloc(sizeof(reliable_net_sendbuffer));
1133                 
1134                         memcpy(rsocket->sbuffers[i]->buffer,data,length);       
1135
1136                         send_header.seq = INTEL_SHORT( rsocket->theirsequence );
1137                         rsocket->ssequence[i] = rsocket->theirsequence;
1138                         
1139                         memcpy(send_header.data,data,length);
1140                         send_header.data_len = INTEL_SHORT( (ushort)length );
1141                         send_header.type = RNT_DATA;
1142                         send_header.send_time = psnet_get_time();
1143                         send_header.send_time = INTEL_FLOAT( send_header.send_time );
1144                         // struct sockaddr_in * rsockaddr = (struct sockaddr_in *)&rsocket->addr;
1145                                         
1146                         if (send_this_packet){
1147                                 if (rsocket->connection_type == NET_TCP) {
1148                                         SDL_assert(Tcp_active);
1149                                         multi_rate_add(np_index, "tcp(h)", RELIABLE_PACKET_HEADER_ONLY_SIZE+rsocket->send_len[i]);
1150                                         bytesout = SENDTO(Unreliable_socket, (char *)&send_header,RELIABLE_PACKET_HEADER_ONLY_SIZE+rsocket->send_len[i],0,&rsocket->addr,sizeof(struct sockaddr), PSNET_TYPE_RELIABLE);
1151                                 } else {
1152                                         ml_printf("Unknown protocol type in nw_SendReliable()!");
1153                                         Int3();
1154                                 }               
1155                         }
1156                         int error = WSAGetLastError();
1157                         if((bytesout==SOCKET_ERROR)&&NETCALL_WOULDBLOCK(error)){
1158                                 //This will cause it to try to send again next frame. (or sooner)
1159                                 rsocket->timesent[i] = psnet_get_time()-(NETRETRYTIME*4);
1160                         } else {
1161                                 rsocket->timesent[i] = psnet_get_time();
1162                         }
1163                         
1164                                                 
1165                         rsocket->theirsequence++;
1166                         return bytesout;
1167                 }
1168         }
1169         ml_printf("PSNET RELIABLE SEND BUFFER OVERRUN. socket = %d",socketid);
1170         // Int3();
1171         return 0;
1172 }
1173
1174 // Return codes:
1175 // -1 socket not connected
1176 // 0 No packet ready to receive
1177 // >0 Buffer filled with the number of bytes recieved
1178 int psnet_rel_get(PSNET_SOCKET socketid, ubyte *buffer, int max_len)
1179 {       
1180         int i;
1181         
1182         reliable_socket *rsocket = NULL;
1183         psnet_rel_work();
1184         if(socketid >= MAXRELIABLESOCKETS){
1185                 ml_printf("Invalid socket id passed to nw_NewReceiveReliable() -- %d",socketid);
1186                 return -1;
1187         }
1188         rsocket = &Reliable_sockets[socketid];
1189         if( (RNF_CONNECTED!=rsocket->status) && (RNF_LIMBO!=rsocket->status) ){
1190                 ml_printf("Can't receive packet because it isn't connected in nw_ReceiveReliable(). socket = %d",socketid);
1191                 return 0;
1192         }
1193         //If the buffer position is the position we are waiting for, fill in 
1194         //the buffer we received in the call to this function and return true                   
1195
1196         for(i=0; i<MAXNETBUFFERS; i++){
1197                 if((rsocket->rsequence[i] == rsocket->oursequence) && rsocket->rbuffers[i]){
1198                         memcpy(buffer,rsocket->rbuffers[i]->buffer, rsocket->recv_len[i]);
1199                         free(rsocket->rbuffers[i]);
1200                         rsocket->rbuffers[i] = NULL;
1201                         rsocket->rsequence[i] = 0;                      
1202                         rsocket->oursequence++;
1203                         return rsocket->recv_len[i];
1204                 }
1205         }
1206
1207         return 0;       
1208 }
1209
1210 // process all active reliable sockets
1211 void psnet_rel_work()
1212 {
1213         int i,j;
1214         int rcode = -1;
1215         int max_len = NETBUFFERSIZE;
1216         fd_set read_fds;                   
1217         struct timeval timeout;
1218         static reliable_header rcv_buff;
1219         static struct sockaddr rcv_addr;
1220         int bytesin = 0;
1221         int addrlen = sizeof(struct sockaddr);
1222         timeout.tv_sec=0;            
1223         timeout.tv_usec=0;
1224
1225         PSNET_TOP_LAYER_PROCESS();
1226                 
1227         // negotitate initial connection with the server
1228         reliable_socket *rsocket = NULL;
1229         if(Serverconn != 0xffffffff){
1230                 //Check to see if we need to send a packet out.
1231                 if((Reliable_sockets[Serverconn].status==RNF_LIMBO) && ((Serverconn != 0xffffffff) && fl_abs((psnet_get_time() - Last_sent_iamhere))>NETRETRYTIME) ){
1232                         reliable_header conn_header;
1233                         //Now send I_AM_HERE packet
1234                         conn_header.type = RNT_I_AM_HERE;
1235                         conn_header.seq = (ushort)(~CONNECTSEQ);
1236                         conn_header.data_len = 0;
1237                         Last_sent_iamhere = psnet_get_time();
1238                         int ret = SOCKET_ERROR;
1239
1240                         if (Reliable_sockets[Serverconn].connection_type == NET_TCP) {
1241                                 SDL_assert(Tcp_active);
1242                                 ret = SENDTO(Unreliable_socket, (char *)&conn_header,RELIABLE_PACKET_HEADER_ONLY_SIZE,0,&Reliable_sockets[Serverconn].addr,sizeof(struct sockaddr), PSNET_TYPE_RELIABLE);
1243                         }
1244
1245                         int error = WSAGetLastError();
1246                         if((ret == SOCKET_ERROR) && NETCALL_WOULDBLOCK(error)){
1247                                 Reliable_sockets[Serverconn].last_packet_sent = psnet_get_time()-NETRETRYTIME;
1248                         } else {
1249                                 Reliable_sockets[Serverconn].last_packet_sent = psnet_get_time();
1250                         }
1251                 }
1252         }
1253
1254         ubyte link_type;
1255         net_addr_t d3_rcv_addr;
1256         struct sockaddr_in *rcvaddr;
1257         int udp_has_data = 0;
1258         do {            
1259                 rsocket = NULL;
1260                 //Check UDP
1261                 FD_ZERO(&read_fds);
1262                 FD_SET(Unreliable_socket, &read_fds);
1263
1264                 udp_has_data = SELECT(Unreliable_socket+1,&read_fds,NULL,NULL,&timeout, PSNET_TYPE_RELIABLE);
1265
1266                 if (udp_has_data <= 0) {
1267                         break;
1268                 }
1269
1270                 addrlen = sizeof(struct sockaddr);
1271                 struct sockaddr_in *tcp_addr = (struct sockaddr_in *)&rcv_addr;
1272                 memset(&d3_rcv_addr,0,sizeof(net_addr_t));
1273                 memset(&rcv_addr,0,sizeof(struct sockaddr));
1274                 bytesin = RECVFROM(Unreliable_socket, (char *)&rcv_buff,sizeof(reliable_header), 0, (struct sockaddr *)&rcv_addr,&addrlen, PSNET_TYPE_RELIABLE);
1275                 rcv_buff.seq = INTEL_SHORT( rcv_buff.seq );
1276                 rcv_buff.data_len = INTEL_SHORT( rcv_buff.data_len );
1277                 rcv_buff.send_time = INTEL_FLOAT( rcv_buff.send_time );
1278                 memcpy(d3_rcv_addr.addr, &tcp_addr->sin_addr.s_addr, 4);
1279                 d3_rcv_addr.port = tcp_addr->sin_port;
1280                 d3_rcv_addr.type = NET_TCP;
1281                 link_type = NET_TCP;
1282
1283                 if(bytesin==-1){
1284                         ml_printf("recvfrom returned an error! -- %d",WSAGetLastError());
1285                         //Int3();//See Kevin                    
1286                         return;
1287                 }
1288                 if(bytesin){
1289                         //Someone wants to connect, so find a slot
1290                         if(rcv_buff.type == RNT_REQ_CONN){
1291                                 for(i=1; i<MAXRELIABLESOCKETS; i++){
1292                                         if( (Reliable_sockets[i].status == RNF_CONNECTED) || (Reliable_sockets[i].status == RNF_LIMBO) ){
1293                                                 //if(memcmp(&rcv_addr,&reliable_sockets[i].addr,sizeof(struct sockaddr))==0)
1294                                                 if(memcmp(&d3_rcv_addr, &Reliable_sockets[i].net_addr, sizeof(net_addr_t)) == 0){
1295                                                         //We already have a reliable link to this user, so we will ignore it...
1296                                                         ml_printf("Received duplicate connection request. %d",i);
1297                                                         //reliable_sockets[i].last_packet_received = timer_GetTime();
1298                                                         psnet_rel_send_ack(&Reliable_sockets[i].addr, rcv_buff.seq, link_type, rcv_buff.send_time);
1299                                                         //We will change this as a hack to prevent later code from hooking us up
1300                                                         rcv_buff.type = 0xff;
1301                                                         continue;
1302                                                 }
1303                                         }
1304                                 }
1305                                 for(i=1; i<MAXRELIABLESOCKETS; i++){
1306                                         if(Reliable_sockets[i].status == RNF_UNUSED){
1307                                                 //Add the new connection here.
1308                                                 Reliable_sockets[i].connection_type=link_type;
1309                                                 memcpy(&Reliable_sockets[i].net_addr, &d3_rcv_addr, sizeof(net_addr_t));
1310                                                 memcpy(&Reliable_sockets[i].addr ,&rcv_addr, sizeof(struct sockaddr));
1311                                                 Reliable_sockets[i].ping_pos = 0;
1312                                                 Reliable_sockets[i].num_ping_samples = 0;
1313                                                 Reliable_sockets[i].status = RNF_LIMBO;
1314                                                 Reliable_sockets[i].last_packet_received = psnet_get_time();
1315                                                 rsocket = &Reliable_sockets[i];
1316                                                 rcvaddr = (struct sockaddr_in *)&rcv_addr;
1317                                                 ml_printf("Connect from %s:%d", inet_ntoa(rcvaddr->sin_addr), htons(rcvaddr->sin_port));
1318                                                 break;
1319                                         }
1320                                 }
1321                                 if(i==MAXRELIABLESOCKETS){
1322                                         //No more connections!
1323                                         ml_printf("Out of incoming reliable connection sockets");
1324                                         //Int3();//See Kevin
1325                                         continue;
1326                                 }
1327                                 psnet_rel_send_ack(&rsocket->addr, rcv_buff.seq, link_type, rcv_buff.send_time);                        
1328                         }
1329                         
1330                         //Find out if this is a packet from someone we were expecting a packet.
1331                         rcvaddr = (struct sockaddr_in *)&rcv_addr;
1332                         for(i=1; i<MAXRELIABLESOCKETS; i++){
1333                                 if(memcmp(&d3_rcv_addr,&Reliable_sockets[i].net_addr,sizeof(net_addr_t)) == 0){
1334                                         rsocket=&Reliable_sockets[i];
1335                                         break;
1336                                 }                               
1337                         }
1338                         if(rsocket == NULL){
1339                                 ml_printf("Received reliable data from unconnected client.");
1340                                 ml_printf("Received from %s:%d",inet_ntoa(rcvaddr->sin_addr),rcvaddr->sin_port);
1341                                 continue ;
1342                         }
1343                         rsocket->last_packet_received = psnet_get_time();
1344                         
1345                         if(rsocket->status != RNF_CONNECTED){
1346                                 //Get out of limbo
1347                                 if(rsocket->status == RNF_LIMBO){
1348                                         //this is our connection to the server
1349                                         if(Serverconn != 0xffffffff){
1350                                                 if(rcv_buff.type == RNT_ACK){
1351                                                         ushort *acknum = (ushort *)&rcv_buff.data;
1352                                                         if(*acknum == (~CONNECTSEQ & 0xffff)){
1353                                                                 rsocket->status = RNF_CONNECTED;
1354                                                                 ml_printf("Got ACK for IAMHERE!");
1355                                                         }
1356                                                         continue;
1357                                                 }
1358                                         } else if(rcv_buff.type == RNT_I_AM_HERE){
1359                                                 rsocket->status = RNF_CONNECTING;
1360                                                 psnet_rel_send_ack(&rsocket->addr, rcv_buff.seq, link_type, rcv_buff.send_time);                
1361                                                 ml_printf("Got IAMHERE!");
1362                                                 continue;
1363                                         }
1364                                 }
1365                                 if((rcv_buff.type == RNT_DATA) && (Serverconn != 0xffffffff)){
1366                                         rsocket->status = RNF_CONNECTED;
1367                                 } else {                                        
1368                                         rsocket->last_packet_received = psnet_get_time();
1369                                         continue;
1370                                 }                               
1371                         }
1372                         //Update the last recv variable so we don't need a heartbeat
1373                         rsocket->last_packet_received = psnet_get_time();
1374
1375                         if(rcv_buff.type == RNT_HEARTBEAT){
1376                                 continue;
1377                         }
1378                         if(rcv_buff.type == RNT_ACK){
1379                                 //Update ping time
1380                                 rsocket->num_ping_samples++;
1381                                 
1382                                 rsocket->pings[rsocket->ping_pos] = rsocket->last_packet_received - rcv_buff.send_time;                         
1383                                 if(rsocket->num_ping_samples >= MAX_PING_HISTORY){
1384                                         float sort_ping[MAX_PING_HISTORY];
1385                                         for(int a=0;a<MAX_PING_HISTORY;a++){
1386                                                 sort_ping[a] = rsocket->pings[a];
1387                                         }
1388
1389                                         qsort(sort_ping ,MAX_PING_HISTORY, sizeof(float), psnet_rel_ping_compare);
1390                                         rsocket->mean_ping = ((sort_ping[MAX_PING_HISTORY/2]+sort_ping[(MAX_PING_HISTORY/2)+1]))/2;                                     
1391                                 }
1392                                 rsocket->ping_pos++;
1393                                 if(rsocket->ping_pos >= MAX_PING_HISTORY){
1394                                         rsocket->ping_pos=0;                            
1395                                 }
1396
1397                                 // if this is an ack for a send buffer on the socket, kill the send buffer. its done
1398                                 for(i=0; i<MAXNETBUFFERS; i++){
1399                                         unsigned int *acksig = (unsigned int *)&rcv_buff.data;
1400                                         if(rsocket){
1401                                                 if(rsocket->sbuffers[i]){
1402                                                         if(rsocket->ssequence[i] == INTEL_INT(*acksig) ){                                                               
1403                                                                 SDL_assert(rsocket->sbuffers[i] != NULL);
1404                                                                 free(rsocket->sbuffers[i]);
1405                                                                 rsocket->sbuffers[i] = NULL;    
1406                                                                 rsocket->ssequence[i] = 0;
1407                                                         }
1408                                                 }
1409                                         }
1410                                 }
1411                                 //remove that packet from the send buffer
1412                                 rsocket->last_packet_received = psnet_get_time();
1413                                 continue;
1414                         }
1415
1416                         if(rcv_buff.type == RNT_DATA_COMP){
1417                                 //More2Come
1418                                 //Decompress it. Put it back in the buffer. Process it as RNT_DATA
1419                                 rcv_buff.type = RNT_DATA;
1420                         }
1421                         if(rcv_buff.type == RNT_DATA){                          
1422                                 //If the data is out of order by >= MAXNETBUFFERS-1 ignore that packet for now
1423                                 int seqdelta;
1424                                 seqdelta = rcv_buff.seq - rsocket->oursequence;
1425                                 if(seqdelta<0) seqdelta = seqdelta*-1;
1426                                 if(seqdelta>=MAXNETBUFFERS - 1){
1427                                         ml_printf("Received reliable packet out of order!");
1428                                         //It's out of order, so we won't ack it, which will mean we will get it again soon.
1429                                         continue;
1430                                 }
1431                                 //else move data into the proper buffer position
1432                                 int savepacket=1;
1433                                 
1434                                 if(rsocket->oursequence < (0xffff - (MAXNETBUFFERS-1))){
1435                                         if (rsocket->oursequence > rcv_buff.seq){
1436                                                 savepacket = 0;
1437                                         }
1438                                 } else {
1439                                         //Sequence is high, so prepare for wrap around
1440                                         if( ((unsigned short)(rcv_buff.seq + rsocket->oursequence)) > (MAXNETBUFFERS-1)){
1441                                                 savepacket = 0; 
1442                                         }
1443                                 }
1444
1445                                 for(i=0; i<MAXNETBUFFERS; i++){
1446                                         if( (NULL != rsocket->rbuffers[i]) && (rsocket->rsequence[i] == rcv_buff.seq)){
1447                                                 //Received duplicate packet!                                            
1448                                                 savepacket = 0;
1449                                         }
1450                                 }
1451                                 if(savepacket){
1452                                         for(i=0; i<MAXNETBUFFERS; i++){
1453                                                 if(NULL == rsocket->rbuffers[i]){                                                       
1454                                                         if(rcv_buff.data_len>max_len){
1455                                                                 rsocket->recv_len[i] = rcv_buff.data_len;
1456                                                         } else {
1457                                                                 rsocket->recv_len[i] = rcv_buff.data_len; 
1458                                                         }
1459                                                         rsocket->rbuffers[i] = (reliable_net_rcvbuffer *)malloc(sizeof(reliable_net_rcvbuffer));
1460                                                         memcpy(rsocket->rbuffers[i]->buffer,rcv_buff.data,rsocket->recv_len[i]);        
1461                                                         rsocket->rsequence[i] = rcv_buff.seq;                                                   
1462                                                         break;
1463                                                 }
1464                                         }
1465                                 }
1466                                 psnet_rel_send_ack(&rsocket->addr, rcv_buff.seq, link_type, rcv_buff.send_time);                
1467                         }
1468                         
1469                 }
1470         } while (udp_has_data > 0);
1471         
1472         // Go through each reliable socket that is connected and do any needed work.
1473         for(j=0; j<MAXRELIABLESOCKETS; j++){
1474                 rsocket=&Reliable_sockets[j];
1475
1476                 if(Serverconn == 0xffffffff){
1477                         if(rsocket->status==RNF_LIMBO){
1478                                 if(fl_abs((psnet_get_time() - rsocket->last_packet_received))>Nettimeout){
1479                                         ml_printf("Reliable (but in limbo) socket (%d) timed out in nw_WorkReliable().",j);
1480                                         memset(rsocket,0,sizeof(reliable_socket));
1481                                         rsocket->status = RNF_UNUSED;//Won't work if this is an outgoing connection.
1482                                 }
1483                         }
1484                 } else {
1485                         if((rsocket->status == RNF_LIMBO) && (fl_abs((psnet_get_time() - First_sent_iamhere)) > Nettimeout)){
1486                                 rsocket->status = RNF_BROKEN;
1487                                 ml_printf("Reliable socket (%d) timed out in nw_WorkReliable().",j);
1488                         }
1489                 }
1490                 
1491                 if(rsocket->status == RNF_CONNECTED){
1492                         float retry_packet_time;
1493                         if((rsocket->mean_ping==0) || (rsocket->mean_ping > (NETRETRYTIME*4))){
1494                                 retry_packet_time = NETRETRYTIME;
1495                         } else {
1496                                 if(rsocket->mean_ping<MIN_NET_RETRYTIME) {
1497                                         retry_packet_time = (float)MIN_NET_RETRYTIME;                                   
1498                                 } else {
1499                                         retry_packet_time = ((float)(float)rsocket->mean_ping * (float)1.25);                                   
1500                                 }
1501                         }
1502                         //Iterate through send buffers.  
1503                         for(i=0;i<MAXNETBUFFERS;i++){
1504                                 // send again
1505                                 if((rsocket->sbuffers[i]) && (fl_abs((psnet_get_time() - rsocket->timesent[i])) >= retry_packet_time)) {
1506                                         reliable_header send_header;                                    
1507                                         send_header.send_time = psnet_get_time();
1508                                         send_header.send_time = INTEL_FLOAT( send_header.send_time );
1509                                         send_header.seq = INTEL_SHORT( rsocket->ssequence[i] );
1510                                         memcpy(send_header.data,rsocket->sbuffers[i]->buffer,rsocket->send_len[i]);
1511                                         send_header.data_len = INTEL_SHORT( (ushort)rsocket->send_len[i] );
1512                                         send_header.type = RNT_DATA;
1513                                         if(rsocket->connection_type == NET_TCP){
1514                                                 rcode = SENDTO(Unreliable_socket, (char *)&send_header,RELIABLE_PACKET_HEADER_ONLY_SIZE+rsocket->send_len[i],0,&rsocket->addr,sizeof(struct sockaddr), PSNET_TYPE_RELIABLE);
1515                                         }
1516                                         int error = WSAGetLastError();
1517                                         if((rcode == SOCKET_ERROR) && NETCALL_WOULDBLOCK(error)){
1518                                                 //The packet didn't get sent, flag it to try again next frame
1519                                                 rsocket->timesent[i] = psnet_get_time()-(NETRETRYTIME*4);
1520                                         } else {
1521                                                 rsocket->last_packet_sent = psnet_get_time();
1522                                                 rsocket->timesent[i] = psnet_get_time();
1523                                         }
1524                                         
1525                                 }//getcwd
1526                         }
1527
1528                         if((rsocket->status == RNF_CONNECTED) && (fl_abs((psnet_get_time() - rsocket->last_packet_sent)) > NETHEARTBEATTIME)) {
1529                                 reliable_header send_header;                            
1530                                 send_header.send_time = psnet_get_time();
1531                                 send_header.send_time = INTEL_FLOAT( send_header.send_time );
1532                                 send_header.seq = 0;
1533                                 send_header.data_len = 0;
1534                                 send_header.type = RNT_HEARTBEAT;
1535
1536                                 rcode = -1;
1537                                 if(rsocket->connection_type == NET_TCP){
1538                                         rcode = SENDTO(Unreliable_socket, (char *)&send_header,RELIABLE_PACKET_HEADER_ONLY_SIZE,0,&rsocket->addr,sizeof(struct sockaddr), PSNET_TYPE_RELIABLE);
1539                                 }
1540                                 int error = WSAGetLastError();
1541                                 if((rcode != SOCKET_ERROR) && NETCALL_WOULDBLOCK(error)){
1542                                         //It must have been sent
1543                                         rsocket->last_packet_sent = psnet_get_time();
1544                                 }
1545                         }
1546
1547                         if((rsocket->status == RNF_CONNECTED) && (fl_abs((psnet_get_time() - rsocket->last_packet_received))>Nettimeout)){
1548                                 //This socket is hosed.....inform someone?
1549                                 ml_printf("Reliable Socket (%d) timed out in nw_WorkReliable().",j);
1550                                 rsocket->status = RNF_BROKEN;
1551                         }
1552                 }
1553         }       
1554 }
1555
1556 // get the status of a reliable socket, see RNF_* defines above
1557 int psnet_rel_get_status(PSNET_SOCKET_RELIABLE socketid)
1558 {       
1559         if(socketid >= MAXRELIABLESOCKETS){             
1560                 return -1;
1561         }
1562
1563         return Reliable_sockets[socketid].status;
1564 }
1565
1566 // function which checks the Listen_socket for possibly incoming requests to be connected.
1567 // returns 0 on error or nothing waiting.  1 if we should try to accept
1568 int psnet_rel_check_for_listen(net_addr_t *from_addr)
1569 {       
1570         struct sockaddr_in *ip_addr;                            // UDP/TCP socket structure
1571         
1572         psnet_rel_work();
1573         int i;
1574         for(i=1; i<MAXRELIABLESOCKETS; i++){
1575                 if(Reliable_sockets[i].status == RNF_CONNECTING){
1576                         Reliable_sockets[i].status = RNF_CONNECTED;
1577                         //memcpy(from_addr,&reliable_sockets[i].addr,sizeof(struct sockaddr));
1578                         ml_printf("New reliable connection in nw_CheckListenSocket().");
1579                         
1580                         if (Reliable_sockets[i].connection_type != NET_TCP) {
1581                                 continue;
1582                         }
1583
1584                         ip_addr = (struct sockaddr_in *)&Reliable_sockets[i].addr;
1585                         memset(from_addr, 0x00, sizeof(net_addr_t));
1586                         from_addr->port = ntohs( ip_addr->sin_port );
1587                         from_addr->type = NET_TCP;
1588                         memcpy(from_addr->addr, &ip_addr->sin_addr.s_addr, 4);
1589
1590                         /*
1591                         char dbg_output[50];
1592                         nw_GetNumbersFromHostAddress(from_addr,dbg_output);
1593                         mprintf((0,"Got address from: %s\n",dbg_output));
1594                         */
1595                         return i;
1596                 }
1597         }
1598         return INVALID_SOCKET;  
1599 }
1600
1601 // attacmpt to connect() to the server's tcp socket.  socket parameter is simply assigned to the
1602 // Reliable_socket socket created in psnet_init
1603 void psnet_rel_connect_to_server(PSNET_SOCKET *socket, net_addr_t *server_addr)
1604 {       
1605         //Send out a RNT_REQ_CONN packet, and wait for it to be acked.
1606         struct sockaddr_in sockaddr;                            // UDP/TCP socket structure
1607         struct sockaddr *addr = NULL;                                           // pointer to struct sockaddr to make coding easier
1608         struct sockaddr rcv_addr;
1609         int addrlen;
1610         ubyte iaddr[4];
1611         ushort port;
1612 //      float time_sent_req = 0;
1613         float first_sent_req = 0;
1614         static reliable_header conn_header;
1615         static reliable_header ack_header;
1616         int bytesin;
1617         struct timeval timeout;
1618         fd_set read_fds;
1619         int i;
1620         *socket = INVALID_SOCKET;       
1621         
1622         memcpy(iaddr, &server_addr->addr, 4);
1623         port = (ushort)(server_addr->port);     // Talk to the server listen port
1624         
1625         conn_header.type = RNT_REQ_CONN;
1626         conn_header.seq = CONNECTSEQ;
1627         conn_header.data_len = 0;
1628         
1629         timeout.tv_sec=0;            
1630         timeout.tv_usec=0;
1631
1632         if (server_addr->type != NET_TCP) {
1633                 return;
1634         }
1635
1636         SDL_assert(Tcp_active);
1637
1638         //Flush out any left overs
1639         FD_ZERO(&read_fds);
1640         FD_SET(Unreliable_socket, &read_fds);
1641         while(SELECT(Unreliable_socket+1, &read_fds, NULL, NULL, &timeout, PSNET_TYPE_RELIABLE)){
1642                 addrlen = sizeof(struct sockaddr);
1643                 bytesin = RECVFROM(Unreliable_socket, (char *)&ack_header,sizeof(reliable_header),0,(struct sockaddr *)&rcv_addr,&addrlen, PSNET_TYPE_RELIABLE);
1644                 if(bytesin==-1){
1645                         //Int3();//See Kevin
1646                         ml_printf("UDP recvfrom returned an error! -- %d",WSAGetLastError());
1647                         break;
1648                         //return;
1649                 }
1650                 FD_ZERO(&read_fds);
1651                 FD_SET(Unreliable_socket, &read_fds);
1652         }
1653
1654         memset(&ack_header,0,sizeof(reliable_header));
1655         SOCKET typeless_sock = 0;
1656         net_addr_t d3_rcv_addr;
1657         memset(&d3_rcv_addr,0,sizeof(net_addr_t));
1658
1659
1660         sockaddr.sin_family = AF_INET;
1661         memcpy(&sockaddr.sin_addr.s_addr, iaddr, 4);
1662         sockaddr.sin_port = htons(port);
1663         addr = (struct sockaddr *)&sockaddr;
1664         if( SOCKET_ERROR == SENDTO(Unreliable_socket, (char *)&conn_header,RELIABLE_PACKET_HEADER_ONLY_SIZE,0,addr,sizeof(struct sockaddr), PSNET_TYPE_RELIABLE) ){
1665                 ml_printf("Unable to send UDP packet in nw_ConnectToServer()! -- %d",WSAGetLastError());
1666                 return;
1667         }
1668         memcpy(d3_rcv_addr.addr, &sockaddr.sin_addr.s_addr, 4);
1669         d3_rcv_addr.port = sockaddr.sin_port;
1670         d3_rcv_addr.type = NET_TCP;
1671         typeless_sock = Unreliable_socket;
1672
1673
1674         first_sent_req = psnet_get_time();
1675 //      time_sent_req = psnet_get_time();
1676         
1677         //Wait until we get a response from the server or we timeout
1678         
1679         do {
1680                 PSNET_TOP_LAYER_PROCESS();
1681
1682                 FD_ZERO(&read_fds);
1683                 FD_SET(typeless_sock, &read_fds);
1684                 if(SELECT(typeless_sock+1, &read_fds, NULL,NULL,&timeout, PSNET_TYPE_RELIABLE)){
1685                         ml_string("selected() in psnet_rel_connect_to_server()");
1686
1687                         addrlen = sizeof(struct sockaddr);
1688                         bytesin = RECVFROM(typeless_sock,(char *)&ack_header,sizeof(reliable_header),0,(struct sockaddr *)&rcv_addr,&addrlen, PSNET_TYPE_RELIABLE);
1689                         if(bytesin==-1){
1690                                 ml_printf("recvfrom returned an error! -- %d",WSAGetLastError());
1691                                 Int3();//See Kevin
1692                                 return;                         
1693                         }
1694                         
1695                         ml_string("received data after select in psnet_rel_connect_to_server()");
1696                         if(bytesin){    
1697                                 ml_string("about to check ack_header.type");
1698                                 if(ack_header.type == RNT_ACK){
1699                                         short *acknum = (short *)&ack_header.data;
1700                                         if(*acknum == CONNECTSEQ){                                              
1701                                                 for(i=1; i<MAXRELIABLESOCKETS; i++){
1702                                                         if(Reliable_sockets[i].status==RNF_UNUSED){
1703                                                                 //Add the new connection here.
1704                                                                 memset(&Reliable_sockets[i],0,sizeof(reliable_socket));
1705                                                                 Reliable_sockets[i].connection_type = (ubyte)server_addr->type;
1706                                                                 memcpy(&Reliable_sockets[i].net_addr,&d3_rcv_addr,sizeof(net_addr_t));
1707                                                                 Reliable_sockets[i].last_packet_received = psnet_get_time();
1708                                                                 memcpy(&Reliable_sockets[i].addr,&rcv_addr,sizeof(struct sockaddr));
1709                                                                 Reliable_sockets[i].status = RNF_LIMBO;
1710                                                                 *socket = i;
1711                                                                 ml_printf("Succesfully connected to server in nw_ConnectToServer().");
1712                                                                 //Now send I_AM_HERE packet
1713                                                                 conn_header.type = RNT_I_AM_HERE;
1714                                                                 conn_header.seq = (ushort)(~CONNECTSEQ);
1715                                                                 conn_header.data_len = 0;
1716                                                                 Serverconn = i;
1717                                                                 First_sent_iamhere = psnet_get_time();
1718                                                                 Last_sent_iamhere = psnet_get_time();
1719                                                                 int rcode = SENDTO(typeless_sock,(char *)&conn_header,RELIABLE_PACKET_HEADER_ONLY_SIZE,0,addr,sizeof(struct sockaddr), PSNET_TYPE_RELIABLE);
1720                                                                 if(rcode == SOCKET_ERROR){
1721                                                                         *socket = INVALID_SOCKET;
1722                                                                         Reliable_sockets[i].status = RNF_UNUSED;
1723                                                                         memset(&Reliable_sockets[i],0,sizeof(reliable_socket));
1724                                                                         ml_printf("Unable to send packet in nw_ConnectToServer()");
1725                                                                         return;
1726                                                                 }
1727                                                                 Reliable_sockets[i].last_packet_sent = psnet_get_time();
1728                                                                 float f;
1729                                                                 f = psnet_get_time();
1730                                                                 while((fl_abs((psnet_get_time() - f))<2) && (Reliable_sockets[i].status != RNF_CONNECTING)){
1731                                                                         psnet_rel_work();
1732                                                                 }
1733                                                                         
1734                                                                 return;
1735                                                         }
1736                                                 }
1737                                                 ml_printf("Out of reliable socket space in nw_ConnectToServer().");
1738                                                 return;                                         
1739                                         } else ml_printf("Received out of sequence ACK in nw_ConnectToServer().");
1740                                 } else ml_printf("Received something that isn't an ACK in nw_ConnectToServer().");
1741                         } else ml_printf("Received 0 bytes from recvfrom() in nw_ConnectToServer().");
1742                 }
1743                 /*
1744                 if((psnet_get_time()-time_sent_req)>2)
1745                 {
1746                         ml_printf("Resending connect request.");
1747                         int ret = SENDTO(typeless_sock,(char *)&conn_header,RELIABLE_PACKET_HEADER_ONLY_SIZE,0,addr,sizeof(struct sockaddr), PSNET_TYPE_RELIABLE);
1748                         if(ret != SOCKET_ERROR){
1749                                 time_sent_req = psnet_get_time();
1750                         } else {
1751                                 ml_printf("Error sending connection request! -- %d",WSAGetLastError() );
1752                         }
1753                 }
1754                 */
1755
1756         } while(fl_abs((psnet_get_time() - first_sent_req)) < RELIABLE_CONNECT_TIME);   
1757 }
1758
1759 // returns the ip address of this computer
1760 /*
1761 int psnet_rel_get_ip()
1762 {
1763         char local[255];
1764         LPHOSTENT hostent;
1765         struct sockaddr_in local_address;
1766         int ret;
1767         
1768         // Get the local host name
1769         memset(&local_address, 0, sizeof(local_address));
1770         ret = gethostname(local, 255 );
1771         if (ret != SOCKET_ERROR ){
1772                 // Resolve host name for local address
1773                 hostent = gethostbyname((char *)local);
1774                 if ( hostent ){
1775                         local_address.sin_addr.s_addr = *((u_long FAR *)(hostent->h_addr));
1776                 }
1777         } else {
1778                 ml_string("SOCKET_ERROR in psnet_rel_get_ip()!");
1779         }
1780         ml_printf(%s:%d", inet_ntoa(rcvaddr->sin_addr), htons(rcvaddr->sin_port)
1781         return local_address.sin_addr.s_addr;
1782 }
1783 */
1784
1785 // returns the ip address of this computer
1786 int psnet_get_ip()
1787 {       
1788         struct sockaddr_in local_address;
1789
1790         if(Psnet_connection == NETWORK_CONNECTION_DIALUP){      
1791                 local_address.sin_addr.s_addr = psnet_ras_status();
1792                 if(local_address.sin_addr.s_addr == INADDR_NONE){
1793                         local_address.sin_addr.s_addr = INADDR_ANY;
1794                 }
1795         } else {
1796                 // Init local address to zero
1797                 local_address.sin_addr.s_addr = INADDR_ANY;                     
1798         }
1799
1800         // NOTE: for memeory checkers, do NOT try to free this
1801         ml_printf("psnet_get_ip() reports IP : %s", inet_ntoa(local_address.sin_addr));
1802         
1803         return local_address.sin_addr.s_addr;
1804 }
1805
1806 // initialize reliable sockets
1807 int psnet_init_rel_tcp(int port, int should_listen)
1808 {
1809         /*
1810         struct sockaddr_in sockaddr;
1811
1812         sockaddr.sin_port = htons((ushort)port);
1813         sockaddr.sin_family = AF_INET; 
1814         unsigned int my_ip;
1815         ml_printf("Setting up reliable sockets.");
1816
1817         my_ip = psnet_get_ip();
1818
1819         memcpy(&sockaddr.sin_addr.s_addr, &my_ip, sizeof(uint));        
1820                         
1821         Reliable_UDP_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP );
1822         if(INVALID_SOCKET == Reliable_UDP_socket){
1823                 ml_printf("Unable to create reliable UDP socket -- %d", WSAGetLastError() );
1824                 
1825                 return 0;
1826         } else if(bind(Reliable_UDP_socket,(struct sockaddr *)&sockaddr,sizeof(struct sockaddr))!=0){
1827                 ml_printf("Unable to bind reliable socket -- %d", WSAGetLastError() );
1828                 
1829                 return 0;
1830         }       
1831         
1832         // make any reliable sockets which we create that aren't listening non-blocking sockets
1833         int error;
1834         unsigned long arg;
1835
1836         arg = TRUE;
1837         error = ioctlsocket( Reliable_UDP_socket, FIONBIO, &arg );
1838         if ( error == SOCKET_ERROR ) {
1839                 ml_printf("Unable to make reliable UDP socket non-blocking -- %d", WSAGetLastError() );
1840                 
1841                 return 0;
1842         }
1843         */      
1844
1845         // success
1846         return 1;
1847 }
1848
1849 void psnet_rel_close()
1850 {
1851         int idx;
1852         PSNET_SOCKET_RELIABLE sock;
1853
1854         // kill all sockets
1855         for(idx=0; idx<MAXRELIABLESOCKETS; idx++){
1856                 if(Reliable_sockets[idx].status != RNF_UNUSED){
1857                         sock = idx;
1858                         psnet_rel_close_socket(&sock);
1859                 }
1860         }
1861 }
1862
1863 // ------------------------------------------------------------------------------------------------------
1864 // PACKET BUFFERING FUNCTIONS
1865 //
1866
1867 // initialize the buffering system
1868 void psnet_buffer_init(network_packet_buffer_list *l)
1869 {
1870         int idx;
1871         
1872         // blast the buffer clean
1873         memset(l->psnet_buffers, 0, sizeof(network_packet_buffer) * MAX_PACKET_BUFFERS);
1874         
1875         // set all buffer sequence #'s to -1
1876         for(idx=0;idx<MAX_PACKET_BUFFERS;idx++){                
1877                 l->psnet_buffers[idx].sequence_number = -1;
1878         }
1879
1880         // initialize the sequence #
1881         l->psnet_seq_number = 0;
1882         l->psnet_lowest_id = -1;
1883         l->psnet_highest_id = -1;
1884 }
1885
1886 // buffer a packet (maintain order!)
1887 void psnet_buffer_packet(network_packet_buffer_list *l, ubyte *data, int length, net_addr_t *from)
1888 {
1889         int idx;
1890         int found_buf = 0;
1891         
1892         // find the first empty packet
1893         for(idx=0;idx<MAX_PACKET_BUFFERS;idx++){
1894                 if(l->psnet_buffers[idx].sequence_number == -1){
1895                         found_buf = 1;
1896                         break;
1897                 }
1898         }
1899
1900         // if we didn't find the buffer, report an overrun
1901         if(!found_buf){
1902                 ml_printf("WARNING - Buffer overrun in psnet");
1903         } else {
1904                 // copy in the data
1905                 memcpy(l->psnet_buffers[idx].data, data, length);
1906                 l->psnet_buffers[idx].len = length;
1907                 memcpy(&l->psnet_buffers[idx].from_addr, from, sizeof(net_addr_t));
1908                 l->psnet_buffers[idx].sequence_number = l->psnet_seq_number;
1909                 
1910                 // keep track of the highest id#
1911                 l->psnet_highest_id = l->psnet_seq_number++;
1912
1913                 // set the lowest id# for the first time
1914                 if(l->psnet_lowest_id == -1){
1915                         l->psnet_lowest_id = l->psnet_highest_id;
1916                 }
1917         }
1918 }
1919
1920 // get the index of the next packet in order!
1921 int psnet_buffer_get_next(network_packet_buffer_list *l, ubyte *data, int *length, net_addr_t *from)
1922 {       
1923         int idx;
1924
1925         // if there are no buffers, do nothing
1926         if((l->psnet_lowest_id == -1) || (l->psnet_lowest_id > l->psnet_highest_id)){
1927                 return 0;
1928         }
1929
1930         // search until we find the lowest packet index id#
1931         for(idx=0;idx<MAX_PACKET_BUFFERS;idx++){
1932                 // if we found the buffer
1933                 if(l->psnet_buffers[idx].sequence_number == l->psnet_lowest_id){
1934                         break;
1935                 }
1936         }
1937
1938         // at this point, we should _always_ have found the buffer
1939         if (idx == MAX_PACKET_BUFFERS) {
1940                 Int3();
1941                 return 0;
1942         }
1943         
1944         // copy out the buffer data
1945         memcpy(data, l->psnet_buffers[idx].data, l->psnet_buffers[idx].len);
1946         *length = l->psnet_buffers[idx].len;
1947         memcpy(from, &l->psnet_buffers[idx].from_addr, sizeof(net_addr_t));
1948
1949         // now we need to cleanup the packet list
1950
1951         // mark the buffer as free
1952         l->psnet_buffers[idx].sequence_number = -1;
1953         l->psnet_lowest_id++;
1954
1955         return 1;
1956 }
1957
1958 // -------------------------------------------------------------------------------------------------------
1959 // PSNET 2 FORWARD DEFINITIONS
1960 //
1961
1962 // if the string is a legally formatted ip string
1963 int psnet_is_valid_numeric_ip(char *ip)
1964 {
1965         char *token;
1966         char copy[100];
1967         int val1,val2,val3,val4;
1968
1969         // get the first ip value
1970         SDL_strlcpy(copy, ip, SDL_arraysize(copy));
1971         token = strtok(copy,".");
1972         if(token == NULL){
1973                 return 0;
1974         } else {
1975                 // get the value of the token
1976                 val1 = atoi(token);
1977                 if((val1 < 0) || (val1 > 255)){
1978                         return 0;
1979                 }
1980         }
1981
1982         // second ip value
1983         token = strtok(NULL,".");
1984         if(token == NULL){
1985                 return 0;
1986         } else {
1987                 // get the value of the token
1988                 val2 = atoi(token);
1989                 if((val2 < 0) || (val2 > 255)){
1990                         return 0;
1991                 }
1992         }
1993
1994         // third ip value
1995         token = strtok(NULL,".");
1996         if(token == NULL){
1997                 return 0;
1998         } else {
1999                 // get the value of the token
2000                 val3 = atoi(token);
2001                 if((val3 < 0) || (val3 > 255)){
2002                         return 0;
2003                 }
2004         }
2005
2006         // third ip value
2007         token = strtok(NULL,"");
2008         if(token == NULL){
2009                 return 0;
2010         } else {
2011                 // get the value of the token
2012                 val4 = atoi(token);
2013                 if((val4 < 0) || (val4 > 255)){
2014                         return 0;
2015                 }
2016         }
2017
2018         // make sure he hasn't entered all 0's
2019         if((val1 == 0) && (val2 == 0) && (val3 == 0) && (val4 == 0)){
2020                 return 0;
2021         }
2022
2023         // valid
2024         return 1;
2025 }
2026
2027 // function called from high level FreeSpace code to determine the status of the networking
2028 // code returns one of a handful of macros
2029 #ifndef PLAT_UNIX
2030 DWORD (__stdcall *pRasEnumConnections)(LPRASCONN lprasconn, LPDWORD lpcb, LPDWORD lpcConnections) = NULL;
2031 DWORD (__stdcall *pRasGetConnectStatus)(HRASCONN hrasconn, LPRASCONNSTATUS lprasconnstatus ) = NULL;
2032 DWORD (__stdcall *pRasGetProjectionInfo)(HRASCONN hrasconn, RASPROJECTION rasprojection, LPVOID lpprojection, LPDWORD lpcb ) = NULL;
2033
2034 // functions to get the status of a RAS connection
2035 unsigned int psnet_ras_status()
2036 {
2037         int rval;
2038         unsigned long size, num_connections, i;
2039         RASCONN rasbuffer[25];
2040         HINSTANCE ras_handle;
2041         unsigned long rasip=0;
2042         RASPPPIP projection;
2043         // int Ras_connected;
2044
2045         Ras_connected = 0;
2046
2047         // first, call a LoadLibrary to load the RAS api
2048         ras_handle = LoadLibrary( (LPCWSTR)"rasapi32.dll" );
2049         if ( ras_handle == NULL ) {
2050                 return INADDR_ANY;
2051         }
2052
2053         pRasEnumConnections = (DWORD (__stdcall *)(LPRASCONN, LPDWORD, LPDWORD))GetProcAddress(ras_handle, "RasEnumConnectionsA");
2054         if (!pRasEnumConnections)       {
2055                 FreeLibrary( ras_handle );
2056                 return INADDR_ANY;
2057         }
2058         pRasGetConnectStatus = (DWORD (__stdcall *)(HRASCONN, LPRASCONNSTATUS))GetProcAddress(ras_handle, "RasGetConnectStatusA");
2059         if (!pRasGetConnectStatus)      {
2060                 FreeLibrary( ras_handle );
2061                 return INADDR_ANY;
2062         }
2063         pRasGetProjectionInfo = (DWORD (__stdcall *)(HRASCONN, RASPROJECTION, LPVOID, LPDWORD))GetProcAddress(ras_handle, "RasGetProjectionInfoA");
2064         if (!pRasGetProjectionInfo)     {
2065                 FreeLibrary( ras_handle );
2066                 return INADDR_ANY;
2067         }
2068
2069         size = sizeof(rasbuffer);
2070         rasbuffer[0].dwSize = sizeof(RASCONN);
2071
2072         rval = pRasEnumConnections( rasbuffer, &size, &num_connections );
2073         if ( rval ) {
2074                 FreeLibrary( ras_handle );
2075                 return INADDR_ANY;
2076         }
2077
2078         // JAS: My computer gets to this point, but I have no RAS connections,
2079         // so just exit
2080         if ( num_connections < 1 )      {
2081                 ml_string("Found no RAS connections");
2082                 FreeLibrary( ras_handle );
2083                 return INADDR_ANY;
2084         }
2085
2086         ml_printf("Found %d connections", num_connections);
2087
2088         for (i = 0; i < num_connections; i++ ) {
2089                 RASCONNSTATUS status;
2090
2091                 ml_printf("Connection %d:", i);
2092                 ml_printf("Entry Name: %s", rasbuffer[i].szEntryName);
2093                 ml_printf("Device Type: %s", rasbuffer[i].szDeviceType);
2094                 ml_printf("Device Name: %s", rasbuffer[i].szDeviceName);
2095
2096                 // get the connection status
2097                 status.dwSize = sizeof(RASCONNSTATUS);
2098                 rval = pRasGetConnectStatus(rasbuffer[i].hrasconn, &status);
2099                 if ( rval != 0 ) {
2100                         FreeLibrary( ras_handle );
2101                         return INADDR_ANY;
2102                 }
2103
2104                 // get the projection informatiom
2105                 size = sizeof(projection);
2106                 projection.dwSize = size;
2107                 rval = pRasGetProjectionInfo(rasbuffer[i].hrasconn, RASP_PppIp, &projection, &size );
2108                 if ( rval != 0 ) {
2109                         FreeLibrary( ras_handle );
2110                         return INADDR_ANY;
2111                 }
2112
2113                 ml_printf("IP Address: %s", projection.szIpAddress);
2114         }
2115
2116         Ras_connected = 1;
2117
2118         FreeLibrary( ras_handle );
2119         rasip = inet_addr((const char *)projection.szIpAddress);
2120         if(rasip==INADDR_NONE){
2121                 return INADDR_ANY;
2122         }
2123
2124         //The ip of the RAS connection
2125         return rasip;
2126 }
2127 #else
2128 unsigned int psnet_ras_status()
2129 {
2130         STUB_FUNCTION;
2131         
2132         return INADDR_ANY;
2133 }
2134 #endif
2135  
2136 // functions to get the status of a RAS connection
2137 /*
2138 void psnet_ras_status()
2139 {
2140         int rval;
2141         unsigned long size, num_connections, i;
2142         RASCONN rasbuffer[25];
2143         HINSTANCE ras_handle;
2144
2145         Ras_connected = 0;
2146
2147         // first, call a LoadLibrary to load the RAS api
2148         ras_handle = LoadLibrary( NOX("rasapi32.dll") );
2149         if ( ras_handle == NULL ) {
2150                 return;
2151         }
2152
2153         pRasEnumConnections = (DWORD (__stdcall *)(LPRASCONN, LPDWORD, LPDWORD))GetProcAddress(ras_handle, NOX("RasEnumConnectionsA"));
2154         if (!pRasEnumConnections)       {
2155                 FreeLibrary( ras_handle );
2156                 return;
2157         }
2158         pRasGetConnectStatus = (DWORD (__stdcall *)(HRASCONN, LPRASCONNSTATUS))GetProcAddress(ras_handle, NOX("RasGetConnectStatusA"));
2159         if (!pRasGetConnectStatus)      {
2160                 FreeLibrary( ras_handle );
2161                 return;
2162         }
2163         pRasGetProjectionInfo = (DWORD (__stdcall *)(HRASCONN, RASPROJECTION, LPVOID, LPDWORD))GetProcAddress(ras_handle, NOX("RasGetProjectionInfoA"));
2164         if (!pRasGetProjectionInfo)     {
2165                 FreeLibrary( ras_handle );
2166                 return;
2167         }
2168
2169         size = sizeof(rasbuffer);
2170         rasbuffer[0].dwSize = sizeof(RASCONN);
2171
2172         rval = pRasEnumConnections( rasbuffer, &size, &num_connections );
2173         if ( rval ) {
2174                 FreeLibrary( ras_handle );
2175                 return;
2176         }
2177
2178         // JAS: My computer gets to this point, but I have no RAS connections,
2179         // so just exit
2180         if ( num_connections < 1 )      {
2181                 ml_printf("Found no connections" );
2182                 FreeLibrary( ras_handle );
2183                 return;
2184         }
2185
2186         ml_printf("Found %d connections", num_connections);
2187
2188         for (i = 0; i < num_connections; i++ ) {
2189                 RASCONNSTATUS status;
2190                 RASPPPIP projection;
2191                 unsigned long size;
2192
2193                 ml_printf("Connection %d:", i);
2194                 ml_printf("Entry Name: %s", rasbuffer[i].szEntryName);
2195                 ml_printf("Device Type: %s", rasbuffer[i].szDeviceType);
2196                 ml_printf("Device Name: %s", rasbuffer[i].szDeviceName);
2197
2198                 // get the connection status
2199                 status.dwSize = sizeof(RASCONNSTATUS);
2200                 rval = pRasGetConnectStatus(rasbuffer[i].hrasconn, &status);
2201                 if ( rval != 0 ) {
2202                         FreeLibrary( ras_handle );
2203                         return;
2204                 }
2205
2206                 ml_printf("\tStatus: %s", (status.rasconnstate==RASCS_Connected)?"Connected":"Not Connected");
2207
2208                 // get the projection informatiom
2209                 size = sizeof(projection);
2210                 projection.dwSize = size;
2211                 rval = pRasGetProjectionInfo(rasbuffer[i].hrasconn, RASP_PppIp, &projection, &size );
2212                 if ( rval != 0 ) {
2213                         FreeLibrary( ras_handle );
2214                         return;
2215                 }
2216
2217                 ml_printf("IP Address: %s", projection.szIpAddress));
2218         }
2219
2220         Ras_connected = 1;
2221
2222         FreeLibrary( ras_handle );
2223 }
2224 */
2225
2226 // set some options on a socket
2227 void psnet_socket_options( SOCKET sock )
2228 {
2229         int broadcast;//, ret;
2230         SOCKLEN_T cursize, cursizesize, bufsize;
2231
2232         // Set the mode of the socket to allow broadcasting
2233         broadcast = 1;
2234         if(setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char *)&broadcast, sizeof(broadcast) )){
2235                 Can_broadcast = 0;
2236         } else {
2237                 Can_broadcast = 1;
2238         }
2239
2240         // reuseaddr
2241         // setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&broadcast, sizeof(broadcast) );
2242
2243         // try and increase the size of my receive buffer
2244         bufsize = MAX_RECEIVE_BUFSIZE;
2245         
2246         // set the current size of the receive buffer
2247         cursizesize = sizeof(int);
2248         getsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char *)&cursize, &cursizesize);
2249         // for ( trysize = bufsize; trysize >= cursize; trysize >>= 1 ) {
2250         /*ret =*/ setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char *)&bufsize, sizeof(bufsize));
2251         /*if ( ret == SOCKET_ERROR ) {
2252                 int wserr;
2253
2254                 wserr = WSAGetLastError();
2255                 // if ( (wserr == WSAENOPROTOOPT) || (wserr == WSAEINVAL) )
2256                         // break;
2257         }*/
2258         // }
2259         getsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char *)&cursize, &cursizesize);
2260         ml_printf("Receive buffer set to %d", cursize);
2261
2262         // set the current size of the send buffer
2263         cursizesize = sizeof(int);
2264         getsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *)&cursize, &cursizesize);
2265         // for ( trysize = bufsize; trysize >= cursize; trysize >>= 1 ) {
2266         /*ret =*/ setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *)&bufsize, sizeof(bufsize));
2267         /*if ( ret == SOCKET_ERROR ) {
2268                 int wserr;
2269
2270                 wserr = WSAGetLastError();
2271                 // if ( (wserr == WSAENOPROTOOPT) || (wserr == WSAEINVAL) ){
2272                         // break;
2273                 // }
2274         }*/
2275         getsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *)&cursize, &cursizesize);
2276         ml_printf("Send buffer set to %d", cursize);
2277 }
2278
2279 // initialize tcp socket
2280 int psnet_init_tcp()
2281 {       
2282         struct sockaddr_in sockaddr;
2283
2284         TCP_socket = INVALID_SOCKET;    
2285         
2286         TCP_socket = socket( AF_INET, SOCK_DGRAM, 0 );
2287         if ( TCP_socket == (int)INVALID_SOCKET ) {
2288                 Tcp_failure_code = WSAGetLastError();
2289                 ml_printf("Error on TCP startup %d", Tcp_failure_code);
2290                 return 0;
2291         }
2292
2293         // bind the socket
2294         memset(&sockaddr,0,sizeof(struct sockaddr_in));
2295         sockaddr.sin_family = AF_INET; 
2296         sockaddr.sin_addr.s_addr = psnet_get_ip();
2297         sockaddr.sin_port = htons( Psnet_default_port );
2298         if ( bind(TCP_socket, (struct sockaddr*)&sockaddr, sizeof (sockaddr)) == SOCKET_ERROR) {
2299                 Tcp_failure_code = WSAGetLastError();
2300                 ml_printf("Couldn't bind TCP socket (%d)! Invalidating TCP", Tcp_failure_code );
2301                 return 0;
2302         }
2303
2304         // set socket options
2305         psnet_socket_options( TCP_socket );             
2306         Tcp_can_broadcast = Can_broadcast;
2307
2308         // success
2309         return 1;
2310 }
2311
2312 // get time in seconds
2313 float psnet_get_time()
2314 {               
2315         return (float)timer_get_milliseconds() / 1000.0f;
2316 }
2317
2318 // mark a socket as having received data
2319 void psnet_mark_received(PSNET_SOCKET_RELIABLE socket)
2320 {
2321         // valid socket?
2322         if((socket == 0xffffffff) || (socket >= MAXRELIABLESOCKETS)){
2323                 return;
2324         }
2325
2326         // mark it
2327         Reliable_sockets[socket].last_packet_received = psnet_get_time();
2328 }
2329
2330 #endif  //  if PSNET2
2331