2 Copyright (C) 1996-1997 Id Software, Inc.
3 Copyright (C) 2002 Mathieu Olivier
4 Copyright (C) 2003 Forest Hale
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.
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.
15 See the GNU General Public License for more details.
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.
26 #define MASTER_PORT 27950
28 cvar_t sv_public = {0, "sv_public", "0"};
29 static cvar_t sv_heartbeatperiod = {CVAR_SAVE, "sv_heartbeatperiod", "180"};
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 [] =
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
44 static double nextheartbeattime = 0;
46 sizebuf_t net_message;
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"};
54 cvar_t cl_netlocalping = {0, "cl_netlocalping","0"};
55 static cvar_t cl_netpacketloss = {0, "cl_netpacketloss","0"};
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;
65 static int unreliableMessagesSent = 0;
66 static int unreliableMessagesReceived = 0;
67 static int reliableMessagesSent = 0;
68 static int reliableMessagesReceived = 0;
70 double masterquerytime = -1000;
71 int masterquerycount = 0;
72 int masterreplycount = 0;
73 int serverquerycount = 0;
74 int serverreplycount = 0;
76 static qbyte sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
77 static qbyte readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
80 lhnetsocket_t *cl_sockets[16];
82 lhnetsocket_t *sv_sockets[16];
84 netconn_t *netconn_list = NULL;
85 mempool_t *netconn_mempool = NULL;
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]"};
92 // HostCache interface
93 hostcache_mask_t hostcache_andmasks[HOSTCACHE_ANDMASKCOUNT];
94 hostcache_mask_t hostcache_ormasks[HOSTCACHE_ORMASKCOUNT];
96 hostcache_infofield_t hostcache_sortbyfield;
97 qboolean hostcache_sortdescending;
99 int hostcache_viewcount = 0;
100 hostcache_t *hostcache_viewset[HOSTCACHE_VIEWCACHESIZE];
102 int hostcache_cachecount;
103 hostcache_t hostcache_cache[HOSTCACHE_TOTALSIZE];
105 qboolean hostcache_consoleoutput;
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 )
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;
119 // we suppose hostcache_viewcount to be valid, ie > 0
120 static void _HostCache_ViewSet_Remove( int index )
122 for( --hostcache_viewcount; index < hostcache_viewcount; index++ )
123 hostcache_viewset[index] = hostcache_viewset[index + 1];
126 // returns true if A should be inserted before B
127 static qboolean _HostCache_SortTest( hostcache_t *A, hostcache_t *B )
129 int result = 0; // > 0 if for numbers A > B and for text if A < B
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 );
150 if( hostcache_sortdescending )
155 static qboolean _hc_testint( int A, hostcache_maskop_t op, int B )
157 if( op == HCMO_LESS )
159 else if( op == HCMO_LESSEQUAL )
161 else if( op == HCMO_EQUAL )
163 else if( op == HCMO_GREATER )
165 else if( op == HCMO_NOTEQUAL )
167 else // HCMO_GREATEREQUAL
171 static qboolean _hc_teststr( const char *A, hostcache_maskop_t op, const char *B )
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;
191 static qboolean _HostCache_TestMask( hostcache_mask_t *mask, hostcache_info_t *info )
193 if( !_hc_testint( info->ping, mask->tests[HCIF_PING], mask->info.ping ) )
195 if( !_hc_testint( info->maxplayers, mask->tests[HCIF_MAXPLAYERS], mask->info.maxplayers ) )
197 if( !_hc_testint( info->numplayers, mask->tests[HCIF_NUMPLAYERS], mask->info.numplayers ) )
199 if( !_hc_testint( info->protocol, mask->tests[HCIF_PROTOCOL], mask->info.protocol ))
201 if( *mask->info.cname
202 && !_hc_teststr( info->cname, mask->tests[HCIF_CNAME], mask->info.cname ) )
205 && !_hc_teststr( info->game, mask->tests[HCIF_GAME], mask->info.game ) )
208 && !_hc_teststr( info->mod, mask->tests[HCIF_MOD], mask->info.mod ) )
211 && !_hc_teststr( info->map, mask->tests[HCIF_MAP], mask->info.map ) )
214 && !_hc_teststr( info->name, mask->tests[HCIF_NAME], mask->info.name ) )
219 static void _HostCache_Insert( hostcache_t *entry )
222 if( hostcache_viewcount == HOSTCACHE_VIEWCACHESIZE )
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 ) )
229 for( start = 0 ; hostcache_ormasks[start].active && start < HOSTCACHE_ORMASKCOUNT ; start++ )
230 if( _HostCache_TestMask( &hostcache_ormasks[start], &entry->info ) )
232 if( start == HOSTCACHE_ORMASKCOUNT || (start > 0 && !hostcache_ormasks[start].active) )
235 if( !hostcache_viewcount ) {
236 _HostCache_ViewSet_InsertBefore( 0, entry );
239 // ok, insert it, we just need to find out where exactly:
242 // check whether to insert it as new first item
243 if( _HostCache_SortTest( entry, hostcache_viewset[0] ) ) {
244 _HostCache_ViewSet_InsertBefore( 0, entry );
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 );
252 end = hostcache_viewcount - 1;
253 while( end > start + 1 )
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
261 // the item has to be in the lower half
264 _HostCache_ViewSet_InsertBefore( start + 1, entry );
267 static void _HostCache_Remove( hostcache_t *entry )
270 for( i = 0; i < hostcache_viewcount; i++ )
272 if (hostcache_viewset[i] == entry)
274 _HostCache_ViewSet_Remove(i);
280 void HostCache_RebuildViewSet(void)
284 hostcache_viewcount = 0;
285 for( i = 0 ; i < hostcache_cachecount ; i++ )
286 if( hostcache_cache[i].finished )
287 _HostCache_Insert( &hostcache_cache[i] );
290 void HostCache_ResetMasks(void)
292 memset( &hostcache_andmasks, 0, sizeof( hostcache_andmasks ) );
293 memset( &hostcache_ormasks, 0, sizeof( hostcache_ormasks ) );
297 static void _HostCache_Test(void)
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++;
312 void HostCache_QueryList(void)
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();
329 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
331 int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
335 if (cl_netpacketloss.integer)
336 for (i = 0;i < cl_numsockets;i++)
337 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
339 if (developer_networking.integer)
341 char addressstring[128], addressstring2[128];
342 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
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);
350 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
355 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
359 if (cl_netpacketloss.integer)
360 for (i = 0;i < cl_numsockets;i++)
361 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
363 ret = LHNET_Write(mysocket, data, length, peeraddress);
364 if (developer_networking.integer)
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);
375 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
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);
381 int NetConn_SendReliableMessage(netconn_t *conn, sizebuf_t *data)
383 unsigned int packetLen;
384 unsigned int dataLen;
386 unsigned int *header;
389 if (data->cursize == 0)
390 Sys_Error("Datagram_SendMessage: zero length message\n");
392 if (data->cursize > (int)sizeof(conn->sendMessage))
393 Sys_Error("Datagram_SendMessage: message too big (%u > %u)\n", data->cursize, sizeof(conn->sendMessage));
395 if (conn->canSend == false)
396 Sys_Error("SendMessage: called with canSend == false\n");
399 memcpy(conn->sendMessage, data->data, data->cursize);
400 conn->sendMessageLength = data->cursize;
402 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
404 dataLen = conn->sendMessageLength;
409 dataLen = MAX_PACKETFRAGMENT;
413 packetLen = NET_HEADERSIZE + dataLen;
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);
420 conn->sendSequence++;
421 conn->canSend = false;
423 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
426 conn->lastSendTime = realtime;
428 reliableMessagesSent++;
432 static void NetConn_SendMessageNext(netconn_t *conn)
434 unsigned int packetLen;
435 unsigned int dataLen;
437 unsigned int *header;
439 if (conn->sendMessageLength && !conn->canSend && conn->sendNext)
441 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
443 dataLen = conn->sendMessageLength;
448 dataLen = MAX_PACKETFRAGMENT;
452 packetLen = NET_HEADERSIZE + dataLen;
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);
459 conn->sendSequence++;
460 conn->sendNext = false;
462 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
465 conn->lastSendTime = realtime;
470 static void NetConn_ReSendMessage(netconn_t *conn)
472 unsigned int packetLen;
473 unsigned int dataLen;
475 unsigned int *header;
477 if (conn->sendMessageLength && !conn->canSend && (realtime - conn->lastSendTime) > 1.0)
479 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
481 dataLen = conn->sendMessageLength;
486 dataLen = MAX_PACKETFRAGMENT;
490 packetLen = NET_HEADERSIZE + dataLen;
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);
497 conn->sendNext = false;
499 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
502 conn->lastSendTime = realtime;
507 qboolean NetConn_CanSendMessage(netconn_t *conn)
509 return conn->canSend;
512 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data)
517 packetLen = NET_HEADERSIZE + data->cursize;
520 if (data->cursize == 0)
521 Sys_Error("Datagram_SendUnreliableMessage: zero length message\n");
523 if (packetLen > (int)sizeof(sendbuffer))
524 Sys_Error("Datagram_SendUnreliableMessage: message too big %u\n", data->cursize);
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);
532 conn->unreliableSendSequence++;
534 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
538 unreliableMessagesSent++;
542 void NetConn_CloseClientPorts(void)
544 for (;cl_numsockets > 0;cl_numsockets--)
545 if (cl_sockets[cl_numsockets - 1])
546 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
549 void NetConn_OpenClientPort(const char *addressstring, int defaultport)
551 lhnetaddress_t address;
553 char addressstring2[1024];
554 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
556 if ((s = LHNET_OpenSocket_Connectionless(&address)))
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);
564 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
565 Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
569 Con_Printf("Client unable to parse address %s\n", addressstring);
572 void NetConn_OpenClientPorts(void)
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);
585 void NetConn_CloseServerPorts(void)
587 for (;sv_numsockets > 0;sv_numsockets--)
588 if (sv_sockets[sv_numsockets - 1])
589 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
592 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
594 lhnetaddress_t address;
596 char addressstring2[1024];
597 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
599 if ((s = LHNET_OpenSocket_Connectionless(&address)))
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);
607 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
608 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
612 Con_Printf("Server unable to parse address %s\n", addressstring);
615 void NetConn_OpenServerPorts(int opennetports)
618 NetConn_CloseServerPorts();
619 port = bound(0, sv_netport.integer, 65535);
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);
629 NetConn_OpenServerPort(net_address.string, port);
630 //NetConn_OpenServerPort(net_address_ipv6.string, port);
632 if (sv_numsockets == 0)
633 Host_Error("NetConn_OpenServerPorts: unable to open any ports!\n");
636 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
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];
645 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
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];
654 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
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;
671 void NetConn_Close(netconn_t *conn)
674 // remove connection from list
675 if (conn == netconn_list)
676 netconn_list = conn->next;
679 for (c = netconn_list;c;c = c->next)
683 c->next = conn->next;
687 // not found in list, we'll avoid crashing here...
695 static int clientport = -1;
696 static int clientport2 = -1;
697 static int hostport = -1;
698 static void NetConn_UpdateServerStuff(void)
700 if (cls.state != ca_dedicated)
702 if (clientport2 != cl_netport.integer)
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");
708 if (cls.state == ca_disconnected && clientport != clientport2)
710 clientport = clientport2;
711 NetConn_CloseClientPorts();
713 if (cl_numsockets == 0)
714 NetConn_OpenClientPorts();
717 if (hostport != sv_netport.integer)
719 hostport = sv_netport.integer;
721 Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
725 int NetConn_ReceivedMessage(netconn_t *conn, qbyte *data, int length)
729 unsigned int sequence;
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))
739 sequence = BigLong(((int *)data)[1]);
743 if (flags & NETFLAG_UNRELIABLE)
745 if (sequence >= conn->unreliableReceiveSequence)
747 if (sequence > conn->unreliableReceiveSequence)
749 count = sequence - conn->unreliableReceiveSequence;
750 droppedDatagrams += count;
751 Con_DPrintf("Dropped %u datagram(s)\n", count);
753 conn->unreliableReceiveSequence = sequence + 1;
754 conn->lastMessageTime = realtime;
755 conn->timeout = realtime + net_messagetimeout.value;
756 unreliableMessagesReceived++;
759 SZ_Clear(&net_message);
760 SZ_Write(&net_message, data, length);
766 Con_DPrint("Got a stale datagram\n");
769 else if (flags & NETFLAG_ACK)
771 if (sequence == (conn->sendSequence - 1))
773 if (sequence == 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)
783 memcpy(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
784 conn->sendNext = true;
785 NetConn_SendMessageNext(conn);
789 conn->sendMessageLength = 0;
790 conn->canSend = true;
794 Con_DPrint("Duplicate ACK received\n");
797 Con_DPrint("Stale ACK received\n");
800 else if (flags & NETFLAG_DATA)
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)
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)
815 reliableMessagesReceived++;
816 length = conn->receiveMessageLength;
817 conn->receiveMessageLength = 0;
820 SZ_Clear(&net_message);
821 SZ_Write(&net_message, conn->receiveMessage, length);
828 receivedDuplicateCount++;
836 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
838 cls.connect_trying = false;
839 M_Update_Return_Reason("");
840 // the connection request succeeded, stop current connection and set up a new connection
842 cls.netcon = NetConn_Open(mysocket, peeraddress);
843 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
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
852 int NetConn_IsLocalGame(void)
854 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
859 int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
862 lhnetaddress_t svaddress;
864 char *string, addressstring2[128], cname[128], ipstring[32];
865 char stringbuf[16384];
867 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
869 // received a command string - strip off the packaging and put it
870 // into our string buffer with NULL termination
873 length = min(length, (int)sizeof(stringbuf) - 1);
874 memcpy(stringbuf, data, length);
875 stringbuf[length] = 0;
878 if (developer.integer)
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);
885 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
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);
893 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
895 M_Update_Return_Reason("Accepted");
896 NetConn_ConnectionEstablished(mysocket, peeraddress);
899 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
901 char rejectreason[32];
902 cls.connect_trying = false;
904 length = max(length - 7, (int)sizeof(rejectreason) - 1);
905 memcpy(rejectreason, string, length);
906 rejectreason[length] = 0;
907 M_Update_Return_Reason(rejectreason);
910 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
912 hostcache_info_t *info;
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 ) )
923 if( n == hostcache_cachecount )
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;
935 if (info->ping == 100000)
938 pingtime = (int)((realtime - hostcache_cache[n].querytime) * 1000.0);
939 pingtime = bound(0, pingtime, 9999);
941 info->ping = pingtime;
943 // legacy/old stuff move it to the menu ASAP
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
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;
956 else if (pingtime >= 200)
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;
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;
974 if (!strncmp(string, "getserversResponse\\", 19) && hostcache_cachecount < HOSTCACHE_TOTALSIZE)
976 // Extract the IP addresses
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)
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 )
993 LHNETADDRESS_FromString(&svaddress, ipstring, 0);
994 NetConn_WriteString(mysocket, "\377\377\377\377getinfo", &svaddress);
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);
1005 ++hostcache_cachecount;
1007 // move on to next address in packet
1014 if (!strncmp(string, "ping", 4))
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);
1021 if (!strncmp(string, "ack", 3))
1024 // we may not have liked the packet, but it was a command packet, so
1025 // we're done processing this packet now
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)
1034 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1038 if (developer.integer)
1039 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1040 if (cls.connect_trying)
1042 lhnetaddress_t clientportaddress;
1043 clientportaddress = *peeraddress;
1046 unsigned int port = (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
1049 LHNETADDRESS_SetPort(&clientportaddress, port);
1051 M_Update_Return_Reason("Accepted");
1052 NetConn_ConnectionEstablished(mysocket, &clientportaddress);
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);
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)
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
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))
1077 if (n == hostCacheCount && hostCacheCount < HOSTCACHESIZE)
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();
1086 if (c != NET_PROTOCOL_VERSION)
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));
1092 strlcpy (hostcache[n].cname, cname, sizeof (hostcache[n].cname));
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);
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);
1110 // we may not have liked the packet, but it was a valid control
1111 // packet, so we're done processing this packet now
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();
1120 void NetConn_ClientFrame(void)
1123 lhnetaddress_t peeraddress;
1125 NetConn_UpdateServerStuff();
1126 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
1128 if (cls.connect_remainingtries == 0)
1130 cls.connect_trying = false;
1131 M_Update_Return_Reason("Connect: Failed");
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);
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)
1154 Con_Print("Connection timed out\n");
1156 Host_ShutdownServer (false);
1158 for (conn = netconn_list;conn;conn = conn->next)
1159 NetConn_ReSendMessage(conn);
1162 #define MAX_CHALLENGES 128
1165 lhnetaddress_t address;
1169 challenge[MAX_CHALLENGES];
1171 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
1175 for (i = 0;i < bufferlength - 1;i++)
1179 c = rand () % (127 - 33) + 33;
1180 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
1186 int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
1188 int i, n, ret, clientnum, responselength, best;
1192 char *s, *string, response[512], addressstring2[128], stringbuf[16384];
1196 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1198 // received a command string - strip off the packaging and put it
1199 // into our string buffer with NULL termination
1202 length = min(length, (int)sizeof(stringbuf) - 1);
1203 memcpy(stringbuf, data, length);
1204 stringbuf[length] = 0;
1207 if (developer.integer)
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);
1214 if (length >= 12 && !memcmp(string, "getchallenge", 12))
1216 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
1218 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
1220 if (besttime > challenge[i].time)
1221 besttime = challenge[best = i].time;
1223 // if we did not find an exact match, choose the oldest and
1224 // update address and string
1225 if (i == MAX_CHALLENGES)
1228 challenge[i].address = *peeraddress;
1229 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
1231 challenge[i].time = realtime;
1232 // send the challenge
1233 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
1236 if (length > 8 && !memcmp(string, "connect\\", 8))
1240 if ((s = SearchInfostring(string, "challenge")))
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))
1246 if (i < MAX_CHALLENGES)
1248 // check engine protocol
1249 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
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);
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)
1261 if (clientnum < svs.maxclients)
1263 // duplicate connection request
1264 if (realtime - client->connecttime < 2.0)
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);
1272 // only kick if old connection seems dead
1273 if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1275 // kick off connection and await retry
1276 client->deadsocket = true;
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)
1285 if (clientnum < svs.maxclients)
1287 // prepare the client struct
1288 if ((conn = NetConn_Open(mysocket, peeraddress)))
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);
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);
1313 if (length >= 7 && !memcmp(string, "getinfo", 7))
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)
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)
1330 if (developer.integer)
1331 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
1332 NetConn_WriteString(mysocket, response, peeraddress);
1337 if (!strncmp(string, "ping", 4))
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);
1344 if (!strncmp(string, "ack", 3))
1347 // we may not have liked the packet, but it was a command packet, so
1348 // we're done processing this packet now
1351 // LordHavoc: disabled netquake control packet support in server
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)
1361 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1365 //if (developer.integer)
1366 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
1367 if (length >= (int)strlen("QUAKE") + 1 + 1)
1369 if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION)
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);
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)
1388 if (clientnum < svs.maxclients)
1390 // duplicate connection request
1391 if (realtime - client->connecttime < 2.0)
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);
1406 else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
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;
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)
1420 if (clientnum < svs.maxclients && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
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);
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);
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"))
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);
1482 case CCREQ_PLAYER_INFO:
1483 if (developer.integer)
1484 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
1487 int playerNumber, activeNumber, clientNumber;
1490 playerNumber = MSG_ReadByte();
1492 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
1493 if (client->active && ++activeNumber == playerNumber)
1495 if (clientNumber != svs.maxclients)
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);
1513 case CCREQ_RULE_INFO:
1514 if (developer.integer)
1515 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
1521 // find the search start location
1522 prevCvarName = MSG_ReadString();
1523 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
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);
1532 MSG_WriteString(&net_message, var->name);
1533 MSG_WriteString(&net_message, var->string);
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);
1544 // we may not have liked the packet, but it was a valid control
1545 // packet, so we're done processing this packet now
1550 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1552 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1554 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length)) == 2)
1555 SV_ReadClientMessage();
1563 void NetConn_ServerFrame(void)
1566 lhnetaddress_t peeraddress;
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++)
1574 // never timeout loopback connections
1575 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
1577 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
1578 SV_DropClient(false);
1581 for (conn = netconn_list;conn;conn = conn->next)
1582 NetConn_ReSendMessage(conn);
1585 void NetConn_QueryMasters(void)
1589 lhnetaddress_t masteraddress;
1592 if (hostcache_cachecount >= HOSTCACHE_TOTALSIZE)
1595 for (i = 0;i < cl_numsockets;i++)
1602 UDP_Broadcast(UDP_controlSock, "\377\377\377\377getinfo", 11);
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);
1616 // build the getservers
1617 dpsnprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
1620 for (masternum = 0;sv_masters[masternum].name;masternum++)
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])))
1625 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
1630 if (!masterquerycount)
1632 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
1633 M_Update_Return_Reason("No network");
1637 void NetConn_Heartbeat(int priority)
1639 lhnetaddress_t masteraddress;
1641 lhnetsocket_t *mysocket;
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;
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
1652 if (sv_heartbeatperiod.value < 30)
1653 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
1654 if (sv_heartbeatperiod.value > 270)
1655 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
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))
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);
1668 int NetConn_SendToAll(sizebuf_t *data, double blocktime)
1671 qbyte sent[MAX_SCOREBOARD];
1673 memset(sent, 0, sizeof(sent));
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
1680 blocktime += Sys_DoubleTime();
1684 NetConn_ClientFrame();
1685 NetConn_ServerFrame();
1686 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1688 if (host_client->netconnection)
1690 if (NetConn_CanSendMessage(host_client->netconnection))
1693 NetConn_SendReliableMessage(host_client->netconnection, data);
1696 if (!NetConn_CanSendMessage(host_client->netconnection))
1701 while (count && Sys_DoubleTime() < blocktime);
1705 static void Net_Heartbeat_f(void)
1708 NetConn_Heartbeat(2);
1710 Con_Print("No server running, can not heartbeat to master server.\n");
1713 void PrintStats(netconn_t *conn)
1715 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, conn->canSend, conn->sendSequence, conn->receiveSequence);
1718 void Net_Stats_f(void)
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)
1735 void Net_Slist_f(void)
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");
1746 HostCache_QueryList();
1749 void NetConn_Init(void)
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)
1775 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
1777 Con_Printf("-ip option used, setting net_address to \"%s\"\n");
1778 Cvar_SetQuick(&net_address, com_argv[i + 1]);
1781 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
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)
1786 i = atoi(com_argv[i + 1]);
1787 if (i >= 0 && i < 65536)
1789 Con_Printf("-port option used, setting port cvar to %i\n", i);
1790 Cvar_SetValueQuick(&sv_netport, i);
1793 Con_Printf("-port option used, but %i is not a valid port number\n", i);
1797 SZ_Alloc(&net_message, NET_MAXMESSAGE, "net_message");
1801 void NetConn_Shutdown(void)
1803 NetConn_CloseClientPorts();
1804 NetConn_CloseServerPorts();