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