]> icculus.org git repositories - divverent/darkplaces.git/blob - netconn.c
fix two compile errors in cg shader
[divverent/darkplaces.git] / netconn.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3 Copyright (C) 2002 Mathieu Olivier
4 Copyright (C) 2003 Forest Hale
5
6 This program is free software; you can redistribute it and/or
7 modify it under the terms of the GNU General Public License
8 as published by the Free Software Foundation; either version 2
9 of the License, or (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14
15 See the GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
20
21 */
22
23 #include "quakedef.h"
24 #include "lhnet.h"
25
26 // for secure rcon authentication
27 #include "hmac.h"
28 #include "mdfour.h"
29 #include <time.h>
30
31 #define QWMASTER_PORT 27000
32 #define DPMASTER_PORT 27950
33
34 // note this defaults on for dedicated servers, off for listen servers
35 cvar_t sv_public = {0, "sv_public", "0", "1: advertises this server on the master server (so that players can find it in the server browser); 0: allow direct queries only; -1: do not respond to direct queries; -2: do not allow anyone to connect"};
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 unsigned short 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] = (int)(entry - serverlist_cache);
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_GetViewEntry(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_GetViewEntry(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_GetViewEntry(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_GetViewEntry(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 = 0, j;
1605                         for (j = 0;j < MAX_RCONS;j++)
1606                         {
1607                                 // note: this value from i is used outside the loop too...
1608                                 i = (cls.rcon_ringpos + j) % MAX_RCONS;
1609                                 if(cls.rcon_commands[i][0])
1610                                         if (!LHNETADDRESS_Compare(peeraddress, &cls.rcon_addresses[i]))
1611                                                 break;
1612                         }
1613                         if (j < MAX_RCONS)
1614                         {
1615                                 char buf[1500];
1616                                 char argbuf[1500];
1617                                 const char *e;
1618                                 int n;
1619                                 dpsnprintf(argbuf, sizeof(argbuf), "%s %s", string + 10, cls.rcon_commands[i]);
1620                                 memcpy(buf, "\377\377\377\377srcon HMAC-MD4 CHALLENGE ", 29);
1621
1622                                 e = strchr(rcon_password.string, ' ');
1623                                 n = e ? e-rcon_password.string : (int)strlen(rcon_password.string);
1624
1625                                 if(HMAC_MDFOUR_16BYTES((unsigned char *) (buf + 29), (unsigned char *) argbuf, strlen(argbuf), (unsigned char *) rcon_password.string, n))
1626                                 {
1627                                         int k;
1628                                         buf[45] = ' ';
1629                                         strlcpy(buf + 46, argbuf, sizeof(buf) - 46);
1630                                         NetConn_Write(mysocket, buf, 46 + strlen(buf + 46), peeraddress);
1631                                         cls.rcon_commands[i][0] = 0;
1632                                         --cls.rcon_trying;
1633
1634                                         for (k = 0;k < MAX_RCONS;k++)
1635                                                 if(cls.rcon_commands[k][0])
1636                                                         if (!LHNETADDRESS_Compare(peeraddress, &cls.rcon_addresses[k]))
1637                                                                 break;
1638                                         if(k < MAX_RCONS)
1639                                         {
1640                                                 int l;
1641                                                 NetConn_WriteString(mysocket, "\377\377\377\377getchallenge", peeraddress);
1642                                                 // extend the timeout on other requests as we asked for a challenge
1643                                                 for (l = 0;l < MAX_RCONS;l++)
1644                                                         if(cls.rcon_commands[l][0])
1645                                                                 if (!LHNETADDRESS_Compare(peeraddress, &cls.rcon_addresses[l]))
1646                                                                         cls.rcon_timeout[l] = realtime + rcon_secure_challengetimeout.value;
1647                                         }
1648
1649                                         return true; // we used up the challenge, so we can't use this oen for connecting now anyway
1650                                 }
1651                         }
1652                 }
1653                 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
1654                 {
1655                         // darkplaces or quake3
1656                         char protocolnames[1400];
1657                         Protocol_Names(protocolnames, sizeof(protocolnames));
1658                         Con_DPrintf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
1659                         M_Update_Return_Reason("Got challenge response");
1660                         // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1661                         InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1662                         // TODO: add userinfo stuff here instead of using NQ commands?
1663                         NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\protocols\\%s\\challenge\\%s", protocolnames, string + 10), peeraddress);
1664                         return true;
1665                 }
1666                 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
1667                 {
1668                         // darkplaces or quake3
1669                         M_Update_Return_Reason("Accepted");
1670                         NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_DARKPLACES3);
1671                         return true;
1672                 }
1673                 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
1674                 {
1675                         char rejectreason[32];
1676                         cls.connect_trying = false;
1677                         string += 7;
1678                         length = min(length - 7, (int)sizeof(rejectreason) - 1);
1679                         memcpy(rejectreason, string, length);
1680                         rejectreason[length] = 0;
1681                         M_Update_Return_Reason(rejectreason);
1682                         return true;
1683                 }
1684                 if (length >= 15 && !memcmp(string, "statusResponse\x0A", 15))
1685                 {
1686                         serverlist_info_t *info;
1687                         char *p;
1688                         int n;
1689
1690                         string += 15;
1691                         // search the cache for this server and update it
1692                         n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1693                         if (n < 0)
1694                                 return true;
1695
1696                         info = &serverlist_cache[n].info;
1697                         info->game[0] = 0;
1698                         info->mod[0]  = 0;
1699                         info->map[0]  = 0;
1700                         info->name[0] = 0;
1701                         info->qcstatus[0] = 0;
1702                         info->players[0] = 0;
1703                         info->protocol = -1;
1704                         info->numplayers = 0;
1705                         info->numbots = -1;
1706                         info->maxplayers  = 0;
1707                         info->gameversion = 0;
1708
1709                         p = strchr(string, '\n');
1710                         if(p)
1711                         {
1712                                 *p = 0; // cut off the string there
1713                                 ++p;
1714                         }
1715                         else
1716                                 Con_Printf("statusResponse without players block?\n");
1717
1718                         if ((s = SearchInfostring(string, "gamename"     )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1719                         if ((s = SearchInfostring(string, "modname"      )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1720                         if ((s = SearchInfostring(string, "mapname"      )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1721                         if ((s = SearchInfostring(string, "hostname"     )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1722                         if ((s = SearchInfostring(string, "protocol"     )) != NULL) info->protocol = atoi(s);
1723                         if ((s = SearchInfostring(string, "clients"      )) != NULL) info->numplayers = atoi(s);
1724                         if ((s = SearchInfostring(string, "bots"         )) != NULL) info->numbots = atoi(s);
1725                         if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1726                         if ((s = SearchInfostring(string, "gameversion"  )) != NULL) info->gameversion = atoi(s);
1727                         if ((s = SearchInfostring(string, "qcstatus"     )) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1728                         if (p                                               != NULL) strlcpy(info->players, p, sizeof(info->players));
1729                         info->numhumans = info->numplayers - max(0, info->numbots);
1730                         info->freeslots = info->maxplayers - info->numplayers;
1731
1732                         NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1733
1734                         return true;
1735                 }
1736                 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
1737                 {
1738                         serverlist_info_t *info;
1739                         int n;
1740
1741                         string += 13;
1742                         // search the cache for this server and update it
1743                         n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1744                         if (n < 0)
1745                                 return true;
1746
1747                         info = &serverlist_cache[n].info;
1748                         info->game[0] = 0;
1749                         info->mod[0]  = 0;
1750                         info->map[0]  = 0;
1751                         info->name[0] = 0;
1752                         info->qcstatus[0] = 0;
1753                         info->players[0] = 0;
1754                         info->protocol = -1;
1755                         info->numplayers = 0;
1756                         info->numbots = -1;
1757                         info->maxplayers  = 0;
1758                         info->gameversion = 0;
1759
1760                         if ((s = SearchInfostring(string, "gamename"     )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1761                         if ((s = SearchInfostring(string, "modname"      )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1762                         if ((s = SearchInfostring(string, "mapname"      )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1763                         if ((s = SearchInfostring(string, "hostname"     )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1764                         if ((s = SearchInfostring(string, "protocol"     )) != NULL) info->protocol = atoi(s);
1765                         if ((s = SearchInfostring(string, "clients"      )) != NULL) info->numplayers = atoi(s);
1766                         if ((s = SearchInfostring(string, "bots"         )) != NULL) info->numbots = atoi(s);
1767                         if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1768                         if ((s = SearchInfostring(string, "gameversion"  )) != NULL) info->gameversion = atoi(s);
1769                         if ((s = SearchInfostring(string, "qcstatus"     )) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1770                         info->numhumans = info->numplayers - max(0, info->numbots);
1771                         info->freeslots = info->maxplayers - info->numplayers;
1772
1773                         NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1774
1775                         return true;
1776                 }
1777                 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1778                 {
1779                         // Extract the IP addresses
1780                         data += 18;
1781                         length -= 18;
1782                         NetConn_ClientParsePacket_ServerList_ParseDPList(peeraddress, data, length, false);
1783                         return true;
1784                 }
1785                 if (!strncmp(string, "getserversExtResponse", 21) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1786                 {
1787                         // Extract the IP addresses
1788                         data += 21;
1789                         length -= 21;
1790                         NetConn_ClientParsePacket_ServerList_ParseDPList(peeraddress, data, length, true);
1791                         return true;
1792                 }
1793                 if (!memcmp(string, "d\n", 2) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1794                 {
1795                         // Extract the IP addresses
1796                         data += 2;
1797                         length -= 2;
1798                         masterreplycount++;
1799                         if (serverlist_consoleoutput)
1800                                 Con_Printf("received QuakeWorld server list from %s...\n", addressstring2);
1801                         while (length >= 6 && (data[0] != 0xFF || data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF) && data[4] * 256 + data[5] != 0)
1802                         {
1803                                 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[0], data[1], data[2], data[3], data[4] * 256 + data[5]);
1804                                 if (serverlist_consoleoutput && developer_networking.integer)
1805                                         Con_Printf("Requesting info from QuakeWorld server %s\n", ipstring);
1806                                 
1807                                 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, ipstring, false ) ) {
1808                                         break;
1809                                 }
1810
1811                                 // move on to next address in packet
1812                                 data += 6;
1813                                 length -= 6;
1814                         }
1815                         // begin or resume serverlist queries
1816                         serverlist_querysleep = false;
1817                         serverlist_querywaittime = realtime + 3;
1818                         return true;
1819                 }
1820                 if (!strncmp(string, "extResponse ", 12))
1821                 {
1822                         ++cl_net_extresponse_count;
1823                         if(cl_net_extresponse_count > NET_EXTRESPONSE_MAX)
1824                                 cl_net_extresponse_count = NET_EXTRESPONSE_MAX;
1825                         cl_net_extresponse_last = (cl_net_extresponse_last + 1) % NET_EXTRESPONSE_MAX;
1826                         dpsnprintf(cl_net_extresponse[cl_net_extresponse_last], sizeof(cl_net_extresponse[cl_net_extresponse_last]), "\"%s\" %s", addressstring2, string + 12);
1827                         return true;
1828                 }
1829                 if (!strncmp(string, "ping", 4))
1830                 {
1831                         if (developer_extra.integer)
1832                                 Con_DPrintf("Received ping from %s, sending ack\n", addressstring2);
1833                         NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1834                         return true;
1835                 }
1836                 if (!strncmp(string, "ack", 3))
1837                         return true;
1838                 // QuakeWorld compatibility
1839                 if (length > 1 && string[0] == 'c' && (string[1] == '-' || (string[1] >= '0' && string[1] <= '9')) && cls.connect_trying)
1840                 {
1841                         // challenge message
1842                         Con_Printf("challenge %s received, sending QuakeWorld connect request back to %s\n", string + 1, addressstring2);
1843                         M_Update_Return_Reason("Got QuakeWorld challenge response");
1844                         cls.qw_qport = qport.integer;
1845                         // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1846                         InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1847                         NetConn_WriteString(mysocket, va("\377\377\377\377connect %i %i %i \"%s\"\n", 28, cls.qw_qport, atoi(string + 1), cls.userinfo), peeraddress);
1848                         return true;
1849                 }
1850                 if (length >= 1 && string[0] == 'j' && cls.connect_trying)
1851                 {
1852                         // accept message
1853                         M_Update_Return_Reason("QuakeWorld Accepted");
1854                         NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_QUAKEWORLD);
1855                         return true;
1856                 }
1857                 if (length > 2 && !memcmp(string, "n\\", 2))
1858                 {
1859                         serverlist_info_t *info;
1860                         int n;
1861
1862                         // qw server status
1863                         if (serverlist_consoleoutput && developer_networking.integer >= 2)
1864                                 Con_Printf("QW server status from server at %s:\n%s\n", addressstring2, string + 1);
1865
1866                         string += 1;
1867                         // search the cache for this server and update it
1868                         n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1869                         if (n < 0)
1870                                 return true;
1871
1872                         info = &serverlist_cache[n].info;
1873                         strlcpy(info->game, "QuakeWorld", sizeof(info->game));
1874                         if ((s = SearchInfostring(string, "*gamedir"     )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0]  = 0;
1875                         if ((s = SearchInfostring(string, "map"          )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0]  = 0;
1876                         if ((s = SearchInfostring(string, "hostname"     )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
1877                         info->protocol = 0;
1878                         info->numplayers = 0; // updated below
1879                         info->numhumans = 0; // updated below
1880                         if ((s = SearchInfostring(string, "maxclients"   )) != NULL) info->maxplayers = atoi(s);else info->maxplayers  = 0;
1881                         if ((s = SearchInfostring(string, "gameversion"  )) != NULL) info->gameversion = atoi(s);else info->gameversion = 0;
1882
1883                         // count active players on server
1884                         // (we could gather more info, but we're just after the number)
1885                         s = strchr(string, '\n');
1886                         if (s)
1887                         {
1888                                 s++;
1889                                 while (s < string + length)
1890                                 {
1891                                         for (;s < string + length && *s != '\n';s++)
1892                                                 ;
1893                                         if (s >= string + length)
1894                                                 break;
1895                                         info->numplayers++;
1896                                         info->numhumans++;
1897                                         s++;
1898                                 }
1899                         }
1900
1901                         NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1902
1903                         return true;
1904                 }
1905                 if (string[0] == 'n')
1906                 {
1907                         // qw print command
1908                         Con_Printf("QW print command from server at %s:\n%s\n", addressstring2, string + 1);
1909                 }
1910                 // we may not have liked the packet, but it was a command packet, so
1911                 // we're done processing this packet now
1912                 return true;
1913         }
1914         // quakeworld ingame packet
1915         if (fromserver && cls.protocol == PROTOCOL_QUAKEWORLD && length >= 8 && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1916         {
1917                 ret = 0;
1918                 CL_ParseServerMessage();
1919                 return ret;
1920         }
1921         // netquake control packets, supported for compatibility only
1922         if (length >= 5 && (control = BuffBigLong(data)) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1923         {
1924                 int n;
1925                 serverlist_info_t *info;
1926
1927                 data += 4;
1928                 length -= 4;
1929                 SZ_Clear(&net_message);
1930                 SZ_Write(&net_message, data, length);
1931                 MSG_BeginReading();
1932                 c = MSG_ReadByte();
1933                 switch (c)
1934                 {
1935                 case CCREP_ACCEPT:
1936                         if (developer_extra.integer)
1937                                 Con_DPrintf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1938                         if (cls.connect_trying)
1939                         {
1940                                 lhnetaddress_t clientportaddress;
1941                                 clientportaddress = *peeraddress;
1942                                 LHNETADDRESS_SetPort(&clientportaddress, MSG_ReadLong());
1943                                 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1944                                 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1945                                 M_Update_Return_Reason("Accepted");
1946                                 NetConn_ConnectionEstablished(mysocket, &clientportaddress, PROTOCOL_QUAKE);
1947                         }
1948                         break;
1949                 case CCREP_REJECT:
1950                         if (developer_extra.integer)
1951                                 Con_DPrintf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1952                         cls.connect_trying = false;
1953                         M_Update_Return_Reason((char *)MSG_ReadString());
1954                         break;
1955                 case CCREP_SERVER_INFO:
1956                         if (developer_extra.integer)
1957                                 Con_DPrintf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1958                         // LordHavoc: because the quake server may report weird addresses
1959                         // we just ignore it and keep the real address
1960                         MSG_ReadString();
1961                         // search the cache for this server and update it
1962                         n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1963                         if (n < 0)
1964                                 break;
1965
1966                         info = &serverlist_cache[n].info;
1967                         strlcpy(info->game, "Quake", sizeof(info->game));
1968                         strlcpy(info->mod , "", sizeof(info->mod)); // mod name is not specified
1969                         strlcpy(info->name, MSG_ReadString(), sizeof(info->name));
1970                         strlcpy(info->map , MSG_ReadString(), sizeof(info->map));
1971                         info->numplayers = MSG_ReadByte();
1972                         info->maxplayers = MSG_ReadByte();
1973                         info->protocol = MSG_ReadByte();
1974
1975                         NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1976
1977                         break;
1978                 case CCREP_RCON: // RocketGuy: ProQuake rcon support
1979                         if (developer_extra.integer)
1980                                 Con_DPrintf("Datagram_ParseConnectionless: received CCREP_RCON from %s.\n", addressstring2);
1981
1982                         Con_Printf("%s\n", MSG_ReadString());
1983                         break;
1984                 case CCREP_PLAYER_INFO:
1985                         // we got a CCREP_PLAYER_INFO??
1986                         //if (developer_extra.integer)
1987                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1988                         break;
1989                 case CCREP_RULE_INFO:
1990                         // we got a CCREP_RULE_INFO??
1991                         //if (developer_extra.integer)
1992                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1993                         break;
1994                 default:
1995                         break;
1996                 }
1997                 SZ_Clear(&net_message);
1998                 // we may not have liked the packet, but it was a valid control
1999                 // packet, so we're done processing this packet now
2000                 return true;
2001         }
2002         ret = 0;
2003         if (fromserver && length >= (int)NET_HEADERSIZE && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
2004                 CL_ParseServerMessage();
2005         return ret;
2006 }
2007
2008 void NetConn_QueryQueueFrame(void)
2009 {
2010         int index;
2011         int queries;
2012         int maxqueries;
2013         double timeouttime;
2014         static double querycounter = 0;
2015
2016         if(!net_slist_pause.integer && serverlist_paused)
2017                 ServerList_RebuildViewList();
2018         serverlist_paused = net_slist_pause.integer != 0;
2019
2020         if (serverlist_querysleep)
2021                 return;
2022
2023         // apply a cool down time after master server replies,
2024         // to avoid messing up the ping times on the servers
2025         if (serverlist_querywaittime > realtime)
2026                 return;
2027
2028         // each time querycounter reaches 1.0 issue a query
2029         querycounter += cl.realframetime * net_slist_queriespersecond.value;
2030         maxqueries = (int)querycounter;
2031         maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer);
2032         querycounter -= maxqueries;
2033
2034         if( maxqueries == 0 ) {
2035                 return;
2036         }
2037
2038         //      scan serverlist and issue queries as needed
2039         serverlist_querysleep = true;
2040
2041         timeouttime     = realtime - net_slist_timeout.value;
2042         for( index = 0, queries = 0 ;   index   < serverlist_cachecount &&      queries < maxqueries    ; index++ )
2043         {
2044                 serverlist_entry_t *entry = &serverlist_cache[ index ];
2045                 if( entry->query != SQS_QUERYING && entry->query != SQS_REFRESHING )
2046                 {
2047                         continue;
2048                 }
2049
2050                 serverlist_querysleep   = false;
2051                 if( entry->querycounter !=      0 && entry->querytime > timeouttime     )
2052                 {
2053                         continue;
2054                 }
2055
2056                 if( entry->querycounter !=      (unsigned) net_slist_maxtries.integer )
2057                 {
2058                         lhnetaddress_t  address;
2059                         int socket;
2060
2061                         LHNETADDRESS_FromString(&address, entry->info.cname, 0);
2062                         if      (entry->protocol == PROTOCOL_QUAKEWORLD)
2063                         {
2064                                 for (socket     = 0; socket     < cl_numsockets ;       socket++)
2065                                         NetConn_WriteString(cl_sockets[socket], "\377\377\377\377status\n", &address);
2066                         }
2067                         else
2068                         {
2069                                 for (socket     = 0; socket     < cl_numsockets ;       socket++)
2070                                         NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getstatus", &address);
2071                         }
2072
2073                         //      update the entry fields
2074                         entry->querytime = realtime;
2075                         entry->querycounter++;
2076
2077                         // if not in the slist menu we should print the server to console
2078                         if (serverlist_consoleoutput)
2079                                 Con_Printf("querying %25s (%i. try)\n", entry->info.cname, entry->querycounter);
2080
2081                         queries++;
2082                 }
2083                 else
2084                 {
2085                         // have we tried to refresh this server?
2086                         if( entry->query == SQS_REFRESHING ) {
2087                                 // yes, so update the reply count (since its not responding anymore)
2088                                 serverreplycount--;
2089                                 if(!serverlist_paused)
2090                                         ServerList_ViewList_Remove(entry);
2091                         }
2092                         entry->query = SQS_TIMEDOUT;
2093                 }
2094         }
2095 }
2096
2097 void NetConn_ClientFrame(void)
2098 {
2099         int i, length;
2100         lhnetaddress_t peeraddress;
2101         NetConn_UpdateSockets();
2102         if (cls.connect_trying && cls.connect_nextsendtime < realtime)
2103         {
2104                 if (cls.connect_remainingtries == 0)
2105                         M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
2106                 cls.connect_nextsendtime = realtime + 1;
2107                 cls.connect_remainingtries--;
2108                 if (cls.connect_remainingtries <= -10)
2109                 {
2110                         cls.connect_trying = false;
2111                         M_Update_Return_Reason("Connect: Failed");
2112                         return;
2113                 }
2114                 // try challenge first (newer DP server or QW)
2115                 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
2116                 // then try netquake as a fallback (old server, or netquake)
2117                 SZ_Clear(&net_message);
2118                 // save space for the header, filled in later
2119                 MSG_WriteLong(&net_message, 0);
2120                 MSG_WriteByte(&net_message, CCREQ_CONNECT);
2121                 MSG_WriteString(&net_message, "QUAKE");
2122                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2123                 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2124                 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
2125                 SZ_Clear(&net_message);
2126         }
2127         for (i = 0;i < cl_numsockets;i++)
2128                 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2129                         NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
2130         NetConn_QueryQueueFrame();
2131         if (cls.netcon && realtime > cls.netcon->timeout && !sv.active)
2132         {
2133                 Con_Print("Connection timed out\n");
2134                 CL_Disconnect();
2135                 Host_ShutdownServer ();
2136         }
2137 }
2138
2139 #define MAX_CHALLENGES 128
2140 struct challenge_s
2141 {
2142         lhnetaddress_t address;
2143         double time;
2144         char string[12];
2145 }
2146 challenge[MAX_CHALLENGES];
2147
2148 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
2149 {
2150         int i;
2151         char c;
2152         for (i = 0;i < bufferlength - 1;i++)
2153         {
2154                 do
2155                 {
2156                         c = rand () % (127 - 33) + 33;
2157                 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
2158                 buffer[i] = c;
2159         }
2160         buffer[i] = 0;
2161 }
2162
2163 /// (div0) build the full response only if possible; better a getinfo response than no response at all if getstatus won't fit
2164 static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg, size_t out_size, qboolean fullstatus)
2165 {
2166         char qcstatus[256];
2167         unsigned int nb_clients = 0, nb_bots = 0, i;
2168         int length;
2169         char teambuf[3];
2170
2171         SV_VM_Begin();
2172
2173         // How many clients are there?
2174         for (i = 0;i < (unsigned int)svs.maxclients;i++)
2175         {
2176                 if (svs.clients[i].active)
2177                 {
2178                         nb_clients++;
2179                         if (!svs.clients[i].netconnection)
2180                                 nb_bots++;
2181                 }
2182         }
2183
2184         *qcstatus = 0;
2185         if(prog->globaloffsets.worldstatus >= 0)
2186         {
2187                 const char *str = PRVM_G_STRING(prog->globaloffsets.worldstatus);
2188                 if(str && *str)
2189                 {
2190                         char *p;
2191                         const char *q;
2192                         p = qcstatus;
2193                         for(q = str; *q; ++q)
2194                                 if(*q != '\\' && *q != '\n')
2195                                         *p++ = *q;
2196                         *p = 0;
2197                 }
2198         }
2199
2200         /// \TODO: we should add more information for the full status string
2201         length = dpsnprintf(out_msg, out_size,
2202                                                 "\377\377\377\377%s\x0A"
2203                                                 "\\gamename\\%s\\modname\\%s\\gameversion\\%d\\sv_maxclients\\%d"
2204                                                 "\\clients\\%d\\bots\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d"
2205                                                 "%s%s"
2206                                                 "%s%s"
2207                                                 "%s",
2208                                                 fullstatus ? "statusResponse" : "infoResponse",
2209                                                 gamename, com_modname, gameversion.integer, svs.maxclients,
2210                                                 nb_clients, nb_bots, sv.name, hostname.string, NET_PROTOCOL_VERSION,
2211                                                 *qcstatus ? "\\qcstatus\\" : "", qcstatus,
2212                                                 challenge ? "\\challenge\\" : "", challenge ? challenge : "",
2213                                                 fullstatus ? "\n" : "");
2214
2215         // Make sure it fits in the buffer
2216         if (length < 0)
2217                 goto bad;
2218
2219         if (fullstatus)
2220         {
2221                 char *ptr;
2222                 int left;
2223                 int savelength;
2224
2225                 savelength = length;
2226
2227                 ptr = out_msg + length;
2228                 left = (int)out_size - length;
2229
2230                 for (i = 0;i < (unsigned int)svs.maxclients;i++)
2231                 {
2232                         client_t *cl = &svs.clients[i];
2233                         if (cl->active)
2234                         {
2235                                 int nameind, cleanind, pingvalue;
2236                                 char curchar;
2237                                 char cleanname [sizeof(cl->name)];
2238
2239                                 // Remove all characters '"' and '\' in the player name
2240                                 nameind = 0;
2241                                 cleanind = 0;
2242                                 do
2243                                 {
2244                                         curchar = cl->name[nameind++];
2245                                         if (curchar != '"' && curchar != '\\')
2246                                         {
2247                                                 cleanname[cleanind++] = curchar;
2248                                                 if (cleanind == sizeof(cleanname) - 1)
2249                                                         break;
2250                                         }
2251                                 } while (curchar != '\0');
2252                                 cleanname[cleanind] = 0; // cleanind is always a valid index even at this point
2253
2254                                 pingvalue = (int)(cl->ping * 1000.0f);
2255                                 if(cl->netconnection)
2256                                         pingvalue = bound(1, pingvalue, 9999);
2257                                 else
2258                                         pingvalue = 0;
2259
2260                                 *qcstatus = 0;
2261                                 if(prog->fieldoffsets.clientstatus >= 0)
2262                                 {
2263                                         const char *str = PRVM_E_STRING(PRVM_EDICT_NUM(i + 1), prog->fieldoffsets.clientstatus);
2264                                         if(str && *str)
2265                                         {
2266                                                 char *p;
2267                                                 const char *q;
2268                                                 p = qcstatus;
2269                                                 for(q = str; *q && p != qcstatus + sizeof(qcstatus) - 1; ++q)
2270                                                         if(*q != '\\' && *q != '"' && !ISWHITESPACE(*q))
2271                                                                 *p++ = *q;
2272                                                 *p = 0;
2273                                         }
2274                                 }
2275
2276                                 if ((gamemode == GAME_NEXUIZ) && (teamplay.integer > 0))
2277                                 {
2278                                         if(cl->frags == -666) // spectator
2279                                                 strlcpy(teambuf, " 0", sizeof(teambuf));
2280                                         else if(cl->colors == 0x44) // red team
2281                                                 strlcpy(teambuf, " 1", sizeof(teambuf));
2282                                         else if(cl->colors == 0xDD) // blue team
2283                                                 strlcpy(teambuf, " 2", sizeof(teambuf));
2284                                         else if(cl->colors == 0xCC) // yellow team
2285                                                 strlcpy(teambuf, " 3", sizeof(teambuf));
2286                                         else if(cl->colors == 0x99) // pink team
2287                                                 strlcpy(teambuf, " 4", sizeof(teambuf));
2288                                         else
2289                                                 strlcpy(teambuf, " 0", sizeof(teambuf));
2290                                 }
2291                                 else
2292                                         *teambuf = 0;
2293
2294                                 // note: team number is inserted according to SoF2 protocol
2295                                 if(*qcstatus)
2296                                         length = dpsnprintf(ptr, left, "%s %d%s \"%s\"\n",
2297                                                                                 qcstatus,
2298                                                                                 pingvalue,
2299                                                                                 teambuf,
2300                                                                                 cleanname);
2301                                 else
2302                                         length = dpsnprintf(ptr, left, "%d %d%s \"%s\"\n",
2303                                                                                 cl->frags,
2304                                                                                 pingvalue,
2305                                                                                 teambuf,
2306                                                                                 cleanname);
2307
2308                                 if(length < 0)
2309                                 {
2310                                         // out of space?
2311                                         // turn it into an infoResponse!
2312                                         out_msg[savelength] = 0;
2313                                         memcpy(out_msg + 4, "infoResponse\x0A", 13);
2314                                         memmove(out_msg + 17, out_msg + 19, savelength - 19);
2315                                         break;
2316                                 }
2317                                 left -= length;
2318                                 ptr += length;
2319                         }
2320                 }
2321         }
2322
2323         SV_VM_End();
2324         return true;
2325
2326 bad:
2327         SV_VM_End();
2328         return false;
2329 }
2330
2331 static qboolean NetConn_PreventConnectFlood(lhnetaddress_t *peeraddress)
2332 {
2333         int floodslotnum, bestfloodslotnum;
2334         double bestfloodtime;
2335         lhnetaddress_t noportpeeraddress;
2336         // see if this is a connect flood
2337         noportpeeraddress = *peeraddress;
2338         LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2339         bestfloodslotnum = 0;
2340         bestfloodtime = sv.connectfloodaddresses[bestfloodslotnum].lasttime;
2341         for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2342         {
2343                 if (bestfloodtime >= sv.connectfloodaddresses[floodslotnum].lasttime)
2344                 {
2345                         bestfloodtime = sv.connectfloodaddresses[floodslotnum].lasttime;
2346                         bestfloodslotnum = floodslotnum;
2347                 }
2348                 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2349                 {
2350                         // this address matches an ongoing flood address
2351                         if (realtime < sv.connectfloodaddresses[floodslotnum].lasttime + net_connectfloodblockingtimeout.value)
2352                         {
2353                                 // renew the ban on this address so it does not expire
2354                                 // until the flood has subsided
2355                                 sv.connectfloodaddresses[floodslotnum].lasttime = realtime;
2356                                 //Con_Printf("Flood detected!\n");
2357                                 return true;
2358                         }
2359                         // the flood appears to have subsided, so allow this
2360                         bestfloodslotnum = floodslotnum; // reuse the same slot
2361                         break;
2362                 }
2363         }
2364         // begin a new timeout on this address
2365         sv.connectfloodaddresses[bestfloodslotnum].address = noportpeeraddress;
2366         sv.connectfloodaddresses[bestfloodslotnum].lasttime = realtime;
2367         //Con_Printf("Flood detection initiated!\n");
2368         return false;
2369 }
2370
2371 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress)
2372 {
2373         int floodslotnum;
2374         lhnetaddress_t noportpeeraddress;
2375         // see if this is a connect flood
2376         noportpeeraddress = *peeraddress;
2377         LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2378         for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2379         {
2380                 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2381                 {
2382                         // this address matches an ongoing flood address
2383                         // remove the ban
2384                         sv.connectfloodaddresses[floodslotnum].address.addresstype = LHNETADDRESSTYPE_NONE;
2385                         sv.connectfloodaddresses[floodslotnum].lasttime = 0;
2386                         //Con_Printf("Flood cleared!\n");
2387                 }
2388         }
2389 }
2390
2391 typedef qboolean (*rcon_matchfunc_t) (lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen);
2392
2393 qboolean hmac_mdfour_time_matching(lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen)
2394 {
2395         char mdfourbuf[16];
2396         long t1, t2;
2397
2398         t1 = (long) time(NULL);
2399         t2 = strtol(s, NULL, 0);
2400         if(abs(t1 - t2) > rcon_secure_maxdiff.integer)
2401                 return false;
2402
2403         if(!HMAC_MDFOUR_16BYTES((unsigned char *) mdfourbuf, (unsigned char *) s, slen, (unsigned char *) password, strlen(password)))
2404                 return false;
2405
2406         return !memcmp(mdfourbuf, hash, 16);
2407 }
2408
2409 qboolean hmac_mdfour_challenge_matching(lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen)
2410 {
2411         char mdfourbuf[16];
2412         int i;
2413
2414         if(slen < (int)(sizeof(challenge[0].string)) - 1)
2415                 return false;
2416
2417         // validate the challenge
2418         for (i = 0;i < MAX_CHALLENGES;i++)
2419                 if(challenge[i].time > 0)
2420                         if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strncmp(challenge[i].string, s, sizeof(challenge[0].string) - 1))
2421                                 break;
2422         // if the challenge is not recognized, drop the packet
2423         if (i == MAX_CHALLENGES)
2424                 return false;
2425
2426         if(!HMAC_MDFOUR_16BYTES((unsigned char *) mdfourbuf, (unsigned char *) s, slen, (unsigned char *) password, strlen(password)))
2427                 return false;
2428
2429         if(memcmp(mdfourbuf, hash, 16))
2430                 return false;
2431
2432         // unmark challenge to prevent replay attacks
2433         challenge[i].time = 0;
2434
2435         return true;
2436 }
2437
2438 qboolean plaintext_matching(lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen)
2439 {
2440         return !strcmp(password, hash);
2441 }
2442
2443 /// returns a string describing the user level, or NULL for auth failure
2444 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)
2445 {
2446         const char *text, *userpass_start, *userpass_end, *userpass_startpass;
2447         static char buf[MAX_INPUTLINE];
2448         qboolean hasquotes;
2449         qboolean restricted = false;
2450         qboolean have_usernames = false;
2451
2452         userpass_start = rcon_password.string;
2453         while((userpass_end = strchr(userpass_start, ' ')))
2454         {
2455                 have_usernames = true;
2456                 strlcpy(buf, userpass_start, ((size_t)(userpass_end-userpass_start) >= sizeof(buf)) ? (int)(sizeof(buf)) : (int)(userpass_end-userpass_start+1));
2457                 if(buf[0])
2458                         if(comparator(peeraddress, buf, password, cs, cslen))
2459                                 goto allow;
2460                 userpass_start = userpass_end + 1;
2461         }
2462         if(userpass_start[0])
2463         {
2464                 userpass_end = userpass_start + strlen(userpass_start);
2465                 if(comparator(peeraddress, userpass_start, password, cs, cslen))
2466                         goto allow;
2467         }
2468
2469         restricted = true;
2470         have_usernames = false;
2471         userpass_start = rcon_restricted_password.string;
2472         while((userpass_end = strchr(userpass_start, ' ')))
2473         {
2474                 have_usernames = true;
2475                 strlcpy(buf, userpass_start, ((size_t)(userpass_end-userpass_start) >= sizeof(buf)) ? (int)(sizeof(buf)) : (int)(userpass_end-userpass_start+1));
2476                 if(buf[0])
2477                         if(comparator(peeraddress, buf, password, cs, cslen))
2478                                 goto check;
2479                 userpass_start = userpass_end + 1;
2480         }
2481         if(userpass_start[0])
2482         {
2483                 userpass_end = userpass_start + strlen(userpass_start);
2484                 if(comparator(peeraddress, userpass_start, password, cs, cslen))
2485                         goto check;
2486         }
2487         
2488         return NULL; // DENIED
2489
2490 check:
2491         for(text = s; text != endpos; ++text)
2492                 if((signed char) *text > 0 && ((signed char) *text < (signed char) ' ' || *text == ';'))
2493                         return NULL; // block possible exploits against the parser/alias expansion
2494
2495         while(s != endpos)
2496         {
2497                 size_t l = strlen(s);
2498                 if(l)
2499                 {
2500                         hasquotes = (strchr(s, '"') != NULL);
2501                         // sorry, we can't allow these substrings in wildcard expressions,
2502                         // as they can mess with the argument counts
2503                         text = rcon_restricted_commands.string;
2504                         while(COM_ParseToken_Console(&text))
2505                         {
2506                                 // com_token now contains a pattern to check for...
2507                                 if(strchr(com_token, '*') || strchr(com_token, '?')) // wildcard expression, * can only match a SINGLE argument
2508                                 {
2509                                         if(!hasquotes)
2510                                                 if(matchpattern_with_separator(s, com_token, true, " ", true)) // note how we excluded tab, newline etc. above
2511                                                         goto match;
2512                                 }
2513                                 else if(strchr(com_token, ' ')) // multi-arg expression? must match in whole
2514                                 {
2515                                         if(!strcmp(com_token, s))
2516                                                 goto match;
2517                                 }
2518                                 else // single-arg expression? must match the beginning of the command
2519                                 {
2520                                         if(!strcmp(com_token, s))
2521                                                 goto match;
2522                                         if(!memcmp(va("%s ", com_token), s, strlen(com_token) + 1))
2523                                                 goto match;
2524                                 }
2525                         }
2526                         // if we got here, nothing matched!
2527                         return NULL;
2528                 }
2529 match:
2530                 s += l + 1;
2531         }
2532
2533 allow:
2534         userpass_startpass = strchr(userpass_start, ':');
2535         if(have_usernames && userpass_startpass && userpass_startpass < userpass_end)
2536                 return va("%srcon (username %.*s)", restricted ? "restricted " : "", (int)(userpass_startpass-userpass_start), userpass_start);
2537
2538         return va("%srcon", restricted ? "restricted " : "");
2539 }
2540
2541 void RCon_Execute(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, const char *addressstring2, const char *userlevel, const char *s, const char *endpos)
2542 {
2543         if(userlevel)
2544         {
2545                 // looks like a legitimate rcon command with the correct password
2546                 const char *s_ptr = s;
2547                 Con_Printf("server received %s command from %s: ", userlevel, host_client ? host_client->name : addressstring2);
2548                 while(s_ptr != endpos)
2549                 {
2550                         size_t l = strlen(s_ptr);
2551                         if(l)
2552                                 Con_Printf(" %s;", s_ptr);
2553                         s_ptr += l + 1;
2554                 }
2555                 Con_Printf("\n");
2556
2557                 if (!host_client || !host_client->netconnection || LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2558                         Con_Rcon_Redirect_Init(mysocket, peeraddress);
2559                 while(s != endpos)
2560                 {
2561                         size_t l = strlen(s);
2562                         if(l)
2563                         {
2564                                 client_t *host_client_save = host_client;
2565                                 Cmd_ExecuteString(s, src_command);
2566                                 host_client = host_client_save;
2567                                 // in case it is a command that changes host_client (like restart)
2568                         }
2569                         s += l + 1;
2570                 }
2571                 Con_Rcon_Redirect_End();
2572         }
2573         else
2574         {
2575                 Con_Printf("server denied rcon access to %s\n", host_client ? host_client->name : addressstring2);
2576         }
2577 }
2578
2579 extern void SV_SendServerinfo (client_t *client);
2580 static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
2581 {
2582         int i, ret, clientnum, best;
2583         double besttime;
2584         client_t *client;
2585         char *s, *string, response[1400], addressstring2[128];
2586         static char stringbuf[16384];
2587         qboolean islocal = (LHNETADDRESS_GetAddressType(peeraddress) == LHNETADDRESSTYPE_LOOP);
2588
2589         if (!sv.active)
2590                 return false;
2591
2592         // convert the address to a string incase we need it
2593         LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
2594
2595         // see if we can identify the sender as a local player
2596         // (this is necessary for rcon to send a reliable reply if the client is
2597         //  actually on the server, not sending remotely)
2598         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2599                 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
2600                         break;
2601         if (i == svs.maxclients)
2602                 host_client = NULL;
2603
2604         if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
2605         {
2606                 // received a command string - strip off the packaging and put it
2607                 // into our string buffer with NULL termination
2608                 data += 4;
2609                 length -= 4;
2610                 length = min(length, (int)sizeof(stringbuf) - 1);
2611                 memcpy(stringbuf, data, length);
2612                 stringbuf[length] = 0;
2613                 string = stringbuf;
2614
2615                 if (developer_extra.integer)
2616                 {
2617                         Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
2618                         Com_HexDumpToConsole(data, length);
2619                 }
2620
2621                 if (length >= 12 && !memcmp(string, "getchallenge", 12) && (islocal || sv_public.integer > -2))
2622                 {
2623                         for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
2624                         {
2625                                 if(challenge[i].time > 0)
2626                                         if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
2627                                                 break;
2628                                 if (besttime > challenge[i].time)
2629                                         besttime = challenge[best = i].time;
2630                         }
2631                         // if we did not find an exact match, choose the oldest and
2632                         // update address and string
2633                         if (i == MAX_CHALLENGES)
2634                         {
2635                                 i = best;
2636                                 challenge[i].address = *peeraddress;
2637                                 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
2638                         }
2639                         challenge[i].time = realtime;
2640                         // send the challenge
2641                         NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
2642                         return true;
2643                 }
2644                 if (length > 8 && !memcmp(string, "connect\\", 8) && (islocal || sv_public.integer > -2))
2645                 {
2646                         string += 7;
2647                         length -= 7;
2648
2649                         if (!(s = SearchInfostring(string, "challenge")))
2650                                 return true;
2651                         // validate the challenge
2652                         for (i = 0;i < MAX_CHALLENGES;i++)
2653                                 if(challenge[i].time > 0)
2654                                         if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
2655                                                 break;
2656                         // if the challenge is not recognized, drop the packet
2657                         if (i == MAX_CHALLENGES)
2658                                 return true;
2659
2660                         // check engine protocol
2661                         if(!(s = SearchInfostring(string, "protocol")) || strcmp(s, "darkplaces 3"))
2662                         {
2663                                 if (developer_extra.integer)
2664                                         Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
2665                                 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
2666                                 return true;
2667                         }
2668
2669                         // see if this is a duplicate connection request or a disconnected
2670                         // client who is rejoining to the same client slot
2671                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2672                         {
2673                                 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2674                                 {
2675                                         // this is a known client...
2676                                         if (client->spawned)
2677                                         {
2678                                                 // client crashed and is coming back,
2679                                                 // keep their stuff intact
2680                                                 if (developer_extra.integer)
2681                                                         Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", addressstring2);
2682                                                 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2683                                                 SV_VM_Begin();
2684                                                 SV_SendServerinfo(client);
2685                                                 SV_VM_End();
2686                                         }
2687                                         else
2688                                         {
2689                                                 // client is still trying to connect,
2690                                                 // so we send a duplicate reply
2691                                                 if (developer_extra.integer)
2692                                                         Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
2693                                                 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2694                                         }
2695                                         return true;
2696                                 }
2697                         }
2698
2699                         if (NetConn_PreventConnectFlood(peeraddress))
2700                                 return true;
2701
2702                         // find an empty client slot for this new client
2703                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2704                         {
2705                                 netconn_t *conn;
2706                                 if (!client->active && (conn = NetConn_Open(mysocket, peeraddress)))
2707                                 {
2708                                         // allocated connection
2709                                         if (developer_extra.integer)
2710                                                 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
2711                                         NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2712                                         // now set up the client
2713                                         SV_VM_Begin();
2714                                         SV_ConnectClient(clientnum, conn);
2715                                         SV_VM_End();
2716                                         NetConn_Heartbeat(1);
2717                                         return true;
2718                                 }
2719                         }
2720
2721                         // no empty slots found - server is full
2722                         if (developer_extra.integer)
2723                                 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
2724                         NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
2725
2726                         return true;
2727                 }
2728                 if (length >= 7 && !memcmp(string, "getinfo", 7) && (islocal || sv_public.integer > -1))
2729                 {
2730                         const char *challenge = NULL;
2731
2732                         // If there was a challenge in the getinfo message
2733                         if (length > 8 && string[7] == ' ')
2734                                 challenge = string + 8;
2735
2736                         if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
2737                         {
2738                                 if (developer_extra.integer)
2739                                         Con_DPrintf("Sending reply to master %s - %s\n", addressstring2, response);
2740                                 NetConn_WriteString(mysocket, response, peeraddress);
2741                         }
2742                         return true;
2743                 }
2744                 if (length >= 9 && !memcmp(string, "getstatus", 9) && (islocal || sv_public.integer > -1))
2745                 {
2746                         const char *challenge = NULL;
2747
2748                         // If there was a challenge in the getinfo message
2749                         if (length > 10 && string[9] == ' ')
2750                                 challenge = string + 10;
2751
2752                         if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
2753                         {
2754                                 if (developer_extra.integer)
2755                                         Con_DPrintf("Sending reply to client %s - %s\n", addressstring2, response);
2756                                 NetConn_WriteString(mysocket, response, peeraddress);
2757                         }
2758                         return true;
2759                 }
2760                 if (length >= 37 && !memcmp(string, "srcon HMAC-MD4 TIME ", 20))
2761                 {
2762                         char *password = string + 20;
2763                         char *timeval = string + 37;
2764                         char *s = strchr(timeval, ' ');
2765                         char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2766                         const char *userlevel;
2767
2768                         if(rcon_secure.integer > 1)
2769                                 return true;
2770
2771                         if(!s)
2772                                 return true; // invalid packet
2773                         ++s;
2774
2775                         userlevel = RCon_Authenticate(peeraddress, password, s, endpos, hmac_mdfour_time_matching, timeval, endpos - timeval - 1); // not including the appended \0 into the HMAC
2776                         RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2777                         return true;
2778                 }
2779                 if (length >= 42 && !memcmp(string, "srcon HMAC-MD4 CHALLENGE ", 25))
2780                 {
2781                         char *password = string + 25;
2782                         char *challenge = string + 42;
2783                         char *s = strchr(challenge, ' ');
2784                         char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2785                         const char *userlevel;
2786                         if(!s)
2787                                 return true; // invalid packet
2788                         ++s;
2789
2790                         userlevel = RCon_Authenticate(peeraddress, password, s, endpos, hmac_mdfour_challenge_matching, challenge, endpos - challenge - 1); // not including the appended \0 into the HMAC
2791                         RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2792                         return true;
2793                 }
2794                 if (length >= 5 && !memcmp(string, "rcon ", 5))
2795                 {
2796                         int i;
2797                         char *s = string + 5;
2798                         char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2799                         char password[64];
2800
2801                         if(rcon_secure.integer > 0)
2802                                 return true;
2803
2804                         for (i = 0;!ISWHITESPACE(*s);s++)
2805                                 if (i < (int)sizeof(password) - 1)
2806                                         password[i++] = *s;
2807                         if(ISWHITESPACE(*s) && s != endpos) // skip leading ugly space
2808                                 ++s;
2809                         password[i] = 0;
2810                         if (!ISWHITESPACE(password[0]))
2811                         {
2812                                 const char *userlevel = RCon_Authenticate(peeraddress, password, s, endpos, plaintext_matching, NULL, 0);
2813                                 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2814                         }
2815                         return true;
2816                 }
2817                 if (!strncmp(string, "extResponse ", 12))
2818                 {
2819                         ++sv_net_extresponse_count;
2820                         if(sv_net_extresponse_count > NET_EXTRESPONSE_MAX)
2821                                 sv_net_extresponse_count = NET_EXTRESPONSE_MAX;
2822                         sv_net_extresponse_last = (sv_net_extresponse_last + 1) % NET_EXTRESPONSE_MAX;
2823                         dpsnprintf(sv_net_extresponse[sv_net_extresponse_last], sizeof(sv_net_extresponse[sv_net_extresponse_last]), "'%s' %s", addressstring2, string + 12);
2824                         return true;
2825                 }
2826                 if (!strncmp(string, "ping", 4))
2827                 {
2828                         if (developer_extra.integer)
2829                                 Con_DPrintf("Received ping from %s, sending ack\n", addressstring2);
2830                         NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
2831                         return true;
2832                 }
2833                 if (!strncmp(string, "ack", 3))
2834                         return true;
2835                 // we may not have liked the packet, but it was a command packet, so
2836                 // we're done processing this packet now
2837                 return true;
2838         }
2839         // netquake control packets, supported for compatibility only, and only
2840         // when running game protocols that are normally served via this connection
2841         // protocol
2842         // (this protects more modern protocols against being used for
2843         //  Quake packet flood Denial Of Service attacks)
2844         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))
2845         {
2846                 int c;
2847                 int protocolnumber;
2848                 const char *protocolname;
2849                 data += 4;
2850                 length -= 4;
2851                 SZ_Clear(&net_message);
2852                 SZ_Write(&net_message, data, length);
2853                 MSG_BeginReading();
2854                 c = MSG_ReadByte();
2855                 switch (c)
2856                 {
2857                 case CCREQ_CONNECT:
2858                         if (developer_extra.integer)
2859                                 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
2860                         if(!islocal && sv_public.integer <= -2)
2861                                 break;
2862
2863                         protocolname = MSG_ReadString();
2864                         protocolnumber = MSG_ReadByte();
2865                         if (strcmp(protocolname, "QUAKE") || protocolnumber != NET_PROTOCOL_VERSION)
2866                         {
2867                                 if (developer_extra.integer)
2868                                         Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
2869                                 SZ_Clear(&net_message);
2870                                 // save space for the header, filled in later
2871                                 MSG_WriteLong(&net_message, 0);
2872                                 MSG_WriteByte(&net_message, CCREP_REJECT);
2873                                 MSG_WriteString(&net_message, "Incompatible version.\n");
2874                                 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2875                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2876                                 SZ_Clear(&net_message);
2877                                 break;
2878                         }
2879
2880                         // see if this connect request comes from a known client
2881                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2882                         {
2883                                 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2884                                 {
2885                                         // this is either a duplicate connection request
2886                                         // or coming back from a timeout
2887                                         // (if so, keep their stuff intact)
2888
2889                                         // send a reply
2890                                         if (developer_extra.integer)
2891                                                 Con_DPrintf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
2892                                         SZ_Clear(&net_message);
2893                                         // save space for the header, filled in later
2894                                         MSG_WriteLong(&net_message, 0);
2895                                         MSG_WriteByte(&net_message, CCREP_ACCEPT);
2896                                         MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
2897                                         StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2898                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2899                                         SZ_Clear(&net_message);
2900
2901                                         // if client is already spawned, re-send the
2902                                         // serverinfo message as they'll need it to play
2903                                         if (client->spawned)
2904                                         {
2905                                                 SV_VM_Begin();
2906                                                 SV_SendServerinfo(client);
2907                                                 SV_VM_End();
2908                                         }
2909                                         return true;
2910                                 }
2911                         }
2912
2913                         // this is a new client, check for connection flood
2914                         if (NetConn_PreventConnectFlood(peeraddress))
2915                                 break;
2916
2917                         // find a slot for the new client
2918                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2919                         {
2920                                 netconn_t *conn;
2921                                 if (!client->active && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
2922                                 {
2923                                         // connect to the client
2924                                         // everything is allocated, just fill in the details
2925                                         strlcpy (conn->address, addressstring2, sizeof (conn->address));
2926                                         if (developer_extra.integer)
2927                                                 Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
2928                                         // send back the info about the server connection
2929                                         SZ_Clear(&net_message);
2930                                         // save space for the header, filled in later
2931                                         MSG_WriteLong(&net_message, 0);
2932                                         MSG_WriteByte(&net_message, CCREP_ACCEPT);
2933                                         MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
2934                                         StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2935                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2936                                         SZ_Clear(&net_message);
2937                                         // now set up the client struct
2938                                         SV_VM_Begin();
2939                                         SV_ConnectClient(clientnum, conn);
2940                                         SV_VM_End();
2941                                         NetConn_Heartbeat(1);
2942                                         return true;
2943                                 }
2944                         }
2945
2946                         if (developer_extra.integer)
2947                                 Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
2948                         // no room; try to let player know
2949                         SZ_Clear(&net_message);
2950                         // save space for the header, filled in later
2951                         MSG_WriteLong(&net_message, 0);
2952                         MSG_WriteByte(&net_message, CCREP_REJECT);
2953                         MSG_WriteString(&net_message, "Server is full.\n");
2954                         StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2955                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2956                         SZ_Clear(&net_message);
2957                         break;
2958                 case CCREQ_SERVER_INFO:
2959                         if (developer_extra.integer)
2960                                 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
2961                         if(!islocal && sv_public.integer <= -1)
2962                                 break;
2963                         if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
2964                         {
2965                                 int numclients;
2966                                 char myaddressstring[128];
2967                                 if (developer_extra.integer)
2968                                         Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
2969                                 SZ_Clear(&net_message);
2970                                 // save space for the header, filled in later
2971                                 MSG_WriteLong(&net_message, 0);
2972                                 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
2973                                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), myaddressstring, sizeof(myaddressstring), true);
2974                                 MSG_WriteString(&net_message, myaddressstring);
2975                                 MSG_WriteString(&net_message, hostname.string);
2976                                 MSG_WriteString(&net_message, sv.name);
2977                                 // How many clients are there?
2978                                 for (i = 0, numclients = 0;i < svs.maxclients;i++)
2979                                         if (svs.clients[i].active)
2980                                                 numclients++;
2981                                 MSG_WriteByte(&net_message, numclients);
2982                                 MSG_WriteByte(&net_message, svs.maxclients);
2983                                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2984                                 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2985                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2986                                 SZ_Clear(&net_message);
2987                         }
2988                         break;
2989                 case CCREQ_PLAYER_INFO:
2990                         if (developer_extra.integer)
2991                                 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
2992                         if(!islocal && sv_public.integer <= -1)
2993                                 break;
2994                         if (sv.active)
2995                         {
2996                                 int playerNumber, activeNumber, clientNumber;
2997                                 client_t *client;
2998
2999                                 playerNumber = MSG_ReadByte();
3000                                 activeNumber = -1;
3001                                 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
3002                                         if (client->active && ++activeNumber == playerNumber)
3003                                                 break;
3004                                 if (clientNumber != svs.maxclients)
3005                                 {
3006                                         SZ_Clear(&net_message);
3007                                         // save space for the header, filled in later
3008                                         MSG_WriteLong(&net_message, 0);
3009                                         MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
3010                                         MSG_WriteByte(&net_message, playerNumber);
3011                                         MSG_WriteString(&net_message, client->name);
3012                                         MSG_WriteLong(&net_message, client->colors);
3013                                         MSG_WriteLong(&net_message, client->frags);
3014                                         MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
3015                                         MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
3016                                         StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
3017                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
3018                                         SZ_Clear(&net_message);
3019                                 }
3020                         }
3021                         break;
3022                 case CCREQ_RULE_INFO:
3023                         if (developer_extra.integer)
3024                                 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
3025                         if(!islocal && sv_public.integer <= -1)
3026                                 break;
3027                         if (sv.active)
3028                         {
3029                                 char *prevCvarName;
3030                                 cvar_t *var;
3031
3032                                 // find the search start location
3033                                 prevCvarName = MSG_ReadString();
3034                                 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
3035
3036                                 // send the response
3037                                 SZ_Clear(&net_message);
3038                                 // save space for the header, filled in later
3039                                 MSG_WriteLong(&net_message, 0);
3040                                 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
3041                                 if (var)
3042                                 {
3043                                         MSG_WriteString(&net_message, var->name);
3044                                         MSG_WriteString(&net_message, var->string);
3045                                 }
3046                                 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
3047                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
3048                                 SZ_Clear(&net_message);
3049                         }
3050                         break;
3051                 default:
3052                         break;
3053                 }
3054                 SZ_Clear(&net_message);
3055                 // we may not have liked the packet, but it was a valid control
3056                 // packet, so we're done processing this packet now
3057                 return true;
3058         }
3059         if (host_client)
3060         {
3061                 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length, sv.protocol, host_client->spawned ? net_messagetimeout.value : net_connecttimeout.value)) == 2)
3062                 {
3063                         SV_VM_Begin();
3064                         SV_ReadClientMessage();
3065                         SV_VM_End();
3066                         return ret;
3067                 }
3068         }
3069         return 0;
3070 }
3071
3072 void NetConn_ServerFrame(void)
3073 {
3074         int i, length;
3075         lhnetaddress_t peeraddress;
3076         for (i = 0;i < sv_numsockets;i++)
3077                 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
3078                         NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
3079         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
3080         {
3081                 // never timeout loopback connections
3082                 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
3083                 {
3084                         Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
3085                         SV_VM_Begin();
3086                         SV_DropClient(false);
3087                         SV_VM_End();
3088                 }
3089         }
3090 }
3091
3092 void NetConn_SleepMicroseconds(int microseconds)
3093 {
3094         LHNET_SleepUntilPacket_Microseconds(microseconds);
3095 }
3096
3097 void NetConn_QueryMasters(qboolean querydp, qboolean queryqw)
3098 {
3099         int i, j;
3100         int masternum;
3101         lhnetaddress_t masteraddress;
3102         lhnetaddress_t broadcastaddress;
3103         char request[256];
3104
3105         if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
3106                 return;
3107
3108         // 26000 is the default quake server port, servers on other ports will not
3109         // be found
3110         // note this is IPv4-only, I doubt there are IPv6-only LANs out there
3111         LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
3112
3113         if (querydp)
3114         {
3115                 for (i = 0;i < cl_numsockets;i++)
3116                 {
3117                         if (cl_sockets[i])
3118                         {
3119                                 const char *cmdname, *extraoptions;
3120                                 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
3121
3122                                 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
3123                                 {
3124                                         // search LAN for Quake servers
3125                                         SZ_Clear(&net_message);
3126                                         // save space for the header, filled in later
3127                                         MSG_WriteLong(&net_message, 0);
3128                                         MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
3129                                         MSG_WriteString(&net_message, "QUAKE");
3130                                         MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
3131                                         StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
3132                                         NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
3133                                         SZ_Clear(&net_message);
3134
3135                                         // search LAN for DarkPlaces servers
3136                                         NetConn_WriteString(cl_sockets[i], "\377\377\377\377getstatus", &broadcastaddress);
3137                                 }
3138
3139                                 // build the getservers message to send to the dpmaster master servers
3140                                 if (LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == LHNETADDRESSTYPE_INET6)
3141                                 {
3142                                         cmdname = "getserversExt";
3143                                         extraoptions = " ipv4 ipv6";  // ask for IPv4 and IPv6 servers
3144                                 }
3145                                 else
3146                                 {
3147                                         cmdname = "getservers";
3148                                         extraoptions = "";
3149                                 }
3150                                 dpsnprintf(request, sizeof(request), "\377\377\377\377%s %s %u empty full%s", cmdname, gamename, NET_PROTOCOL_VERSION, extraoptions);
3151
3152                                 // search internet
3153                                 for (masternum = 0;sv_masters[masternum].name;masternum++)
3154                                 {
3155                                         if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == af)
3156                                         {
3157                                                 masterquerycount++;
3158                                                 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
3159                                         }
3160                                 }
3161
3162                                 // search favorite servers
3163                                 for(j = 0; j < nFavorites; ++j)
3164                                 {
3165                                         if(LHNETADDRESS_GetAddressType(&favorites[j]) == af)
3166                                         {
3167                                                 if(LHNETADDRESS_ToString(&favorites[j], request, sizeof(request), true))
3168                                                         NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, request, true );
3169                                         }
3170                                 }
3171                         }
3172                 }
3173         }
3174
3175         // only query QuakeWorld servers when the user wants to
3176         if (queryqw)
3177         {
3178                 for (i = 0;i < cl_numsockets;i++)
3179                 {
3180                         if (cl_sockets[i])
3181                         {
3182                                 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
3183
3184                                 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
3185                                 {
3186                                         // search LAN for QuakeWorld servers
3187                                         NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &broadcastaddress);
3188
3189                                         // build the getservers message to send to the qwmaster master servers
3190                                         // note this has no -1 prefix, and the trailing nul byte is sent
3191                                         dpsnprintf(request, sizeof(request), "c\n");
3192                                 }
3193
3194                                 // search internet
3195                                 for (masternum = 0;sv_qwmasters[masternum].name;masternum++)
3196                                 {
3197                                         if (sv_qwmasters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_qwmasters[masternum].string, QWMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
3198                                         {
3199                                                 if (m_state != m_slist)
3200                                                 {
3201                                                         char lookupstring[128];
3202                                                         LHNETADDRESS_ToString(&masteraddress, lookupstring, sizeof(lookupstring), true);
3203                                                         Con_Printf("Querying master %s (resolved from %s)\n", lookupstring, sv_qwmasters[masternum].string);
3204                                                 }
3205                                                 masterquerycount++;
3206                                                 NetConn_Write(cl_sockets[i], request, (int)strlen(request) + 1, &masteraddress);
3207                                         }
3208                                 }
3209
3210                                 // search favorite servers
3211                                 for(j = 0; j < nFavorites; ++j)
3212                                 {
3213                                         if(LHNETADDRESS_GetAddressType(&favorites[j]) == af)
3214                                         {
3215                                                 if(LHNETADDRESS_ToString(&favorites[j], request, sizeof(request), true))
3216                                                 {
3217                                                         NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &favorites[j]);
3218                                                         NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, request, true );
3219                                                 }
3220                                         }
3221                                 }
3222                         }
3223                 }
3224         }
3225         if (!masterquerycount)
3226         {
3227                 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
3228                 M_Update_Return_Reason("No network");
3229         }
3230 }
3231
3232 void NetConn_Heartbeat(int priority)
3233 {
3234         lhnetaddress_t masteraddress;
3235         int masternum;
3236         lhnetsocket_t *mysocket;
3237
3238         // if it's a state change (client connected), limit next heartbeat to no
3239         // more than 30 sec in the future
3240         if (priority == 1 && nextheartbeattime > realtime + 30.0)
3241                 nextheartbeattime = realtime + 30.0;
3242
3243         // limit heartbeatperiod to 30 to 270 second range,
3244         // lower limit is to avoid abusing master servers with excess traffic,
3245         // upper limit is to avoid timing out on the master server (which uses
3246         // 300 sec timeout)
3247         if (sv_heartbeatperiod.value < 30)
3248                 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
3249         if (sv_heartbeatperiod.value > 270)
3250                 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
3251
3252         // make advertising optional and don't advertise singleplayer games, and
3253         // only send a heartbeat as often as the admin wants
3254         if (sv.active && sv_public.integer > 0 && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
3255         {
3256                 nextheartbeattime = realtime + sv_heartbeatperiod.value;
3257                 for (masternum = 0;sv_masters[masternum].name;masternum++)
3258                         if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
3259                                 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
3260         }
3261 }
3262
3263 static void Net_Heartbeat_f(void)
3264 {
3265         if (sv.active)
3266                 NetConn_Heartbeat(2);
3267         else
3268                 Con_Print("No server running, can not heartbeat to master server.\n");
3269 }
3270
3271 void PrintStats(netconn_t *conn)
3272 {
3273         if ((cls.state == ca_connected && cls.protocol == PROTOCOL_QUAKEWORLD) || (sv.active && sv.protocol == PROTOCOL_QUAKEWORLD))
3274                 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->outgoing_unreliable_sequence, conn->qw.incoming_sequence);
3275         else
3276                 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->nq.sendSequence, conn->nq.receiveSequence);
3277 }
3278
3279 void Net_Stats_f(void)
3280 {
3281         netconn_t *conn;
3282         Con_Printf("unreliable messages sent   = %i\n", unreliableMessagesSent);
3283         Con_Printf("unreliable messages recv   = %i\n", unreliableMessagesReceived);
3284         Con_Printf("reliable messages sent     = %i\n", reliableMessagesSent);
3285         Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
3286         Con_Printf("packetsSent                = %i\n", packetsSent);
3287         Con_Printf("packetsReSent              = %i\n", packetsReSent);
3288         Con_Printf("packetsReceived            = %i\n", packetsReceived);
3289         Con_Printf("receivedDuplicateCount     = %i\n", receivedDuplicateCount);
3290         Con_Printf("droppedDatagrams           = %i\n", droppedDatagrams);
3291         Con_Print("connections                =\n");
3292         for (conn = netconn_list;conn;conn = conn->next)
3293                 PrintStats(conn);
3294 }
3295
3296 void Net_Refresh_f(void)
3297 {
3298         if (m_state != m_slist) {
3299                 Con_Print("Sending new requests to master servers\n");
3300                 ServerList_QueryList(false, true, false, true);
3301                 Con_Print("Listening for replies...\n");
3302         } else
3303                 ServerList_QueryList(false, true, false, false);
3304 }
3305
3306 void Net_Slist_f(void)
3307 {
3308         ServerList_ResetMasks();
3309         serverlist_sortbyfield = SLIF_PING;
3310         serverlist_sortflags = 0;
3311     if (m_state != m_slist) {
3312                 Con_Print("Sending requests to master servers\n");
3313                 ServerList_QueryList(true, true, false, true);
3314                 Con_Print("Listening for replies...\n");
3315         } else
3316                 ServerList_QueryList(true, true, false, false);
3317 }
3318
3319 void Net_SlistQW_f(void)
3320 {
3321         ServerList_ResetMasks();
3322         serverlist_sortbyfield = SLIF_PING;
3323         serverlist_sortflags = 0;
3324     if (m_state != m_slist) {
3325                 Con_Print("Sending requests to master servers\n");
3326                 ServerList_QueryList(true, false, true, true);
3327                 serverlist_consoleoutput = true;
3328                 Con_Print("Listening for replies...\n");
3329         } else
3330                 ServerList_QueryList(true, false, true, false);
3331 }
3332
3333 void NetConn_Init(void)
3334 {
3335         int i;
3336         lhnetaddress_t tempaddress;
3337         netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
3338         Cmd_AddCommand("net_stats", Net_Stats_f, "print network statistics");
3339         Cmd_AddCommand("net_slist", Net_Slist_f, "query dp master servers and print all server information");
3340         Cmd_AddCommand("net_slistqw", Net_SlistQW_f, "query qw master servers and print all server information");
3341         Cmd_AddCommand("net_refresh", Net_Refresh_f, "query dp master servers and refresh all server information");
3342         Cmd_AddCommand("heartbeat", Net_Heartbeat_f, "send a heartbeat to the master server (updates your server information)");
3343         Cvar_RegisterVariable(&rcon_restricted_password);
3344         Cvar_RegisterVariable(&rcon_restricted_commands);
3345         Cvar_RegisterVariable(&rcon_secure_maxdiff);
3346         Cvar_RegisterVariable(&net_slist_queriespersecond);
3347         Cvar_RegisterVariable(&net_slist_queriesperframe);
3348         Cvar_RegisterVariable(&net_slist_timeout);
3349         Cvar_RegisterVariable(&net_slist_maxtries);
3350         Cvar_RegisterVariable(&net_slist_favorites);
3351         Cvar_RegisterVariable(&net_slist_pause);
3352         Cvar_RegisterVariable(&net_messagetimeout);
3353         Cvar_RegisterVariable(&net_connecttimeout);
3354         Cvar_RegisterVariable(&net_connectfloodblockingtimeout);
3355         Cvar_RegisterVariable(&cl_netlocalping);
3356         Cvar_RegisterVariable(&cl_netpacketloss_send);
3357         Cvar_RegisterVariable(&cl_netpacketloss_receive);
3358         Cvar_RegisterVariable(&hostname);
3359         Cvar_RegisterVariable(&developer_networking);
3360         Cvar_RegisterVariable(&cl_netport);
3361         Cvar_RegisterVariable(&sv_netport);
3362         Cvar_RegisterVariable(&net_address);
3363         Cvar_RegisterVariable(&net_address_ipv6);
3364         Cvar_RegisterVariable(&sv_public);
3365         Cvar_RegisterVariable(&sv_heartbeatperiod);
3366         for (i = 0;sv_masters[i].name;i++)
3367                 Cvar_RegisterVariable(&sv_masters[i]);
3368         Cvar_RegisterVariable(&gameversion);
3369         Cvar_RegisterVariable(&gameversion_min);
3370         Cvar_RegisterVariable(&gameversion_max);
3371 // 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.
3372         if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
3373         {
3374                 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
3375                 {
3376                         Con_Printf("-ip option used, setting net_address to \"%s\"\n", com_argv[i + 1]);
3377                         Cvar_SetQuick(&net_address, com_argv[i + 1]);
3378                 }
3379                 else
3380                         Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
3381         }
3382 // 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
3383         if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
3384         {
3385                 i = atoi(com_argv[i + 1]);
3386                 if (i >= 0 && i < 65536)
3387                 {
3388                         Con_Printf("-port option used, setting port cvar to %i\n", i);
3389                         Cvar_SetValueQuick(&sv_netport, i);
3390                 }
3391                 else
3392                         Con_Printf("-port option used, but %i is not a valid port number\n", i);
3393         }
3394         cl_numsockets = 0;
3395         sv_numsockets = 0;
3396         net_message.data = net_message_buf;
3397         net_message.maxsize = sizeof(net_message_buf);
3398         net_message.cursize = 0;
3399         LHNET_Init();
3400 }
3401
3402 void NetConn_Shutdown(void)
3403 {
3404         NetConn_CloseClientPorts();
3405         NetConn_CloseServerPorts();
3406         LHNET_Shutdown();
3407 }
3408