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