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