]> icculus.org git repositories - divverent/darkplaces.git/blob - netconn.c
now does a togglemenu if there were no demos started and not connecting to a server...
[divverent/darkplaces.git] / netconn.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3 Copyright (C) 2002 Mathieu Olivier
4 Copyright (C) 2003 Forest Hale
5
6 This program is free software; you can redistribute it and/or
7 modify it under the terms of the GNU General Public License
8 as published by the Free Software Foundation; either version 2
9 of the License, or (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14
15 See the GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
20
21 */
22
23 #include "quakedef.h"
24 #include "lhnet.h"
25
26 #define MASTER_PORT 27950
27
28 cvar_t sv_public = {0, "sv_public", "0"};
29 static cvar_t sv_heartbeatperiod = {CVAR_SAVE, "sv_heartbeatperiod", "180"};
30
31 // FIXME: resolve DNS on masters whenever their value changes and cache it (to avoid major delays in active servers when they heartbeat)
32 static cvar_t sv_masters [] =
33 {
34         {CVAR_SAVE, "sv_master1", ""},
35         {CVAR_SAVE, "sv_master2", ""},
36         {CVAR_SAVE, "sv_master3", ""},
37         {CVAR_SAVE, "sv_master4", ""},
38         {0, "sv_masterextra1", "69.59.212.88"}, // ghdigital.com
39         {0, "sv_masterextra2", "66.169.205.13"}, // dpmaster.deathmask.net
40         {0, "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                                 serverquerycount++;
985         
986                                 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], (data[5] << 8) | data[6]);
987                                 if (developer.integer)
988                                         Con_Printf("Requesting info from server %s\n", ipstring);                               
989                                 // ignore the rest of the message if the hostcache is full
990                                 if( hostcache_cachecount == HOSTCACHE_TOTALSIZE )
991                                         break;
992
993                                 LHNETADDRESS_FromString(&svaddress, ipstring, 0);
994                                 NetConn_WriteString(mysocket, "\377\377\377\377getinfo", &svaddress);
995
996                                 memset(&hostcache_cache[hostcache_cachecount], 0, sizeof(hostcache_cache[hostcache_cachecount]));
997                                 // store the data the engine cares about (address and ping)
998                                 strlcpy (hostcache_cache[hostcache_cachecount].info.cname, ipstring, sizeof (hostcache_cache[hostcache_cachecount].info.cname));
999                                 hostcache_cache[hostcache_cachecount].info.ping = 100000;
1000                                 hostcache_cache[hostcache_cachecount].querytime = realtime;
1001                                 // if not in the slist menu we should print the server to console
1002                                 if (hostcache_consoleoutput)
1003                                         Con_Printf("querying %s\n", ipstring);
1004
1005                                 ++hostcache_cachecount;
1006
1007                                 // move on to next address in packet
1008                                 data += 7;
1009                                 length -= 7;
1010                         }
1011                         return true;
1012                 }
1013                 /*
1014                 if (!strncmp(string, "ping", 4))
1015                 {
1016                         if (developer.integer)
1017                                 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1018                         NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1019                         return true;
1020                 }
1021                 if (!strncmp(string, "ack", 3))
1022                         return true;
1023                 */
1024                 // we may not have liked the packet, but it was a command packet, so
1025                 // we're done processing this packet now
1026                 return true;
1027         }
1028         // netquake control packets, supported for compatibility only
1029         if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1030         {
1031                 c = data[4];
1032                 data += 5;
1033                 length -= 5;
1034                 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1035                 switch (c)
1036                 {
1037                 case CCREP_ACCEPT:
1038                         if (developer.integer)
1039                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1040                         if (cls.connect_trying)
1041                         {
1042                                 lhnetaddress_t clientportaddress;
1043                                 clientportaddress = *peeraddress;
1044                                 if (length >= 4)
1045                                 {
1046                                         unsigned int port = (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
1047                                         data += 4;
1048                                         length -= 4;
1049                                         LHNETADDRESS_SetPort(&clientportaddress, port);
1050                                 }
1051                                 M_Update_Return_Reason("Accepted");
1052                                 NetConn_ConnectionEstablished(mysocket, &clientportaddress);
1053                         }
1054                         break;
1055                 case CCREP_REJECT:
1056                         if (developer.integer)
1057                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1058                         cls.connect_trying = false;
1059                         M_Update_Return_Reason(data);
1060                         break;
1061 #if 0
1062                 case CCREP_SERVER_INFO:
1063                         if (developer.integer)
1064                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1065                         if (cls.state != ca_dedicated)
1066                         {
1067                                 // LordHavoc: because the UDP driver reports 0.0.0.0:26000 as the address
1068                                 // string we just ignore it and keep the real address
1069                                 MSG_ReadString();
1070                                 // hostcache only uses text addresses
1071                                 cname = UDP_AddrToString(readaddr);
1072                                 // search the cache for this server
1073                                 for (n = 0; n < hostCacheCount; n++)
1074                                         if (!strcmp(cname, hostcache[n].cname))
1075                                                 break;
1076                                 // add it
1077                                 if (n == hostCacheCount && hostCacheCount < HOSTCACHESIZE)
1078                                 {
1079                                         hostCacheCount++;
1080                                         memset(&hostcache[n], 0, sizeof(hostcache[n]));
1081                                         strlcpy (hostcache[n].name, MSG_ReadString(), sizeof (hostcache[n].name));
1082                                         strlcpy (hostcache[n].map, MSG_ReadString(), sizeof (hostcache[n].map));
1083                                         hostcache[n].users = MSG_ReadByte();
1084                                         hostcache[n].maxusers = MSG_ReadByte();
1085                                         c = MSG_ReadByte();
1086                                         if (c != NET_PROTOCOL_VERSION)
1087                                         {
1088                                                 strlcpy (hostcache[n].cname, hostcache[n].name, sizeof (hostcache[n].cname));
1089                                                 strcpy(hostcache[n].name, "*");
1090                                                 strlcat (hostcache[n].name, hostcache[n].cname, sizeof(hostcache[n].name));
1091                                         }
1092                                         strlcpy (hostcache[n].cname, cname, sizeof (hostcache[n].cname));
1093                                 }
1094                         }
1095                         break;
1096                 case CCREP_PLAYER_INFO:
1097                         // we got a CCREP_PLAYER_INFO??
1098                         //if (developer.integer)
1099                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1100                         break;
1101                 case CCREP_RULE_INFO:
1102                         // we got a CCREP_RULE_INFO??
1103                         //if (developer.integer)
1104                                 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1105                         break;
1106 #endif
1107                 default:
1108                         break;
1109                 }
1110                 // we may not have liked the packet, but it was a valid control
1111                 // packet, so we're done processing this packet now
1112                 return true;
1113         }
1114         ret = 0;
1115         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)
1116                 CL_ParseServerMessage();
1117         return ret;
1118 }
1119
1120 void NetConn_ClientFrame(void)
1121 {
1122         int i, length;
1123         lhnetaddress_t peeraddress;
1124         netconn_t *conn;
1125         NetConn_UpdateServerStuff();
1126         if (cls.connect_trying && cls.connect_nextsendtime < realtime)
1127         {
1128                 if (cls.connect_remainingtries == 0)
1129                 {
1130                         cls.connect_trying = false;
1131                         M_Update_Return_Reason("Connect: Failed");
1132                         return;
1133                 }
1134                 cls.connect_nextsendtime = realtime + 1;
1135                 cls.connect_remainingtries--;
1136                 // try challenge first (newer server)
1137                 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
1138                 // then try netquake as a fallback (old server, or netquake)
1139                 SZ_Clear(&net_message);
1140                 // save space for the header, filled in later
1141                 MSG_WriteLong(&net_message, 0);
1142                 MSG_WriteByte(&net_message, CCREQ_CONNECT);
1143                 MSG_WriteString(&net_message, "QUAKE");
1144                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1145                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1146                 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
1147                 SZ_Clear(&net_message);
1148         }
1149         for (i = 0;i < cl_numsockets;i++)
1150                 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1151                         NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
1152         if (cls.netcon && realtime > cls.netcon->timeout)
1153         {
1154                 Con_Print("Connection timed out\n");
1155                 CL_Disconnect();
1156                 Host_ShutdownServer (false);
1157         }
1158         for (conn = netconn_list;conn;conn = conn->next)
1159                 NetConn_ReSendMessage(conn);
1160 }
1161
1162 #define MAX_CHALLENGES 128
1163 struct
1164 {
1165         lhnetaddress_t address;
1166         double time;
1167         char string[12];
1168 }
1169 challenge[MAX_CHALLENGES];
1170
1171 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
1172 {
1173         int i;
1174         char c;
1175         for (i = 0;i < bufferlength - 1;i++)
1176         {
1177                 do
1178                 {
1179                         c = rand () % (127 - 33) + 33;
1180                 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
1181                 buffer[i] = c;
1182         }
1183         buffer[i] = 0;
1184 }
1185
1186 int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
1187 {
1188         int i, n, ret, clientnum, responselength, best;
1189         double besttime;
1190         client_t *client;
1191         netconn_t *conn;
1192         char *s, *string, response[512], addressstring2[128], stringbuf[16384];
1193
1194         if (sv.active)
1195         {
1196                 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1197                 {
1198                         // received a command string - strip off the packaging and put it
1199                         // into our string buffer with NULL termination
1200                         data += 4;
1201                         length -= 4;
1202                         length = min(length, (int)sizeof(stringbuf) - 1);
1203                         memcpy(stringbuf, data, length);
1204                         stringbuf[length] = 0;
1205                         string = stringbuf;
1206
1207                         if (developer.integer)
1208                         {
1209                                 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1210                                 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
1211                                 Com_HexDumpToConsole(data, length);
1212                         }
1213
1214                         if (length >= 12 && !memcmp(string, "getchallenge", 12))
1215                         {
1216                                 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
1217                                 {
1218                                         if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
1219                                                 break;
1220                                         if (besttime > challenge[i].time)
1221                                                 besttime = challenge[best = i].time;
1222                                 }
1223                                 // if we did not find an exact match, choose the oldest and
1224                                 // update address and string
1225                                 if (i == MAX_CHALLENGES)
1226                                 {
1227                                         i = best;
1228                                         challenge[i].address = *peeraddress;
1229                                         NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
1230                                 }
1231                                 challenge[i].time = realtime;
1232                                 // send the challenge
1233                                 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
1234                                 return true;
1235                         }
1236                         if (length > 8 && !memcmp(string, "connect\\", 8))
1237                         {
1238                                 string += 7;
1239                                 length -= 7;
1240                                 if ((s = SearchInfostring(string, "challenge")))
1241                                 {
1242                                         // validate the challenge
1243                                         for (i = 0;i < MAX_CHALLENGES;i++)
1244                                                 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1245                                                         break;
1246                                         if (i < MAX_CHALLENGES)
1247                                         {
1248                                                 // check engine protocol
1249                                                 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
1250                                                 {
1251                                                         if (developer.integer)
1252                                                                 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
1253                                                         NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
1254                                                 }
1255                                                 else
1256                                                 {
1257                                                         // see if this is a duplicate connection request
1258                                                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1259                                                                 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1260                                                                         break;
1261                                                         if (clientnum < svs.maxclients)
1262                                                         {
1263                                                                 // duplicate connection request
1264                                                                 if (realtime - client->connecttime < 2.0)
1265                                                                 {
1266                                                                         // client is still trying to connect,
1267                                                                         // so we send a duplicate reply
1268                                                                         if (developer.integer)
1269                                                                                 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
1270                                                                         NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1271                                                                 }
1272                                                                 // only kick if old connection seems dead
1273                                                                 if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1274                                                                 {
1275                                                                         // kick off connection and await retry
1276                                                                         client->deadsocket = true;
1277                                                                 }
1278                                                         }
1279                                                         else
1280                                                         {
1281                                                                 // this is a new client, find a slot
1282                                                                 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1283                                                                         if (!client->active)
1284                                                                                 break;
1285                                                                 if (clientnum < svs.maxclients)
1286                                                                 {
1287                                                                         // prepare the client struct
1288                                                                         if ((conn = NetConn_Open(mysocket, peeraddress)))
1289                                                                         {
1290                                                                                 // allocated connection
1291                                                                                 LHNETADDRESS_ToString(peeraddress, conn->address, sizeof(conn->address), true);
1292                                                                                 if (developer.integer)
1293                                                                                         Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
1294                                                                                 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1295                                                                                 // now set up the client
1296                                                                                 SV_ConnectClient(clientnum, conn);
1297                                                                                 NetConn_Heartbeat(1);
1298                                                                         }
1299                                                                 }
1300                                                                 else
1301                                                                 {
1302                                                                         // server is full
1303                                                                         if (developer.integer)
1304                                                                                 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
1305                                                                         NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
1306                                                                 }
1307                                                         }
1308                                                 }
1309                                         }
1310                                 }
1311                                 return true;
1312                         }
1313                         if (length >= 7 && !memcmp(string, "getinfo", 7))
1314                         {
1315                                 const char *challenge = NULL;
1316                                 // If there was a challenge in the getinfo message
1317                                 if (length > 8 && string[7] == ' ')
1318                                         challenge = string + 8;
1319                                 for (i = 0, n = 0;i < svs.maxclients;i++)
1320                                         if (svs.clients[i].active)
1321                                                 n++;
1322                                 responselength = dpsnprintf(response, sizeof(response), "\377\377\377\377infoResponse\x0A"
1323                                                         "\\gamename\\%s\\modname\\%s\\sv_maxclients\\%d"
1324                                                         "\\clients\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d%s%s",
1325                                                         gamename, com_modname, svs.maxclients, n,
1326                                                         sv.name, hostname.string, NET_PROTOCOL_VERSION, challenge ? "\\challenge\\" : "", challenge ? challenge : "");
1327                                 // does it fit in the buffer?
1328                                 if (responselength >= 0)
1329                                 {
1330                                         if (developer.integer)
1331                                                 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
1332                                         NetConn_WriteString(mysocket, response, peeraddress);
1333                                 }
1334                                 return true;
1335                         }
1336                         /*
1337                         if (!strncmp(string, "ping", 4))
1338                         {
1339                                 if (developer.integer)
1340                                         Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1341                                 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1342                                 return true;
1343                         }
1344                         if (!strncmp(string, "ack", 3))
1345                                 return true;
1346                         */
1347                         // we may not have liked the packet, but it was a command packet, so
1348                         // we're done processing this packet now
1349                         return true;
1350                 }
1351                 // LordHavoc: disabled netquake control packet support in server
1352 #if 0
1353                 {
1354                         int c, control;
1355                         // netquake control packets, supported for compatibility only
1356                         if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1357                         {
1358                                 c = data[4];
1359                                 data += 5;
1360                                 length -= 5;
1361                                 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1362                                 switch (c)
1363                                 {
1364                                 case CCREQ_CONNECT:
1365                                         //if (developer.integer)
1366                                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
1367                                         if (length >= (int)strlen("QUAKE") + 1 + 1)
1368                                         {
1369                                                 if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION)
1370                                                 {
1371                                                         if (developer.integer)
1372                                                                 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
1373                                                         SZ_Clear(&net_message);
1374                                                         // save space for the header, filled in later
1375                                                         MSG_WriteLong(&net_message, 0);
1376                                                         MSG_WriteByte(&net_message, CCREP_REJECT);
1377                                                         MSG_WriteString(&net_message, "Incompatible version.\n");
1378                                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1379                                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1380                                                         SZ_Clear(&net_message);
1381                                                 }
1382                                                 else
1383                                                 {
1384                                                         // see if this is a duplicate connection request
1385                                                         for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1386                                                                 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1387                                                                         break;
1388                                                         if (clientnum < svs.maxclients)
1389                                                         {
1390                                                                 // duplicate connection request
1391                                                                 if (realtime - client->connecttime < 2.0)
1392                                                                 {
1393                                                                         // client is still trying to connect,
1394                                                                         // so we send a duplicate reply
1395                                                                         if (developer.integer)
1396                                                                                 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
1397                                                                         SZ_Clear(&net_message);
1398                                                                         // save space for the header, filled in later
1399                                                                         MSG_WriteLong(&net_message, 0);
1400                                                                         MSG_WriteByte(&net_message, CCREP_ACCEPT);
1401                                                                         MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
1402                                                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1403                                                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1404                                                                         SZ_Clear(&net_message);
1405                                                                 }
1406                                                                 else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1407                                                                 {
1408                                                                         // the old client hasn't sent us anything
1409                                                                         // in quite a while, so kick off and let
1410                                                                         // the retry take care of it...
1411                                                                         client->deadsocket = true;
1412                                                                 }
1413                                                         }
1414                                                         else
1415                                                         {
1416                                                                 // this is a new client, find a slot
1417                                                                 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1418                                                                         if (!client->active)
1419                                                                                 break;
1420                                                                 if (clientnum < svs.maxclients && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
1421                                                                 {
1422                                                                         // connect to the client
1423                                                                         // everything is allocated, just fill in the details
1424                                                                         strlcpy (conn->address, addressstring2, sizeof (conn->address));
1425                                                                         if (developer.integer)
1426                                                                                 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
1427                                                                         // send back the info about the server connection
1428                                                                         SZ_Clear(&net_message);
1429                                                                         // save space for the header, filled in later
1430                                                                         MSG_WriteLong(&net_message, 0);
1431                                                                         MSG_WriteByte(&net_message, CCREP_ACCEPT);
1432                                                                         MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
1433                                                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1434                                                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1435                                                                         SZ_Clear(&net_message);
1436                                                                         // now set up the client struct
1437                                                                         SV_ConnectClient(clientnum, conn);
1438                                                                         NetConn_Heartbeat(1);
1439                                                                 }
1440                                                                 else
1441                                                                 {
1442                                                                         //if (developer.integer)
1443                                                                                 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
1444                                                                         // no room; try to let player know
1445                                                                         SZ_Clear(&net_message);
1446                                                                         // save space for the header, filled in later
1447                                                                         MSG_WriteLong(&net_message, 0);
1448                                                                         MSG_WriteByte(&net_message, CCREP_REJECT);
1449                                                                         MSG_WriteString(&net_message, "Server is full.\n");
1450                                                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1451                                                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1452                                                                         SZ_Clear(&net_message);
1453                                                                 }
1454                                                         }
1455                                                 }
1456                                         }
1457                                         break;
1458 #if 0
1459                                 case CCREQ_SERVER_INFO:
1460                                         if (developer.integer)
1461                                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
1462                                         if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
1463                                         {
1464                                                 if (developer.integer)
1465                                                         Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
1466                                                 SZ_Clear(&net_message);
1467                                                 // save space for the header, filled in later
1468                                                 MSG_WriteLong(&net_message, 0);
1469                                                 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
1470                                                 UDP_GetSocketAddr(UDP_acceptSock, &newaddr);
1471                                                 MSG_WriteString(&net_message, UDP_AddrToString(&newaddr));
1472                                                 MSG_WriteString(&net_message, hostname.string);
1473                                                 MSG_WriteString(&net_message, sv.name);
1474                                                 MSG_WriteByte(&net_message, net_activeconnections);
1475                                                 MSG_WriteByte(&net_message, svs.maxclients);
1476                                                 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1477                                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1478                                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1479                                                 SZ_Clear(&net_message);
1480                                         }
1481                                         break;
1482                                 case CCREQ_PLAYER_INFO:
1483                                         if (developer.integer)
1484                                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
1485                                         if (sv.active)
1486                                         {
1487                                                 int playerNumber, activeNumber, clientNumber;
1488                                                 client_t *client;
1489
1490                                                 playerNumber = MSG_ReadByte();
1491                                                 activeNumber = -1;
1492                                                 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
1493                                                         if (client->active && ++activeNumber == playerNumber)
1494                                                                 break;
1495                                                 if (clientNumber != svs.maxclients)
1496                                                 {
1497                                                         SZ_Clear(&net_message);
1498                                                         // save space for the header, filled in later
1499                                                         MSG_WriteLong(&net_message, 0);
1500                                                         MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
1501                                                         MSG_WriteByte(&net_message, playerNumber);
1502                                                         MSG_WriteString(&net_message, client->name);
1503                                                         MSG_WriteLong(&net_message, client->colors);
1504                                                         MSG_WriteLong(&net_message, (int)client->edict->v->frags);
1505                                                         MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
1506                                                         MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
1507                                                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1508                                                         NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1509                                                         SZ_Clear(&net_message);
1510                                                 }
1511                                         }
1512                                         break;
1513                                 case CCREQ_RULE_INFO:
1514                                         if (developer.integer)
1515                                                 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
1516                                         if (sv.active)
1517                                         {
1518                                                 char *prevCvarName;
1519                                                 cvar_t *var;
1520
1521                                                 // find the search start location
1522                                                 prevCvarName = MSG_ReadString();
1523                                                 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
1524
1525                                                 // send the response
1526                                                 SZ_Clear(&net_message);
1527                                                 // save space for the header, filled in later
1528                                                 MSG_WriteLong(&net_message, 0);
1529                                                 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
1530                                                 if (var)
1531                                                 {
1532                                                         MSG_WriteString(&net_message, var->name);
1533                                                         MSG_WriteString(&net_message, var->string);
1534                                                 }
1535                                                 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1536                                                 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1537                                                 SZ_Clear(&net_message);
1538                                         }
1539                                         break;
1540 #endif
1541                                 default:
1542                                         break;
1543                                 }
1544                                 // we may not have liked the packet, but it was a valid control
1545                                 // packet, so we're done processing this packet now
1546                                 return true;
1547                         }
1548                 }
1549 #endif
1550                 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1551                 {
1552                         if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1553                         {
1554                                 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length)) == 2)
1555                                         SV_ReadClientMessage();
1556                                 return ret;
1557                         }
1558                 }
1559         }
1560         return 0;
1561 }
1562
1563 void NetConn_ServerFrame(void)
1564 {
1565         int i, length;
1566         lhnetaddress_t peeraddress;
1567         netconn_t *conn;
1568         NetConn_UpdateServerStuff();
1569         for (i = 0;i < sv_numsockets;i++)
1570                 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1571                         NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
1572         for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1573         {
1574                 // never timeout loopback connections
1575                 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
1576                 {
1577                         Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
1578                         SV_DropClient(false);
1579                 }
1580         }
1581         for (conn = netconn_list;conn;conn = conn->next)
1582                 NetConn_ReSendMessage(conn);
1583 }
1584
1585 void NetConn_QueryMasters(void)
1586 {
1587         int i;
1588         int masternum;
1589         lhnetaddress_t masteraddress;
1590         char request[256];
1591
1592         if (hostcache_cachecount >= HOSTCACHE_TOTALSIZE)
1593                 return;
1594
1595         for (i = 0;i < cl_numsockets;i++)
1596         {
1597                 if (cl_sockets[i])
1598                 {
1599 #if 0
1600                         // search LAN
1601 #if 1
1602                         UDP_Broadcast(UDP_controlSock, "\377\377\377\377getinfo", 11);
1603 #else
1604                         SZ_Clear(&net_message);
1605                         // save space for the header, filled in later
1606                         MSG_WriteLong(&net_message, 0);
1607                         MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
1608                         MSG_WriteString(&net_message, "QUAKE");
1609                         MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1610                         *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1611                         UDP_Broadcast(UDP_controlSock, net_message.data, net_message.cursize);
1612                         SZ_Clear(&net_message);
1613 #endif
1614 #endif
1615
1616                         // build the getservers
1617                         dpsnprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
1618
1619                         // search internet
1620                         for (masternum = 0;sv_masters[masternum].name;masternum++)
1621                         {
1622                                 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
1623                                 {
1624                                         masterquerycount++;
1625                                         NetConn_WriteString(cl_sockets[i], request, &masteraddress);
1626                                 }
1627                         }
1628                 }
1629         }
1630         if (!masterquerycount)
1631         {
1632                 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
1633                 M_Update_Return_Reason("No network");
1634         }
1635 }
1636
1637 void NetConn_Heartbeat(int priority)
1638 {
1639         lhnetaddress_t masteraddress;
1640         int masternum;
1641         lhnetsocket_t *mysocket;
1642
1643         // if it's a state change (client connected), limit next heartbeat to no
1644         // more than 30 sec in the future
1645         if (priority == 1 && nextheartbeattime > realtime + 30.0)
1646                 nextheartbeattime = realtime + 30.0;
1647
1648         // limit heartbeatperiod to 30 to 270 second range,
1649         // lower limit is to avoid abusing master servers with excess traffic,
1650         // upper limit is to avoid timing out on the master server (which uses
1651         // 300 sec timeout)
1652         if (sv_heartbeatperiod.value < 30)
1653                 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
1654         if (sv_heartbeatperiod.value > 270)
1655                 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
1656
1657         // make advertising optional and don't advertise singleplayer games, and
1658         // only send a heartbeat as often as the admin wants
1659         if (sv.active && sv_public.integer && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
1660         {
1661                 nextheartbeattime = realtime + sv_heartbeatperiod.value;
1662                 for (masternum = 0;sv_masters[masternum].name;masternum++)
1663                         if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
1664                                 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
1665         }
1666 }
1667
1668 int NetConn_SendToAll(sizebuf_t *data, double blocktime)
1669 {
1670         int i, count = 0;
1671         qbyte sent[MAX_SCOREBOARD];
1672
1673         memset(sent, 0, sizeof(sent));
1674
1675         // simultaneously wait for the first CanSendMessage and send the message,
1676         // then wait for a second CanSendMessage (verifying it was received), or
1677         // the client drops and is no longer counted
1678         // the loop aborts when either it runs out of clients to send to, or a
1679         // timeout expires
1680         blocktime += Sys_DoubleTime();
1681         do
1682         {
1683                 count = 0;
1684                 NetConn_ClientFrame();
1685                 NetConn_ServerFrame();
1686                 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1687                 {
1688                         if (host_client->netconnection)
1689                         {
1690                                 if (NetConn_CanSendMessage(host_client->netconnection))
1691                                 {
1692                                         if (!sent[i])
1693                                                 NetConn_SendReliableMessage(host_client->netconnection, data);
1694                                         sent[i] = true;
1695                                 }
1696                                 if (!NetConn_CanSendMessage(host_client->netconnection))
1697                                         count++;
1698                         }
1699                 }
1700         }
1701         while (count && Sys_DoubleTime() < blocktime);
1702         return count;
1703 }
1704
1705 static void Net_Heartbeat_f(void)
1706 {
1707         if (sv.active)
1708                 NetConn_Heartbeat(2);
1709         else
1710                 Con_Print("No server running, can not heartbeat to master server.\n");
1711 }
1712
1713 void PrintStats(netconn_t *conn)
1714 {
1715         Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, conn->canSend, conn->sendSequence, conn->receiveSequence);
1716 }
1717
1718 void Net_Stats_f(void)
1719 {
1720         netconn_t *conn;
1721         Con_Printf("unreliable messages sent   = %i\n", unreliableMessagesSent);
1722         Con_Printf("unreliable messages recv   = %i\n", unreliableMessagesReceived);
1723         Con_Printf("reliable messages sent     = %i\n", reliableMessagesSent);
1724         Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
1725         Con_Printf("packetsSent                = %i\n", packetsSent);
1726         Con_Printf("packetsReSent              = %i\n", packetsReSent);
1727         Con_Printf("packetsReceived            = %i\n", packetsReceived);
1728         Con_Printf("receivedDuplicateCount     = %i\n", receivedDuplicateCount);
1729         Con_Printf("droppedDatagrams           = %i\n", droppedDatagrams);
1730         Con_Print("connections                =\n");
1731         for (conn = netconn_list;conn;conn = conn->next)
1732                 PrintStats(conn);
1733 }
1734
1735 void Net_Slist_f(void)
1736 {
1737         HostCache_ResetMasks();
1738         hostcache_sortbyfield = HCIF_PING;
1739         hostcache_sortdescending = false;
1740     if (m_state != m_slist) {
1741                 Con_Print("Sending requests to master servers\n");
1742                 HostCache_QueryList();
1743                 hostcache_consoleoutput = true;
1744                 Con_Print("Listening for replies...\n");
1745         } else
1746                 HostCache_QueryList();
1747 }
1748
1749 void NetConn_Init(void)
1750 {
1751         int i;
1752         lhnetaddress_t tempaddress;
1753         netconn_mempool = Mem_AllocPool("Networking", 0, NULL);
1754         Cmd_AddCommand("net_stats", Net_Stats_f);
1755         Cmd_AddCommand("net_slist", Net_Slist_f);
1756         Cmd_AddCommand("heartbeat", Net_Heartbeat_f);
1757         Cvar_RegisterVariable(&net_messagetimeout);
1758         Cvar_RegisterVariable(&net_messagerejointimeout);
1759         Cvar_RegisterVariable(&net_connecttimeout);
1760         Cvar_RegisterVariable(&cl_netlocalping);
1761         Cvar_RegisterVariable(&cl_netpacketloss);
1762         Cvar_RegisterVariable(&hostname);
1763         Cvar_RegisterVariable(&developer_networking);
1764         Cvar_RegisterVariable(&cl_netport);
1765         Cvar_RegisterVariable(&sv_netport);
1766         Cvar_RegisterVariable(&net_address);
1767         //Cvar_RegisterVariable(&net_address_ipv6);
1768         Cvar_RegisterVariable(&sv_public);
1769         Cvar_RegisterVariable(&sv_heartbeatperiod);
1770         for (i = 0;sv_masters[i].name;i++)
1771                 Cvar_RegisterVariable(&sv_masters[i]);
1772 // 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.
1773         if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
1774         {
1775                 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
1776                 {
1777                         Con_Printf("-ip option used, setting net_address to \"%s\"\n");
1778                         Cvar_SetQuick(&net_address, com_argv[i + 1]);
1779                 }
1780                 else
1781                         Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
1782         }
1783 // 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
1784         if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
1785         {
1786                 i = atoi(com_argv[i + 1]);
1787                 if (i >= 0 && i < 65536)
1788                 {
1789                         Con_Printf("-port option used, setting port cvar to %i\n", i);
1790                         Cvar_SetValueQuick(&sv_netport, i);
1791                 }
1792                 else
1793                         Con_Printf("-port option used, but %i is not a valid port number\n", i);
1794         }
1795         cl_numsockets = 0;
1796         sv_numsockets = 0;
1797         SZ_Alloc(&net_message, NET_MAXMESSAGE, "net_message");
1798         LHNET_Init();
1799 }
1800
1801 void NetConn_Shutdown(void)
1802 {
1803         NetConn_CloseClientPorts();
1804         NetConn_CloseServerPorts();
1805         LHNET_Shutdown();
1806 }
1807