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