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