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