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