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