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