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