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