]> icculus.org git repositories - divverent/darkplaces.git/blob - netconn.c
make menu QC aware of player list; add extension DP_SV_QCSTATUS to allow QC to overri...
[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                 Mem_Free((char *)qcstatus);
1962
1963         // Make sure it fits in the buffer
1964         if (length < 0)
1965                 goto bad;
1966
1967         if (fullstatus)
1968         {
1969                 char *ptr;
1970                 int left;
1971                 int savelength;
1972
1973                 savelength = length;
1974
1975                 ptr = out_msg + length;
1976                 left = (int)out_size - length;
1977
1978                 for (i = 0;i < (unsigned int)svs.maxclients;i++)
1979                 {
1980                         client_t *cl = &svs.clients[i];
1981                         if (cl->active)
1982                         {
1983                                 int nameind, cleanind, pingvalue;
1984                                 char curchar;
1985                                 char cleanname [sizeof(cl->name)];
1986
1987                                 // Remove all characters '"' and '\' in the player name
1988                                 nameind = 0;
1989                                 cleanind = 0;
1990                                 do
1991                                 {
1992                                         curchar = cl->name[nameind++];
1993                                         if (curchar != '"' && curchar != '\\')
1994                                         {
1995                                                 cleanname[cleanind++] = curchar;
1996                                                 if (cleanind == sizeof(cleanname) - 1)
1997                                                         break;
1998                                         }
1999                                 } while (curchar != '\0');
2000
2001                                 pingvalue = (int)(cl->ping * 1000.0f);
2002                                 if(cl->netconnection)
2003                                         pingvalue = bound(1, pingvalue, 9999);
2004                                 else
2005                                         pingvalue = 0;
2006
2007                                 if(prog->fieldoffsets.clientstatus >= 0)
2008                                 {
2009                                         const char *str = PRVM_E_STRING(PRVM_EDICT_NUM(i + 1), prog->fieldoffsets.clientstatus);
2010                                         if(str && *str)
2011                                         {
2012                                                 char *p;
2013                                                 const char *q;
2014                                                 qcstatus = p = Mem_Alloc(tempmempool, strlen(str) + 1);
2015                                                 for(q = str; *q; ++q)
2016                                                         if(*q != '\\' && *q != ' ')
2017                                                                 *p++ = *q;
2018                                                 *p = 0;
2019                                         }
2020                                 }
2021
2022                                 if(qcstatus)
2023                                 {
2024                                         length = dpsnprintf(ptr, left, "%s %d \"%s\"\n",
2025                                                                                 qcstatus,
2026                                                                                 pingvalue,
2027                                                                                 cleanname);
2028                                         Mem_Free((char *)qcstatus);
2029                                 }
2030                                 else
2031                                         length = dpsnprintf(ptr, left, "%d %d \"%s\"\n",
2032                                                                                 cl->frags,
2033                                                                                 pingvalue,
2034                                                                                 cleanname);
2035
2036                                 if(length < 0)
2037                                 {
2038                                         // out of space?
2039                                         // turn it into an infoResponse!
2040                                         out_msg[savelength] = 0;
2041                                         memcpy(out_msg + 4, "infoResponse\x0A", 13);
2042                                         memmove(out_msg + 17, out_msg + 19, savelength - 19);
2043                                         break;
2044                                 }
2045                                 left -= length;
2046                                 ptr += length;
2047                         }
2048                 }
2049         }
2050
2051         SV_VM_End();
2052         return true;
2053
2054 bad:
2055         SV_VM_End();
2056         return false;
2057 }
2058
2059 static qboolean NetConn_PreventConnectFlood(lhnetaddress_t *peeraddress)
2060 {
2061         int floodslotnum, bestfloodslotnum;
2062         double bestfloodtime;
2063         lhnetaddress_t noportpeeraddress;
2064         // see if this is a connect flood
2065         noportpeeraddress = *peeraddress;
2066         LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2067         bestfloodslotnum = 0;
2068         bestfloodtime = sv.connectfloodaddresses[bestfloodslotnum].lasttime;
2069         for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2070         {
2071                 if (bestfloodtime >= sv.connectfloodaddresses[floodslotnum].lasttime)
2072                 {
2073                         bestfloodtime = sv.connectfloodaddresses[floodslotnum].lasttime;
2074                         bestfloodslotnum = floodslotnum;
2075                 }
2076                 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2077                 {
2078                         // this address matches an ongoing flood address
2079                         if (realtime < sv.connectfloodaddresses[floodslotnum].lasttime + net_connectfloodblockingtimeout.value)
2080                         {
2081                                 // renew the ban on this address so it does not expire
2082                                 // until the flood has subsided
2083                                 sv.connectfloodaddresses[floodslotnum].lasttime = realtime;
2084                                 //Con_Printf("Flood detected!\n");
2085                                 return true;
2086                         }
2087                         // the flood appears to have subsided, so allow this
2088                         bestfloodslotnum = floodslotnum; // reuse the same slot
2089                         break;
2090                 }
2091         }
2092         // begin a new timeout on this address
2093         sv.connectfloodaddresses[bestfloodslotnum].address = noportpeeraddress;
2094         sv.connectfloodaddresses[bestfloodslotnum].lasttime = realtime;
2095         //Con_Printf("Flood detection initiated!\n");
2096         return false;
2097 }
2098
2099 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress)
2100 {
2101         int floodslotnum;
2102         lhnetaddress_t noportpeeraddress;
2103         // see if this is a connect flood
2104         noportpeeraddress = *peeraddress;
2105         LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2106         for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2107         {
2108                 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2109                 {
2110                         // this address matches an ongoing flood address
2111                         // remove the ban
2112                         sv.connectfloodaddresses[floodslotnum].address.addresstype = LHNETADDRESSTYPE_NONE;
2113                         sv.connectfloodaddresses[floodslotnum].lasttime = 0;
2114                         //Con_Printf("Flood cleared!\n");
2115                 }
2116         }
2117 }
2118
2119 // returns a string describing the user level, or NULL for auth failure
2120 const char *RCon_Authenticate(const char *password, const char *s, const char *endpos)
2121 {
2122         const char *text;
2123         qboolean hasquotes;
2124
2125         if(!strcmp(rcon_password.string, password))
2126                 return "rcon";
2127         
2128         if(strcmp(rcon_restricted_password.string, password))
2129                 return NULL;
2130
2131         for(text = s; text != endpos; ++text)
2132                 if(*text > 0 && (*text < ' ' || *text == ';'))
2133                         return NULL; // block possible exploits against the parser/alias expansion
2134
2135         while(s != endpos)
2136         {
2137                 size_t l = strlen(s);
2138                 if(l)
2139                 {
2140                         hasquotes = (strchr(s, '"') != NULL);
2141                         // sorry, we can't allow these substrings in wildcard expressions,
2142                         // as they can mess with the argument counts
2143                         text = rcon_restricted_commands.string;
2144                         while(COM_ParseToken_Console(&text))
2145                         {
2146                                 // com_token now contains a pattern to check for...
2147                                 if(strchr(com_token, '*') || strchr(com_token, '?')) // wildcard expression, * can only match a SINGLE argument
2148                                 {
2149                                         if(!hasquotes)
2150                                                 if(matchpattern_with_separator(s, com_token, true, " ", true)) // note how we excluded tab, newline etc. above
2151                                                         goto match;
2152                                 }
2153                                 else if(strchr(com_token, ' ')) // multi-arg expression? must match in whole
2154                                 {
2155                                         if(!strcmp(com_token, s))
2156                                                 goto match;
2157                                 }
2158                                 else // single-arg expression? must match the beginning of the command
2159                                 {
2160                                         if(!strcmp(com_token, s))
2161                                                 goto match;
2162                                         if(!memcmp(va("%s ", com_token), s, strlen(com_token) + 1))
2163                                                 goto match;
2164                                 }
2165                         }
2166                         // if we got here, nothing matched!
2167                         return NULL;
2168                 }
2169 match:
2170                 s += l + 1;
2171         }
2172
2173         return "restricted rcon";
2174 }
2175
2176 extern void SV_SendServerinfo (client_t *client);
2177 static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
2178 {
2179         int i, ret, clientnum, best;
2180         double besttime;
2181         client_t *client;
2182         char *s, *string, response[1400], addressstring2[128], stringbuf[16384];
2183         qboolean islocal = (LHNETADDRESS_GetAddressType(peeraddress) == LHNETADDRESSTYPE_LOOP);
2184
2185         if (!sv.active)
2186                 return false;
2187
2188         // convert the address to a string incase we need it
2189         LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
2190
2191         // see if we can identify the sender as a local player
2192         // (this is necessary for rcon to send a reliable reply if the client is
2193         //  actually on the server, not sending remotely)
2194         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2195                 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
2196                         break;
2197         if (i == svs.maxclients)
2198                 host_client = NULL;
2199
2200         if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
2201         {
2202                 // received a command string - strip off the packaging and put it
2203                 // into our string buffer with NULL termination
2204                 data += 4;
2205                 length -= 4;
2206                 length = min(length, (int)sizeof(stringbuf) - 1);
2207                 memcpy(stringbuf, data, length);
2208                 stringbuf[length] = 0;
2209                 string = stringbuf;
2210
2211                 if (developer.integer >= 10)
2212                 {
2213                         Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
2214                         Com_HexDumpToConsole(data, length);
2215                 }
2216
2217                 if (length >= 12 && !memcmp(string, "getchallenge", 12) && (islocal || sv_public.integer > -2))
2218                 {
2219                         for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
2220                         {
2221                                 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
2222                                         break;
2223                                 if (besttime > challenge[i].time)
2224                                         besttime = challenge[best = i].time;
2225                         }
2226                         // if we did not find an exact match, choose the oldest and
2227                         // update address and string
2228                         if (i == MAX_CHALLENGES)
2229                         {
2230                                 i = best;
2231                                 challenge[i].address = *peeraddress;
2232                                 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
2233                         }
2234                         challenge[i].time = realtime;
2235                         // send the challenge
2236                         NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
2237                         return true;
2238                 }
2239                 if (length > 8 && !memcmp(string, "connect\\", 8) && (islocal || sv_public.integer > -2))
2240                 {
2241                         string += 7;
2242                         length -= 7;
2243
2244                         if (!(s = SearchInfostring(string, "challenge")))
2245                                 return true;
2246                         // validate the challenge
2247                         for (i = 0;i < MAX_CHALLENGES;i++)
2248                                 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
2249                                         break;
2250                         // if the challenge is not recognized, drop the packet
2251                         if (i == MAX_CHALLENGES)
2252                                 return true;
2253
2254                         // check engine protocol
2255                         if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
2256                         {
2257                                 if (developer.integer >= 10)
2258                                         Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
2259                                 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
2260                                 return true;
2261                         }
2262
2263                         // see if this is a duplicate connection request or a disconnected
2264                         // client who is rejoining to the same client slot
2265                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2266                         {
2267                                 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2268                                 {
2269                                         // this is a known client...
2270                                         if (client->spawned)
2271                                         {
2272                                                 // client crashed and is coming back,
2273                                                 // keep their stuff intact
2274                                                 if (developer.integer >= 10)
2275                                                         Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", addressstring2);
2276                                                 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2277                                                 SV_VM_Begin();
2278                                                 SV_SendServerinfo(client);
2279                                                 SV_VM_End();
2280                                         }
2281                                         else
2282                                         {
2283                                                 // client is still trying to connect,
2284                                                 // so we send a duplicate reply
2285                                                 if (developer.integer >= 10)
2286                                                         Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
2287                                                 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2288                                         }
2289                                         return true;
2290                                 }
2291                         }
2292
2293                         if (NetConn_PreventConnectFlood(peeraddress))
2294                                 return true;
2295
2296                         // find an empty client slot for this new client
2297                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2298                         {
2299                                 netconn_t *conn;
2300                                 if (!client->active && (conn = NetConn_Open(mysocket, peeraddress)))
2301                                 {
2302                                         // allocated connection
2303                                         if (developer.integer >= 10)
2304                                                 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
2305                                         NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2306                                         // now set up the client
2307                                         SV_VM_Begin();
2308                                         SV_ConnectClient(clientnum, conn);
2309                                         SV_VM_End();
2310                                         NetConn_Heartbeat(1);
2311                                         return true;
2312                                 }
2313                         }
2314
2315                         // no empty slots found - server is full
2316                         if (developer.integer >= 10)
2317                                 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
2318                         NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
2319
2320                         return true;
2321                 }
2322                 if (length >= 7 && !memcmp(string, "getinfo", 7) && (islocal || sv_public.integer > -1))
2323                 {
2324                         const char *challenge = NULL;
2325
2326                         // If there was a challenge in the getinfo message
2327                         if (length > 8 && string[7] == ' ')
2328                                 challenge = string + 8;
2329
2330                         if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
2331                         {
2332                                 if (developer.integer >= 10)
2333                                         Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
2334                                 NetConn_WriteString(mysocket, response, peeraddress);
2335                         }
2336                         return true;
2337                 }
2338                 if (length >= 9 && !memcmp(string, "getstatus", 9) && (islocal || sv_public.integer > -1))
2339                 {
2340                         const char *challenge = NULL;
2341
2342                         // If there was a challenge in the getinfo message
2343                         if (length > 10 && string[9] == ' ')
2344                                 challenge = string + 10;
2345
2346                         if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
2347                         {
2348                                 if (developer.integer >= 10)
2349                                         Con_Printf("Sending reply to client %s - %s\n", addressstring2, response);
2350                                 NetConn_WriteString(mysocket, response, peeraddress);
2351                         }
2352                         return true;
2353                 }
2354                 if (length >= 5 && !memcmp(string, "rcon ", 5))
2355                 {
2356                         int i;
2357                         char *s = string + 5;
2358                         char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2359                         char password[64];
2360                         for (i = 0;*s > ' ';s++)
2361                                 if (i < (int)sizeof(password) - 1)
2362                                         password[i++] = *s;
2363                         if(*s <= ' ' && s != endpos) // skip leading ugly space
2364                                 ++s;
2365                         password[i] = 0;
2366                         if (password[0] > ' ')
2367                         {
2368                                 const char *userlevel = RCon_Authenticate(password, s, endpos);
2369                                 if(userlevel)
2370                                 {
2371                                         // looks like a legitimate rcon command with the correct password
2372                                         char *s_ptr = s;
2373                                         Con_Printf("server received %s command from %s: ", userlevel, host_client ? host_client->name : addressstring2);
2374                                         while(s_ptr != endpos)
2375                                         {
2376                                                 size_t l = strlen(s_ptr);
2377                                                 if(l)
2378                                                         Con_Printf(" %s;", s_ptr);
2379                                                 s_ptr += l + 1;
2380                                         }
2381                                         Con_Printf("\n");
2382                                         rcon_redirect = true;
2383                                         rcon_redirect_bufferpos = 0;
2384                                         while(s != endpos)
2385                                         {
2386                                                 size_t l = strlen(s);
2387                                                 if(l)
2388                                                 {
2389                                                         client_t *host_client_save = host_client;
2390                                                         Cmd_ExecuteString(s, src_command);
2391                                                         host_client = host_client_save;
2392                                                         // in case it is a command that changes host_client (like restart)
2393                                                 }
2394                                                 s += l + 1;
2395                                         }
2396                                         rcon_redirect_buffer[rcon_redirect_bufferpos] = 0;
2397                                         rcon_redirect = false;
2398                                         // print resulting text to client
2399                                         // if client is playing, send a reliable reply instead of
2400                                         // a command packet
2401                                         if (host_client)
2402                                         {
2403                                                 // if the netconnection is loop, then this is the
2404                                                 // local player on a listen mode server, and it would
2405                                                 // result in duplicate printing to the console
2406                                                 // (not that the local player should be using rcon
2407                                                 //  when they have the console)
2408                                                 if (host_client->netconnection && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2409                                                         SV_ClientPrintf("%s", rcon_redirect_buffer);
2410                                         }
2411                                         else
2412                                         {
2413                                                 // qw print command
2414                                                 dpsnprintf(response, sizeof(response), "\377\377\377\377n%s", rcon_redirect_buffer);
2415                                                 NetConn_WriteString(mysocket, response, peeraddress);
2416                                         }
2417                                 }
2418                                 else
2419                                 {
2420                                         Con_Printf("server denied rcon access to %s\n", host_client ? host_client->name : addressstring2);
2421                                 }
2422                         }
2423                         return true;
2424                 }
2425                 if (!strncmp(string, "ping", 4))
2426                 {
2427                         if (developer.integer >= 10)
2428                                 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
2429                         NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
2430                         return true;
2431                 }
2432                 if (!strncmp(string, "ack", 3))
2433                         return true;
2434                 // we may not have liked the packet, but it was a command packet, so
2435                 // we're done processing this packet now
2436                 return true;
2437         }
2438         // netquake control packets, supported for compatibility only, and only
2439         // when running game protocols that are normally served via this connection
2440         // protocol
2441         // (this protects more modern protocols against being used for
2442         //  Quake packet flood Denial Of Service attacks)
2443         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))
2444         {
2445                 int c;
2446                 int protocolnumber;
2447                 const char *protocolname;
2448                 data += 4;
2449                 length -= 4;
2450                 SZ_Clear(&net_message);
2451                 SZ_Write(&net_message, data, length);
2452                 MSG_BeginReading();
2453                 c = MSG_ReadByte();
2454                 switch (c)
2455                 {
2456                 case CCREQ_CONNECT:
2457                         if (developer.integer >= 10)
2458                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
2459                         if(!islocal && sv_public.integer <= -2)
2460                                 break;
2461
2462                         protocolname = MSG_ReadString();
2463                         protocolnumber = MSG_ReadByte();
2464                         if (strcmp(protocolname, "QUAKE") || protocolnumber != NET_PROTOCOL_VERSION)
2465                         {
2466                                 if (developer.integer >= 10)
2467                                         Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
2468                                 SZ_Clear(&net_message);
2469                                 // save space for the header, filled in later
2470                                 MSG_WriteLong(&net_message, 0);
2471                                 MSG_WriteByte(&net_message, CCREP_REJECT);
2472                                 MSG_WriteString(&net_message, "Incompatible version.\n");
2473                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2474                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2475                                 SZ_Clear(&net_message);
2476                                 break;
2477                         }
2478
2479                         // see if this connect request comes from a known client
2480                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2481                         {
2482                                 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2483                                 {
2484                                         // this is either a duplicate connection request
2485                                         // or coming back from a timeout
2486                                         // (if so, keep their stuff intact)
2487
2488                                         // send a reply
2489                                         if (developer.integer >= 10)
2490                                                 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
2491                                         SZ_Clear(&net_message);
2492                                         // save space for the header, filled in later
2493                                         MSG_WriteLong(&net_message, 0);
2494                                         MSG_WriteByte(&net_message, CCREP_ACCEPT);
2495                                         MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
2496                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2497                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2498                                         SZ_Clear(&net_message);
2499
2500                                         // if client is already spawned, re-send the
2501                                         // serverinfo message as they'll need it to play
2502                                         if (client->spawned)
2503                                         {
2504                                                 SV_VM_Begin();
2505                                                 SV_SendServerinfo(client);
2506                                                 SV_VM_End();
2507                                         }
2508                                         return true;
2509                                 }
2510                         }
2511
2512                         // this is a new client, check for connection flood
2513                         if (NetConn_PreventConnectFlood(peeraddress))
2514                                 break;
2515
2516                         // find a slot for the new client
2517                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2518                         {
2519                                 netconn_t *conn;
2520                                 if (!client->active && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
2521                                 {
2522                                         // connect to the client
2523                                         // everything is allocated, just fill in the details
2524                                         strlcpy (conn->address, addressstring2, sizeof (conn->address));
2525                                         if (developer.integer >= 10)
2526                                                 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
2527                                         // send back the info about the server connection
2528                                         SZ_Clear(&net_message);
2529                                         // save space for the header, filled in later
2530                                         MSG_WriteLong(&net_message, 0);
2531                                         MSG_WriteByte(&net_message, CCREP_ACCEPT);
2532                                         MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
2533                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2534                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2535                                         SZ_Clear(&net_message);
2536                                         // now set up the client struct
2537                                         SV_VM_Begin();
2538                                         SV_ConnectClient(clientnum, conn);
2539                                         SV_VM_End();
2540                                         NetConn_Heartbeat(1);
2541                                         return true;
2542                                 }
2543                         }
2544
2545                         if (developer.integer >= 10)
2546                                 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
2547                         // no room; try to let player know
2548                         SZ_Clear(&net_message);
2549                         // save space for the header, filled in later
2550                         MSG_WriteLong(&net_message, 0);
2551                         MSG_WriteByte(&net_message, CCREP_REJECT);
2552                         MSG_WriteString(&net_message, "Server is full.\n");
2553                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2554                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2555                         SZ_Clear(&net_message);
2556                         break;
2557                 case CCREQ_SERVER_INFO:
2558                         if (developer.integer >= 10)
2559                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
2560                         if(!islocal && sv_public.integer <= -1)
2561                                 break;
2562                         if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
2563                         {
2564                                 int numclients;
2565                                 char myaddressstring[128];
2566                                 if (developer.integer >= 10)
2567                                         Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
2568                                 SZ_Clear(&net_message);
2569                                 // save space for the header, filled in later
2570                                 MSG_WriteLong(&net_message, 0);
2571                                 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
2572                                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), myaddressstring, sizeof(myaddressstring), true);
2573                                 MSG_WriteString(&net_message, myaddressstring);
2574                                 MSG_WriteString(&net_message, hostname.string);
2575                                 MSG_WriteString(&net_message, sv.name);
2576                                 // How many clients are there?
2577                                 for (i = 0, numclients = 0;i < svs.maxclients;i++)
2578                                         if (svs.clients[i].active)
2579                                                 numclients++;
2580                                 MSG_WriteByte(&net_message, numclients);
2581                                 MSG_WriteByte(&net_message, svs.maxclients);
2582                                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2583                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2584                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2585                                 SZ_Clear(&net_message);
2586                         }
2587                         break;
2588                 case CCREQ_PLAYER_INFO:
2589                         if (developer.integer >= 10)
2590                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
2591                         if(!islocal && sv_public.integer <= -1)
2592                                 break;
2593                         if (sv.active)
2594                         {
2595                                 int playerNumber, activeNumber, clientNumber;
2596                                 client_t *client;
2597
2598                                 playerNumber = MSG_ReadByte();
2599                                 activeNumber = -1;
2600                                 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
2601                                         if (client->active && ++activeNumber == playerNumber)
2602                                                 break;
2603                                 if (clientNumber != svs.maxclients)
2604                                 {
2605                                         SZ_Clear(&net_message);
2606                                         // save space for the header, filled in later
2607                                         MSG_WriteLong(&net_message, 0);
2608                                         MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
2609                                         MSG_WriteByte(&net_message, playerNumber);
2610                                         MSG_WriteString(&net_message, client->name);
2611                                         MSG_WriteLong(&net_message, client->colors);
2612                                         MSG_WriteLong(&net_message, client->frags);
2613                                         MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
2614                                         MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
2615                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2616                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2617                                         SZ_Clear(&net_message);
2618                                 }
2619                         }
2620                         break;
2621                 case CCREQ_RULE_INFO:
2622                         if (developer.integer >= 10)
2623                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
2624                         if(!islocal && sv_public.integer <= -1)
2625                                 break;
2626                         if (sv.active)
2627                         {
2628                                 char *prevCvarName;
2629                                 cvar_t *var;
2630
2631                                 // find the search start location
2632                                 prevCvarName = MSG_ReadString();
2633                                 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
2634
2635                                 // send the response
2636                                 SZ_Clear(&net_message);
2637                                 // save space for the header, filled in later
2638                                 MSG_WriteLong(&net_message, 0);
2639                                 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
2640                                 if (var)
2641                                 {
2642                                         MSG_WriteString(&net_message, var->name);
2643                                         MSG_WriteString(&net_message, var->string);
2644                                 }
2645                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2646                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2647                                 SZ_Clear(&net_message);
2648                         }
2649                         break;
2650                 default:
2651                         break;
2652                 }
2653                 SZ_Clear(&net_message);
2654                 // we may not have liked the packet, but it was a valid control
2655                 // packet, so we're done processing this packet now
2656                 return true;
2657         }
2658         if (host_client)
2659         {
2660                 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length, sv.protocol, host_client->spawned ? net_messagetimeout.value : net_connecttimeout.value)) == 2)
2661                 {
2662                         SV_VM_Begin();
2663                         SV_ReadClientMessage();
2664                         SV_VM_End();
2665                         return ret;
2666                 }
2667         }
2668         return 0;
2669 }
2670
2671 void NetConn_ServerFrame(void)
2672 {
2673         int i, length;
2674         lhnetaddress_t peeraddress;
2675         for (i = 0;i < sv_numsockets;i++)
2676                 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2677                         NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
2678         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2679         {
2680                 // never timeout loopback connections
2681                 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2682                 {
2683                         Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
2684                         SV_VM_Begin();
2685                         SV_DropClient(false);
2686                         SV_VM_End();
2687                 }
2688         }
2689 }
2690
2691 void NetConn_SleepMicroseconds(int microseconds)
2692 {
2693         LHNET_SleepUntilPacket_Microseconds(microseconds);
2694 }
2695
2696 void NetConn_QueryMasters(qboolean querydp, qboolean queryqw)
2697 {
2698         int i;
2699         int masternum;
2700         lhnetaddress_t masteraddress;
2701         lhnetaddress_t broadcastaddress;
2702         char request[256];
2703
2704         if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
2705                 return;
2706
2707         // 26000 is the default quake server port, servers on other ports will not
2708         // be found
2709         // note this is IPv4-only, I doubt there are IPv6-only LANs out there
2710         LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
2711
2712         if (querydp)
2713         {
2714                 for (i = 0;i < cl_numsockets;i++)
2715                 {
2716                         if (cl_sockets[i])
2717                         {
2718                                 // search LAN for Quake servers
2719                                 SZ_Clear(&net_message);
2720                                 // save space for the header, filled in later
2721                                 MSG_WriteLong(&net_message, 0);
2722                                 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
2723                                 MSG_WriteString(&net_message, "QUAKE");
2724                                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2725                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2726                                 NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
2727                                 SZ_Clear(&net_message);
2728
2729                                 // search LAN for DarkPlaces servers
2730                                 NetConn_WriteString(cl_sockets[i], "\377\377\377\377getstatus", &broadcastaddress);
2731
2732                                 // build the getservers message to send to the dpmaster master servers
2733                                 dpsnprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
2734
2735                                 // search internet
2736                                 for (masternum = 0;sv_masters[masternum].name;masternum++)
2737                                 {
2738                                         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])))
2739                                         {
2740                                                 masterquerycount++;
2741                                                 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
2742                                         }
2743                                 }
2744                         }
2745                 }
2746         }
2747
2748         // only query QuakeWorld servers when the user wants to
2749         if (queryqw)
2750         {
2751                 for (i = 0;i < cl_numsockets;i++)
2752                 {
2753                         if (cl_sockets[i])
2754                         {
2755                                 // search LAN for QuakeWorld servers
2756                                 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &broadcastaddress);
2757
2758                                 // build the getservers message to send to the qwmaster master servers
2759                                 // note this has no -1 prefix, and the trailing nul byte is sent
2760                                 dpsnprintf(request, sizeof(request), "c\n");
2761
2762                                 // search internet
2763                                 for (masternum = 0;sv_qwmasters[masternum].name;masternum++)
2764                                 {
2765                                         if (sv_qwmasters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_qwmasters[masternum].string, QWMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
2766                                         {
2767                                                 if (m_state != m_slist)
2768                                                 {
2769                                                         char lookupstring[128];
2770                                                         LHNETADDRESS_ToString(&masteraddress, lookupstring, sizeof(lookupstring), true);
2771                                                         Con_Printf("Querying master %s (resolved from %s)\n", lookupstring, sv_qwmasters[masternum].string);
2772                                                 }
2773                                                 masterquerycount++;
2774                                                 NetConn_Write(cl_sockets[i], request, (int)strlen(request) + 1, &masteraddress);
2775                                         }
2776                                 }
2777                         }
2778                 }
2779         }
2780         if (!masterquerycount)
2781         {
2782                 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
2783                 M_Update_Return_Reason("No network");
2784         }
2785 }
2786
2787 void NetConn_Heartbeat(int priority)
2788 {
2789         lhnetaddress_t masteraddress;
2790         int masternum;
2791         lhnetsocket_t *mysocket;
2792
2793         // if it's a state change (client connected), limit next heartbeat to no
2794         // more than 30 sec in the future
2795         if (priority == 1 && nextheartbeattime > realtime + 30.0)
2796                 nextheartbeattime = realtime + 30.0;
2797
2798         // limit heartbeatperiod to 30 to 270 second range,
2799         // lower limit is to avoid abusing master servers with excess traffic,
2800         // upper limit is to avoid timing out on the master server (which uses
2801         // 300 sec timeout)
2802         if (sv_heartbeatperiod.value < 30)
2803                 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
2804         if (sv_heartbeatperiod.value > 270)
2805                 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
2806
2807         // make advertising optional and don't advertise singleplayer games, and
2808         // only send a heartbeat as often as the admin wants
2809         if (sv.active && sv_public.integer > 0 && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
2810         {
2811                 nextheartbeattime = realtime + sv_heartbeatperiod.value;
2812                 for (masternum = 0;sv_masters[masternum].name;masternum++)
2813                         if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
2814                                 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
2815         }
2816 }
2817
2818 static void Net_Heartbeat_f(void)
2819 {
2820         if (sv.active)
2821                 NetConn_Heartbeat(2);
2822         else
2823                 Con_Print("No server running, can not heartbeat to master server.\n");
2824 }
2825
2826 void PrintStats(netconn_t *conn)
2827 {
2828         if ((cls.state == ca_connected && cls.protocol == PROTOCOL_QUAKEWORLD) || (sv.active && sv.protocol == PROTOCOL_QUAKEWORLD))
2829                 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->outgoing_unreliable_sequence, conn->qw.incoming_sequence);
2830         else
2831                 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->nq.sendSequence, conn->nq.receiveSequence);
2832 }
2833
2834 void Net_Stats_f(void)
2835 {
2836         netconn_t *conn;
2837         Con_Printf("unreliable messages sent   = %i\n", unreliableMessagesSent);
2838         Con_Printf("unreliable messages recv   = %i\n", unreliableMessagesReceived);
2839         Con_Printf("reliable messages sent     = %i\n", reliableMessagesSent);
2840         Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
2841         Con_Printf("packetsSent                = %i\n", packetsSent);
2842         Con_Printf("packetsReSent              = %i\n", packetsReSent);
2843         Con_Printf("packetsReceived            = %i\n", packetsReceived);
2844         Con_Printf("receivedDuplicateCount     = %i\n", receivedDuplicateCount);
2845         Con_Printf("droppedDatagrams           = %i\n", droppedDatagrams);
2846         Con_Print("connections                =\n");
2847         for (conn = netconn_list;conn;conn = conn->next)
2848                 PrintStats(conn);
2849 }
2850
2851 void Net_Refresh_f(void)
2852 {
2853         if (m_state != m_slist) {
2854                 Con_Print("Sending new requests to master servers\n");
2855                 ServerList_QueryList(false, true, false, true);
2856                 Con_Print("Listening for replies...\n");
2857         } else
2858                 ServerList_QueryList(false, true, false, false);
2859 }
2860
2861 void Net_Slist_f(void)
2862 {
2863         ServerList_ResetMasks();
2864         serverlist_sortbyfield = SLIF_PING;
2865         serverlist_sortdescending = false;
2866     if (m_state != m_slist) {
2867                 Con_Print("Sending requests to master servers\n");
2868                 ServerList_QueryList(true, true, false, true);
2869                 Con_Print("Listening for replies...\n");
2870         } else
2871                 ServerList_QueryList(true, true, false, false);
2872 }
2873
2874 void Net_SlistQW_f(void)
2875 {
2876         ServerList_ResetMasks();
2877         serverlist_sortbyfield = SLIF_PING;
2878         serverlist_sortdescending = false;
2879     if (m_state != m_slist) {
2880                 Con_Print("Sending requests to master servers\n");
2881                 ServerList_QueryList(true, false, true, true);
2882                 serverlist_consoleoutput = true;
2883                 Con_Print("Listening for replies...\n");
2884         } else
2885                 ServerList_QueryList(true, false, true, false);
2886 }
2887
2888 void NetConn_Init(void)
2889 {
2890         int i;
2891         lhnetaddress_t tempaddress;
2892         netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
2893         Cmd_AddCommand("net_stats", Net_Stats_f, "print network statistics");
2894         Cmd_AddCommand("net_slist", Net_Slist_f, "query dp master servers and print all server information");
2895         Cmd_AddCommand("net_slistqw", Net_SlistQW_f, "query qw master servers and print all server information");
2896         Cmd_AddCommand("net_refresh", Net_Refresh_f, "query dp master servers and refresh all server information");
2897         Cmd_AddCommand("heartbeat", Net_Heartbeat_f, "send a heartbeat to the master server (updates your server information)");
2898         Cvar_RegisterVariable(&rcon_restricted_password);
2899         Cvar_RegisterVariable(&rcon_restricted_commands);
2900         Cvar_RegisterVariable(&net_slist_queriespersecond);
2901         Cvar_RegisterVariable(&net_slist_queriesperframe);
2902         Cvar_RegisterVariable(&net_slist_timeout);
2903         Cvar_RegisterVariable(&net_slist_maxtries);
2904         Cvar_RegisterVariable(&net_slist_pause);
2905         Cvar_RegisterVariable(&net_messagetimeout);
2906         Cvar_RegisterVariable(&net_connecttimeout);
2907         Cvar_RegisterVariable(&net_connectfloodblockingtimeout);
2908         Cvar_RegisterVariable(&cl_netlocalping);
2909         Cvar_RegisterVariable(&cl_netpacketloss_send);
2910         Cvar_RegisterVariable(&cl_netpacketloss_receive);
2911         Cvar_RegisterVariable(&hostname);
2912         Cvar_RegisterVariable(&developer_networking);
2913         Cvar_RegisterVariable(&cl_netport);
2914         Cvar_RegisterVariable(&sv_netport);
2915         Cvar_RegisterVariable(&net_address);
2916         //Cvar_RegisterVariable(&net_address_ipv6);
2917         Cvar_RegisterVariable(&sv_public);
2918         Cvar_RegisterVariable(&sv_heartbeatperiod);
2919         for (i = 0;sv_masters[i].name;i++)
2920                 Cvar_RegisterVariable(&sv_masters[i]);
2921         Cvar_RegisterVariable(&gameversion);
2922 // 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.
2923         if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
2924         {
2925                 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
2926                 {
2927                         Con_Printf("-ip option used, setting net_address to \"%s\"\n", com_argv[i + 1]);
2928                         Cvar_SetQuick(&net_address, com_argv[i + 1]);
2929                 }
2930                 else
2931                         Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
2932         }
2933 // 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
2934         if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
2935         {
2936                 i = atoi(com_argv[i + 1]);
2937                 if (i >= 0 && i < 65536)
2938                 {
2939                         Con_Printf("-port option used, setting port cvar to %i\n", i);
2940                         Cvar_SetValueQuick(&sv_netport, i);
2941                 }
2942                 else
2943                         Con_Printf("-port option used, but %i is not a valid port number\n", i);
2944         }
2945         cl_numsockets = 0;
2946         sv_numsockets = 0;
2947         net_message.data = net_message_buf;
2948         net_message.maxsize = sizeof(net_message_buf);
2949         net_message.cursize = 0;
2950         LHNET_Init();
2951 }
2952
2953 void NetConn_Shutdown(void)
2954 {
2955         NetConn_CloseClientPorts();
2956         NetConn_CloseServerPorts();
2957         LHNET_Shutdown();
2958 }
2959