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