Attempt to stabilize ODE. Now using constant step (sys_ticrate set steptime) - on...
[divverent/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 "lhnet.h"
25
26 // for secure rcon authentication
27 #include "hmac.h"
28 #include "mdfour.h"
29 #include <time.h>
30
31 #define QWMASTER_PORT 27000
32 #define DPMASTER_PORT 27950
33
34 // note this defaults on for dedicated servers, off for listen servers
35 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"};
36 cvar_t sv_public_rejectreason = {0, "sv_public_rejectreason", "The server is closing.", "Rejection reason for connects when sv_public is -2"};
37 static cvar_t sv_heartbeatperiod = {CVAR_SAVE, "sv_heartbeatperiod", "120", "how often to send heartbeat in seconds (only used if sv_public is 1)"};
38
39 static cvar_t sv_masters [] =
40 {
41         {CVAR_SAVE, "sv_master1", "", "user-chosen master server 1"},
42         {CVAR_SAVE, "sv_master2", "", "user-chosen master server 2"},
43         {CVAR_SAVE, "sv_master3", "", "user-chosen master server 3"},
44         {CVAR_SAVE, "sv_master4", "", "user-chosen master server 4"},
45         {0, "sv_masterextra1", "69.59.212.88", "ghdigital.com - default master server 1 (admin: LordHavoc)"}, // admin: LordHavoc
46         {0, "sv_masterextra2", "64.22.107.125", "dpmaster.deathmask.net - default master server 2 (admin: Willis)"}, // admin: Willis
47         {0, "sv_masterextra3", "92.62.40.73", "dpmaster.tchr.no - default master server 3 (admin: tChr)"}, // admin: tChr
48 #ifdef SUPPORTIPV6
49         {0, "sv_masterextra4", "[2001:41d0:2:1628::4450]:27950", "dpmaster.div0.qc.to - default master server 4 (admin: divVerent)"}, // admin: divVerent
50 #endif
51         {0, NULL, NULL, NULL}
52 };
53
54 static cvar_t sv_qwmasters [] =
55 {
56         {CVAR_SAVE, "sv_qwmaster1", "", "user-chosen qwmaster server 1"},
57         {CVAR_SAVE, "sv_qwmaster2", "", "user-chosen qwmaster server 2"},
58         {CVAR_SAVE, "sv_qwmaster3", "", "user-chosen qwmaster server 3"},
59         {CVAR_SAVE, "sv_qwmaster4", "", "user-chosen qwmaster server 4"},
60         {0, "sv_qwmasterextra1", "master.quakeservers.net:27000", "Global master server. (admin: unknown)"},
61         {0, "sv_qwmasterextra2", "asgaard.morphos-team.net:27000", "Global master server. (admin: unknown)"},
62         {0, "sv_qwmasterextra3", "qwmaster.ocrana.de:27000", "German master server. (admin: unknown)"},
63         {0, "sv_qwmasterextra4", "masterserver.exhale.de:27000", "German master server. (admin: unknown)"},
64         {0, "sv_qwmasterextra5", "kubus.rulez.pl:27000", "Poland master server. (admin: unknown)"},
65         {0, NULL, NULL, NULL}
66 };
67
68 static double nextheartbeattime = 0;
69
70 sizebuf_t net_message;
71 static unsigned char net_message_buf[NET_MAXMESSAGE];
72
73 cvar_t net_messagetimeout = {0, "net_messagetimeout","300", "drops players who have not sent any packets for this many seconds"};
74 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."};
75 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)"};
76 cvar_t hostname = {CVAR_SAVE, "hostname", "UNNAMED", "server message to show in server browser"};
77 cvar_t developer_networking = {0, "developer_networking", "0", "prints all received and sent packets (recommended only for debugging)"};
78
79 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)"};
80 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)"};
81 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)"};
82 static cvar_t net_slist_queriespersecond = {0, "net_slist_queriespersecond", "20", "how many server information requests to send per second"};
83 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)"};
84 static cvar_t net_slist_timeout = {0, "net_slist_timeout", "4", "how long to listen for a server information response before giving up"};
85 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"};
86 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)"};
87 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"};
88 static cvar_t gameversion = {0, "gameversion", "0", "version of game data (mod-specific) to be sent to querying clients"};
89 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"};
90 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"};
91 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"};
92 static cvar_t rcon_restricted_commands = {0, "rcon_restricted_commands", "", "allowed commands for rcon when the restricted mode password was used"};
93 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)"};
94 extern cvar_t rcon_secure;
95 extern cvar_t rcon_secure_challengetimeout;
96
97 /* statistic counters */
98 static int packetsSent = 0;
99 static int packetsReSent = 0;
100 static int packetsReceived = 0;
101 static int receivedDuplicateCount = 0;
102 static int droppedDatagrams = 0;
103
104 static int unreliableMessagesSent = 0;
105 static int unreliableMessagesReceived = 0;
106 static int reliableMessagesSent = 0;
107 static int reliableMessagesReceived = 0;
108
109 double masterquerytime = -1000;
110 int masterquerycount = 0;
111 int masterreplycount = 0;
112 int serverquerycount = 0;
113 int serverreplycount = 0;
114
115 challenge_t challenge[MAX_CHALLENGES];
116
117 /// this is only false if there are still servers left to query
118 static qboolean serverlist_querysleep = true;
119 static qboolean serverlist_paused = false;
120 /// this is pushed a second or two ahead of realtime whenever a master server
121 /// reply is received, to avoid issuing queries while master replies are still
122 /// flooding in (which would make a mess of the ping times)
123 static double serverlist_querywaittime = 0;
124
125 static unsigned char sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
126 static unsigned char readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
127 static unsigned char cryptosendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE+CRYPTO_HEADERSIZE];
128 static unsigned char cryptoreadbuffer[NET_HEADERSIZE+NET_MAXMESSAGE+CRYPTO_HEADERSIZE];
129
130 static int cl_numsockets;
131 static lhnetsocket_t *cl_sockets[16];
132 static int sv_numsockets;
133 static lhnetsocket_t *sv_sockets[16];
134
135 netconn_t *netconn_list = NULL;
136 mempool_t *netconn_mempool = NULL;
137
138 cvar_t cl_netport = {0, "cl_port", "0", "forces client to use chosen port number if not 0"};
139 cvar_t sv_netport = {0, "port", "26000", "server port for players to connect to"};
140 cvar_t net_address = {0, "net_address", "", "network address to open ipv4 ports on (if empty, use default interfaces)"};
141 cvar_t net_address_ipv6 = {0, "net_address_ipv6", "", "network address to open ipv6 ports on (if empty, use default interfaces)"};
142
143 char cl_net_extresponse[NET_EXTRESPONSE_MAX][1400];
144 int cl_net_extresponse_count = 0;
145 int cl_net_extresponse_last = 0;
146
147 char sv_net_extresponse[NET_EXTRESPONSE_MAX][1400];
148 int sv_net_extresponse_count = 0;
149 int sv_net_extresponse_last = 0;
150
151 // ServerList interface
152 serverlist_mask_t serverlist_andmasks[SERVERLIST_ANDMASKCOUNT];
153 serverlist_mask_t serverlist_ormasks[SERVERLIST_ORMASKCOUNT];
154
155 serverlist_infofield_t serverlist_sortbyfield;
156 int serverlist_sortflags;
157
158 int serverlist_viewcount = 0;
159 unsigned short serverlist_viewlist[SERVERLIST_VIEWLISTSIZE];
160
161 int serverlist_maxcachecount = 0;
162 int serverlist_cachecount = 0;
163 serverlist_entry_t *serverlist_cache = NULL;
164
165 qboolean serverlist_consoleoutput;
166
167 static int nFavorites = 0;
168 static lhnetaddress_t favorites[MAX_FAVORITESERVERS];
169 static int nFavorites_idfp = 0;
170 static char favorites_idfp[MAX_FAVORITESERVERS][FP64_SIZE+1];
171
172 void NetConn_UpdateFavorites(void)
173 {
174         const char *p;
175         nFavorites = 0;
176         nFavorites_idfp = 0;
177         p = net_slist_favorites.string;
178         while((size_t) nFavorites < sizeof(favorites) / sizeof(*favorites) && COM_ParseToken_Console(&p))
179         {
180                 if(com_token[0] != '[' && strlen(com_token) == FP64_SIZE && !strchr(com_token, '.'))
181                 // currently 44 bytes, longest possible IPv6 address: 39 bytes, so this works
182                 // (if v6 address contains port, it must start with '[')
183                 {
184                         strlcpy(favorites_idfp[nFavorites_idfp], com_token, sizeof(favorites_idfp[nFavorites_idfp]));
185                         ++nFavorites_idfp;
186                 }
187                 else 
188                 {
189                         if(LHNETADDRESS_FromString(&favorites[nFavorites], com_token, 26000))
190                                 ++nFavorites;
191                 }
192         }
193 }
194
195 /// helper function to insert a value into the viewset
196 /// spare entries will be removed
197 static void _ServerList_ViewList_Helper_InsertBefore( int index, serverlist_entry_t *entry )
198 {
199     int i;
200         if( serverlist_viewcount < SERVERLIST_VIEWLISTSIZE ) {
201                 i = serverlist_viewcount++;
202         } else {
203                 i = SERVERLIST_VIEWLISTSIZE - 1;
204         }
205
206         for( ; i > index ; i-- )
207                 serverlist_viewlist[ i ] = serverlist_viewlist[ i - 1 ];
208
209         serverlist_viewlist[index] = (int)(entry - serverlist_cache);
210 }
211
212 /// we suppose serverlist_viewcount to be valid, ie > 0
213 static void _ServerList_ViewList_Helper_Remove( int index )
214 {
215         serverlist_viewcount--;
216         for( ; index < serverlist_viewcount ; index++ )
217                 serverlist_viewlist[index] = serverlist_viewlist[index + 1];
218 }
219
220 /// \returns true if A should be inserted before B
221 static qboolean _ServerList_Entry_Compare( serverlist_entry_t *A, serverlist_entry_t *B )
222 {
223         int result = 0; // > 0 if for numbers A > B and for text if A < B
224
225         if( serverlist_sortflags & SLSF_FAVORITESFIRST )
226         {
227                 if(A->info.isfavorite != B->info.isfavorite)
228                         return A->info.isfavorite;
229         }
230
231         switch( serverlist_sortbyfield ) {
232                 case SLIF_PING:
233                         result = A->info.ping - B->info.ping;
234                         break;
235                 case SLIF_MAXPLAYERS:
236                         result = A->info.maxplayers - B->info.maxplayers;
237                         break;
238                 case SLIF_NUMPLAYERS:
239                         result = A->info.numplayers - B->info.numplayers;
240                         break;
241                 case SLIF_NUMBOTS:
242                         result = A->info.numbots - B->info.numbots;
243                         break;
244                 case SLIF_NUMHUMANS:
245                         result = A->info.numhumans - B->info.numhumans;
246                         break;
247                 case SLIF_FREESLOTS:
248                         result = A->info.freeslots - B->info.freeslots;
249                         break;
250                 case SLIF_PROTOCOL:
251                         result = A->info.protocol - B->info.protocol;
252                         break;
253                 case SLIF_CNAME:
254                         result = strcmp( B->info.cname, A->info.cname );
255                         break;
256                 case SLIF_GAME:
257                         result = strcasecmp( B->info.game, A->info.game );
258                         break;
259                 case SLIF_MAP:
260                         result = strcasecmp( B->info.map, A->info.map );
261                         break;
262                 case SLIF_MOD:
263                         result = strcasecmp( B->info.mod, A->info.mod );
264                         break;
265                 case SLIF_NAME:
266                         result = strcasecmp( B->info.name, A->info.name );
267                         break;
268                 case SLIF_QCSTATUS:
269                         result = strcasecmp( B->info.qcstatus, A->info.qcstatus ); // not really THAT useful, though
270                         break;
271                 case SLIF_ISFAVORITE:
272                         result = !!B->info.isfavorite - !!A->info.isfavorite;
273                         break;
274                 default:
275                         Con_DPrint( "_ServerList_Entry_Compare: Bad serverlist_sortbyfield!\n" );
276                         break;
277         }
278
279         if (result != 0)
280         {
281                 if( serverlist_sortflags & SLSF_DESCENDING )
282                         return result > 0;
283                 else
284                         return result < 0;
285         }
286
287         // if the chosen sort key is identical, sort by index
288         // (makes this a stable sort, so that later replies from servers won't
289         //  shuffle the servers around when they have the same ping)
290         return A < B;
291 }
292
293 static qboolean _ServerList_CompareInt( int A, serverlist_maskop_t op, int B )
294 {
295         // This should actually be done with some intermediate and end-of-function return
296         switch( op ) {
297                 case SLMO_LESS:
298                         return A < B;
299                 case SLMO_LESSEQUAL:
300                         return A <= B;
301                 case SLMO_EQUAL:
302                         return A == B;
303                 case SLMO_GREATER:
304                         return A > B;
305                 case SLMO_NOTEQUAL:
306                         return A != B;
307                 case SLMO_GREATEREQUAL:
308                 case SLMO_CONTAINS:
309                 case SLMO_NOTCONTAIN:
310                 case SLMO_STARTSWITH:
311                 case SLMO_NOTSTARTSWITH:
312                         return A >= B;
313                 default:
314                         Con_DPrint( "_ServerList_CompareInt: Bad op!\n" );
315                         return false;
316         }
317 }
318
319 static qboolean _ServerList_CompareStr( const char *A, serverlist_maskop_t op, const char *B )
320 {
321         int i;
322         char bufferA[ 1400 ], bufferB[ 1400 ]; // should be more than enough
323         COM_StringDecolorize(A, 0, bufferA, sizeof(bufferA), false);
324         for (i = 0;i < (int)sizeof(bufferA)-1 && bufferA[i];i++)
325                 bufferA[i] = (bufferA[i] >= 'A' && bufferA[i] <= 'Z') ? (bufferA[i] + 'a' - 'A') : bufferA[i];
326         bufferA[i] = 0;
327         for (i = 0;i < (int)sizeof(bufferB)-1 && B[i];i++)
328                 bufferB[i] = (B[i] >= 'A' && B[i] <= 'Z') ? (B[i] + 'a' - 'A') : B[i];
329         bufferB[i] = 0;
330
331         // Same here, also using an intermediate & final return would be more appropriate
332         // A info B mask
333         switch( op ) {
334                 case SLMO_CONTAINS:
335                         return *bufferB && !!strstr( bufferA, bufferB ); // we want a real bool
336                 case SLMO_NOTCONTAIN:
337                         return !*bufferB || !strstr( bufferA, bufferB );
338                 case SLMO_STARTSWITH:
339                         //Con_Printf("startsWith: %s %s\n", bufferA, bufferB);
340                         return *bufferB && !memcmp(bufferA, bufferB, strlen(bufferB));
341                 case SLMO_NOTSTARTSWITH:
342                         return !*bufferB || memcmp(bufferA, bufferB, strlen(bufferB));
343                 case SLMO_LESS:
344                         return strcmp( bufferA, bufferB ) < 0;
345                 case SLMO_LESSEQUAL:
346                         return strcmp( bufferA, bufferB ) <= 0;
347                 case SLMO_EQUAL:
348                         return strcmp( bufferA, bufferB ) == 0;
349                 case SLMO_GREATER:
350                         return strcmp( bufferA, bufferB ) > 0;
351                 case SLMO_NOTEQUAL:
352                         return strcmp( bufferA, bufferB ) != 0;
353                 case SLMO_GREATEREQUAL:
354                         return strcmp( bufferA, bufferB ) >= 0;
355                 default:
356                         Con_DPrint( "_ServerList_CompareStr: Bad op!\n" );
357                         return false;
358         }
359 }
360
361 static qboolean _ServerList_Entry_Mask( serverlist_mask_t *mask, serverlist_info_t *info )
362 {
363         if( !_ServerList_CompareInt( info->ping, mask->tests[SLIF_PING], mask->info.ping ) )
364                 return false;
365         if( !_ServerList_CompareInt( info->maxplayers, mask->tests[SLIF_MAXPLAYERS], mask->info.maxplayers ) )
366                 return false;
367         if( !_ServerList_CompareInt( info->numplayers, mask->tests[SLIF_NUMPLAYERS], mask->info.numplayers ) )
368                 return false;
369         if( !_ServerList_CompareInt( info->numbots, mask->tests[SLIF_NUMBOTS], mask->info.numbots ) )
370                 return false;
371         if( !_ServerList_CompareInt( info->numhumans, mask->tests[SLIF_NUMHUMANS], mask->info.numhumans ) )
372                 return false;
373         if( !_ServerList_CompareInt( info->freeslots, mask->tests[SLIF_FREESLOTS], mask->info.freeslots ) )
374                 return false;
375         if( !_ServerList_CompareInt( info->protocol, mask->tests[SLIF_PROTOCOL], mask->info.protocol ))
376                 return false;
377         if( *mask->info.cname
378                 && !_ServerList_CompareStr( info->cname, mask->tests[SLIF_CNAME], mask->info.cname ) )
379                 return false;
380         if( *mask->info.game
381                 && !_ServerList_CompareStr( info->game, mask->tests[SLIF_GAME], mask->info.game ) )
382                 return false;
383         if( *mask->info.mod
384                 && !_ServerList_CompareStr( info->mod, mask->tests[SLIF_MOD], mask->info.mod ) )
385                 return false;
386         if( *mask->info.map
387                 && !_ServerList_CompareStr( info->map, mask->tests[SLIF_MAP], mask->info.map ) )
388                 return false;
389         if( *mask->info.name
390                 && !_ServerList_CompareStr( info->name, mask->tests[SLIF_NAME], mask->info.name ) )
391                 return false;
392         if( *mask->info.qcstatus
393                 && !_ServerList_CompareStr( info->qcstatus, mask->tests[SLIF_QCSTATUS], mask->info.qcstatus ) )
394                 return false;
395         if( *mask->info.players
396                 && !_ServerList_CompareStr( info->players, mask->tests[SLIF_PLAYERS], mask->info.players ) )
397                 return false;
398         if( !_ServerList_CompareInt( info->isfavorite, mask->tests[SLIF_ISFAVORITE], mask->info.isfavorite ))
399                 return false;
400         return true;
401 }
402
403 static void ServerList_ViewList_Insert( serverlist_entry_t *entry )
404 {
405         int start, end, mid, i;
406         lhnetaddress_t addr;
407
408         // reject incompatible servers
409         if(
410                 entry->info.gameversion != gameversion.integer
411                 &&
412                 !(
413                            gameversion_min.integer >= 0 // min/max range set by user/mod?
414                         && gameversion_max.integer >= 0
415                         && gameversion_min.integer >= entry->info.gameversion // version of server in min/max range?
416                         && gameversion_max.integer <= entry->info.gameversion
417                  )
418         )
419                 return;
420
421         // refresh the "favorite" status
422         entry->info.isfavorite = false;
423         if(LHNETADDRESS_FromString(&addr, entry->info.cname, 26000))
424         {
425                 char idfp[FP64_SIZE+1];
426                 for(i = 0; i < nFavorites; ++i)
427                 {
428                         if(LHNETADDRESS_Compare(&addr, &favorites[i]) == 0)
429                         {
430                                 entry->info.isfavorite = true;
431                                 break;
432                         }
433                 }
434                 if(Crypto_RetrieveHostKey(&addr, 0, NULL, 0, idfp, sizeof(idfp), NULL))
435                 {
436                         for(i = 0; i < nFavorites_idfp; ++i)
437                         {
438                                 if(!strcmp(idfp, favorites_idfp[i]))
439                                 {
440                                         entry->info.isfavorite = true;
441                                         break;
442                                 }
443                         }
444                 }
445         }
446
447         // FIXME: change this to be more readable (...)
448         // now check whether it passes through the masks
449         for( start = 0 ; start < SERVERLIST_ANDMASKCOUNT && serverlist_andmasks[start].active; start++ )
450                 if( !_ServerList_Entry_Mask( &serverlist_andmasks[start], &entry->info ) )
451                         return;
452
453         for( start = 0 ; start < SERVERLIST_ORMASKCOUNT && serverlist_ormasks[start].active ; start++ )
454                 if( _ServerList_Entry_Mask( &serverlist_ormasks[start], &entry->info ) )
455                         break;
456         if( start == SERVERLIST_ORMASKCOUNT || (start > 0 && !serverlist_ormasks[start].active) )
457                 return;
458
459         if( !serverlist_viewcount ) {
460                 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
461                 return;
462         }
463         // ok, insert it, we just need to find out where exactly:
464
465         // two special cases
466         // check whether to insert it as new first item
467         if( _ServerList_Entry_Compare( entry, ServerList_GetViewEntry(0) ) ) {
468                 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
469                 return;
470         } // check whether to insert it as new last item
471         else if( !_ServerList_Entry_Compare( entry, ServerList_GetViewEntry(serverlist_viewcount - 1) ) ) {
472                 _ServerList_ViewList_Helper_InsertBefore( serverlist_viewcount, entry );
473                 return;
474         }
475         start = 0;
476         end = serverlist_viewcount - 1;
477         while( end > start + 1 )
478         {
479                 mid = (start + end) / 2;
480                 // test the item that lies in the middle between start and end
481                 if( _ServerList_Entry_Compare( entry, ServerList_GetViewEntry(mid) ) )
482                         // the item has to be in the upper half
483                         end = mid;
484                 else
485                         // the item has to be in the lower half
486                         start = mid;
487         }
488         _ServerList_ViewList_Helper_InsertBefore( start + 1, entry );
489 }
490
491 static void ServerList_ViewList_Remove( serverlist_entry_t *entry )
492 {
493         int i;
494         for( i = 0; i < serverlist_viewcount; i++ )
495         {
496                 if (ServerList_GetViewEntry(i) == entry)
497                 {
498                         _ServerList_ViewList_Helper_Remove(i);
499                         break;
500                 }
501         }
502 }
503
504 void ServerList_RebuildViewList(void)
505 {
506         int i;
507
508         serverlist_viewcount = 0;
509         for( i = 0 ; i < serverlist_cachecount ; i++ ) {
510                 serverlist_entry_t *entry = &serverlist_cache[i];
511                 // also display entries that are currently being refreshed [11/8/2007 Black]
512                 if( entry->query == SQS_QUERIED || entry->query == SQS_REFRESHING )
513                         ServerList_ViewList_Insert( entry );
514         }
515 }
516
517 void ServerList_ResetMasks(void)
518 {
519         int i;
520
521         memset( &serverlist_andmasks, 0, sizeof( serverlist_andmasks ) );
522         memset( &serverlist_ormasks, 0, sizeof( serverlist_ormasks ) );
523         // numbots needs to be compared to -1 to always succeed
524         for(i = 0; i < SERVERLIST_ANDMASKCOUNT; ++i)
525                 serverlist_andmasks[i].info.numbots = -1;
526         for(i = 0; i < SERVERLIST_ORMASKCOUNT; ++i)
527                 serverlist_ormasks[i].info.numbots = -1;
528 }
529
530 void ServerList_GetPlayerStatistics(int *numplayerspointer, int *maxplayerspointer)
531 {
532         int i;
533         int numplayers = 0, maxplayers = 0;
534         for (i = 0;i < serverlist_cachecount;i++)
535         {
536                 if (serverlist_cache[i].query == SQS_QUERIED)
537                 {
538                         numplayers += serverlist_cache[i].info.numhumans;
539                         maxplayers += serverlist_cache[i].info.maxplayers;
540                 }
541         }
542         *numplayerspointer = numplayers;
543         *maxplayerspointer = maxplayers;
544 }
545
546 #if 0
547 static void _ServerList_Test(void)
548 {
549         int i;
550         if (serverlist_maxcachecount <= 1024)
551         {
552                 serverlist_maxcachecount = 1024;
553                 serverlist_cache = (serverlist_entry_t *)Mem_Realloc(netconn_mempool, (void *)serverlist_cache, sizeof(serverlist_entry_t) * serverlist_maxcachecount);
554         }
555         for( i = 0 ; i < 1024 ; i++ ) {
556                 memset( &serverlist_cache[serverlist_cachecount], 0, sizeof( serverlist_entry_t ) );
557                 serverlist_cache[serverlist_cachecount].info.ping = 1000 + 1024 - i;
558                 dpsnprintf( serverlist_cache[serverlist_cachecount].info.name, sizeof(serverlist_cache[serverlist_cachecount].info.name), "Black's ServerList Test %i", i );
559                 serverlist_cache[serverlist_cachecount].finished = true;
560                 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 );
561                 ServerList_ViewList_Insert( &serverlist_cache[serverlist_cachecount] );
562                 serverlist_cachecount++;
563         }
564 }
565 #endif
566
567 void ServerList_QueryList(qboolean resetcache, qboolean querydp, qboolean queryqw, qboolean consoleoutput)
568 {
569         masterquerytime = realtime;
570         masterquerycount = 0;
571         masterreplycount = 0;
572         if( resetcache ) {
573                 serverquerycount = 0;
574                 serverreplycount = 0;
575                 serverlist_cachecount = 0;
576                 serverlist_viewcount = 0;
577                 serverlist_maxcachecount = 0;
578                 serverlist_cache = (serverlist_entry_t *)Mem_Realloc(netconn_mempool, (void *)serverlist_cache, sizeof(serverlist_entry_t) * serverlist_maxcachecount);
579         } else {
580                 // refresh all entries
581                 int n;
582                 for( n = 0 ; n < serverlist_cachecount ; n++ ) {
583                         serverlist_entry_t *entry = &serverlist_cache[ n ];
584                         entry->query = SQS_REFRESHING;
585                         entry->querycounter = 0;
586                 }
587         }
588         serverlist_consoleoutput = consoleoutput;
589
590         //_ServerList_Test();
591
592         NetConn_QueryMasters(querydp, queryqw);
593 }
594
595 // rest
596
597 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
598 {
599         int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
600         int i;
601         if (length == 0)
602                 return 0;
603         if (cl_netpacketloss_receive.integer)
604                 for (i = 0;i < cl_numsockets;i++)
605                         if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss_receive.integer)
606                                 return 0;
607         if (developer_networking.integer)
608         {
609                 char addressstring[128], addressstring2[128];
610                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
611                 if (length > 0)
612                 {
613                         LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
614                         Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", (void *)mysocket, addressstring, (void *)data, maxlength, (void *)peeraddress, length, addressstring2);
615                         Com_HexDumpToConsole((unsigned char *)data, length);
616                 }
617                 else
618                         Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", (void *)mysocket, addressstring, (void *)data, maxlength, (void *)peeraddress, length);
619         }
620         return length;
621 }
622
623 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
624 {
625         int ret;
626         int i;
627         if (cl_netpacketloss_send.integer)
628                 for (i = 0;i < cl_numsockets;i++)
629                         if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss_send.integer)
630                                 return length;
631         ret = LHNET_Write(mysocket, data, length, peeraddress);
632         if (developer_networking.integer)
633         {
634                 char addressstring[128], addressstring2[128];
635                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
636                 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
637                 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)");
638                 Com_HexDumpToConsole((unsigned char *)data, length);
639         }
640         return ret;
641 }
642
643 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
644 {
645         // note this does not include the trailing NULL because we add that in the parser
646         return NetConn_Write(mysocket, string, (int)strlen(string), peeraddress);
647 }
648
649 qboolean NetConn_CanSend(netconn_t *conn)
650 {
651         conn->outgoing_packetcounter = (conn->outgoing_packetcounter + 1) % NETGRAPH_PACKETS;
652         conn->outgoing_netgraph[conn->outgoing_packetcounter].time            = realtime;
653         conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes = NETGRAPH_NOPACKET;
654         conn->outgoing_netgraph[conn->outgoing_packetcounter].reliablebytes   = NETGRAPH_NOPACKET;
655         conn->outgoing_netgraph[conn->outgoing_packetcounter].ackbytes        = NETGRAPH_NOPACKET;
656         if (realtime > conn->cleartime)
657                 return true;
658         else
659         {
660                 conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes = NETGRAPH_CHOKEDPACKET;
661                 return false;
662         }
663 }
664
665 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data, protocolversion_t protocol, int rate, qboolean quakesignon_suppressreliables)
666 {
667         int totallen = 0;
668
669         // if this packet was supposedly choked, but we find ourselves sending one
670         // anyway, make sure the size counting starts at zero
671         // (this mostly happens on level changes and disconnects and such)
672         if (conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes == NETGRAPH_CHOKEDPACKET)
673                 conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes = NETGRAPH_NOPACKET;
674
675         if (protocol == PROTOCOL_QUAKEWORLD)
676         {
677                 int packetLen;
678                 qboolean sendreliable;
679
680                 // note that it is ok to send empty messages to the qw server,
681                 // otherwise it won't respond to us at all
682
683                 sendreliable = false;
684                 // if the remote side dropped the last reliable message, resend it
685                 if (conn->qw.incoming_acknowledged > conn->qw.last_reliable_sequence && conn->qw.incoming_reliable_acknowledged != conn->qw.reliable_sequence)
686                         sendreliable = true;
687                 // if the reliable transmit buffer is empty, copy the current message out
688                 if (!conn->sendMessageLength && conn->message.cursize)
689                 {
690                         memcpy (conn->sendMessage, conn->message.data, conn->message.cursize);
691                         conn->sendMessageLength = conn->message.cursize;
692                         SZ_Clear(&conn->message); // clear the message buffer
693                         conn->qw.reliable_sequence ^= 1;
694                         sendreliable = true;
695                 }
696                 // outgoing unreliable packet number, and outgoing reliable packet number (0 or 1)
697                 StoreLittleLong(sendbuffer, (unsigned int)conn->outgoing_unreliable_sequence | ((unsigned int)sendreliable<<31));
698                 // last received unreliable packet number, and last received reliable packet number (0 or 1)
699                 StoreLittleLong(sendbuffer + 4, (unsigned int)conn->qw.incoming_sequence | ((unsigned int)conn->qw.incoming_reliable_sequence<<31));
700                 packetLen = 8;
701                 conn->outgoing_unreliable_sequence++;
702                 // client sends qport in every packet
703                 if (conn == cls.netcon)
704                 {
705                         *((short *)(sendbuffer + 8)) = LittleShort(cls.qw_qport);
706                         packetLen += 2;
707                         // also update cls.qw_outgoing_sequence
708                         cls.qw_outgoing_sequence = conn->outgoing_unreliable_sequence;
709                 }
710                 if (packetLen + (sendreliable ? conn->sendMessageLength : 0) > 1400)
711                 {
712                         Con_Printf ("NetConn_SendUnreliableMessage: reliable message too big %u\n", data->cursize);
713                         return -1;
714                 }
715
716                 conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes += packetLen + 28;
717
718                 // add the reliable message if there is one
719                 if (sendreliable)
720                 {
721                         conn->outgoing_netgraph[conn->outgoing_packetcounter].reliablebytes += conn->sendMessageLength + 28;
722                         memcpy(sendbuffer + packetLen, conn->sendMessage, conn->sendMessageLength);
723                         packetLen += conn->sendMessageLength;
724                         conn->qw.last_reliable_sequence = conn->outgoing_unreliable_sequence;
725                 }
726
727                 // add the unreliable message if possible
728                 if (packetLen + data->cursize <= 1400)
729                 {
730                         conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes += data->cursize + 28;
731                         memcpy(sendbuffer + packetLen, data->data, data->cursize);
732                         packetLen += data->cursize;
733                 }
734
735                 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
736
737                 packetsSent++;
738                 unreliableMessagesSent++;
739
740                 totallen += packetLen + 28;
741         }
742         else
743         {
744                 unsigned int packetLen;
745                 unsigned int dataLen;
746                 unsigned int eom;
747                 const void *sendme;
748                 size_t sendmelen;
749
750                 // if a reliable message fragment has been lost, send it again
751                 if (conn->sendMessageLength && (realtime - conn->lastSendTime) > 1.0)
752                 {
753                         if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
754                         {
755                                 dataLen = conn->sendMessageLength;
756                                 eom = NETFLAG_EOM;
757                         }
758                         else
759                         {
760                                 dataLen = MAX_PACKETFRAGMENT;
761                                 eom = 0;
762                         }
763
764                         packetLen = NET_HEADERSIZE + dataLen;
765
766                         StoreBigLong(sendbuffer, packetLen | (NETFLAG_DATA | eom));
767                         StoreBigLong(sendbuffer + 4, conn->nq.sendSequence - 1);
768                         memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
769
770                         conn->outgoing_netgraph[conn->outgoing_packetcounter].reliablebytes += packetLen + 28;
771
772                         sendme = Crypto_EncryptPacket(&conn->crypto, &sendbuffer, packetLen, &cryptosendbuffer, &sendmelen, sizeof(cryptosendbuffer));
773                         if (sendme && NetConn_Write(conn->mysocket, sendme, sendmelen, &conn->peeraddress) == (int)sendmelen)
774                         {
775                                 conn->lastSendTime = realtime;
776                                 packetsReSent++;
777                         }
778
779                         totallen += sendmelen + 28;
780                 }
781
782                 // if we have a new reliable message to send, do so
783                 if (!conn->sendMessageLength && conn->message.cursize && !quakesignon_suppressreliables)
784                 {
785                         if (conn->message.cursize > (int)sizeof(conn->sendMessage))
786                         {
787                                 Con_Printf("NetConn_SendUnreliableMessage: reliable message too big (%u > %u)\n", conn->message.cursize, (int)sizeof(conn->sendMessage));
788                                 conn->message.overflowed = true;
789                                 return -1;
790                         }
791
792                         if (developer_networking.integer && conn == cls.netcon)
793                         {
794                                 Con_Print("client sending reliable message to server:\n");
795                                 SZ_HexDumpToConsole(&conn->message);
796                         }
797
798                         memcpy(conn->sendMessage, conn->message.data, conn->message.cursize);
799                         conn->sendMessageLength = conn->message.cursize;
800                         SZ_Clear(&conn->message);
801
802                         if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
803                         {
804                                 dataLen = conn->sendMessageLength;
805                                 eom = NETFLAG_EOM;
806                         }
807                         else
808                         {
809                                 dataLen = MAX_PACKETFRAGMENT;
810                                 eom = 0;
811                         }
812
813                         packetLen = NET_HEADERSIZE + dataLen;
814
815                         StoreBigLong(sendbuffer, packetLen | (NETFLAG_DATA | eom));
816                         StoreBigLong(sendbuffer + 4, conn->nq.sendSequence);
817                         memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
818
819                         conn->nq.sendSequence++;
820
821                         conn->outgoing_netgraph[conn->outgoing_packetcounter].reliablebytes += packetLen + 28;
822
823                         sendme = Crypto_EncryptPacket(&conn->crypto, &sendbuffer, packetLen, &cryptosendbuffer, &sendmelen, sizeof(cryptosendbuffer));
824                         if(sendme)
825                                 NetConn_Write(conn->mysocket, sendme, sendmelen, &conn->peeraddress);
826
827                         conn->lastSendTime = realtime;
828                         packetsSent++;
829                         reliableMessagesSent++;
830
831                         totallen += sendmelen + 28;
832                 }
833
834                 // if we have an unreliable message to send, do so
835                 if (data->cursize)
836                 {
837                         packetLen = NET_HEADERSIZE + data->cursize;
838
839                         if (packetLen > (int)sizeof(sendbuffer))
840                         {
841                                 Con_Printf("NetConn_SendUnreliableMessage: message too big %u\n", data->cursize);
842                                 return -1;
843                         }
844
845                         StoreBigLong(sendbuffer, packetLen | NETFLAG_UNRELIABLE);
846                         StoreBigLong(sendbuffer + 4, conn->outgoing_unreliable_sequence);
847                         memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
848
849                         conn->outgoing_unreliable_sequence++;
850
851                         conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes += packetLen + 28;
852
853                         sendme = Crypto_EncryptPacket(&conn->crypto, &sendbuffer, packetLen, &cryptosendbuffer, &sendmelen, sizeof(cryptosendbuffer));
854                         if(sendme)
855                                 NetConn_Write(conn->mysocket, sendme, sendmelen, &conn->peeraddress);
856
857                         packetsSent++;
858                         unreliableMessagesSent++;
859
860                         totallen += sendmelen + 28;
861                 }
862         }
863
864         // delay later packets to obey rate limit
865         if (conn->cleartime < realtime - 0.1)
866                 conn->cleartime = realtime - 0.1;
867         conn->cleartime = conn->cleartime + (double)totallen / (double)rate;
868         if (conn->cleartime < realtime)
869                 conn->cleartime = realtime;
870
871         return 0;
872 }
873
874 qboolean NetConn_HaveClientPorts(void)
875 {
876         return !!cl_numsockets;
877 }
878
879 qboolean NetConn_HaveServerPorts(void)
880 {
881         return !!sv_numsockets;
882 }
883
884 void NetConn_CloseClientPorts(void)
885 {
886         for (;cl_numsockets > 0;cl_numsockets--)
887                 if (cl_sockets[cl_numsockets - 1])
888                         LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
889 }
890
891 void NetConn_OpenClientPort(const char *addressstring, lhnetaddresstype_t addresstype, int defaultport)
892 {
893         lhnetaddress_t address;
894         lhnetsocket_t *s;
895         int success;
896         char addressstring2[1024];
897         if (addressstring && addressstring[0])
898                 success = LHNETADDRESS_FromString(&address, addressstring, defaultport);
899         else
900                 success = LHNETADDRESS_FromPort(&address, addresstype, defaultport);
901         if (success)
902         {
903                 if ((s = LHNET_OpenSocket_Connectionless(&address)))
904                 {
905                         cl_sockets[cl_numsockets++] = s;
906                         LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
907                         if (addresstype != LHNETADDRESSTYPE_LOOP)
908                                 Con_Printf("Client opened a socket on address %s\n", addressstring2);
909                 }
910                 else
911                 {
912                         LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
913                         Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
914                 }
915         }
916         else
917                 Con_Printf("Client unable to parse address %s\n", addressstring);
918 }
919
920 void NetConn_OpenClientPorts(void)
921 {
922         int port;
923         NetConn_CloseClientPorts();
924         port = bound(0, cl_netport.integer, 65535);
925         if (cl_netport.integer != port)
926                 Cvar_SetValueQuick(&cl_netport, port);
927         if(port == 0)
928                 Con_Printf("Client using an automatically assigned port\n");
929         else
930                 Con_Printf("Client using port %i\n", port);
931         NetConn_OpenClientPort(NULL, LHNETADDRESSTYPE_LOOP, 2);
932         NetConn_OpenClientPort(net_address.string, LHNETADDRESSTYPE_INET4, port);
933 #ifdef SUPPORTIPV6
934         NetConn_OpenClientPort(net_address_ipv6.string, LHNETADDRESSTYPE_INET6, port);
935 #endif
936 }
937
938 void NetConn_CloseServerPorts(void)
939 {
940         for (;sv_numsockets > 0;sv_numsockets--)
941                 if (sv_sockets[sv_numsockets - 1])
942                         LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
943 }
944
945 qboolean NetConn_OpenServerPort(const char *addressstring, lhnetaddresstype_t addresstype, int defaultport, int range)
946 {
947         lhnetaddress_t address;
948         lhnetsocket_t *s;
949         int port;
950         char addressstring2[1024];
951         int success;
952
953         for (port = defaultport; port <= defaultport + range; port++)
954         {
955                 if (addressstring && addressstring[0])
956                         success = LHNETADDRESS_FromString(&address, addressstring, port);
957                 else
958                         success = LHNETADDRESS_FromPort(&address, addresstype, port);
959                 if (success)
960                 {
961                         if ((s = LHNET_OpenSocket_Connectionless(&address)))
962                         {
963                                 sv_sockets[sv_numsockets++] = s;
964                                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
965                                 if (addresstype != LHNETADDRESSTYPE_LOOP)
966                                         Con_Printf("Server listening on address %s\n", addressstring2);
967                                 return true;
968                         }
969                         else
970                         {
971                                 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
972                                 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
973                         }
974                 }
975                 else
976                 {
977                         Con_Printf("Server unable to parse address %s\n", addressstring);
978                         // if it cant parse one address, it wont be able to parse another for sure
979                         return false;
980                 }
981         }
982         return false;
983 }
984
985 void NetConn_OpenServerPorts(int opennetports)
986 {
987         int port;
988         NetConn_CloseServerPorts();
989         NetConn_UpdateSockets();
990         port = bound(0, sv_netport.integer, 65535);
991         if (port == 0)
992                 port = 26000;
993         Con_Printf("Server using port %i\n", port);
994         if (sv_netport.integer != port)
995                 Cvar_SetValueQuick(&sv_netport, port);
996         if (cls.state != ca_dedicated)
997                 NetConn_OpenServerPort(NULL, LHNETADDRESSTYPE_LOOP, 1, 1);
998         if (opennetports)
999         {
1000 #ifdef SUPPORTIPV6
1001                 qboolean ip4success = NetConn_OpenServerPort(net_address.string, LHNETADDRESSTYPE_INET4, port, 100);
1002                 NetConn_OpenServerPort(net_address_ipv6.string, LHNETADDRESSTYPE_INET6, port, ip4success ? 1 : 100);
1003 #else
1004                 NetConn_OpenServerPort(net_address.string, LHNETADDRESSTYPE_INET4, port, 100);
1005 #endif
1006         }
1007         if (sv_numsockets == 0)
1008                 Host_Error("NetConn_OpenServerPorts: unable to open any ports!");
1009 }
1010
1011 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
1012 {
1013         int i, a = LHNETADDRESS_GetAddressType(address);
1014         for (i = 0;i < cl_numsockets;i++)
1015                 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
1016                         return cl_sockets[i];
1017         return NULL;
1018 }
1019
1020 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
1021 {
1022         int i, a = LHNETADDRESS_GetAddressType(address);
1023         for (i = 0;i < sv_numsockets;i++)
1024                 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
1025                         return sv_sockets[i];
1026         return NULL;
1027 }
1028
1029 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
1030 {
1031         netconn_t *conn;
1032         conn = (netconn_t *)Mem_Alloc(netconn_mempool, sizeof(*conn));
1033         conn->mysocket = mysocket;
1034         conn->peeraddress = *peeraddress;
1035         conn->lastMessageTime = realtime;
1036         conn->message.data = conn->messagedata;
1037         conn->message.maxsize = sizeof(conn->messagedata);
1038         conn->message.cursize = 0;
1039         // LordHavoc: (inspired by ProQuake) use a short connect timeout to
1040         // reduce effectiveness of connection request floods
1041         conn->timeout = realtime + net_connecttimeout.value;
1042         LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
1043         conn->next = netconn_list;
1044         netconn_list = conn;
1045         return conn;
1046 }
1047
1048 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress);
1049 void NetConn_Close(netconn_t *conn)
1050 {
1051         netconn_t *c;
1052         // remove connection from list
1053
1054         // allow the client to reconnect immediately
1055         NetConn_ClearConnectFlood(&(conn->peeraddress));
1056
1057         if (conn == netconn_list)
1058                 netconn_list = conn->next;
1059         else
1060         {
1061                 for (c = netconn_list;c;c = c->next)
1062                 {
1063                         if (c->next == conn)
1064                         {
1065                                 c->next = conn->next;
1066                                 break;
1067                         }
1068                 }
1069                 // not found in list, we'll avoid crashing here...
1070                 if (!c)
1071                         return;
1072         }
1073         // free connection
1074         Mem_Free(conn);
1075 }
1076
1077 static int clientport = -1;
1078 static int clientport2 = -1;
1079 static int hostport = -1;
1080 void NetConn_UpdateSockets(void)
1081 {
1082         int i, j;
1083
1084         if (cls.state != ca_dedicated)
1085         {
1086                 if (clientport2 != cl_netport.integer)
1087                 {
1088                         clientport2 = cl_netport.integer;
1089                         if (cls.state == ca_connected)
1090                                 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
1091                 }
1092                 if (cls.state == ca_disconnected && clientport != clientport2)
1093                 {
1094                         clientport = clientport2;
1095                         NetConn_CloseClientPorts();
1096                 }
1097                 if (cl_numsockets == 0)
1098                         NetConn_OpenClientPorts();
1099         }
1100
1101         if (hostport != sv_netport.integer)
1102         {
1103                 hostport = sv_netport.integer;
1104                 if (sv.active)
1105                         Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
1106         }
1107
1108         for (j = 0;j < MAX_RCONS;j++)
1109         {
1110                 i = (cls.rcon_ringpos + j + 1) % MAX_RCONS;
1111                 if(cls.rcon_commands[i][0])
1112                 {
1113                         if(realtime > cls.rcon_timeout[i])
1114                         {
1115                                 char s[128];
1116                                 LHNETADDRESS_ToString(&cls.rcon_addresses[i], s, sizeof(s), true);
1117                                 Con_Printf("rcon to %s (for command %s) failed: challenge request timed out\n", s, cls.rcon_commands[i]);
1118                                 cls.rcon_commands[i][0] = 0;
1119                                 --cls.rcon_trying;
1120                                 break;
1121                         }
1122                 }
1123         }
1124 }
1125
1126 static int NetConn_ReceivedMessage(netconn_t *conn, const unsigned char *data, size_t length, protocolversion_t protocol, double newtimeout)
1127 {
1128         int originallength = length;
1129         if (length < 8)
1130                 return 0;
1131
1132         if (protocol == PROTOCOL_QUAKEWORLD)
1133         {
1134                 int sequence, sequence_ack;
1135                 int reliable_ack, reliable_message;
1136                 int count;
1137                 //int qport;
1138
1139                 sequence = LittleLong(*((int *)(data + 0)));
1140                 sequence_ack = LittleLong(*((int *)(data + 4)));
1141                 data += 8;
1142                 length -= 8;
1143
1144                 if (conn != cls.netcon)
1145                 {
1146                         // server only
1147                         if (length < 2)
1148                                 return 0;
1149                         // 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?)
1150                         //qport = LittleShort(*((int *)(data + 8)));
1151                         data += 2;
1152                         length -= 2;
1153                 }
1154
1155                 packetsReceived++;
1156                 reliable_message = (sequence >> 31) & 1;
1157                 reliable_ack = (sequence_ack >> 31) & 1;
1158                 sequence &= ~(1<<31);
1159                 sequence_ack &= ~(1<<31);
1160                 if (sequence <= conn->qw.incoming_sequence)
1161                 {
1162                         //Con_DPrint("Got a stale datagram\n");
1163                         return 0;
1164                 }
1165                 count = sequence - (conn->qw.incoming_sequence + 1);
1166                 if (count > 0)
1167                 {
1168                         droppedDatagrams += count;
1169                         //Con_DPrintf("Dropped %u datagram(s)\n", count);
1170                         while (count--)
1171                         {
1172                                 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1173                                 conn->incoming_netgraph[conn->incoming_packetcounter].time            = realtime;
1174                                 conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = NETGRAPH_LOSTPACKET;
1175                                 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes   = NETGRAPH_NOPACKET;
1176                                 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes        = NETGRAPH_NOPACKET;
1177                         }
1178                 }
1179                 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1180                 conn->incoming_netgraph[conn->incoming_packetcounter].time            = realtime;
1181                 conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = originallength + 28;
1182                 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes   = NETGRAPH_NOPACKET;
1183                 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes        = NETGRAPH_NOPACKET;
1184                 if (reliable_ack == conn->qw.reliable_sequence)
1185                 {
1186                         // received, now we will be able to send another reliable message
1187                         conn->sendMessageLength = 0;
1188                         reliableMessagesReceived++;
1189                 }
1190                 conn->qw.incoming_sequence = sequence;
1191                 if (conn == cls.netcon)
1192                         cls.qw_incoming_sequence = conn->qw.incoming_sequence;
1193                 conn->qw.incoming_acknowledged = sequence_ack;
1194                 conn->qw.incoming_reliable_acknowledged = reliable_ack;
1195                 if (reliable_message)
1196                         conn->qw.incoming_reliable_sequence ^= 1;
1197                 conn->lastMessageTime = realtime;
1198                 conn->timeout = realtime + newtimeout;
1199                 unreliableMessagesReceived++;
1200                 SZ_Clear(&net_message);
1201                 SZ_Write(&net_message, data, length);
1202                 MSG_BeginReading();
1203                 return 2;
1204         }
1205         else
1206         {
1207                 unsigned int count;
1208                 unsigned int flags;
1209                 unsigned int sequence;
1210                 size_t qlength;
1211                 const void *sendme;
1212                 size_t sendmelen;
1213
1214                 originallength = length;
1215                 data = (const unsigned char *) Crypto_DecryptPacket(&conn->crypto, data, length, cryptoreadbuffer, &length, sizeof(cryptoreadbuffer));
1216                 if(!data)
1217                         return 0;
1218                 if(length < 8)
1219                         return 0;
1220
1221                 qlength = (unsigned int)BuffBigLong(data);
1222                 flags = qlength & ~NETFLAG_LENGTH_MASK;
1223                 qlength &= NETFLAG_LENGTH_MASK;
1224                 // control packets were already handled
1225                 if (!(flags & NETFLAG_CTL) && qlength == length)
1226                 {
1227                         sequence = BuffBigLong(data + 4);
1228                         packetsReceived++;
1229                         data += 8;
1230                         length -= 8;
1231                         if (flags & NETFLAG_UNRELIABLE)
1232                         {
1233                                 if (sequence >= conn->nq.unreliableReceiveSequence)
1234                                 {
1235                                         if (sequence > conn->nq.unreliableReceiveSequence)
1236                                         {
1237                                                 count = sequence - conn->nq.unreliableReceiveSequence;
1238                                                 droppedDatagrams += count;
1239                                                 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1240                                                 while (count--)
1241                                                 {
1242                                                         conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1243                                                         conn->incoming_netgraph[conn->incoming_packetcounter].time            = realtime;
1244                                                         conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = NETGRAPH_LOSTPACKET;
1245                                                         conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes   = NETGRAPH_NOPACKET;
1246                                                         conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes        = NETGRAPH_NOPACKET;
1247                                                 }
1248                                         }
1249                                         conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1250                                         conn->incoming_netgraph[conn->incoming_packetcounter].time            = realtime;
1251                                         conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = originallength + 28;
1252                                         conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes   = NETGRAPH_NOPACKET;
1253                                         conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes        = NETGRAPH_NOPACKET;
1254                                         conn->nq.unreliableReceiveSequence = sequence + 1;
1255                                         conn->lastMessageTime = realtime;
1256                                         conn->timeout = realtime + newtimeout;
1257                                         unreliableMessagesReceived++;
1258                                         if (length > 0)
1259                                         {
1260                                                 SZ_Clear(&net_message);
1261                                                 SZ_Write(&net_message, data, length);
1262                                                 MSG_BeginReading();
1263                                                 return 2;
1264                                         }
1265                                 }
1266                                 //else
1267                                 //      Con_DPrint("Got a stale datagram\n");
1268                                 return 1;
1269                         }
1270                         else if (flags & NETFLAG_ACK)
1271                         {
1272                                 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes += originallength + 28;
1273                                 if (sequence == (conn->nq.sendSequence - 1))
1274                                 {
1275                                         if (sequence == conn->nq.ackSequence)
1276                                         {
1277                                                 conn->nq.ackSequence++;
1278                                                 if (conn->nq.ackSequence != conn->nq.sendSequence)
1279                                                         Con_DPrint("ack sequencing error\n");
1280                                                 conn->lastMessageTime = realtime;
1281                                                 conn->timeout = realtime + newtimeout;
1282                                                 if (conn->sendMessageLength > MAX_PACKETFRAGMENT)
1283                                                 {
1284                                                         unsigned int packetLen;
1285                                                         unsigned int dataLen;
1286                                                         unsigned int eom;
1287
1288                                                         conn->sendMessageLength -= MAX_PACKETFRAGMENT;
1289                                                         memmove(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
1290
1291                                                         if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
1292                                                         {
1293                                                                 dataLen = conn->sendMessageLength;
1294                                                                 eom = NETFLAG_EOM;
1295                                                         }
1296                                                         else
1297                                                         {
1298                                                                 dataLen = MAX_PACKETFRAGMENT;
1299                                                                 eom = 0;
1300                                                         }
1301
1302                                                         packetLen = NET_HEADERSIZE + dataLen;
1303
1304                                                         StoreBigLong(sendbuffer, packetLen | (NETFLAG_DATA | eom));
1305                                                         StoreBigLong(sendbuffer + 4, conn->nq.sendSequence);
1306                                                         memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
1307
1308                                                         conn->nq.sendSequence++;
1309
1310                                                         sendme = Crypto_EncryptPacket(&conn->crypto, &sendbuffer, packetLen, &cryptosendbuffer, &sendmelen, sizeof(cryptosendbuffer));
1311                                                         if (sendme && NetConn_Write(conn->mysocket, sendme, sendmelen, &conn->peeraddress) == (int)sendmelen)
1312                                                         {
1313                                                                 conn->lastSendTime = realtime;
1314                                                                 packetsSent++;
1315                                                         }
1316                                                 }
1317                                                 else
1318                                                         conn->sendMessageLength = 0;
1319                                         }
1320                                         //else
1321                                         //      Con_DPrint("Duplicate ACK received\n");
1322                                 }
1323                                 //else
1324                                 //      Con_DPrint("Stale ACK received\n");
1325                                 return 1;
1326                         }
1327                         else if (flags & NETFLAG_DATA)
1328                         {
1329                                 unsigned char temppacket[8];
1330                                 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes   += originallength + 28;
1331                                 conn->outgoing_netgraph[conn->outgoing_packetcounter].ackbytes        += 8 + 28;
1332                                 StoreBigLong(temppacket, 8 | NETFLAG_ACK);
1333                                 StoreBigLong(temppacket + 4, sequence);
1334                                 sendme = Crypto_EncryptPacket(&conn->crypto, temppacket, 8, &cryptosendbuffer, &sendmelen, sizeof(cryptosendbuffer));
1335                                 if(sendme)
1336                                         NetConn_Write(conn->mysocket, sendme, sendmelen, &conn->peeraddress);
1337                                 if (sequence == conn->nq.receiveSequence)
1338                                 {
1339                                         conn->lastMessageTime = realtime;
1340                                         conn->timeout = realtime + newtimeout;
1341                                         conn->nq.receiveSequence++;
1342                                         if( conn->receiveMessageLength + length <= (int)sizeof( conn->receiveMessage ) ) {
1343                                                 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
1344                                                 conn->receiveMessageLength += length;
1345                                         } else {
1346                                                 Con_Printf( "Reliable message (seq: %i) too big for message buffer!\n"
1347                                                                         "Dropping the message!\n", sequence );
1348                                                 conn->receiveMessageLength = 0;
1349                                                 return 1;
1350                                         }
1351                                         if (flags & NETFLAG_EOM)
1352                                         {
1353                                                 reliableMessagesReceived++;
1354                                                 length = conn->receiveMessageLength;
1355                                                 conn->receiveMessageLength = 0;
1356                                                 if (length > 0)
1357                                                 {
1358                                                         SZ_Clear(&net_message);
1359                                                         SZ_Write(&net_message, conn->receiveMessage, length);
1360                                                         MSG_BeginReading();
1361                                                         return 2;
1362                                                 }
1363                                         }
1364                                 }
1365                                 else
1366                                         receivedDuplicateCount++;
1367                                 return 1;
1368                         }
1369                 }
1370         }
1371         return 0;
1372 }
1373
1374 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, protocolversion_t initialprotocol)
1375 {
1376         crypto_t *crypto;
1377         cls.connect_trying = false;
1378         M_Update_Return_Reason("");
1379         // the connection request succeeded, stop current connection and set up a new connection
1380         CL_Disconnect();
1381         // if we're connecting to a remote server, shut down any local server
1382         if (LHNETADDRESS_GetAddressType(peeraddress) != LHNETADDRESSTYPE_LOOP && sv.active)
1383                 Host_ShutdownServer ();
1384         // allocate a net connection to keep track of things
1385         cls.netcon = NetConn_Open(mysocket, peeraddress);
1386         crypto = &cls.crypto;
1387         if(crypto && crypto->authenticated)
1388         {
1389                 Crypto_ServerFinishInstance(&cls.netcon->crypto, crypto);
1390                 Con_Printf("%s connection to %s has been established: server is %s@%.*s, I am %.*s@%.*s\n",
1391                                 crypto->use_aes ? "Encrypted" : "Authenticated",
1392                                 cls.netcon->address,
1393                                 crypto->server_idfp[0] ? crypto->server_idfp : "-",
1394                                 crypto_keyfp_recommended_length, crypto->server_keyfp[0] ? crypto->server_keyfp : "-",
1395                                 crypto_keyfp_recommended_length, crypto->client_idfp[0] ? crypto->client_idfp : "-",
1396                                 crypto_keyfp_recommended_length, crypto->client_keyfp[0] ? crypto->client_keyfp : "-"
1397                                 );
1398         }
1399         Con_Printf("Connection accepted to %s\n", cls.netcon->address);
1400         key_dest = key_game;
1401         m_state = m_none;
1402         cls.demonum = -1;                       // not in the demo loop now
1403         cls.state = ca_connected;
1404         cls.signon = 0;                         // need all the signon messages before playing
1405         cls.protocol = initialprotocol;
1406         // reset move sequence numbering on this new connection
1407         cls.servermovesequence = 0;
1408         if (cls.protocol == PROTOCOL_QUAKEWORLD)
1409                 Cmd_ForwardStringToServer("new");
1410         if (cls.protocol == PROTOCOL_QUAKE)
1411         {
1412                 // write a keepalive (clc_nop) as it seems to greatly improve the
1413                 // chances of connecting to a netquake server
1414                 sizebuf_t msg;
1415                 unsigned char buf[4];
1416                 memset(&msg, 0, sizeof(msg));
1417                 msg.data = buf;
1418                 msg.maxsize = sizeof(buf);
1419                 MSG_WriteChar(&msg, clc_nop);
1420                 NetConn_SendUnreliableMessage(cls.netcon, &msg, cls.protocol, 10000, false);
1421         }
1422 }
1423
1424 int NetConn_IsLocalGame(void)
1425 {
1426         if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
1427                 return true;
1428         return false;
1429 }
1430
1431 static int NetConn_ClientParsePacket_ServerList_ProcessReply(const char *addressstring)
1432 {
1433         int n;
1434         int pingtime;
1435         serverlist_entry_t *entry = NULL;
1436
1437         // search the cache for this server and update it
1438         for (n = 0;n < serverlist_cachecount;n++) {
1439                 entry = &serverlist_cache[ n ];
1440                 if (!strcmp(addressstring, entry->info.cname))
1441                         break;
1442         }
1443
1444         if (n == serverlist_cachecount)
1445         {
1446                 // LAN search doesnt require an answer from the master server so we wont
1447                 // know the ping nor will it be initialized already...
1448
1449                 // find a slot
1450                 if (serverlist_cachecount == SERVERLIST_TOTALSIZE)
1451                         return -1;
1452
1453                 if (serverlist_maxcachecount <= serverlist_cachecount)
1454                 {
1455                         serverlist_maxcachecount += 64;
1456                         serverlist_cache = (serverlist_entry_t *)Mem_Realloc(netconn_mempool, (void *)serverlist_cache, sizeof(serverlist_entry_t) * serverlist_maxcachecount);
1457                 }
1458                 entry = &serverlist_cache[n];
1459
1460                 memset(entry, 0, sizeof(*entry));
1461                 // store the data the engine cares about (address and ping)
1462                 strlcpy(entry->info.cname, addressstring, sizeof(entry->info.cname));
1463                 entry->info.ping = 100000;
1464                 entry->querytime = realtime;
1465                 // if not in the slist menu we should print the server to console
1466                 if (serverlist_consoleoutput)
1467                         Con_Printf("querying %s\n", addressstring);
1468                 ++serverlist_cachecount;
1469         }
1470         // if this is the first reply from this server, count it as having replied
1471         pingtime = (int)((realtime - entry->querytime) * 1000.0 + 0.5);
1472         pingtime = bound(0, pingtime, 9999);
1473         if (entry->query == SQS_REFRESHING) {
1474                 entry->info.ping = pingtime;
1475                 entry->query = SQS_QUERIED;
1476         } else {
1477                 // convert to unsigned to catch the -1
1478                 // 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]
1479                 entry->info.ping = min((unsigned) entry->info.ping, (unsigned) pingtime);
1480                 serverreplycount++;
1481         }
1482         
1483         // other server info is updated by the caller
1484         return n;
1485 }
1486
1487 static void NetConn_ClientParsePacket_ServerList_UpdateCache(int n)
1488 {
1489         serverlist_entry_t *entry = &serverlist_cache[n];
1490         serverlist_info_t *info = &entry->info;
1491         // update description strings for engine menu and console output
1492         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);
1493         dpsnprintf(entry->line2, sizeof(serverlist_cache[n].line2), "^4%-21.21s %-19.19s ^%c%-17.17s^4 %-20.20s", info->cname, info->game,
1494                         (
1495                          info->gameversion != gameversion.integer
1496                          &&
1497                          !(
1498                                     gameversion_min.integer >= 0 // min/max range set by user/mod?
1499                                  && gameversion_max.integer >= 0
1500                                  && gameversion_min.integer >= info->gameversion // version of server in min/max range?
1501                                  && gameversion_max.integer <= info->gameversion
1502                           )
1503                         ) ? '1' : '4',
1504                         info->mod, info->map);
1505         if (entry->query == SQS_QUERIED)
1506         {
1507                 if(!serverlist_paused)
1508                         ServerList_ViewList_Remove(entry);
1509         }
1510         // if not in the slist menu we should print the server to console (if wanted)
1511         else if( serverlist_consoleoutput )
1512                 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1513         // and finally, update the view set
1514         if(!serverlist_paused)
1515                 ServerList_ViewList_Insert( entry );
1516         //      update the entry's state
1517         serverlist_cache[n].query = SQS_QUERIED;
1518 }
1519
1520 // returns true, if it's sensible to continue the processing
1521 static qboolean NetConn_ClientParsePacket_ServerList_PrepareQuery( int protocol, const char *ipstring, qboolean isfavorite ) {
1522         int n;
1523         serverlist_entry_t *entry;
1524
1525         //      ignore the rest of the message if the serverlist is full
1526         if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1527                 return false;
1528         //      also ignore     it      if      we      have already queried    it      (other master server    response)
1529         for( n =        0 ; n   < serverlist_cachecount ; n++   )
1530                 if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1531                         break;
1532
1533         if( n < serverlist_cachecount ) {
1534                 // the entry has already been queried once or 
1535                 return true;
1536         }
1537
1538         if (serverlist_maxcachecount <= n)
1539         {
1540                 serverlist_maxcachecount += 64;
1541                 serverlist_cache = (serverlist_entry_t *)Mem_Realloc(netconn_mempool, (void *)serverlist_cache, sizeof(serverlist_entry_t) * serverlist_maxcachecount);
1542         }
1543
1544         entry = &serverlist_cache[n];
1545
1546         memset(entry, 0, sizeof(entry));
1547         entry->protocol =       protocol;
1548         //      store   the data        the engine cares about (address and     ping)
1549         strlcpy (entry->info.cname, ipstring, sizeof(entry->info.cname));
1550
1551         entry->info.isfavorite = isfavorite;
1552         
1553         // no, then reset the ping right away
1554         entry->info.ping = -1;
1555         // we also want to increase the serverlist_cachecount then
1556         serverlist_cachecount++;
1557         serverquerycount++;
1558
1559         entry->query =  SQS_QUERYING;
1560
1561         return true;
1562 }
1563
1564 static void NetConn_ClientParsePacket_ServerList_ParseDPList(lhnetaddress_t *senderaddress, const unsigned char *data, int length, qboolean isextended)
1565 {
1566         masterreplycount++;
1567         if (serverlist_consoleoutput)
1568                 Con_Printf("received DarkPlaces %sserver list...\n", isextended ? "extended " : "");
1569         while (length >= 7)
1570         {
1571                 char ipstring [128];
1572
1573                 // IPv4 address
1574                 if (data[0] == '\\')
1575                 {
1576                         unsigned short port = data[5] * 256 + data[6];
1577
1578                         if (port != 0 && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF))
1579                                 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%hu", data[1], data[2], data[3], data[4], port);
1580
1581                         // move on to next address in packet
1582                         data += 7;
1583                         length -= 7;
1584                 }
1585                 // IPv6 address
1586                 else if (data[0] == '/' && isextended && length >= 19)
1587                 {
1588                         unsigned short port = data[17] * 256 + data[18];
1589
1590                         if (port != 0)
1591                         {
1592 #ifdef WHY_JUST_WHY
1593                                 const char *ifname;
1594
1595                                 /// \TODO: make some basic checks of the IP address (broadcast, ...)
1596
1597                                 ifname = LHNETADDRESS_GetInterfaceName(senderaddress);
1598                                 if (ifname != NULL)
1599                                 {
1600                                         dpsnprintf (ipstring, sizeof (ipstring), "[%x:%x:%x:%x:%x:%x:%x:%x%%%s]:%hu",
1601                                                                 (data[1] << 8) | data[2], (data[3] << 8) | data[4], (data[5] << 8) | data[6], (data[7] << 8) | data[8],
1602                                                                 (data[9] << 8) | data[10], (data[11] << 8) | data[12], (data[13] << 8) | data[14], (data[15] << 8) | data[16],
1603                                                                 ifname, port);
1604                                 }
1605                                 else
1606 #endif
1607                                 {
1608                                         dpsnprintf (ipstring, sizeof (ipstring), "[%x:%x:%x:%x:%x:%x:%x:%x]:%hu",
1609                                                                 (data[1] << 8) | data[2], (data[3] << 8) | data[4], (data[5] << 8) | data[6], (data[7] << 8) | data[8],
1610                                                                 (data[9] << 8) | data[10], (data[11] << 8) | data[12], (data[13] << 8) | data[14], (data[15] << 8) | data[16],
1611                                                                 port);
1612                                 }
1613                         }
1614
1615                         // move on to next address in packet
1616                         data += 19;
1617                         length -= 19;
1618                 }
1619                 else
1620                 {
1621                         Con_Print("Error while parsing the server list\n");
1622                         break;
1623                 }
1624
1625                 if (serverlist_consoleoutput && developer_networking.integer)
1626                         Con_Printf("Requesting info from DarkPlaces server %s\n", ipstring);
1627                 
1628                 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, ipstring, false ) ) {
1629                         break;
1630                 }
1631
1632         }
1633
1634         // begin or resume serverlist queries
1635         serverlist_querysleep = false;
1636         serverlist_querywaittime = realtime + 3;
1637 }
1638
1639 static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1640 {
1641         qboolean fromserver;
1642         int ret, c, control;
1643         const char *s;
1644         char *string, addressstring2[128], ipstring[32];
1645         char stringbuf[16384];
1646         char senddata[NET_HEADERSIZE+NET_MAXMESSAGE+CRYPTO_HEADERSIZE];
1647         size_t sendlength;
1648
1649         // quakeworld ingame packet
1650         fromserver = cls.netcon && mysocket == cls.netcon->mysocket && !LHNETADDRESS_Compare(&cls.netcon->peeraddress, peeraddress);
1651
1652         // convert the address to a string incase we need it
1653         LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1654
1655         if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1656         {
1657                 // received a command string - strip off the packaging and put it
1658                 // into our string buffer with NULL termination
1659                 data += 4;
1660                 length -= 4;
1661                 length = min(length, (int)sizeof(stringbuf) - 1);
1662                 memcpy(stringbuf, data, length);
1663                 stringbuf[length] = 0;
1664                 string = stringbuf;
1665
1666                 if (developer_networking.integer)
1667                 {
1668                         Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
1669                         Com_HexDumpToConsole(data, length);
1670                 }
1671
1672                 sendlength = sizeof(senddata) - 4;
1673                 switch(Crypto_ClientParsePacket(string, length, senddata+4, &sendlength, peeraddress))
1674                 {
1675                         case CRYPTO_NOMATCH:
1676                                 // nothing to do
1677                                 break;
1678                         case CRYPTO_MATCH:
1679                                 if(sendlength)
1680                                 {
1681                                         memcpy(senddata, "\377\377\377\377", 4);
1682                                         NetConn_Write(mysocket, senddata, sendlength+4, peeraddress);
1683                                 }
1684                                 break;
1685                         case CRYPTO_DISCARD:
1686                                 if(sendlength)
1687                                 {
1688                                         memcpy(senddata, "\377\377\377\377", 4);
1689                                         NetConn_Write(mysocket, senddata, sendlength+4, peeraddress);
1690                                 }
1691                                 return true;
1692                                 break;
1693                         case CRYPTO_REPLACE:
1694                                 string = senddata+4;
1695                                 length = sendlength;
1696                                 break;
1697                 }
1698
1699                 if (length >= 10 && !memcmp(string, "challenge ", 10) && cls.rcon_trying)
1700                 {
1701                         int i = 0, j;
1702                         for (j = 0;j < MAX_RCONS;j++)
1703                         {
1704                                 // note: this value from i is used outside the loop too...
1705                                 i = (cls.rcon_ringpos + j) % MAX_RCONS;
1706                                 if(cls.rcon_commands[i][0])
1707                                         if (!LHNETADDRESS_Compare(peeraddress, &cls.rcon_addresses[i]))
1708                                                 break;
1709                         }
1710                         if (j < MAX_RCONS)
1711                         {
1712                                 char buf[1500];
1713                                 char argbuf[1500];
1714                                 const char *e;
1715                                 int n;
1716                                 dpsnprintf(argbuf, sizeof(argbuf), "%s %s", string + 10, cls.rcon_commands[i]);
1717                                 memcpy(buf, "\377\377\377\377srcon HMAC-MD4 CHALLENGE ", 29);
1718
1719                                 e = strchr(rcon_password.string, ' ');
1720                                 n = e ? e-rcon_password.string : (int)strlen(rcon_password.string);
1721
1722                                 if(HMAC_MDFOUR_16BYTES((unsigned char *) (buf + 29), (unsigned char *) argbuf, strlen(argbuf), (unsigned char *) rcon_password.string, n))
1723                                 {
1724                                         int k;
1725                                         buf[45] = ' ';
1726                                         strlcpy(buf + 46, argbuf, sizeof(buf) - 46);
1727                                         NetConn_Write(mysocket, buf, 46 + strlen(buf + 46), peeraddress);
1728                                         cls.rcon_commands[i][0] = 0;
1729                                         --cls.rcon_trying;
1730
1731                                         for (k = 0;k < MAX_RCONS;k++)
1732                                                 if(cls.rcon_commands[k][0])
1733                                                         if (!LHNETADDRESS_Compare(peeraddress, &cls.rcon_addresses[k]))
1734                                                                 break;
1735                                         if(k < MAX_RCONS)
1736                                         {
1737                                                 int l;
1738                                                 NetConn_WriteString(mysocket, "\377\377\377\377getchallenge", peeraddress);
1739                                                 // extend the timeout on other requests as we asked for a challenge
1740                                                 for (l = 0;l < MAX_RCONS;l++)
1741                                                         if(cls.rcon_commands[l][0])
1742                                                                 if (!LHNETADDRESS_Compare(peeraddress, &cls.rcon_addresses[l]))
1743                                                                         cls.rcon_timeout[l] = realtime + rcon_secure_challengetimeout.value;
1744                                         }
1745
1746                                         return true; // we used up the challenge, so we can't use this oen for connecting now anyway
1747                                 }
1748                         }
1749                 }
1750                 if (length >= 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
1751                 {
1752                         // darkplaces or quake3
1753                         char protocolnames[1400];
1754                         Protocol_Names(protocolnames, sizeof(protocolnames));
1755                         Con_DPrintf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
1756                         M_Update_Return_Reason("Got challenge response");
1757                         // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1758                         InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1759                         // TODO: add userinfo stuff here instead of using NQ commands?
1760                         NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\protocols\\%s%s\\challenge\\%s", protocolnames, cls.connect_userinfo, string + 10), peeraddress);
1761                         return true;
1762                 }
1763                 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
1764                 {
1765                         // darkplaces or quake3
1766                         M_Update_Return_Reason("Accepted");
1767                         NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_DARKPLACES3);
1768                         return true;
1769                 }
1770                 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
1771                 {
1772                         char rejectreason[128];
1773                         cls.connect_trying = false;
1774                         string += 7;
1775                         length = min(length - 7, (int)sizeof(rejectreason) - 1);
1776                         memcpy(rejectreason, string, length);
1777                         rejectreason[length] = 0;
1778                         M_Update_Return_Reason(rejectreason);
1779                         return true;
1780                 }
1781                 if (length >= 15 && !memcmp(string, "statusResponse\x0A", 15))
1782                 {
1783                         serverlist_info_t *info;
1784                         char *p;
1785                         int n;
1786
1787                         string += 15;
1788                         // search the cache for this server and update it
1789                         n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1790                         if (n < 0)
1791                                 return true;
1792
1793                         info = &serverlist_cache[n].info;
1794                         info->game[0] = 0;
1795                         info->mod[0]  = 0;
1796                         info->map[0]  = 0;
1797                         info->name[0] = 0;
1798                         info->qcstatus[0] = 0;
1799                         info->players[0] = 0;
1800                         info->protocol = -1;
1801                         info->numplayers = 0;
1802                         info->numbots = -1;
1803                         info->maxplayers  = 0;
1804                         info->gameversion = 0;
1805
1806                         p = strchr(string, '\n');
1807                         if(p)
1808                         {
1809                                 *p = 0; // cut off the string there
1810                                 ++p;
1811                         }
1812                         else
1813                                 Con_Printf("statusResponse without players block?\n");
1814
1815                         if ((s = SearchInfostring(string, "gamename"     )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1816                         if ((s = SearchInfostring(string, "modname"      )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1817                         if ((s = SearchInfostring(string, "mapname"      )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1818                         if ((s = SearchInfostring(string, "hostname"     )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1819                         if ((s = SearchInfostring(string, "protocol"     )) != NULL) info->protocol = atoi(s);
1820                         if ((s = SearchInfostring(string, "clients"      )) != NULL) info->numplayers = atoi(s);
1821                         if ((s = SearchInfostring(string, "bots"         )) != NULL) info->numbots = atoi(s);
1822                         if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1823                         if ((s = SearchInfostring(string, "gameversion"  )) != NULL) info->gameversion = atoi(s);
1824                         if ((s = SearchInfostring(string, "qcstatus"     )) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1825                         if (p                                               != NULL) strlcpy(info->players, p, sizeof(info->players));
1826                         info->numhumans = info->numplayers - max(0, info->numbots);
1827                         info->freeslots = info->maxplayers - info->numplayers;
1828
1829                         NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1830
1831                         return true;
1832                 }
1833                 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
1834                 {
1835                         serverlist_info_t *info;
1836                         int n;
1837
1838                         string += 13;
1839                         // search the cache for this server and update it
1840                         n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1841                         if (n < 0)
1842                                 return true;
1843
1844                         info = &serverlist_cache[n].info;
1845                         info->game[0] = 0;
1846                         info->mod[0]  = 0;
1847                         info->map[0]  = 0;
1848                         info->name[0] = 0;
1849                         info->qcstatus[0] = 0;
1850                         info->players[0] = 0;
1851                         info->protocol = -1;
1852                         info->numplayers = 0;
1853                         info->numbots = -1;
1854                         info->maxplayers  = 0;
1855                         info->gameversion = 0;
1856
1857                         if ((s = SearchInfostring(string, "gamename"     )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1858                         if ((s = SearchInfostring(string, "modname"      )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1859                         if ((s = SearchInfostring(string, "mapname"      )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1860                         if ((s = SearchInfostring(string, "hostname"     )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1861                         if ((s = SearchInfostring(string, "protocol"     )) != NULL) info->protocol = atoi(s);
1862                         if ((s = SearchInfostring(string, "clients"      )) != NULL) info->numplayers = atoi(s);
1863                         if ((s = SearchInfostring(string, "bots"         )) != NULL) info->numbots = atoi(s);
1864                         if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1865                         if ((s = SearchInfostring(string, "gameversion"  )) != NULL) info->gameversion = atoi(s);
1866                         if ((s = SearchInfostring(string, "qcstatus"     )) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1867                         info->numhumans = info->numplayers - max(0, info->numbots);
1868                         info->freeslots = info->maxplayers - info->numplayers;
1869
1870                         NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1871
1872                         return true;
1873                 }
1874                 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1875                 {
1876                         // Extract the IP addresses
1877                         data += 18;
1878                         length -= 18;
1879                         NetConn_ClientParsePacket_ServerList_ParseDPList(peeraddress, data, length, false);
1880                         return true;
1881                 }
1882                 if (!strncmp(string, "getserversExtResponse", 21) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1883                 {
1884                         // Extract the IP addresses
1885                         data += 21;
1886                         length -= 21;
1887                         NetConn_ClientParsePacket_ServerList_ParseDPList(peeraddress, data, length, true);
1888                         return true;
1889                 }
1890                 if (!memcmp(string, "d\n", 2) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1891                 {
1892                         // Extract the IP addresses
1893                         data += 2;
1894                         length -= 2;
1895                         masterreplycount++;
1896                         if (serverlist_consoleoutput)
1897                                 Con_Printf("received QuakeWorld server list from %s...\n", addressstring2);
1898                         while (length >= 6 && (data[0] != 0xFF || data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF) && data[4] * 256 + data[5] != 0)
1899                         {
1900                                 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[0], data[1], data[2], data[3], data[4] * 256 + data[5]);
1901                                 if (serverlist_consoleoutput && developer_networking.integer)
1902                                         Con_Printf("Requesting info from QuakeWorld server %s\n", ipstring);
1903                                 
1904                                 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, ipstring, false ) ) {
1905                                         break;
1906                                 }
1907
1908                                 // move on to next address in packet
1909                                 data += 6;
1910                                 length -= 6;
1911                         }
1912                         // begin or resume serverlist queries
1913                         serverlist_querysleep = false;
1914                         serverlist_querywaittime = realtime + 3;
1915                         return true;
1916                 }
1917                 if (!strncmp(string, "extResponse ", 12))
1918                 {
1919                         ++cl_net_extresponse_count;
1920                         if(cl_net_extresponse_count > NET_EXTRESPONSE_MAX)
1921                                 cl_net_extresponse_count = NET_EXTRESPONSE_MAX;
1922                         cl_net_extresponse_last = (cl_net_extresponse_last + 1) % NET_EXTRESPONSE_MAX;
1923                         dpsnprintf(cl_net_extresponse[cl_net_extresponse_last], sizeof(cl_net_extresponse[cl_net_extresponse_last]), "\"%s\" %s", addressstring2, string + 12);
1924                         return true;
1925                 }
1926                 if (!strncmp(string, "ping", 4))
1927                 {
1928                         if (developer_extra.integer)
1929                                 Con_DPrintf("Received ping from %s, sending ack\n", addressstring2);
1930                         NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1931                         return true;
1932                 }
1933                 if (!strncmp(string, "ack", 3))
1934                         return true;
1935                 // QuakeWorld compatibility
1936                 if (length > 1 && string[0] == 'c' && (string[1] == '-' || (string[1] >= '0' && string[1] <= '9')) && cls.connect_trying)
1937                 {
1938                         // challenge message
1939                         Con_Printf("challenge %s received, sending QuakeWorld connect request back to %s\n", string + 1, addressstring2);
1940                         M_Update_Return_Reason("Got QuakeWorld challenge response");
1941                         cls.qw_qport = qport.integer;
1942                         // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1943                         InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1944                         NetConn_WriteString(mysocket, va("\377\377\377\377connect %i %i %i \"%s%s\"\n", 28, cls.qw_qport, atoi(string + 1), cls.userinfo, cls.connect_userinfo), peeraddress);
1945                         return true;
1946                 }
1947                 if (length >= 1 && string[0] == 'j' && cls.connect_trying)
1948                 {
1949                         // accept message
1950                         M_Update_Return_Reason("QuakeWorld Accepted");
1951                         NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_QUAKEWORLD);
1952                         return true;
1953                 }
1954                 if (length > 2 && !memcmp(string, "n\\", 2))
1955                 {
1956                         serverlist_info_t *info;
1957                         int n;
1958
1959                         // qw server status
1960                         if (serverlist_consoleoutput && developer_networking.integer >= 2)
1961                                 Con_Printf("QW server status from server at %s:\n%s\n", addressstring2, string + 1);
1962
1963                         string += 1;
1964                         // search the cache for this server and update it
1965                         n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1966                         if (n < 0)
1967                                 return true;
1968
1969                         info = &serverlist_cache[n].info;
1970                         strlcpy(info->game, "QuakeWorld", sizeof(info->game));
1971                         if ((s = SearchInfostring(string, "*gamedir"     )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0]  = 0;
1972                         if ((s = SearchInfostring(string, "map"          )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0]  = 0;
1973                         if ((s = SearchInfostring(string, "hostname"     )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
1974                         info->protocol = 0;
1975                         info->numplayers = 0; // updated below
1976                         info->numhumans = 0; // updated below
1977                         if ((s = SearchInfostring(string, "maxclients"   )) != NULL) info->maxplayers = atoi(s);else info->maxplayers  = 0;
1978                         if ((s = SearchInfostring(string, "gameversion"  )) != NULL) info->gameversion = atoi(s);else info->gameversion = 0;
1979
1980                         // count active players on server
1981                         // (we could gather more info, but we're just after the number)
1982                         s = strchr(string, '\n');
1983                         if (s)
1984                         {
1985                                 s++;
1986                                 while (s < string + length)
1987                                 {
1988                                         for (;s < string + length && *s != '\n';s++)
1989                                                 ;
1990                                         if (s >= string + length)
1991                                                 break;
1992                                         info->numplayers++;
1993                                         info->numhumans++;
1994                                         s++;
1995                                 }
1996                         }
1997
1998                         NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1999
2000                         return true;
2001                 }
2002                 if (string[0] == 'n')
2003                 {
2004                         // qw print command
2005                         Con_Printf("QW print command from server at %s:\n%s\n", addressstring2, string + 1);
2006                 }
2007                 // we may not have liked the packet, but it was a command packet, so
2008                 // we're done processing this packet now
2009                 return true;
2010         }
2011         // quakeworld ingame packet
2012         if (fromserver && cls.protocol == PROTOCOL_QUAKEWORLD && length >= 8 && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
2013         {
2014                 ret = 0;
2015                 CL_ParseServerMessage();
2016                 return ret;
2017         }
2018         // netquake control packets, supported for compatibility only
2019         if (length >= 5 && (control = BuffBigLong(data)) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length && !ENCRYPTION_REQUIRED)
2020         {
2021                 int n;
2022                 serverlist_info_t *info;
2023
2024                 data += 4;
2025                 length -= 4;
2026                 SZ_Clear(&net_message);
2027                 SZ_Write(&net_message, data, length);
2028                 MSG_BeginReading();
2029                 c = MSG_ReadByte();
2030                 switch (c)
2031                 {
2032                 case CCREP_ACCEPT:
2033                         if (developer_extra.integer)
2034                                 Con_DPrintf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
2035                         if (cls.connect_trying)
2036                         {
2037                                 lhnetaddress_t clientportaddress;
2038                                 clientportaddress = *peeraddress;
2039                                 LHNETADDRESS_SetPort(&clientportaddress, MSG_ReadLong());
2040                                 // extra ProQuake stuff
2041                                 if (length >= 6)
2042                                         cls.proquake_servermod = MSG_ReadByte(); // MOD_PROQUAKE
2043                                 else
2044                                         cls.proquake_servermod = 0;
2045                                 if (length >= 7)
2046                                         cls.proquake_serverversion = MSG_ReadByte(); // version * 10
2047                                 else
2048                                         cls.proquake_serverversion = 0;
2049                                 if (length >= 8)
2050                                         cls.proquake_serverflags = MSG_ReadByte(); // flags (mainly PQF_CHEATFREE)
2051                                 else
2052                                         cls.proquake_serverflags = 0;
2053                                 if (cls.proquake_servermod == 1)
2054                                         Con_Printf("Connected to ProQuake %.1f server, enabling precise aim\n", cls.proquake_serverversion / 10.0f);
2055                                 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
2056                                 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
2057                                 M_Update_Return_Reason("Accepted");
2058                                 NetConn_ConnectionEstablished(mysocket, &clientportaddress, PROTOCOL_QUAKE);
2059                         }
2060                         break;
2061                 case CCREP_REJECT:
2062                         if (developer_extra.integer)
2063                                 Con_DPrintf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
2064                         cls.connect_trying = false;
2065                         M_Update_Return_Reason((char *)MSG_ReadString());
2066                         break;
2067                 case CCREP_SERVER_INFO:
2068                         if (developer_extra.integer)
2069                                 Con_DPrintf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
2070                         // LordHavoc: because the quake server may report weird addresses
2071                         // we just ignore it and keep the real address
2072                         MSG_ReadString();
2073                         // search the cache for this server and update it
2074                         n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
2075                         if (n < 0)
2076                                 break;
2077
2078                         info = &serverlist_cache[n].info;
2079                         strlcpy(info->game, "Quake", sizeof(info->game));
2080                         strlcpy(info->mod , "", sizeof(info->mod)); // mod name is not specified
2081                         strlcpy(info->name, MSG_ReadString(), sizeof(info->name));
2082                         strlcpy(info->map , MSG_ReadString(), sizeof(info->map));
2083                         info->numplayers = MSG_ReadByte();
2084                         info->maxplayers = MSG_ReadByte();
2085                         info->protocol = MSG_ReadByte();
2086
2087                         NetConn_ClientParsePacket_ServerList_UpdateCache(n);
2088
2089                         break;
2090                 case CCREP_RCON: // RocketGuy: ProQuake rcon support
2091                         if (developer_extra.integer)
2092                                 Con_DPrintf("Datagram_ParseConnectionless: received CCREP_RCON from %s.\n", addressstring2);
2093
2094                         Con_Printf("%s\n", MSG_ReadString());
2095                         break;
2096                 case CCREP_PLAYER_INFO:
2097                         // we got a CCREP_PLAYER_INFO??
2098                         //if (developer_extra.integer)
2099                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
2100                         break;
2101                 case CCREP_RULE_INFO:
2102                         // we got a CCREP_RULE_INFO??
2103                         //if (developer_extra.integer)
2104                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
2105                         break;
2106                 default:
2107                         break;
2108                 }
2109                 SZ_Clear(&net_message);
2110                 // we may not have liked the packet, but it was a valid control
2111                 // packet, so we're done processing this packet now
2112                 return true;
2113         }
2114         ret = 0;
2115         if (fromserver && length >= (int)NET_HEADERSIZE && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
2116                 CL_ParseServerMessage();
2117         return ret;
2118 }
2119
2120 void NetConn_QueryQueueFrame(void)
2121 {
2122         int index;
2123         int queries;
2124         int maxqueries;
2125         double timeouttime;
2126         static double querycounter = 0;
2127
2128         if(!net_slist_pause.integer && serverlist_paused)
2129                 ServerList_RebuildViewList();
2130         serverlist_paused = net_slist_pause.integer != 0;
2131
2132         if (serverlist_querysleep)
2133                 return;
2134
2135         // apply a cool down time after master server replies,
2136         // to avoid messing up the ping times on the servers
2137         if (serverlist_querywaittime > realtime)
2138                 return;
2139
2140         // each time querycounter reaches 1.0 issue a query
2141         querycounter += cl.realframetime * net_slist_queriespersecond.value;
2142         maxqueries = (int)querycounter;
2143         maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer);
2144         querycounter -= maxqueries;
2145
2146         if( maxqueries == 0 ) {
2147                 return;
2148         }
2149
2150         //      scan serverlist and issue queries as needed
2151         serverlist_querysleep = true;
2152
2153         timeouttime     = realtime - net_slist_timeout.value;
2154         for( index = 0, queries = 0 ;   index   < serverlist_cachecount &&      queries < maxqueries    ; index++ )
2155         {
2156                 serverlist_entry_t *entry = &serverlist_cache[ index ];
2157                 if( entry->query != SQS_QUERYING && entry->query != SQS_REFRESHING )
2158                 {
2159                         continue;
2160                 }
2161
2162                 serverlist_querysleep   = false;
2163                 if( entry->querycounter !=      0 && entry->querytime > timeouttime     )
2164                 {
2165                         continue;
2166                 }
2167
2168                 if( entry->querycounter !=      (unsigned) net_slist_maxtries.integer )
2169                 {
2170                         lhnetaddress_t  address;
2171                         int socket;
2172
2173                         LHNETADDRESS_FromString(&address, entry->info.cname, 0);
2174                         if      (entry->protocol == PROTOCOL_QUAKEWORLD)
2175                         {
2176                                 for (socket     = 0; socket     < cl_numsockets ;       socket++)
2177                                         NetConn_WriteString(cl_sockets[socket], "\377\377\377\377status\n", &address);
2178                         }
2179                         else
2180                         {
2181                                 for (socket     = 0; socket     < cl_numsockets ;       socket++)
2182                                         NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getstatus", &address);
2183                         }
2184
2185                         //      update the entry fields
2186                         entry->querytime = realtime;
2187                         entry->querycounter++;
2188
2189                         // if not in the slist menu we should print the server to console
2190                         if (serverlist_consoleoutput)
2191                                 Con_Printf("querying %25s (%i. try)\n", entry->info.cname, entry->querycounter);
2192
2193                         queries++;
2194                 }
2195                 else
2196                 {
2197                         // have we tried to refresh this server?
2198                         if( entry->query == SQS_REFRESHING ) {
2199                                 // yes, so update the reply count (since its not responding anymore)
2200                                 serverreplycount--;
2201                                 if(!serverlist_paused)
2202                                         ServerList_ViewList_Remove(entry);
2203                         }
2204                         entry->query = SQS_TIMEDOUT;
2205                 }
2206         }
2207 }
2208
2209 void NetConn_ClientFrame(void)
2210 {
2211         int i, length;
2212         lhnetaddress_t peeraddress;
2213         NetConn_UpdateSockets();
2214         if (cls.connect_trying && cls.connect_nextsendtime < realtime)
2215         {
2216                 if (cls.connect_remainingtries == 0)
2217                         M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
2218                 cls.connect_nextsendtime = realtime + 1;
2219                 cls.connect_remainingtries--;
2220                 if (cls.connect_remainingtries <= -10)
2221                 {
2222                         cls.connect_trying = false;
2223                         M_Update_Return_Reason("Connect: Failed");
2224                         return;
2225                 }
2226                 // try challenge first (newer DP server or QW)
2227                 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
2228                 // then try netquake as a fallback (old server, or netquake)
2229                 SZ_Clear(&net_message);
2230                 // save space for the header, filled in later
2231                 MSG_WriteLong(&net_message, 0);
2232                 MSG_WriteByte(&net_message, CCREQ_CONNECT);
2233                 MSG_WriteString(&net_message, "QUAKE");
2234                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2235                 // extended proquake stuff
2236                 MSG_WriteByte(&net_message, 1); // mod = MOD_PROQUAKE
2237                 // this version matches ProQuake 3.40, the first version to support
2238                 // the NAT fix, and it only supports the NAT fix for ProQuake 3.40 or
2239                 // higher clients, so we pretend we are that version...
2240                 MSG_WriteByte(&net_message, 34); // version * 10
2241                 MSG_WriteByte(&net_message, 0); // flags
2242                 MSG_WriteLong(&net_message, 0); // password
2243                 // write the packetsize now...
2244                 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2245                 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
2246                 SZ_Clear(&net_message);
2247         }
2248         for (i = 0;i < cl_numsockets;i++)
2249         {
2250                 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2251                 {
2252 //                      R_TimeReport("clientreadnetwork");
2253                         NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
2254 //                      R_TimeReport("clientparsepacket");
2255                 }
2256         }
2257         NetConn_QueryQueueFrame();
2258         if (cls.netcon && realtime > cls.netcon->timeout && !sv.active)
2259         {
2260                 Con_Print("Connection timed out\n");
2261                 CL_Disconnect();
2262                 Host_ShutdownServer ();
2263         }
2264 }
2265
2266 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
2267 {
2268         int i;
2269         char c;
2270         for (i = 0;i < bufferlength - 1;i++)
2271         {
2272                 do
2273                 {
2274                         c = rand () % (127 - 33) + 33;
2275                 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
2276                 buffer[i] = c;
2277         }
2278         buffer[i] = 0;
2279 }
2280
2281 /// (div0) build the full response only if possible; better a getinfo response than no response at all if getstatus won't fit
2282 static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg, size_t out_size, qboolean fullstatus)
2283 {
2284         char qcstatus[256];
2285         unsigned int nb_clients = 0, nb_bots = 0, i;
2286         int length;
2287         char teambuf[3];
2288         const char *crypto_idstring;
2289
2290         SV_VM_Begin();
2291
2292         // How many clients are there?
2293         for (i = 0;i < (unsigned int)svs.maxclients;i++)
2294         {
2295                 if (svs.clients[i].active)
2296                 {
2297                         nb_clients++;
2298                         if (!svs.clients[i].netconnection)
2299                                 nb_bots++;
2300                 }
2301         }
2302
2303         *qcstatus = 0;
2304         if(prog->globaloffsets.worldstatus >= 0)
2305         {
2306                 const char *str = PRVM_G_STRING(prog->globaloffsets.worldstatus);
2307                 if(str && *str)
2308                 {
2309                         char *p;
2310                         const char *q;
2311                         p = qcstatus;
2312                         for(q = str; *q && p - qcstatus < (ptrdiff_t)(sizeof(qcstatus)) - 1; ++q)
2313                                 if(*q != '\\' && *q != '\n')
2314                                         *p++ = *q;
2315                         *p = 0;
2316                 }
2317         }
2318
2319         /// \TODO: we should add more information for the full status string
2320         crypto_idstring = Crypto_GetInfoResponseDataString();
2321         length = dpsnprintf(out_msg, out_size,
2322                                                 "\377\377\377\377%s\x0A"
2323                                                 "\\gamename\\%s\\modname\\%s\\gameversion\\%d\\sv_maxclients\\%d"
2324                                                 "\\clients\\%d\\bots\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d"
2325                                                 "%s%s"
2326                                                 "%s%s"
2327                                                 "%s%s"
2328                                                 "%s",
2329                                                 fullstatus ? "statusResponse" : "infoResponse",
2330                                                 gamename, com_modname, gameversion.integer, svs.maxclients,
2331                                                 nb_clients, nb_bots, sv.worldbasename, hostname.string, NET_PROTOCOL_VERSION,
2332                                                 *qcstatus ? "\\qcstatus\\" : "", qcstatus,
2333                                                 challenge ? "\\challenge\\" : "", challenge ? challenge : "",
2334                                                 crypto_idstring ? "\\d0_blind_id\\" : "", crypto_idstring ? crypto_idstring : "",
2335                                                 fullstatus ? "\n" : "");
2336
2337         // Make sure it fits in the buffer
2338         if (length < 0)
2339                 goto bad;
2340
2341         if (fullstatus)
2342         {
2343                 char *ptr;
2344                 int left;
2345                 int savelength;
2346
2347                 savelength = length;
2348
2349                 ptr = out_msg + length;
2350                 left = (int)out_size - length;
2351
2352                 for (i = 0;i < (unsigned int)svs.maxclients;i++)
2353                 {
2354                         client_t *cl = &svs.clients[i];
2355                         if (cl->active)
2356                         {
2357                                 int nameind, cleanind, pingvalue;
2358                                 char curchar;
2359                                 char cleanname [sizeof(cl->name)];
2360
2361                                 // Remove all characters '"' and '\' in the player name
2362                                 nameind = 0;
2363                                 cleanind = 0;
2364                                 do
2365                                 {
2366                                         curchar = cl->name[nameind++];
2367                                         if (curchar != '"' && curchar != '\\')
2368                                         {
2369                                                 cleanname[cleanind++] = curchar;
2370                                                 if (cleanind == sizeof(cleanname) - 1)
2371                                                         break;
2372                                         }
2373                                 } while (curchar != '\0');
2374                                 cleanname[cleanind] = 0; // cleanind is always a valid index even at this point
2375
2376                                 pingvalue = (int)(cl->ping * 1000.0f);
2377                                 if(cl->netconnection)
2378                                         pingvalue = bound(1, pingvalue, 9999);
2379                                 else
2380                                         pingvalue = 0;
2381
2382                                 *qcstatus = 0;
2383                                 if(prog->fieldoffsets.clientstatus >= 0)
2384                                 {
2385                                         const char *str = PRVM_E_STRING(PRVM_EDICT_NUM(i + 1), prog->fieldoffsets.clientstatus);
2386                                         if(str && *str)
2387                                         {
2388                                                 char *p;
2389                                                 const char *q;
2390                                                 p = qcstatus;
2391                                                 for(q = str; *q && p != qcstatus + sizeof(qcstatus) - 1; ++q)
2392                                                         if(*q != '\\' && *q != '"' && !ISWHITESPACE(*q))
2393                                                                 *p++ = *q;
2394                                                 *p = 0;
2395                                         }
2396                                 }
2397
2398                                 if ((gamemode == GAME_NEXUIZ || gamemode == GAME_XONOTIC) && (teamplay.integer > 0))
2399                                 {
2400                                         if(cl->frags == -666) // spectator
2401                                                 strlcpy(teambuf, " 0", sizeof(teambuf));
2402                                         else if(cl->colors == 0x44) // red team
2403                                                 strlcpy(teambuf, " 1", sizeof(teambuf));
2404                                         else if(cl->colors == 0xDD) // blue team
2405                                                 strlcpy(teambuf, " 2", sizeof(teambuf));
2406                                         else if(cl->colors == 0xCC) // yellow team
2407                                                 strlcpy(teambuf, " 3", sizeof(teambuf));
2408                                         else if(cl->colors == 0x99) // pink team
2409                                                 strlcpy(teambuf, " 4", sizeof(teambuf));
2410                                         else
2411                                                 strlcpy(teambuf, " 0", sizeof(teambuf));
2412                                 }
2413                                 else
2414                                         *teambuf = 0;
2415
2416                                 // note: team number is inserted according to SoF2 protocol
2417                                 if(*qcstatus)
2418                                         length = dpsnprintf(ptr, left, "%s %d%s \"%s\"\n",
2419                                                                                 qcstatus,
2420                                                                                 pingvalue,
2421                                                                                 teambuf,
2422                                                                                 cleanname);
2423                                 else
2424                                         length = dpsnprintf(ptr, left, "%d %d%s \"%s\"\n",
2425                                                                                 cl->frags,
2426                                                                                 pingvalue,
2427                                                                                 teambuf,
2428                                                                                 cleanname);
2429
2430                                 if(length < 0)
2431                                 {
2432                                         // out of space?
2433                                         // turn it into an infoResponse!
2434                                         out_msg[savelength] = 0;
2435                                         memcpy(out_msg + 4, "infoResponse\x0A", 13);
2436                                         memmove(out_msg + 17, out_msg + 19, savelength - 19);
2437                                         break;
2438                                 }
2439                                 left -= length;
2440                                 ptr += length;
2441                         }
2442                 }
2443         }
2444
2445         SV_VM_End();
2446         return true;
2447
2448 bad:
2449         SV_VM_End();
2450         return false;
2451 }
2452
2453 static qboolean NetConn_PreventConnectFlood(lhnetaddress_t *peeraddress)
2454 {
2455         int floodslotnum, bestfloodslotnum;
2456         double bestfloodtime;
2457         lhnetaddress_t noportpeeraddress;
2458         // see if this is a connect flood
2459         noportpeeraddress = *peeraddress;
2460         LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2461         bestfloodslotnum = 0;
2462         bestfloodtime = sv.connectfloodaddresses[bestfloodslotnum].lasttime;
2463         for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2464         {
2465                 if (bestfloodtime >= sv.connectfloodaddresses[floodslotnum].lasttime)
2466                 {
2467                         bestfloodtime = sv.connectfloodaddresses[floodslotnum].lasttime;
2468                         bestfloodslotnum = floodslotnum;
2469                 }
2470                 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2471                 {
2472                         // this address matches an ongoing flood address
2473                         if (realtime < sv.connectfloodaddresses[floodslotnum].lasttime + net_connectfloodblockingtimeout.value)
2474                         {
2475                                 // renew the ban on this address so it does not expire
2476                                 // until the flood has subsided
2477                                 sv.connectfloodaddresses[floodslotnum].lasttime = realtime;
2478                                 //Con_Printf("Flood detected!\n");
2479                                 return true;
2480                         }
2481                         // the flood appears to have subsided, so allow this
2482                         bestfloodslotnum = floodslotnum; // reuse the same slot
2483                         break;
2484                 }
2485         }
2486         // begin a new timeout on this address
2487         sv.connectfloodaddresses[bestfloodslotnum].address = noportpeeraddress;
2488         sv.connectfloodaddresses[bestfloodslotnum].lasttime = realtime;
2489         //Con_Printf("Flood detection initiated!\n");
2490         return false;
2491 }
2492
2493 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress)
2494 {
2495         int floodslotnum;
2496         lhnetaddress_t noportpeeraddress;
2497         // see if this is a connect flood
2498         noportpeeraddress = *peeraddress;
2499         LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2500         for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2501         {
2502                 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2503                 {
2504                         // this address matches an ongoing flood address
2505                         // remove the ban
2506                         sv.connectfloodaddresses[floodslotnum].address.addresstype = LHNETADDRESSTYPE_NONE;
2507                         sv.connectfloodaddresses[floodslotnum].lasttime = 0;
2508                         //Con_Printf("Flood cleared!\n");
2509                 }
2510         }
2511 }
2512
2513 typedef qboolean (*rcon_matchfunc_t) (lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen);
2514
2515 qboolean hmac_mdfour_time_matching(lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen)
2516 {
2517         char mdfourbuf[16];
2518         long t1, t2;
2519
2520         t1 = (long) time(NULL);
2521         t2 = strtol(s, NULL, 0);
2522         if(abs(t1 - t2) > rcon_secure_maxdiff.integer)
2523                 return false;
2524
2525         if(!HMAC_MDFOUR_16BYTES((unsigned char *) mdfourbuf, (unsigned char *) s, slen, (unsigned char *) password, strlen(password)))
2526                 return false;
2527
2528         return !memcmp(mdfourbuf, hash, 16);
2529 }
2530
2531 qboolean hmac_mdfour_challenge_matching(lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen)
2532 {
2533         char mdfourbuf[16];
2534         int i;
2535
2536         if(slen < (int)(sizeof(challenge[0].string)) - 1)
2537                 return false;
2538
2539         // validate the challenge
2540         for (i = 0;i < MAX_CHALLENGES;i++)
2541                 if(challenge[i].time > 0)
2542                         if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strncmp(challenge[i].string, s, sizeof(challenge[0].string) - 1))
2543                                 break;
2544         // if the challenge is not recognized, drop the packet
2545         if (i == MAX_CHALLENGES)
2546                 return false;
2547
2548         if(!HMAC_MDFOUR_16BYTES((unsigned char *) mdfourbuf, (unsigned char *) s, slen, (unsigned char *) password, strlen(password)))
2549                 return false;
2550
2551         if(memcmp(mdfourbuf, hash, 16))
2552                 return false;
2553
2554         // unmark challenge to prevent replay attacks
2555         challenge[i].time = 0;
2556
2557         return true;
2558 }
2559
2560 qboolean plaintext_matching(lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen)
2561 {
2562         return !strcmp(password, hash);
2563 }
2564
2565 /// returns a string describing the user level, or NULL for auth failure
2566 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)
2567 {
2568         const char *text, *userpass_start, *userpass_end, *userpass_startpass;
2569         static char buf[MAX_INPUTLINE];
2570         qboolean hasquotes;
2571         qboolean restricted = false;
2572         qboolean have_usernames = false;
2573
2574         userpass_start = rcon_password.string;
2575         while((userpass_end = strchr(userpass_start, ' ')))
2576         {
2577                 have_usernames = true;
2578                 strlcpy(buf, userpass_start, ((size_t)(userpass_end-userpass_start) >= sizeof(buf)) ? (int)(sizeof(buf)) : (int)(userpass_end-userpass_start+1));
2579                 if(buf[0])
2580                         if(comparator(peeraddress, buf, password, cs, cslen))
2581                                 goto allow;
2582                 userpass_start = userpass_end + 1;
2583         }
2584         if(userpass_start[0])
2585         {
2586                 userpass_end = userpass_start + strlen(userpass_start);
2587                 if(comparator(peeraddress, userpass_start, password, cs, cslen))
2588                         goto allow;
2589         }
2590
2591         restricted = true;
2592         have_usernames = false;
2593         userpass_start = rcon_restricted_password.string;
2594         while((userpass_end = strchr(userpass_start, ' ')))
2595         {
2596                 have_usernames = true;
2597                 strlcpy(buf, userpass_start, ((size_t)(userpass_end-userpass_start) >= sizeof(buf)) ? (int)(sizeof(buf)) : (int)(userpass_end-userpass_start+1));
2598                 if(buf[0])
2599                         if(comparator(peeraddress, buf, password, cs, cslen))
2600                                 goto check;
2601                 userpass_start = userpass_end + 1;
2602         }
2603         if(userpass_start[0])
2604         {
2605                 userpass_end = userpass_start + strlen(userpass_start);
2606                 if(comparator(peeraddress, userpass_start, password, cs, cslen))
2607                         goto check;
2608         }
2609         
2610         return NULL; // DENIED
2611
2612 check:
2613         for(text = s; text != endpos; ++text)
2614                 if((signed char) *text > 0 && ((signed char) *text < (signed char) ' ' || *text == ';'))
2615                         return NULL; // block possible exploits against the parser/alias expansion
2616
2617         while(s != endpos)
2618         {
2619                 size_t l = strlen(s);
2620                 if(l)
2621                 {
2622                         hasquotes = (strchr(s, '"') != NULL);
2623                         // sorry, we can't allow these substrings in wildcard expressions,
2624                         // as they can mess with the argument counts
2625                         text = rcon_restricted_commands.string;
2626                         while(COM_ParseToken_Console(&text))
2627                         {
2628                                 // com_token now contains a pattern to check for...
2629                                 if(strchr(com_token, '*') || strchr(com_token, '?')) // wildcard expression, * can only match a SINGLE argument
2630                                 {
2631                                         if(!hasquotes)
2632                                                 if(matchpattern_with_separator(s, com_token, true, " ", true)) // note how we excluded tab, newline etc. above
2633                                                         goto match;
2634                                 }
2635                                 else if(strchr(com_token, ' ')) // multi-arg expression? must match in whole
2636                                 {
2637                                         if(!strcmp(com_token, s))
2638                                                 goto match;
2639                                 }
2640                                 else // single-arg expression? must match the beginning of the command
2641                                 {
2642                                         if(!strcmp(com_token, s))
2643                                                 goto match;
2644                                         if(!memcmp(va("%s ", com_token), s, strlen(com_token) + 1))
2645                                                 goto match;
2646                                 }
2647                         }
2648                         // if we got here, nothing matched!
2649                         return NULL;
2650                 }
2651 match:
2652                 s += l + 1;
2653         }
2654
2655 allow:
2656         userpass_startpass = strchr(userpass_start, ':');
2657         if(have_usernames && userpass_startpass && userpass_startpass < userpass_end)
2658                 return va("%srcon (username %.*s)", restricted ? "restricted " : "", (int)(userpass_startpass-userpass_start), userpass_start);
2659
2660         return va("%srcon", restricted ? "restricted " : "");
2661 }
2662
2663 void RCon_Execute(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, const char *addressstring2, const char *userlevel, const char *s, const char *endpos, qboolean proquakeprotocol)
2664 {
2665         if(userlevel)
2666         {
2667                 // looks like a legitimate rcon command with the correct password
2668                 const char *s_ptr = s;
2669                 Con_Printf("server received %s command from %s: ", userlevel, host_client ? host_client->name : addressstring2);
2670                 while(s_ptr != endpos)
2671                 {
2672                         size_t l = strlen(s_ptr);
2673                         if(l)
2674                                 Con_Printf(" %s;", s_ptr);
2675                         s_ptr += l + 1;
2676                 }
2677                 Con_Printf("\n");
2678
2679                 if (!host_client || !host_client->netconnection || LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2680                         Con_Rcon_Redirect_Init(mysocket, peeraddress, proquakeprotocol);
2681                 while(s != endpos)
2682                 {
2683                         size_t l = strlen(s);
2684                         if(l)
2685                         {
2686                                 client_t *host_client_save = host_client;
2687                                 Cmd_ExecuteString(s, src_command);
2688                                 host_client = host_client_save;
2689                                 // in case it is a command that changes host_client (like restart)
2690                         }
2691                         s += l + 1;
2692                 }
2693                 Con_Rcon_Redirect_End();
2694         }
2695         else
2696         {
2697                 Con_Printf("server denied rcon access to %s\n", host_client ? host_client->name : addressstring2);
2698         }
2699 }
2700
2701 extern void SV_SendServerinfo (client_t *client);
2702 static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
2703 {
2704         int i, ret, clientnum, best;
2705         double besttime;
2706         client_t *client;
2707         char *s, *string, response[1400], addressstring2[128];
2708         static char stringbuf[16384];
2709         qboolean islocal = (LHNETADDRESS_GetAddressType(peeraddress) == LHNETADDRESSTYPE_LOOP);
2710         char senddata[NET_HEADERSIZE+NET_MAXMESSAGE+CRYPTO_HEADERSIZE];
2711         size_t sendlength, response_len;
2712
2713         if (!sv.active)
2714                 return false;
2715
2716         // convert the address to a string incase we need it
2717         LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
2718
2719         // see if we can identify the sender as a local player
2720         // (this is necessary for rcon to send a reliable reply if the client is
2721         //  actually on the server, not sending remotely)
2722         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2723                 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
2724                         break;
2725         if (i == svs.maxclients)
2726                 host_client = NULL;
2727
2728         if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
2729         {
2730                 // received a command string - strip off the packaging and put it
2731                 // into our string buffer with NULL termination
2732                 data += 4;
2733                 length -= 4;
2734                 length = min(length, (int)sizeof(stringbuf) - 1);
2735                 memcpy(stringbuf, data, length);
2736                 stringbuf[length] = 0;
2737                 string = stringbuf;
2738
2739                 if (developer_extra.integer)
2740                 {
2741                         Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
2742                         Com_HexDumpToConsole(data, length);
2743                 }
2744
2745                 sendlength = sizeof(senddata) - 4;
2746                 switch(Crypto_ServerParsePacket(string, length, senddata+4, &sendlength, peeraddress))
2747                 {
2748                         case CRYPTO_NOMATCH:
2749                                 // nothing to do
2750                                 break;
2751                         case CRYPTO_MATCH:
2752                                 if(sendlength)
2753                                 {
2754                                         memcpy(senddata, "\377\377\377\377", 4);
2755                                         NetConn_Write(mysocket, senddata, sendlength+4, peeraddress);
2756                                 }
2757                                 break;
2758                         case CRYPTO_DISCARD:
2759                                 if(sendlength)
2760                                 {
2761                                         memcpy(senddata, "\377\377\377\377", 4);
2762                                         NetConn_Write(mysocket, senddata, sendlength+4, peeraddress);
2763                                 }
2764                                 return true;
2765                                 break;
2766                         case CRYPTO_REPLACE:
2767                                 string = senddata+4;
2768                                 length = sendlength;
2769                                 break;
2770                 }
2771
2772                 if (length >= 12 && !memcmp(string, "getchallenge", 12) && (islocal || sv_public.integer > -3))
2773                 {
2774                         for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
2775                         {
2776                                 if(challenge[i].time > 0)
2777                                         if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
2778                                                 break;
2779                                 if (besttime > challenge[i].time)
2780                                         besttime = challenge[best = i].time;
2781                         }
2782                         // if we did not find an exact match, choose the oldest and
2783                         // update address and string
2784                         if (i == MAX_CHALLENGES)
2785                         {
2786                                 i = best;
2787                                 challenge[i].address = *peeraddress;
2788                                 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
2789                         }
2790                         challenge[i].time = realtime;
2791                         // send the challenge
2792                         dpsnprintf(response, sizeof(response), "\377\377\377\377challenge %s", challenge[i].string);
2793                         response_len = strlen(response) + 1;
2794                         Crypto_ServerAppendToChallenge(string, length, response, &response_len, sizeof(response));
2795                         NetConn_Write(mysocket, response, response_len, peeraddress);
2796                         return true;
2797                 }
2798                 if (length > 8 && !memcmp(string, "connect\\", 8))
2799                 {
2800                         crypto_t *crypto = Crypto_ServerGetInstance(peeraddress);
2801                         string += 7;
2802                         length -= 7;
2803
2804                         if(crypto && crypto->authenticated)
2805                         {
2806                                 // no need to check challenge
2807                                 if(crypto_developer.integer)
2808                                 {
2809                                         Con_Printf("%s connection to %s is being established: client is %s@%.*s, I am %.*s@%.*s\n",
2810                                                         crypto->use_aes ? "Encrypted" : "Authenticated",
2811                                                         addressstring2,
2812                                                         crypto->client_idfp[0] ? crypto->client_idfp : "-",
2813                                                         crypto_keyfp_recommended_length, crypto->client_keyfp[0] ? crypto->client_keyfp : "-",
2814                                                         crypto_keyfp_recommended_length, crypto->server_idfp[0] ? crypto->server_idfp : "-",
2815                                                         crypto_keyfp_recommended_length, crypto->server_keyfp[0] ? crypto->server_keyfp : "-"
2816                                                   );
2817                                 }
2818                         }
2819                         else
2820                         {
2821                                 if ((s = SearchInfostring(string, "challenge")))
2822                                 {
2823                                         // validate the challenge
2824                                         for (i = 0;i < MAX_CHALLENGES;i++)
2825                                                 if(challenge[i].time > 0)
2826                                                         if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
2827                                                                 break;
2828                                         // if the challenge is not recognized, drop the packet
2829                                         if (i == MAX_CHALLENGES)
2830                                                 return true;
2831                                 }
2832                         }
2833
2834                         if((s = SearchInfostring(string, "message")))
2835                                 Con_DPrintf("Connecting client %s sent us the message: %s\n", addressstring2, s);
2836
2837                         if(!(islocal || sv_public.integer > -2))
2838                         {
2839                                 if (developer_extra.integer)
2840                                         Con_Printf("Datagram_ParseConnectionless: sending \"reject %s\" to %s.\n", sv_public_rejectreason.string, addressstring2);
2841                                 NetConn_WriteString(mysocket, va("\377\377\377\377reject %s", sv_public_rejectreason.string), peeraddress);
2842                                 return true;
2843                         }
2844
2845                         // check engine protocol
2846                         if(!(s = SearchInfostring(string, "protocol")) || strcmp(s, "darkplaces 3"))
2847                         {
2848                                 if (developer_extra.integer)
2849                                         Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
2850                                 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
2851                                 return true;
2852                         }
2853
2854                         // see if this is a duplicate connection request or a disconnected
2855                         // client who is rejoining to the same client slot
2856                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2857                         {
2858                                 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2859                                 {
2860                                         // this is a known client...
2861                                         if(crypto && crypto->authenticated)
2862                                         {
2863                                                 // reject if changing key!
2864                                                 if(client->netconnection->crypto.authenticated)
2865                                                 {
2866                                                         if(
2867                                                                         strcmp(client->netconnection->crypto.client_idfp, crypto->client_idfp)
2868                                                                         ||
2869                                                                         strcmp(client->netconnection->crypto.server_idfp, crypto->server_idfp)
2870                                                                         ||
2871                                                                         strcmp(client->netconnection->crypto.client_keyfp, crypto->client_keyfp)
2872                                                                         ||