changed several DPrint's and developer cvar checks to higher developer cvar levels...
[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", "advertises this server on the master server (so that players can find it in the server browser)"};
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", "12.166.196.192", "default master server 3 (admin: Venim)"}, // admin: Venim
42         {0, "sv_masterextra4", "excalibur.nvg.ntnu.no", "default master server 4 (admin: tChr)"}, // admin: tChr
43         {0, NULL, NULL, NULL}
44 };
45
46 static cvar_t sv_qwmasters [] =
47 {
48         {CVAR_SAVE, "sv_qwmaster1", "", "user-chosen qwmaster server 1"},
49         {CVAR_SAVE, "sv_qwmaster2", "", "user-chosen qwmaster server 2"},
50         {CVAR_SAVE, "sv_qwmaster3", "", "user-chosen qwmaster server 3"},
51         {CVAR_SAVE, "sv_qwmaster4", "", "user-chosen qwmaster server 4"},
52         {0, "sv_qwmasterextra1", "satan.idsoftware.com", "default qwmaster server 1 (admin: idSoftware)"},
53         {0, "sv_qwmasterextra2", "192.246.40.37:27000", "id Limbo (admin: id Software)"},
54         {0, "sv_qwmasterextra3", "192.246.40.37:27002", "id CTF (admin: id Software)"},
55         {0, "sv_qwmasterextra4", "192.246.40.37:27003", "id TeamFortress (admin: id Software)"},
56         {0, "sv_qwmasterextra5", "192.246.40.37:27004", "id Miscilaneous (admin: id Software)"},
57         {0, "sv_qwmasterextra6", "192.246.40.37:27006", "id Deathmatch Only (admin: id Software)"},
58         {0, "sv_qwmasterextra7", "150.254.66.120:27000", "Poland's master server. (admin: unknown)"},
59         {0, "sv_qwmasterextra8", "62.112.145.129:27000", "Ocrana master server. (admin: unknown)"},
60         {0, "sv_qwmasterextra9", "master.edome.net", "edome master server. (admin: unknown)"},
61         {0, "sv_qwmasterextra10", "qwmaster.barrysworld.com", "barrysworld master server. (admin: unknown)"},
62         {0, "sv_qwmasterextra11", "qwmaster.ocrana.de:27000", "Ocrana2 master server. (admin: unknown)"},
63         {0, "sv_qwmasterextra12", "213.221.174.165:27000", "unknown1 master server. (admin: unknown)"},
64         {0, "sv_qwmasterextra13", "195.74.0.8", "unknown2 master server. (admin: unknown)"},
65         {0, "sv_qwmasterextra14", "192.246.40.37", "unknown3 master server. (admin: unknown)"},
66         {0, "sv_qwmasterextra15", "192.246.40.37:27006", "unknown4 master server. (admin: unknown)"},
67         {0, "sv_qwmasterextra16", "204.182.161.2", "unknown5 master server. (admin: unknown)"},
68         {0, NULL, NULL, NULL}
69 };
70
71 static double nextheartbeattime = 0;
72
73 sizebuf_t net_message;
74 static unsigned char net_message_buf[NET_MAXMESSAGE];
75
76 cvar_t net_messagetimeout = {0, "net_messagetimeout","300", "drops players who have not sent any packets for this many seconds"};
77 cvar_t net_messagerejointimeout = {0, "net_messagerejointimeout","10", "give a player this much time in seconds to rejoin and continue playing (not losing frags and such)"};
78 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)"};
79 cvar_t hostname = {CVAR_SAVE, "hostname", "UNNAMED", "server message to show in server browser"};
80 cvar_t developer_networking = {0, "developer_networking", "0", "prints all received and sent packets (recommended only for debugging)"};
81
82 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)"};
83 static cvar_t cl_netpacketloss = {0, "cl_netpacketloss","0", "drops this percentage of packets (incoming and outgoing), useful for testing network protocol robustness (effects failing to start, sounds failing to play, etc)"};
84 static cvar_t net_slist_queriespersecond = {0, "net_slist_queriespersecond", "20", "how many server information requests to send per second"};
85 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)"};
86 static cvar_t net_slist_timeout = {0, "net_slist_timeout", "4", "how long to listen for a server information response before giving up"};
87 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)"};
88
89 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"};
90
91 /* statistic counters */
92 static int packetsSent = 0;
93 static int packetsReSent = 0;
94 static int packetsReceived = 0;
95 static int receivedDuplicateCount = 0;
96 static int droppedDatagrams = 0;
97
98 static int unreliableMessagesSent = 0;
99 static int unreliableMessagesReceived = 0;
100 static int reliableMessagesSent = 0;
101 static int reliableMessagesReceived = 0;
102
103 double masterquerytime = -1000;
104 int masterquerycount = 0;
105 int masterreplycount = 0;
106 int serverquerycount = 0;
107 int serverreplycount = 0;
108
109 // this is only false if there are still servers left to query
110 static qboolean serverlist_querysleep = true;
111 // this is pushed a second or two ahead of realtime whenever a master server
112 // reply is received, to avoid issuing queries while master replies are still
113 // flooding in (which would make a mess of the ping times)
114 static double serverlist_querywaittime = 0;
115
116 static unsigned char sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
117 static unsigned char readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
118
119 static int cl_numsockets;
120 static lhnetsocket_t *cl_sockets[16];
121 static int sv_numsockets;
122 static lhnetsocket_t *sv_sockets[16];
123
124 netconn_t *netconn_list = NULL;
125 mempool_t *netconn_mempool = NULL;
126
127 cvar_t cl_netport = {0, "cl_port", "0", "forces client to use chosen port number if not 0"};
128 cvar_t sv_netport = {0, "port", "26000", "server port for players to connect to"};
129 cvar_t net_address = {0, "net_address", "0.0.0.0", "network address to open ports on"};
130 //cvar_t net_netaddress_ipv6 = {0, "net_address_ipv6", "[0:0:0:0:0:0:0:0]", "network address to open ipv6 ports on"};
131
132 // ServerList interface
133 serverlist_mask_t serverlist_andmasks[SERVERLIST_ANDMASKCOUNT];
134 serverlist_mask_t serverlist_ormasks[SERVERLIST_ORMASKCOUNT];
135
136 serverlist_infofield_t serverlist_sortbyfield;
137 qboolean serverlist_sortdescending;
138
139 int serverlist_viewcount = 0;
140 serverlist_entry_t *serverlist_viewlist[SERVERLIST_VIEWLISTSIZE];
141
142 int serverlist_cachecount;
143 serverlist_entry_t serverlist_cache[SERVERLIST_TOTALSIZE];
144
145 qboolean serverlist_consoleoutput;
146
147 // helper function to insert a value into the viewset
148 // spare entries will be removed
149 static void _ServerList_ViewList_Helper_InsertBefore( int index, serverlist_entry_t *entry )
150 {
151     int i;
152         if( serverlist_viewcount < SERVERLIST_VIEWLISTSIZE ) {
153                 i = serverlist_viewcount++;
154         } else {
155                 i = SERVERLIST_VIEWLISTSIZE - 1;
156         }
157
158         for( ; i > index ; i-- )
159                 serverlist_viewlist[ i ] = serverlist_viewlist[ i - 1 ];
160
161         serverlist_viewlist[index] = entry;
162 }
163
164 // we suppose serverlist_viewcount to be valid, ie > 0
165 static void _ServerList_ViewList_Helper_Remove( int index )
166 {
167         serverlist_viewcount--;
168         for( ; index < serverlist_viewcount ; index++ )
169                 serverlist_viewlist[index] = serverlist_viewlist[index + 1];
170 }
171
172 // returns true if A should be inserted before B
173 static qboolean _ServerList_Entry_Compare( serverlist_entry_t *A, serverlist_entry_t *B )
174 {
175         int result = 0; // > 0 if for numbers A > B and for text if A < B
176
177         switch( serverlist_sortbyfield ) {
178                 case SLIF_PING:
179                         result = A->info.ping - B->info.ping;
180                         break;
181                 case SLIF_MAXPLAYERS:
182                         result = A->info.maxplayers - B->info.maxplayers;
183                         break;
184                 case SLIF_NUMPLAYERS:
185                         result = A->info.numplayers - B->info.numplayers;
186                         break;
187                 case SLIF_PROTOCOL:
188                         result = A->info.protocol - B->info.protocol;
189                         break;
190                 case SLIF_CNAME:
191                         result = strcmp( B->info.cname, A->info.cname );
192                         break;
193                 case SLIF_GAME:
194                         result = strcmp( B->info.game, A->info.game );
195                         break;
196                 case SLIF_MAP:
197                         result = strcmp( B->info.map, A->info.map );
198                         break;
199                 case SLIF_MOD:
200                         result = strcmp( B->info.mod, A->info.mod );
201                         break;
202                 case SLIF_NAME:
203                         result = strcmp( B->info.name, A->info.name );
204                         break;
205                 default:
206                         Con_DPrint( "_ServerList_Entry_Compare: Bad serverlist_sortbyfield!\n" );
207                         break;
208         }
209
210         if( serverlist_sortdescending )
211                 return result > 0;
212         return result < 0;
213 }
214
215 static qboolean _ServerList_CompareInt( int A, serverlist_maskop_t op, int B )
216 {
217         // This should actually be done with some intermediate and end-of-function return
218         switch( op ) {
219                 case SLMO_LESS:
220                         return A < B;
221                 case SLMO_LESSEQUAL:
222                         return A <= B;
223                 case SLMO_EQUAL:
224                         return A == B;
225                 case SLMO_GREATER:
226                         return A > B;
227                 case SLMO_NOTEQUAL:
228                         return A != B;
229                 case SLMO_GREATEREQUAL:
230                 case SLMO_CONTAINS:
231                 case SLMO_NOTCONTAIN:
232                         return A >= B;
233                 default:
234                         Con_DPrint( "_ServerList_CompareInt: Bad op!\n" );
235                         return false;
236         }
237 }
238
239 static qboolean _ServerList_CompareStr( const char *A, serverlist_maskop_t op, const char *B )
240 {
241         int i;
242         char bufferA[ 256 ], bufferB[ 256 ]; // should be more than enough
243         for (i = 0;i < (int)sizeof(bufferA)-1 && A[i];i++)
244                 bufferA[i] = (A[i] >= 'A' && A[i] <= 'Z') ? (A[i] + 'a' - 'A') : A[i];
245         bufferA[i] = 0;
246         for (i = 0;i < (int)sizeof(bufferB)-1 && B[i];i++)
247                 bufferB[i] = (B[i] >= 'A' && B[i] <= 'Z') ? (B[i] + 'a' - 'A') : B[i];
248         bufferB[i] = 0;
249
250         // Same here, also using an intermediate & final return would be more appropriate
251         // A info B mask
252         switch( op ) {
253                 case SLMO_CONTAINS:
254                         return *bufferB && !!strstr( bufferA, bufferB ); // we want a real bool
255                 case SLMO_NOTCONTAIN:
256                         return !*bufferB || !strstr( bufferA, bufferB );
257                 case SLMO_LESS:
258                         return strcmp( bufferA, bufferB ) < 0;
259                 case SLMO_LESSEQUAL:
260                         return strcmp( bufferA, bufferB ) <= 0;
261                 case SLMO_EQUAL:
262                         return strcmp( bufferA, bufferB ) == 0;
263                 case SLMO_GREATER:
264                         return strcmp( bufferA, bufferB ) > 0;
265                 case SLMO_NOTEQUAL:
266                         return strcmp( bufferA, bufferB ) != 0;
267                 case SLMO_GREATEREQUAL:
268                         return strcmp( bufferA, bufferB ) >= 0;
269                 default:
270                         Con_DPrint( "_ServerList_CompareStr: Bad op!\n" );
271                         return false;
272         }
273 }
274
275 static qboolean _ServerList_Entry_Mask( serverlist_mask_t *mask, serverlist_info_t *info )
276 {
277         if( !_ServerList_CompareInt( info->ping, mask->tests[SLIF_PING], mask->info.ping ) )
278                 return false;
279         if( !_ServerList_CompareInt( info->maxplayers, mask->tests[SLIF_MAXPLAYERS], mask->info.maxplayers ) )
280                 return false;
281         if( !_ServerList_CompareInt( info->numplayers, mask->tests[SLIF_NUMPLAYERS], mask->info.numplayers ) )
282                 return false;
283         if( !_ServerList_CompareInt( info->protocol, mask->tests[SLIF_PROTOCOL], mask->info.protocol ))
284                 return false;
285         if( *mask->info.cname
286                 && !_ServerList_CompareStr( info->cname, mask->tests[SLIF_CNAME], mask->info.cname ) )
287                 return false;
288         if( *mask->info.game
289                 && !_ServerList_CompareStr( info->game, mask->tests[SLIF_GAME], mask->info.game ) )
290                 return false;
291         if( *mask->info.mod
292                 && !_ServerList_CompareStr( info->mod, mask->tests[SLIF_MOD], mask->info.mod ) )
293                 return false;
294         if( *mask->info.map
295                 && !_ServerList_CompareStr( info->map, mask->tests[SLIF_MAP], mask->info.map ) )
296                 return false;
297         if( *mask->info.name
298                 && !_ServerList_CompareStr( info->name, mask->tests[SLIF_NAME], mask->info.name ) )
299                 return false;
300         return true;
301 }
302
303 static void ServerList_ViewList_Insert( serverlist_entry_t *entry )
304 {
305         int start, end, mid;
306
307         // reject incompatible servers
308         if (entry->info.gameversion != gameversion.integer)
309                 return;
310
311         // FIXME: change this to be more readable (...)
312         // now check whether it passes through the masks
313         for( start = 0 ; serverlist_andmasks[start].active && start < SERVERLIST_ANDMASKCOUNT ; start++ )
314                 if( !_ServerList_Entry_Mask( &serverlist_andmasks[start], &entry->info ) )
315                         return;
316
317         for( start = 0 ; serverlist_ormasks[start].active && start < SERVERLIST_ORMASKCOUNT ; start++ )
318                 if( _ServerList_Entry_Mask( &serverlist_ormasks[start], &entry->info ) )
319                         break;
320         if( start == SERVERLIST_ORMASKCOUNT || (start > 0 && !serverlist_ormasks[start].active) )
321                 return;
322
323         if( !serverlist_viewcount ) {
324                 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
325                 return;
326         }
327         // ok, insert it, we just need to find out where exactly:
328
329         // two special cases
330         // check whether to insert it as new first item
331         if( _ServerList_Entry_Compare( entry, serverlist_viewlist[0] ) ) {
332                 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
333                 return;
334         } // check whether to insert it as new last item
335         else if( !_ServerList_Entry_Compare( entry, serverlist_viewlist[serverlist_viewcount - 1] ) ) {
336                 _ServerList_ViewList_Helper_InsertBefore( serverlist_viewcount, entry );
337                 return;
338         }
339         start = 0;
340         end = serverlist_viewcount - 1;
341         while( end > start + 1 )
342         {
343                 mid = (start + end) / 2;
344                 // test the item that lies in the middle between start and end
345                 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[mid] ) )
346                         // the item has to be in the upper half
347                         end = mid;
348                 else
349                         // the item has to be in the lower half
350                         start = mid;
351         }
352         _ServerList_ViewList_Helper_InsertBefore( start + 1, entry );
353 }
354
355 static void ServerList_ViewList_Remove( serverlist_entry_t *entry )
356 {
357         int i;
358         for( i = 0; i < serverlist_viewcount; i++ )
359         {
360                 if (serverlist_viewlist[i] == entry)
361                 {
362                         _ServerList_ViewList_Helper_Remove(i);
363                         break;
364                 }
365         }
366 }
367
368 void ServerList_RebuildViewList(void)
369 {
370         int i;
371
372         serverlist_viewcount = 0;
373         for( i = 0 ; i < serverlist_cachecount ; i++ )
374                 if( serverlist_cache[i].query == SQS_QUERIED )
375                         ServerList_ViewList_Insert( &serverlist_cache[i] );
376 }
377
378 void ServerList_ResetMasks(void)
379 {
380         memset( &serverlist_andmasks, 0, sizeof( serverlist_andmasks ) );
381         memset( &serverlist_ormasks, 0, sizeof( serverlist_ormasks ) );
382 }
383
384 #if 0
385 static void _ServerList_Test(void)
386 {
387         int i;
388         for( i = 0 ; i < 1024 ; i++ ) {
389                 memset( &serverlist_cache[serverlist_cachecount], 0, sizeof( serverlist_entry_t ) );
390                 serverlist_cache[serverlist_cachecount].info.ping = 1000 + 1024 - i;
391                 dpsnprintf( serverlist_cache[serverlist_cachecount].info.name, sizeof(serverlist_cache[serverlist_cachecount].info.name), "Black's ServerList Test %i", i );
392                 serverlist_cache[serverlist_cachecount].finished = true;
393                 sprintf( serverlist_cache[serverlist_cachecount].line1, "%i %s", serverlist_cache[serverlist_cachecount].info.ping, serverlist_cache[serverlist_cachecount].info.name );
394                 ServerList_ViewList_Insert( &serverlist_cache[serverlist_cachecount] );
395                 serverlist_cachecount++;
396         }
397 }
398 #endif
399
400 void ServerList_QueryList(qboolean querydp, qboolean queryqw)
401 {
402         //masterquerytime = realtime;
403         masterquerytime = Sys_DoubleTime();
404         masterquerycount = 0;
405         masterreplycount = 0;
406         serverquerycount = 0;
407         serverreplycount = 0;
408         serverlist_cachecount = 0;
409         serverlist_viewcount = 0;
410         serverlist_consoleoutput = false;
411
412         //_ServerList_Test();
413
414         NetConn_QueryMasters(querydp, queryqw);
415 }
416
417 // rest
418
419 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
420 {
421         int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
422         int i;
423         if (length == 0)
424                 return 0;
425         if (cl_netpacketloss.integer)
426                 for (i = 0;i < cl_numsockets;i++)
427                         if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
428                                 return 0;
429         if (developer_networking.integer)
430         {
431                 char addressstring[128], addressstring2[128];
432                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
433                 if (length > 0)
434                 {
435                         LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
436                         Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", mysocket, addressstring, data, maxlength, peeraddress, length, addressstring2);
437                         Com_HexDumpToConsole((unsigned char *)data, length);
438                 }
439                 else
440                         Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
441         }
442         return length;
443 }
444
445 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
446 {
447         int ret;
448         int i;
449         if (cl_netpacketloss.integer)
450                 for (i = 0;i < cl_numsockets;i++)
451                         if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
452                                 return length;
453         ret = LHNET_Write(mysocket, data, length, peeraddress);
454         if (developer_networking.integer)
455         {
456                 char addressstring[128], addressstring2[128];
457                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
458                 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
459                 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", mysocket, addressstring, data, length, peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
460                 Com_HexDumpToConsole((unsigned char *)data, length);
461         }
462         return ret;
463 }
464
465 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
466 {
467         // note this does not include the trailing NULL because we add that in the parser
468         return NetConn_Write(mysocket, string, (int)strlen(string), peeraddress);
469 }
470
471 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data, protocolversion_t protocol)
472 {
473         if (protocol == PROTOCOL_QUAKEWORLD)
474         {
475                 int packetLen;
476                 qboolean sendreliable;
477
478                 // note that it is ok to send empty messages to the qw server,
479                 // otherwise it won't respond to us at all
480
481                 sendreliable = false;
482                 // if the remote side dropped the last reliable message, resend it
483                 if (conn->qw.incoming_acknowledged > conn->qw.last_reliable_sequence && conn->qw.incoming_reliable_acknowledged != conn->qw.reliable_sequence)
484                         sendreliable = true;
485                 // if the reliable transmit buffer is empty, copy the current message out
486                 if (!conn->sendMessageLength && conn->message.cursize)
487                 {
488                         memcpy (conn->sendMessage, conn->message.data, conn->message.cursize);
489                         conn->sendMessageLength = conn->message.cursize;
490                         SZ_Clear(&conn->message); // clear the message buffer
491                         conn->qw.reliable_sequence ^= 1;
492                         sendreliable = true;
493                 }
494                 // outgoing unreliable packet number, and outgoing reliable packet number (0 or 1)
495                 *((int *)(sendbuffer + 0)) = LittleLong((unsigned int)conn->qw.outgoing_sequence | ((unsigned int)sendreliable<<31));
496                 // last received unreliable packet number, and last received reliable packet number (0 or 1)
497                 *((int *)(sendbuffer + 4)) = LittleLong((unsigned int)conn->qw.incoming_sequence | ((unsigned int)conn->qw.incoming_reliable_sequence<<31));
498                 packetLen = 8;
499                 conn->qw.outgoing_sequence++;
500                 // client sends qport in every packet
501                 if (conn == cls.netcon)
502                 {
503                         *((short *)(sendbuffer + 8)) = LittleShort(cls.qw_qport);
504                         packetLen += 2;
505                 }
506                 if (packetLen + (sendreliable ? conn->sendMessageLength : 0) > 1400)
507                 {
508                         Con_Printf ("NetConn_SendUnreliableMessage: reliable message too big %u\n", data->cursize);
509                         return -1;
510                 }
511                 // add the reliable message if there is one
512                 if (sendreliable)
513                 {
514                         memcpy(sendbuffer + packetLen, conn->sendMessage, conn->sendMessageLength);
515                         packetLen += conn->sendMessageLength;
516                         conn->qw.last_reliable_sequence = conn->qw.outgoing_sequence;
517                 }
518                 // add the unreliable message if possible
519                 if (packetLen + data->cursize <= 1400)
520                 {
521                         memcpy(sendbuffer + packetLen, data->data, data->cursize);
522                         packetLen += data->cursize;
523                 }
524
525                 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
526
527                 packetsSent++;
528                 unreliableMessagesSent++;
529
530                 // delay later packets to obey rate limit
531                 conn->qw.cleartime = max(conn->qw.cleartime, realtime) + packetLen * conn->qw.rate;
532
533                 return 0;
534         }
535         else
536         {
537                 unsigned int packetLen;
538                 unsigned int dataLen;
539                 unsigned int eom;
540                 unsigned int *header;
541
542                 // if a reliable message fragment has been lost, send it again
543                 if (conn->sendMessageLength && (realtime - conn->lastSendTime) > 1.0)
544                 {
545                         if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
546                         {
547                                 dataLen = conn->sendMessageLength;
548                                 eom = NETFLAG_EOM;
549                         }
550                         else
551                         {
552                                 dataLen = MAX_PACKETFRAGMENT;
553                                 eom = 0;
554                         }
555
556                         packetLen = NET_HEADERSIZE + dataLen;
557
558                         header = (unsigned int *)sendbuffer;
559                         header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
560                         header[1] = BigLong(conn->nq.sendSequence - 1);
561                         memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
562
563                         if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
564                         {
565                                 conn->lastSendTime = realtime;
566                                 packetsReSent++;
567                         }
568                 }
569
570                 // if we have a new reliable message to send, do so
571                 if (!conn->sendMessageLength && conn->message.cursize)
572                 {
573                         if (conn->message.cursize > (int)sizeof(conn->sendMessage))
574                         {
575                                 Con_Printf("NetConn_SendUnreliableMessage: reliable message too big (%u > %u)\n", conn->message.cursize, sizeof(conn->sendMessage));
576                                 conn->message.overflowed = true;
577                                 return -1;
578                         }
579
580                         if (developer_networking.integer && conn == cls.netcon)
581                         {
582                                 Con_Print("client sending reliable message to server:\n");
583                                 SZ_HexDumpToConsole(&conn->message);
584                         }
585
586                         memcpy(conn->sendMessage, conn->message.data, conn->message.cursize);
587                         conn->sendMessageLength = conn->message.cursize;
588                         SZ_Clear(&conn->message);
589
590                         if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
591                         {
592                                 dataLen = conn->sendMessageLength;
593                                 eom = NETFLAG_EOM;
594                         }
595                         else
596                         {
597                                 dataLen = MAX_PACKETFRAGMENT;
598                                 eom = 0;
599                         }
600
601                         packetLen = NET_HEADERSIZE + dataLen;
602
603                         header = (unsigned int *)sendbuffer;
604                         header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
605                         header[1] = BigLong(conn->nq.sendSequence);
606                         memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
607
608                         conn->nq.sendSequence++;
609
610                         NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
611
612                         conn->lastSendTime = realtime;
613                         packetsSent++;
614                         reliableMessagesSent++;
615                 }
616
617                 // if we have an unreliable message to send, do so
618                 if (data->cursize)
619                 {
620                         packetLen = NET_HEADERSIZE + data->cursize;
621
622                         if (packetLen > (int)sizeof(sendbuffer))
623                         {
624                                 Con_Printf("NetConn_SendUnreliableMessage: message too big %u\n", data->cursize);
625                                 return -1;
626                         }
627
628                         header = (unsigned int *)sendbuffer;
629                         header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
630                         header[1] = BigLong(conn->nq.unreliableSendSequence);
631                         memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
632
633                         conn->nq.unreliableSendSequence++;
634
635                         NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
636
637                         packetsSent++;
638                         unreliableMessagesSent++;
639                 }
640                 return 0;
641         }
642 }
643
644 void NetConn_CloseClientPorts(void)
645 {
646         for (;cl_numsockets > 0;cl_numsockets--)
647                 if (cl_sockets[cl_numsockets - 1])
648                         LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
649 }
650
651 void NetConn_OpenClientPort(const char *addressstring, int defaultport)
652 {
653         lhnetaddress_t address;
654         lhnetsocket_t *s;
655         char addressstring2[1024];
656         if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
657         {
658                 if ((s = LHNET_OpenSocket_Connectionless(&address)))
659                 {
660                         cl_sockets[cl_numsockets++] = s;
661                         LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
662                         Con_Printf("Client opened a socket on address %s\n", addressstring2);
663                 }
664                 else
665                 {
666                         LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
667                         Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
668                 }
669         }
670         else
671                 Con_Printf("Client unable to parse address %s\n", addressstring);
672 }
673
674 void NetConn_OpenClientPorts(void)
675 {
676         int port;
677         NetConn_CloseClientPorts();
678         port = bound(0, cl_netport.integer, 65535);
679         if (cl_netport.integer != port)
680                 Cvar_SetValueQuick(&cl_netport, port);
681         Con_Printf("Client using port %i\n", port);
682         NetConn_OpenClientPort("local:2", 0);
683         NetConn_OpenClientPort(net_address.string, port);
684         //NetConn_OpenClientPort(net_address_ipv6.string, port);
685 }
686
687 void NetConn_CloseServerPorts(void)
688 {
689         for (;sv_numsockets > 0;sv_numsockets--)
690                 if (sv_sockets[sv_numsockets - 1])
691                         LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
692 }
693
694 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
695 {
696         lhnetaddress_t address;
697         lhnetsocket_t *s;
698         int port;
699         char addressstring2[1024];
700
701         for (port = defaultport; port <= defaultport + 100; port++)
702         {
703                 if (LHNETADDRESS_FromString(&address, addressstring, port))
704                 {
705                         if ((s = LHNET_OpenSocket_Connectionless(&address)))
706                         {
707                                 sv_sockets[sv_numsockets++] = s;
708                                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
709                                 Con_Printf("Server listening on address %s\n", addressstring2);
710                                 break;
711                         }
712                         else
713                         {
714                                 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
715                                 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
716                         }
717                 }
718                 else
719                 {
720                         Con_Printf("Server unable to parse address %s\n", addressstring);
721                         // if it cant parse one address, it wont be able to parse another for sure
722                         break;
723                 }
724         }
725 }
726
727 void NetConn_OpenServerPorts(int opennetports)
728 {
729         int port;
730         NetConn_CloseServerPorts();
731         NetConn_UpdateSockets();
732         port = bound(0, sv_netport.integer, 65535);
733         if (port == 0)
734                 port = 26000;
735         Con_Printf("Server using port %i\n", port);
736         if (sv_netport.integer != port)
737                 Cvar_SetValueQuick(&sv_netport, port);
738         if (cls.state != ca_dedicated)
739                 NetConn_OpenServerPort("local:1", 0);
740         if (opennetports)
741         {
742                 NetConn_OpenServerPort(net_address.string, port);
743                 //NetConn_OpenServerPort(net_address_ipv6.string, port);
744         }
745         if (sv_numsockets == 0)
746                 Host_Error("NetConn_OpenServerPorts: unable to open any ports!");
747 }
748
749 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
750 {
751         int i, a = LHNETADDRESS_GetAddressType(address);
752         for (i = 0;i < cl_numsockets;i++)
753                 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
754                         return cl_sockets[i];
755         return NULL;
756 }
757
758 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
759 {
760         int i, a = LHNETADDRESS_GetAddressType(address);
761         for (i = 0;i < sv_numsockets;i++)
762                 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
763                         return sv_sockets[i];
764         return NULL;
765 }
766
767 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
768 {
769         netconn_t *conn;
770         conn = (netconn_t *)Mem_Alloc(netconn_mempool, sizeof(*conn));
771         conn->mysocket = mysocket;
772         conn->peeraddress = *peeraddress;
773         conn->lastMessageTime = realtime;
774         conn->message.data = conn->messagedata;
775         conn->message.maxsize = sizeof(conn->messagedata);
776         conn->message.cursize = 0;
777         // LordHavoc: (inspired by ProQuake) use a short connect timeout to
778         // reduce effectiveness of connection request floods
779         conn->timeout = realtime + net_connecttimeout.value;
780         LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
781         conn->next = netconn_list;
782         netconn_list = conn;
783         return conn;
784 }
785
786 void NetConn_Close(netconn_t *conn)
787 {
788         netconn_t *c;
789         // remove connection from list
790         if (conn == netconn_list)
791                 netconn_list = conn->next;
792         else
793         {
794                 for (c = netconn_list;c;c = c->next)
795                 {
796                         if (c->next == conn)
797                         {
798                                 c->next = conn->next;
799                                 break;
800                         }
801                 }
802                 // not found in list, we'll avoid crashing here...
803                 if (!c)
804                         return;
805         }
806         // free connection
807         Mem_Free(conn);
808 }
809
810 static int clientport = -1;
811 static int clientport2 = -1;
812 static int hostport = -1;
813 void NetConn_UpdateSockets(void)
814 {
815         if (cls.state != ca_dedicated)
816         {
817                 if (clientport2 != cl_netport.integer)
818                 {
819                         clientport2 = cl_netport.integer;
820                         if (cls.state == ca_connected)
821                                 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
822                 }
823                 if (cls.state == ca_disconnected && clientport != clientport2)
824                 {
825                         clientport = clientport2;
826                         NetConn_CloseClientPorts();
827                 }
828                 if (cl_numsockets == 0)
829                         NetConn_OpenClientPorts();
830         }
831
832         if (hostport != sv_netport.integer)
833         {
834                 hostport = sv_netport.integer;
835                 if (sv.active)
836                         Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
837         }
838 }
839
840 static int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int length, protocolversion_t protocol)
841 {
842         if (length < 8)
843                 return 0;
844
845         if (protocol == PROTOCOL_QUAKEWORLD)
846         {
847                 int sequence, sequence_ack;
848                 int reliable_ack, reliable_message;
849                 int count;
850                 int qport;
851
852                 sequence = LittleLong(*((int *)(data + 0)));
853                 sequence_ack = LittleLong(*((int *)(data + 4)));
854                 data += 8;
855                 length -= 8;
856
857                 if (conn != cls.netcon)
858                 {
859                         // server only
860                         if (length < 2)
861                                 return 0;
862                         // 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?)
863                         qport = LittleShort(*((int *)(data + 8)));
864                         data += 2;
865                         length -= 2;
866                 }
867
868                 packetsReceived++;
869                 reliable_message = (sequence >> 31) & 1;
870                 reliable_ack = (sequence_ack >> 31) & 1;
871                 sequence &= ~(1<<31);
872                 sequence_ack &= ~(1<<31);
873                 if (sequence <= conn->qw.incoming_sequence)
874                 {
875                         Con_DPrint("Got a stale datagram\n");
876                         return 0;
877                 }
878                 count = sequence - (conn->qw.incoming_sequence + 1);
879                 if (count > 0)
880                 {
881                         droppedDatagrams += count;
882                         Con_DPrintf("Dropped %u datagram(s)\n", count);
883                 }
884                 if (reliable_ack == conn->qw.reliable_sequence)
885                 {
886                         // received, now we will be able to send another reliable message
887                         conn->sendMessageLength = 0;
888                         reliableMessagesReceived++;
889                 }
890                 conn->qw.incoming_sequence = sequence;
891                 conn->qw.incoming_acknowledged = sequence_ack;
892                 conn->qw.incoming_reliable_acknowledged = reliable_ack;
893                 if (reliable_message)
894                         conn->qw.incoming_reliable_sequence ^= 1;
895                 conn->lastMessageTime = realtime;
896                 conn->timeout = realtime + net_messagetimeout.value;
897                 unreliableMessagesReceived++;
898                 SZ_Clear(&net_message);
899                 SZ_Write(&net_message, data, length);
900                 MSG_BeginReading();
901                 return 2;
902         }
903         else
904         {
905                 unsigned int count;
906                 unsigned int flags;
907                 unsigned int sequence;
908                 int qlength;
909
910                 qlength = (unsigned int)BigLong(((int *)data)[0]);
911                 flags = qlength & ~NETFLAG_LENGTH_MASK;
912                 qlength &= NETFLAG_LENGTH_MASK;
913                 // control packets were already handled
914                 if (!(flags & NETFLAG_CTL) && qlength == length)
915                 {
916                         sequence = BigLong(((int *)data)[1]);
917                         packetsReceived++;
918                         data += 8;
919                         length -= 8;
920                         if (flags & NETFLAG_UNRELIABLE)
921                         {
922                                 if (sequence >= conn->nq.unreliableReceiveSequence)
923                                 {
924                                         if (sequence > conn->nq.unreliableReceiveSequence)
925                                         {
926                                                 count = sequence - conn->nq.unreliableReceiveSequence;
927                                                 droppedDatagrams += count;
928                                                 Con_DPrintf("Dropped %u datagram(s)\n", count);
929                                         }
930                                         conn->nq.unreliableReceiveSequence = sequence + 1;
931                                         conn->lastMessageTime = realtime;
932                                         conn->timeout = realtime + net_messagetimeout.value;
933                                         unreliableMessagesReceived++;
934                                         if (length > 0)
935                                         {
936                                                 SZ_Clear(&net_message);
937                                                 SZ_Write(&net_message, data, length);
938                                                 MSG_BeginReading();
939                                                 return 2;
940                                         }
941                                 }
942                                 else
943                                         Con_DPrint("Got a stale datagram\n");
944                                 return 1;
945                         }
946                         else if (flags & NETFLAG_ACK)
947                         {
948                                 if (sequence == (conn->nq.sendSequence - 1))
949                                 {
950                                         if (sequence == conn->nq.ackSequence)
951                                         {
952                                                 conn->nq.ackSequence++;
953                                                 if (conn->nq.ackSequence != conn->nq.sendSequence)
954                                                         Con_DPrint("ack sequencing error\n");
955                                                 conn->lastMessageTime = realtime;
956                                                 conn->timeout = realtime + net_messagetimeout.value;
957                                                 if (conn->sendMessageLength > MAX_PACKETFRAGMENT)
958                                                 {
959                                                         unsigned int packetLen;
960                                                         unsigned int dataLen;
961                                                         unsigned int eom;
962                                                         unsigned int *header;
963
964                                                         conn->sendMessageLength -= MAX_PACKETFRAGMENT;
965                                                         memcpy(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
966
967                                                         if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
968                                                         {
969                                                                 dataLen = conn->sendMessageLength;
970                                                                 eom = NETFLAG_EOM;
971                                                         }
972                                                         else
973                                                         {
974                                                                 dataLen = MAX_PACKETFRAGMENT;
975                                                                 eom = 0;
976                                                         }
977
978                                                         packetLen = NET_HEADERSIZE + dataLen;
979
980                                                         header = (unsigned int *)sendbuffer;
981                                                         header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
982                                                         header[1] = BigLong(conn->nq.sendSequence);
983                                                         memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
984
985                                                         conn->nq.sendSequence++;
986
987                                                         if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
988                                                         {
989                                                                 conn->lastSendTime = realtime;
990                                                                 packetsSent++;
991                                                         }
992                                                 }
993                                                 else
994                                                         conn->sendMessageLength = 0;
995                                         }
996                                         else
997                                                 Con_DPrint("Duplicate ACK received\n");
998                                 }
999                                 else
1000                                         Con_DPrint("Stale ACK received\n");
1001                                 return 1;
1002                         }
1003                         else if (flags & NETFLAG_DATA)
1004                         {
1005                                 unsigned int temppacket[2];
1006                                 temppacket[0] = BigLong(8 | NETFLAG_ACK);
1007                                 temppacket[1] = BigLong(sequence);
1008                                 NetConn_Write(conn->mysocket, (unsigned char *)temppacket, 8, &conn->peeraddress);
1009                                 if (sequence == conn->nq.receiveSequence)
1010                                 {
1011                                         conn->lastMessageTime = realtime;
1012                                         conn->timeout = realtime + net_messagetimeout.value;
1013                                         conn->nq.receiveSequence++;
1014                                         if( conn->receiveMessageLength + length <= (int)sizeof( conn->receiveMessage ) ) {
1015                                                 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
1016                                                 conn->receiveMessageLength += length;
1017                                         } else {
1018                                                 Con_Printf( "Reliable message (seq: %i) too big for message buffer!\n"
1019                                                                         "Dropping the message!\n", sequence );
1020                                                 conn->receiveMessageLength = 0;
1021                                                 return 1;
1022                                         }
1023                                         if (flags & NETFLAG_EOM)
1024                                         {
1025                                                 reliableMessagesReceived++;
1026                                                 length = conn->receiveMessageLength;
1027                                                 conn->receiveMessageLength = 0;
1028                                                 if (length > 0)
1029                                                 {
1030                                                         SZ_Clear(&net_message);
1031                                                         SZ_Write(&net_message, conn->receiveMessage, length);
1032                                                         MSG_BeginReading();
1033                                                         return 2;
1034                                                 }
1035                                         }
1036                                 }
1037                                 else
1038                                         receivedDuplicateCount++;
1039                                 return 1;
1040                         }
1041                 }
1042         }
1043         return 0;
1044 }
1045
1046 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, protocolversion_t initialprotocol)
1047 {
1048         cls.connect_trying = false;
1049         M_Update_Return_Reason("");
1050         // the connection request succeeded, stop current connection and set up a new connection
1051         CL_Disconnect();
1052         // if we're connecting to a remote server, shut down any local server
1053         if (LHNETADDRESS_GetAddressType(peeraddress) != LHNETADDRESSTYPE_LOOP && sv.active)
1054                 Host_ShutdownServer ();
1055         // allocate a net connection to keep track of things
1056         cls.netcon = NetConn_Open(mysocket, peeraddress);
1057         Con_Printf("Connection accepted to %s\n", cls.netcon->address);
1058         key_dest = key_game;
1059         m_state = m_none;
1060         cls.demonum = -1;                       // not in the demo loop now
1061         cls.state = ca_connected;
1062         cls.signon = 0;                         // need all the signon messages before playing
1063         cls.protocol = initialprotocol;
1064         if (cls.protocol == PROTOCOL_QUAKEWORLD)
1065                 Cmd_ForwardStringToServer("new");
1066 }
1067
1068 int NetConn_IsLocalGame(void)
1069 {
1070         if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
1071                 return true;
1072         return false;
1073 }
1074
1075 static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1076 {
1077         qboolean fromserver;
1078         int ret, c, control;
1079         const char *s;
1080         char *string, addressstring2[128], cname[128], ipstring[32];
1081         char stringbuf[16384];
1082
1083         // quakeworld ingame packet
1084         fromserver = cls.netcon && mysocket == cls.netcon->mysocket && !LHNETADDRESS_Compare(&cls.netcon->peeraddress, peeraddress);
1085
1086         if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1087         {
1088                 // received a command string - strip off the packaging and put it
1089                 // into our string buffer with NULL termination
1090                 data += 4;
1091                 length -= 4;
1092                 length = min(length, (int)sizeof(stringbuf) - 1);
1093                 memcpy(stringbuf, data, length);
1094                 stringbuf[length] = 0;
1095                 string = stringbuf;
1096
1097                 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1098
1099                 if (developer_networking.integer)
1100                 {
1101                         Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
1102                         Com_HexDumpToConsole(data, length);
1103                 }
1104
1105                 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
1106                 {
1107                         // darkplaces or quake3
1108                         char protocolnames[1400];
1109                         Protocol_Names(protocolnames, sizeof(protocolnames));
1110                         Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
1111                         M_Update_Return_Reason("Got challenge response");
1112                         NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\protocols\\%s\\challenge\\%s", protocolnames, string + 10), peeraddress);
1113                         return true;
1114                 }
1115                 if (length > 1 && string[0] == 'c' && (string[1] == '-' || (string[1] >= '0' && string[1] <= '9')))
1116                 {
1117                         // quakeworld
1118                         LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1119                         Con_Printf("\"%s\" received, sending QuakeWorld connect request back to %s\n", string, addressstring2);
1120                         M_Update_Return_Reason("Got QuakeWorld challenge response");
1121                         cls.qw_qport = qport.integer;
1122                         NetConn_WriteString(mysocket, va("\377\377\377\377connect 28 %i %i \"%s\"\n", cls.qw_qport, atoi(string + 1), cls.userinfo), peeraddress);
1123                 }
1124                 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
1125                 {
1126                         // darkplaces or quake3
1127                         M_Update_Return_Reason("Accepted");
1128                         NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_DARKPLACES3);
1129                         return true;
1130                 }
1131                 if (length > 1 && string[0] == 'j' && cls.connect_trying)
1132                 {
1133                         // quakeworld
1134                         M_Update_Return_Reason("QuakeWorld Accepted");
1135                         NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_QUAKEWORLD);
1136                         return true;
1137                 }
1138                 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
1139                 {
1140                         char rejectreason[32];
1141                         cls.connect_trying = false;
1142                         string += 7;
1143                         length = max(length - 7, (int)sizeof(rejectreason) - 1);
1144                         memcpy(rejectreason, string, length);
1145                         rejectreason[length] = 0;
1146                         M_Update_Return_Reason(rejectreason);
1147                         return true;
1148                 }
1149                 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
1150                 {
1151                         serverlist_info_t *info;
1152                         int n;
1153                         double pingtime;
1154
1155                         string += 13;
1156                         // serverlist only uses text addresses
1157                         LHNETADDRESS_ToString(peeraddress, cname, sizeof(cname), true);
1158                         // search the cache for this server and update it
1159                         for( n = 0; n < serverlist_cachecount; n++ )
1160                                 if( !strcmp( cname, serverlist_cache[n].info.cname ) )
1161                                         break;
1162                         if( n == serverlist_cachecount ) {
1163                                 // LAN search doesnt require an answer from the master server so we wont
1164                                 // know the ping nor will it be initialized already...
1165
1166                                 // find a slot
1167                                 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1168                                         return true;
1169
1170                                 memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
1171                                 // store the data the engine cares about (address and ping)
1172                                 strlcpy (serverlist_cache[serverlist_cachecount].info.cname, cname, sizeof (serverlist_cache[serverlist_cachecount].info.cname));
1173                                 serverlist_cache[serverlist_cachecount].info.ping = 100000;
1174                                 //serverlist_cache[serverlist_cachecount].querytime = realtime;
1175                                 serverlist_cache[serverlist_cachecount].querytime = Sys_DoubleTime();
1176                                 // if not in the slist menu we should print the server to console
1177                                 if (serverlist_consoleoutput) {
1178                                         Con_Printf("querying %s\n", ipstring);
1179                                 }
1180
1181                                 ++serverlist_cachecount;
1182                         }
1183
1184                         info = &serverlist_cache[n].info;
1185                         if ((s = SearchInfostring(string, "gamename"     )) != NULL) strlcpy(info->game, s, sizeof (info->game));else info->game[0] = 0;
1186                         if ((s = SearchInfostring(string, "modname"      )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0]  = 0;
1187                         if ((s = SearchInfostring(string, "mapname"      )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0]  = 0;
1188                         if ((s = SearchInfostring(string, "hostname"     )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
1189                         if ((s = SearchInfostring(string, "protocol"     )) != NULL) info->protocol = atoi(s);else info->protocol = -1;
1190                         if ((s = SearchInfostring(string, "clients"      )) != NULL) info->numplayers = atoi(s);else info->numplayers = 0;
1191                         if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);else info->maxplayers  = 0;
1192                         if ((s = SearchInfostring(string, "gameversion"  )) != NULL) info->gameversion = atoi(s);else info->gameversion = 0;
1193
1194                         if (info->ping == 100000)
1195                                         serverreplycount++;
1196
1197                         pingtime = (int)((Sys_DoubleTime() - serverlist_cache[n].querytime) * 1000.0 + 0.5);
1198                         pingtime = bound(0, pingtime, 9999);
1199                         // update the ping
1200                         info->ping = pingtime;
1201
1202                         // legacy/old stuff move it to the menu ASAP
1203
1204                         // build description strings for the things users care about
1205                         dpsnprintf(serverlist_cache[n].line1, sizeof(serverlist_cache[n].line1), "^%c%5d^7 ^%c%3u^7/%3u %-65.65s", pingtime >= 300 ? '1' : (pingtime >= 200 ? '3' : '7'), (int)pingtime, ((info->numplayers > 0 && info->numplayers < info->maxplayers) ? (info->numplayers >= 4 ? '7' : '3') : '1'), info->numplayers, info->maxplayers, info->name);
1206                         dpsnprintf(serverlist_cache[n].line2, sizeof(serverlist_cache[n].line2), "^5%-21.21s %-19.19s ^%c%-17.17s^5 %-20.20s", info->cname, info->game, (info->gameversion != gameversion.integer) ? '1' : '5', info->mod, info->map);
1207                         if( serverlist_cache[n].query == SQS_QUERIED ) {
1208                                 ServerList_ViewList_Remove( &serverlist_cache[n] );
1209                         }
1210                         // if not in the slist menu we should print the server to console (if wanted)
1211                         else if( serverlist_consoleoutput )
1212                                 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1213                         // and finally, update the view set
1214                         ServerList_ViewList_Insert( &serverlist_cache[n] );
1215                         serverlist_cache[n].query = SQS_QUERIED;
1216
1217                         return true;
1218                 }
1219                 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1220                 {
1221                         // Extract the IP addresses
1222                         data += 18;
1223                         length -= 18;
1224                         masterreplycount++;
1225                         if (serverlist_consoleoutput)
1226                                 Con_Print("received DarkPlaces server list...\n");
1227                         while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
1228                         {
1229                                 int n;
1230
1231                                 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], data[5] * 256 + data[6]);
1232                                 if (serverlist_consoleoutput && developer_networking.integer)
1233                                         Con_Printf("Requesting info from DarkPlaces server %s\n", ipstring);
1234                                 // ignore the rest of the message if the serverlist is full
1235                                 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1236                                         break;
1237                                 // also ignore it if we have already queried it (other master server response)
1238                                 for( n = 0 ; n < serverlist_cachecount ; n++ )
1239                                         if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1240                                                 break;
1241                                 if( n >= serverlist_cachecount )
1242                                 {
1243                                         serverquerycount++;
1244
1245                                         memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
1246                                         serverlist_cache[serverlist_cachecount].protocol = PROTOCOL_DARKPLACES7;
1247                                         // store the data the engine cares about (address and ping)
1248                                         strlcpy (serverlist_cache[serverlist_cachecount].info.cname, ipstring, sizeof (serverlist_cache[serverlist_cachecount].info.cname));
1249                                         serverlist_cache[serverlist_cachecount].info.ping = 100000;
1250                                         serverlist_cache[serverlist_cachecount].query = SQS_QUERYING;
1251
1252                                         ++serverlist_cachecount;
1253                                 }
1254
1255                                 // move on to next address in packet
1256                                 data += 7;
1257                                 length -= 7;
1258                         }
1259                         // begin or resume serverlist queries
1260                         serverlist_querysleep = false;
1261                         serverlist_querywaittime = realtime + 3;
1262                         return true;
1263                 }
1264                 if (!memcmp(string, "d\n", 2) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1265                 {
1266                         // Extract the IP addresses
1267                         data += 2;
1268                         length -= 2;
1269                         masterreplycount++;
1270                         if (serverlist_consoleoutput)
1271                                 Con_Print("received QuakeWorld server list...\n");
1272                         while (length >= 6 && (data[0] != 0xFF || data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF) && data[4] * 256 + data[5] != 0)
1273                         {
1274                                 int n;
1275
1276                                 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[0], data[1], data[2], data[3], data[4] * 256 + data[5]);
1277                                 if (serverlist_consoleoutput && developer_networking.integer)
1278                                         Con_Printf("Requesting info from QuakeWorld server %s\n", ipstring);
1279                                 // ignore the rest of the message if the serverlist is full
1280                                 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1281                                         break;
1282                                 // also ignore it if we have already queried it (other master server response)
1283                                 for( n = 0 ; n < serverlist_cachecount ; n++ )
1284                                         if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1285                                                 break;
1286                                 if( n >= serverlist_cachecount )
1287                                 {
1288                                         serverquerycount++;
1289
1290                                         memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
1291                                         serverlist_cache[serverlist_cachecount].protocol = PROTOCOL_QUAKEWORLD;
1292                                         // store the data the engine cares about (address and ping)
1293                                         strlcpy (serverlist_cache[serverlist_cachecount].info.cname, ipstring, sizeof (serverlist_cache[serverlist_cachecount].info.cname));
1294                                         serverlist_cache[serverlist_cachecount].info.ping = 100000;
1295                                         serverlist_cache[serverlist_cachecount].query = SQS_QUERYING;
1296
1297                                         ++serverlist_cachecount;
1298                                 }
1299
1300                                 // move on to next address in packet
1301                                 data += 6;
1302                                 length -= 6;
1303                         }
1304                         // begin or resume serverlist queries
1305                         serverlist_querysleep = false;
1306                         serverlist_querywaittime = realtime + 3;
1307                         return true;
1308                 }
1309                 /*
1310                 if (!strncmp(string, "ping", 4))
1311                 {
1312                         if (developer.integer >= 10)
1313                                 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1314                         NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1315                         return true;
1316                 }
1317                 if (!strncmp(string, "ack", 3))
1318                         return true;
1319                 */
1320                 // QuakeWorld compatibility
1321                 if (length >= 1 && string[0] == 'j' && cls.connect_trying)
1322                 {
1323                         // accept message
1324                         M_Update_Return_Reason("Accepted");
1325                         NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_QUAKEWORLD);
1326                         return true;
1327                 }
1328                 if (length > 1 && string[0] == 'c' && string[1] >= '0' && string[1] <= '9' && cls.connect_trying)
1329                 {
1330                         // challenge message
1331                         LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1332                         Con_Printf("challenge %s received, sending connect request back to %s\n", string + 1, addressstring2);
1333                         M_Update_Return_Reason("Got challenge response");
1334                         cls.qw_qport = qport.integer;
1335                         InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1336                         InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "name", cl_name.string);
1337                         InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "topcolor", va("%i", (cl_color.integer >> 4) & 15));
1338                         InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "bottomcolor", va("%i", (cl_color.integer) & 15));
1339                         InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "rate", va("%i", cl_rate.integer));
1340                         InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "msg", "1");
1341                         InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ver", engineversion);
1342                         NetConn_WriteString(mysocket, va("\377\377\377\377connect %i %i %i \"%s\"\n", 28, cls.qw_qport, atoi(string + 1), cls.userinfo), peeraddress);
1343                         return true;
1344                 }
1345                 if (length > 2 && !memcmp(string, "n\\", 2))
1346                 {
1347                         serverlist_info_t *info;
1348                         int n;
1349                         double pingtime;
1350
1351                         // qw server status
1352                         if (serverlist_consoleoutput && developer_networking.integer >= 2)
1353                                 Con_Printf("QW server status from server at %s:\n%s\n", addressstring2, string + 1);
1354
1355                         string += 1;
1356                         // serverlist only uses text addresses
1357                         LHNETADDRESS_ToString(peeraddress, cname, sizeof(cname), true);
1358                         // search the cache for this server and update it
1359                         for( n = 0; n < serverlist_cachecount; n++ )
1360                                 if( !strcmp( cname, serverlist_cache[n].info.cname ) )
1361                                         break;
1362                         if( n == serverlist_cachecount ) {
1363                                 // LAN search doesnt require an answer from the master server so we wont
1364                                 // know the ping nor will it be initialized already...
1365
1366                                 // find a slot
1367                                 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1368                                         return true;
1369
1370                                 memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
1371                                 // store the data the engine cares about (address and ping)
1372                                 strlcpy (serverlist_cache[serverlist_cachecount].info.cname, cname, sizeof (serverlist_cache[serverlist_cachecount].info.cname));
1373                                 serverlist_cache[serverlist_cachecount].info.ping = 100000;
1374                                 //serverlist_cache[serverlist_cachecount].querytime = realtime;
1375                                 serverlist_cache[serverlist_cachecount].querytime = Sys_DoubleTime();
1376                                 // if not in the slist menu we should print the server to console
1377                                 if (serverlist_consoleoutput) {
1378                                         Con_Printf("querying %s\n", ipstring);
1379                                 }
1380
1381                                 ++serverlist_cachecount;
1382                         }
1383
1384                         info = &serverlist_cache[n].info;
1385                         strlcpy(info->game, "QuakeWorld", sizeof(info->game));;
1386                         if ((s = SearchInfostring(string, "*gamedir"     )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0]  = 0;
1387                         if ((s = SearchInfostring(string, "map"          )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0]  = 0;
1388                         if ((s = SearchInfostring(string, "hostname"     )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
1389                         info->protocol = 0;
1390                         info->numplayers = 0; // updated below
1391                         if ((s = SearchInfostring(string, "maxclients"   )) != NULL) info->maxplayers = atoi(s);else info->maxplayers  = 0;
1392                         if ((s = SearchInfostring(string, "gameversion"  )) != NULL) info->gameversion = atoi(s);else info->gameversion = 0;
1393
1394                         // count active players on server
1395                         // (we could gather more info, but we're just after the number)
1396                         s = strchr(string, '\n');
1397                         if (s)
1398                         {
1399                                 s++;
1400                                 while (s < string + length)
1401                                 {
1402                                         for (;s < string + length && *s != '\n';s++)
1403                                                 ;
1404                                         if (s >= string + length)
1405                                                 break;
1406                                         info->numplayers++;
1407                                         s++;
1408                                 }
1409                         }
1410
1411                         if (info->ping == 100000)
1412                                         serverreplycount++;
1413
1414                         pingtime = (int)((Sys_DoubleTime() - serverlist_cache[n].querytime) * 1000.0 + 0.5);
1415                         pingtime = bound(0, pingtime, 9999);
1416                         // update the ping
1417                         info->ping = pingtime;
1418
1419                         // legacy/old stuff move it to the menu ASAP
1420
1421                         // build description strings for the things users care about
1422                         dpsnprintf(serverlist_cache[n].line1, sizeof(serverlist_cache[n].line1), "^%c%5d^7 ^%c%3u^7/%3u %-65.65s", pingtime >= 300 ? '1' : (pingtime >= 200 ? '3' : '7'), (int)pingtime, ((info->numplayers > 0 && info->numplayers < info->maxplayers) ? (info->numplayers >= 4 ? '7' : '3') : '1'), info->numplayers, info->maxplayers, info->name);
1423                         dpsnprintf(serverlist_cache[n].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);
1424                         if( serverlist_cache[n].query == SQS_QUERIED ) {
1425                                 ServerList_ViewList_Remove( &serverlist_cache[n] );
1426                         }
1427                         // if not in the slist menu we should print the server to console (if wanted)
1428                         else if( serverlist_consoleoutput )
1429                                 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1430                         // and finally, update the view set
1431                         ServerList_ViewList_Insert( &serverlist_cache[n] );
1432                         serverlist_cache[n].query = SQS_QUERIED;
1433
1434                         return true;
1435                 }
1436                 if (string[0] == 'n')
1437                 {
1438                         // qw print command
1439                         Con_Printf("QW print command from server at %s:\n%s\n", addressstring2, string + 1);
1440                 }
1441                 // we may not have liked the packet, but it was a command packet, so
1442                 // we're done processing this packet now
1443                 return true;
1444         }
1445         // quakeworld ingame packet
1446         if (fromserver && cls.protocol == PROTOCOL_QUAKEWORLD && length >= 8 && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol)) == 2)
1447         {
1448                 ret = 0;
1449                 CL_ParseServerMessage();
1450                 return ret;
1451         }
1452         // netquake control packets, supported for compatibility only
1453         if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1454         {
1455                 c = data[4];
1456                 data += 5;
1457                 length -= 5;
1458                 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1459                 switch (c)
1460                 {
1461                 case CCREP_ACCEPT:
1462                         if (developer.integer >= 10)
1463                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1464                         if (cls.connect_trying)
1465                         {
1466                                 lhnetaddress_t clientportaddress;
1467                                 clientportaddress = *peeraddress;
1468                                 if (length >= 4)
1469                                 {
1470                                         unsigned int port = (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
1471                                         data += 4;
1472                                         length -= 4;
1473                                         LHNETADDRESS_SetPort(&clientportaddress, port);
1474                                 }
1475                                 M_Update_Return_Reason("Accepted");
1476                                 NetConn_ConnectionEstablished(mysocket, &clientportaddress, PROTOCOL_QUAKE);
1477                         }
1478                         break;
1479                 case CCREP_REJECT:
1480                         if (developer.integer >= 10)
1481                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1482                         cls.connect_trying = false;
1483                         M_Update_Return_Reason((char *)data);
1484                         break;
1485 #if 0
1486                 case CCREP_SERVER_INFO:
1487                         if (developer.integer >= 10)
1488                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1489                         if (cls.state != ca_dedicated)
1490                         {
1491                                 // LordHavoc: because the UDP driver reports 0.0.0.0:26000 as the address
1492                                 // string we just ignore it and keep the real address
1493                                 MSG_ReadString();
1494                                 // serverlist only uses text addresses
1495                                 cname = UDP_AddrToString(readaddr);
1496                                 // search the cache for this server
1497                                 for (n = 0; n < hostCacheCount; n++)
1498                                         if (!strcmp(cname, serverlist[n].cname))
1499                                                 break;
1500                                 // add it
1501                                 if (n == hostCacheCount && hostCacheCount < SERVERLISTSIZE)
1502                                 {
1503                                         hostCacheCount++;
1504                                         memset(&serverlist[n], 0, sizeof(serverlist[n]));
1505                                         strlcpy (serverlist[n].name, MSG_ReadString(), sizeof (serverlist[n].name));
1506                                         strlcpy (serverlist[n].map, MSG_ReadString(), sizeof (serverlist[n].map));
1507                                         serverlist[n].users = MSG_ReadByte();
1508                                         serverlist[n].maxusers = MSG_ReadByte();
1509                                         c = MSG_ReadByte();
1510                                         if (c != NET_PROTOCOL_VERSION)
1511                                         {
1512                                                 strlcpy (serverlist[n].cname, serverlist[n].name, sizeof (serverlist[n].cname));
1513                                                 strcpy(serverlist[n].name, "*");
1514                                                 strlcat (serverlist[n].name, serverlist[n].cname, sizeof(serverlist[n].name));
1515                                         }
1516                                         strlcpy (serverlist[n].cname, cname, sizeof (serverlist[n].cname));
1517                                 }
1518                         }
1519                         break;
1520                 case CCREP_PLAYER_INFO:
1521                         // we got a CCREP_PLAYER_INFO??
1522                         //if (developer.integer >= 10)
1523                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1524                         break;
1525                 case CCREP_RULE_INFO:
1526                         // we got a CCREP_RULE_INFO??
1527                         //if (developer.integer >= 10)
1528                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1529                         break;
1530 #endif
1531                 default:
1532                         break;
1533                 }
1534                 // we may not have liked the packet, but it was a valid control
1535                 // packet, so we're done processing this packet now
1536                 return true;
1537         }
1538         ret = 0;
1539         if (fromserver && length >= (int)NET_HEADERSIZE && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol)) == 2)
1540                 CL_ParseServerMessage();
1541         return ret;
1542 }
1543
1544 void NetConn_QueryQueueFrame(void)
1545 {
1546         int index;
1547         int queries;
1548         int maxqueries;
1549         double timeouttime;
1550         static double querycounter = 0;
1551
1552         if (serverlist_querysleep)
1553                 return;
1554
1555         // apply a cool down time after master server replies,
1556         // to avoid messing up the ping times on the servers
1557         if (serverlist_querywaittime > realtime)
1558                 return;
1559
1560         // each time querycounter reaches 1.0 issue a query
1561         querycounter += host_realframetime * net_slist_queriespersecond.value;
1562         maxqueries = (int)querycounter;
1563         maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer);
1564         querycounter -= maxqueries;
1565
1566         if( maxqueries == 0 ) {
1567                 return;
1568         }
1569
1570         // scan serverlist and issue queries as needed
1571     serverlist_querysleep = true;
1572
1573         timeouttime = realtime - net_slist_timeout.value;
1574         for( index = 0, queries = 0 ; index < serverlist_cachecount && queries < maxqueries ; index++ )
1575         {
1576                 serverlist_entry_t *entry = &serverlist_cache[ index ];
1577                 if( entry->query != SQS_QUERYING )
1578                 {
1579                         continue;
1580                 }
1581
1582         serverlist_querysleep = false;
1583                 if( entry->querycounter != 0 && entry->querytime > timeouttime )
1584                 {
1585                         continue;
1586                 }
1587
1588                 if( entry->querycounter != (unsigned) net_slist_maxtries.integer )
1589                 {
1590                         lhnetaddress_t address;
1591                         int socket;
1592
1593                         LHNETADDRESS_FromString(&address, entry->info.cname, 0);
1594                         if (entry->protocol == PROTOCOL_QUAKEWORLD)
1595                         {
1596                                 for (socket = 0; socket < cl_numsockets ; socket++)
1597                                         NetConn_WriteString(cl_sockets[socket], "\377\377\377\377status\n", &address);
1598                         }
1599                         else
1600                         {
1601                                 for (socket = 0; socket < cl_numsockets ; socket++)
1602                                         NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getinfo", &address);
1603                         }
1604
1605                         //entry->querytime = realtime;
1606                         entry->querytime = Sys_DoubleTime();
1607                         entry->querycounter++;
1608
1609                         // if not in the slist menu we should print the server to console
1610                         if (serverlist_consoleoutput)
1611                                 Con_Printf("querying %25s (%i. try)\n", entry->info.cname, entry->querycounter);
1612
1613                         queries++;
1614                 }
1615                 else
1616                 {
1617                         entry->query = SQS_TIMEDOUT;
1618                 }
1619         }
1620 }
1621
1622 void NetConn_ClientFrame(void)
1623 {
1624         int i, length;
1625         lhnetaddress_t peeraddress;
1626         NetConn_UpdateSockets();
1627         if (cls.connect_trying && cls.connect_nextsendtime < realtime)
1628         {
1629                 if (cls.connect_remainingtries == 0)
1630                         M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
1631                 cls.connect_nextsendtime = realtime + 1;
1632                 cls.connect_remainingtries--;
1633                 if (cls.connect_remainingtries <= -10)
1634                 {
1635                         cls.connect_trying = false;
1636                         M_Update_Return_Reason("Connect: Failed");
1637                         return;
1638                 }
1639                 // try challenge first (newer DP server or QW)
1640                 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
1641                 // then try netquake as a fallback (old server, or netquake)
1642                 SZ_Clear(&net_message);
1643                 // save space for the header, filled in later
1644                 MSG_WriteLong(&net_message, 0);
1645                 MSG_WriteByte(&net_message, CCREQ_CONNECT);
1646                 MSG_WriteString(&net_message, "QUAKE");
1647                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1648                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1649                 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
1650                 SZ_Clear(&net_message);
1651         }
1652         for (i = 0;i < cl_numsockets;i++)
1653                 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1654                         NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
1655         NetConn_QueryQueueFrame();
1656         if (cls.netcon && realtime > cls.netcon->timeout)
1657         {
1658                 Con_Print("Connection timed out\n");
1659                 CL_Disconnect();
1660                 Host_ShutdownServer ();
1661         }
1662 }
1663
1664 #define MAX_CHALLENGES 128
1665 struct challenge_s
1666 {
1667         lhnetaddress_t address;
1668         double time;
1669         char string[12];
1670 }
1671 challenge[MAX_CHALLENGES];
1672
1673 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
1674 {
1675         int i;
1676         char c;
1677         for (i = 0;i < bufferlength - 1;i++)
1678         {
1679                 do
1680                 {
1681                         c = rand () % (127 - 33) + 33;
1682                 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
1683                 buffer[i] = c;
1684         }
1685         buffer[i] = 0;
1686 }
1687
1688 static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg, size_t out_size, qboolean fullstatus)
1689 {
1690         unsigned int nb_clients = 0, i;
1691         int length;
1692
1693         // How many clients are there?
1694         for (i = 0;i < (unsigned int)svs.maxclients;i++)
1695                 if (svs.clients[i].active)
1696                         nb_clients++;
1697
1698         // TODO: we should add more information for the full status string
1699         length = dpsnprintf(out_msg, out_size,
1700                                                 "\377\377\377\377%s\x0A"
1701                                                 "\\gamename\\%s\\modname\\%s\\gameversion\\%d\\sv_maxclients\\%d"
1702                                                 "\\clients\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d"
1703                                                 "%s%s"
1704                                                 "%s",
1705                                                 fullstatus ? "statusResponse" : "infoResponse",
1706                                                 gamename, com_modname, gameversion.integer, svs.maxclients,
1707                                                 nb_clients, sv.name, hostname.string, NET_PROTOCOL_VERSION,
1708                                                 challenge ? "\\challenge\\" : "", challenge ? challenge : "",
1709                                                 fullstatus ? "\n" : "");
1710
1711         // Make sure it fits in the buffer
1712         if (length < 0)
1713                 return false;
1714
1715         if (fullstatus)
1716         {
1717                 char *ptr;
1718                 int left;
1719
1720                 ptr = out_msg + length;
1721                 left = (int)out_size - length;
1722
1723                 for (i = 0;i < (unsigned int)svs.maxclients;i++)
1724                 {
1725                         client_t *cl = &svs.clients[i];
1726                         if (cl->active)
1727                         {
1728                                 int nameind, cleanind;
1729                                 char curchar;
1730                                 char cleanname [sizeof(cl->name)];
1731
1732                                 // Remove all characters '"' and '\' in the player name
1733                                 nameind = 0;
1734                                 cleanind = 0;
1735                                 do
1736                                 {
1737                                         curchar = cl->name[nameind++];
1738                                         if (curchar != '"' && curchar != '\\')
1739                                         {
1740                                                 cleanname[cleanind++] = curchar;
1741                                                 if (cleanind == sizeof(cleanname) - 1)
1742                                                         break;
1743                                         }
1744                                 } while (curchar != '\0');
1745
1746                                 length = dpsnprintf(ptr, left, "%d %d \"%s\"\n",
1747                                                                         cl->frags,
1748                                                                         (int)(cl->ping * 1000.0f),
1749                                                                         cleanname);
1750                                 if(length < 0)
1751                                         return false;
1752                                 left -= length;
1753                                 ptr += length;
1754                         }
1755                 }
1756         }
1757
1758         return true;
1759 }
1760
1761 extern void SV_SendServerinfo (client_t *client);
1762 static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1763 {
1764         int i, ret, clientnum, best;
1765         double besttime;
1766         client_t *client;
1767         netconn_t *conn;
1768         char *s, *string, response[1400], addressstring2[128], stringbuf[16384];
1769
1770         // see if we can identify the sender as a local player
1771         // (this is necessary for rcon to send a reliable reply if the client is
1772         //  actually on the server, not sending remotely)
1773         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1774                 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1775                         break;
1776         if (i == svs.maxclients)
1777                 host_client = NULL;
1778
1779         if (sv.active)
1780         {
1781                 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1782                 {
1783                         // received a command string - strip off the packaging and put it
1784                         // into our string buffer with NULL termination
1785                         data += 4;
1786                         length -= 4;
1787                         length = min(length, (int)sizeof(stringbuf) - 1);
1788                         memcpy(stringbuf, data, length);
1789                         stringbuf[length] = 0;
1790                         string = stringbuf;
1791
1792                         if (developer.integer >= 10)
1793                         {
1794                                 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1795                                 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
1796                                 Com_HexDumpToConsole(data, length);
1797                         }
1798
1799                         if (length >= 12 && !memcmp(string, "getchallenge", 12))
1800                         {
1801                                 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
1802                                 {
1803                                         if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
1804                                                 break;
1805                                         if (besttime > challenge[i].time)
1806                                                 besttime = challenge[best = i].time;
1807                                 }
1808                                 // if we did not find an exact match, choose the oldest and
1809                                 // update address and string
1810                                 if (i == MAX_CHALLENGES)
1811                                 {
1812                                         i = best;
1813                                         challenge[i].address = *peeraddress;
1814                                         NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
1815                                 }
1816                                 challenge[i].time = realtime;
1817                                 // send the challenge
1818                                 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
1819                                 return true;
1820                         }
1821                         if (length > 8 && !memcmp(string, "connect\\", 8))
1822                         {
1823                                 string += 7;
1824                                 length -= 7;
1825                                 if ((s = SearchInfostring(string, "challenge")))
1826                                 {
1827                                         // validate the challenge
1828                                         for (i = 0;i < MAX_CHALLENGES;i++)
1829                                                 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1830                                                         break;
1831                                         if (i < MAX_CHALLENGES)
1832                                         {
1833                                                 // check engine protocol
1834                                                 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
1835                                                 {
1836                                                         if (developer.integer >= 10)
1837                                                                 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
1838                                                         NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
1839                                                 }
1840                                                 else
1841                                                 {
1842                                                         // see if this is a duplicate connection request
1843                                                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1844                                                                 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1845                                                                         break;
1846                                                         if (clientnum < svs.maxclients && realtime - client->connecttime < net_messagerejointimeout.value)
1847                                                         {
1848                                                                 // client is still trying to connect,
1849                                                                 // so we send a duplicate reply
1850                                                                 if (developer.integer >= 10)
1851                                                                         Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
1852                                                                 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1853                                                         }
1854 #if 0
1855                                                         else if (clientnum < svs.maxclients)
1856                                                         {
1857                                                                 if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1858                                                                 {
1859                                                                         // client crashed and is coming back, keep their stuff intact
1860                                                                         SV_SendServerinfo(client);
1861                                                                         //host_client = client;
1862                                                                         //SV_DropClient (true);
1863                                                                 }
1864                                                                 // else ignore them
1865                                                         }
1866 #endif
1867                                                         else
1868                                                         {
1869                                                                 // this is a new client, find a slot
1870                                                                 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1871                                                                         if (!client->active)
1872                                                                                 break;
1873                                                                 if (clientnum < svs.maxclients)
1874                                                                 {
1875                                                                         // prepare the client struct
1876                                                                         if ((conn = NetConn_Open(mysocket, peeraddress)))
1877                                                                         {
1878                                                                                 // allocated connection
1879                                                                                 LHNETADDRESS_ToString(peeraddress, conn->address, sizeof(conn->address), true);
1880                                                                                 if (developer.integer >= 10)
1881                                                                                         Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
1882                                                                                 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1883                                                                                 // now set up the client
1884                                                                                 SV_VM_Begin();
1885                                                                                 SV_ConnectClient(clientnum, conn);
1886                                                                                 SV_VM_End();
1887                                                                                 NetConn_Heartbeat(1);
1888                                                                         }
1889                                                                 }
1890                                                                 else
1891                                                                 {
1892                                                                         // server is full
1893                                                                         if (developer.integer >= 10)
1894                                                                                 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
1895                                                                         NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
1896                                                                 }
1897                                                         }
1898                                                 }
1899                                         }
1900                                 }
1901                                 return true;
1902                         }
1903                         if (length >= 7 && !memcmp(string, "getinfo", 7))
1904                         {
1905                                 const char *challenge = NULL;
1906
1907                                 // If there was a challenge in the getinfo message
1908                                 if (length > 8 && string[7] == ' ')
1909                                         challenge = string + 8;
1910
1911                                 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
1912                                 {
1913                                         if (developer.integer >= 10)
1914                                                 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
1915                                         NetConn_WriteString(mysocket, response, peeraddress);
1916                                 }
1917                                 return true;
1918                         }
1919                         if (length >= 9 && !memcmp(string, "getstatus", 9))
1920                         {
1921                                 const char *challenge = NULL;
1922
1923                                 // If there was a challenge in the getinfo message
1924                                 if (length > 10 && string[9] == ' ')
1925                                         challenge = string + 10;
1926
1927                                 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
1928                                 {
1929                                         if (developer.integer >= 10)
1930                                                 Con_Printf("Sending reply to client %s - %s\n", addressstring2, response);
1931                                         NetConn_WriteString(mysocket, response, peeraddress);
1932                                 }
1933                                 return true;
1934                         }
1935                         if (length >= 5 && !memcmp(string, "rcon ", 5))
1936                         {
1937                                 int i;
1938                                 char *s = string + 5;
1939                                 char password[64];
1940                                 for (i = 0;*s > ' ';s++)
1941                                         if (i < (int)sizeof(password) - 1)
1942                                                 password[i++] = *s;
1943                                 password[i] = 0;
1944                                 if (password[0] > ' ' && !strcmp(rcon_password.string, password))
1945                                 {
1946                                         // looks like a legitimate rcon command with the correct password
1947                                         Con_Printf("server received rcon command from %s:\n%s\n", host_client ? host_client->name : addressstring2, s);
1948                                         rcon_redirect = true;
1949                                         rcon_redirect_bufferpos = 0;
1950                                         Cmd_ExecuteString(s, src_command);
1951                                         rcon_redirect_buffer[rcon_redirect_bufferpos] = 0;
1952                                         rcon_redirect = false;
1953                                         // print resulting text to client
1954                                         // if client is playing, send a reliable reply instead of
1955                                         // a command packet
1956                                         if (host_client)
1957                                         {
1958                                                 // if the netconnection is loop, then this is the
1959                                                 // local player on a listen mode server, and it would
1960                                                 // result in duplicate printing to the console
1961                                                 // (not that the local player should be using rcon
1962                                                 //  when they have the console)
1963                                                 if (host_client->netconnection && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
1964                                                         SV_ClientPrintf("%s", rcon_redirect_buffer);
1965                                         }
1966                                         else
1967                                         {
1968                                                 // qw print command
1969                                                 dpsnprintf(response, sizeof(response), "\377\377\377\377n%s", rcon_redirect_buffer);
1970                                                 NetConn_WriteString(mysocket, response, peeraddress);
1971                                         }
1972                                 }
1973                                 return true;
1974                         }
1975                         /*
1976                         if (!strncmp(string, "ping", 4))
1977                         {
1978                                 if (developer.integer >= 10)
1979                                         Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1980                                 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1981                                 return true;
1982                         }
1983                         if (!strncmp(string, "ack", 3))
1984                                 return true;
1985                         */
1986                         // we may not have liked the packet, but it was a command packet, so
1987                         // we're done processing this packet now
1988                         return true;
1989                 }
1990                 // LordHavoc: disabled netquake control packet support in server
1991 #if 0
1992                 {
1993                         int c, control;
1994                         // netquake control packets, supported for compatibility only
1995                         if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1996                         {
1997                                 c = data[4];
1998                                 data += 5;
1999                                 length -= 5;
2000                                 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
2001                                 switch (c)
2002                                 {
2003                                 case CCREQ_CONNECT:
2004                                         if (developer.integer >= 10)
2005                                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
2006                                         if (length >= (int)strlen("QUAKE") + 1 + 1)
2007                                         {
2008                                                 if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION)
2009                                                 {
2010                                                         if (developer.integer >= 10)
2011                                                                 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
2012                                                         SZ_Clear(&net_message);
2013                                                         // save space for the header, filled in later
2014                                                         MSG_WriteLong(&net_message, 0);
2015                                                         MSG_WriteByte(&net_message, CCREP_REJECT);
2016                                                         MSG_WriteString(&net_message, "Incompatible version.\n");
2017                                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2018                                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2019                                                         SZ_Clear(&net_message);
2020                                                 }
2021                                                 else
2022                                                 {
2023                                                         // see if this is a duplicate connection request
2024                                                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2025                                                                 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2026                                                                         break;
2027                                                         if (clientnum < svs.maxclients)
2028                                                         {
2029                                                                 // duplicate connection request
2030                                                                 if (realtime - client->connecttime < 2.0)
2031                                                                 {
2032                                                                         // client is still trying to connect,
2033                                                                         // so we send a duplicate reply
2034                                                                         if (developer.integer >= 10)
2035                                                                                 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
2036                                                                         SZ_Clear(&net_message);
2037                                                                         // save space for the header, filled in later
2038                                                                         MSG_WriteLong(&net_message, 0);
2039                                                                         MSG_WriteByte(&net_message, CCREP_ACCEPT);
2040                                                                         MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
2041                                                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2042                                                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2043                                                                         SZ_Clear(&net_message);
2044                                                                 }
2045 #if 0
2046                                                                 else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
2047                                                                 {
2048                                                                         SV_SendServerinfo(client);
2049                                                                         // the old client hasn't sent us anything
2050                                                                         // in quite a while, so kick off and let
2051                                                                         // the retry take care of it...
2052                                                                         //host_client = client;
2053                                                                         //SV_DropClient (true);
2054                                                                 }
2055 #endif
2056                                                         }
2057                                                         else
2058                                                         {
2059                                                                 // this is a new client, find a slot
2060                                                                 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2061                                                                         if (!client->active)
2062                                                                                 break;
2063                                                                 if (clientnum < svs.maxclients && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
2064                                                                 {
2065                                                                         // connect to the client
2066                                                                         // everything is allocated, just fill in the details
2067                                                                         strlcpy (conn->address, addressstring2, sizeof (conn->address));
2068                                                                         if (developer.integer >= 10)
2069                                                                                 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
2070                                                                         // send back the info about the server connection
2071                                                                         SZ_Clear(&net_message);
2072                                                                         // save space for the header, filled in later
2073                                                                         MSG_WriteLong(&net_message, 0);
2074                                                                         MSG_WriteByte(&net_message, CCREP_ACCEPT);
2075                                                                         MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
2076                                                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2077                                                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2078                                                                         SZ_Clear(&net_message);
2079                                                                         // now set up the client struct
2080                                                                         SV_VM_Begin();
2081                                                                         SV_ConnectClient(clientnum, conn);
2082                                                                         SV_VM_End();
2083                                                                         NetConn_Heartbeat(1);
2084                                                                 }
2085                                                                 else
2086                                                                 {
2087                                                                         if (developer.integer >= 10)
2088                                                                                 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
2089                                                                         // no room; try to let player know
2090                                                                         SZ_Clear(&net_message);
2091                                                                         // save space for the header, filled in later
2092                                                                         MSG_WriteLong(&net_message, 0);
2093                                                                         MSG_WriteByte(&net_message, CCREP_REJECT);
2094                                                                         MSG_WriteString(&net_message, "Server is full.\n");
2095                                                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2096                                                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2097                                                                         SZ_Clear(&net_message);
2098                                                                 }
2099                                                         }
2100                                                 }
2101                                         }
2102                                         break;
2103 #if 0
2104                                 case CCREQ_SERVER_INFO:
2105                                         if (developer.integer >= 10)
2106                                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
2107                                         if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
2108                                         {
2109                                                 if (developer.integer >= 10)
2110                                                         Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
2111                                                 SZ_Clear(&net_message);
2112                                                 // save space for the header, filled in later
2113                                                 MSG_WriteLong(&net_message, 0);
2114                                                 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
2115                                                 UDP_GetSocketAddr(UDP_acceptSock, &newaddr);
2116                                                 MSG_WriteString(&net_message, UDP_AddrToString(&newaddr));
2117                                                 MSG_WriteString(&net_message, hostname.string);
2118                                                 MSG_WriteString(&net_message, sv.name);
2119                                                 MSG_WriteByte(&net_message, net_activeconnections);
2120                                                 MSG_WriteByte(&net_message, svs.maxclients);
2121                                                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2122                                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2123                                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2124                                                 SZ_Clear(&net_message);
2125                                         }
2126                                         break;
2127                                 case CCREQ_PLAYER_INFO:
2128                                         if (developer.integer >= 10)
2129                                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
2130                                         if (sv.active)
2131                                         {
2132                                                 int playerNumber, activeNumber, clientNumber;
2133                                                 client_t *client;
2134
2135                                                 playerNumber = MSG_ReadByte();
2136                                                 activeNumber = -1;
2137                                                 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
2138                                                         if (client->active && ++activeNumber == playerNumber)
2139                                                                 break;
2140                                                 if (clientNumber != svs.maxclients)
2141                                                 {
2142                                                         SZ_Clear(&net_message);
2143                                                         // save space for the header, filled in later
2144                                                         MSG_WriteLong(&net_message, 0);
2145                                                         MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
2146                                                         MSG_WriteByte(&net_message, playerNumber);
2147                                                         MSG_WriteString(&net_message, client->name);
2148                                                         MSG_WriteLong(&net_message, client->colors);
2149                                                         MSG_WriteLong(&net_message, (int)client->edict->fields.server->frags);
2150                                                         MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
2151                                                         MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
2152                                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2153                                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2154                                                         SZ_Clear(&net_message);
2155                                                 }
2156                                         }
2157                                         break;
2158                                 case CCREQ_RULE_INFO:
2159                                         if (developer.integer >= 10)
2160                                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
2161                                         if (sv.active)
2162                                         {
2163                                                 char *prevCvarName;
2164                                                 cvar_t *var;
2165
2166                                                 // find the search start location
2167                                                 prevCvarName = MSG_ReadString();
2168                                                 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
2169
2170                                                 // send the response
2171                                                 SZ_Clear(&net_message);
2172                                                 // save space for the header, filled in later
2173                                                 MSG_WriteLong(&net_message, 0);
2174                                                 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
2175                                                 if (var)
2176                                                 {
2177                                                         MSG_WriteString(&net_message, var->name);
2178                                                         MSG_WriteString(&net_message, var->string);
2179                                                 }
2180                                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2181                                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2182                                                 SZ_Clear(&net_message);
2183                                         }
2184                                         break;
2185 #endif
2186                                 default:
2187                                         break;
2188                                 }
2189                                 // we may not have liked the packet, but it was a valid control
2190                                 // packet, so we're done processing this packet now
2191                                 return true;
2192                         }
2193                 }
2194 #endif
2195                 if (host_client)
2196                 {
2197                         if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length, sv.protocol)) == 2)
2198                         {
2199                                 SV_VM_Begin();
2200                                 SV_ReadClientMessage();
2201                                 SV_VM_End();
2202                                 return ret;
2203                         }
2204                 }
2205         }
2206         return 0;
2207 }
2208
2209 void NetConn_ServerFrame(void)
2210 {
2211         int i, length;
2212         lhnetaddress_t peeraddress;
2213         NetConn_UpdateSockets();
2214         for (i = 0;i < sv_numsockets;i++)
2215                 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2216                         NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
2217         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2218         {
2219                 // never timeout loopback connections
2220                 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2221                 {
2222                         Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
2223                         SV_VM_Begin();
2224                         SV_DropClient(false);
2225                         SV_VM_End();
2226                 }
2227         }
2228 }
2229
2230 void NetConn_QueryMasters(qboolean querydp, qboolean queryqw)
2231 {
2232         int i;
2233         int masternum;
2234         lhnetaddress_t masteraddress;
2235         lhnetaddress_t broadcastaddress;
2236         char request[256];
2237
2238         if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
2239                 return;
2240
2241         // 26000 is the default quake server port, servers on other ports will not
2242         // be found
2243         // note this is IPv4-only, I doubt there are IPv6-only LANs out there
2244         LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
2245
2246         if (querydp)
2247         {
2248                 for (i = 0;i < cl_numsockets;i++)
2249                 {
2250                         if (cl_sockets[i])
2251                         {
2252                                 // search LAN for Quake servers
2253                                 SZ_Clear(&net_message);
2254                                 // save space for the header, filled in later
2255                                 MSG_WriteLong(&net_message, 0);
2256                                 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
2257                                 MSG_WriteString(&net_message, "QUAKE");
2258                                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2259                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2260                                 NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
2261                                 SZ_Clear(&net_message);
2262
2263                                 // search LAN for DarkPlaces servers
2264                                 NetConn_WriteString(cl_sockets[i], "\377\377\377\377getinfo", &broadcastaddress);
2265
2266                                 // build the getservers message to send to the dpmaster master servers
2267                                 dpsnprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
2268
2269                                 // search internet
2270                                 for (masternum = 0;sv_masters[masternum].name;masternum++)
2271                                 {
2272                                         if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
2273                                         {
2274                                                 masterquerycount++;
2275                                                 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
2276                                         }
2277                                 }
2278                         }
2279                 }
2280         }
2281
2282         // only query QuakeWorld servers when the user wants to
2283         if (queryqw)
2284         {
2285                 for (i = 0;i < cl_numsockets;i++)
2286                 {
2287                         if (cl_sockets[i])
2288                         {
2289                                 // search LAN for QuakeWorld servers
2290                                 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &broadcastaddress);
2291
2292                                 // build the getservers message to send to the qwmaster master servers
2293                                 // note this has no -1 prefix, and the trailing nul byte is sent
2294                                 dpsnprintf(request, sizeof(request), "c\n");
2295
2296                                 // search internet
2297                                 for (masternum = 0;sv_qwmasters[masternum].name;masternum++)
2298                                 {
2299                                         if (sv_qwmasters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_qwmasters[masternum].string, QWMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
2300                                         {
2301                                                 masterquerycount++;
2302                                                 NetConn_Write(cl_sockets[i], request, 7, &masteraddress);
2303                                         }
2304                                 }
2305                         }
2306                 }
2307         }
2308         if (!masterquerycount)
2309         {
2310                 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
2311                 M_Update_Return_Reason("No network");
2312         }
2313 }
2314
2315 void NetConn_Heartbeat(int priority)
2316 {
2317         lhnetaddress_t masteraddress;
2318         int masternum;
2319         lhnetsocket_t *mysocket;
2320
2321         // if it's a state change (client connected), limit next heartbeat to no
2322         // more than 30 sec in the future
2323         if (priority == 1 && nextheartbeattime > realtime + 30.0)
2324                 nextheartbeattime = realtime + 30.0;
2325
2326         // limit heartbeatperiod to 30 to 270 second range,
2327         // lower limit is to avoid abusing master servers with excess traffic,
2328         // upper limit is to avoid timing out on the master server (which uses
2329         // 300 sec timeout)
2330         if (sv_heartbeatperiod.value < 30)
2331                 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
2332         if (sv_heartbeatperiod.value > 270)
2333                 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
2334
2335         // make advertising optional and don't advertise singleplayer games, and
2336         // only send a heartbeat as often as the admin wants
2337         if (sv.active && sv_public.integer && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
2338         {
2339                 nextheartbeattime = realtime + sv_heartbeatperiod.value;
2340                 for (masternum = 0;sv_masters[masternum].name;masternum++)
2341                         if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
2342                                 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
2343         }
2344 }
2345
2346 static void Net_Heartbeat_f(void)
2347 {
2348         if (sv.active)
2349                 NetConn_Heartbeat(2);
2350         else
2351                 Con_Print("No server running, can not heartbeat to master server.\n");
2352 }
2353
2354 void PrintStats(netconn_t *conn)
2355 {
2356         if ((cls.state == ca_connected && cls.protocol == PROTOCOL_QUAKEWORLD) || (sv.active && sv.protocol == PROTOCOL_QUAKEWORLD))
2357                 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->qw.outgoing_sequence, conn->qw.incoming_sequence);
2358         else
2359                 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->nq.sendSequence, conn->nq.receiveSequence);
2360 }
2361
2362 void Net_Stats_f(void)
2363 {
2364         netconn_t *conn;
2365         Con_Printf("unreliable messages sent   = %i\n", unreliableMessagesSent);
2366         Con_Printf("unreliable messages recv   = %i\n", unreliableMessagesReceived);
2367         Con_Printf("reliable messages sent     = %i\n", reliableMessagesSent);
2368         Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
2369         Con_Printf("packetsSent                = %i\n", packetsSent);
2370         Con_Printf("packetsReSent              = %i\n", packetsReSent);
2371         Con_Printf("packetsReceived            = %i\n", packetsReceived);
2372         Con_Printf("receivedDuplicateCount     = %i\n", receivedDuplicateCount);
2373         Con_Printf("droppedDatagrams           = %i\n", droppedDatagrams);
2374         Con_Print("connections                =\n");
2375         for (conn = netconn_list;conn;conn = conn->next)
2376                 PrintStats(conn);
2377 }
2378
2379 void Net_Slist_f(void)
2380 {
2381         ServerList_ResetMasks();
2382         serverlist_sortbyfield = SLIF_PING;
2383         serverlist_sortdescending = false;
2384     if (m_state != m_slist) {
2385                 Con_Print("Sending requests to master servers\n");
2386                 ServerList_QueryList(true, false);
2387                 serverlist_consoleoutput = true;
2388                 Con_Print("Listening for replies...\n");
2389         } else
2390                 ServerList_QueryList(true, false);
2391 }
2392
2393 void Net_SlistQW_f(void)
2394 {
2395         ServerList_ResetMasks();
2396         serverlist_sortbyfield = SLIF_PING;
2397         serverlist_sortdescending = false;
2398     if (m_state != m_slist) {
2399                 Con_Print("Sending requests to master servers\n");
2400                 ServerList_QueryList(false, true);
2401                 serverlist_consoleoutput = true;
2402                 Con_Print("Listening for replies...\n");
2403         } else
2404                 ServerList_QueryList(false, true);
2405 }
2406
2407 void NetConn_Init(void)
2408 {
2409         int i;
2410         lhnetaddress_t tempaddress;
2411         netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
2412         Cmd_AddCommand("net_stats", Net_Stats_f, "print network statistics");
2413         Cmd_AddCommand("net_slist", Net_Slist_f, "query dp master servers and print all server information");
2414         Cmd_AddCommand("net_slistqw", Net_SlistQW_f, "query qw master servers and print all server information");
2415         Cmd_AddCommand("heartbeat", Net_Heartbeat_f, "send a heartbeat to the master server (updates your server information)");
2416         Cvar_RegisterVariable(&net_slist_queriespersecond);
2417         Cvar_RegisterVariable(&net_slist_queriesperframe);
2418         Cvar_RegisterVariable(&net_slist_timeout);
2419         Cvar_RegisterVariable(&net_slist_maxtries);
2420         Cvar_RegisterVariable(&net_messagetimeout);
2421         Cvar_RegisterVariable(&net_messagerejointimeout);
2422         Cvar_RegisterVariable(&net_connecttimeout);
2423         Cvar_RegisterVariable(&cl_netlocalping);
2424         Cvar_RegisterVariable(&cl_netpacketloss);
2425         Cvar_RegisterVariable(&hostname);
2426         Cvar_RegisterVariable(&developer_networking);
2427         Cvar_RegisterVariable(&cl_netport);
2428         Cvar_RegisterVariable(&sv_netport);
2429         Cvar_RegisterVariable(&net_address);
2430         //Cvar_RegisterVariable(&net_address_ipv6);
2431         Cvar_RegisterVariable(&sv_public);
2432         Cvar_RegisterVariable(&sv_heartbeatperiod);
2433         for (i = 0;sv_masters[i].name;i++)
2434                 Cvar_RegisterVariable(&sv_masters[i]);
2435         Cvar_RegisterVariable(&gameversion);
2436 // 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.
2437         if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
2438         {
2439                 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
2440                 {
2441                         Con_Printf("-ip option used, setting net_address to \"%s\"\n");
2442                         Cvar_SetQuick(&net_address, com_argv[i + 1]);
2443                 }
2444                 else
2445                         Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
2446         }
2447 // 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
2448         if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
2449         {
2450                 i = atoi(com_argv[i + 1]);
2451                 if (i >= 0 && i < 65536)
2452                 {
2453                         Con_Printf("-port option used, setting port cvar to %i\n", i);
2454                         Cvar_SetValueQuick(&sv_netport, i);
2455                 }
2456                 else
2457                         Con_Printf("-port option used, but %i is not a valid port number\n", i);
2458         }
2459         cl_numsockets = 0;
2460         sv_numsockets = 0;
2461         net_message.data = net_message_buf;
2462         net_message.maxsize = sizeof(net_message_buf);
2463         net_message.cursize = 0;
2464         LHNET_Init();
2465 }
2466
2467 void NetConn_Shutdown(void)
2468 {
2469         NetConn_CloseClientPorts();
2470         NetConn_CloseServerPorts();
2471         LHNET_Shutdown();
2472 }
2473