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