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