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