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