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