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