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