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