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