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