reorganize sv_public code; add a level -3 that blocks at getchallenge level, but...
[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 // for secure rcon authentication
27 #include "hmac.h"
28 #include "mdfour.h"
29 #include <time.h>
30
31 #define QWMASTER_PORT 27000
32 #define DPMASTER_PORT 27950
33
34 // note this defaults on for dedicated servers, off for listen servers
35 cvar_t sv_public = {0, "sv_public", "0", "1: advertises this server on the master server (so that players can find it in the server browser); 0: allow direct queries only; -1: do not respond to direct queries; -2: do not allow anyone to connect; -3: already block at getchallenge level"};
36 cvar_t sv_public_rejectreason = {0, "sv_public_rejectreason", "The server is closing.", "Rejection reason for connects when sv_public is -2"};
37 static cvar_t sv_heartbeatperiod = {CVAR_SAVE, "sv_heartbeatperiod", "120", "how often to send heartbeat in seconds (only used if sv_public is 1)"};
38
39 static cvar_t sv_masters [] =
40 {
41         {CVAR_SAVE, "sv_master1", "", "user-chosen master server 1"},
42         {CVAR_SAVE, "sv_master2", "", "user-chosen master server 2"},
43         {CVAR_SAVE, "sv_master3", "", "user-chosen master server 3"},
44         {CVAR_SAVE, "sv_master4", "", "user-chosen master server 4"},
45         {0, "sv_masterextra1", "69.59.212.88", "ghdigital.com - default master server 1 (admin: LordHavoc)"}, // admin: LordHavoc
46         {0, "sv_masterextra2", "64.22.107.125", "dpmaster.deathmask.net - default master server 2 (admin: Willis)"}, // admin: Willis
47         {0, "sv_masterextra3", "92.62.40.73", "dpmaster.tchr.no - default master server 3 (admin: tChr)"}, // admin: tChr
48         {0, NULL, NULL, NULL}
49 };
50
51 static cvar_t sv_qwmasters [] =
52 {
53         {CVAR_SAVE, "sv_qwmaster1", "", "user-chosen qwmaster server 1"},
54         {CVAR_SAVE, "sv_qwmaster2", "", "user-chosen qwmaster server 2"},
55         {CVAR_SAVE, "sv_qwmaster3", "", "user-chosen qwmaster server 3"},
56         {CVAR_SAVE, "sv_qwmaster4", "", "user-chosen qwmaster server 4"},
57         {0, "sv_qwmasterextra1", "master.quakeservers.net:27000", "Global master server. (admin: unknown)"},
58         {0, "sv_qwmasterextra2", "asgaard.morphos-team.net:27000", "Global master server. (admin: unknown)"},
59         {0, "sv_qwmasterextra3", "qwmaster.ocrana.de:27000", "German master server. (admin: unknown)"},
60         {0, "sv_qwmasterextra4", "masterserver.exhale.de:27000", "German master server. (admin: unknown)"},
61         {0, "sv_qwmasterextra5", "kubus.rulez.pl:27000", "Poland master server. (admin: unknown)"},
62         {0, NULL, NULL, NULL}
63 };
64
65 static double nextheartbeattime = 0;
66
67 sizebuf_t net_message;
68 static unsigned char net_message_buf[NET_MAXMESSAGE];
69
70 cvar_t net_messagetimeout = {0, "net_messagetimeout","300", "drops players who have not sent any packets for this many seconds"};
71 cvar_t net_connecttimeout = {0, "net_connecttimeout","15", "after requesting a connection, the client must reply within this many seconds or be dropped (cuts down on connect floods). Must be above 10 seconds."};
72 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)"};
73 cvar_t hostname = {CVAR_SAVE, "hostname", "UNNAMED", "server message to show in server browser"};
74 cvar_t developer_networking = {0, "developer_networking", "0", "prints all received and sent packets (recommended only for debugging)"};
75
76 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)"};
77 static cvar_t cl_netpacketloss_send = {0, "cl_netpacketloss_send","0", "drops this percentage of outgoing packets, useful for testing network protocol robustness (jerky movement, prediction errors, etc)"};
78 static cvar_t cl_netpacketloss_receive = {0, "cl_netpacketloss_receive","0", "drops this percentage of incoming packets, useful for testing network protocol robustness (jerky movement, effects failing to start, sounds failing to play, etc)"};
79 static cvar_t net_slist_queriespersecond = {0, "net_slist_queriespersecond", "20", "how many server information requests to send per second"};
80 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)"};
81 static cvar_t net_slist_timeout = {0, "net_slist_timeout", "4", "how long to listen for a server information response before giving up"};
82 static cvar_t net_slist_pause = {0, "net_slist_pause", "0", "when set to 1, the server list won't update until it is set back to 0"};
83 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)"};
84 static cvar_t net_slist_favorites = {CVAR_SAVE | CVAR_NQUSERINFOHACK, "net_slist_favorites", "", "contains a list of IP addresses and ports to always query explicitly"};
85 static cvar_t gameversion = {0, "gameversion", "0", "version of game data (mod-specific) to be sent to querying clients"};
86 static cvar_t gameversion_min = {0, "gameversion_min", "-1", "minimum version of game data (mod-specific), when client and server gameversion mismatch in the server browser the server is shown as incompatible; if -1, gameversion is used alone"};
87 static cvar_t gameversion_max = {0, "gameversion_max", "-1", "maximum version of game data (mod-specific), when client and server gameversion mismatch in the server browser the server is shown as incompatible; if -1, gameversion is used alone"};
88 static cvar_t rcon_restricted_password = {CVAR_PRIVATE, "rcon_restricted_password", "", "password to authenticate rcon commands in restricted mode; may be set to a string of the form user1:pass1 user2:pass2 user3:pass3 to allow multiple user accounts - the client then has to specify ONE of these combinations"};
89 static cvar_t rcon_restricted_commands = {0, "rcon_restricted_commands", "", "allowed commands for rcon when the restricted mode password was used"};
90 static cvar_t rcon_secure_maxdiff = {0, "rcon_secure_maxdiff", "5", "maximum time difference between rcon request and server system clock (to protect against replay attack)"};
91 extern cvar_t rcon_secure;
92 extern cvar_t rcon_secure_challengetimeout;
93
94 /* statistic counters */
95 static int packetsSent = 0;
96 static int packetsReSent = 0;
97 static int packetsReceived = 0;
98 static int receivedDuplicateCount = 0;
99 static int droppedDatagrams = 0;
100
101 static int unreliableMessagesSent = 0;
102 static int unreliableMessagesReceived = 0;
103 static int reliableMessagesSent = 0;
104 static int reliableMessagesReceived = 0;
105
106 double masterquerytime = -1000;
107 int masterquerycount = 0;
108 int masterreplycount = 0;
109 int serverquerycount = 0;
110 int serverreplycount = 0;
111
112 /// this is only false if there are still servers left to query
113 static qboolean serverlist_querysleep = true;
114 static qboolean serverlist_paused = false;
115 /// this is pushed a second or two ahead of realtime whenever a master server
116 /// reply is received, to avoid issuing queries while master replies are still
117 /// flooding in (which would make a mess of the ping times)
118 static double serverlist_querywaittime = 0;
119
120 static unsigned char sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
121 static unsigned char readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
122
123 static int cl_numsockets;
124 static lhnetsocket_t *cl_sockets[16];
125 static int sv_numsockets;
126 static lhnetsocket_t *sv_sockets[16];
127
128 netconn_t *netconn_list = NULL;
129 mempool_t *netconn_mempool = NULL;
130
131 cvar_t cl_netport = {0, "cl_port", "0", "forces client to use chosen port number if not 0"};
132 cvar_t sv_netport = {0, "port", "26000", "server port for players to connect to"};
133 cvar_t net_address = {0, "net_address", "", "network address to open ipv4 ports on (if empty, use default interfaces)"};
134 cvar_t net_address_ipv6 = {0, "net_address_ipv6", "", "network address to open ipv6 ports on (if empty, use default interfaces)"};
135
136 char cl_net_extresponse[NET_EXTRESPONSE_MAX][1400];
137 int cl_net_extresponse_count = 0;
138 int cl_net_extresponse_last = 0;
139
140 char sv_net_extresponse[NET_EXTRESPONSE_MAX][1400];
141 int sv_net_extresponse_count = 0;
142 int sv_net_extresponse_last = 0;
143
144 // ServerList interface
145 serverlist_mask_t serverlist_andmasks[SERVERLIST_ANDMASKCOUNT];
146 serverlist_mask_t serverlist_ormasks[SERVERLIST_ORMASKCOUNT];
147
148 serverlist_infofield_t serverlist_sortbyfield;
149 int serverlist_sortflags;
150
151 int serverlist_viewcount = 0;
152 unsigned short serverlist_viewlist[SERVERLIST_VIEWLISTSIZE];
153
154 int serverlist_maxcachecount = 0;
155 int serverlist_cachecount = 0;
156 serverlist_entry_t *serverlist_cache = NULL;
157
158 qboolean serverlist_consoleoutput;
159
160 static int nFavorites = 0;
161 static lhnetaddress_t favorites[MAX_FAVORITESERVERS];
162
163 void NetConn_UpdateFavorites(void)
164 {
165         const char *p;
166         nFavorites = 0;
167         p = net_slist_favorites.string;
168         while((size_t) nFavorites < sizeof(favorites) / sizeof(*favorites) && COM_ParseToken_Console(&p))
169         {
170                 if(LHNETADDRESS_FromString(&favorites[nFavorites], com_token, 26000))
171                         ++nFavorites;
172         }
173 }
174
175 /// helper function to insert a value into the viewset
176 /// spare entries will be removed
177 static void _ServerList_ViewList_Helper_InsertBefore( int index, serverlist_entry_t *entry )
178 {
179     int i;
180         if( serverlist_viewcount < SERVERLIST_VIEWLISTSIZE ) {
181                 i = serverlist_viewcount++;
182         } else {
183                 i = SERVERLIST_VIEWLISTSIZE - 1;
184         }
185
186         for( ; i > index ; i-- )
187                 serverlist_viewlist[ i ] = serverlist_viewlist[ i - 1 ];
188
189         serverlist_viewlist[index] = (int)(entry - serverlist_cache);
190 }
191
192 /// we suppose serverlist_viewcount to be valid, ie > 0
193 static void _ServerList_ViewList_Helper_Remove( int index )
194 {
195         serverlist_viewcount--;
196         for( ; index < serverlist_viewcount ; index++ )
197                 serverlist_viewlist[index] = serverlist_viewlist[index + 1];
198 }
199
200 /// \returns true if A should be inserted before B
201 static qboolean _ServerList_Entry_Compare( serverlist_entry_t *A, serverlist_entry_t *B )
202 {
203         int result = 0; // > 0 if for numbers A > B and for text if A < B
204
205         if( serverlist_sortflags & SLSF_FAVORITESFIRST )
206         {
207                 if(A->info.isfavorite != B->info.isfavorite)
208                         return A->info.isfavorite;
209         }
210
211         switch( serverlist_sortbyfield ) {
212                 case SLIF_PING:
213                         result = A->info.ping - B->info.ping;
214                         break;
215                 case SLIF_MAXPLAYERS:
216                         result = A->info.maxplayers - B->info.maxplayers;
217                         break;
218                 case SLIF_NUMPLAYERS:
219                         result = A->info.numplayers - B->info.numplayers;
220                         break;
221                 case SLIF_NUMBOTS:
222                         result = A->info.numbots - B->info.numbots;
223                         break;
224                 case SLIF_NUMHUMANS:
225                         result = A->info.numhumans - B->info.numhumans;
226                         break;
227                 case SLIF_FREESLOTS:
228                         result = A->info.freeslots - B->info.freeslots;
229                         break;
230                 case SLIF_PROTOCOL:
231                         result = A->info.protocol - B->info.protocol;
232                         break;
233                 case SLIF_CNAME:
234                         result = strcmp( B->info.cname, A->info.cname );
235                         break;
236                 case SLIF_GAME:
237                         result = strcasecmp( B->info.game, A->info.game );
238                         break;
239                 case SLIF_MAP:
240                         result = strcasecmp( B->info.map, A->info.map );
241                         break;
242                 case SLIF_MOD:
243                         result = strcasecmp( B->info.mod, A->info.mod );
244                         break;
245                 case SLIF_NAME:
246                         result = strcasecmp( B->info.name, A->info.name );
247                         break;
248                 case SLIF_QCSTATUS:
249                         result = strcasecmp( B->info.qcstatus, A->info.qcstatus ); // not really THAT useful, though
250                         break;
251                 case SLIF_ISFAVORITE:
252                         result = !!B->info.isfavorite - !!A->info.isfavorite;
253                         break;
254                 default:
255                         Con_DPrint( "_ServerList_Entry_Compare: Bad serverlist_sortbyfield!\n" );
256                         break;
257         }
258
259         if (result != 0)
260         {
261                 if( serverlist_sortflags & SLSF_DESCENDING )
262                         return result > 0;
263                 else
264                         return result < 0;
265         }
266
267         // if the chosen sort key is identical, sort by index
268         // (makes this a stable sort, so that later replies from servers won't
269         //  shuffle the servers around when they have the same ping)
270         return A < B;
271 }
272
273 static qboolean _ServerList_CompareInt( int A, serverlist_maskop_t op, int B )
274 {
275         // This should actually be done with some intermediate and end-of-function return
276         switch( op ) {
277                 case SLMO_LESS:
278                         return A < B;
279                 case SLMO_LESSEQUAL:
280                         return A <= B;
281                 case SLMO_EQUAL:
282                         return A == B;
283                 case SLMO_GREATER:
284                         return A > B;
285                 case SLMO_NOTEQUAL:
286                         return A != B;
287                 case SLMO_GREATEREQUAL:
288                 case SLMO_CONTAINS:
289                 case SLMO_NOTCONTAIN:
290                 case SLMO_STARTSWITH:
291                 case SLMO_NOTSTARTSWITH:
292                         return A >= B;
293                 default:
294                         Con_DPrint( "_ServerList_CompareInt: Bad op!\n" );
295                         return false;
296         }
297 }
298
299 static qboolean _ServerList_CompareStr( const char *A, serverlist_maskop_t op, const char *B )
300 {
301         int i;
302         char bufferA[ 1400 ], bufferB[ 1400 ]; // should be more than enough
303         COM_StringDecolorize(A, 0, bufferA, sizeof(bufferA), false);
304         for (i = 0;i < (int)sizeof(bufferA)-1 && bufferA[i];i++)
305                 bufferA[i] = (bufferA[i] >= 'A' && bufferA[i] <= 'Z') ? (bufferA[i] + 'a' - 'A') : bufferA[i];
306         bufferA[i] = 0;
307         for (i = 0;i < (int)sizeof(bufferB)-1 && B[i];i++)
308                 bufferB[i] = (B[i] >= 'A' && B[i] <= 'Z') ? (B[i] + 'a' - 'A') : B[i];
309         bufferB[i] = 0;
310
311         // Same here, also using an intermediate & final return would be more appropriate
312         // A info B mask
313         switch( op ) {
314                 case SLMO_CONTAINS:
315                         return *bufferB && !!strstr( bufferA, bufferB ); // we want a real bool
316                 case SLMO_NOTCONTAIN:
317                         return !*bufferB || !strstr( bufferA, bufferB );
318                 case SLMO_STARTSWITH:
319                         //Con_Printf("startsWith: %s %s\n", bufferA, bufferB);
320                         return *bufferB && !memcmp(bufferA, bufferB, strlen(bufferB));
321                 case SLMO_NOTSTARTSWITH:
322                         return !*bufferB || memcmp(bufferA, bufferB, strlen(bufferB));
323                 case SLMO_LESS:
324                         return strcmp( bufferA, bufferB ) < 0;
325                 case SLMO_LESSEQUAL:
326                         return strcmp( bufferA, bufferB ) <= 0;
327                 case SLMO_EQUAL:
328                         return strcmp( bufferA, bufferB ) == 0;
329                 case SLMO_GREATER:
330                         return strcmp( bufferA, bufferB ) > 0;
331                 case SLMO_NOTEQUAL:
332                         return strcmp( bufferA, bufferB ) != 0;
333                 case SLMO_GREATEREQUAL:
334                         return strcmp( bufferA, bufferB ) >= 0;
335                 default:
336                         Con_DPrint( "_ServerList_CompareStr: Bad op!\n" );
337                         return false;
338         }
339 }
340
341 static qboolean _ServerList_Entry_Mask( serverlist_mask_t *mask, serverlist_info_t *info )
342 {
343         if( !_ServerList_CompareInt( info->ping, mask->tests[SLIF_PING], mask->info.ping ) )
344                 return false;
345         if( !_ServerList_CompareInt( info->maxplayers, mask->tests[SLIF_MAXPLAYERS], mask->info.maxplayers ) )
346                 return false;
347         if( !_ServerList_CompareInt( info->numplayers, mask->tests[SLIF_NUMPLAYERS], mask->info.numplayers ) )
348                 return false;
349         if( !_ServerList_CompareInt( info->numbots, mask->tests[SLIF_NUMBOTS], mask->info.numbots ) )
350                 return false;
351         if( !_ServerList_CompareInt( info->numhumans, mask->tests[SLIF_NUMHUMANS], mask->info.numhumans ) )
352                 return false;
353         if( !_ServerList_CompareInt( info->freeslots, mask->tests[SLIF_FREESLOTS], mask->info.freeslots ) )
354                 return false;
355         if( !_ServerList_CompareInt( info->protocol, mask->tests[SLIF_PROTOCOL], mask->info.protocol ))
356                 return false;
357         if( *mask->info.cname
358                 && !_ServerList_CompareStr( info->cname, mask->tests[SLIF_CNAME], mask->info.cname ) )
359                 return false;
360         if( *mask->info.game
361                 && !_ServerList_CompareStr( info->game, mask->tests[SLIF_GAME], mask->info.game ) )
362                 return false;
363         if( *mask->info.mod
364                 && !_ServerList_CompareStr( info->mod, mask->tests[SLIF_MOD], mask->info.mod ) )
365                 return false;
366         if( *mask->info.map
367                 && !_ServerList_CompareStr( info->map, mask->tests[SLIF_MAP], mask->info.map ) )
368                 return false;
369         if( *mask->info.name
370                 && !_ServerList_CompareStr( info->name, mask->tests[SLIF_NAME], mask->info.name ) )
371                 return false;
372         if( *mask->info.qcstatus
373                 && !_ServerList_CompareStr( info->qcstatus, mask->tests[SLIF_QCSTATUS], mask->info.qcstatus ) )
374                 return false;
375         if( *mask->info.players
376                 && !_ServerList_CompareStr( info->players, mask->tests[SLIF_PLAYERS], mask->info.players ) )
377                 return false;
378         if( !_ServerList_CompareInt( info->isfavorite, mask->tests[SLIF_ISFAVORITE], mask->info.isfavorite ))
379                 return false;
380         return true;
381 }
382
383 static void ServerList_ViewList_Insert( serverlist_entry_t *entry )
384 {
385         int start, end, mid, i;
386         lhnetaddress_t addr;
387
388         // reject incompatible servers
389         if(
390                 entry->info.gameversion != gameversion.integer
391                 &&
392                 !(
393                            gameversion_min.integer >= 0 // min/max range set by user/mod?
394                         && gameversion_max.integer >= 0
395                         && gameversion_min.integer >= entry->info.gameversion // version of server in min/max range?
396                         && gameversion_max.integer <= entry->info.gameversion
397                  )
398         )
399                 return;
400
401         // refresh the "favorite" status
402         entry->info.isfavorite = false;
403         if(LHNETADDRESS_FromString(&addr, entry->info.cname, 26000))
404         {
405                 for(i = 0; i < nFavorites; ++i)
406                 {
407                         if(LHNETADDRESS_Compare(&addr, &favorites[i]) == 0)
408                         {
409                                 entry->info.isfavorite = true;
410                                 break;
411                         }
412                 }
413         }
414
415         // FIXME: change this to be more readable (...)
416         // now check whether it passes through the masks
417         for( start = 0 ; start < SERVERLIST_ANDMASKCOUNT && serverlist_andmasks[start].active; start++ )
418                 if( !_ServerList_Entry_Mask( &serverlist_andmasks[start], &entry->info ) )
419                         return;
420
421         for( start = 0 ; start < SERVERLIST_ORMASKCOUNT && serverlist_ormasks[start].active ; start++ )
422                 if( _ServerList_Entry_Mask( &serverlist_ormasks[start], &entry->info ) )
423                         break;
424         if( start == SERVERLIST_ORMASKCOUNT || (start > 0 && !serverlist_ormasks[start].active) )
425                 return;
426
427         if( !serverlist_viewcount ) {
428                 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
429                 return;
430         }
431         // ok, insert it, we just need to find out where exactly:
432
433         // two special cases
434         // check whether to insert it as new first item
435         if( _ServerList_Entry_Compare( entry, ServerList_GetViewEntry(0) ) ) {
436                 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
437                 return;
438         } // check whether to insert it as new last item
439         else if( !_ServerList_Entry_Compare( entry, ServerList_GetViewEntry(serverlist_viewcount - 1) ) ) {
440                 _ServerList_ViewList_Helper_InsertBefore( serverlist_viewcount, entry );
441                 return;
442         }
443         start = 0;
444         end = serverlist_viewcount - 1;
445         while( end > start + 1 )
446         {
447                 mid = (start + end) / 2;
448                 // test the item that lies in the middle between start and end
449                 if( _ServerList_Entry_Compare( entry, ServerList_GetViewEntry(mid) ) )
450                         // the item has to be in the upper half
451                         end = mid;
452                 else
453                         // the item has to be in the lower half
454                         start = mid;
455         }
456         _ServerList_ViewList_Helper_InsertBefore( start + 1, entry );
457 }
458
459 static void ServerList_ViewList_Remove( serverlist_entry_t *entry )
460 {
461         int i;
462         for( i = 0; i < serverlist_viewcount; i++ )
463         {
464                 if (ServerList_GetViewEntry(i) == entry)
465                 {
466                         _ServerList_ViewList_Helper_Remove(i);
467                         break;
468                 }
469         }
470 }
471
472 void ServerList_RebuildViewList(void)
473 {
474         int i;
475
476         serverlist_viewcount = 0;
477         for( i = 0 ; i < serverlist_cachecount ; i++ ) {
478                 serverlist_entry_t *entry = &serverlist_cache[i];
479                 // also display entries that are currently being refreshed [11/8/2007 Black]
480                 if( entry->query == SQS_QUERIED || entry->query == SQS_REFRESHING )
481                         ServerList_ViewList_Insert( entry );
482         }
483 }
484
485 void ServerList_ResetMasks(void)
486 {
487         int i;
488
489         memset( &serverlist_andmasks, 0, sizeof( serverlist_andmasks ) );
490         memset( &serverlist_ormasks, 0, sizeof( serverlist_ormasks ) );
491         // numbots needs to be compared to -1 to always succeed
492         for(i = 0; i < SERVERLIST_ANDMASKCOUNT; ++i)
493                 serverlist_andmasks[i].info.numbots = -1;
494         for(i = 0; i < SERVERLIST_ORMASKCOUNT; ++i)
495                 serverlist_ormasks[i].info.numbots = -1;
496 }
497
498 void ServerList_GetPlayerStatistics(int *numplayerspointer, int *maxplayerspointer)
499 {
500         int i;
501         int numplayers = 0, maxplayers = 0;
502         for (i = 0;i < serverlist_cachecount;i++)
503         {
504                 if (serverlist_cache[i].query == SQS_QUERIED)
505                 {
506                         numplayers += serverlist_cache[i].info.numhumans;
507                         maxplayers += serverlist_cache[i].info.maxplayers;
508                 }
509         }
510         *numplayerspointer = numplayers;
511         *maxplayerspointer = maxplayers;
512 }
513
514 #if 0
515 static void _ServerList_Test(void)
516 {
517         int i;
518         if (serverlist_maxcachecount <= 1024)
519         {
520                 serverlist_maxcachecount = 1024;
521                 serverlist_cache = (serverlist_entry_t *)Mem_Realloc(netconn_mempool, (void *)serverlist_cache, sizeof(serverlist_entry_t) * serverlist_maxcachecount);
522         }
523         for( i = 0 ; i < 1024 ; i++ ) {
524                 memset( &serverlist_cache[serverlist_cachecount], 0, sizeof( serverlist_entry_t ) );
525                 serverlist_cache[serverlist_cachecount].info.ping = 1000 + 1024 - i;
526                 dpsnprintf( serverlist_cache[serverlist_cachecount].info.name, sizeof(serverlist_cache[serverlist_cachecount].info.name), "Black's ServerList Test %i", i );
527                 serverlist_cache[serverlist_cachecount].finished = true;
528                 dpsnprintf( serverlist_cache[serverlist_cachecount].line1, sizeof(serverlist_cache[serverlist_cachecount].info.line1), "%i %s", serverlist_cache[serverlist_cachecount].info.ping, serverlist_cache[serverlist_cachecount].info.name );
529                 ServerList_ViewList_Insert( &serverlist_cache[serverlist_cachecount] );
530                 serverlist_cachecount++;
531         }
532 }
533 #endif
534
535 void ServerList_QueryList(qboolean resetcache, qboolean querydp, qboolean queryqw, qboolean consoleoutput)
536 {
537         masterquerytime = realtime;
538         masterquerycount = 0;
539         masterreplycount = 0;
540         if( resetcache ) {
541                 serverquerycount = 0;
542                 serverreplycount = 0;
543                 serverlist_cachecount = 0;
544                 serverlist_viewcount = 0;
545                 serverlist_maxcachecount = 0;
546                 serverlist_cache = (serverlist_entry_t *)Mem_Realloc(netconn_mempool, (void *)serverlist_cache, sizeof(serverlist_entry_t) * serverlist_maxcachecount);
547         } else {
548                 // refresh all entries
549                 int n;
550                 for( n = 0 ; n < serverlist_cachecount ; n++ ) {
551                         serverlist_entry_t *entry = &serverlist_cache[ n ];
552                         entry->query = SQS_REFRESHING;
553                         entry->querycounter = 0;
554                 }
555         }
556         serverlist_consoleoutput = consoleoutput;
557
558         //_ServerList_Test();
559
560         NetConn_QueryMasters(querydp, queryqw);
561 }
562
563 // rest
564
565 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
566 {
567         int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
568         int i;
569         if (length == 0)
570                 return 0;
571         if (cl_netpacketloss_receive.integer)
572                 for (i = 0;i < cl_numsockets;i++)
573                         if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss_receive.integer)
574                                 return 0;
575         if (developer_networking.integer)
576         {
577                 char addressstring[128], addressstring2[128];
578                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
579                 if (length > 0)
580                 {
581                         LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
582                         Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", (void *)mysocket, addressstring, (void *)data, maxlength, (void *)peeraddress, length, addressstring2);
583                         Com_HexDumpToConsole((unsigned char *)data, length);
584                 }
585                 else
586                         Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", (void *)mysocket, addressstring, (void *)data, maxlength, (void *)peeraddress, length);
587         }
588         return length;
589 }
590
591 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
592 {
593         int ret;
594         int i;
595         if (cl_netpacketloss_send.integer)
596                 for (i = 0;i < cl_numsockets;i++)
597                         if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss_send.integer)
598                                 return length;
599         ret = LHNET_Write(mysocket, data, length, peeraddress);
600         if (developer_networking.integer)
601         {
602                 char addressstring[128], addressstring2[128];
603                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
604                 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
605                 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", (void *)mysocket, addressstring, (void *)data, length, (void *)peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
606                 Com_HexDumpToConsole((unsigned char *)data, length);
607         }
608         return ret;
609 }
610
611 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
612 {
613         // note this does not include the trailing NULL because we add that in the parser
614         return NetConn_Write(mysocket, string, (int)strlen(string), peeraddress);
615 }
616
617 qboolean NetConn_CanSend(netconn_t *conn)
618 {
619         conn->outgoing_packetcounter = (conn->outgoing_packetcounter + 1) % NETGRAPH_PACKETS;
620         conn->outgoing_netgraph[conn->outgoing_packetcounter].time            = realtime;
621         conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes = NETGRAPH_NOPACKET;
622         conn->outgoing_netgraph[conn->outgoing_packetcounter].reliablebytes   = NETGRAPH_NOPACKET;
623         conn->outgoing_netgraph[conn->outgoing_packetcounter].ackbytes        = NETGRAPH_NOPACKET;
624         if (realtime > conn->cleartime)
625                 return true;
626         else
627         {
628                 conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes = NETGRAPH_CHOKEDPACKET;
629                 return false;
630         }
631 }
632
633 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data, protocolversion_t protocol, int rate, qboolean quakesignon_suppressreliables)
634 {
635         int totallen = 0;
636
637         // if this packet was supposedly choked, but we find ourselves sending one
638         // anyway, make sure the size counting starts at zero
639         // (this mostly happens on level changes and disconnects and such)
640         if (conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes == NETGRAPH_CHOKEDPACKET)
641                 conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes = NETGRAPH_NOPACKET;
642
643         if (protocol == PROTOCOL_QUAKEWORLD)
644         {
645                 int packetLen;
646                 qboolean sendreliable;
647
648                 // note that it is ok to send empty messages to the qw server,
649                 // otherwise it won't respond to us at all
650
651                 sendreliable = false;
652                 // if the remote side dropped the last reliable message, resend it
653                 if (conn->qw.incoming_acknowledged > conn->qw.last_reliable_sequence && conn->qw.incoming_reliable_acknowledged != conn->qw.reliable_sequence)
654                         sendreliable = true;
655                 // if the reliable transmit buffer is empty, copy the current message out
656                 if (!conn->sendMessageLength && conn->message.cursize)
657                 {
658                         memcpy (conn->sendMessage, conn->message.data, conn->message.cursize);
659                         conn->sendMessageLength = conn->message.cursize;
660                         SZ_Clear(&conn->message); // clear the message buffer
661                         conn->qw.reliable_sequence ^= 1;
662                         sendreliable = true;
663                 }
664                 // outgoing unreliable packet number, and outgoing reliable packet number (0 or 1)
665                 StoreLittleLong(sendbuffer, (unsigned int)conn->outgoing_unreliable_sequence | ((unsigned int)sendreliable<<31));
666                 // last received unreliable packet number, and last received reliable packet number (0 or 1)
667                 StoreLittleLong(sendbuffer + 4, (unsigned int)conn->qw.incoming_sequence | ((unsigned int)conn->qw.incoming_reliable_sequence<<31));
668                 packetLen = 8;
669                 conn->outgoing_unreliable_sequence++;
670                 // client sends qport in every packet
671                 if (conn == cls.netcon)
672                 {
673                         *((short *)(sendbuffer + 8)) = LittleShort(cls.qw_qport);
674                         packetLen += 2;
675                         // also update cls.qw_outgoing_sequence
676                         cls.qw_outgoing_sequence = conn->outgoing_unreliable_sequence;
677                 }
678                 if (packetLen + (sendreliable ? conn->sendMessageLength : 0) > 1400)
679                 {
680                         Con_Printf ("NetConn_SendUnreliableMessage: reliable message too big %u\n", data->cursize);
681                         return -1;
682                 }
683
684                 conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes += packetLen + 28;
685
686                 // add the reliable message if there is one
687                 if (sendreliable)
688                 {
689                         conn->outgoing_netgraph[conn->outgoing_packetcounter].reliablebytes += conn->sendMessageLength + 28;
690                         memcpy(sendbuffer + packetLen, conn->sendMessage, conn->sendMessageLength);
691                         packetLen += conn->sendMessageLength;
692                         conn->qw.last_reliable_sequence = conn->outgoing_unreliable_sequence;
693                 }
694
695                 // add the unreliable message if possible
696                 if (packetLen + data->cursize <= 1400)
697                 {
698                         conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes += data->cursize + 28;
699                         memcpy(sendbuffer + packetLen, data->data, data->cursize);
700                         packetLen += data->cursize;
701                 }
702
703                 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
704
705                 packetsSent++;
706                 unreliableMessagesSent++;
707
708                 totallen += packetLen + 28;
709         }
710         else
711         {
712                 unsigned int packetLen;
713                 unsigned int dataLen;
714                 unsigned int eom;
715
716                 // if a reliable message fragment has been lost, send it again
717                 if (conn->sendMessageLength && (realtime - conn->lastSendTime) > 1.0)
718                 {
719                         if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
720                         {
721                                 dataLen = conn->sendMessageLength;
722                                 eom = NETFLAG_EOM;
723                         }
724                         else
725                         {
726                                 dataLen = MAX_PACKETFRAGMENT;
727                                 eom = 0;
728                         }
729
730                         packetLen = NET_HEADERSIZE + dataLen;
731
732                         StoreBigLong(sendbuffer, packetLen | (NETFLAG_DATA | eom));
733                         StoreBigLong(sendbuffer + 4, conn->nq.sendSequence - 1);
734                         memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
735
736                         conn->outgoing_netgraph[conn->outgoing_packetcounter].reliablebytes += packetLen + 28;
737
738                         if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
739                         {
740                                 conn->lastSendTime = realtime;
741                                 packetsReSent++;
742                         }
743
744                         totallen += packetLen + 28;
745                 }
746
747                 // if we have a new reliable message to send, do so
748                 if (!conn->sendMessageLength && conn->message.cursize && !quakesignon_suppressreliables)
749                 {
750                         if (conn->message.cursize > (int)sizeof(conn->sendMessage))
751                         {
752                                 Con_Printf("NetConn_SendUnreliableMessage: reliable message too big (%u > %u)\n", conn->message.cursize, (int)sizeof(conn->sendMessage));
753                                 conn->message.overflowed = true;
754                                 return -1;
755                         }
756
757                         if (developer_networking.integer && conn == cls.netcon)
758                         {
759                                 Con_Print("client sending reliable message to server:\n");
760                                 SZ_HexDumpToConsole(&conn->message);
761                         }
762
763                         memcpy(conn->sendMessage, conn->message.data, conn->message.cursize);
764                         conn->sendMessageLength = conn->message.cursize;
765                         SZ_Clear(&conn->message);
766
767                         if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
768                         {
769                                 dataLen = conn->sendMessageLength;
770                                 eom = NETFLAG_EOM;
771                         }
772                         else
773                         {
774                                 dataLen = MAX_PACKETFRAGMENT;
775                                 eom = 0;
776                         }
777
778                         packetLen = NET_HEADERSIZE + dataLen;
779
780                         StoreBigLong(sendbuffer, packetLen | (NETFLAG_DATA | eom));
781                         StoreBigLong(sendbuffer + 4, conn->nq.sendSequence);
782                         memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
783
784                         conn->nq.sendSequence++;
785
786                         conn->outgoing_netgraph[conn->outgoing_packetcounter].reliablebytes += packetLen + 28;
787
788                         NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
789
790                         conn->lastSendTime = realtime;
791                         packetsSent++;
792                         reliableMessagesSent++;
793
794                         totallen += packetLen + 28;
795                 }
796
797                 // if we have an unreliable message to send, do so
798                 if (data->cursize)
799                 {
800                         packetLen = NET_HEADERSIZE + data->cursize;
801
802                         if (packetLen > (int)sizeof(sendbuffer))
803                         {
804                                 Con_Printf("NetConn_SendUnreliableMessage: message too big %u\n", data->cursize);
805                                 return -1;
806                         }
807
808                         StoreBigLong(sendbuffer, packetLen | NETFLAG_UNRELIABLE);
809                         StoreBigLong(sendbuffer + 4, conn->outgoing_unreliable_sequence);
810                         memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
811
812                         conn->outgoing_unreliable_sequence++;
813
814                         conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes += packetLen + 28;
815
816                         NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
817
818                         packetsSent++;
819                         unreliableMessagesSent++;
820
821                         totallen += packetLen + 28;
822                 }
823         }
824
825         // delay later packets to obey rate limit
826         if (conn->cleartime < realtime - 0.1)
827                 conn->cleartime = realtime - 0.1;
828         conn->cleartime = conn->cleartime + (double)totallen / (double)rate;
829         if (conn->cleartime < realtime)
830                 conn->cleartime = realtime;
831
832         return 0;
833 }
834
835 qboolean NetConn_HaveClientPorts(void)
836 {
837         return !!cl_numsockets;
838 }
839
840 qboolean NetConn_HaveServerPorts(void)
841 {
842         return !!sv_numsockets;
843 }
844
845 void NetConn_CloseClientPorts(void)
846 {
847         for (;cl_numsockets > 0;cl_numsockets--)
848                 if (cl_sockets[cl_numsockets - 1])
849                         LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
850 }
851
852 void NetConn_OpenClientPort(const char *addressstring, lhnetaddresstype_t addresstype, int defaultport)
853 {
854         lhnetaddress_t address;
855         lhnetsocket_t *s;
856         int success;
857         char addressstring2[1024];
858         if (addressstring && addressstring[0])
859                 success = LHNETADDRESS_FromString(&address, addressstring, defaultport);
860         else
861                 success = LHNETADDRESS_FromPort(&address, addresstype, defaultport);
862         if (success)
863         {
864                 if ((s = LHNET_OpenSocket_Connectionless(&address)))
865                 {
866                         cl_sockets[cl_numsockets++] = s;
867                         LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
868                         if (addresstype != LHNETADDRESSTYPE_LOOP)
869                                 Con_Printf("Client opened a socket on address %s\n", addressstring2);
870                 }
871                 else
872                 {
873                         LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
874                         Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
875                 }
876         }
877         else
878                 Con_Printf("Client unable to parse address %s\n", addressstring);
879 }
880
881 void NetConn_OpenClientPorts(void)
882 {
883         int port;
884         NetConn_CloseClientPorts();
885         port = bound(0, cl_netport.integer, 65535);
886         if (cl_netport.integer != port)
887                 Cvar_SetValueQuick(&cl_netport, port);
888         if(port == 0)
889                 Con_Printf("Client using an automatically assigned port\n");
890         else
891                 Con_Printf("Client using port %i\n", port);
892         NetConn_OpenClientPort(NULL, LHNETADDRESSTYPE_LOOP, 2);
893         NetConn_OpenClientPort(net_address.string, LHNETADDRESSTYPE_INET4, port);
894 #ifdef SUPPORTIPV6
895         NetConn_OpenClientPort(net_address_ipv6.string, LHNETADDRESSTYPE_INET6, port);
896 #endif
897 }
898
899 void NetConn_CloseServerPorts(void)
900 {
901         for (;sv_numsockets > 0;sv_numsockets--)
902                 if (sv_sockets[sv_numsockets - 1])
903                         LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
904 }
905
906 qboolean NetConn_OpenServerPort(const char *addressstring, lhnetaddresstype_t addresstype, int defaultport, int range)
907 {
908         lhnetaddress_t address;
909         lhnetsocket_t *s;
910         int port;
911         char addressstring2[1024];
912         int success;
913
914         for (port = defaultport; port <= defaultport + range; port++)
915         {
916                 if (addressstring && addressstring[0])
917                         success = LHNETADDRESS_FromString(&address, addressstring, port);
918                 else
919                         success = LHNETADDRESS_FromPort(&address, addresstype, port);
920                 if (success)
921                 {
922                         if ((s = LHNET_OpenSocket_Connectionless(&address)))
923                         {
924                                 sv_sockets[sv_numsockets++] = s;
925                                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
926                                 if (addresstype != LHNETADDRESSTYPE_LOOP)
927                                         Con_Printf("Server listening on address %s\n", addressstring2);
928                                 return true;
929                         }
930                         else
931                         {
932                                 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
933                                 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
934                         }
935                 }
936                 else
937                 {
938                         Con_Printf("Server unable to parse address %s\n", addressstring);
939                         // if it cant parse one address, it wont be able to parse another for sure
940                         return false;
941                 }
942         }
943         return false;
944 }
945
946 void NetConn_OpenServerPorts(int opennetports)
947 {
948         int port;
949         NetConn_CloseServerPorts();
950         NetConn_UpdateSockets();
951         port = bound(0, sv_netport.integer, 65535);
952         if (port == 0)
953                 port = 26000;
954         Con_Printf("Server using port %i\n", port);
955         if (sv_netport.integer != port)
956                 Cvar_SetValueQuick(&sv_netport, port);
957         if (cls.state != ca_dedicated)
958                 NetConn_OpenServerPort(NULL, LHNETADDRESSTYPE_LOOP, 1, 1);
959         if (opennetports)
960         {
961 #ifdef SUPPORTIPV6
962                 qboolean ip4success = NetConn_OpenServerPort(net_address.string, LHNETADDRESSTYPE_INET4, port, 100);
963                 NetConn_OpenServerPort(net_address_ipv6.string, LHNETADDRESSTYPE_INET6, port, ip4success ? 1 : 100);
964 #else
965                 NetConn_OpenServerPort(net_address.string, LHNETADDRESSTYPE_INET4, port, 100);
966 #endif
967         }
968         if (sv_numsockets == 0)
969                 Host_Error("NetConn_OpenServerPorts: unable to open any ports!");
970 }
971
972 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
973 {
974         int i, a = LHNETADDRESS_GetAddressType(address);
975         for (i = 0;i < cl_numsockets;i++)
976                 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
977                         return cl_sockets[i];
978         return NULL;
979 }
980
981 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
982 {
983         int i, a = LHNETADDRESS_GetAddressType(address);
984         for (i = 0;i < sv_numsockets;i++)
985                 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
986                         return sv_sockets[i];
987         return NULL;
988 }
989
990 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
991 {
992         netconn_t *conn;
993         conn = (netconn_t *)Mem_Alloc(netconn_mempool, sizeof(*conn));
994         conn->mysocket = mysocket;
995         conn->peeraddress = *peeraddress;
996         conn->lastMessageTime = realtime;
997         conn->message.data = conn->messagedata;
998         conn->message.maxsize = sizeof(conn->messagedata);
999         conn->message.cursize = 0;
1000         // LordHavoc: (inspired by ProQuake) use a short connect timeout to
1001         // reduce effectiveness of connection request floods
1002         conn->timeout = realtime + net_connecttimeout.value;
1003         LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
1004         conn->next = netconn_list;
1005         netconn_list = conn;
1006         return conn;
1007 }
1008
1009 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress);
1010 void NetConn_Close(netconn_t *conn)
1011 {
1012         netconn_t *c;
1013         // remove connection from list
1014
1015         // allow the client to reconnect immediately
1016         NetConn_ClearConnectFlood(&(conn->peeraddress));
1017
1018         if (conn == netconn_list)
1019                 netconn_list = conn->next;
1020         else
1021         {
1022                 for (c = netconn_list;c;c = c->next)
1023                 {
1024                         if (c->next == conn)
1025                         {
1026                                 c->next = conn->next;
1027                                 break;
1028                         }
1029                 }
1030                 // not found in list, we'll avoid crashing here...
1031                 if (!c)
1032                         return;
1033         }
1034         // free connection
1035         Mem_Free(conn);
1036 }
1037
1038 static int clientport = -1;
1039 static int clientport2 = -1;
1040 static int hostport = -1;
1041 void NetConn_UpdateSockets(void)
1042 {
1043         int i, j;
1044
1045         if (cls.state != ca_dedicated)
1046         {
1047                 if (clientport2 != cl_netport.integer)
1048                 {
1049                         clientport2 = cl_netport.integer;
1050                         if (cls.state == ca_connected)
1051                                 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
1052                 }
1053                 if (cls.state == ca_disconnected && clientport != clientport2)
1054                 {
1055                         clientport = clientport2;
1056                         NetConn_CloseClientPorts();
1057                 }
1058                 if (cl_numsockets == 0)
1059                         NetConn_OpenClientPorts();
1060         }
1061
1062         if (hostport != sv_netport.integer)
1063         {
1064                 hostport = sv_netport.integer;
1065                 if (sv.active)
1066                         Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
1067         }
1068
1069         for (j = 0;j < MAX_RCONS;j++)
1070         {
1071                 i = (cls.rcon_ringpos + j + 1) % MAX_RCONS;
1072                 if(cls.rcon_commands[i][0])
1073                 {
1074                         if(realtime > cls.rcon_timeout[i])
1075                         {
1076                                 char s[128];
1077                                 LHNETADDRESS_ToString(&cls.rcon_addresses[i], s, sizeof(s), true);
1078                                 Con_Printf("rcon to %s (for command %s) failed: challenge request timed out\n", s, cls.rcon_commands[i]);
1079                                 cls.rcon_commands[i][0] = 0;
1080                                 --cls.rcon_trying;
1081                                 break;
1082                         }
1083                 }
1084         }
1085 }
1086
1087 static int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int length, protocolversion_t protocol, double newtimeout)
1088 {
1089         int originallength = length;
1090         if (length < 8)
1091                 return 0;
1092
1093         if (protocol == PROTOCOL_QUAKEWORLD)
1094         {
1095                 int sequence, sequence_ack;
1096                 int reliable_ack, reliable_message;
1097                 int count;
1098                 //int qport;
1099
1100                 sequence = LittleLong(*((int *)(data + 0)));
1101                 sequence_ack = LittleLong(*((int *)(data + 4)));
1102                 data += 8;
1103                 length -= 8;
1104
1105                 if (conn != cls.netcon)
1106                 {
1107                         // server only
1108                         if (length < 2)
1109                                 return 0;
1110                         // 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?)
1111                         //qport = LittleShort(*((int *)(data + 8)));
1112                         data += 2;
1113                         length -= 2;
1114                 }
1115
1116                 packetsReceived++;
1117                 reliable_message = (sequence >> 31) & 1;
1118                 reliable_ack = (sequence_ack >> 31) & 1;
1119                 sequence &= ~(1<<31);
1120                 sequence_ack &= ~(1<<31);
1121                 if (sequence <= conn->qw.incoming_sequence)
1122                 {
1123                         //Con_DPrint("Got a stale datagram\n");
1124                         return 0;
1125                 }
1126                 count = sequence - (conn->qw.incoming_sequence + 1);
1127                 if (count > 0)
1128                 {
1129                         droppedDatagrams += count;
1130                         //Con_DPrintf("Dropped %u datagram(s)\n", count);
1131                         while (count--)
1132                         {
1133                                 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1134                                 conn->incoming_netgraph[conn->incoming_packetcounter].time            = realtime;
1135                                 conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = NETGRAPH_LOSTPACKET;
1136                                 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes   = NETGRAPH_NOPACKET;
1137                                 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes        = NETGRAPH_NOPACKET;
1138                         }
1139                 }
1140                 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1141                 conn->incoming_netgraph[conn->incoming_packetcounter].time            = realtime;
1142                 conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = originallength + 28;
1143                 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes   = NETGRAPH_NOPACKET;
1144                 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes        = NETGRAPH_NOPACKET;
1145                 if (reliable_ack == conn->qw.reliable_sequence)
1146                 {
1147                         // received, now we will be able to send another reliable message
1148                         conn->sendMessageLength = 0;
1149                         reliableMessagesReceived++;
1150                 }
1151                 conn->qw.incoming_sequence = sequence;
1152                 if (conn == cls.netcon)
1153                         cls.qw_incoming_sequence = conn->qw.incoming_sequence;
1154                 conn->qw.incoming_acknowledged = sequence_ack;
1155                 conn->qw.incoming_reliable_acknowledged = reliable_ack;
1156                 if (reliable_message)
1157                         conn->qw.incoming_reliable_sequence ^= 1;
1158                 conn->lastMessageTime = realtime;
1159                 conn->timeout = realtime + newtimeout;
1160                 unreliableMessagesReceived++;
1161                 SZ_Clear(&net_message);
1162                 SZ_Write(&net_message, data, length);
1163                 MSG_BeginReading();
1164                 return 2;
1165         }
1166         else
1167         {
1168                 unsigned int count;
1169                 unsigned int flags;
1170                 unsigned int sequence;
1171                 int qlength;
1172
1173                 qlength = (unsigned int)BuffBigLong(data);
1174                 flags = qlength & ~NETFLAG_LENGTH_MASK;
1175                 qlength &= NETFLAG_LENGTH_MASK;
1176                 // control packets were already handled
1177                 if (!(flags & NETFLAG_CTL) && qlength == length)
1178                 {
1179                         sequence = BuffBigLong(data + 4);
1180                         packetsReceived++;
1181                         data += 8;
1182                         length -= 8;
1183                         if (flags & NETFLAG_UNRELIABLE)
1184                         {
1185                                 if (sequence >= conn->nq.unreliableReceiveSequence)
1186                                 {
1187                                         if (sequence > conn->nq.unreliableReceiveSequence)
1188                                         {
1189                                                 count = sequence - conn->nq.unreliableReceiveSequence;
1190                                                 droppedDatagrams += count;
1191                                                 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1192                                                 while (count--)
1193                                                 {
1194                                                         conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1195                                                         conn->incoming_netgraph[conn->incoming_packetcounter].time            = realtime;
1196                                                         conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = NETGRAPH_LOSTPACKET;
1197                                                         conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes   = NETGRAPH_NOPACKET;
1198                                                         conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes        = NETGRAPH_NOPACKET;
1199                                                 }
1200                                         }
1201                                         conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1202                                         conn->incoming_netgraph[conn->incoming_packetcounter].time            = realtime;
1203                                         conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = originallength + 28;
1204                                         conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes   = NETGRAPH_NOPACKET;
1205                                         conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes        = NETGRAPH_NOPACKET;
1206                                         conn->nq.unreliableReceiveSequence = sequence + 1;
1207                                         conn->lastMessageTime = realtime;
1208                                         conn->timeout = realtime + newtimeout;
1209                                         unreliableMessagesReceived++;
1210                                         if (length > 0)
1211                                         {
1212                                                 SZ_Clear(&net_message);
1213                                                 SZ_Write(&net_message, data, length);
1214                                                 MSG_BeginReading();
1215                                                 return 2;
1216                                         }
1217                                 }
1218                                 //else
1219                                 //      Con_DPrint("Got a stale datagram\n");
1220                                 return 1;
1221                         }
1222                         else if (flags & NETFLAG_ACK)
1223                         {
1224                                 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes += originallength + 28;
1225                                 if (sequence == (conn->nq.sendSequence - 1))
1226                                 {
1227                                         if (sequence == conn->nq.ackSequence)
1228                                         {
1229                                                 conn->nq.ackSequence++;
1230                                                 if (conn->nq.ackSequence != conn->nq.sendSequence)
1231                                                         Con_DPrint("ack sequencing error\n");
1232                                                 conn->lastMessageTime = realtime;
1233                                                 conn->timeout = realtime + newtimeout;
1234                                                 if (conn->sendMessageLength > MAX_PACKETFRAGMENT)
1235                                                 {
1236                                                         unsigned int packetLen;
1237                                                         unsigned int dataLen;
1238                                                         unsigned int eom;
1239
1240                                                         conn->sendMessageLength -= MAX_PACKETFRAGMENT;
1241                                                         memmove(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
1242
1243                                                         if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
1244                                                         {
1245                                                                 dataLen = conn->sendMessageLength;
1246                                                                 eom = NETFLAG_EOM;
1247                                                         }
1248                                                         else
1249                                                         {
1250                                                                 dataLen = MAX_PACKETFRAGMENT;
1251                                                                 eom = 0;
1252                                                         }
1253
1254                                                         packetLen = NET_HEADERSIZE + dataLen;
1255
1256                                                         StoreBigLong(sendbuffer, packetLen | (NETFLAG_DATA | eom));
1257                                                         StoreBigLong(sendbuffer + 4, conn->nq.sendSequence);
1258                                                         memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
1259
1260                                                         conn->nq.sendSequence++;
1261
1262                                                         if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
1263                                                         {
1264                                                                 conn->lastSendTime = realtime;
1265                                                                 packetsSent++;
1266                                                         }
1267                                                 }
1268                                                 else
1269                                                         conn->sendMessageLength = 0;
1270                                         }
1271                                         //else
1272                                         //      Con_DPrint("Duplicate ACK received\n");
1273                                 }
1274                                 //else
1275                                 //      Con_DPrint("Stale ACK received\n");
1276                                 return 1;
1277                         }
1278                         else if (flags & NETFLAG_DATA)
1279                         {
1280                                 unsigned char temppacket[8];
1281                                 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes   += originallength + 28;
1282                                 conn->outgoing_netgraph[conn->outgoing_packetcounter].ackbytes        += 8 + 28;
1283                                 StoreBigLong(temppacket, 8 | NETFLAG_ACK);
1284                                 StoreBigLong(temppacket + 4, sequence);
1285                                 NetConn_Write(conn->mysocket, (unsigned char *)temppacket, 8, &conn->peeraddress);
1286                                 if (sequence == conn->nq.receiveSequence)
1287                                 {
1288                                         conn->lastMessageTime = realtime;
1289                                         conn->timeout = realtime + newtimeout;
1290                                         conn->nq.receiveSequence++;
1291                                         if( conn->receiveMessageLength + length <= (int)sizeof( conn->receiveMessage ) ) {
1292                                                 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
1293                                                 conn->receiveMessageLength += length;
1294                                         } else {
1295                                                 Con_Printf( "Reliable message (seq: %i) too big for message buffer!\n"
1296                                                                         "Dropping the message!\n", sequence );
1297                                                 conn->receiveMessageLength = 0;
1298                                                 return 1;
1299                                         }
1300                                         if (flags & NETFLAG_EOM)
1301                                         {
1302                                                 reliableMessagesReceived++;
1303                                                 length = conn->receiveMessageLength;
1304                                                 conn->receiveMessageLength = 0;
1305                                                 if (length > 0)
1306                                                 {
1307                                                         SZ_Clear(&net_message);
1308                                                         SZ_Write(&net_message, conn->receiveMessage, length);
1309                                                         MSG_BeginReading();
1310                                                         return 2;
1311                                                 }
1312                                         }
1313                                 }
1314                                 else
1315                                         receivedDuplicateCount++;
1316                                 return 1;
1317                         }
1318                 }
1319         }
1320         return 0;
1321 }
1322
1323 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, protocolversion_t initialprotocol)
1324 {
1325         cls.connect_trying = false;
1326         M_Update_Return_Reason("");
1327         // the connection request succeeded, stop current connection and set up a new connection
1328         CL_Disconnect();
1329         // if we're connecting to a remote server, shut down any local server
1330         if (LHNETADDRESS_GetAddressType(peeraddress) != LHNETADDRESSTYPE_LOOP && sv.active)
1331                 Host_ShutdownServer ();
1332         // allocate a net connection to keep track of things
1333         cls.netcon = NetConn_Open(mysocket, peeraddress);
1334         Con_Printf("Connection accepted to %s\n", cls.netcon->address);
1335         key_dest = key_game;
1336         m_state = m_none;
1337         cls.demonum = -1;                       // not in the demo loop now
1338         cls.state = ca_connected;
1339         cls.signon = 0;                         // need all the signon messages before playing
1340         cls.protocol = initialprotocol;
1341         // reset move sequence numbering on this new connection
1342         cls.servermovesequence = 0;
1343         if (cls.protocol == PROTOCOL_QUAKEWORLD)
1344                 Cmd_ForwardStringToServer("new");
1345         if (cls.protocol == PROTOCOL_QUAKE)
1346         {
1347                 // write a keepalive (clc_nop) as it seems to greatly improve the
1348                 // chances of connecting to a netquake server
1349                 sizebuf_t msg;
1350                 unsigned char buf[4];
1351                 memset(&msg, 0, sizeof(msg));
1352                 msg.data = buf;
1353                 msg.maxsize = sizeof(buf);
1354                 MSG_WriteChar(&msg, clc_nop);
1355                 NetConn_SendUnreliableMessage(cls.netcon, &msg, cls.protocol, 10000, false);
1356         }
1357 }
1358
1359 int NetConn_IsLocalGame(void)
1360 {
1361         if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
1362                 return true;
1363         return false;
1364 }
1365
1366 static int NetConn_ClientParsePacket_ServerList_ProcessReply(const char *addressstring)
1367 {
1368         int n;
1369         int pingtime;
1370         serverlist_entry_t *entry = NULL;
1371
1372         // search the cache for this server and update it
1373         for (n = 0;n < serverlist_cachecount;n++) {
1374                 entry = &serverlist_cache[ n ];
1375                 if (!strcmp(addressstring, entry->info.cname))
1376                         break;
1377         }
1378
1379         if (n == serverlist_cachecount)
1380         {
1381                 // LAN search doesnt require an answer from the master server so we wont
1382                 // know the ping nor will it be initialized already...
1383
1384                 // find a slot
1385                 if (serverlist_cachecount == SERVERLIST_TOTALSIZE)
1386                         return -1;
1387
1388                 if (serverlist_maxcachecount <= serverlist_cachecount)
1389                 {
1390                         serverlist_maxcachecount += 64;
1391                         serverlist_cache = (serverlist_entry_t *)Mem_Realloc(netconn_mempool, (void *)serverlist_cache, sizeof(serverlist_entry_t) * serverlist_maxcachecount);
1392                 }
1393                 entry = &serverlist_cache[n];
1394
1395                 memset(entry, 0, sizeof(*entry));
1396                 // store the data the engine cares about (address and ping)
1397                 strlcpy(entry->info.cname, addressstring, sizeof(entry->info.cname));
1398                 entry->info.ping = 100000;
1399                 entry->querytime = realtime;
1400                 // if not in the slist menu we should print the server to console
1401                 if (serverlist_consoleoutput)
1402                         Con_Printf("querying %s\n", addressstring);
1403                 ++serverlist_cachecount;
1404         }
1405         // if this is the first reply from this server, count it as having replied
1406         pingtime = (int)((realtime - entry->querytime) * 1000.0 + 0.5);
1407         pingtime = bound(0, pingtime, 9999);
1408         if (entry->query == SQS_REFRESHING) {
1409                 entry->info.ping = pingtime;
1410                 entry->query = SQS_QUERIED;
1411         } else {
1412                 // convert to unsigned to catch the -1
1413                 // I still dont like this but its better than the old 10000 magic ping number - as in easier to type and read :( [11/8/2007 Black]
1414                 entry->info.ping = min((unsigned) entry->info.ping, (unsigned) pingtime);
1415                 serverreplycount++;
1416         }
1417         
1418         // other server info is updated by the caller
1419         return n;
1420 }
1421
1422 static void NetConn_ClientParsePacket_ServerList_UpdateCache(int n)
1423 {
1424         serverlist_entry_t *entry = &serverlist_cache[n];
1425         serverlist_info_t *info = &entry->info;
1426         // update description strings for engine menu and console output
1427         dpsnprintf(entry->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->numhumans > 0 && info->numhumans < info->maxplayers) ? (info->numhumans >= 4 ? '7' : '3') : '1'), info->numplayers, info->maxplayers, info->name);
1428         dpsnprintf(entry->line2, sizeof(serverlist_cache[n].line2), "^4%-21.21s %-19.19s ^%c%-17.17s^4 %-20.20s", info->cname, info->game,
1429                         (
1430                          info->gameversion != gameversion.integer
1431                          &&
1432                          !(
1433                                     gameversion_min.integer >= 0 // min/max range set by user/mod?
1434                                  && gameversion_max.integer >= 0
1435                                  && gameversion_min.integer >= info->gameversion // version of server in min/max range?
1436                                  && gameversion_max.integer <= info->gameversion
1437                           )
1438                         ) ? '1' : '4',
1439                         info->mod, info->map);
1440         if (entry->query == SQS_QUERIED)
1441         {
1442                 if(!serverlist_paused)
1443                         ServerList_ViewList_Remove(entry);
1444         }
1445         // if not in the slist menu we should print the server to console (if wanted)
1446         else if( serverlist_consoleoutput )
1447                 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1448         // and finally, update the view set
1449         if(!serverlist_paused)
1450                 ServerList_ViewList_Insert( entry );
1451         //      update the entry's state
1452         serverlist_cache[n].query = SQS_QUERIED;
1453 }
1454
1455 // returns true, if it's sensible to continue the processing
1456 static qboolean NetConn_ClientParsePacket_ServerList_PrepareQuery( int protocol, const char *ipstring, qboolean isfavorite ) {
1457         int n;
1458         serverlist_entry_t *entry;
1459
1460         //      ignore the rest of the message if the serverlist is full
1461         if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1462                 return false;
1463         //      also ignore     it      if      we      have already queried    it      (other master server    response)
1464         for( n =        0 ; n   < serverlist_cachecount ; n++   )
1465                 if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1466                         break;
1467
1468         if( n < serverlist_cachecount ) {
1469                 // the entry has already been queried once or 
1470                 return true;
1471         }
1472
1473         if (serverlist_maxcachecount <= n)
1474         {
1475                 serverlist_maxcachecount += 64;
1476                 serverlist_cache = (serverlist_entry_t *)Mem_Realloc(netconn_mempool, (void *)serverlist_cache, sizeof(serverlist_entry_t) * serverlist_maxcachecount);
1477         }
1478
1479         entry = &serverlist_cache[n];
1480
1481         memset(entry, 0, sizeof(entry));
1482         entry->protocol =       protocol;
1483         //      store   the data        the engine cares about (address and     ping)
1484         strlcpy (entry->info.cname, ipstring, sizeof(entry->info.cname));
1485
1486         entry->info.isfavorite = isfavorite;
1487         
1488         // no, then reset the ping right away
1489         entry->info.ping = -1;
1490         // we also want to increase the serverlist_cachecount then
1491         serverlist_cachecount++;
1492         serverquerycount++;
1493
1494         entry->query =  SQS_QUERYING;
1495
1496         return true;
1497 }
1498
1499 static void NetConn_ClientParsePacket_ServerList_ParseDPList(lhnetaddress_t *senderaddress, const unsigned char *data, int length, qboolean isextended)
1500 {
1501         masterreplycount++;
1502         if (serverlist_consoleoutput)
1503                 Con_Printf("received DarkPlaces %sserver list...\n", isextended ? "extended " : "");
1504         while (length >= 7)
1505         {
1506                 char ipstring [128];
1507
1508                 // IPv4 address
1509                 if (data[0] == '\\')
1510                 {
1511                         unsigned short port = data[5] * 256 + data[6];
1512
1513                         if (port != 0 && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF))
1514                                 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%hu", data[1], data[2], data[3], data[4], port);
1515
1516                         // move on to next address in packet
1517                         data += 7;
1518                         length -= 7;
1519                 }
1520                 // IPv6 address
1521                 else if (data[0] == '/' && isextended && length >= 19)
1522                 {
1523                         unsigned short port = data[17] * 256 + data[18];
1524
1525                         if (port != 0)
1526                         {
1527                                 const char *ifname;
1528
1529                                 /// \TODO: make some basic checks of the IP address (broadcast, ...)
1530
1531                                 ifname = LHNETADDRESS_GetInterfaceName(senderaddress);
1532                                 if (ifname != NULL)
1533                                 {
1534                                         dpsnprintf (ipstring, sizeof (ipstring), "[%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x%%%s]:%hu",
1535                                                                 data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8],
1536                                                                 data[9], data[10], data[11], data[12], data[13], data[14], data[15], data[16],
1537                                                                 ifname, port);
1538                                 }
1539                                 else
1540                                 {
1541                                         dpsnprintf (ipstring, sizeof (ipstring), "[%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x]:%hu",
1542                                                                 data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8],
1543                                                                 data[9], data[10], data[11], data[12], data[13], data[14], data[15], data[16],
1544                                                                 port);
1545                                 }
1546                         }
1547
1548                         // move on to next address in packet
1549                         data += 19;
1550                         length -= 19;
1551                 }
1552                 else
1553                 {
1554                         Con_Print("Error while parsing the server list\n");
1555                         break;
1556                 }
1557
1558                 if (serverlist_consoleoutput && developer_networking.integer)
1559                         Con_Printf("Requesting info from DarkPlaces server %s\n", ipstring);
1560                 
1561                 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, ipstring, false ) ) {
1562                         break;
1563                 }
1564
1565         }
1566
1567         // begin or resume serverlist queries
1568         serverlist_querysleep = false;
1569         serverlist_querywaittime = realtime + 3;
1570 }
1571
1572 static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1573 {
1574         qboolean fromserver;
1575         int ret, c, control;
1576         const char *s;
1577         char *string, addressstring2[128], ipstring[32];
1578         char stringbuf[16384];
1579
1580         // quakeworld ingame packet
1581         fromserver = cls.netcon && mysocket == cls.netcon->mysocket && !LHNETADDRESS_Compare(&cls.netcon->peeraddress, peeraddress);
1582
1583         // convert the address to a string incase we need it
1584         LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1585
1586         if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1587         {
1588                 // received a command string - strip off the packaging and put it
1589                 // into our string buffer with NULL termination
1590                 data += 4;
1591                 length -= 4;
1592                 length = min(length, (int)sizeof(stringbuf) - 1);
1593                 memcpy(stringbuf, data, length);
1594                 stringbuf[length] = 0;
1595                 string = stringbuf;
1596
1597                 if (developer_networking.integer)
1598                 {
1599                         Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
1600                         Com_HexDumpToConsole(data, length);
1601                 }
1602
1603                 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.rcon_trying)
1604                 {
1605                         int i = 0, j;
1606                         for (j = 0;j < MAX_RCONS;j++)
1607                         {
1608                                 // note: this value from i is used outside the loop too...
1609                                 i = (cls.rcon_ringpos + j) % MAX_RCONS;
1610                                 if(cls.rcon_commands[i][0])
1611                                         if (!LHNETADDRESS_Compare(peeraddress, &cls.rcon_addresses[i]))
1612                                                 break;
1613                         }
1614                         if (j < MAX_RCONS)
1615                         {
1616                                 char buf[1500];
1617                                 char argbuf[1500];
1618                                 const char *e;
1619                                 int n;
1620                                 dpsnprintf(argbuf, sizeof(argbuf), "%s %s", string + 10, cls.rcon_commands[i]);
1621                                 memcpy(buf, "\377\377\377\377srcon HMAC-MD4 CHALLENGE ", 29);
1622
1623                                 e = strchr(rcon_password.string, ' ');
1624                                 n = e ? e-rcon_password.string : (int)strlen(rcon_password.string);
1625
1626                                 if(HMAC_MDFOUR_16BYTES((unsigned char *) (buf + 29), (unsigned char *) argbuf, strlen(argbuf), (unsigned char *) rcon_password.string, n))
1627                                 {
1628                                         int k;
1629                                         buf[45] = ' ';
1630                                         strlcpy(buf + 46, argbuf, sizeof(buf) - 46);
1631                                         NetConn_Write(mysocket, buf, 46 + strlen(buf + 46), peeraddress);
1632                                         cls.rcon_commands[i][0] = 0;
1633                                         --cls.rcon_trying;
1634
1635                                         for (k = 0;k < MAX_RCONS;k++)
1636                                                 if(cls.rcon_commands[k][0])
1637                                                         if (!LHNETADDRESS_Compare(peeraddress, &cls.rcon_addresses[k]))
1638                                                                 break;
1639                                         if(k < MAX_RCONS)
1640                                         {
1641                                                 int l;
1642                                                 NetConn_WriteString(mysocket, "\377\377\377\377getchallenge", peeraddress);
1643                                                 // extend the timeout on other requests as we asked for a challenge
1644                                                 for (l = 0;l < MAX_RCONS;l++)
1645                                                         if(cls.rcon_commands[l][0])
1646                                                                 if (!LHNETADDRESS_Compare(peeraddress, &cls.rcon_addresses[l]))
1647                                                                         cls.rcon_timeout[l] = realtime + rcon_secure_challengetimeout.value;
1648                                         }
1649
1650                                         return true; // we used up the challenge, so we can't use this oen for connecting now anyway
1651                                 }
1652                         }
1653                 }
1654                 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
1655                 {
1656                         // darkplaces or quake3
1657                         char protocolnames[1400];
1658                         Protocol_Names(protocolnames, sizeof(protocolnames));
1659                         Con_DPrintf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
1660                         M_Update_Return_Reason("Got challenge response");
1661                         // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1662                         InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1663                         // TODO: add userinfo stuff here instead of using NQ commands?
1664                         NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\protocols\\%s%s\\challenge\\%s", protocolnames, cls.connect_userinfo, string + 10), peeraddress);
1665                         return true;
1666                 }
1667                 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
1668                 {
1669                         // darkplaces or quake3
1670                         M_Update_Return_Reason("Accepted");
1671                         NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_DARKPLACES3);
1672                         return true;
1673                 }
1674                 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
1675                 {
1676                         char rejectreason[32];
1677                         cls.connect_trying = false;
1678                         string += 7;
1679                         length = min(length - 7, (int)sizeof(rejectreason) - 1);
1680                         memcpy(rejectreason, string, length);
1681                         rejectreason[length] = 0;
1682                         M_Update_Return_Reason(rejectreason);
1683                         return true;
1684                 }
1685                 if (length >= 15 && !memcmp(string, "statusResponse\x0A", 15))
1686                 {
1687                         serverlist_info_t *info;
1688                         char *p;
1689                         int n;
1690
1691                         string += 15;
1692                         // search the cache for this server and update it
1693                         n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1694                         if (n < 0)
1695                                 return true;
1696
1697                         info = &serverlist_cache[n].info;
1698                         info->game[0] = 0;
1699                         info->mod[0]  = 0;
1700                         info->map[0]  = 0;
1701                         info->name[0] = 0;
1702                         info->qcstatus[0] = 0;
1703                         info->players[0] = 0;
1704                         info->protocol = -1;
1705                         info->numplayers = 0;
1706                         info->numbots = -1;
1707                         info->maxplayers  = 0;
1708                         info->gameversion = 0;
1709
1710                         p = strchr(string, '\n');
1711                         if(p)
1712                         {
1713                                 *p = 0; // cut off the string there
1714                                 ++p;
1715                         }
1716                         else
1717                                 Con_Printf("statusResponse without players block?\n");
1718
1719                         if ((s = SearchInfostring(string, "gamename"     )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1720                         if ((s = SearchInfostring(string, "modname"      )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1721                         if ((s = SearchInfostring(string, "mapname"      )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1722                         if ((s = SearchInfostring(string, "hostname"     )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1723                         if ((s = SearchInfostring(string, "protocol"     )) != NULL) info->protocol = atoi(s);
1724                         if ((s = SearchInfostring(string, "clients"      )) != NULL) info->numplayers = atoi(s);
1725                         if ((s = SearchInfostring(string, "bots"         )) != NULL) info->numbots = atoi(s);
1726                         if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1727                         if ((s = SearchInfostring(string, "gameversion"  )) != NULL) info->gameversion = atoi(s);
1728                         if ((s = SearchInfostring(string, "qcstatus"     )) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1729                         if (p                                               != NULL) strlcpy(info->players, p, sizeof(info->players));
1730                         info->numhumans = info->numplayers - max(0, info->numbots);
1731                         info->freeslots = info->maxplayers - info->numplayers;
1732
1733                         NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1734
1735                         return true;
1736                 }
1737                 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
1738                 {
1739                         serverlist_info_t *info;
1740                         int n;
1741
1742                         string += 13;
1743                         // search the cache for this server and update it
1744                         n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1745                         if (n < 0)
1746                                 return true;
1747
1748                         info = &serverlist_cache[n].info;
1749                         info->game[0] = 0;
1750                         info->mod[0]  = 0;
1751                         info->map[0]  = 0;
1752                         info->name[0] = 0;
1753                         info->qcstatus[0] = 0;
1754                         info->players[0] = 0;
1755                         info->protocol = -1;
1756                         info->numplayers = 0;
1757                         info->numbots = -1;
1758                         info->maxplayers  = 0;
1759                         info->gameversion = 0;
1760
1761                         if ((s = SearchInfostring(string, "gamename"     )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1762                         if ((s = SearchInfostring(string, "modname"      )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1763                         if ((s = SearchInfostring(string, "mapname"      )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1764                         if ((s = SearchInfostring(string, "hostname"     )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1765                         if ((s = SearchInfostring(string, "protocol"     )) != NULL) info->protocol = atoi(s);
1766                         if ((s = SearchInfostring(string, "clients"      )) != NULL) info->numplayers = atoi(s);
1767                         if ((s = SearchInfostring(string, "bots"         )) != NULL) info->numbots = atoi(s);
1768                         if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1769                         if ((s = SearchInfostring(string, "gameversion"  )) != NULL) info->gameversion = atoi(s);
1770                         if ((s = SearchInfostring(string, "qcstatus"     )) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1771                         info->numhumans = info->numplayers - max(0, info->numbots);
1772                         info->freeslots = info->maxplayers - info->numplayers;
1773
1774                         NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1775
1776                         return true;
1777                 }
1778                 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1779                 {
1780                         // Extract the IP addresses
1781                         data += 18;
1782                         length -= 18;
1783                         NetConn_ClientParsePacket_ServerList_ParseDPList(peeraddress, data, length, false);
1784                         return true;
1785                 }
1786                 if (!strncmp(string, "getserversExtResponse", 21) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1787                 {
1788                         // Extract the IP addresses
1789                         data += 21;
1790                         length -= 21;
1791                         NetConn_ClientParsePacket_ServerList_ParseDPList(peeraddress, data, length, true);
1792                         return true;
1793                 }
1794                 if (!memcmp(string, "d\n", 2) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1795                 {
1796                         // Extract the IP addresses
1797                         data += 2;
1798                         length -= 2;
1799                         masterreplycount++;
1800                         if (serverlist_consoleoutput)
1801                                 Con_Printf("received QuakeWorld server list from %s...\n", addressstring2);
1802                         while (length >= 6 && (data[0] != 0xFF || data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF) && data[4] * 256 + data[5] != 0)
1803                         {
1804                                 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[0], data[1], data[2], data[3], data[4] * 256 + data[5]);
1805                                 if (serverlist_consoleoutput && developer_networking.integer)
1806                                         Con_Printf("Requesting info from QuakeWorld server %s\n", ipstring);
1807                                 
1808                                 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, ipstring, false ) ) {
1809                                         break;
1810                                 }
1811
1812                                 // move on to next address in packet
1813                                 data += 6;
1814                                 length -= 6;
1815                         }
1816                         // begin or resume serverlist queries
1817                         serverlist_querysleep = false;
1818                         serverlist_querywaittime = realtime + 3;
1819                         return true;
1820                 }
1821                 if (!strncmp(string, "extResponse ", 12))
1822                 {
1823                         ++cl_net_extresponse_count;
1824                         if(cl_net_extresponse_count > NET_EXTRESPONSE_MAX)
1825                                 cl_net_extresponse_count = NET_EXTRESPONSE_MAX;
1826                         cl_net_extresponse_last = (cl_net_extresponse_last + 1) % NET_EXTRESPONSE_MAX;
1827                         dpsnprintf(cl_net_extresponse[cl_net_extresponse_last], sizeof(cl_net_extresponse[cl_net_extresponse_last]), "\"%s\" %s", addressstring2, string + 12);
1828                         return true;
1829                 }
1830                 if (!strncmp(string, "ping", 4))
1831                 {
1832                         if (developer_extra.integer)
1833                                 Con_DPrintf("Received ping from %s, sending ack\n", addressstring2);
1834                         NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1835                         return true;
1836                 }
1837                 if (!strncmp(string, "ack", 3))
1838                         return true;
1839                 // QuakeWorld compatibility
1840                 if (length > 1 && string[0] == 'c' && (string[1] == '-' || (string[1] >= '0' && string[1] <= '9')) && cls.connect_trying)
1841                 {
1842                         // challenge message
1843                         Con_Printf("challenge %s received, sending QuakeWorld connect request back to %s\n", string + 1, addressstring2);
1844                         M_Update_Return_Reason("Got QuakeWorld challenge response");
1845                         cls.qw_qport = qport.integer;
1846                         // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1847                         InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1848                         NetConn_WriteString(mysocket, va("\377\377\377\377connect %i %i %i \"%s%s\"\n", 28, cls.qw_qport, atoi(string + 1), cls.userinfo, cls.connect_userinfo), peeraddress);
1849                         return true;
1850                 }
1851                 if (length >= 1 && string[0] == 'j' && cls.connect_trying)
1852                 {
1853                         // accept message
1854                         M_Update_Return_Reason("QuakeWorld Accepted");
1855                         NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_QUAKEWORLD);
1856                         return true;
1857                 }
1858                 if (length > 2 && !memcmp(string, "n\\", 2))
1859                 {
1860                         serverlist_info_t *info;
1861                         int n;
1862
1863                         // qw server status
1864                         if (serverlist_consoleoutput && developer_networking.integer >= 2)
1865                                 Con_Printf("QW server status from server at %s:\n%s\n", addressstring2, string + 1);
1866
1867                         string += 1;
1868                         // search the cache for this server and update it
1869                         n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1870                         if (n < 0)
1871                                 return true;
1872
1873                         info = &serverlist_cache[n].info;
1874                         strlcpy(info->game, "QuakeWorld", sizeof(info->game));
1875                         if ((s = SearchInfostring(string, "*gamedir"     )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0]  = 0;
1876                         if ((s = SearchInfostring(string, "map"          )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0]  = 0;
1877                         if ((s = SearchInfostring(string, "hostname"     )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
1878                         info->protocol = 0;
1879                         info->numplayers = 0; // updated below
1880                         info->numhumans = 0; // updated below
1881                         if ((s = SearchInfostring(string, "maxclients"   )) != NULL) info->maxplayers = atoi(s);else info->maxplayers  = 0;
1882                         if ((s = SearchInfostring(string, "gameversion"  )) != NULL) info->gameversion = atoi(s);else info->gameversion = 0;
1883
1884                         // count active players on server
1885                         // (we could gather more info, but we're just after the number)
1886                         s = strchr(string, '\n');
1887                         if (s)
1888                         {
1889                                 s++;
1890                                 while (s < string + length)
1891                                 {
1892                                         for (;s < string + length && *s != '\n';s++)
1893                                                 ;
1894                                         if (s >= string + length)
1895                                                 break;
1896                                         info->numplayers++;
1897                                         info->numhumans++;
1898                                         s++;
1899                                 }
1900                         }
1901
1902                         NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1903
1904                         return true;
1905                 }
1906                 if (string[0] == 'n')
1907                 {
1908                         // qw print command
1909                         Con_Printf("QW print command from server at %s:\n%s\n", addressstring2, string + 1);
1910                 }
1911                 // we may not have liked the packet, but it was a command packet, so
1912                 // we're done processing this packet now
1913                 return true;
1914         }
1915         // quakeworld ingame packet
1916         if (fromserver && cls.protocol == PROTOCOL_QUAKEWORLD && length >= 8 && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1917         {
1918                 ret = 0;
1919                 CL_ParseServerMessage();
1920                 return ret;
1921         }
1922         // netquake control packets, supported for compatibility only
1923         if (length >= 5 && (control = BuffBigLong(data)) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1924         {
1925                 int n;
1926                 serverlist_info_t *info;
1927
1928                 data += 4;
1929                 length -= 4;
1930                 SZ_Clear(&net_message);
1931                 SZ_Write(&net_message, data, length);
1932                 MSG_BeginReading();
1933                 c = MSG_ReadByte();
1934                 switch (c)
1935                 {
1936                 case CCREP_ACCEPT:
1937                         if (developer_extra.integer)
1938                                 Con_DPrintf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1939                         if (cls.connect_trying)
1940                         {
1941                                 lhnetaddress_t clientportaddress;
1942                                 clientportaddress = *peeraddress;
1943                                 LHNETADDRESS_SetPort(&clientportaddress, MSG_ReadLong());
1944                                 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1945                                 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1946                                 M_Update_Return_Reason("Accepted");
1947                                 NetConn_ConnectionEstablished(mysocket, &clientportaddress, PROTOCOL_QUAKE);
1948                         }
1949                         break;
1950                 case CCREP_REJECT:
1951                         if (developer_extra.integer)
1952                                 Con_DPrintf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1953                         cls.connect_trying = false;
1954                         M_Update_Return_Reason((char *)MSG_ReadString());
1955                         break;
1956                 case CCREP_SERVER_INFO:
1957                         if (developer_extra.integer)
1958                                 Con_DPrintf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1959                         // LordHavoc: because the quake server may report weird addresses
1960                         // we just ignore it and keep the real address
1961                         MSG_ReadString();
1962                         // search the cache for this server and update it
1963                         n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1964                         if (n < 0)
1965                                 break;
1966
1967                         info = &serverlist_cache[n].info;
1968                         strlcpy(info->game, "Quake", sizeof(info->game));
1969                         strlcpy(info->mod , "", sizeof(info->mod)); // mod name is not specified
1970                         strlcpy(info->name, MSG_ReadString(), sizeof(info->name));
1971                         strlcpy(info->map , MSG_ReadString(), sizeof(info->map));
1972                         info->numplayers = MSG_ReadByte();
1973                         info->maxplayers = MSG_ReadByte();
1974                         info->protocol = MSG_ReadByte();
1975
1976                         NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1977
1978                         break;
1979                 case CCREP_RCON: // RocketGuy: ProQuake rcon support
1980                         if (developer_extra.integer)
1981                                 Con_DPrintf("Datagram_ParseConnectionless: received CCREP_RCON from %s.\n", addressstring2);
1982
1983                         Con_Printf("%s\n", MSG_ReadString());
1984                         break;
1985                 case CCREP_PLAYER_INFO:
1986                         // we got a CCREP_PLAYER_INFO??
1987                         //if (developer_extra.integer)
1988                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1989                         break;
1990                 case CCREP_RULE_INFO:
1991                         // we got a CCREP_RULE_INFO??
1992                         //if (developer_extra.integer)
1993                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1994                         break;
1995                 default:
1996                         break;
1997                 }
1998                 SZ_Clear(&net_message);
1999                 // we may not have liked the packet, but it was a valid control
2000                 // packet, so we're done processing this packet now
2001                 return true;
2002         }
2003         ret = 0;
2004         if (fromserver && length >= (int)NET_HEADERSIZE && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
2005                 CL_ParseServerMessage();
2006         return ret;
2007 }
2008
2009 void NetConn_QueryQueueFrame(void)
2010 {
2011         int index;
2012         int queries;
2013         int maxqueries;
2014         double timeouttime;
2015         static double querycounter = 0;
2016
2017         if(!net_slist_pause.integer && serverlist_paused)
2018                 ServerList_RebuildViewList();
2019         serverlist_paused = net_slist_pause.integer != 0;
2020
2021         if (serverlist_querysleep)
2022                 return;
2023
2024         // apply a cool down time after master server replies,
2025         // to avoid messing up the ping times on the servers
2026         if (serverlist_querywaittime > realtime)
2027                 return;
2028
2029         // each time querycounter reaches 1.0 issue a query
2030         querycounter += cl.realframetime * net_slist_queriespersecond.value;
2031         maxqueries = (int)querycounter;
2032         maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer);
2033         querycounter -= maxqueries;
2034
2035         if( maxqueries == 0 ) {
2036                 return;
2037         }
2038
2039         //      scan serverlist and issue queries as needed
2040         serverlist_querysleep = true;
2041
2042         timeouttime     = realtime - net_slist_timeout.value;
2043         for( index = 0, queries = 0 ;   index   < serverlist_cachecount &&      queries < maxqueries    ; index++ )
2044         {
2045                 serverlist_entry_t *entry = &serverlist_cache[ index ];
2046                 if( entry->query != SQS_QUERYING && entry->query != SQS_REFRESHING )
2047                 {
2048                         continue;
2049                 }
2050
2051                 serverlist_querysleep   = false;
2052                 if( entry->querycounter !=      0 && entry->querytime > timeouttime     )
2053                 {
2054                         continue;
2055                 }
2056
2057                 if( entry->querycounter !=      (unsigned) net_slist_maxtries.integer )
2058                 {
2059                         lhnetaddress_t  address;
2060                         int socket;
2061
2062                         LHNETADDRESS_FromString(&address, entry->info.cname, 0);
2063                         if      (entry->protocol == PROTOCOL_QUAKEWORLD)
2064                         {
2065                                 for (socket     = 0; socket     < cl_numsockets ;       socket++)
2066                                         NetConn_WriteString(cl_sockets[socket], "\377\377\377\377status\n", &address);
2067                         }
2068                         else
2069                         {
2070                                 for (socket     = 0; socket     < cl_numsockets ;       socket++)
2071                                         NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getstatus", &address);
2072                         }
2073
2074                         //      update the entry fields
2075                         entry->querytime = realtime;
2076                         entry->querycounter++;
2077
2078                         // if not in the slist menu we should print the server to console
2079                         if (serverlist_consoleoutput)
2080                                 Con_Printf("querying %25s (%i. try)\n", entry->info.cname, entry->querycounter);
2081
2082                         queries++;
2083                 }
2084                 else
2085                 {
2086                         // have we tried to refresh this server?
2087                         if( entry->query == SQS_REFRESHING ) {
2088                                 // yes, so update the reply count (since its not responding anymore)
2089                                 serverreplycount--;
2090                                 if(!serverlist_paused)
2091                                         ServerList_ViewList_Remove(entry);
2092                         }
2093                         entry->query = SQS_TIMEDOUT;
2094                 }
2095         }
2096 }
2097
2098 void NetConn_ClientFrame(void)
2099 {
2100         int i, length;
2101         lhnetaddress_t peeraddress;
2102         NetConn_UpdateSockets();
2103         if (cls.connect_trying && cls.connect_nextsendtime < realtime)
2104         {
2105                 if (cls.connect_remainingtries == 0)
2106                         M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
2107                 cls.connect_nextsendtime = realtime + 1;
2108                 cls.connect_remainingtries--;
2109                 if (cls.connect_remainingtries <= -10)
2110                 {
2111                         cls.connect_trying = false;
2112                         M_Update_Return_Reason("Connect: Failed");
2113                         return;
2114                 }
2115                 // try challenge first (newer DP server or QW)
2116                 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
2117                 // then try netquake as a fallback (old server, or netquake)
2118                 SZ_Clear(&net_message);
2119                 // save space for the header, filled in later
2120                 MSG_WriteLong(&net_message, 0);
2121                 MSG_WriteByte(&net_message, CCREQ_CONNECT);
2122                 MSG_WriteString(&net_message, "QUAKE");
2123                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2124                 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2125                 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
2126                 SZ_Clear(&net_message);
2127         }
2128         for (i = 0;i < cl_numsockets;i++)
2129         {
2130                 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2131                 {
2132 //                      R_TimeReport("clientreadnetwork");
2133                         NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
2134 //                      R_TimeReport("clientparsepacket");
2135                 }
2136         }
2137         NetConn_QueryQueueFrame();
2138         if (cls.netcon && realtime > cls.netcon->timeout && !sv.active)
2139         {
2140                 Con_Print("Connection timed out\n");
2141                 CL_Disconnect();
2142                 Host_ShutdownServer ();
2143         }
2144 }
2145
2146 #define MAX_CHALLENGES 128
2147 struct challenge_s
2148 {
2149         lhnetaddress_t address;
2150         double time;
2151         char string[12];
2152 }
2153 challenge[MAX_CHALLENGES];
2154
2155 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
2156 {
2157         int i;
2158         char c;
2159         for (i = 0;i < bufferlength - 1;i++)
2160         {
2161                 do
2162                 {
2163                         c = rand () % (127 - 33) + 33;
2164                 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
2165                 buffer[i] = c;
2166         }
2167         buffer[i] = 0;
2168 }
2169
2170 /// (div0) build the full response only if possible; better a getinfo response than no response at all if getstatus won't fit
2171 static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg, size_t out_size, qboolean fullstatus)
2172 {
2173         char qcstatus[256];
2174         unsigned int nb_clients = 0, nb_bots = 0, i;
2175         int length;
2176         char teambuf[3];
2177
2178         SV_VM_Begin();
2179
2180         // How many clients are there?
2181         for (i = 0;i < (unsigned int)svs.maxclients;i++)
2182         {
2183                 if (svs.clients[i].active)
2184                 {
2185                         nb_clients++;
2186                         if (!svs.clients[i].netconnection)
2187                                 nb_bots++;
2188                 }
2189         }
2190
2191         *qcstatus = 0;
2192         if(prog->globaloffsets.worldstatus >= 0)
2193         {
2194                 const char *str = PRVM_G_STRING(prog->globaloffsets.worldstatus);
2195                 if(str && *str)
2196                 {
2197                         char *p;
2198                         const char *q;
2199                         p = qcstatus;
2200                         for(q = str; *q; ++q)
2201                                 if(*q != '\\' && *q != '\n')
2202                                         *p++ = *q;
2203                         *p = 0;
2204                 }
2205         }
2206
2207         /// \TODO: we should add more information for the full status string
2208         length = dpsnprintf(out_msg, out_size,
2209                                                 "\377\377\377\377%s\x0A"
2210                                                 "\\gamename\\%s\\modname\\%s\\gameversion\\%d\\sv_maxclients\\%d"
2211                                                 "\\clients\\%d\\bots\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d"
2212                                                 "%s%s"
2213                                                 "%s%s"
2214                                                 "%s",
2215                                                 fullstatus ? "statusResponse" : "infoResponse",
2216                                                 gamename, com_modname, gameversion.integer, svs.maxclients,
2217                                                 nb_clients, nb_bots, sv.worldbasename, hostname.string, NET_PROTOCOL_VERSION,
2218                                                 *qcstatus ? "\\qcstatus\\" : "", qcstatus,
2219                                                 challenge ? "\\challenge\\" : "", challenge ? challenge : "",
2220                                                 fullstatus ? "\n" : "");
2221
2222         // Make sure it fits in the buffer
2223         if (length < 0)
2224                 goto bad;
2225
2226         if (fullstatus)
2227         {
2228                 char *ptr;
2229                 int left;
2230                 int savelength;
2231
2232                 savelength = length;
2233
2234                 ptr = out_msg + length;
2235                 left = (int)out_size - length;
2236
2237                 for (i = 0;i < (unsigned int)svs.maxclients;i++)
2238                 {
2239                         client_t *cl = &svs.clients[i];
2240                         if (cl->active)
2241                         {
2242                                 int nameind, cleanind, pingvalue;
2243                                 char curchar;
2244                                 char cleanname [sizeof(cl->name)];
2245
2246                                 // Remove all characters '"' and '\' in the player name
2247                                 nameind = 0;
2248                                 cleanind = 0;
2249                                 do
2250                                 {
2251                                         curchar = cl->name[nameind++];
2252                                         if (curchar != '"' && curchar != '\\')
2253                                         {
2254                                                 cleanname[cleanind++] = curchar;
2255                                                 if (cleanind == sizeof(cleanname) - 1)
2256                                                         break;
2257                                         }
2258                                 } while (curchar != '\0');
2259                                 cleanname[cleanind] = 0; // cleanind is always a valid index even at this point
2260
2261                                 pingvalue = (int)(cl->ping * 1000.0f);
2262                                 if(cl->netconnection)
2263                                         pingvalue = bound(1, pingvalue, 9999);
2264                                 else
2265                                         pingvalue = 0;
2266
2267                                 *qcstatus = 0;
2268                                 if(prog->fieldoffsets.clientstatus >= 0)
2269                                 {
2270                                         const char *str = PRVM_E_STRING(PRVM_EDICT_NUM(i + 1), prog->fieldoffsets.clientstatus);
2271                                         if(str && *str)
2272                                         {
2273                                                 char *p;
2274                                                 const char *q;
2275                                                 p = qcstatus;
2276                                                 for(q = str; *q && p != qcstatus + sizeof(qcstatus) - 1; ++q)
2277                                                         if(*q != '\\' && *q != '"' && !ISWHITESPACE(*q))
2278                                                                 *p++ = *q;
2279                                                 *p = 0;
2280                                         }
2281                                 }
2282
2283                                 if ((gamemode == GAME_NEXUIZ || gamemode == GAME_XONOTIC) && (teamplay.integer > 0))
2284                                 {
2285                                         if(cl->frags == -666) // spectator
2286                                                 strlcpy(teambuf, " 0", sizeof(teambuf));
2287                                         else if(cl->colors == 0x44) // red team
2288                                                 strlcpy(teambuf, " 1", sizeof(teambuf));
2289                                         else if(cl->colors == 0xDD) // blue team
2290                                                 strlcpy(teambuf, " 2", sizeof(teambuf));
2291                                         else if(cl->colors == 0xCC) // yellow team
2292                                                 strlcpy(teambuf, " 3", sizeof(teambuf));
2293                                         else if(cl->colors == 0x99) // pink team
2294                                                 strlcpy(teambuf, " 4", sizeof(teambuf));
2295                                         else
2296                                                 strlcpy(teambuf, " 0", sizeof(teambuf));
2297                                 }
2298                                 else
2299                                         *teambuf = 0;
2300
2301                                 // note: team number is inserted according to SoF2 protocol
2302                                 if(*qcstatus)
2303                                         length = dpsnprintf(ptr, left, "%s %d%s \"%s\"\n",
2304                                                                                 qcstatus,
2305                                                                                 pingvalue,
2306                                                                                 teambuf,
2307                                                                                 cleanname);
2308                                 else
2309                                         length = dpsnprintf(ptr, left, "%d %d%s \"%s\"\n",
2310                                                                                 cl->frags,
2311                                                                                 pingvalue,
2312                                                                                 teambuf,
2313                                                                                 cleanname);
2314
2315                                 if(length < 0)
2316                                 {
2317                                         // out of space?
2318                                         // turn it into an infoResponse!
2319                                         out_msg[savelength] = 0;
2320                                         memcpy(out_msg + 4, "infoResponse\x0A", 13);
2321                                         memmove(out_msg + 17, out_msg + 19, savelength - 19);
2322                                         break;
2323                                 }
2324                                 left -= length;
2325                                 ptr += length;
2326                         }
2327                 }
2328         }
2329
2330         SV_VM_End();
2331         return true;
2332
2333 bad:
2334         SV_VM_End();
2335         return false;
2336 }
2337
2338 static qboolean NetConn_PreventConnectFlood(lhnetaddress_t *peeraddress)
2339 {
2340         int floodslotnum, bestfloodslotnum;
2341         double bestfloodtime;
2342         lhnetaddress_t noportpeeraddress;
2343         // see if this is a connect flood
2344         noportpeeraddress = *peeraddress;
2345         LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2346         bestfloodslotnum = 0;
2347         bestfloodtime = sv.connectfloodaddresses[bestfloodslotnum].lasttime;
2348         for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2349         {
2350                 if (bestfloodtime >= sv.connectfloodaddresses[floodslotnum].lasttime)
2351                 {
2352                         bestfloodtime = sv.connectfloodaddresses[floodslotnum].lasttime;
2353                         bestfloodslotnum = floodslotnum;
2354                 }
2355                 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2356                 {
2357                         // this address matches an ongoing flood address
2358                         if (realtime < sv.connectfloodaddresses[floodslotnum].lasttime + net_connectfloodblockingtimeout.value)
2359                         {
2360                                 // renew the ban on this address so it does not expire
2361                                 // until the flood has subsided
2362                                 sv.connectfloodaddresses[floodslotnum].lasttime = realtime;
2363                                 //Con_Printf("Flood detected!\n");
2364                                 return true;
2365                         }
2366                         // the flood appears to have subsided, so allow this
2367                         bestfloodslotnum = floodslotnum; // reuse the same slot
2368                         break;
2369                 }
2370         }
2371         // begin a new timeout on this address
2372         sv.connectfloodaddresses[bestfloodslotnum].address = noportpeeraddress;
2373         sv.connectfloodaddresses[bestfloodslotnum].lasttime = realtime;
2374         //Con_Printf("Flood detection initiated!\n");
2375         return false;
2376 }
2377
2378 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress)
2379 {
2380         int floodslotnum;
2381         lhnetaddress_t noportpeeraddress;
2382         // see if this is a connect flood
2383         noportpeeraddress = *peeraddress;
2384         LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2385         for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2386         {
2387                 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2388                 {
2389                         // this address matches an ongoing flood address
2390                         // remove the ban
2391                         sv.connectfloodaddresses[floodslotnum].address.addresstype = LHNETADDRESSTYPE_NONE;
2392                         sv.connectfloodaddresses[floodslotnum].lasttime = 0;
2393                         //Con_Printf("Flood cleared!\n");
2394                 }
2395         }
2396 }
2397
2398 typedef qboolean (*rcon_matchfunc_t) (lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen);
2399
2400 qboolean hmac_mdfour_time_matching(lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen)
2401 {
2402         char mdfourbuf[16];
2403         long t1, t2;
2404
2405         t1 = (long) time(NULL);
2406         t2 = strtol(s, NULL, 0);
2407         if(abs(t1 - t2) > rcon_secure_maxdiff.integer)
2408                 return false;
2409
2410         if(!HMAC_MDFOUR_16BYTES((unsigned char *) mdfourbuf, (unsigned char *) s, slen, (unsigned char *) password, strlen(password)))
2411                 return false;
2412
2413         return !memcmp(mdfourbuf, hash, 16);
2414 }
2415
2416 qboolean hmac_mdfour_challenge_matching(lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen)
2417 {
2418         char mdfourbuf[16];
2419         int i;
2420
2421         if(slen < (int)(sizeof(challenge[0].string)) - 1)
2422                 return false;
2423
2424         // validate the challenge
2425         for (i = 0;i < MAX_CHALLENGES;i++)
2426                 if(challenge[i].time > 0)
2427                         if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strncmp(challenge[i].string, s, sizeof(challenge[0].string) - 1))
2428                                 break;
2429         // if the challenge is not recognized, drop the packet
2430         if (i == MAX_CHALLENGES)
2431                 return false;
2432
2433         if(!HMAC_MDFOUR_16BYTES((unsigned char *) mdfourbuf, (unsigned char *) s, slen, (unsigned char *) password, strlen(password)))
2434                 return false;
2435
2436         if(memcmp(mdfourbuf, hash, 16))
2437                 return false;
2438
2439         // unmark challenge to prevent replay attacks
2440         challenge[i].time = 0;
2441
2442         return true;
2443 }
2444
2445 qboolean plaintext_matching(lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen)
2446 {
2447         return !strcmp(password, hash);
2448 }
2449
2450 /// returns a string describing the user level, or NULL for auth failure
2451 const char *RCon_Authenticate(lhnetaddress_t *peeraddress, const char *password, const char *s, const char *endpos, rcon_matchfunc_t comparator, const char *cs, int cslen)
2452 {
2453         const char *text, *userpass_start, *userpass_end, *userpass_startpass;
2454         static char buf[MAX_INPUTLINE];
2455         qboolean hasquotes;
2456         qboolean restricted = false;
2457         qboolean have_usernames = false;
2458
2459         userpass_start = rcon_password.string;
2460         while((userpass_end = strchr(userpass_start, ' ')))
2461         {
2462                 have_usernames = true;
2463                 strlcpy(buf, userpass_start, ((size_t)(userpass_end-userpass_start) >= sizeof(buf)) ? (int)(sizeof(buf)) : (int)(userpass_end-userpass_start+1));
2464                 if(buf[0])
2465                         if(comparator(peeraddress, buf, password, cs, cslen))
2466                                 goto allow;
2467                 userpass_start = userpass_end + 1;
2468         }
2469         if(userpass_start[0])
2470         {
2471                 userpass_end = userpass_start + strlen(userpass_start);
2472                 if(comparator(peeraddress, userpass_start, password, cs, cslen))
2473                         goto allow;
2474         }
2475
2476         restricted = true;
2477         have_usernames = false;
2478         userpass_start = rcon_restricted_password.string;
2479         while((userpass_end = strchr(userpass_start, ' ')))
2480         {
2481                 have_usernames = true;
2482                 strlcpy(buf, userpass_start, ((size_t)(userpass_end-userpass_start) >= sizeof(buf)) ? (int)(sizeof(buf)) : (int)(userpass_end-userpass_start+1));
2483                 if(buf[0])
2484                         if(comparator(peeraddress, buf, password, cs, cslen))
2485                                 goto check;
2486                 userpass_start = userpass_end + 1;
2487         }
2488         if(userpass_start[0])
2489         {
2490                 userpass_end = userpass_start + strlen(userpass_start);
2491                 if(comparator(peeraddress, userpass_start, password, cs, cslen))
2492                         goto check;
2493         }
2494         
2495         return NULL; // DENIED
2496
2497 check:
2498         for(text = s; text != endpos; ++text)
2499                 if((signed char) *text > 0 && ((signed char) *text < (signed char) ' ' || *text == ';'))
2500                         return NULL; // block possible exploits against the parser/alias expansion
2501
2502         while(s != endpos)
2503         {
2504                 size_t l = strlen(s);
2505                 if(l)
2506                 {
2507                         hasquotes = (strchr(s, '"') != NULL);
2508                         // sorry, we can't allow these substrings in wildcard expressions,
2509                         // as they can mess with the argument counts
2510                         text = rcon_restricted_commands.string;
2511                         while(COM_ParseToken_Console(&text))
2512                         {
2513                                 // com_token now contains a pattern to check for...
2514                                 if(strchr(com_token, '*') || strchr(com_token, '?')) // wildcard expression, * can only match a SINGLE argument
2515                                 {
2516                                         if(!hasquotes)
2517                                                 if(matchpattern_with_separator(s, com_token, true, " ", true)) // note how we excluded tab, newline etc. above
2518                                                         goto match;
2519                                 }
2520                                 else if(strchr(com_token, ' ')) // multi-arg expression? must match in whole
2521                                 {
2522                                         if(!strcmp(com_token, s))
2523                                                 goto match;
2524                                 }
2525                                 else // single-arg expression? must match the beginning of the command
2526                                 {
2527                                         if(!strcmp(com_token, s))
2528                                                 goto match;
2529                                         if(!memcmp(va("%s ", com_token), s, strlen(com_token) + 1))
2530                                                 goto match;
2531                                 }
2532                         }
2533                         // if we got here, nothing matched!
2534                         return NULL;
2535                 }
2536 match:
2537                 s += l + 1;
2538         }
2539
2540 allow:
2541         userpass_startpass = strchr(userpass_start, ':');
2542         if(have_usernames && userpass_startpass && userpass_startpass < userpass_end)
2543                 return va("%srcon (username %.*s)", restricted ? "restricted " : "", (int)(userpass_startpass-userpass_start), userpass_start);
2544
2545         return va("%srcon", restricted ? "restricted " : "");
2546 }
2547
2548 void RCon_Execute(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, const char *addressstring2, const char *userlevel, const char *s, const char *endpos)
2549 {
2550         if(userlevel)
2551         {
2552                 // looks like a legitimate rcon command with the correct password
2553                 const char *s_ptr = s;
2554                 Con_Printf("server received %s command from %s: ", userlevel, host_client ? host_client->name : addressstring2);
2555                 while(s_ptr != endpos)
2556                 {
2557                         size_t l = strlen(s_ptr);
2558                         if(l)
2559                                 Con_Printf(" %s;", s_ptr);
2560                         s_ptr += l + 1;
2561                 }
2562                 Con_Printf("\n");
2563
2564                 if (!host_client || !host_client->netconnection || LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2565                         Con_Rcon_Redirect_Init(mysocket, peeraddress);
2566                 while(s != endpos)
2567                 {
2568                         size_t l = strlen(s);
2569                         if(l)
2570                         {
2571                                 client_t *host_client_save = host_client;
2572                                 Cmd_ExecuteString(s, src_command);
2573                                 host_client = host_client_save;
2574                                 // in case it is a command that changes host_client (like restart)
2575                         }
2576                         s += l + 1;
2577                 }
2578                 Con_Rcon_Redirect_End();
2579         }
2580         else
2581         {
2582                 Con_Printf("server denied rcon access to %s\n", host_client ? host_client->name : addressstring2);
2583         }
2584 }
2585
2586 extern void SV_SendServerinfo (client_t *client);
2587 static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
2588 {
2589         int i, ret, clientnum, best;
2590         double besttime;
2591         client_t *client;
2592         char *s, *string, response[1400], addressstring2[128];
2593         static char stringbuf[16384];
2594         qboolean islocal = (LHNETADDRESS_GetAddressType(peeraddress) == LHNETADDRESSTYPE_LOOP);
2595
2596         if (!sv.active)
2597                 return false;
2598
2599         // convert the address to a string incase we need it
2600         LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
2601
2602         // see if we can identify the sender as a local player
2603         // (this is necessary for rcon to send a reliable reply if the client is
2604         //  actually on the server, not sending remotely)
2605         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2606                 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
2607                         break;
2608         if (i == svs.maxclients)
2609                 host_client = NULL;
2610
2611         if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
2612         {
2613                 // received a command string - strip off the packaging and put it
2614                 // into our string buffer with NULL termination
2615                 data += 4;
2616                 length -= 4;
2617                 length = min(length, (int)sizeof(stringbuf) - 1);
2618                 memcpy(stringbuf, data, length);
2619                 stringbuf[length] = 0;
2620                 string = stringbuf;
2621
2622                 if (developer_extra.integer)
2623                 {
2624                         Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
2625                         Com_HexDumpToConsole(data, length);
2626                 }
2627
2628                 if (length >= 12 && !memcmp(string, "getchallenge", 12) && (islocal || sv_public.integer > -3))
2629                 {
2630                         for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
2631                         {
2632                                 if(challenge[i].time > 0)
2633                                         if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
2634                                                 break;
2635                                 if (besttime > challenge[i].time)
2636                                         besttime = challenge[best = i].time;
2637                         }
2638                         // if we did not find an exact match, choose the oldest and
2639                         // update address and string
2640                         if (i == MAX_CHALLENGES)
2641                         {
2642                                 i = best;
2643                                 challenge[i].address = *peeraddress;
2644                                 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
2645                         }
2646                         challenge[i].time = realtime;
2647                         // send the challenge
2648                         NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
2649                         return true;
2650                 }
2651                 if (length > 8 && !memcmp(string, "connect\\", 8))
2652                 {
2653                         string += 7;
2654                         length -= 7;
2655
2656                         if (!(s = SearchInfostring(string, "challenge")))
2657                                 return true;
2658                         // validate the challenge
2659                         for (i = 0;i < MAX_CHALLENGES;i++)
2660                                 if(challenge[i].time > 0)
2661                                         if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
2662                                                 break;
2663                         // if the challenge is not recognized, drop the packet
2664                         if (i == MAX_CHALLENGES)
2665                                 return true;
2666
2667                         if(!(islocal || sv_public.integer > -2))
2668                         {
2669                                 if (developer_extra.integer)
2670                                         Con_Printf("Datagram_ParseConnectionless: sending \"reject %s\" to %s.\n", sv_public_rejectreason.string, addressstring2);
2671                                 NetConn_WriteString(mysocket, va("\377\377\377\377reject %s", sv_public_rejectreason.string), peeraddress);
2672                                 return true;
2673                         }
2674
2675                         // check engine protocol
2676                         if(!(s = SearchInfostring(string, "protocol")) || strcmp(s, "darkplaces 3"))
2677                         {
2678                                 if (developer_extra.integer)
2679                                         Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
2680                                 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
2681                                 return true;
2682                         }
2683
2684                         // see if this is a duplicate connection request or a disconnected
2685                         // client who is rejoining to the same client slot
2686                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2687                         {
2688                                 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2689                                 {
2690                                         // this is a known client...
2691                                         if (client->spawned)
2692                                         {
2693                                                 // client crashed and is coming back,
2694                                                 // keep their stuff intact
2695                                                 if (developer_extra.integer)
2696                                                         Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", addressstring2);
2697                                                 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2698                                                 SV_VM_Begin();
2699                                                 SV_SendServerinfo(client);
2700                                                 SV_VM_End();
2701                                         }
2702                                         else
2703                                         {
2704                                                 // client is still trying to connect,
2705                                                 // so we send a duplicate reply
2706                                                 if (developer_extra.integer)
2707                                                         Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
2708                                                 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2709                                         }
2710                                         return true;
2711                                 }
2712                         }
2713
2714                         if (NetConn_PreventConnectFlood(peeraddress))
2715                                 return true;
2716
2717                         // find an empty client slot for this new client
2718                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2719                         {
2720                                 netconn_t *conn;
2721                                 if (!client->active && (conn = NetConn_Open(mysocket, peeraddress)))
2722                                 {
2723                                         // allocated connection
2724                                         if (developer_extra.integer)
2725                                                 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
2726                                         NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2727                                         // now set up the client
2728                                         SV_VM_Begin();
2729                                         SV_ConnectClient(clientnum, conn);
2730                                         SV_VM_End();
2731                                         NetConn_Heartbeat(1);
2732                                         return true;
2733                                 }
2734                         }
2735
2736                         // no empty slots found - server is full
2737                         if (developer_extra.integer)
2738                                 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
2739                         NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
2740
2741                         return true;
2742                 }
2743                 if (length >= 7 && !memcmp(string, "getinfo", 7) && (islocal || sv_public.integer > -1))
2744                 {
2745                         const char *challenge = NULL;
2746
2747                         // If there was a challenge in the getinfo message
2748                         if (length > 8 && string[7] == ' ')
2749                                 challenge = string + 8;
2750
2751                         if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
2752                         {
2753                                 if (developer_extra.integer)
2754                                         Con_DPrintf("Sending reply to master %s - %s\n", addressstring2, response);
2755                                 NetConn_WriteString(mysocket, response, peeraddress);
2756                         }
2757                         return true;
2758                 }
2759                 if (length >= 9 && !memcmp(string, "getstatus", 9) && (islocal || sv_public.integer > -1))
2760                 {
2761                         const char *challenge = NULL;
2762
2763                         // If there was a challenge in the getinfo message
2764                         if (length > 10 && string[9] == ' ')
2765                                 challenge = string + 10;
2766
2767                         if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
2768                         {
2769                                 if (developer_extra.integer)
2770                                         Con_DPrintf("Sending reply to client %s - %s\n", addressstring2, response);
2771                                 NetConn_WriteString(mysocket, response, peeraddress);
2772                         }
2773                         return true;
2774                 }
2775                 if (length >= 37 && !memcmp(string, "srcon HMAC-MD4 TIME ", 20))
2776                 {
2777                         char *password = string + 20;
2778                         char *timeval = string + 37;
2779                         char *s = strchr(timeval, ' ');
2780                         char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2781                         const char *userlevel;
2782
2783                         if(rcon_secure.integer > 1)
2784                                 return true;
2785
2786                         if(!s)
2787                                 return true; // invalid packet
2788                         ++s;
2789
2790                         userlevel = RCon_Authenticate(peeraddress, password, s, endpos, hmac_mdfour_time_matching, timeval, endpos - timeval - 1); // not including the appended \0 into the HMAC
2791                         RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2792                         return true;
2793                 }
2794                 if (length >= 42 && !memcmp(string, "srcon HMAC-MD4 CHALLENGE ", 25))
2795                 {
2796                         char *password = string + 25;
2797                         char *challenge = string + 42;
2798                         char *s = strchr(challenge, ' ');
2799                         char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2800                         const char *userlevel;
2801                         if(!s)
2802                                 return true; // invalid packet
2803                         ++s;
2804
2805                         userlevel = RCon_Authenticate(peeraddress, password, s, endpos, hmac_mdfour_challenge_matching, challenge, endpos - challenge - 1); // not including the appended \0 into the HMAC
2806                         RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2807                         return true;
2808                 }
2809                 if (length >= 5 && !memcmp(string, "rcon ", 5))
2810                 {
2811                         int i;
2812                         char *s = string + 5;
2813                         char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2814                         char password[64];
2815
2816                         if(rcon_secure.integer > 0)
2817                                 return true;
2818
2819                         for (i = 0;!ISWHITESPACE(*s);s++)
2820                                 if (i < (int)sizeof(password) - 1)
2821                                         password[i++] = *s;
2822                         if(ISWHITESPACE(*s) && s != endpos) // skip leading ugly space
2823                                 ++s;
2824                         password[i] = 0;
2825                         if (!ISWHITESPACE(password[0]))
2826                         {
2827                                 const char *userlevel = RCon_Authenticate(peeraddress, password, s, endpos, plaintext_matching, NULL, 0);
2828                                 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2829                         }
2830                         return true;
2831                 }
2832                 if (!strncmp(string, "extResponse ", 12))
2833                 {
2834                         ++sv_net_extresponse_count;
2835                         if(sv_net_extresponse_count > NET_EXTRESPONSE_MAX)
2836                                 sv_net_extresponse_count = NET_EXTRESPONSE_MAX;
2837                         sv_net_extresponse_last = (sv_net_extresponse_last + 1) % NET_EXTRESPONSE_MAX;
2838                         dpsnprintf(sv_net_extresponse[sv_net_extresponse_last], sizeof(sv_net_extresponse[sv_net_extresponse_last]), "'%s' %s", addressstring2, string + 12);
2839                         return true;
2840                 }
2841                 if (!strncmp(string, "ping", 4))
2842                 {
2843                         if (developer_extra.integer)
2844                                 Con_DPrintf("Received ping from %s, sending ack\n", addressstring2);
2845                         NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
2846                         return true;
2847                 }
2848                 if (!strncmp(string, "ack", 3))
2849                         return true;
2850                 // we may not have liked the packet, but it was a command packet, so
2851                 // we're done processing this packet now
2852                 return true;
2853         }
2854         // netquake control packets, supported for compatibility only, and only
2855         // when running game protocols that are normally served via this connection
2856         // protocol
2857         // (this protects more modern protocols against being used for
2858         //  Quake packet flood Denial Of Service attacks)
2859         if (length >= 5 && (i = BuffBigLong(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_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3 || sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3))
2860         {
2861                 int c;
2862                 int protocolnumber;
2863                 const char *protocolname;
2864                 data += 4;
2865                 length -= 4;
2866                 SZ_Clear(&net_message);
2867                 SZ_Write(&net_message, data, length);
2868                 MSG_BeginReading();
2869                 c = MSG_ReadByte();
2870                 switch (c)
2871                 {
2872                 case CCREQ_CONNECT:
2873                         if (developer_extra.integer)
2874                                 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
2875                         if(!(islocal || sv_public.integer > -2))
2876                         {
2877                                 if (developer_extra.integer)
2878                                         Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_REJECT \"%s\" to %s.\n", sv_public_rejectreason.string, addressstring2);
2879                                 SZ_Clear(&net_message);
2880                                 // save space for the header, filled in later
2881                                 MSG_WriteLong(&net_message, 0);
2882                                 MSG_WriteByte(&net_message, CCREP_REJECT);
2883                                 MSG_WriteString(&net_message, va("%s\n", sv_public_rejectreason.string));
2884                                 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2885                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2886                                 SZ_Clear(&net_message);
2887                                 break;
2888                         }
2889
2890                         protocolname = MSG_ReadString();
2891                         protocolnumber = MSG_ReadByte();
2892                         if (strcmp(protocolname, "QUAKE") || protocolnumber != NET_PROTOCOL_VERSION)
2893                         {
2894                                 if (developer_extra.integer)
2895                                         Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
2896                                 SZ_Clear(&net_message);
2897                                 // save space for the header, filled in later
2898                                 MSG_WriteLong(&net_message, 0);
2899                                 MSG_WriteByte(&net_message, CCREP_REJECT);
2900                                 MSG_WriteString(&net_message, "Incompatible version.\n");
2901                                 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2902                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2903                                 SZ_Clear(&net_message);
2904                                 break;
2905                         }
2906
2907                         // see if this connect request comes from a known client
2908                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2909                         {
2910                                 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2911                                 {
2912                                         // this is either a duplicate connection request
2913                                         // or coming back from a timeout
2914                                         // (if so, keep their stuff intact)
2915
2916                                         // send a reply
2917                                         if (developer_extra.integer)
2918                                                 Con_DPrintf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
2919                                         SZ_Clear(&net_message);
2920                                         // save space for the header, filled in later
2921                                         MSG_WriteLong(&net_message, 0);
2922                                         MSG_WriteByte(&net_message, CCREP_ACCEPT);
2923                                         MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
2924                                         StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2925                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2926                                         SZ_Clear(&net_message);
2927
2928                                         // if client is already spawned, re-send the
2929                                         // serverinfo message as they'll need it to play
2930                                         if (client->spawned)
2931                                         {
2932                                                 SV_VM_Begin();
2933                                                 SV_SendServerinfo(client);
2934                                                 SV_VM_End();
2935                                         }
2936                                         return true;
2937                                 }
2938                         }
2939
2940                         // this is a new client, check for connection flood
2941                         if (NetConn_PreventConnectFlood(peeraddress))
2942                                 break;
2943
2944                         // find a slot for the new client
2945                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2946                         {
2947                                 netconn_t *conn;
2948                                 if (!client->active && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
2949                                 {
2950                                         // connect to the client
2951                                         // everything is allocated, just fill in the details
2952                                         strlcpy (conn->address, addressstring2, sizeof (conn->address));
2953                                         if (developer_extra.integer)
2954                                                 Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
2955                                         // send back the info about the server connection
2956                                         SZ_Clear(&net_message);
2957                                         // save space for the header, filled in later
2958                                         MSG_WriteLong(&net_message, 0);
2959                                         MSG_WriteByte(&net_message, CCREP_ACCEPT);
2960                                         MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
2961                                         StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2962                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2963                                         SZ_Clear(&net_message);
2964                                         // now set up the client struct
2965                                         SV_VM_Begin();
2966                                         SV_ConnectClient(clientnum, conn);
2967                                         SV_VM_End();
2968                                         NetConn_Heartbeat(1);
2969                                         return true;
2970                                 }
2971                         }
2972
2973                         if (developer_extra.integer)
2974                                 Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
2975                         // no room; try to let player know
2976                         SZ_Clear(&net_message);
2977                         // save space for the header, filled in later
2978                         MSG_WriteLong(&net_message, 0);
2979                         MSG_WriteByte(&net_message, CCREP_REJECT);
2980                         MSG_WriteString(&net_message, "Server is full.\n");
2981                         StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2982                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2983                         SZ_Clear(&net_message);
2984                         break;
2985                 case CCREQ_SERVER_INFO:
2986                         if (developer_extra.integer)
2987                                 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
2988                         if(!(islocal || sv_public.integer > -1))
2989                                 break;
2990                         if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
2991                         {
2992                                 int numclients;
2993                                 char myaddressstring[128];
2994                                 if (developer_extra.integer)
2995                                         Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
2996                                 SZ_Clear(&net_message);
2997                                 // save space for the header, filled in later
2998                                 MSG_WriteLong(&net_message, 0);
2999                                 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
3000                                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), myaddressstring, sizeof(myaddressstring), true);
3001                                 MSG_WriteString(&net_message, myaddressstring);
3002                                 MSG_WriteString(&net_message, hostname.string);
3003                                 MSG_WriteString(&net_message, sv.name);
3004                                 // How many clients are there?
3005                                 for (i = 0, numclients = 0;i < svs.maxclients;i++)
3006                                         if (svs.clients[i].active)
3007                                                 numclients++;
3008                                 MSG_WriteByte(&net_message, numclients);
3009                                 MSG_WriteByte(&net_message, svs.maxclients);
3010                                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
3011                                 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
3012                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
3013                                 SZ_Clear(&net_message);
3014                         }
3015                         break;
3016                 case CCREQ_PLAYER_INFO:
3017                         if (developer_extra.integer)
3018                                 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
3019                         if(!(islocal || sv_public.integer > -1))
3020                                 break;
3021                         if (sv.active)
3022                         {
3023                                 int playerNumber, activeNumber, clientNumber;
3024                                 client_t *client;
3025
3026                                 playerNumber = MSG_ReadByte();
3027                                 activeNumber = -1;
3028                                 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
3029                                         if (client->active && ++activeNumber == playerNumber)
3030                                                 break;
3031                                 if (clientNumber != svs.maxclients)
3032                                 {
3033                                         SZ_Clear(&net_message);
3034                                         // save space for the header, filled in later
3035                                         MSG_WriteLong(&net_message, 0);
3036                                         MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
3037                                         MSG_WriteByte(&net_message, playerNumber);
3038                                         MSG_WriteString(&net_message, client->name);
3039                                         MSG_WriteLong(&net_message, client->colors);
3040                                         MSG_WriteLong(&net_message, client->frags);
3041                                         MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
3042                                         MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
3043                                         StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
3044                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
3045                                         SZ_Clear(&net_message);
3046                                 }
3047                         }
3048                         break;
3049                 case CCREQ_RULE_INFO:
3050                         if (developer_extra.integer)
3051                                 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
3052                         if(!(islocal || sv_public.integer > -1))
3053                                 break;
3054                         if (sv.active)
3055                         {
3056                                 char *prevCvarName;
3057                                 cvar_t *var;
3058
3059                                 // find the search start location
3060                                 prevCvarName = MSG_ReadString();
3061                                 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
3062
3063                                 // send the response
3064                                 SZ_Clear(&net_message);
3065                                 // save space for the header, filled in later
3066                                 MSG_WriteLong(&net_message, 0);
3067                                 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
3068                                 if (var)
3069                                 {
3070                                         MSG_WriteString(&net_message, var->name);
3071                                         MSG_WriteString(&net_message, var->string);
3072                                 }
3073                                 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
3074                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
3075                                 SZ_Clear(&net_message);
3076                         }
3077                         break;
3078                 default:
3079                         break;
3080                 }
3081                 SZ_Clear(&net_message);
3082                 // we may not have liked the packet, but it was a valid control
3083                 // packet, so we're done processing this packet now
3084                 return true;
3085         }
3086         if (host_client)
3087         {
3088                 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length, sv.protocol, host_client->spawned ? net_messagetimeout.value : net_connecttimeout.value)) == 2)
3089                 {
3090                         SV_VM_Begin();
3091                         SV_ReadClientMessage();
3092                         SV_VM_End();
3093                         return ret;
3094                 }
3095         }
3096         return 0;
3097 }
3098
3099 void NetConn_ServerFrame(void)
3100 {
3101         int i, length;
3102         lhnetaddress_t peeraddress;
3103         for (i = 0;i < sv_numsockets;i++)
3104                 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
3105                         NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
3106         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
3107         {
3108                 // never timeout loopback connections
3109                 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
3110                 {
3111                         Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
3112                         SV_VM_Begin();
3113                         SV_DropClient(false);
3114                         SV_VM_End();
3115                 }
3116         }
3117 }
3118
3119 void NetConn_SleepMicroseconds(int microseconds)
3120 {
3121         LHNET_SleepUntilPacket_Microseconds(microseconds);
3122 }
3123
3124 void NetConn_QueryMasters(qboolean querydp, qboolean queryqw)
3125 {
3126         int i, j;
3127         int masternum;
3128         lhnetaddress_t masteraddress;
3129         lhnetaddress_t broadcastaddress;
3130         char request[256];
3131
3132         if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
3133                 return;
3134
3135         // 26000 is the default quake server port, servers on other ports will not
3136         // be found
3137         // note this is IPv4-only, I doubt there are IPv6-only LANs out there
3138         LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
3139
3140         if (querydp)
3141         {
3142                 for (i = 0;i < cl_numsockets;i++)
3143                 {
3144                         if (cl_sockets[i])
3145                         {
3146                                 const char *cmdname, *extraoptions;
3147                                 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
3148
3149                                 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
3150                                 {
3151                                         // search LAN for Quake servers
3152                                         SZ_Clear(&net_message);
3153                                         // save space for the header, filled in later
3154                                         MSG_WriteLong(&net_message, 0);
3155                                         MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
3156                                         MSG_WriteString(&net_message, "QUAKE");
3157                                         MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
3158                                         StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
3159                                         NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
3160                                         SZ_Clear(&net_message);
3161
3162                                         // search LAN for DarkPlaces servers
3163                                         NetConn_WriteString(cl_sockets[i], "\377\377\377\377getstatus", &broadcastaddress);
3164                                 }
3165
3166                                 // build the getservers message to send to the dpmaster master servers
3167                                 if (LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == LHNETADDRESSTYPE_INET6)
3168                                 {
3169                                         cmdname = "getserversExt";
3170                                         extraoptions = " ipv4 ipv6";  // ask for IPv4 and IPv6 servers
3171                                 }
3172                                 else
3173                                 {
3174                                         cmdname = "getservers";
3175                                         extraoptions = "";
3176                                 }
3177                                 dpsnprintf(request, sizeof(request), "\377\377\377\377%s %s %u empty full%s", cmdname, gamename, NET_PROTOCOL_VERSION, extraoptions);
3178
3179                                 // search internet
3180                                 for (masternum = 0;sv_masters[masternum].name;masternum++)
3181                                 {
3182                                         if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == af)
3183                                         {
3184                                                 masterquerycount++;
3185                                                 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
3186                                         }
3187                                 }
3188
3189                                 // search favorite servers
3190                                 for(j = 0; j < nFavorites; ++j)
3191                                 {
3192                                         if(LHNETADDRESS_GetAddressType(&favorites[j]) == af)
3193                                         {
3194                                                 if(LHNETADDRESS_ToString(&favorites[j], request, sizeof(request), true))
3195                                                         NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, request, true );
3196                                         }
3197                                 }
3198                         }
3199                 }
3200         }
3201
3202         // only query QuakeWorld servers when the user wants to
3203         if (queryqw)
3204         {
3205                 for (i = 0;i < cl_numsockets;i++)
3206                 {
3207                         if (cl_sockets[i])
3208                         {
3209                                 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
3210
3211                                 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
3212                                 {
3213                                         // search LAN for QuakeWorld servers
3214                                         NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &broadcastaddress);
3215