]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - netconn.c
change representation of string offsets for allocated strings and engine
[xonotic/darkplaces.git] / netconn.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3 Copyright (C) 2002 Mathieu Olivier
4 Copyright (C) 2003 Forest Hale
5
6 This program is free software; you can redistribute it and/or
7 modify it under the terms of the GNU General Public License
8 as published by the Free Software Foundation; either version 2
9 of the License, or (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14
15 See the GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
20
21 */
22
23 #include "quakedef.h"
24 #include "lhnet.h"
25
26 // for secure rcon authentication
27 #include "hmac.h"
28 #include "mdfour.h"
29 #include <time.h>
30
31 #define QWMASTER_PORT 27000
32 #define DPMASTER_PORT 27950
33
34 // note this defaults on for dedicated servers, off for listen servers
35 cvar_t sv_public = {0, "sv_public", "0", "1: advertises this server on the master server (so that players can find it in the server browser); 0: allow direct queries only; -1: do not respond to direct queries; -2: do not allow anyone to connect"};
36 static cvar_t sv_heartbeatperiod = {CVAR_SAVE, "sv_heartbeatperiod", "120", "how often to send heartbeat in seconds (only used if sv_public is 1)"};
37
38 static cvar_t sv_masters [] =
39 {
40         {CVAR_SAVE, "sv_master1", "", "user-chosen master server 1"},
41         {CVAR_SAVE, "sv_master2", "", "user-chosen master server 2"},
42         {CVAR_SAVE, "sv_master3", "", "user-chosen master server 3"},
43         {CVAR_SAVE, "sv_master4", "", "user-chosen master server 4"},
44         {0, "sv_masterextra1", "69.59.212.88", "ghdigital.com - default master server 1 (admin: LordHavoc)"}, // admin: LordHavoc
45         {0, "sv_masterextra2", "64.22.107.125", "dpmaster.deathmask.net - default master server 2 (admin: Willis)"}, // admin: Willis
46         {0, "sv_masterextra3", "92.62.40.73", "dpmaster.tchr.no - default master server 3 (admin: tChr)"}, // admin: tChr
47         {0, NULL, NULL, NULL}
48 };
49
50 static cvar_t sv_qwmasters [] =
51 {
52         {CVAR_SAVE, "sv_qwmaster1", "", "user-chosen qwmaster server 1"},
53         {CVAR_SAVE, "sv_qwmaster2", "", "user-chosen qwmaster server 2"},
54         {CVAR_SAVE, "sv_qwmaster3", "", "user-chosen qwmaster server 3"},
55         {CVAR_SAVE, "sv_qwmaster4", "", "user-chosen qwmaster server 4"},
56         {0, "sv_qwmasterextra1", "master.quakeservers.net:27000", "Global master server. (admin: unknown)"},
57         {0, "sv_qwmasterextra2", "asgaard.morphos-team.net:27000", "Global master server. (admin: unknown)"},
58         {0, "sv_qwmasterextra3", "qwmaster.ocrana.de:27000", "German master server. (admin: unknown)"},
59         {0, "sv_qwmasterextra4", "masterserver.exhale.de:27000", "German master server. (admin: unknown)"},
60         {0, "sv_qwmasterextra5", "kubus.rulez.pl:27000", "Poland master server. (admin: unknown)"},
61         {0, NULL, NULL, NULL}
62 };
63
64 static double nextheartbeattime = 0;
65
66 sizebuf_t net_message;
67 static unsigned char net_message_buf[NET_MAXMESSAGE];
68
69 cvar_t net_messagetimeout = {0, "net_messagetimeout","300", "drops players who have not sent any packets for this many seconds"};
70 cvar_t net_connecttimeout = {0, "net_connecttimeout","15", "after requesting a connection, the client must reply within this many seconds or be dropped (cuts down on connect floods). Must be above 10 seconds."};
71 cvar_t net_connectfloodblockingtimeout = {0, "net_connectfloodblockingtimeout", "5", "when a connection packet is received, it will block all future connect packets from that IP address for this many seconds (cuts down on connect floods)"};
72 cvar_t hostname = {CVAR_SAVE, "hostname", "UNNAMED", "server message to show in server browser"};
73 cvar_t developer_networking = {0, "developer_networking", "0", "prints all received and sent packets (recommended only for debugging)"};
74
75 cvar_t cl_netlocalping = {0, "cl_netlocalping","0", "lags local loopback connection by this much ping time (useful to play more fairly on your own server with people with higher pings)"};
76 static cvar_t cl_netpacketloss_send = {0, "cl_netpacketloss_send","0", "drops this percentage of outgoing packets, useful for testing network protocol robustness (jerky movement, prediction errors, etc)"};
77 static cvar_t cl_netpacketloss_receive = {0, "cl_netpacketloss_receive","0", "drops this percentage of incoming packets, useful for testing network protocol robustness (jerky movement, effects failing to start, sounds failing to play, etc)"};
78 static cvar_t net_slist_queriespersecond = {0, "net_slist_queriespersecond", "20", "how many server information requests to send per second"};
79 static cvar_t net_slist_queriesperframe = {0, "net_slist_queriesperframe", "4", "maximum number of server information requests to send each rendered frame (guards against low framerates causing problems)"};
80 static cvar_t net_slist_timeout = {0, "net_slist_timeout", "4", "how long to listen for a server information response before giving up"};
81 static cvar_t net_slist_pause = {0, "net_slist_pause", "0", "when set to 1, the server list won't update until it is set back to 0"};
82 static cvar_t net_slist_maxtries = {0, "net_slist_maxtries", "3", "how many times to ask the same server for information (more times gives better ping reports but takes longer)"};
83 static cvar_t net_slist_favorites = {CVAR_SAVE | CVAR_NQUSERINFOHACK, "net_slist_favorites", "", "contains a list of IP addresses and ports to always query explicitly"};
84 static cvar_t gameversion = {0, "gameversion", "0", "version of game data (mod-specific) to be sent to querying clients"};
85 static cvar_t gameversion_min = {0, "gameversion_min", "-1", "minimum version of game data (mod-specific), when client and server gameversion mismatch in the server browser the server is shown as incompatible; if -1, gameversion is used alone"};
86 static cvar_t gameversion_max = {0, "gameversion_max", "-1", "maximum version of game data (mod-specific), when client and server gameversion mismatch in the server browser the server is shown as incompatible; if -1, gameversion is used alone"};
87 static cvar_t rcon_restricted_password = {CVAR_PRIVATE, "rcon_restricted_password", "", "password to authenticate rcon commands in restricted mode; may be set to a string of the form user1:pass1 user2:pass2 user3:pass3 to allow multiple user accounts - the client then has to specify ONE of these combinations"};
88 static cvar_t rcon_restricted_commands = {0, "rcon_restricted_commands", "", "allowed commands for rcon when the restricted mode password was used"};
89 static cvar_t rcon_secure_maxdiff = {0, "rcon_secure_maxdiff", "5", "maximum time difference between rcon request and server system clock (to protect against replay attack)"};
90 extern cvar_t rcon_secure;
91 extern cvar_t rcon_secure_challengetimeout;
92
93 /* statistic counters */
94 static int packetsSent = 0;
95 static int packetsReSent = 0;
96 static int packetsReceived = 0;
97 static int receivedDuplicateCount = 0;
98 static int droppedDatagrams = 0;
99
100 static int unreliableMessagesSent = 0;
101 static int unreliableMessagesReceived = 0;
102 static int reliableMessagesSent = 0;
103 static int reliableMessagesReceived = 0;
104
105 double masterquerytime = -1000;
106 int masterquerycount = 0;
107 int masterreplycount = 0;
108 int serverquerycount = 0;
109 int serverreplycount = 0;
110
111 /// this is only false if there are still servers left to query
112 static qboolean serverlist_querysleep = true;
113 static qboolean serverlist_paused = false;
114 /// this is pushed a second or two ahead of realtime whenever a master server
115 /// reply is received, to avoid issuing queries while master replies are still
116 /// flooding in (which would make a mess of the ping times)
117 static double serverlist_querywaittime = 0;
118
119 static unsigned char sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
120 static unsigned char readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
121
122 static int cl_numsockets;
123 static lhnetsocket_t *cl_sockets[16];
124 static int sv_numsockets;
125 static lhnetsocket_t *sv_sockets[16];
126
127 netconn_t *netconn_list = NULL;
128 mempool_t *netconn_mempool = NULL;
129
130 cvar_t cl_netport = {0, "cl_port", "0", "forces client to use chosen port number if not 0"};
131 cvar_t sv_netport = {0, "port", "26000", "server port for players to connect to"};
132 cvar_t net_address = {0, "net_address", "", "network address to open ipv4 ports on (if empty, use default interfaces)"};
133 cvar_t net_address_ipv6 = {0, "net_address_ipv6", "", "network address to open ipv6 ports on (if empty, use default interfaces)"};
134
135 char cl_net_extresponse[NET_EXTRESPONSE_MAX][1400];
136 int cl_net_extresponse_count = 0;
137 int cl_net_extresponse_last = 0;
138
139 char sv_net_extresponse[NET_EXTRESPONSE_MAX][1400];
140 int sv_net_extresponse_count = 0;
141 int sv_net_extresponse_last = 0;
142
143 // ServerList interface
144 serverlist_mask_t serverlist_andmasks[SERVERLIST_ANDMASKCOUNT];
145 serverlist_mask_t serverlist_ormasks[SERVERLIST_ORMASKCOUNT];
146
147 serverlist_infofield_t serverlist_sortbyfield;
148 int serverlist_sortflags;
149
150 int serverlist_viewcount = 0;
151 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         {
2129                 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2130                 {
2131 //                      R_TimeReport("clientreadnetwork");
2132                         NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
2133 //                      R_TimeReport("clientparsepacket");
2134                 }
2135         }
2136         NetConn_QueryQueueFrame();
2137         if (cls.netcon && realtime > cls.netcon->timeout && !sv.active)
2138         {
2139                 Con_Print("Connection timed out\n");
2140                 CL_Disconnect();
2141                 Host_ShutdownServer ();
2142         }
2143 }
2144
2145 #define MAX_CHALLENGES 128
2146 struct challenge_s
2147 {
2148         lhnetaddress_t address;
2149         double time;
2150         char string[12];
2151 }
2152 challenge[MAX_CHALLENGES];
2153
2154 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
2155 {
2156         int i;
2157         char c;
2158         for (i = 0;i < bufferlength - 1;i++)
2159         {
2160                 do
2161                 {
2162                         c = rand () % (127 - 33) + 33;
2163                 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
2164                 buffer[i] = c;
2165         }
2166         buffer[i] = 0;
2167 }
2168
2169 /// (div0) build the full response only if possible; better a getinfo response than no response at all if getstatus won't fit
2170 static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg, size_t out_size, qboolean fullstatus)
2171 {
2172         char qcstatus[256];
2173         unsigned int nb_clients = 0, nb_bots = 0, i;
2174         int length;
2175         char teambuf[3];
2176
2177         SV_VM_Begin();
2178
2179         // How many clients are there?
2180         for (i = 0;i < (unsigned int)svs.maxclients;i++)
2181         {
2182                 if (svs.clients[i].active)
2183                 {
2184                         nb_clients++;
2185                         if (!svs.clients[i].netconnection)
2186                                 nb_bots++;
2187                 }
2188         }
2189
2190         *qcstatus = 0;
2191         if(prog->globaloffsets.worldstatus >= 0)
2192         {
2193                 const char *str = PRVM_G_STRING(prog->globaloffsets.worldstatus);
2194                 if(str && *str)
2195                 {
2196                         char *p;
2197                         const char *q;
2198                         p = qcstatus;
2199                         for(q = str; *q; ++q)
2200                                 if(*q != '\\' && *q != '\n')
2201                                         *p++ = *q;
2202                         *p = 0;
2203                 }
2204         }
2205
2206         /// \TODO: we should add more information for the full status string
2207         length = dpsnprintf(out_msg, out_size,
2208                                                 "\377\377\377\377%s\x0A"
2209                                                 "\\gamename\\%s\\modname\\%s\\gameversion\\%d\\sv_maxclients\\%d"
2210                                                 "\\clients\\%d\\bots\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d"
2211                                                 "%s%s"
2212                                                 "%s%s"
2213                                                 "%s",
2214                                                 fullstatus ? "statusResponse" : "infoResponse",
2215                                                 gamename, com_modname, gameversion.integer, svs.maxclients,
2216                                                 nb_clients, nb_bots, sv.name, hostname.string, NET_PROTOCOL_VERSION,
2217                                                 *qcstatus ? "\\qcstatus\\" : "", qcstatus,
2218                                                 challenge ? "\\challenge\\" : "", challenge ? challenge : "",
2219                                                 fullstatus ? "\n" : "");
2220
2221         // Make sure it fits in the buffer
2222         if (length < 0)
2223                 goto bad;
2224
2225         if (fullstatus)
2226         {
2227                 char *ptr;
2228                 int left;
2229                 int savelength;
2230
2231                 savelength = length;
2232
2233                 ptr = out_msg + length;
2234                 left = (int)out_size - length;
2235
2236                 for (i = 0;i < (unsigned int)svs.maxclients;i++)
2237                 {
2238                         client_t *cl = &svs.clients[i];
2239                         if (cl->active)
2240                         {
2241                                 int nameind, cleanind, pingvalue;
2242                                 char curchar;
2243                                 char cleanname [sizeof(cl->name)];
2244
2245                                 // Remove all characters '"' and '\' in the player name
2246                                 nameind = 0;
2247                                 cleanind = 0;
2248                                 do
2249                                 {
2250                                         curchar = cl->name[nameind++];
2251                                         if (curchar != '"' && curchar != '\\')
2252                                         {
2253                                                 cleanname[cleanind++] = curchar;
2254                                                 if (cleanind == sizeof(cleanname) - 1)
2255                                                         break;
2256                                         }
2257                                 } while (curchar != '\0');
2258                                 cleanname[cleanind] = 0; // cleanind is always a valid index even at this point
2259
2260                                 pingvalue = (int)(cl->ping * 1000.0f);
2261                                 if(cl->netconnection)
2262                                         pingvalue = bound(1, pingvalue, 9999);
2263                                 else
2264                                         pingvalue = 0;
2265
2266                                 *qcstatus = 0;
2267                                 if(prog->fieldoffsets.clientstatus >= 0)
2268                                 {
2269                                         const char *str = PRVM_E_STRING(PRVM_EDICT_NUM(i + 1), prog->fieldoffsets.clientstatus);
2270                                         if(str && *str)
2271                                         {
2272                                                 char *p;
2273                                                 const char *q;
2274                                                 p = qcstatus;
2275                                                 for(q = str; *q && p != qcstatus + sizeof(qcstatus) - 1; ++q)
2276                                                         if(*q != '\\' && *q != '"' && !ISWHITESPACE(*q))
2277                                                                 *p++ = *q;
2278                                                 *p = 0;
2279                                         }
2280                                 }
2281
2282                                 if ((gamemode == GAME_NEXUIZ) && (teamplay.integer > 0))
2283                                 {
2284                                         if(cl->frags == -666) // spectator
2285                                                 strlcpy(teambuf, " 0", sizeof(teambuf));
2286                                         else if(cl->colors == 0x44) // red team
2287                                                 strlcpy(teambuf, " 1", sizeof(teambuf));
2288                                         else if(cl->colors == 0xDD) // blue team
2289                                                 strlcpy(teambuf, " 2", sizeof(teambuf));
2290                                         else if(cl->colors == 0xCC) // yellow team
2291                                                 strlcpy(teambuf, " 3", sizeof(teambuf));
2292                                         else if(cl->colors == 0x99) // pink team
2293                                                 strlcpy(teambuf, " 4", sizeof(teambuf));
2294                                         else
2295                                                 strlcpy(teambuf, " 0", sizeof(teambuf));
2296                                 }
2297                                 else
2298                                         *teambuf = 0;
2299
2300                                 // note: team number is inserted according to SoF2 protocol
2301                                 if(*qcstatus)
2302                                         length = dpsnprintf(ptr, left, "%s %d%s \"%s\"\n",
2303                                                                                 qcstatus,
2304                                                                                 pingvalue,
2305                                                                                 teambuf,
2306                                                                                 cleanname);
2307                                 else
2308                                         length = dpsnprintf(ptr, left, "%d %d%s \"%s\"\n",
2309                                                                                 cl->frags,
2310                                                                                 pingvalue,
2311                                                                                 teambuf,
2312                                                                                 cleanname);
2313
2314                                 if(length < 0)
2315                                 {
2316                                         // out of space?
2317                                         // turn it into an infoResponse!
2318                                         out_msg[savelength] = 0;
2319                                         memcpy(out_msg + 4, "infoResponse\x0A", 13);
2320                                         memmove(out_msg + 17, out_msg + 19, savelength - 19);
2321                                         break;
2322                                 }
2323                                 left -= length;
2324                                 ptr += length;
2325                         }
2326                 }
2327         }
2328
2329         SV_VM_End();
2330         return true;
2331
2332 bad:
2333         SV_VM_End();
2334         return false;
2335 }
2336
2337 static qboolean NetConn_PreventConnectFlood(lhnetaddress_t *peeraddress)
2338 {
2339         int floodslotnum, bestfloodslotnum;
2340         double bestfloodtime;
2341         lhnetaddress_t noportpeeraddress;
2342         // see if this is a connect flood
2343         noportpeeraddress = *peeraddress;
2344         LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2345         bestfloodslotnum = 0;
2346         bestfloodtime = sv.connectfloodaddresses[bestfloodslotnum].lasttime;
2347         for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2348         {
2349                 if (bestfloodtime >= sv.connectfloodaddresses[floodslotnum].lasttime)
2350                 {
2351                         bestfloodtime = sv.connectfloodaddresses[floodslotnum].lasttime;
2352                         bestfloodslotnum = floodslotnum;
2353                 }
2354                 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2355                 {
2356                         // this address matches an ongoing flood address
2357                         if (realtime < sv.connectfloodaddresses[floodslotnum].lasttime + net_connectfloodblockingtimeout.value)
2358                         {
2359                                 // renew the ban on this address so it does not expire
2360                                 // until the flood has subsided
2361                                 sv.connectfloodaddresses[floodslotnum].lasttime = realtime;
2362                                 //Con_Printf("Flood detected!\n");
2363                                 return true;
2364                         }
2365                         // the flood appears to have subsided, so allow this
2366                         bestfloodslotnum = floodslotnum; // reuse the same slot
2367                         break;
2368                 }
2369         }
2370         // begin a new timeout on this address
2371         sv.connectfloodaddresses[bestfloodslotnum].address = noportpeeraddress;
2372         sv.connectfloodaddresses[bestfloodslotnum].lasttime = realtime;
2373         //Con_Printf("Flood detection initiated!\n");
2374         return false;
2375 }
2376
2377 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress)
2378 {
2379         int floodslotnum;
2380         lhnetaddress_t noportpeeraddress;
2381         // see if this is a connect flood
2382         noportpeeraddress = *peeraddress;
2383         LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2384         for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2385         {
2386                 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2387                 {
2388                         // this address matches an ongoing flood address
2389                         // remove the ban
2390                         sv.connectfloodaddresses[floodslotnum].address.addresstype = LHNETADDRESSTYPE_NONE;
2391                         sv.connectfloodaddresses[floodslotnum].lasttime = 0;
2392                         //Con_Printf("Flood cleared!\n");
2393                 }
2394         }
2395 }
2396
2397 typedef qboolean (*rcon_matchfunc_t) (lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen);
2398
2399 qboolean hmac_mdfour_time_matching(lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen)
2400 {
2401         char mdfourbuf[16];
2402         long t1, t2;
2403
2404         t1 = (long) time(NULL);
2405         t2 = strtol(s, NULL, 0);
2406         if(abs(t1 - t2) > rcon_secure_maxdiff.integer)
2407                 return false;
2408
2409         if(!HMAC_MDFOUR_16BYTES((unsigned char *) mdfourbuf, (unsigned char *) s, slen, (unsigned char *) password, strlen(password)))
2410                 return false;
2411
2412         return !memcmp(mdfourbuf, hash, 16);
2413 }
2414
2415 qboolean hmac_mdfour_challenge_matching(lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen)
2416 {
2417         char mdfourbuf[16];
2418         int i;
2419
2420         if(slen < (int)(sizeof(challenge[0].string)) - 1)
2421                 return false;
2422
2423         // validate the challenge
2424         for (i = 0;i < MAX_CHALLENGES;i++)
2425                 if(challenge[i].time > 0)
2426                         if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strncmp(challenge[i].string, s, sizeof(challenge[0].string) - 1))
2427                                 break;
2428         // if the challenge is not recognized, drop the packet
2429         if (i == MAX_CHALLENGES)
2430                 return false;
2431
2432         if(!HMAC_MDFOUR_16BYTES((unsigned char *) mdfourbuf, (unsigned char *) s, slen, (unsigned char *) password, strlen(password)))
2433                 return false;
2434
2435         if(memcmp(mdfourbuf, hash, 16))
2436                 return false;
2437
2438         // unmark challenge to prevent replay attacks
2439         challenge[i].time = 0;
2440
2441         return true;
2442 }
2443
2444 qboolean plaintext_matching(lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen)
2445 {
2446         return !strcmp(password, hash);
2447 }
2448
2449 /// returns a string describing the user level, or NULL for auth failure
2450 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)
2451 {
2452         const char *text, *userpass_start, *userpass_end, *userpass_startpass;
2453         static char buf[MAX_INPUTLINE];
2454         qboolean hasquotes;
2455         qboolean restricted = false;
2456         qboolean have_usernames = false;
2457
2458         userpass_start = rcon_password.string;
2459         while((userpass_end = strchr(userpass_start, ' ')))
2460         {
2461                 have_usernames = true;
2462                 strlcpy(buf, userpass_start, ((size_t)(userpass_end-userpass_start) >= sizeof(buf)) ? (int)(sizeof(buf)) : (int)(userpass_end-userpass_start+1));
2463                 if(buf[0])
2464                         if(comparator(peeraddress, buf, password, cs, cslen))
2465                                 goto allow;
2466                 userpass_start = userpass_end + 1;
2467         }
2468         if(userpass_start[0])
2469         {
2470                 userpass_end = userpass_start + strlen(userpass_start);
2471                 if(comparator(peeraddress, userpass_start, password, cs, cslen))
2472                         goto allow;
2473         }
2474
2475         restricted = true;
2476         have_usernames = false;
2477         userpass_start = rcon_restricted_password.string;
2478         while((userpass_end = strchr(userpass_start, ' ')))
2479         {
2480                 have_usernames = true;
2481                 strlcpy(buf, userpass_start, ((size_t)(userpass_end-userpass_start) >= sizeof(buf)) ? (int)(sizeof(buf)) : (int)(userpass_end-userpass_start+1));
2482                 if(buf[0])
2483                         if(comparator(peeraddress, buf, password, cs, cslen))
2484                                 goto check;
2485                 userpass_start = userpass_end + 1;
2486         }
2487         if(userpass_start[0])
2488         {
2489                 userpass_end = userpass_start + strlen(userpass_start);
2490                 if(comparator(peeraddress, userpass_start, password, cs, cslen))
2491                         goto check;
2492         }
2493         
2494         return NULL; // DENIED
2495
2496 check:
2497         for(text = s; text != endpos; ++text)
2498                 if((signed char) *text > 0 && ((signed char) *text < (signed char) ' ' || *text == ';'))
2499                         return NULL; // block possible exploits against the parser/alias expansion
2500
2501         while(s != endpos)
2502         {
2503                 size_t l = strlen(s);
2504                 if(l)
2505                 {
2506                         hasquotes = (strchr(s, '"') != NULL);
2507                         // sorry, we can't allow these substrings in wildcard expressions,
2508                         // as they can mess with the argument counts
2509                         text = rcon_restricted_commands.string;
2510                         while(COM_ParseToken_Console(&text))
2511                         {
2512                                 // com_token now contains a pattern to check for...
2513                                 if(strchr(com_token, '*') || strchr(com_token, '?')) // wildcard expression, * can only match a SINGLE argument
2514                                 {
2515                                         if(!hasquotes)
2516                                                 if(matchpattern_with_separator(s, com_token, true, " ", true)) // note how we excluded tab, newline etc. above
2517                                                         goto match;
2518                                 }
2519                                 else if(strchr(com_token, ' ')) // multi-arg expression? must match in whole
2520                                 {
2521                                         if(!strcmp(com_token, s))
2522                                                 goto match;
2523                                 }
2524                                 else // single-arg expression? must match the beginning of the command
2525                                 {
2526                                         if(!strcmp(com_token, s))
2527                                                 goto match;
2528                                         if(!memcmp(va("%s ", com_token), s, strlen(com_token) + 1))
2529                                                 goto match;
2530                                 }
2531                         }
2532                         // if we got here, nothing matched!
2533                         return NULL;
2534                 }
2535 match:
2536                 s += l + 1;
2537         }
2538
2539 allow:
2540         userpass_startpass = strchr(userpass_start, ':');
2541         if(have_usernames && userpass_startpass && userpass_startpass < userpass_end)
2542                 return va("%srcon (username %.*s)", restricted ? "restricted " : "", (int)(userpass_startpass-userpass_start), userpass_start);
2543
2544         return va("%srcon", restricted ? "restricted " : "");
2545 }
2546
2547 void RCon_Execute(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, const char *addressstring2, const char *userlevel, const char *s, const char *endpos)
2548 {
2549         if(userlevel)
2550         {
2551                 // looks like a legitimate rcon command with the correct password
2552                 const char *s_ptr = s;
2553                 Con_Printf("server received %s command from %s: ", userlevel, host_client ? host_client->name : addressstring2);
2554                 while(s_ptr != endpos)
2555                 {
2556                         size_t l = strlen(s_ptr);
2557                         if(l)
2558                                 Con_Printf(" %s;", s_ptr);
2559                         s_ptr += l + 1;
2560                 }
2561                 Con_Printf("\n");
2562
2563                 if (!host_client || !host_client->netconnection || LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2564                         Con_Rcon_Redirect_Init(mysocket, peeraddress);
2565                 while(s != endpos)
2566                 {
2567                         size_t l = strlen(s);
2568                         if(l)
2569                         {
2570                                 client_t *host_client_save = host_client;
2571                                 Cmd_ExecuteString(s, src_command);
2572                                 host_client = host_client_save;
2573                                 // in case it is a command that changes host_client (like restart)
2574                         }
2575                         s += l + 1;
2576                 }
2577                 Con_Rcon_Redirect_End();
2578         }
2579         else
2580         {
2581                 Con_Printf("server denied rcon access to %s\n", host_client ? host_client->name : addressstring2);
2582         }
2583 }
2584
2585 extern void SV_SendServerinfo (client_t *client);
2586 static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
2587 {
2588         int i, ret, clientnum, best;
2589         double besttime;
2590         client_t *client;
2591         char *s, *string, response[1400], addressstring2[128];
2592         static char stringbuf[16384];
2593         qboolean islocal = (LHNETADDRESS_GetAddressType(peeraddress) == LHNETADDRESSTYPE_LOOP);
2594
2595         if (!sv.active)
2596                 return false;
2597
2598         // convert the address to a string incase we need it
2599         LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
2600
2601         // see if we can identify the sender as a local player
2602         // (this is necessary for rcon to send a reliable reply if the client is
2603         //  actually on the server, not sending remotely)
2604         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2605                 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
2606                         break;
2607         if (i == svs.maxclients)
2608                 host_client = NULL;
2609
2610         if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
2611         {
2612                 // received a command string - strip off the packaging and put it
2613                 // into our string buffer with NULL termination
2614                 data += 4;
2615                 length -= 4;
2616                 length = min(length, (int)sizeof(stringbuf) - 1);
2617                 memcpy(stringbuf, data, length);
2618                 stringbuf[length] = 0;
2619                 string = stringbuf;
2620
2621                 if (developer_extra.integer)
2622                 {
2623                         Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
2624                         Com_HexDumpToConsole(data, length);
2625                 }
2626
2627                 if (length >= 12 && !memcmp(string, "getchallenge", 12) && (islocal || sv_public.integer > -2))
2628                 {
2629                         for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
2630                         {
2631                                 if(challenge[i].time > 0)
2632                                         if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
2633                                                 break;
2634                                 if (besttime > challenge[i].time)
2635                                         besttime = challenge[best = i].time;
2636                         }
2637                         // if we did not find an exact match, choose the oldest and
2638                         // update address and string
2639                         if (i == MAX_CHALLENGES)
2640                         {
2641                                 i = best;
2642                                 challenge[i].address = *peeraddress;
2643                                 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
2644                         }
2645                         challenge[i].time = realtime;
2646                         // send the challenge
2647                         NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
2648                         return true;
2649                 }
2650                 if (length > 8 && !memcmp(string, "connect\\", 8) && (islocal || sv_public.integer > -2))
2651                 {
2652                         string += 7;
2653                         length -= 7;
2654
2655                         if (!(s = SearchInfostring(string, "challenge")))
2656                                 return true;
2657                         // validate the challenge
2658                         for (i = 0;i < MAX_CHALLENGES;i++)
2659                                 if(challenge[i].time > 0)
2660                                         if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
2661                                                 break;
2662                         // if the challenge is not recognized, drop the packet
2663                         if (i == MAX_CHALLENGES)
2664                                 return true;
2665
2666                         // check engine protocol
2667                         if(!(s = SearchInfostring(string, "protocol")) || strcmp(s, "darkplaces 3"))
2668                         {
2669                                 if (developer_extra.integer)
2670                                         Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
2671                                 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
2672                                 return true;
2673                         }
2674
2675                         // see if this is a duplicate connection request or a disconnected
2676                         // client who is rejoining to the same client slot
2677                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2678                         {
2679                                 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2680                                 {
2681                                         // this is a known client...
2682                                         if (client->spawned)
2683                                         {
2684                                                 // client crashed and is coming back,
2685                                                 // keep their stuff intact
2686                                                 if (developer_extra.integer)
2687                                                         Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", addressstring2);
2688                                                 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2689                                                 SV_VM_Begin();
2690                                                 SV_SendServerinfo(client);
2691                                                 SV_VM_End();
2692                                         }
2693                                         else
2694                                         {
2695                                                 // client is still trying to connect,
2696                                                 // so we send a duplicate reply
2697                                                 if (developer_extra.integer)
2698                                                         Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
2699                                                 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2700                                         }
2701                                         return true;
2702                                 }
2703                         }
2704
2705                         if (NetConn_PreventConnectFlood(peeraddress))
2706                                 return true;
2707
2708                         // find an empty client slot for this new client
2709                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2710                         {
2711                                 netconn_t *conn;
2712                                 if (!client->active && (conn = NetConn_Open(mysocket, peeraddress)))
2713                                 {
2714                                         // allocated connection
2715                                         if (developer_extra.integer)
2716                                                 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
2717                                         NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2718                                         // now set up the client
2719                                         SV_VM_Begin();
2720                                         SV_ConnectClient(clientnum, conn);
2721                                         SV_VM_End();
2722                                         NetConn_Heartbeat(1);
2723                                         return true;
2724                                 }
2725                         }
2726
2727                         // no empty slots found - server is full
2728                         if (developer_extra.integer)
2729                                 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
2730                         NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
2731
2732                         return true;
2733                 }
2734                 if (length >= 7 && !memcmp(string, "getinfo", 7) && (islocal || sv_public.integer > -1))
2735                 {
2736                         const char *challenge = NULL;
2737
2738                         // If there was a challenge in the getinfo message
2739                         if (length > 8 && string[7] == ' ')
2740                                 challenge = string + 8;
2741
2742                         if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
2743                         {
2744                                 if (developer_extra.integer)
2745                                         Con_DPrintf("Sending reply to master %s - %s\n", addressstring2, response);
2746                                 NetConn_WriteString(mysocket, response, peeraddress);
2747                         }
2748                         return true;
2749                 }
2750                 if (length >= 9 && !memcmp(string, "getstatus", 9) && (islocal || sv_public.integer > -1))
2751                 {
2752                         const char *challenge = NULL;
2753
2754                         // If there was a challenge in the getinfo message
2755                         if (length > 10 && string[9] == ' ')
2756                                 challenge = string + 10;
2757
2758                         if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
2759                         {
2760                                 if (developer_extra.integer)
2761                                         Con_DPrintf("Sending reply to client %s - %s\n", addressstring2, response);
2762                                 NetConn_WriteString(mysocket, response, peeraddress);
2763                         }
2764                         return true;
2765                 }
2766                 if (length >= 37 && !memcmp(string, "srcon HMAC-MD4 TIME ", 20))
2767                 {
2768                         char *password = string + 20;
2769                         char *timeval = string + 37;
2770                         char *s = strchr(timeval, ' ');
2771                         char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2772                         const char *userlevel;
2773
2774                         if(rcon_secure.integer > 1)
2775                                 return true;
2776
2777                         if(!s)
2778                                 return true; // invalid packet
2779                         ++s;
2780
2781                         userlevel = RCon_Authenticate(peeraddress, password, s, endpos, hmac_mdfour_time_matching, timeval, endpos - timeval - 1); // not including the appended \0 into the HMAC
2782                         RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2783                         return true;
2784                 }
2785                 if (length >= 42 && !memcmp(string, "srcon HMAC-MD4 CHALLENGE ", 25))
2786                 {
2787                         char *password = string + 25;
2788                         char *challenge = string + 42;
2789                         char *s = strchr(challenge, ' ');
2790                         char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2791                         const char *userlevel;
2792                         if(!s)
2793                                 return true; // invalid packet
2794                         ++s;
2795
2796                         userlevel = RCon_Authenticate(peeraddress, password, s, endpos, hmac_mdfour_challenge_matching, challenge, endpos - challenge - 1); // not including the appended \0 into the HMAC
2797                         RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2798                         return true;
2799                 }
2800                 if (length >= 5 && !memcmp(string, "rcon ", 5))
2801                 {
2802                         int i;
2803                         char *s = string + 5;
2804                         char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2805                         char password[64];
2806
2807                         if(rcon_secure.integer > 0)
2808                                 return true;
2809
2810                         for (i = 0;!ISWHITESPACE(*s);s++)
2811                                 if (i < (int)sizeof(password) - 1)
2812                                         password[i++] = *s;
2813                         if(ISWHITESPACE(*s) && s != endpos) // skip leading ugly space
2814                                 ++s;
2815                         password[i] = 0;
2816                         if (!ISWHITESPACE(password[0]))
2817                         {
2818                                 const char *userlevel = RCon_Authenticate(peeraddress, password, s, endpos, plaintext_matching, NULL, 0);
2819                                 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2820                         }
2821                         return true;
2822                 }
2823                 if (!strncmp(string, "extResponse ", 12))
2824                 {
2825                         ++sv_net_extresponse_count;
2826                         if(sv_net_extresponse_count > NET_EXTRESPONSE_MAX)
2827                                 sv_net_extresponse_count = NET_EXTRESPONSE_MAX;
2828                         sv_net_extresponse_last = (sv_net_extresponse_last + 1) % NET_EXTRESPONSE_MAX;
2829                         dpsnprintf(sv_net_extresponse[sv_net_extresponse_last], sizeof(sv_net_extresponse[sv_net_extresponse_last]), "'%s' %s", addressstring2, string + 12);
2830                         return true;
2831                 }
2832                 if (!strncmp(string, "ping", 4))
2833                 {
2834                         if (developer_extra.integer)
2835                                 Con_DPrintf("Received ping from %s, sending ack\n", addressstring2);
2836                         NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
2837                         return true;
2838                 }
2839                 if (!strncmp(string, "ack", 3))
2840                         return true;
2841                 // we may not have liked the packet, but it was a command packet, so
2842                 // we're done processing this packet now
2843                 return true;
2844         }
2845         // netquake control packets, supported for compatibility only, and only
2846         // when running game protocols that are normally served via this connection
2847         // protocol
2848         // (this protects more modern protocols against being used for
2849         //  Quake packet flood Denial Of Service attacks)
2850         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))
2851         {
2852                 int c;
2853                 int protocolnumber;
2854                 const char *protocolname;
2855                 data += 4;
2856                 length -= 4;
2857                 SZ_Clear(&net_message);
2858                 SZ_Write(&net_message, data, length);
2859                 MSG_BeginReading();
2860                 c = MSG_ReadByte();
2861                 switch (c)
2862                 {
2863                 case CCREQ_CONNECT:
2864                         if (developer_extra.integer)
2865                                 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
2866                         if(!islocal && sv_public.integer <= -2)
2867                                 break;
2868
2869                         protocolname = MSG_ReadString();
2870                         protocolnumber = MSG_ReadByte();
2871                         if (strcmp(protocolname, "QUAKE") || protocolnumber != NET_PROTOCOL_VERSION)
2872                         {
2873                                 if (developer_extra.integer)
2874                                         Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
2875                                 SZ_Clear(&net_message);
2876                                 // save space for the header, filled in later
2877                                 MSG_WriteLong(&net_message, 0);
2878                                 MSG_WriteByte(&net_message, CCREP_REJECT);
2879                                 MSG_WriteString(&net_message, "Incompatible version.\n");
2880                                 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2881                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2882                                 SZ_Clear(&net_message);
2883                                 break;
2884                         }
2885
2886                         // see if this connect request comes from a known client
2887                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2888                         {
2889                                 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2890                                 {
2891                                         // this is either a duplicate connection request
2892                                         // or coming back from a timeout
2893                                         // (if so, keep their stuff intact)
2894
2895                                         // send a reply
2896                                         if (developer_extra.integer)
2897                                                 Con_DPrintf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
2898                                         SZ_Clear(&net_message);
2899                                         // save space for the header, filled in later
2900                                         MSG_WriteLong(&net_message, 0);
2901                                         MSG_WriteByte(&net_message, CCREP_ACCEPT);
2902                                         MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
2903                                         StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2904                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2905                                         SZ_Clear(&net_message);
2906
2907                                         // if client is already spawned, re-send the
2908                                         // serverinfo message as they'll need it to play
2909                                         if (client->spawned)
2910                                         {
2911                                                 SV_VM_Begin();
2912                                                 SV_SendServerinfo(client);
2913                                                 SV_VM_End();
2914                                         }
2915                                         return true;
2916                                 }
2917                         }
2918
2919                         // this is a new client, check for connection flood
2920                         if (NetConn_PreventConnectFlood(peeraddress))
2921                                 break;
2922
2923                         // find a slot for the new client
2924                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2925                         {
2926                                 netconn_t *conn;
2927                                 if (!client->active && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
2928                                 {
2929                                         // connect to the client
2930                                         // everything is allocated, just fill in the details
2931                                         strlcpy (conn->address, addressstring2, sizeof (conn->address));
2932                                         if (developer_extra.integer)
2933                                                 Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
2934                                         // send back the info about the server connection
2935                                         SZ_Clear(&net_message);
2936                                         // save space for the header, filled in later
2937                                         MSG_WriteLong(&net_message, 0);
2938                                         MSG_WriteByte(&net_message, CCREP_ACCEPT);
2939                                         MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
2940                                         StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2941                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2942                                         SZ_Clear(&net_message);
2943                                         // now set up the client struct
2944                                         SV_VM_Begin();
2945                                         SV_ConnectClient(clientnum, conn);
2946                                         SV_VM_End();
2947                                         NetConn_Heartbeat(1);
2948                                         return true;
2949                                 }
2950                         }
2951
2952                         if (developer_extra.integer)
2953                                 Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
2954                         // no room; try to let player know
2955                         SZ_Clear(&net_message);
2956                         // save space for the header, filled in later
2957                         MSG_WriteLong(&net_message, 0);
2958                         MSG_WriteByte(&net_message, CCREP_REJECT);
2959                         MSG_WriteString(&net_message, "Server is full.\n");
2960                         StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2961                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2962                         SZ_Clear(&net_message);
2963                         break;
2964                 case CCREQ_SERVER_INFO:
2965                         if (developer_extra.integer)
2966                                 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
2967                         if(!islocal && sv_public.integer <= -1)
2968                                 break;
2969                         if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
2970                         {
2971                                 int numclients;
2972                                 char myaddressstring[128];
2973                                 if (developer_extra.integer)
2974                                         Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
2975                                 SZ_Clear(&net_message);
2976                                 // save space for the header, filled in later
2977                                 MSG_WriteLong(&net_message, 0);
2978                                 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
2979                                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), myaddressstring, sizeof(myaddressstring), true);
2980                                 MSG_WriteString(&net_message, myaddressstring);
2981                                 MSG_WriteString(&net_message, hostname.string);
2982                                 MSG_WriteString(&net_message, sv.name);
2983                                 // How many clients are there?
2984                                 for (i = 0, numclients = 0;i < svs.maxclients;i++)
2985                                         if (svs.clients[i].active)
2986                                                 numclients++;
2987                                 MSG_WriteByte(&net_message, numclients);
2988                                 MSG_WriteByte(&net_message, svs.maxclients);
2989                                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2990                                 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2991                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2992                                 SZ_Clear(&net_message);
2993                         }
2994                         break;
2995                 case CCREQ_PLAYER_INFO:
2996                         if (developer_extra.integer)
2997                                 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
2998                         if(!islocal && sv_public.integer <= -1)
2999                                 break;
3000                         if (sv.active)
3001                         {
3002                                 int playerNumber, activeNumber, clientNumber;
3003                                 client_t *client;
3004
3005                                 playerNumber = MSG_ReadByte();
3006                                 activeNumber = -1;
3007                                 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
3008                                         if (client->active && ++activeNumber == playerNumber)
3009                                                 break;
3010                                 if (clientNumber != svs.maxclients)
3011                                 {
3012                                         SZ_Clear(&net_message);
3013                                         // save space for the header, filled in later
3014                                         MSG_WriteLong(&net_message, 0);
3015                                         MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
3016                                         MSG_WriteByte(&net_message, playerNumber);
3017                                         MSG_WriteString(&net_message, client->name);
3018                                         MSG_WriteLong(&net_message, client->colors);
3019                                         MSG_WriteLong(&net_message, client->frags);
3020                                         MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
3021                                         MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
3022                                         StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
3023                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
3024                                         SZ_Clear(&net_message);
3025                                 }
3026                         }
3027                         break;
3028                 case CCREQ_RULE_INFO:
3029                         if (developer_extra.integer)
3030                                 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
3031                         if(!islocal && sv_public.integer <= -1)
3032                                 break;
3033                         if (sv.active)
3034                         {
3035                                 char *prevCvarName;
3036                                 cvar_t *var;
3037
3038                                 // find the search start location
3039                                 prevCvarName = MSG_ReadString();
3040                                 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
3041
3042                                 // send the response
3043                                 SZ_Clear(&net_message);
3044                                 // save space for the header, filled in later
3045                                 MSG_WriteLong(&net_message, 0);
3046                                 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
3047                                 if (var)
3048                                 {
3049                                         MSG_WriteString(&net_message, var->name);
3050                                         MSG_WriteString(&net_message, var->string);
3051                                 }
3052                                 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
3053                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
3054                                 SZ_Clear(&net_message);
3055                         }
3056                         break;
3057                 default:
3058                         break;
3059                 }
3060                 SZ_Clear(&net_message);
3061                 // we may not have liked the packet, but it was a valid control
3062                 // packet, so we're done processing this packet now
3063                 return true;
3064         }
3065         if (host_client)
3066         {
3067                 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length, sv.protocol, host_client->spawned ? net_messagetimeout.value : net_connecttimeout.value)) == 2)
3068                 {
3069                         SV_VM_Begin();
3070                         SV_ReadClientMessage();
3071                         SV_VM_End();
3072                         return ret;
3073                 }
3074         }
3075         return 0;
3076 }
3077
3078 void NetConn_ServerFrame(void)
3079 {
3080         int i, length;
3081         lhnetaddress_t peeraddress;
3082         for (i = 0;i < sv_numsockets;i++)
3083                 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
3084                         NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
3085         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
3086         {
3087                 // never timeout loopback connections
3088                 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
3089                 {
3090                         Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
3091                         SV_VM_Begin();
3092                         SV_DropClient(false);
3093                         SV_VM_End();
3094                 }
3095         }
3096 }
3097
3098 void NetConn_SleepMicroseconds(int microseconds)
3099 {
3100         LHNET_SleepUntilPacket_Microseconds(microseconds);
3101 }
3102
3103 void NetConn_QueryMasters(qboolean querydp, qboolean queryqw)
3104 {
3105         int i, j;
3106         int masternum;
3107         lhnetaddress_t masteraddress;
3108         lhnetaddress_t broadcastaddress;
3109         char request[256];
3110
3111         if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
3112                 return;
3113
3114         // 26000 is the default quake server port, servers on other ports will not
3115         // be found
3116         // note this is IPv4-only, I doubt there are IPv6-only LANs out there
3117         LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
3118
3119         if (querydp)
3120         {
3121                 for (i = 0;i < cl_numsockets;i++)
3122                 {
3123                         if (cl_sockets[i])
3124                         {
3125                                 const char *cmdname, *extraoptions;
3126                                 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
3127
3128                                 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
3129                                 {
3130                                         // search LAN for Quake servers
3131                                         SZ_Clear(&net_message);
3132                                         // save space for the header, filled in later
3133                                         MSG_WriteLong(&net_message, 0);
3134                                         MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
3135                                         MSG_WriteString(&net_message, "QUAKE");
3136                                         MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
3137                                         StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
3138                                         NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
3139                                         SZ_Clear(&net_message);
3140
3141                                         // search LAN for DarkPlaces servers
3142                                         NetConn_WriteString(cl_sockets[i], "\377\377\377\377getstatus", &broadcastaddress);
3143                                 }
3144
3145                                 // build the getservers message to send to the dpmaster master servers
3146                                 if (LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == LHNETADDRESSTYPE_INET6)
3147                                 {
3148                                         cmdname = "getserversExt";
3149                                         extraoptions = " ipv4 ipv6";  // ask for IPv4 and IPv6 servers
3150                                 }
3151                                 else
3152                                 {
3153                                         cmdname = "getservers";
3154                                         extraoptions = "";
3155                                 }
3156                                 dpsnprintf(request, sizeof(request), "\377\377\377\377%s %s %u empty full%s", cmdname, gamename, NET_PROTOCOL_VERSION, extraoptions);
3157
3158                                 // search internet
3159                                 for (masternum = 0;sv_masters[masternum].name;masternum++)
3160                                 {
3161                                         if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == af)
3162                                         {
3163                                                 masterquerycount++;
3164                                                 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
3165                                         }
3166                                 }
3167
3168                                 // search favorite servers
3169                                 for(j = 0; j < nFavorites; ++j)
3170                                 {
3171                                         if(LHNETADDRESS_GetAddressType(&favorites[j]) == af)
3172                                         {
3173                                                 if(LHNETADDRESS_ToString(&favorites[j], request, sizeof(request), true))
3174                                                         NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, request, true );
3175                                         }
3176                                 }
3177                         }
3178                 }
3179         }
3180
3181         // only query QuakeWorld servers when the user wants to
3182         if (queryqw)
3183         {
3184                 for (i = 0;i < cl_numsockets;i++)
3185                 {
3186                         if (cl_sockets[i])
3187                         {
3188                                 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
3189
3190                                 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
3191                                 {
3192                                         // search LAN for QuakeWorld servers
3193                                         NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &broadcastaddress);
3194
3195                                         // build the getservers message to send to the qwmaster master servers
3196                                         // note this has no -1 prefix, and the trailing nul byte is sent
3197                                         dpsnprintf(request, sizeof(request), "c\n");
3198                                 }
3199
3200                                 // search internet
3201                                 for (masternum = 0;sv_qwmasters[masternum].name;masternum++)
3202                                 {
3203                                         if (sv_qwmasters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_qwmasters[masternum].string, QWMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
3204                                         {
3205                                                 if (m_state != m_slist)
3206                                                 {
3207                                                         char lookupstring[128];
3208                                                         LHNETADDRESS_ToString(&masteraddress, lookupstring, sizeof(lookupstring), true);
3209                                                         Con_Printf("Querying master %s (resolved from %s)\n", lookupstring, sv_qwmasters[masternum].string);
3210                                                 }
3211                                                 masterquerycount++;
3212                                                 NetConn_Write(cl_sockets[i], request, (int)strlen(request) + 1, &masteraddress);
3213                                         }
3214                                 }
3215
3216                                 // search favorite servers
3217                                 for(j = 0; j < nFavorites; ++j)
3218                                 {
3219                                         if(LHNETADDRESS_GetAddressType(&favorites[j]) == af)
3220                                         {
3221                                                 if(LHNETADDRESS_ToString(&favorites[j], request, sizeof(request), true))
3222                                                 {
3223                                                         NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &favorites[j]);
3224                                                         NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, request, true );
3225                                                 }
3226                                         }
3227                                 }
3228                         }
3229                 }
3230         }
3231         if (!masterquerycount)
3232         {
3233                 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
3234                 M_Update_Return_Reason("No network");
3235         }
3236 }
3237
3238 void NetConn_Heartbeat(int priority)
3239 {
3240         lhnetaddress_t masteraddress;
3241         int masternum;
3242         lhnetsocket_t *mysocket;
3243
3244         // if it's a state change (client connected), limit next heartbeat to no
3245         // more than 30 sec in the future
3246         if (priority == 1 && nextheartbeattime > realtime + 30.0)
3247                 nextheartbeattime = realtime + 30.0;
3248
3249         // limit heartbeatperiod to 30 to 270 second range,
3250         // lower limit is to avoid abusing master servers with excess traffic,
3251         // upper limit is to avoid timing out on the master server (which uses
3252         // 300 sec timeout)
3253         if (sv_heartbeatperiod.value < 30)
3254                 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
3255         if (sv_heartbeatperiod.value > 270)
3256                 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
3257
3258         // make advertising optional and don't advertise singleplayer games, and
3259         // only send a heartbeat as often as the admin wants
3260         if (sv.active && sv_public.integer > 0 && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
3261         {
3262                 nextheartbeattime = realtime + sv_heartbeatperiod.value;
3263                 for (masternum = 0;sv_masters[masternum].name;masternum++)
3264                         if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
3265                                 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
3266         }
3267 }
3268
3269 static void Net_Heartbeat_f(void)
3270 {
3271         if (sv.active)
3272                 NetConn_Heartbeat(2);
3273         else
3274                 Con_Print("No server running, can not heartbeat to master server.\n");
3275 }
3276
3277 void PrintStats(netconn_t *conn)
3278 {
3279         if ((cls.state == ca_connected && cls.protocol == PROTOCOL_QUAKEWORLD) || (sv.active && sv.protocol == PROTOCOL_QUAKEWORLD))
3280                 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->outgoing_unreliable_sequence, conn->qw.incoming_sequence);
3281         else
3282                 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->nq.sendSequence, conn->nq.receiveSequence);
3283 }
3284
3285 void Net_Stats_f(void)
3286 {
3287         netconn_t *conn;
3288         Con_Printf("unreliable messages sent   = %i\n", unreliableMessagesSent);
3289         Con_Printf("unreliable messages recv   = %i\n", unreliableMessagesReceived);
3290         Con_Printf("reliable messages sent     = %i\n", reliableMessagesSent);
3291         Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
3292         Con_Printf("packetsSent                = %i\n", packetsSent);
3293         Con_Printf("packetsReSent              = %i\n", packetsReSent);
3294         Con_Printf("packetsReceived            = %i\n", packetsReceived);
3295         Con_Printf("receivedDuplicateCount     = %i\n", receivedDuplicateCount);
3296         Con_Printf("droppedDatagrams           = %i\n", droppedDatagrams);
3297         Con_Print("connections                =\n");
3298         for (conn = netconn_list;conn;conn = conn->next)
3299                 PrintStats(conn);
3300 }
3301
3302 void Net_Refresh_f(void)
3303 {
3304         if (m_state != m_slist) {
3305                 Con_Print("Sending new requests to master servers\n");
3306                 ServerList_QueryList(false, true, false, true);
3307                 Con_Print("Listening for replies...\n");
3308         } else
3309                 ServerList_QueryList(false, true, false, false);
3310 }
3311
3312 void Net_Slist_f(void)
3313 {
3314         ServerList_ResetMasks();
3315         serverlist_sortbyfield = SLIF_PING;
3316         serverlist_sortflags = 0;
3317     if (m_state != m_slist) {
3318                 Con_Print("Sending requests to master servers\n");
3319                 ServerList_QueryList(true, true, false, true);
3320                 Con_Print("Listening for replies...\n");
3321         } else
3322                 ServerList_QueryList(true, true, false, false);
3323 }
3324
3325 void Net_SlistQW_f(void)
3326 {
3327         ServerList_ResetMasks();
3328         serverlist_sortbyfield = SLIF_PING;
3329         serverlist_sortflags = 0;
3330     if (m_state != m_slist) {
3331                 Con_Print("Sending requests to master servers\n");
3332                 ServerList_QueryList(true, false, true, true);
3333                 serverlist_consoleoutput = true;
3334                 Con_Print("Listening for replies...\n");
3335         } else
3336                 ServerList_QueryList(true, false, true, false);
3337 }
3338
3339 void NetConn_Init(void)
3340 {
3341         int i;
3342         lhnetaddress_t tempaddress;
3343         netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
3344         Cmd_AddCommand("net_stats", Net_Stats_f, "print network statistics");
3345         Cmd_AddCommand("net_slist", Net_Slist_f, "query dp master servers and print all server information");
3346         Cmd_AddCommand("net_slistqw", Net_SlistQW_f, "query qw master servers and print all server information");
3347         Cmd_AddCommand("net_refresh", Net_Refresh_f, "query dp master servers and refresh all server information");
3348         Cmd_AddCommand("heartbeat", Net_Heartbeat_f, "send a heartbeat to the master server (updates your server information)");
3349         Cvar_RegisterVariable(&rcon_restricted_password);
3350         Cvar_RegisterVariable(&rcon_restricted_commands);
3351         Cvar_RegisterVariable(&rcon_secure_maxdiff);
3352         Cvar_RegisterVariable(&net_slist_queriespersecond);
3353         Cvar_RegisterVariable(&net_slist_queriesperframe);
3354         Cvar_RegisterVariable(&net_slist_timeout);
3355         Cvar_RegisterVariable(&net_slist_maxtries);
3356         Cvar_RegisterVariable(&net_slist_favorites);
3357         Cvar_RegisterVariable(&net_slist_pause);
3358         Cvar_RegisterVariable(&net_messagetimeout);
3359         Cvar_RegisterVariable(&net_connecttimeout);
3360         Cvar_RegisterVariable(&net_connectfloodblockingtimeout);
3361         Cvar_RegisterVariable(&cl_netlocalping);
3362         Cvar_RegisterVariable(&cl_netpacketloss_send);
3363         Cvar_RegisterVariable(&cl_netpacketloss_receive);
3364         Cvar_RegisterVariable(&hostname);
3365         Cvar_RegisterVariable(&developer_networking);
3366         Cvar_RegisterVariable(&cl_netport);
3367         Cvar_RegisterVariable(&sv_netport);
3368         Cvar_RegisterVariable(&net_address);
3369         Cvar_RegisterVariable(&net_address_ipv6);
3370         Cvar_RegisterVariable(&sv_public);
3371         Cvar_RegisterVariable(&sv_heartbeatperiod);
3372         for (i = 0;sv_masters[i].name;i++)
3373                 Cvar_RegisterVariable(&sv_masters[i]);
3374         Cvar_RegisterVariable(&gameversion);
3375         Cvar_RegisterVariable(&gameversion_min);
3376         Cvar_RegisterVariable(&gameversion_max);
3377 // 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.
3378         if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
3379         {
3380                 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
3381                 {
3382                         Con_Printf("-ip option used, setting net_address to \"%s\"\n", com_argv[i + 1]);
3383                         Cvar_SetQuick(&net_address, com_argv[i + 1]);
3384                 }
3385                 else
3386                         Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
3387         }
3388 // 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
3389         if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
3390         {
3391                 i = atoi(com_argv[i + 1]);
3392                 if (i >= 0 && i < 65536)
3393                 {
3394                         Con_Printf("-port option used, setting port cvar to %i\n", i);
3395                         Cvar_SetValueQuick(&sv_netport, i);
3396                 }
3397                 else
3398                         Con_Printf("-port option used, but %i is not a valid port number\n", i);
3399         }
3400         cl_numsockets = 0;
3401         sv_numsockets = 0;
3402         net_message.data = net_message_buf;
3403         net_message.maxsize = sizeof(net_message_buf);
3404         net_message.cursize = 0;
3405         LHNET_Init();
3406 }
3407
3408 void NetConn_Shutdown(void)
3409 {
3410         NetConn_CloseClientPorts();
3411         NetConn_CloseServerPorts();
3412         LHNET_Shutdown();
3413 }
3414