]> git.xonotic.org Git - xonotic/darkplaces.git/blob - netconn.c
61ffeeda57765948744ddaa9818e2a282baa01aa
[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 = {CF_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 = {CF_SERVER, "sv_public_rejectreason", "The server is closing.", "Rejection reason for connects when sv_public is -2"};
38 static cvar_t sv_heartbeatperiod = {CF_SERVER | CF_ARCHIVE, "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         {CF_CLIENT | CF_SERVER | CF_ARCHIVE, "sv_master1", "", "user-chosen master server 1"},
44         {CF_CLIENT | CF_SERVER | CF_ARCHIVE, "sv_master2", "", "user-chosen master server 2"},
45         {CF_CLIENT | CF_SERVER | CF_ARCHIVE, "sv_master3", "", "user-chosen master server 3"},
46         {CF_CLIENT | CF_SERVER | CF_ARCHIVE, "sv_master4", "", "user-chosen master server 4"},
47         {CF_CLIENT | CF_SERVER, "sv_masterextra1", "dpmaster.deathmask.net", "dpmaster.deathmask.net - default master server 1 (admin: Willis)"}, // admin: Willis
48         {CF_CLIENT | CF_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         {CF_CLIENT | CF_SERVER | CF_ARCHIVE, "sv_qwmaster1", "", "user-chosen qwmaster server 1"},
56         {CF_CLIENT | CF_SERVER | CF_ARCHIVE, "sv_qwmaster2", "", "user-chosen qwmaster server 2"},
57         {CF_CLIENT | CF_SERVER | CF_ARCHIVE, "sv_qwmaster3", "", "user-chosen qwmaster server 3"},
58         {CF_CLIENT | CF_SERVER | CF_ARCHIVE, "sv_qwmaster4", "", "user-chosen qwmaster server 4"},
59         {CF_CLIENT | CF_SERVER, "sv_qwmasterextra1", "master.quakeservers.net:27000", "Global master server. (admin: unknown)"},
60         {CF_CLIENT | CF_SERVER, "sv_qwmasterextra2", "asgaard.morphos-team.net:27000", "Global master server. (admin: unknown)"},
61         {CF_CLIENT | CF_SERVER, "sv_qwmasterextra3", "qwmaster.ocrana.de:27000", "German master server. (admin: unknown)"},
62         {CF_CLIENT | CF_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 = {CF_CLIENT | CF_SERVER, "net_test", "0", "internal development use only, leave it alone (usually does nothing anyway)"};
77 cvar_t net_usesizelimit = {CF_SERVER, "net_usesizelimit", "2", "use packet size limiting (0: never, 1: in non-CSQC mode, 2: always)"};
78 cvar_t net_burstreserve = {CF_SERVER, "net_burstreserve", "0.3", "how much of the burst time to reserve for packet size spikes"};
79 cvar_t net_messagetimeout = {CF_CLIENT | CF_SERVER, "net_messagetimeout","300", "drops players who have not sent any packets for this many seconds"};
80 cvar_t net_connecttimeout = {CF_CLIENT | CF_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 = {CF_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 = {CF_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 = {CF_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 = {CF_CLIENT, "net_sourceaddresscheck", "1", "compare the source IP address for replies (more secure, may break some bad multihoming setups"};
85 cvar_t hostname = {CF_SERVER | CF_ARCHIVE, "hostname", "UNNAMED", "server message to show in server browser"};
86 cvar_t developer_networking = {CF_CLIENT | CF_SERVER, "developer_networking", "0", "prints all received and sent packets (recommended only for debugging)"};
87
88 cvar_t net_fakelag = {CF_CLIENT, "net_fakelag","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 net_fakeloss_send = {CF_CLIENT, "net_fakeloss_send","0", "drops this percentage of outgoing packets, useful for testing network protocol robustness (jerky movement, prediction errors, etc)"};
90 static cvar_t net_fakeloss_receive = {CF_CLIENT, "net_fakeloss_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 = {CF_CLIENT, "net_slist_queriespersecond", "20", "how many server information requests to send per second"};
92 static cvar_t net_slist_queriesperframe = {CF_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 = {CF_CLIENT, "net_slist_timeout", "4", "how long to listen for a server information response before giving up"};
94 static cvar_t net_slist_pause = {CF_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 = {CF_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 = {CF_CLIENT | CF_ARCHIVE, "net_slist_favorites", "", "contains a list of IP addresses and ports to always query explicitly"};
97 static cvar_t net_tos_dscp = {CF_CLIENT | CF_ARCHIVE, "net_tos_dscp", "32", "DiffServ Codepoint for network sockets (may need game restart to apply)"};
98 static cvar_t gameversion = {CF_SERVER, "gameversion", "0", "version of game data (mod-specific) to be sent to querying clients"};
99 static cvar_t gameversion_min = {CF_CLIENT | CF_SERVER, "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 = {CF_CLIENT | CF_SERVER, "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 = {CF_SERVER | CF_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 = {CF_SERVER, "rcon_restricted_commands", "", "allowed commands for rcon when the restricted mode password was used"};
103 static cvar_t rcon_secure_maxdiff = {CF_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 qbool serverlist_querysleep = true;
118 static qbool 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 = {CF_CLIENT, "cl_port", "0", "forces client to use chosen port number if not 0"};
135 cvar_t sv_netport = {CF_SERVER, "port", "26000", "server port for players to connect to"};
136 cvar_t net_address = {CF_CLIENT | CF_SERVER, "net_address", "", "network address to open ipv4 ports on (if empty, use default interfaces)"};
137 cvar_t net_address_ipv6 = {CF_CLIENT | CF_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 qbool 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_c(cvar_t *var)
170 {
171         const char *p;
172         nFavorites = 0;
173         nFavorites_idfp = 0;
174         p = var->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 qbool _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 qbool _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 qbool _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 qbool _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(qbool resetcache, qbool querydp, qbool queryqw, qbool consoleoutput)
580 {
581         masterquerytime = host.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 (net_fakeloss_receive.integer)
622                 for (i = 0;i < cl_numsockets;i++)
623                         if (cl_sockets[i] == mysocket && (rand() % 100) < net_fakeloss_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 (net_fakeloss_send.integer)
646                 for (i = 0;i < cl_numsockets;i++)
647                         if (cl_sockets[i] == mysocket && (rand() % 100) < net_fakeloss_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 qbool NetConn_CanSend(netconn_t *conn)
672 {
673         conn->outgoing_packetcounter = (conn->outgoing_packetcounter + 1) % NETGRAPH_PACKETS;
674         conn->outgoing_netgraph[conn->outgoing_packetcounter].time            = host.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 (host.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 < host.realtime - bursttime)
694                 *cleartime = host.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 < host.realtime)
701                         *cleartime = host.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, qbool 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                 qbool 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 && (host.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 = host.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 = host.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 qbool NetConn_HaveClientPorts(void)
935 {
936         return !!cl_numsockets;
937 }
938
939 qbool 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(CON_ERROR "Client failed to open a socket on address %s\n", addressstring2);
974                 }
975         }
976         else
977                 Con_Printf(CON_ERROR "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 qbool 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(CON_ERROR "Server failed to open socket on address %s\n", addressstring2);
1038                         }
1039                 }
1040                 else
1041                 {
1042                         Con_Printf(CON_ERROR "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         if (sv_netport.integer != port)
1064                 Cvar_SetValueQuick(&sv_netport, port);
1065         if (cls.state != ca_dedicated)
1066                 NetConn_OpenServerPort(NULL, LHNETADDRESSTYPE_LOOP, 1, 1);
1067         if (opennetports)
1068         {
1069 #ifndef NOSUPPORTIPV6
1070                 qbool ip4success = NetConn_OpenServerPort(net_address.string, LHNETADDRESSTYPE_INET4, port, 100);
1071                 NetConn_OpenServerPort(net_address_ipv6.string, LHNETADDRESSTYPE_INET6, port, ip4success ? 1 : 100);
1072 #else
1073                 NetConn_OpenServerPort(net_address.string, LHNETADDRESSTYPE_INET4, port, 100);
1074 #endif
1075         }
1076         if (sv_numsockets == 0)
1077                 Host_Error("NetConn_OpenServerPorts: unable to open any ports!");
1078 }
1079
1080 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
1081 {
1082         int i, a = LHNETADDRESS_GetAddressType(address);
1083         for (i = 0;i < cl_numsockets;i++)
1084                 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
1085                         return cl_sockets[i];
1086         return NULL;
1087 }
1088
1089 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
1090 {
1091         int i, a = LHNETADDRESS_GetAddressType(address);
1092         for (i = 0;i < sv_numsockets;i++)
1093                 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
1094                         return sv_sockets[i];
1095         return NULL;
1096 }
1097
1098 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
1099 {
1100         netconn_t *conn;
1101         conn = (netconn_t *)Mem_Alloc(netconn_mempool, sizeof(*conn));
1102         conn->mysocket = mysocket;
1103         conn->peeraddress = *peeraddress;
1104         conn->lastMessageTime = host.realtime;
1105         conn->message.data = conn->messagedata;
1106         conn->message.maxsize = sizeof(conn->messagedata);
1107         conn->message.cursize = 0;
1108         // LadyHavoc: (inspired by ProQuake) use a short connect timeout to
1109         // reduce effectiveness of connection request floods
1110         conn->timeout = host.realtime + net_connecttimeout.value;
1111         LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
1112         conn->next = netconn_list;
1113         netconn_list = conn;
1114         return conn;
1115 }
1116
1117 void NetConn_ClearFlood(lhnetaddress_t *peeraddress, server_floodaddress_t *floodlist, size_t floodlength);
1118 void NetConn_Close(netconn_t *conn)
1119 {
1120         netconn_t *c;
1121         // remove connection from list
1122
1123         // allow the client to reconnect immediately
1124         NetConn_ClearFlood(&(conn->peeraddress), sv.connectfloodaddresses, sizeof(sv.connectfloodaddresses) / sizeof(sv.connectfloodaddresses[0]));
1125
1126         if (conn == netconn_list)
1127                 netconn_list = conn->next;
1128         else
1129         {
1130                 for (c = netconn_list;c;c = c->next)
1131                 {
1132                         if (c->next == conn)
1133                         {
1134                                 c->next = conn->next;
1135                                 break;
1136                         }
1137                 }
1138                 // not found in list, we'll avoid crashing here...
1139                 if (!c)
1140                         return;
1141         }
1142         // free connection
1143         Mem_Free(conn);
1144 }
1145
1146 static int clientport = -1;
1147 static int clientport2 = -1;
1148 static int hostport = -1;
1149 void NetConn_UpdateSockets(void)
1150 {
1151         int i, j;
1152
1153         // TODO add logic to automatically close sockets if needed
1154         LHNET_DefaultDSCP(net_tos_dscp.integer);
1155
1156         if (cls.state != ca_dedicated)
1157         {
1158                 if (clientport2 != cl_netport.integer)
1159                 {
1160                         clientport2 = cl_netport.integer;
1161                         if (cls.state == ca_connected)
1162                                 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
1163                 }
1164                 if (cls.state == ca_disconnected && clientport != clientport2)
1165                 {
1166                         clientport = clientport2;
1167                         NetConn_CloseClientPorts();
1168                 }
1169                 if (cl_numsockets == 0)
1170                         NetConn_OpenClientPorts();
1171         }
1172
1173         if (hostport != sv_netport.integer)
1174         {
1175                 hostport = sv_netport.integer;
1176                 if (sv.active)
1177                         Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
1178         }
1179
1180         for (j = 0;j < MAX_RCONS;j++)
1181         {
1182                 i = (cls.rcon_ringpos + j + 1) % MAX_RCONS;
1183                 if(cls.rcon_commands[i][0])
1184                 {
1185                         if(host.realtime > cls.rcon_timeout[i])
1186                         {
1187                                 char s[128];
1188                                 LHNETADDRESS_ToString(&cls.rcon_addresses[i], s, sizeof(s), true);
1189                                 Con_Printf("rcon to %s (for command %s) failed: challenge request timed out\n", s, cls.rcon_commands[i]);
1190                                 cls.rcon_commands[i][0] = 0;
1191                                 --cls.rcon_trying;
1192                                 break;
1193                         }
1194                 }
1195         }
1196 }
1197
1198 static int NetConn_ReceivedMessage(netconn_t *conn, const unsigned char *data, size_t length, protocolversion_t protocol, double newtimeout)
1199 {
1200         int originallength = (int)length;
1201         unsigned char sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
1202         unsigned char cryptosendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE+CRYPTO_HEADERSIZE];
1203         unsigned char cryptoreadbuffer[NET_HEADERSIZE+NET_MAXMESSAGE+CRYPTO_HEADERSIZE];
1204         if (length < 8)
1205                 return 0;
1206
1207         if (protocol == PROTOCOL_QUAKEWORLD)
1208         {
1209                 unsigned int sequence, sequence_ack;
1210                 qbool reliable_ack, reliable_message;
1211                 int count;
1212                 //int qport;
1213
1214                 sequence = LittleLong(*((int *)(data + 0)));
1215                 sequence_ack = LittleLong(*((int *)(data + 4)));
1216                 data += 8;
1217                 length -= 8;
1218
1219                 if (conn != cls.netcon)
1220                 {
1221                         // server only
1222                         if (length < 2)
1223                                 return 0;
1224                         // 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?)
1225                         //qport = LittleShort(*((int *)(data + 8)));
1226                         data += 2;
1227                         length -= 2;
1228                 }
1229
1230                 conn->packetsReceived++;
1231                 reliable_message = (sequence >> 31) != 0;
1232                 reliable_ack = (sequence_ack >> 31) != 0;
1233                 sequence &= ~(1<<31);
1234                 sequence_ack &= ~(1<<31);
1235                 if (sequence <= conn->qw.incoming_sequence)
1236                 {
1237                         //Con_DPrint("Got a stale datagram\n");
1238                         return 0;
1239                 }
1240                 count = sequence - (conn->qw.incoming_sequence + 1);
1241                 if (count > 0)
1242                 {
1243                         conn->droppedDatagrams += count;
1244                         //Con_DPrintf("Dropped %u datagram(s)\n", count);
1245                         // If too may packets have been dropped, only write the
1246                         // last NETGRAPH_PACKETS ones to the netgraph. Why?
1247                         // Because there's no point in writing more than
1248                         // these as the netgraph is going to be full anyway.
1249                         if (count > NETGRAPH_PACKETS)
1250                                 count = NETGRAPH_PACKETS;
1251                         while (count--)
1252                         {
1253                                 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1254                                 conn->incoming_netgraph[conn->incoming_packetcounter].time            = host.realtime;
1255                                 conn->incoming_netgraph[conn->incoming_packetcounter].cleartime       = conn->incoming_cleartime;
1256                                 conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = NETGRAPH_LOSTPACKET;
1257                                 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes   = NETGRAPH_NOPACKET;
1258                                 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes        = NETGRAPH_NOPACKET;
1259                         }
1260                 }
1261                 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1262                 conn->incoming_netgraph[conn->incoming_packetcounter].time            = host.realtime;
1263                 conn->incoming_netgraph[conn->incoming_packetcounter].cleartime       = conn->incoming_cleartime;
1264                 conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = originallength + 28;
1265                 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes   = NETGRAPH_NOPACKET;
1266                 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes        = NETGRAPH_NOPACKET;
1267                 NetConn_UpdateCleartime(&conn->incoming_cleartime, cl_rate.integer, cl_rate_burstsize.integer, originallength + 28);
1268
1269                 // limit bursts to one packet in size ("dialup mode" emulating old behaviour)
1270                 if (net_test.integer)
1271                 {
1272                         if (conn->cleartime < host.realtime)
1273                                 conn->cleartime = host.realtime;
1274                 }
1275
1276                 if (reliable_ack == conn->qw.reliable_sequence)
1277                 {
1278                         // received, now we will be able to send another reliable message
1279                         conn->sendMessageLength = 0;
1280                         conn->reliableMessagesReceived++;
1281                 }
1282                 conn->qw.incoming_sequence = sequence;
1283                 if (conn == cls.netcon)
1284                         cls.qw_incoming_sequence = conn->qw.incoming_sequence;
1285                 conn->qw.incoming_acknowledged = sequence_ack;
1286                 conn->qw.incoming_reliable_acknowledged = reliable_ack;
1287                 if (reliable_message)
1288                         conn->qw.incoming_reliable_sequence ^= 1;
1289                 conn->lastMessageTime = host.realtime;
1290                 conn->timeout = host.realtime + newtimeout;
1291                 conn->unreliableMessagesReceived++;
1292                 if (conn == cls.netcon)
1293                 {
1294                         SZ_Clear(&cl_message);
1295                         SZ_Write(&cl_message, data, (int)length);
1296                         MSG_BeginReading(&cl_message);
1297                 }
1298                 else
1299                 {
1300                         SZ_Clear(&sv_message);
1301                         SZ_Write(&sv_message, data, (int)length);
1302                         MSG_BeginReading(&sv_message);
1303                 }
1304                 return 2;
1305         }
1306         else
1307         {
1308                 unsigned int count;
1309                 unsigned int flags;
1310                 unsigned int sequence;
1311                 size_t qlength;
1312                 const void *sendme;
1313                 size_t sendmelen;
1314
1315                 originallength = (int)length;
1316                 data = (const unsigned char *) Crypto_DecryptPacket(&conn->crypto, data, length, cryptoreadbuffer, &length, sizeof(cryptoreadbuffer));
1317                 if(!data)
1318                         return 0;
1319                 if(length < 8)
1320                         return 0;
1321
1322                 qlength = (unsigned int)BuffBigLong(data);
1323                 flags = qlength & ~NETFLAG_LENGTH_MASK;
1324                 qlength &= NETFLAG_LENGTH_MASK;
1325                 // control packets were already handled
1326                 if (!(flags & NETFLAG_CTL) && qlength == length)
1327                 {
1328                         sequence = BuffBigLong(data + 4);
1329                         conn->packetsReceived++;
1330                         data += 8;
1331                         length -= 8;
1332                         if (flags & NETFLAG_UNRELIABLE)
1333                         {
1334                                 if (sequence >= conn->nq.unreliableReceiveSequence)
1335                                 {
1336                                         if (sequence > conn->nq.unreliableReceiveSequence)
1337                                         {
1338                                                 count = sequence - conn->nq.unreliableReceiveSequence;
1339                                                 conn->droppedDatagrams += count;
1340                                                 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1341                                                 // If too may packets have been dropped, only write the
1342                                                 // last NETGRAPH_PACKETS ones to the netgraph. Why?
1343                                                 // Because there's no point in writing more than
1344                                                 // these as the netgraph is going to be full anyway.
1345                                                 if (count > NETGRAPH_PACKETS)
1346                                                         count = NETGRAPH_PACKETS;
1347                                                 while (count--)
1348                                                 {
1349                                                         conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1350                                                         conn->incoming_netgraph[conn->incoming_packetcounter].time            = host.realtime;
1351                                                         conn->incoming_netgraph[conn->incoming_packetcounter].cleartime       = conn->incoming_cleartime;
1352                                                         conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = NETGRAPH_LOSTPACKET;
1353                                                         conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes   = NETGRAPH_NOPACKET;
1354                                                         conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes        = NETGRAPH_NOPACKET;
1355                                                 }
1356                                         }
1357                                         conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1358                                         conn->incoming_netgraph[conn->incoming_packetcounter].time            = host.realtime;
1359                                         conn->incoming_netgraph[conn->incoming_packetcounter].cleartime       = conn->incoming_cleartime;
1360                                         conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = originallength + 28;
1361                                         conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes   = NETGRAPH_NOPACKET;
1362                                         conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes        = NETGRAPH_NOPACKET;
1363                                         NetConn_UpdateCleartime(&conn->incoming_cleartime, cl_rate.integer, cl_rate_burstsize.integer, originallength + 28);
1364
1365                                         conn->nq.unreliableReceiveSequence = sequence + 1;
1366                                         conn->lastMessageTime = host.realtime;
1367                                         conn->timeout = host.realtime + newtimeout;
1368                                         conn->unreliableMessagesReceived++;
1369                                         if (length > 0)
1370                                         {
1371                                                 if (conn == cls.netcon)
1372                                                 {
1373                                                         SZ_Clear(&cl_message);
1374                                                         SZ_Write(&cl_message, data, (int)length);
1375                                                         MSG_BeginReading(&cl_message);
1376                                                 }
1377                                                 else
1378                                                 {
1379                                                         SZ_Clear(&sv_message);
1380                                                         SZ_Write(&sv_message, data, (int)length);
1381                                                         MSG_BeginReading(&sv_message);
1382                                                 }
1383                                                 return 2;
1384                                         }
1385                                 }
1386                                 //else
1387                                 //      Con_DPrint("Got a stale datagram\n");
1388                                 return 1;
1389                         }
1390                         else if (flags & NETFLAG_ACK)
1391                         {
1392                                 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes += originallength + 28;
1393                                 NetConn_UpdateCleartime(&conn->incoming_cleartime, cl_rate.integer, cl_rate_burstsize.integer, originallength + 28);
1394
1395                                 if (sequence == (conn->nq.sendSequence - 1))
1396                                 {
1397                                         if (sequence == conn->nq.ackSequence)
1398                                         {
1399                                                 conn->nq.ackSequence++;
1400                                                 if (conn->nq.ackSequence != conn->nq.sendSequence)
1401                                                         Con_DPrint("ack sequencing error\n");
1402                                                 conn->lastMessageTime = host.realtime;
1403                                                 conn->timeout = host.realtime + newtimeout;
1404                                                 if (conn->sendMessageLength > MAX_PACKETFRAGMENT)
1405                                                 {
1406                                                         unsigned int packetLen;
1407                                                         unsigned int dataLen;
1408                                                         unsigned int eom;
1409
1410                                                         conn->sendMessageLength -= MAX_PACKETFRAGMENT;
1411                                                         memmove(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
1412
1413                                                         if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
1414                                                         {
1415                                                                 dataLen = conn->sendMessageLength;
1416                                                                 eom = NETFLAG_EOM;
1417                                                         }
1418                                                         else
1419                                                         {
1420                                                                 dataLen = MAX_PACKETFRAGMENT;
1421                                                                 eom = 0;
1422                                                         }
1423
1424                                                         packetLen = NET_HEADERSIZE + dataLen;
1425
1426                                                         StoreBigLong(sendbuffer, packetLen | (NETFLAG_DATA | eom | NetConn_AddCryptoFlag(&conn->crypto)));
1427                                                         StoreBigLong(sendbuffer + 4, conn->nq.sendSequence);
1428                                                         memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
1429
1430                                                         conn->nq.sendSequence++;
1431
1432                                                         sendme = Crypto_EncryptPacket(&conn->crypto, &sendbuffer, packetLen, &cryptosendbuffer, &sendmelen, sizeof(cryptosendbuffer));
1433                                                         if (sendme && NetConn_Write(conn->mysocket, sendme, (int)sendmelen, &conn->peeraddress) == (int)sendmelen)
1434                                                         {
1435                                                                 conn->lastSendTime = host.realtime;
1436                                                                 conn->packetsSent++;
1437                                                         }
1438                                                 }
1439                                                 else
1440                                                         conn->sendMessageLength = 0;
1441                                         }
1442                                         //else
1443                                         //      Con_DPrint("Duplicate ACK received\n");
1444                                 }
1445                                 //else
1446                                 //      Con_DPrint("Stale ACK received\n");
1447                                 return 1;
1448                         }
1449                         else if (flags & NETFLAG_DATA)
1450                         {
1451                                 unsigned char temppacket[8];
1452                                 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes   += originallength + 28;
1453                                 NetConn_UpdateCleartime(&conn->incoming_cleartime, cl_rate.integer, cl_rate_burstsize.integer, originallength + 28);
1454
1455                                 conn->outgoing_netgraph[conn->outgoing_packetcounter].ackbytes        += 8 + 28;
1456
1457                                 StoreBigLong(temppacket, 8 | NETFLAG_ACK | NetConn_AddCryptoFlag(&conn->crypto));
1458                                 StoreBigLong(temppacket + 4, sequence);
1459                                 sendme = Crypto_EncryptPacket(&conn->crypto, temppacket, 8, &cryptosendbuffer, &sendmelen, sizeof(cryptosendbuffer));
1460                                 if(sendme)
1461                                         NetConn_Write(conn->mysocket, sendme, (int)sendmelen, &conn->peeraddress);
1462                                 if (sequence == conn->nq.receiveSequence)
1463                                 {
1464                                         conn->lastMessageTime = host.realtime;
1465                                         conn->timeout = host.realtime + newtimeout;
1466                                         conn->nq.receiveSequence++;
1467                                         if( conn->receiveMessageLength + length <= (int)sizeof( conn->receiveMessage ) ) {
1468                                                 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
1469                                                 conn->receiveMessageLength += (int)length;
1470                                         } else {
1471                                                 Con_Printf( "Reliable message (seq: %i) too big for message buffer!\n"
1472                                                                         "Dropping the message!\n", sequence );
1473                                                 conn->receiveMessageLength = 0;
1474                                                 return 1;
1475                                         }
1476                                         if (flags & NETFLAG_EOM)
1477                                         {
1478                                                 conn->reliableMessagesReceived++;
1479                                                 length = conn->receiveMessageLength;
1480                                                 conn->receiveMessageLength = 0;
1481                                                 if (length > 0)
1482                                                 {
1483                                                         if (conn == cls.netcon)
1484                                                         {
1485                                                                 SZ_Clear(&cl_message);
1486                                                                 SZ_Write(&cl_message, conn->receiveMessage, (int)length);
1487                                                                 MSG_BeginReading(&cl_message);
1488                                                         }
1489                                                         else
1490                                                         {
1491                                                                 SZ_Clear(&sv_message);
1492                                                                 SZ_Write(&sv_message, conn->receiveMessage, (int)length);
1493                                                                 MSG_BeginReading(&sv_message);
1494                                                         }
1495                                                         return 2;
1496                                                 }
1497                                         }
1498                                 }
1499                                 else
1500                                         conn->receivedDuplicateCount++;
1501                                 return 1;
1502                         }
1503                 }
1504         }
1505         return 0;
1506 }
1507
1508 static void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, protocolversion_t initialprotocol)
1509 {
1510         crypto_t *crypto;
1511         cls.connect_trying = false;
1512 #ifdef CONFIG_MENU
1513         M_Update_Return_Reason("");
1514 #endif
1515         // if we're connecting to a remote server, shut down any local server
1516         if (LHNETADDRESS_GetAddressType(peeraddress) != LHNETADDRESSTYPE_LOOP && sv.active)
1517         {
1518                 SV_LockThreadMutex();
1519                 SV_Shutdown ();
1520                 SV_UnlockThreadMutex();
1521         }
1522         if(cls.state == ca_connected || cls.demoplayback)
1523                 CL_Disconnect();
1524         // allocate a net connection to keep track of things
1525         cls.netcon = NetConn_Open(mysocket, peeraddress);
1526         crypto = &cls.netcon->crypto;
1527         if(cls.crypto.authenticated)
1528         {
1529                 Crypto_FinishInstance(crypto, &cls.crypto);
1530                 Con_Printf("%s connection to %s has been established: server is %s@%s%.*s, I am %.*s@%s%.*s\n",
1531                                 crypto->use_aes ? "Encrypted" : "Authenticated",
1532                                 cls.netcon->address,
1533                                 crypto->server_idfp[0] ? crypto->server_idfp : "-",
1534                                 (crypto->server_issigned || !crypto->server_keyfp[0]) ? "" : "~",
1535                                 crypto_keyfp_recommended_length, crypto->server_keyfp[0] ? crypto->server_keyfp : "-",
1536                                 crypto_keyfp_recommended_length, crypto->client_idfp[0] ? crypto->client_idfp : "-",
1537                                 (crypto->client_issigned || !crypto->client_keyfp[0]) ? "" : "~",
1538                                 crypto_keyfp_recommended_length, crypto->client_keyfp[0] ? crypto->client_keyfp : "-"
1539                                 );
1540         }
1541         Con_Printf("Connection accepted to %s\n", cls.netcon->address);
1542         key_dest = key_game;
1543 #ifdef CONFIG_MENU
1544         m_state = m_none;
1545 #endif
1546         cls.demonum = -1;                       // not in the demo loop now
1547         cls.state = ca_connected;
1548         cls.signon = 0;                         // need all the signon messages before playing
1549         cls.protocol = initialprotocol;
1550         // reset move sequence numbering on this new connection
1551         cls.servermovesequence = 0;
1552         if (cls.protocol == PROTOCOL_QUAKEWORLD)
1553                 CL_ForwardToServer("new");
1554         if (cls.protocol == PROTOCOL_QUAKE)
1555         {
1556                 // write a keepalive (clc_nop) as it seems to greatly improve the
1557                 // chances of connecting to a netquake server
1558                 sizebuf_t msg;
1559                 unsigned char buf[4];
1560                 memset(&msg, 0, sizeof(msg));
1561                 msg.data = buf;
1562                 msg.maxsize = sizeof(buf);
1563                 MSG_WriteChar(&msg, clc_nop);
1564                 NetConn_SendUnreliableMessage(cls.netcon, &msg, cls.protocol, 10000, 0, false);
1565         }
1566 }
1567
1568 int NetConn_IsLocalGame(void)
1569 {
1570         if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
1571                 return true;
1572         return false;
1573 }
1574
1575 #ifdef CONFIG_MENU
1576 static int NetConn_ClientParsePacket_ServerList_ProcessReply(const char *addressstring)
1577 {
1578         int n;
1579         int pingtime;
1580         serverlist_entry_t *entry = NULL;
1581
1582         // search the cache for this server and update it
1583         for (n = 0;n < serverlist_cachecount;n++) {
1584                 entry = &serverlist_cache[ n ];
1585                 if (!strcmp(addressstring, entry->info.cname))
1586                         break;
1587         }
1588
1589         if (n == serverlist_cachecount)
1590         {
1591                 // LAN search doesnt require an answer from the master server so we wont
1592                 // know the ping nor will it be initialized already...
1593
1594                 // find a slot
1595                 if (serverlist_cachecount == SERVERLIST_TOTALSIZE)
1596                         return -1;
1597
1598                 if (serverlist_maxcachecount <= serverlist_cachecount)
1599                 {
1600                         serverlist_maxcachecount += 64;
1601                         serverlist_cache = (serverlist_entry_t *)Mem_Realloc(netconn_mempool, (void *)serverlist_cache, sizeof(serverlist_entry_t) * serverlist_maxcachecount);
1602                 }
1603                 entry = &serverlist_cache[n];
1604
1605                 memset(entry, 0, sizeof(*entry));
1606                 // store the data the engine cares about (address and ping)
1607                 strlcpy(entry->info.cname, addressstring, sizeof(entry->info.cname));
1608                 entry->info.ping = 100000;
1609                 entry->querytime = host.realtime;
1610                 // if not in the slist menu we should print the server to console
1611                 if (serverlist_consoleoutput)
1612                         Con_Printf("querying %s\n", addressstring);
1613                 ++serverlist_cachecount;
1614         }
1615         // if this is the first reply from this server, count it as having replied
1616         pingtime = (int)((host.realtime - entry->querytime) * 1000.0 + 0.5);
1617         pingtime = bound(0, pingtime, 9999);
1618         if (entry->query == SQS_REFRESHING) {
1619                 entry->info.ping = pingtime;
1620                 entry->query = SQS_QUERIED;
1621         } else {
1622                 // convert to unsigned to catch the -1
1623                 // 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]
1624                 entry->info.ping = min((unsigned) entry->info.ping, (unsigned) pingtime);
1625                 serverreplycount++;
1626         }
1627         
1628         // other server info is updated by the caller
1629         return n;
1630 }
1631
1632 static void NetConn_ClientParsePacket_ServerList_UpdateCache(int n)
1633 {
1634         serverlist_entry_t *entry = &serverlist_cache[n];
1635         serverlist_info_t *info = &entry->info;
1636         // update description strings for engine menu and console output
1637         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);
1638         dpsnprintf(entry->line2, sizeof(serverlist_cache[n].line2), "^4%-21.21s %-19.19s ^%c%-17.17s^4 %-20.20s", info->cname, info->game,
1639                         (
1640                          info->gameversion != gameversion.integer
1641                          &&
1642                          !(
1643                                     gameversion_min.integer >= 0 // min/max range set by user/mod?
1644                                  && gameversion_max.integer >= 0
1645                                  && gameversion_min.integer <= info->gameversion // version of server in min/max range?
1646                                  && gameversion_max.integer >= info->gameversion
1647                           )
1648                         ) ? '1' : '4',
1649                         info->mod, info->map);
1650         if (entry->query == SQS_QUERIED)
1651         {
1652                 if(!serverlist_paused)
1653                         ServerList_ViewList_Remove(entry);
1654         }
1655         // if not in the slist menu we should print the server to console (if wanted)
1656         else if( serverlist_consoleoutput )
1657                 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1658         // and finally, update the view set
1659         if(!serverlist_paused)
1660                 ServerList_ViewList_Insert( entry );
1661         //      update the entry's state
1662         serverlist_cache[n].query = SQS_QUERIED;
1663 }
1664
1665 // returns true, if it's sensible to continue the processing
1666 static qbool NetConn_ClientParsePacket_ServerList_PrepareQuery( int protocol, const char *ipstring, qbool isfavorite ) {
1667         int n;
1668         serverlist_entry_t *entry;
1669
1670         //      ignore the rest of the message if the serverlist is full
1671         if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1672                 return false;
1673         //      also ignore     it      if      we      have already queried    it      (other master server    response)
1674         for( n =        0 ; n   < serverlist_cachecount ; n++   )
1675                 if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1676                         break;
1677
1678         if( n < serverlist_cachecount ) {
1679                 // the entry has already been queried once or 
1680                 return true;
1681         }
1682
1683         if (serverlist_maxcachecount <= n)
1684         {
1685                 serverlist_maxcachecount += 64;
1686                 serverlist_cache = (serverlist_entry_t *)Mem_Realloc(netconn_mempool, (void *)serverlist_cache, sizeof(serverlist_entry_t) * serverlist_maxcachecount);
1687         }
1688
1689         entry = &serverlist_cache[n];
1690
1691         memset(entry, 0, sizeof(*entry));
1692         entry->protocol =       protocol;
1693         //      store   the data        the engine cares about (address and     ping)
1694         strlcpy (entry->info.cname, ipstring, sizeof(entry->info.cname));
1695
1696         entry->info.isfavorite = isfavorite;
1697         
1698         // no, then reset the ping right away
1699         entry->info.ping = -1;
1700         // we also want to increase the serverlist_cachecount then
1701         serverlist_cachecount++;
1702         serverquerycount++;
1703
1704         entry->query =  SQS_QUERYING;
1705
1706         return true;
1707 }
1708
1709 static void NetConn_ClientParsePacket_ServerList_ParseDPList(lhnetaddress_t *senderaddress, const unsigned char *data, int length, qbool isextended)
1710 {
1711         masterreplycount++;
1712         if (serverlist_consoleoutput)
1713                 Con_Printf("received DarkPlaces %sserver list...\n", isextended ? "extended " : "");
1714         while (length >= 7)
1715         {
1716                 char ipstring [128];
1717
1718                 // IPv4 address
1719                 if (data[0] == '\\')
1720                 {
1721                         unsigned short port = data[5] * 256 + data[6];
1722
1723                         if (port != 0 && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF))
1724                                 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%hu", data[1], data[2], data[3], data[4], port);
1725
1726                         // move on to next address in packet
1727                         data += 7;
1728                         length -= 7;
1729                 }
1730                 // IPv6 address
1731                 else if (data[0] == '/' && isextended && length >= 19)
1732                 {
1733                         unsigned short port = data[17] * 256 + data[18];
1734
1735                         if (port != 0)
1736                         {
1737 #ifdef WHY_JUST_WHY
1738                                 const char *ifname;
1739                                 char ifnamebuf[16];
1740
1741                                 /// \TODO: make some basic checks of the IP address (broadcast, ...)
1742
1743                                 ifname = LHNETADDRESS_GetInterfaceName(senderaddress, ifnamebuf, sizeof(ifnamebuf));
1744                                 if (ifname != NULL)
1745                                 {
1746                                         dpsnprintf (ipstring, sizeof (ipstring), "[%x:%x:%x:%x:%x:%x:%x:%x%%%s]:%hu",
1747                                                                 (data[1] << 8) | data[2], (data[3] << 8) | data[4], (data[5] << 8) | data[6], (data[7] << 8) | data[8],
1748                                                                 (data[9] << 8) | data[10], (data[11] << 8) | data[12], (data[13] << 8) | data[14], (data[15] << 8) | data[16],
1749                                                                 ifname, port);
1750                                 }
1751                                 else
1752 #endif
1753                                 {
1754                                         dpsnprintf (ipstring, sizeof (ipstring), "[%x:%x:%x:%x:%x:%x:%x:%x]:%hu",
1755                                                                 (data[1] << 8) | data[2], (data[3] << 8) | data[4], (data[5] << 8) | data[6], (data[7] << 8) | data[8],
1756                                                                 (data[9] << 8) | data[10], (data[11] << 8) | data[12], (data[13] << 8) | data[14], (data[15] << 8) | data[16],
1757                                                                 port);
1758                                 }
1759                         }
1760
1761                         // move on to next address in packet
1762                         data += 19;
1763                         length -= 19;
1764                 }
1765                 else
1766                 {
1767                         Con_Print("Error while parsing the server list\n");
1768                         break;
1769                 }
1770
1771                 if (serverlist_consoleoutput && developer_networking.integer)
1772                         Con_Printf("Requesting info from DarkPlaces server %s\n", ipstring);
1773                 
1774                 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, ipstring, false ) ) {
1775                         break;
1776                 }
1777
1778         }
1779
1780         // begin or resume serverlist queries
1781         serverlist_querysleep = false;
1782         serverlist_querywaittime = host.realtime + 3;
1783 }
1784 #endif
1785
1786 static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1787 {
1788         qbool fromserver;
1789         int ret, c;
1790         char *string, addressstring2[128];
1791         char stringbuf[16384];
1792         char senddata[NET_HEADERSIZE+NET_MAXMESSAGE+CRYPTO_HEADERSIZE];
1793         size_t sendlength;
1794 #ifdef CONFIG_MENU
1795         char infostringvalue[MAX_INPUTLINE];
1796         char ipstring[32];
1797         const char *s;
1798 #endif
1799
1800         // quakeworld ingame packet
1801         fromserver = cls.netcon && mysocket == cls.netcon->mysocket && !LHNETADDRESS_Compare(&cls.netcon->peeraddress, peeraddress);
1802
1803         // convert the address to a string incase we need it
1804         LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1805
1806         if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1807         {
1808                 // received a command string - strip off the packaging and put it
1809                 // into our string buffer with NULL termination
1810                 data += 4;
1811                 length -= 4;
1812                 length = min(length, (int)sizeof(stringbuf) - 1);
1813                 memcpy(stringbuf, data, length);
1814                 stringbuf[length] = 0;
1815                 string = stringbuf;
1816
1817                 if (developer_networking.integer)
1818                 {
1819                         Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
1820                         Com_HexDumpToConsole(data, length);
1821                 }
1822
1823                 sendlength = sizeof(senddata) - 4;
1824                 switch(Crypto_ClientParsePacket(string, length, senddata+4, &sendlength, peeraddress))
1825                 {
1826                         case CRYPTO_NOMATCH:
1827                                 // nothing to do
1828                                 break;
1829                         case CRYPTO_MATCH:
1830                                 if(sendlength)
1831                                 {
1832                                         memcpy(senddata, "\377\377\377\377", 4);
1833                                         NetConn_Write(mysocket, senddata, (int)sendlength+4, peeraddress);
1834                                 }
1835                                 break;
1836                         case CRYPTO_DISCARD:
1837                                 if(sendlength)
1838                                 {
1839                                         memcpy(senddata, "\377\377\377\377", 4);
1840                                         NetConn_Write(mysocket, senddata, (int)sendlength+4, peeraddress);
1841                                 }
1842                                 return true;
1843                                 break;
1844                         case CRYPTO_REPLACE:
1845                                 string = senddata+4;
1846                                 length = (int)sendlength;
1847                                 break;
1848                 }
1849
1850                 if (length >= 10 && !memcmp(string, "challenge ", 10) && cls.rcon_trying)
1851                 {
1852                         int i = 0, j;
1853                         for (j = 0;j < MAX_RCONS;j++)
1854                         {
1855                                 // note: this value from i is used outside the loop too...
1856                                 i = (cls.rcon_ringpos + j) % MAX_RCONS;
1857                                 if(cls.rcon_commands[i][0])
1858                                         if (!LHNETADDRESS_Compare(peeraddress, &cls.rcon_addresses[i]))
1859                                                 break;
1860                         }
1861                         if (j < MAX_RCONS)
1862                         {
1863                                 char buf[1500];
1864                                 char argbuf[1500];
1865                                 const char *e;
1866                                 int n;
1867                                 dpsnprintf(argbuf, sizeof(argbuf), "%s %s", string + 10, cls.rcon_commands[i]);
1868                                 memcpy(buf, "\377\377\377\377srcon HMAC-MD4 CHALLENGE ", 29);
1869
1870                                 e = strchr(rcon_password.string, ' ');
1871                                 n = e ? e-rcon_password.string : (int)strlen(rcon_password.string);
1872
1873                                 if(HMAC_MDFOUR_16BYTES((unsigned char *) (buf + 29), (unsigned char *) argbuf, (int)strlen(argbuf), (unsigned char *) rcon_password.string, n))
1874                                 {
1875                                         int k;
1876                                         buf[45] = ' ';
1877                                         strlcpy(buf + 46, argbuf, sizeof(buf) - 46);
1878                                         NetConn_Write(mysocket, buf, 46 + (int)strlen(buf + 46), peeraddress);
1879                                         cls.rcon_commands[i][0] = 0;
1880                                         --cls.rcon_trying;
1881
1882                                         for (k = 0;k < MAX_RCONS;k++)
1883                                                 if(cls.rcon_commands[k][0])
1884                                                         if (!LHNETADDRESS_Compare(peeraddress, &cls.rcon_addresses[k]))
1885                                                                 break;
1886                                         if(k < MAX_RCONS)
1887                                         {
1888                                                 int l;
1889                                                 NetConn_WriteString(mysocket, "\377\377\377\377getchallenge", peeraddress);
1890                                                 // extend the timeout on other requests as we asked for a challenge
1891                                                 for (l = 0;l < MAX_RCONS;l++)
1892                                                         if(cls.rcon_commands[l][0])
1893                                                                 if (!LHNETADDRESS_Compare(peeraddress, &cls.rcon_addresses[l]))
1894                                                                         cls.rcon_timeout[l] = host.realtime + rcon_secure_challengetimeout.value;
1895                                         }
1896
1897                                         return true; // we used up the challenge, so we can't use this oen for connecting now anyway
1898                                 }
1899                         }
1900                 }
1901                 if (length >= 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
1902                 {
1903                         // darkplaces or quake3
1904                         char protocolnames[1400];
1905                         Con_DPrintf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
1906                         if (net_sourceaddresscheck.integer && LHNETADDRESS_Compare(peeraddress, &cls.connect_address)) {
1907                                 Con_DPrintf("challenge message from wrong server %s\n", addressstring2);
1908                                 return true;
1909                         }
1910                         Protocol_Names(protocolnames, sizeof(protocolnames));
1911 #ifdef CONFIG_MENU
1912                         M_Update_Return_Reason("Got challenge response");
1913 #endif
1914                         // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1915                         InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1916                         // TODO: add userinfo stuff here instead of using NQ commands?
1917                         memcpy(senddata, "\377\377\377\377", 4);
1918                         dpsnprintf(senddata+4, sizeof(senddata)-4, "connect\\protocol\\darkplaces 3\\protocols\\%s%s\\challenge\\%s", protocolnames, cls.connect_userinfo, string + 10);
1919                         NetConn_WriteString(mysocket, senddata, peeraddress);
1920                         return true;
1921                 }
1922                 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
1923                 {
1924                         // darkplaces or quake3
1925                         if (net_sourceaddresscheck.integer && LHNETADDRESS_Compare(peeraddress, &cls.connect_address)) {
1926                                 Con_DPrintf("accept message from wrong server %s\n", addressstring2);
1927                                 return true;
1928                         }
1929 #ifdef CONFIG_MENU
1930                         M_Update_Return_Reason("Accepted");
1931 #endif
1932                         NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_DARKPLACES3);
1933                         return true;
1934                 }
1935                 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
1936                 {
1937                         char rejectreason[128];
1938                         if (net_sourceaddresscheck.integer && LHNETADDRESS_Compare(peeraddress, &cls.connect_address)) {
1939                                 Con_DPrintf("reject message from wrong server %s\n", addressstring2);
1940                                 return true;
1941                         }
1942                         cls.connect_trying = false;
1943                         string += 7;
1944                         length = min(length - 7, (int)sizeof(rejectreason) - 1);
1945                         memcpy(rejectreason, string, length);
1946                         rejectreason[length] = 0;
1947 #ifdef CONFIG_MENU
1948                         M_Update_Return_Reason(rejectreason);
1949 #endif
1950                         return true;
1951                 }
1952 #ifdef CONFIG_MENU
1953                 if(key_dest != key_game)
1954                 {
1955                         if (length >= 15 && !memcmp(string, "statusResponse\x0A", 15))
1956                         {
1957                                 serverlist_info_t *info;
1958                                 char *p;
1959                                 int n;
1960
1961                                 string += 15;
1962                                 // search the cache for this server and update it
1963                                 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1964                                 if (n < 0)
1965                                         return true;
1966
1967                                 info = &serverlist_cache[n].info;
1968                                 info->game[0] = 0;
1969                                 info->mod[0]  = 0;
1970                                 info->map[0]  = 0;
1971                                 info->name[0] = 0;
1972                                 info->qcstatus[0] = 0;
1973                                 info->players[0] = 0;
1974                                 info->protocol = -1;
1975                                 info->numplayers = 0;
1976                                 info->numbots = -1;
1977                                 info->maxplayers  = 0;
1978                                 info->gameversion = 0;
1979
1980                                 p = strchr(string, '\n');
1981                                 if(p)
1982                                 {
1983                                         *p = 0; // cut off the string there
1984                                         ++p;
1985                                 }
1986                                 else
1987                                         Con_Printf("statusResponse without players block?\n");
1988
1989                                 if ((s = InfoString_GetValue(string, "gamename"     , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->game, s, sizeof (info->game));
1990                                 if ((s = InfoString_GetValue(string, "modname"      , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1991                                 if ((s = InfoString_GetValue(string, "mapname"      , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1992                                 if ((s = InfoString_GetValue(string, "hostname"     , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->name, s, sizeof (info->name));
1993                                 if ((s = InfoString_GetValue(string, "protocol"     , infostringvalue, sizeof(infostringvalue))) != NULL) info->protocol = atoi(s);
1994                                 if ((s = InfoString_GetValue(string, "clients"      , infostringvalue, sizeof(infostringvalue))) != NULL) info->numplayers = atoi(s);
1995                                 if ((s = InfoString_GetValue(string, "bots"         , infostringvalue, sizeof(infostringvalue))) != NULL) info->numbots = atoi(s);
1996                                 if ((s = InfoString_GetValue(string, "sv_maxclients", infostringvalue, sizeof(infostringvalue))) != NULL) info->maxplayers = atoi(s);
1997                                 if ((s = InfoString_GetValue(string, "gameversion"  , infostringvalue, sizeof(infostringvalue))) != NULL) info->gameversion = atoi(s);
1998                                 if ((s = InfoString_GetValue(string, "qcstatus"     , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1999                                 if (p                                                                                         != NULL) strlcpy(info->players, p, sizeof(info->players));
2000                                 info->numhumans = info->numplayers - max(0, info->numbots);
2001                                 info->freeslots = info->maxplayers - info->numplayers;
2002
2003                                 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
2004
2005                                 return true;
2006                         }
2007                         if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
2008                         {
2009                                 serverlist_info_t *info;
2010                                 int n;
2011
2012                                 string += 13;
2013                                 // search the cache for this server and update it
2014                                 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
2015                                 if (n < 0)
2016                                         return true;
2017
2018                                 info = &serverlist_cache[n].info;
2019                                 info->game[0] = 0;
2020                                 info->mod[0]  = 0;
2021                                 info->map[0]  = 0;
2022                                 info->name[0] = 0;
2023                                 info->qcstatus[0] = 0;
2024                                 info->players[0] = 0;
2025                                 info->protocol = -1;
2026                                 info->numplayers = 0;
2027                                 info->numbots = -1;
2028                                 info->maxplayers  = 0;
2029                                 info->gameversion = 0;
2030
2031                                 if ((s = InfoString_GetValue(string, "gamename"     , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->game, s, sizeof (info->game));
2032                                 if ((s = InfoString_GetValue(string, "modname"      , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
2033                                 if ((s = InfoString_GetValue(string, "mapname"      , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->map , s, sizeof (info->map ));
2034                                 if ((s = InfoString_GetValue(string, "hostname"     , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->name, s, sizeof (info->name));
2035                                 if ((s = InfoString_GetValue(string, "protocol"     , infostringvalue, sizeof(infostringvalue))) != NULL) info->protocol = atoi(s);
2036                                 if ((s = InfoString_GetValue(string, "clients"      , infostringvalue, sizeof(infostringvalue))) != NULL) info->numplayers = atoi(s);
2037                                 if ((s = InfoString_GetValue(string, "bots"         , infostringvalue, sizeof(infostringvalue))) != NULL) info->numbots = atoi(s);
2038                                 if ((s = InfoString_GetValue(string, "sv_maxclients", infostringvalue, sizeof(infostringvalue))) != NULL) info->maxplayers = atoi(s);
2039                                 if ((s = InfoString_GetValue(string, "gameversion"  , infostringvalue, sizeof(infostringvalue))) != NULL) info->gameversion = atoi(s);
2040                                 if ((s = InfoString_GetValue(string, "qcstatus"     , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
2041                                 info->numhumans = info->numplayers - max(0, info->numbots);
2042                                 info->freeslots = info->maxplayers - info->numplayers;
2043
2044                                 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
2045
2046                                 return true;
2047                         }
2048                         if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
2049                         {
2050                                 // Extract the IP addresses
2051                                 data += 18;
2052                                 length -= 18;
2053                                 NetConn_ClientParsePacket_ServerList_ParseDPList(peeraddress, data, length, false);
2054                                 return true;
2055                         }
2056                         if (!strncmp(string, "getserversExtResponse", 21) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
2057                         {
2058                                 // Extract the IP addresses
2059                                 data += 21;
2060                                 length -= 21;
2061                                 NetConn_ClientParsePacket_ServerList_ParseDPList(peeraddress, data, length, true);
2062                                 return true;
2063                         }
2064                         if (!memcmp(string, "d\n", 2) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
2065                         {
2066                                 // Extract the IP addresses
2067                                 data += 2;
2068                                 length -= 2;
2069                                 masterreplycount++;
2070                                 if (serverlist_consoleoutput)
2071                                         Con_Printf("received QuakeWorld server list from %s...\n", addressstring2);
2072                                 while (length >= 6 && (data[0] != 0xFF || data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF) && data[4] * 256 + data[5] != 0)
2073                                 {
2074                                         dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[0], data[1], data[2], data[3], data[4] * 256 + data[5]);
2075                                         if (serverlist_consoleoutput && developer_networking.integer)
2076                                                 Con_Printf("Requesting info from QuakeWorld server %s\n", ipstring);
2077                                         
2078                                         if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, ipstring, false ) ) {
2079                                                 break;
2080                                         }
2081
2082                                         // move on to next address in packet
2083                                         data += 6;
2084                                         length -= 6;
2085                                 }
2086                                 // begin or resume serverlist queries
2087                                 serverlist_querysleep = false;
2088                                 serverlist_querywaittime = host.realtime + 3;
2089                                 return true;
2090                         }
2091                 }
2092 #endif
2093                 if (!strncmp(string, "extResponse ", 12))
2094                 {
2095                         ++cl_net_extresponse_count;
2096                         if(cl_net_extresponse_count > NET_EXTRESPONSE_MAX)
2097                                 cl_net_extresponse_count = NET_EXTRESPONSE_MAX;
2098                         cl_net_extresponse_last = (cl_net_extresponse_last + 1) % NET_EXTRESPONSE_MAX;
2099                         dpsnprintf(cl_net_extresponse[cl_net_extresponse_last], sizeof(cl_net_extresponse[cl_net_extresponse_last]), "\"%s\" %s", addressstring2, string + 12);
2100                         return true;
2101                 }
2102                 if (!strncmp(string, "ping", 4))
2103                 {
2104                         if (developer_extra.integer)
2105                                 Con_DPrintf("Received ping from %s, sending ack\n", addressstring2);
2106                         NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
2107                         return true;
2108                 }
2109                 if (!strncmp(string, "ack", 3))
2110                         return true;
2111                 // QuakeWorld compatibility
2112                 if (length > 1 && string[0] == 'c' && (string[1] == '-' || (string[1] >= '0' && string[1] <= '9')) && cls.connect_trying)
2113                 {
2114                         // challenge message
2115                         if (net_sourceaddresscheck.integer && LHNETADDRESS_Compare(peeraddress, &cls.connect_address)) {
2116                                 Con_DPrintf("c message from wrong server %s\n", addressstring2);
2117                                 return true;
2118                         }
2119                         Con_Printf("challenge %s received, sending QuakeWorld connect request back to %s\n", string + 1, addressstring2);
2120 #ifdef CONFIG_MENU
2121                         M_Update_Return_Reason("Got QuakeWorld challenge response");
2122 #endif
2123                         cls.qw_qport = qport.integer;
2124                         // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
2125                         InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
2126                         memcpy(senddata, "\377\377\377\377", 4);
2127                         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);
2128                         NetConn_WriteString(mysocket, senddata, peeraddress);
2129                         return true;
2130                 }
2131                 if (length >= 1 && string[0] == 'j' && cls.connect_trying)
2132                 {
2133                         // accept message
2134                         if (net_sourceaddresscheck.integer && LHNETADDRESS_Compare(peeraddress, &cls.connect_address)) {
2135                                 Con_DPrintf("j message from wrong server %s\n", addressstring2);
2136                                 return true;
2137                         }
2138 #ifdef CONFIG_MENU
2139                         M_Update_Return_Reason("QuakeWorld Accepted");
2140 #endif
2141                         NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_QUAKEWORLD);
2142                         return true;
2143                 }
2144                 if (length > 2 && !memcmp(string, "n\\", 2))
2145                 {
2146 #ifdef CONFIG_MENU
2147                         serverlist_info_t *info;
2148                         int n;
2149
2150                         // qw server status
2151                         if (serverlist_consoleoutput && developer_networking.integer >= 2)
2152                                 Con_Printf("QW server status from server at %s:\n%s\n", addressstring2, string + 1);
2153
2154                         string += 1;
2155                         // search the cache for this server and update it
2156                         n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
2157                         if (n < 0)
2158                                 return true;
2159
2160                         info = &serverlist_cache[n].info;
2161                         strlcpy(info->game, "QuakeWorld", sizeof(info->game));
2162                         if ((s = InfoString_GetValue(string, "*gamedir"     , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0]  = 0;
2163                         if ((s = InfoString_GetValue(string, "map"          , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0]  = 0;
2164                         if ((s = InfoString_GetValue(string, "hostname"     , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
2165                         info->protocol = 0;
2166                         info->numplayers = 0; // updated below
2167                         info->numhumans = 0; // updated below
2168                         if ((s = InfoString_GetValue(string, "maxclients"   , infostringvalue, sizeof(infostringvalue))) != NULL) info->maxplayers = atoi(s);else info->maxplayers  = 0;
2169                         if ((s = InfoString_GetValue(string, "gameversion"  , infostringvalue, sizeof(infostringvalue))) != NULL) info->gameversion = atoi(s);else info->gameversion = 0;
2170
2171                         // count active players on server
2172                         // (we could gather more info, but we're just after the number)
2173                         s = strchr(string, '\n');
2174                         if (s)
2175                         {
2176                                 s++;
2177                                 while (s < string + length)
2178                                 {
2179                                         for (;s < string + length && *s != '\n';s++)
2180                                                 ;
2181                                         if (s >= string + length)
2182                                                 break;
2183                                         info->numplayers++;
2184                                         info->numhumans++;
2185                                         s++;
2186                                 }
2187                         }
2188
2189                         NetConn_ClientParsePacket_ServerList_UpdateCache(n);
2190 #endif
2191                         return true;
2192                 }
2193                 if (string[0] == 'n')
2194                 {
2195                         // qw print command, used by rcon replies too
2196                         if (net_sourceaddresscheck.integer && LHNETADDRESS_Compare(peeraddress, &cls.connect_address) && LHNETADDRESS_Compare(peeraddress, &cls.rcon_address)) {
2197                                 Con_DPrintf("n message from wrong server %s\n", addressstring2);
2198                                 return true;
2199                         }
2200                         Con_Printf("QW print command from server at %s:\n%s\n", addressstring2, string + 1);
2201                 }
2202                 // we may not have liked the packet, but it was a command packet, so
2203                 // we're done processing this packet now
2204                 return true;
2205         }
2206         // quakeworld ingame packet
2207         if (fromserver && cls.protocol == PROTOCOL_QUAKEWORLD && length >= 8 && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
2208         {
2209                 ret = 0;
2210                 CL_ParseServerMessage();
2211                 return ret;
2212         }
2213         // netquake control packets, supported for compatibility only
2214         if (length >= 5 && BuffBigLong(data) == ((int)NETFLAG_CTL | length) && !ENCRYPTION_REQUIRED)
2215         {
2216 #ifdef CONFIG_MENU
2217                 int n;
2218                 serverlist_info_t *info;
2219 #endif
2220
2221                 data += 4;
2222                 length -= 4;
2223                 SZ_Clear(&cl_message);
2224                 SZ_Write(&cl_message, data, length);
2225                 MSG_BeginReading(&cl_message);
2226                 c = MSG_ReadByte(&cl_message);
2227                 switch (c)
2228                 {
2229                 case CCREP_ACCEPT:
2230                         if (developer_extra.integer)
2231                                 Con_DPrintf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
2232                         if (cls.connect_trying)
2233                         {
2234                                 lhnetaddress_t clientportaddress;
2235                                 if (net_sourceaddresscheck.integer && LHNETADDRESS_Compare(peeraddress, &cls.connect_address)) {
2236                                         Con_DPrintf("CCREP_ACCEPT message from wrong server %s\n", addressstring2);
2237                                         break;
2238                                 }
2239                                 clientportaddress = *peeraddress;
2240                                 LHNETADDRESS_SetPort(&clientportaddress, MSG_ReadLong(&cl_message));
2241                                 // extra ProQuake stuff
2242                                 if (length >= 6)
2243                                         cls.proquake_servermod = MSG_ReadByte(&cl_message); // MOD_PROQUAKE
2244                                 else
2245                                         cls.proquake_servermod = 0;
2246                                 if (length >= 7)
2247                                         cls.proquake_serverversion = MSG_ReadByte(&cl_message); // version * 10
2248                                 else
2249                                         cls.proquake_serverversion = 0;
2250                                 if (length >= 8)
2251                                         cls.proquake_serverflags = MSG_ReadByte(&cl_message); // flags (mainly PQF_CHEATFREE)
2252                                 else
2253                                         cls.proquake_serverflags = 0;
2254                                 if (cls.proquake_servermod == 1)
2255                                         Con_Printf("Connected to ProQuake %.1f server, enabling precise aim\n", cls.proquake_serverversion / 10.0f);
2256                                 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
2257                                 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
2258 #ifdef CONFIG_MENU
2259                                 M_Update_Return_Reason("Accepted");
2260 #endif
2261                                 NetConn_ConnectionEstablished(mysocket, &clientportaddress, PROTOCOL_QUAKE);
2262                         }
2263                         break;
2264                 case CCREP_REJECT:
2265                         if (developer_extra.integer) {
2266                                 Con_DPrintf("CCREP_REJECT message from wrong server %s\n", addressstring2);
2267                                 break;
2268                         }
2269                         if (net_sourceaddresscheck.integer && LHNETADDRESS_Compare(peeraddress, &cls.connect_address))
2270                                 break;
2271                         cls.connect_trying = false;
2272 #ifdef CONFIG_MENU
2273                         M_Update_Return_Reason((char *)MSG_ReadString(&cl_message, cl_readstring, sizeof(cl_readstring)));
2274 #endif
2275                         break;
2276                 case CCREP_SERVER_INFO:
2277                         if (developer_extra.integer)
2278                                 Con_DPrintf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
2279 #ifdef CONFIG_MENU
2280                         // LadyHavoc: because the quake server may report weird addresses
2281                         // we just ignore it and keep the real address
2282                         MSG_ReadString(&cl_message, cl_readstring, sizeof(cl_readstring));
2283                         // search the cache for this server and update it
2284                         n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
2285                         if (n < 0)
2286                                 break;
2287
2288                         info = &serverlist_cache[n].info;
2289                         strlcpy(info->game, "Quake", sizeof(info->game));
2290                         strlcpy(info->mod , "", sizeof(info->mod)); // mod name is not specified
2291                         strlcpy(info->name, MSG_ReadString(&cl_message, cl_readstring, sizeof(cl_readstring)), sizeof(info->name));
2292                         strlcpy(info->map , MSG_ReadString(&cl_message, cl_readstring, sizeof(cl_readstring)), sizeof(info->map));
2293                         info->numplayers = MSG_ReadByte(&cl_message);
2294                         info->maxplayers = MSG_ReadByte(&cl_message);
2295                         info->protocol = MSG_ReadByte(&cl_message);
2296
2297                         NetConn_ClientParsePacket_ServerList_UpdateCache(n);
2298 #endif
2299                         break;
2300                 case CCREP_RCON: // RocketGuy: ProQuake rcon support
2301                         if (net_sourceaddresscheck.integer && LHNETADDRESS_Compare(peeraddress, &cls.rcon_address)) {
2302                                 Con_DPrintf("CCREP_RCON message from wrong server %s\n", addressstring2);
2303                                 break;
2304                         }
2305                         if (developer_extra.integer)
2306                                 Con_DPrintf("Datagram_ParseConnectionless: received CCREP_RCON from %s.\n", addressstring2);
2307
2308                         Con_Printf("%s\n", MSG_ReadString(&cl_message, cl_readstring, sizeof(cl_readstring)));
2309                         break;
2310                 case CCREP_PLAYER_INFO:
2311                         // we got a CCREP_PLAYER_INFO??
2312                         //if (developer_extra.integer)
2313                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
2314                         break;
2315                 case CCREP_RULE_INFO:
2316                         // we got a CCREP_RULE_INFO??
2317                         //if (developer_extra.integer)
2318                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
2319                         break;
2320                 default:
2321                         break;
2322                 }
2323                 SZ_Clear(&cl_message);
2324                 // we may not have liked the packet, but it was a valid control
2325                 // packet, so we're done processing this packet now
2326                 return true;
2327         }
2328         ret = 0;
2329         if (fromserver && length >= (int)NET_HEADERSIZE && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
2330                 CL_ParseServerMessage();
2331         return ret;
2332 }
2333
2334 #ifdef CONFIG_MENU
2335 void NetConn_QueryQueueFrame(void)
2336 {
2337         int index;
2338         int queries;
2339         int maxqueries;
2340         double timeouttime;
2341         static double querycounter = 0;
2342
2343         if(!net_slist_pause.integer && serverlist_paused)
2344                 ServerList_RebuildViewList();
2345         serverlist_paused = net_slist_pause.integer != 0;
2346
2347         if (serverlist_querysleep)
2348                 return;
2349
2350         // apply a cool down time after master server replies,
2351         // to avoid messing up the ping times on the servers
2352         if (serverlist_querywaittime > host.realtime)
2353                 return;
2354
2355         // each time querycounter reaches 1.0 issue a query
2356         querycounter += cl.realframetime * net_slist_queriespersecond.value;
2357         maxqueries = (int)querycounter;
2358         maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer);
2359         querycounter -= maxqueries;
2360
2361         if( maxqueries == 0 ) {
2362                 return;
2363         }
2364
2365         //      scan serverlist and issue queries as needed
2366         serverlist_querysleep = true;
2367
2368         timeouttime     = host.realtime - net_slist_timeout.value;
2369         for( index = 0, queries = 0 ;   index   < serverlist_cachecount &&      queries < maxqueries    ; index++ )
2370         {
2371                 serverlist_entry_t *entry = &serverlist_cache[ index ];
2372                 if( entry->query != SQS_QUERYING && entry->query != SQS_REFRESHING )
2373                 {
2374                         continue;
2375                 }
2376
2377                 serverlist_querysleep   = false;
2378                 if( entry->querycounter !=      0 && entry->querytime > timeouttime     )
2379                 {
2380                         continue;
2381                 }
2382
2383                 if( entry->querycounter !=      (unsigned) net_slist_maxtries.integer )
2384                 {
2385                         lhnetaddress_t  address;
2386                         int socket;
2387
2388                         LHNETADDRESS_FromString(&address, entry->info.cname, 0);
2389                         if      (entry->protocol == PROTOCOL_QUAKEWORLD)
2390                         {
2391                                 for (socket     = 0; socket     < cl_numsockets ;       socket++)
2392                                         NetConn_WriteString(cl_sockets[socket], "\377\377\377\377status\n", &address);
2393                         }
2394                         else
2395                         {
2396                                 for (socket     = 0; socket     < cl_numsockets ;       socket++)
2397                                         NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getstatus", &address);
2398                         }
2399
2400                         //      update the entry fields
2401                         entry->querytime = host.realtime;
2402                         entry->querycounter++;
2403
2404                         // if not in the slist menu we should print the server to console
2405                         if (serverlist_consoleoutput)
2406                                 Con_Printf("querying %25s (%i. try)\n", entry->info.cname, entry->querycounter);
2407
2408                         queries++;
2409                 }
2410                 else
2411                 {
2412                         // have we tried to refresh this server?
2413                         if( entry->query == SQS_REFRESHING ) {
2414                                 // yes, so update the reply count (since its not responding anymore)
2415                                 serverreplycount--;
2416                                 if(!serverlist_paused)
2417                                         ServerList_ViewList_Remove(entry);
2418                         }
2419                         entry->query = SQS_TIMEDOUT;
2420                 }
2421         }
2422 }
2423 #endif
2424
2425 void NetConn_ClientFrame(void)
2426 {
2427         int i, length;
2428         lhnetaddress_t peeraddress;
2429         unsigned char readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
2430         NetConn_UpdateSockets();
2431         if (cls.connect_trying && cls.connect_nextsendtime < host.realtime)
2432         {
2433 #ifdef CONFIG_MENU
2434                 if (cls.connect_remainingtries == 0)
2435                         M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
2436 #endif
2437                 cls.connect_nextsendtime = host.realtime + 1;
2438                 cls.connect_remainingtries--;
2439                 if (cls.connect_remainingtries <= -10)
2440                 {
2441                         cls.connect_trying = false;
2442 #ifdef CONFIG_MENU
2443                         M_Update_Return_Reason("Connect: Failed");
2444 #endif
2445                         return;
2446                 }
2447                 // try challenge first (newer DP server or QW)
2448                 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
2449                 // then try netquake as a fallback (old server, or netquake)
2450                 SZ_Clear(&cl_message);
2451                 // save space for the header, filled in later
2452                 MSG_WriteLong(&cl_message, 0);
2453                 MSG_WriteByte(&cl_message, CCREQ_CONNECT);
2454                 MSG_WriteString(&cl_message, "QUAKE");
2455                 MSG_WriteByte(&cl_message, NET_PROTOCOL_VERSION);
2456                 // extended proquake stuff
2457                 MSG_WriteByte(&cl_message, 1); // mod = MOD_PROQUAKE
2458                 // this version matches ProQuake 3.40, the first version to support
2459                 // the NAT fix, and it only supports the NAT fix for ProQuake 3.40 or
2460                 // higher clients, so we pretend we are that version...
2461                 MSG_WriteByte(&cl_message, 34); // version * 10
2462                 MSG_WriteByte(&cl_message, 0); // flags
2463                 MSG_WriteLong(&cl_message, 0); // password
2464                 // write the packetsize now...
2465                 StoreBigLong(cl_message.data, NETFLAG_CTL | (cl_message.cursize & NETFLAG_LENGTH_MASK));
2466                 NetConn_Write(cls.connect_mysocket, cl_message.data, cl_message.cursize, &cls.connect_address);
2467                 SZ_Clear(&cl_message);
2468         }
2469         for (i = 0;i < cl_numsockets;i++)
2470         {
2471                 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2472                 {
2473 //                      R_TimeReport("clientreadnetwork");
2474                         NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
2475 //                      R_TimeReport("clientparsepacket");
2476                 }
2477         }
2478 #ifdef CONFIG_MENU
2479         NetConn_QueryQueueFrame();
2480 #endif
2481         if (cls.netcon && host.realtime > cls.netcon->timeout && !sv.active)
2482         {
2483                 Con_Print("Connection timed out\n");
2484                 CL_Disconnect();
2485                 SV_LockThreadMutex();
2486                 SV_Shutdown ();
2487                 SV_UnlockThreadMutex();
2488         }
2489 }
2490
2491 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
2492 {
2493         int i;
2494         char c;
2495         for (i = 0;i < bufferlength - 1;i++)
2496         {
2497                 do
2498                 {
2499                         c = rand () % (127 - 33) + 33;
2500                 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
2501                 buffer[i] = c;
2502         }
2503         buffer[i] = 0;
2504 }
2505
2506 /// (div0) build the full response only if possible; better a getinfo response than no response at all if getstatus won't fit
2507 static qbool NetConn_BuildStatusResponse(const char* challenge, char* out_msg, size_t out_size, qbool fullstatus)
2508 {
2509         prvm_prog_t *prog = SVVM_prog;
2510         char qcstatus[256];
2511         unsigned int nb_clients = 0, nb_bots = 0, i;
2512         int length;
2513         char teambuf[3];
2514         const char *crypto_idstring;
2515         const char *worldstatusstr;
2516
2517         // How many clients are there?
2518         for (i = 0;i < (unsigned int)svs.maxclients;i++)
2519         {
2520                 if (svs.clients[i].active)
2521                 {
2522                         nb_clients++;
2523                         if (!svs.clients[i].netconnection)
2524                                 nb_bots++;
2525                 }
2526         }
2527
2528         *qcstatus = 0;
2529         worldstatusstr = PRVM_GetString(prog, PRVM_serverglobalstring(worldstatus));
2530         if(worldstatusstr && *worldstatusstr)
2531         {
2532                 char *p;
2533                 const char *q;
2534                 p = qcstatus;
2535                 for(q = worldstatusstr; *q && (size_t)(p - qcstatus) < (sizeof(qcstatus) - 1); ++q)
2536                         if(*q != '\\' && *q != '\n')
2537                                 *p++ = *q;
2538                 *p = 0;
2539         }
2540
2541         /// \TODO: we should add more information for the full status string
2542         crypto_idstring = Crypto_GetInfoResponseDataString();
2543         length = dpsnprintf(out_msg, out_size,
2544                                                 "\377\377\377\377%s\x0A"
2545                                                 "\\gamename\\%s\\modname\\%s\\gameversion\\%d\\sv_maxclients\\%d"
2546                                                 "\\clients\\%d\\bots\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d"
2547                                                 "%s%s"
2548                                                 "%s%s"
2549                                                 "%s%s"
2550                                                 "%s",
2551                                                 fullstatus ? "statusResponse" : "infoResponse",
2552                                                 gamenetworkfiltername, com_modname, gameversion.integer, svs.maxclients,
2553                                                 nb_clients, nb_bots, sv.worldbasename, hostname.string, NET_PROTOCOL_VERSION,
2554                                                 *qcstatus ? "\\qcstatus\\" : "", qcstatus,
2555                                                 challenge ? "\\challenge\\" : "", challenge ? challenge : "",
2556                                                 crypto_idstring ? "\\d0_blind_id\\" : "", crypto_idstring ? crypto_idstring : "",
2557                                                 fullstatus ? "\n" : "");
2558
2559         // Make sure it fits in the buffer
2560         if (length < 0)
2561                 goto bad;
2562
2563         if (fullstatus)
2564         {
2565                 char *ptr;
2566                 int left;
2567                 int savelength;
2568
2569                 savelength = length;
2570
2571                 ptr = out_msg + length;
2572                 left = (int)out_size - length;
2573
2574                 for (i = 0;i < (unsigned int)svs.maxclients;i++)
2575                 {
2576                         client_t *client = &svs.clients[i];
2577                         if (client->active)
2578                         {
2579                                 int nameind, cleanind, pingvalue;
2580                                 char curchar;
2581                                 char cleanname [sizeof(client->name)];
2582                                 const char *statusstr;
2583                                 prvm_edict_t *ed;
2584
2585                                 // Remove all characters '"' and '\' in the player name
2586                                 nameind = 0;
2587                                 cleanind = 0;
2588                                 do
2589                                 {
2590                                         curchar = client->name[nameind++];
2591                                         if (curchar != '"' && curchar != '\\')
2592                                         {
2593                                                 cleanname[cleanind++] = curchar;
2594                                                 if (cleanind == sizeof(cleanname) - 1)
2595                                                         break;
2596                                         }
2597                                 } while (curchar != '\0');
2598                                 cleanname[cleanind] = 0; // cleanind is always a valid index even at this point
2599
2600                                 pingvalue = (int)(client->ping * 1000.0f);
2601                                 if(client->netconnection)
2602                                         pingvalue = bound(1, pingvalue, 9999);
2603                                 else
2604                                         pingvalue = 0;
2605
2606                                 *qcstatus = 0;
2607                                 ed = PRVM_EDICT_NUM(i + 1);
2608                                 statusstr = PRVM_GetString(prog, PRVM_serveredictstring(ed, clientstatus));
2609                                 if(statusstr && *statusstr)
2610                                 {
2611                                         char *p;
2612                                         const char *q;
2613                                         p = qcstatus;
2614                                         for(q = statusstr; *q && p != qcstatus + sizeof(qcstatus) - 1; ++q)
2615                                                 if(*q != '\\' && *q != '"' && !ISWHITESPACE(*q))
2616                                                         *p++ = *q;
2617                                         *p = 0;
2618                                 }
2619
2620                                 if (IS_NEXUIZ_DERIVED(gamemode) && (teamplay.integer > 0))
2621                                 {
2622                                         if(client->frags == -666) // spectator
2623                                                 strlcpy(teambuf, " 0", sizeof(teambuf));
2624                                         else if(client->colors == 0x44) // red team
2625                                                 strlcpy(teambuf, " 1", sizeof(teambuf));
2626                                         else if(client->colors == 0xDD) // blue team
2627                                                 strlcpy(teambuf, " 2", sizeof(teambuf));
2628                                         else if(client->colors == 0xCC) // yellow team
2629                                                 strlcpy(teambuf, " 3", sizeof(teambuf));
2630                                         else if(client->colors == 0x99) // pink team
2631                                                 strlcpy(teambuf, " 4", sizeof(teambuf));
2632                                         else
2633                                                 strlcpy(teambuf, " 0", sizeof(teambuf));
2634                                 }
2635                                 else
2636                                         *teambuf = 0;
2637
2638                                 // note: team number is inserted according to SoF2 protocol
2639                                 if(*qcstatus)
2640                                         length = dpsnprintf(ptr, left, "%s %d%s \"%s\"\n",
2641                                                                                 qcstatus,
2642                                                                                 pingvalue,
2643                                                                                 teambuf,
2644                                                                                 cleanname);
2645                                 else
2646                                         length = dpsnprintf(ptr, left, "%d %d%s \"%s\"\n",
2647                                                                                 client->frags,
2648                                                                                 pingvalue,
2649                                                                                 teambuf,
2650                                                                                 cleanname);
2651
2652                                 if(length < 0)
2653                                 {
2654                                         // out of space?
2655                                         // turn it into an infoResponse!
2656                                         out_msg[savelength] = 0;
2657                                         memcpy(out_msg + 4, "infoResponse\x0A", 13);
2658                                         memmove(out_msg + 17, out_msg + 19, savelength - 19);
2659                                         break;
2660                                 }
2661                                 left -= length;
2662                                 ptr += length;
2663                         }
2664                 }
2665         }
2666
2667         return true;
2668
2669 bad:
2670         return false;
2671 }
2672
2673 static qbool NetConn_PreventFlood(lhnetaddress_t *peeraddress, server_floodaddress_t *floodlist, size_t floodlength, double floodtime, qbool renew)
2674 {
2675         size_t floodslotnum, bestfloodslotnum;
2676         double bestfloodtime;
2677         lhnetaddress_t noportpeeraddress;
2678         // see if this is a connect flood
2679         noportpeeraddress = *peeraddress;
2680         LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2681         bestfloodslotnum = 0;
2682         bestfloodtime = floodlist[bestfloodslotnum].lasttime;
2683         for (floodslotnum = 0;floodslotnum < floodlength;floodslotnum++)
2684         {
2685                 if (bestfloodtime >= floodlist[floodslotnum].lasttime)
2686                 {
2687                         bestfloodtime = floodlist[floodslotnum].lasttime;
2688                         bestfloodslotnum = floodslotnum;
2689                 }
2690                 if (floodlist[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &floodlist[floodslotnum].address) == 0)
2691                 {
2692                         // this address matches an ongoing flood address
2693                         if (host.realtime < floodlist[floodslotnum].lasttime + floodtime)
2694                         {
2695                                 if(renew)
2696                                 {
2697                                         // renew the ban on this address so it does not expire
2698                                         // until the flood has subsided
2699                                         floodlist[floodslotnum].lasttime = host.realtime;
2700                                 }
2701                                 //Con_Printf("Flood detected!\n");
2702                                 return true;
2703                         }
2704                         // the flood appears to have subsided, so allow this
2705                         bestfloodslotnum = floodslotnum; // reuse the same slot
2706                         break;
2707                 }
2708         }
2709         // begin a new timeout on this address
2710         floodlist[bestfloodslotnum].address = noportpeeraddress;
2711         floodlist[bestfloodslotnum].lasttime = host.realtime;
2712         //Con_Printf("Flood detection initiated!\n");
2713         return false;
2714 }
2715
2716 void NetConn_ClearFlood(lhnetaddress_t *peeraddress, server_floodaddress_t *floodlist, size_t floodlength)
2717 {
2718         size_t floodslotnum;
2719         lhnetaddress_t noportpeeraddress;
2720         // see if this is a connect flood
2721         noportpeeraddress = *peeraddress;
2722         LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2723         for (floodslotnum = 0;floodslotnum < floodlength;floodslotnum++)
2724         {
2725                 if (floodlist[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &floodlist[floodslotnum].address) == 0)
2726                 {
2727                         // this address matches an ongoing flood address
2728                         // remove the ban
2729                         floodlist[floodslotnum].address.addresstype = LHNETADDRESSTYPE_NONE;
2730                         floodlist[floodslotnum].lasttime = 0;
2731                         //Con_Printf("Flood cleared!\n");
2732                 }
2733         }
2734 }
2735
2736 typedef qbool (*rcon_matchfunc_t) (lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen);
2737
2738 static qbool hmac_mdfour_time_matching(lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen)
2739 {
2740         char mdfourbuf[16];
2741         long t1, t2;
2742
2743         if (!password[0]) {
2744                 Con_Print(CON_ERROR "LOGIC ERROR: RCon_Authenticate should never call the comparator with an empty password. Please report.\n");
2745                 return false;
2746         }
2747
2748         t1 = (long) time(NULL);
2749         t2 = strtol(s, NULL, 0);
2750         if(labs(t1 - t2) > rcon_secure_maxdiff.integer)
2751                 return false;
2752
2753         if(!HMAC_MDFOUR_16BYTES((unsigned char *) mdfourbuf, (unsigned char *) s, slen, (unsigned char *) password, (int)strlen(password)))
2754                 return false;
2755
2756         return !memcmp(mdfourbuf, hash, 16);
2757 }
2758
2759 static qbool hmac_mdfour_challenge_matching(lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen)
2760 {
2761         char mdfourbuf[16];
2762         int i;
2763
2764         if (!password[0]) {
2765                 Con_Print(CON_ERROR "LOGIC ERROR: RCon_Authenticate should never call the comparator with an empty password. Please report.\n");
2766                 return false;
2767         }
2768
2769         if(slen < (int)(sizeof(challenges[0].string)) - 1)
2770                 return false;
2771
2772         // validate the challenge
2773         for (i = 0;i < MAX_CHALLENGES;i++)
2774                 if(challenges[i].time > 0)
2775                         if (!LHNETADDRESS_Compare(peeraddress, &challenges[i].address) && !strncmp(challenges[i].string, s, sizeof(challenges[0].string) - 1))
2776                                 break;
2777         // if the challenge is not recognized, drop the packet
2778         if (i == MAX_CHALLENGES)
2779                 return false;
2780
2781         if(!HMAC_MDFOUR_16BYTES((unsigned char *) mdfourbuf, (unsigned char *) s, slen, (unsigned char *) password, (int)strlen(password)))
2782                 return false;
2783
2784         if(memcmp(mdfourbuf, hash, 16))
2785                 return false;
2786
2787         // unmark challenge to prevent replay attacks
2788         challenges[i].time = 0;
2789
2790         return true;
2791 }
2792
2793 static qbool plaintext_matching(lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen)
2794 {
2795         if (!password[0]) {
2796                 Con_Print(CON_ERROR "LOGIC ERROR: RCon_Authenticate should never call the comparator with an empty password. Please report.\n");
2797                 return false;
2798         }
2799
2800         return !strcmp(password, hash);
2801 }
2802
2803 /// returns a string describing the user level, or NULL for auth failure
2804 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)
2805 {
2806         const char *text, *userpass_start, *userpass_end, *userpass_startpass;
2807         static char buf[MAX_INPUTLINE];
2808         qbool hasquotes;
2809         qbool restricted = false;
2810         qbool have_usernames = false;
2811         static char vabuf[1024];
2812
2813         userpass_start = rcon_password.string;
2814         while((userpass_end = strchr(userpass_start, ' ')))
2815         {
2816                 have_usernames = true;
2817                 strlcpy(buf, userpass_start, ((size_t)(userpass_end-userpass_start) >= sizeof(buf)) ? (int)(sizeof(buf)) : (int)(userpass_end-userpass_start+1));
2818                 if(buf[0])  // Ignore empty entries due to leading/duplicate space.
2819                         if(comparator(peeraddress, buf, password, cs, cslen))
2820                                 goto allow;
2821                 userpass_start = userpass_end + 1;
2822         }
2823         if(userpass_start[0])  // Ignore empty trailing entry due to trailing space or password not set.
2824         {
2825                 userpass_end = userpass_start + strlen(userpass_start);
2826                 if(comparator(peeraddress, userpass_start, password, cs, cslen))
2827                         goto allow;
2828         }
2829
2830         restricted = true;
2831         have_usernames = false;
2832         userpass_start = rcon_restricted_password.string;
2833         while((userpass_end = strchr(userpass_start, ' ')))
2834         {
2835                 have_usernames = true;
2836                 strlcpy(buf, userpass_start, ((size_t)(userpass_end-userpass_start) >= sizeof(buf)) ? (int)(sizeof(buf)) : (int)(userpass_end-userpass_start+1));
2837                 if(buf[0])  // Ignore empty entries due to leading/duplicate space.
2838                         if(comparator(peeraddress, buf, password, cs, cslen))
2839                                 goto check;
2840                 userpass_start = userpass_end + 1;
2841         }
2842         if(userpass_start[0])  // Ignore empty trailing entry due to trailing space or password not set.
2843         {
2844                 userpass_end = userpass_start + strlen(userpass_start);
2845                 if(comparator(peeraddress, userpass_start, password, cs, cslen))
2846                         goto check;
2847         }
2848         
2849         return NULL; // DENIED
2850
2851 check:
2852         for(text = s; text != endpos; ++text)
2853                 if((signed char) *text > 0 && ((signed char) *text < (signed char) ' ' || *text == ';'))
2854                         return NULL; // block possible exploits against the parser/alias expansion
2855
2856         while(s != endpos)
2857         {
2858                 size_t l = strlen(s);
2859                 if(l)
2860                 {
2861                         hasquotes = (strchr(s, '"') != NULL);
2862                         // sorry, we can't allow these substrings in wildcard expressions,
2863                         // as they can mess with the argument counts
2864                         text = rcon_restricted_commands.string;
2865                         while(COM_ParseToken_Console(&text))
2866                         {
2867                                 // com_token now contains a pattern to check for...
2868                                 if(strchr(com_token, '*') || strchr(com_token, '?')) // wildcard expression, * can only match a SINGLE argument
2869                                 {
2870                                         if(!hasquotes)
2871                                                 if(matchpattern_with_separator(s, com_token, true, " ", true)) // note how we excluded tab, newline etc. above
2872                                                         goto match;
2873                                 }
2874                                 else if(strchr(com_token, ' ')) // multi-arg expression? must match in whole
2875                                 {
2876                                         if(!strcmp(com_token, s))
2877                                                 goto match;
2878                                 }
2879                                 else // single-arg expression? must match the beginning of the command
2880                                 {
2881                                         if(!strcmp(com_token, s))
2882                                                 goto match;
2883                                         if(!memcmp(va(vabuf, sizeof(vabuf), "%s ", com_token), s, strlen(com_token) + 1))
2884                                                 goto match;
2885                                 }
2886                         }
2887                         // if we got here, nothing matched!
2888                         return NULL;
2889                 }
2890 match:
2891                 s += l + 1;
2892         }
2893
2894 allow:
2895         userpass_startpass = strchr(userpass_start, ':');
2896         if(have_usernames && userpass_startpass && userpass_startpass < userpass_end)
2897                 return va(vabuf, sizeof(vabuf), "%srcon (username %.*s)", restricted ? "restricted " : "", (int)(userpass_startpass-userpass_start), userpass_start);
2898
2899         return va(vabuf, sizeof(vabuf), "%srcon", restricted ? "restricted " : "");
2900 }
2901
2902 static void RCon_Execute(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, const char *addressstring2, const char *userlevel, const char *s, const char *endpos, qbool proquakeprotocol)
2903 {
2904         if(userlevel)
2905         {
2906                 // looks like a legitimate rcon command with the correct password
2907                 const char *s_ptr = s;
2908                 Con_Printf("server received %s command from %s: ", userlevel, host_client ? host_client->name : addressstring2);
2909                 while(s_ptr != endpos)
2910                 {
2911                         size_t l = strlen(s_ptr);
2912                         if(l)
2913                                 Con_Printf(" %s;", s_ptr);
2914                         s_ptr += l + 1;
2915                 }
2916                 Con_Printf("\n");
2917
2918                 if (!host_client || !host_client->netconnection || LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2919                         Con_Rcon_Redirect_Init(mysocket, peeraddress, proquakeprotocol);
2920                 while(s != endpos)
2921                 {
2922                         size_t l = strlen(s);
2923                         if(l)
2924                         {
2925                                 client_t *host_client_save = host_client;
2926                                 Cmd_ExecuteString(cmd_server, s, src_local, true);
2927                                 host_client = host_client_save;
2928                                 // in case it is a command that changes host_client (like restart)
2929                         }
2930                         s += l + 1;
2931                 }
2932                 Con_Rcon_Redirect_End();
2933         }
2934         else
2935         {
2936                 Con_Printf("server denied rcon access to %s\n", host_client ? host_client->name : addressstring2);
2937         }
2938 }
2939
2940 static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
2941 {
2942         int i, ret, clientnum, best;
2943         double besttime;
2944         char *string, response[2800], addressstring2[128];
2945         static char stringbuf[16384]; // server only
2946         qbool islocal = (LHNETADDRESS_GetAddressType(peeraddress) == LHNETADDRESSTYPE_LOOP);
2947         char senddata[NET_HEADERSIZE+NET_MAXMESSAGE+CRYPTO_HEADERSIZE];
2948         size_t sendlength, response_len;
2949         char infostringvalue[MAX_INPUTLINE];
2950
2951         if (!sv.active)
2952                 return false;
2953
2954         // convert the address to a string incase we need it
2955         LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
2956
2957         // see if we can identify the sender as a local player
2958         // (this is necessary for rcon to send a reliable reply if the client is
2959         //  actually on the server, not sending remotely)
2960         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2961                 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
2962                         break;
2963         if (i == svs.maxclients)
2964                 host_client = NULL;
2965
2966         if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
2967         {
2968                 // received a command string - strip off the packaging and put it
2969                 // into our string buffer with NULL termination
2970                 data += 4;
2971                 length -= 4;
2972                 length = min(length, (int)sizeof(stringbuf) - 1);
2973                 memcpy(stringbuf, data, length);
2974                 stringbuf[length] = 0;
2975                 string = stringbuf;
2976
2977                 if (developer_extra.integer)
2978                 {
2979                         Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
2980                         Com_HexDumpToConsole(data, length);
2981                 }
2982
2983                 sendlength = sizeof(senddata) - 4;
2984                 switch(Crypto_ServerParsePacket(string, length, senddata+4, &sendlength, peeraddress))
2985                 {
2986                         case CRYPTO_NOMATCH:
2987                                 // nothing to do
2988                                 break;
2989                         case CRYPTO_MATCH:
2990                                 if(sendlength)
2991                                 {
2992                                         memcpy(senddata, "\377\377\377\377", 4);
2993                                         NetConn_Write(mysocket, senddata, (int)sendlength+4, peeraddress);
2994                                 }
2995                                 break;
2996                         case CRYPTO_DISCARD:
2997                                 if(sendlength)
2998                                 {
2999                                         memcpy(senddata, "\377\377\377\377", 4);
3000                                         NetConn_Write(mysocket, senddata, (int)sendlength+4, peeraddress);
3001                                 }
3002                                 return true;
3003                                 break;
3004                         case CRYPTO_REPLACE:
3005                                 string = senddata+4;
3006                                 length = (int)sendlength;
3007                                 break;
3008                 }
3009
3010                 if (length >= 12 && !memcmp(string, "getchallenge", 12) && (islocal || sv_public.integer > -3))
3011                 {
3012                         for (i = 0, best = 0, besttime = host.realtime;i < MAX_CHALLENGES;i++)
3013                         {
3014                                 if(challenges[i].time > 0)
3015                                         if (!LHNETADDRESS_Compare(peeraddress, &challenges[i].address))
3016                                                 break;
3017                                 if (besttime > challenges[i].time)
3018                                         besttime = challenges[best = i].time;
3019                         }
3020                         // if we did not find an exact match, choose the oldest and
3021                         // update address and string
3022                         if (i == MAX_CHALLENGES)
3023                         {
3024                                 i = best;
3025                                 challenges[i].address = *peeraddress;
3026                                 NetConn_BuildChallengeString(challenges[i].string, sizeof(challenges[i].string));
3027                         }
3028                         else
3029                         {
3030                                 // flood control: drop if requesting challenge too often
3031                                 if(challenges[i].time > host.realtime - net_challengefloodblockingtimeout.value)
3032                                         return true;
3033                         }
3034                         challenges[i].time = host.realtime;
3035                         // send the challenge
3036                         memcpy(response, "\377\377\377\377", 4);
3037                         dpsnprintf(response+4, sizeof(response)-4, "challenge %s", challenges[i].string);
3038                         response_len = strlen(response) + 1;
3039                         Crypto_ServerAppendToChallenge(string, length, response, &response_len, sizeof(response));
3040                         NetConn_Write(mysocket, response, (int)response_len, peeraddress);
3041                         return true;
3042                 }
3043                 if (length > 8 && !memcmp(string, "connect\\", 8))
3044                 {
3045                         char *s;
3046                         client_t *client;
3047                         crypto_t *crypto = Crypto_ServerGetInstance(peeraddress);
3048                         string += 7;
3049                         length -= 7;
3050
3051                         if(crypto && crypto->authenticated)
3052                         {
3053                                 // no need to check challenge
3054                                 if(crypto_developer.integer)
3055                                 {
3056                                         Con_Printf("%s connection to %s is being established: client is %s@%s%.*s, I am %.*s@%s%.*s\n",
3057                                                         crypto->use_aes ? "Encrypted" : "Authenticated",
3058                                                         addressstring2,
3059                                                         crypto->client_idfp[0] ? crypto->client_idfp : "-",
3060                                                         (crypto->client_issigned || !crypto->client_keyfp[0]) ? "" : "~",
3061                                                         crypto_keyfp_recommended_length, crypto->client_keyfp[0] ? crypto->client_keyfp : "-",
3062                                                         crypto_keyfp_recommended_length, crypto->server_idfp[0] ? crypto->server_idfp : "-",
3063                                                         (crypto->server_issigned || !crypto->server_keyfp[0]) ? "" : "~",
3064                                                         crypto_keyfp_recommended_length, crypto->server_keyfp[0] ? crypto->server_keyfp : "-"
3065                                                   );
3066                                 }
3067                         }
3068                         else
3069                         {
3070                                 if ((s = InfoString_GetValue(string, "challenge", infostringvalue, sizeof(infostringvalue))))
3071                                 {
3072                                         // validate the challenge
3073                                         for (i = 0;i < MAX_CHALLENGES;i++)
3074                                                 if(challenges[i].time > 0)
3075                                                         if (!LHNETADDRESS_Compare(peeraddress, &challenges[i].address) && !strcmp(challenges[i].string, s))
3076                                                                 break;
3077                                         // if the challenge is not recognized, drop the packet
3078                                         if (i == MAX_CHALLENGES)
3079                                                 return true;
3080                                 }
3081                         }
3082
3083                         if((s = InfoString_GetValue(string, "message", infostringvalue, sizeof(infostringvalue))))
3084                                 Con_DPrintf("Connecting client %s sent us the message: %s\n", addressstring2, s);
3085
3086                         if(!(islocal || sv_public.integer > -2))
3087                         {
3088                                 if (developer_extra.integer)
3089                                         Con_Printf("Datagram_ParseConnectionless: sending \"reject %s\" to %s.\n", sv_public_rejectreason.string, addressstring2);
3090                                 memcpy(response, "\377\377\377\377", 4);
3091                                 dpsnprintf(response+4, sizeof(response)-4, "reject %s", sv_public_rejectreason.string);
3092                                 NetConn_WriteString(mysocket, response, peeraddress);
3093                                 return true;
3094                         }
3095
3096                         // check engine protocol
3097                         if(!(s = InfoString_GetValue(string, "protocol", infostringvalue, sizeof(infostringvalue))) || strcmp(s, "darkplaces 3"))
3098                         {
3099                                 if (developer_extra.integer)
3100                                         Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
3101                                 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
3102                                 return true;
3103                         }
3104
3105                         // see if this is a duplicate connection request or a disconnected
3106                         // client who is rejoining to the same client slot
3107                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
3108                         {
3109                                 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
3110                                 {
3111                                         // this is a known client...
3112                                         if(crypto && crypto->authenticated)
3113                                         {
3114                                                 // reject if changing key!
3115                                                 if(client->netconnection->crypto.authenticated)
3116                                                 {
3117                                                         if(
3118                                                                         strcmp(client->netconnection->crypto.client_idfp, crypto->client_idfp)
3119                                                                         ||
3120                                                                         strcmp(client->netconnection->crypto.server_idfp, crypto->server_idfp)
3121                                                                         ||
3122                                                                         strcmp(client->netconnection->crypto.client_keyfp, crypto->client_keyfp)
3123                                                                         ||
3124                                                                         strcmp(client->netconnection->crypto.server_keyfp, crypto->server_keyfp)
3125                                                           )
3126                                                         {
3127                                                                 if (developer_extra.integer)
3128                                                                         Con_Printf("Datagram_ParseConnectionless: sending \"reject Attempt to change key of crypto.\" to %s.\n", addressstring2);
3129                                                                 NetConn_WriteString(mysocket, "\377\377\377\377reject Attempt to change key of crypto.", peeraddress);
3130                                                                 return true;
3131                                                         }
3132                                                 }
3133                                         }
3134                                         else
3135                                         {
3136                                                 // reject if downgrading!
3137                                                 if(client->netconnection->crypto.authenticated)
3138                                                 {
3139                                                         if (developer_extra.integer)
3140                                                                 Con_Printf("Datagram_ParseConnectionless: sending \"reject Attempt to downgrade crypto.\" to %s.\n", addressstring2);
3141                                                         NetConn_WriteString(mysocket, "\377\377\377\377reject Attempt to downgrade crypto.", peeraddress);
3142                                                         return true;
3143                                                 }
3144                                         }
3145                                         if (client->begun)
3146                                         {
3147                                                 // client crashed and is coming back,
3148                                                 // keep their stuff intact
3149                                                 if (developer_extra.integer)
3150                                                         Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", addressstring2);
3151                                                 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
3152                                                 if(crypto && crypto->authenticated)
3153                                                         Crypto_FinishInstance(&client->netconnection->crypto, crypto);
3154                                                 SV_SendServerinfo(client);
3155                                         }
3156                                         else
3157                                         {
3158                                                 // client is still trying to connect,
3159                                                 // so we send a duplicate reply
3160                                                 if (developer_extra.integer)
3161                                                         Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
3162                                                 if(crypto && crypto->authenticated)
3163                                                         Crypto_FinishInstance(&client->netconnection->crypto, crypto);
3164                                                 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
3165                                         }
3166                                         return true;
3167                                 }
3168                         }
3169
3170                         if (NetConn_PreventFlood(peeraddress, sv.connectfloodaddresses, sizeof(sv.connectfloodaddresses) / sizeof(sv.connectfloodaddresses[0]), net_connectfloodblockingtimeout.value, true))
3171                                 return true;
3172
3173                         // find an empty client slot for this new client
3174                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
3175                         {
3176                                 netconn_t *conn;
3177                                 if (!client->active && (conn = NetConn_Open(mysocket, peeraddress)))
3178                                 {
3179                                         // allocated connection
3180                                         if (developer_extra.integer)
3181                                                 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
3182                                         NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
3183                                         // now set up the client
3184                                         if(crypto && crypto->authenticated)
3185                                                 Crypto_FinishInstance(&conn->crypto, crypto);
3186                                         SV_ConnectClient(clientnum, conn);
3187                                         NetConn_Heartbeat(1);
3188                                         return true;
3189                                 }
3190                         }
3191
3192                         // no empty slots found - server is full
3193                         if (developer_extra.integer)
3194                                 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
3195                         NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
3196
3197                         return true;
3198                 }
3199                 if (length >= 7 && !memcmp(string, "getinfo", 7) && (islocal || sv_public.integer > -1))
3200                 {
3201                         const char *challenge = NULL;
3202
3203                         if (NetConn_PreventFlood(peeraddress, sv.getstatusfloodaddresses, sizeof(sv.getstatusfloodaddresses) / sizeof(sv.getstatusfloodaddresses[0]), net_getstatusfloodblockingtimeout.value, false))
3204                                 return true;
3205
3206                         // If there was a challenge in the getinfo message
3207                         if (length > 8 && string[7] == ' ')
3208                                 challenge = string + 8;
3209
3210                         if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
3211                         {
3212                                 if (developer_extra.integer)
3213                                         Con_DPrintf("Sending reply to master %s - %s\n", addressstring2, response);
3214                                 NetConn_WriteString(mysocket, response, peeraddress);
3215                         }
3216                         return true;
3217                 }
3218                 if (length >= 9 && !memcmp(string, "getstatus", 9) && (islocal || sv_public.integer > -1))
3219                 {
3220                         const char *challenge = NULL;
3221
3222                         if (NetConn_PreventFlood(peeraddress, sv.getstatusfloodaddresses, sizeof(sv.getstatusfloodaddresses) / sizeof(sv.getstatusfloodaddresses[0]), net_getstatusfloodblockingtimeout.value, false))
3223                                 return true;
3224
3225                         // If there was a challenge in the getinfo message
3226                         if (length > 10 && string[9] == ' ')
3227                                 challenge = string + 10;
3228
3229                         if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
3230                         {
3231                                 if (developer_extra.integer)
3232                                         Con_DPrintf("Sending reply to client %s - %s\n", addressstring2, response);
3233                                 NetConn_WriteString(mysocket, response, peeraddress);
3234                         }
3235                         return true;
3236                 }
3237                 if (length >= 37 && !memcmp(string, "srcon HMAC-MD4 TIME ", 20))
3238                 {
3239                         char *password = string + 20;
3240                         char *timeval = string + 37;
3241                         char *s = strchr(timeval, ' ');
3242                         char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
3243                         const char *userlevel;
3244
3245                         if(rcon_secure.integer > 1)
3246                                 return true;
3247
3248                         if(!s)
3249                                 return true; // invalid packet
3250                         ++s;
3251
3252                         userlevel = RCon_Authenticate(peeraddress, password, s, endpos, hmac_mdfour_time_matching, timeval, endpos - timeval - 1); // not including the appended \0 into the HMAC
3253                         RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos, false);
3254                         return true;
3255                 }
3256                 if (length >= 42 && !memcmp(string, "srcon HMAC-MD4 CHALLENGE ", 25))
3257                 {
3258                         char *password = string + 25;
3259                         char *challenge = string + 42;
3260                         char *s = strchr(challenge, ' ');
3261                         char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
3262                         const char *userlevel;
3263                         if(!s)
3264                                 return true; // invalid packet
3265                         ++s;
3266
3267                         userlevel = RCon_Authenticate(peeraddress, password, s, endpos, hmac_mdfour_challenge_matching, challenge, endpos - challenge - 1); // not including the appended \0 into the HMAC
3268                         RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos, false);
3269                         return true;
3270                 }
3271                 if (length >= 5 && !memcmp(string, "rcon ", 5))
3272                 {
3273                         int j;
3274                         char *s = string + 5;
3275                         char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
3276                         char password[64];
3277
3278                         if(rcon_secure.integer > 0)
3279                                 return true;
3280
3281                         for (j = 0;!ISWHITESPACE(*s);s++)
3282                                 if (j < (int)sizeof(password) - 1)
3283                                         password[j++] = *s;
3284                         if(ISWHITESPACE(*s) && s != endpos) // skip leading ugly space
3285                                 ++s;
3286                         password[j] = 0;
3287                         if (!ISWHITESPACE(password[0]))
3288                         {
3289                                 const char *userlevel = RCon_Authenticate(peeraddress, password, s, endpos, plaintext_matching, NULL, 0);
3290                                 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos, false);
3291                         }
3292                         return true;
3293                 }
3294                 if (!strncmp(string, "extResponse ", 12))
3295                 {
3296                         ++sv_net_extresponse_count;
3297                         if(sv_net_extresponse_count > NET_EXTRESPONSE_MAX)
3298                                 sv_net_extresponse_count = NET_EXTRESPONSE_MAX;
3299                         sv_net_extresponse_last = (sv_net_extresponse_last + 1) % NET_EXTRESPONSE_MAX;
3300                         dpsnprintf(sv_net_extresponse[sv_net_extresponse_last], sizeof(sv_net_extresponse[sv_net_extresponse_last]), "'%s' %s", addressstring2, string + 12);
3301                         return true;
3302                 }
3303                 if (!strncmp(string, "ping", 4))
3304                 {
3305                         if (developer_extra.integer)
3306                                 Con_DPrintf("Received ping from %s, sending ack\n", addressstring2);
3307                         NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
3308                         return true;
3309                 }
3310                 if (!strncmp(string, "ack", 3))
3311                         return true;
3312                 // we may not have liked the packet, but it was a command packet, so
3313                 // we're done processing this packet now
3314                 return true;
3315         }
3316         // netquake control packets, supported for compatibility only, and only
3317         // when running game protocols that are normally served via this connection
3318         // protocol
3319         // (this protects more modern protocols against being used for
3320         //  Quake packet flood Denial Of Service attacks)
3321         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)
3322         {
3323                 int c;
3324                 int protocolnumber;
3325                 const char *protocolname;
3326                 client_t *knownclient;
3327                 client_t *newclient;
3328                 data += 4;
3329                 length -= 4;
3330                 SZ_Clear(&sv_message);
3331                 SZ_Write(&sv_message, data, length);
3332                 MSG_BeginReading(&sv_message);
3333                 c = MSG_ReadByte(&sv_message);
3334                 switch (c)
3335                 {
3336                 case CCREQ_CONNECT:
3337                         if (developer_extra.integer)
3338                                 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
3339                         if(!(islocal || sv_public.integer > -2))
3340                         {
3341                                 if (developer_extra.integer)
3342                                         Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_REJECT \"%s\" to %s.\n", sv_public_rejectreason.string, addressstring2);
3343                                 SZ_Clear(&sv_message);
3344                                 // save space for the header, filled in later
3345                                 MSG_WriteLong(&sv_message, 0);
3346                                 MSG_WriteByte(&sv_message, CCREP_REJECT);
3347                                 MSG_WriteUnterminatedString(&sv_message, sv_public_rejectreason.string);
3348                                 MSG_WriteString(&sv_message, "\n");
3349                                 StoreBigLong(sv_message.data, NETFLAG_CTL | (sv_message.cursize & NETFLAG_LENGTH_MASK));
3350                                 NetConn_Write(mysocket, sv_message.data, sv_message.cursize, peeraddress);
3351                                 SZ_Clear(&sv_message);
3352                                 break;
3353                         }
3354
3355                         protocolname = MSG_ReadString(&sv_message, sv_readstring, sizeof(sv_readstring));
3356                         protocolnumber = MSG_ReadByte(&sv_message);
3357                         if (strcmp(protocolname, "QUAKE") || protocolnumber != NET_PROTOCOL_VERSION)
3358                         {
3359                                 if (developer_extra.integer)
3360                                         Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
3361                                 SZ_Clear(&sv_message);
3362                                 // save space for the header, filled in later
3363                                 MSG_WriteLong(&sv_message, 0);
3364                                 MSG_WriteByte(&sv_message, CCREP_REJECT);
3365                                 MSG_WriteString(&sv_message, "Incompatible version.\n");
3366                                 StoreBigLong(sv_message.data, NETFLAG_CTL | (sv_message.cursize & NETFLAG_LENGTH_MASK));
3367                                 NetConn_Write(mysocket, sv_message.data, sv_message.cursize, peeraddress);
3368                                 SZ_Clear(&sv_message);
3369                                 break;
3370                         }
3371
3372                         // see if this connect request comes from a known client
3373                         for (clientnum = 0, knownclient = svs.clients;clientnum < svs.maxclients;clientnum++, knownclient++)
3374                         {
3375                                 if (knownclient->netconnection && LHNETADDRESS_Compare(peeraddress, &knownclient->netconnection->peeraddress) == 0)
3376                                 {
3377                                         // this is either a duplicate connection request
3378                                         // or coming back from a timeout
3379                                         // (if so, keep their stuff intact)
3380
3381                                         crypto_t *crypto = Crypto_ServerGetInstance(peeraddress);
3382                                         if((crypto && crypto->authenticated) || knownclient->netconnection->crypto.authenticated)
3383                                         {
3384                                                 if (developer_extra.integer)
3385                                                         Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Attempt to downgrade crypto.\" to %s.\n", addressstring2);
3386                                                 SZ_Clear(&sv_message);
3387                                                 // save space for the header, filled in later
3388                                                 MSG_WriteLong(&sv_message, 0);
3389                                                 MSG_WriteByte(&sv_message, CCREP_REJECT);
3390                                                 MSG_WriteString(&sv_message, "Attempt to downgrade crypto.\n");
3391                                                 StoreBigLong(sv_message.data, NETFLAG_CTL | (sv_message.cursize & NETFLAG_LENGTH_MASK));
3392                                                 NetConn_Write(mysocket, sv_message.data, sv_message.cursize, peeraddress);
3393                                                 SZ_Clear(&sv_message);
3394                                                 return true;
3395                                         }
3396
3397                                         // send a reply
3398                                         if (developer_extra.integer)
3399                                                 Con_DPrintf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
3400                                         SZ_Clear(&sv_message);
3401                                         // save space for the header, filled in later
3402                                         MSG_WriteLong(&sv_message, 0);
3403                                         MSG_WriteByte(&sv_message, CCREP_ACCEPT);
3404                                         MSG_WriteLong(&sv_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(knownclient->netconnection->mysocket)));
3405                                         StoreBigLong(sv_message.data, NETFLAG_CTL | (sv_message.cursize & NETFLAG_LENGTH_MASK));
3406                                         NetConn_Write(mysocket, sv_message.data, sv_message.cursize, peeraddress);
3407                                         SZ_Clear(&sv_message);
3408
3409                                         // if client is already spawned, re-send the
3410                                         // serverinfo message as they'll need it to play
3411                                         if (knownclient->begun)
3412                                                 SV_SendServerinfo(knownclient);
3413                                         return true;
3414                                 }
3415                         }
3416
3417                         // this is a new client, check for connection flood
3418                         if (NetConn_PreventFlood(peeraddress, sv.connectfloodaddresses, sizeof(sv.connectfloodaddresses) / sizeof(sv.connectfloodaddresses[0]), net_connectfloodblockingtimeout.value, true))
3419                                 break;
3420
3421                         // find a slot for the new client
3422                         for (clientnum = 0, newclient = svs.clients;clientnum < svs.maxclients;clientnum++, newclient++)
3423                         {
3424                                 netconn_t *conn;
3425                                 if (!newclient->active && (newclient->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
3426                                 {
3427                                         // connect to the client
3428                                         // everything is allocated, just fill in the details
3429                                         strlcpy (conn->address, addressstring2, sizeof (conn->address));
3430                                         if (developer_extra.integer)
3431                                                 Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
3432                                         // send back the info about the server connection
3433                                         SZ_Clear(&sv_message);
3434                                         // save space for the header, filled in later
3435                                         MSG_WriteLong(&sv_message, 0);
3436                                         MSG_WriteByte(&sv_message, CCREP_ACCEPT);
3437                                         MSG_WriteLong(&sv_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
3438                                         StoreBigLong(sv_message.data, NETFLAG_CTL | (sv_message.cursize & NETFLAG_LENGTH_MASK));
3439                                         NetConn_Write(mysocket, sv_message.data, sv_message.cursize, peeraddress);
3440                                         SZ_Clear(&sv_message);
3441                                         // now set up the client struct
3442                                         SV_ConnectClient(clientnum, conn);
3443                                         NetConn_Heartbeat(1);
3444                                         return true;
3445                                 }
3446                         }
3447
3448                         if (developer_extra.integer)
3449                                 Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
3450                         // no room; try to let player know
3451                         SZ_Clear(&sv_message);
3452                         // save space for the header, filled in later
3453                         MSG_WriteLong(&sv_message, 0);
3454                         MSG_WriteByte(&sv_message, CCREP_REJECT);
3455                         MSG_WriteString(&sv_message, "Server is full.\n");
3456                         StoreBigLong(sv_message.data, NETFLAG_CTL | (sv_message.cursize & NETFLAG_LENGTH_MASK));
3457                         NetConn_Write(mysocket, sv_message.data, sv_message.cursize, peeraddress);
3458                         SZ_Clear(&sv_message);
3459                         break;
3460                 case CCREQ_SERVER_INFO:
3461                         if (developer_extra.integer)
3462                                 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
3463                         if(!(islocal || sv_public.integer > -1))
3464                                 break;
3465
3466                         if (NetConn_PreventFlood(peeraddress, sv.getstatusfloodaddresses, sizeof(sv.getstatusfloodaddresses) / sizeof(sv.getstatusfloodaddresses[0]), net_getstatusfloodblockingtimeout.value, false))
3467                                 break;
3468
3469                         if (sv.active && !strcmp(MSG_ReadString(&sv_message, sv_readstring, sizeof(sv_readstring)), "QUAKE"))
3470                         {
3471                                 int numclients;
3472                                 char myaddressstring[128];
3473                                 if (developer_extra.integer)
3474                                         Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
3475                                 SZ_Clear(&sv_message);
3476                                 // save space for the header, filled in later
3477                                 MSG_WriteLong(&sv_message, 0);
3478                                 MSG_WriteByte(&sv_message, CCREP_SERVER_INFO);
3479                                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), myaddressstring, sizeof(myaddressstring), true);
3480                                 MSG_WriteString(&sv_message, myaddressstring);
3481                                 MSG_WriteString(&sv_message, hostname.string);
3482                                 MSG_WriteString(&sv_message, sv.name);
3483                                 // How many clients are there?
3484                                 for (i = 0, numclients = 0;i < svs.maxclients;i++)
3485                                         if (svs.clients[i].active)
3486                                                 numclients++;
3487                                 MSG_WriteByte(&sv_message, numclients);
3488                                 MSG_WriteByte(&sv_message, svs.maxclients);
3489                                 MSG_WriteByte(&sv_message, NET_PROTOCOL_VERSION);
3490                                 StoreBigLong(sv_message.data, NETFLAG_CTL | (sv_message.cursize & NETFLAG_LENGTH_MASK));
3491                                 NetConn_Write(mysocket, sv_message.data, sv_message.cursize, peeraddress);
3492                                 SZ_Clear(&sv_message);
3493                         }
3494                         break;
3495                 case CCREQ_PLAYER_INFO:
3496                         if (developer_extra.integer)
3497                                 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
3498                         if(!(islocal || sv_public.integer > -1))
3499                                 break;
3500
3501                         if (NetConn_PreventFlood(peeraddress, sv.getstatusfloodaddresses, sizeof(sv.getstatusfloodaddresses) / sizeof(sv.getstatusfloodaddresses[0]), net_getstatusfloodblockingtimeout.value, false))
3502                                 break;
3503
3504                         if (sv.active)
3505                         {
3506                                 int playerNumber, activeNumber, clientNumber;
3507                                 client_t *client;
3508
3509                                 playerNumber = MSG_ReadByte(&sv_message);
3510                                 activeNumber = -1;
3511                                 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
3512                                         if (client->active && ++activeNumber == playerNumber)
3513                                                 break;
3514                                 if (clientNumber != svs.maxclients)
3515                                 {
3516                                         SZ_Clear(&sv_message);
3517                                         // save space for the header, filled in later
3518                                         MSG_WriteLong(&sv_message, 0);
3519                                         MSG_WriteByte(&sv_message, CCREP_PLAYER_INFO);
3520                                         MSG_WriteByte(&sv_message, playerNumber);
3521                                         MSG_WriteString(&sv_message, client->name);
3522                                         MSG_WriteLong(&sv_message, client->colors);
3523                                         MSG_WriteLong(&sv_message, client->frags);
3524                                         MSG_WriteLong(&sv_message, (int)(host.realtime - client->connecttime));
3525                                         if(sv_status_privacy.integer)
3526                                                 MSG_WriteString(&sv_message, client->netconnection ? "hidden" : "botclient");
3527                                         else
3528                                                 MSG_WriteString(&sv_message, client->netconnection ? client->netconnection->address : "botclient");
3529                                         StoreBigLong(sv_message.data, NETFLAG_CTL | (sv_message.cursize & NETFLAG_LENGTH_MASK));
3530                                         NetConn_Write(mysocket, sv_message.data, sv_message.cursize, peeraddress);
3531                                         SZ_Clear(&sv_message);
3532                                 }
3533                         }
3534                         break;
3535                 case CCREQ_RULE_INFO:
3536                         if (developer_extra.integer)
3537                                 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
3538                         if(!(islocal || sv_public.integer > -1))
3539                                 break;
3540
3541                         // no flood check here, as it only returns one cvar for one cvar and clients may iterate quickly
3542
3543                         if (sv.active)
3544                         {
3545                                 char *prevCvarName;
3546                                 cvar_t *var;
3547
3548                                 // find the search start location
3549                                 prevCvarName = MSG_ReadString(&sv_message, sv_readstring, sizeof(sv_readstring));
3550                                 var = Cvar_FindVarAfter(&cvars_all, prevCvarName, CF_NOTIFY);
3551
3552                                 // send the response
3553                                 SZ_Clear(&sv_message);
3554                                 // save space for the header, filled in later
3555                                 MSG_WriteLong(&sv_message, 0);
3556                                 MSG_WriteByte(&sv_message, CCREP_RULE_INFO);
3557                                 if (var)
3558                                 {
3559                                         MSG_WriteString(&sv_message, var->name);
3560                                         MSG_WriteString(&sv_message, var->string);
3561                                 }
3562                                 StoreBigLong(sv_message.data, NETFLAG_CTL | (sv_message.cursize & NETFLAG_LENGTH_MASK));
3563                                 NetConn_Write(mysocket, sv_message.data, sv_message.cursize, peeraddress);
3564                                 SZ_Clear(&sv_message);
3565                         }
3566                         break;
3567                 case CCREQ_RCON:
3568                         if (developer_extra.integer)
3569                                 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_RCON from %s.\n", addressstring2);
3570                         if (sv.active && !rcon_secure.integer)
3571                         {
3572                                 char password[2048];
3573                                 char cmd[2048];
3574                                 char *s;
3575                                 char *endpos;
3576                                 const char *userlevel;
3577                                 strlcpy(password, MSG_ReadString(&sv_message, sv_readstring, sizeof(sv_readstring)), sizeof(password));
3578                                 strlcpy(cmd, MSG_ReadString(&sv_message, sv_readstring, sizeof(sv_readstring)), sizeof(cmd));
3579                                 s = cmd;
3580                                 endpos = cmd + strlen(cmd) + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
3581                                 userlevel = RCon_Authenticate(peeraddress, password, s, endpos, plaintext_matching, NULL, 0);
3582                                 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos, true);
3583                                 return true;
3584                         }
3585                         break;
3586                 default:
3587                         break;
3588                 }
3589                 SZ_Clear(&sv_message);
3590                 // we may not have liked the packet, but it was a valid control
3591                 // packet, so we're done processing this packet now
3592                 return true;
3593         }
3594         if (host_client)
3595         {
3596                 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length, sv.protocol, host_client->begun ? net_messagetimeout.value : net_connecttimeout.value)) == 2)
3597                 {
3598                         SV_ReadClientMessage();
3599                         return ret;
3600                 }
3601         }
3602         return 0;
3603 }
3604
3605 void NetConn_ServerFrame(void)
3606 {
3607         int i, length;
3608         lhnetaddress_t peeraddress;
3609         unsigned char readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
3610         for (i = 0;i < sv_numsockets;i++)
3611                 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
3612                         NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
3613 }
3614
3615 void NetConn_SleepMicroseconds(int microseconds)
3616 {
3617         LHNET_SleepUntilPacket_Microseconds(microseconds);
3618 }
3619
3620 #ifdef CONFIG_MENU
3621 void NetConn_QueryMasters(qbool querydp, qbool queryqw)
3622 {
3623         int i, j;
3624         int masternum;
3625         lhnetaddress_t masteraddress;
3626         lhnetaddress_t broadcastaddress;
3627         char request[256];
3628
3629         if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
3630                 return;
3631
3632         // 26000 is the default quake server port, servers on other ports will not
3633         // be found
3634         // note this is IPv4-only, I doubt there are IPv6-only LANs out there
3635         LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
3636
3637         if (querydp)
3638         {
3639                 for (i = 0;i < cl_numsockets;i++)
3640                 {
3641                         if (cl_sockets[i])
3642                         {
3643                                 const char *cmdname, *extraoptions;
3644                                 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
3645
3646                                 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
3647                                 {
3648                                         // search LAN for Quake servers
3649                                         SZ_Clear(&cl_message);
3650                                         // save space for the header, filled in later
3651                                         MSG_WriteLong(&cl_message, 0);
3652                                         MSG_WriteByte(&cl_message, CCREQ_SERVER_INFO);
3653                                         MSG_WriteString(&cl_message, "QUAKE");
3654                                         MSG_WriteByte(&cl_message, NET_PROTOCOL_VERSION);
3655                                         StoreBigLong(cl_message.data, NETFLAG_CTL | (cl_message.cursize & NETFLAG_LENGTH_MASK));
3656                                         NetConn_Write(cl_sockets[i], cl_message.data, cl_message.cursize, &broadcastaddress);
3657                                         SZ_Clear(&cl_message);
3658
3659                                         // search LAN for DarkPlaces servers
3660                                         NetConn_WriteString(cl_sockets[i], "\377\377\377\377getstatus", &broadcastaddress);
3661                                 }
3662
3663                                 // build the getservers message to send to the dpmaster master servers
3664                                 if (LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == LHNETADDRESSTYPE_INET6)
3665                                 {
3666                                         cmdname = "getserversExt";
3667                                         extraoptions = " ipv4 ipv6";  // ask for IPv4 and IPv6 servers
3668                                 }
3669                                 else
3670                                 {
3671                                         cmdname = "getservers";
3672                                         extraoptions = "";
3673                                 }
3674                                 memcpy(request, "\377\377\377\377", 4);
3675                                 dpsnprintf(request+4, sizeof(request)-4, "%s %s %u empty full%s", cmdname, gamenetworkfiltername, NET_PROTOCOL_VERSION, extraoptions);
3676
3677                                 // search internet
3678                                 for (masternum = 0;sv_masters[masternum].name;masternum++)
3679                                 {
3680                                         if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == af)
3681                                         {
3682                                                 masterquerycount++;
3683                                                 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
3684                                         }
3685                                 }
3686
3687                                 // search favorite servers
3688                                 for(j = 0; j < nFavorites; ++j)
3689                                 {
3690                                         if(LHNETADDRESS_GetAddressType(&favorites[j]) == af)
3691                                         {
3692                                                 if(LHNETADDRESS_ToString(&favorites[j], request, sizeof(request), true))
3693                                                         NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, request, true );
3694                                         }
3695                                 }
3696                         }
3697                 }
3698         }
3699
3700         // only query QuakeWorld servers when the user wants to
3701         if (queryqw)
3702         {
3703                 for (i = 0;i < cl_numsockets;i++)
3704                 {
3705                         if (cl_sockets[i])
3706                         {
3707                                 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
3708
3709                                 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
3710                                 {
3711                                         // search LAN for QuakeWorld servers
3712                                         NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &broadcastaddress);
3713
3714                                         // build the getservers message to send to the qwmaster master servers
3715                                         // note this has no -1 prefix, and the trailing nul byte is sent
3716                                         dpsnprintf(request, sizeof(request), "c\n");
3717                                 }
3718
3719                                 // search internet
3720                                 for (masternum = 0;sv_qwmasters[masternum].name;masternum++)
3721                                 {
3722                                         if (sv_qwmasters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_qwmasters[masternum].string, QWMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
3723                                         {
3724                                                 if (m_state != m_slist)
3725                                                 {
3726                                                         char lookupstring[128];
3727                                                         LHNETADDRESS_ToString(&masteraddress, lookupstring, sizeof(lookupstring), true);
3728                                                         Con_Printf("Querying master %s (resolved from %s)\n", lookupstring, sv_qwmasters[masternum].string);
3729                                                 }
3730                                                 masterquerycount++;
3731                                                 NetConn_Write(cl_sockets[i], request, (int)strlen(request) + 1, &masteraddress);
3732                                         }
3733                                 }
3734
3735                                 // search favorite servers
3736                                 for(j = 0; j < nFavorites; ++j)
3737                                 {
3738                                         if(LHNETADDRESS_GetAddressType(&favorites[j]) == af)
3739                                         {
3740                                                 if(LHNETADDRESS_ToString(&favorites[j], request, sizeof(request), true))
3741                                                 {
3742                                                         NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &favorites[j]);
3743                                                         NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, request, true );
3744                                                 }
3745                                         }
3746                                 }
3747                         }
3748                 }
3749         }
3750         if (!masterquerycount)
3751         {
3752                 Con_Print(CON_ERROR "Unable to query master servers, no suitable network sockets active.\n");
3753                 M_Update_Return_Reason("No network");
3754         }
3755 }
3756 #endif
3757
3758 void NetConn_Heartbeat(int priority)
3759 {
3760         lhnetaddress_t masteraddress;
3761         int masternum;
3762         lhnetsocket_t *mysocket;
3763
3764         // if it's a state change (client connected), limit next heartbeat to no
3765         // more than 30 sec in the future
3766         if (priority == 1 && nextheartbeattime > host.realtime + 30.0)
3767                 nextheartbeattime = host.realtime + 30.0;
3768
3769         // limit heartbeatperiod to 30 to 270 second range,
3770         // lower limit is to avoid abusing master servers with excess traffic,
3771         // upper limit is to avoid timing out on the master server (which uses
3772         // 300 sec timeout)
3773         if (sv_heartbeatperiod.value < 30)
3774                 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
3775         if (sv_heartbeatperiod.value > 270)
3776                 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
3777
3778         // make advertising optional and don't advertise singleplayer games, and
3779         // only send a heartbeat as often as the admin wants
3780         if (sv.active && sv_public.integer > 0 && svs.maxclients >= 2 && (priority > 1 || host.realtime > nextheartbeattime))
3781         {
3782                 nextheartbeattime = host.realtime + sv_heartbeatperiod.value;
3783                 for (masternum = 0;sv_masters[masternum].name;masternum++)
3784                         if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
3785                                 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
3786         }
3787 }
3788
3789 static void Net_Heartbeat_f(cmd_state_t *cmd)
3790 {
3791         if (sv.active)
3792                 NetConn_Heartbeat(2);
3793         else
3794                 Con_Print("No server running, can not heartbeat to master server.\n");
3795 }
3796
3797 static void PrintStats(netconn_t *conn)
3798 {
3799         if ((cls.state == ca_connected && cls.protocol == PROTOCOL_QUAKEWORLD) || (sv.active && sv.protocol == PROTOCOL_QUAKEWORLD))
3800                 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->outgoing_unreliable_sequence, conn->qw.incoming_sequence);
3801         else
3802                 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->nq.sendSequence, conn->nq.receiveSequence);
3803         Con_Printf("unreliable messages sent   = %i\n", conn->unreliableMessagesSent);
3804         Con_Printf("unreliable messages recv   = %i\n", conn->unreliableMessagesReceived);
3805         Con_Printf("reliable messages sent     = %i\n", conn->reliableMessagesSent);
3806         Con_Printf("reliable messages received = %i\n", conn->reliableMessagesReceived);
3807         Con_Printf("packetsSent                = %i\n", conn->packetsSent);
3808         Con_Printf("packetsReSent              = %i\n", conn->packetsReSent);
3809         Con_Printf("packetsReceived            = %i\n", conn->packetsReceived);
3810         Con_Printf("receivedDuplicateCount     = %i\n", conn->receivedDuplicateCount);
3811         Con_Printf("droppedDatagrams           = %i\n", conn->droppedDatagrams);
3812 }
3813
3814 void Net_Stats_f(cmd_state_t *cmd)
3815 {
3816         netconn_t *conn;
3817         Con_Print("connections                =\n");
3818         for (conn = netconn_list;conn;conn = conn->next)
3819                 PrintStats(conn);
3820 }
3821
3822 #ifdef CONFIG_MENU
3823 void Net_Refresh_f(cmd_state_t *cmd)
3824 {
3825         if (m_state != m_slist) {
3826                 Con_Print("Sending new requests to master servers\n");
3827                 ServerList_QueryList(false, true, false, true);
3828                 Con_Print("Listening for replies...\n");
3829         } else
3830                 ServerList_QueryList(false, true, false, false);
3831 }
3832
3833 void Net_Slist_f(cmd_state_t *cmd)
3834 {
3835         ServerList_ResetMasks();
3836         serverlist_sortbyfield = SLIF_PING;
3837         serverlist_sortflags = 0;
3838     if (m_state != m_slist) {
3839                 Con_Print("Sending requests to master servers\n");
3840                 ServerList_QueryList(true, true, false, true);
3841                 Con_Print("Listening for replies...\n");
3842         } else
3843                 ServerList_QueryList(true, true, false, false);
3844 }
3845
3846 void Net_SlistQW_f(cmd_state_t *cmd)
3847 {
3848         ServerList_ResetMasks();
3849         serverlist_sortbyfield = SLIF_PING;
3850         serverlist_sortflags = 0;
3851     if (m_state != m_slist) {
3852                 Con_Print("Sending requests to master servers\n");
3853                 ServerList_QueryList(true, false, true, true);
3854                 serverlist_consoleoutput = true;
3855                 Con_Print("Listening for replies...\n");
3856         } else
3857                 ServerList_QueryList(true, false, true, false);
3858 }
3859 #endif
3860
3861 void NetConn_Init(void)
3862 {
3863         int i;
3864         lhnetaddress_t tempaddress;
3865         netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
3866         Cmd_AddCommand(CF_SHARED, "net_stats", Net_Stats_f, "print network statistics");
3867 #ifdef CONFIG_MENU
3868         Cmd_AddCommand(CF_CLIENT, "net_slist", Net_Slist_f, "query dp master servers and print all server information");
3869         Cmd_AddCommand(CF_CLIENT, "net_slistqw", Net_SlistQW_f, "query qw master servers and print all server information");
3870         Cmd_AddCommand(CF_CLIENT, "net_refresh", Net_Refresh_f, "query dp master servers and refresh all server information");
3871 #endif
3872         Cmd_AddCommand(CF_SERVER, "heartbeat", Net_Heartbeat_f, "send a heartbeat to the master server (updates your server information)");
3873         Cvar_RegisterVariable(&net_test);
3874         Cvar_RegisterVariable(&net_usesizelimit);
3875         Cvar_RegisterVariable(&net_burstreserve);
3876         Cvar_RegisterVariable(&rcon_restricted_password);
3877         Cvar_RegisterVariable(&rcon_restricted_commands);
3878         Cvar_RegisterVariable(&rcon_secure_maxdiff);
3879         Cvar_RegisterVariable(&net_slist_queriespersecond);
3880         Cvar_RegisterVariable(&net_slist_queriesperframe);
3881         Cvar_RegisterVariable(&net_slist_timeout);
3882         Cvar_RegisterVariable(&net_slist_maxtries);
3883         Cvar_RegisterVariable(&net_slist_favorites);
3884 #ifdef CONFIG_MENU
3885         Cvar_RegisterCallback(&net_slist_favorites, NetConn_UpdateFavorites_c);
3886 #endif
3887         Cvar_RegisterVariable(&net_slist_pause);
3888         if(LHNET_DefaultDSCP(-1) >= 0) // register cvar only if supported
3889                 Cvar_RegisterVariable(&net_tos_dscp);
3890         Cvar_RegisterVariable(&net_messagetimeout);
3891         Cvar_RegisterVariable(&net_connecttimeout);
3892         Cvar_RegisterVariable(&net_connectfloodblockingtimeout);
3893         Cvar_RegisterVariable(&net_challengefloodblockingtimeout);
3894         Cvar_RegisterVariable(&net_getstatusfloodblockingtimeout);
3895         Cvar_RegisterVariable(&net_sourceaddresscheck);
3896         Cvar_RegisterVariable(&net_fakelag);
3897         Cvar_RegisterVariable(&net_fakeloss_send);
3898         Cvar_RegisterVariable(&net_fakeloss_receive);
3899         Cvar_RegisterAlias(&net_fakelag, "cl_netlocalping");
3900         Cvar_RegisterAlias(&net_fakeloss_send, "cl_netpacketloss_send");
3901         Cvar_RegisterAlias(&net_fakeloss_receive, "cl_netpacketloss_receive");
3902         Cvar_RegisterVariable(&hostname);
3903         Cvar_RegisterVariable(&developer_networking);
3904         Cvar_RegisterVariable(&cl_netport);
3905         Cvar_RegisterVariable(&sv_netport);
3906         Cvar_RegisterVariable(&net_address);
3907         Cvar_RegisterVariable(&net_address_ipv6);
3908         Cvar_RegisterVariable(&sv_public);
3909         Cvar_RegisterVariable(&sv_public_rejectreason);
3910         Cvar_RegisterVariable(&sv_heartbeatperiod);
3911         for (i = 0;sv_masters[i].name;i++)
3912                 Cvar_RegisterVariable(&sv_masters[i]);
3913         Cvar_RegisterVariable(&gameversion);
3914         Cvar_RegisterVariable(&gameversion_min);
3915         Cvar_RegisterVariable(&gameversion_max);
3916 // 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.
3917         if ((i = Sys_CheckParm("-ip")) && i + 1 < sys.argc)
3918         {
3919                 if (LHNETADDRESS_FromString(&tempaddress, sys.argv[i + 1], 0) == 1)
3920                 {
3921                         Con_Printf("-ip option used, setting net_address to \"%s\"\n", sys.argv[i + 1]);
3922                         Cvar_SetQuick(&net_address, sys.argv[i + 1]);
3923                 }
3924                 else
3925                         Con_Printf(CON_ERROR "-ip option used, but unable to parse the address \"%s\"\n", sys.argv[i + 1]);
3926         }
3927 // 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
3928         if (((i = Sys_CheckParm("-port")) || (i = Sys_CheckParm("-ipport")) || (i = Sys_CheckParm("-udpport"))) && i + 1 < sys.argc)
3929         {
3930                 i = atoi(sys.argv[i + 1]);
3931                 if (i >= 0 && i < 65536)
3932                 {
3933                         Con_Printf("-port option used, setting port cvar to %i\n", i);
3934                         Cvar_SetValueQuick(&sv_netport, i);
3935                 }
3936                 else
3937                         Con_Printf(CON_ERROR "-port option used, but %i is not a valid port number\n", i);
3938         }
3939         cl_numsockets = 0;
3940         sv_numsockets = 0;
3941         cl_message.data = cl_message_buf;
3942         cl_message.maxsize = sizeof(cl_message_buf);
3943         cl_message.cursize = 0;
3944         sv_message.data = sv_message_buf;
3945         sv_message.maxsize = sizeof(sv_message_buf);
3946         sv_message.cursize = 0;
3947         LHNET_Init();
3948         if (Thread_HasThreads())
3949                 netconn_mutex = Thread_CreateMutex();
3950 }
3951
3952 void NetConn_Shutdown(void)
3953 {
3954         NetConn_CloseClientPorts();
3955         NetConn_CloseServerPorts();
3956         LHNET_Shutdown();
3957         if (netconn_mutex)
3958                 Thread_DestroyMutex(netconn_mutex);
3959         netconn_mutex = NULL;
3960 }
3961