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