]> icculus.org git repositories - divverent/darkplaces.git/blob - netconn.c
Increased the size of the text box containing the name of the server to join, so...
[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 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
877 {
878         lhnetaddress_t address;
879         lhnetsocket_t *s;
880         int port;
881         char addressstring2[1024];
882
883         for (port = defaultport; port <= defaultport + 100; 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                                 break;
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                         break;
905                 }
906         }
907 }
908
909 void NetConn_OpenServerPorts(int opennetports)
910 {
911         int port;
912         NetConn_CloseServerPorts();
913         NetConn_UpdateSockets();
914         port = bound(0, sv_netport.integer, 65535);
915         if (port == 0)
916                 port = 26000;
917         Con_Printf("Server using port %i\n", port);
918         if (sv_netport.integer != port)
919                 Cvar_SetValueQuick(&sv_netport, port);
920         if (cls.state != ca_dedicated)
921                 NetConn_OpenServerPort("local:1", 0);
922         if (opennetports)
923         {
924                 NetConn_OpenServerPort(net_address.string, port);
925                 NetConn_OpenServerPort(net_address_ipv6.string, port);
926         }
927         if (sv_numsockets == 0)
928                 Host_Error("NetConn_OpenServerPorts: unable to open any ports!");
929 }
930
931 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
932 {
933         int i, a = LHNETADDRESS_GetAddressType(address);
934         for (i = 0;i < cl_numsockets;i++)
935                 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
936                         return cl_sockets[i];
937         return NULL;
938 }
939
940 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
941 {
942         int i, a = LHNETADDRESS_GetAddressType(address);
943         for (i = 0;i < sv_numsockets;i++)
944                 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
945                         return sv_sockets[i];
946         return NULL;
947 }
948
949 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
950 {
951         netconn_t *conn;
952         conn = (netconn_t *)Mem_Alloc(netconn_mempool, sizeof(*conn));
953         conn->mysocket = mysocket;
954         conn->peeraddress = *peeraddress;
955         conn->lastMessageTime = realtime;
956         conn->message.data = conn->messagedata;
957         conn->message.maxsize = sizeof(conn->messagedata);
958         conn->message.cursize = 0;
959         // LordHavoc: (inspired by ProQuake) use a short connect timeout to
960         // reduce effectiveness of connection request floods
961         conn->timeout = realtime + net_connecttimeout.value;
962         LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
963         conn->next = netconn_list;
964         netconn_list = conn;
965         return conn;
966 }
967
968 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress);
969 void NetConn_Close(netconn_t *conn)
970 {
971         netconn_t *c;
972         // remove connection from list
973
974         // allow the client to reconnect immediately
975         NetConn_ClearConnectFlood(&(conn->peeraddress));
976
977         if (conn == netconn_list)
978                 netconn_list = conn->next;
979         else
980         {
981                 for (c = netconn_list;c;c = c->next)
982                 {
983                         if (c->next == conn)
984                         {
985                                 c->next = conn->next;
986                                 break;
987                         }
988                 }
989                 // not found in list, we'll avoid crashing here...
990                 if (!c)
991                         return;
992         }
993         // free connection
994         Mem_Free(conn);
995 }
996
997 static int clientport = -1;
998 static int clientport2 = -1;
999 static int hostport = -1;
1000 void NetConn_UpdateSockets(void)
1001 {
1002         if (cls.state != ca_dedicated)
1003         {
1004                 if (clientport2 != cl_netport.integer)
1005                 {
1006                         clientport2 = cl_netport.integer;
1007                         if (cls.state == ca_connected)
1008                                 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
1009                 }
1010                 if (cls.state == ca_disconnected && clientport != clientport2)
1011                 {
1012                         clientport = clientport2;
1013                         NetConn_CloseClientPorts();
1014                 }
1015                 if (cl_numsockets == 0)
1016                         NetConn_OpenClientPorts();
1017         }
1018
1019         if (hostport != sv_netport.integer)
1020         {
1021                 hostport = sv_netport.integer;
1022                 if (sv.active)
1023                         Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
1024         }
1025 }
1026
1027 static int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int length, protocolversion_t protocol, double newtimeout)
1028 {
1029         int originallength = length;
1030         if (length < 8)
1031                 return 0;
1032
1033         if (protocol == PROTOCOL_QUAKEWORLD)
1034         {
1035                 int sequence, sequence_ack;
1036                 int reliable_ack, reliable_message;
1037                 int count;
1038                 int qport;
1039
1040                 sequence = LittleLong(*((int *)(data + 0)));
1041                 sequence_ack = LittleLong(*((int *)(data + 4)));
1042                 data += 8;
1043                 length -= 8;
1044
1045                 if (conn != cls.netcon)
1046                 {
1047                         // server only
1048                         if (length < 2)
1049                                 return 0;
1050                         // 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?)
1051                         qport = LittleShort(*((int *)(data + 8)));
1052                         data += 2;
1053                         length -= 2;
1054                 }
1055
1056                 packetsReceived++;
1057                 reliable_message = (sequence >> 31) & 1;
1058                 reliable_ack = (sequence_ack >> 31) & 1;
1059                 sequence &= ~(1<<31);
1060                 sequence_ack &= ~(1<<31);
1061                 if (sequence <= conn->qw.incoming_sequence)
1062                 {
1063                         //Con_DPrint("Got a stale datagram\n");
1064                         return 0;
1065                 }
1066                 count = sequence - (conn->qw.incoming_sequence + 1);
1067                 if (count > 0)
1068                 {
1069                         droppedDatagrams += count;
1070                         //Con_DPrintf("Dropped %u datagram(s)\n", count);
1071                         while (count--)
1072                         {
1073                                 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1074                                 conn->incoming_unreliablesize[conn->incoming_packetcounter] = NETGRAPH_LOSTPACKET;
1075                                 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1076                                 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1077                         }
1078                 }
1079                 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1080                 conn->incoming_unreliablesize[conn->incoming_packetcounter] = originallength;
1081                 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1082                 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1083                 if (reliable_ack == conn->qw.reliable_sequence)
1084                 {
1085                         // received, now we will be able to send another reliable message
1086                         conn->sendMessageLength = 0;
1087                         reliableMessagesReceived++;
1088                 }
1089                 conn->qw.incoming_sequence = sequence;
1090                 if (conn == cls.netcon)
1091                         cls.qw_incoming_sequence = conn->qw.incoming_sequence;
1092                 conn->qw.incoming_acknowledged = sequence_ack;
1093                 conn->qw.incoming_reliable_acknowledged = reliable_ack;
1094                 if (reliable_message)
1095                         conn->qw.incoming_reliable_sequence ^= 1;
1096                 conn->lastMessageTime = realtime;
1097                 conn->timeout = realtime + newtimeout;
1098                 unreliableMessagesReceived++;
1099                 SZ_Clear(&net_message);
1100                 SZ_Write(&net_message, data, length);
1101                 MSG_BeginReading();
1102                 return 2;
1103         }
1104         else
1105         {
1106                 unsigned int count;
1107                 unsigned int flags;
1108                 unsigned int sequence;
1109                 int qlength;
1110
1111                 qlength = (unsigned int)BigLong(((int *)data)[0]);
1112                 flags = qlength & ~NETFLAG_LENGTH_MASK;
1113                 qlength &= NETFLAG_LENGTH_MASK;
1114                 // control packets were already handled
1115                 if (!(flags & NETFLAG_CTL) && qlength == length)
1116                 {
1117                         sequence = BigLong(((int *)data)[1]);
1118                         packetsReceived++;
1119                         data += 8;
1120                         length -= 8;
1121                         if (flags & NETFLAG_UNRELIABLE)
1122                         {
1123                                 if (sequence >= conn->nq.unreliableReceiveSequence)
1124                                 {
1125                                         if (sequence > conn->nq.unreliableReceiveSequence)
1126                                         {
1127                                                 count = sequence - conn->nq.unreliableReceiveSequence;
1128                                                 droppedDatagrams += count;
1129                                                 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1130                                                 while (count--)
1131                                                 {
1132                                                         conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1133                                                         conn->incoming_unreliablesize[conn->incoming_packetcounter] = NETGRAPH_LOSTPACKET;
1134                                                         conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1135                                                         conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1136                                                 }
1137                                         }
1138                                         conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1139                                         conn->incoming_unreliablesize[conn->incoming_packetcounter] = originallength;
1140                                         conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1141                                         conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1142                                         conn->nq.unreliableReceiveSequence = sequence + 1;
1143                                         conn->lastMessageTime = realtime;
1144                                         conn->timeout = realtime + newtimeout;
1145                                         unreliableMessagesReceived++;
1146                                         if (length > 0)
1147                                         {
1148                                                 SZ_Clear(&net_message);
1149                                                 SZ_Write(&net_message, data, length);
1150                                                 MSG_BeginReading();
1151                                                 return 2;
1152                                         }
1153                                 }
1154                                 //else
1155                                 //      Con_DPrint("Got a stale datagram\n");
1156                                 return 1;
1157                         }
1158                         else if (flags & NETFLAG_ACK)
1159                         {
1160                                 conn->incoming_acksize[conn->incoming_packetcounter] += originallength;
1161                                 if (sequence == (conn->nq.sendSequence - 1))
1162                                 {
1163                                         if (sequence == conn->nq.ackSequence)
1164                                         {
1165                                                 conn->nq.ackSequence++;
1166                                                 if (conn->nq.ackSequence != conn->nq.sendSequence)
1167                                                         Con_DPrint("ack sequencing error\n");
1168                                                 conn->lastMessageTime = realtime;
1169                                                 conn->timeout = realtime + newtimeout;
1170                                                 if (conn->sendMessageLength > MAX_PACKETFRAGMENT)
1171                                                 {
1172                                                         unsigned int packetLen;
1173                                                         unsigned int dataLen;
1174                                                         unsigned int eom;
1175                                                         unsigned int *header;
1176
1177                                                         conn->sendMessageLength -= MAX_PACKETFRAGMENT;
1178                                                         memmove(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
1179
1180                                                         if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
1181                                                         {
1182                                                                 dataLen = conn->sendMessageLength;
1183                                                                 eom = NETFLAG_EOM;
1184                                                         }
1185                                                         else
1186                                                         {
1187                                                                 dataLen = MAX_PACKETFRAGMENT;
1188                                                                 eom = 0;
1189                                                         }
1190
1191                                                         packetLen = NET_HEADERSIZE + dataLen;
1192
1193                                                         header = (unsigned int *)sendbuffer;
1194                                                         header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
1195                                                         header[1] = BigLong(conn->nq.sendSequence);
1196                                                         memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
1197
1198                                                         conn->nq.sendSequence++;
1199
1200                                                         if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
1201                                                         {
1202                                                                 conn->lastSendTime = realtime;
1203                                                                 packetsSent++;
1204                                                         }
1205                                                 }
1206                                                 else
1207                                                         conn->sendMessageLength = 0;
1208                                         }
1209                                         //else
1210                                         //      Con_DPrint("Duplicate ACK received\n");
1211                                 }
1212                                 //else
1213                                 //      Con_DPrint("Stale ACK received\n");
1214                                 return 1;
1215                         }
1216                         else if (flags & NETFLAG_DATA)
1217                         {
1218                                 unsigned int temppacket[2];
1219                                 conn->incoming_reliablesize[conn->incoming_packetcounter] += originallength;
1220                                 conn->outgoing_acksize[conn->outgoing_packetcounter] += 8;
1221                                 temppacket[0] = BigLong(8 | NETFLAG_ACK);
1222                                 temppacket[1] = BigLong(sequence);
1223                                 NetConn_Write(conn->mysocket, (unsigned char *)temppacket, 8, &conn->peeraddress);
1224                                 if (sequence == conn->nq.receiveSequence)
1225                                 {
1226                                         conn->lastMessageTime = realtime;
1227                                         conn->timeout = realtime + newtimeout;
1228                                         conn->nq.receiveSequence++;
1229                                         if( conn->receiveMessageLength + length <= (int)sizeof( conn->receiveMessage ) ) {
1230                                                 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
1231                                                 conn->receiveMessageLength += length;
1232                                         } else {
1233                                                 Con_Printf( "Reliable message (seq: %i) too big for message buffer!\n"
1234                                                                         "Dropping the message!\n", sequence );
1235                                                 conn->receiveMessageLength = 0;
1236                                                 return 1;
1237                                         }
1238                                         if (flags & NETFLAG_EOM)
1239                                         {
1240                                                 reliableMessagesReceived++;
1241                                                 length = conn->receiveMessageLength;
1242                                                 conn->receiveMessageLength = 0;
1243                                                 if (length > 0)
1244                                                 {
1245                                                         SZ_Clear(&net_message);
1246                                                         SZ_Write(&net_message, conn->receiveMessage, length);
1247                                                         MSG_BeginReading();
1248                                                         return 2;
1249                                                 }
1250                                         }
1251                                 }
1252                                 else
1253                                         receivedDuplicateCount++;
1254                                 return 1;
1255                         }
1256                 }
1257         }
1258         return 0;
1259 }
1260
1261 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, protocolversion_t initialprotocol)
1262 {
1263         cls.connect_trying = false;
1264         M_Update_Return_Reason("");
1265         // the connection request succeeded, stop current connection and set up a new connection
1266         CL_Disconnect();
1267         // if we're connecting to a remote server, shut down any local server
1268         if (LHNETADDRESS_GetAddressType(peeraddress) != LHNETADDRESSTYPE_LOOP && sv.active)
1269                 Host_ShutdownServer ();
1270         // allocate a net connection to keep track of things
1271         cls.netcon = NetConn_Open(mysocket, peeraddress);
1272         Con_Printf("Connection accepted to %s\n", cls.netcon->address);
1273         key_dest = key_game;
1274         m_state = m_none;
1275         cls.demonum = -1;                       // not in the demo loop now
1276         cls.state = ca_connected;
1277         cls.signon = 0;                         // need all the signon messages before playing
1278         cls.protocol = initialprotocol;
1279         // reset move sequence numbering on this new connection
1280         cls.servermovesequence = 0;
1281         if (cls.protocol == PROTOCOL_QUAKEWORLD)
1282                 Cmd_ForwardStringToServer("new");
1283         if (cls.protocol == PROTOCOL_QUAKE)
1284         {
1285                 // write a keepalive (clc_nop) as it seems to greatly improve the
1286                 // chances of connecting to a netquake server
1287                 sizebuf_t msg;
1288                 unsigned char buf[4];
1289                 memset(&msg, 0, sizeof(msg));
1290                 msg.data = buf;
1291                 msg.maxsize = sizeof(buf);
1292                 MSG_WriteChar(&msg, clc_nop);
1293                 NetConn_SendUnreliableMessage(cls.netcon, &msg, cls.protocol, 10000, false);
1294         }
1295 }
1296
1297 int NetConn_IsLocalGame(void)
1298 {
1299         if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
1300                 return true;
1301         return false;
1302 }
1303
1304 static int NetConn_ClientParsePacket_ServerList_ProcessReply(const char *addressstring)
1305 {
1306         int n;
1307         int pingtime;
1308         serverlist_entry_t *entry = NULL;
1309
1310         // search the cache for this server and update it
1311         for (n = 0;n < serverlist_cachecount;n++) {
1312                 entry = &serverlist_cache[ n ];
1313                 if (!strcmp(addressstring, entry->info.cname))
1314                         break;
1315         }
1316
1317         if (n == serverlist_cachecount)
1318         {
1319                 // LAN search doesnt require an answer from the master server so we wont
1320                 // know the ping nor will it be initialized already...
1321
1322                 // find a slot
1323                 if (serverlist_cachecount == SERVERLIST_TOTALSIZE)
1324                         return -1;
1325
1326                 entry = &serverlist_cache[n];
1327
1328                 memset(entry, 0, sizeof(*entry));
1329                 // store the data the engine cares about (address and ping)
1330                 strlcpy(entry->info.cname, addressstring, sizeof(entry->info.cname));
1331                 entry->info.ping = 100000;
1332                 entry->querytime = realtime;
1333                 // if not in the slist menu we should print the server to console
1334                 if (serverlist_consoleoutput)
1335                         Con_Printf("querying %s\n", addressstring);
1336                 ++serverlist_cachecount;
1337         }
1338         // if this is the first reply from this server, count it as having replied
1339         pingtime = (int)((realtime - entry->querytime) * 1000.0 + 0.5);
1340         pingtime = bound(0, pingtime, 9999);
1341         if (entry->query == SQS_REFRESHING) {
1342                 entry->info.ping = pingtime;
1343                 entry->query = SQS_QUERIED;
1344         } else {
1345                 // convert to unsigned to catch the -1
1346                 // 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]
1347                 entry->info.ping = min((unsigned) entry->info.ping, (unsigned) pingtime);
1348                 serverreplycount++;
1349         }
1350         
1351         // other server info is updated by the caller
1352         return n;
1353 }
1354
1355 static void NetConn_ClientParsePacket_ServerList_UpdateCache(int n)
1356 {
1357         serverlist_entry_t *entry = &serverlist_cache[n];
1358         serverlist_info_t *info = &entry->info;
1359         // update description strings for engine menu and console output
1360         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);
1361         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);
1362         if (entry->query == SQS_QUERIED)
1363         {
1364                 if(!serverlist_paused)
1365                         ServerList_ViewList_Remove(entry);
1366         }
1367         // if not in the slist menu we should print the server to console (if wanted)
1368         else if( serverlist_consoleoutput )
1369                 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1370         // and finally, update the view set
1371         if(!serverlist_paused)
1372                 ServerList_ViewList_Insert( entry );
1373         //      update the entry's state
1374         serverlist_cache[n].query = SQS_QUERIED;
1375 }
1376
1377 // returns true, if it's sensible to continue the processing
1378 static qboolean NetConn_ClientParsePacket_ServerList_PrepareQuery( int protocol, const char *ipstring, qboolean isfavorite ) {
1379         int n;
1380         serverlist_entry_t *entry;
1381
1382         //      ignore the rest of the message if the serverlist is full
1383         if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1384                 return false;
1385         //      also ignore     it      if      we      have already queried    it      (other master server    response)
1386         for( n =        0 ; n   < serverlist_cachecount ; n++   )
1387                 if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1388                         break;
1389
1390         entry = &serverlist_cache[n];
1391
1392         if( n < serverlist_cachecount ) {
1393                 // the entry has already been queried once or 
1394                 return true;
1395         }
1396
1397         memset(entry, 0, sizeof(entry));
1398         entry->protocol =       protocol;
1399         //      store   the data        the engine cares about (address and     ping)
1400         strlcpy (entry->info.cname, ipstring, sizeof(entry->info.cname));
1401
1402         entry->info.isfavorite = isfavorite;
1403         
1404         // no, then reset the ping right away
1405         entry->info.ping = -1;
1406         // we also want to increase the serverlist_cachecount then
1407         serverlist_cachecount++;
1408         serverquerycount++;
1409
1410         entry->query =  SQS_QUERYING;
1411
1412         return true;
1413 }
1414
1415 static void NetConn_ClientParsePacket_ServerList_ParseDPList(lhnetaddress_t *senderaddress, const unsigned char *data, int length, qboolean isextended)
1416 {
1417         masterreplycount++;
1418         if (serverlist_consoleoutput)
1419                 Con_Printf("received DarkPlaces %sserver list...\n", isextended ? "extended " : "");
1420         while (length >= 7)
1421         {
1422                 char ipstring [128];
1423
1424                 // IPv4 address
1425                 if (data[0] == '\\')
1426                 {
1427                         unsigned short port = data[5] * 256 + data[6];
1428
1429                         if (port != 0 && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF))
1430                                 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%hu", data[1], data[2], data[3], data[4], port);
1431
1432                         // move on to next address in packet
1433                         data += 7;
1434                         length -= 7;
1435                 }
1436                 // IPv6 address
1437                 else if (data[0] == '/' && isextended && length >= 19)
1438                 {
1439                         unsigned short port = data[17] * 256 + data[18];
1440
1441                         if (port != 0)
1442                         {
1443                                 const char *ifname;
1444
1445                                 // TODO: make some basic checks of the IP address (broadcast, ...)
1446
1447                                 ifname = LHNETADDRESS_GetInterfaceName(senderaddress);
1448                                 if (ifname != NULL)
1449                                 {
1450                                         dpsnprintf (ipstring, sizeof (ipstring), "[%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x%%%s]:%hu",
1451                                                                 data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8],
1452                                                                 data[9], data[10], data[11], data[12], data[13], data[14], data[15], data[16],
1453                                                                 ifname, port);
1454                                 }
1455                                 else
1456                                 {
1457                                         dpsnprintf (ipstring, sizeof (ipstring), "[%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x]:%hu",
1458                                                                 data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8],
1459                                                                 data[9], data[10], data[11], data[12], data[13], data[14], data[15], data[16],
1460                                                                 port);
1461                                 }
1462                         }
1463
1464                         // move on to next address in packet
1465                         data += 19;
1466                         length -= 19;
1467                 }
1468                 else
1469                 {
1470                         Con_Print("Error while parsing the server list\n");
1471                         break;
1472                 }
1473
1474                 if (serverlist_consoleoutput && developer_networking.integer)
1475                         Con_Printf("Requesting info from DarkPlaces server %s\n", ipstring);
1476                 
1477                 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, ipstring, false ) ) {
1478                         break;
1479                 }
1480
1481         }
1482
1483         // begin or resume serverlist queries
1484         serverlist_querysleep = false;
1485         serverlist_querywaittime = realtime + 3;
1486 }
1487
1488 static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1489 {
1490         qboolean fromserver;
1491         int ret, c, control;
1492         const char *s;
1493         char *string, addressstring2[128], ipstring[32];
1494         char stringbuf[16384];
1495
1496         // quakeworld ingame packet
1497         fromserver = cls.netcon && mysocket == cls.netcon->mysocket && !LHNETADDRESS_Compare(&cls.netcon->peeraddress, peeraddress);
1498
1499         // convert the address to a string incase we need it
1500         LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1501
1502         if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1503         {
1504                 // received a command string - strip off the packaging and put it
1505                 // into our string buffer with NULL termination
1506                 data += 4;
1507                 length -= 4;
1508                 length = min(length, (int)sizeof(stringbuf) - 1);
1509                 memcpy(stringbuf, data, length);
1510                 stringbuf[length] = 0;
1511                 string = stringbuf;
1512
1513                 if (developer_networking.integer)
1514                 {
1515                         Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
1516                         Com_HexDumpToConsole(data, length);
1517                 }
1518
1519                 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
1520                 {
1521                         // darkplaces or quake3
1522                         char protocolnames[1400];
1523                         Protocol_Names(protocolnames, sizeof(protocolnames));
1524                         Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
1525                         M_Update_Return_Reason("Got challenge response");
1526                         // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1527                         InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1528                         // TODO: add userinfo stuff here instead of using NQ commands?
1529                         NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\protocols\\%s\\challenge\\%s", protocolnames, string + 10), peeraddress);
1530                         return true;
1531                 }
1532                 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
1533                 {
1534                         // darkplaces or quake3
1535                         M_Update_Return_Reason("Accepted");
1536                         NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_DARKPLACES3);
1537                         return true;
1538                 }
1539                 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
1540                 {
1541                         char rejectreason[32];
1542                         cls.connect_trying = false;
1543                         string += 7;
1544                         length = min(length - 7, (int)sizeof(rejectreason) - 1);
1545                         memcpy(rejectreason, string, length);
1546                         rejectreason[length] = 0;
1547                         M_Update_Return_Reason(rejectreason);
1548                         return true;
1549                 }
1550                 if (length >= 15 && !memcmp(string, "statusResponse\x0A", 15))
1551                 {
1552                         serverlist_info_t *info;
1553                         char *p;
1554                         int n;
1555
1556                         string += 15;
1557                         // search the cache for this server and update it
1558                         n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1559                         if (n < 0)
1560                                 return true;
1561
1562                         info = &serverlist_cache[n].info;
1563                         info->game[0] = 0;
1564                         info->mod[0]  = 0;
1565                         info->map[0]  = 0;
1566                         info->name[0] = 0;
1567                         info->qcstatus[0] = 0;
1568                         info->players[0] = 0;
1569                         info->protocol = -1;
1570                         info->numplayers = 0;
1571                         info->numbots = -1;
1572                         info->maxplayers  = 0;
1573                         info->gameversion = 0;
1574
1575                         p = strchr(string, '\n');
1576                         if(p)
1577                         {
1578                                 *p = 0; // cut off the string there
1579                                 ++p;
1580                         }
1581                         else
1582                                 Con_Printf("statusResponse without players block?\n");
1583
1584                         if ((s = SearchInfostring(string, "gamename"     )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1585                         if ((s = SearchInfostring(string, "modname"      )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1586                         if ((s = SearchInfostring(string, "mapname"      )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1587                         if ((s = SearchInfostring(string, "hostname"     )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1588                         if ((s = SearchInfostring(string, "protocol"     )) != NULL) info->protocol = atoi(s);
1589                         if ((s = SearchInfostring(string, "clients"      )) != NULL) info->numplayers = atoi(s);
1590                         if ((s = SearchInfostring(string, "bots"         )) != NULL) info->numbots = atoi(s);
1591                         if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1592                         if ((s = SearchInfostring(string, "gameversion"  )) != NULL) info->gameversion = atoi(s);
1593                         if ((s = SearchInfostring(string, "qcstatus"     )) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1594                         if (p                                               != NULL) strlcpy(info->players, p, sizeof(info->players));
1595                         info->numhumans = info->numplayers - max(0, info->numbots);
1596                         info->freeslots = info->maxplayers - info->numplayers;
1597
1598                         NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1599
1600                         return true;
1601                 }
1602                 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
1603                 {
1604                         serverlist_info_t *info;
1605                         int n;
1606
1607                         string += 13;
1608                         // search the cache for this server and update it
1609                         n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1610                         if (n < 0)
1611                                 return true;
1612
1613                         info = &serverlist_cache[n].info;
1614                         info->game[0] = 0;
1615                         info->mod[0]  = 0;
1616                         info->map[0]  = 0;
1617                         info->name[0] = 0;
1618                         info->qcstatus[0] = 0;
1619                         info->players[0] = 0;
1620                         info->protocol = -1;
1621                         info->numplayers = 0;
1622                         info->numbots = -1;
1623                         info->maxplayers  = 0;
1624                         info->gameversion = 0;
1625
1626                         if ((s = SearchInfostring(string, "gamename"     )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1627                         if ((s = SearchInfostring(string, "modname"      )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1628                         if ((s = SearchInfostring(string, "mapname"      )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1629                         if ((s = SearchInfostring(string, "hostname"     )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1630                         if ((s = SearchInfostring(string, "protocol"     )) != NULL) info->protocol = atoi(s);
1631                         if ((s = SearchInfostring(string, "clients"      )) != NULL) info->numplayers = atoi(s);
1632                         if ((s = SearchInfostring(string, "bots"         )) != NULL) info->numbots = atoi(s);
1633                         if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1634                         if ((s = SearchInfostring(string, "gameversion"  )) != NULL) info->gameversion = atoi(s);
1635                         if ((s = SearchInfostring(string, "qcstatus"     )) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1636                         info->numhumans = info->numplayers - max(0, info->numbots);
1637                         info->freeslots = info->maxplayers - info->numplayers;
1638
1639                         NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1640
1641                         return true;
1642                 }
1643                 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1644                 {
1645                         // Extract the IP addresses
1646                         data += 18;
1647                         length -= 18;
1648                         NetConn_ClientParsePacket_ServerList_ParseDPList(peeraddress, data, length, false);
1649                         return true;
1650                 }
1651                 if (!strncmp(string, "getserversExtResponse", 21) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1652                 {
1653                         // Extract the IP addresses
1654                         data += 21;
1655                         length -= 21;
1656                         NetConn_ClientParsePacket_ServerList_ParseDPList(peeraddress, data, length, true);
1657                         return true;
1658                 }
1659                 if (!memcmp(string, "d\n", 2) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1660                 {
1661                         // Extract the IP addresses
1662                         data += 2;
1663                         length -= 2;
1664                         masterreplycount++;
1665                         if (serverlist_consoleoutput)
1666                                 Con_Printf("received QuakeWorld server list from %s...\n", addressstring2);
1667                         while (length >= 6 && (data[0] != 0xFF || data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF) && data[4] * 256 + data[5] != 0)
1668                         {
1669                                 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[0], data[1], data[2], data[3], data[4] * 256 + data[5]);
1670                                 if (serverlist_consoleoutput && developer_networking.integer)
1671                                         Con_Printf("Requesting info from QuakeWorld server %s\n", ipstring);
1672                                 
1673                                 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, ipstring, false ) ) {
1674                                         break;
1675                                 }
1676
1677                                 // move on to next address in packet
1678                                 data += 6;
1679                                 length -= 6;
1680                         }
1681                         // begin or resume serverlist queries
1682                         serverlist_querysleep = false;
1683                         serverlist_querywaittime = realtime + 3;
1684                         return true;
1685                 }
1686                 if (!strncmp(string, "extResponse ", 12))
1687                 {
1688                         ++net_extresponse_count;
1689                         if(net_extresponse_count > NET_EXTRESPONSE_MAX)
1690                                 net_extresponse_count = NET_EXTRESPONSE_MAX;
1691                         net_extresponse_last = (net_extresponse_last + 1) % NET_EXTRESPONSE_MAX;
1692                         dpsnprintf(net_extresponse[net_extresponse_last], sizeof(net_extresponse[net_extresponse_last]), "'%s' %s", addressstring2, string + 12);
1693                         return true;
1694                 }
1695                 if (!strncmp(string, "ping", 4))
1696                 {
1697                         if (developer.integer >= 10)
1698                                 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
1699                         NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1700                         return true;
1701                 }
1702                 if (!strncmp(string, "ack", 3))
1703                         return true;
1704                 // QuakeWorld compatibility
1705                 if (length > 1 && string[0] == 'c' && (string[1] == '-' || (string[1] >= '0' && string[1] <= '9')) && cls.connect_trying)
1706                 {
1707                         // challenge message
1708                         Con_Printf("challenge %s received, sending QuakeWorld connect request back to %s\n", string + 1, addressstring2);
1709                         M_Update_Return_Reason("Got QuakeWorld challenge response");
1710                         cls.qw_qport = qport.integer;
1711                         // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1712                         InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1713                         NetConn_WriteString(mysocket, va("\377\377\377\377connect %i %i %i \"%s\"\n", 28, cls.qw_qport, atoi(string + 1), cls.userinfo), peeraddress);
1714                         return true;
1715                 }
1716                 if (length >= 1 && string[0] == 'j' && cls.connect_trying)
1717                 {
1718                         // accept message
1719                         M_Update_Return_Reason("QuakeWorld Accepted");
1720                         NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_QUAKEWORLD);
1721                         return true;
1722                 }
1723                 if (length > 2 && !memcmp(string, "n\\", 2))
1724                 {
1725                         serverlist_info_t *info;
1726                         int n;
1727
1728                         // qw server status
1729                         if (serverlist_consoleoutput && developer_networking.integer >= 2)
1730                                 Con_Printf("QW server status from server at %s:\n%s\n", addressstring2, string + 1);
1731
1732                         string += 1;
1733                         // search the cache for this server and update it
1734                         n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1735                         if (n < 0)
1736                                 return true;
1737
1738                         info = &serverlist_cache[n].info;
1739                         strlcpy(info->game, "QuakeWorld", sizeof(info->game));
1740                         if ((s = SearchInfostring(string, "*gamedir"     )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0]  = 0;
1741                         if ((s = SearchInfostring(string, "map"          )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0]  = 0;
1742                         if ((s = SearchInfostring(string, "hostname"     )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
1743                         info->protocol = 0;
1744                         info->numplayers = 0; // updated below
1745                         info->numhumans = 0; // updated below
1746                         if ((s = SearchInfostring(string, "maxclients"   )) != NULL) info->maxplayers = atoi(s);else info->maxplayers  = 0;
1747                         if ((s = SearchInfostring(string, "gameversion"  )) != NULL) info->gameversion = atoi(s);else info->gameversion = 0;
1748
1749                         // count active players on server
1750                         // (we could gather more info, but we're just after the number)
1751                         s = strchr(string, '\n');
1752                         if (s)
1753                         {
1754                                 s++;
1755                                 while (s < string + length)
1756                                 {
1757                                         for (;s < string + length && *s != '\n';s++)
1758                                                 ;
1759                                         if (s >= string + length)
1760                                                 break;
1761                                         info->numplayers++;
1762                                         info->numhumans++;
1763                                         s++;
1764                                 }
1765                         }
1766
1767                         NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1768
1769                         return true;
1770                 }
1771                 if (string[0] == 'n')
1772                 {
1773                         // qw print command
1774                         Con_Printf("QW print command from server at %s:\n%s\n", addressstring2, string + 1);
1775                 }
1776                 // we may not have liked the packet, but it was a command packet, so
1777                 // we're done processing this packet now
1778                 return true;
1779         }
1780         // quakeworld ingame packet
1781         if (fromserver && cls.protocol == PROTOCOL_QUAKEWORLD && length >= 8 && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1782         {
1783                 ret = 0;
1784                 CL_ParseServerMessage();
1785                 return ret;
1786         }
1787         // netquake control packets, supported for compatibility only
1788         if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1789         {
1790                 int n;
1791                 serverlist_info_t *info;
1792
1793                 data += 4;
1794                 length -= 4;
1795                 SZ_Clear(&net_message);
1796                 SZ_Write(&net_message, data, length);
1797                 MSG_BeginReading();
1798                 c = MSG_ReadByte();
1799                 switch (c)
1800                 {
1801                 case CCREP_ACCEPT:
1802                         if (developer.integer >= 10)
1803                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1804                         if (cls.connect_trying)
1805                         {
1806                                 lhnetaddress_t clientportaddress;
1807                                 clientportaddress = *peeraddress;
1808                                 LHNETADDRESS_SetPort(&clientportaddress, MSG_ReadLong());
1809                                 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1810                                 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1811                                 M_Update_Return_Reason("Accepted");
1812                                 NetConn_ConnectionEstablished(mysocket, &clientportaddress, PROTOCOL_QUAKE);
1813                         }
1814                         break;
1815                 case CCREP_REJECT:
1816                         if (developer.integer >= 10)
1817                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1818                         cls.connect_trying = false;
1819                         M_Update_Return_Reason((char *)MSG_ReadString());
1820                         break;
1821                 case CCREP_SERVER_INFO:
1822                         if (developer.integer >= 10)
1823                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1824                         // LordHavoc: because the quake server may report weird addresses
1825                         // we just ignore it and keep the real address
1826                         MSG_ReadString();
1827                         // search the cache for this server and update it
1828                         n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1829                         if (n < 0)
1830                                 break;
1831
1832                         info = &serverlist_cache[n].info;
1833                         strlcpy(info->game, "Quake", sizeof(info->game));
1834                         strlcpy(info->mod , "", sizeof(info->mod)); // mod name is not specified
1835                         strlcpy(info->name, MSG_ReadString(), sizeof(info->name));
1836                         strlcpy(info->map , MSG_ReadString(), sizeof(info->map));
1837                         info->numplayers = MSG_ReadByte();
1838                         info->maxplayers = MSG_ReadByte();
1839                         info->protocol = MSG_ReadByte();
1840
1841                         NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1842
1843                         break;
1844                 case CCREP_PLAYER_INFO:
1845                         // we got a CCREP_PLAYER_INFO??
1846                         //if (developer.integer >= 10)
1847                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1848                         break;
1849                 case CCREP_RULE_INFO:
1850                         // we got a CCREP_RULE_INFO??
1851                         //if (developer.integer >= 10)
1852                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1853                         break;
1854                 default:
1855                         break;
1856                 }
1857                 SZ_Clear(&net_message);
1858                 // we may not have liked the packet, but it was a valid control
1859                 // packet, so we're done processing this packet now
1860                 return true;
1861         }
1862         ret = 0;
1863         if (fromserver && length >= (int)NET_HEADERSIZE && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1864                 CL_ParseServerMessage();
1865         return ret;
1866 }
1867
1868 void NetConn_QueryQueueFrame(void)
1869 {
1870         int index;
1871         int queries;
1872         int maxqueries;
1873         double timeouttime;
1874         static double querycounter = 0;
1875
1876         if(!net_slist_pause.integer && serverlist_paused)
1877                 ServerList_RebuildViewList();
1878         serverlist_paused = net_slist_pause.integer;
1879
1880         if (serverlist_querysleep)
1881                 return;
1882
1883         // apply a cool down time after master server replies,
1884         // to avoid messing up the ping times on the servers
1885         if (serverlist_querywaittime > realtime)
1886                 return;
1887
1888         // each time querycounter reaches 1.0 issue a query
1889         querycounter += cl.realframetime * net_slist_queriespersecond.value;
1890         maxqueries = (int)querycounter;
1891         maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer);
1892         querycounter -= maxqueries;
1893
1894         if( maxqueries == 0 ) {
1895                 return;
1896         }
1897
1898         //      scan serverlist and issue queries as needed
1899         serverlist_querysleep = true;
1900
1901         timeouttime     = realtime - net_slist_timeout.value;
1902         for( index = 0, queries = 0 ;   index   < serverlist_cachecount &&      queries < maxqueries    ; index++ )
1903         {
1904                 serverlist_entry_t *entry = &serverlist_cache[ index ];
1905                 if( entry->query != SQS_QUERYING && entry->query != SQS_REFRESHING )
1906                 {
1907                         continue;
1908                 }
1909
1910                 serverlist_querysleep   = false;
1911                 if( entry->querycounter !=      0 && entry->querytime > timeouttime     )
1912                 {
1913                         continue;
1914                 }
1915
1916                 if( entry->querycounter !=      (unsigned) net_slist_maxtries.integer )
1917                 {
1918                         lhnetaddress_t  address;
1919                         int socket;
1920
1921                         LHNETADDRESS_FromString(&address, entry->info.cname, 0);
1922                         if      (entry->protocol == PROTOCOL_QUAKEWORLD)
1923                         {
1924                                 for (socket     = 0; socket     < cl_numsockets ;       socket++)
1925                                         NetConn_WriteString(cl_sockets[socket], "\377\377\377\377status\n", &address);
1926                         }
1927                         else
1928                         {
1929                                 for (socket     = 0; socket     < cl_numsockets ;       socket++)
1930                                         NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getstatus", &address);
1931                         }
1932
1933                         //      update the entry fields
1934                         entry->querytime = realtime;
1935                         entry->querycounter++;
1936
1937                         // if not in the slist menu we should print the server to console
1938                         if (serverlist_consoleoutput)
1939                                 Con_Printf("querying %25s (%i. try)\n", entry->info.cname, entry->querycounter);
1940
1941                         queries++;
1942                 }
1943                 else
1944                 {
1945                         // have we tried to refresh this server?
1946                         if( entry->query == SQS_REFRESHING ) {
1947                                 // yes, so update the reply count (since its not responding anymore)
1948                                 serverreplycount--;
1949                                 if(!serverlist_paused)
1950                                         ServerList_ViewList_Remove(entry);
1951                         }
1952                         entry->query = SQS_TIMEDOUT;
1953                 }
1954         }
1955 }
1956
1957 void NetConn_ClientFrame(void)
1958 {
1959         int i, length;
1960         lhnetaddress_t peeraddress;
1961         NetConn_UpdateSockets();
1962         if (cls.connect_trying && cls.connect_nextsendtime < realtime)
1963         {
1964                 if (cls.connect_remainingtries == 0)
1965                         M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
1966                 cls.connect_nextsendtime = realtime + 1;
1967                 cls.connect_remainingtries--;
1968                 if (cls.connect_remainingtries <= -10)
1969                 {
1970                         cls.connect_trying = false;
1971                         M_Update_Return_Reason("Connect: Failed");
1972                         return;
1973                 }
1974                 // try challenge first (newer DP server or QW)
1975                 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
1976                 // then try netquake as a fallback (old server, or netquake)
1977                 SZ_Clear(&net_message);
1978                 // save space for the header, filled in later
1979                 MSG_WriteLong(&net_message, 0);
1980                 MSG_WriteByte(&net_message, CCREQ_CONNECT);
1981                 MSG_WriteString(&net_message, "QUAKE");
1982                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1983                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1984                 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
1985                 SZ_Clear(&net_message);
1986         }
1987         for (i = 0;i < cl_numsockets;i++)
1988                 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1989                         NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
1990         NetConn_QueryQueueFrame();
1991         if (cls.netcon && realtime > cls.netcon->timeout && !sv.active)
1992         {
1993                 Con_Print("Connection timed out\n");
1994                 CL_Disconnect();
1995                 Host_ShutdownServer ();
1996         }
1997 }
1998
1999 #define MAX_CHALLENGES 128
2000 struct challenge_s
2001 {
2002         lhnetaddress_t address;
2003         double time;
2004         char string[12];
2005 }
2006 challenge[MAX_CHALLENGES];
2007
2008 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
2009 {
2010         int i;
2011         char c;
2012         for (i = 0;i < bufferlength - 1;i++)
2013         {
2014                 do
2015                 {
2016                         c = rand () % (127 - 33) + 33;
2017                 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
2018                 buffer[i] = c;
2019         }
2020         buffer[i] = 0;
2021 }
2022
2023 // (div0) build the full response only if possible; better a getinfo response than no response at all if getstatus won't fit
2024 static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg, size_t out_size, qboolean fullstatus)
2025 {
2026         char qcstatus[256];
2027         unsigned int nb_clients = 0, nb_bots = 0, i;
2028         int length;
2029         char teambuf[3];
2030
2031         SV_VM_Begin();
2032
2033         // How many clients are there?
2034         for (i = 0;i < (unsigned int)svs.maxclients;i++)
2035         {
2036                 if (svs.clients[i].active)
2037                 {
2038                         nb_clients++;
2039                         if (!svs.clients[i].netconnection)
2040                                 nb_bots++;
2041                 }
2042         }
2043
2044         *qcstatus = 0;
2045         if(prog->globaloffsets.worldstatus >= 0)
2046         {
2047                 const char *str = PRVM_G_STRING(prog->globaloffsets.worldstatus);
2048                 if(str && *str)
2049                 {
2050                         char *p;
2051                         const char *q;
2052                         p = qcstatus;
2053                         for(q = str; *q; ++q)
2054                                 if(*q != '\\' && *q != '\n')
2055                                         *p++ = *q;
2056                         *p = 0;
2057                 }
2058         }
2059
2060         // TODO: we should add more information for the full status string
2061         length = dpsnprintf(out_msg, out_size,
2062                                                 "\377\377\377\377%s\x0A"
2063                                                 "\\gamename\\%s\\modname\\%s\\gameversion\\%d\\sv_maxclients\\%d"
2064                                                 "\\clients\\%d\\bots\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d"
2065                                                 "%s%s"
2066                                                 "%s%s"
2067                                                 "%s",
2068                                                 fullstatus ? "statusResponse" : "infoResponse",
2069                                                 gamename, com_modname, gameversion.integer, svs.maxclients,
2070                                                 nb_clients, nb_bots, sv.name, hostname.string, NET_PROTOCOL_VERSION,
2071                                                 *qcstatus ? "\\qcstatus\\" : "", qcstatus,
2072                                                 challenge ? "\\challenge\\" : "", challenge ? challenge : "",
2073                                                 fullstatus ? "\n" : "");
2074
2075         // Make sure it fits in the buffer
2076         if (length < 0)
2077                 goto bad;
2078
2079         if (fullstatus)
2080         {
2081                 char *ptr;
2082                 int left;
2083                 int savelength;
2084
2085                 savelength = length;
2086
2087                 ptr = out_msg + length;
2088                 left = (int)out_size - length;
2089
2090                 for (i = 0;i < (unsigned int)svs.maxclients;i++)
2091                 {
2092                         client_t *cl = &svs.clients[i];
2093                         if (cl->active)
2094                         {
2095                                 int nameind, cleanind, pingvalue;
2096                                 char curchar;
2097                                 char cleanname [sizeof(cl->name)];
2098
2099                                 // Remove all characters '"' and '\' in the player name
2100                                 nameind = 0;
2101                                 cleanind = 0;
2102                                 do
2103                                 {
2104                                         curchar = cl->name[nameind++];
2105                                         if (curchar != '"' && curchar != '\\')
2106                                         {
2107                                                 cleanname[cleanind++] = curchar;
2108                                                 if (cleanind == sizeof(cleanname) - 1)
2109                                                         break;
2110                                         }
2111                                 } while (curchar != '\0');
2112                                 cleanname[cleanind] = 0; // cleanind is always a valid index even at this point
2113
2114                                 pingvalue = (int)(cl->ping * 1000.0f);
2115                                 if(cl->netconnection)
2116                                         pingvalue = bound(1, pingvalue, 9999);
2117                                 else
2118                                         pingvalue = 0;
2119
2120                                 *qcstatus = 0;
2121                                 if(prog->fieldoffsets.clientstatus >= 0)
2122                                 {
2123                                         const char *str = PRVM_E_STRING(PRVM_EDICT_NUM(i + 1), prog->fieldoffsets.clientstatus);
2124                                         if(str && *str)
2125                                         {
2126                                                 char *p;
2127                                                 const char *q;
2128                                                 p = qcstatus;
2129                                                 for(q = str; *q && p != qcstatus + sizeof(qcstatus) - 1; ++q)
2130                                                         if(*q != '\\' && *q != '"' && !ISWHITESPACE(*q))
2131                                                                 *p++ = *q;
2132                                                 *p = 0;
2133                                         }
2134                                 }
2135
2136                                 if ((gamemode == GAME_NEXUIZ) && (teamplay.integer > 0))
2137                                 {
2138                                         if(cl->frags == -666) // spectator
2139                                                 strlcpy(teambuf, " 0", sizeof(teambuf));
2140                                         else if(cl->colors == 0x44) // red team
2141                                                 strlcpy(teambuf, " 1", sizeof(teambuf));
2142                                         else if(cl->colors == 0xDD) // blue team
2143                                                 strlcpy(teambuf, " 2", sizeof(teambuf));
2144                                         else if(cl->colors == 0xCC) // yellow team
2145                                                 strlcpy(teambuf, " 3", sizeof(teambuf));
2146                                         else if(cl->colors == 0x99) // pink team
2147                                                 strlcpy(teambuf, " 4", sizeof(teambuf));
2148                                         else
2149                                                 strlcpy(teambuf, " 0", sizeof(teambuf));
2150                                 }
2151                                 else
2152                                         *teambuf = 0;
2153
2154                                 // note: team number is inserted according to SoF2 protocol
2155                                 if(*qcstatus)
2156                                         length = dpsnprintf(ptr, left, "%s %d%s \"%s\"\n",
2157                                                                                 qcstatus,
2158                                                                                 pingvalue,
2159                                                                                 teambuf,
2160                                                                                 cleanname);
2161                                 else
2162                                         length = dpsnprintf(ptr, left, "%d %d%s \"%s\"\n",
2163                                                                                 cl->frags,
2164                                                                                 pingvalue,
2165                                                                                 teambuf,
2166                                                                                 cleanname);
2167
2168                                 if(length < 0)
2169                                 {
2170                                         // out of space?
2171                                         // turn it into an infoResponse!
2172                                         out_msg[savelength] = 0;
2173                                         memcpy(out_msg + 4, "infoResponse\x0A", 13);
2174                                         memmove(out_msg + 17, out_msg + 19, savelength - 19);
2175                                         break;
2176                                 }
2177                                 left -= length;
2178                                 ptr += length;
2179                         }
2180                 }
2181         }
2182
2183         SV_VM_End();
2184         return true;
2185
2186 bad:
2187         SV_VM_End();
2188         return false;
2189 }
2190
2191 static qboolean NetConn_PreventConnectFlood(lhnetaddress_t *peeraddress)
2192 {
2193         int floodslotnum, bestfloodslotnum;
2194         double bestfloodtime;
2195         lhnetaddress_t noportpeeraddress;
2196         // see if this is a connect flood
2197         noportpeeraddress = *peeraddress;
2198         LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2199         bestfloodslotnum = 0;
2200         bestfloodtime = sv.connectfloodaddresses[bestfloodslotnum].lasttime;
2201         for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2202         {
2203                 if (bestfloodtime >= sv.connectfloodaddresses[floodslotnum].lasttime)
2204                 {
2205                         bestfloodtime = sv.connectfloodaddresses[floodslotnum].lasttime;
2206                         bestfloodslotnum = floodslotnum;
2207                 }
2208                 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2209                 {
2210                         // this address matches an ongoing flood address
2211                         if (realtime < sv.connectfloodaddresses[floodslotnum].lasttime + net_connectfloodblockingtimeout.value)
2212                         {
2213                                 // renew the ban on this address so it does not expire
2214                                 // until the flood has subsided
2215                                 sv.connectfloodaddresses[floodslotnum].lasttime = realtime;
2216                                 //Con_Printf("Flood detected!\n");
2217                                 return true;
2218                         }
2219                         // the flood appears to have subsided, so allow this
2220                         bestfloodslotnum = floodslotnum; // reuse the same slot
2221                         break;
2222                 }
2223         }
2224         // begin a new timeout on this address
2225         sv.connectfloodaddresses[bestfloodslotnum].address = noportpeeraddress;
2226         sv.connectfloodaddresses[bestfloodslotnum].lasttime = realtime;
2227         //Con_Printf("Flood detection initiated!\n");
2228         return false;
2229 }
2230
2231 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress)
2232 {
2233         int floodslotnum;
2234         lhnetaddress_t noportpeeraddress;
2235         // see if this is a connect flood
2236         noportpeeraddress = *peeraddress;
2237         LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2238         for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2239         {
2240                 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2241                 {
2242                         // this address matches an ongoing flood address
2243                         // remove the ban
2244                         sv.connectfloodaddresses[floodslotnum].address.addresstype = LHNETADDRESSTYPE_NONE;
2245                         sv.connectfloodaddresses[floodslotnum].lasttime = 0;
2246                         //Con_Printf("Flood cleared!\n");
2247                 }
2248         }
2249 }
2250
2251 typedef qboolean (*rcon_matchfunc_t) (const char *password, const char *hash, const char *s, int slen);
2252
2253 qboolean hmac_mdfour_matching(const char *password, const char *hash, const char *s, int slen)
2254 {
2255         char mdfourbuf[16];
2256         long t1, t2;
2257
2258         t1 = (long) time(NULL);
2259         t2 = strtol(s, NULL, 0);
2260         if(abs(t1 - t2) > rcon_secure_maxdiff.integer)
2261                 return false;
2262
2263         if(!HMAC_MDFOUR_16BYTES((unsigned char *) mdfourbuf, (unsigned char *) s, slen, (unsigned char *) password, strlen(password)))
2264                 return false;
2265
2266         return !memcmp(mdfourbuf, hash, 16);
2267 }
2268
2269 qboolean plaintext_matching(const char *password, const char *hash, const char *s, int slen)
2270 {
2271         return !strcmp(password, hash);
2272 }
2273
2274 // returns a string describing the user level, or NULL for auth failure
2275 const char *RCon_Authenticate(const char *password, const char *s, const char *endpos, rcon_matchfunc_t comparator, const char *cs, int cslen)
2276 {
2277         const char *text;
2278         qboolean hasquotes;
2279
2280         if(comparator(rcon_password.string, password, cs, cslen))
2281                 return "rcon";
2282         
2283         if(!comparator(rcon_restricted_password.string, password, cs, cslen))
2284                 return NULL;
2285
2286         for(text = s; text != endpos; ++text)
2287                 if((signed char) *text > 0 && ((signed char) *text < (signed char) ' ' || *text == ';'))
2288                         return NULL; // block possible exploits against the parser/alias expansion
2289
2290         while(s != endpos)
2291         {
2292                 size_t l = strlen(s);
2293                 if(l)
2294                 {
2295                         hasquotes = (strchr(s, '"') != NULL);
2296                         // sorry, we can't allow these substrings in wildcard expressions,
2297                         // as they can mess with the argument counts
2298                         text = rcon_restricted_commands.string;
2299                         while(COM_ParseToken_Console(&text))
2300                         {
2301                                 // com_token now contains a pattern to check for...
2302                                 if(strchr(com_token, '*') || strchr(com_token, '?')) // wildcard expression, * can only match a SINGLE argument
2303                                 {
2304                                         if(!hasquotes)
2305                                                 if(matchpattern_with_separator(s, com_token, true, " ", true)) // note how we excluded tab, newline etc. above
2306                                                         goto match;
2307                                 }
2308                                 else if(strchr(com_token, ' ')) // multi-arg expression? must match in whole
2309                                 {
2310                                         if(!strcmp(com_token, s))
2311                                                 goto match;
2312                                 }
2313                                 else // single-arg expression? must match the beginning of the command
2314                                 {
2315                                         if(!strcmp(com_token, s))
2316                                                 goto match;
2317                                         if(!memcmp(va("%s ", com_token), s, strlen(com_token) + 1))
2318                                                 goto match;
2319                                 }
2320                         }
2321                         // if we got here, nothing matched!
2322                         return NULL;
2323                 }
2324 match:
2325                 s += l + 1;
2326         }
2327
2328         return "restricted rcon";
2329 }
2330
2331 void RCon_Execute(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, const char *addressstring2, const char *userlevel, const char *s, const char *endpos)
2332 {
2333         if(userlevel)
2334         {
2335                 // looks like a legitimate rcon command with the correct password
2336                 const char *s_ptr = s;
2337                 Con_Printf("server received %s command from %s: ", userlevel, host_client ? host_client->name : addressstring2);
2338                 while(s_ptr != endpos)
2339                 {
2340                         size_t l = strlen(s_ptr);
2341                         if(l)
2342                                 Con_Printf(" %s;", s_ptr);
2343                         s_ptr += l + 1;
2344                 }
2345                 Con_Printf("\n");
2346
2347                 if (!host_client || !host_client->netconnection || LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2348                         Con_Rcon_Redirect_Init(mysocket, peeraddress);
2349                 while(s != endpos)
2350                 {
2351                         size_t l = strlen(s);
2352                         if(l)
2353                         {
2354                                 client_t *host_client_save = host_client;
2355                                 Cmd_ExecuteString(s, src_command);
2356                                 host_client = host_client_save;
2357                                 // in case it is a command that changes host_client (like restart)
2358                         }
2359                         s += l + 1;
2360                 }
2361                 Con_Rcon_Redirect_End();
2362         }
2363         else
2364         {
2365                 Con_Printf("server denied rcon access to %s\n", host_client ? host_client->name : addressstring2);
2366         }
2367 }
2368
2369 extern void SV_SendServerinfo (client_t *client);
2370 static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
2371 {
2372         int i, ret, clientnum, best;
2373         double besttime;
2374         client_t *client;
2375         char *s, *string, response[1400], addressstring2[128], stringbuf[16384];
2376         qboolean islocal = (LHNETADDRESS_GetAddressType(peeraddress) == LHNETADDRESSTYPE_LOOP);
2377
2378         if (!sv.active)
2379                 return false;
2380
2381         // convert the address to a string incase we need it
2382         LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
2383
2384         // see if we can identify the sender as a local player
2385         // (this is necessary for rcon to send a reliable reply if the client is
2386         //  actually on the server, not sending remotely)
2387         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2388                 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
2389                         break;
2390         if (i == svs.maxclients)
2391                 host_client = NULL;
2392
2393         if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
2394         {
2395                 // received a command string - strip off the packaging and put it
2396                 // into our string buffer with NULL termination
2397                 data += 4;
2398                 length -= 4;
2399                 length = min(length, (int)sizeof(stringbuf) - 1);
2400                 memcpy(stringbuf, data, length);
2401                 stringbuf[length] = 0;
2402                 string = stringbuf;
2403
2404                 if (developer.integer >= 10)
2405                 {
2406                         Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
2407                         Com_HexDumpToConsole(data, length);
2408                 }
2409
2410                 if (length >= 12 && !memcmp(string, "getchallenge", 12) && (islocal || sv_public.integer > -2))
2411                 {
2412                         for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
2413                         {
2414                                 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
2415                                         break;
2416                                 if (besttime > challenge[i].time)
2417                                         besttime = challenge[best = i].time;
2418                         }
2419                         // if we did not find an exact match, choose the oldest and
2420                         // update address and string
2421                         if (i == MAX_CHALLENGES)
2422                         {
2423                                 i = best;
2424                                 challenge[i].address = *peeraddress;
2425                                 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
2426                         }
2427                         challenge[i].time = realtime;
2428                         // send the challenge
2429                         NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
2430                         return true;
2431                 }
2432                 if (length > 8 && !memcmp(string, "connect\\", 8) && (islocal || sv_public.integer > -2))
2433                 {
2434                         string += 7;
2435                         length -= 7;
2436
2437                         if (!(s = SearchInfostring(string, "challenge")))
2438                                 return true;
2439                         // validate the challenge
2440                         for (i = 0;i < MAX_CHALLENGES;i++)
2441                                 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
2442                                         break;
2443                         // if the challenge is not recognized, drop the packet
2444                         if (i == MAX_CHALLENGES)
2445                                 return true;
2446
2447                         // check engine protocol
2448                         if(!(s = SearchInfostring(string, "protocol")) || strcmp(s, "darkplaces 3"))
2449                         {
2450                                 if (developer.integer >= 10)
2451                                         Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
2452                                 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
2453                                 return true;
2454                         }
2455
2456                         // see if this is a duplicate connection request or a disconnected
2457                         // client who is rejoining to the same client slot
2458                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2459                         {
2460                                 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2461                                 {
2462                                         // this is a known client...
2463                                         if (client->spawned)
2464                                         {
2465                                                 // client crashed and is coming back,
2466                                                 // keep their stuff intact
2467                                                 if (developer.integer >= 10)
2468                                                         Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", addressstring2);
2469                                                 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2470                                                 SV_VM_Begin();
2471                                                 SV_SendServerinfo(client);
2472                                                 SV_VM_End();
2473                                         }
2474                                         else
2475                                         {
2476                                                 // client is still trying to connect,
2477                                                 // so we send a duplicate reply
2478                                                 if (developer.integer >= 10)
2479                                                         Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
2480                                                 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2481                                         }
2482                                         return true;
2483                                 }
2484                         }
2485
2486                         if (NetConn_PreventConnectFlood(peeraddress))
2487                                 return true;
2488
2489                         // find an empty client slot for this new client
2490                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2491                         {
2492                                 netconn_t *conn;
2493                                 if (!client->active && (conn = NetConn_Open(mysocket, peeraddress)))
2494                                 {
2495                                         // allocated connection
2496                                         if (developer.integer >= 10)
2497                                                 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
2498                                         NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2499                                         // now set up the client
2500                                         SV_VM_Begin();
2501                                         SV_ConnectClient(clientnum, conn);
2502                                         SV_VM_End();
2503                                         NetConn_Heartbeat(1);
2504                                         return true;
2505                                 }
2506                         }
2507
2508                         // no empty slots found - server is full
2509                         if (developer.integer >= 10)
2510                                 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
2511                         NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
2512
2513                         return true;
2514                 }
2515                 if (length >= 7 && !memcmp(string, "getinfo", 7) && (islocal || sv_public.integer > -1))
2516                 {
2517                         const char *challenge = NULL;
2518
2519                         // If there was a challenge in the getinfo message
2520                         if (length > 8 && string[7] == ' ')
2521                                 challenge = string + 8;
2522
2523                         if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
2524                         {
2525                                 if (developer.integer >= 10)
2526                                         Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
2527                                 NetConn_WriteString(mysocket, response, peeraddress);
2528                         }
2529                         return true;
2530                 }
2531                 if (length >= 9 && !memcmp(string, "getstatus", 9) && (islocal || sv_public.integer > -1))
2532                 {
2533                         const char *challenge = NULL;
2534
2535                         // If there was a challenge in the getinfo message
2536                         if (length > 10 && string[9] == ' ')
2537                                 challenge = string + 10;
2538
2539                         if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
2540                         {
2541                                 if (developer.integer >= 10)
2542                                         Con_Printf("Sending reply to client %s - %s\n", addressstring2, response);
2543                                 NetConn_WriteString(mysocket, response, peeraddress);
2544                         }
2545                         return true;
2546                 }
2547                 if (length >= 37 && !memcmp(string, "srcon HMAC-MD4 TIME ", 20))
2548                 {
2549                         char *password = string + 20;
2550                         char *timeval = string + 37;
2551                         char *s = strchr(timeval, ' ');
2552                         char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2553                         const char *userlevel;
2554                         if(!s)
2555                                 return true; // invalid packet
2556                         ++s;
2557
2558                         userlevel = RCon_Authenticate(password, s, endpos, hmac_mdfour_matching, timeval, endpos - timeval - 1); // not including the appended \0 into the HMAC
2559                         RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2560                         return true;
2561                 }
2562                 if (length >= 5 && !memcmp(string, "rcon ", 5))
2563                 {
2564                         int i;
2565                         char *s = string + 5;
2566                         char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2567                         char password[64];
2568
2569                         if(rcon_secure.integer)
2570                                 return true;
2571
2572                         for (i = 0;!ISWHITESPACE(*s);s++)
2573                                 if (i < (int)sizeof(password) - 1)
2574                                         password[i++] = *s;
2575                         if(ISWHITESPACE(*s) && s != endpos) // skip leading ugly space
2576                                 ++s;
2577                         password[i] = 0;
2578                         if (!ISWHITESPACE(password[0]))
2579                         {
2580                                 const char *userlevel = RCon_Authenticate(password, s, endpos, plaintext_matching, NULL, 0);
2581                                 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2582                         }
2583                         return true;
2584                 }
2585                 if (!strncmp(string, "ping", 4))
2586                 {
2587                         if (developer.integer >= 10)
2588                                 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
2589                         NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
2590                         return true;
2591                 }
2592                 if (!strncmp(string, "ack", 3))
2593                         return true;
2594                 // we may not have liked the packet, but it was a command packet, so
2595                 // we're done processing this packet now
2596                 return true;
2597         }
2598         // netquake control packets, supported for compatibility only, and only
2599         // when running game protocols that are normally served via this connection
2600         // protocol
2601         // (this protects more modern protocols against being used for
2602         //  Quake packet flood Denial Of Service attacks)
2603         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))
2604         {
2605                 int c;
2606                 int protocolnumber;
2607                 const char *protocolname;
2608                 data += 4;
2609                 length -= 4;
2610                 SZ_Clear(&net_message);
2611                 SZ_Write(&net_message, data, length);
2612                 MSG_BeginReading();
2613                 c = MSG_ReadByte();
2614                 switch (c)
2615                 {
2616                 case CCREQ_CONNECT:
2617                         if (developer.integer >= 10)
2618                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
2619                         if(!islocal && sv_public.integer <= -2)
2620                                 break;
2621
2622                         protocolname = MSG_ReadString();
2623                         protocolnumber = MSG_ReadByte();
2624                         if (strcmp(protocolname, "QUAKE") || protocolnumber != NET_PROTOCOL_VERSION)
2625                         {
2626                                 if (developer.integer >= 10)
2627                                         Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
2628                                 SZ_Clear(&net_message);
2629                                 // save space for the header, filled in later
2630                                 MSG_WriteLong(&net_message, 0);
2631                                 MSG_WriteByte(&net_message, CCREP_REJECT);
2632                                 MSG_WriteString(&net_message, "Incompatible version.\n");
2633                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2634                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2635                                 SZ_Clear(&net_message);
2636                                 break;
2637                         }
2638
2639                         // see if this connect request comes from a known client
2640                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2641                         {
2642                                 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2643                                 {
2644                                         // this is either a duplicate connection request
2645                                         // or coming back from a timeout
2646                                         // (if so, keep their stuff intact)
2647
2648                                         // send a reply
2649                                         if (developer.integer >= 10)
2650                                                 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
2651                                         SZ_Clear(&net_message);
2652                                         // save space for the header, filled in later
2653                                         MSG_WriteLong(&net_message, 0);
2654                                         MSG_WriteByte(&net_message, CCREP_ACCEPT);
2655                                         MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
2656                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2657                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2658                                         SZ_Clear(&net_message);
2659
2660                                         // if client is already spawned, re-send the
2661                                         // serverinfo message as they'll need it to play
2662                                         if (client->spawned)
2663                                         {
2664                                                 SV_VM_Begin();
2665                                                 SV_SendServerinfo(client);
2666                                                 SV_VM_End();
2667                                         }
2668                                         return true;
2669                                 }
2670                         }
2671
2672                         // this is a new client, check for connection flood
2673                         if (NetConn_PreventConnectFlood(peeraddress))
2674                                 break;
2675
2676                         // find a slot for the new client
2677                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2678                         {
2679                                 netconn_t *conn;
2680                                 if (!client->active && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
2681                                 {
2682                                         // connect to the client
2683                                         // everything is allocated, just fill in the details
2684                                         strlcpy (conn->address, addressstring2, sizeof (conn->address));
2685                                         if (developer.integer >= 10)
2686                                                 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
2687                                         // send back the info about the server connection
2688                                         SZ_Clear(&net_message);
2689                                         // save space for the header, filled in later
2690                                         MSG_WriteLong(&net_message, 0);
2691                                         MSG_WriteByte(&net_message, CCREP_ACCEPT);
2692                                         MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
2693                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2694                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2695                                         SZ_Clear(&net_message);
2696                                         // now set up the client struct
2697                                         SV_VM_Begin();
2698                                         SV_ConnectClient(clientnum, conn);
2699                                         SV_VM_End();
2700                                         NetConn_Heartbeat(1);
2701                                         return true;
2702                                 }
2703                         }
2704
2705                         if (developer.integer >= 10)
2706                                 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
2707                         // no room; try to let player know
2708                         SZ_Clear(&net_message);
2709                         // save space for the header, filled in later
2710                         MSG_WriteLong(&net_message, 0);
2711                         MSG_WriteByte(&net_message, CCREP_REJECT);
2712                         MSG_WriteString(&net_message, "Server is full.\n");
2713                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2714                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2715                         SZ_Clear(&net_message);
2716                         break;
2717                 case CCREQ_SERVER_INFO:
2718                         if (developer.integer >= 10)
2719                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
2720                         if(!islocal && sv_public.integer <= -1)
2721                                 break;
2722                         if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
2723                         {
2724                                 int numclients;
2725                                 char myaddressstring[128];
2726                                 if (developer.integer >= 10)
2727                                         Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
2728                                 SZ_Clear(&net_message);
2729                                 // save space for the header, filled in later
2730                                 MSG_WriteLong(&net_message, 0);
2731                                 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
2732                                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), myaddressstring, sizeof(myaddressstring), true);
2733                                 MSG_WriteString(&net_message, myaddressstring);
2734                                 MSG_WriteString(&net_message, hostname.string);
2735                                 MSG_WriteString(&net_message, sv.name);
2736                                 // How many clients are there?
2737                                 for (i = 0, numclients = 0;i < svs.maxclients;i++)
2738                                         if (svs.clients[i].active)
2739                                                 numclients++;
2740                                 MSG_WriteByte(&net_message, numclients);
2741                                 MSG_WriteByte(&net_message, svs.maxclients);
2742                                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2743                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2744                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2745                                 SZ_Clear(&net_message);
2746                         }
2747                         break;
2748                 case CCREQ_PLAYER_INFO:
2749                         if (developer.integer >= 10)
2750                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
2751                         if(!islocal && sv_public.integer <= -1)
2752                                 break;
2753                         if (sv.active)
2754                         {
2755                                 int playerNumber, activeNumber, clientNumber;
2756                                 client_t *client;
2757
2758                                 playerNumber = MSG_ReadByte();
2759                                 activeNumber = -1;
2760                                 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
2761                                         if (client->active && ++activeNumber == playerNumber)
2762                                                 break;
2763                                 if (clientNumber != svs.maxclients)
2764                                 {
2765                                         SZ_Clear(&net_message);
2766                                         // save space for the header, filled in later
2767                                         MSG_WriteLong(&net_message, 0);
2768                                         MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
2769                                         MSG_WriteByte(&net_message, playerNumber);
2770                                         MSG_WriteString(&net_message, client->name);
2771                                         MSG_WriteLong(&net_message, client->colors);
2772                                         MSG_WriteLong(&net_message, client->frags);
2773                                         MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
2774                                         MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
2775                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2776                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2777                                         SZ_Clear(&net_message);
2778                                 }
2779                         }
2780                         break;
2781                 case CCREQ_RULE_INFO:
2782                         if (developer.integer >= 10)
2783                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
2784                         if(!islocal && sv_public.integer <= -1)
2785                                 break;
2786                         if (sv.active)
2787                         {
2788                                 char *prevCvarName;
2789                                 cvar_t *var;
2790
2791                                 // find the search start location
2792                                 prevCvarName = MSG_ReadString();
2793                                 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
2794
2795                                 // send the response
2796                                 SZ_Clear(&net_message);
2797                                 // save space for the header, filled in later
2798                                 MSG_WriteLong(&net_message, 0);
2799                                 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
2800                                 if (var)
2801                                 {
2802                                         MSG_WriteString(&net_message, var->name);
2803                                         MSG_WriteString(&net_message, var->string);
2804                                 }
2805                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2806                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2807                                 SZ_Clear(&net_message);
2808                         }
2809                         break;
2810                 default:
2811                         break;
2812                 }
2813                 SZ_Clear(&net_message);
2814                 // we may not have liked the packet, but it was a valid control
2815                 // packet, so we're done processing this packet now
2816                 return true;
2817         }
2818         if (host_client)
2819         {
2820                 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length, sv.protocol, host_client->spawned ? net_messagetimeout.value : net_connecttimeout.value)) == 2)
2821                 {
2822                         SV_VM_Begin();
2823                         SV_ReadClientMessage();
2824                         SV_VM_End();
2825                         return ret;
2826                 }
2827         }
2828         return 0;
2829 }
2830
2831 void NetConn_ServerFrame(void)
2832 {
2833         int i, length;
2834         lhnetaddress_t peeraddress;
2835         for (i = 0;i < sv_numsockets;i++)
2836                 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2837                         NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
2838         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2839         {
2840                 // never timeout loopback connections
2841                 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2842                 {
2843                         Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
2844                         SV_VM_Begin();
2845                         SV_DropClient(false);
2846                         SV_VM_End();
2847                 }
2848         }
2849 }
2850
2851 void NetConn_SleepMicroseconds(int microseconds)
2852 {
2853         LHNET_SleepUntilPacket_Microseconds(microseconds);
2854 }
2855
2856 void NetConn_QueryMasters(qboolean querydp, qboolean queryqw)
2857 {
2858         int i, j;
2859         int masternum;
2860         lhnetaddress_t masteraddress;
2861         lhnetaddress_t broadcastaddress;
2862         char request[256];
2863
2864         if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
2865                 return;
2866
2867         // 26000 is the default quake server port, servers on other ports will not
2868         // be found
2869         // note this is IPv4-only, I doubt there are IPv6-only LANs out there
2870         LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
2871
2872         if (querydp)
2873         {
2874                 for (i = 0;i < cl_numsockets;i++)
2875                 {
2876                         if (cl_sockets[i])
2877                         {
2878                                 const char *cmdname, *extraoptions;
2879                                 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
2880
2881                                 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
2882                                 {
2883                                         // search LAN for Quake servers
2884                                         SZ_Clear(&net_message);
2885                                         // save space for the header, filled in later
2886                                         MSG_WriteLong(&net_message, 0);
2887                                         MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
2888                                         MSG_WriteString(&net_message, "QUAKE");
2889                                         MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2890                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2891                                         NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
2892                                         SZ_Clear(&net_message);
2893
2894                                         // search LAN for DarkPlaces servers
2895                                         NetConn_WriteString(cl_sockets[i], "\377\377\377\377getstatus", &broadcastaddress);
2896                                 }
2897
2898                                 // build the getservers message to send to the dpmaster master servers
2899                                 if (LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == LHNETADDRESSTYPE_INET6)
2900                                 {
2901                                         cmdname = "getserversExt";
2902                                         extraoptions = " ipv4 ipv6";  // ask for IPv4 and IPv6 servers
2903                                 }
2904                                 else
2905                                 {
2906                                         cmdname = "getservers";
2907                                         extraoptions = "";
2908                                 }
2909                                 dpsnprintf(request, sizeof(request), "\377\377\377\377%s %s %u empty full%s", cmdname, gamename, NET_PROTOCOL_VERSION, extraoptions);
2910
2911                                 // search internet
2912                                 for (masternum = 0;sv_masters[masternum].name;masternum++)
2913                                 {
2914                                         if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == af)
2915                                         {
2916                                                 masterquerycount++;
2917                                                 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
2918                                         }
2919                                 }
2920
2921                                 // search favorite servers
2922                                 for(j = 0; j < nFavorites; ++j)
2923                                 {
2924                                         if(LHNETADDRESS_GetAddressType(&favorites[j]) == af)
2925                                         {
2926                                                 if(LHNETADDRESS_ToString(&favorites[j], request, sizeof(request), true))
2927                                                         NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, request, true );
2928                                         }
2929                                 }
2930                         }
2931                 }
2932         }
2933
2934         // only query QuakeWorld servers when the user wants to
2935         if (queryqw)
2936         {
2937                 for (i = 0;i < cl_numsockets;i++)
2938                 {
2939                         if (cl_sockets[i])
2940                         {
2941                                 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
2942
2943                                 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
2944                                 {
2945                                         // search LAN for QuakeWorld servers
2946                                         NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &broadcastaddress);
2947
2948                                         // build the getservers message to send to the qwmaster master servers
2949                                         // note this has no -1 prefix, and the trailing nul byte is sent
2950                                         dpsnprintf(request, sizeof(request), "c\n");
2951                                 }
2952
2953                                 // search internet
2954                                 for (masternum = 0;sv_qwmasters[masternum].name;masternum++)
2955                                 {
2956                                         if (sv_qwmasters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_qwmasters[masternum].string, QWMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
2957                                         {
2958                                                 if (m_state != m_slist)
2959                                                 {
2960                                                         char lookupstring[128];
2961                                                         LHNETADDRESS_ToString(&masteraddress, lookupstring, sizeof(lookupstring), true);
2962                                                         Con_Printf("Querying master %s (resolved from %s)\n", lookupstring, sv_qwmasters[masternum].string);
2963                                                 }
2964                                                 masterquerycount++;
2965                                                 NetConn_Write(cl_sockets[i], request, (int)strlen(request) + 1, &masteraddress);
2966                                         }
2967                                 }
2968
2969                                 // search favorite servers
2970                                 for(j = 0; j < nFavorites; ++j)
2971                                 {
2972                                         if(LHNETADDRESS_GetAddressType(&favorites[j]) == af)
2973                                         {
2974                                                 if(LHNETADDRESS_ToString(&favorites[j], request, sizeof(request), true))
2975                                                 {
2976                                                         NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &favorites[j]);
2977                                                         NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, request, true );
2978                                                 }
2979                                         }
2980                                 }
2981                         }
2982                 }
2983         }
2984         if (!masterquerycount)
2985         {
2986                 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
2987                 M_Update_Return_Reason("No network");
2988         }
2989 }
2990
2991 void NetConn_Heartbeat(int priority)
2992 {
2993         lhnetaddress_t masteraddress;
2994         int masternum;
2995         lhnetsocket_t *mysocket;
2996
2997         // if it's a state change (client connected), limit next heartbeat to no
2998         // more than 30 sec in the future
2999         if (priority == 1 && nextheartbeattime > realtime + 30.0)
3000                 nextheartbeattime = realtime + 30.0;
3001
3002         // limit heartbeatperiod to 30 to 270 second range,
3003         // lower limit is to avoid abusing master servers with excess traffic,
3004         // upper limit is to avoid timing out on the master server (which uses
3005         // 300 sec timeout)
3006         if (sv_heartbeatperiod.value < 30)
3007                 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
3008         if (sv_heartbeatperiod.value > 270)
3009                 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
3010
3011         // make advertising optional and don't advertise singleplayer games, and
3012         // only send a heartbeat as often as the admin wants
3013         if (sv.active && sv_public.integer > 0 && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
3014         {
3015                 nextheartbeattime = realtime + sv_heartbeatperiod.value;
3016                 for (masternum = 0;sv_masters[masternum].name;masternum++)
3017                         if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
3018                                 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
3019         }
3020 }
3021
3022 static void Net_Heartbeat_f(void)
3023 {
3024         if (sv.active)
3025                 NetConn_Heartbeat(2);
3026         else
3027                 Con_Print("No server running, can not heartbeat to master server.\n");
3028 }
3029
3030 void PrintStats(netconn_t *conn)
3031 {
3032         if ((cls.state == ca_connected && cls.protocol == PROTOCOL_QUAKEWORLD) || (sv.active && sv.protocol == PROTOCOL_QUAKEWORLD))
3033                 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->outgoing_unreliable_sequence, conn->qw.incoming_sequence);
3034         else
3035                 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->nq.sendSequence, conn->nq.receiveSequence);
3036 }
3037
3038 void Net_Stats_f(void)
3039 {
3040         netconn_t *conn;
3041         Con_Printf("unreliable messages sent   = %i\n", unreliableMessagesSent);
3042         Con_Printf("unreliable messages recv   = %i\n", unreliableMessagesReceived);
3043         Con_Printf("reliable messages sent     = %i\n", reliableMessagesSent);
3044         Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
3045         Con_Printf("packetsSent                = %i\n", packetsSent);
3046         Con_Printf("packetsReSent              = %i\n", packetsReSent);
3047         Con_Printf("packetsReceived            = %i\n", packetsReceived);
3048         Con_Printf("receivedDuplicateCount     = %i\n", receivedDuplicateCount);
3049         Con_Printf("droppedDatagrams           = %i\n", droppedDatagrams);
3050         Con_Print("connections                =\n");
3051         for (conn = netconn_list;conn;conn = conn->next)
3052                 PrintStats(conn);
3053 }
3054
3055 void Net_Refresh_f(void)
3056 {
3057         if (m_state != m_slist) {
3058                 Con_Print("Sending new requests to master servers\n");
3059                 ServerList_QueryList(false, true, false, true);
3060                 Con_Print("Listening for replies...\n");
3061         } else
3062                 ServerList_QueryList(false, true, false, false);
3063 }
3064
3065 void Net_Slist_f(void)
3066 {
3067         ServerList_ResetMasks();
3068         serverlist_sortbyfield = SLIF_PING;
3069         serverlist_sortflags = 0;
3070     if (m_state != m_slist) {
3071                 Con_Print("Sending requests to master servers\n");
3072                 ServerList_QueryList(true, true, false, true);
3073                 Con_Print("Listening for replies...\n");
3074         } else
3075                 ServerList_QueryList(true, true, false, false);
3076 }
3077
3078 void Net_SlistQW_f(void)
3079 {
3080         ServerList_ResetMasks();
3081         serverlist_sortbyfield = SLIF_PING;
3082         serverlist_sortflags = 0;
3083     if (m_state != m_slist) {
3084                 Con_Print("Sending requests to master servers\n");
3085                 ServerList_QueryList(true, false, true, true);
3086                 serverlist_consoleoutput = true;
3087                 Con_Print("Listening for replies...\n");
3088         } else
3089                 ServerList_QueryList(true, false, true, false);
3090 }
3091
3092 void NetConn_Init(void)
3093 {
3094         int i;
3095         lhnetaddress_t tempaddress;
3096         netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
3097         Cmd_AddCommand("net_stats", Net_Stats_f, "print network statistics");
3098         Cmd_AddCommand("net_slist", Net_Slist_f, "query dp master servers and print all server information");
3099         Cmd_AddCommand("net_slistqw", Net_SlistQW_f, "query qw master servers and print all server information");
3100         Cmd_AddCommand("net_refresh", Net_Refresh_f, "query dp master servers and refresh all server information");
3101         Cmd_AddCommand("heartbeat", Net_Heartbeat_f, "send a heartbeat to the master server (updates your server information)");
3102         Cvar_RegisterVariable(&rcon_restricted_password);
3103         Cvar_RegisterVariable(&rcon_restricted_commands);
3104         Cvar_RegisterVariable(&rcon_secure_maxdiff);
3105         Cvar_RegisterVariable(&net_slist_queriespersecond);
3106         Cvar_RegisterVariable(&net_slist_queriesperframe);
3107         Cvar_RegisterVariable(&net_slist_timeout);
3108         Cvar_RegisterVariable(&net_slist_maxtries);
3109         Cvar_RegisterVariable(&net_slist_favorites);
3110         Cvar_RegisterVariable(&net_slist_pause);
3111         Cvar_RegisterVariable(&net_messagetimeout);
3112         Cvar_RegisterVariable(&net_connecttimeout);
3113         Cvar_RegisterVariable(&net_connectfloodblockingtimeout);
3114         Cvar_RegisterVariable(&cl_netlocalping);
3115         Cvar_RegisterVariable(&cl_netpacketloss_send);
3116         Cvar_RegisterVariable(&cl_netpacketloss_receive);
3117         Cvar_RegisterVariable(&hostname);
3118         Cvar_RegisterVariable(&developer_networking);
3119         Cvar_RegisterVariable(&cl_netport);
3120         Cvar_RegisterVariable(&sv_netport);
3121         Cvar_RegisterVariable(&net_address);
3122         Cvar_RegisterVariable(&net_address_ipv6);
3123         Cvar_RegisterVariable(&sv_public);
3124         Cvar_RegisterVariable(&sv_heartbeatperiod);
3125         for (i = 0;sv_masters[i].name;i++)
3126                 Cvar_RegisterVariable(&sv_masters[i]);
3127         Cvar_RegisterVariable(&gameversion);
3128 // 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.
3129         if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
3130         {
3131                 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
3132                 {
3133                         Con_Printf("-ip option used, setting net_address to \"%s\"\n", com_argv[i + 1]);
3134                         Cvar_SetQuick(&net_address, com_argv[i + 1]);
3135                 }
3136                 else
3137                         Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
3138         }
3139 // 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
3140         if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
3141         {
3142                 i = atoi(com_argv[i + 1]);
3143                 if (i >= 0 && i < 65536)
3144                 {
3145                         Con_Printf("-port option used, setting port cvar to %i\n", i);
3146                         Cvar_SetValueQuick(&sv_netport, i);
3147                 }
3148                 else
3149                         Con_Printf("-port option used, but %i is not a valid port number\n", i);
3150         }
3151         cl_numsockets = 0;
3152         sv_numsockets = 0;
3153         net_message.data = net_message_buf;
3154         net_message.maxsize = sizeof(net_message_buf);
3155         net_message.cursize = 0;
3156         LHNET_Init();
3157 }
3158
3159 void NetConn_Shutdown(void)
3160 {
3161         NetConn_CloseClientPorts();
3162         NetConn_CloseServerPorts();
3163         LHNET_Shutdown();
3164 }
3165