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