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