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