]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - netconn.c
93199c116a7a8b7319200cb0c9a7b1372c78867e
[xonotic/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         HMAC_MDFOUR_16BYTES((unsigned char *) mdfourbuf, (unsigned char *) s, slen, (unsigned char *) password, strlen(password));
2196         return !memcmp(mdfourbuf, hash, 16);
2197 }
2198
2199 qboolean plaintext_matching(const char *password, const char *hash, const char *s, int slen)
2200 {
2201         return !strcmp(password, hash);
2202 }
2203
2204 // returns a string describing the user level, or NULL for auth failure
2205 const char *RCon_Authenticate(const char *password, const char *s, const char *endpos, rcon_matchfunc_t comparator, const char *cs, int cslen)
2206 {
2207         const char *text;
2208         qboolean hasquotes;
2209
2210         if(comparator(rcon_password.string, password, cs, cslen))
2211                 return "rcon";
2212         
2213         if(!comparator(rcon_restricted_password.string, password, cs, cslen))
2214                 return NULL;
2215
2216         for(text = s; text != endpos; ++text)
2217                 if((signed char) *text > 0 && ((signed char) *text < (signed char) ' ' || *text == ';'))
2218                         return NULL; // block possible exploits against the parser/alias expansion
2219
2220         while(s != endpos)
2221         {
2222                 size_t l = strlen(s);
2223                 if(l)
2224                 {
2225                         hasquotes = (strchr(s, '"') != NULL);
2226                         // sorry, we can't allow these substrings in wildcard expressions,
2227                         // as they can mess with the argument counts
2228                         text = rcon_restricted_commands.string;
2229                         while(COM_ParseToken_Console(&text))
2230                         {
2231                                 // com_token now contains a pattern to check for...
2232                                 if(strchr(com_token, '*') || strchr(com_token, '?')) // wildcard expression, * can only match a SINGLE argument
2233                                 {
2234                                         if(!hasquotes)
2235                                                 if(matchpattern_with_separator(s, com_token, true, " ", true)) // note how we excluded tab, newline etc. above
2236                                                         goto match;
2237                                 }
2238                                 else if(strchr(com_token, ' ')) // multi-arg expression? must match in whole
2239                                 {
2240                                         if(!strcmp(com_token, s))
2241                                                 goto match;
2242                                 }
2243                                 else // single-arg expression? must match the beginning of the command
2244                                 {
2245                                         if(!strcmp(com_token, s))
2246                                                 goto match;
2247                                         if(!memcmp(va("%s ", com_token), s, strlen(com_token) + 1))
2248                                                 goto match;
2249                                 }
2250                         }
2251                         // if we got here, nothing matched!
2252                         return NULL;
2253                 }
2254 match:
2255                 s += l + 1;
2256         }
2257
2258         return "restricted rcon";
2259 }
2260
2261 void RCon_Execute(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, const char *addressstring2, const char *userlevel, const char *s, const char *endpos)
2262 {
2263         if(userlevel)
2264         {
2265                 // looks like a legitimate rcon command with the correct password
2266                 const char *s_ptr = s;
2267                 Con_Printf("server received %s command from %s: ", userlevel, host_client ? host_client->name : addressstring2);
2268                 while(s_ptr != endpos)
2269                 {
2270                         size_t l = strlen(s_ptr);
2271                         if(l)
2272                                 Con_Printf(" %s;", s_ptr);
2273                         s_ptr += l + 1;
2274                 }
2275                 Con_Printf("\n");
2276
2277                 if (!host_client || !host_client->netconnection || LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2278                         Con_Rcon_Redirect_Init(mysocket, peeraddress);
2279                 while(s != endpos)
2280                 {
2281                         size_t l = strlen(s);
2282                         if(l)
2283                         {
2284                                 client_t *host_client_save = host_client;
2285                                 Cmd_ExecuteString(s, src_command);
2286                                 host_client = host_client_save;
2287                                 // in case it is a command that changes host_client (like restart)
2288                         }
2289                         s += l + 1;
2290                 }
2291                 Con_Rcon_Redirect_End();
2292         }
2293         else
2294         {
2295                 Con_Printf("server denied rcon access to %s\n", host_client ? host_client->name : addressstring2);
2296         }
2297 }
2298
2299 extern void SV_SendServerinfo (client_t *client);
2300 static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
2301 {
2302         int i, ret, clientnum, best;
2303         double besttime;
2304         client_t *client;
2305         char *s, *string, response[1400], addressstring2[128], stringbuf[16384];
2306         qboolean islocal = (LHNETADDRESS_GetAddressType(peeraddress) == LHNETADDRESSTYPE_LOOP);
2307
2308         if (!sv.active)
2309                 return false;
2310
2311         // convert the address to a string incase we need it
2312         LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
2313
2314         // see if we can identify the sender as a local player
2315         // (this is necessary for rcon to send a reliable reply if the client is
2316         //  actually on the server, not sending remotely)
2317         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2318                 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
2319                         break;
2320         if (i == svs.maxclients)
2321                 host_client = NULL;
2322
2323         if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
2324         {
2325                 // received a command string - strip off the packaging and put it
2326                 // into our string buffer with NULL termination
2327                 data += 4;
2328                 length -= 4;
2329                 length = min(length, (int)sizeof(stringbuf) - 1);
2330                 memcpy(stringbuf, data, length);
2331                 stringbuf[length] = 0;
2332                 string = stringbuf;
2333
2334                 if (developer.integer >= 10)
2335                 {
2336                         Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
2337                         Com_HexDumpToConsole(data, length);
2338                 }
2339
2340                 if (length >= 12 && !memcmp(string, "getchallenge", 12) && (islocal || sv_public.integer > -2))
2341                 {
2342                         for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
2343                         {
2344                                 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
2345                                         break;
2346                                 if (besttime > challenge[i].time)
2347                                         besttime = challenge[best = i].time;
2348                         }
2349                         // if we did not find an exact match, choose the oldest and
2350                         // update address and string
2351                         if (i == MAX_CHALLENGES)
2352                         {
2353                                 i = best;
2354                                 challenge[i].address = *peeraddress;
2355                                 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
2356                         }
2357                         challenge[i].time = realtime;
2358                         // send the challenge
2359                         NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
2360                         return true;
2361                 }
2362                 if (length > 8 && !memcmp(string, "connect\\", 8) && (islocal || sv_public.integer > -2))
2363                 {
2364                         string += 7;
2365                         length -= 7;
2366
2367                         if (!(s = SearchInfostring(string, "challenge")))
2368                                 return true;
2369                         // validate the challenge
2370                         for (i = 0;i < MAX_CHALLENGES;i++)
2371                                 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
2372                                         break;
2373                         // if the challenge is not recognized, drop the packet
2374                         if (i == MAX_CHALLENGES)
2375                                 return true;
2376
2377                         // check engine protocol
2378                         if(!(s = SearchInfostring(string, "protocol")) || strcmp(s, "darkplaces 3"))
2379                         {
2380                                 if (developer.integer >= 10)
2381                                         Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
2382                                 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
2383                                 return true;
2384                         }
2385
2386                         // see if this is a duplicate connection request or a disconnected
2387                         // client who is rejoining to the same client slot
2388                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2389                         {
2390                                 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2391                                 {
2392                                         // this is a known client...
2393                                         if (client->spawned)
2394                                         {
2395                                                 // client crashed and is coming back,
2396                                                 // keep their stuff intact
2397                                                 if (developer.integer >= 10)
2398                                                         Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", addressstring2);
2399                                                 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2400                                                 SV_VM_Begin();
2401                                                 SV_SendServerinfo(client);
2402                                                 SV_VM_End();
2403                                         }
2404                                         else
2405                                         {
2406                                                 // client is still trying to connect,
2407                                                 // so we send a duplicate reply
2408                                                 if (developer.integer >= 10)
2409                                                         Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
2410                                                 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2411                                         }
2412                                         return true;
2413                                 }
2414                         }
2415
2416                         if (NetConn_PreventConnectFlood(peeraddress))
2417                                 return true;
2418
2419                         // find an empty client slot for this new client
2420                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2421                         {
2422                                 netconn_t *conn;
2423                                 if (!client->active && (conn = NetConn_Open(mysocket, peeraddress)))
2424                                 {
2425                                         // allocated connection
2426                                         if (developer.integer >= 10)
2427                                                 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
2428                                         NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2429                                         // now set up the client
2430                                         SV_VM_Begin();
2431                                         SV_ConnectClient(clientnum, conn);
2432                                         SV_VM_End();
2433                                         NetConn_Heartbeat(1);
2434                                         return true;
2435                                 }
2436                         }
2437
2438                         // no empty slots found - server is full
2439                         if (developer.integer >= 10)
2440                                 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
2441                         NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
2442
2443                         return true;
2444                 }
2445                 if (length >= 7 && !memcmp(string, "getinfo", 7) && (islocal || sv_public.integer > -1))
2446                 {
2447                         const char *challenge = NULL;
2448
2449                         // If there was a challenge in the getinfo message
2450                         if (length > 8 && string[7] == ' ')
2451                                 challenge = string + 8;
2452
2453                         if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
2454                         {
2455                                 if (developer.integer >= 10)
2456                                         Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
2457                                 NetConn_WriteString(mysocket, response, peeraddress);
2458                         }
2459                         return true;
2460                 }
2461                 if (length >= 9 && !memcmp(string, "getstatus", 9) && (islocal || sv_public.integer > -1))
2462                 {
2463                         const char *challenge = NULL;
2464
2465                         // If there was a challenge in the getinfo message
2466                         if (length > 10 && string[9] == ' ')
2467                                 challenge = string + 10;
2468
2469                         if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
2470                         {
2471                                 if (developer.integer >= 10)
2472                                         Con_Printf("Sending reply to client %s - %s\n", addressstring2, response);
2473                                 NetConn_WriteString(mysocket, response, peeraddress);
2474                         }
2475                         return true;
2476                 }
2477                 if (length >= 37 && !memcmp(string, "srcon HMAC-MD4 TIME ", 20))
2478                 {
2479                         char *password = string + 20;
2480                         char *timeval = string + 37;
2481                         char *s = strchr(timeval, ' ');
2482                         char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2483                         const char *userlevel;
2484                         if(!s)
2485                                 return true; // invalid packet
2486                         ++s;
2487
2488                         userlevel = RCon_Authenticate(password, s, endpos, hmac_mdfour_matching, timeval, endpos - timeval - 1); // not including the appended \0 into the HMAC
2489                         RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2490                         return true;
2491                 }
2492                 if (length >= 5 && !memcmp(string, "rcon ", 5))
2493                 {
2494                         int i;
2495                         char *s = string + 5;
2496                         char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2497                         char password[64];
2498
2499                         if(rcon_secure.integer)
2500                                 return true;
2501
2502                         for (i = 0;!ISWHITESPACE(*s);s++)
2503                                 if (i < (int)sizeof(password) - 1)
2504                                         password[i++] = *s;
2505                         if(ISWHITESPACE(*s) && s != endpos) // skip leading ugly space
2506                                 ++s;
2507                         password[i] = 0;
2508                         if (!ISWHITESPACE(password[0]))
2509                         {
2510                                 const char *userlevel = RCon_Authenticate(password, s, endpos, plaintext_matching, NULL, 0);
2511                                 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2512                         }
2513                         return true;
2514                 }
2515                 if (!strncmp(string, "ping", 4))
2516                 {
2517                         if (developer.integer >= 10)
2518                                 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
2519                         NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
2520                         return true;
2521                 }
2522                 if (!strncmp(string, "ack", 3))
2523                         return true;
2524                 // we may not have liked the packet, but it was a command packet, so
2525                 // we're done processing this packet now
2526                 return true;
2527         }
2528         // netquake control packets, supported for compatibility only, and only
2529         // when running game protocols that are normally served via this connection
2530         // protocol
2531         // (this protects more modern protocols against being used for
2532         //  Quake packet flood Denial Of Service attacks)
2533         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))
2534         {
2535                 int c;
2536                 int protocolnumber;
2537                 const char *protocolname;
2538                 data += 4;
2539                 length -= 4;
2540                 SZ_Clear(&net_message);
2541                 SZ_Write(&net_message, data, length);
2542                 MSG_BeginReading();
2543                 c = MSG_ReadByte();
2544                 switch (c)
2545                 {
2546                 case CCREQ_CONNECT:
2547                         if (developer.integer >= 10)
2548                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
2549                         if(!islocal && sv_public.integer <= -2)
2550                                 break;
2551
2552                         protocolname = MSG_ReadString();
2553                         protocolnumber = MSG_ReadByte();
2554                         if (strcmp(protocolname, "QUAKE") || protocolnumber != NET_PROTOCOL_VERSION)
2555                         {
2556                                 if (developer.integer >= 10)
2557                                         Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
2558                                 SZ_Clear(&net_message);
2559                                 // save space for the header, filled in later
2560                                 MSG_WriteLong(&net_message, 0);
2561                                 MSG_WriteByte(&net_message, CCREP_REJECT);
2562                                 MSG_WriteString(&net_message, "Incompatible version.\n");
2563                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2564                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2565                                 SZ_Clear(&net_message);
2566                                 break;
2567                         }
2568
2569                         // see if this connect request comes from a known client
2570                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2571                         {
2572                                 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2573                                 {
2574                                         // this is either a duplicate connection request
2575                                         // or coming back from a timeout
2576                                         // (if so, keep their stuff intact)
2577
2578                                         // send a reply
2579                                         if (developer.integer >= 10)
2580                                                 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
2581                                         SZ_Clear(&net_message);
2582                                         // save space for the header, filled in later
2583                                         MSG_WriteLong(&net_message, 0);
2584                                         MSG_WriteByte(&net_message, CCREP_ACCEPT);
2585                                         MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
2586                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2587                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2588                                         SZ_Clear(&net_message);
2589
2590                                         // if client is already spawned, re-send the
2591                                         // serverinfo message as they'll need it to play
2592                                         if (client->spawned)
2593                                         {
2594                                                 SV_VM_Begin();
2595                                                 SV_SendServerinfo(client);
2596                                                 SV_VM_End();
2597                                         }
2598                                         return true;
2599                                 }
2600                         }
2601
2602                         // this is a new client, check for connection flood
2603                         if (NetConn_PreventConnectFlood(peeraddress))
2604                                 break;
2605
2606                         // find a slot for the new client
2607                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2608                         {
2609                                 netconn_t *conn;
2610                                 if (!client->active && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
2611                                 {
2612                                         // connect to the client
2613                                         // everything is allocated, just fill in the details
2614                                         strlcpy (conn->address, addressstring2, sizeof (conn->address));
2615                                         if (developer.integer >= 10)
2616                                                 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
2617                                         // send back the info about the server connection
2618                                         SZ_Clear(&net_message);
2619                                         // save space for the header, filled in later
2620                                         MSG_WriteLong(&net_message, 0);
2621                                         MSG_WriteByte(&net_message, CCREP_ACCEPT);
2622                                         MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
2623                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2624                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2625                                         SZ_Clear(&net_message);
2626                                         // now set up the client struct
2627                                         SV_VM_Begin();
2628                                         SV_ConnectClient(clientnum, conn);
2629                                         SV_VM_End();
2630                                         NetConn_Heartbeat(1);
2631                                         return true;
2632                                 }
2633                         }
2634
2635                         if (developer.integer >= 10)
2636                                 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
2637                         // no room; try to let player know
2638                         SZ_Clear(&net_message);
2639                         // save space for the header, filled in later
2640                         MSG_WriteLong(&net_message, 0);
2641                         MSG_WriteByte(&net_message, CCREP_REJECT);
2642                         MSG_WriteString(&net_message, "Server is full.\n");
2643                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2644                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2645                         SZ_Clear(&net_message);
2646                         break;
2647                 case CCREQ_SERVER_INFO:
2648                         if (developer.integer >= 10)
2649                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
2650                         if(!islocal && sv_public.integer <= -1)
2651                                 break;
2652                         if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
2653                         {
2654                                 int numclients;
2655                                 char myaddressstring[128];
2656                                 if (developer.integer >= 10)
2657                                         Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
2658                                 SZ_Clear(&net_message);
2659                                 // save space for the header, filled in later
2660                                 MSG_WriteLong(&net_message, 0);
2661                                 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
2662                                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), myaddressstring, sizeof(myaddressstring), true);
2663                                 MSG_WriteString(&net_message, myaddressstring);
2664                                 MSG_WriteString(&net_message, hostname.string);
2665                                 MSG_WriteString(&net_message, sv.name);
2666                                 // How many clients are there?
2667                                 for (i = 0, numclients = 0;i < svs.maxclients;i++)
2668                                         if (svs.clients[i].active)
2669                                                 numclients++;
2670                                 MSG_WriteByte(&net_message, numclients);
2671                                 MSG_WriteByte(&net_message, svs.maxclients);
2672                                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2673                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2674                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2675                                 SZ_Clear(&net_message);
2676                         }
2677                         break;
2678                 case CCREQ_PLAYER_INFO:
2679                         if (developer.integer >= 10)
2680                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
2681                         if(!islocal && sv_public.integer <= -1)
2682                                 break;
2683                         if (sv.active)
2684                         {
2685                                 int playerNumber, activeNumber, clientNumber;
2686                                 client_t *client;
2687
2688                                 playerNumber = MSG_ReadByte();
2689                                 activeNumber = -1;
2690                                 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
2691                                         if (client->active && ++activeNumber == playerNumber)
2692                                                 break;
2693                                 if (clientNumber != svs.maxclients)
2694                                 {
2695                                         SZ_Clear(&net_message);
2696                                         // save space for the header, filled in later
2697                                         MSG_WriteLong(&net_message, 0);
2698                                         MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
2699                                         MSG_WriteByte(&net_message, playerNumber);
2700                                         MSG_WriteString(&net_message, client->name);
2701                                         MSG_WriteLong(&net_message, client->colors);
2702                                         MSG_WriteLong(&net_message, client->frags);
2703                                         MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
2704                                         MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
2705                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2706                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2707                                         SZ_Clear(&net_message);
2708                                 }
2709                         }
2710                         break;
2711                 case CCREQ_RULE_INFO:
2712                         if (developer.integer >= 10)
2713                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
2714                         if(!islocal && sv_public.integer <= -1)
2715                                 break;
2716                         if (sv.active)
2717                         {
2718                                 char *prevCvarName;
2719                                 cvar_t *var;
2720
2721                                 // find the search start location
2722                                 prevCvarName = MSG_ReadString();
2723                                 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
2724
2725                                 // send the response
2726                                 SZ_Clear(&net_message);
2727                                 // save space for the header, filled in later
2728                                 MSG_WriteLong(&net_message, 0);
2729                                 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
2730                                 if (var)
2731                                 {
2732                                         MSG_WriteString(&net_message, var->name);
2733                                         MSG_WriteString(&net_message, var->string);
2734                                 }
2735                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2736                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2737                                 SZ_Clear(&net_message);
2738                         }
2739                         break;
2740                 default:
2741                         break;
2742                 }
2743                 SZ_Clear(&net_message);
2744                 // we may not have liked the packet, but it was a valid control
2745                 // packet, so we're done processing this packet now
2746                 return true;
2747         }
2748         if (host_client)
2749         {
2750                 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length, sv.protocol, host_client->spawned ? net_messagetimeout.value : net_connecttimeout.value)) == 2)
2751                 {
2752                         SV_VM_Begin();
2753                         SV_ReadClientMessage();
2754                         SV_VM_End();
2755                         return ret;
2756                 }
2757         }
2758         return 0;
2759 }
2760
2761 void NetConn_ServerFrame(void)
2762 {
2763         int i, length;
2764         lhnetaddress_t peeraddress;
2765         for (i = 0;i < sv_numsockets;i++)
2766                 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2767                         NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
2768         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2769         {
2770                 // never timeout loopback connections
2771                 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2772                 {
2773                         Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
2774                         SV_VM_Begin();
2775                         SV_DropClient(false);
2776                         SV_VM_End();
2777                 }
2778         }
2779 }
2780
2781 void NetConn_SleepMicroseconds(int microseconds)
2782 {
2783         LHNET_SleepUntilPacket_Microseconds(microseconds);
2784 }
2785
2786 void NetConn_QueryMasters(qboolean querydp, qboolean queryqw)
2787 {
2788         int i;
2789         int masternum;
2790         lhnetaddress_t masteraddress;
2791         lhnetaddress_t broadcastaddress;
2792         lhnetaddress_t serveraddress;
2793         const char *text;
2794         char request[256];
2795
2796         if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
2797                 return;
2798
2799         // 26000 is the default quake server port, servers on other ports will not
2800         // be found
2801         // note this is IPv4-only, I doubt there are IPv6-only LANs out there
2802         LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
2803
2804         if (querydp)
2805         {
2806                 for (i = 0;i < cl_numsockets;i++)
2807                 {
2808                         if (cl_sockets[i])
2809                         {
2810                                 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
2811
2812                                 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
2813                                 {
2814                                         // search LAN for Quake servers
2815                                         SZ_Clear(&net_message);
2816                                         // save space for the header, filled in later
2817                                         MSG_WriteLong(&net_message, 0);
2818                                         MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
2819                                         MSG_WriteString(&net_message, "QUAKE");
2820                                         MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2821                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2822                                         NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
2823                                         SZ_Clear(&net_message);
2824
2825                                         // search LAN for DarkPlaces servers
2826                                         NetConn_WriteString(cl_sockets[i], "\377\377\377\377getstatus", &broadcastaddress);
2827                                 }
2828
2829                                 // build the getservers message to send to the dpmaster master servers
2830                                 dpsnprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
2831
2832                                 // search internet
2833                                 for (masternum = 0;sv_masters[masternum].name;masternum++)
2834                                 {
2835                                         if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == af)
2836                                         {
2837                                                 masterquerycount++;
2838                                                 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
2839                                         }
2840                                 }
2841
2842                                 // search favorite servers
2843                                 text = net_slist_favorites.string;
2844                                 while(COM_ParseToken_Console(&text))
2845                                 {
2846                                         if(LHNETADDRESS_FromString(&serveraddress, com_token, 26000) && LHNETADDRESS_GetAddressType(&masteraddress) == af)
2847                                         {
2848                                                 NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, com_token, true );
2849                                         }
2850                                 }
2851                         }
2852                 }
2853         }
2854
2855         // only query QuakeWorld servers when the user wants to
2856         if (queryqw)
2857         {
2858                 for (i = 0;i < cl_numsockets;i++)
2859                 {
2860                         if (cl_sockets[i])
2861                         {
2862                                 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
2863
2864                                 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
2865                                 {
2866                                         // search LAN for QuakeWorld servers
2867                                         NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &broadcastaddress);
2868
2869                                         // build the getservers message to send to the qwmaster master servers
2870                                         // note this has no -1 prefix, and the trailing nul byte is sent
2871                                         dpsnprintf(request, sizeof(request), "c\n");
2872                                 }
2873
2874                                 // search internet
2875                                 for (masternum = 0;sv_qwmasters[masternum].name;masternum++)
2876                                 {
2877                                         if (sv_qwmasters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_qwmasters[masternum].string, QWMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
2878                                         {
2879                                                 if (m_state != m_slist)
2880                                                 {
2881                                                         char lookupstring[128];
2882                                                         LHNETADDRESS_ToString(&masteraddress, lookupstring, sizeof(lookupstring), true);
2883                                                         Con_Printf("Querying master %s (resolved from %s)\n", lookupstring, sv_qwmasters[masternum].string);
2884                                                 }
2885                                                 masterquerycount++;
2886                                                 NetConn_Write(cl_sockets[i], request, (int)strlen(request) + 1, &masteraddress);
2887                                         }
2888                                 }
2889
2890                                 // search favorite servers
2891                                 text = net_slist_favorites.string;
2892                                 while(COM_ParseToken_Console(&text))
2893                                 {
2894                                         if(LHNETADDRESS_FromString(&serveraddress, com_token, 26000) && LHNETADDRESS_GetAddressType(&masteraddress) == af)
2895                                         {
2896                                                 // writing AND querying to catch replies for both
2897                                                 // protocols (in case DP has been queried above, this
2898                                                 // would only try the DP protocol otherwise)
2899                                                 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &serveraddress);
2900                                                 NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, com_token, true );
2901                                         }
2902                                 }
2903                         }
2904                 }
2905         }
2906         if (!masterquerycount)
2907         {
2908                 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
2909                 M_Update_Return_Reason("No network");
2910         }
2911 }
2912
2913 void NetConn_Heartbeat(int priority)
2914 {
2915         lhnetaddress_t masteraddress;
2916         int masternum;
2917         lhnetsocket_t *mysocket;
2918
2919         // if it's a state change (client connected), limit next heartbeat to no
2920         // more than 30 sec in the future
2921         if (priority == 1 && nextheartbeattime > realtime + 30.0)
2922                 nextheartbeattime = realtime + 30.0;
2923
2924         // limit heartbeatperiod to 30 to 270 second range,
2925         // lower limit is to avoid abusing master servers with excess traffic,
2926         // upper limit is to avoid timing out on the master server (which uses
2927         // 300 sec timeout)
2928         if (sv_heartbeatperiod.value < 30)
2929                 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
2930         if (sv_heartbeatperiod.value > 270)
2931                 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
2932
2933         // make advertising optional and don't advertise singleplayer games, and
2934         // only send a heartbeat as often as the admin wants
2935         if (sv.active && sv_public.integer > 0 && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
2936         {
2937                 nextheartbeattime = realtime + sv_heartbeatperiod.value;
2938                 for (masternum = 0;sv_masters[masternum].name;masternum++)
2939                         if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
2940                                 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
2941         }
2942 }
2943
2944 static void Net_Heartbeat_f(void)
2945 {
2946         if (sv.active)
2947                 NetConn_Heartbeat(2);
2948         else
2949                 Con_Print("No server running, can not heartbeat to master server.\n");
2950 }
2951
2952 void PrintStats(netconn_t *conn)
2953 {
2954         if ((cls.state == ca_connected && cls.protocol == PROTOCOL_QUAKEWORLD) || (sv.active && sv.protocol == PROTOCOL_QUAKEWORLD))
2955                 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->outgoing_unreliable_sequence, conn->qw.incoming_sequence);
2956         else
2957                 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->nq.sendSequence, conn->nq.receiveSequence);
2958 }
2959
2960 void Net_Stats_f(void)
2961 {
2962         netconn_t *conn;
2963         Con_Printf("unreliable messages sent   = %i\n", unreliableMessagesSent);
2964         Con_Printf("unreliable messages recv   = %i\n", unreliableMessagesReceived);
2965         Con_Printf("reliable messages sent     = %i\n", reliableMessagesSent);
2966         Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
2967         Con_Printf("packetsSent                = %i\n", packetsSent);
2968         Con_Printf("packetsReSent              = %i\n", packetsReSent);
2969         Con_Printf("packetsReceived            = %i\n", packetsReceived);
2970         Con_Printf("receivedDuplicateCount     = %i\n", receivedDuplicateCount);
2971         Con_Printf("droppedDatagrams           = %i\n", droppedDatagrams);
2972         Con_Print("connections                =\n");
2973         for (conn = netconn_list;conn;conn = conn->next)
2974                 PrintStats(conn);
2975 }
2976
2977 void Net_Refresh_f(void)
2978 {
2979         if (m_state != m_slist) {
2980                 Con_Print("Sending new requests to master servers\n");
2981                 ServerList_QueryList(false, true, false, true);
2982                 Con_Print("Listening for replies...\n");
2983         } else
2984                 ServerList_QueryList(false, true, false, false);
2985 }
2986
2987 void Net_Slist_f(void)
2988 {
2989         ServerList_ResetMasks();
2990         serverlist_sortbyfield = SLIF_PING;
2991         serverlist_sortflags = 0;
2992     if (m_state != m_slist) {
2993                 Con_Print("Sending requests to master servers\n");
2994                 ServerList_QueryList(true, true, false, true);
2995                 Con_Print("Listening for replies...\n");
2996         } else
2997                 ServerList_QueryList(true, true, false, false);
2998 }
2999
3000 void Net_SlistQW_f(void)
3001 {
3002         ServerList_ResetMasks();
3003         serverlist_sortbyfield = SLIF_PING;
3004         serverlist_sortflags = 0;
3005     if (m_state != m_slist) {
3006                 Con_Print("Sending requests to master servers\n");
3007                 ServerList_QueryList(true, false, true, true);
3008                 serverlist_consoleoutput = true;
3009                 Con_Print("Listening for replies...\n");
3010         } else
3011                 ServerList_QueryList(true, false, true, false);
3012 }
3013
3014 void NetConn_Init(void)
3015 {
3016         int i;
3017         lhnetaddress_t tempaddress;
3018         netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
3019         Cmd_AddCommand("net_stats", Net_Stats_f, "print network statistics");
3020         Cmd_AddCommand("net_slist", Net_Slist_f, "query dp master servers and print all server information");
3021         Cmd_AddCommand("net_slistqw", Net_SlistQW_f, "query qw master servers and print all server information");
3022         Cmd_AddCommand("net_refresh", Net_Refresh_f, "query dp master servers and refresh all server information");
3023         Cmd_AddCommand("heartbeat", Net_Heartbeat_f, "send a heartbeat to the master server (updates your server information)");
3024         Cvar_RegisterVariable(&rcon_restricted_password);
3025         Cvar_RegisterVariable(&rcon_restricted_commands);
3026         Cvar_RegisterVariable(&rcon_secure_maxdiff);
3027         Cvar_RegisterVariable(&net_slist_queriespersecond);
3028         Cvar_RegisterVariable(&net_slist_queriesperframe);
3029         Cvar_RegisterVariable(&net_slist_timeout);
3030         Cvar_RegisterVariable(&net_slist_maxtries);
3031         Cvar_RegisterVariable(&net_slist_favorites);
3032         Cvar_RegisterVariable(&net_slist_pause);
3033         Cvar_RegisterVariable(&net_messagetimeout);
3034         Cvar_RegisterVariable(&net_connecttimeout);
3035         Cvar_RegisterVariable(&net_connectfloodblockingtimeout);
3036         Cvar_RegisterVariable(&cl_netlocalping);
3037         Cvar_RegisterVariable(&cl_netpacketloss_send);
3038         Cvar_RegisterVariable(&cl_netpacketloss_receive);
3039         Cvar_RegisterVariable(&hostname);
3040         Cvar_RegisterVariable(&developer_networking);
3041         Cvar_RegisterVariable(&cl_netport);
3042         Cvar_RegisterVariable(&sv_netport);
3043         Cvar_RegisterVariable(&net_address);
3044         //Cvar_RegisterVariable(&net_address_ipv6);
3045         Cvar_RegisterVariable(&sv_public);
3046         Cvar_RegisterVariable(&sv_heartbeatperiod);
3047         for (i = 0;sv_masters[i].name;i++)
3048                 Cvar_RegisterVariable(&sv_masters[i]);
3049         Cvar_RegisterVariable(&gameversion);
3050 // 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.
3051         if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
3052         {
3053                 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
3054                 {
3055                         Con_Printf("-ip option used, setting net_address to \"%s\"\n", com_argv[i + 1]);
3056                         Cvar_SetQuick(&net_address, com_argv[i + 1]);
3057                 }
3058                 else
3059                         Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
3060         }
3061 // 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
3062         if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
3063         {
3064                 i = atoi(com_argv[i + 1]);
3065                 if (i >= 0 && i < 65536)
3066                 {
3067                         Con_Printf("-port option used, setting port cvar to %i\n", i);
3068                         Cvar_SetValueQuick(&sv_netport, i);
3069                 }
3070                 else
3071                         Con_Printf("-port option used, but %i is not a valid port number\n", i);
3072         }
3073         cl_numsockets = 0;
3074         sv_numsockets = 0;
3075         net_message.data = net_message_buf;
3076         net_message.maxsize = sizeof(net_message_buf);
3077         net_message.cursize = 0;
3078         LHNET_Init();
3079 }
3080
3081 void NetConn_Shutdown(void)
3082 {
3083         NetConn_CloseClientPorts();
3084         NetConn_CloseServerPorts();
3085         LHNET_Shutdown();
3086 }
3087