corrected some svc_nop's to clc_nop's (same value but more correct)
[divverent/darkplaces.git] / netconn.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3 Copyright (C) 2002 Mathieu Olivier
4 Copyright (C) 2003 Forest Hale
5
6 This program is free software; you can redistribute it and/or
7 modify it under the terms of the GNU General Public License
8 as published by the Free Software Foundation; either version 2
9 of the License, or (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14
15 See the GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
20
21 */
22
23 #include "quakedef.h"
24 #include "lhnet.h"
25
26 #define QWMASTER_PORT 27000
27 #define DPMASTER_PORT 27950
28
29 // note this defaults on for dedicated servers, off for listen servers
30 cvar_t sv_public = {0, "sv_public", "0", "advertises this server on the master server (so that players can find it in the server browser)"};
31 static cvar_t sv_heartbeatperiod = {CVAR_SAVE, "sv_heartbeatperiod", "120", "how often to send heartbeat in seconds (only used if sv_public is 1)"};
32
33 static cvar_t sv_masters [] =
34 {
35         {CVAR_SAVE, "sv_master1", "", "user-chosen master server 1"},
36         {CVAR_SAVE, "sv_master2", "", "user-chosen master server 2"},
37         {CVAR_SAVE, "sv_master3", "", "user-chosen master server 3"},
38         {CVAR_SAVE, "sv_master4", "", "user-chosen master server 4"},
39         {0, "sv_masterextra1", "ghdigital.com", "default master server 1 (admin: LordHavoc)"}, // admin: LordHavoc
40         {0, "sv_masterextra2", "dpmaster.deathmask.net", "default master server 2 (admin: Willis)"}, // admin: Willis
41         {0, "sv_masterextra3", "12.166.196.192", "default master server 3 (admin: Venim)"}, // admin: Venim
42         {0, "sv_masterextra4", "excalibur.nvg.ntnu.no", "default master server 4 (admin: tChr)"}, // admin: tChr
43         {0, NULL, NULL, NULL}
44 };
45
46 static cvar_t sv_qwmasters [] =
47 {
48         {CVAR_SAVE, "sv_qwmaster1", "", "user-chosen qwmaster server 1"},
49         {CVAR_SAVE, "sv_qwmaster2", "", "user-chosen qwmaster server 2"},
50         {CVAR_SAVE, "sv_qwmaster3", "", "user-chosen qwmaster server 3"},
51         {CVAR_SAVE, "sv_qwmaster4", "", "user-chosen qwmaster server 4"},
52         {0, "sv_qwmasterextra1", "192.246.40.37:27000", "id Limbo (admin: id Software)"},
53         {0, "sv_qwmasterextra2", "192.246.40.37:27002", "id CTF (admin: id Software)"},
54         {0, "sv_qwmasterextra3", "192.246.40.37:27003", "id TeamFortress (admin: id Software)"},
55         {0, "sv_qwmasterextra4", "192.246.40.37:27004", "id Miscilaneous (admin: id Software)"},
56         {0, "sv_qwmasterextra5", "192.246.40.37:27006", "id Deathmatch Only (admin: id Software)"},
57         {0, "sv_qwmasterextra6", "150.254.66.120:27000", "Poland's master server. (admin: unknown)"},
58         {0, "sv_qwmasterextra7", "62.112.145.129:27000", "Ocrana master server. (admin: unknown)"},
59         {0, "sv_qwmasterextra8", "master.edome.net", "edome master server. (admin: unknown)"},
60         {0, "sv_qwmasterextra9", "qwmaster.barrysworld.com", "barrysworld master server. (admin: unknown)"},
61         {0, "sv_qwmasterextra10", "qwmaster.ocrana.de:27000", "Ocrana2 master server. (admin: unknown)"},
62         {0, "sv_qwmasterextra11", "213.221.174.165:27000", "unknown1 master server. (admin: unknown)"},
63         {0, "sv_qwmasterextra12", "195.74.0.8", "unknown2 master server. (admin: unknown)"},
64         {0, "sv_qwmasterextra13", "204.182.161.2", "unknown3 master server. (admin: unknown)"},
65         {0, NULL, NULL, NULL}
66 };
67
68 static double nextheartbeattime = 0;
69
70 sizebuf_t net_message;
71 static unsigned char net_message_buf[NET_MAXMESSAGE];
72
73 cvar_t net_messagetimeout = {0, "net_messagetimeout","300", "drops players who have not sent any packets for this many seconds"};
74 cvar_t net_connecttimeout = {0, "net_connecttimeout","10", "after requesting a connection, the client must reply within this many seconds or be dropped (cuts down on connect floods)"};
75 cvar_t net_connectfloodblockingtimeout = {0, "net_connectfloodblockingtimeout", "5", "when a connection packet is received, it will block all future connect packets from that IP address for this many seconds (cuts down on connect floods)"};
76 cvar_t hostname = {CVAR_SAVE, "hostname", "UNNAMED", "server message to show in server browser"};
77 cvar_t developer_networking = {0, "developer_networking", "0", "prints all received and sent packets (recommended only for debugging)"};
78
79 cvar_t cl_netlocalping = {0, "cl_netlocalping","0", "lags local loopback connection by this much ping time (useful to play more fairly on your own server with people with higher pings)"};
80 static cvar_t cl_netpacketloss = {0, "cl_netpacketloss","0", "drops this percentage of packets (incoming and outgoing), useful for testing network protocol robustness (effects failing to start, sounds failing to play, etc)"};
81 static cvar_t net_slist_queriespersecond = {0, "net_slist_queriespersecond", "20", "how many server information requests to send per second"};
82 static cvar_t net_slist_queriesperframe = {0, "net_slist_queriesperframe", "4", "maximum number of server information requests to send each rendered frame (guards against low framerates causing problems)"};
83 static cvar_t net_slist_timeout = {0, "net_slist_timeout", "4", "how long to listen for a server information response before giving up"};
84 static cvar_t net_slist_maxtries = {0, "net_slist_maxtries", "3", "how many times to ask the same server for information (more times gives better ping reports but takes longer)"};
85
86 static cvar_t gameversion = {0, "gameversion", "0", "version of game data (mod-specific), when client and server gameversion mismatch in the server browser the server is shown as incompatible"};
87
88 /* statistic counters */
89 static int packetsSent = 0;
90 static int packetsReSent = 0;
91 static int packetsReceived = 0;
92 static int receivedDuplicateCount = 0;
93 static int droppedDatagrams = 0;
94
95 static int unreliableMessagesSent = 0;
96 static int unreliableMessagesReceived = 0;
97 static int reliableMessagesSent = 0;
98 static int reliableMessagesReceived = 0;
99
100 double masterquerytime = -1000;
101 int masterquerycount = 0;
102 int masterreplycount = 0;
103 int serverquerycount = 0;
104 int serverreplycount = 0;
105
106 // this is only false if there are still servers left to query
107 static qboolean serverlist_querysleep = true;
108 // this is pushed a second or two ahead of realtime whenever a master server
109 // reply is received, to avoid issuing queries while master replies are still
110 // flooding in (which would make a mess of the ping times)
111 static double serverlist_querywaittime = 0;
112
113 static unsigned char sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
114 static unsigned char readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
115
116 static int cl_numsockets;
117 static lhnetsocket_t *cl_sockets[16];
118 static int sv_numsockets;
119 static lhnetsocket_t *sv_sockets[16];
120
121 netconn_t *netconn_list = NULL;
122 mempool_t *netconn_mempool = NULL;
123
124 cvar_t cl_netport = {0, "cl_port", "0", "forces client to use chosen port number if not 0"};
125 cvar_t sv_netport = {0, "port", "26000", "server port for players to connect to"};
126 cvar_t net_address = {0, "net_address", "0.0.0.0", "network address to open ports on"};
127 //cvar_t net_netaddress_ipv6 = {0, "net_address_ipv6", "[0:0:0:0:0:0:0:0]", "network address to open ipv6 ports on"};
128
129 // ServerList interface
130 serverlist_mask_t serverlist_andmasks[SERVERLIST_ANDMASKCOUNT];
131 serverlist_mask_t serverlist_ormasks[SERVERLIST_ORMASKCOUNT];
132
133 serverlist_infofield_t serverlist_sortbyfield;
134 qboolean serverlist_sortdescending;
135
136 int serverlist_viewcount = 0;
137 serverlist_entry_t *serverlist_viewlist[SERVERLIST_VIEWLISTSIZE];
138
139 int serverlist_cachecount;
140 serverlist_entry_t serverlist_cache[SERVERLIST_TOTALSIZE];
141
142 qboolean serverlist_consoleoutput;
143
144 // helper function to insert a value into the viewset
145 // spare entries will be removed
146 static void _ServerList_ViewList_Helper_InsertBefore( int index, serverlist_entry_t *entry )
147 {
148     int i;
149         if( serverlist_viewcount < SERVERLIST_VIEWLISTSIZE ) {
150                 i = serverlist_viewcount++;
151         } else {
152                 i = SERVERLIST_VIEWLISTSIZE - 1;
153         }
154
155         for( ; i > index ; i-- )
156                 serverlist_viewlist[ i ] = serverlist_viewlist[ i - 1 ];
157
158         serverlist_viewlist[index] = entry;
159 }
160
161 // we suppose serverlist_viewcount to be valid, ie > 0
162 static void _ServerList_ViewList_Helper_Remove( int index )
163 {
164         serverlist_viewcount--;
165         for( ; index < serverlist_viewcount ; index++ )
166                 serverlist_viewlist[index] = serverlist_viewlist[index + 1];
167 }
168
169 // returns true if A should be inserted before B
170 static qboolean _ServerList_Entry_Compare( serverlist_entry_t *A, serverlist_entry_t *B )
171 {
172         int result = 0; // > 0 if for numbers A > B and for text if A < B
173
174         switch( serverlist_sortbyfield ) {
175                 case SLIF_PING:
176                         result = A->info.ping - B->info.ping;
177                         break;
178                 case SLIF_MAXPLAYERS:
179                         result = A->info.maxplayers - B->info.maxplayers;
180                         break;
181                 case SLIF_NUMPLAYERS:
182                         result = A->info.numplayers - B->info.numplayers;
183                         break;
184                 case SLIF_PROTOCOL:
185                         result = A->info.protocol - B->info.protocol;
186                         break;
187                 case SLIF_CNAME:
188                         result = strcmp( B->info.cname, A->info.cname );
189                         break;
190                 case SLIF_GAME:
191                         result = strcmp( B->info.game, A->info.game );
192                         break;
193                 case SLIF_MAP:
194                         result = strcmp( B->info.map, A->info.map );
195                         break;
196                 case SLIF_MOD:
197                         result = strcmp( B->info.mod, A->info.mod );
198                         break;
199                 case SLIF_NAME:
200                         result = strcmp( B->info.name, A->info.name );
201                         break;
202                 default:
203                         Con_DPrint( "_ServerList_Entry_Compare: Bad serverlist_sortbyfield!\n" );
204                         break;
205         }
206
207         if( serverlist_sortdescending )
208                 return result > 0;
209         if (result != 0)
210                 return result < 0;
211         // if the chosen sort key is identical, sort by index
212         // (makes this a stable sort, so that later replies from servers won't
213         //  shuffle the servers around when they have the same ping)
214         return A < B;
215 }
216
217 static qboolean _ServerList_CompareInt( int A, serverlist_maskop_t op, int B )
218 {
219         // This should actually be done with some intermediate and end-of-function return
220         switch( op ) {
221                 case SLMO_LESS:
222                         return A < B;
223                 case SLMO_LESSEQUAL:
224                         return A <= B;
225                 case SLMO_EQUAL:
226                         return A == B;
227                 case SLMO_GREATER:
228                         return A > B;
229                 case SLMO_NOTEQUAL:
230                         return A != B;
231                 case SLMO_GREATEREQUAL:
232                 case SLMO_CONTAINS:
233                 case SLMO_NOTCONTAIN:
234                         return A >= B;
235                 default:
236                         Con_DPrint( "_ServerList_CompareInt: Bad op!\n" );
237                         return false;
238         }
239 }
240
241 static qboolean _ServerList_CompareStr( const char *A, serverlist_maskop_t op, const char *B )
242 {
243         int i;
244         char bufferA[ 256 ], bufferB[ 256 ]; // should be more than enough
245         for (i = 0;i < (int)sizeof(bufferA)-1 && A[i];i++)
246                 bufferA[i] = (A[i] >= 'A' && A[i] <= 'Z') ? (A[i] + 'a' - 'A') : A[i];
247         bufferA[i] = 0;
248         for (i = 0;i < (int)sizeof(bufferB)-1 && B[i];i++)
249                 bufferB[i] = (B[i] >= 'A' && B[i] <= 'Z') ? (B[i] + 'a' - 'A') : B[i];
250         bufferB[i] = 0;
251
252         // Same here, also using an intermediate & final return would be more appropriate
253         // A info B mask
254         switch( op ) {
255                 case SLMO_CONTAINS:
256                         return *bufferB && !!strstr( bufferA, bufferB ); // we want a real bool
257                 case SLMO_NOTCONTAIN:
258                         return !*bufferB || !strstr( bufferA, bufferB );
259                 case SLMO_LESS:
260                         return strcmp( bufferA, bufferB ) < 0;
261                 case SLMO_LESSEQUAL:
262                         return strcmp( bufferA, bufferB ) <= 0;
263                 case SLMO_EQUAL:
264                         return strcmp( bufferA, bufferB ) == 0;
265                 case SLMO_GREATER:
266                         return strcmp( bufferA, bufferB ) > 0;
267                 case SLMO_NOTEQUAL:
268                         return strcmp( bufferA, bufferB ) != 0;
269                 case SLMO_GREATEREQUAL:
270                         return strcmp( bufferA, bufferB ) >= 0;
271                 default:
272                         Con_DPrint( "_ServerList_CompareStr: Bad op!\n" );
273                         return false;
274         }
275 }
276
277 static qboolean _ServerList_Entry_Mask( serverlist_mask_t *mask, serverlist_info_t *info )
278 {
279         if( !_ServerList_CompareInt( info->ping, mask->tests[SLIF_PING], mask->info.ping ) )
280                 return false;
281         if( !_ServerList_CompareInt( info->maxplayers, mask->tests[SLIF_MAXPLAYERS], mask->info.maxplayers ) )
282                 return false;
283         if( !_ServerList_CompareInt( info->numplayers, mask->tests[SLIF_NUMPLAYERS], mask->info.numplayers ) )
284                 return false;
285         if( !_ServerList_CompareInt( info->protocol, mask->tests[SLIF_PROTOCOL], mask->info.protocol ))
286                 return false;
287         if( *mask->info.cname
288                 && !_ServerList_CompareStr( info->cname, mask->tests[SLIF_CNAME], mask->info.cname ) )
289                 return false;
290         if( *mask->info.game
291                 && !_ServerList_CompareStr( info->game, mask->tests[SLIF_GAME], mask->info.game ) )
292                 return false;
293         if( *mask->info.mod
294                 && !_ServerList_CompareStr( info->mod, mask->tests[SLIF_MOD], mask->info.mod ) )
295                 return false;
296         if( *mask->info.map
297                 && !_ServerList_CompareStr( info->map, mask->tests[SLIF_MAP], mask->info.map ) )
298                 return false;
299         if( *mask->info.name
300                 && !_ServerList_CompareStr( info->name, mask->tests[SLIF_NAME], mask->info.name ) )
301                 return false;
302         return true;
303 }
304
305 static void ServerList_ViewList_Insert( serverlist_entry_t *entry )
306 {
307         int start, end, mid;
308
309         // reject incompatible servers
310         if (entry->info.gameversion != gameversion.integer)
311                 return;
312
313         // FIXME: change this to be more readable (...)
314         // now check whether it passes through the masks
315         for( start = 0 ; serverlist_andmasks[start].active && start < SERVERLIST_ANDMASKCOUNT ; start++ )
316                 if( !_ServerList_Entry_Mask( &serverlist_andmasks[start], &entry->info ) )
317                         return;
318
319         for( start = 0 ; serverlist_ormasks[start].active && start < SERVERLIST_ORMASKCOUNT ; start++ )
320                 if( _ServerList_Entry_Mask( &serverlist_ormasks[start], &entry->info ) )
321                         break;
322         if( start == SERVERLIST_ORMASKCOUNT || (start > 0 && !serverlist_ormasks[start].active) )
323                 return;
324
325         if( !serverlist_viewcount ) {
326                 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
327                 return;
328         }
329         // ok, insert it, we just need to find out where exactly:
330
331         // two special cases
332         // check whether to insert it as new first item
333         if( _ServerList_Entry_Compare( entry, serverlist_viewlist[0] ) ) {
334                 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
335                 return;
336         } // check whether to insert it as new last item
337         else if( !_ServerList_Entry_Compare( entry, serverlist_viewlist[serverlist_viewcount - 1] ) ) {
338                 _ServerList_ViewList_Helper_InsertBefore( serverlist_viewcount, entry );
339                 return;
340         }
341         start = 0;
342         end = serverlist_viewcount - 1;
343         while( end > start + 1 )
344         {
345                 mid = (start + end) / 2;
346                 // test the item that lies in the middle between start and end
347                 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[mid] ) )
348                         // the item has to be in the upper half
349                         end = mid;
350                 else
351                         // the item has to be in the lower half
352                         start = mid;
353         }
354         _ServerList_ViewList_Helper_InsertBefore( start + 1, entry );
355 }
356
357 static void ServerList_ViewList_Remove( serverlist_entry_t *entry )
358 {
359         int i;
360         for( i = 0; i < serverlist_viewcount; i++ )
361         {
362                 if (serverlist_viewlist[i] == entry)
363                 {
364                         _ServerList_ViewList_Helper_Remove(i);
365                         break;
366                 }
367         }
368 }
369
370 void ServerList_RebuildViewList(void)
371 {
372         int i;
373
374         serverlist_viewcount = 0;
375         for( i = 0 ; i < serverlist_cachecount ; i++ )
376                 if( serverlist_cache[i].query == SQS_QUERIED )
377                         ServerList_ViewList_Insert( &serverlist_cache[i] );
378 }
379
380 void ServerList_ResetMasks(void)
381 {
382         memset( &serverlist_andmasks, 0, sizeof( serverlist_andmasks ) );
383         memset( &serverlist_ormasks, 0, sizeof( serverlist_ormasks ) );
384 }
385
386 #if 0
387 static void _ServerList_Test(void)
388 {
389         int i;
390         for( i = 0 ; i < 1024 ; i++ ) {
391                 memset( &serverlist_cache[serverlist_cachecount], 0, sizeof( serverlist_entry_t ) );
392                 serverlist_cache[serverlist_cachecount].info.ping = 1000 + 1024 - i;
393                 dpsnprintf( serverlist_cache[serverlist_cachecount].info.name, sizeof(serverlist_cache[serverlist_cachecount].info.name), "Black's ServerList Test %i", i );
394                 serverlist_cache[serverlist_cachecount].finished = true;
395                 sprintf( serverlist_cache[serverlist_cachecount].line1, "%i %s", serverlist_cache[serverlist_cachecount].info.ping, serverlist_cache[serverlist_cachecount].info.name );
396                 ServerList_ViewList_Insert( &serverlist_cache[serverlist_cachecount] );
397                 serverlist_cachecount++;
398         }
399 }
400 #endif
401
402 void ServerList_QueryList(qboolean querydp, qboolean queryqw)
403 {
404         //masterquerytime = realtime;
405         masterquerytime = Sys_DoubleTime();
406         masterquerycount = 0;
407         masterreplycount = 0;
408         serverquerycount = 0;
409         serverreplycount = 0;
410         serverlist_cachecount = 0;
411         serverlist_viewcount = 0;
412         serverlist_consoleoutput = false;
413
414         //_ServerList_Test();
415
416         NetConn_QueryMasters(querydp, queryqw);
417 }
418
419 // rest
420
421 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
422 {
423         int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
424         int i;
425         if (length == 0)
426                 return 0;
427         if (cl_netpacketloss.integer)
428                 for (i = 0;i < cl_numsockets;i++)
429                         if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
430                                 return 0;
431         if (developer_networking.integer)
432         {
433                 char addressstring[128], addressstring2[128];
434                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
435                 if (length > 0)
436                 {
437                         LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
438                         Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", mysocket, addressstring, data, maxlength, peeraddress, length, addressstring2);
439                         Com_HexDumpToConsole((unsigned char *)data, length);
440                 }
441                 else
442                         Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
443         }
444         return length;
445 }
446
447 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
448 {
449         int ret;
450         int i;
451         if (cl_netpacketloss.integer)
452                 for (i = 0;i < cl_numsockets;i++)
453                         if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
454                                 return length;
455         ret = LHNET_Write(mysocket, data, length, peeraddress);
456         if (developer_networking.integer)
457         {
458                 char addressstring[128], addressstring2[128];
459                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
460                 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
461                 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", mysocket, addressstring, data, length, peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
462                 Com_HexDumpToConsole((unsigned char *)data, length);
463         }
464         return ret;
465 }
466
467 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
468 {
469         // note this does not include the trailing NULL because we add that in the parser
470         return NetConn_Write(mysocket, string, (int)strlen(string), peeraddress);
471 }
472
473 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data, protocolversion_t protocol)
474 {
475         if (protocol == PROTOCOL_QUAKEWORLD)
476         {
477                 int packetLen;
478                 qboolean sendreliable;
479
480                 // note that it is ok to send empty messages to the qw server,
481                 // otherwise it won't respond to us at all
482
483                 sendreliable = false;
484                 // if the remote side dropped the last reliable message, resend it
485                 if (conn->qw.incoming_acknowledged > conn->qw.last_reliable_sequence && conn->qw.incoming_reliable_acknowledged != conn->qw.reliable_sequence)
486                         sendreliable = true;
487                 // if the reliable transmit buffer is empty, copy the current message out
488                 if (!conn->sendMessageLength && conn->message.cursize)
489                 {
490                         memcpy (conn->sendMessage, conn->message.data, conn->message.cursize);
491                         conn->sendMessageLength = conn->message.cursize;
492                         SZ_Clear(&conn->message); // clear the message buffer
493                         conn->qw.reliable_sequence ^= 1;
494                         sendreliable = true;
495                 }
496                 // outgoing unreliable packet number, and outgoing reliable packet number (0 or 1)
497                 *((int *)(sendbuffer + 0)) = LittleLong((unsigned int)conn->qw.outgoing_sequence | ((unsigned int)sendreliable<<31));
498                 // last received unreliable packet number, and last received reliable packet number (0 or 1)
499                 *((int *)(sendbuffer + 4)) = LittleLong((unsigned int)conn->qw.incoming_sequence | ((unsigned int)conn->qw.incoming_reliable_sequence<<31));
500                 packetLen = 8;
501                 conn->qw.outgoing_sequence++;
502                 // client sends qport in every packet
503                 if (conn == cls.netcon)
504                 {
505                         *((short *)(sendbuffer + 8)) = LittleShort(cls.qw_qport);
506                         packetLen += 2;
507                         // also update cls.qw_outgoing_sequence
508                         cls.qw_outgoing_sequence = conn->qw.outgoing_sequence;
509                 }
510                 if (packetLen + (sendreliable ? conn->sendMessageLength : 0) > 1400)
511                 {
512                         Con_Printf ("NetConn_SendUnreliableMessage: reliable message too big %u\n", data->cursize);
513                         return -1;
514                 }
515                 // add the reliable message if there is one
516                 if (sendreliable)
517                 {
518                         memcpy(sendbuffer + packetLen, conn->sendMessage, conn->sendMessageLength);
519                         packetLen += conn->sendMessageLength;
520                         conn->qw.last_reliable_sequence = conn->qw.outgoing_sequence;
521                 }
522                 // add the unreliable message if possible
523                 if (packetLen + data->cursize <= 1400)
524                 {
525                         memcpy(sendbuffer + packetLen, data->data, data->cursize);
526                         packetLen += data->cursize;
527                 }
528
529                 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
530
531                 packetsSent++;
532                 unreliableMessagesSent++;
533
534                 // delay later packets to obey rate limit
535                 conn->qw.cleartime = max(conn->qw.cleartime, realtime) + packetLen * conn->qw.rate;
536
537                 return 0;
538         }
539         else
540         {
541                 unsigned int packetLen;
542                 unsigned int dataLen;
543                 unsigned int eom;
544                 unsigned int *header;
545
546                 // if a reliable message fragment has been lost, send it again
547                 if (conn->sendMessageLength && (realtime - conn->lastSendTime) > 1.0)
548                 {
549                         if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
550                         {
551                                 dataLen = conn->sendMessageLength;
552                                 eom = NETFLAG_EOM;
553                         }
554                         else
555                         {
556                                 dataLen = MAX_PACKETFRAGMENT;
557                                 eom = 0;
558                         }
559
560                         packetLen = NET_HEADERSIZE + dataLen;
561
562                         header = (unsigned int *)sendbuffer;
563                         header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
564                         header[1] = BigLong(conn->nq.sendSequence - 1);
565                         memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
566
567                         if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
568                         {
569                                 conn->lastSendTime = realtime;
570                                 packetsReSent++;
571                         }
572                 }
573
574                 // if we have a new reliable message to send, do so
575                 if (!conn->sendMessageLength && conn->message.cursize)
576                 {
577                         if (conn->message.cursize > (int)sizeof(conn->sendMessage))
578                         {
579                                 Con_Printf("NetConn_SendUnreliableMessage: reliable message too big (%u > %u)\n", conn->message.cursize, sizeof(conn->sendMessage));
580                                 conn->message.overflowed = true;
581                                 return -1;
582                         }
583
584                         if (developer_networking.integer && conn == cls.netcon)
585                         {
586                                 Con_Print("client sending reliable message to server:\n");
587                                 SZ_HexDumpToConsole(&conn->message);
588                         }
589
590                         memcpy(conn->sendMessage, conn->message.data, conn->message.cursize);
591                         conn->sendMessageLength = conn->message.cursize;
592                         SZ_Clear(&conn->message);
593
594                         if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
595                         {
596                                 dataLen = conn->sendMessageLength;
597                                 eom = NETFLAG_EOM;
598                         }
599                         else
600                         {
601                                 dataLen = MAX_PACKETFRAGMENT;
602                                 eom = 0;
603                         }
604
605                         packetLen = NET_HEADERSIZE + dataLen;
606
607                         header = (unsigned int *)sendbuffer;
608                         header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
609                         header[1] = BigLong(conn->nq.sendSequence);
610                         memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
611
612                         conn->nq.sendSequence++;
613
614                         NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
615
616                         conn->lastSendTime = realtime;
617                         packetsSent++;
618                         reliableMessagesSent++;
619                 }
620
621                 // if we have an unreliable message to send, do so
622                 if (data->cursize)
623                 {
624                         packetLen = NET_HEADERSIZE + data->cursize;
625
626                         if (packetLen > (int)sizeof(sendbuffer))
627                         {
628                                 Con_Printf("NetConn_SendUnreliableMessage: message too big %u\n", data->cursize);
629                                 return -1;
630                         }
631
632                         header = (unsigned int *)sendbuffer;
633                         header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
634                         header[1] = BigLong(conn->nq.unreliableSendSequence);
635                         memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
636
637                         conn->nq.unreliableSendSequence++;
638
639                         NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
640
641                         packetsSent++;
642                         unreliableMessagesSent++;
643                 }
644                 return 0;
645         }
646 }
647
648 void NetConn_CloseClientPorts(void)
649 {
650         for (;cl_numsockets > 0;cl_numsockets--)
651                 if (cl_sockets[cl_numsockets - 1])
652                         LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
653 }
654
655 void NetConn_OpenClientPort(const char *addressstring, int defaultport)
656 {
657         lhnetaddress_t address;
658         lhnetsocket_t *s;
659         char addressstring2[1024];
660         if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
661         {
662                 if ((s = LHNET_OpenSocket_Connectionless(&address)))
663                 {
664                         cl_sockets[cl_numsockets++] = s;
665                         LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
666                         Con_Printf("Client opened a socket on address %s\n", addressstring2);
667                 }
668                 else
669                 {
670                         LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
671                         Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
672                 }
673         }
674         else
675                 Con_Printf("Client unable to parse address %s\n", addressstring);
676 }
677
678 void NetConn_OpenClientPorts(void)
679 {
680         int port;
681         NetConn_CloseClientPorts();
682         port = bound(0, cl_netport.integer, 65535);
683         if (cl_netport.integer != port)
684                 Cvar_SetValueQuick(&cl_netport, port);
685         Con_Printf("Client using port %i\n", port);
686         NetConn_OpenClientPort("local:2", 0);
687         NetConn_OpenClientPort(net_address.string, port);
688         //NetConn_OpenClientPort(net_address_ipv6.string, port);
689 }
690
691 void NetConn_CloseServerPorts(void)
692 {
693         for (;sv_numsockets > 0;sv_numsockets--)
694                 if (sv_sockets[sv_numsockets - 1])
695                         LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
696 }
697
698 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
699 {
700         lhnetaddress_t address;
701         lhnetsocket_t *s;
702         int port;
703         char addressstring2[1024];
704
705         for (port = defaultport; port <= defaultport + 100; port++)
706         {
707                 if (LHNETADDRESS_FromString(&address, addressstring, port))
708                 {
709                         if ((s = LHNET_OpenSocket_Connectionless(&address)))
710                         {
711                                 sv_sockets[sv_numsockets++] = s;
712                                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
713                                 Con_Printf("Server listening on address %s\n", addressstring2);
714                                 break;
715                         }
716                         else
717                         {
718                                 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
719                                 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
720                         }
721                 }
722                 else
723                 {
724                         Con_Printf("Server unable to parse address %s\n", addressstring);
725                         // if it cant parse one address, it wont be able to parse another for sure
726                         break;
727                 }
728         }
729 }
730
731 void NetConn_OpenServerPorts(int opennetports)
732 {
733         int port;
734         NetConn_CloseServerPorts();
735         NetConn_UpdateSockets();
736         port = bound(0, sv_netport.integer, 65535);
737         if (port == 0)
738                 port = 26000;
739         Con_Printf("Server using port %i\n", port);
740         if (sv_netport.integer != port)
741                 Cvar_SetValueQuick(&sv_netport, port);
742         if (cls.state != ca_dedicated)
743                 NetConn_OpenServerPort("local:1", 0);
744         if (opennetports)
745         {
746                 NetConn_OpenServerPort(net_address.string, port);
747                 //NetConn_OpenServerPort(net_address_ipv6.string, port);
748         }
749         if (sv_numsockets == 0)
750                 Host_Error("NetConn_OpenServerPorts: unable to open any ports!");
751 }
752
753 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
754 {
755         int i, a = LHNETADDRESS_GetAddressType(address);
756         for (i = 0;i < cl_numsockets;i++)
757                 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
758                         return cl_sockets[i];
759         return NULL;
760 }
761
762 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
763 {
764         int i, a = LHNETADDRESS_GetAddressType(address);
765         for (i = 0;i < sv_numsockets;i++)
766                 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
767                         return sv_sockets[i];
768         return NULL;
769 }
770
771 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
772 {
773         netconn_t *conn;
774         conn = (netconn_t *)Mem_Alloc(netconn_mempool, sizeof(*conn));
775         conn->mysocket = mysocket;
776         conn->peeraddress = *peeraddress;
777         conn->lastMessageTime = realtime;
778         conn->message.data = conn->messagedata;
779         conn->message.maxsize = sizeof(conn->messagedata);
780         conn->message.cursize = 0;
781         // LordHavoc: (inspired by ProQuake) use a short connect timeout to
782         // reduce effectiveness of connection request floods
783         conn->timeout = realtime + net_connecttimeout.value;
784         LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
785         conn->next = netconn_list;
786         netconn_list = conn;
787         return conn;
788 }
789
790 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress);
791 void NetConn_Close(netconn_t *conn)
792 {
793         netconn_t *c;
794         // remove connection from list
795
796         // allow the client to reconnect immediately
797         NetConn_ClearConnectFlood(&(conn->peeraddress));
798
799         if (conn == netconn_list)
800                 netconn_list = conn->next;
801         else
802         {
803                 for (c = netconn_list;c;c = c->next)
804                 {
805                         if (c->next == conn)
806                         {
807                                 c->next = conn->next;
808                                 break;
809                         }
810                 }
811                 // not found in list, we'll avoid crashing here...
812                 if (!c)
813                         return;
814         }
815         // free connection
816         Mem_Free(conn);
817 }
818
819 static int clientport = -1;
820 static int clientport2 = -1;
821 static int hostport = -1;
822 void NetConn_UpdateSockets(void)
823 {
824         if (cls.state != ca_dedicated)
825         {
826                 if (clientport2 != cl_netport.integer)
827                 {
828                         clientport2 = cl_netport.integer;
829                         if (cls.state == ca_connected)
830                                 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
831                 }
832                 if (cls.state == ca_disconnected && clientport != clientport2)
833                 {
834                         clientport = clientport2;
835                         NetConn_CloseClientPorts();
836                 }
837                 if (cl_numsockets == 0)
838                         NetConn_OpenClientPorts();
839         }
840
841         if (hostport != sv_netport.integer)
842         {
843                 hostport = sv_netport.integer;
844                 if (sv.active)
845                         Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
846         }
847 }
848
849 static int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int length, protocolversion_t protocol, double newtimeout)
850 {
851         if (length < 8)
852                 return 0;
853
854         // TODO: add netgraph stuff rather than just packetloss counting...
855
856         if (protocol == PROTOCOL_QUAKEWORLD)
857         {
858                 int sequence, sequence_ack;
859                 int reliable_ack, reliable_message;
860                 int count;
861                 int qport;
862
863                 sequence = LittleLong(*((int *)(data + 0)));
864                 sequence_ack = LittleLong(*((int *)(data + 4)));
865                 data += 8;
866                 length -= 8;
867
868                 if (conn != cls.netcon)
869                 {
870                         // server only
871                         if (length < 2)
872                                 return 0;
873                         // TODO: use qport to identify that this client really is who they say they are?  (and elsewhere in the code to identify the connection without a port match?)
874                         qport = LittleShort(*((int *)(data + 8)));
875                         data += 2;
876                         length -= 2;
877                 }
878
879                 packetsReceived++;
880                 reliable_message = (sequence >> 31) & 1;
881                 reliable_ack = (sequence_ack >> 31) & 1;
882                 sequence &= ~(1<<31);
883                 sequence_ack &= ~(1<<31);
884                 if (sequence <= conn->qw.incoming_sequence)
885                 {
886                         //Con_DPrint("Got a stale datagram\n");
887                         return 0;
888                 }
889                 count = sequence - (conn->qw.incoming_sequence + 1);
890                 if (count > 0)
891                 {
892                         droppedDatagrams += count;
893                         //Con_DPrintf("Dropped %u datagram(s)\n", count);
894                         while (count--)
895                         {
896                                 conn->packetlost[conn->packetlostcounter] = true;
897                                 conn->packetlostcounter = (conn->packetlostcounter + 1) % 100;
898                         }
899                 }
900                 conn->packetlost[conn->packetlostcounter] = false;
901                 conn->packetlostcounter = (conn->packetlostcounter + 1) % 100;
902                 if (reliable_ack == conn->qw.reliable_sequence)
903                 {
904                         // received, now we will be able to send another reliable message
905                         conn->sendMessageLength = 0;
906                         reliableMessagesReceived++;
907                 }
908                 conn->qw.incoming_sequence = sequence;
909                 if (conn == cls.netcon)
910                         cls.qw_incoming_sequence = conn->qw.incoming_sequence;
911                 conn->qw.incoming_acknowledged = sequence_ack;
912                 conn->qw.incoming_reliable_acknowledged = reliable_ack;
913                 if (reliable_message)
914                         conn->qw.incoming_reliable_sequence ^= 1;
915                 conn->lastMessageTime = realtime;
916                 conn->timeout = realtime + newtimeout;
917                 unreliableMessagesReceived++;
918                 SZ_Clear(&net_message);
919                 SZ_Write(&net_message, data, length);
920                 MSG_BeginReading();
921                 return 2;
922         }
923         else
924         {
925                 unsigned int count;
926                 unsigned int flags;
927                 unsigned int sequence;
928                 int qlength;
929
930                 qlength = (unsigned int)BigLong(((int *)data)[0]);
931                 flags = qlength & ~NETFLAG_LENGTH_MASK;
932                 qlength &= NETFLAG_LENGTH_MASK;
933                 // control packets were already handled
934                 if (!(flags & NETFLAG_CTL) && qlength == length)
935                 {
936                         sequence = BigLong(((int *)data)[1]);
937                         packetsReceived++;
938                         data += 8;
939                         length -= 8;
940                         if (flags & NETFLAG_UNRELIABLE)
941                         {
942                                 if (sequence >= conn->nq.unreliableReceiveSequence)
943                                 {
944                                         if (sequence > conn->nq.unreliableReceiveSequence)
945                                         {
946                                                 count = sequence - conn->nq.unreliableReceiveSequence;
947                                                 droppedDatagrams += count;
948                                                 //Con_DPrintf("Dropped %u datagram(s)\n", count);
949                                                 while (count--)
950                                                 {
951                                                         conn->packetlost[conn->packetlostcounter] = true;
952                                                         conn->packetlostcounter = (conn->packetlostcounter + 1) % 100;
953                                                 }
954                                         }
955                                         conn->packetlost[conn->packetlostcounter] = false;
956                                         conn->packetlostcounter = (conn->packetlostcounter + 1) % 100;
957                                         conn->nq.unreliableReceiveSequence = sequence + 1;
958                                         conn->lastMessageTime = realtime;
959                                         conn->timeout = realtime + newtimeout;
960                                         unreliableMessagesReceived++;
961                                         if (length > 0)
962                                         {
963                                                 SZ_Clear(&net_message);
964                                                 SZ_Write(&net_message, data, length);
965                                                 MSG_BeginReading();
966                                                 return 2;
967                                         }
968                                 }
969                                 //else
970                                 //      Con_DPrint("Got a stale datagram\n");
971                                 return 1;
972                         }
973                         else if (flags & NETFLAG_ACK)
974                         {
975                                 if (sequence == (conn->nq.sendSequence - 1))
976                                 {
977                                         if (sequence == conn->nq.ackSequence)
978                                         {
979                                                 conn->nq.ackSequence++;
980                                                 if (conn->nq.ackSequence != conn->nq.sendSequence)
981                                                         Con_DPrint("ack sequencing error\n");
982                                                 conn->lastMessageTime = realtime;
983                                                 conn->timeout = realtime + newtimeout;
984                                                 if (conn->sendMessageLength > MAX_PACKETFRAGMENT)
985                                                 {
986                                                         unsigned int packetLen;
987                                                         unsigned int dataLen;
988                                                         unsigned int eom;
989                                                         unsigned int *header;
990
991                                                         conn->sendMessageLength -= MAX_PACKETFRAGMENT;
992                                                         memcpy(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
993
994                                                         if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
995                                                         {
996                                                                 dataLen = conn->sendMessageLength;
997                                                                 eom = NETFLAG_EOM;
998                                                         }
999                                                         else
1000                                                         {
1001                                                                 dataLen = MAX_PACKETFRAGMENT;
1002                                                                 eom = 0;
1003                                                         }
1004
1005                                                         packetLen = NET_HEADERSIZE + dataLen;
1006
1007                                                         header = (unsigned int *)sendbuffer;
1008                                                         header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
1009                                                         header[1] = BigLong(conn->nq.sendSequence);
1010                                                         memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
1011
1012                                                         conn->nq.sendSequence++;
1013
1014                                                         if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
1015                                                         {
1016                                                                 conn->lastSendTime = realtime;
1017                                                                 packetsSent++;
1018                                                         }
1019                                                 }
1020                                                 else
1021                                                         conn->sendMessageLength = 0;
1022                                         }
1023                                         //else
1024                                         //      Con_DPrint("Duplicate ACK received\n");
1025                                 }
1026                                 //else
1027                                 //      Con_DPrint("Stale ACK received\n");
1028                                 return 1;
1029                         }
1030                         else if (flags & NETFLAG_DATA)
1031                         {
1032                                 unsigned int temppacket[2];
1033                                 temppacket[0] = BigLong(8 | NETFLAG_ACK);
1034                                 temppacket[1] = BigLong(sequence);
1035                                 NetConn_Write(conn->mysocket, (unsigned char *)temppacket, 8, &conn->peeraddress);
1036                                 if (sequence == conn->nq.receiveSequence)
1037                                 {
1038                                         conn->lastMessageTime = realtime;
1039                                         conn->timeout = realtime + newtimeout;
1040                                         conn->nq.receiveSequence++;
1041                                         if( conn->receiveMessageLength + length <= (int)sizeof( conn->receiveMessage ) ) {
1042                                                 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
1043                                                 conn->receiveMessageLength += length;
1044                                         } else {
1045                                                 Con_Printf( "Reliable message (seq: %i) too big for message buffer!\n"
1046                                                                         "Dropping the message!\n", sequence );
1047                                                 conn->receiveMessageLength = 0;
1048                                                 return 1;
1049                                         }
1050                                         if (flags & NETFLAG_EOM)
1051                                         {
1052                                                 reliableMessagesReceived++;
1053                                                 length = conn->receiveMessageLength;
1054                                                 conn->receiveMessageLength = 0;
1055                                                 if (length > 0)
1056                                                 {
1057                                                         SZ_Clear(&net_message);
1058                                                         SZ_Write(&net_message, conn->receiveMessage, length);
1059                                                         MSG_BeginReading();
1060                                                         return 2;
1061                                                 }
1062                                         }
1063                                 }
1064                                 else
1065                                         receivedDuplicateCount++;
1066                                 return 1;
1067                         }
1068                 }
1069         }
1070         return 0;
1071 }
1072
1073 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, protocolversion_t initialprotocol)
1074 {
1075         cls.connect_trying = false;
1076         M_Update_Return_Reason("");
1077         // the connection request succeeded, stop current connection and set up a new connection
1078         CL_Disconnect();
1079         // if we're connecting to a remote server, shut down any local server
1080         if (LHNETADDRESS_GetAddressType(peeraddress) != LHNETADDRESSTYPE_LOOP && sv.active)
1081                 Host_ShutdownServer ();
1082         // allocate a net connection to keep track of things
1083         cls.netcon = NetConn_Open(mysocket, peeraddress);
1084         Con_Printf("Connection accepted to %s\n", cls.netcon->address);
1085         key_dest = key_game;
1086         m_state = m_none;
1087         cls.demonum = -1;                       // not in the demo loop now
1088         cls.state = ca_connected;
1089         cls.signon = 0;                         // need all the signon messages before playing
1090         cls.protocol = initialprotocol;
1091         if (cls.protocol == PROTOCOL_QUAKEWORLD)
1092                 Cmd_ForwardStringToServer("new");
1093         if (cls.protocol == PROTOCOL_QUAKE)
1094         {
1095                 // write a keepalive (clc_nop) as it seems to greatly improve the
1096                 // chances of connecting to a netquake server
1097                 sizebuf_t msg;
1098                 unsigned char buf[4];
1099                 memset(&msg, 0, sizeof(msg));
1100                 msg.data = buf;
1101                 msg.maxsize = sizeof(buf);
1102                 MSG_WriteChar(&msg, clc_nop);
1103                 NetConn_SendUnreliableMessage(cls.netcon, &msg, cls.protocol);
1104         }
1105 }
1106
1107 int NetConn_IsLocalGame(void)
1108 {
1109         if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
1110                 return true;
1111         return false;
1112 }
1113
1114 static int NetConn_ClientParsePacket_ServerList_ProcessReply(const char *addressstring)
1115 {
1116         int n;
1117         int pingtime;
1118         // search the cache for this server and update it
1119         for (n = 0;n < serverlist_cachecount;n++)
1120                 if (!strcmp(addressstring, serverlist_cache[n].info.cname))
1121                         break;
1122         if (n == serverlist_cachecount)
1123         {
1124                 // LAN search doesnt require an answer from the master server so we wont
1125                 // know the ping nor will it be initialized already...
1126
1127                 // find a slot
1128                 if (serverlist_cachecount == SERVERLIST_TOTALSIZE)
1129                         return -1;
1130
1131                 memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
1132                 // store the data the engine cares about (address and ping)
1133                 strlcpy(serverlist_cache[serverlist_cachecount].info.cname, addressstring, sizeof(serverlist_cache[serverlist_cachecount].info.cname));
1134                 serverlist_cache[serverlist_cachecount].info.ping = 100000;
1135                 //serverlist_cache[serverlist_cachecount].querytime = realtime;
1136                 serverlist_cache[serverlist_cachecount].querytime = Sys_DoubleTime();
1137                 // if not in the slist menu we should print the server to console
1138                 if (serverlist_consoleoutput)
1139                         Con_Printf("querying %s\n", addressstring);
1140                 ++serverlist_cachecount;
1141         }
1142         // if this is the first reply from this server, count it as having replied
1143         if (serverlist_cache[n].info.ping == 100000)
1144                 serverreplycount++;
1145         pingtime = (int)((Sys_DoubleTime() - serverlist_cache[n].querytime) * 1000.0 + 0.5);
1146         pingtime = bound(0, pingtime, 9999);
1147         // update the ping
1148         serverlist_cache[n].info.ping = min(serverlist_cache[n].info.ping, pingtime);
1149         // other server info is updated by the caller
1150         return n;
1151 }
1152
1153 static void NetConn_ClientParsePacket_ServerList_UpdateCache(int n)
1154 {
1155         serverlist_info_t *info = &serverlist_cache[n].info;
1156         // update description strings for engine menu and console output
1157         dpsnprintf(serverlist_cache[n].line1, sizeof(serverlist_cache[n].line1), "^%c%5d^7 ^%c%3u^7/%3u %-65.65s", info->ping >= 300 ? '1' : (info->ping >= 200 ? '3' : '7'), (int)info->ping, ((info->numplayers > 0 && info->numplayers < info->maxplayers) ? (info->numplayers >= 4 ? '7' : '3') : '1'), info->numplayers, info->maxplayers, info->name);
1158         dpsnprintf(serverlist_cache[n].line2, sizeof(serverlist_cache[n].line2), "^4%-21.21s %-19.19s ^%c%-17.17s^4 %-20.20s", info->cname, info->game, (info->gameversion != gameversion.integer) ? '1' : '4', info->mod, info->map);
1159         if (serverlist_cache[n].query == SQS_QUERIED)
1160                 ServerList_ViewList_Remove(&serverlist_cache[n]);
1161         // if not in the slist menu we should print the server to console (if wanted)
1162         else if( serverlist_consoleoutput )
1163                 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1164         // and finally, update the view set
1165         ServerList_ViewList_Insert( &serverlist_cache[n] );
1166         serverlist_cache[n].query = SQS_QUERIED;
1167 }
1168
1169 static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1170 {
1171         qboolean fromserver;
1172         int ret, c, control;
1173         const char *s;
1174         char *string, addressstring2[128], ipstring[32];
1175         char stringbuf[16384];
1176
1177         // quakeworld ingame packet
1178         fromserver = cls.netcon && mysocket == cls.netcon->mysocket && !LHNETADDRESS_Compare(&cls.netcon->peeraddress, peeraddress);
1179
1180         // convert the address to a string incase we need it
1181         LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1182
1183         if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1184         {
1185                 // received a command string - strip off the packaging and put it
1186                 // into our string buffer with NULL termination
1187                 data += 4;
1188                 length -= 4;
1189                 length = min(length, (int)sizeof(stringbuf) - 1);
1190                 memcpy(stringbuf, data, length);
1191                 stringbuf[length] = 0;
1192                 string = stringbuf;
1193
1194                 if (developer_networking.integer)
1195                 {
1196                         Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
1197                         Com_HexDumpToConsole(data, length);
1198                 }
1199
1200                 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
1201                 {
1202                         // darkplaces or quake3
1203                         char protocolnames[1400];
1204                         Protocol_Names(protocolnames, sizeof(protocolnames));
1205                         Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
1206                         M_Update_Return_Reason("Got challenge response");
1207                         // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1208                         InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1209                         // TODO: add userinfo stuff here instead of using NQ commands?
1210                         NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\protocols\\%s\\challenge\\%s", protocolnames, string + 10), peeraddress);
1211                         return true;
1212                 }
1213                 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
1214                 {
1215                         // darkplaces or quake3
1216                         M_Update_Return_Reason("Accepted");
1217                         NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_DARKPLACES3);
1218                         return true;
1219                 }
1220                 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
1221                 {
1222                         char rejectreason[32];
1223                         cls.connect_trying = false;
1224                         string += 7;
1225                         length = max(length - 7, (int)sizeof(rejectreason) - 1);
1226                         memcpy(rejectreason, string, length);
1227                         rejectreason[length] = 0;
1228                         M_Update_Return_Reason(rejectreason);
1229                         return true;
1230                 }
1231                 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
1232                 {
1233                         serverlist_info_t *info;
1234                         int n;
1235
1236                         string += 13;
1237                         // search the cache for this server and update it
1238                         n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1239                         if (n < 0)
1240                                 return true;
1241
1242                         info = &serverlist_cache[n].info;
1243                         if ((s = SearchInfostring(string, "gamename"     )) != NULL) strlcpy(info->game, s, sizeof (info->game));else info->game[0] = 0;
1244                         if ((s = SearchInfostring(string, "modname"      )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0]  = 0;
1245                         if ((s = SearchInfostring(string, "mapname"      )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0]  = 0;
1246                         if ((s = SearchInfostring(string, "hostname"     )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
1247                         if ((s = SearchInfostring(string, "protocol"     )) != NULL) info->protocol = atoi(s);else info->protocol = -1;
1248                         if ((s = SearchInfostring(string, "clients"      )) != NULL) info->numplayers = atoi(s);else info->numplayers = 0;
1249                         if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);else info->maxplayers  = 0;
1250                         if ((s = SearchInfostring(string, "gameversion"  )) != NULL) info->gameversion = atoi(s);else info->gameversion = 0;
1251
1252                         NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1253
1254                         return true;
1255                 }
1256                 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1257                 {
1258                         // Extract the IP addresses
1259                         data += 18;
1260                         length -= 18;
1261                         masterreplycount++;
1262                         if (serverlist_consoleoutput)
1263                                 Con_Print("received DarkPlaces server list...\n");
1264                         while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
1265                         {
1266                                 int n;
1267
1268                                 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], data[5] * 256 + data[6]);
1269                                 if (serverlist_consoleoutput && developer_networking.integer)
1270                                         Con_Printf("Requesting info from DarkPlaces server %s\n", ipstring);
1271                                 // ignore the rest of the message if the serverlist is full
1272                                 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1273                                         break;
1274                                 // also ignore it if we have already queried it (other master server response)
1275                                 for( n = 0 ; n < serverlist_cachecount ; n++ )
1276                                         if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1277                                                 break;
1278                                 if( n >= serverlist_cachecount )
1279                                 {
1280                                         serverquerycount++;
1281
1282                                         memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
1283                                         serverlist_cache[serverlist_cachecount].protocol = PROTOCOL_DARKPLACES7;
1284                                         // store the data the engine cares about (address and ping)
1285                                         strlcpy (serverlist_cache[serverlist_cachecount].info.cname, ipstring, sizeof (serverlist_cache[serverlist_cachecount].info.cname));
1286                                         serverlist_cache[serverlist_cachecount].info.ping = 100000;
1287                                         serverlist_cache[serverlist_cachecount].query = SQS_QUERYING;
1288
1289                                         ++serverlist_cachecount;
1290                                 }
1291
1292                                 // move on to next address in packet
1293                                 data += 7;
1294                                 length -= 7;
1295                         }
1296                         // begin or resume serverlist queries
1297                         serverlist_querysleep = false;
1298                         serverlist_querywaittime = realtime + 3;
1299                         return true;
1300                 }
1301                 if (!memcmp(string, "d\n", 2) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1302                 {
1303                         // Extract the IP addresses
1304                         data += 2;
1305                         length -= 2;
1306                         masterreplycount++;
1307                         if (serverlist_consoleoutput)
1308                                 Con_Printf("received QuakeWorld server list from %s...\n", addressstring2);
1309                         while (length >= 6 && (data[0] != 0xFF || data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF) && data[4] * 256 + data[5] != 0)
1310                         {
1311                                 int n;
1312
1313                                 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[0], data[1], data[2], data[3], data[4] * 256 + data[5]);
1314                                 if (serverlist_consoleoutput && developer_networking.integer)
1315                                         Con_Printf("Requesting info from QuakeWorld server %s\n", ipstring);
1316                                 // ignore the rest of the message if the serverlist is full
1317                                 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1318                                         break;
1319                                 // also ignore it if we have already queried it (other master server response)
1320                                 for( n = 0 ; n < serverlist_cachecount ; n++ )
1321                                         if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1322                                                 break;
1323                                 if( n >= serverlist_cachecount )
1324                                 {
1325                                         serverquerycount++;
1326
1327                                         memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
1328                                         serverlist_cache[serverlist_cachecount].protocol = PROTOCOL_QUAKEWORLD;
1329                                         // store the data the engine cares about (address and ping)
1330                                         strlcpy (serverlist_cache[serverlist_cachecount].info.cname, ipstring, sizeof (serverlist_cache[serverlist_cachecount].info.cname));
1331                                         serverlist_cache[serverlist_cachecount].info.ping = 100000;
1332                                         serverlist_cache[serverlist_cachecount].query = SQS_QUERYING;
1333
1334                                         ++serverlist_cachecount;
1335                                 }
1336
1337                                 // move on to next address in packet
1338                                 data += 6;
1339                                 length -= 6;
1340                         }
1341                         // begin or resume serverlist queries
1342                         serverlist_querysleep = false;
1343                         serverlist_querywaittime = realtime + 3;
1344                         return true;
1345                 }
1346                 if (!strncmp(string, "ping", 4))
1347                 {
1348                         if (developer.integer >= 10)
1349                                 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
1350                         NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1351                         return true;
1352                 }
1353                 if (!strncmp(string, "ack", 3))
1354                         return true;
1355                 // QuakeWorld compatibility
1356                 if (length > 1 && string[0] == 'c' && (string[1] == '-' || (string[1] >= '0' && string[1] <= '9')) && cls.connect_trying)
1357                 {
1358                         // challenge message
1359                         Con_Printf("challenge %s received, sending QuakeWorld connect request back to %s\n", string + 1, addressstring2);
1360                         M_Update_Return_Reason("Got QuakeWorld challenge response");
1361                         cls.qw_qport = qport.integer;
1362                         // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1363                         InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1364                         NetConn_WriteString(mysocket, va("\377\377\377\377connect %i %i %i \"%s\"\n", 28, cls.qw_qport, atoi(string + 1), cls.userinfo), peeraddress);
1365                         return true;
1366                 }
1367                 if (length >= 1 && string[0] == 'j' && cls.connect_trying)
1368                 {
1369                         // accept message
1370                         M_Update_Return_Reason("QuakeWorld Accepted");
1371                         NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_QUAKEWORLD);
1372                         return true;
1373                 }
1374                 if (length > 2 && !memcmp(string, "n\\", 2))
1375                 {
1376                         serverlist_info_t *info;
1377                         int n;
1378
1379                         // qw server status
1380                         if (serverlist_consoleoutput && developer_networking.integer >= 2)
1381                                 Con_Printf("QW server status from server at %s:\n%s\n", addressstring2, string + 1);
1382
1383                         string += 1;
1384                         // search the cache for this server and update it
1385                         n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1386                         if (n < 0)
1387                                 return true;
1388
1389                         info = &serverlist_cache[n].info;
1390                         strlcpy(info->game, "QuakeWorld", sizeof(info->game));;
1391                         if ((s = SearchInfostring(string, "*gamedir"     )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0]  = 0;
1392                         if ((s = SearchInfostring(string, "map"          )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0]  = 0;
1393                         if ((s = SearchInfostring(string, "hostname"     )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
1394                         info->protocol = 0;
1395                         info->numplayers = 0; // updated below
1396                         if ((s = SearchInfostring(string, "maxclients"   )) != NULL) info->maxplayers = atoi(s);else info->maxplayers  = 0;
1397                         if ((s = SearchInfostring(string, "gameversion"  )) != NULL) info->gameversion = atoi(s);else info->gameversion = 0;
1398
1399                         // count active players on server
1400                         // (we could gather more info, but we're just after the number)
1401                         s = strchr(string, '\n');
1402                         if (s)
1403                         {
1404                                 s++;
1405                                 while (s < string + length)
1406                                 {
1407                                         for (;s < string + length && *s != '\n';s++)
1408                                                 ;
1409                                         if (s >= string + length)
1410                                                 break;
1411                                         info->numplayers++;
1412                                         s++;
1413                                 }
1414                         }
1415
1416                         NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1417
1418                         return true;
1419                 }
1420                 if (string[0] == 'n')
1421                 {
1422                         // qw print command
1423                         Con_Printf("QW print command from server at %s:\n%s\n", addressstring2, string + 1);
1424                 }
1425                 // we may not have liked the packet, but it was a command packet, so
1426                 // we're done processing this packet now
1427                 return true;
1428         }
1429         // quakeworld ingame packet
1430         if (fromserver && cls.protocol == PROTOCOL_QUAKEWORLD && length >= 8 && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1431         {
1432                 ret = 0;
1433                 CL_ParseServerMessage();
1434                 return ret;
1435         }
1436         // netquake control packets, supported for compatibility only
1437         if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1438         {
1439                 int n;
1440                 serverlist_info_t *info;
1441
1442                 c = data[4];
1443                 data += 5;
1444                 length -= 5;
1445                 switch (c)
1446                 {
1447                 case CCREP_ACCEPT:
1448                         if (developer.integer >= 10)
1449                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1450                         if (cls.connect_trying)
1451                         {
1452                                 lhnetaddress_t clientportaddress;
1453                                 clientportaddress = *peeraddress;
1454                                 if (length >= 4)
1455                                 {
1456                                         unsigned int port = (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
1457                                         data += 4;
1458                                         length -= 4;
1459                                         LHNETADDRESS_SetPort(&clientportaddress, port);
1460                                 }
1461                                 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1462                                 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1463                                 M_Update_Return_Reason("Accepted");
1464                                 NetConn_ConnectionEstablished(mysocket, &clientportaddress, PROTOCOL_QUAKE);
1465                         }
1466                         break;
1467                 case CCREP_REJECT:
1468                         if (developer.integer >= 10)
1469                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1470                         cls.connect_trying = false;
1471                         M_Update_Return_Reason((char *)data);
1472                         break;
1473                 case CCREP_SERVER_INFO:
1474                         if (developer.integer >= 10)
1475                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1476                         // LordHavoc: because the quake server may report weird addresses
1477                         // we just ignore it and keep the real address
1478                         MSG_ReadString();
1479                         // search the cache for this server and update it
1480                         n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1481                         if (n < 0)
1482                                 break;
1483
1484                         info = &serverlist_cache[n].info;
1485                         strlcpy(info->game, "Quake", sizeof(info->game));
1486                         strlcpy(info->mod , "", sizeof(info->mod)); // mod name is not specified
1487                         strlcpy(info->name, MSG_ReadString(), sizeof(info->name));
1488                         strlcpy(info->map , MSG_ReadString(), sizeof(info->map));
1489                         info->numplayers = MSG_ReadByte();
1490                         info->maxplayers = MSG_ReadByte();
1491                         info->protocol = MSG_ReadByte();
1492
1493                         NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1494
1495                         break;
1496                 case CCREP_PLAYER_INFO:
1497                         // we got a CCREP_PLAYER_INFO??
1498                         //if (developer.integer >= 10)
1499                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1500                         break;
1501                 case CCREP_RULE_INFO:
1502                         // we got a CCREP_RULE_INFO??
1503                         //if (developer.integer >= 10)
1504                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1505                         break;
1506                 default:
1507                         break;
1508                 }
1509                 // we may not have liked the packet, but it was a valid control
1510                 // packet, so we're done processing this packet now
1511                 return true;
1512         }
1513         ret = 0;
1514         if (fromserver && length >= (int)NET_HEADERSIZE && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1515                 CL_ParseServerMessage();
1516         return ret;
1517 }
1518
1519 void NetConn_QueryQueueFrame(void)
1520 {
1521         int index;
1522         int queries;
1523         int maxqueries;
1524         double timeouttime;
1525         static double querycounter = 0;
1526
1527         if (serverlist_querysleep)
1528                 return;
1529
1530         // apply a cool down time after master server replies,
1531         // to avoid messing up the ping times on the servers
1532         if (serverlist_querywaittime > realtime)
1533                 return;
1534
1535         // each time querycounter reaches 1.0 issue a query
1536         querycounter += cl.realframetime * net_slist_queriespersecond.value;
1537         maxqueries = (int)querycounter;
1538         maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer);
1539         querycounter -= maxqueries;
1540
1541         if( maxqueries == 0 ) {
1542                 return;
1543         }
1544
1545         // scan serverlist and issue queries as needed
1546     serverlist_querysleep = true;
1547
1548         timeouttime = realtime - net_slist_timeout.value;
1549         for( index = 0, queries = 0 ; index < serverlist_cachecount && queries < maxqueries ; index++ )
1550         {
1551                 serverlist_entry_t *entry = &serverlist_cache[ index ];
1552                 if( entry->query != SQS_QUERYING )
1553                 {
1554                         continue;
1555                 }
1556
1557         serverlist_querysleep = false;
1558                 if( entry->querycounter != 0 && entry->querytime > timeouttime )
1559                 {
1560                         continue;
1561                 }
1562
1563                 if( entry->querycounter != (unsigned) net_slist_maxtries.integer )
1564                 {
1565                         lhnetaddress_t address;
1566                         int socket;
1567
1568                         LHNETADDRESS_FromString(&address, entry->info.cname, 0);
1569                         if (entry->protocol == PROTOCOL_QUAKEWORLD)
1570                         {
1571                                 for (socket = 0; socket < cl_numsockets ; socket++)
1572                                         NetConn_WriteString(cl_sockets[socket], "\377\377\377\377status\n", &address);
1573                         }
1574                         else
1575                         {
1576                                 for (socket = 0; socket < cl_numsockets ; socket++)
1577                                         NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getinfo", &address);
1578                         }
1579
1580                         //entry->querytime = realtime;
1581                         entry->querytime = Sys_DoubleTime();
1582                         entry->querycounter++;
1583
1584                         // if not in the slist menu we should print the server to console
1585                         if (serverlist_consoleoutput)
1586                                 Con_Printf("querying %25s (%i. try)\n", entry->info.cname, entry->querycounter);
1587
1588                         queries++;
1589                 }
1590                 else
1591                 {
1592                         entry->query = SQS_TIMEDOUT;
1593                 }
1594         }
1595 }
1596
1597 void NetConn_ClientFrame(void)
1598 {
1599         int i, length;
1600         lhnetaddress_t peeraddress;
1601         NetConn_UpdateSockets();
1602         if (cls.connect_trying && cls.connect_nextsendtime < realtime)
1603         {
1604                 if (cls.connect_remainingtries == 0)
1605                         M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
1606                 cls.connect_nextsendtime = realtime + 1;
1607                 cls.connect_remainingtries--;
1608                 if (cls.connect_remainingtries <= -10)
1609                 {
1610                         cls.connect_trying = false;
1611                         M_Update_Return_Reason("Connect: Failed");
1612                         return;
1613                 }
1614                 // try challenge first (newer DP server or QW)
1615                 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
1616                 // then try netquake as a fallback (old server, or netquake)
1617                 SZ_Clear(&net_message);
1618                 // save space for the header, filled in later
1619                 MSG_WriteLong(&net_message, 0);
1620                 MSG_WriteByte(&net_message, CCREQ_CONNECT);
1621                 MSG_WriteString(&net_message, "QUAKE");
1622                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1623                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1624                 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
1625                 SZ_Clear(&net_message);
1626         }
1627         for (i = 0;i < cl_numsockets;i++)
1628                 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1629                         NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
1630         NetConn_QueryQueueFrame();
1631         if (cls.netcon && realtime > cls.netcon->timeout)
1632         {
1633                 Con_Print("Connection timed out\n");
1634                 CL_Disconnect();
1635                 Host_ShutdownServer ();
1636         }
1637 }
1638
1639 #define MAX_CHALLENGES 128
1640 struct challenge_s
1641 {
1642         lhnetaddress_t address;
1643         double time;
1644         char string[12];
1645 }
1646 challenge[MAX_CHALLENGES];
1647
1648 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
1649 {
1650         int i;
1651         char c;
1652         for (i = 0;i < bufferlength - 1;i++)
1653         {
1654                 do
1655                 {
1656                         c = rand () % (127 - 33) + 33;
1657                 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
1658                 buffer[i] = c;
1659         }
1660         buffer[i] = 0;
1661 }
1662
1663 static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg, size_t out_size, qboolean fullstatus)
1664 {
1665         unsigned int nb_clients = 0, i;
1666         int length;
1667
1668         // How many clients are there?
1669         for (i = 0;i < (unsigned int)svs.maxclients;i++)
1670                 if (svs.clients[i].active)
1671                         nb_clients++;
1672
1673         // TODO: we should add more information for the full status string
1674         length = dpsnprintf(out_msg, out_size,
1675                                                 "\377\377\377\377%s\x0A"
1676                                                 "\\gamename\\%s\\modname\\%s\\gameversion\\%d\\sv_maxclients\\%d"
1677                                                 "\\clients\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d"
1678                                                 "%s%s"
1679                                                 "%s",
1680                                                 fullstatus ? "statusResponse" : "infoResponse",
1681                                                 gamename, com_modname, gameversion.integer, svs.maxclients,
1682                                                 nb_clients, sv.name, hostname.string, NET_PROTOCOL_VERSION,
1683                                                 challenge ? "\\challenge\\" : "", challenge ? challenge : "",
1684                                                 fullstatus ? "\n" : "");
1685
1686         // Make sure it fits in the buffer
1687         if (length < 0)
1688                 return false;
1689
1690         if (fullstatus)
1691         {
1692                 char *ptr;
1693                 int left;
1694
1695                 ptr = out_msg + length;
1696                 left = (int)out_size - length;
1697
1698                 for (i = 0;i < (unsigned int)svs.maxclients;i++)
1699                 {
1700                         client_t *cl = &svs.clients[i];
1701                         if (cl->active)
1702                         {
1703                                 int nameind, cleanind;
1704                                 char curchar;
1705                                 char cleanname [sizeof(cl->name)];
1706
1707                                 // Remove all characters '"' and '\' in the player name
1708                                 nameind = 0;
1709                                 cleanind = 0;
1710                                 do
1711                                 {
1712                                         curchar = cl->name[nameind++];
1713                                         if (curchar != '"' && curchar != '\\')
1714                                         {
1715                                                 cleanname[cleanind++] = curchar;
1716                                                 if (cleanind == sizeof(cleanname) - 1)
1717                                                         break;
1718                                         }
1719                                 } while (curchar != '\0');
1720
1721                                 length = dpsnprintf(ptr, left, "%d %d \"%s\"\n",
1722                                                                         cl->frags,
1723                                                                         (int)(cl->ping * 1000.0f),
1724                                                                         cleanname);
1725                                 if(length < 0)
1726                                         return false;
1727                                 left -= length;
1728                                 ptr += length;
1729                         }
1730                 }
1731         }
1732
1733         return true;
1734 }
1735
1736 static qboolean NetConn_PreventConnectFlood(lhnetaddress_t *peeraddress)
1737 {
1738         int floodslotnum, bestfloodslotnum;
1739         double bestfloodtime;
1740         lhnetaddress_t noportpeeraddress;
1741         // see if this is a connect flood
1742         noportpeeraddress = *peeraddress;
1743         LHNETADDRESS_SetPort(&noportpeeraddress, 0);
1744         bestfloodslotnum = 0;
1745         bestfloodtime = sv.connectfloodaddresses[bestfloodslotnum].lasttime;
1746         for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
1747         {
1748                 if (bestfloodtime >= sv.connectfloodaddresses[floodslotnum].lasttime)
1749                 {
1750                         bestfloodtime = sv.connectfloodaddresses[floodslotnum].lasttime;
1751                         bestfloodslotnum = floodslotnum;
1752                 }
1753                 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
1754                 {
1755                         // this address matches an ongoing flood address
1756                         if (realtime < sv.connectfloodaddresses[floodslotnum].lasttime + net_connectfloodblockingtimeout.value)
1757                         {
1758                                 // renew the ban on this address so it does not expire
1759                                 // until the flood has subsided
1760                                 sv.connectfloodaddresses[floodslotnum].lasttime = realtime;
1761                                 //Con_Printf("Flood detected!\n");
1762                                 return true;
1763                         }
1764                         // the flood appears to have subsided, so allow this
1765                         bestfloodslotnum = floodslotnum; // reuse the same slot
1766                         break;
1767                 }
1768         }
1769         // begin a new timeout on this address
1770         sv.connectfloodaddresses[bestfloodslotnum].address = noportpeeraddress;
1771         sv.connectfloodaddresses[bestfloodslotnum].lasttime = realtime;
1772         //Con_Printf("Flood detection initiated!\n");
1773         return false;
1774 }
1775
1776 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress)
1777 {
1778         int floodslotnum;
1779         lhnetaddress_t noportpeeraddress;
1780         // see if this is a connect flood
1781         noportpeeraddress = *peeraddress;
1782         LHNETADDRESS_SetPort(&noportpeeraddress, 0);
1783         for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
1784         {
1785                 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
1786                 {
1787                         // this address matches an ongoing flood address
1788                         // remove the ban
1789                         sv.connectfloodaddresses[floodslotnum].address.addresstype = LHNETADDRESSTYPE_NONE;
1790                         sv.connectfloodaddresses[floodslotnum].lasttime = 0;
1791                         //Con_Printf("Flood cleared!\n");
1792                 }
1793         }
1794 }
1795
1796 extern void SV_SendServerinfo (client_t *client);
1797 static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1798 {
1799         int i, ret, clientnum, best;
1800         double besttime;
1801         client_t *client;
1802         char *s, *string, response[1400], addressstring2[128], stringbuf[16384];
1803
1804         if (!sv.active)
1805                 return false;
1806
1807         // convert the address to a string incase we need it
1808         LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1809
1810         // see if we can identify the sender as a local player
1811         // (this is necessary for rcon to send a reliable reply if the client is
1812         //  actually on the server, not sending remotely)
1813         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1814                 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1815                         break;
1816         if (i == svs.maxclients)
1817                 host_client = NULL;
1818
1819         if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1820         {
1821                 // received a command string - strip off the packaging and put it
1822                 // into our string buffer with NULL termination
1823                 data += 4;
1824                 length -= 4;
1825                 length = min(length, (int)sizeof(stringbuf) - 1);
1826                 memcpy(stringbuf, data, length);
1827                 stringbuf[length] = 0;
1828                 string = stringbuf;
1829
1830                 if (developer.integer >= 10)
1831                 {
1832                         Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
1833                         Com_HexDumpToConsole(data, length);
1834                 }
1835
1836                 if (length >= 12 && !memcmp(string, "getchallenge", 12))
1837                 {
1838                         for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
1839                         {
1840                                 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
1841                                         break;
1842                                 if (besttime > challenge[i].time)
1843                                         besttime = challenge[best = i].time;
1844                         }
1845                         // if we did not find an exact match, choose the oldest and
1846                         // update address and string
1847                         if (i == MAX_CHALLENGES)
1848                         {
1849                                 i = best;
1850                                 challenge[i].address = *peeraddress;
1851                                 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
1852                         }
1853                         challenge[i].time = realtime;
1854                         // send the challenge
1855                         NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
1856                         return true;
1857                 }
1858                 if (length > 8 && !memcmp(string, "connect\\", 8))
1859                 {
1860                         string += 7;
1861                         length -= 7;
1862
1863                         if (!(s = SearchInfostring(string, "challenge")))
1864                                 return true;
1865                         // validate the challenge
1866                         for (i = 0;i < MAX_CHALLENGES;i++)
1867                                 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1868                                         break;
1869                         // if the challenge is not recognized, drop the packet
1870                         if (i == MAX_CHALLENGES)
1871                                 return true;
1872
1873                         // check engine protocol
1874                         if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
1875                         {
1876                                 if (developer.integer >= 10)
1877                                         Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
1878                                 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
1879                                 return true;
1880                         }
1881
1882                         // see if this is a duplicate connection request or a disconnected
1883                         // client who is rejoining to the same client slot
1884                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1885                         {
1886                                 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1887                                 {
1888                                         // this is a known client...
1889                                         if (client->spawned)
1890                                         {
1891                                                 // client crashed and is coming back,
1892                                                 // keep their stuff intact
1893                                                 if (developer.integer >= 10)
1894                                                         Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", addressstring2);
1895                                                 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1896                                                 SV_VM_Begin();
1897                                                 SV_SendServerinfo(client);
1898                                                 SV_VM_End();
1899                                         }
1900                                         else
1901                                         {
1902                                                 // client is still trying to connect,
1903                                                 // so we send a duplicate reply
1904                                                 if (developer.integer >= 10)
1905                                                         Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
1906                                                 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1907                                         }
1908                                         return true;
1909                                 }
1910                         }
1911
1912                         if (NetConn_PreventConnectFlood(peeraddress))
1913                                 return true;
1914
1915                         // find an empty client slot for this new client
1916                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1917                         {
1918                                 netconn_t *conn;
1919                                 if (!client->active && (conn = NetConn_Open(mysocket, peeraddress)))
1920                                 {
1921                                         // allocated connection
1922                                         if (developer.integer >= 10)
1923                                                 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
1924                                         NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1925                                         // now set up the client
1926                                         SV_VM_Begin();
1927                                         SV_ConnectClient(clientnum, conn);
1928                                         SV_VM_End();
1929                                         NetConn_Heartbeat(1);
1930                                         return true;
1931                                 }
1932                         }
1933
1934                         // no empty slots found - server is full
1935                         if (developer.integer >= 10)
1936                                 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
1937                         NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
1938
1939                         return true;
1940                 }
1941                 if (length >= 7 && !memcmp(string, "getinfo", 7))
1942                 {
1943                         const char *challenge = NULL;
1944
1945                         // If there was a challenge in the getinfo message
1946                         if (length > 8 && string[7] == ' ')
1947                                 challenge = string + 8;
1948
1949                         if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
1950                         {
1951                                 if (developer.integer >= 10)
1952                                         Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
1953                                 NetConn_WriteString(mysocket, response, peeraddress);
1954                         }
1955                         return true;
1956                 }
1957                 if (length >= 9 && !memcmp(string, "getstatus", 9))
1958                 {
1959                         const char *challenge = NULL;
1960
1961                         // If there was a challenge in the getinfo message
1962                         if (length > 10 && string[9] == ' ')
1963                                 challenge = string + 10;
1964
1965                         if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
1966                         {
1967                                 if (developer.integer >= 10)
1968                                         Con_Printf("Sending reply to client %s - %s\n", addressstring2, response);
1969                                 NetConn_WriteString(mysocket, response, peeraddress);
1970                         }
1971                         return true;
1972                 }
1973                 if (length >= 5 && !memcmp(string, "rcon ", 5))
1974                 {
1975                         int i;
1976                         char *s = string + 5;
1977                         char password[64];
1978                         for (i = 0;*s > ' ';s++)
1979                                 if (i < (int)sizeof(password) - 1)
1980                                         password[i++] = *s;
1981                         password[i] = 0;
1982                         if (password[0] > ' ' && !strcmp(rcon_password.string, password))
1983                         {
1984                                 // looks like a legitimate rcon command with the correct password
1985                                 Con_Printf("server received rcon command from %s:\n%s\n", host_client ? host_client->name : addressstring2, s);
1986                                 rcon_redirect = true;
1987                                 rcon_redirect_bufferpos = 0;
1988                                 Cmd_ExecuteString(s, src_command);
1989                                 rcon_redirect_buffer[rcon_redirect_bufferpos] = 0;
1990                                 rcon_redirect = false;
1991                                 // print resulting text to client
1992                                 // if client is playing, send a reliable reply instead of
1993                                 // a command packet
1994                                 if (host_client)
1995                                 {
1996                                         // if the netconnection is loop, then this is the
1997                                         // local player on a listen mode server, and it would
1998                                         // result in duplicate printing to the console
1999                                         // (not that the local player should be using rcon
2000                                         //  when they have the console)
2001                                         if (host_client->netconnection && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2002                                                 SV_ClientPrintf("%s", rcon_redirect_buffer);
2003                                 }
2004                                 else
2005                                 {
2006                                         // qw print command
2007                                         dpsnprintf(response, sizeof(response), "\377\377\377\377n%s", rcon_redirect_buffer);
2008                                         NetConn_WriteString(mysocket, response, peeraddress);
2009                                 }
2010                         }
2011                         return true;
2012                 }
2013                 if (!strncmp(string, "ping", 4))
2014                 {
2015                         if (developer.integer >= 10)
2016                                 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
2017                         NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
2018                         return true;
2019                 }
2020                 if (!strncmp(string, "ack", 3))
2021                         return true;
2022                 // we may not have liked the packet, but it was a command packet, so
2023                 // we're done processing this packet now
2024                 return true;
2025         }
2026         // netquake control packets, supported for compatibility only, and only
2027         // when running game protocols that are normally served via this connection
2028         // protocol
2029         // (this protects more modern protocols against being used for
2030         //  Quake packet flood Denial Of Service attacks)
2031         if (length >= 5 && (i = BigLong(*((int *)data))) && (i & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (i & NETFLAG_LENGTH_MASK) == length && (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3))
2032         {
2033                 int c = data[4];
2034                 data += 5;
2035                 length -= 5;
2036                 switch (c)
2037                 {
2038                 case CCREQ_CONNECT:
2039                         if (developer.integer >= 10)
2040                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
2041                         if (length < (int)strlen("QUAKE") + 1 + 1)
2042                                 break;
2043
2044                         if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION)
2045                         {
2046                                 if (developer.integer >= 10)
2047                                         Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
2048                                 SZ_Clear(&net_message);
2049                                 // save space for the header, filled in later
2050                                 MSG_WriteLong(&net_message, 0);
2051                                 MSG_WriteByte(&net_message, CCREP_REJECT);
2052                                 MSG_WriteString(&net_message, "Incompatible version.\n");
2053                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2054                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2055                                 SZ_Clear(&net_message);
2056                                 break;
2057                         }
2058
2059                         // see if this connect request comes from a known client
2060                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2061                         {
2062                                 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2063                                 {
2064                                         // this is either a duplicate connection request
2065                                         // or coming back from a timeout
2066                                         // (if so, keep their stuff intact)
2067
2068                                         // send a reply
2069                                         if (developer.integer >= 10)
2070                                                 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
2071                                         SZ_Clear(&net_message);
2072                                         // save space for the header, filled in later
2073                                         MSG_WriteLong(&net_message, 0);
2074                                         MSG_WriteByte(&net_message, CCREP_ACCEPT);
2075                                         MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
2076                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2077                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2078                                         SZ_Clear(&net_message);
2079
2080                                         // if client is already spawned, re-send the
2081                                         // serverinfo message as they'll need it to play
2082                                         if (client->spawned)
2083                                         {
2084                                                 SV_VM_Begin();
2085                                                 SV_SendServerinfo(client);
2086                                                 SV_VM_End();
2087                                         }
2088                                         return true;
2089                                 }
2090                         }
2091
2092                         // this is a new client, check for connection flood
2093                         if (NetConn_PreventConnectFlood(peeraddress))
2094                                 break;
2095
2096                         // find a slot for the new client
2097                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2098                         {
2099                                 netconn_t *conn;
2100                                 if (!client->active && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
2101                                 {
2102                                         // connect to the client
2103                                         // everything is allocated, just fill in the details
2104                                         strlcpy (conn->address, addressstring2, sizeof (conn->address));
2105                                         if (developer.integer >= 10)
2106                                                 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
2107                                         // send back the info about the server connection
2108                                         SZ_Clear(&net_message);
2109                                         // save space for the header, filled in later
2110                                         MSG_WriteLong(&net_message, 0);
2111                                         MSG_WriteByte(&net_message, CCREP_ACCEPT);
2112                                         MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
2113                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2114                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2115                                         SZ_Clear(&net_message);
2116                                         // now set up the client struct
2117                                         SV_VM_Begin();
2118                                         SV_ConnectClient(clientnum, conn);
2119                                         SV_VM_End();
2120                                         NetConn_Heartbeat(1);
2121                                         return true;
2122                                 }
2123                         }
2124
2125                         if (developer.integer >= 10)
2126                                 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
2127                         // no room; try to let player know
2128                         SZ_Clear(&net_message);
2129                         // save space for the header, filled in later
2130                         MSG_WriteLong(&net_message, 0);
2131                         MSG_WriteByte(&net_message, CCREP_REJECT);
2132                         MSG_WriteString(&net_message, "Server is full.\n");
2133                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2134                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2135                         SZ_Clear(&net_message);
2136                         break;
2137                 case CCREQ_SERVER_INFO:
2138                         if (developer.integer >= 10)
2139                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
2140                         if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
2141                         {
2142                                 int numclients;
2143                                 char myaddressstring[128];
2144                                 if (developer.integer >= 10)
2145                                         Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
2146                                 SZ_Clear(&net_message);
2147                                 // save space for the header, filled in later
2148                                 MSG_WriteLong(&net_message, 0);
2149                                 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
2150                                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), myaddressstring, sizeof(myaddressstring), true);
2151                                 MSG_WriteString(&net_message, myaddressstring);
2152                                 MSG_WriteString(&net_message, hostname.string);
2153                                 MSG_WriteString(&net_message, sv.name);
2154                                 // How many clients are there?
2155                                 for (i = 0, numclients = 0;i < svs.maxclients;i++)
2156                                         if (svs.clients[i].active)
2157                                                 numclients++;
2158                                 MSG_WriteByte(&net_message, numclients);
2159                                 MSG_WriteByte(&net_message, svs.maxclients);
2160                                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2161                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2162                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2163                                 SZ_Clear(&net_message);
2164                         }
2165                         break;
2166                 case CCREQ_PLAYER_INFO:
2167                         if (developer.integer >= 10)
2168                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
2169                         if (sv.active)
2170                         {
2171                                 int playerNumber, activeNumber, clientNumber;
2172                                 client_t *client;
2173
2174                                 playerNumber = MSG_ReadByte();
2175                                 activeNumber = -1;
2176                                 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
2177                                         if (client->active && ++activeNumber == playerNumber)
2178                                                 break;
2179                                 if (clientNumber != svs.maxclients)
2180                                 {
2181                                         SZ_Clear(&net_message);
2182                                         // save space for the header, filled in later
2183                                         MSG_WriteLong(&net_message, 0);
2184                                         MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
2185                                         MSG_WriteByte(&net_message, playerNumber);
2186                                         MSG_WriteString(&net_message, client->name);
2187                                         MSG_WriteLong(&net_message, client->colors);
2188                                         MSG_WriteLong(&net_message, (int)client->edict->fields.server->frags);
2189                                         MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
2190                                         MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
2191                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2192                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2193                                         SZ_Clear(&net_message);
2194                                 }
2195                         }
2196                         break;
2197                 case CCREQ_RULE_INFO:
2198                         if (developer.integer >= 10)
2199                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
2200                         if (sv.active)
2201                         {
2202                                 char *prevCvarName;
2203                                 cvar_t *var;
2204
2205                                 // find the search start location
2206                                 prevCvarName = MSG_ReadString();
2207                                 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
2208
2209                                 // send the response
2210                                 SZ_Clear(&net_message);
2211                                 // save space for the header, filled in later
2212                                 MSG_WriteLong(&net_message, 0);
2213                                 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
2214                                 if (var)
2215                                 {
2216                                         MSG_WriteString(&net_message, var->name);
2217                                         MSG_WriteString(&net_message, var->string);
2218                                 }
2219                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2220                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2221                                 SZ_Clear(&net_message);
2222                         }
2223                         break;
2224                 default:
2225                         break;
2226                 }
2227                 // we may not have liked the packet, but it was a valid control
2228                 // packet, so we're done processing this packet now
2229                 return true;
2230         }
2231         if (host_client)
2232         {
2233                 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length, sv.protocol, host_client->spawned ? net_messagetimeout.value : net_connecttimeout.value)) == 2)
2234                 {
2235                         SV_VM_Begin();
2236                         SV_ReadClientMessage();
2237                         SV_VM_End();
2238                         return ret;
2239                 }
2240         }
2241         return 0;
2242 }
2243
2244 void NetConn_ServerFrame(void)
2245 {
2246         int i, length;
2247         lhnetaddress_t peeraddress;
2248         for (i = 0;i < sv_numsockets;i++)
2249                 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2250                         NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
2251         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2252         {
2253                 // never timeout loopback connections
2254                 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2255                 {
2256                         Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
2257                         SV_VM_Begin();
2258                         SV_DropClient(false);
2259                         SV_VM_End();
2260                 }
2261         }
2262 }
2263
2264 void NetConn_QueryMasters(qboolean querydp, qboolean queryqw)
2265 {
2266         int i;
2267         int masternum;
2268         lhnetaddress_t masteraddress;
2269         lhnetaddress_t broadcastaddress;
2270         char request[256];
2271
2272         if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
2273                 return;
2274
2275         // 26000 is the default quake server port, servers on other ports will not
2276         // be found
2277         // note this is IPv4-only, I doubt there are IPv6-only LANs out there
2278         LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
2279
2280         if (querydp)
2281         {
2282                 for (i = 0;i < cl_numsockets;i++)
2283                 {
2284                         if (cl_sockets[i])
2285                         {
2286                                 // search LAN for Quake servers
2287                                 SZ_Clear(&net_message);
2288                                 // save space for the header, filled in later
2289                                 MSG_WriteLong(&net_message, 0);
2290                                 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
2291                                 MSG_WriteString(&net_message, "QUAKE");
2292                                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2293                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2294                                 NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
2295                                 SZ_Clear(&net_message);
2296
2297                                 // search LAN for DarkPlaces servers
2298                                 NetConn_WriteString(cl_sockets[i], "\377\377\377\377getinfo", &broadcastaddress);
2299
2300                                 // build the getservers message to send to the dpmaster master servers
2301                                 dpsnprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
2302
2303                                 // search internet
2304                                 for (masternum = 0;sv_masters[masternum].name;masternum++)
2305                                 {
2306                                         if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
2307                                         {
2308                                                 masterquerycount++;
2309                                                 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
2310                                         }
2311                                 }
2312                         }
2313                 }
2314         }
2315
2316         // only query QuakeWorld servers when the user wants to
2317         if (queryqw)
2318         {
2319                 for (i = 0;i < cl_numsockets;i++)
2320                 {
2321                         if (cl_sockets[i])
2322                         {
2323                                 // search LAN for QuakeWorld servers
2324                                 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &broadcastaddress);
2325
2326                                 // build the getservers message to send to the qwmaster master servers
2327                                 // note this has no -1 prefix, and the trailing nul byte is sent
2328                                 dpsnprintf(request, sizeof(request), "c\n");
2329
2330                                 // search internet
2331                                 for (masternum = 0;sv_qwmasters[masternum].name;masternum++)
2332                                 {
2333                                         if (sv_qwmasters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_qwmasters[masternum].string, QWMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
2334                                         {
2335                                                 if (m_state != m_slist)
2336                                                 {
2337                                                         char lookupstring[128];
2338                                                         LHNETADDRESS_ToString(&masteraddress, lookupstring, sizeof(lookupstring), true);
2339                                                         Con_Printf("Querying master %s (resolved from %s)\n", lookupstring, sv_qwmasters[masternum].string);
2340                                                 }
2341                                                 masterquerycount++;
2342                                                 NetConn_Write(cl_sockets[i], request, (int)strlen(request) + 1, &masteraddress);
2343                                         }
2344                                 }
2345                         }
2346                 }
2347         }
2348         if (!masterquerycount)
2349         {
2350                 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
2351                 M_Update_Return_Reason("No network");
2352         }
2353 }
2354
2355 void NetConn_Heartbeat(int priority)
2356 {
2357         lhnetaddress_t masteraddress;
2358         int masternum;
2359         lhnetsocket_t *mysocket;
2360
2361         // if it's a state change (client connected), limit next heartbeat to no
2362         // more than 30 sec in the future
2363         if (priority == 1 && nextheartbeattime > realtime + 30.0)
2364                 nextheartbeattime = realtime + 30.0;
2365
2366         // limit heartbeatperiod to 30 to 270 second range,
2367         // lower limit is to avoid abusing master servers with excess traffic,
2368         // upper limit is to avoid timing out on the master server (which uses
2369         // 300 sec timeout)
2370         if (sv_heartbeatperiod.value < 30)
2371                 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
2372         if (sv_heartbeatperiod.value > 270)
2373                 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
2374
2375         // make advertising optional and don't advertise singleplayer games, and
2376         // only send a heartbeat as often as the admin wants
2377         if (sv.active && sv_public.integer && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
2378         {
2379                 nextheartbeattime = realtime + sv_heartbeatperiod.value;
2380                 for (masternum = 0;sv_masters[masternum].name;masternum++)
2381                         if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
2382                                 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
2383         }
2384 }
2385
2386 static void Net_Heartbeat_f(void)
2387 {
2388         if (sv.active)
2389                 NetConn_Heartbeat(2);
2390         else
2391                 Con_Print("No server running, can not heartbeat to master server.\n");
2392 }
2393
2394 void PrintStats(netconn_t *conn)
2395 {
2396         if ((cls.state == ca_connected && cls.protocol == PROTOCOL_QUAKEWORLD) || (sv.active && sv.protocol == PROTOCOL_QUAKEWORLD))
2397                 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->qw.outgoing_sequence, conn->qw.incoming_sequence);
2398         else
2399                 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->nq.sendSequence, conn->nq.receiveSequence);
2400 }
2401
2402 void Net_Stats_f(void)
2403 {
2404         netconn_t *conn;
2405         Con_Printf("unreliable messages sent   = %i\n", unreliableMessagesSent);
2406         Con_Printf("unreliable messages recv   = %i\n", unreliableMessagesReceived);
2407         Con_Printf("reliable messages sent     = %i\n", reliableMessagesSent);
2408         Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
2409         Con_Printf("packetsSent                = %i\n", packetsSent);
2410         Con_Printf("packetsReSent              = %i\n", packetsReSent);
2411         Con_Printf("packetsReceived            = %i\n", packetsReceived);
2412         Con_Printf("receivedDuplicateCount     = %i\n", receivedDuplicateCount);
2413         Con_Printf("droppedDatagrams           = %i\n", droppedDatagrams);
2414         Con_Print("connections                =\n");
2415         for (conn = netconn_list;conn;conn = conn->next)
2416                 PrintStats(conn);
2417 }
2418
2419 void Net_Slist_f(void)
2420 {
2421         ServerList_ResetMasks();
2422         serverlist_sortbyfield = SLIF_PING;
2423         serverlist_sortdescending = false;
2424     if (m_state != m_slist) {
2425                 Con_Print("Sending requests to master servers\n");
2426                 ServerList_QueryList(true, false);
2427                 serverlist_consoleoutput = true;
2428                 Con_Print("Listening for replies...\n");
2429         } else
2430                 ServerList_QueryList(true, false);
2431 }
2432
2433 void Net_SlistQW_f(void)
2434 {
2435         ServerList_ResetMasks();
2436         serverlist_sortbyfield = SLIF_PING;
2437         serverlist_sortdescending = false;
2438     if (m_state != m_slist) {
2439                 Con_Print("Sending requests to master servers\n");
2440                 ServerList_QueryList(false, true);
2441                 serverlist_consoleoutput = true;
2442                 Con_Print("Listening for replies...\n");
2443         } else
2444                 ServerList_QueryList(false, true);
2445 }
2446
2447 void NetConn_Init(void)
2448 {
2449         int i;
2450         lhnetaddress_t tempaddress;
2451         netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
2452         Cmd_AddCommand("net_stats", Net_Stats_f, "print network statistics");
2453         Cmd_AddCommand("net_slist", Net_Slist_f, "query dp master servers and print all server information");
2454         Cmd_AddCommand("net_slistqw", Net_SlistQW_f, "query qw master servers and print all server information");
2455         Cmd_AddCommand("heartbeat", Net_Heartbeat_f, "send a heartbeat to the master server (updates your server information)");
2456         Cvar_RegisterVariable(&net_slist_queriespersecond);
2457         Cvar_RegisterVariable(&net_slist_queriesperframe);
2458         Cvar_RegisterVariable(&net_slist_timeout);
2459         Cvar_RegisterVariable(&net_slist_maxtries);
2460         Cvar_RegisterVariable(&net_messagetimeout);
2461         Cvar_RegisterVariable(&net_connecttimeout);
2462         Cvar_RegisterVariable(&net_connectfloodblockingtimeout);
2463         Cvar_RegisterVariable(&cl_netlocalping);
2464         Cvar_RegisterVariable(&cl_netpacketloss);
2465         Cvar_RegisterVariable(&hostname);
2466         Cvar_RegisterVariable(&developer_networking);
2467         Cvar_RegisterVariable(&cl_netport);
2468         Cvar_RegisterVariable(&sv_netport);
2469         Cvar_RegisterVariable(&net_address);
2470         //Cvar_RegisterVariable(&net_address_ipv6);
2471         Cvar_RegisterVariable(&sv_public);
2472         Cvar_RegisterVariable(&sv_heartbeatperiod);
2473         for (i = 0;sv_masters[i].name;i++)
2474                 Cvar_RegisterVariable(&sv_masters[i]);
2475         Cvar_RegisterVariable(&gameversion);
2476 // COMMANDLINEOPTION: Server: -ip <ipaddress> sets the ip address of this machine for purposes of networking (default 0.0.0.0 also known as INADDR_ANY), use only if you have multiple network adapters and need to choose one specifically.
2477         if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
2478         {
2479                 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
2480                 {
2481                         Con_Printf("-ip option used, setting net_address to \"%s\"\n");
2482                         Cvar_SetQuick(&net_address, com_argv[i + 1]);
2483                 }
2484                 else
2485                         Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
2486         }
2487 // COMMANDLINEOPTION: Server: -port <portnumber> sets the port to use for a server (default 26000, the same port as QUAKE itself), useful if you host multiple servers on your machine
2488         if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
2489         {
2490                 i = atoi(com_argv[i + 1]);
2491                 if (i >= 0 && i < 65536)
2492                 {
2493                         Con_Printf("-port option used, setting port cvar to %i\n", i);
2494                         Cvar_SetValueQuick(&sv_netport, i);
2495                 }
2496                 else
2497                         Con_Printf("-port option used, but %i is not a valid port number\n", i);
2498         }
2499         cl_numsockets = 0;
2500         sv_numsockets = 0;
2501         net_message.data = net_message_buf;
2502         net_message.maxsize = sizeof(net_message_buf);
2503         net_message.cursize = 0;
2504         LHNET_Init();
2505 }
2506
2507 void NetConn_Shutdown(void)
2508 {
2509         NetConn_CloseClientPorts();
2510         NetConn_CloseServerPorts();
2511         LHNET_Shutdown();
2512 }
2513