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