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