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