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
43 static double nextheartbeattime = 0;
45 sizebuf_t net_message;
47 cvar_t net_messagetimeout = {0, "net_messagetimeout","300"};
48 cvar_t net_messagerejointimeout = {0, "net_messagerejointimeout","10"};
49 cvar_t net_connecttimeout = {0, "net_connecttimeout","10"};
50 cvar_t hostname = {CVAR_SAVE, "hostname", "UNNAMED"};
51 cvar_t developer_networking = {0, "developer_networking", "0"};
53 cvar_t cl_netlocalping = {0, "cl_netlocalping","0"};
54 static cvar_t cl_netpacketloss = {0, "cl_netpacketloss","0"};
57 /* statistic counters */
58 static int packetsSent = 0;
59 static int packetsReSent = 0;
60 static int packetsReceived = 0;
61 static int receivedDuplicateCount = 0;
62 static int droppedDatagrams = 0;
64 static int unreliableMessagesSent = 0;
65 static int unreliableMessagesReceived = 0;
66 static int reliableMessagesSent = 0;
67 static int reliableMessagesReceived = 0;
69 double masterquerytime = -1000;
70 int masterquerycount = 0;
71 int masterreplycount = 0;
72 int serverquerycount = 0;
73 int serverreplycount = 0;
75 static qbyte sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
76 static qbyte readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
79 lhnetsocket_t *cl_sockets[16];
81 lhnetsocket_t *sv_sockets[16];
83 netconn_t *netconn_list = NULL;
84 mempool_t *netconn_mempool = NULL;
86 cvar_t cl_netport = {0, "cl_port", "0"};
87 cvar_t sv_netport = {0, "port", "26000"};
88 cvar_t net_address = {0, "net_address", "0.0.0.0"};
89 //cvar_t net_netaddress_ipv6 = {0, "net_address_ipv6", "[0:0:0:0:0:0:0:0]"};
91 // HostCache interface
92 hostcache_mask_t hostcache_andmasks[HOSTCACHE_ANDMASKCOUNT];
93 hostcache_mask_t hostcache_ormasks[HOSTCACHE_ORMASKCOUNT];
95 hostcache_infofield_t hostcache_sortbyfield;
96 qboolean hostcache_sortdescending;
98 int hostcache_viewcount = 0;
99 hostcache_t *hostcache_viewset[HOSTCACHE_VIEWCACHESIZE];
101 int hostcache_cachecount;
102 hostcache_t hostcache_cache[HOSTCACHE_TOTALSIZE];
104 qboolean hostcache_consoleoutput;
106 // helper function to insert a value into the viewset
107 // spare entries will be removed
108 static void _HostCache_ViewSet_InsertBefore( int index, hostcache_t *entry )
111 if( ++hostcache_viewcount > HOSTCACHE_VIEWCACHESIZE )
112 hostcache_viewcount = HOSTCACHE_VIEWCACHESIZE;
113 for( i = hostcache_viewcount - 1; i > index; i-- )
114 hostcache_viewset[i] = hostcache_viewset[i - 1];
115 hostcache_viewset[index] = entry;
118 // we suppose hostcache_viewcount to be valid, ie > 0
119 static void _HostCache_ViewSet_Remove( int index )
121 for( --hostcache_viewcount; index < hostcache_viewcount; index++ )
122 hostcache_viewset[index] = hostcache_viewset[index + 1];
125 // returns true if A should be inserted before B
126 static qboolean _HostCache_SortTest( hostcache_t *A, hostcache_t *B )
128 int result; // > 0 if for numbers A > B and for text if A < B
130 if( hostcache_sortbyfield == HCIF_PING )
131 result = A->info.ping - B->info.ping;
132 else if( hostcache_sortbyfield == HCIF_MAXPLAYERS )
133 result = A->info.maxplayers - B->info.maxplayers;
134 else if( hostcache_sortbyfield == HCIF_NUMPLAYERS )
135 result = A->info.numplayers - B->info.numplayers;
136 else if( hostcache_sortbyfield == HCIF_PROTOCOL )
137 result = A->info.protocol - B->info.protocol;
138 else if( hostcache_sortbyfield == HCIF_CNAME )
139 result = strcmp( B->info.cname, A->info.cname );
140 else if( hostcache_sortbyfield == HCIF_GAME )
141 result = strcmp( B->info.game, A->info.game );
142 else if( hostcache_sortbyfield == HCIF_MAP )
143 result = strcmp( B->info.map, A->info.map );
144 else if( hostcache_sortbyfield == HCIF_MOD )
145 result = strcmp( B->info.mod, A->info.mod );
146 else if( hostcache_sortbyfield == HCIF_NAME )
147 result = strcmp( B->info.name, A->info.name );
149 if( hostcache_sortdescending )
154 static qboolean _hc_testint( int A, hostcache_maskop_t op, int B )
156 if( op == HCMO_LESS )
158 else if( op == HCMO_LESSEQUAL )
160 else if( op == HCMO_EQUAL )
162 else if( op == HCMO_GREATER )
164 else if( op == HCMO_NOTEQUAL )
166 else // HCMO_GREATEREQUAL
170 static qboolean _hc_teststr( const char *A, hostcache_maskop_t op, const char *B )
172 if( op == HCMO_CONTAINS ) // A info B mask
173 return *B && !!strstr( A, B ); // we want a real bool
174 else if( op == HCMO_NOTCONTAIN )
175 return !*B || !strstr( A, B );
176 else if( op == HCMO_LESS )
177 return strcmp( A, B ) < 0;
178 else if( op == HCMO_LESSEQUAL )
179 return strcmp( A, B ) <= 0;
180 else if( op == HCMO_EQUAL )
181 return strcmp( A, B ) == 0;
182 else if( op == HCMO_GREATER )
183 return strcmp( A, B ) > 0;
184 else if( op == HCMO_NOTEQUAL )
185 return strcmp( A, B ) != 0;
186 else // HCMO_GREATEREQUAL
187 return strcmp( A, B ) >= 0;
190 static qboolean _HostCache_TestMask( hostcache_mask_t *mask, hostcache_info_t *info )
192 if( !_hc_testint( info->ping, mask->tests[HCIF_PING], mask->info.ping ) )
194 if( !_hc_testint( info->maxplayers, mask->tests[HCIF_MAXPLAYERS], mask->info.maxplayers ) )
196 if( !_hc_testint( info->numplayers, mask->tests[HCIF_NUMPLAYERS], mask->info.numplayers ) )
198 if( !_hc_testint( info->protocol, mask->tests[HCIF_PROTOCOL], mask->info.protocol ))
200 if( *mask->info.cname
201 && !_hc_teststr( info->cname, mask->tests[HCIF_CNAME], mask->info.cname ) )
204 && !_hc_teststr( info->game, mask->tests[HCIF_GAME], mask->info.game ) )
207 && !_hc_teststr( info->mod, mask->tests[HCIF_MOD], mask->info.mod ) )
210 && !_hc_teststr( info->map, mask->tests[HCIF_MAP], mask->info.map ) )
213 && !_hc_teststr( info->name, mask->tests[HCIF_NAME], mask->info.name ) )
218 static void _HostCache_Insert( hostcache_t *entry )
221 if( hostcache_viewcount == HOSTCACHE_VIEWCACHESIZE )
223 // now check whether it passes through the masks mask
224 for( start = 0 ; hostcache_andmasks[start].active && start < HOSTCACHE_ANDMASKCOUNT ; start++ )
225 if( !_HostCache_TestMask( &hostcache_andmasks[start], &entry->info ) )
228 for( start = 0 ; hostcache_ormasks[start].active && start < HOSTCACHE_ORMASKCOUNT ; start++ )
229 if( _HostCache_TestMask( &hostcache_ormasks[start], &entry->info ) )
231 if( start == HOSTCACHE_ORMASKCOUNT || (start > 0 && !hostcache_ormasks[start].active) )
234 if( !hostcache_viewcount ) {
235 _HostCache_ViewSet_InsertBefore( 0, entry );
238 // ok, insert it, we just need to find out where exactly:
241 // check whether to insert it as new first item
242 if( _HostCache_SortTest( entry, hostcache_viewset[0] ) ) {
243 _HostCache_ViewSet_InsertBefore( 0, entry );
245 } // check whether to insert it as new last item
246 else if( !_HostCache_SortTest( entry, hostcache_viewset[hostcache_viewcount - 1] ) ) {
247 _HostCache_ViewSet_InsertBefore( hostcache_viewcount, entry );
251 end = hostcache_viewcount - 1;
252 while( end > start + 1 )
254 mid = (start + end) / 2;
255 // test the item that lies in the middle between start and end
256 if( _HostCache_SortTest( entry, hostcache_viewset[mid] ) )
257 // the item has to be in the upper half
260 // the item has to be in the lower half
263 _HostCache_ViewSet_InsertBefore( start + 1, entry );
266 static void _HostCache_Remove( hostcache_t *entry )
269 for( i = 0; i < hostcache_viewcount; i++ )
271 if (hostcache_viewset[i] == entry)
273 _HostCache_ViewSet_Remove(i);
279 void HostCache_RebuildViewSet(void)
283 hostcache_viewcount = 0;
284 for( i = 0 ; i < hostcache_cachecount ; i++ )
285 if( hostcache_cache[i].finished )
286 _HostCache_Insert( &hostcache_cache[i] );
289 void HostCache_ResetMasks(void)
291 memset( &hostcache_andmasks, 0, sizeof( hostcache_andmasks ) );
292 memset( &hostcache_ormasks, 0, sizeof( hostcache_ormasks ) );
296 static void _HostCache_Test(void)
299 for( i = 0 ; i < 1024 ; i++ ) {
300 memset( &hostcache_cache[hostcache_cachecount], 0, sizeof( hostcache_t ) );
301 hostcache_cache[hostcache_cachecount].info.ping = rand() % 450 + 250;
302 snprintf( hostcache_cache[hostcache_cachecount].info.name, 128, "Black's HostCache Test %i", i );
303 hostcache_cache[hostcache_cachecount].finished = true;
304 sprintf( hostcache_cache[hostcache_cachecount].line1, "%i %s", hostcache_cache[hostcache_cachecount].info.ping, hostcache_cache[hostcache_cachecount].info.name );
305 _HostCache_Insert( &hostcache_cache[hostcache_cachecount] );
306 hostcache_cachecount++;
311 void HostCache_QueryList(void)
313 masterquerytime = realtime;
314 masterquerycount = 0;
315 masterreplycount = 0;
316 serverquerycount = 0;
317 serverreplycount = 0;
318 hostcache_cachecount = 0;
319 hostcache_viewcount = 0;
320 hostcache_consoleoutput = false;
321 NetConn_QueryMasters();
328 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
330 int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
332 if (cl_netpacketloss.integer)
333 for (i = 0;i < cl_numsockets;i++)
334 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
336 if (developer_networking.integer && length != 0)
338 char addressstring[128], addressstring2[128];
339 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
342 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
343 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", mysocket, addressstring, data, maxlength, peeraddress, length, addressstring2);
344 Com_HexDumpToConsole(data, length);
347 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
352 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
356 if (cl_netpacketloss.integer)
357 for (i = 0;i < cl_numsockets;i++)
358 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
360 ret = LHNET_Write(mysocket, data, length, peeraddress);
361 if (developer_networking.integer)
363 char addressstring[128], addressstring2[128];
364 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
365 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
366 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", mysocket, addressstring, data, length, peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
367 Com_HexDumpToConsole(data, length);
372 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
374 // note this does not include the trailing NULL because we add that in the parser
375 return NetConn_Write(mysocket, string, strlen(string), peeraddress);
378 int NetConn_SendReliableMessage(netconn_t *conn, sizebuf_t *data)
380 unsigned int packetLen;
381 unsigned int dataLen;
383 unsigned int *header;
386 if (data->cursize == 0)
387 Sys_Error("Datagram_SendMessage: zero length message\n");
389 if (data->cursize > (int)sizeof(conn->sendMessage))
390 Sys_Error("Datagram_SendMessage: message too big (%u > %u)\n", data->cursize, sizeof(conn->sendMessage));
392 if (conn->canSend == false)
393 Sys_Error("SendMessage: called with canSend == false\n");
396 memcpy(conn->sendMessage, data->data, data->cursize);
397 conn->sendMessageLength = data->cursize;
399 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
401 dataLen = conn->sendMessageLength;
406 dataLen = MAX_PACKETFRAGMENT;
410 packetLen = NET_HEADERSIZE + dataLen;
412 header = (void *)sendbuffer;
413 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
414 header[1] = BigLong(conn->sendSequence);
415 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
417 conn->sendSequence++;
418 conn->canSend = false;
420 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
423 conn->lastSendTime = realtime;
425 reliableMessagesSent++;
429 static void NetConn_SendMessageNext(netconn_t *conn)
431 unsigned int packetLen;
432 unsigned int dataLen;
434 unsigned int *header;
436 if (conn->sendMessageLength && !conn->canSend && conn->sendNext)
438 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
440 dataLen = conn->sendMessageLength;
445 dataLen = MAX_PACKETFRAGMENT;
449 packetLen = NET_HEADERSIZE + dataLen;
451 header = (void *)sendbuffer;
452 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
453 header[1] = BigLong(conn->sendSequence);
454 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
456 conn->sendSequence++;
457 conn->sendNext = false;
459 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
462 conn->lastSendTime = realtime;
467 static void NetConn_ReSendMessage(netconn_t *conn)
469 unsigned int packetLen;
470 unsigned int dataLen;
472 unsigned int *header;
474 if (conn->sendMessageLength && !conn->canSend && (realtime - conn->lastSendTime) > 1.0)
476 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
478 dataLen = conn->sendMessageLength;
483 dataLen = MAX_PACKETFRAGMENT;
487 packetLen = NET_HEADERSIZE + dataLen;
489 header = (void *)sendbuffer;
490 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
491 header[1] = BigLong(conn->sendSequence - 1);
492 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
494 conn->sendNext = false;
496 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
499 conn->lastSendTime = realtime;
504 qboolean NetConn_CanSendMessage(netconn_t *conn)
506 return conn->canSend;
509 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data)
514 packetLen = NET_HEADERSIZE + data->cursize;
517 if (data->cursize == 0)
518 Sys_Error("Datagram_SendUnreliableMessage: zero length message\n");
520 if (packetLen > (int)sizeof(sendbuffer))
521 Sys_Error("Datagram_SendUnreliableMessage: message too big %u\n", data->cursize);
524 header = (void *)sendbuffer;
525 header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
526 header[1] = BigLong(conn->unreliableSendSequence);
527 memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
529 conn->unreliableSendSequence++;
531 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
535 unreliableMessagesSent++;
539 void NetConn_CloseClientPorts(void)
541 for (;cl_numsockets > 0;cl_numsockets--)
542 if (cl_sockets[cl_numsockets - 1])
543 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
546 void NetConn_OpenClientPort(const char *addressstring, int defaultport)
548 lhnetaddress_t address;
550 char addressstring2[1024];
551 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
553 if ((s = LHNET_OpenSocket_Connectionless(&address)))
555 cl_sockets[cl_numsockets++] = s;
556 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
557 Con_Printf("Client opened a socket on address %s\n", addressstring2);
561 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
562 Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
566 Con_Printf("Client unable to parse address %s\n", addressstring);
569 void NetConn_OpenClientPorts(void)
572 NetConn_CloseClientPorts();
573 port = bound(0, cl_netport.integer, 65535);
574 if (cl_netport.integer != port)
575 Cvar_SetValueQuick(&cl_netport, port);
576 Con_Printf("Client using port %i\n", port);
577 NetConn_OpenClientPort("local:2", 0);
578 NetConn_OpenClientPort(net_address.string, port);
579 //NetConn_OpenClientPort(net_address_ipv6.string, port);
582 void NetConn_CloseServerPorts(void)
584 for (;sv_numsockets > 0;sv_numsockets--)
585 if (sv_sockets[sv_numsockets - 1])
586 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
589 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
591 lhnetaddress_t address;
593 char addressstring2[1024];
594 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
596 if ((s = LHNET_OpenSocket_Connectionless(&address)))
598 sv_sockets[sv_numsockets++] = s;
599 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
600 Con_Printf("Server listening on address %s\n", addressstring2);
604 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
605 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
609 Con_Printf("Server unable to parse address %s\n", addressstring);
612 void NetConn_OpenServerPorts(int opennetports)
615 NetConn_CloseServerPorts();
616 port = bound(0, sv_netport.integer, 65535);
619 Con_Printf("Server using port %i\n", port);
620 if (sv_netport.integer != port)
621 Cvar_SetValueQuick(&sv_netport, port);
622 if (cls.state != ca_dedicated)
623 NetConn_OpenServerPort("local:1", 0);
626 NetConn_OpenServerPort(net_address.string, port);
627 //NetConn_OpenServerPort(net_address_ipv6.string, port);
629 if (sv_numsockets == 0)
630 Host_Error("NetConn_OpenServerPorts: unable to open any ports!\n");
633 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
635 int i, a = LHNETADDRESS_GetAddressType(address);
636 for (i = 0;i < cl_numsockets;i++)
637 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
638 return cl_sockets[i];
642 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
644 int i, a = LHNETADDRESS_GetAddressType(address);
645 for (i = 0;i < sv_numsockets;i++)
646 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
647 return sv_sockets[i];
651 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
654 conn = Mem_Alloc(netconn_mempool, sizeof(*conn));
655 conn->mysocket = mysocket;
656 conn->peeraddress = *peeraddress;
657 conn->canSend = true;
658 conn->lastMessageTime = realtime;
659 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
660 // reduce effectiveness of connection request floods
661 conn->timeout = realtime + net_connecttimeout.value;
662 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
663 conn->next = netconn_list;
668 void NetConn_Close(netconn_t *conn)
671 // remove connection from list
672 if (conn == netconn_list)
673 netconn_list = conn->next;
676 for (c = netconn_list;c;c = c->next)
680 c->next = conn->next;
684 // not found in list, we'll avoid crashing here...
692 static int clientport = -1;
693 static int clientport2 = -1;
694 static int hostport = -1;
695 static void NetConn_UpdateServerStuff(void)
697 if (cls.state != ca_dedicated)
699 if (clientport2 != cl_netport.integer)
701 clientport2 = cl_netport.integer;
702 if (cls.state == ca_connected)
703 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
705 if (cls.state == ca_disconnected && clientport != clientport2)
707 clientport = clientport2;
708 NetConn_CloseClientPorts();
710 if (cl_numsockets == 0)
711 NetConn_OpenClientPorts();
714 if (hostport != sv_netport.integer)
716 hostport = sv_netport.integer;
718 Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
722 int NetConn_ReceivedMessage(netconn_t *conn, qbyte *data, int length)
726 unsigned int sequence;
730 length = BigLong(((int *)data)[0]);
731 flags = length & ~NETFLAG_LENGTH_MASK;
732 length &= NETFLAG_LENGTH_MASK;
733 // control packets were already handled
734 if (!(flags & NETFLAG_CTL))
736 sequence = BigLong(((int *)data)[1]);
740 if (flags & NETFLAG_UNRELIABLE)
742 if (sequence >= conn->unreliableReceiveSequence)
744 if (sequence > conn->unreliableReceiveSequence)
746 count = sequence - conn->unreliableReceiveSequence;
747 droppedDatagrams += count;
748 Con_DPrintf("Dropped %u datagram(s)\n", count);
750 conn->unreliableReceiveSequence = sequence + 1;
751 conn->lastMessageTime = realtime;
752 conn->timeout = realtime + net_messagetimeout.value;
753 unreliableMessagesReceived++;
756 SZ_Clear(&net_message);
757 SZ_Write(&net_message, data, length);
763 Con_DPrint("Got a stale datagram\n");
766 else if (flags & NETFLAG_ACK)
768 if (sequence == (conn->sendSequence - 1))
770 if (sequence == conn->ackSequence)
773 if (conn->ackSequence != conn->sendSequence)
774 Con_DPrint("ack sequencing error\n");
775 conn->lastMessageTime = realtime;
776 conn->timeout = realtime + net_messagetimeout.value;
777 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
778 if (conn->sendMessageLength > 0)
780 memcpy(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
781 conn->sendNext = true;
782 NetConn_SendMessageNext(conn);
786 conn->sendMessageLength = 0;
787 conn->canSend = true;
791 Con_DPrint("Duplicate ACK received\n");
794 Con_DPrint("Stale ACK received\n");
797 else if (flags & NETFLAG_DATA)
799 unsigned int temppacket[2];
800 temppacket[0] = BigLong(8 | NETFLAG_ACK);
801 temppacket[1] = BigLong(sequence);
802 NetConn_Write(conn->mysocket, (qbyte *)temppacket, 8, &conn->peeraddress);
803 if (sequence == conn->receiveSequence)
805 conn->lastMessageTime = realtime;
806 conn->timeout = realtime + net_messagetimeout.value;
807 conn->receiveSequence++;
808 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
809 conn->receiveMessageLength += length;
810 if (flags & NETFLAG_EOM)
812 reliableMessagesReceived++;
813 length = conn->receiveMessageLength;
814 conn->receiveMessageLength = 0;
817 SZ_Clear(&net_message);
818 SZ_Write(&net_message, conn->receiveMessage, length);
825 receivedDuplicateCount++;
833 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
835 cls.connect_trying = false;
836 M_Update_Return_Reason("");
837 // the connection request succeeded, stop current connection and set up a new connection
839 cls.netcon = NetConn_Open(mysocket, peeraddress);
840 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
843 cls.demonum = -1; // not in the demo loop now
844 cls.state = ca_connected;
845 cls.signon = 0; // need all the signon messages before playing
847 SCR_BeginLoadingPlaque();
850 int NetConn_IsLocalGame(void)
852 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
857 int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
860 lhnetaddress_t svaddress;
862 char *string, addressstring2[128], cname[128], ipstring[32];
863 char stringbuf[16384];
865 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
867 // received a command string - strip off the packaging and put it
868 // into our string buffer with NULL termination
871 length = min(length, (int)sizeof(stringbuf) - 1);
872 memcpy(stringbuf, data, length);
873 stringbuf[length] = 0;
876 if (developer.integer)
878 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
879 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
880 Com_HexDumpToConsole(data, length);
883 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
885 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
886 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
887 M_Update_Return_Reason("Got challenge response");
888 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\challenge\\%s", string + 10), peeraddress);
891 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
893 M_Update_Return_Reason("Accepted");
894 NetConn_ConnectionEstablished(mysocket, peeraddress);
897 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
899 char rejectreason[32];
900 cls.connect_trying = false;
902 length = max(length - 7, (int)sizeof(rejectreason) - 1);
903 memcpy(rejectreason, string, length);
904 rejectreason[length] = 0;
905 M_Update_Return_Reason(rejectreason);
908 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
910 hostcache_info_t *info;
915 // hostcache only uses text addresses
916 LHNETADDRESS_ToString(peeraddress, cname, sizeof(cname), true);
917 // search the cache for this server and update it
918 for( n = 0; n < hostcache_cachecount; n++ )
919 if( !strcmp( cname, hostcache_cache[n].info.cname ) )
921 if( n == hostcache_cachecount )
924 info = &hostcache_cache[n].info;
925 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));else info->game[0] = 0;
926 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0] = 0;
927 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0] = 0;
928 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
929 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);else info->protocol = -1;
930 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);else info->numplayers = 0;
931 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);else info->maxplayers = 0;
933 if (info->ping == 100000)
936 pingtime = (int)((realtime - hostcache_cache[n].querytime) * 1000.0);
937 pingtime = bound(0, pingtime, 9999);
939 info->ping = pingtime;
941 // legacy/old stuff move it to the menu ASAP
943 // build description strings for the things users care about
944 snprintf(hostcache_cache[n].line1, sizeof(hostcache_cache[n].line1), "%5d%c%3u/%3u %-65.65s", (int)pingtime, info->protocol != NET_PROTOCOL_VERSION ? '*' : ' ', info->numplayers, info->maxplayers, info->name);
945 snprintf(hostcache_cache[n].line2, sizeof(hostcache_cache[n].line2), "%-21.21s %-19.19s %-17.17s %-20.20s", info->cname, info->game, info->mod, info->map);
946 // if ping is especially high, display it as such
949 // orange numbers (lower block)
950 for (i = 0;i < 5;i++)
951 if (hostcache_cache[n].line1[i] != ' ')
952 hostcache_cache[n].line1[i] += 128;
954 else if (pingtime >= 200)
956 // yellow numbers (in upper block)
957 for (i = 0;i < 5;i++)
958 if (hostcache_cache[n].line1[i] != ' ')
959 hostcache_cache[n].line1[i] -= 30;
961 // if not in the slist menu we should print the server to console
962 if( hostcache_consoleoutput )
963 Con_Printf("%s\n%s\n", hostcache_cache[n].line1, hostcache_cache[n].line2);
964 // and finally, update the view set
965 if( hostcache_cache[n].finished )
966 _HostCache_Remove( &hostcache_cache[n] );
967 _HostCache_Insert( &hostcache_cache[n] );
968 hostcache_cache[n].finished = true;
972 if (!strncmp(string, "getserversResponse\\", 19) && hostcache_cachecount < HOSTCACHE_TOTALSIZE)
974 // Extract the IP addresses
978 if (hostcache_consoleoutput)
979 Con_Print("received server list...\n");
980 while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
984 snprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], (data[5] << 8) | data[6]);
985 if (developer.integer)
986 Con_Printf("Requesting info from server %s\n", ipstring);
987 // ignore the rest of the message if the hostcache is full
988 if( hostcache_cachecount == HOSTCACHE_TOTALSIZE )
991 LHNETADDRESS_FromString(&svaddress, ipstring, 0);
992 NetConn_WriteString(mysocket, "\377\377\377\377getinfo", &svaddress);
994 memset(&hostcache_cache[hostcache_cachecount], 0, sizeof(hostcache_cache[hostcache_cachecount]));
995 // store the data the engine cares about (address and ping)
996 strlcpy (hostcache_cache[hostcache_cachecount].info.cname, ipstring, sizeof (hostcache_cache[hostcache_cachecount].info.cname));
997 hostcache_cache[hostcache_cachecount].info.ping = 100000;
998 hostcache_cache[hostcache_cachecount].querytime = realtime;
999 // if not in the slist menu we should print the server to console
1000 if (hostcache_consoleoutput)
1001 Con_Printf("querying %s\n", ipstring);
1003 ++hostcache_cachecount;
1005 // move on to next address in packet
1012 if (!strncmp(string, "ping", 4))
1014 if (developer.integer)
1015 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1016 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1019 if (!strncmp(string, "ack", 3))
1022 // we may not have liked the packet, but it was a command packet, so
1023 // we're done processing this packet now
1026 // netquake control packets, supported for compatibility only
1027 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1032 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1036 if (developer.integer)
1037 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1038 if (cls.connect_trying)
1040 lhnetaddress_t clientportaddress;
1041 clientportaddress = *peeraddress;
1044 unsigned int port = (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
1047 LHNETADDRESS_SetPort(&clientportaddress, port);
1049 M_Update_Return_Reason("Accepted");
1050 NetConn_ConnectionEstablished(mysocket, &clientportaddress);
1054 if (developer.integer)
1055 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1056 cls.connect_trying = false;
1057 M_Update_Return_Reason(data);
1060 case CCREP_SERVER_INFO:
1061 if (developer.integer)
1062 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1063 if (cls.state != ca_dedicated)
1065 // LordHavoc: because the UDP driver reports 0.0.0.0:26000 as the address
1066 // string we just ignore it and keep the real address
1068 // hostcache only uses text addresses
1069 cname = UDP_AddrToString(readaddr);
1070 // search the cache for this server
1071 for (n = 0; n < hostCacheCount; n++)
1072 if (!strcmp(cname, hostcache[n].cname))
1075 if (n == hostCacheCount && hostCacheCount < HOSTCACHESIZE)
1078 memset(&hostcache[n], 0, sizeof(hostcache[n]));
1079 strlcpy (hostcache[n].name, MSG_ReadString(), sizeof (hostcache[n].name));
1080 strlcpy (hostcache[n].map, MSG_ReadString(), sizeof (hostcache[n].map));
1081 hostcache[n].users = MSG_ReadByte();
1082 hostcache[n].maxusers = MSG_ReadByte();
1084 if (c != NET_PROTOCOL_VERSION)
1086 strlcpy (hostcache[n].cname, hostcache[n].name, sizeof (hostcache[n].cname));
1087 strcpy(hostcache[n].name, "*");
1088 strlcat (hostcache[n].name, hostcache[n].cname, sizeof(hostcache[n].name));
1090 strlcpy (hostcache[n].cname, cname, sizeof (hostcache[n].cname));
1094 case CCREP_PLAYER_INFO:
1095 // we got a CCREP_PLAYER_INFO??
1096 //if (developer.integer)
1097 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1099 case CCREP_RULE_INFO:
1100 // we got a CCREP_RULE_INFO??
1101 //if (developer.integer)
1102 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1108 // we may not have liked the packet, but it was a valid control
1109 // packet, so we're done processing this packet now
1113 if (length >= (int)NET_HEADERSIZE && cls.netcon && mysocket == cls.netcon->mysocket && !LHNETADDRESS_Compare(&cls.netcon->peeraddress, peeraddress) && (ret = NetConn_ReceivedMessage(cls.netcon, data, length)) == 2)
1114 CL_ParseServerMessage();
1118 void NetConn_ClientFrame(void)
1121 lhnetaddress_t peeraddress;
1123 NetConn_UpdateServerStuff();
1124 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
1126 if (cls.connect_remainingtries == 0)
1128 cls.connect_trying = false;
1129 M_Update_Return_Reason("Connect: Failed");
1132 cls.connect_nextsendtime = realtime + 1;
1133 cls.connect_remainingtries--;
1134 // try challenge first (newer server)
1135 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
1136 // then try netquake as a fallback (old server, or netquake)
1137 SZ_Clear(&net_message);
1138 // save space for the header, filled in later
1139 MSG_WriteLong(&net_message, 0);
1140 MSG_WriteByte(&net_message, CCREQ_CONNECT);
1141 MSG_WriteString(&net_message, "QUAKE");
1142 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1143 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1144 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
1145 SZ_Clear(&net_message);
1147 for (i = 0;i < cl_numsockets;i++)
1148 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1149 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
1150 if (cls.netcon && realtime > cls.netcon->timeout)
1152 Con_Print("Connection timed out\n");
1154 Host_ShutdownServer (false);
1156 for (conn = netconn_list;conn;conn = conn->next)
1157 NetConn_ReSendMessage(conn);
1160 #define MAX_CHALLENGES 128
1163 lhnetaddress_t address;
1167 challenge[MAX_CHALLENGES];
1169 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
1173 for (i = 0;i < bufferlength - 1;i++)
1177 c = rand () % (127 - 33) + 33;
1178 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
1184 int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
1186 int i, n, ret, clientnum, responselength, best;
1190 char *s, *string, response[512], addressstring2[128], stringbuf[16384];
1194 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1196 // received a command string - strip off the packaging and put it
1197 // into our string buffer with NULL termination
1200 length = min(length, (int)sizeof(stringbuf) - 1);
1201 memcpy(stringbuf, data, length);
1202 stringbuf[length] = 0;
1205 if (developer.integer)
1207 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1208 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
1209 Com_HexDumpToConsole(data, length);
1212 if (length >= 12 && !memcmp(string, "getchallenge", 12))
1214 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
1216 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
1218 if (besttime > challenge[i].time)
1219 besttime = challenge[best = i].time;
1221 // if we did not find an exact match, choose the oldest and
1222 // update address and string
1223 if (i == MAX_CHALLENGES)
1226 challenge[i].address = *peeraddress;
1227 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
1229 challenge[i].time = realtime;
1230 // send the challenge
1231 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
1234 if (length > 8 && !memcmp(string, "connect\\", 8))
1238 if ((s = SearchInfostring(string, "challenge")))
1240 // validate the challenge
1241 for (i = 0;i < MAX_CHALLENGES;i++)
1242 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1244 if (i < MAX_CHALLENGES)
1246 // check engine protocol
1247 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
1249 if (developer.integer)
1250 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
1251 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
1255 // see if this is a duplicate connection request
1256 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1257 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1259 if (clientnum < svs.maxclients)
1261 // duplicate connection request
1262 if (realtime - client->connecttime < 2.0)
1264 // client is still trying to connect,
1265 // so we send a duplicate reply
1266 if (developer.integer)
1267 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
1268 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1270 // only kick if old connection seems dead
1271 if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1273 // kick off connection and await retry
1274 client->deadsocket = true;
1279 // this is a new client, find a slot
1280 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1281 if (!client->active)
1283 if (clientnum < svs.maxclients)
1285 // prepare the client struct
1286 if ((conn = NetConn_Open(mysocket, peeraddress)))
1288 // allocated connection
1289 LHNETADDRESS_ToString(peeraddress, conn->address, sizeof(conn->address), true);
1290 if (developer.integer)
1291 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
1292 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1293 // now set up the client
1294 SV_ConnectClient(clientnum, conn);
1295 NetConn_Heartbeat(1);
1301 if (developer.integer)
1302 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
1303 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
1311 if (length >= 7 && !memcmp(string, "getinfo", 7))
1313 const char *challenge = NULL;
1314 // If there was a challenge in the getinfo message
1315 if (length > 8 && string[7] == ' ')
1316 challenge = string + 8;
1317 for (i = 0, n = 0;i < svs.maxclients;i++)
1318 if (svs.clients[i].active)
1320 responselength = snprintf(response, sizeof(response), "\377\377\377\377infoResponse\x0A"
1321 "\\gamename\\%s\\modname\\%s\\sv_maxclients\\%d"
1322 "\\clients\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d%s%s",
1323 gamename, com_modname, svs.maxclients, n,
1324 sv.name, hostname.string, NET_PROTOCOL_VERSION, challenge ? "\\challenge\\" : "", challenge ? challenge : "");
1325 // does it fit in the buffer?
1326 if (responselength < (int)sizeof(response))
1328 if (developer.integer)
1329 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
1330 NetConn_WriteString(mysocket, response, peeraddress);
1335 if (!strncmp(string, "ping", 4))
1337 if (developer.integer)
1338 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1339 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1342 if (!strncmp(string, "ack", 3))
1345 // we may not have liked the packet, but it was a command packet, so
1346 // we're done processing this packet now
1349 // LordHavoc: disabled netquake control packet support in server
1353 // netquake control packets, supported for compatibility only
1354 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1359 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1363 //if (developer.integer)
1364 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
1365 if (length >= (int)strlen("QUAKE") + 1 + 1)
1367 if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION)
1369 if (developer.integer)
1370 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
1371 SZ_Clear(&net_message);
1372 // save space for the header, filled in later
1373 MSG_WriteLong(&net_message, 0);
1374 MSG_WriteByte(&net_message, CCREP_REJECT);
1375 MSG_WriteString(&net_message, "Incompatible version.\n");
1376 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1377 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1378 SZ_Clear(&net_message);
1382 // see if this is a duplicate connection request
1383 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1384 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1386 if (clientnum < svs.maxclients)
1388 // duplicate connection request
1389 if (realtime - client->connecttime < 2.0)
1391 // client is still trying to connect,
1392 // so we send a duplicate reply
1393 if (developer.integer)
1394 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
1395 SZ_Clear(&net_message);
1396 // save space for the header, filled in later
1397 MSG_WriteLong(&net_message, 0);
1398 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1399 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
1400 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1401 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1402 SZ_Clear(&net_message);
1404 else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1406 // the old client hasn't sent us anything
1407 // in quite a while, so kick off and let
1408 // the retry take care of it...
1409 client->deadsocket = true;
1414 // this is a new client, find a slot
1415 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1416 if (!client->active)
1418 if (clientnum < svs.maxclients && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
1420 // connect to the client
1421 // everything is allocated, just fill in the details
1422 strlcpy (conn->address, addressstring2, sizeof (conn->address));
1423 if (developer.integer)
1424 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
1425 // send back the info about the server connection
1426 SZ_Clear(&net_message);
1427 // save space for the header, filled in later
1428 MSG_WriteLong(&net_message, 0);
1429 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1430 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
1431 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1432 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1433 SZ_Clear(&net_message);
1434 // now set up the client struct
1435 SV_ConnectClient(clientnum, conn);
1436 NetConn_Heartbeat(1);
1440 //if (developer.integer)
1441 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
1442 // no room; try to let player know
1443 SZ_Clear(&net_message);
1444 // save space for the header, filled in later
1445 MSG_WriteLong(&net_message, 0);
1446 MSG_WriteByte(&net_message, CCREP_REJECT);
1447 MSG_WriteString(&net_message, "Server is full.\n");
1448 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1449 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1450 SZ_Clear(&net_message);
1457 case CCREQ_SERVER_INFO:
1458 if (developer.integer)
1459 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
1460 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
1462 if (developer.integer)
1463 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
1464 SZ_Clear(&net_message);
1465 // save space for the header, filled in later
1466 MSG_WriteLong(&net_message, 0);
1467 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
1468 UDP_GetSocketAddr(UDP_acceptSock, &newaddr);
1469 MSG_WriteString(&net_message, UDP_AddrToString(&newaddr));
1470 MSG_WriteString(&net_message, hostname.string);
1471 MSG_WriteString(&net_message, sv.name);
1472 MSG_WriteByte(&net_message, net_activeconnections);
1473 MSG_WriteByte(&net_message, svs.maxclients);
1474 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1475 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1476 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1477 SZ_Clear(&net_message);
1480 case CCREQ_PLAYER_INFO:
1481 if (developer.integer)
1482 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
1485 int playerNumber, activeNumber, clientNumber;
1488 playerNumber = MSG_ReadByte();
1490 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
1491 if (client->active && ++activeNumber == playerNumber)
1493 if (clientNumber != svs.maxclients)
1495 SZ_Clear(&net_message);
1496 // save space for the header, filled in later
1497 MSG_WriteLong(&net_message, 0);
1498 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
1499 MSG_WriteByte(&net_message, playerNumber);
1500 MSG_WriteString(&net_message, client->name);
1501 MSG_WriteLong(&net_message, client->colors);
1502 MSG_WriteLong(&net_message, (int)client->edict->v->frags);
1503 MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
1504 MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
1505 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1506 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1507 SZ_Clear(&net_message);
1511 case CCREQ_RULE_INFO:
1512 if (developer.integer)
1513 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
1519 // find the search start location
1520 prevCvarName = MSG_ReadString();
1521 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
1523 // send the response
1524 SZ_Clear(&net_message);
1525 // save space for the header, filled in later
1526 MSG_WriteLong(&net_message, 0);
1527 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
1530 MSG_WriteString(&net_message, var->name);
1531 MSG_WriteString(&net_message, var->string);
1533 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1534 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1535 SZ_Clear(&net_message);
1542 // we may not have liked the packet, but it was a valid control
1543 // packet, so we're done processing this packet now
1548 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1550 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1552 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length)) == 2)
1553 SV_ReadClientMessage();
1561 void NetConn_ServerFrame(void)
1564 lhnetaddress_t peeraddress;
1566 NetConn_UpdateServerStuff();
1567 for (i = 0;i < sv_numsockets;i++)
1568 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1569 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
1570 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1572 // never timeout loopback connections
1573 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
1575 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
1576 SV_DropClient(false);
1579 for (conn = netconn_list;conn;conn = conn->next)
1580 NetConn_ReSendMessage(conn);
1583 void NetConn_QueryMasters(void)
1587 lhnetaddress_t masteraddress;
1590 if (hostcache_cachecount >= HOSTCACHE_TOTALSIZE)
1593 for (i = 0;i < cl_numsockets;i++)
1600 UDP_Broadcast(UDP_controlSock, "\377\377\377\377getinfo", 11);
1602 SZ_Clear(&net_message);
1603 // save space for the header, filled in later
1604 MSG_WriteLong(&net_message, 0);
1605 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
1606 MSG_WriteString(&net_message, "QUAKE");
1607 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1608 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1609 UDP_Broadcast(UDP_controlSock, net_message.data, net_message.cursize);
1610 SZ_Clear(&net_message);
1614 // build the getservers
1615 snprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
1618 for (masternum = 0;sv_masters[masternum].name;masternum++)
1620 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
1623 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
1628 if (!masterquerycount)
1630 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
1631 M_Update_Return_Reason("No network");
1635 void NetConn_Heartbeat(int priority)
1637 lhnetaddress_t masteraddress;
1639 lhnetsocket_t *mysocket;
1641 // if it's a state change (client connected), limit next heartbeat to no
1642 // more than 30 sec in the future
1643 if (priority == 1 && nextheartbeattime > realtime + 30.0)
1644 nextheartbeattime = realtime + 30.0;
1646 // limit heartbeatperiod to 30 to 270 second range,
1647 // lower limit is to avoid abusing master servers with excess traffic,
1648 // upper limit is to avoid timing out on the master server (which uses
1650 if (sv_heartbeatperiod.value < 30)
1651 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
1652 if (sv_heartbeatperiod.value > 270)
1653 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
1655 // make advertising optional and don't advertise singleplayer games, and
1656 // only send a heartbeat as often as the admin wants
1657 if (sv.active && sv_public.integer && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
1659 nextheartbeattime = realtime + sv_heartbeatperiod.value;
1660 for (masternum = 0;sv_masters[masternum].name;masternum++)
1661 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
1662 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
1666 int NetConn_SendToAll(sizebuf_t *data, double blocktime)
1669 qbyte sent[MAX_SCOREBOARD];
1671 memset(sent, 0, sizeof(sent));
1673 // simultaneously wait for the first CanSendMessage and send the message,
1674 // then wait for a second CanSendMessage (verifying it was received), or
1675 // the client drops and is no longer counted
1676 // the loop aborts when either it runs out of clients to send to, or a
1678 blocktime += Sys_DoubleTime();
1682 NetConn_ClientFrame();
1683 NetConn_ServerFrame();
1684 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1686 if (host_client->netconnection)
1688 if (NetConn_CanSendMessage(host_client->netconnection))
1691 NetConn_SendReliableMessage(host_client->netconnection, data);
1694 if (!NetConn_CanSendMessage(host_client->netconnection))
1699 while (count && Sys_DoubleTime() < blocktime);
1703 static void Net_Heartbeat_f(void)
1706 NetConn_Heartbeat(2);
1708 Con_Print("No server running, can not heartbeat to master server.\n");
1711 void PrintStats(netconn_t *conn)
1713 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, conn->canSend, conn->sendSequence, conn->receiveSequence);
1716 void Net_Stats_f(void)
1719 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
1720 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
1721 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
1722 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
1723 Con_Printf("packetsSent = %i\n", packetsSent);
1724 Con_Printf("packetsReSent = %i\n", packetsReSent);
1725 Con_Printf("packetsReceived = %i\n", packetsReceived);
1726 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
1727 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
1728 Con_Print("connections =\n");
1729 for (conn = netconn_list;conn;conn = conn->next)
1733 void Net_Slist_f(void)
1735 HostCache_ResetMasks();
1736 hostcache_sortbyfield = HCIF_PING;
1737 hostcache_sortdescending = false;
1738 if (m_state != m_slist) {
1739 Con_Print("Sending requests to master servers\n");
1740 HostCache_QueryList();
1741 hostcache_consoleoutput = true;
1742 Con_Print("Listening for replies...\n");
1744 HostCache_QueryList();
1747 void NetConn_Init(void)
1750 lhnetaddress_t tempaddress;
1751 netconn_mempool = Mem_AllocPool("Networking", 0, NULL);
1752 Cmd_AddCommand("net_stats", Net_Stats_f);
1753 Cmd_AddCommand("net_slist", Net_Slist_f);
1754 Cmd_AddCommand("heartbeat", Net_Heartbeat_f);
1755 Cvar_RegisterVariable(&net_messagetimeout);
1756 Cvar_RegisterVariable(&net_messagerejointimeout);
1757 Cvar_RegisterVariable(&net_connecttimeout);
1758 Cvar_RegisterVariable(&cl_netlocalping);
1759 Cvar_RegisterVariable(&cl_netpacketloss);
1760 Cvar_RegisterVariable(&hostname);
1761 Cvar_RegisterVariable(&developer_networking);
1762 Cvar_RegisterVariable(&cl_netport);
1763 Cvar_RegisterVariable(&sv_netport);
1764 Cvar_RegisterVariable(&net_address);
1765 //Cvar_RegisterVariable(&net_address_ipv6);
1766 Cvar_RegisterVariable(&sv_public);
1767 Cvar_RegisterVariable(&sv_heartbeatperiod);
1768 for (i = 0;sv_masters[i].name;i++)
1769 Cvar_RegisterVariable(&sv_masters[i]);
1770 // COMMANDLINEOPTION: Server: -ip <ipaddress> sets the ip address of this machine for purposes of networking (default 0.0.0.0 also known as INADDR_ANY), use only if you have multiple network adapters and need to choose one specifically.
1771 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
1773 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
1775 Con_Printf("-ip option used, setting net_address to \"%s\"\n");
1776 Cvar_SetQuick(&net_address, com_argv[i + 1]);
1779 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
1781 // COMMANDLINEOPTION: Server: -port <portnumber> sets the port to use for a server (default 26000, the same port as QUAKE itself), useful if you host multiple servers on your machine
1782 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
1784 i = atoi(com_argv[i + 1]);
1785 if (i >= 0 && i < 65536)
1787 Con_Printf("-port option used, setting port cvar to %i\n", i);
1788 Cvar_SetValueQuick(&sv_netport, i);
1791 Con_Printf("-port option used, but %i is not a valid port number\n", i);
1795 SZ_Alloc(&net_message, NET_MAXMESSAGE, "net_message");
1799 void NetConn_Shutdown(void)
1801 NetConn_CloseClientPorts();
1802 NetConn_CloseServerPorts();