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